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
2b9a2500378e6dd2dce2c5c12b3fbe26cb86406a
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/special_functions/trigonometric/complex_deriv.lean
65bd9c6f5e77b3683e1bb3951558333ddfdef2ba
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
2,610
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Benjamin Davidson -/ import analysis.special_functions.trigonometric.complex import analysis.special_functions.trigonometric.deriv /-! # Complex trigonometric functions Basic facts and derivatives for the complex trigonometric functions. -/ noncomputable theory namespace complex open set filter open_locale real lemma has_strict_deriv_at_tan {x : ℂ} (h : cos x ≠ 0) : has_strict_deriv_at tan (1 / (cos x)^2) x := begin convert (has_strict_deriv_at_sin x).div (has_strict_deriv_at_cos x) h, rw ← sin_sq_add_cos_sq x, ring, end lemma has_deriv_at_tan {x : ℂ} (h : cos x ≠ 0) : has_deriv_at tan (1 / (cos x)^2) x := (has_strict_deriv_at_tan h).has_deriv_at open_locale topological_space lemma tendsto_abs_tan_of_cos_eq_zero {x : ℂ} (hx : cos x = 0) : tendsto (λ x, abs (tan x)) (𝓝[≠] x) at_top := begin simp only [tan_eq_sin_div_cos, ← norm_eq_abs, norm_div], have A : sin x ≠ 0 := λ h, by simpa [*, sq] using sin_sq_add_cos_sq x, have B : tendsto cos (𝓝[≠] (x)) (𝓝[≠] 0), from hx ▸ (has_deriv_at_cos x).tendsto_punctured_nhds (neg_ne_zero.2 A), exact continuous_sin.continuous_within_at.norm.mul_at_top (norm_pos_iff.2 A) (tendsto_norm_nhds_within_zero.comp B).inv_tendsto_zero, end lemma tendsto_abs_tan_at_top (k : ℤ) : tendsto (λ x, abs (tan x)) (𝓝[≠] ((2 * k + 1) * π / 2)) at_top := tendsto_abs_tan_of_cos_eq_zero $ cos_eq_zero_iff.2 ⟨k, rfl⟩ @[simp] lemma continuous_at_tan {x : ℂ} : continuous_at tan x ↔ cos x ≠ 0 := begin refine ⟨λ hc h₀, _, λ h, (has_deriv_at_tan h).continuous_at⟩, exact not_tendsto_nhds_of_tendsto_at_top (tendsto_abs_tan_of_cos_eq_zero h₀) _ (hc.norm.tendsto.mono_left inf_le_left) end @[simp] lemma differentiable_at_tan {x : ℂ} : differentiable_at ℂ tan x ↔ cos x ≠ 0 := ⟨λ h, continuous_at_tan.1 h.continuous_at, λ h, (has_deriv_at_tan h).differentiable_at⟩ @[simp] lemma deriv_tan (x : ℂ) : deriv tan x = 1 / (cos x)^2 := if h : cos x = 0 then have ¬differentiable_at ℂ tan x := mt differentiable_at_tan.1 (not_not.2 h), by simp [deriv_zero_of_not_differentiable_at this, h, sq] else (has_deriv_at_tan h).deriv @[simp] lemma cont_diff_at_tan {x : ℂ} {n : with_top ℕ} : cont_diff_at ℂ n tan x ↔ cos x ≠ 0 := ⟨λ h, continuous_at_tan.1 h.continuous_at, cont_diff_sin.cont_diff_at.div cont_diff_cos.cont_diff_at⟩ end complex
c35bffcba7eed821407ed633aefd59b3a49aaf9b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/specialize3.lean
9bbbddc64fbaa55cd9cc98fea1aa2d83fa0bf2cf
[ "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
380
lean
class Class where instance empty: Class := {} mutual inductive T (δ: Class) where | mk (ss: List (S δ)) inductive S (δ: Class) where | mk (ts: List (T δ)) end mutual partial def str_T: T δ → String | .mk ss => "\n".intercalate (ss.map str_S) partial def str_S: S δ → String | .mk ts => "\n".intercalate (ts.map str_T) end def error := str_T (T.mk (δ := empty) [])
b6eb793d426085a6ef4284308731ce8917fa5706
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/linear_algebra/linear_independent.lean
e71ed61309c28997986ca175e42b5836501edc3c
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
50,493
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Alexander Bentkamp, Anne Baanen -/ import linear_algebra.finsupp import linear_algebra.prod import linear_algebra.pi import order.zorn import data.finset.order import data.equiv.fin /-! # Linear independence This file defines linear independence in a module or vector space. It is inspired by Isabelle/HOL's linear algebra, and hence indirectly by HOL Light. We define `linear_independent R v` as `ker (finsupp.total ι M R v) = ⊥`. Here `finsupp.total` is the linear map sending a function `f : ι →₀ R` with finite support to the linear combination of vectors from `v` with these coefficients. Then we prove that several other statements are equivalent to this one, including injectivity of `finsupp.total ι M R v` and some versions with explicitly written linear combinations. ## Main definitions All definitions are given for families of vectors, i.e. `v : ι → M` where `M` is the module or vector space and `ι : Type*` is an arbitrary indexing type. * `linear_independent R v` states that the elements of the family `v` are linearly independent. * `linear_independent.repr hv x` returns the linear combination representing `x : span R (range v)` on the linearly independent vectors `v`, given `hv : linear_independent R v` (using classical choice). `linear_independent.repr hv` is provided as a linear map. ## Main statements We prove several specialized tests for linear independence of families of vectors and of sets of vectors. * `fintype.linear_independent_iff`: if `ι` is a finite type, then any function `f : ι → R` has finite support, so we can reformulate the statement using `∑ i : ι, f i • v i` instead of a sum over an auxiliary `s : finset ι`; * `linear_independent_empty_type`: a family indexed by an empty type is linearly independent; * `linear_independent_unique_iff`: if `ι` is a singleton, then `linear_independent K v` is equivalent to `v (default ι) ≠ 0`; * linear_independent_option`, `linear_independent_sum`, `linear_independent_fin_cons`, `linear_independent_fin_succ`: type-specific tests for linear independence of families of vector fields; * `linear_independent_insert`, `linear_independent_union`, `linear_independent_pair`, `linear_independent_singleton`: linear independence tests for set operations. In many cases we additionally provide dot-style operations (e.g., `linear_independent.union`) to make the linear independence tests usable as `hv.insert ha` etc. We also prove that any family of vectors includes a linear independent subfamily spanning the same submodule. ## Implementation notes We use families instead of sets because it allows us to say that two identical vectors are linearly dependent. If you want to use sets, use the family `(λ x, x : s → M)` given a set `s : set M`. The lemmas `linear_independent.to_subtype_range` and `linear_independent.of_subtype_range` connect those two worlds. ## Tags linearly dependent, linear dependence, linearly independent, linear independence -/ noncomputable theory open function set submodule open_locale classical big_operators universe u variables {ι : Type*} {ι' : Type*} {R : Type*} {K : Type*} variables {M : Type*} {M' M'' : Type*} {V : Type u} {V' : Type*} section module variables {v : ι → M} variables [semiring R] [add_comm_monoid M] [add_comm_monoid M'] [add_comm_monoid M''] variables [module R M] [module R M'] [module R M''] variables {a b : R} {x y : M} variables (R) (v) /-- `linear_independent R v` states the family of vectors `v` is linearly independent over `R`. -/ def linear_independent : Prop := (finsupp.total ι M R v).ker = ⊥ variables {R} {v} theorem linear_independent_iff : linear_independent R v ↔ ∀l, finsupp.total ι M R v l = 0 → l = 0 := by simp [linear_independent, linear_map.ker_eq_bot'] theorem linear_independent_iff' : linear_independent R v ↔ ∀ s : finset ι, ∀ g : ι → R, ∑ i in s, g i • v i = 0 → ∀ i ∈ s, g i = 0 := linear_independent_iff.trans ⟨λ hf s g hg i his, have h : _ := hf (∑ i in s, finsupp.single i (g i)) $ by simpa only [linear_map.map_sum, finsupp.total_single] using hg, calc g i = (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single i (g i)) : by rw [finsupp.lapply_apply, finsupp.single_eq_same] ... = ∑ j in s, (finsupp.lapply i : (ι →₀ R) →ₗ[R] R) (finsupp.single j (g j)) : eq.symm $ finset.sum_eq_single i (λ j hjs hji, by rw [finsupp.lapply_apply, finsupp.single_eq_of_ne hji]) (λ hnis, hnis.elim his) ... = (∑ j in s, finsupp.single j (g j)) i : (finsupp.lapply i : (ι →₀ R) →ₗ[R] R).map_sum.symm ... = 0 : finsupp.ext_iff.1 h i, λ hf l hl, finsupp.ext $ λ i, classical.by_contradiction $ λ hni, hni $ hf _ _ hl _ $ finsupp.mem_support_iff.2 hni⟩ theorem linear_independent_iff'' : linear_independent R v ↔ ∀ (s : finset ι) (g : ι → R) (hg : ∀ i ∉ s, g i = 0), ∑ i in s, g i • v i = 0 → ∀ i, g i = 0 := linear_independent_iff'.trans ⟨λ H s g hg hv i, if his : i ∈ s then H s g hv i his else hg i his, λ H s g hg i hi, by { convert H s (λ j, if j ∈ s then g j else 0) (λ j hj, if_neg hj) (by simp_rw [ite_smul, zero_smul, finset.sum_extend_by_zero, hg]) i, exact (if_pos hi).symm }⟩ theorem linear_dependent_iff : ¬ linear_independent R v ↔ ∃ s : finset ι, ∃ g : ι → R, (∑ i in s, g i • v i) = 0 ∧ (∃ i ∈ s, g i ≠ 0) := begin rw linear_independent_iff', simp only [exists_prop, not_forall], end theorem fintype.linear_independent_iff [fintype ι] : linear_independent R v ↔ ∀ g : ι → R, ∑ i, g i • v i = 0 → ∀ i, g i = 0 := begin refine ⟨λ H g, by simpa using linear_independent_iff'.1 H finset.univ g, λ H, linear_independent_iff''.2 $ λ s g hg hs i, H _ _ _⟩, rw ← hs, refine (finset.sum_subset (finset.subset_univ _) (λ i _ hi, _)).symm, rw [hg i hi, zero_smul] end /-- A finite family of vectors `v i` is linear independent iff the linear map that sends `c : ι → R` to `∑ i, c i • v i` has the trivial kernel. -/ theorem fintype.linear_independent_iff' [fintype ι] : linear_independent R v ↔ (linear_map.lsum R (λ i : ι, R) ℕ (λ i, linear_map.id.smul_right (v i))).ker = ⊥ := by simp [fintype.linear_independent_iff, linear_map.ker_eq_bot', funext_iff] lemma linear_independent_empty_type (h : ¬ nonempty ι) : linear_independent R v := begin rw [linear_independent_iff], intros, ext i, exact false.elim (h ⟨i⟩) end lemma linear_independent.ne_zero [nontrivial R] (i : ι) (hv : linear_independent R v) : v i ≠ 0 := λ h, @zero_ne_one R _ _ $ eq.symm begin suffices : (finsupp.single i 1 : ι →₀ R) i = 0, {simpa}, rw linear_independent_iff.1 hv (finsupp.single i 1), { simp }, { simp [h] } end /-- A subfamily of a linearly independent family (i.e., a composition with an injective map) is a linearly independent family. -/ lemma linear_independent.comp (h : linear_independent R v) (f : ι' → ι) (hf : injective f) : linear_independent R (v ∘ f) := begin rw [linear_independent_iff, finsupp.total_comp], intros l hl, have h_map_domain : ∀ x, (finsupp.map_domain f l) (f x) = 0, by rw linear_independent_iff.1 h (finsupp.map_domain f l) hl; simp, ext x, convert h_map_domain x, rw [finsupp.map_domain_apply hf] end /-- If `v` is a linearly independent family of vectors and the kernel of a linear map `f` is disjoint with the sumodule spaned by the vectors of `v`, then `f ∘ v` is a linearly independent family of vectors. See also `linear_independent.map'` for a special case assuming `ker f = ⊥`. -/ lemma linear_independent.map (hv : linear_independent R v) {f : M →ₗ[R] M'} (hf_inj : disjoint (span R (range v)) f.ker) : linear_independent R (f ∘ v) := begin rw [disjoint, ← set.image_univ, finsupp.span_eq_map_total, map_inf_eq_map_inf_comap, map_le_iff_le_comap, comap_bot, finsupp.supported_univ, top_inf_eq] at hf_inj, unfold linear_independent at hv ⊢, rw [hv, le_bot_iff] at hf_inj, haveI : inhabited M := ⟨0⟩, rw [finsupp.total_comp, @finsupp.lmap_domain_total _ _ R _ _ _ _ _ _ _ _ _ _ f, linear_map.ker_comp, hf_inj], exact λ _, rfl, end /-- An injective linear map sends linearly independent families of vectors to linearly independent families of vectors. See also `linear_independent.map` for a more general statement. -/ lemma linear_independent.map' (hv : linear_independent R v) (f : M →ₗ[R] M') (hf_inj : f.ker = ⊥) : linear_independent R (f ∘ v) := hv.map $ by simp [hf_inj] /-- If the image of a family of vectors under a linear map is linearly independent, then so is the original family. -/ lemma linear_independent.of_comp (f : M →ₗ[R] M') (hfv : linear_independent R (f ∘ v)) : linear_independent R v := linear_independent_iff'.2 $ λ s g hg i his, have ∑ (i : ι) in s, g i • f (v i) = 0, by simp_rw [← f.map_smul, ← f.map_sum, hg, f.map_zero], linear_independent_iff'.1 hfv s g this i his /-- If `f` is an injective linear map, then the family `f ∘ v` is linearly independent if and only if the family `v` is linearly independent. -/ protected lemma linear_map.linear_independent_iff (f : M →ₗ[R] M') (hf_inj : f.ker = ⊥) : linear_independent R (f ∘ v) ↔ linear_independent R v := ⟨λ h, h.of_comp f, λ h, h.map $ by simp only [hf_inj, disjoint_bot_right]⟩ @[nontriviality] lemma linear_independent_of_subsingleton [subsingleton R] : linear_independent R v := linear_independent_iff.2 (λ l hl, subsingleton.elim _ _) theorem linear_independent_equiv (e : ι ≃ ι') {f : ι' → M} : linear_independent R (f ∘ e) ↔ linear_independent R f := ⟨λ h, function.comp.right_id f ▸ e.self_comp_symm ▸ h.comp _ e.symm.injective, λ h, h.comp _ e.injective⟩ theorem linear_independent_equiv' (e : ι ≃ ι') {f : ι' → M} {g : ι → M} (h : f ∘ e = g) : linear_independent R g ↔ linear_independent R f := h ▸ linear_independent_equiv e theorem linear_independent_subtype_range {ι} {f : ι → M} (hf : injective f) : linear_independent R (coe : range f → M) ↔ linear_independent R f := iff.symm $ linear_independent_equiv' (equiv.of_injective f hf) rfl alias linear_independent_subtype_range ↔ linear_independent.of_subtype_range _ theorem linear_independent_image {ι} {s : set ι} {f : ι → M} (hf : set.inj_on f s) : linear_independent R (λ x : s, f x) ↔ linear_independent R (λ x : f '' s, (x : M)) := linear_independent_equiv' (equiv.set.image_of_inj_on _ _ hf) rfl lemma linear_independent_span (hs : linear_independent R v) : @linear_independent ι R (span R (range v)) (λ i : ι, ⟨v i, subset_span (mem_range_self i)⟩) _ _ _ := linear_independent.of_comp (span R (range v)).subtype hs /-- See `linear_independent.fin_cons` for a family of elements in a vector space. -/ lemma linear_independent.fin_cons' {m : ℕ} (x : M) (v : fin m → M) (hli : linear_independent R v) (x_ortho : (∀ (c : R) (y : submodule.span R (set.range v)), c • x + y = (0 : M) → c = 0)) : linear_independent R (fin.cons x v : fin m.succ → M) := begin rw fintype.linear_independent_iff at hli ⊢, rintros g total_eq j, have zero_not_mem : (0 : fin m.succ) ∉ finset.univ.image (fin.succ : fin m → fin m.succ), { rw finset.mem_image, rintro ⟨x, hx, succ_eq⟩, exact fin.succ_ne_zero _ succ_eq }, simp only [submodule.coe_mk, fin.univ_succ, finset.sum_insert zero_not_mem, fin.cons_zero, fin.cons_succ, forall_true_iff, imp_self, fin.succ_inj, finset.sum_image] at total_eq, have : g 0 = 0, { refine x_ortho (g 0) ⟨∑ (i : fin m), g i.succ • v i, _⟩ total_eq, exact sum_mem _ (λ i _, smul_mem _ _ (subset_span ⟨i, rfl⟩)) }, refine fin.cases this (λ j, _) j, apply hli (λ i, g i.succ), simpa only [this, zero_smul, zero_add] using total_eq end /-- A set of linearly independent vectors in a module `M` over a semiring `K` is also linearly independent over a subring `R` of `K`. The implementation uses minimal assumptions about the relationship between `R`, `K` and `M`. The version where `K` is an `R`-algebra is `linear_independent.restrict_scalars_algebras`. -/ lemma linear_independent.restrict_scalars [semiring K] [smul_with_zero R K] [module K M] [is_scalar_tower R K M] (hinj : function.injective (λ r : R, r • (1 : K))) (li : linear_independent K v) : linear_independent R v := begin refine linear_independent_iff'.mpr (λ s g hg i hi, hinj (eq.trans _ (zero_smul _ _).symm)), refine (linear_independent_iff'.mp li : _) _ _ _ i hi, simp_rw [smul_assoc, one_smul], exact hg, end section subtype /-! The following lemmas use the subtype defined by a set in `M` as the index set `ι`. -/ theorem linear_independent_comp_subtype {s : set ι} : linear_independent R (v ∘ coe : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total ι M R v) l = 0 → l = 0 := begin simp only [linear_independent_iff, (∘), finsupp.mem_supported, finsupp.total_apply, set.subset_def, finset.mem_coe], split, { intros h l hl₁ hl₂, have := h (l.subtype_domain s) ((finsupp.sum_subtype_domain_index hl₁).trans hl₂), exact (finsupp.subtype_domain_eq_zero_iff hl₁).1 this }, { intros h l hl, refine finsupp.emb_domain_eq_zero.1 (h (l.emb_domain $ function.embedding.subtype s) _ _), { suffices : ∀ i hi, ¬l ⟨i, hi⟩ = 0 → i ∈ s, by simpa, intros, assumption }, { rwa [finsupp.emb_domain_eq_map_domain, finsupp.sum_map_domain_index], exacts [λ _, zero_smul _ _, λ _ _ _, add_smul _ _ _] } } end lemma linear_dependent_comp_subtype' {s : set ι} : ¬ linear_independent R (v ∘ coe : s → M) ↔ ∃ f : ι →₀ R, f ∈ finsupp.supported R R s ∧ finsupp.total ι M R v f = 0 ∧ f ≠ 0 := by simp [linear_independent_comp_subtype] /-- A version of `linear_dependent_comp_subtype'` with `finsupp.total` unfolded. -/ lemma linear_dependent_comp_subtype {s : set ι} : ¬ linear_independent R (v ∘ coe : s → M) ↔ ∃ f : ι →₀ R, f ∈ finsupp.supported R R s ∧ ∑ i in f.support, f i • v i = 0 ∧ f ≠ 0 := linear_dependent_comp_subtype' theorem linear_independent_subtype {s : set M} : linear_independent R (λ x, x : s → M) ↔ ∀ l ∈ (finsupp.supported R R s), (finsupp.total M M R id) l = 0 → l = 0 := by apply @linear_independent_comp_subtype _ _ _ id theorem linear_independent_comp_subtype_disjoint {s : set ι} : linear_independent R (v ∘ coe : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total ι M R v).ker := by rw [linear_independent_comp_subtype, linear_map.disjoint_ker] theorem linear_independent_subtype_disjoint {s : set M} : linear_independent R (λ x, x : s → M) ↔ disjoint (finsupp.supported R R s) (finsupp.total M M R id).ker := by apply @linear_independent_comp_subtype_disjoint _ _ _ id theorem linear_independent_iff_total_on {s : set M} : linear_independent R (λ x, x : s → M) ↔ (finsupp.total_on M M R id s).ker = ⊥ := by rw [finsupp.total_on, linear_map.ker, linear_map.comap_cod_restrict, map_bot, comap_bot, linear_map.ker_comp, linear_independent_subtype_disjoint, disjoint, ← map_comap_subtype, map_le_iff_le_comap, comap_bot, ker_subtype, le_bot_iff] lemma linear_independent.restrict_of_comp_subtype {s : set ι} (hs : linear_independent R (v ∘ coe : s → M)) : linear_independent R (s.restrict v) := hs variables (R M) lemma linear_independent_empty : linear_independent R (λ x, x : (∅ : set M) → M) := by simp [linear_independent_subtype_disjoint] variables {R M} lemma linear_independent.mono {t s : set M} (h : t ⊆ s) : linear_independent R (λ x, x : s → M) → linear_independent R (λ x, x : t → M) := begin simp only [linear_independent_subtype_disjoint], exact (disjoint.mono_left (finsupp.supported_mono h)) end lemma linear_independent_of_finite (s : set M) (H : ∀ t ⊆ s, finite t → linear_independent R (λ x, x : t → M)) : linear_independent R (λ x, x : s → M) := linear_independent_subtype.2 $ λ l hl, linear_independent_subtype.1 (H _ hl (finset.finite_to_set _)) l (subset.refl _) lemma linear_independent_Union_of_directed {η : Type*} {s : η → set M} (hs : directed (⊆) s) (h : ∀ i, linear_independent R (λ x, x : s i → M)) : linear_independent R (λ x, x : (⋃ i, s i) → M) := begin by_cases hη : nonempty η, { resetI, refine linear_independent_of_finite (⋃ i, s i) (λ t ht ft, _), rcases finite_subset_Union ft ht with ⟨I, fi, hI⟩, rcases hs.finset_le fi.to_finset with ⟨i, hi⟩, exact (h i).mono (subset.trans hI $ bUnion_subset $ λ j hj, hi j (fi.mem_to_finset.2 hj)) }, { refine (linear_independent_empty _ _).mono _, rintro _ ⟨_, ⟨i, _⟩, _⟩, exact hη ⟨i⟩ } end lemma linear_independent_sUnion_of_directed {s : set (set M)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, linear_independent R (λ x, x : (a : set M) → M)) : linear_independent R (λ x, x : (⋃₀ s) → M) := by rw sUnion_eq_Union; exact linear_independent_Union_of_directed hs.directed_coe (by simpa using h) lemma linear_independent_bUnion_of_directed {η} {s : set η} {t : η → set M} (hs : directed_on (t ⁻¹'o (⊆)) s) (h : ∀a∈s, linear_independent R (λ x, x : t a → M)) : linear_independent R (λ x, x : (⋃a∈s, t a) → M) := by rw bUnion_eq_Union; exact linear_independent_Union_of_directed (directed_comp.2 $ hs.directed_coe) (by simpa using h) end subtype end module /-! ### Properties which require `ring R` -/ section module variables {v : ι → M} variables [ring R] [add_comm_group M] [add_comm_group M'] [add_comm_group M''] variables [module R M] [module R M'] [module R M''] variables {a b : R} {x y : M} theorem linear_independent_iff_injective_total : linear_independent R v ↔ function.injective (finsupp.total ι M R v) := linear_independent_iff.trans (finsupp.total ι M R v).to_add_monoid_hom.injective_iff.symm alias linear_independent_iff_injective_total ↔ linear_independent.injective_total _ lemma linear_independent.injective [nontrivial R] (hv : linear_independent R v) : injective v := begin intros i j hij, let l : ι →₀ R := finsupp.single i (1 : R) - finsupp.single j 1, have h_total : finsupp.total ι M R v l = 0, { simp_rw [linear_map.map_sub, finsupp.total_apply], simp [hij] }, have h_single_eq : finsupp.single i (1 : R) = finsupp.single j 1, { rw linear_independent_iff at hv, simp [eq_add_of_sub_eq' (hv l h_total)] }, simpa [finsupp.single_eq_single_iff] using h_single_eq end theorem linear_independent.to_subtype_range {ι} {f : ι → M} (hf : linear_independent R f) : linear_independent R (coe : range f → M) := begin nontriviality R, exact (linear_independent_subtype_range hf.injective).2 hf end theorem linear_independent.to_subtype_range' {ι} {f : ι → M} (hf : linear_independent R f) {t} (ht : range f = t) : linear_independent R (coe : t → M) := ht ▸ hf.to_subtype_range theorem linear_independent.image_of_comp {ι ι'} (s : set ι) (f : ι → ι') (g : ι' → M) (hs : linear_independent R (λ x : s, g (f x))) : linear_independent R (λ x : f '' s, g x) := begin nontriviality R, have : inj_on f s, from inj_on_iff_injective.2 hs.injective.of_comp, exact (linear_independent_equiv' (equiv.set.image_of_inj_on f s this) rfl).1 hs end theorem linear_independent.image {ι} {s : set ι} {f : ι → M} (hs : linear_independent R (λ x : s, f x)) : linear_independent R (λ x : f '' s, (x : M)) := by convert linear_independent.image_of_comp s f id hs section subtype /-! The following lemmas use the subtype defined by a set in `M` as the index set `ι`. -/ lemma linear_independent.disjoint_span_image (hv : linear_independent R v) {s t : set ι} (hs : disjoint s t) : disjoint (submodule.span R $ v '' s) (submodule.span R $ v '' t) := begin simp only [disjoint_def, finsupp.mem_span_iff_total], rintros _ ⟨l₁, hl₁, rfl⟩ ⟨l₂, hl₂, H⟩, rw [hv.injective_total.eq_iff] at H, subst l₂, have : l₁ = 0 := finsupp.disjoint_supported_supported hs (submodule.mem_inf.2 ⟨hl₁, hl₂⟩), simp [this] end lemma linear_independent_sum {v : ι ⊕ ι' → M} : linear_independent R v ↔ linear_independent R (v ∘ sum.inl) ∧ linear_independent R (v ∘ sum.inr) ∧ disjoint (submodule.span R (range (v ∘ sum.inl))) (submodule.span R (range (v ∘ sum.inr))) := begin rw [range_comp v, range_comp v], refine ⟨λ h, ⟨h.comp _ sum.inl_injective, h.comp _ sum.inr_injective, h.disjoint_span_image is_compl_range_inl_range_inr.1⟩, _⟩, rintro ⟨hl, hr, hlr⟩, rw [linear_independent_iff'] at *, intros s g hg i hi, have : ∑ i in s.preimage sum.inl (sum.inl_injective.inj_on _), (λ x, g x • v x) (sum.inl i) + ∑ i in s.preimage sum.inr (sum.inr_injective.inj_on _), (λ x, g x • v x) (sum.inr i) = 0, { rw [finset.sum_preimage', finset.sum_preimage', ← finset.sum_union, ← finset.filter_or], { simpa only [← mem_union, range_inl_union_range_inr, mem_univ, finset.filter_true] }, { exact finset.disjoint_filter.2 (λ x hx, disjoint_left.1 is_compl_range_inl_range_inr.1) } }, { rw ← eq_neg_iff_add_eq_zero at this, rw [disjoint_def'] at hlr, have A := hlr _ (sum_mem _ $ λ i hi, _) _ (neg_mem _ $ sum_mem _ $ λ i hi, _) this, { cases i with i i, { exact hl _ _ A i (finset.mem_preimage.2 hi) }, { rw [this, neg_eq_zero] at A, exact hr _ _ A i (finset.mem_preimage.2 hi) } }, { exact smul_mem _ _ (subset_span ⟨sum.inl i, mem_range_self _, rfl⟩) }, { exact smul_mem _ _ (subset_span ⟨sum.inr i, mem_range_self _, rfl⟩) } } end lemma linear_independent.sum_type {v' : ι' → M} (hv : linear_independent R v) (hv' : linear_independent R v') (h : disjoint (submodule.span R (range v)) (submodule.span R (range v'))) : linear_independent R (sum.elim v v') := linear_independent_sum.2 ⟨hv, hv', h⟩ lemma linear_independent.union {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M)) (hst : disjoint (span R s) (span R t)) : linear_independent R (λ x, x : (s ∪ t) → M) := (hs.sum_type ht $ by simpa).to_subtype_range' $ by simp lemma linear_independent_Union_finite_subtype {ι : Type*} {f : ι → set M} (hl : ∀i, linear_independent R (λ x, x : f i → M)) (hd : ∀i, ∀t:set ι, finite t → i ∉ t → disjoint (span R (f i)) (⨆i∈t, span R (f i))) : linear_independent R (λ x, x : (⋃i, f i) → M) := begin rw [Union_eq_Union_finset f], apply linear_independent_Union_of_directed, apply directed_of_sup, exact (assume t₁ t₂ ht, Union_subset_Union $ assume i, Union_subset_Union_const $ assume h, ht h), assume t, rw [set.Union, ← finset.sup_eq_supr], refine t.induction_on _ _, { rw finset.sup_empty, apply linear_independent_empty_type (not_nonempty_iff_imp_false.2 _), exact λ x, set.not_mem_empty x (subtype.mem x) }, { rintros i s his ih, rw [finset.sup_insert], refine (hl _).union ih _, rw [finset.sup_eq_supr], refine (hd i _ _ his).mono_right _, { simp only [(span_Union _).symm], refine span_mono (@supr_le_supr2 (set M) _ _ _ _ _ _), rintros i, exact ⟨i, le_refl _⟩ }, { exact s.finite_to_set } } end lemma linear_independent_Union_finite {η : Type*} {ιs : η → Type*} {f : Π j : η, ιs j → M} (hindep : ∀j, linear_independent R (f j)) (hd : ∀i, ∀t:set η, finite t → i ∉ t → disjoint (span R (range (f i))) (⨆i∈t, span R (range (f i)))) : linear_independent R (λ ji : Σ j, ιs j, f ji.1 ji.2) := begin nontriviality R, apply linear_independent.of_subtype_range, { rintros ⟨x₁, x₂⟩ ⟨y₁, y₂⟩ hxy, by_cases h_cases : x₁ = y₁, subst h_cases, { apply sigma.eq, rw linear_independent.injective (hindep _) hxy, refl }, { have h0 : f x₁ x₂ = 0, { apply disjoint_def.1 (hd x₁ {y₁} (finite_singleton y₁) (λ h, h_cases (eq_of_mem_singleton h))) (f x₁ x₂) (subset_span (mem_range_self _)), rw supr_singleton, simp only at hxy, rw hxy, exact (subset_span (mem_range_self y₂)) }, exact false.elim ((hindep x₁).ne_zero _ h0) } }, rw range_sigma_eq_Union_range, apply linear_independent_Union_finite_subtype (λ j, (hindep j).to_subtype_range) hd, end end subtype section repr variables (hv : linear_independent R v) /-- Canonical isomorphism between linear combinations and the span of linearly independent vectors. -/ def linear_independent.total_equiv (hv : linear_independent R v) : (ι →₀ R) ≃ₗ[R] span R (range v) := begin apply linear_equiv.of_bijective (linear_map.cod_restrict (span R (range v)) (finsupp.total ι M R v) _), { rw linear_map.ker_cod_restrict, apply hv }, { rw [linear_map.range_eq_map, linear_map.map_cod_restrict, ← linear_map.range_le_iff_comap, range_subtype, map_top], rw finsupp.range_total, apply le_refl (span R (range v)) }, { intro l, rw ← finsupp.range_total, rw linear_map.mem_range, apply mem_range_self l } end /-- Linear combination representing a vector in the span of linearly independent vectors. Given a family of linearly independent vectors, we can represent any vector in their span as a linear combination of these vectors. These are provided by this linear map. It is simply one direction of `linear_independent.total_equiv`. -/ def linear_independent.repr (hv : linear_independent R v) : span R (range v) →ₗ[R] ι →₀ R := hv.total_equiv.symm lemma linear_independent.total_repr (x) : finsupp.total ι M R v (hv.repr x) = x := subtype.ext_iff.1 (linear_equiv.apply_symm_apply hv.total_equiv x) lemma linear_independent.total_comp_repr : (finsupp.total ι M R v).comp hv.repr = submodule.subtype _ := linear_map.ext $ hv.total_repr lemma linear_independent.repr_ker : hv.repr.ker = ⊥ := by rw [linear_independent.repr, linear_equiv.ker] lemma linear_independent.repr_range : hv.repr.range = ⊤ := by rw [linear_independent.repr, linear_equiv.range] lemma linear_independent.repr_eq {l : ι →₀ R} {x} (eq : finsupp.total ι M R v l = ↑x) : hv.repr x = l := begin have : ↑((linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l) = finsupp.total ι M R v l := rfl, have : (linear_independent.total_equiv hv : (ι →₀ R) →ₗ[R] span R (range v)) l = x, { rw eq at this, exact subtype.ext_iff.2 this }, rw ←linear_equiv.symm_apply_apply hv.total_equiv l, rw ←this, refl, end lemma linear_independent.repr_eq_single (i) (x) (hx : ↑x = v i) : hv.repr x = finsupp.single i 1 := begin apply hv.repr_eq, simp [finsupp.total_single, hx] end -- TODO: why is this so slow? lemma linear_independent_iff_not_smul_mem_span : linear_independent R v ↔ (∀ (i : ι) (a : R), a • (v i) ∈ span R (v '' (univ \ {i})) → a = 0) := ⟨ λ hv i a ha, begin rw [finsupp.span_eq_map_total, mem_map] at ha, rcases ha with ⟨l, hl, e⟩, rw sub_eq_zero.1 (linear_independent_iff.1 hv (l - finsupp.single i a) (by simp [e])) at hl, by_contra hn, exact (not_mem_of_mem_diff (hl $ by simp [hn])) (mem_singleton _), end, λ H, linear_independent_iff.2 $ λ l hl, begin ext i, simp only [finsupp.zero_apply], by_contra hn, refine hn (H i _ _), refine (finsupp.mem_span_iff_total _).2 ⟨finsupp.single i (l i) - l, _, _⟩, { rw finsupp.mem_supported', intros j hj, have hij : j = i := not_not.1 (λ hij : j ≠ i, hj ((mem_diff _).2 ⟨mem_univ _, λ h, hij (eq_of_mem_singleton h)⟩)), simp [hij] }, { simp [hl] } end⟩ variable (R) lemma exists_maximal_independent' (s : ι → M) : ∃ I : set ι, linear_independent R (λ x : I, s x) ∧ ∀ J : set ι, I ⊆ J → linear_independent R (λ x : J, s x) → I = J := begin let indep : set ι → Prop := λ I, linear_independent R (s ∘ coe : I → M), let X := { I : set ι // indep I }, let r : X → X → Prop := λ I J, I.1 ⊆ J.1, have key : ∀ c : set X, zorn.chain r c → indep (⋃ (I : X) (H : I ∈ c), I), { intros c hc, dsimp [indep], rw [linear_independent_comp_subtype], intros f hsupport hsum, rcases eq_empty_or_nonempty c with rfl | ⟨a, hac⟩, { simpa using hsupport }, haveI : is_refl X r := ⟨λ _, set.subset.refl _⟩, obtain ⟨I, I_mem, hI⟩ : ∃ I ∈ c, (f.support : set ι) ⊆ I := finset.exists_mem_subset_of_subset_bUnion_of_directed_on hac hc.directed_on hsupport, exact linear_independent_comp_subtype.mp I.2 f hI hsum }, have trans : transitive r := λ I J K, set.subset.trans, obtain ⟨⟨I, hli : indep I⟩, hmax : ∀ a, r ⟨I, hli⟩ a → r a ⟨I, hli⟩⟩ := @zorn.exists_maximal_of_chains_bounded _ r (λ c hc, ⟨⟨⋃ I ∈ c, (I : set ι), key c hc⟩, λ I, set.subset_bUnion_of_mem⟩) trans, exact ⟨I, hli, λ J hsub hli, set.subset.antisymm hsub (hmax ⟨J, hli⟩ hsub)⟩, end lemma exists_maximal_independent (s : ι → M) : ∃ I : set ι, linear_independent R (λ x : I, s x) ∧ ∀ i ∉ I, ∃ a : R, a ≠ 0 ∧ a • s i ∈ span R (s '' I) := begin classical, rcases exists_maximal_independent' R s with ⟨I, hIlinind, hImaximal⟩, use [I, hIlinind], intros i hi, specialize hImaximal (I ∪ {i}) (by simp), set J := I ∪ {i} with hJ, have memJ : ∀ {x}, x ∈ J ↔ x = i ∨ x ∈ I, by simp [hJ], have hiJ : i ∈ J := by simp, have h := mt hImaximal _, swap, { intro h2, rw h2 at hi, exact absurd hiJ hi }, obtain ⟨f, supp_f, sum_f, f_ne⟩ := linear_dependent_comp_subtype.mp h, have hfi : f i ≠ 0, { contrapose hIlinind, refine linear_dependent_comp_subtype.mpr ⟨f, _, sum_f, f_ne⟩, simp only [finsupp.mem_supported, hJ] at ⊢ supp_f, rintro x hx, refine (memJ.mp (supp_f hx)).resolve_left _, rintro rfl, exact hIlinind (finsupp.mem_support_iff.mp hx) }, use [f i, hfi], have hfi' : i ∈ f.support := finsupp.mem_support_iff.mpr hfi, rw [← finset.insert_erase hfi', finset.sum_insert (finset.not_mem_erase _ _), add_eq_zero_iff_eq_neg] at sum_f, rw sum_f, refine neg_mem _ (sum_mem _ (λ c hc, smul_mem _ _ (subset_span ⟨c, _, rfl⟩))), exact (memJ.mp (supp_f (finset.erase_subset _ _ hc))).resolve_left (finset.ne_of_mem_erase hc), end end repr lemma surjective_of_linear_independent_of_span [nontrivial R] (hv : linear_independent R v) (f : ι' ↪ ι) (hss : range v ⊆ span R (range (v ∘ f))) : surjective f := begin intros i, let repr : (span R (range (v ∘ f)) : Type*) → ι' →₀ R := (hv.comp f f.injective).repr, let l := (repr ⟨v i, hss (mem_range_self i)⟩).map_domain f, have h_total_l : finsupp.total ι M R v l = v i, { dsimp only [l], rw finsupp.total_map_domain, rw (hv.comp f f.injective).total_repr, { refl }, { exact f.injective } }, have h_total_eq : (finsupp.total ι M R v) l = (finsupp.total ι M R v) (finsupp.single i 1), by rw [h_total_l, finsupp.total_single, one_smul], have l_eq : l = _ := linear_map.ker_eq_bot.1 hv h_total_eq, dsimp only [l] at l_eq, rw ←finsupp.emb_domain_eq_map_domain at l_eq, rcases finsupp.single_of_emb_domain_single (repr ⟨v i, _⟩) f i (1 : R) zero_ne_one.symm l_eq with ⟨i', hi'⟩, use i', exact hi'.2 end lemma eq_of_linear_independent_of_span_subtype [nontrivial R] {s t : set M} (hs : linear_independent R (λ x, x : s → M)) (h : t ⊆ s) (hst : s ⊆ span R t) : s = t := begin let f : t ↪ s := ⟨λ x, ⟨x.1, h x.2⟩, λ a b hab, subtype.coe_injective (subtype.mk.inj hab)⟩, have h_surj : surjective f, { apply surjective_of_linear_independent_of_span hs f _, convert hst; simp [f, comp], }, show s = t, { apply subset.antisymm _ h, intros x hx, rcases h_surj ⟨x, hx⟩ with ⟨y, hy⟩, convert y.mem, rw ← subtype.mk.inj hy, refl } end open linear_map lemma linear_independent.image_subtype {s : set M} {f : M →ₗ M'} (hs : linear_independent R (λ x, x : s → M)) (hf_inj : disjoint (span R s) f.ker) : linear_independent R (λ x, x : f '' s → M') := begin rw [← @subtype.range_coe _ s] at hf_inj, refine (hs.map hf_inj).to_subtype_range' _, simp [set.range_comp f] end lemma linear_independent.inl_union_inr {s : set M} {t : set M'} (hs : linear_independent R (λ x, x : s → M)) (ht : linear_independent R (λ x, x : t → M')) : linear_independent R (λ x, x : inl R M M' '' s ∪ inr R M M' '' t → M × M') := begin refine (hs.image_subtype _).union (ht.image_subtype _) _; [simp, simp, skip], simp only [span_image], simp [disjoint_iff, prod_inf_prod] end lemma linear_independent_inl_union_inr' {v : ι → M} {v' : ι' → M'} (hv : linear_independent R v) (hv' : linear_independent R v') : linear_independent R (sum.elim (inl R M M' ∘ v) (inr R M M' ∘ v')) := (hv.map' (inl R M M') ker_inl).sum_type (hv'.map' (inr R M M') ker_inr) $ begin refine is_compl_range_inl_inr.disjoint.mono _ _; simp only [span_le, range_coe, range_comp_subset_range], end /-- Dedekind's linear independence of characters -/ -- See, for example, Keith Conrad's note -- <https://kconrad.math.uconn.edu/blurbs/galoistheory/linearchar.pdf> theorem linear_independent_monoid_hom (G : Type*) [monoid G] (L : Type*) [comm_ring L] [no_zero_divisors L] : @linear_independent _ L (G → L) (λ f, f : (G →* L) → (G → L)) _ _ _ := by letI := classical.dec_eq (G →* L); letI : mul_action L L := distrib_mul_action.to_mul_action; -- We prove linear independence by showing that only the trivial linear combination vanishes. exact linear_independent_iff'.2 -- To do this, we use `finset` induction, (λ s, finset.induction_on s (λ g hg i, false.elim) $ λ a s has ih g hg, -- Here -- * `a` is a new character we will insert into the `finset` of characters `s`, -- * `ih` is the fact that only the trivial linear combination of characters in `s` is zero -- * `hg` is the fact that `g` are the coefficients of a linear combination summing to zero -- and it remains to prove that `g` vanishes on `insert a s`. -- We now make the key calculation: -- For any character `i` in the original `finset`, we have `g i • i = g i • a` as functions on the -- monoid `G`. have h1 : ∀ i ∈ s, (g i • i : G → L) = g i • a, from λ i his, funext $ λ x : G, -- We prove these expressions are equal by showing -- the differences of their values on each monoid element `x` is zero eq_of_sub_eq_zero $ ih (λ j, g j * j x - g j * a x) (funext $ λ y : G, calc -- After that, it's just a chase scene. (∑ i in s, ((g i * i x - g i * a x) • i : G → L)) y = ∑ i in s, (g i * i x - g i * a x) * i y : finset.sum_apply _ _ _ ... = ∑ i in s, (g i * i x * i y - g i * a x * i y) : finset.sum_congr rfl (λ _ _, sub_mul _ _ _) ... = ∑ i in s, g i * i x * i y - ∑ i in s, g i * a x * i y : finset.sum_sub_distrib ... = (g a * a x * a y + ∑ i in s, g i * i x * i y) - (g a * a x * a y + ∑ i in s, g i * a x * i y) : by rw add_sub_add_left_eq_sub ... = ∑ i in insert a s, g i * i x * i y - ∑ i in insert a s, g i * a x * i y : by rw [finset.sum_insert has, finset.sum_insert has] ... = ∑ i in insert a s, g i * i (x * y) - ∑ i in insert a s, a x * (g i * i y) : congr (congr_arg has_sub.sub (finset.sum_congr rfl $ λ i _, by rw [i.map_mul, mul_assoc])) (finset.sum_congr rfl $ λ _ _, by rw [mul_assoc, mul_left_comm]) ... = (∑ i in insert a s, (g i • i : G → L)) (x * y) - a x * (∑ i in insert a s, (g i • i : G → L)) y : by rw [finset.sum_apply, finset.sum_apply, finset.mul_sum]; refl ... = 0 - a x * 0 : by rw hg; refl ... = 0 : by rw [mul_zero, sub_zero]) i his, -- On the other hand, since `a` is not already in `s`, for any character `i ∈ s` -- there is some element of the monoid on which it differs from `a`. have h2 : ∀ i : G →* L, i ∈ s → ∃ y, i y ≠ a y, from λ i his, classical.by_contradiction $ λ h, have hia : i = a, from monoid_hom.ext $ λ y, classical.by_contradiction $ λ hy, h ⟨y, hy⟩, has $ hia ▸ his, -- From these two facts we deduce that `g` actually vanishes on `s`, have h3 : ∀ i ∈ s, g i = 0, from λ i his, let ⟨y, hy⟩ := h2 i his in have h : g i • i y = g i • a y, from congr_fun (h1 i his) y, or.resolve_right (mul_eq_zero.1 $ by rw [mul_sub, sub_eq_zero]; exact h) (sub_ne_zero_of_ne hy), -- And so, using the fact that the linear combination over `s` and over `insert a s` both vanish, -- we deduce that `g a = 0`. have h4 : g a = 0, from calc g a = g a * 1 : (mul_one _).symm ... = (g a • a : G → L) 1 : by rw ← a.map_one; refl ... = (∑ i in insert a s, (g i • i : G → L)) 1 : begin rw finset.sum_eq_single a, { intros i his hia, rw finset.mem_insert at his, rw [h3 i (his.resolve_left hia), zero_smul] }, { intros haas, exfalso, apply haas, exact finset.mem_insert_self a s } end ... = 0 : by rw hg; refl, -- Now we're done; the last two facts together imply that `g` vanishes on every element -- of `insert a s`. (finset.forall_mem_insert _ _ _).2 ⟨h4, h3⟩) lemma le_of_span_le_span [nontrivial R] {s t u: set M} (hl : linear_independent R (coe : u → M )) (hsu : s ⊆ u) (htu : t ⊆ u) (hst : span R s ≤ span R t) : s ⊆ t := begin have := eq_of_linear_independent_of_span_subtype (hl.mono (set.union_subset hsu htu)) (set.subset_union_right _ _) (set.union_subset (set.subset.trans subset_span hst) subset_span), rw ← this, apply set.subset_union_left end lemma span_le_span_iff [nontrivial R] {s t u: set M} (hl : linear_independent R (coe : u → M)) (hsu : s ⊆ u) (htu : t ⊆ u) : span R s ≤ span R t ↔ s ⊆ t := ⟨le_of_span_le_span hl hsu htu, span_mono⟩ end module section nontrivial variables [ring R] [nontrivial R] [add_comm_group M] [add_comm_group M'] variables [module R M] [no_zero_smul_divisors R M] [module R M'] variables {v : ι → M} {s t : set M} {x y z : M} lemma linear_independent_unique_iff (v : ι → M) [unique ι] : linear_independent R v ↔ v (default ι) ≠ 0 := begin simp only [linear_independent_iff, finsupp.total_unique, smul_eq_zero], refine ⟨λ h hv, _, λ hv l hl, finsupp.unique_ext $ hl.resolve_right hv⟩, have := h (finsupp.single (default ι) 1) (or.inr hv), exact one_ne_zero (finsupp.single_eq_zero.1 this) end alias linear_independent_unique_iff ↔ _ linear_independent_unique lemma linear_independent_singleton {x : M} (hx : x ≠ 0) : linear_independent R (λ x, x : ({x} : set M) → M) := linear_independent_unique coe hx end nontrivial /-! ### Properties which require `division_ring K` These can be considered generalizations of properties of linear independence in vector spaces. -/ section module variables [division_ring K] [add_comm_group V] [add_comm_group V'] variables [module K V] [module K V'] variables {v : ι → V} {s t : set V} {x y z : V} open submodule /- TODO: some of the following proofs can generalized with a zero_ne_one predicate type class (instead of a data containing type class) -/ lemma mem_span_insert_exchange : x ∈ span K (insert y s) → x ∉ span K s → y ∈ span K (insert x s) := begin simp [mem_span_insert], rintro a z hz rfl h, refine ⟨a⁻¹, -a⁻¹ • z, smul_mem _ _ hz, _⟩, have a0 : a ≠ 0, {rintro rfl, simp * at *}, simp [a0, smul_add, smul_smul] end lemma linear_independent_iff_not_mem_span : linear_independent K v ↔ (∀i, v i ∉ span K (v '' (univ \ {i}))) := begin apply linear_independent_iff_not_smul_mem_span.trans, split, { intros h i h_in_span, apply one_ne_zero (h i 1 (by simp [h_in_span])) }, { intros h i a ha, by_contradiction ha', exact false.elim (h _ ((smul_mem_iff _ ha').1 ha)) } end lemma linear_independent.insert (hs : linear_independent K (λ b, b : s → V)) (hx : x ∉ span K s) : linear_independent K (λ b, b : insert x s → V) := begin rw ← union_singleton, have x0 : x ≠ 0 := mt (by rintro rfl; apply zero_mem _) hx, apply hs.union (linear_independent_singleton x0), rwa [disjoint_span_singleton' x0] end lemma linear_independent_option' : linear_independent K (λ o, option.cases_on' o x v : option ι → V) ↔ linear_independent K v ∧ (x ∉ submodule.span K (range v)) := begin rw [← linear_independent_equiv (equiv.option_equiv_sum_punit ι).symm, linear_independent_sum, @range_unique _ punit, @linear_independent_unique_iff punit, disjoint_span_singleton], dsimp [(∘)], refine ⟨λ h, ⟨h.1, λ hx, h.2.1 $ h.2.2 hx⟩, λ h, ⟨h.1, _, λ hx, (h.2 hx).elim⟩⟩, rintro rfl, exact h.2 (zero_mem _) end lemma linear_independent.option (hv : linear_independent K v) (hx : x ∉ submodule.span K (range v)) : linear_independent K (λ o, option.cases_on' o x v : option ι → V) := linear_independent_option'.2 ⟨hv, hx⟩ lemma linear_independent_option {v : option ι → V} : linear_independent K v ↔ linear_independent K (v ∘ coe : ι → V) ∧ v none ∉ submodule.span K (range (v ∘ coe : ι → V)) := by simp only [← linear_independent_option', option.cases_on'_none_coe] theorem linear_independent_insert' {ι} {s : set ι} {a : ι} {f : ι → V} (has : a ∉ s) : linear_independent K (λ x : insert a s, f x) ↔ linear_independent K (λ x : s, f x) ∧ f a ∉ submodule.span K (f '' s) := by { rw [← linear_independent_equiv ((equiv.option_equiv_sum_punit _).trans (equiv.set.insert has).symm), linear_independent_option], simp [(∘), range_comp f] } theorem linear_independent_insert (hxs : x ∉ s) : linear_independent K (λ b : insert x s, (b : V)) ↔ linear_independent K (λ b : s, (b : V)) ∧ x ∉ submodule.span K s := (@linear_independent_insert' _ _ _ _ _ _ _ _ id hxs).trans $ by simp lemma linear_independent_pair {x y : V} (hx : x ≠ 0) (hy : ∀ a : K, a • x ≠ y) : linear_independent K (coe : ({x, y} : set V) → V) := pair_comm y x ▸ (linear_independent_singleton hx).insert $ mt mem_span_singleton.1 (not_exists.2 hy) lemma linear_independent_fin_cons {n} {v : fin n → V} : linear_independent K (fin.cons x v : fin (n + 1) → V) ↔ linear_independent K v ∧ x ∉ submodule.span K (range v) := begin rw [← linear_independent_equiv (fin_succ_equiv n).symm, linear_independent_option], convert iff.rfl, { ext, -- TODO: why doesn't simp use `fin_succ_equiv_symm_coe` here? rw [comp_app, comp_app, fin_succ_equiv_symm_coe, fin.cons_succ] }, { rw [comp_app, fin_succ_equiv_symm_none, fin.cons_zero] }, { ext, rw [comp_app, comp_app, fin_succ_equiv_symm_coe, fin.cons_succ] } end lemma linear_independent_fin_snoc {n} {v : fin n → V} : linear_independent K (fin.snoc v x : fin (n + 1) → V) ↔ linear_independent K v ∧ x ∉ submodule.span K (range v) := by rw [fin.snoc_eq_cons_rotate, linear_independent_equiv, linear_independent_fin_cons] /-- See `linear_independent.fin_cons'` for an uglier version that works if you only have a module over a semiring. -/ lemma linear_independent.fin_cons {n} {v : fin n → V} (hv : linear_independent K v) (hx : x ∉ submodule.span K (range v)) : linear_independent K (fin.cons x v : fin (n + 1) → V) := linear_independent_fin_cons.2 ⟨hv, hx⟩ lemma linear_independent_fin_succ {n} {v : fin (n + 1) → V} : linear_independent K v ↔ linear_independent K (fin.tail v) ∧ v 0 ∉ submodule.span K (range $ fin.tail v) := by rw [← linear_independent_fin_cons, fin.cons_self_tail] lemma linear_independent_fin_succ' {n} {v : fin (n + 1) → V} : linear_independent K v ↔ linear_independent K (fin.init v) ∧ v (fin.last _) ∉ submodule.span K (range $ fin.init v) := by rw [← linear_independent_fin_snoc, fin.snoc_init_self] lemma linear_independent_fin2 {f : fin 2 → V} : linear_independent K f ↔ f 1 ≠ 0 ∧ ∀ a : K, a • f 1 ≠ f 0 := by rw [linear_independent_fin_succ, linear_independent_unique_iff, range_unique, mem_span_singleton, not_exists, show fin.tail f (default (fin 1)) = f 1, by rw ← fin.succ_zero_eq_one; refl] lemma exists_linear_independent (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : ∃b⊆t, s ⊆ b ∧ t ⊆ span K b ∧ linear_independent K (λ x, x : b → V) := begin rcases zorn.zorn_subset_nonempty {b | b ⊆ t ∧ linear_independent K (λ x, x : b → V)} _ _ ⟨hst, hs⟩ with ⟨b, ⟨bt, bi⟩, sb, h⟩, { refine ⟨b, bt, sb, λ x xt, _, bi⟩, by_contra hn, apply hn, rw ← h _ ⟨insert_subset.2 ⟨xt, bt⟩, bi.insert hn⟩ (subset_insert _ _), exact subset_span (mem_insert _ _) }, { refine λ c hc cc c0, ⟨⋃₀ c, ⟨_, _⟩, λ x, _⟩, { exact sUnion_subset (λ x xc, (hc xc).1) }, { exact linear_independent_sUnion_of_directed cc.directed_on (λ x xc, (hc xc).2) }, { exact subset_sUnion_of_mem } } end /-- `linear_independent.extend` adds vectors to a linear independent set `s ⊆ t` until it spans all elements of `t`. -/ noncomputable def linear_independent.extend (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : set V := classical.some (exists_linear_independent hs hst) lemma linear_independent.extend_subset (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : hs.extend hst ⊆ t := let ⟨hbt, hsb, htb, hli⟩ := classical.some_spec (exists_linear_independent hs hst) in hbt lemma linear_independent.subset_extend (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : s ⊆ hs.extend hst := let ⟨hbt, hsb, htb, hli⟩ := classical.some_spec (exists_linear_independent hs hst) in hsb lemma linear_independent.subset_span_extend (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : t ⊆ span K (hs.extend hst) := let ⟨hbt, hsb, htb, hli⟩ := classical.some_spec (exists_linear_independent hs hst) in htb lemma linear_independent.linear_independent_extend (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ t) : linear_independent K (coe : hs.extend hst → V) := let ⟨hbt, hsb, htb, hli⟩ := classical.some_spec (exists_linear_independent hs hst) in hli variables {K V} -- TODO(Mario): rewrite? lemma exists_of_linear_independent_of_finite_span {t : finset V} (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ (span K ↑t : submodule K V)) : ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = t.card := have ∀t, ∀(s' : finset V), ↑s' ⊆ s → s ∩ ↑t = ∅ → s ⊆ (span K ↑(s' ∪ t) : submodule K V) → ∃t':finset V, ↑t' ⊆ s ∪ ↑t ∧ s ⊆ ↑t' ∧ t'.card = (s' ∪ t).card := assume t, finset.induction_on t (assume s' hs' _ hss', have s = ↑s', from eq_of_linear_independent_of_span_subtype hs hs' $ by simpa using hss', ⟨s', by simp [this]⟩) (assume b₁ t hb₁t ih s' hs' hst hss', have hb₁s : b₁ ∉ s, from assume h, have b₁ ∈ s ∩ ↑(insert b₁ t), from ⟨h, finset.mem_insert_self _ _⟩, by rwa [hst] at this, have hb₁s' : b₁ ∉ s', from assume h, hb₁s $ hs' h, have hst : s ∩ ↑t = ∅, from eq_empty_of_subset_empty $ subset.trans (by simp [inter_subset_inter, subset.refl]) (le_of_eq hst), classical.by_cases (assume : s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨u, hust, hsu, eq⟩ := ih _ hs' hst this in have hb₁u : b₁ ∉ u, from assume h, (hust h).elim hb₁s hb₁t, ⟨insert b₁ u, by simp [insert_subset_insert hust], subset.trans hsu (by simp), by simp [eq, hb₁t, hb₁s', hb₁u]⟩) (assume : ¬ s ⊆ (span K ↑(s' ∪ t) : submodule K V), let ⟨b₂, hb₂s, hb₂t⟩ := not_subset.mp this in have hb₂t' : b₂ ∉ s' ∪ t, from assume h, hb₂t $ subset_span h, have s ⊆ (span K ↑(insert b₂ s' ∪ t) : submodule K V), from assume b₃ hb₃, have ↑(s' ∪ insert b₁ t) ⊆ insert b₁ (insert b₂ ↑(s' ∪ t) : set V), by simp [insert_eq, -singleton_union, -union_singleton, union_subset_union, subset.refl, subset_union_right], have hb₃ : b₃ ∈ span K (insert b₁ (insert b₂ ↑(s' ∪ t) : set V)), from span_mono this (hss' hb₃), have s ⊆ (span K (insert b₁ ↑(s' ∪ t)) : submodule K V), by simpa [insert_eq, -singleton_union, -union_singleton] using hss', have hb₁ : b₁ ∈ span K (insert b₂ ↑(s' ∪ t)), from mem_span_insert_exchange (this hb₂s) hb₂t, by rw [span_insert_eq_span hb₁] at hb₃; simpa using hb₃, let ⟨u, hust, hsu, eq⟩ := ih _ (by simp [insert_subset, hb₂s, hs']) hst this in ⟨u, subset.trans hust $ union_subset_union (subset.refl _) (by simp [subset_insert]), hsu, by simp [eq, hb₂t', hb₁t, hb₁s']⟩)), begin have eq : t.filter (λx, x ∈ s) ∪ t.filter (λx, x ∉ s) = t, { ext1 x, by_cases x ∈ s; simp * }, apply exists.elim (this (t.filter (λx, x ∉ s)) (t.filter (λx, x ∈ s)) (by simp [set.subset_def]) (by simp [set.ext_iff] {contextual := tt}) (by rwa [eq])), intros u h, exact ⟨u, subset.trans h.1 (by simp [subset_def, and_imp, or_imp_distrib] {contextual:=tt}), h.2.1, by simp only [h.2.2, eq]⟩ end lemma exists_finite_card_le_of_finite_of_linear_independent_of_span (ht : finite t) (hs : linear_independent K (λ x, x : s → V)) (hst : s ⊆ span K t) : ∃h : finite s, h.to_finset.card ≤ ht.to_finset.card := have s ⊆ (span K ↑(ht.to_finset) : submodule K V), by simp; assumption, let ⟨u, hust, hsu, eq⟩ := exists_of_linear_independent_of_finite_span hs this in have finite s, from u.finite_to_set.subset hsu, ⟨this, by rw [←eq]; exact (finset.card_le_of_subset $ finset.coe_subset.mp $ by simp [hsu])⟩ end module
b55ac281c1e265a4bf96c00db15fcec42993ca63
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/tactic/rewrite_search/frontend.lean
a5dbd4bf0b26002f596e9dbfe00b9f8dca941542
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
4,053
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Keeley Hoek, Scott Morrison -/ import tactic.rewrite_search.explain import tactic.rewrite_search.discovery import tactic.rewrite_search.search /-! # `rewrite_search`: solving goals by searching for a series of rewrites. `rewrite_search` is a tactic for solving equalities or iff statements by searching for a sequence of rewrite tactic applications. ## Algorithm sketch The fundamental data structure behind the search algorithm is a graph of expressions. Each vertex represents one expression, and an edge in the graph represents a way to rewrite one expression into another with a single application of a rewrite tactic. Thus, a path in the graph represents a way to rewrite one expression into another with multiple applications of a rewrite tactic. The graph starts out with two vertices, one for the left hand side of the equality, and one for the right hand side of the equality. The basic loop of the algorithm is to repeatedly add edges to the graph by taking vertices in the graph and applying a possible rewrite to them. Through this process, the graph is made up of two connected components; one component contains expressions that are equivalent to the left hand side, and one component contains expressions that are equivalent to the right hand side. The algorithm completes when we discover an edge that connects the two components, creating a path of rewrites that connects the left hand side and right hand side of the graph. For more detail, see Keeley's report at https://hoek.io/res/2018.s2.lean.report.pdf, although note that the edit distance mechanism described is currently not implemented, only plain breadth-first search. This algorithm is generally superior to one that only expands nodes starting from a single side, because it is replacing one tree of depth `2d` with two trees of depth `d`. This is a quadratic speedup for regular trees; our trees aren't regular but it's still probably a much better algorithm. We can only use this specific algorithm for rewrite-type tactics, though, not general sequences of tactics, because it relies on the fact that any rewrite can be reversed. ## File structure * `discovery.lean` contains the logic for figuring out which rewrite rules to consider. * `search.lean` contains the graph algorithms to find a successful sequence of tactics. * `explain.lean` generates concise Lean code to run a tactic, from the autogenerated sequence of tactics. * `frontend.lean` contains the user-facing interface to the `rewrite_search` tactics. * `types.lean` contains data structures shared across multiple of these components. -/ namespace tactic.interactive open lean.parser interactive interactive.types tactic.rewrite_search /-- Search for a chain of rewrites to prove an equation or iff statement. Collects rewrite rules, runs a graph search to find a chain of rewrites to prove the current target, and generates a string explanation for it. Takes an optional list of rewrite rules specified in the same way as the `rw` tactic accepts. -/ meta def rewrite_search (explain : parse $ optional (tk "?")) (rs : parse $ optional (list_of (rw_rule_p $ lean.parser.pexpr 0))) (cfg : config := {}) : tactic unit := do t ← tactic.target, if t.has_meta_var then tactic.fail "rewrite_search is not suitable for goals containing metavariables" else tactic.skip, implicit_rules ← collect_rules, explicit_rules ← (rs.get_or_else []).mmap (λ ⟨_, dir, pe⟩, do e ← to_expr' pe, return (e, dir)), let rules := implicit_rules ++ explicit_rules, g ← mk_graph cfg rules t, (_, proof, steps) ← g.find_proof, tactic.exact proof, if explain.is_some then explain_search_result cfg rules proof steps else skip add_tactic_doc { name := "rewrite_search", category := doc_category.tactic, decl_names := [`tactic.interactive.rewrite_search], tags := ["rewrite", "automation"] } end tactic.interactive
1b0e59cc2f05649dd1968e263d549e9f8bcd2fe0
cc5bb0a18c45fa529fc8bf0365b1fbf48464c5a8
/library/init/meta/coinductive_predicates.lean
8c2f00eece7327d7247f656bc70e5b8c6da5b808
[ "Apache-2.0" ]
permissive
mk12/lean
6bb58b9f3cfe312236b41779478d345399f00918
092fc89333160661c4c5a6295f3054cafff4341e
refs/heads/master
1,609,531,450,083
1,501,275,267,000
1,501,278,025,000
98,760,144
0
0
null
1,501,364,485,000
1,501,364,485,000
null
UTF-8
Lean
false
false
23,187
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl (CMU) -/ prelude import init.meta.expr init.meta.tactic init.meta.constructor_tactic init.meta.attribute import init.meta.interactive namespace name def last_string : name → string | anonymous := "[anonymous]" | (mk_string s _) := s | (mk_numeral _ n) := last_string n end name namespace expr open expr meta def replace_with (e : expr) (s : expr) (s' : expr) : expr := e.replace $ λc d, if c = s then some (s'.lift_vars 0 d) else none meta def local_binder_info : expr → binder_info | (local_const x n bi t) := bi | e := binder_info.default meta def to_implicit_binder : expr → expr | (local_const n₁ n₂ _ d) := local_const n₁ n₂ binder_info.implicit d | (lam n _ d b) := lam n binder_info.implicit d b | (pi n _ d b) := pi n binder_info.implicit d b | e := e meta def get_app_fn_args_aux : list expr → expr → expr × list expr | r (app f a) := get_app_fn_args_aux (a::r) f | r e := (e, r) meta def get_app_fn_args : expr → expr × list expr := get_app_fn_args_aux [] end expr namespace tactic open level expr tactic meta def mk_local_pisn : expr → nat → tactic (list expr × expr) | (pi n bi d b) (c + 1) := do p ← mk_local' n bi d, (ps, r) ← mk_local_pisn (b.instantiate_var p) c, return ((p :: ps), r) | e 0 := return ([], e) | _ _ := failed meta def drop_pis : list expr → expr → tactic expr | (list.cons v vs) (pi n bi d b) := do t ← infer_type v, guard (t =ₐ d), drop_pis vs (b.instantiate_var v) | [] e := return e | _ _ := failed meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration := declaration.thm n ls t (task.pure e) meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) : tactic expr := do ((), body) ← solve_aux type tac, body ← instantiate_mvars body, add_decl $ mk_theorem n ls type body, return $ const n $ ls.map param meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr := args.mfoldr (λarg i:expr, do t ← infer_type arg, sort l ← infer_type t, return $ if arg.occurs i ∨ l ≠ level.zero then (const `Exists [l] : expr) t (i.lambdas [arg]) else (const `and [] : expr) t i) inner meta def mk_op_lst (op : expr) (empty : expr) : list expr → expr | [] := empty | [e] := e | (e :: es) := op e $ mk_op_lst es meta def mk_and_lst : list expr → expr := mk_op_lst `(and) `(true) meta def mk_or_lst : list expr → expr := mk_op_lst `(or) `(false) meta def elim_gen_prod : nat → expr → list expr → tactic (list expr × expr) | 0 e hs := return (hs, e) | (n + 1) e hs := do [([h, h'], _)] ← induction e [], elim_gen_prod n h' (hs ++ [h]) private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr) | 0 e hs := return (hs, e) | (n + 1) e hs := do [([h], _), ([h'], _)] ← induction e [], swap, elim_gen_sum_aux n h' (h::hs) meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do (hs, h') ← elim_gen_sum_aux n e [], gs ← get_goals, set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1), return $ hs.reverse ++ [h'] end tactic section universe u @[user_attribute] def monotonicity := { user_attribute . name := `monotonicity, descr := "Monotonicity rules for predicates" } lemma monotonicity.pi {α : Sort u} {p q : α → Prop} (h : ∀a, implies (p a) (q a)) : implies (Πa, p a) (Πa, q a) := assume h' a, h a (h' a) lemma monotonicity.imp {p p' q q' : Prop} (h₁ : implies p' q') (h₂ : implies q p) : implies (p → p') (q → q') := assume h, h₁ ∘ h ∘ h₂ @[monotonicity] lemma monotonicity.const (p : Prop) : implies p p := id @[monotonicity] lemma monotonicity.true (p : Prop) : implies p true := assume _, trivial @[monotonicity] lemma monotonicity.false (p : Prop) : implies false p := false.elim @[monotonicity] lemma monotonicity.exists {α : Sort u} {p q : α → Prop} (h : ∀a, implies (p a) (q a)) : implies (∃a, p a) (∃a, q a) := exists_imp_exists h @[monotonicity] lemma monotonicity.and {p p' q q' : Prop} (hp : implies p p') (hq : implies q q') : implies (p ∧ q) (p' ∧ q') := and.imp hp hq @[monotonicity] lemma monotonicity.or {p p' q q' : Prop} (hp : implies p p') (hq : implies q q') : implies (p ∨ q) (p' ∨ q') := or.imp hp hq @[monotonicity] lemma monotonicity.not {p q : Prop} (h : implies p q) : implies (¬ q) (¬ p) := mt h end namespace tactic open expr tactic /- TODO: use backchaining -/ private meta def mono_aux (ns : list name) (hs : list expr) : tactic unit := do intros, (do `(implies %%p %%q) ← target, (do is_def_eq p q, eapplyc `monotone.const) <|> (do (expr.pi pn pbi pd pb) ← return p, (expr.pi qn qbi qd qb) ← return q, sort u ← infer_type pd, (do is_def_eq pd qd, let p' := expr.lam pn pbi pd pb, let q' := expr.lam qn qbi qd qb, eapply $ (const `monotonicity.pi [u] : expr) pd p' q') <|> (do guard $ u = level.zero ∧ is_arrow p ∧ is_arrow q, let p' := pb.lower_vars 0 1, let q' := qb.lower_vars 0 1, eapply $ (const `monotonicity.imp []: expr) pd p' qd q'))) <|> first (hs.map $ λh, apply_core h {md := transparency.none, new_goals := new_goals.non_dep_only} >> skip) <|> first (ns.map $ λn, do c ← mk_const n, apply_core c {md := transparency.none, new_goals := new_goals.non_dep_only}, skip), all_goals mono_aux meta def mono (e : expr) (hs : list expr) : tactic unit := do t ← target, t' ← infer_type e, ns ← attribute.get_instances `monotonicity, ((), p) ← solve_aux `(implies %%t' %%t) (mono_aux ns hs), exact (p e) end tactic /- The coinductive predicate `pred`: coinductive {u} pred (A) : a → Prop | r : ∀A b, pred A p where `u` is a list of universe parameters `A` is a list of global parameters `pred` is a list predicates to be defined `a` are the indices for each `pred` `r` is a list of introduction rules for each `pred` `b` is a list of parameters for each rule in `r` and `pred` `p` is are the instances of `a` using `A` and `b` `pred` is compiled to the following defintions: inductive {u} pred.functional (A) ([pred'] : a → Prop) : a → Prop | r : ∀a [f], b[pred/pred'] → pred.functional a [f] p lemma {u} pred.functional.mono (A) ([pred₁] [pred₂] : a → Prop) [(h : ∀b, pred₁ b → pred₂ b)] : ∀p, pred.functional A pred₁ p → pred.functional A pred₂ p def {u} pred_i (A) (a) : Prop := ∃[pred'], (Λi, ∀a, pred_i a → pred_i.functional A [pred] a) ∧ pred'_i a lemma {u} pred_i.corec_functional (A) [Λi, C_i : a_i → Prop] [Λi, h : ∀a, C_i a → pred_i.functional A C_i a] : ∀a, C_i a → pred_i A a lemma {u} pred_i.destruct (A) (a) : pred A a → pred.functional A [pred A] a lemma {u} pred_i.construct (A) : ∀a, pred_i.functional A [pred A] a → pred_i A a lemma {u} pred_i.cases_on (A) (C : a → Prop) {a} (h : pred_i a) [Λi, ∀a, b → C p] → C a lemma {u} pred_i.corec_on (A) [(C : a → Prop)] (a) (h : C_i a) [Λi, h_i : ∀a, C_i a → [V j ∃b, a = p]] : pred_i A a lemma {u} pred.r (A) (b) : pred_i A p -/ namespace tactic open level expr tactic namespace add_coinductive_predicate /- private -/ meta structure coind_rule : Type := (orig_nm : name) (func_nm : name) (type : expr) (loc_type : expr) (args : list expr) (loc_args : list expr) (concl : expr) (insts : list expr) /- private -/ meta structure coind_pred : Type := (u_names : list name) (params : list expr) (pd_name : name) (type : expr) (intros : list coind_rule) (locals : list expr) (f₁ f₂ : expr) (u_f : level) namespace coind_pred meta def u_params (pd : coind_pred) : list level := pd.u_names.map param meta def f₁_l (pd : coind_pred) : expr := pd.f₁.app_of_list pd.locals meta def f₂_l (pd : coind_pred) : expr := pd.f₂.app_of_list pd.locals meta def pred (pd : coind_pred) : expr := const pd.pd_name pd.u_params meta def func (pd : coind_pred) : expr := const (pd.pd_name ++ "functional") pd.u_params meta def func_g (pd : coind_pred) : expr := pd.func.app_of_list $ pd.params meta def pred_g (pd : coind_pred) : expr := pd.pred.app_of_list $ pd.params meta def impl_locals (pd : coind_pred) : list expr := pd.locals.map to_implicit_binder meta def impl_params (pd : coind_pred) : list expr := pd.params.map to_implicit_binder meta def le (pd : coind_pred) (f₁ f₂ : expr) : expr := (imp (f₁.app_of_list pd.locals) (f₂.app_of_list pd.locals)).pis pd.impl_locals meta def corec_functional (pd : coind_pred) : expr := const (pd.pd_name ++ "corec_functional") pd.u_params meta def mono (pd : coind_pred) : expr := const (pd.func.const_name ++ "mono") pd.u_params meta def rec' (pd : coind_pred) : tactic expr := do let c := pd.func.const_name ++ "rec", env ← get_env, decl ← env.get c, let num := decl.univ_params.length, return (const c $ if num = pd.u_params.length then pd.u_params else level.zero :: pd.u_params) -- ^^ `rec`'s universes are not always `u_params`, e.g. eq, wf, false meta def construct (pd : coind_pred) : expr := const (pd.pd_name ++ "construct") pd.u_params meta def destruct (pd : coind_pred) : expr := const (pd.pd_name ++ "destruct") pd.u_params meta def add_theorem (pd : coind_pred) (n : name) (type : expr) (tac : tactic unit) : tactic expr := add_theorem_by n pd.u_names type tac end coind_pred end add_coinductive_predicate open add_coinductive_predicate /- compact_relation bs as_ps: Product a relation of the form: R := λ as, ∃ bs, Λ_i a_i = p_i[bs] This relation is user visible, so we compact it by removing each `b_j` where a `p_i = b_j`, and hence `a_i = b_j`. We need to take care when there are `p_i` and `p_j` with `p_i = p_j = b_k`. -/ private meta def compact_relation : list expr → list (expr × expr) → list expr × list (expr × expr) | [] ps := ([], ps) | (list.cons b bs) ps := match ps.span (λap:expr × expr, ¬ ap.2 =ₐ b) with | (_, []) := let (bs, ps) := compact_relation bs ps in (b::bs, ps) | (ps₁, list.cons (a, _) ps₂) := let i := a.instantiate_local b.local_uniq_name in compact_relation (bs.map i) ((ps₁ ++ ps₂).map (λ⟨a, p⟩, (a, i p))) end meta def add_coinductive_predicate (u_names : list name) (params : list expr) (preds : list $ expr × list expr) : command := do let params_names := params.map local_pp_name, let u_params := u_names.map param, pre_info ← preds.mmap (λ⟨c, is⟩, do (ls, t) ← mk_local_pis c.local_type, (is_def_eq t `(Prop) <|> fail (format! "Type of {c.local_pp_name} is not Prop. Currently only " ++ "coinductive predicates are supported.")), let n := if preds.length = 1 then "" else "_" ++ c.local_pp_name.last_string, f₁ ← mk_local_def (mk_simple_name $ "C" ++ n) c.local_type, f₂ ← mk_local_def (mk_simple_name $ "C₂" ++ n) c.local_type, return (ls, (f₁, f₂))), let fs := pre_info.map prod.snd, let fs₁ := fs.map prod.fst, let fs₂ := fs.map prod.snd, pds ← (preds.zip pre_info).mmap (λ⟨⟨c, is⟩, ls, f₁, f₂⟩, do sort u_f ← infer_type f₁ >>= infer_type, let pred_g := λc:expr, (const c.local_uniq_name u_params : expr).app_of_list params, intros ← is.mmap (λi, do (args, t') ← mk_local_pis i.local_type, (name.mk_string sub p) ← return i.local_uniq_name, let loc_args := args.map $ λe, (fs₁.zip preds).foldl (λ(e:expr) ⟨f, c, _⟩, e.replace_with (pred_g c) f) e, let t' := t'.replace_with (pred_g c) f₂, return { tactic.add_coinductive_predicate.coind_rule . orig_nm := i.local_uniq_name, func_nm := (p ++ "functional") ++ sub, type := i.local_type, loc_type := t'.pis loc_args, concl := t', loc_args := loc_args, args := args, insts := t'.get_app_args }), return { tactic.add_coinductive_predicate.coind_pred . pd_name := c.local_uniq_name, type := c.local_type, f₁ := f₁, f₂ := f₂, u_f := u_f, intros := intros, locals := ls, params := params, u_names := u_names }), /- Introduce all functionals -/ pds.mmap' (λpd:coind_pred, do let func_f₁ := pd.func_g.app_of_list $ fs₁, let func_f₂ := pd.func_g.app_of_list $ fs₂, /- Define functional for `pd` as inductive predicate -/ func_intros ← pd.intros.mmap (λr:coind_rule, do let t := instantiate_local pd.f₂.local_uniq_name (pd.func_g.app_of_list fs₁) r.loc_type, return (r.func_nm, r.orig_nm, t.pis $ params ++ fs₁)), add_inductive pd.func.const_name u_names (params.length + preds.length) (pd.type.pis $ params ++ fs₁) (func_intros.map $ λ⟨t, _, r⟩, (t, r)), /- Prove monotonicity rule -/ mono_params ← pds.mmap (λpd, do h ← mk_local_def `h $ pd.le pd.f₁ pd.f₂, return [pd.f₁, pd.f₂, h]), pd.add_theorem (pd.func.const_name ++ "mono") ((pd.le func_f₁ func_f₂).pis $ params ++ mono_params.join) (do ps ← intro_lst $ params.map expr.local_pp_name, fs ← pds.mmap (λpd, do [f₁, f₂, h] ← intro_lst [pd.f₁.local_pp_name, pd.f₂.local_pp_name, `h], -- the type of h' reduces to h let h' := local_const h.local_uniq_name h.local_pp_name h.local_binder_info $ (((const `implies [] : expr) (f₁.app_of_list pd.locals) (f₂.app_of_list pd.locals)).pis pd.locals).instantiate_locals $ (ps.zip params).map $ λ⟨lv, p⟩, (p.local_uniq_name, lv), return (f₂, h')), m ← pd.rec', eapply $ m.app_of_list ps, -- somehow `induction` / `cases` doesn't work? func_intros.mmap' (λ⟨n, pp_n, t⟩, solve1 $ do bs ← intros, ms ← apply_core ((const n u_params).app_of_list $ ps ++ fs.map prod.fst) {new_goals := new_goals.all}, params ← (ms.zip bs).enum.mfilter (λ⟨n, m, d⟩, bnot <$> is_assigned m), params.mmap' (λ⟨n, m, d⟩, mono d (fs.map prod.snd) <|> fail format! "failed to prove montonoicity of {n+1}. parameter of intro-rule {pp_n}")))), pds.mmap' (λpd, do let func_f := λpd:coind_pred, pd.func_g.app_of_list $ pds.map coind_pred.f₁, /- define final predicate -/ pred_body ← mk_exists_lst (pds.map coind_pred.f₁) $ mk_and_lst $ (pds.map $ λpd, pd.le pd.f₁ (func_f pd)) ++ [pd.f₁.app_of_list pd.locals], add_decl $ mk_definition pd.pd_name u_names (pd.type.pis $ params) $ pred_body.lambdas $ params ++ pd.locals, /- prove `corec_functional` rule -/ hs ← pds.mmap $ λpd:coind_pred, mk_local_def `hc $ pd.le pd.f₁ (func_f pd), pd.add_theorem (pd.pred.const_name ++ "corec_functional") ((pd.le pd.f₁ pd.pred_g).pis $ params ++ fs₁ ++ hs) (do intro_lst $ params.map local_pp_name, fs ← intro_lst $ fs₁.map local_pp_name, hs ← intro_lst $ hs.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, whnf_target, fs.mmap' existsi, hs.mmap' (λf, econstructor >> exact f), exact h)), let func_f := λpd : coind_pred, pd.func_g.app_of_list $ pds.map coind_pred.pred_g, /- prove `destruct` rules -/ pds.enum.mmap' (λ⟨n, pd⟩, do let destruct := pd.le pd.pred_g (func_f pd), pd.add_theorem (pd.pred.const_name ++ "destruct") (destruct.pis params) (do ps ← intro_lst $ params.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, (fs, h) ← elim_gen_prod pds.length h [], (hs, h) ← elim_gen_prod pds.length h [], eapply $ pd.mono.app_of_list ps, pds.mmap' (λpd:coind_pred, focus1 $ do eapply $ pd.corec_functional, focus $ hs.map exact), some h' ← return $ hs.nth n, eapply h', exact h)), /- prove `construct` rules -/ pds.mmap' (λpd, pd.add_theorem (pd.pred.const_name ++ "construct") ((pd.le (func_f pd) pd.pred_g).pis params) (do ps ← intro_lst $ params.map local_pp_name, let func_pred_g := λpd:coind_pred, pd.func.app_of_list $ ps ++ pds.map (λpd:coind_pred, pd.pred.app_of_list ps), eapply $ pd.corec_functional.app_of_list $ ps ++ pds.map func_pred_g, pds.mmap' (λpd:coind_pred, solve1 $ do eapply $ pd.mono.app_of_list ps, pds.mmap' (λpd, solve1 $ eapply $ pd.destruct.app_of_list ps)))), /- prove `cases_on` rules -/ pds.mmap' (λpd, do let C := pd.f₁.to_implicit_binder, h ← mk_local_def `h $ pd.pred_g.app_of_list pd.locals, rules ← pd.intros.mmap (λr:coind_rule, do mk_local_def (mk_simple_name r.orig_nm.last_string) $ (C.app_of_list r.insts).pis r.args), cases_on ← pd.add_theorem (pd.pred.const_name ++ "cases_on") ((C.app_of_list pd.locals).pis $ params ++ [C] ++ pd.impl_locals ++ [h] ++ rules) (do ps ← intro_lst $ params.map local_pp_name, C ← intro `C, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, rules ← intro_lst $ rules.map local_pp_name, func_rec ← pd.rec', eapply $ func_rec.app_of_list $ ps ++ pds.map (λpd, pd.pred.app_of_list ps) ++ [C] ++ rules, eapply $ pd.destruct, exact h), set_basic_attribute `elab_as_eliminator cases_on.const_name), /- prove `corec_on` rules -/ pds.mmap' (λpd, do rules ← pds.mmap (λpd, do intros ← pd.intros.mmap (λr, do let (bs, eqs) := compact_relation r.loc_args $ pd.locals.zip r.insts, eqs ← eqs.mmap (λ⟨l, i⟩, do sort u ← infer_type l.local_type, return $ (const `eq [u] : expr) l.local_type i l), match bs, eqs with | [], [] := return ((0, 0), mk_true) | _, [] := prod.mk (bs.length, 0) <$> mk_exists_lst bs.init bs.ilast.local_type | _, _ := prod.mk (bs.length, eqs.length) <$> mk_exists_lst bs (mk_and_lst eqs) end), let shape := intros.map prod.fst, let intros := intros.map prod.snd, prod.mk shape <$> mk_local_def (mk_simple_name $ "h_" ++ pd.pd_name.last_string) (((pd.f₁.app_of_list pd.locals).imp (mk_or_lst intros)).pis pd.locals)), let shape := rules.map prod.fst, let rules := rules.map prod.snd, h ← mk_local_def `h $ pd.f₁.app_of_list pd.locals, pd.add_theorem (pd.pred.const_name ++ "corec_on") ((pd.pred_g.app_of_list $ pd.locals).pis $ params ++ fs₁ ++ pd.impl_locals ++ [h] ++ rules) (do ps ← intro_lst $ params.map local_pp_name, fs ← intro_lst $ fs₁.map local_pp_name, ls ← intro_lst $ pd.locals.map local_pp_name, h ← intro `h, rules ← intro_lst $ rules.map local_pp_name, eapply $ pd.corec_functional.app_of_list $ ps ++ fs, (pds.zip $ rules.zip shape).mmap (λ⟨pd, hr, s⟩, solve1 $ do ls ← intro_lst $ pd.locals.map local_pp_name, h' ← intro `h, h' ← note `h' none $ hr.app_of_list ls h', match s.length with | 0 := induction h' >> skip -- h' : false | (n+1) := do hs ← elim_gen_sum n h', (hs.zip $ pd.intros.zip s).mmap' (λ⟨h, r, n_bs, n_eqs⟩, solve1 $ do (as, h) ← elim_gen_prod (n_bs - (if n_eqs = 0 then 1 else 0)) h [], if n_eqs > 0 then do (eqs, eq') ← elim_gen_prod (n_eqs - 1) h [], (eqs ++ [eq']).mmap' subst else skip, eapply ((const r.func_nm u_params).app_of_list $ ps ++ fs), repeat assumption) end), exact h)), /- prove constructors -/ pds.mmap' (λpd, pd.intros.mmap' (λr, pd.add_theorem r.orig_nm (r.type.pis params) $ do ps ← intro_lst $ params.map local_pp_name, bs ← intros, eapply $ pd.construct, exact $ (const r.func_nm u_params).app_of_list $ ps ++ pds.map (λpd, pd.pred.app_of_list ps) ++ bs)), pds.mmap' (λpd:coind_pred, set_basic_attribute `irreducible pd.pd_name), try triv -- we setup a trivial goal for the tactic framework open lean.parser open interactive @[user_command] meta def coinductive_predicate (meta_info : decl_meta_info) (_ : parse $ tk "coinductive") : lean.parser unit := do decl ← inductive_decl.parse meta_info, add_coinductive_predicate decl.u_names decl.params $ decl.decls.map $ λ d, (d.sig, d.intros), decl.decls.mmap' $ λ d, do { get_env >>= λ env, set_env $ env.add_namespace d.name, meta_info.attrs.apply d.name, d.attrs.apply d.name, some doc_string ← pure meta_info.doc_string | skip, add_doc_string d.name doc_string } /-- Prepares coinduction proofs. This tactic constructs the coinduction invariant from the quantifiers in the current goal. Current version: do not support mutual inductive rules (i.e. only a since C -/ meta def coinduction (rule : expr) : tactic unit := focus1 $ do ctxts' ← intros, -- TODO: why do we need to fix the type here? ctxts ← ctxts'.mmap (λv, local_const v.local_uniq_name v.local_pp_name v.local_binder_info <$> infer_type v), mvars ← apply_core rule {approx := ff, new_goals := new_goals.all}, -- analyse relation g ← list.head <$> get_goals, (list.cons _ m_is) ← return $ mvars.drop_while (λv, v ≠ g), tgt ← target, (is, ty) ← mk_local_pis tgt, -- construct coinduction predicate (bs, eqs) ← compact_relation ctxts <$> ((is.zip m_is).mmap (λ⟨i, m⟩, prod.mk i <$> instantiate_mvars m)), solve1 (do eqs ← mk_and_lst <$> eqs.mmap (λ⟨i, m⟩, mk_app `eq [m, i] >>= instantiate_mvars), rel ← mk_exists_lst bs eqs, exact (rel.lambdas is)), -- prove predicate solve1 (do target >>= instantiate_mvars >>= change, -- TODO: bug in existsi & constructor when mvars in hyptohesis bs.mmap existsi, repeat econstructor), -- clean up remaining coinduction steps all_goals (do ctxts'.reverse.mmap clear, target >>= instantiate_mvars >>= change, -- TODO: bug in subst when mvars in hyptohesis is ← intro_lst $ is.map expr.local_pp_name, h ← intro1, (_, h) ← elim_gen_prod (bs.length - (if eqs.length = 0 then 1 else 0)) h [], (match eqs with | [] := clear h | (e::eqs) := do (hs, h) ← elim_gen_prod eqs.length h [], (h::(hs.reverse)).mmap' subst end)) namespace interactive open interactive interactive.types expr lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many meta def coinduction (corec_name : parse ident) (revert : parse $ (tk "generalizing" *> ident*)?) : tactic unit := do rule ← mk_const corec_name, locals ← mmap tactic.get_local $ revert.get_or_else [], revert_lst locals, tactic.coinduction rule, skip end interactive end tactic
576c297f6f6965e1eca1e00ed663b416c523441c
bdb33f8b7ea65f7705fc342a178508e2722eb851
/data/fp/basic.lean
14d0c4d9595de0aa5e1ebd53968e74460d14754c
[ "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
6,809
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Implementation of floating-point numbers (experimental). -/ import data.rat namespace fp inductive rmode | NE -- round to nearest even class float_cfg := (prec emax : ℕ) (prec_pos : prec > 0) (prec_max : prec ≤ emax) variable [C : float_cfg] include C def prec := C.prec def emax := C.emax def emin : ℤ := 1 - C.emax structure nan_pl := (sign : bool) (pl : fin (2^prec)) (pl_pos : 0 < pl.1) class fpsettings := (merge_nan : nan_pl → nan_pl → nan_pl) (default_nan : nan_pl) namespace lean instance fpsettings : fpsettings := { merge_nan := λ n1 n2, n1, default_nan := ⟨ff, ⟨1, nat.pow_lt_pow_of_lt_right dec_trivial C.prec_pos⟩, dec_trivial⟩ } end lean def valid_finite (e : ℤ) (m : ℕ) : Prop := emin ≤ e + prec - 1 ∧ e + prec - 1 ≤ emax ∧ e = max (e + m.size - prec) emin instance dec_valid_finite (e m) : decidable (valid_finite e m) := by unfold valid_finite; apply_instance inductive float | inf {} : bool → float | nan {} : nan_pl → float | finite {} : bool → Π e m, valid_finite e m → float def float.is_finite : float → bool | (float.finite s e m f) := tt | _ := ff def shift2 (a b : ℕ) : ℤ → ℕ × ℕ | (int.of_nat e) := (a.shiftl e, b) | -[1+ e] := (a, b.shiftl e.succ) def to_rat : Π (f : float), f.is_finite → ℚ | (float.finite s e m f) _ := let (n, d) := shift2 m 1 e, r := rat.mk_nat n d in if s then -r else r theorem float.zero.valid : valid_finite emin 0 := ⟨begin rw add_sub_assoc, apply le_add_of_nonneg_right, apply sub_nonneg_of_le, apply int.coe_nat_le_coe_nat_of_le, exact C.prec_pos end, by simpa [emin] using show (prec : ℤ) ≤ emax + float_cfg.emax, from le_trans (int.coe_nat_le.2 C.prec_max) (le_add_of_nonneg_left (int.coe_zero_le _)), by rw max_eq_right; simp⟩ def float.zero (s : bool) : float := float.finite s emin 0 float.zero.valid protected def float.sign : float → bool | (float.inf s) := s | (float.nan ⟨s, pl, h⟩) := s | (float.finite s e m f) := s protected def float.is_zero : float → bool | (float.finite s e 0 f) := tt | _ := ff protected def float.neg : float → float | (float.inf s) := float.inf (bnot s) | (float.nan ⟨s, pl, h⟩) := float.nan ⟨bnot s, pl, h⟩ | (float.finite s e m f) := float.finite (bnot s) e m f def div_nat_lt_two_pow (n d : ℕ) : ℤ → bool | (int.of_nat e) := n < d.shiftl e | -[1+ e] := n.shiftl e.succ < d -- TODO(Mario): Prove these and drop 'meta' set_option eqn_compiler.zeta true meta def of_pos_rat_dn (n : ℕ+) (d : ℕ+) : float × bool := let e₁ : ℤ := n.1.size - d.1.size - prec, (d₁, n₁) := shift2 d.1 n.1 (e₁ + prec), e₂ := if n₁ < d₁ then e₁ - 1 else e₁, e₃ := max e₂ emin, (d₂, n₂) := shift2 d.1 n.1 (e₃ + prec), r := rat.mk_nat n₂ d₂, m := r.floor in (float.finite ff e₃ (int.to_nat m) undefined, r.denom = 1) meta def next_up_pos (e m) (v : valid_finite e m) : float := let m' := m.succ in if ss : m'.size = m.size then float.finite ff e m' (by unfold valid_finite at *; rw ss; exact v) else if h : e = emax then float.inf ff else float.finite ff e.succ (nat.div2 m') undefined meta def next_dn_pos (e m) (v : valid_finite e m) : float := match m with | 0 := next_up_pos _ _ float.zero.valid | nat.succ m' := if ss : m'.size = m.size then float.finite ff e m' (by unfold valid_finite at *; rw ss; exact v) else if h : e = emin then float.finite ff emin m' undefined else float.finite ff e.pred (bit1 m') undefined end meta def next_up : float → float | (float.finite ff e m f) := next_up_pos e m f | (float.finite tt e m f) := float.neg $ next_dn_pos e m f | f := f meta def next_dn : float → float | (float.finite ff e m f) := next_dn_pos e m f | (float.finite tt e m f) := float.neg $ next_up_pos e m f | f := f meta def of_rat_up : ℚ → float | ⟨0, _, _, _⟩ := float.zero ff | ⟨nat.succ n, d, h, _⟩ := let (f, exact) := of_pos_rat_dn n.succ_pnat ⟨d, h⟩ in if exact then f else next_up f | ⟨-[1+n], d, h, _⟩ := float.neg (of_pos_rat_dn n.succ_pnat ⟨d, h⟩).1 meta def of_rat_dn (r : ℚ) : float := float.neg $ of_rat_up (-r) meta def of_rat : rmode → ℚ → float | rmode.NE r := let low := of_rat_dn r, high := of_rat_up r in if hf : high.is_finite then if r = to_rat _ hf then high else if lf : low.is_finite then if r - to_rat _ lf > to_rat _ hf - r then high else if r - to_rat _ lf < to_rat _ hf - r then low else match low, lf with float.finite s e m f, _ := if 2 ∣ m then low else high end else float.inf tt else float.inf ff namespace float variable [S : fpsettings] def default_nan : float := nan fpsettings.default_nan instance : has_neg float := ⟨float.neg⟩ meta def add (mode : rmode) : float → float → float | (nan p₁) (nan p₂) := nan $ fpsettings.merge_nan p₁ p₂ | (nan p₁) _ := nan p₁ | _ (nan p₂) := nan p₂ | (inf tt) (inf ff) := default_nan | (inf ff) (inf tt) := default_nan | (inf s₁) _ := inf s₁ | _ (inf s₂) := inf s₂ | (finite s₁ e₁ m₁ v₁) (finite s₂ e₂ m₂ v₂) := let f₁ := finite s₁ e₁ m₁ v₁, f₂ := finite s₂ e₂ m₂ v₂ in of_rat mode (to_rat f₁ rfl + to_rat f₂ rfl) meta instance : has_add float := ⟨float.add rmode.NE⟩ meta def sub (mode : rmode) (f1 f2 : float) : float := add mode f1 (-f2) meta instance : has_sub float := ⟨float.sub rmode.NE⟩ meta def mul (mode : rmode) : float → float → float | (nan p₁) (nan p₂) := nan $ fpsettings.merge_nan p₁ p₂ | (nan p₁) _ := nan p₁ | _ (nan p₂) := nan p₂ | (inf s₁) f₂ := if f₂.is_zero then default_nan else inf (bxor s₁ f₂.sign) | f₁ (inf s₂) := if f₁.is_zero then default_nan else inf (bxor f₁.sign s₂) | (finite s₁ e₁ m₁ v₁) (finite s₂ e₂ m₂ v₂) := let f₁ := finite s₁ e₁ m₁ v₁, f₂ := finite s₂ e₂ m₂ v₂ in of_rat mode (to_rat f₁ rfl * to_rat f₂ rfl) meta def div (mode : rmode) : float → float → float | (nan p₁) (nan p₂) := nan $ fpsettings.merge_nan p₁ p₂ | (nan p₁) _ := nan p₁ | _ (nan p₂) := nan p₂ | (inf s₁) (inf s₂) := default_nan | (inf s₁) f₂ := inf (bxor s₁ f₂.sign) | f₁ (inf s₂) := zero (bxor f₁.sign s₂) | (finite s₁ e₁ m₁ v₁) (finite s₂ e₂ m₂ v₂) := let f₁ := finite s₁ e₁ m₁ v₁, f₂ := finite s₂ e₂ m₂ v₂ in if f₂.is_zero then inf (bxor s₁ s₂) else of_rat mode (to_rat f₁ rfl / to_rat f₂ rfl) end float end fp
d5367cb61ce983fe5ecca7ecec3b348a731d8c1e
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/shrinking_lemma.lean
811c342b1486c504d5b485e0abd22a5f9f8f7c9e
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
12,202
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Reid Barton -/ import topology.separation /-! # The shrinking lemma In this file we prove a few versions of the shrinking lemma. The lemma says that in a normal topological space a point finite open covering can be “shrunk”: for a point finite open covering `u : ι → set X` there exists a refinement `v : ι → set X` such that `closure (v i) ⊆ u i`. For finite or countable coverings this lemma can be proved without the axiom of choice, see [ncatlab](https://ncatlab.org/nlab/show/shrinking+lemma) for details. We only formalize the most general result that works for any covering but needs the axiom of choice. We prove two versions of the lemma: * `exists_subset_Union_closure_subset` deals with a covering of a closed set in a normal space; * `exists_Union_eq_closure_subset` deals with a covering of the whole space. ## Tags normal space, shrinking lemma -/ open set zorn function open_locale classical noncomputable theory variables {ι X : Type*} [topological_space X] [normal_space X] namespace shrinking_lemma /-- Auxiliary definition for the proof of `shrinking_lemma`. A partial refinement of a covering `⋃ i, u i` of a set `s` is a map `v : ι → set X` and a set `carrier : set ι` such that * `s ⊆ ⋃ i, v i`; * all `v i` are open; * if `i ∈ carrier v`, then `closure (v i) ⊆ u i`; * if `i ∉ carrier`, then `v i = u i`. This type is equipped with the folowing partial order: `v ≤ v'` if `v.carrier ⊆ v'.carrier` and `v i = v' i` for `i ∈ v.carrier`. We will use Zorn's lemma to prove that this type has a maximal element, then show that the maximal element must have `carrier = univ`. -/ @[nolint has_inhabited_instance] -- the trivial refinement needs `u` to be a covering structure partial_refinement (u : ι → set X) (s : set X) := (to_fun : ι → set X) (carrier : set ι) (is_open' : ∀ i, is_open (to_fun i)) (subset_Union' : s ⊆ ⋃ i, to_fun i) (closure_subset' : ∀ i ∈ carrier, closure (to_fun i) ⊆ (u i)) (apply_eq' : ∀ i ∉ carrier, to_fun i = u i) namespace partial_refinement variables {u : ι → set X} {s : set X} instance : has_coe_to_fun (partial_refinement u s) (λ _, ι → set X) := ⟨to_fun⟩ lemma subset_Union (v : partial_refinement u s) : s ⊆ ⋃ i, v i := v.subset_Union' lemma closure_subset (v : partial_refinement u s) {i : ι} (hi : i ∈ v.carrier) : closure (v i) ⊆ (u i) := v.closure_subset' i hi lemma apply_eq (v : partial_refinement u s) {i : ι} (hi : i ∉ v.carrier) : v i = u i := v.apply_eq' i hi protected lemma is_open (v : partial_refinement u s) (i : ι) : is_open (v i) := v.is_open' i protected lemma subset (v : partial_refinement u s) (i : ι) : v i ⊆ u i := if h : i ∈ v.carrier then subset.trans subset_closure (v.closure_subset h) else (v.apply_eq h).le attribute [ext] partial_refinement instance : partial_order (partial_refinement u s) := { le := λ v₁ v₂, v₁.carrier ⊆ v₂.carrier ∧ ∀ i ∈ v₁.carrier, v₁ i = v₂ i, le_refl := λ v, ⟨subset.refl _, λ _ _, rfl⟩, le_trans := λ v₁ v₂ v₃ h₁₂ h₂₃, ⟨subset.trans h₁₂.1 h₂₃.1, λ i hi, (h₁₂.2 i hi).trans (h₂₃.2 i $ h₁₂.1 hi)⟩, le_antisymm := λ v₁ v₂ h₁₂ h₂₁, have hc : v₁.carrier = v₂.carrier, from subset.antisymm h₁₂.1 h₂₁.1, ext _ _ (funext $ λ x, if hx : x ∈ v₁.carrier then h₁₂.2 _ hx else (v₁.apply_eq hx).trans (eq.symm $ v₂.apply_eq $ hc ▸ hx)) hc } /-- If two partial refinements `v₁`, `v₂` belong to a chain (hence, they are comparable) and `i` belongs to the carriers of both partial refinements, then `v₁ i = v₂ i`. -/ lemma apply_eq_of_chain {c : set (partial_refinement u s)} (hc : chain (≤) c) {v₁ v₂} (h₁ : v₁ ∈ c) (h₂ : v₂ ∈ c) {i} (hi₁ : i ∈ v₁.carrier) (hi₂ : i ∈ v₂.carrier) : v₁ i = v₂ i := begin wlog hle : v₁ ≤ v₂ := hc.total_of_refl h₁ h₂ using [v₁ v₂, v₂ v₁], exact hle.2 _ hi₁, end /-- The carrier of the least upper bound of a non-empty chain of partial refinements is the union of their carriers. -/ def chain_Sup_carrier (c : set (partial_refinement u s)) : set ι := ⋃ v ∈ c, carrier v /-- Choice of an element of a nonempty chain of partial refinements. If `i` belongs to one of `carrier v`, `v ∈ c`, then `find c ne i` is one of these partial refinements. -/ def find (c : set (partial_refinement u s)) (ne : c.nonempty) (i : ι) : partial_refinement u s := if hi : ∃ v ∈ c, i ∈ carrier v then hi.some else ne.some lemma find_mem {c : set (partial_refinement u s)} (i : ι) (ne : c.nonempty) : find c ne i ∈ c := by { rw find, split_ifs, exacts [h.some_spec.fst, ne.some_spec] } lemma mem_find_carrier_iff {c : set (partial_refinement u s)} {i : ι} (ne : c.nonempty) : i ∈ (find c ne i).carrier ↔ i ∈ chain_Sup_carrier c := begin rw find, split_ifs, { have : i ∈ h.some.carrier ∧ i ∈ chain_Sup_carrier c, from ⟨h.some_spec.snd, mem_Union₂.2 h⟩, simp only [this] }, { have : i ∉ ne.some.carrier ∧ i ∉ chain_Sup_carrier c, from ⟨λ hi, h ⟨_, ne.some_spec, hi⟩, mt mem_Union₂.1 h⟩, simp only [this] } end lemma find_apply_of_mem {c : set (partial_refinement u s)} (hc : chain (≤) c) (ne : c.nonempty) {i v} (hv : v ∈ c) (hi : i ∈ carrier v) : find c ne i i = v i := apply_eq_of_chain hc (find_mem _ _) hv ((mem_find_carrier_iff _).2 $ mem_Union₂.2 ⟨v, hv, hi⟩) hi /-- Least upper bound of a nonempty chain of partial refinements. -/ def chain_Sup (c : set (partial_refinement u s)) (hc : chain (≤) c) (ne : c.nonempty) (hfin : ∀ x ∈ s, finite {i | x ∈ u i}) (hU : s ⊆ ⋃ i, u i) : partial_refinement u s := begin refine ⟨λ i, find c ne i i, chain_Sup_carrier c, λ i, (find _ _ _).is_open i, λ x hxs, mem_Union.2 _, λ i hi, (find c ne i).closure_subset ((mem_find_carrier_iff _).2 hi), λ i hi, (find c ne i).apply_eq (mt (mem_find_carrier_iff _).1 hi)⟩, rcases em (∃ i ∉ chain_Sup_carrier c, x ∈ u i) with ⟨i, hi, hxi⟩|hx, { use i, rwa (find c ne i).apply_eq (mt (mem_find_carrier_iff _).1 hi) }, { simp_rw [not_exists, not_imp_not, chain_Sup_carrier, mem_Union₂] at hx, haveI : nonempty (partial_refinement u s) := ⟨ne.some⟩, choose! v hvc hiv using hx, rcases (hfin x hxs).exists_maximal_wrt v _ (mem_Union.1 (hU hxs)) with ⟨i, hxi : x ∈ u i, hmax : ∀ j, x ∈ u j → v i ≤ v j → v i = v j⟩, rcases mem_Union.1 ((v i).subset_Union hxs) with ⟨j, hj⟩, use j, have hj' : x ∈ u j := (v i).subset _ hj, have : v j ≤ v i, from (hc.total_of_refl (hvc _ hxi) (hvc _ hj')).elim (λ h, (hmax j hj' h).ge) id, rwa find_apply_of_mem hc ne (hvc _ hxi) (this.1 $ hiv _ hj') } end /-- `chain_Sup hu c hc ne hfin hU` is an upper bound of the chain `c`. -/ lemma le_chain_Sup {c : set (partial_refinement u s)} (hc : chain (≤) c) (ne : c.nonempty) (hfin : ∀ x ∈ s, finite {i | x ∈ u i}) (hU : s ⊆ ⋃ i, u i) {v} (hv : v ∈ c) : v ≤ chain_Sup c hc ne hfin hU := ⟨λ i hi, mem_bUnion hv hi, λ i hi, (find_apply_of_mem hc _ hv hi).symm⟩ /-- If `s` is a closed set, `v` is a partial refinement, and `i` is an index such that `i ∉ v.carrier`, then there exists a partial refinement that is strictly greater than `v`. -/ lemma exists_gt (v : partial_refinement u s) (hs : is_closed s) (i : ι) (hi : i ∉ v.carrier) : ∃ v' : partial_refinement u s, v < v' := begin have I : s ∩ (⋂ j ≠ i, (v j)ᶜ) ⊆ v i, { simp only [subset_def, mem_inter_eq, mem_Inter, and_imp], intros x hxs H, rcases mem_Union.1 (v.subset_Union hxs) with ⟨j, hj⟩, exact (em (j = i)).elim (λ h, h ▸ hj) (λ h, (H j h hj).elim) }, have C : is_closed (s ∩ (⋂ j ≠ i, (v j)ᶜ)), from is_closed.inter hs (is_closed_bInter $ λ _ _, is_closed_compl_iff.2 $ v.is_open _), rcases normal_exists_closure_subset C (v.is_open i) I with ⟨vi, ovi, hvi, cvi⟩, refine ⟨⟨update v i vi, insert i v.carrier, _, _, _, _⟩, _, _⟩, { intro j, by_cases h : j = i; simp [h, ovi, v.is_open] }, { refine λ x hx, mem_Union.2 _, rcases em (∃ j ≠ i, x ∈ v j) with ⟨j, hji, hj⟩|h, { use j, rwa update_noteq hji }, { push_neg at h, use i, rw update_same, exact hvi ⟨hx, mem_bInter h⟩ } }, { rintro j (rfl|hj), { rwa [update_same, ← v.apply_eq hi] }, { rw update_noteq (ne_of_mem_of_not_mem hj hi), exact v.closure_subset hj } }, { intros j hj, rw [mem_insert_iff, not_or_distrib] at hj, rw [update_noteq hj.1, v.apply_eq hj.2] }, { refine ⟨subset_insert _ _, λ j hj, _⟩, exact (update_noteq (ne_of_mem_of_not_mem hj hi) _ _).symm }, { exact λ hle, hi (hle.1 $ mem_insert _ _) } end end partial_refinement end shrinking_lemma open shrinking_lemma variables {u : ι → set X} {s : set X} /-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk" to a new open cover so that the closure of each new open set is contained in the corresponding original open set. -/ lemma exists_subset_Union_closure_subset (hs : is_closed s) (uo : ∀ i, is_open (u i)) (uf : ∀ x ∈ s, finite {i | x ∈ u i}) (us : s ⊆ ⋃ i, u i) : ∃ v : ι → set X, s ⊆ Union v ∧ (∀ i, is_open (v i)) ∧ ∀ i, closure (v i) ⊆ u i := begin classical, haveI : nonempty (partial_refinement u s) := ⟨⟨u, ∅, uo, us, λ _, false.elim, λ _ _, rfl⟩⟩, have : ∀ c : set (partial_refinement u s), chain (≤) c → c.nonempty → ∃ ub, ∀ v ∈ c, v ≤ ub, from λ c hc ne, ⟨partial_refinement.chain_Sup c hc ne uf us, λ v hv, partial_refinement.le_chain_Sup _ _ _ _ hv⟩, rcases zorn_nonempty_partial_order this with ⟨v, hv⟩, suffices : ∀ i, i ∈ v.carrier, from ⟨v, v.subset_Union, λ i, v.is_open _, λ i, v.closure_subset (this i)⟩, contrapose! hv, rcases hv with ⟨i, hi⟩, rcases v.exists_gt hs i hi with ⟨v', hlt⟩, exact ⟨v', hlt.le, hlt.ne'⟩ end /-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk" to a new closed cover so that each new closed set is contained in the corresponding original open set. See also `exists_subset_Union_closure_subset` for a stronger statement. -/ lemma exists_subset_Union_closed_subset (hs : is_closed s) (uo : ∀ i, is_open (u i)) (uf : ∀ x ∈ s, finite {i | x ∈ u i}) (us : s ⊆ ⋃ i, u i) : ∃ v : ι → set X, s ⊆ Union v ∧ (∀ i, is_closed (v i)) ∧ ∀ i, v i ⊆ u i := let ⟨v, hsv, hvo, hv⟩ := exists_subset_Union_closure_subset hs uo uf us in ⟨λ i, closure (v i), subset.trans hsv (Union_mono $ λ i, subset_closure), λ i, is_closed_closure, hv⟩ /-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk" to a new open cover so that the closure of each new open set is contained in the corresponding original open set. -/ lemma exists_Union_eq_closure_subset (uo : ∀ i, is_open (u i)) (uf : ∀ x, finite {i | x ∈ u i}) (uU : (⋃ i, u i) = univ) : ∃ v : ι → set X, Union v = univ ∧ (∀ i, is_open (v i)) ∧ ∀ i, closure (v i) ⊆ u i := let ⟨v, vU, hv⟩ := exists_subset_Union_closure_subset is_closed_univ uo (λ x _, uf x) uU.ge in ⟨v, univ_subset_iff.1 vU, hv⟩ /-- Shrinking lemma. A point-finite open cover of a closed subset of a normal space can be "shrunk" to a new closed cover so that each of the new closed sets is contained in the corresponding original open set. See also `exists_Union_eq_closure_subset` for a stronger statement. -/ lemma exists_Union_eq_closed_subset (uo : ∀ i, is_open (u i)) (uf : ∀ x, finite {i | x ∈ u i}) (uU : (⋃ i, u i) = univ) : ∃ v : ι → set X, Union v = univ ∧ (∀ i, is_closed (v i)) ∧ ∀ i, v i ⊆ u i := let ⟨v, vU, hv⟩ := exists_subset_Union_closed_subset is_closed_univ uo (λ x _, uf x) uU.ge in ⟨v, univ_subset_iff.1 vU, hv⟩
75c6e851f737d9480dae0e55d96ae57f2b283362
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/measure_theory/measurable_space_def.lean
7dbb7923caccff77b686304db9131c23d9842167
[ "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,003
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 -/ import data.set.disjointed import data.set.countable import algebra.indicator_function import data.equiv.encodable.lattice import data.tprod import order.filter.lift /-! # Measurable spaces and measurable functions This file defines measurable spaces and measurable functions. A measurable space is a set equipped with a σ-algebra, a collection of subsets closed under complementation and countable union. A function between measurable spaces is measurable if the preimage of each measurable subset is measurable. σ-algebras on a fixed set `α` form a complete lattice. Here we order σ-algebras by writing `m₁ ≤ m₂` if every set which is `m₁`-measurable is also `m₂`-measurable (that is, `m₁` is a subset of `m₂`). In particular, any collection of subsets of `α` generates a smallest σ-algebra which contains all of them. Do not add measurability lemmas (which could be tagged with @[measurability]) to this file, since the measurability tactic is downstream from here. Use `measure_theory.measurable_space` instead. ## References * <https://en.wikipedia.org/wiki/Measurable_space> * <https://en.wikipedia.org/wiki/Sigma-algebra> * <https://en.wikipedia.org/wiki/Dynkin_system> ## Tags measurable space, σ-algebra, measurable function -/ open set encodable function equiv open_locale classical filter variables {α β γ δ δ' : Type*} {ι : Sort*} {s t u : set α} /-- A measurable space is a space equipped with a σ-algebra. -/ structure measurable_space (α : Type*) := (measurable_set' : set α → Prop) (measurable_set_empty : measurable_set' ∅) (measurable_set_compl : ∀ s, measurable_set' s → measurable_set' sᶜ) (measurable_set_Union : ∀ f : ℕ → set α, (∀ i, measurable_set' (f i)) → measurable_set' (⋃ i, f i)) attribute [class] measurable_space instance [h : measurable_space α] : measurable_space (order_dual α) := h section variable [measurable_space α] /-- `measurable_set s` means that `s` is measurable (in the ambient measure space on `α`) -/ def measurable_set : set α → Prop := ‹measurable_space α›.measurable_set' @[simp] lemma measurable_set.empty : measurable_set (∅ : set α) := ‹measurable_space α›.measurable_set_empty lemma measurable_set.compl : measurable_set s → measurable_set sᶜ := ‹measurable_space α›.measurable_set_compl s lemma measurable_set.of_compl (h : measurable_set sᶜ) : measurable_set s := compl_compl s ▸ h.compl @[simp] lemma measurable_set.compl_iff : measurable_set sᶜ ↔ measurable_set s := ⟨measurable_set.of_compl, measurable_set.compl⟩ @[simp] lemma measurable_set.univ : measurable_set (univ : set α) := by simpa using (@measurable_set.empty α _).compl @[nontriviality] lemma subsingleton.measurable_set [subsingleton α] {s : set α} : measurable_set s := subsingleton.set_cases measurable_set.empty measurable_set.univ s lemma measurable_set.congr {s t : set α} (hs : measurable_set s) (h : s = t) : measurable_set t := by rwa ← h lemma measurable_set.bUnion_decode₂ [encodable β] ⦃f : β → set α⦄ (h : ∀ b, measurable_set (f b)) (n : ℕ) : measurable_set (⋃ b ∈ decode₂ β n, f b) := encodable.Union_decode₂_cases measurable_set.empty h lemma measurable_set.Union [encodable β] ⦃f : β → set α⦄ (h : ∀ b, measurable_set (f b)) : measurable_set (⋃ b, f b) := begin rw ← encodable.Union_decode₂, exact ‹measurable_space α›.measurable_set_Union _ (measurable_set.bUnion_decode₂ h) end lemma measurable_set.bUnion {f : β → set α} {s : set β} (hs : countable s) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋃ b ∈ s, f b) := begin rw bUnion_eq_Union, haveI := hs.to_encodable, exact measurable_set.Union (by simpa using h) end lemma set.finite.measurable_set_bUnion {f : β → set α} {s : set β} (hs : finite s) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋃ b ∈ s, f b) := measurable_set.bUnion hs.countable h lemma finset.measurable_set_bUnion {f : β → set α} (s : finset β) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋃ b ∈ s, f b) := s.finite_to_set.measurable_set_bUnion h lemma measurable_set.sUnion {s : set (set α)} (hs : countable s) (h : ∀ t ∈ s, measurable_set t) : measurable_set (⋃₀ s) := by { rw sUnion_eq_bUnion, exact measurable_set.bUnion hs h } lemma set.finite.measurable_set_sUnion {s : set (set α)} (hs : finite s) (h : ∀ t ∈ s, measurable_set t) : measurable_set (⋃₀ s) := measurable_set.sUnion hs.countable h lemma measurable_set.Union_Prop {p : Prop} {f : p → set α} (hf : ∀ b, measurable_set (f b)) : measurable_set (⋃ b, f b) := by { by_cases p; simp [h, hf, measurable_set.empty] } lemma measurable_set.Inter [encodable β] {f : β → set α} (h : ∀ b, measurable_set (f b)) : measurable_set (⋂ b, f b) := measurable_set.compl_iff.1 $ by { rw compl_Inter, exact measurable_set.Union (λ b, (h b).compl) } section fintype local attribute [instance] fintype.encodable lemma measurable_set.Union_fintype [fintype β] {f : β → set α} (h : ∀ b, measurable_set (f b)) : measurable_set (⋃ b, f b) := measurable_set.Union h lemma measurable_set.Inter_fintype [fintype β] {f : β → set α} (h : ∀ b, measurable_set (f b)) : measurable_set (⋂ b, f b) := measurable_set.Inter h end fintype lemma measurable_set.bInter {f : β → set α} {s : set β} (hs : countable s) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋂ b ∈ s, f b) := measurable_set.compl_iff.1 $ by { rw compl_bInter, exact measurable_set.bUnion hs (λ b hb, (h b hb).compl) } lemma set.finite.measurable_set_bInter {f : β → set α} {s : set β} (hs : finite s) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋂ b ∈ s, f b) := measurable_set.bInter hs.countable h lemma finset.measurable_set_bInter {f : β → set α} (s : finset β) (h : ∀ b ∈ s, measurable_set (f b)) : measurable_set (⋂ b ∈ s, f b) := s.finite_to_set.measurable_set_bInter h lemma measurable_set.sInter {s : set (set α)} (hs : countable s) (h : ∀ t ∈ s, measurable_set t) : measurable_set (⋂₀ s) := by { rw sInter_eq_bInter, exact measurable_set.bInter hs h } lemma set.finite.measurable_set_sInter {s : set (set α)} (hs : finite s) (h : ∀ t ∈ s, measurable_set t) : measurable_set (⋂₀ s) := measurable_set.sInter hs.countable h lemma measurable_set.Inter_Prop {p : Prop} {f : p → set α} (hf : ∀ b, measurable_set (f b)) : measurable_set (⋂ b, f b) := by { by_cases p; simp [h, hf, measurable_set.univ] } @[simp] lemma measurable_set.union {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (s₁ ∪ s₂) := by { rw union_eq_Union, exact measurable_set.Union (bool.forall_bool.2 ⟨h₂, h₁⟩) } @[simp] lemma measurable_set.inter {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (s₁ ∩ s₂) := by { rw inter_eq_compl_compl_union_compl, exact (h₁.compl.union h₂.compl).compl } @[simp] lemma measurable_set.diff {s₁ s₂ : set α} (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (s₁ \ s₂) := h₁.inter h₂.compl @[simp] lemma measurable_set.ite {t s₁ s₂ : set α} (ht : measurable_set t) (h₁ : measurable_set s₁) (h₂ : measurable_set s₂) : measurable_set (t.ite s₁ s₂) := (h₁.inter ht).union (h₂.diff ht) @[simp] lemma measurable_set.disjointed {f : ℕ → set α} (h : ∀ i, measurable_set (f i)) (n) : measurable_set (disjointed f n) := disjointed_induct (h n) (assume t i ht, measurable_set.diff ht $ h _) @[simp] lemma measurable_set.const (p : Prop) : measurable_set {a : α | p} := by { by_cases p; simp [h, measurable_set.empty]; apply measurable_set.univ } /-- Every set has a measurable superset. Declare this as local instance as needed. -/ lemma nonempty_measurable_superset (s : set α) : nonempty { t // s ⊆ t ∧ measurable_set t} := ⟨⟨univ, subset_univ s, measurable_set.univ⟩⟩ end @[ext] lemma measurable_space.ext : ∀ {m₁ m₂ : measurable_space α}, (∀ s : set α, m₁.measurable_set' s ↔ m₂.measurable_set' s) → m₁ = m₂ | ⟨s₁, _, _, _⟩ ⟨s₂, _, _, _⟩ h := have s₁ = s₂, from funext $ assume x, propext $ h x, by subst this @[ext] lemma measurable_space.ext_iff {m₁ m₂ : measurable_space α} : m₁ = m₂ ↔ (∀ s : set α, m₁.measurable_set' s ↔ m₂.measurable_set' s) := ⟨by { unfreezingI {rintro rfl}, intro s, refl }, measurable_space.ext⟩ /-- A typeclass mixin for `measurable_space`s such that each singleton is measurable. -/ class measurable_singleton_class (α : Type*) [measurable_space α] : Prop := (measurable_set_singleton : ∀ x, measurable_set ({x} : set α)) export measurable_singleton_class (measurable_set_singleton) attribute [simp] measurable_set_singleton section measurable_singleton_class variables [measurable_space α] [measurable_singleton_class α] lemma measurable_set_eq {a : α} : measurable_set {x | x = a} := measurable_set_singleton a lemma measurable_set.insert {s : set α} (hs : measurable_set s) (a : α) : measurable_set (insert a s) := (measurable_set_singleton a).union hs @[simp] lemma measurable_set_insert {a : α} {s : set α} : measurable_set (insert a s) ↔ measurable_set s := ⟨λ h, if ha : a ∈ s then by rwa ← insert_eq_of_mem ha else insert_diff_self_of_not_mem ha ▸ h.diff (measurable_set_singleton _), λ h, h.insert a⟩ lemma set.finite.measurable_set {s : set α} (hs : finite s) : measurable_set s := finite.induction_on hs measurable_set.empty $ λ a s ha hsf hsm, hsm.insert _ protected lemma finset.measurable_set (s : finset α) : measurable_set (↑s : set α) := s.finite_to_set.measurable_set lemma set.countable.measurable_set {s : set α} (hs : countable s) : measurable_set s := begin rw [← bUnion_of_singleton s], exact measurable_set.bUnion hs (λ b hb, measurable_set_singleton b) end end measurable_singleton_class namespace measurable_space section complete_lattice instance : partial_order (measurable_space α) := { le := λ m₁ m₂, m₁.measurable_set' ≤ m₂.measurable_set', le_refl := assume a b, le_refl _, le_trans := assume a b c, le_trans, le_antisymm := assume a b h₁ h₂, measurable_space.ext $ assume s, ⟨h₁ s, h₂ s⟩ } /-- The smallest σ-algebra containing a collection `s` of basic sets -/ inductive generate_measurable (s : set (set α)) : set α → Prop | basic : ∀ u ∈ s, generate_measurable u | empty : generate_measurable ∅ | compl : ∀ s, generate_measurable s → generate_measurable sᶜ | union : ∀ f : ℕ → set α, (∀ n, generate_measurable (f n)) → generate_measurable (⋃ i, f i) /-- Construct the smallest measure space containing a collection of basic sets -/ def generate_from (s : set (set α)) : measurable_space α := { measurable_set' := generate_measurable s, measurable_set_empty := generate_measurable.empty, measurable_set_compl := generate_measurable.compl, measurable_set_Union := generate_measurable.union } lemma measurable_set_generate_from {s : set (set α)} {t : set α} (ht : t ∈ s) : (generate_from s).measurable_set' t := generate_measurable.basic t ht lemma generate_from_le {s : set (set α)} {m : measurable_space α} (h : ∀ t ∈ s, m.measurable_set' t) : generate_from s ≤ m := assume t (ht : generate_measurable s t), ht.rec_on h (measurable_set_empty m) (assume s _ hs, measurable_set_compl m s hs) (assume f _ hf, measurable_set_Union m f hf) lemma generate_from_le_iff {s : set (set α)} (m : measurable_space α) : generate_from s ≤ m ↔ s ⊆ {t | m.measurable_set' t} := iff.intro (assume h u hu, h _ $ measurable_set_generate_from hu) (assume h, generate_from_le h) @[simp] lemma generate_from_measurable_set [measurable_space α] : generate_from {s : set α | measurable_set s} = ‹_› := le_antisymm (generate_from_le $ λ _, id) $ λ s, measurable_set_generate_from /-- If `g` is a collection of subsets of `α` such that the `σ`-algebra generated from `g` contains the same sets as `g`, then `g` was already a `σ`-algebra. -/ protected def mk_of_closure (g : set (set α)) (hg : {t | (generate_from g).measurable_set' t} = g) : measurable_space α := { measurable_set' := λ s, s ∈ g, measurable_set_empty := hg ▸ measurable_set_empty _, measurable_set_compl := hg ▸ measurable_set_compl _, measurable_set_Union := hg ▸ measurable_set_Union _ } lemma mk_of_closure_sets {s : set (set α)} {hs : {t | (generate_from s).measurable_set' t} = s} : measurable_space.mk_of_closure s hs = generate_from s := measurable_space.ext $ assume t, show t ∈ s ↔ _, by { conv_lhs { rw [← hs] }, refl } /-- We get a Galois insertion between `σ`-algebras on `α` and `set (set α)` by using `generate_from` on one side and the collection of measurable sets on the other side. -/ def gi_generate_from : galois_insertion (@generate_from α) (λ m, {t | @measurable_set α m t}) := { gc := assume s, generate_from_le_iff, le_l_u := assume m s, measurable_set_generate_from, choice := λ g hg, measurable_space.mk_of_closure g $ le_antisymm hg $ (generate_from_le_iff _).1 le_rfl, choice_eq := assume g hg, mk_of_closure_sets } instance : complete_lattice (measurable_space α) := gi_generate_from.lift_complete_lattice instance : inhabited (measurable_space α) := ⟨⊤⟩ lemma measurable_set_bot_iff {s : set α} : @measurable_set α ⊥ s ↔ (s = ∅ ∨ s = univ) := let b : measurable_space α := { measurable_set' := λ s, s = ∅ ∨ s = univ, measurable_set_empty := or.inl rfl, measurable_set_compl := by simp [or_imp_distrib] {contextual := tt}, measurable_set_Union := assume f hf, classical.by_cases (assume h : ∃i, f i = univ, let ⟨i, hi⟩ := h in or.inr $ eq_univ_of_univ_subset $ hi ▸ le_supr f i) (assume h : ¬ ∃i, f i = univ, or.inl $ eq_empty_of_subset_empty $ Union_subset $ assume i, (hf i).elim (by simp {contextual := tt}) (assume hi, false.elim $ h ⟨i, hi⟩)) } in have b = ⊥, from bot_unique $ assume s hs, hs.elim (λ s, s.symm ▸ @measurable_set_empty _ ⊥) (λ s, s.symm ▸ @measurable_set.univ _ ⊥), this ▸ iff.rfl @[simp] theorem measurable_set_top {s : set α} : @measurable_set _ ⊤ s := trivial @[simp] theorem measurable_set_inf {m₁ m₂ : measurable_space α} {s : set α} : @measurable_set _ (m₁ ⊓ m₂) s ↔ @measurable_set _ m₁ s ∧ @measurable_set _ m₂ s := iff.rfl @[simp] theorem measurable_set_Inf {ms : set (measurable_space α)} {s : set α} : @measurable_set _ (Inf ms) s ↔ ∀ m ∈ ms, @measurable_set _ m s := show s ∈ (⋂ m ∈ ms, {t | @measurable_set _ m t }) ↔ _, by simp @[simp] theorem measurable_set_infi {ι} {m : ι → measurable_space α} {s : set α} : @measurable_set _ (infi m) s ↔ ∀ i, @measurable_set _ (m i) s := show s ∈ (λ m, {s | @measurable_set _ m s }) (infi m) ↔ _, by { rw (@gi_generate_from α).gc.u_infi, simp } theorem measurable_set_sup {m₁ m₂ : measurable_space α} {s : set α} : @measurable_set _ (m₁ ⊔ m₂) s ↔ generate_measurable (m₁.measurable_set' ∪ m₂.measurable_set') s := iff.refl _ theorem measurable_set_Sup {ms : set (measurable_space α)} {s : set α} : @measurable_set _ (Sup ms) s ↔ generate_measurable {s : set α | ∃ m ∈ ms, @measurable_set _ m s} s := begin change @measurable_set' _ (generate_from $ ⋃ m ∈ ms, _) _ ↔ _, simp [generate_from, ← set_of_exists] end theorem measurable_set_supr {ι} {m : ι → measurable_space α} {s : set α} : @measurable_set _ (supr m) s ↔ generate_measurable {s : set α | ∃ i, @measurable_set _ (m i) s} s := begin convert @measurable_set_Sup _ (range m) s, simp, end end complete_lattice end measurable_space section measurable_functions open measurable_space /-- A function `f` between measurable spaces is measurable if the preimage of every measurable set is measurable. -/ def measurable [measurable_space α] [measurable_space β] (f : α → β) : Prop := ∀ ⦃t : set β⦄, measurable_set t → measurable_set (f ⁻¹' t) variables [measurable_space α] [measurable_space β] [measurable_space γ] lemma measurable_id : measurable (@id α) := λ t, id lemma measurable_id' : measurable (λ a : α, a) := measurable_id lemma measurable.comp {g : β → γ} {f : α → β} (hg : measurable g) (hf : measurable f) : measurable (g ∘ f) := λ t ht, hf (hg ht) @[simp] lemma measurable_const {a : α} : measurable (λ b : β, a) := assume s hs, measurable_set.const (a ∈ s) end measurable_functions
2670ddd2e93ad88e190f15fc566ca3480e064923
43390109ab88557e6090f3245c47479c123ee500
/src/Topology/Material/real_results.lean
1ad88efc3486bacdf4f11f371dec638c31f77639
[ "Apache-2.0" ]
permissive
Ja1941/xena-UROP-2018
41f0956519f94d56b8bf6834a8d39473f4923200
b111fb87f343cf79eca3b886f99ee15c1dd9884b
refs/heads/master
1,662,355,955,139
1,590,577,325,000
1,590,577,325,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,680
lean
/- Copyright (c) 2018 Luca Gerolla. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luca Gerolla, Kevin Buzzard Prove basic results of real continuous functions and closed intervals -/ import analysis.topology.continuity import analysis.topology.topological_space import analysis.topology.infinite_sum import analysis.topology.topological_structures import analysis.topology.uniform_space import analysis.real import data.real.basic tactic.norm_num import data.set.basic universe u open set filter lattice classical noncomputable theory -- Useful continuity results for functions ℝ → ℝ theorem real.continuous_add_const (r : ℝ) : continuous (λ x : ℝ, x + r) := begin have H₁ : continuous (λ x, (x,r) : ℝ → ℝ × ℝ), exact continuous.prod_mk continuous_id continuous_const, exact continuous.comp H₁ continuous_add', end theorem real.continuous_sub_const (r : ℝ) : continuous (λ x : ℝ, x - r) := continuous_sub continuous_id continuous_const theorem real.continuous_mul_const (r : ℝ) : continuous (λ x : ℝ, r*x) := begin have H₁ : continuous (λ x, (r,x) : ℝ → ℝ × ℝ), exact continuous.prod_mk continuous_const continuous_id, show continuous ( (λ p : ℝ × ℝ , p.1 * p.2) ∘ (λ (x : ℝ), (r,x))), refine continuous.comp H₁ continuous_mul' , end theorem real.continuous_mul_const_right (r : ℝ) : continuous (λ x : ℝ, x*r) := begin have H₁ : continuous (λ x, (x,r) : ℝ → ℝ × ℝ), exact continuous.prod_mk continuous_id continuous_const, refine continuous.comp H₁ continuous_mul' , end theorem real.continuous_div_const (r : ℝ) : continuous (λ x : ℝ, x / r) := begin conv in (_ / r) begin rw div_eq_mul_inv, end, have H₁ : continuous (λ x, (x,r⁻¹) : ℝ → ℝ × ℝ), exact continuous.prod_mk continuous_id continuous_const, exact continuous.comp H₁ continuous_mul', end theorem real.continuous_scale (a b : ℝ) : continuous (λ x : ℝ, (x + a) / b) := continuous.comp (real.continuous_add_const a) (real.continuous_div_const b) theorem real.continuous_linear (m q : ℝ) : continuous (λ x : ℝ, m * x + q) := continuous.comp (real.continuous_mul_const m) (real.continuous_add_const q) --- Definition of closed intervals in ℝ def int_clos { r s : ℝ } ( Hrs : r < s ) : set ℝ := {x : ℝ | r ≤ x ∧ x ≤ s} theorem is_closed_int_clos { r s : ℝ } ( Hrs : r < s ) : is_closed (int_clos Hrs) := is_closed_inter (is_closed_ge' r) (is_closed_le' s)
af4ea0d2627974c461ca5bd372259f921f16b25f
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/run/meta5.lean
724639b32021d8cd770a10f196950c4cfef00d7d
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
631
lean
import Lean.Meta open Lean open Lean.Meta def tst1 : MetaM Unit := withLocalDeclD `y (mkConst `Nat) $ fun y => do withLetDecl `x (mkConst `Nat) (mkNatLit 0) $ fun x => do { mvar ← mkFreshExprMVar (mkConst `Nat) MetavarKind.syntheticOpaque; trace! `Meta mvar; r ← mkLambdaFVars #[y, x] mvar; trace! `Meta r; let v := mkApp2 (mkConst `Nat.add) x y; assignExprMVar mvar.mvarId! v; trace! `Meta mvar; trace! `Meta r; mctx ← getMCtx; mctx.decls.forM $ fun mvarId mvarDecl => do { trace! `Meta ("?" ++ mvarId ++ " : " ++ mvarDecl.type); pure () }; pure () } set_option trace.Meta true #eval tst1
7f6518c449378feb1fee91b2d082455cd62b5353
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/group_theory/perm/cycle_type.lean
f55de161b79ffd511c8b497bc9d8351e3a88b659
[ "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
26,296
lean
/- Copyright (c) 2020 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import algebra.gcd_monoid.multiset import combinatorics.partition import group_theory.perm.cycles import ring_theory.int.basic import tactic.linarith /-! # Cycle Types In this file we define the cycle type of a permutation. ## Main definitions - `σ.cycle_type` where `σ` is a permutation of a `fintype` - `σ.partition` where `σ` is a permutation of a `fintype` ## Main results - `sum_cycle_type` : The sum of `σ.cycle_type` equals `σ.support.card` - `lcm_cycle_type` : The lcm of `σ.cycle_type` equals `order_of σ` - `is_conj_iff_cycle_type_eq` : Two permutations are conjugate if and only if they have the same cycle type. * `exists_prime_order_of_dvd_card`: For every prime `p` dividing the order of a finite group `G` there exists an element of order `p` in `G`. This is known as Cauchy`s theorem. -/ namespace equiv.perm open equiv list multiset variables {α : Type*} [fintype α] section cycle_type variables [decidable_eq α] /-- The cycle type of a permutation -/ def cycle_type (σ : perm α) : multiset ℕ := σ.cycle_factors_finset.1.map (finset.card ∘ support) lemma cycle_type_def (σ : perm α) : σ.cycle_type = σ.cycle_factors_finset.1.map (finset.card ∘ support) := rfl lemma cycle_type_eq' {σ : perm α} (s : finset (perm α)) (h1 : ∀ f : perm α, f ∈ s → f.is_cycle) (h2 : ∀ (a ∈ s) (b ∈ s), a ≠ b → disjoint a b) (h0 : s.noncomm_prod id (λ a ha b hb, (em (a = b)).by_cases (λ h, h ▸ commute.refl a) (set.pairwise_on.mono' (λ _ _, disjoint.commute) h2 a ha b hb)) = σ) : σ.cycle_type = s.1.map (finset.card ∘ support) := begin rw cycle_type_def, congr, rw cycle_factors_finset_eq_finset, exact ⟨h1, h2, h0⟩ end lemma cycle_type_eq {σ : perm α} (l : list (perm α)) (h0 : l.prod = σ) (h1 : ∀ σ : perm α, σ ∈ l → σ.is_cycle) (h2 : l.pairwise disjoint) : σ.cycle_type = l.map (finset.card ∘ support) := begin have hl : l.nodup := nodup_of_pairwise_disjoint_cycles h1 h2, rw cycle_type_eq' l.to_finset, { simp [list.erase_dup_eq_self.mpr hl] }, { simpa using h1 }, { simpa [hl] using h0 }, { simpa [list.erase_dup_eq_self.mpr hl] using list.forall_of_pairwise disjoint.symmetric h2 } end lemma cycle_type_one : (1 : perm α).cycle_type = 0 := cycle_type_eq [] rfl (λ _, false.elim) pairwise.nil lemma cycle_type_eq_zero {σ : perm α} : σ.cycle_type = 0 ↔ σ = 1 := by simp [cycle_type_def, cycle_factors_finset_eq_empty_iff] lemma card_cycle_type_eq_zero {σ : perm α} : σ.cycle_type.card = 0 ↔ σ = 1 := by rw [card_eq_zero, cycle_type_eq_zero] lemma two_le_of_mem_cycle_type {σ : perm α} {n : ℕ} (h : n ∈ σ.cycle_type) : 2 ≤ n := begin simp only [cycle_type_def, ←finset.mem_def, function.comp_app, multiset.mem_map, mem_cycle_factors_finset_iff] at h, obtain ⟨_, ⟨hc, -⟩, rfl⟩ := h, exact hc.two_le_card_support end lemma one_lt_of_mem_cycle_type {σ : perm α} {n : ℕ} (h : n ∈ σ.cycle_type) : 1 < n := two_le_of_mem_cycle_type h lemma is_cycle.cycle_type {σ : perm α} (hσ : is_cycle σ) : σ.cycle_type = [σ.support.card] := cycle_type_eq [σ] (mul_one σ) (λ τ hτ, (congr_arg is_cycle (list.mem_singleton.mp hτ)).mpr hσ) (pairwise_singleton disjoint σ) lemma card_cycle_type_eq_one {σ : perm α} : σ.cycle_type.card = 1 ↔ σ.is_cycle := begin rw card_eq_one, simp_rw [cycle_type_def, multiset.map_eq_singleton, ←finset.singleton_val, finset.val_inj, cycle_factors_finset_eq_singleton_iff], split, { rintro ⟨_, _, ⟨h, -⟩, -⟩, exact h }, { intro h, use [σ.support.card, σ], simp [h] } end lemma disjoint.cycle_type {σ τ : perm α} (h : disjoint σ τ) : (σ * τ).cycle_type = σ.cycle_type + τ.cycle_type := begin rw [cycle_type_def, cycle_type_def, cycle_type_def, h.cycle_factors_finset_mul_eq_union, ←map_add, finset.union_val, multiset.add_eq_union_iff_disjoint.mpr _], rw [←finset.disjoint_val], exact h.disjoint_cycle_factors_finset end lemma cycle_type_inv (σ : perm α) : σ⁻¹.cycle_type = σ.cycle_type := cycle_induction_on (λ τ : perm α, τ⁻¹.cycle_type = τ.cycle_type) σ rfl (λ σ hσ, by rw [hσ.cycle_type, hσ.inv.cycle_type, support_inv]) (λ σ τ hστ hc hσ hτ, by rw [mul_inv_rev, hστ.cycle_type, ←hσ, ←hτ, add_comm, disjoint.cycle_type (λ x, or.imp (λ h : τ x = x, inv_eq_iff_eq.mpr h.symm) (λ h : σ x = x, inv_eq_iff_eq.mpr h.symm) (hστ x).symm)]) lemma cycle_type_conj {σ τ : perm α} : (τ * σ * τ⁻¹).cycle_type = σ.cycle_type := begin revert τ, apply cycle_induction_on _ σ, { intro, simp }, { intros σ hσ τ, rw [hσ.cycle_type, hσ.is_cycle_conj.cycle_type, card_support_conj] }, { intros σ τ hd hc hσ hτ π, rw [← conj_mul, hd.cycle_type, disjoint.cycle_type, hσ, hτ], intro a, apply (hd (π⁻¹ a)).imp _ _; { intro h, rw [perm.mul_apply, perm.mul_apply, h, apply_inv_self] } } end lemma sum_cycle_type (σ : perm α) : σ.cycle_type.sum = σ.support.card := cycle_induction_on (λ τ : perm α, τ.cycle_type.sum = τ.support.card) σ (by rw [cycle_type_one, sum_zero, support_one, finset.card_empty]) (λ σ hσ, by rw [hσ.cycle_type, coe_sum, list.sum_singleton]) (λ σ τ hστ hc hσ hτ, by rw [hστ.cycle_type, sum_add, hσ, hτ, hστ.card_support_mul]) lemma sign_of_cycle_type (σ : perm α) : sign σ = (σ.cycle_type.map (λ n, -(-1 : units ℤ) ^ n)).prod := cycle_induction_on (λ τ : perm α, sign τ = (τ.cycle_type.map (λ n, -(-1 : units ℤ) ^ n)).prod) σ (by rw [sign_one, cycle_type_one, map_zero, prod_zero]) (λ σ hσ, by rw [hσ.sign, hσ.cycle_type, coe_map, coe_prod, list.map_singleton, list.prod_singleton]) (λ σ τ hστ hc hσ hτ, by rw [sign_mul, hσ, hτ, hστ.cycle_type, map_add, prod_add]) lemma lcm_cycle_type (σ : perm α) : σ.cycle_type.lcm = order_of σ := cycle_induction_on (λ τ : perm α, τ.cycle_type.lcm = order_of τ) σ (by rw [cycle_type_one, lcm_zero, order_of_one]) (λ σ hσ, by rw [hσ.cycle_type, ←singleton_coe, ←singleton_eq_cons, lcm_singleton, order_of_is_cycle hσ, normalize_eq]) (λ σ τ hστ hc hσ hτ, by rw [hστ.cycle_type, lcm_add, lcm_eq_nat_lcm, hστ.order_of, hσ, hτ]) lemma dvd_of_mem_cycle_type {σ : perm α} {n : ℕ} (h : n ∈ σ.cycle_type) : n ∣ order_of σ := begin rw ← lcm_cycle_type, exact dvd_lcm h, end lemma order_of_cycle_of_dvd_order_of (f : perm α) (x : α) : order_of (cycle_of f x) ∣ order_of f := begin by_cases hx : f x = x, { rw ←cycle_of_eq_one_iff at hx, simp [hx] }, { refine dvd_of_mem_cycle_type _, rw [cycle_type, multiset.mem_map], refine ⟨f.cycle_of x, _, _⟩, { rwa [←finset.mem_def, cycle_of_mem_cycle_factors_finset_iff, mem_support] }, { simp [order_of_is_cycle (is_cycle_cycle_of _ hx)] } } end lemma two_dvd_card_support {σ : perm α} (hσ : σ ^ 2 = 1) : 2 ∣ σ.support.card := (congr_arg (has_dvd.dvd 2) σ.sum_cycle_type).mp (multiset.dvd_sum (λ n hn, by rw le_antisymm (nat.le_of_dvd zero_lt_two $ (dvd_of_mem_cycle_type hn).trans $ order_of_dvd_of_pow_eq_one hσ) (two_le_of_mem_cycle_type hn))) lemma cycle_type_prime_order {σ : perm α} (hσ : (order_of σ).prime) : ∃ n : ℕ, σ.cycle_type = repeat (order_of σ) (n + 1) := begin rw eq_repeat_of_mem (λ n hn, or_iff_not_imp_left.mp (hσ.2 n (dvd_of_mem_cycle_type hn)) (ne_of_gt (one_lt_of_mem_cycle_type hn))), use σ.cycle_type.card - 1, rw nat.sub_add_cancel, rw [nat.succ_le_iff, pos_iff_ne_zero, ne, card_cycle_type_eq_zero], rintro rfl, rw order_of_one at hσ, exact hσ.ne_one rfl, end lemma is_cycle_of_prime_order {σ : perm α} (h1 : (order_of σ).prime) (h2 : σ.support.card < 2 * (order_of σ)) : σ.is_cycle := begin obtain ⟨n, hn⟩ := cycle_type_prime_order h1, rw [←σ.sum_cycle_type, hn, multiset.sum_repeat, nsmul_eq_mul, nat.cast_id, mul_lt_mul_right (order_of_pos σ), nat.succ_lt_succ_iff, nat.lt_succ_iff, nat.le_zero_iff] at h2, rw [←card_cycle_type_eq_one, hn, card_repeat, h2], end lemma cycle_type_le_of_mem_cycle_factors_finset {f g : perm α} (hf : f ∈ g.cycle_factors_finset) : f.cycle_type ≤ g.cycle_type := begin rw mem_cycle_factors_finset_iff at hf, rw [cycle_type_def, cycle_type_def, hf.left.cycle_factors_finset_eq_singleton], refine map_le_map _, simpa [←finset.mem_def, mem_cycle_factors_finset_iff] using hf end lemma cycle_type_mul_mem_cycle_factors_finset_eq_sub {f g : perm α} (hf : f ∈ g.cycle_factors_finset) : (g * f⁻¹).cycle_type = g.cycle_type - f.cycle_type := begin suffices : (g * f⁻¹).cycle_type + f.cycle_type = g.cycle_type - f.cycle_type + f.cycle_type, { rw sub_add_cancel_of_le (cycle_type_le_of_mem_cycle_factors_finset hf) at this, simp [←this] }, simp [←(disjoint_mul_inv_of_mem_cycle_factors_finset hf).cycle_type, sub_add_cancel_of_le (cycle_type_le_of_mem_cycle_factors_finset hf)] end theorem is_conj_of_cycle_type_eq {σ τ : perm α} (h : cycle_type σ = cycle_type τ) : is_conj σ τ := begin revert τ, apply cycle_induction_on _ σ, { intros τ h, rw [cycle_type_one, eq_comm, cycle_type_eq_zero] at h, rw h }, { intros σ hσ τ hστ, have hτ := card_cycle_type_eq_one.2 hσ, rw [hστ, card_cycle_type_eq_one] at hτ, apply hσ.is_conj hτ, rw [hσ.cycle_type, hτ.cycle_type, coe_eq_coe, singleton_perm] at hστ, simp only [and_true, eq_self_iff_true] at hστ, exact hστ }, { intros σ τ hστ hσ h1 h2 π hπ, rw [hστ.cycle_type] at hπ, { have h : σ.support.card ∈ map (finset.card ∘ perm.support) π.cycle_factors_finset.val, { simp [←cycle_type_def, ←hπ, hσ.cycle_type] }, obtain ⟨σ', hσ'l, hσ'⟩ := multiset.mem_map.mp h, have key : is_conj (σ' * (π * σ'⁻¹)) π, { rw is_conj_iff, use σ'⁻¹, simp [mul_assoc] }, refine is_conj.trans _ key, have hs : σ.cycle_type = σ'.cycle_type, { rw [←finset.mem_def, mem_cycle_factors_finset_iff] at hσ'l, rw [hσ.cycle_type, ←hσ', hσ'l.left.cycle_type] }, refine hστ.is_conj_mul (h1 hs) (h2 _) _, { rw [cycle_type_mul_mem_cycle_factors_finset_eq_sub, ←hπ, add_comm, hs, add_sub_cancel_right], rwa finset.mem_def }, { exact (disjoint_mul_inv_of_mem_cycle_factors_finset hσ'l).symm } } } end theorem is_conj_iff_cycle_type_eq {σ τ : perm α} : is_conj σ τ ↔ σ.cycle_type = τ.cycle_type := ⟨λ h, begin obtain ⟨π, rfl⟩ := is_conj_iff.1 h, rw cycle_type_conj, end, is_conj_of_cycle_type_eq⟩ @[simp] lemma cycle_type_extend_domain {β : Type*} [fintype β] [decidable_eq β] {p : β → Prop} [decidable_pred p] (f : α ≃ subtype p) {g : perm α} : cycle_type (g.extend_domain f) = cycle_type g := begin apply cycle_induction_on _ g, { rw [extend_domain_one, cycle_type_one, cycle_type_one] }, { intros σ hσ, rw [(hσ.extend_domain f).cycle_type, hσ.cycle_type, card_support_extend_domain] }, { intros σ τ hd hc hσ hτ, rw [hd.cycle_type, ← extend_domain_mul, (hd.extend_domain f).cycle_type, hσ, hτ] } end lemma mem_cycle_type_iff {n : ℕ} {σ : perm α} : n ∈ cycle_type σ ↔ ∃ c τ : perm α, σ = c * τ ∧ disjoint c τ ∧ is_cycle c ∧ c.support.card = n := begin split, { intro h, obtain ⟨l, rfl, hlc, hld⟩ := trunc_cycle_factors σ, rw cycle_type_eq _ rfl hlc hld at h, obtain ⟨c, cl, rfl⟩ := list.exists_of_mem_map h, rw (list.perm_cons_erase cl).pairwise_iff (λ _ _ hd, _) at hld, swap, { exact hd.symm }, refine ⟨c, (l.erase c).prod, _, _, hlc _ cl, rfl⟩, { rw [← list.prod_cons, (list.perm_cons_erase cl).symm.prod_eq' (hld.imp (λ _ _, disjoint.commute))] }, { exact disjoint_prod_right _ (λ g, list.rel_of_pairwise_cons hld) } }, { rintros ⟨c, t, rfl, hd, hc, rfl⟩, simp [hd.cycle_type, hc.cycle_type] } end lemma le_card_support_of_mem_cycle_type {n : ℕ} {σ : perm α} (h : n ∈ cycle_type σ) : n ≤ σ.support.card := (le_sum_of_mem h).trans (le_of_eq σ.sum_cycle_type) lemma cycle_type_of_card_le_mem_cycle_type_add_two {n : ℕ} {g : perm α} (hn2 : fintype.card α < n + 2) (hng : n ∈ g.cycle_type) : g.cycle_type = {n} := begin obtain ⟨c, g', rfl, hd, hc, rfl⟩ := mem_cycle_type_iff.1 hng, by_cases g'1 : g' = 1, { rw [hd.cycle_type, hc.cycle_type, multiset.singleton_eq_cons, multiset.singleton_coe, g'1, cycle_type_one, add_zero] }, contrapose! hn2, apply le_trans _ (c * g').support.card_le_univ, rw [hd.card_support_mul], exact add_le_add_left (two_le_card_support_of_ne_one g'1) _, end end cycle_type lemma card_compl_support_modeq [decidable_eq α] {p n : ℕ} [hp : fact p.prime] {σ : perm α} (hσ : σ ^ p ^ n = 1) : σ.supportᶜ.card ≡ fintype.card α [MOD p] := begin rw [nat.modeq_iff_dvd' σ.supportᶜ.card_le_univ, ←finset.card_compl, compl_compl], refine (congr_arg _ σ.sum_cycle_type).mp (multiset.dvd_sum (λ k hk, _)), obtain ⟨m, -, hm⟩ := (nat.dvd_prime_pow hp.out).mp (order_of_dvd_of_pow_eq_one hσ), obtain ⟨l, -, rfl⟩ := (nat.dvd_prime_pow hp.out).mp ((congr_arg _ hm).mp (dvd_of_mem_cycle_type hk)), exact dvd_pow_self _ (λ h, (one_lt_of_mem_cycle_type hk).ne $ by rw [h, pow_zero]), end lemma exists_fixed_point_of_prime {p n : ℕ} [hp : fact p.prime] (hα : ¬ p ∣ fintype.card α) {σ : perm α} (hσ : σ ^ p ^ n = 1) : ∃ a : α, σ a = a := begin classical, contrapose! hα, simp_rw ← mem_support at hα, exact nat.modeq_zero_iff_dvd.mp ((congr_arg _ (finset.card_eq_zero.mpr (compl_eq_bot.mpr (finset.eq_univ_iff_forall.mpr hα)))).mp (card_compl_support_modeq hσ).symm), end lemma exists_fixed_point_of_prime' {p n : ℕ} [hp : fact p.prime] (hα : p ∣ fintype.card α) {σ : perm α} (hσ : σ ^ p ^ n = 1) {a : α} (ha : σ a = a) : ∃ b : α, σ b = b ∧ b ≠ a := begin classical, have h : ∀ b : α, b ∈ σ.supportᶜ ↔ σ b = b := λ b, by rw [finset.mem_compl, mem_support, not_not], obtain ⟨b, hb1, hb2⟩ := finset.exists_ne_of_one_lt_card (lt_of_lt_of_le hp.out.one_lt (nat.le_of_dvd (finset.card_pos.mpr ⟨a, (h a).mpr ha⟩) (nat.modeq_zero_iff_dvd.mp ((card_compl_support_modeq hσ).trans (nat.modeq_zero_iff_dvd.mpr hα))))) a, exact ⟨b, (h b).mp hb1, hb2⟩, end lemma is_cycle_of_prime_order' {σ : perm α} (h1 : (order_of σ).prime) (h2 : fintype.card α < 2 * (order_of σ)) : σ.is_cycle := begin classical, exact is_cycle_of_prime_order h1 (lt_of_le_of_lt σ.support.card_le_univ h2), end lemma is_cycle_of_prime_order'' {σ : perm α} (h1 : (fintype.card α).prime) (h2 : order_of σ = fintype.card α) : σ.is_cycle := is_cycle_of_prime_order' ((congr_arg nat.prime h2).mpr h1) begin classical, rw [←one_mul (fintype.card α), ←h2, mul_lt_mul_right (order_of_pos σ)], exact one_lt_two, end section cauchy variables (G : Type*) [group G] (n : ℕ) /-- The type of vectors with terms from `G`, length `n`, and product equal to `1:G`. -/ def vectors_prod_eq_one : set (vector G n) := {v | v.to_list.prod = 1} namespace vectors_prod_eq_one lemma mem_iff {n : ℕ} (v : vector G n) : v ∈ vectors_prod_eq_one G n ↔ v.to_list.prod = 1 := iff.rfl lemma zero_eq : vectors_prod_eq_one G 0 = {vector.nil} := set.eq_singleton_iff_unique_mem.mpr ⟨eq.refl (1 : G), λ v hv, v.eq_nil⟩ lemma one_eq : vectors_prod_eq_one G 1 = {vector.nil.cons 1} := begin simp_rw [set.eq_singleton_iff_unique_mem, mem_iff, vector.to_list_singleton, list.prod_singleton, vector.head_cons], exact ⟨rfl, λ v hv, v.cons_head_tail.symm.trans (congr_arg2 vector.cons hv v.tail.eq_nil)⟩, end instance zero_unique : unique (vectors_prod_eq_one G 0) := by { rw zero_eq, exact set.unique_singleton vector.nil } instance one_unique : unique (vectors_prod_eq_one G 1) := by { rw one_eq, exact set.unique_singleton (vector.nil.cons 1) } /-- Given a vector `v` of length `n`, make a vector of length `n + 1` whose product is `1`, by appending the inverse of the product of `v`. -/ @[simps] def vector_equiv : vector G n ≃ vectors_prod_eq_one G (n + 1) := { to_fun := λ v, ⟨v.to_list.prod⁻¹ ::ᵥ v, by rw [mem_iff, vector.to_list_cons, list.prod_cons, inv_mul_self]⟩, inv_fun := λ v, v.1.tail, left_inv := λ v, v.tail_cons v.to_list.prod⁻¹, right_inv := λ v, subtype.ext ((congr_arg2 vector.cons (eq_inv_of_mul_eq_one (by { rw [←list.prod_cons, ←vector.to_list_cons, v.1.cons_head_tail], exact v.2 })).symm rfl).trans v.1.cons_head_tail) } /-- Given a vector `v` of length `n` whose product is 1, make a vector of length `n - 1`, by deleting the last entry of `v`. -/ def equiv_vector : vectors_prod_eq_one G n ≃ vector G (n - 1) := ((vector_equiv G (n - 1)).trans (if hn : n = 0 then (show vectors_prod_eq_one G (n - 1 + 1) ≃ vectors_prod_eq_one G n, by { rw hn, exact equiv_of_unique_of_unique }) else by rw nat.sub_add_cancel (nat.pos_of_ne_zero hn))).symm instance [fintype G] : fintype (vectors_prod_eq_one G n) := fintype.of_equiv (vector G (n - 1)) (equiv_vector G n).symm lemma card [fintype G] : fintype.card (vectors_prod_eq_one G n) = fintype.card G ^ (n - 1) := (fintype.card_congr (equiv_vector G n)).trans (card_vector (n - 1)) variables {G n} {g : G} (v : vectors_prod_eq_one G n) (j k : ℕ) /-- Rotate a vector whose product is 1. -/ def rotate : vectors_prod_eq_one G n := ⟨⟨_, (v.1.1.length_rotate k).trans v.1.2⟩, list.prod_rotate_eq_one_of_prod_eq_one v.2 k⟩ lemma rotate_zero : rotate v 0 = v := subtype.ext (subtype.ext v.1.1.rotate_zero) lemma rotate_rotate : rotate (rotate v j) k = rotate v (j + k) := subtype.ext (subtype.ext (v.1.1.rotate_rotate j k)) lemma rotate_length : rotate v n = v := subtype.ext (subtype.ext ((congr_arg _ v.1.2.symm).trans v.1.1.rotate_length)) end vectors_prod_eq_one lemma exists_prime_order_of_dvd_card {G : Type*} [group G] [fintype G] (p : ℕ) [hp : fact p.prime] (hdvd : p ∣ fintype.card G) : ∃ x : G, order_of x = p := begin have hp' : p - 1 ≠ 0 := mt nat.sub_eq_zero_iff_le.mp (not_le_of_lt hp.out.one_lt), have Scard := calc p ∣ fintype.card G ^ (p - 1) : hdvd.trans (dvd_pow (dvd_refl _) hp') ... = fintype.card (vectors_prod_eq_one G p) : (vectors_prod_eq_one.card G p).symm, let f : ℕ → vectors_prod_eq_one G p → vectors_prod_eq_one G p := λ k v, vectors_prod_eq_one.rotate v k, have hf1 : ∀ v, f 0 v = v := vectors_prod_eq_one.rotate_zero, have hf2 : ∀ j k v, f k (f j v) = f (j + k) v := λ j k v, vectors_prod_eq_one.rotate_rotate v j k, have hf3 : ∀ v, f p v = v := vectors_prod_eq_one.rotate_length, let σ := equiv.mk (f 1) (f (p - 1)) (λ s, by rw [hf2, add_sub_cancel_of_le hp.out.one_lt.le, hf3]) (λ s, by rw [hf2, nat.sub_add_cancel hp.out.pos, hf3]), have hσ : ∀ k v, (σ ^ k) v = f k v := λ k v, nat.rec (hf1 v).symm (λ k hk, eq.trans (by exact congr_arg σ hk) (hf2 k 1 v)) k, replace hσ : σ ^ (p ^ 1) = 1 := perm.ext (λ v, by rw [pow_one, hσ, hf3, one_apply]), let v₀ : vectors_prod_eq_one G p := ⟨vector.repeat 1 p, (list.prod_repeat 1 p).trans (one_pow p)⟩, have hv₀ : σ v₀ = v₀ := subtype.ext (subtype.ext (list.rotate_repeat (1 : G) p 1)), obtain ⟨v, hv1, hv2⟩ := exists_fixed_point_of_prime' Scard hσ hv₀, refine exists_imp_exists (λ g hg, order_of_eq_prime _ (λ hg', hv2 _)) (list.rotate_one_eq_self_iff_eq_repeat.mp (subtype.ext_iff.mp (subtype.ext_iff.mp hv1))), { rw [←list.prod_repeat, ←v.1.2, ←hg, (show v.val.val.prod = 1, from v.2)] }, { rw [subtype.ext_iff_val, subtype.ext_iff_val, hg, hg', v.1.2], refl }, end end cauchy lemma subgroup_eq_top_of_swap_mem [decidable_eq α] {H : subgroup (perm α)} [d : decidable_pred (∈ H)] {τ : perm α} (h0 : (fintype.card α).prime) (h1 : fintype.card α ∣ fintype.card H) (h2 : τ ∈ H) (h3 : is_swap τ) : H = ⊤ := begin haveI : fact (fintype.card α).prime := ⟨h0⟩, obtain ⟨σ, hσ⟩ := exists_prime_order_of_dvd_card (fintype.card α) h1, have hσ1 : order_of (σ : perm α) = fintype.card α := (order_of_subgroup σ).trans hσ, have hσ2 : is_cycle ↑σ := is_cycle_of_prime_order'' h0 hσ1, have hσ3 : (σ : perm α).support = ⊤ := finset.eq_univ_of_card (σ : perm α).support ((order_of_is_cycle hσ2).symm.trans hσ1), have hσ4 : subgroup.closure {↑σ, τ} = ⊤ := closure_prime_cycle_swap h0 hσ2 hσ3 h3, rw [eq_top_iff, ←hσ4, subgroup.closure_le, set.insert_subset, set.singleton_subset_iff], exact ⟨subtype.mem σ, h2⟩, end section partition variables [decidable_eq α] /-- The partition corresponding to a permutation -/ def partition (σ : perm α) : (fintype.card α).partition := { parts := σ.cycle_type + repeat 1 (fintype.card α - σ.support.card), parts_pos := λ n hn, begin cases mem_add.mp hn with hn hn, { exact zero_lt_one.trans (one_lt_of_mem_cycle_type hn) }, { exact lt_of_lt_of_le zero_lt_one (ge_of_eq (multiset.eq_of_mem_repeat hn)) }, end, parts_sum := by rw [sum_add, sum_cycle_type, multiset.sum_repeat, nsmul_eq_mul, nat.cast_id, mul_one, add_sub_cancel_of_le σ.support.card_le_univ] } lemma parts_partition {σ : perm α} : σ.partition.parts = σ.cycle_type + repeat 1 (fintype.card α - σ.support.card) := rfl lemma filter_parts_partition_eq_cycle_type {σ : perm α} : (partition σ).parts.filter (λ n, 2 ≤ n) = σ.cycle_type := begin rw [parts_partition, filter_add, multiset.filter_eq_self.2 (λ _, two_le_of_mem_cycle_type), multiset.filter_eq_nil.2 (λ a h, _), add_zero], rw multiset.eq_of_mem_repeat h, dec_trivial end lemma partition_eq_of_is_conj {σ τ : perm α} : is_conj σ τ ↔ σ.partition = τ.partition := begin rw [is_conj_iff_cycle_type_eq], refine ⟨λ h, _, λ h, _⟩, { rw [nat.partition.ext_iff, parts_partition, parts_partition, ← sum_cycle_type, ← sum_cycle_type, h] }, { rw [← filter_parts_partition_eq_cycle_type, ← filter_parts_partition_eq_cycle_type, h] } end end partition /-! ### 3-cycles -/ /-- A three-cycle is a cycle of length 3. -/ def is_three_cycle [decidable_eq α] (σ : perm α) : Prop := σ.cycle_type = {3} namespace is_three_cycle variables [decidable_eq α] {σ : perm α} lemma cycle_type (h : is_three_cycle σ) : σ.cycle_type = {3} := h lemma card_support (h : is_three_cycle σ) : σ.support.card = 3 := by rw [←sum_cycle_type, h.cycle_type, multiset.sum_singleton] lemma _root_.card_support_eq_three_iff : σ.support.card = 3 ↔ σ.is_three_cycle := begin refine ⟨λ h, _, is_three_cycle.card_support⟩, by_cases h0 : σ.cycle_type = 0, { rw [←sum_cycle_type, h0, sum_zero] at h, exact (ne_of_lt zero_lt_three h).elim }, obtain ⟨n, hn⟩ := exists_mem_of_ne_zero h0, by_cases h1 : σ.cycle_type.erase n = 0, { rw [←sum_cycle_type, ←cons_erase hn, h1, ←singleton_eq_cons, multiset.sum_singleton] at h, rw [is_three_cycle, ←cons_erase hn, h1, h, singleton_eq_cons] }, obtain ⟨m, hm⟩ := exists_mem_of_ne_zero h1, rw [←sum_cycle_type, ←cons_erase hn, ←cons_erase hm, multiset.sum_cons, multiset.sum_cons] at h, linarith [two_le_of_mem_cycle_type hn, two_le_of_mem_cycle_type (mem_of_mem_erase hm)], end lemma is_cycle (h : is_three_cycle σ) : is_cycle σ := by rw [←card_cycle_type_eq_one, h.cycle_type, card_singleton] lemma sign (h : is_three_cycle σ) : sign σ = 1 := begin rw [sign_of_cycle_type, h.cycle_type], refl, end lemma inv {f : perm α} (h : is_three_cycle f) : is_three_cycle (f⁻¹) := by rwa [is_three_cycle, cycle_type_inv] @[simp] lemma inv_iff {f : perm α} : is_three_cycle (f⁻¹) ↔ is_three_cycle f := ⟨by { rw ← inv_inv f, apply inv }, inv⟩ lemma order_of {g : perm α} (ht : is_three_cycle g) : order_of g = 3 := by rw [←lcm_cycle_type, ht.cycle_type, multiset.lcm_singleton, normalize_eq] lemma is_three_cycle_sq {g : perm α} (ht : is_three_cycle g) : is_three_cycle (g * g) := begin rw [←pow_two, ←card_support_eq_three_iff, support_pow_coprime, ht.card_support], rw [ht.order_of, nat.coprime_iff_gcd_eq_one], norm_num, end end is_three_cycle section variable [decidable_eq α] lemma is_three_cycle_swap_mul_swap_same {a b c : α} (ab : a ≠ b) (ac : a ≠ c) (bc : b ≠ c) : is_three_cycle (swap a b * swap a c) := begin suffices h : support (swap a b * swap a c) = {a, b, c}, { rw [←card_support_eq_three_iff, h], simp [ab, ac, bc] }, apply le_antisymm ((support_mul_le _ _).trans (λ x, _)) (λ x hx, _), { simp [ab, ac, bc] }, { simp only [finset.mem_insert, finset.mem_singleton] at hx, rw mem_support, simp only [perm.coe_mul, function.comp_app, ne.def], obtain rfl | rfl | rfl := hx, { rw [swap_apply_left, swap_apply_of_ne_of_ne ac.symm bc.symm], exact ac.symm }, { rw [swap_apply_of_ne_of_ne ab.symm bc, swap_apply_right], exact ab }, { rw [swap_apply_right, swap_apply_left], exact bc } } end open subgroup lemma swap_mul_swap_same_mem_closure_three_cycles {a b c : α} (ab : a ≠ b) (ac : a ≠ c) : (swap a b * swap a c) ∈ closure {σ : perm α | is_three_cycle σ } := begin by_cases bc : b = c, { subst bc, simp [one_mem] }, exact subset_closure (is_three_cycle_swap_mul_swap_same ab ac bc) end lemma is_swap.mul_mem_closure_three_cycles {σ τ : perm α} (hσ : is_swap σ) (hτ : is_swap τ) : σ * τ ∈ closure {σ : perm α | is_three_cycle σ } := begin obtain ⟨a, b, ab, rfl⟩ := hσ, obtain ⟨c, d, cd, rfl⟩ := hτ, by_cases ac : a = c, { subst ac, exact swap_mul_swap_same_mem_closure_three_cycles ab cd }, have h' : swap a b * swap c d = swap a b * swap a c * (swap c a * swap c d), { simp [swap_comm c a, mul_assoc] }, rw h', exact mul_mem _ (swap_mul_swap_same_mem_closure_three_cycles ab ac) (swap_mul_swap_same_mem_closure_three_cycles (ne.symm ac) cd), end end end equiv.perm
b762d212fa71e50919bc24a6d89500d35a2d905b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/data/int/bitwise.lean
0114fb8fc132ef91e503888d78ca827d24cb7ac0
[ "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
10,170
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad -/ import data.int.basic import data.nat.pow import data.nat.size /-! # Bitwise operations on integers > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Recursors * `int.bit_cases_on`: Parity disjunction. Something is true/defined on `ℤ` if it's true/defined for even and for odd values. -/ namespace int /-! ### bitwise ops -/ @[simp] lemma bodd_zero : bodd 0 = ff := rfl @[simp] lemma bodd_one : bodd 1 = tt := rfl lemma bodd_two : bodd 2 = ff := rfl @[simp, norm_cast] lemma bodd_coe (n : ℕ) : int.bodd n = nat.bodd n := rfl @[simp] lemma bodd_sub_nat_nat (m n : ℕ) : bodd (sub_nat_nat m n) = bxor m.bodd n.bodd := by apply sub_nat_nat_elim m n (λ m n i, bodd i = bxor m.bodd n.bodd); intros; simp; cases i.bodd; simp @[simp] lemma bodd_neg_of_nat (n : ℕ) : bodd (neg_of_nat n) = n.bodd := by cases n; simp; refl @[simp] lemma bodd_neg (n : ℤ) : bodd (-n) = bodd n := by cases n; simp [has_neg.neg, int.coe_nat_eq, int.neg, bodd, -of_nat_eq_coe] @[simp] lemma bodd_add (m n : ℤ) : bodd (m + n) = bxor (bodd m) (bodd n) := by cases m with m m; cases n with n n; unfold has_add.add; simp [int.add, -of_nat_eq_coe, bool.bxor_comm] @[simp] lemma bodd_mul (m n : ℤ) : bodd (m * n) = bodd m && bodd n := by cases m with m m; cases n with n n; simp [← int.mul_def, int.mul, -of_nat_eq_coe, bool.bxor_comm] theorem bodd_add_div2 : ∀ n, cond (bodd n) 1 0 + 2 * div2 n = n | (n : ℕ) := by rw [show (cond (bodd n) 1 0 : ℤ) = (cond (bodd n) 1 0 : ℕ), by cases bodd n; refl]; exact congr_arg of_nat n.bodd_add_div2 | -[1+ n] := begin refine eq.trans _ (congr_arg neg_succ_of_nat n.bodd_add_div2), dsimp [bodd], cases nat.bodd n; dsimp [cond, bnot, div2, int.mul], { change -[1+ 2 * nat.div2 n] = _, rw zero_add }, { rw [zero_add, add_comm], refl } end theorem div2_val : ∀ n, div2 n = n / 2 | (n : ℕ) := congr_arg of_nat n.div2_val | -[1+ n] := congr_arg neg_succ_of_nat n.div2_val lemma bit0_val (n : ℤ) : bit0 n = 2 * n := (two_mul _).symm lemma bit1_val (n : ℤ) : bit1 n = 2 * n + 1 := congr_arg (+(1:ℤ)) (bit0_val _) lemma bit_val (b n) : bit b n = 2 * n + cond b 1 0 := by { cases b, apply (bit0_val n).trans (add_zero _).symm, apply bit1_val } lemma bit_decomp (n : ℤ) : bit (bodd n) (div2 n) = n := (bit_val _ _).trans $ (add_comm _ _).trans $ bodd_add_div2 _ /-- Defines a function from `ℤ` conditionally, if it is defined for odd and even integers separately using `bit`. -/ def {u} bit_cases_on {C : ℤ → Sort u} (n) (h : ∀ b n, C (bit b n)) : C n := by rw [← bit_decomp n]; apply h @[simp] lemma bit_zero : bit ff 0 = 0 := rfl @[simp] lemma bit_coe_nat (b) (n : ℕ) : bit b n = nat.bit b n := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bit_neg_succ (b) (n : ℕ) : bit b -[1+ n] = -[1+ nat.bit (bnot b) n] := by rw [bit_val, nat.bit_val]; cases b; refl @[simp] lemma bodd_bit (b n) : bodd (bit b n) = b := by rw bit_val; simp; cases b; cases bodd n; refl @[simp] lemma bodd_bit0 (n : ℤ) : bodd (bit0 n) = ff := bodd_bit ff n @[simp] lemma bodd_bit1 (n : ℤ) : bodd (bit1 n) = tt := bodd_bit tt n lemma bit0_ne_bit1 (m n : ℤ) : bit0 m ≠ bit1 n := mt (congr_arg bodd) $ by simp lemma bit1_ne_bit0 (m n : ℤ) : bit1 m ≠ bit0 n := (bit0_ne_bit1 _ _).symm lemma bit1_ne_zero (m : ℤ) : bit1 m ≠ 0 := by simpa only [bit0_zero] using bit1_ne_bit0 m 0 @[simp] lemma test_bit_zero (b) : ∀ n, test_bit (bit b n) 0 = b | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_zero | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_zero]; clear test_bit_zero; cases b; refl @[simp] lemma test_bit_succ (m b) : ∀ n, test_bit (bit b n) (nat.succ m) = test_bit n m | (n : ℕ) := by rw [bit_coe_nat]; apply nat.test_bit_succ | -[1+ n] := by rw [bit_neg_succ]; dsimp [test_bit]; rw [nat.test_bit_succ] private meta def bitwise_tac : tactic unit := `[ funext m, funext n, cases m with m m; cases n with n n; try {refl}, all_goals { apply congr_arg of_nat <|> apply congr_arg neg_succ_of_nat, try {dsimp [nat.land, nat.ldiff, nat.lor]}, try {rw [ show nat.bitwise (λ a b, a && bnot b) n m = nat.bitwise (λ a b, b && bnot a) m n, from congr_fun (congr_fun (@nat.bitwise_swap (λ a b, b && bnot a) rfl) n) m]}, apply congr_arg (λ f, nat.bitwise f m n), funext a, funext b, cases a; cases b; refl }, all_goals {unfold nat.land nat.ldiff nat.lor} ] theorem bitwise_or : bitwise bor = lor := by bitwise_tac theorem bitwise_and : bitwise band = land := by bitwise_tac theorem bitwise_diff : bitwise (λ a b, a && bnot b) = ldiff := by bitwise_tac theorem bitwise_xor : bitwise bxor = lxor := by bitwise_tac @[simp] lemma bitwise_bit (f : bool → bool → bool) (a m b n) : bitwise f (bit a m) (bit b n) = bit (f a b) (bitwise f m n) := begin cases m with m m; cases n with n n; repeat { rw [← int.coe_nat_eq] <|> rw bit_coe_nat <|> rw bit_neg_succ }; unfold bitwise nat_bitwise bnot; [ induction h : f ff ff, induction h : f ff tt, induction h : f tt ff, induction h : f tt tt ], all_goals { unfold cond, rw nat.bitwise_bit, repeat { rw bit_coe_nat <|> rw bit_neg_succ <|> rw bnot_bnot } }, all_goals { unfold bnot {fail_if_unchanged := ff}; rw h; refl } end @[simp] lemma lor_bit (a m b n) : lor (bit a m) (bit b n) = bit (a || b) (lor m n) := by rw [← bitwise_or, bitwise_bit] @[simp] lemma land_bit (a m b n) : land (bit a m) (bit b n) = bit (a && b) (land m n) := by rw [← bitwise_and, bitwise_bit] @[simp] lemma ldiff_bit (a m b n) : ldiff (bit a m) (bit b n) = bit (a && bnot b) (ldiff m n) := by rw [← bitwise_diff, bitwise_bit] @[simp] lemma lxor_bit (a m b n) : lxor (bit a m) (bit b n) = bit (bxor a b) (lxor m n) := by rw [← bitwise_xor, bitwise_bit] @[simp] lemma lnot_bit (b) : ∀ n, lnot (bit b n) = bit (bnot b) (lnot n) | (n : ℕ) := by simp [lnot] | -[1+ n] := by simp [lnot] @[simp] lemma test_bit_bitwise (f : bool → bool → bool) (m n k) : test_bit (bitwise f m n) k = f (test_bit m k) (test_bit n k) := begin induction k with k IH generalizing m n; apply bit_cases_on m; intros a m'; apply bit_cases_on n; intros b n'; rw bitwise_bit, { simp [test_bit_zero] }, { simp [test_bit_succ, IH] } end @[simp] lemma test_bit_lor (m n k) : test_bit (lor m n) k = test_bit m k || test_bit n k := by rw [← bitwise_or, test_bit_bitwise] @[simp] lemma test_bit_land (m n k) : test_bit (land m n) k = test_bit m k && test_bit n k := by rw [← bitwise_and, test_bit_bitwise] @[simp] lemma test_bit_ldiff (m n k) : test_bit (ldiff m n) k = test_bit m k && bnot (test_bit n k) := by rw [← bitwise_diff, test_bit_bitwise] @[simp] lemma test_bit_lxor (m n k) : test_bit (lxor m n) k = bxor (test_bit m k) (test_bit n k) := by rw [← bitwise_xor, test_bit_bitwise] @[simp] lemma test_bit_lnot : ∀ n k, test_bit (lnot n) k = bnot (test_bit n k) | (n : ℕ) k := by simp [lnot, test_bit] | -[1+ n] k := by simp [lnot, test_bit] @[simp] lemma shiftl_neg (m n : ℤ) : shiftl m (-n) = shiftr m n := rfl @[simp] lemma shiftr_neg (m n : ℤ) : shiftr m (-n) = shiftl m n := by rw [← shiftl_neg, neg_neg] @[simp] lemma shiftl_coe_nat (m n : ℕ) : shiftl m n = nat.shiftl m n := rfl @[simp] lemma shiftr_coe_nat (m n : ℕ) : shiftr m n = nat.shiftr m n := by cases n; refl @[simp] lemma shiftl_neg_succ (m n : ℕ) : shiftl -[1+ m] n = -[1+ nat.shiftl' tt m n] := rfl @[simp] lemma shiftr_neg_succ (m n : ℕ) : shiftr -[1+ m] n = -[1+ nat.shiftr m n] := by cases n; refl lemma shiftr_add : ∀ (m : ℤ) (n k : ℕ), shiftr m (n + k) = shiftr (shiftr m n) k | (m : ℕ) n k := by rw [shiftr_coe_nat, shiftr_coe_nat, ← int.coe_nat_add, shiftr_coe_nat, nat.shiftr_add] | -[1+ m] n k := by rw [shiftr_neg_succ, shiftr_neg_succ, ← int.coe_nat_add, shiftr_neg_succ, nat.shiftr_add] /-! ### bitwise ops -/ local attribute [simp] int.zero_div lemma shiftl_add : ∀ (m : ℤ) (n : ℕ) (k : ℤ), shiftl m (n + k) = shiftl (shiftl m n) k | (m : ℕ) n (k:ℕ) := congr_arg of_nat (nat.shiftl_add _ _ _) | -[1+ m] n (k:ℕ) := congr_arg neg_succ_of_nat (nat.shiftl'_add _ _ _ _) | (m : ℕ) n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl ↑m i = nat.shiftr (nat.shiftl m n) k) (λ i n, congr_arg coe $ by rw [← nat.shiftl_sub, add_tsub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg coe $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl_sub, tsub_self]; refl) | -[1+ m] n -[1+k] := sub_nat_nat_elim n k.succ (λ n k i, shiftl -[1+ m] i = -[1+ nat.shiftr (nat.shiftl' tt m n) k]) (λ i n, congr_arg neg_succ_of_nat $ by rw [← nat.shiftl'_sub, add_tsub_cancel_left]; apply nat.le_add_right) (λ i n, congr_arg neg_succ_of_nat $ by rw [add_assoc, nat.shiftr_add, ← nat.shiftl'_sub, tsub_self]; refl) lemma shiftl_sub (m : ℤ) (n : ℕ) (k : ℤ) : shiftl m (n - k) = shiftr (shiftl m n) k := shiftl_add _ _ _ lemma shiftl_eq_mul_pow : ∀ (m : ℤ) (n : ℕ), shiftl m n = m * ↑(2 ^ n) | (m : ℕ) n := congr_arg coe (nat.shiftl_eq_mul_pow _ _) | -[1+ m] n := @congr_arg ℕ ℤ _ _ (λi, -i) (nat.shiftl'_tt_eq_mul_pow _ _) lemma shiftr_eq_div_pow : ∀ (m : ℤ) (n : ℕ), shiftr m n = m / ↑(2 ^ n) | (m : ℕ) n := by rw shiftr_coe_nat; exact congr_arg coe (nat.shiftr_eq_div_pow _ _) | -[1+ m] n := begin rw [shiftr_neg_succ, neg_succ_of_nat_div, nat.shiftr_eq_div_pow], refl, exact coe_nat_lt_coe_nat_of_lt (pow_pos dec_trivial _) end lemma one_shiftl (n : ℕ) : shiftl 1 n = (2 ^ n : ℕ) := congr_arg coe (nat.one_shiftl _) @[simp] lemma zero_shiftl : ∀ n : ℤ, shiftl 0 n = 0 | (n : ℕ) := congr_arg coe (nat.zero_shiftl _) | -[1+ n] := congr_arg coe (nat.zero_shiftr _) @[simp] lemma zero_shiftr (n) : shiftr 0 n = 0 := zero_shiftl _ end int
b7723538639fc780d603c6d450a9dd8043af8816
9dc8cecdf3c4634764a18254e94d43da07142918
/src/category_theory/monad/limits.lean
aa3cbf51c4909fec48b1c24fd239c30108f92cbd
[ "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
15,238
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Bhavik Mehta -/ import category_theory.monad.adjunction import category_theory.adjunction.limits import category_theory.limits.preserves.shapes.terminal /-! # Limits and colimits in the category of algebras This file shows that the forgetful functor `forget T : algebra T ⥤ C` for a monad `T : C ⥤ C` creates limits and creates any colimits which `T` preserves. This is used to show that `algebra T` has any limits which `C` has, and any colimits which `C` has and `T` preserves. This is generalised to the case of a monadic functor `D ⥤ C`. ## TODO Dualise for the category of coalgebras and comonadic left adjoints. -/ namespace category_theory open category open category_theory.limits universes v u v₁ v₂ u₁ u₂ -- morphism levels before object levels. See note [category_theory universes]. namespace monad variables {C : Type u₁} [category.{v₁} C] variables {T : monad C} variables {J : Type u} [category.{v} J] namespace forget_creates_limits variables (D : J ⥤ algebra T) (c : cone (D ⋙ T.forget)) (t : is_limit c) /-- (Impl) The natural transformation used to define the new cone -/ @[simps] def γ : (D ⋙ T.forget ⋙ ↑T) ⟶ D ⋙ T.forget := { app := λ j, (D.obj j).a } /-- (Impl) This new cone is used to construct the algebra structure -/ @[simps π_app] def new_cone : cone (D ⋙ forget T) := { X := T.obj c.X, π := (functor.const_comp _ _ ↑T).inv ≫ whisker_right c.π T ≫ γ D } /-- The algebra structure which will be the apex of the new limit cone for `D`. -/ @[simps] def cone_point : algebra T := { A := c.X, a := t.lift (new_cone D c), unit' := t.hom_ext $ λ j, begin rw [category.assoc, t.fac, new_cone_π_app, ←T.η.naturality_assoc, functor.id_map, (D.obj j).unit], dsimp, simp -- See library note [dsimp, simp] end, assoc' := t.hom_ext $ λ j, begin rw [category.assoc, category.assoc, t.fac (new_cone D c), new_cone_π_app, ←functor.map_comp_assoc, t.fac (new_cone D c), new_cone_π_app, ←T.μ.naturality_assoc, (D.obj j).assoc, functor.map_comp, category.assoc], refl, end } /-- (Impl) Construct the lifted cone in `algebra T` which will be limiting. -/ @[simps] def lifted_cone : cone D := { X := cone_point D c t, π := { app := λ j, { f := c.π.app j }, naturality' := λ X Y f, by { ext1, dsimp, erw c.w f, simp } } } /-- (Impl) Prove that the lifted cone is limiting. -/ @[simps] def lifted_cone_is_limit : is_limit (lifted_cone D c t) := { lift := λ s, { f := t.lift ((forget T).map_cone s), h' := t.hom_ext $ λ j, begin dsimp, rw [category.assoc, category.assoc, t.fac, new_cone_π_app, ←functor.map_comp_assoc, t.fac, functor.map_cone_π_app], apply (s.π.app j).h, end }, uniq' := λ s m J, begin ext1, apply t.hom_ext, intro j, simpa [t.fac ((forget T).map_cone s) j] using congr_arg algebra.hom.f (J j), end } end forget_creates_limits -- Theorem 5.6.5 from [Riehl][riehl2017] /-- The forgetful functor from the Eilenberg-Moore category creates limits. -/ noncomputable instance forget_creates_limits : creates_limits_of_size (forget T) := { creates_limits_of_shape := λ J 𝒥, by exactI { creates_limit := λ D, creates_limit_of_reflects_iso (λ c t, { lifted_cone := forget_creates_limits.lifted_cone D c t, valid_lift := cones.ext (iso.refl _) (λ j, (id_comp _).symm), makes_limit := forget_creates_limits.lifted_cone_is_limit _ _ _ } ) } } /-- `D ⋙ forget T` has a limit, then `D` has a limit. -/ lemma has_limit_of_comp_forget_has_limit (D : J ⥤ algebra T) [has_limit (D ⋙ forget T)] : has_limit D := has_limit_of_created D (forget T) namespace forget_creates_colimits -- Let's hide the implementation details in a namespace variables {D : J ⥤ algebra T} (c : cocone (D ⋙ forget T)) (t : is_colimit c) -- We have a diagram D of shape J in the category of algebras, and we assume that we are given a -- colimit for its image D ⋙ forget T under the forgetful functor, say its apex is L. -- We'll construct a colimiting coalgebra for D, whose carrier will also be L. -- To do this, we must find a map TL ⟶ L. Since T preserves colimits, TL is also a colimit. -- In particular, it is a colimit for the diagram `(D ⋙ forget T) ⋙ T` -- so to construct a map TL ⟶ L it suffices to show that L is the apex of a cocone for this diagram. -- In other words, we need a natural transformation from const L to `(D ⋙ forget T) ⋙ T`. -- But we already know that L is the apex of a cocone for the diagram `D ⋙ forget T`, so it -- suffices to give a natural transformation `((D ⋙ forget T) ⋙ T) ⟶ (D ⋙ forget T)`: /-- (Impl) The natural transformation given by the algebra structure maps, used to construct a cocone `c` with apex `colimit (D ⋙ forget T)`. -/ @[simps] def γ : ((D ⋙ forget T) ⋙ ↑T) ⟶ (D ⋙ forget T) := { app := λ j, (D.obj j).a } /-- (Impl) A cocone for the diagram `(D ⋙ forget T) ⋙ T` found by composing the natural transformation `γ` with the colimiting cocone for `D ⋙ forget T`. -/ @[simps] def new_cocone : cocone ((D ⋙ forget T) ⋙ ↑T) := { X := c.X, ι := γ ≫ c.ι } variables [preserves_colimit (D ⋙ forget T) (T : C ⥤ C)] /-- (Impl) Define the map `λ : TL ⟶ L`, which will serve as the structure of the coalgebra on `L`, and we will show is the colimiting object. We use the cocone constructed by `c` and the fact that `T` preserves colimits to produce this morphism. -/ @[reducible] def lambda : ((T : C ⥤ C).map_cocone c).X ⟶ c.X := (is_colimit_of_preserves _ t).desc (new_cocone c) /-- (Impl) The key property defining the map `λ : TL ⟶ L`. -/ lemma commuting (j : J) : (T : C ⥤ C).map (c.ι.app j) ≫ lambda c t = (D.obj j).a ≫ c.ι.app j := (is_colimit_of_preserves _ t).fac (new_cocone c) j variables [preserves_colimit ((D ⋙ forget T) ⋙ ↑T) (T : C ⥤ C)] /-- (Impl) Construct the colimiting algebra from the map `λ : TL ⟶ L` given by `lambda`. We are required to show it satisfies the two algebra laws, which follow from the algebra laws for the image of `D` and our `commuting` lemma. -/ @[simps] def cocone_point : algebra T := { A := c.X, a := lambda c t, unit' := begin apply t.hom_ext, intro j, rw [(show c.ι.app j ≫ T.η.app c.X ≫ _ = T.η.app (D.obj j).A ≫ _ ≫ _, from T.η.naturality_assoc _ _), commuting, algebra.unit_assoc (D.obj j)], dsimp, simp -- See library note [dsimp, simp] end, assoc' := begin refine (is_colimit_of_preserves _ (is_colimit_of_preserves _ t)).hom_ext (λ j, _), rw [functor.map_cocone_ι_app, functor.map_cocone_ι_app, (show (T : C ⥤ C).map ((T : C ⥤ C).map _) ≫ _ ≫ _ = _, from T.μ.naturality_assoc _ _), ←functor.map_comp_assoc, commuting, functor.map_comp, category.assoc, commuting], apply (D.obj j).assoc_assoc _, end } /-- (Impl) Construct the lifted cocone in `algebra T` which will be colimiting. -/ @[simps] def lifted_cocone : cocone D := { X := cocone_point c t, ι := { app := λ j, { f := c.ι.app j, h' := commuting _ _ _ }, naturality' := λ A B f, by { ext1, dsimp, rw [comp_id], apply c.w } } } /-- (Impl) Prove that the lifted cocone is colimiting. -/ @[simps] def lifted_cocone_is_colimit : is_colimit (lifted_cocone c t) := { desc := λ s, { f := t.desc ((forget T).map_cocone s), h' := (is_colimit_of_preserves (T : C ⥤ C) t).hom_ext $ λ j, begin dsimp, rw [←functor.map_comp_assoc, ←category.assoc, t.fac, commuting, category.assoc, t.fac], apply algebra.hom.h, end }, uniq' := λ s m J, by { ext1, apply t.hom_ext, intro j, simpa using congr_arg algebra.hom.f (J j) } } end forget_creates_colimits open forget_creates_colimits -- TODO: the converse of this is true as well /-- The forgetful functor from the Eilenberg-Moore category for a monad creates any colimit which the monad itself preserves. -/ noncomputable instance forget_creates_colimit (D : J ⥤ algebra T) [preserves_colimit (D ⋙ forget T) (T : C ⥤ C)] [preserves_colimit ((D ⋙ forget T) ⋙ ↑T) (T : C ⥤ C)] : creates_colimit D (forget T) := creates_colimit_of_reflects_iso $ λ c t, { lifted_cocone := { X := cocone_point c t, ι := { app := λ j, { f := c.ι.app j, h' := commuting _ _ _ }, naturality' := λ A B f, by { ext1, dsimp, erw [comp_id, c.w] } } }, valid_lift := cocones.ext (iso.refl _) (by tidy), makes_colimit := lifted_cocone_is_colimit _ _ } noncomputable instance forget_creates_colimits_of_shape [preserves_colimits_of_shape J (T : C ⥤ C)] : creates_colimits_of_shape J (forget T) := { creates_colimit := λ K, by apply_instance } noncomputable instance forget_creates_colimits [preserves_colimits_of_size.{v u} (T : C ⥤ C)] : creates_colimits_of_size.{v u} (forget T) := { creates_colimits_of_shape := λ J 𝒥₁, by apply_instance } /-- For `D : J ⥤ algebra T`, `D ⋙ forget T` has a colimit, then `D` has a colimit provided colimits of shape `J` are preserved by `T`. -/ lemma forget_creates_colimits_of_monad_preserves [preserves_colimits_of_shape J (T : C ⥤ C)] (D : J ⥤ algebra T) [has_colimit (D ⋙ forget T)] : has_colimit D := has_colimit_of_created D (forget T) end monad variables {C : Type u₁} [category.{v₁} C] {D : Type u₂} [category.{v₂} D] variables {J : Type u} [category.{v} J] instance comp_comparison_forget_has_limit (F : J ⥤ D) (R : D ⥤ C) [monadic_right_adjoint R] [has_limit (F ⋙ R)] : has_limit ((F ⋙ monad.comparison (adjunction.of_right_adjoint R)) ⋙ monad.forget _) := @has_limit_of_iso _ _ _ _ (F ⋙ R) _ _ (iso_whisker_left F (monad.comparison_forget (adjunction.of_right_adjoint R)).symm) instance comp_comparison_has_limit (F : J ⥤ D) (R : D ⥤ C) [monadic_right_adjoint R] [has_limit (F ⋙ R)] : has_limit (F ⋙ monad.comparison (adjunction.of_right_adjoint R)) := monad.has_limit_of_comp_forget_has_limit (F ⋙ monad.comparison (adjunction.of_right_adjoint R)) /-- Any monadic functor creates limits. -/ noncomputable def monadic_creates_limits (R : D ⥤ C) [monadic_right_adjoint R] : creates_limits_of_size.{v u} R := creates_limits_of_nat_iso (monad.comparison_forget (adjunction.of_right_adjoint R)) /-- The forgetful functor from the Eilenberg-Moore category for a monad creates any colimit which the monad itself preserves. -/ noncomputable def monadic_creates_colimit_of_preserves_colimit (R : D ⥤ C) (K : J ⥤ D) [monadic_right_adjoint R] [preserves_colimit (K ⋙ R) (left_adjoint R ⋙ R)] [preserves_colimit ((K ⋙ R) ⋙ left_adjoint R ⋙ R) (left_adjoint R ⋙ R)] : creates_colimit K R := begin apply creates_colimit_of_nat_iso (monad.comparison_forget (adjunction.of_right_adjoint R)), apply category_theory.comp_creates_colimit _ _, apply_instance, let i : ((K ⋙ monad.comparison (adjunction.of_right_adjoint R)) ⋙ monad.forget _) ≅ K ⋙ R := functor.associator _ _ _ ≪≫ iso_whisker_left K (monad.comparison_forget (adjunction.of_right_adjoint R)), apply category_theory.monad.forget_creates_colimit _, { dsimp, refine preserves_colimit_of_iso_diagram _ i.symm }, { dsimp, refine preserves_colimit_of_iso_diagram _ (iso_whisker_right i (left_adjoint R ⋙ R)).symm }, end /-- A monadic functor creates any colimits of shapes it preserves. -/ noncomputable def monadic_creates_colimits_of_shape_of_preserves_colimits_of_shape (R : D ⥤ C) [monadic_right_adjoint R] [preserves_colimits_of_shape J R] : creates_colimits_of_shape J R := begin have : preserves_colimits_of_shape J (left_adjoint R ⋙ R), { apply category_theory.limits.comp_preserves_colimits_of_shape _ _, apply (adjunction.left_adjoint_preserves_colimits (adjunction.of_right_adjoint R)).1, apply_instance }, exactI ⟨λ K, monadic_creates_colimit_of_preserves_colimit _ _⟩, end /-- A monadic functor creates colimits if it preserves colimits. -/ noncomputable def monadic_creates_colimits_of_preserves_colimits (R : D ⥤ C) [monadic_right_adjoint R] [preserves_colimits_of_size.{v u} R] : creates_colimits_of_size.{v u} R := { creates_colimits_of_shape := λ J 𝒥₁, by exactI monadic_creates_colimits_of_shape_of_preserves_colimits_of_shape _ } section lemma has_limit_of_reflective (F : J ⥤ D) (R : D ⥤ C) [has_limit (F ⋙ R)] [reflective R] : has_limit F := by { haveI := monadic_creates_limits.{v u} R, exact has_limit_of_created F R } /-- If `C` has limits of shape `J` then any reflective subcategory has limits of shape `J`. -/ lemma has_limits_of_shape_of_reflective [has_limits_of_shape J C] (R : D ⥤ C) [reflective R] : has_limits_of_shape J D := { has_limit := λ F, has_limit_of_reflective F R } /-- If `C` has limits then any reflective subcategory has limits. -/ lemma has_limits_of_reflective (R : D ⥤ C) [has_limits_of_size.{v u} C] [reflective R] : has_limits_of_size.{v u} D := { has_limits_of_shape := λ J 𝒥₁, by exactI has_limits_of_shape_of_reflective R } /-- If `C` has colimits of shape `J` then any reflective subcategory has colimits of shape `J`. -/ lemma has_colimits_of_shape_of_reflective (R : D ⥤ C) [reflective R] [has_colimits_of_shape J C] : has_colimits_of_shape J D := { has_colimit := λ F, begin let c := (left_adjoint R).map_cocone (colimit.cocone (F ⋙ R)), letI : preserves_colimits_of_shape J _ := (adjunction.of_right_adjoint R).left_adjoint_preserves_colimits.1, let t : is_colimit c := is_colimit_of_preserves (left_adjoint R) (colimit.is_colimit _), apply has_colimit.mk ⟨_, (is_colimit.precompose_inv_equiv _ _).symm t⟩, apply (iso_whisker_left F (as_iso (adjunction.of_right_adjoint R).counit) : _) ≪≫ F.right_unitor, end } /-- If `C` has colimits then any reflective subcategory has colimits. -/ lemma has_colimits_of_reflective (R : D ⥤ C) [reflective R] [has_colimits_of_size.{v u} C] : has_colimits_of_size.{v u} D := { has_colimits_of_shape := λ J 𝒥, by exactI has_colimits_of_shape_of_reflective R } /-- The reflector always preserves terminal objects. Note this in general doesn't apply to any other limit. -/ noncomputable def left_adjoint_preserves_terminal_of_reflective (R : D ⥤ C) [reflective R] : preserves_limits_of_shape (discrete.{v} pempty) (left_adjoint R) := { preserves_limit := λ K, let F := functor.empty.{v} D in begin apply preserves_limit_of_iso_diagram _ (functor.empty_ext (F ⋙ R) _), fsplit, intros c h, haveI : has_limit (F ⋙ R) := ⟨⟨⟨c,h⟩⟩⟩, haveI : has_limit F := has_limit_of_reflective F R, apply is_limit_change_empty_cone D (limit.is_limit F), apply (as_iso ((adjunction.of_right_adjoint R).counit.app _)).symm.trans, { apply (left_adjoint R).map_iso, letI := monadic_creates_limits.{v v} R, let := (category_theory.preserves_limit_of_creates_limit_and_has_limit F R).preserves, apply (this (limit.is_limit F)).cone_point_unique_up_to_iso h }, apply_instance, end } end end category_theory
4254ed5da71620a94802c6738bf31fd7cd77eaf7
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/stage0/src/Lean/Elab/DeclModifiers.lean
1384e3675a442785859d3aefe784c55db31fc33b
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
10,010
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, Sebastian Ullrich -/ import Lean.Structure import Lean.Elab.Attributes namespace Lean.Elab /-- Ensure the environment does not contain a declaration with name `declName`. Recall that a private declaration cannot shadow a non-private one and vice-versa, although they internally have different names. -/ def checkNotAlreadyDeclared {m} [Monad m] [MonadEnv m] [MonadError m] (declName : Name) : m Unit := do let env ← getEnv if env.contains declName then match privateToUserName? declName with | none => throwError "'{declName}' has already been declared" | some declName => throwError "private declaration '{declName}' has already been declared" if env.contains (mkPrivateName env declName) then throwError "a private declaration '{declName}' has already been declared" match privateToUserName? declName with | none => pure () | some declName => if env.contains declName then throwError "a non-private declaration '{declName}' has already been declared" /-- Declaration visibility modifier. That is, whether a declaration is regular, protected or private. -/ inductive Visibility where | regular | «protected» | «private» deriving Inhabited instance : ToString Visibility where toString | .regular => "regular" | .private => "private" | .protected => "protected" /-- Whether a declaration is default, partial or nonrec. -/ inductive RecKind where | «partial» | «nonrec» | default deriving Inhabited /-- Flags and data added to declarations (eg docstrings, attributes, `private`, `unsafe`, `partial`, ...). -/ structure Modifiers where docString? : Option String := none visibility : Visibility := Visibility.regular isNoncomputable : Bool := false recKind : RecKind := RecKind.default isUnsafe : Bool := false attrs : Array Attribute := #[] deriving Inhabited def Modifiers.isPrivate : Modifiers → Bool | { visibility := .private, .. } => true | _ => false def Modifiers.isProtected : Modifiers → Bool | { visibility := .protected, .. } => true | _ => false def Modifiers.isPartial : Modifiers → Bool | { recKind := .partial, .. } => true | _ => false def Modifiers.isNonrec : Modifiers → Bool | { recKind := .nonrec, .. } => true | _ => false /-- Store `attr` in `modifiers` -/ def Modifiers.addAttribute (modifiers : Modifiers) (attr : Attribute) : Modifiers := { modifiers with attrs := modifiers.attrs.push attr } instance : ToFormat Modifiers := ⟨fun m => let components : List Format := (match m.docString? with | some str => [f!"/--{str}-/"] | none => []) ++ (match m.visibility with | .regular => [] | .protected => [f!"protected"] | .private => [f!"private"]) ++ (if m.isNoncomputable then [f!"noncomputable"] else []) ++ (match m.recKind with | RecKind.partial => [f!"partial"] | RecKind.nonrec => [f!"nonrec"] | _ => []) ++ (if m.isUnsafe then [f!"unsafe"] else []) ++ m.attrs.toList.map (fun attr => format attr) Format.bracket "{" (Format.joinSep components ("," ++ Format.line)) "}"⟩ instance : ToString Modifiers := ⟨toString ∘ format⟩ /-- Retrieve doc string from `stx` of the form `(docComment)?`. -/ def expandOptDocComment? [Monad m] [MonadError m] (optDocComment : Syntax) : m (Option String) := match optDocComment.getOptional? with | none => return none | some s => match s[1] with | .atom _ val => return some (val.extract 0 (val.endPos - ⟨2⟩)) | _ => throwErrorAt s "unexpected doc string{indentD s[1]}" section Methods variable [Monad m] [MonadEnv m] [MonadResolveName m] [MonadError m] [MonadMacroAdapter m] [MonadRecDepth m] [MonadTrace m] [MonadOptions m] [AddMessageContext m] [MonadLog m] [MonadInfoTree m] [MonadLiftT IO m] /-- Elaborate declaration modifiers (i.e., attributes, `partial`, `private`, `proctected`, `unsafe`, `noncomputable`, doc string)-/ def elabModifiers (stx : Syntax) : m Modifiers := do let docCommentStx := stx[0] let attrsStx := stx[1] let visibilityStx := stx[2] let noncompStx := stx[3] let unsafeStx := stx[4] let recKind := if stx[5].isNone then RecKind.default else if stx[5][0].getKind == ``Parser.Command.partial then RecKind.partial else RecKind.nonrec let docString? ← match docCommentStx.getOptional? with | none => pure none | some s => pure (some (← getDocStringText ⟨s⟩)) let visibility ← match visibilityStx.getOptional? with | none => pure Visibility.regular | some v => let kind := v.getKind if kind == ``Parser.Command.private then pure Visibility.private else if kind == ``Parser.Command.protected then pure Visibility.protected else throwErrorAt v "unexpected visibility modifier" let attrs ← match attrsStx.getOptional? with | none => pure #[] | some attrs => elabDeclAttrs attrs return { docString?, visibility, recKind, attrs, isUnsafe := !unsafeStx.isNone isNoncomputable := !noncompStx.isNone } /-- Ensure the function has not already been declared, and apply the given visibility setting to `declName`. If `private`, return the updated name using our internal encoding for private names. If `protected`, register `declName` as protected in the environment. -/ def applyVisibility (visibility : Visibility) (declName : Name) : m Name := do match visibility with | .private => let declName := mkPrivateName (← getEnv) declName checkNotAlreadyDeclared declName return declName | .protected => checkNotAlreadyDeclared declName modifyEnv fun env => addProtected env declName return declName | _ => checkNotAlreadyDeclared declName pure declName def checkIfShadowingStructureField (declName : Name) : m Unit := do match declName with | Name.str pre .. => if isStructure (← getEnv) pre then let fieldNames := getStructureFieldsFlattened (← getEnv) pre for fieldName in fieldNames do if pre ++ fieldName == declName then throwError "invalid declaration name '{declName}', structure '{pre}' has field '{fieldName}'" | _ => pure () def mkDeclName (currNamespace : Name) (modifiers : Modifiers) (shortName : Name) : m (Name × Name) := do let mut shortName := shortName let mut currNamespace := currNamespace let view := extractMacroScopes shortName let name := view.name let isRootName := (`_root_).isPrefixOf name if name == `_root_ then throwError "invalid declaration name `_root_`, `_root_` is a prefix used to refer to the 'root' namespace" let declName := if isRootName then { view with name := name.replacePrefix `_root_ Name.anonymous }.review else currNamespace ++ shortName if isRootName then let .str p s := name | throwError "invalid declaration name '{name}'" shortName := Name.mkSimple s currNamespace := p.replacePrefix `_root_ Name.anonymous checkIfShadowingStructureField declName let declName ← applyVisibility modifiers.visibility declName match modifiers.visibility with | Visibility.protected => match currNamespace with | .str _ s => pure (declName, Name.mkSimple s ++ shortName) | _ => throwError "protected declarations must be in a namespace" | _ => pure (declName, shortName) /-- `declId` is of the form ``` leading_parser ident >> optional (".{" >> sepBy1 ident ", " >> "}") ``` but we also accept a single identifier to users to make macro writing more convenient . -/ def expandDeclIdCore (declId : Syntax) : Name × Syntax := if declId.isIdent then (declId.getId, mkNullNode) else let id := declId[0].getId let optUnivDeclStx := declId[1] (id, optUnivDeclStx) /-- `expandDeclId` resulting type. -/ structure ExpandDeclIdResult where /-- Short name for recursively referring to the declaration. -/ shortName : Name /-- Fully qualified name that will be used to name the declaration in the kernel. -/ declName : Name /-- Universe parameter names provided using the `universe` command and `.{...}` notation. -/ levelNames : List Name /-- Given a declaration identifier (e.g., `ident (".{" ident,+ "}")?`) that may contain explicit universe parameters - Ensure the new universe parameters do not shadow universe parameters declared using `universe` command. - Create the fully qualified named for the declaration using the current namespace, and given `modifiers` - Create a short version for recursively referring to the declaration. Recall that the `protected` modifier affects the generation of the short name. The result also contains the universe parameters provided using `universe` command, and the `.{...}` notation. This commands also stores the doc string stored in `modifiers`. -/ def expandDeclId (currNamespace : Name) (currLevelNames : List Name) (declId : Syntax) (modifiers : Modifiers) : m ExpandDeclIdResult := do -- ident >> optional (".{" >> sepBy1 ident ", " >> "}") let (shortName, optUnivDeclStx) := expandDeclIdCore declId let levelNames ← if optUnivDeclStx.isNone then pure currLevelNames else let extraLevels := optUnivDeclStx[1].getArgs.getEvenElems extraLevels.foldlM (fun levelNames idStx => let id := idStx.getId if levelNames.elem id then withRef idStx <| throwAlreadyDeclaredUniverseLevel id else pure (id :: levelNames)) currLevelNames let (declName, shortName) ← withRef declId <| mkDeclName currNamespace modifiers shortName addDocString' declName modifiers.docString? return { shortName := shortName, declName := declName, levelNames := levelNames } end Methods end Lean.Elab
51e44745f7bb5579c16eab57b9cadbc9a7b700b3
4fa161becb8ce7378a709f5992a594764699e268
/src/measure_theory/outer_measure.lean
4d002c2d23d9e33b52937614af657886c1ae522c
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
22,209
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 Outer measures -- overapproximations of measures -/ import analysis.specific_limits import measure_theory.measurable_space /-! # Outer Measures An outer measure is a function `μ : set α → ennreal`, from the powerset of a type to the extended nonnegative real numbers that satisfies the following conditions: 1. `μ ∅ = 0`; 2. `μ` is monotone; 3. `μ` is countably subadditive. This means that the outer measure of a countable union is at most the sum of the outer measure on the individual sets. Note that we do not need `α` to be measurable to define an outer measure. The outer measures on a type `α` form a complete lattice. Given an arbitrary function `m : set α → ennreal` that sends `∅` to `0` we can define an outer measure on `α` that on `s` is defined to be the infimum of `∑ᵢ, m (sᵢ)` for all collections of sets `sᵢ` that cover `s`. This is the unique maximal outer measure that is at most the given function. Given an outer measure `m`, the Carathéodory-measurable sets are the sets `s` such that for all sets `t` we have `m t = m (t ∩ s) + m (t \ s)`. This forms a measurable space. ## Main statements * `outer_measure.of_function` is the greatest outer measure that is at most the given function. * `caratheodory` is the Carathéodory-measurable space of an outer measure. * `Inf_eq_of_function_Inf_gen` is a characterization of the infimum of outer measures. ## References * <https://en.wikipedia.org/wiki/Outer_measure> * <https://en.wikipedia.org/wiki/Carath%C3%A9odory%27s_criterion> ## Tags outer measure, Carathéodory-measurable, Carathéodory's criterion -/ noncomputable theory open set finset function filter encodable open_locale classical big_operators namespace measure_theory /-- An outer measure is a countably subadditive monotone function that sends `∅` to `0`. -/ structure outer_measure (α : Type*) := (measure_of : set α → ennreal) (empty : measure_of ∅ = 0) (mono : ∀{s₁ s₂}, s₁ ⊆ s₂ → measure_of s₁ ≤ measure_of s₂) (Union_nat : ∀(s:ℕ → set α), measure_of (⋃i, s i) ≤ (∑'i, measure_of (s i))) namespace outer_measure instance {α} : has_coe_to_fun (outer_measure α) := ⟨_, λ m, m.measure_of⟩ section basic variables {α : Type*} {ms : set (outer_measure α)} {m : outer_measure α} @[simp] theorem empty' (m : outer_measure α) : m ∅ = 0 := m.empty theorem mono' (m : outer_measure α) {s₁ s₂} (h : s₁ ⊆ s₂) : m s₁ ≤ m s₂ := m.mono h theorem Union_aux (m : set α → ennreal) (m0 : m ∅ = 0) {β} [encodable β] (s : β → set α) : (∑' b, m (s b)) = ∑' i, m (⋃ b ∈ decode2 β i, s b) := begin have H : ∀ n, m (⋃ b ∈ decode2 β n, s b) ≠ 0 → (decode2 β n).is_some, { intros n h, cases decode2 β n with b, { exact (h (by simp [m0])).elim }, { exact rfl } }, refine tsum_eq_tsum_of_ne_zero_bij (λ n h, option.get (H n h)) _ _ _, { intros m n hm hn e, have := mem_decode2.1 (option.get_mem (H n hn)), rwa [← e, mem_decode2.1 (option.get_mem (H m hm))] at this }, { intros b h, refine ⟨encode b, _, _⟩, { convert h, simp [set.ext_iff, encodek2] }, { exact option.get_of_mem _ (encodek2 _) } }, { intros n h, transitivity, swap, rw [show decode2 β n = _, from option.get_mem (H n h)], congr, simp [set.ext_iff, -option.some_get] } end protected theorem Union (m : outer_measure α) {β} [encodable β] (s : β → set α) : m (⋃i, s i) ≤ (∑'i, m (s i)) := by rw [Union_decode2, Union_aux _ m.empty' s]; exact m.Union_nat _ lemma Union_null (m : outer_measure α) {β} [encodable β] {s : β → set α} (h : ∀ i, m (s i) = 0) : m (⋃i, s i) = 0 := by simpa [h] using m.Union s protected lemma union (m : outer_measure α) (s₁ s₂ : set α) : m (s₁ ∪ s₂) ≤ m s₁ + m s₂ := begin convert m.Union (λ b, cond b s₁ s₂), { simp [union_eq_Union] }, { rw tsum_fintype, change _ = _ + _, simp } end lemma union_null (m : outer_measure α) {s₁ s₂ : set α} (h₁ : m s₁ = 0) (h₂ : m s₂ = 0) : m (s₁ ∪ s₂) = 0 := by simpa [h₁, h₂] using m.union s₁ s₂ @[ext] lemma ext : ∀{μ₁ μ₂ : outer_measure α}, (∀s, μ₁ s = μ₂ s) → μ₁ = μ₂ | ⟨m₁, e₁, _, u₁⟩ ⟨m₂, e₂, _, u₂⟩ h := by congr; exact funext h instance : has_zero (outer_measure α) := ⟨{ measure_of := λ_, 0, empty := rfl, mono := assume _ _ _, le_refl 0, Union_nat := assume s, zero_le _ }⟩ @[simp] theorem zero_apply (s : set α) : (0 : outer_measure α) s = 0 := rfl instance : inhabited (outer_measure α) := ⟨0⟩ instance : has_add (outer_measure α) := ⟨λm₁ m₂, { measure_of := λs, m₁ s + m₂ s, empty := show m₁ ∅ + m₂ ∅ = 0, by simp [outer_measure.empty], mono := assume s₁ s₂ h, add_le_add' (m₁.mono h) (m₂.mono h), Union_nat := assume s, calc m₁ (⋃i, s i) + m₂ (⋃i, s i) ≤ (∑'i, m₁ (s i)) + (∑'i, m₂ (s i)) : add_le_add' (m₁.Union_nat s) (m₂.Union_nat s) ... = _ : ennreal.tsum_add.symm}⟩ @[simp] theorem add_apply (m₁ m₂ : outer_measure α) (s : set α) : (m₁ + m₂) s = m₁ s + m₂ s := rfl instance add_comm_monoid : add_comm_monoid (outer_measure α) := { zero := 0, add := (+), add_comm := assume a b, ext $ assume s, add_comm _ _, add_assoc := assume a b c, ext $ assume s, add_assoc _ _ _, add_zero := assume a, ext $ assume s, add_zero _, zero_add := assume a, ext $ assume s, by simp } instance : has_bot (outer_measure α) := ⟨0⟩ instance outer_measure.order_bot : order_bot (outer_measure α) := { le := λm₁ m₂, ∀s, m₁ s ≤ m₂ s, bot := 0, le_refl := assume a s, le_refl _, le_trans := assume a b c hab hbc s, le_trans (hab s) (hbc s), le_antisymm := assume a b hab hba, ext $ assume s, le_antisymm (hab s) (hba s), bot_le := assume a s, zero_le _ } section supremum instance : has_Sup (outer_measure α) := ⟨λms, { measure_of := λs, ⨆m:ms, m.val s, empty := le_zero_iff_eq.1 $ supr_le $ λ ⟨m, h⟩, le_of_eq m.empty, mono := assume s₁ s₂ hs, supr_le_supr $ assume ⟨m, hm⟩, m.mono hs, Union_nat := assume f, supr_le $ assume m, calc m.val (⋃i, f i) ≤ (∑' (i : ℕ), m.val (f i)) : m.val.Union_nat _ ... ≤ (∑'i, ⨆m:ms, m.val (f i)) : ennreal.tsum_le_tsum $ assume i, le_supr (λm:ms, m.val (f i)) m }⟩ protected lemma le_Sup (hm : m ∈ ms) : m ≤ Sup ms := λ s, le_supr (λm:ms, m.val s) ⟨m, hm⟩ protected lemma Sup_le (hm : ∀m' ∈ ms, m' ≤ m) : Sup ms ≤ m := λ s, (supr_le $ assume ⟨m', h'⟩, (hm m' h') s) instance : has_Inf (outer_measure α) := ⟨λs, Sup {m | ∀m'∈s, m ≤ m'}⟩ protected lemma Inf_le (hm : m ∈ ms) : Inf ms ≤ m := outer_measure.Sup_le $ assume m' h', h' _ hm protected lemma le_Inf (hm : ∀m' ∈ ms, m ≤ m') : m ≤ Inf ms := outer_measure.le_Sup hm instance : complete_lattice (outer_measure α) := { top := Sup univ, le_top := assume a, outer_measure.le_Sup (mem_univ a), Sup := Sup, Sup_le := assume s m, outer_measure.Sup_le, le_Sup := assume s m, outer_measure.le_Sup, Inf := Inf, Inf_le := assume s m, outer_measure.Inf_le, le_Inf := assume s m, outer_measure.le_Inf, sup := λa b, Sup {a, b}, le_sup_left := assume a b, outer_measure.le_Sup $ by simp, le_sup_right := assume a b, outer_measure.le_Sup $ by simp, sup_le := assume a b c ha hb, outer_measure.Sup_le $ by simp [or_imp_distrib, ha, hb] {contextual:=tt}, inf := λa b, Inf {a, b}, inf_le_left := assume a b, outer_measure.Inf_le $ by simp, inf_le_right := assume a b, outer_measure.Inf_le $ by simp, le_inf := assume a b c ha hb, outer_measure.le_Inf $ by simp [or_imp_distrib, ha, hb] {contextual:=tt}, .. outer_measure.order_bot } @[simp] theorem Sup_apply (ms : set (outer_measure α)) (s : set α) : (Sup ms) s = ⨆ m : ms, m s := rfl @[simp] theorem supr_apply {ι} (f : ι → outer_measure α) (s : set α) : (⨆ i : ι, f i) s = ⨆ i, f i s := le_antisymm (supr_le $ λ ⟨_, i, rfl⟩, le_supr _ i) (supr_le $ λ i, le_supr (λ (m : {a : outer_measure α // ∃ i, f i = a}), m.1 s) ⟨f i, i, rfl⟩) @[simp] theorem sup_apply (m₁ m₂ : outer_measure α) (s : set α) : (m₁ ⊔ m₂) s = m₁ s ⊔ m₂ s := by have := supr_apply (λ b, cond b m₁ m₂) s; rwa [supr_bool_eq, supr_bool_eq] at this end supremum /-- The pushforward of `m` along `f`. The outer measure on `s` is defined to be `m (f ⁻¹' s)`. -/ def map {β} (f : α → β) (m : outer_measure α) : outer_measure β := { measure_of := λs, m (f ⁻¹' s), empty := m.empty, mono := λ s t h, m.mono (preimage_mono h), Union_nat := λ s, by rw [preimage_Union]; exact m.Union_nat (λ i, f ⁻¹' s i) } @[simp] theorem map_apply {β} (f : α → β) (m : outer_measure α) (s : set β) : map f m s = m (f ⁻¹' s) := rfl @[simp] theorem map_id (m : outer_measure α) : map id m = m := ext $ λ s, rfl @[simp] theorem map_map {β γ} (f : α → β) (g : β → γ) (m : outer_measure α) : map g (map f m) = map (g ∘ f) m := ext $ λ s, rfl instance : functor outer_measure := {map := λ α β, map} instance : is_lawful_functor outer_measure := { id_map := λ α, map_id, comp_map := λ α β γ f g m, (map_map f g m).symm } /-- The dirac outer measure. -/ def dirac (a : α) : outer_measure α := { measure_of := λs, ⨆ h : a ∈ s, 1, empty := by simp, mono := λ s t h, supr_le_supr2 (λ h', ⟨h h', le_refl _⟩), Union_nat := λ s, supr_le $ λ h, let ⟨i, h⟩ := mem_Union.1 h in le_trans (by exact le_supr _ h) (ennreal.le_tsum i) } @[simp] theorem dirac_apply (a : α) (s : set α) : dirac a s = ⨆ h : a ∈ s, 1 := rfl /-- The sum of an (arbitrary) collection of outer measures. -/ def sum {ι} (f : ι → outer_measure α) : outer_measure α := { measure_of := λs, ∑' i, f i s, empty := by simp, mono := λ s t h, ennreal.tsum_le_tsum (λ i, (f i).mono' h), Union_nat := λ s, by rw ennreal.tsum_comm; exact ennreal.tsum_le_tsum (λ i, (f i).Union_nat _) } @[simp] theorem sum_apply {ι} (f : ι → outer_measure α) (s : set α) : sum f s = ∑' i, f i s := rfl instance : has_scalar ennreal (outer_measure α) := ⟨λ a m, { measure_of := λs, a * m s, empty := by simp, mono := λ s t h, canonically_ordered_semiring.mul_le_mul (le_refl _) (m.mono' h), Union_nat := λ s, by rw ennreal.tsum_mul_left; exact canonically_ordered_semiring.mul_le_mul (le_refl _) (m.Union_nat _) }⟩ @[simp] theorem smul_apply (a : ennreal) (m : outer_measure α) (s : set α) : (a • m) s = a * m s := rfl instance : semimodule ennreal (outer_measure α) := { smul_add := λ a m₁ m₂, ext $ λ s, mul_add _ _ _, add_smul := λ a b m, ext $ λ s, add_mul _ _ _, mul_smul := λ a b m, ext $ λ s, mul_assoc _ _ _, one_smul := λ m, ext $ λ s, one_mul _, zero_smul := λ m, ext $ λ s, zero_mul _, smul_zero := λ a, ext $ λ s, mul_zero _, ..outer_measure.has_scalar } theorem smul_dirac_apply (a : ennreal) (b : α) (s : set α) : (a • dirac b) s = ⨆ h : b ∈ s, a := by by_cases b ∈ s; simp [h] theorem top_apply {s : set α} (h : s.nonempty) : (⊤ : outer_measure α) s = ⊤ := let ⟨a, as⟩ := h in top_unique $ le_supr_of_le ⟨(⊤ : ennreal) • dirac a, trivial⟩ $ by simp [smul_dirac_apply, as] end basic section of_function set_option eqn_compiler.zeta true /-- Given any function `m` assigning measures to sets satisying `m ∅ = 0`, there is a unique maximal outer measure `μ` satisfying `μ s ≤ m s` for all `s : set α`. -/ protected def of_function {α : Type*} (m : set α → ennreal) (m_empty : m ∅ = 0) : outer_measure α := let μ := λs, ⨅{f : ℕ → set α} (h : s ⊆ ⋃i, f i), ∑'i, m (f i) in { measure_of := μ, empty := le_antisymm (infi_le_of_le (λ_, ∅) $ infi_le_of_le (empty_subset _) $ by simp [m_empty]) (zero_le _), mono := assume s₁ s₂ hs, infi_le_infi $ assume f, infi_le_infi2 $ assume hb, ⟨subset.trans hs hb, le_refl _⟩, Union_nat := assume s, ennreal.le_of_forall_epsilon_le $ begin assume ε hε (hb : (∑'i, μ (s i)) < ⊤), rcases ennreal.exists_pos_sum_of_encodable (ennreal.coe_lt_coe.2 hε) ℕ with ⟨ε', hε', hl⟩, refine le_trans _ (add_le_add_left' (le_of_lt hl)), rw ← ennreal.tsum_add, choose f hf using show ∀i, ∃f:ℕ → set α, s i ⊆ (⋃i, f i) ∧ (∑'i, m (f i)) < μ (s i) + ε' i, { intro, have : μ (s i) < μ (s i) + ε' i := ennreal.lt_add_right (lt_of_le_of_lt (by apply ennreal.le_tsum) hb) (by simpa using hε' i), simpa [μ, infi_lt_iff] }, refine le_trans _ (ennreal.tsum_le_tsum $ λ i, le_of_lt (hf i).2), rw [← ennreal.tsum_prod, ← tsum_equiv equiv.nat_prod_nat_equiv_nat.symm], swap, {apply_instance}, refine infi_le_of_le _ (infi_le _ _), exact Union_subset (λ i, subset.trans (hf i).1 $ Union_subset $ λ j, subset.trans (by simp) $ subset_Union _ $ equiv.nat_prod_nat_equiv_nat (i, j)), end } theorem of_function_le {α : Type*} (m : set α → ennreal) (m_empty s) : outer_measure.of_function m m_empty s ≤ m s := let f : ℕ → set α := λi, nat.rec_on i s (λn s, ∅) in infi_le_of_le f $ infi_le_of_le (subset_Union f 0) $ le_of_eq $ calc (∑'i, m (f i)) = ∑ i in {0}, m (f i) : tsum_eq_sum $ by intro i; cases i; simp [m_empty] ... = m s : by simp; refl theorem le_of_function {α : Type*} {m m_empty} {μ : outer_measure α} : μ ≤ outer_measure.of_function m m_empty ↔ ∀ s, μ s ≤ m s := ⟨λ H s, le_trans (H _) (of_function_le _ _ _), λ H s, le_infi $ λ f, le_infi $ λ hs, le_trans (μ.mono hs) $ le_trans (μ.Union f) $ ennreal.tsum_le_tsum $ λ i, H _⟩ end of_function section caratheodory_measurable universe u parameters {α : Type u} (m : outer_measure α) include m local attribute [simp] set.inter_comm set.inter_left_comm set.inter_assoc variables {s s₁ s₂ : set α} /-- A set `s` is Carathéodory-measurable for an outer measure `m` if for all sets `t` we have `m t = m (t ∩ s) + m (t \ s)`. -/ private def C (s : set α) : Prop := ∀t, m t = m (t ∩ s) + m (t \ s) private lemma C_iff_le {s : set α} : C s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t := forall_congr $ λ t, le_antisymm_iff.trans $ and_iff_right $ by convert m.union _ _; rw inter_union_diff t s @[simp] private lemma C_empty : C ∅ := by simp [C, m.empty, diff_empty] private lemma C_compl : C s₁ → C (- s₁) := by simp [C, diff_eq, add_comm] @[simp] private lemma C_compl_iff : C (- s) ↔ C s := ⟨λ h, by simpa using C_compl m h, C_compl⟩ private lemma C_union (h₁ : C s₁) (h₂ : C s₂) : C (s₁ ∪ s₂) := λ t, begin rw [h₁ t, h₂ (t ∩ s₁), h₂ (t \ s₁), h₁ (t ∩ (s₁ ∪ s₂)), inter_diff_assoc _ _ s₁, set.inter_assoc _ _ s₁, inter_eq_self_of_subset_right (set.subset_union_left _ _), union_diff_left, h₂ (t ∩ s₁)], simp [diff_eq, add_assoc] end private lemma measure_inter_union (h : s₁ ∩ s₂ ⊆ ∅) (h₁ : C s₁) {t : set α} : m (t ∩ (s₁ ∪ s₂)) = m (t ∩ s₁) + m (t ∩ s₂) := by rw [h₁, set.inter_assoc, set.union_inter_cancel_left, inter_diff_assoc, union_diff_cancel_left h] private lemma C_Union_lt {s : ℕ → set α} : ∀{n:ℕ}, (∀i<n, C (s i)) → C (⋃i<n, s i) | 0 h := by simp [nat.not_lt_zero] | (n + 1) h := by rw Union_lt_succ; exact C_union m (h n (le_refl (n + 1))) (C_Union_lt $ assume i hi, h i $ lt_of_lt_of_le hi $ nat.le_succ _) private lemma C_inter (h₁ : C s₁) (h₂ : C s₂) : C (s₁ ∩ s₂) := by rw [← C_compl_iff, compl_inter]; from C_union _ (C_compl _ h₁) (C_compl _ h₂) private lemma C_sum {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) {t : set α} : ∀ {n}, ∑ i in finset.range n, m (t ∩ s i) = m (t ∩ ⋃i<n, s i) | 0 := by simp [nat.not_lt_zero, m.empty] | (nat.succ n) := begin simp [Union_lt_succ, range_succ], rw [measure_inter_union m _ (h n), C_sum], intro a, simpa [range_succ] using λ h₁ i hi h₂, hd _ _ (ne_of_gt hi) ⟨h₁, h₂⟩ end private lemma C_Union_nat {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) : C (⋃i, s i) := C_iff_le.2 $ λ t, begin have hp : m (t ∩ ⋃i, s i) ≤ (⨆n, m (t ∩ ⋃i<n, s i)), { convert m.Union (λ i, t ∩ s i), { rw inter_Union }, { simp [ennreal.tsum_eq_supr_nat, C_sum m h hd] } }, refine le_trans (add_le_add_right' hp) _, rw ennreal.supr_add, refine supr_le (λ n, le_trans (add_le_add_left' _) (ge_of_eq (C_Union_lt m (λ i _, h i) _))), refine m.mono (diff_subset_diff_right _), exact bUnion_subset (λ i _, subset_Union _ i), end private lemma f_Union {s : ℕ → set α} (h : ∀i, C (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑'i, m (s i) := begin refine le_antisymm (m.Union_nat s) _, rw ennreal.tsum_eq_supr_nat, refine supr_le (λ n, _), have := @C_sum _ m _ h hd univ n, simp at this, simp [this], exact m.mono (bUnion_subset (λ i _, subset_Union _ i)), end /-- The Carathéodory-measurable sets for an outer measure `m` form a Dynkin system. -/ private def caratheodory_dynkin : measurable_space.dynkin_system α := { has := C, has_empty := C_empty, has_compl := assume s, C_compl, has_Union_nat := assume f hf hn, C_Union_nat hn hf } /-- Given an outer measure `μ`, the Carathéodory-measurable space is defined such that `s` is measurable if `∀t, μ t = μ (t ∩ s) + μ (t \ s)`. -/ protected def caratheodory : measurable_space α := caratheodory_dynkin.to_measurable_space $ assume s₁ s₂, C_inter lemma is_caratheodory {s : set α} : caratheodory.is_measurable s ↔ ∀t, m t = m (t ∩ s) + m (t \ s) := iff.rfl lemma is_caratheodory_le {s : set α} : caratheodory.is_measurable s ↔ ∀t, m (t ∩ s) + m (t \ s) ≤ m t := C_iff_le protected lemma Union_eq_of_caratheodory {s : ℕ → set α} (h : ∀i, caratheodory.is_measurable (s i)) (hd : pairwise (disjoint on s)) : m (⋃i, s i) = ∑'i, m (s i) := f_Union h hd end caratheodory_measurable variables {α : Type*} lemma caratheodory_is_measurable {m : set α → ennreal} {s : set α} {h₀ : m ∅ = 0} (hs : ∀t, m (t ∩ s) + m (t \ s) ≤ m t) : (outer_measure.of_function m h₀).caratheodory.is_measurable s := let o := (outer_measure.of_function m h₀) in (is_caratheodory_le o).2 $ λ t, le_infi $ λ f, le_infi $ λ hf, begin refine le_trans (add_le_add' (infi_le_of_le (λi, f i ∩ s) $ infi_le _ _) (infi_le_of_le (λi, f i \ s) $ infi_le _ _)) _, { rw ← Union_inter, exact inter_subset_inter_left _ hf }, { rw ← Union_diff, exact diff_subset_diff_left hf }, { rw ← ennreal.tsum_add, exact ennreal.tsum_le_tsum (λ i, hs _) } end @[simp] theorem zero_caratheodory : (0 : outer_measure α).caratheodory = ⊤ := top_unique $ λ s _ t, (add_zero _).symm theorem top_caratheodory : (⊤ : outer_measure α).caratheodory = ⊤ := top_unique $ assume s hs, (is_caratheodory_le _).2 $ assume t, t.eq_empty_or_nonempty.elim (λ ht, by simp [ht]) (λ ht, by simp only [ht, top_apply, le_top]) theorem le_add_caratheodory (m₁ m₂ : outer_measure α) : m₁.caratheodory ⊓ m₂.caratheodory ≤ (m₁ + m₂ : outer_measure α).caratheodory := λ s ⟨hs₁, hs₂⟩ t, by simp [hs₁ t, hs₂ t, add_left_comm, add_assoc] theorem le_sum_caratheodory {ι} (m : ι → outer_measure α) : (⨅ i, (m i).caratheodory) ≤ (sum m).caratheodory := λ s h t, by simp [λ i, measurable_space.is_measurable_infi.1 h i t, ennreal.tsum_add] theorem le_smul_caratheodory (a : ennreal) (m : outer_measure α) : m.caratheodory ≤ (a • m).caratheodory := λ s h t, by simp [h t, mul_add] @[simp] theorem dirac_caratheodory (a : α) : (dirac a).caratheodory = ⊤ := top_unique $ λ s _ t, begin by_cases a ∈ t; simp [h], by_cases a ∈ s; simp [h] end section Inf_gen /-- Given a set of outer measures, we define a new function that on a set `s` is defined to be the infimum of `μ(s)` for the outer measures `μ` in the collection. We ensure that this function is defined to be `0` on `∅`, even if the collection of outer measures is empty. The outer measure generated by this function is the infimum of the given outer measures. -/ def Inf_gen (m : set (outer_measure α)) (s : set α) : ennreal := ⨆(h : s.nonempty), ⨅ (μ : outer_measure α) (h : μ ∈ m), μ s @[simp] lemma Inf_gen_empty (m : set (outer_measure α)) : Inf_gen m ∅ = 0 := by simp [Inf_gen, empty_not_nonempty] lemma Inf_gen_nonempty1 (m : set (outer_measure α)) (t : set α) (h : t.nonempty) : Inf_gen m t = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) := by rw [Inf_gen, supr_pos h] lemma Inf_gen_nonempty2 (m : set (outer_measure α)) (μ) (h : μ ∈ m) (t) : Inf_gen m t = (⨅ (μ : outer_measure α) (h : μ ∈ m), μ t) := begin cases t.eq_empty_or_nonempty with ht ht, { simp [ht], refine (bot_unique $ infi_le_of_le μ $ _).symm, refine infi_le_of_le h (le_refl ⊥) }, { exact Inf_gen_nonempty1 m t ht } end lemma Inf_eq_of_function_Inf_gen (m : set (outer_measure α)) : Inf m = outer_measure.of_function (Inf_gen m) (Inf_gen_empty m) := begin refine le_antisymm (assume t', le_of_function.2 (assume t, _) _) (_root_.le_Inf $ assume μ hμ t, le_trans (outer_measure.of_function_le _ _ _) _); cases t.eq_empty_or_nonempty with ht ht; simp [ht, Inf_gen_nonempty1], { assume μ hμ, exact (show Inf m ≤ μ, from _root_.Inf_le hμ) t }, { exact infi_le_of_le μ (infi_le _ hμ) } end end Inf_gen end outer_measure end measure_theory
8b250ec166c5cab72aa860ec1c4ebfa1e0e81d02
a11f4536efad51bc2b648123619720f3b9318c0f
/src/limit_of_seq4.lean
7a8081c2cc7bca159673608748c520f3cf7d6aa1
[]
no_license
ezrasitorus/codewars_lean
909471d43f5130669a90b8e11afc37aec2f21d8f
6d1abcc1253403511f4cfd767c645596175e4fd3
refs/heads/master
1,672,659,589,352
1,603,281,507,000
1,603,281,507,000
288,579,451
0
0
null
null
null
null
UTF-8
Lean
false
false
1,062
lean
import data.real.basic open classical attribute [instance] prop_decidable /- Rigorous definition of a limit For a sequence x_n, we say that \lim_{n \to \infty} x_n = l if ∀ ε > 0, ∃ N, n ≥ N → |x_n - l| < ε -/ def lim_to_inf (x : ℕ → ℝ) (l : ℝ) := ∀ ε > 0, ∃ N, ∀ n ≥ N, abs (x n - l) < ε /- Bounded sequences A sequence is bounded if |x_n| \leq B for some constant B and all n -/ -- Lean's mathlib already defines bounded so we rename our -- predicate as bounded' to avoid name clashes def bounded' (x : ℕ → ℝ) := ∃ B, ∀ n, abs (x n) ≤ B theorem exercise_1p13 (x y : ℕ → ℝ) (h₁ : lim_to_inf x 0) (h₂ : bounded' y) : lim_to_inf (λ n, x n * y n) 0 := begin intros ε ε_pos, rcases h₂ with ⟨B, hB⟩, let ε' := ε / ((abs B) + 1), have key : 0 < (abs B) + 1, exact add_pos_of_nonneg_of_pos (abs_nonneg B) zero_lt_one, have ε'_pos : ε' > 0, exact div_pos ε_pos key, rcases h₁ ε' ε'_pos with ⟨N, hN⟩, use N, intros n hn, end
1d0345cb44d57c080d06d177b995563d59de0a4b
f57749ca63d6416f807b770f67559503fdb21001
/hott/hit/torus.hlean
b7ffb43a332dfb8b953afcdca3467acb3205460b
[ "Apache-2.0" ]
permissive
aliassaf/lean
bd54e85bed07b1ff6f01396551867b2677cbc6ac
f9b069b6a50756588b309b3d716c447004203152
refs/heads/master
1,610,982,152,948
1,438,916,029,000
1,438,916,029,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,595
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Declaration of the torus -/ import .two_quotient open two_quotient eq bool unit relation namespace torus definition torus_R (x y : unit) := bool local infix `⬝r`:75 := @e_closure.trans unit torus_R star star star local postfix `⁻¹ʳ`:(max+10) := @e_closure.symm unit torus_R star star local notation `[`:max a `]`:0 := @e_closure.of_rel unit torus_R star star a inductive torus_Q : Π⦃x y : unit⦄, e_closure torus_R x y → e_closure torus_R x y → Type := | Qmk : torus_Q ([ff] ⬝r [tt]) ([tt] ⬝r [ff]) definition torus := two_quotient torus_R torus_Q definition base : torus := incl0 _ _ star definition loop1 : base = base := incl1 _ _ ff definition loop2 : base = base := incl1 _ _ tt definition surf : loop1 ⬝ loop2 = loop2 ⬝ loop1 := incl2 _ _ torus_Q.Qmk -- protected definition rec {P : torus → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb) -- (Pl2 : Pb =[loop2] Pb) (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2) -- (x : torus) : P x := -- sorry -- example {P : torus → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb) (Pl2 : Pb =[loop2] Pb) -- (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2) : torus.rec Pb Pl1 Pl2 Pf base = Pb := idp -- definition rec_loop1 {P : torus → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb) -- (Pl2 : Pb =[loop2] Pb) (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2) -- : apdo (torus.rec Pb Pl1 Pl2 Pf) loop1 = Pl1 := -- sorry -- definition rec_loop2 {P : torus → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb) -- (Pl2 : Pb =[loop2] Pb) (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2) -- : apdo (torus.rec Pb Pl1 Pl2 Pf) loop2 = Pl2 := -- sorry -- definition rec_surf {P : torus → Type} (Pb : P base) (Pl1 : Pb =[loop1] Pb) -- (Pl2 : Pb =[loop2] Pb) (Pf : squareover P fill Pl1 Pl1 Pl2 Pl2) -- : cubeover P rfl1 (apds (torus.rec Pb Pl1 Pl2 Pf) fill) Pf -- (vdeg_squareover !rec_loop2) (vdeg_squareover !rec_loop2) -- (vdeg_squareover !rec_loop1) (vdeg_squareover !rec_loop1) := -- sorry protected definition elim {P : Type} (Pb : P) (Pl1 : Pb = Pb) (Pl2 : Pb = Pb) (Ps : Pl1 ⬝ Pl2 = Pl2 ⬝ Pl1) (x : torus) : P := begin induction x, { exact Pb}, { induction s, { exact Pl1}, { exact Pl2}}, { induction q, exact Ps}, end protected definition elim_on [reducible] {P : Type} (x : torus) (Pb : P) (Pl1 : Pb = Pb) (Pl2 : Pb = Pb) (Ps : Pl1 ⬝ Pl2 = Pl2 ⬝ Pl1) : P := torus.elim Pb Pl1 Pl2 Ps x definition elim_loop1 {P : Type} (Pb : P) (Pl1 : Pb = Pb) (Pl2 : Pb = Pb) (Ps : Pl1 ⬝ Pl2 = Pl2 ⬝ Pl1) : ap (torus.elim Pb Pl1 Pl2 Ps) loop1 = Pl1 := !elim_incl1 definition elim_loop2 {P : Type} (Pb : P) (Pl1 : Pb = Pb) (Pl2 : Pb = Pb) (Ps : Pl1 ⬝ Pl2 = Pl2 ⬝ Pl1) : ap (torus.elim Pb Pl1 Pl2 Ps) loop2 = Pl2 := !elim_incl1 /- TODO(Leo): uncomment after we finish elim_incl2 definition elim_surf {P : Type} (Pb : P) (Pl1 : Pb = Pb) (Pl2 : Pb = Pb) (Ps : Pl1 ⬝ Pl2 = Pl2 ⬝ Pl1) : square (ap02 (torus.elim Pb Pl1 Pl2 Ps) surf) Ps (!ap_con ⬝ (!elim_loop1 ◾ !elim_loop2)) (!ap_con ⬝ (!elim_loop2 ◾ !elim_loop1)) := !elim_incl2 -/ end torus attribute torus.base [constructor] attribute /-torus.rec-/ torus.elim [unfold 6] [recursor 6] --attribute torus.elim_type [unfold 9] attribute /-torus.rec_on-/ torus.elim_on [unfold 2] --attribute torus.elim_type_on [unfold 6]
5da5537c18182626bdb4a7d7cdf4a61db3d0b072
5412d79aa1dc0b521605c38bef9f0d4557b5a29d
/stage0/src/Lean/Server/FileWorker.lean
38308cf35dcd747c4e0988973d8490d08517badb
[ "Apache-2.0" ]
permissive
smunix/lean4
a450ec0927dc1c74816a1bf2818bf8600c9fc9bf
3407202436c141e3243eafbecb4b8720599b970a
refs/heads/master
1,676,334,875,188
1,610,128,510,000
1,610,128,521,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,177
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Init.System.IO import Std.Data.RBMap import Lean.Environment import Lean.PrettyPrinter import Lean.Data.Lsp import Lean.Data.Json.FromToJson import Lean.Server.Snapshots import Lean.Server.Utils import Lean.Server.AsyncList /-! For general server architecture, see `README.md`. For details of IPC communication, see `Watchdog.lean`. This module implements per-file worker processes. File processing and requests+notifications against a file should be concurrent for two reasons: - By the LSP standard, requests should be cancellable. - Since Lean allows arbitrary user code to be executed during elaboration via the tactic framework, elaboration can be extremely slow and even not halt in some cases. Users should be able to work with the file while this is happening, e.g. make new changes to the file or send requests. To achieve these goals, elaboration is executed in a chain of tasks, where each task corresponds to the elaboration of one command. When the elaboration of one command is done, the next task is spawned. On didChange notifications, we search for the task in which the change occured. If we stumble across a task that has not yet finished before finding the task we're looking for, we terminate it and start the elaboration there, otherwise we start the elaboration at the task where the change occured. Requests iterate over tasks until they find the command that they need to answer the request. In order to not block the main thread, this is done in a request task. If a task that the request task waits for is terminated, a change occured somewhere before the command that the request is looking for and the request sends a "content changed" error. -/ namespace Lean.Server.FileWorker open Lsp open IO open Snapshots open Lean.Parser.Command section Utils private def logSnapContent (s : Snapshot) (text : FileMap) : IO Unit := IO.eprintln s!"[{s.beginPos}, {s.endPos}]: `{text.source.extract s.beginPos (s.endPos-1)}`" inductive TaskError where | aborted | eof | ioError (e : IO.Error) instance : Coe IO.Error TaskError := ⟨TaskError.ioError⟩ structure CancelToken where ref : IO.Ref Bool deriving Inhabited namespace CancelToken def new : IO CancelToken := CancelToken.mk <$> IO.mkRef false def check [MonadExceptOf TaskError m] [MonadLiftT (ST RealWorld) m] [Monad m] (tk : CancelToken) : m Unit := do let c ← tk.ref.get if c = true then throw TaskError.aborted def set (tk : CancelToken) : IO Unit := tk.ref.set true end CancelToken /-- A document editable in the sense that we track the environment and parser state after each command so that edits can be applied without recompiling code appearing earlier in the file. -/ structure EditableDocument where meta : DocumentMeta /- The first snapshot is that after the header. -/ headerSnap : Snapshot /- Subsequent snapshots occur after each command. -/ cmdSnaps : AsyncList TaskError Snapshot cancelTk : CancelToken deriving Inhabited end Utils open IO open Std (RBMap RBMap.empty) open JsonRpc section ServerM -- Pending requests are tracked so that requests can be cancelled by cancelling the corresponding task, -- which would be cancelled by the GC if we did not track these requests. abbrev PendingRequestMap := RBMap RequestID (Task (Except IO.Error Unit)) (fun a b => Decidable.decide (a < b)) structure ServerContext where hIn : FS.Stream hOut : FS.Stream docRef : IO.Ref EditableDocument pendingRequestsRef : IO.Ref PendingRequestMap abbrev ServerM := ReaderT ServerContext IO def updatePendingRequests (map : PendingRequestMap → PendingRequestMap) : ServerM Unit := do (←read).pendingRequestsRef.modify map /-- Elaborates the next command after `parentSnap` and emits diagnostics. -/ private def nextCmdSnap (m : DocumentMeta) (parentSnap : Snapshot) (cancelTk : CancelToken) : ExceptT TaskError ServerM Snapshot := do cancelTk.check let st ← read let maybeSnap ← compileNextCmd m.text.source parentSnap cancelTk.check let sendDiagnostics (msgLog : MessageLog) : IO Unit := do let diagnostics ← msgLog.msgs.mapM (msgToDiagnostic m.text) st.hOut.writeLspNotification { method := "textDocument/publishDiagnostics" param := { uri := m.uri version? := m.version diagnostics := diagnostics.toArray : PublishDiagnosticsParams } } match maybeSnap with | Sum.inl snap => /- NOTE(MH): This relies on the client discarding old diagnostics upon receiving new ones while prefering newer versions over old ones. The former is necessary because we do not explicitly clear older diagnostics, while the latter is necessary because we do not guarantee that diagnostics are emitted in order. Specifically, it may happen that we interrupted this elaboration task right at this point and a newer elaboration task emits diagnostics, after which we emit old diagnostics because we did not yet detect the interrupt. Explicitly clearing diagnostics is difficult for a similar reason, because we cannot guarantee that no further diagnostics are emitted after clearing them. -/ sendDiagnostics <| snap.msgLog.add { fileName := "<ignored>" pos := m.text.toPosition snap.endPos severity := MessageSeverity.information data := "processing..." } snap | Sum.inr msgLog => sendDiagnostics msgLog throw TaskError.eof /-- Elaborates all commands after `initSnap`, emitting the diagnostics. -/ def unfoldCmdSnaps (m : DocumentMeta) (initSnap : Snapshot) (cancelTk : CancelToken) : ServerM (AsyncList TaskError Snapshot) := do -- TODO(MH): check for interrupt with increased precision AsyncList.unfoldAsync (nextCmdSnap m . cancelTk (←read)) initSnap (some fun _ => pure TaskError.aborted) /-- Compiles the contents of a Lean file. -/ def compileDocument (m : DocumentMeta) : ServerM Unit := do let headerSnap@⟨_, _, _, SnapshotData.headerData env msgLog opts⟩ ← Snapshots.compileHeader m.text.source | throwServerError "Internal server error: invalid header snapshot" let cancelTk ← CancelToken.new let cmdSnaps ← unfoldCmdSnaps m headerSnap cancelTk (←read).docRef.set ⟨m, headerSnap, cmdSnaps, cancelTk⟩ /-- Given the new document and `changePos`, the UTF-8 offset of a change into the pre-change source, updates editable doc state. -/ def updateDocument (newMeta : DocumentMeta) (changePos : String.Pos) : ServerM Unit := do -- The watchdog only restarts the file worker when the syntax tree of the header changes. -- If e.g. a newline is deleted, it will not restart this file worker, but we still -- need to reparse the header so that the offsets are correct. let st ← read let oldDoc ← st.docRef.get let newHeaderSnap ← reparseHeader newMeta.text.source oldDoc.headerSnap if newHeaderSnap.stx != oldDoc.headerSnap.stx then throwServerError "Internal server error: header changed but worker wasn't restarted." let ⟨cmdSnaps, e?⟩ ← oldDoc.cmdSnaps.updateFinishedPrefix match e? with -- This case should not be possible. only the main task aborts tasks and ensures that aborted tasks -- do not show up in `snapshots` of an EditableDocument. | some TaskError.aborted => throwServerError "Internal server error: elab task was aborted while still in use." | some (TaskError.ioError ioError) => throw ioError | _ => -- No error or EOF oldDoc.cancelTk.set -- NOTE(WN): we invalidate eagerly as `endPos` consumes input greedily. To re-elaborate only -- when really necessary, we could do a whitespace-aware `Syntax` comparison instead. let mut validSnaps := cmdSnaps.finishedPrefix.takeWhile (fun s => s.endPos < changePos) if validSnaps.length = 0 then let cancelTk ← CancelToken.new let newCmdSnaps ← unfoldCmdSnaps newMeta newHeaderSnap cancelTk st.docRef.set ⟨newMeta, newHeaderSnap, newCmdSnaps, cancelTk⟩ else /- When at least one valid non-header snap exists, it may happen that a change does not fall within the syntactic range of that last snap but still modifies it by appending tokens. We check for this here. We do not currently handle crazy grammars in which an appended token can merge two or more previous commands into one. To do so would require reparsing the entire file. -/ let mut lastSnap := validSnaps.getLast! let preLastSnap := if validSnaps.length ≥ 2 then validSnaps.get! (validSnaps.length - 2) else newHeaderSnap let newLastStx ← parseNextCmd newMeta.text.source preLastSnap if newLastStx != lastSnap.stx then validSnaps ← validSnaps.dropLast lastSnap ← preLastSnap let cancelTk ← CancelToken.new let newSnaps ← unfoldCmdSnaps newMeta lastSnap cancelTk let newCmdSnaps := AsyncList.ofList validSnaps ++ newSnaps st.docRef.set ⟨newMeta, newHeaderSnap, newCmdSnaps, cancelTk⟩ end ServerM /- Notifications are handled in the main thread. They may change global worker state such as the current file contents. -/ section NotificationHandling def handleDidOpen (p : DidOpenTextDocumentParams) : ServerM Unit := let doc := p.textDocument /- NOTE(WN): `toFileMap` marks line beginnings as immediately following "\n", which should be enough to handle both LF and CRLF correctly. This is because LSP always refers to characters by (line, column), so if we get the line number correct it shouldn't matter that there is a CR there. -/ compileDocument ⟨doc.uri, doc.version, doc.text.toFileMap⟩ def handleDidChange (p : DidChangeTextDocumentParams) : ServerM Unit := do let docId := p.textDocument let changes := p.contentChanges let oldDoc ← (←read).docRef.get let some newVersion ← pure docId.version? | throwServerError "Expected version number" if newVersion ≤ oldDoc.meta.version then -- TODO(WN): This happens on restart sometimes. IO.eprintln s!"Got outdated version number: {newVersion} ≤ {oldDoc.meta.version}" else if ¬ changes.isEmpty then let (newDocText, minStartOff) := foldDocumentChanges changes oldDoc.meta.text updateDocument ⟨docId.uri, newVersion, newDocText⟩ minStartOff -- TODO(WN): cancel pending requests? def handleCancelRequest (p : CancelParams) : ServerM Unit := do updatePendingRequests (fun pendingRequests => pendingRequests.erase p.id) end NotificationHandling /- Request handlers are given by `Task`s executed asynchronously. They may be cancelled at any time, so they should check the cancellation token when possible to handle this cooperatively. Any exceptions thrown in a handler will be reported to the client as LSP error responses. -/ section RequestHandling structure RequestError where code : ErrorCode message : String -- TODO(WN): the type is too complicated abbrev RequestM α := ServerM $ Task $ Except IO.Error $ Except RequestError α /- Requests that need data from a certain command should traverse the snapshots by successively getting the next task, meaning that we might need to wait for elaboration. When that happens, the request should send a "content changed" error to the user (this way, the server doesn't get bogged down in requests for an old state of the document). Requests need to manually check for whether their task has been cancelled, so that they can reply with a RequestCancelled error. -/ partial def handleHover (id : RequestID) (p : HoverParams) : ServerM (Task (Except IO.Error (Except RequestError (Option Hover)))) := do let doc ← (←read).docRef.get let text := doc.meta.text let hoverPos := text.lspPosToUtf8Pos p.position let findTask ← doc.cmdSnaps.waitFind? (fun s => s.endPos > hoverPos) (IO.mapTask · findTask) fun | Except.error TaskError.aborted => pure $ Except.error { code := ErrorCode.contentModified, message := "File changed." } | Except.error (TaskError.ioError e) => throwThe IO.Error e | Except.error TaskError.eof => pure $ Except.ok none | Except.ok snap? => do let snap? := snap?.filter (fun s => s.beginPos ≤ hoverPos) if let some snap := snap? then if snap.stx.getKind == ``Lean.Parser.Command.declaration then -- TODO(WN): 1. get at the right subexpression -- 2. reply with delaborated type return Except.ok $ some { contents := { kind := MarkupKind.plaintext value := s!"Declaration." } range? := some { start := text.utf8PosToLspPos snap.beginPos «end» := text.utf8PosToLspPos snap.endPos } } return Except.ok none def handleWaitForDiagnostics (id : RequestID) (p : WaitForDiagnosticsParam) : ServerM (Task (Except IO.Error (Except RequestError WaitForDiagnostics))) := do let st ← read let e ← st.docRef.get let t ← e.cmdSnaps.waitAll t.map fun _ => Except.ok $ Except.ok WaitForDiagnostics.mk def rangeOfSyntax (text : FileMap) (stx : Syntax) : Range := ⟨text.utf8PosToLspPos <| stx.getHeadInfo.get!.pos.get!, text.utf8PosToLspPos <| stx.getTailPos.get!⟩ partial def handleDocumentSymbol (id : RequestID) (p : DocumentSymbolParams) : ServerM (Task (Except IO.Error (Except RequestError DocumentSymbolResult))) := do let st ← read asTask do let doc ← st.docRef.get let ⟨cmdSnaps, end?⟩ ← doc.cmdSnaps.updateFinishedPrefix let mut stxs := cmdSnaps.finishedPrefix.map (·.stx) if end?.isNone then if let some lastSnap := cmdSnaps.finishedPrefix.getLast? then stxs := stxs ++ (← parseAhead doc.meta.text.source lastSnap).toList let (syms, _) := toDocumentSymbols doc.meta.text stxs return Except.ok { syms := syms.toArray } where toDocumentSymbols (text : FileMap) | [] => ([], []) | stx::stxs => match stx with | `(namespace $id) => sectionLikeToDocumentSymbols text stx stxs (id.getId.toString) SymbolKind.namespace id | `(section $(id)?) => sectionLikeToDocumentSymbols text stx stxs ((·.getId.toString) <$> id |>.getD "<section>") SymbolKind.namespace (id.getD stx) | `(end $(id)?) => ([], stx::stxs) | _ => let (syms, stxs') := toDocumentSymbols text stxs if stx.isOfKind ``Lean.Parser.Command.declaration then let (name, selection) := match stx with | `($dm:declModifiers $ak:attrKind instance $[$np:namedPrio]? $[$id:ident$[.{$ls,*}]?]? $sig:declSig $val) => ((·.getId.toString) <$> id |>.getD s!"instance {sig.reprint.getD ""}", id.getD sig) | _ => match stx[1][1] with | `(declId|$id:ident$[.{$ls,*}]?) => (id.getId.toString, id) | _ => (stx[1][0].isIdOrAtom?.getD "<unknown>", stx[1][0]) (DocumentSymbol.mk { name := name kind := SymbolKind.method range := rangeOfSyntax text stx selectionRange := rangeOfSyntax text selection } :: syms, stxs') else (syms, stxs') sectionLikeToDocumentSymbols (text : FileMap) (stx : Syntax) (stxs : List Syntax) (name : String) (kind : SymbolKind) (selection : Syntax) := let (syms, stxs') := toDocumentSymbols text stxs -- discard `end` let (syms', stxs'') := toDocumentSymbols text (stxs'.drop 1) let endStx := match stxs' with | endStx::_ => endStx | [] => (stx::stxs').getLast! (DocumentSymbol.mk { name := name kind := kind range := ⟨(rangeOfSyntax text stx).start, (rangeOfSyntax text endStx).«end»⟩ selectionRange := rangeOfSyntax text selection children? := syms.toArray } :: syms', stxs'') end RequestHandling section MessageHandling def parseParams (paramType : Type) [FromJson paramType] (params : Json) : ServerM paramType := match fromJson? params with | some parsed => pure parsed | none => throwServerError s!"Got param with wrong structure: {params.compress}" def handleNotification (method : String) (params : Json) : ServerM Unit := do let handle := fun paramType [FromJson paramType] (handler : paramType → ServerM Unit) => parseParams paramType params >>= handler match method with | "textDocument/didChange" => handle DidChangeTextDocumentParams handleDidChange | "$/cancelRequest" => handle CancelParams handleCancelRequest | _ => throwServerError s!"Got unsupported notification method: {method}" def queueRequest (id : RequestID) (requestTask : Task (Except IO.Error Unit)) : ServerM Unit := do updatePendingRequests (fun pendingRequests => pendingRequests.insert id requestTask) def handleRequest (id : RequestID) (method : String) (params : Json) : ServerM Unit := do let handle := fun paramType [FromJson paramType] respType [ToJson respType] (handler : RequestID → paramType → RequestM respType) => do let st ← read let p ← parseParams paramType params let t ← handler id p let t₁ ← (IO.mapTask · t) fun | Except.ok (Except.ok resp) => st.hOut.writeLspResponse ⟨id, resp⟩ | Except.ok (Except.error e) => st.hOut.writeLspResponseError { id := id, code := e.code, message := e.message } | Except.error e => st.hOut.writeLspResponseError { id := id, code := ErrorCode.internalError, message := toString e } queueRequest id t₁ match method with | "textDocument/waitForDiagnostics" => handle WaitForDiagnosticsParam WaitForDiagnostics handleWaitForDiagnostics | "textDocument/hover" => handle HoverParams (Option Hover) handleHover | "textDocument/documentSymbol" => handle DocumentSymbolParams DocumentSymbolResult handleDocumentSymbol | _ => throwServerError s!"Got unsupported request: {method}" end MessageHandling section MainLoop partial def mainLoop : ServerM Unit := do let st ← read let msg ← st.hIn.readLspMessage let pendingRequests ← st.pendingRequestsRef.get let filterFinishedTasks (acc : PendingRequestMap) (id : RequestID) (task : Task (Except IO.Error Unit)) : ServerM PendingRequestMap := do if (←hasFinished task) then /- Handler tasks are constructed so that the only possible errors here are failures of writing a response into the stream. -/ if let Except.error e := task.get then throwServerError s!"Failed responding to request {id}: {e}" acc.erase id else acc let pendingRequests ← pendingRequests.foldM filterFinishedTasks pendingRequests st.pendingRequestsRef.set pendingRequests match msg with | Message.request id method (some params) => handleRequest id method (toJson params) mainLoop | Message.notification "exit" none => -- should be sufficient to shut down the file worker. -- references are lost => tasks are marked as cancelled -- => all tasks eventually quit () | Message.notification method (some params) => handleNotification method (toJson params) mainLoop | _ => throwServerError "Got invalid JSON-RPC message" end MainLoop def initAndRunWorker (i o e : FS.Stream) : IO Unit := do let i ← maybeTee "fwIn.txt" false i let o ← maybeTee "fwOut.txt" true o -- TODO(WN): act in accordance with InitializeParams let _ ← i.readLspRequestAs "initialize" InitializeParams let ⟨_, param⟩ ← i.readLspNotificationAs "textDocument/didOpen" DidOpenTextDocumentParams let e ← e.withPrefix s!"[{param.textDocument.uri}] " let _ ← IO.setStderr e let ctx : ServerContext := { hIn := i hOut := o -- `openDocument` will not access `docRef`, but set it docRef := ←IO.mkRef arbitrary pendingRequestsRef := ←IO.mkRef (RBMap.empty : PendingRequestMap) } ReaderT.run (do handleDidOpen param; mainLoop) ctx @[export lean_server_worker_main] def workerMain : IO UInt32 := do let i ← IO.getStdin let o ← IO.getStdout let e ← IO.getStderr try initAndRunWorker i o e return 0 catch err => e.putStrLn s!"Worker error: {err}" return 1 end Lean.Server.FileWorker
f3f53638649e67f8edb28b1ada402b9203edfde0
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/src/Lean/Compiler/IR/Basic.lean
542d52bbc7b5032003aefa8647b2141f32337ecb
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
26,209
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.KVMap import Lean.Data.Name import Lean.Data.Format import Lean.Compiler.ExternAttr /- Implements (extended) λPure and λRc proposed in the article "Counting Immutable Beans", Sebastian Ullrich and Leonardo de Moura. The Lean to IR transformation produces λPure code, and this part is implemented in C++. The procedures described in the paper above are implemented in Lean. -/ namespace Lean.IR /- Function identifier -/ abbrev FunId := Name abbrev Index := Nat /- Variable identifier -/ structure VarId where idx : Index deriving Inhabited /- Join point identifier -/ structure JoinPointId where idx : Index deriving Inhabited abbrev Index.lt (a b : Index) : Bool := a < b instance : BEq VarId := ⟨fun a b => a.idx == b.idx⟩ instance : ToString VarId := ⟨fun a => "x_" ++ toString a.idx⟩ instance : ToFormat VarId := ⟨fun a => toString a⟩ instance : Hashable VarId := ⟨fun a => hash a.idx⟩ instance : BEq JoinPointId := ⟨fun a b => a.idx == b.idx⟩ instance : ToString JoinPointId := ⟨fun a => "block_" ++ toString a.idx⟩ instance : ToFormat JoinPointId := ⟨fun a => toString a⟩ instance : Hashable JoinPointId := ⟨fun a => hash a.idx⟩ abbrev MData := KVMap abbrev MData.empty : MData := {} /- Low Level IR types. Most are self explanatory. - `usize` represents the C++ `size_t` Type. We have it here because it is 32-bit in 32-bit machines, and 64-bit in 64-bit machines, and we want the C++ backend for our Compiler to generate platform independent code. - `irrelevant` for Lean types, propositions and proofs. - `object` a pointer to a value in the heap. - `tobject` a pointer to a value in the heap or tagged pointer (i.e., the least significant bit is 1) storing a scalar value. - `struct` and `union` are used to return small values (e.g., `Option`, `Prod`, `Except`) on the stack. Remark: the RC operations for `tobject` are slightly more expensive because we first need to test whether the `tobject` is really a pointer or not. Remark: the Lean runtime assumes that sizeof(void*) == sizeof(sizeT). Lean cannot be compiled on old platforms where this is not True. Since values of type `struct` and `union` are only used to return values, We assume they must be used/consumed "linearly". We use the term "linear" here to mean "exactly once" in each execution. That is, given `x : S`, where `S` is a struct, then one of the following must hold in each (execution) branch. 1- `x` occurs only at a single `ret x` instruction. That is, it is being consumed by being returned. 2- `x` occurs only at a single `ctor`. That is, it is being "consumed" by being stored into another `struct/union`. 3- We extract (aka project) every single field of `x` exactly once. That is, we are consuming `x` by consuming each of one of its components. Minor refinement: we don't need to consume scalar fields or struct/union fields that do not contain object fields. -/ inductive IRType where | float | uint8 | uint16 | uint32 | uint64 | usize | irrelevant | object | tobject | struct (leanTypeName : Option Name) (types : Array IRType) : IRType | union (leanTypeName : Name) (types : Array IRType) : IRType deriving Inhabited namespace IRType partial def beq : IRType → IRType → Bool | float, float => true | uint8, uint8 => true | uint16, uint16 => true | uint32, uint32 => true | uint64, uint64 => true | usize, usize => true | irrelevant, irrelevant => true | object, object => true | tobject, tobject => true | struct n₁ tys₁, struct n₂ tys₂ => n₁ == n₂ && Array.isEqv tys₁ tys₂ beq | union n₁ tys₁, union n₂ tys₂ => n₁ == n₂ && Array.isEqv tys₁ tys₂ beq | _, _ => false instance : BEq IRType := ⟨beq⟩ def isScalar : IRType → Bool | float => true | uint8 => true | uint16 => true | uint32 => true | uint64 => true | usize => true | _ => false def isObj : IRType → Bool | object => true | tobject => true | _ => false def isIrrelevant : IRType → Bool | irrelevant => true | _ => false def isStruct : IRType → Bool | struct _ _ => true | _ => false def isUnion : IRType → Bool | union _ _ => true | _ => false end IRType /- Arguments to applications, constructors, etc. We use `irrelevant` for Lean types, propositions and proofs that have been erased. Recall that for a Function `f`, we also generate `f._rarg` which does not take `irrelevant` arguments. However, `f._rarg` is only safe to be used in full applications. -/ inductive Arg where | var (id : VarId) | irrelevant deriving Inhabited protected def Arg.beq : Arg → Arg → Bool | var x, var y => x == y | irrelevant, irrelevant => true | _, _ => false instance : BEq Arg := ⟨Arg.beq⟩ @[export lean_ir_mk_var_arg] def mkVarArg (id : VarId) : Arg := Arg.var id inductive LitVal where | num (v : Nat) | str (v : String) def LitVal.beq : LitVal → LitVal → Bool | num v₁, num v₂ => v₁ == v₂ | str v₁, str v₂ => v₁ == v₂ | _, _ => false instance : BEq LitVal := ⟨LitVal.beq⟩ /- Constructor information. - `name` is the Name of the Constructor in Lean. - `cidx` is the Constructor index (aka tag). - `size` is the number of arguments of type `object/tobject`. - `usize` is the number of arguments of type `usize`. - `ssize` is the number of bytes used to store scalar values. Recall that a Constructor object contains a header, then a sequence of pointers to other Lean objects, a sequence of `USize` (i.e., `size_t`) scalar values, and a sequence of other scalar values. -/ structure CtorInfo where name : Name cidx : Nat size : Nat usize : Nat ssize : Nat def CtorInfo.beq : CtorInfo → CtorInfo → Bool | ⟨n₁, cidx₁, size₁, usize₁, ssize₁⟩, ⟨n₂, cidx₂, size₂, usize₂, ssize₂⟩ => n₁ == n₂ && cidx₁ == cidx₂ && size₁ == size₂ && usize₁ == usize₂ && ssize₁ == ssize₂ instance : BEq CtorInfo := ⟨CtorInfo.beq⟩ def CtorInfo.isRef (info : CtorInfo) : Bool := info.size > 0 || info.usize > 0 || info.ssize > 0 def CtorInfo.isScalar (info : CtorInfo) : Bool := !info.isRef inductive Expr where /- We use `ctor` mainly for constructing Lean object/tobject values `lean_ctor_object` in the runtime. This instruction is also used to creat `struct` and `union` return values. For `union`, only `i.cidx` is relevant. For `struct`, `i` is irrelevant. -/ | ctor (i : CtorInfo) (ys : Array Arg) | reset (n : Nat) (x : VarId) /- `reuse x in ctor_i ys` instruction in the paper. -/ | reuse (x : VarId) (i : CtorInfo) (updtHeader : Bool) (ys : Array Arg) /- Extract the `tobject` value at Position `sizeof(void*)*i` from `x`. We also use `proj` for extracting fields from `struct` return values, and casting `union` return values. -/ | proj (i : Nat) (x : VarId) /- Extract the `Usize` value at Position `sizeof(void*)*i` from `x`. -/ | uproj (i : Nat) (x : VarId) /- Extract the scalar value at Position `sizeof(void*)*n + offset` from `x`. -/ | sproj (n : Nat) (offset : Nat) (x : VarId) /- Full application. -/ | fap (c : FunId) (ys : Array Arg) /- Partial application that creates a `pap` value (aka closure in our nonstandard terminology). -/ | pap (c : FunId) (ys : Array Arg) /- Application. `x` must be a `pap` value. -/ | ap (x : VarId) (ys : Array Arg) /- Given `x : ty` where `ty` is a scalar type, this operation returns a value of Type `tobject`. For small scalar values, the Result is a tagged pointer, and no memory allocation is performed. -/ | box (ty : IRType) (x : VarId) /- Given `x : [t]object`, obtain the scalar value. -/ | unbox (x : VarId) | lit (v : LitVal) /- Return `1 : uint8` Iff `RC(x) > 1` -/ | isShared (x : VarId) /- Return `1 : uint8` Iff `x : tobject` is a tagged pointer (storing a scalar value). -/ | isTaggedPtr (x : VarId) @[export lean_ir_mk_ctor_expr] def mkCtorExpr (n : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) (ys : Array Arg) : Expr := Expr.ctor ⟨n, cidx, size, usize, ssize⟩ ys @[export lean_ir_mk_proj_expr] def mkProjExpr (i : Nat) (x : VarId) : Expr := Expr.proj i x @[export lean_ir_mk_uproj_expr] def mkUProjExpr (i : Nat) (x : VarId) : Expr := Expr.uproj i x @[export lean_ir_mk_sproj_expr] def mkSProjExpr (n : Nat) (offset : Nat) (x : VarId) : Expr := Expr.sproj n offset x @[export lean_ir_mk_fapp_expr] def mkFAppExpr (c : FunId) (ys : Array Arg) : Expr := Expr.fap c ys @[export lean_ir_mk_papp_expr] def mkPAppExpr (c : FunId) (ys : Array Arg) : Expr := Expr.pap c ys @[export lean_ir_mk_app_expr] def mkAppExpr (x : VarId) (ys : Array Arg) : Expr := Expr.ap x ys @[export lean_ir_mk_num_expr] def mkNumExpr (v : Nat) : Expr := Expr.lit (LitVal.num v) @[export lean_ir_mk_str_expr] def mkStrExpr (v : String) : Expr := Expr.lit (LitVal.str v) structure Param where x : VarId borrow : Bool ty : IRType deriving Inhabited @[export lean_ir_mk_param] def mkParam (x : VarId) (borrow : Bool) (ty : IRType) : Param := ⟨x, borrow, ty⟩ inductive AltCore (FnBody : Type) : Type where | ctor (info : CtorInfo) (b : FnBody) : AltCore FnBody | default (b : FnBody) : AltCore FnBody inductive FnBody where /- `let x : ty := e; b` -/ | vdecl (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) /- Join point Declaration `block_j (xs) := e; b` -/ | jdecl (j : JoinPointId) (xs : Array Param) (v : FnBody) (b : FnBody) /- Store `y` at Position `sizeof(void*)*i` in `x`. `x` must be a Constructor object and `RC(x)` must be 1. This operation is not part of λPure is only used during optimization. -/ | set (x : VarId) (i : Nat) (y : Arg) (b : FnBody) | setTag (x : VarId) (cidx : Nat) (b : FnBody) /- Store `y : Usize` at Position `sizeof(void*)*i` in `x`. `x` must be a Constructor object and `RC(x)` must be 1. -/ | uset (x : VarId) (i : Nat) (y : VarId) (b : FnBody) /- Store `y : ty` at Position `sizeof(void*)*i + offset` in `x`. `x` must be a Constructor object and `RC(x)` must be 1. `ty` must not be `object`, `tobject`, `irrelevant` nor `Usize`. -/ | sset (x : VarId) (i : Nat) (offset : Nat) (y : VarId) (ty : IRType) (b : FnBody) /- RC increment for `object`. If c == `true`, then `inc` must check whether `x` is a tagged pointer or not. If `persistent == true` then `x` is statically known to be a persistent object. -/ | inc (x : VarId) (n : Nat) (c : Bool) (persistent : Bool) (b : FnBody) /- RC decrement for `object`. If c == `true`, then `inc` must check whether `x` is a tagged pointer or not. If `persistent == true` then `x` is statically known to be a persistent object. -/ | dec (x : VarId) (n : Nat) (c : Bool) (persistent : Bool) (b : FnBody) | del (x : VarId) (b : FnBody) | mdata (d : MData) (b : FnBody) | case (tid : Name) (x : VarId) (xType : IRType) (cs : Array (AltCore FnBody)) | ret (x : Arg) /- Jump to join point `j` -/ | jmp (j : JoinPointId) (ys : Array Arg) | unreachable instance : Inhabited FnBody := ⟨FnBody.unreachable⟩ abbrev FnBody.nil := FnBody.unreachable @[export lean_ir_mk_vdecl] def mkVDecl (x : VarId) (ty : IRType) (e : Expr) (b : FnBody) : FnBody := FnBody.vdecl x ty e b @[export lean_ir_mk_jdecl] def mkJDecl (j : JoinPointId) (xs : Array Param) (v : FnBody) (b : FnBody) : FnBody := FnBody.jdecl j xs v b @[export lean_ir_mk_uset] def mkUSet (x : VarId) (i : Nat) (y : VarId) (b : FnBody) : FnBody := FnBody.uset x i y b @[export lean_ir_mk_sset] def mkSSet (x : VarId) (i : Nat) (offset : Nat) (y : VarId) (ty : IRType) (b : FnBody) : FnBody := FnBody.sset x i offset y ty b @[export lean_ir_mk_case] def mkCase (tid : Name) (x : VarId) (cs : Array (AltCore FnBody)) : FnBody := -- Type field `xType` is set by `explicitBoxing` compiler pass. FnBody.case tid x IRType.object cs @[export lean_ir_mk_ret] def mkRet (x : Arg) : FnBody := FnBody.ret x @[export lean_ir_mk_jmp] def mkJmp (j : JoinPointId) (ys : Array Arg) : FnBody := FnBody.jmp j ys @[export lean_ir_mk_unreachable] def mkUnreachable : Unit → FnBody := fun _ => FnBody.unreachable abbrev Alt := AltCore FnBody @[matchPattern] abbrev Alt.ctor := @AltCore.ctor FnBody @[matchPattern] abbrev Alt.default := @AltCore.default FnBody instance : Inhabited Alt := ⟨Alt.default arbitrary⟩ def FnBody.isTerminal : FnBody → Bool | FnBody.case _ _ _ _ => true | FnBody.ret _ => true | FnBody.jmp _ _ => true | FnBody.unreachable => true | _ => false def FnBody.body : FnBody → FnBody | FnBody.vdecl _ _ _ b => b | FnBody.jdecl _ _ _ b => b | FnBody.set _ _ _ b => b | FnBody.uset _ _ _ b => b | FnBody.sset _ _ _ _ _ b => b | FnBody.setTag _ _ b => b | FnBody.inc _ _ _ _ b => b | FnBody.dec _ _ _ _ b => b | FnBody.del _ b => b | FnBody.mdata _ b => b | other => other def FnBody.setBody : FnBody → FnBody → FnBody | FnBody.vdecl x t v _, b => FnBody.vdecl x t v b | FnBody.jdecl j xs v _, b => FnBody.jdecl j xs v b | FnBody.set x i y _, b => FnBody.set x i y b | FnBody.uset x i y _, b => FnBody.uset x i y b | FnBody.sset x i o y t _, b => FnBody.sset x i o y t b | FnBody.setTag x i _, b => FnBody.setTag x i b | FnBody.inc x n c p _, b => FnBody.inc x n c p b | FnBody.dec x n c p _, b => FnBody.dec x n c p b | FnBody.del x _, b => FnBody.del x b | FnBody.mdata d _, b => FnBody.mdata d b | other, b => other @[inline] def FnBody.resetBody (b : FnBody) : FnBody := b.setBody FnBody.nil /- If b is a non terminal, then return a pair `(c, b')` s.t. `b == c <;> b'`, and c.body == FnBody.nil -/ @[inline] def FnBody.split (b : FnBody) : FnBody × FnBody := let b' := b.body let c := b.resetBody (c, b') def AltCore.body : Alt → FnBody | Alt.ctor _ b => b | Alt.default b => b def AltCore.setBody : Alt → FnBody → Alt | Alt.ctor c _, b => Alt.ctor c b | Alt.default _, b => Alt.default b @[inline] def AltCore.modifyBody (f : FnBody → FnBody) : AltCore FnBody → Alt | Alt.ctor c b => Alt.ctor c (f b) | Alt.default b => Alt.default (f b) @[inline] def AltCore.mmodifyBody {m : Type → Type} [Monad m] (f : FnBody → m FnBody) : AltCore FnBody → m Alt | Alt.ctor c b => Alt.ctor c <$> f b | Alt.default b => Alt.default <$> f b def Alt.isDefault : Alt → Bool | Alt.ctor _ _ => false | Alt.default _ => true def push (bs : Array FnBody) (b : FnBody) : Array FnBody := let b := b.resetBody bs.push b partial def flattenAux (b : FnBody) (r : Array FnBody) : (Array FnBody) × FnBody := if b.isTerminal then (r, b) else flattenAux b.body (push r b) def FnBody.flatten (b : FnBody) : (Array FnBody) × FnBody := flattenAux b #[] partial def reshapeAux (a : Array FnBody) (i : Nat) (b : FnBody) : FnBody := if i == 0 then b else let i := i - 1 let (curr, a) := a.swapAt! i arbitrary let b := curr.setBody b reshapeAux a i b def reshape (bs : Array FnBody) (term : FnBody) : FnBody := reshapeAux bs bs.size term @[inline] def modifyJPs (bs : Array FnBody) (f : FnBody → FnBody) : Array FnBody := bs.map fun b => match b with | FnBody.jdecl j xs v k => FnBody.jdecl j xs (f v) k | other => other @[inline] def mmodifyJPs {m : Type → Type} [Monad m] (bs : Array FnBody) (f : FnBody → m FnBody) : m (Array FnBody) := bs.mapM fun b => match b with | FnBody.jdecl j xs v k => do let v ← f v; pure $ FnBody.jdecl j xs v k | other => pure other @[export lean_ir_mk_alt] def mkAlt (n : Name) (cidx : Nat) (size : Nat) (usize : Nat) (ssize : Nat) (b : FnBody) : Alt := Alt.ctor ⟨n, cidx, size, usize, ssize⟩ b /-- Extra information associated with a declaration. -/ structure DeclInfo where /-- If `some <blame>`, then declaration depends on `<blame>` which uses a `sorry` axiom. -/ sorryDep? : Option Name := none inductive Decl where | fdecl (f : FunId) (xs : Array Param) (type : IRType) (body : FnBody) (info : DeclInfo) | extern (f : FunId) (xs : Array Param) (type : IRType) (ext : ExternAttrData) deriving Inhabited namespace Decl def name : Decl → FunId | Decl.fdecl f .. => f | Decl.extern f .. => f def params : Decl → Array Param | Decl.fdecl (xs := xs) .. => xs | Decl.extern (xs := xs) .. => xs def resultType : Decl → IRType | Decl.fdecl (type := t) .. => t | Decl.extern (type := t) .. => t def isExtern : Decl → Bool | Decl.extern .. => true | _ => false def getInfo : Decl → DeclInfo | Decl.fdecl (info := info) .. => info | _ => {} def updateBody! (d : Decl) (bNew : FnBody) : Decl := match d with | Decl.fdecl f xs t b info => Decl.fdecl f xs t bNew info | _ => panic! "expected definition" end Decl @[export lean_ir_mk_decl] def mkDecl (f : FunId) (xs : Array Param) (ty : IRType) (b : FnBody) : Decl := Decl.fdecl f xs ty b {} @[export lean_ir_mk_extern_decl] def mkExternDecl (f : FunId) (xs : Array Param) (ty : IRType) (e : ExternAttrData) : Decl := Decl.extern f xs ty e open Std (RBTree RBTree.empty RBMap) /-- Set of variable and join point names -/ abbrev IndexSet := RBTree Index Index.lt instance : Inhabited IndexSet := ⟨{}⟩ def mkIndexSet (idx : Index) : IndexSet := RBTree.empty.insert idx inductive LocalContextEntry where | param : IRType → LocalContextEntry | localVar : IRType → Expr → LocalContextEntry | joinPoint : Array Param → FnBody → LocalContextEntry abbrev LocalContext := RBMap Index LocalContextEntry Index.lt def LocalContext.addLocal (ctx : LocalContext) (x : VarId) (t : IRType) (v : Expr) : LocalContext := ctx.insert x.idx (LocalContextEntry.localVar t v) def LocalContext.addJP (ctx : LocalContext) (j : JoinPointId) (xs : Array Param) (b : FnBody) : LocalContext := ctx.insert j.idx (LocalContextEntry.joinPoint xs b) def LocalContext.addParam (ctx : LocalContext) (p : Param) : LocalContext := ctx.insert p.x.idx (LocalContextEntry.param p.ty) def LocalContext.addParams (ctx : LocalContext) (ps : Array Param) : LocalContext := ps.foldl LocalContext.addParam ctx def LocalContext.isJP (ctx : LocalContext) (idx : Index) : Bool := match ctx.find? idx with | some (LocalContextEntry.joinPoint _ _) => true | other => false def LocalContext.getJPBody (ctx : LocalContext) (j : JoinPointId) : Option FnBody := match ctx.find? j.idx with | some (LocalContextEntry.joinPoint _ b) => some b | other => none def LocalContext.getJPParams (ctx : LocalContext) (j : JoinPointId) : Option (Array Param) := match ctx.find? j.idx with | some (LocalContextEntry.joinPoint ys _) => some ys | other => none def LocalContext.isParam (ctx : LocalContext) (idx : Index) : Bool := match ctx.find? idx with | some (LocalContextEntry.param _) => true | other => false def LocalContext.isLocalVar (ctx : LocalContext) (idx : Index) : Bool := match ctx.find? idx with | some (LocalContextEntry.localVar _ _) => true | other => false def LocalContext.contains (ctx : LocalContext) (idx : Index) : Bool := Std.RBMap.contains ctx idx def LocalContext.eraseJoinPointDecl (ctx : LocalContext) (j : JoinPointId) : LocalContext := ctx.erase j.idx def LocalContext.getType (ctx : LocalContext) (x : VarId) : Option IRType := match ctx.find? x.idx with | some (LocalContextEntry.param t) => some t | some (LocalContextEntry.localVar t _) => some t | other => none def LocalContext.getValue (ctx : LocalContext) (x : VarId) : Option Expr := match ctx.find? x.idx with | some (LocalContextEntry.localVar _ v) => some v | other => none abbrev IndexRenaming := RBMap Index Index Index.lt class AlphaEqv (α : Type) where aeqv : IndexRenaming → α → α → Bool export AlphaEqv (aeqv) def VarId.alphaEqv (ρ : IndexRenaming) (v₁ v₂ : VarId) : Bool := match ρ.find? v₁.idx with | some v => v == v₂.idx | none => v₁ == v₂ instance : AlphaEqv VarId := ⟨VarId.alphaEqv⟩ def Arg.alphaEqv (ρ : IndexRenaming) : Arg → Arg → Bool | Arg.var v₁, Arg.var v₂ => aeqv ρ v₁ v₂ | Arg.irrelevant, Arg.irrelevant => true | _, _ => false instance : AlphaEqv Arg := ⟨Arg.alphaEqv⟩ def args.alphaEqv (ρ : IndexRenaming) (args₁ args₂ : Array Arg) : Bool := Array.isEqv args₁ args₂ (fun a b => aeqv ρ a b) instance: AlphaEqv (Array Arg) := ⟨args.alphaEqv⟩ def Expr.alphaEqv (ρ : IndexRenaming) : Expr → Expr → Bool | Expr.ctor i₁ ys₁, Expr.ctor i₂ ys₂ => i₁ == i₂ && aeqv ρ ys₁ ys₂ | Expr.reset n₁ x₁, Expr.reset n₂ x₂ => n₁ == n₂ && aeqv ρ x₁ x₂ | Expr.reuse x₁ i₁ u₁ ys₁, Expr.reuse x₂ i₂ u₂ ys₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && u₁ == u₂ && aeqv ρ ys₁ ys₂ | Expr.proj i₁ x₁, Expr.proj i₂ x₂ => i₁ == i₂ && aeqv ρ x₁ x₂ | Expr.uproj i₁ x₁, Expr.uproj i₂ x₂ => i₁ == i₂ && aeqv ρ x₁ x₂ | Expr.sproj n₁ o₁ x₁, Expr.sproj n₂ o₂ x₂ => n₁ == n₂ && o₁ == o₂ && aeqv ρ x₁ x₂ | Expr.fap c₁ ys₁, Expr.fap c₂ ys₂ => c₁ == c₂ && aeqv ρ ys₁ ys₂ | Expr.pap c₁ ys₁, Expr.pap c₂ ys₂ => c₁ == c₂ && aeqv ρ ys₁ ys₂ | Expr.ap x₁ ys₁, Expr.ap x₂ ys₂ => aeqv ρ x₁ x₂ && aeqv ρ ys₁ ys₂ | Expr.box ty₁ x₁, Expr.box ty₂ x₂ => ty₁ == ty₂ && aeqv ρ x₁ x₂ | Expr.unbox x₁, Expr.unbox x₂ => aeqv ρ x₁ x₂ | Expr.lit v₁, Expr.lit v₂ => v₁ == v₂ | Expr.isShared x₁, Expr.isShared x₂ => aeqv ρ x₁ x₂ | Expr.isTaggedPtr x₁, Expr.isTaggedPtr x₂ => aeqv ρ x₁ x₂ | _, _ => false instance : AlphaEqv Expr:= ⟨Expr.alphaEqv⟩ def addVarRename (ρ : IndexRenaming) (x₁ x₂ : Nat) := if x₁ == x₂ then ρ else ρ.insert x₁ x₂ def addParamRename (ρ : IndexRenaming) (p₁ p₂ : Param) : Option IndexRenaming := if p₁.ty == p₂.ty && p₁.borrow = p₂.borrow then some (addVarRename ρ p₁.x.idx p₂.x.idx) else none def addParamsRename (ρ : IndexRenaming) (ps₁ ps₂ : Array Param) : Option IndexRenaming := OptionM.run do if ps₁.size != ps₂.size then failure else let mut ρ := ρ for i in [:ps₁.size] do ρ ← addParamRename ρ ps₁[i] ps₂[i] pure ρ partial def FnBody.alphaEqv : IndexRenaming → FnBody → FnBody → Bool | ρ, FnBody.vdecl x₁ t₁ v₁ b₁, FnBody.vdecl x₂ t₂ v₂ b₂ => t₁ == t₂ && aeqv ρ v₁ v₂ && alphaEqv (addVarRename ρ x₁.idx x₂.idx) b₁ b₂ | ρ, FnBody.jdecl j₁ ys₁ v₁ b₁, FnBody.jdecl j₂ ys₂ v₂ b₂ => match addParamsRename ρ ys₁ ys₂ with | some ρ' => alphaEqv ρ' v₁ v₂ && alphaEqv (addVarRename ρ j₁.idx j₂.idx) b₁ b₂ | none => false | ρ, FnBody.set x₁ i₁ y₁ b₁, FnBody.set x₂ i₂ y₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && aeqv ρ y₁ y₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.uset x₁ i₁ y₁ b₁, FnBody.uset x₂ i₂ y₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && aeqv ρ y₁ y₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.sset x₁ i₁ o₁ y₁ t₁ b₁, FnBody.sset x₂ i₂ o₂ y₂ t₂ b₂ => aeqv ρ x₁ x₂ && i₁ = i₂ && o₁ = o₂ && aeqv ρ y₁ y₂ && t₁ == t₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.setTag x₁ i₁ b₁, FnBody.setTag x₂ i₂ b₂ => aeqv ρ x₁ x₂ && i₁ == i₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.inc x₁ n₁ c₁ p₁ b₁, FnBody.inc x₂ n₂ c₂ p₂ b₂ => aeqv ρ x₁ x₂ && n₁ == n₂ && c₁ == c₂ && p₁ == p₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.dec x₁ n₁ c₁ p₁ b₁, FnBody.dec x₂ n₂ c₂ p₂ b₂ => aeqv ρ x₁ x₂ && n₁ == n₂ && c₁ == c₂ && p₁ == p₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.del x₁ b₁, FnBody.del x₂ b₂ => aeqv ρ x₁ x₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.mdata m₁ b₁, FnBody.mdata m₂ b₂ => m₁ == m₂ && alphaEqv ρ b₁ b₂ | ρ, FnBody.case n₁ x₁ _ alts₁, FnBody.case n₂ x₂ _ alts₂ => n₁ == n₂ && aeqv ρ x₁ x₂ && Array.isEqv alts₁ alts₂ (fun alt₁ alt₂ => match alt₁, alt₂ with | Alt.ctor i₁ b₁, Alt.ctor i₂ b₂ => i₁ == i₂ && alphaEqv ρ b₁ b₂ | Alt.default b₁, Alt.default b₂ => alphaEqv ρ b₁ b₂ | _, _ => false) | ρ, FnBody.jmp j₁ ys₁, FnBody.jmp j₂ ys₂ => j₁ == j₂ && aeqv ρ ys₁ ys₂ | ρ, FnBody.ret x₁, FnBody.ret x₂ => aeqv ρ x₁ x₂ | _, FnBody.unreachable, FnBody.unreachable => true | _, _, _ => false def FnBody.beq (b₁ b₂ : FnBody) : Bool := FnBody.alphaEqv ∅ b₁ b₂ instance : BEq FnBody := ⟨FnBody.beq⟩ abbrev VarIdSet := RBTree VarId (fun x y => x.idx < y.idx) instance : Inhabited VarIdSet := ⟨{}⟩ def mkIf (x : VarId) (t e : FnBody) : FnBody := FnBody.case `Bool x IRType.uint8 #[ Alt.ctor {name := `Bool.false, cidx := 0, size := 0, usize := 0, ssize := 0} e, Alt.ctor {name := `Bool.true, cidx := 1, size := 0, usize := 0, ssize := 0} t ] end Lean.IR
2fa1fdb6166be441e507cf6579b83be5adc2efc3
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/ring2.lean
d1d203e7b3a2f141ad6f20ae37f972c4796d0bcb
[]
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
10,837
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.tactic.ring import Mathlib.data.num.lemmas import Mathlib.data.tree import Mathlib.PostPort universes u_1 l namespace Mathlib /-! # ring2 An experimental variant on the `ring` tactic that uses computational reflection instead of proof generation. Useful for kernel benchmarking. -/ namespace tree /-- `(reflect' t u α)` quasiquotes a tree `(t: tree expr)` of quoted values of type `α` at level `u` into an `expr` which reifies to a `tree α` containing the reifications of the `expr`s from the original `t`. -/ /-- Returns an element indexed by `n`, or zero if `n` isn't a valid index. See `tree.get`. -/ protected def get_or_zero {α : Type u_1} [HasZero α] (t : tree α) (n : pos_num) : α := get_or_else n t 0 end tree namespace tactic.ring2 /-- A reflected/meta representation of an expression in a commutative semiring. This representation is a direct translation of such expressions - see `horner_expr` for a normal form. -/ /- (atom n) is an opaque element of the csring. For example, inductive csring_expr where | atom : pos_num → csring_expr | const : num → csring_expr | add : csring_expr → csring_expr → csring_expr | mul : csring_expr → csring_expr → csring_expr | pow : csring_expr → num → csring_expr a local variable in the context. n indexes into a storage of such atoms - a `tree α`. -/ /- (const n) is technically the csring's one, added n times. Or the zero if n is 0. -/ namespace csring_expr protected instance inhabited : Inhabited csring_expr := { default := const 0 } /-- Evaluates a reflected `csring_expr` into an element of the original `comm_semiring` type `α`, retrieving opaque elements (atoms) from the tree `t`. -/ def eval {α : Type u_1} [comm_semiring α] (t : tree α) : csring_expr → α := sorry end csring_expr /-- An efficient representation of expressions in a commutative semiring using the sparse Horner normal form. This type admits non-optimal instantiations (e.g. `P` can be represented as `P+0+0`), so to get good performance out of it, care must be taken to maintain an optimal, *canonical* form. -/ /- (const n) is a constant n in the csring, similarly to the same inductive horner_expr where | const : znum → horner_expr | horner : horner_expr → pos_num → num → horner_expr → horner_expr constructor in `csring_expr`. This one, however, can be negative. -/ /- (horner a x n b) is a*xⁿ + b, where x is the x-th atom in the atom tree. -/ namespace horner_expr /-- True iff the `horner_expr` argument is a valid `csring_expr`. For that to be the case, all its constants must be non-negative. -/ def is_cs : horner_expr → Prop := sorry protected instance has_zero : HasZero horner_expr := { zero := const 0 } protected instance has_one : HasOne horner_expr := { one := const 1 } protected instance inhabited : Inhabited horner_expr := { default := 0 } /-- Represent a `csring_expr.atom` in Horner form. -/ def atom (n : pos_num) : horner_expr := horner 1 n 1 0 def to_string : horner_expr → string := sorry protected instance has_to_string : has_to_string horner_expr := has_to_string.mk to_string /-- Alternative constructor for (horner a x n b) which maintains canonical form by simplifying special cases of `a`. -/ def horner' (a : horner_expr) (x : pos_num) (n : num) (b : horner_expr) : horner_expr := sorry def add_const (k : znum) (e : horner_expr) : horner_expr := ite (k = 0) e (horner_expr.rec (fun (n : znum) => const (k + n)) (fun (a : horner_expr) (x : pos_num) (n : num) (b A B : horner_expr) => horner a x n B) e) def add_aux (a₁ : horner_expr) (A₁ : horner_expr → horner_expr) (x₁ : pos_num) : horner_expr → num → horner_expr → (horner_expr → horner_expr) → horner_expr := sorry def add : horner_expr → horner_expr → horner_expr := sorry /-begin induction e₁ with n₁ a₁ x₁ n₁ b₁ A₁ B₁ generalizing e₂, { exact add_const n₁ e₂ }, exact match e₂ with e₂ := begin induction e₂ with n₂ a₂ x₂ n₂ b₂ A₂ B₂ generalizing n₁ b₁; let e₁ := horner a₁ x₁ n₁ b₁, { exact add_const n₂ e₁ }, let e₂ := horner a₂ x₂ n₂ b₂, exact match pos_num.cmp x₁ x₂ with | ordering.lt := horner a₁ x₁ n₁ (B₁ e₂) | ordering.gt := horner a₂ x₂ n₂ (B₂ n₁ b₁) | ordering.eq := match num.sub' n₁ n₂ with | znum.zero := horner' (A₁ a₂) x₁ n₁ (B₁ b₂) | (znum.pos k) := horner (A₂ k 0) x₁ n₂ (B₁ b₂) | (znum.neg k) := horner (A₁ (horner a₂ x₁ k 0)) x₁ n₁ (B₁ b₂) end end end end end-/ def neg (e : horner_expr) : horner_expr := horner_expr.rec (fun (n : znum) => const (-n)) (fun (a : horner_expr) (x : pos_num) (n : num) (b A B : horner_expr) => horner A x n B) e def mul_const (k : znum) (e : horner_expr) : horner_expr := ite (k = 0) 0 (ite (k = 1) e (horner_expr.rec (fun (n : znum) => const (n * k)) (fun (a : horner_expr) (x : pos_num) (n : num) (b A B : horner_expr) => horner A x n B) e)) def mul_aux (a₁ : horner_expr) (x₁ : pos_num) (n₁ : num) (b₁ : horner_expr) (A₁ : horner_expr → horner_expr) (B₁ : horner_expr → horner_expr) : horner_expr → horner_expr := sorry def mul : horner_expr → horner_expr → horner_expr := sorry /-begin induction e₁ with n₁ a₁ x₁ n₁ b₁ A₁ B₁ generalizing e₂, { exact mul_const n₁ e₂ }, induction e₂ with n₂ a₂ x₂ n₂ b₂ A₂ B₂; let e₁ := horner a₁ x₁ n₁ b₁, { exact mul_const n₂ e₁ }, let e₂ := horner a₂ x₂ n₂ b₂, cases pos_num.cmp x₁ x₂, { exact horner (A₁ e₂) x₁ n₁ (B₁ e₂) }, { let haa := horner' A₂ x₁ n₂ 0, exact if b₂ = 0 then haa else haa.add (horner (A₁ b₂) x₁ n₁ (B₁ b₂)) }, { exact horner A₂ x₂ n₂ B₂ } end-/ protected instance has_add : Add horner_expr := { add := add } protected instance has_neg : Neg horner_expr := { neg := neg } protected instance has_mul : Mul horner_expr := { mul := mul } def pow (e : horner_expr) : num → horner_expr := sorry def inv (e : horner_expr) : horner_expr := 0 /-- Brings expressions into Horner normal form. -/ def of_csexpr : csring_expr → horner_expr := sorry /-- Evaluates a reflected `horner_expr` - see `csring_expr.eval`. -/ def cseval {α : Type u_1} [comm_semiring α] (t : tree α) : horner_expr → α := sorry theorem cseval_atom {α : Type u_1} [comm_semiring α] (t : tree α) (n : pos_num) : is_cs (atom n) ∧ cseval t (atom n) = tree.get_or_zero t n := { left := { left := Exists.intro 1 rfl, right := Exists.intro 0 rfl }, right := Eq.symm (ring.horner_atom (tree.get_or_zero t n)) } theorem cseval_add_const {α : Type u_1} [comm_semiring α] (t : tree α) (k : num) {e : horner_expr} (cs : is_cs e) : is_cs (add_const (num.to_znum k) e) ∧ cseval t (add_const (num.to_znum k) e) = ↑k + cseval t e := sorry theorem cseval_horner' {α : Type u_1} [comm_semiring α] (t : tree α) (a : horner_expr) (x : pos_num) (n : num) (b : horner_expr) (h₁ : is_cs a) (h₂ : is_cs b) : is_cs (horner' a x n b) ∧ cseval t (horner' a x n b) = ring.horner (cseval t a) (tree.get_or_zero t x) (↑n) (cseval t b) := sorry theorem cseval_add {α : Type u_1} [comm_semiring α] (t : tree α) {e₁ : horner_expr} {e₂ : horner_expr} (cs₁ : is_cs e₁) (cs₂ : is_cs e₂) : is_cs (add e₁ e₂) ∧ cseval t (add e₁ e₂) = cseval t e₁ + cseval t e₂ := sorry theorem cseval_mul_const {α : Type u_1} [comm_semiring α] (t : tree α) (k : num) {e : horner_expr} (cs : is_cs e) : is_cs (mul_const (num.to_znum k) e) ∧ cseval t (mul_const (num.to_znum k) e) = cseval t e * ↑k := sorry theorem cseval_mul {α : Type u_1} [comm_semiring α] (t : tree α) {e₁ : horner_expr} {e₂ : horner_expr} (cs₁ : is_cs e₁) (cs₂ : is_cs e₂) : is_cs (mul e₁ e₂) ∧ cseval t (mul e₁ e₂) = cseval t e₁ * cseval t e₂ := sorry theorem cseval_pow {α : Type u_1} [comm_semiring α] (t : tree α) {x : horner_expr} (cs : is_cs x) (n : num) : is_cs (pow x n) ∧ cseval t (pow x n) = cseval t x ^ ↑n := sorry /-- For any given tree `t` of atoms and any reflected expression `r`, the Horner form of `r` is a valid csring expression, and under `t`, the Horner form evaluates to the same thing as `r`. -/ theorem cseval_of_csexpr {α : Type u_1} [comm_semiring α] (t : tree α) (r : csring_expr) : is_cs (of_csexpr r) ∧ cseval t (of_csexpr r) = csring_expr.eval t r := sorry end horner_expr /-- The main proof-by-reflection theorem. Given reflected csring expressions `r₁` and `r₂` plus a storage `t` of atoms, if both expressions go to the same Horner normal form, then the original non-reflected expressions are equal. `H` follows from kernel reduction and is therefore `rfl`. -/ theorem correctness {α : Type u_1} [comm_semiring α] (t : tree α) (r₁ : csring_expr) (r₂ : csring_expr) (H : horner_expr.of_csexpr r₁ = horner_expr.of_csexpr r₂) : csring_expr.eval t r₁ = csring_expr.eval t r₂ := sorry /-- Reflects a csring expression into a `csring_expr`, together with a dlist of atoms, i.e. opaque variables over which the expression is a polynomial. -/ /-| `(%%e₁ - %%e₂) := let (r₁, l₁) := reflect_expr e₁, (r₂, l₂) := reflect_expr e₂ in (r₁.add r₂.neg, l₁ ++ l₂) | `(- %%e) := let (r, l) := reflect_expr e in (r.neg, l)-/ /-| `(has_inv.inv %%e) := let (r, l) := reflect_expr e in (r.neg, l) | `(%%e₁ / %%e₂) := let (r₁, l₁) := reflect_expr e₁, (r₂, l₂) := reflect_expr e₂ in (r₁.mul r₂.inv, l₁ ++ l₂)-/ /-- In the output of `reflect_expr`, `atom`s are initialized with incorrect indices. The indices cannot be computed until the whole tree is built, so another pass over the expressions is needed - this is what `replace` does. The computation (expressed in the state monad) fixes up `atom`s to match their positions in the atom tree. The initial state is a list of all atom occurrences in the goal, left-to-right. -/ --| (csring_expr.neg x) := csring_expr.neg <$> x.replace --| (csring_expr.inv x) := csring_expr.inv <$> x.replace end tactic.ring2 namespace tactic namespace interactive /-- `ring2` solves equations in the language of rings. It supports only the commutative semiring operations, i.e. it does not normalize subtraction or division. This variant on the `ring` tactic uses kernel computation instead of proof generation. In general, you should use `ring` instead of `ring2`. -/
bde7459ca2927b81328d4a51b7d6d1b9c18b742c
30b012bb72d640ec30c8fdd4c45fdfa67beb012c
/tactic/explode.lean
ea2c7d11947ea378c447262dd700eb798d1b18fc
[ "Apache-2.0" ]
permissive
kckennylau/mathlib
21fb810b701b10d6606d9002a4004f7672262e83
47b3477e20ffb5a06588dd3abb01fe0fe3205646
refs/heads/master
1,634,976,409,281
1,542,042,832,000
1,542,319,733,000
109,560,458
0
0
Apache-2.0
1,542,369,208,000
1,509,867,494,000
Lean
UTF-8
Lean
false
false
4,804
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Displays a proof term in a line by line format somewhat akin to a Fitch style proof or the Metamath proof style. -/ import tactic.basic open expr tactic namespace tactic namespace explode -- TODO(Mario): move back to list.basic @[simp] def head' {α} : list α → option α | [] := none | (a :: l) := some a inductive status | reg | intro | lam | sintro meta structure entry := (expr : expr) (line : nat) (depth : nat) (status : status) (thm : string) (deps : list nat) meta def pad_right (l : list string) : list string := let n := l.foldl (λ r (s:string), max r s.length) 0 in l.map $ λ s, nat.iterate (λ s, s.push ' ') (n - s.length) s meta structure entries := mk' :: (s : expr_map entry) (l : list entry) meta def entries.find (es : entries) (e : expr) := es.s.find e meta def entries.size (es : entries) := es.s.size meta def entries.add : entries → entry → entries | es@⟨s, l⟩ e := if s.contains e.expr then es else ⟨s.insert e.expr e, e :: l⟩ meta def entries.head (es : entries) : option entry := head' es.l meta instance : inhabited entries := ⟨⟨expr_map.mk _, []⟩⟩ meta def format_aux : list string → list string → list string → list entry → tactic format | (line :: lines) (dep :: deps) (thm :: thms) (en :: es) := do fmt ← do { let margin := string.join (list.repeat " │" en.depth), let margin := match en.status with | status.sintro := " ├" ++ margin | status.intro := " │" ++ margin ++ " ┌" | status.reg := " │" ++ margin ++ "" | status.lam := " │" ++ margin ++ "" end, p ← infer_type en.expr >>= pp, let lhs := line ++ "│" ++ dep ++ "│ " ++ thm ++ margin ++ " ", return $ format.of_string lhs ++ to_string p ++ format.line }, (++ fmt) <$> format_aux lines deps thms es | _ _ _ _ := return format.nil meta instance : has_to_tactic_format entries := ⟨λ es : entries, let lines := pad_right $ es.l.map (λ en, to_string en.line), deps := pad_right $ es.l.map (λ en, string.intercalate "," (en.deps.map to_string)), thms := pad_right $ es.l.map entry.thm in format_aux lines deps thms es.l⟩ meta def append_dep (filter : expr → tactic unit) (es : entries) (e : expr) (deps : list nat) : tactic (list nat) := do { ei ← es.find e, filter ei.expr, return (ei.line :: deps) } <|> return deps end explode open explode meta mutual def explode.core, explode.args (filter : expr → tactic unit) with explode.core : expr → bool → nat → entries → tactic entries | e@(lam n bi d b) si depth es := do m ← mk_fresh_name, let l := local_const m n bi d, let b' := instantiate_var b l, if si then let en : entry := ⟨l, es.size, depth, status.sintro, to_string n, []⟩ in explode.core b' si depth (es.add en) else do let en : entry := ⟨l, es.size, depth, status.intro, to_string n, []⟩, es' ← explode.core b' si (depth + 1) (es.add en), return $ es'.add ⟨e, es'.size, depth, status.lam, "∀I", [es'.size - 1]⟩ | e si depth es := filter e >> match get_app_fn_args e with | (const n _, args) := explode.args e args depth es (to_string n) [] | (fn, []) := do p ← pp fn, let en : entry := ⟨fn, es.size, depth, status.reg, to_string p, []⟩, return (es.add en) | (fn, args) := do es' ← explode.core fn ff depth es, deps ← explode.append_dep filter es' fn [], explode.args e args depth es' "∀E" deps end with explode.args : expr → list expr → nat → entries → string → list nat → tactic entries | e (arg :: args) depth es thm deps := do es' ← explode.core arg ff depth es <|> return es, deps' ← explode.append_dep filter es' arg deps, explode.args e args depth es' thm deps' | e [] depth es thm deps := return (es.add ⟨e, es.size, depth, status.reg, thm, deps.reverse⟩) meta def explode_expr (e : expr) (hide_non_prop := tt) : tactic entries := let filter := if hide_non_prop then λ e, is_proof e >>= guardb else λ _, skip in tactic.explode.core filter e tt 0 (default _) meta def explode (n : name) : tactic unit := do const n _ ← resolve_name n | fail "cannot resolve name", d ← get_decl n, v ← match d with | (declaration.defn _ _ _ v _ _) := return v | (declaration.thm _ _ _ v) := return v.get | _ := fail "not a definition" end, t ← pp d.type, explode_expr v <* trace (to_fmt n ++ " : " ++ t) >>= trace open interactive lean lean.parser interaction_monad.result @[user_command] meta def explode_cmd (_ : parse $ tk "#explode") : parser unit := do n ← ident, explode n . -- #explode iff_true_intro end tactic
58146a98d836901b9a1c0b5923fcb2cc3a436e54
c09f5945267fd905e23a77be83d9a78580e04a4a
/src/topology/instances/ennreal.lean
becf23d2d0883345d543113aa652eecbb1b855d9
[ "Apache-2.0" ]
permissive
OHIHIYA20/mathlib
023a6df35355b5b6eb931c404f7dd7535dccfa89
1ec0a1f49db97d45e8666a3bf33217ff79ca1d87
refs/heads/master
1,587,964,529,965
1,551,819,319,000
1,551,819,319,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
28,682
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Johannes Hölzl Extended non-negative reals -/ import topology.instances.nnreal data.real.ennreal noncomputable theory open classical set lattice filter metric local attribute [instance] prop_decidable variables {α : Type*} {β : Type*} {γ : Type*} local notation `∞` := ennreal.infinity namespace ennreal variables {a b c d : ennreal} {r p q : nnreal} section topological_space open topological_space /-- Topology on `ennreal`. Note: this is different from the `emetric_space` topology. The `emetric_space` topology has `is_open {⊤}`, while this topology doesn't have singleton elements. -/ instance : topological_space ennreal := topological_space.generate_from {s | ∃a, s = {b | a < b} ∨ s = {b | b < a}} instance : orderable_topology ennreal := ⟨rfl⟩ instance : t2_space ennreal := by apply_instance instance : second_countable_topology ennreal := ⟨⟨⋃q ≥ (0:ℚ), {{a : ennreal | a < nnreal.of_real q}, {a : ennreal | ↑(nnreal.of_real q) < a}}, countable_bUnion (countable_encodable _) $ assume a ha, countable_insert (countable_singleton _), le_antisymm (generate_from_le $ λ s h, begin rcases h with ⟨a, hs | hs⟩; [ rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ a < nnreal.of_real q}, {b | ↑(nnreal.of_real q) < b}, from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn a b, and_assoc]), rw show s = ⋃q∈{q:ℚ | 0 ≤ q ∧ ↑(nnreal.of_real q) < a}, {b | b < ↑(nnreal.of_real q)}, from set.ext (assume b, by simp [hs, @ennreal.lt_iff_exists_rat_btwn b a, and_comm, and_assoc])]; { apply is_open_Union, intro q, apply is_open_Union, intro hq, exact generate_open.basic _ (mem_bUnion hq.1 $ by simp) } end) (generate_from_le $ by simp [or_imp_distrib, is_open_lt', is_open_gt'] {contextual := tt})⟩⟩ lemma embedding_coe : embedding (coe : nnreal → ennreal) := and.intro (assume a b, coe_eq_coe.1) $ begin refine le_antisymm _ _, { rw [orderable_topology.topology_eq_generate_intervals nnreal], refine generate_from_le (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, exact ⟨{b : ennreal | ↑a < b}, @is_open_lt' ennreal ennreal.topological_space _ _ _, by simp⟩, exact ⟨{b : ennreal | b < ↑a}, @is_open_gt' ennreal ennreal.topological_space _ _ _, by simp⟩, }, { rw [orderable_topology.topology_eq_generate_intervals ennreal, induced_le_iff_le_coinduced], refine generate_from_le (assume s ha, _), rcases ha with ⟨a, rfl | rfl⟩, show is_open {b : nnreal | a < ↑b}, { cases a; simp [none_eq_top, some_eq_coe, is_open_lt'] }, show is_open {b : nnreal | ↑b < a}, { cases a; simp [none_eq_top, some_eq_coe, is_open_gt', is_open_const] } } end lemma is_open_ne_top : is_open {a : ennreal | a ≠ ⊤} := is_open_neg (is_closed_eq continuous_id continuous_const) lemma coe_range_mem_nhds : range (coe : nnreal → ennreal) ∈ (nhds (r : ennreal)).sets := have {a : ennreal | a ≠ ⊤} = range (coe : nnreal → ennreal), from set.ext $ assume a, by cases a; simp [none_eq_top, some_eq_coe], this ▸ mem_nhds_sets is_open_ne_top coe_ne_top lemma tendsto_coe {f : filter α} {m : α → nnreal} {a : nnreal} : tendsto (λa, (m a : ennreal)) f (nhds ↑a) ↔ tendsto m f (nhds a) := embedding_coe.tendsto_nhds_iff.symm lemma continuous_coe {α} [topological_space α] {f : α → nnreal} : continuous (λa, (f a : ennreal)) ↔ continuous f := embedding_coe.continuous_iff.symm lemma nhds_coe {r : nnreal} : nhds (r : ennreal) = (nhds r).map coe := by rw [embedding_coe.2, map_nhds_induced_eq coe_range_mem_nhds] lemma nhds_coe_coe {r p : nnreal} : nhds ((r : ennreal), (p : ennreal)) = (nhds (r, p)).map (λp:nnreal×nnreal, (p.1, p.2)) := begin rw [(embedding_prod_mk embedding_coe embedding_coe).map_nhds_eq], rw [← prod_range_range_eq], exact prod_mem_nhds_sets coe_range_mem_nhds coe_range_mem_nhds end lemma continuous_of_real : continuous ennreal.of_real := continuous.comp nnreal.continuous_of_real (continuous_coe.2 continuous_id) lemma tendsto_of_real {f : filter α} {m : α → ℝ} {a : ℝ} (h : tendsto m f (nhds a)) : tendsto (λa, ennreal.of_real (m a)) f (nhds (ennreal.of_real a)) := tendsto.comp h (continuous.tendsto continuous_of_real _) lemma tendsto_to_nnreal {a : ennreal} : a ≠ ⊤ → tendsto (ennreal.to_nnreal) (nhds a) (nhds a.to_nnreal) := begin cases a; simp [some_eq_coe, none_eq_top, nhds_coe, tendsto_map'_iff, (∘)], exact tendsto_id end lemma tendsto_nhds_top {m : α → ennreal} {f : filter α} (h : ∀n:ℕ, {a | ↑n < m a} ∈ f.sets) : tendsto m f (nhds ⊤) := tendsto_nhds_generate_from $ assume s hs, match s, hs with | _, ⟨none, or.inl rfl⟩, hr := (lt_irrefl ⊤ hr).elim | _, ⟨some r, or.inl rfl⟩, hr := let ⟨n, hrn⟩ := exists_nat_gt r in mem_sets_of_superset (h n) $ assume a hnma, show ↑r < m a, from lt_trans (show (r : ennreal) < n, from (coe_nat n) ▸ coe_lt_coe.2 hrn) hnma | _, ⟨a, or.inr rfl⟩, hr := (not_top_lt $ show ⊤ < a, from hr).elim end lemma tendsto_coe_nnreal_nhds_top {α} {l : filter α} {f : α → nnreal} (h : tendsto f l at_top) : tendsto (λa, (f a : ennreal)) l (nhds (⊤:ennreal)) := tendsto_nhds_top $ assume n, have {a : α | ↑(n+1) ≤ f a} ∈ l.sets := h $ mem_at_top _, mem_sets_of_superset this $ assume a (ha : ↑(n+1) ≤ f a), begin rw [← coe_nat], dsimp, exact coe_lt_coe.2 (lt_of_lt_of_le (nat.cast_lt.2 (nat.lt_succ_self _)) ha) end instance : topological_add_monoid ennreal := ⟨ continuous_iff_continuous_at.2 $ have hl : ∀a:ennreal, tendsto (λ (p : ennreal × ennreal), p.fst + p.snd) (nhds (⊤, a)) (nhds ⊤), from assume a, tendsto_nhds_top $ assume n, have set.prod {a | ↑n < a } univ ∈ (nhds ((⊤:ennreal), a)).sets, from prod_mem_nhds_sets (lt_mem_nhds $ coe_nat n ▸ coe_lt_top) univ_mem_sets, begin filter_upwards [this] assume ⟨a₁, a₂⟩ ⟨h₁, h₂⟩, lt_of_lt_of_le h₁ (le_add_right $ le_refl _) end, begin rintro ⟨a₁, a₂⟩, cases a₁, { simp [continuous_at, none_eq_top, hl a₂], }, cases a₂, { simp [continuous_at, none_eq_top, some_eq_coe, nhds_swap (a₁ : ennreal) ⊤, tendsto_map'_iff, (∘), hl ↑a₁] }, simp [continuous_at, some_eq_coe, nhds_coe_coe, tendsto_map'_iff, (∘)], simp only [coe_add.symm, tendsto_coe, tendsto_add'] end ⟩ protected lemma tendsto_mul' (ha : a ≠ 0 ∨ b ≠ ⊤) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λp:ennreal×ennreal, p.1 * p.2) (nhds (a, b)) (nhds (a * b)) := have ht : ∀b:ennreal, b ≠ 0 → tendsto (λp:ennreal×ennreal, p.1 * p.2) (nhds ((⊤:ennreal), b)) (nhds ⊤), begin refine assume b hb, tendsto_nhds_top $ assume n, _, rcases dense (zero_lt_iff_ne_zero.2 hb) with ⟨ε', hε', hεb'⟩, rcases ennreal.lt_iff_exists_coe.1 hεb' with ⟨ε, rfl, h⟩, rcases exists_nat_gt (↑n / ε) with ⟨m, hm⟩, have hε : ε > 0, from coe_lt_coe.1 hε', refine mem_sets_of_superset (prod_mem_nhds_sets (lt_mem_nhds $ @coe_lt_top m) (lt_mem_nhds $ h)) _, rintros ⟨a₁, a₂⟩ ⟨h₁, h₂⟩, dsimp at h₁ h₂ ⊢, calc (n:ennreal) = ↑(((n:nnreal) / ε) * ε) : begin simp [nnreal.div_def], rw [mul_assoc, ← coe_mul, nnreal.inv_mul_cancel, coe_one, ← coe_nat, mul_one], exact zero_lt_iff_ne_zero.1 hε end ... < (↑m * ε : nnreal) : coe_lt_coe.2 $ mul_lt_mul hm (le_refl _) hε (nat.cast_nonneg _) ... ≤ a₁ * a₂ : by rw [coe_mul]; exact canonically_ordered_semiring.mul_le_mul (le_of_lt h₁) (le_of_lt h₂) end, begin cases a, {simp [none_eq_top] at hb, simp [none_eq_top, ht b hb, top_mul, hb] }, cases b, { simp [none_eq_top] at ha, have ha' : a ≠ 0, from mt coe_eq_coe.2 ha, simp [*, nhds_swap (a : ennreal) ⊤, none_eq_top, some_eq_coe, top_mul, tendsto_map'_iff, (∘), mul_comm] }, simp [some_eq_coe, nhds_coe_coe, tendsto_map'_iff, (∘)], simp only [coe_mul.symm, tendsto_coe, tendsto_mul'] end protected lemma tendsto_mul {f : filter α} {ma : α → ennreal} {mb : α → ennreal} {a b : ennreal} (hma : tendsto ma f (nhds a)) (ha : a ≠ 0 ∨ b ≠ ⊤) (hmb : tendsto mb f (nhds b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λa, ma a * mb a) f (nhds (a * b)) := show tendsto ((λp:ennreal×ennreal, p.1 * p.2) ∘ (λa, (ma a, mb a))) f (nhds (a * b)), from tendsto.comp (tendsto_prod_mk_nhds hma hmb) (ennreal.tendsto_mul' ha hb) protected lemma tendsto_mul_right {f : filter α} {m : α → ennreal} {a b : ennreal} (hm : tendsto m f (nhds b)) (hb : b ≠ 0 ∨ a ≠ ⊤) : tendsto (λb, a * m b) f (nhds (a * b)) := by_cases (assume : a = 0, by simp [this, tendsto_const_nhds]) (assume ha : a ≠ 0, ennreal.tendsto_mul tendsto_const_nhds (or.inl ha) hm hb) lemma Sup_add {s : set ennreal} (hs : s ≠ ∅) : Sup s + a = ⨆b∈s, b + a := have Sup ((λb, b + a) '' s) = Sup s + a, from is_lub_iff_Sup_eq.mp $ is_lub_of_is_lub_of_tendsto (assume x _ y _ h, add_le_add' h (le_refl _)) is_lub_Sup hs (tendsto_add (tendsto_id' inf_le_left) tendsto_const_nhds), by simp [Sup_image, -add_comm] at this; exact this.symm lemma supr_add {ι : Sort*} {s : ι → ennreal} [h : nonempty ι] : supr s + a = ⨆b, s b + a := let ⟨x⟩ := h in calc supr s + a = Sup (range s) + a : by simp [Sup_range] ... = (⨆b∈range s, b + a) : Sup_add $ ne_empty_iff_exists_mem.mpr ⟨s x, x, rfl⟩ ... = _ : by simp [supr_range, -mem_range] lemma add_supr {ι : Sort*} {s : ι → ennreal} [h : nonempty ι] : a + supr s = ⨆b, a + s b := by rw [add_comm, supr_add]; simp lemma supr_add_supr {ι : Sort*} {f g : ι → ennreal} (h : ∀i j, ∃k, f i + g j ≤ f k + g k) : supr f + supr g = (⨆ a, f a + g a) := begin by_cases hι : nonempty ι, { letI := hι, refine le_antisymm _ (supr_le $ λ a, add_le_add' (le_supr _ _) (le_supr _ _)), simpa [add_supr, supr_add] using λ i j:ι, show f i + g j ≤ ⨆ a, f a + g a, from let ⟨k, hk⟩ := h i j in le_supr_of_le k hk }, { have : ∀f:ι → ennreal, (⨆i, f i) = 0 := assume f, bot_unique (supr_le $ assume i, (hι ⟨i⟩).elim), rw [this, this, this, zero_add] } end lemma supr_add_supr_of_monotone {ι : Sort*} [semilattice_sup ι] {f g : ι → ennreal} (hf : monotone f) (hg : monotone g) : supr f + supr g = (⨆ a, f a + g a) := supr_add_supr $ assume i j, ⟨i ⊔ j, add_le_add' (hf $ le_sup_left) (hg $ le_sup_right)⟩ lemma finset_sum_supr_nat {α} {ι} [semilattice_sup ι] {s : finset α} {f : α → ι → ennreal} (hf : ∀a, monotone (f a)) : s.sum (λa, supr (f a)) = (⨆ n, s.sum (λa, f a n)) := begin refine finset.induction_on s _ _, { simp, exact (bot_unique $ supr_le $ assume i, le_refl ⊥).symm }, { assume a s has ih, simp only [finset.sum_insert has], rw [ih, supr_add_supr_of_monotone (hf a)], assume i j h, exact (finset.sum_le_sum' $ assume a ha, hf a h) } end lemma mul_Sup {s : set ennreal} {a : ennreal} : a * Sup s = ⨆i∈s, a * i := begin by_cases hs : ∀x∈s, x = (0:ennreal), { have h₁ : Sup s = 0 := (bot_unique $ Sup_le $ assume a ha, (hs a ha).symm ▸ le_refl 0), have h₂ : (⨆i ∈ s, a * i) = 0 := (bot_unique $ supr_le $ assume a, supr_le $ assume ha, by simp [hs a ha]), rw [h₁, h₂, mul_zero] }, { simp only [not_forall] at hs, rcases hs with ⟨x, hx, hx0⟩, have s₀ : s ≠ ∅ := not_eq_empty_iff_exists.2 ⟨x, hx⟩, have s₁ : Sup s ≠ 0 := zero_lt_iff_ne_zero.1 (lt_of_lt_of_le (zero_lt_iff_ne_zero.2 hx0) (le_Sup hx)), have : Sup ((λb, a * b) '' s) = a * Sup s := is_lub_iff_Sup_eq.mp (is_lub_of_is_lub_of_tendsto (assume x _ y _ h, canonically_ordered_semiring.mul_le_mul (le_refl _) h) is_lub_Sup s₀ (ennreal.tendsto_mul_right (tendsto_id' inf_le_left) (or.inl s₁))), rw [this.symm, Sup_image] } end lemma mul_supr {ι : Sort*} {f : ι → ennreal} {a : ennreal} : a * supr f = ⨆i, a * f i := by rw [← Sup_range, mul_Sup, supr_range] lemma supr_mul {ι : Sort*} {f : ι → ennreal} {a : ennreal} : supr f * a = ⨆i, f i * a := by rw [mul_comm, mul_supr]; congr; funext; rw [mul_comm] protected lemma tendsto_coe_sub : ∀{b:ennreal}, tendsto (λb:ennreal, ↑r - b) (nhds b) (nhds (↑r - b)) := begin refine (forall_ennreal.2 $ and.intro (assume a, _) _), { simp [@nhds_coe a, tendsto_map'_iff, (∘), tendsto_coe, coe_sub.symm], exact nnreal.tendsto_sub tendsto_const_nhds tendsto_id }, simp, exact (tendsto.congr' (mem_sets_of_superset (lt_mem_nhds $ @coe_lt_top r) $ by simp [le_of_lt] {contextual := tt})) tendsto_const_nhds end lemma sub_supr {ι : Sort*} [hι : nonempty ι] {b : ι → ennreal} (hr : a < ⊤) : a - (⨆i, b i) = (⨅i, a - b i) := let ⟨i⟩ := hι in let ⟨r, eq, _⟩ := lt_iff_exists_coe.mp hr in have Inf ((λb, ↑r - b) '' range b) = ↑r - (⨆i, b i), from is_glb_iff_Inf_eq.mp $ is_glb_of_is_lub_of_tendsto (assume x _ y _, sub_le_sub (le_refl _)) is_lub_supr (ne_empty_of_mem ⟨i, rfl⟩) (tendsto.comp (tendsto_id' inf_le_left) ennreal.tendsto_coe_sub), by rw [eq, ←this]; simp [Inf_image, infi_range, -mem_range]; exact le_refl _ end topological_space section tsum variables {f g : α → ennreal} protected lemma is_sum_coe {f : α → nnreal} {r : nnreal} : is_sum (λa, (f a : ennreal)) ↑r ↔ is_sum f r := have (λs:finset α, s.sum (coe ∘ f)) = (coe : nnreal → ennreal) ∘ (λs:finset α, s.sum f), from funext $ assume s, ennreal.coe_finset_sum.symm, by unfold is_sum; rw [this, tendsto_coe] protected lemma tsum_coe_eq {f : α → nnreal} (h : is_sum f r) : (∑a, (f a : ennreal)) = r := tsum_eq_is_sum $ ennreal.is_sum_coe.2 $ h protected lemma tsum_coe {f : α → nnreal} : has_sum f → (∑a, (f a : ennreal)) = ↑(tsum f) | ⟨r, hr⟩ := by rw [tsum_eq_is_sum hr, ennreal.tsum_coe_eq hr] protected lemma is_sum : is_sum f (⨆s:finset α, s.sum f) := tendsto_orderable.2 ⟨assume a' ha', let ⟨s, hs⟩ := lt_supr_iff.mp ha' in mem_at_top_sets.mpr ⟨s, assume t ht, lt_of_lt_of_le hs $ finset.sum_le_sum_of_subset ht⟩, assume a' ha', univ_mem_sets' $ assume s, have s.sum f ≤ ⨆(s : finset α), s.sum f, from le_supr (λ(s : finset α), s.sum f) s, lt_of_le_of_lt this ha'⟩ @[simp] protected lemma has_sum : has_sum f := ⟨_, ennreal.is_sum⟩ protected lemma tsum_eq_supr_sum : (∑a, f a) = (⨆s:finset α, s.sum f) := tsum_eq_is_sum ennreal.is_sum protected lemma tsum_sigma {β : α → Type*} (f : Πa, β a → ennreal) : (∑p:Σa, β a, f p.1 p.2) = (∑a b, f a b) := tsum_sigma (assume b, ennreal.has_sum) ennreal.has_sum protected lemma tsum_prod {f : α → β → ennreal} : (∑p:α×β, f p.1 p.2) = (∑a, ∑b, f a b) := let j : α × β → (Σa:α, β) := λp, sigma.mk p.1 p.2 in let i : (Σa:α, β) → α × β := λp, (p.1, p.2) in let f' : (Σa:α, β) → ennreal := λp, f p.1 p.2 in calc (∑p:α×β, f' (j p)) = (∑p:Σa:α, β, f p.1 p.2) : tsum_eq_tsum_of_iso j i (assume ⟨a, b⟩, rfl) (assume ⟨a, b⟩, rfl) ... = (∑a, ∑b, f a b) : ennreal.tsum_sigma f protected lemma tsum_comm {f : α → β → ennreal} : (∑a, ∑b, f a b) = (∑b, ∑a, f a b) := let f' : α×β → ennreal := λp, f p.1 p.2 in calc (∑a, ∑b, f a b) = (∑p:α×β, f' p) : ennreal.tsum_prod.symm ... = (∑p:β×α, f' (prod.swap p)) : (tsum_eq_tsum_of_iso prod.swap (@prod.swap α β) (assume ⟨a, b⟩, rfl) (assume ⟨a, b⟩, rfl)).symm ... = (∑b, ∑a, f' (prod.swap (b, a))) : @ennreal.tsum_prod β α (λb a, f' (prod.swap (b, a))) protected lemma tsum_add : (∑a, f a + g a) = (∑a, f a) + (∑a, g a) := tsum_add ennreal.has_sum ennreal.has_sum protected lemma tsum_le_tsum (h : ∀a, f a ≤ g a) : (∑a, f a) ≤ (∑a, g a) := tsum_le_tsum h ennreal.has_sum ennreal.has_sum protected lemma tsum_eq_supr_nat {f : ℕ → ennreal} : (∑i:ℕ, f i) = (⨆i:ℕ, (finset.range i).sum f) := calc _ = (⨆s:finset ℕ, s.sum f) : ennreal.tsum_eq_supr_sum ... = (⨆i:ℕ, (finset.range i).sum f) : le_antisymm (supr_le_supr2 $ assume s, let ⟨n, hn⟩ := finset.exists_nat_subset_range s in ⟨n, finset.sum_le_sum_of_subset hn⟩) (supr_le_supr2 $ assume i, ⟨finset.range i, le_refl _⟩) protected lemma le_tsum (a : α) : f a ≤ (∑a, f a) := calc f a = ({a} : finset α).sum f : by simp ... ≤ (⨆s:finset α, s.sum f) : le_supr (λs:finset α, s.sum f) _ ... = (∑a, f a) : by rw [ennreal.tsum_eq_supr_sum] protected lemma mul_tsum : (∑i, a * f i) = a * (∑i, f i) := if h : ∀i, f i = 0 then by simp [h] else let ⟨i, (hi : f i ≠ 0)⟩ := classical.not_forall.mp h in have sum_ne_0 : (∑i, f i) ≠ 0, from ne_of_gt $ calc 0 < f i : lt_of_le_of_ne (zero_le _) hi.symm ... ≤ (∑i, f i) : ennreal.le_tsum _, have tendsto (λs:finset α, s.sum ((*) a ∘ f)) at_top (nhds (a * (∑i, f i))), by rw [← show (*) a ∘ (λs:finset α, s.sum f) = λs, s.sum ((*) a ∘ f), from funext $ λ s, finset.mul_sum]; exact ennreal.tendsto_mul_right (is_sum_tsum ennreal.has_sum) (or.inl sum_ne_0), tsum_eq_is_sum this protected lemma tsum_mul : (∑i, f i * a) = (∑i, f i) * a := by simp [mul_comm, ennreal.mul_tsum] @[simp] lemma tsum_supr_eq {α : Type*} (a : α) {f : α → ennreal} : (∑b:α, ⨆ (h : a = b), f b) = f a := le_antisymm (by rw [ennreal.tsum_eq_supr_sum]; exact supr_le (assume s, calc s.sum (λb, ⨆ (h : a = b), f b) ≤ (finset.singleton a).sum (λb, ⨆ (h : a = b), f b) : finset.sum_le_sum_of_ne_zero $ assume b _ hb, suffices a = b, by simpa using this.symm, classical.by_contradiction $ assume h, by simpa [h] using hb ... = f a : by simp)) (calc f a ≤ (⨆ (h : a = a), f a) : le_supr (λh:a=a, f a) rfl ... ≤ (∑b:α, ⨆ (h : a = b), f b) : ennreal.le_tsum _) lemma is_sum_iff_tendsto_nat {f : ℕ → ennreal} (r : ennreal) : is_sum f r ↔ tendsto (λn:ℕ, (finset.range n).sum f) at_top (nhds r) := begin refine ⟨tendsto_sum_nat_of_is_sum, assume h, _⟩, rw [← supr_eq_of_tendsto _ h, ← ennreal.tsum_eq_supr_nat], { exact is_sum_tsum ennreal.has_sum }, { exact assume s t hst, finset.sum_le_sum_of_subset (finset.range_subset.2 hst) } end end tsum end ennreal namespace nnreal lemma exists_le_is_sum_of_le {f g : β → nnreal} {r : nnreal} (hgf : ∀b, g b ≤ f b) (hfr : is_sum f r) : ∃p≤r, is_sum g p := have (∑b, (g b : ennreal)) ≤ r, begin refine is_sum_le (assume b, _) (is_sum_tsum ennreal.has_sum) (ennreal.is_sum_coe.2 hfr), exact ennreal.coe_le_coe.2 (hgf _) end, let ⟨p, eq, hpr⟩ := ennreal.le_coe_iff.1 this in ⟨p, hpr, ennreal.is_sum_coe.1 $ eq ▸ is_sum_tsum ennreal.has_sum⟩ lemma has_sum_of_le {f g : β → nnreal} (hgf : ∀b, g b ≤ f b) : has_sum f → has_sum g | ⟨r, hfr⟩ := let ⟨p, _, hp⟩ := exists_le_is_sum_of_le hgf hfr in has_sum_spec hp lemma is_sum_iff_tendsto_nat {f : ℕ → nnreal} (r : nnreal) : is_sum f r ↔ tendsto (λn:ℕ, (finset.range n).sum f) at_top (nhds r) := begin rw [← ennreal.is_sum_coe, ennreal.is_sum_iff_tendsto_nat], simp only [ennreal.coe_finset_sum.symm], exact ennreal.tendsto_coe end end nnreal lemma has_sum_of_nonneg_of_le {f g : β → ℝ} (hg : ∀b, 0 ≤ g b) (hgf : ∀b, g b ≤ f b) (hf : has_sum f) : has_sum g := let f' (b : β) : nnreal := ⟨f b, le_trans (hg b) (hgf b)⟩ in let g' (b : β) : nnreal := ⟨g b, hg b⟩ in have has_sum f', from nnreal.has_sum_coe.1 hf, have has_sum g', from nnreal.has_sum_of_le (assume b, (@nnreal.coe_le (g' b) (f' b)).2 $ hgf b) this, show has_sum (λb, g' b : β → ℝ), from nnreal.has_sum_coe.2 this lemma is_sum_iff_tendsto_nat_of_nonneg {f : ℕ → ℝ} (hf : ∀i, 0 ≤ f i) (r : ℝ) : is_sum f r ↔ tendsto (λn:ℕ, (finset.range n).sum f) at_top (nhds r) := ⟨tendsto_sum_nat_of_is_sum, assume hfr, have 0 ≤ r := ge_of_tendsto at_top_ne_bot hfr $ univ_mem_sets' $ assume i, show 0 ≤ (finset.range i).sum f, from finset.zero_le_sum $ assume i _, hf i, let f' (n : ℕ) : nnreal := ⟨f n, hf n⟩, r' : nnreal := ⟨r, this⟩ in have f_eq : f = (λi:ℕ, (f' i : ℝ)) := rfl, have r_eq : r = r' := rfl, begin rw [f_eq, r_eq, nnreal.is_sum_coe, nnreal.is_sum_iff_tendsto_nat, ← nnreal.tendsto_coe], simp only [nnreal.sum_coe], exact hfr end⟩ lemma infi_real_pos_eq_infi_nnreal_pos {α : Type*} [complete_lattice α] {f : ℝ → α} : (⨅(n:ℝ) (h : n > 0), f n) = (⨅(n:nnreal) (h : n > 0), f n) := le_antisymm (le_infi $ assume n, le_infi $ assume hn, infi_le_of_le n $ infi_le _ (nnreal.coe_pos.2 hn)) (le_infi $ assume r, le_infi $ assume hr, infi_le_of_le ⟨r, le_of_lt hr⟩ $ infi_le _ hr) section variables [emetric_space β] open lattice ennreal filter emetric /-- In an emetric ball, the distance between points is everywhere finite -/ lemma edist_ne_top_of_mem_ball {a : β} {r : ennreal} (x y : ball a r) : edist x.1 y.1 ≠ ⊤ := lt_top_iff_ne_top.1 $ calc edist x y ≤ edist a x + edist a y : edist_triangle_left x.1 y.1 a ... < r + r : by rw [edist_comm a x, edist_comm a y]; exact add_lt_add x.2 y.2 ... ≤ ⊤ : le_top /-- Each ball in an extended metric space gives us a metric space, as the edist is everywhere finite. -/ def metric_space_emetric_ball (a : β) (r : ennreal) : metric_space (ball a r) := emetric_space.to_metric_space edist_ne_top_of_mem_ball local attribute [instance] metric_space_emetric_ball lemma nhds_eq_nhds_emetric_ball (a x : β) (r : ennreal) (h : x ∈ ball a r) : nhds x = map (coe : ball a r → β) (nhds ⟨x, h⟩) := (map_nhds_subtype_val_eq _ $ mem_nhds_sets emetric.is_open_ball h).symm end section variable [emetric_space α] open emetric /-- Yet another metric characterization of Cauchy sequences on integers. This one is often the most efficient. -/ lemma emetric.cauchy_seq_iff_le_tendsto_0 [inhabited β] [semilattice_sup β] {s : β → α} : cauchy_seq s ↔ (∃ (b: β → ennreal), (∀ n m N : β, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N) ∧ (tendsto b at_top (nhds 0))) := ⟨begin assume hs, rw emetric.cauchy_seq_iff at hs, /- `s` is Cauchy sequence. The sequence `b` will be constructed by taking the supremum of the distances between `s n` and `s m` for `n m ≥ N`-/ let b := λN, Sup ((λ(p : β × β), edist (s p.1) (s p.2))''{p | p.1 ≥ N ∧ p.2 ≥ N}), --Prove that it bounds the distances of points in the Cauchy sequence have C : ∀ n m N, N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N, { refine λm n N hm hn, le_Sup _, use (prod.mk m n), simp only [and_true, eq_self_iff_true, set.mem_set_of_eq], exact ⟨hm, hn⟩ }, --Prove that it tends to `0`, by using the Cauchy property of `s` have D : tendsto b at_top (nhds 0), { refine tendsto_orderable.2 ⟨λa ha, absurd ha (ennreal.not_lt_zero), λε εpos, _⟩, rcases dense εpos with ⟨δ, δpos, δlt⟩, rcases hs δ δpos with ⟨N, hN⟩, refine filter.mem_at_top_sets.2 ⟨N, λn hn, _⟩, have : b n ≤ δ := Sup_le begin simp only [and_imp, set.mem_image, set.mem_set_of_eq, exists_imp_distrib, prod.exists], intros d p q hp hq hd, rw ← hd, exact le_of_lt (hN q p (le_trans hn hq) (le_trans hn hp)) end, simpa using lt_of_le_of_lt this δlt }, -- Conclude exact ⟨b, ⟨C, D⟩⟩ end, begin rintros ⟨b, ⟨b_bound, b_lim⟩⟩, /-b : ℕ → ℝ, b_bound : ∀ (n m N : ℕ), N ≤ n → N ≤ m → edist (s n) (s m) ≤ b N, b_lim : tendsto b at_top (nhds 0)-/ refine emetric.cauchy_seq_iff.2 (λε εpos, _), have : {n | b n < ε} ∈ at_top.sets := (tendsto_orderable.1 b_lim ).2 _ εpos, rcases filter.mem_at_top_sets.1 this with ⟨N, hN⟩, exact ⟨N, λm n hm hn, calc edist (s n) (s m) ≤ b N : b_bound n m N hn hm ... < ε : (hN _ (le_refl N)) ⟩ end⟩ lemma continuous_of_le_add_edist {f : α → ennreal} (C : ennreal) (hC : C ≠ ⊤) (h : ∀x y, f x ≤ f y + C * edist x y) : continuous f := begin refine continuous_iff_continuous_at.2 (λx, tendsto_orderable.2 ⟨_, _⟩), show ∀e, e < f x → {y : α | e < f y} ∈ (nhds x).sets, { assume e he, let ε := min (f x - e) 1, have : ε < ⊤ := lt_of_le_of_lt (min_le_right _ _) (by simp [lt_top_iff_ne_top]), have : 0 < ε := by simp [ε, hC, he, ennreal.zero_lt_one], have : 0 < C⁻¹ * (ε/2) := bot_lt_iff_ne_bot.2 (by simp [hC, (ne_of_lt this).symm, ennreal.mul_eq_zero]), have I : C * (C⁻¹ * (ε/2)) < ε, { by_cases C_zero : C = 0, { simp [C_zero, ‹0 < ε›] }, { calc C * (C⁻¹ * (ε/2)) = (C * C⁻¹) * (ε/2) : by simp [mul_assoc] ... = ε/2 : by simp [ennreal.mul_inv_cancel C_zero hC] ... < ε : ennreal.half_lt_self (bot_lt_iff_ne_bot.1 ‹0 < ε›) (lt_top_iff_ne_top.1 ‹ε < ⊤›) }}, have : ball x (C⁻¹ * (ε/2)) ⊆ {y : α | e < f y}, { rintros y hy, by_cases htop : f y = ⊤, { simp [htop, lt_top_iff_ne_top, ne_top_of_lt he] }, { simp at hy, have : e + ε < f y + ε := calc e + ε ≤ e + (f x - e) : add_le_add_left' (min_le_left _ _) ... = f x : by simp [le_of_lt he] ... ≤ f y + C * edist x y : h x y ... = f y + C * edist y x : by simp [edist_comm] ... ≤ f y + C * (C⁻¹ * (ε/2)) : add_le_add_left' $ canonically_ordered_semiring.mul_le_mul (le_refl _) (le_of_lt hy) ... < f y + ε : (ennreal.add_lt_add_iff_left (lt_top_iff_ne_top.2 htop)).2 I, show e < f y, from (ennreal.add_lt_add_iff_right ‹ε < ⊤›).1 this }}, apply filter.mem_sets_of_superset (ball_mem_nhds _ (‹0 < C⁻¹ * (ε/2)›)) this }, show ∀e, f x < e → {y : α | f y < e} ∈ (nhds x).sets, { assume e he, let ε := min (e - f x) 1, have : ε < ⊤ := lt_of_le_of_lt (min_le_right _ _) (by simp [lt_top_iff_ne_top]), have : 0 < ε := by simp [ε, he, ennreal.zero_lt_one], have : 0 < C⁻¹ * (ε/2) := bot_lt_iff_ne_bot.2 (by simp [hC, (ne_of_lt this).symm, ennreal.mul_eq_zero]), have I : C * (C⁻¹ * (ε/2)) < ε, { by_cases C_zero : C = 0, simp [C_zero, ‹0 < ε›], calc C * (C⁻¹ * (ε/2)) = (C * C⁻¹) * (ε/2) : by simp [mul_assoc] ... = ε/2 : by simp [ennreal.mul_inv_cancel C_zero hC] ... < ε : ennreal.half_lt_self (bot_lt_iff_ne_bot.1 ‹0 < ε›) (lt_top_iff_ne_top.1 ‹ε < ⊤›) }, have : ball x (C⁻¹ * (ε/2)) ⊆ {y : α | f y < e}, { rintros y hy, have htop : f x ≠ ⊤ := ne_top_of_lt he, show f y < e, from calc f y ≤ f x + C * edist y x : h y x ... ≤ f x + C * (C⁻¹ * (ε/2)) : add_le_add_left' $ canonically_ordered_semiring.mul_le_mul (le_refl _) (le_of_lt hy) ... < f x + ε : (ennreal.add_lt_add_iff_left (lt_top_iff_ne_top.2 htop)).2 I ... ≤ f x + (e - f x) : add_le_add_left' (min_le_left _ _) ... = e : by simp [le_of_lt he] }, apply filter.mem_sets_of_superset (ball_mem_nhds _ (‹0 < C⁻¹ * (ε/2)›)) this }, end theorem continuous_edist' : continuous (λp:α×α, edist p.1 p.2) := begin apply continuous_of_le_add_edist 2 (by simp), rintros ⟨x, y⟩ ⟨x', y'⟩, calc edist x y ≤ edist x x' + edist x' y' + edist y' y : edist_triangle4 _ _ _ _ ... = edist x' y' + (edist x x' + edist y y') : by simp [add_comm, edist_comm] ... ≤ edist x' y' + (edist (x, y) (x', y') + edist (x, y) (x', y')) : add_le_add_left' (add_le_add' (by simp [edist, le_refl]) (by simp [edist, le_refl])) ... = edist x' y' + 2 * edist (x, y) (x', y') : by rw [← mul_two, mul_comm] end theorem continuous_edist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, edist (f b) (g b)) := (hf.prod_mk hg).comp continuous_edist' theorem tendsto_edist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (nhds a)) (hg : tendsto g x (nhds b)) : tendsto (λx, edist (f x) (g x)) x (nhds (edist a b)) := have tendsto (λp:α×α, edist p.1 p.2) (nhds (a, b)) (nhds (edist a b)), from continuous_iff_continuous_at.mp continuous_edist' (a, b), (hf.prod_mk hg).comp (by rw [nhds_prod_eq] at this; exact this) end --section
51fd9cfdf3470e42c41646ab37692f3b71f39b88
d31b9f832ff922a603f76cf32e0f3aa822640508
/src/hott/types/fiber.lean
dd6e81b38fe1bc4af6f6f841e49f4dd4926b2ddd
[ "Apache-2.0" ]
permissive
javra/hott3
6e7a9e72a991a2fae32e5764982e521dca617b16
cd51f2ab2aa48c1246a188f9b525b30f76c3d651
refs/heads/master
1,585,819,679,148
1,531,232,382,000
1,536,682,965,000
154,294,022
0
0
Apache-2.0
1,540,284,376,000
1,540,284,375,000
null
UTF-8
Lean
false
false
18,817
lean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Mike Shulman Ported from Coq HoTT Theorems about fibers -/ import .sigma .eq .pi ..cubical.squareover .pointed .eq universes u v w hott_theory namespace hott open hott.equiv hott.sigma hott.eq hott.pi hott.pointed hott.is_equiv structure fiber {A B : Type _} (f : A → B) (b : B) := (point : A) (point_eq : f point = b) namespace fiber variables {A : Type _} {B : Type _} {f : A → B} {b : B} @[hott] protected def sigma_char (f : A → B) (b : B) : fiber f b ≃ (Σ(a : A), f a = b) := begin fapply equiv.MK, {intro x, exact ⟨point x, point_eq x⟩}, {intro x, exact (fiber.mk x.1 x.2)}, {intro x, cases x, apply idp }, {intro x, cases x, apply idp }, end @[hott, hsimp] def sigma_char_mk_snd {A B : Type*} (f : A → B) (a : A) (b : B) (p : f a = b) : ((fiber.sigma_char f b) ⟨ a , p ⟩).snd = p := refl _ @[hott, hsimp] def sigma_char_mk_fst {A B : Type*} (f : A → B) (a : A) (b : B) (p : f a = b) : ((fiber.sigma_char f b) ⟨ a , p ⟩).fst = a := refl _ @[hott] def fiber_eq_equiv (x y : fiber f b) : (x = y) ≃ (Σ(p : point x = point y), point_eq x = ap f p ⬝ point_eq y) := begin apply equiv.trans, apply eq_equiv_fn_eq_of_equiv, apply fiber.sigma_char, apply equiv.trans, apply sigma_eq_equiv, apply sigma_equiv_sigma_right, intro p, apply eq_pathover_equiv_Fl, end @[hott] def fiber_eq {x y : fiber f b} (p : point x = point y) (q : point_eq x = ap f p ⬝ point_eq y) : x = y := to_inv (fiber_eq_equiv _ _) ⟨p, q⟩ @[hott] def fiber_pathover {X : Type _} {A B : X → Type _} {x₁ x₂ : X} {p : x₁ = x₂} {f : Πx, A x → B x} {b : Πx, B x} {v₁ : fiber (f x₁) (b x₁)} {v₂ : fiber (f x₂) (b x₂)} (q : point v₁ =[p] point v₂) (r : squareover B hrfl (pathover_idp_of_eq _ (point_eq v₁)) (pathover_idp_of_eq _ (point_eq v₂)) (apo f q) (apd b p)) : v₁ =[p; λ x, fiber (f x) (b x)] v₂ := begin apply (pathover_of_fn_pathover_fn (λ (x : X), @fiber.sigma_char (A x) (B x) (f x) (b x))), dsimp, fapply sigma_pathover; dsimp, { exact q}, { induction v₁ with a₁ p₁, induction v₂ with a₂ p₂, dsimp at *, induction q, apply pathover_idp_of_eq, apply eq_of_vdeg_square, dsimp[hrfl] at r, dsimp[apo, apd] at r, exact (square_of_squareover_ids B r)} end open is_trunc @[hott] def π₁ {B : A → Type _} : (Σa, B a) → A := sigma.fst @[hott] def fiber_pr1 (B : A → Type _) (a : A) : fiber (π₁ : (Σa, B a) → A) a ≃ B a := calc fiber π₁ a ≃ Σ(u : Σ a, B a), (π₁ u) = a : fiber.sigma_char _ _ ... ≃ Σ (a' : A) (b : B a'), a' = a : (sigma_assoc_equiv (λ (u : Σ a, B a), (π₁ u) = a) ) ⁻¹ᵉ ... ≃ Σa' (p : a' = a), B a' : sigma_equiv_sigma_right (λa', comm_equiv_nondep _ _) ... ≃ Σ(w : Σ a', a'=a), B (π₁ w) : sigma_assoc_equiv (λ (w : Σ a', a'=a), B (π₁ w)) ... ≃ B a : sigma_equiv_of_is_contr_left (λ (w : Σ a', a'=a), B (π₁ w)) @[hott] def sigma_fiber_equiv (f : A → B) : (Σb, fiber f b) ≃ A := calc (Σb, fiber f b) ≃ Σb a, f a = b : sigma_equiv_sigma_right (λb, fiber.sigma_char _ b) ... ≃ Σa b, f a = b : sigma_comm_equiv _ ... ≃ A : sigma_equiv_of_is_contr_right _ @[hott, instance] def is_pointed_fiber (f : A → B) (a : A) : pointed (fiber f (f a)) := pointed.mk (fiber.mk a idp) @[hott] def pointed_fiber (f : A → B) (a : A) : Type* := pointed.Mk (fiber.mk a (idpath (f a))) @[hott, reducible] def is_trunc_fun (n : ℕ₋₂) (f : A → B) := Π(b : B), is_trunc n (fiber f b) @[hott, reducible] def is_contr_fun (f : A → B) := is_trunc_fun -2 f -- pre and post composition with equivalences open function variable (f) @[hott] protected def equiv_postcompose {B' : Type _} (g : B ≃ B') --[H : is_equiv g] (b : B) : fiber (g ∘ f) (g b) ≃ fiber f b := calc fiber (g ∘ f) (g b) ≃ Σa : A, g (f a) = g b : fiber.sigma_char _ _ ... ≃ Σa : A, f a = b : begin apply sigma_equiv_sigma_right, intro a, apply equiv.symm, apply eq_equiv_fn_eq end ... ≃ fiber f b : (fiber.sigma_char _ _) ⁻¹ᵉ @[hott] protected def equiv_precompose {A' : Type _} (g : A' ≃ A) --[H : is_equiv g] (b : B) : fiber (f ∘ g) b ≃ fiber f b := calc fiber (f ∘ g) b ≃ Σa' : A', f (g a') = b : fiber.sigma_char _ _ ... ≃ Σa : A, f a = b : begin apply sigma_equiv_sigma g, intro a', apply erfl end ... ≃ fiber f b : (fiber.sigma_char _ _) ⁻¹ᵉ end fiber open unit is_trunc pointed namespace fiber @[hott] def fiber_star_equiv (A : Type _) : fiber (λx : A, star) star ≃ A := begin fapply equiv.MK, { intro f, cases f with a H, exact a }, { intro a, apply fiber.mk a, reflexivity }, { intro a, reflexivity }, { intro f, cases f with a H, change fiber.mk a (refl star) = fiber.mk a H, rwr [is_set.elim H (refl star)] } end @[hott] def fiber_const_equiv (A : Type _) (a₀ : A) (a : A) : fiber (λz : unit, a₀) a ≃ a₀ = a := calc fiber (λz : unit, a₀) a ≃ Σz : unit, a₀ = a : fiber.sigma_char _ _ ... ≃ a₀ = a : sigma_unit_left _ -- the pointed fiber of a pointed map, which is the fiber over the basepoint open pointed @[hott] def pfiber {X Y : Type*} (f : X →* Y) : Type* := pointed.MK (fiber f pt) (fiber.mk pt (respect_pt _)) @[hott] def ppoint {X Y : Type*} (f : X →* Y) : pfiber f →* X := pmap.mk point idp @[hott] def pfiber.sigma_char {A B : Type*} (f : A →* B) : pfiber f ≃* pointed.MK (Σa, f a = pt) ⟨pt, respect_pt f⟩ := pequiv_of_equiv (fiber.sigma_char f pt) idp @[hott, hsimp] def pfiber.sigma_char_mk_snd {A B : Type*} (f : A →* B) (a : A) (p : f a = pt) : ((pfiber.sigma_char f).to_pmap ⟨ a , p ⟩).snd = p := refl _ @[hott] def pointed_fst {A : Type*} (B : A → Type) (pt_B : B pt) : pointed.MK (Σa, B a) ⟨pt, pt_B⟩ →* A := pmap.mk π₁ (refl _) @[hott] def ppoint_sigma_char {A B : Type*} (f : A →* B) : ppoint f ~* (pointed_fst _ _) ∘* (pfiber.sigma_char f).to_pmap := phomotopy.refl _ @[hott] def pfiber_pequiv_of_phomotopy {A B : Type*} {f g : A →* B} (h : f ~* g) : pfiber f ≃* pfiber g := begin fapply pequiv_of_equiv, { refine (fiber.sigma_char f pt ⬝e _ ⬝e (fiber.sigma_char g pt)⁻¹ᵉ), apply sigma_equiv_sigma_right, intros a, apply equiv_eq_closed_left, apply (to_homotopy h) }, { refine (fiber_eq rfl _), change (h pt)⁻¹ ⬝ respect_pt f = idp ⬝ respect_pt g, rwr idp_con, apply inv_con_eq_of_eq_con, symmetry, exact (to_homotopy_pt h) } end @[hott] def transport_fiber_equiv {A B : Type _} (f : A → B) {b1 b2 : B} (p : b1 = b2) : fiber f b1 ≃ fiber f b2 := calc fiber f b1 ≃ Σa, f a = b1 : fiber.sigma_char _ _ ... ≃ Σa, f a = b2 : sigma_equiv_sigma_right (λa, equiv_eq_closed_right (f a) p) ... ≃ fiber f b2 : (fiber.sigma_char _ _) ⁻¹ᵉ @[hott,hsimp] def transport_fiber_equiv_mk {A B : Type _} (f : A → B) {b1 b2 : B} (p : b1 = b2) (a : A) (q : f a = b1) : (transport_fiber_equiv f p) ⟨ a , q ⟩ = ⟨ a , q ⬝ p ⟩ := begin induction p, induction q, refl end @[hott, hsimp] def snd_point_pfiber_eq_respect_pt {A B : Type*} (f : A →* B) : (pfiber f).Point = ⟨ pt , respect_pt f ⟩ := by refl @[hott] def pequiv_postcompose {A B B' : Type*} (f : A →* B) (g : B ≃* B') : pfiber (g.to_pmap ∘* f) ≃* pfiber f := begin fapply pequiv_of_equiv, refine transport_fiber_equiv (g.to_pmap ∘* f) (respect_pt g.to_pmap)⁻¹ ⬝e fiber.equiv_postcompose f (equiv_of_pequiv g) (Point B), dsimp, apply (ap (fiber.mk (Point A))), refine (con.assoc _ _ _) ⬝ _, apply inv_con_eq_of_eq_con, dsimp, rwr [con.assoc, eq.con.right_inv, con_idp, ← ap_compose], exact ap_con_eq_con (λ x, ap g⁻¹ᵉ*.to_pmap (ap g.to_pmap (pleft_inv' g x)⁻¹) ⬝ ap g⁻¹ᵉ*.to_pmap (pright_inv g (g.to_pmap x)) ⬝ pleft_inv' g x) (respect_pt f) end @[hott] def pequiv_precompose {A A' B : Type*} (f : A →* B) (g : A' ≃* A) : pfiber (f ∘* g.to_pmap) ≃* pfiber f := begin fapply pequiv_of_equiv, refine fiber.equiv_precompose f (equiv_of_pequiv g) (Point B), apply (eq_of_fn_eq_fn (fiber.sigma_char _ _)), fapply sigma_eq, { apply respect_pt g.to_pmap }, { apply eq_pathover_Fl' } end @[hott] def pfiber_pequiv_of_square {A B C D : Type*} {f : A →* B} {g : C →* D} (h : A ≃* C) (k : B ≃* D) (s : k.to_pmap ∘* f ~* g ∘* h.to_pmap) : pfiber f ≃* pfiber g := calc pfiber f ≃* pfiber (k.to_pmap ∘* f) : (pequiv_postcompose f k) ⁻¹ᵉ* ... ≃* pfiber (g ∘* h.to_pmap) : pfiber_pequiv_of_phomotopy s ... ≃* pfiber g : (pequiv_precompose _ _) @[hott] def pcompose_ppoint {A B : Type*} (f : A →* B) : f ∘* ppoint f ~* pconst (pfiber f) B := begin fapply phomotopy.mk, { exact point_eq }, { exact !idp_con⁻¹ } end @[hott] def point_fiber_eq {A B : Type _} {f : A → B} {b : B} {x y : fiber f b} (p : point x = point y) (q : point_eq x = ap f p ⬝ point_eq y) : ap point (fiber_eq p q) = p := begin induction x with a γ, induction y with a' γ', dsimp at p q, induction p, induction γ', dsimp at q, hinduction q using eq.rec_symm, reflexivity end @[hott] def fiber_eq_equiv_fiber {A B : Type _} {f : A → B} {b : B} (x y : fiber f b) : x = y ≃ fiber (ap1_gen f (point_eq x) (point_eq y)) (idpath b) := calc x = y ≃ fiber.sigma_char f b x = fiber.sigma_char f b y : eq_equiv_fn_eq_of_equiv (fiber.sigma_char f b) x y ... ≃ Σ(p : point x = point y), point_eq x =[p; λ z, f z = b] point_eq y : sigma_eq_equiv _ _ ... ≃ Σ(p : point x = point y), (point_eq x)⁻¹ ⬝ ap f p ⬝ point_eq y = idp : sigma_equiv_sigma_right (λp, calc point_eq x =[p; λ z, f z = b] point_eq y ≃ point_eq x = ap f p ⬝ point_eq y : eq_pathover_equiv_Fl _ _ _ ... ≃ ap f p ⬝ point_eq y = point_eq x : eq_equiv_eq_symm _ _ ... ≃ (point_eq x)⁻¹ ⬝ (ap f p ⬝ point_eq y) = idp : eq_equiv_inv_con_eq_idp _ _ ... ≃ (point_eq x)⁻¹ ⬝ ap f p ⬝ point_eq y = idp : equiv_eq_closed_left _ (con.assoc _ _ _) ⁻¹) ... ≃ fiber (ap1_gen f (point_eq x) (point_eq y)) (idpath b) : (fiber.sigma_char _ _) ⁻¹ᵉ @[hott] def loop_pfiber {A B : Type*} (f : A →* B) : Ω (pfiber f) ≃* pfiber (Ω→ f) := pequiv_of_equiv (fiber_eq_equiv_fiber (Point (pfiber f)) (Point (pfiber f))) begin induction f with f f₀, induction B with B b₀, dsimp at f f₀, induction f₀, reflexivity end @[hott] def pfiber_loop_space {A B : Type*} (f : A →* B) : pfiber (Ω→ f) ≃* Ω (pfiber f) := (loop_pfiber f)⁻¹ᵉ* @[hott] def point_fiber_eq_equiv_fiber {A B : Type _} {f : A → B} {b : B} {x y : fiber f b} (p : x = y) : point (fiber_eq_equiv_fiber x y p) = ap1_gen point idp idp p := by induction p; reflexivity @[hott] lemma ppoint_loop_pfiber {A B : Type*} (f : A →* B) : ppoint (Ω→ f) ∘* (loop_pfiber f).to_pmap ~* Ω→ (ppoint f) := phomotopy.mk (point_fiber_eq_equiv_fiber) begin induction f with f f₀, induction B with B b₀, dsimp at f f₀, induction f₀, reflexivity end @[hott] lemma ppoint_loop_pfiber_inv {A B : Type*} (f : A →* B) : Ω→ (ppoint f) ∘* ((loop_pfiber f)⁻¹ᵉ*).to_pmap ~* ppoint (Ω→ f) := (phomotopy_pinv_right_of_phomotopy (ppoint_loop_pfiber f))⁻¹* @[hott] def pfiber_pequiv_of_phomotopy_ppoint {A B : Type*} {f g : A →* B} (h : f ~* g) : ppoint g ∘* (pfiber_pequiv_of_phomotopy h).to_pmap ~* ppoint f := begin induction f with f f₀, induction g with g g₀, induction h with h h₀, induction B with B b₀, induction A with A a₀, dsimp at *, induction g₀, dsimp [respect_pt] at h₀, induction h₀, dsimp [ppoint], fapply phomotopy.mk, { reflexivity }, { refine idp_con _ ⬝ _, symmetry, apply point_fiber_eq } end @[hott] def pequiv_postcompose_ppoint {A B B' : Type*} (f : A →* B) (g : B ≃* B') : ppoint f ∘* (fiber.pequiv_postcompose f g).to_pmap ~* ppoint (g.to_pmap ∘* f) := begin induction f with f f₀, induction g with g hg g₀, induction B with B b₀, induction B' with B' b₀', dsimp at *, induction g₀, induction f₀, fapply phomotopy.mk, { reflexivity }, { refine idp_con _ ⬝ _, symmetry, dsimp [ppoint], refine (ap_compose' _ _ _) ⬝ _, apply ap_constant } end @[hott] def pequiv_precompose_ppoint {A A' B : Type*} (f : A →* B) (g : A' ≃* A) : ppoint f ∘* (fiber.pequiv_precompose f g).to_pmap ~* g.to_pmap ∘* ppoint (f ∘* g.to_pmap) := begin induction f with f f₀, induction g with g h₁ h₂ p₁ p₂, induction B with B b₀, induction g with g g₀, induction A with A a₀', dsimp at *, induction g₀, induction f₀, reflexivity end @[hott] def pfiber_pequiv_of_square_ppoint {A B C D : Type*} {f : A →* B} {g : C →* D} (h : A ≃* C) (k : B ≃* D) (s : k.to_pmap ∘* f ~* g ∘* h.to_pmap) : ppoint g ∘* (pfiber_pequiv_of_square h k s).to_pmap ~* h.to_pmap ∘* ppoint f := begin refine (passoc _ _ _) ⁻¹* ⬝* _, refine pwhisker_right _ (pequiv_precompose_ppoint _ _) ⬝* _, refine (passoc _ _ _) ⬝* _, apply pwhisker_left, refine (passoc _ _ _) ⁻¹* ⬝* _, refine pwhisker_right _ (pfiber_pequiv_of_phomotopy_ppoint _) ⬝* _, apply pinv_right_phomotopy_of_phomotopy, refine (pequiv_postcompose_ppoint _ _)⁻¹*, end -- this breaks certain proofs if it is an instance @[hott] def is_trunc_fiber (n : ℕ₋₂) {A B : Type _} (f : A → B) (b : B) [is_trunc n A] [is_trunc (n.+1) B] : is_trunc n (fiber f b) := is_trunc_equiv_closed_rev n (fiber.sigma_char _ _) (is_trunc_sigma _ n) @[hott] def is_trunc_pfiber (n : ℕ₋₂) {A B : Type*} (f : A →* B) [is_trunc n A] [is_trunc (n.+1) B] : is_trunc n (pfiber f) := is_trunc_fiber n f pt @[hott] def fiber_equiv_of_is_contr {A B : Type _} (f : A → B) (b : B) [is_contr B] : fiber f b ≃ A := (fiber.sigma_char _ _) ⬝e sigma_equiv_of_is_contr_right _ @[hott] def pfiber_pequiv_of_is_contr {A B : Type*} (f : A →* B) [is_contr B] : pfiber f ≃* A := pequiv_of_equiv (fiber_equiv_of_is_contr f pt) idp @[hott] def pfiber_ppoint_equiv {A B : Type*} (f : A →* B) : pfiber (ppoint f) ≃ Ω B := calc pfiber (ppoint f) ≃ Σ(x : pfiber f), ppoint f x = pt : fiber.sigma_char _ _ ... ≃ Σ(x : Σa, f a = pt), x.1 = pt : by exact sigma_equiv_sigma (fiber.sigma_char _ _) (λ a, erfl) ... ≃ Σ(x : Σa, a = pt), f x.1 = pt : sigma_assoc_comm_equiv (λa, f a = pt) (λa, a = pt) ... ≃ f pt = pt : sigma_equiv_of_is_contr_left _ ⬝e by refl ... ≃ Ω B : equiv_eq_closed_left _ (respect_pt _) @[hott] def pfiber_ppoint_pequiv {A B : Type*} (f : A →* B) : pfiber (ppoint f) ≃* Ω B := pequiv_of_equiv (pfiber_ppoint_equiv f) (con.left_inv _) @[hott] def fiber_ppoint_equiv_eq {A B : Type*} {f : A →* B} {a : A} (p : f a = pt) (q : ppoint f (fiber.mk a p) = pt) : pfiber_ppoint_equiv f (fiber.mk (fiber.mk a p) q) = (respect_pt f)⁻¹ ⬝ ap f q⁻¹ ⬝ p := begin refine _ ⬝ (con.assoc _ _ _) ⁻¹, apply whisker_left, dsimp [sigma_equiv_of_is_contr_left], refine eq_transport_Fl _ _ ⬝ _, apply whisker_right, refine inverse2 (ap_inv _ _) ⬝ (inv_inv _) ⬝ _, refine ap_compose f sigma.fst _ ⬝ ap02 f _, apply ap_fst_center_eq_sigma_eq' end @[hott] def fiber_ppoint_equiv_inv_eq {A B : Type*} (f : A →* B) (p : Ω B) : (pfiber_ppoint_equiv f)⁻¹ᵉ p = fiber.mk (fiber.mk pt (respect_pt f ⬝ p)) idp := begin apply inv_eq_of_eq, refine _ ⬝ (fiber_ppoint_equiv_eq _ _)⁻¹, exact (inv_con_cancel_left _ _)⁻¹ end end fiber open function is_equiv namespace fiber /- @[hott] theorem 4.7.6 -/ variables {A : Type _} {P : A → Type _ } {Q : A → Type _} variable (f : Πa, P a → Q a) @[hott] def fiber_total_equiv {a : A} (q : Q a) : fiber (total f) ⟨a , q⟩ ≃ fiber (f a) q := calc fiber (total f) ⟨a , q⟩ ≃ Σ(w : Σx, P x), (⟨w.1 , f w.1 w.2 ⟩ : Σ x, _) = ⟨a , q⟩ : fiber.sigma_char _ _ ... ≃ Σ(x : A), Σ(p : P x), (⟨x , f x p⟩ : Σx, _) = ⟨a , q⟩ : (@sigma_assoc_equiv A P (λ(w : Σx, P x), (⟨w.1 , f w.1 w.2 ⟩ : Σ x, _) = ⟨a , q⟩))⁻¹ᵉ ... ≃ Σ(x : A), Σ(p : P x), Σ(H : x = a), f x p =[H] q : begin apply sigma_equiv_sigma_right, intro x, apply sigma_equiv_sigma_right, intro p, apply sigma_eq_equiv end ... ≃ Σ(x : A), Σ(H : x = a), Σ(p : P x), f x p =[H] q : begin apply sigma_equiv_sigma_right, intro x, apply sigma_comm_equiv end ... ≃ Σ(w : Σx, x = a), Σ(p : P w.1), f w.1 p =[w.2] q : sigma_assoc_equiv (λ(w : Σx, x = a), Σ(p : P w.1), f w.1 p =[w.2] q) ... ≃ Σ(p : P (center (Σx, x=a)).1), f (center (Σx, x=a)).1 p =[(center (Σx, x=a)).2] q : sigma_equiv_of_is_contr_left _ ... ≃ Σ(p : P a), f a p =[idpath a] q : equiv_of_eq idp ... ≃ Σ(p : P a), f a p = q : begin apply sigma_equiv_sigma_right, intro p, apply pathover_idp end ... ≃ fiber (f a) q : (fiber.sigma_char _ _)⁻¹ᵉ end fiber end hott
f9ecd5f3620a667fda71aa51f184d94deb5fe5c9
491068d2ad28831e7dade8d6dff871c3e49d9431
/library/algebra/ordered_ring.lean
a56d4828b5ce15cd6e1cf38012054dec9be096ea
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
26,577
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Here an "ordered_ring" is partially ordered ring, which is ordered with respect to both a weak order and an associated strict order. Our numeric structures (int, rat, and real) will be instances of "linear_ordered_comm_ring". This development is modeled after Isabelle's library. -/ import algebra.ordered_group algebra.ring open eq eq.ops namespace algebra variable {A : Type} private definition absurd_a_lt_a {B : Type} {a : A} [s : strict_order A] (H : a < a) : B := absurd H (lt.irrefl a) /- semiring structures -/ structure ordered_semiring [class] (A : Type) extends semiring A, ordered_cancel_comm_monoid A := (mul_le_mul_of_nonneg_left: ∀a b c, le a b → le zero c → le (mul c a) (mul c b)) (mul_le_mul_of_nonneg_right: ∀a b c, le a b → le zero c → le (mul a c) (mul b c)) (mul_lt_mul_of_pos_left: ∀a b c, lt a b → lt zero c → lt (mul c a) (mul c b)) (mul_lt_mul_of_pos_right: ∀a b c, lt a b → lt zero c → lt (mul a c) (mul b c)) section variable [s : ordered_semiring A] variables (a b c d e : A) include s theorem mul_le_mul_of_nonneg_left {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : c * a ≤ c * b := !ordered_semiring.mul_le_mul_of_nonneg_left Hab Hc theorem mul_le_mul_of_nonneg_right {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : a * c ≤ b * c := !ordered_semiring.mul_le_mul_of_nonneg_right Hab Hc -- TODO: there are four variations, depending on which variables we assume to be nonneg theorem mul_le_mul {a b c d : A} (Hac : a ≤ c) (Hbd : b ≤ d) (nn_b : 0 ≤ b) (nn_c : 0 ≤ c) : a * b ≤ c * d := calc a * b ≤ c * b : mul_le_mul_of_nonneg_right Hac nn_b ... ≤ c * d : mul_le_mul_of_nonneg_left Hbd nn_c theorem mul_nonneg {a b : A} (Ha : a ≥ 0) (Hb : b ≥ 0) : a * b ≥ 0 := begin have H : 0 * b ≤ a * b, from mul_le_mul_of_nonneg_right Ha Hb, rewrite zero_mul at H, exact H end theorem mul_nonpos_of_nonneg_of_nonpos {a b : A} (Ha : a ≥ 0) (Hb : b ≤ 0) : a * b ≤ 0 := begin have H : a * b ≤ a * 0, from mul_le_mul_of_nonneg_left Hb Ha, rewrite mul_zero at H, exact H end theorem mul_nonpos_of_nonpos_of_nonneg {a b : A} (Ha : a ≤ 0) (Hb : b ≥ 0) : a * b ≤ 0 := begin have H : a * b ≤ 0 * b, from mul_le_mul_of_nonneg_right Ha Hb, rewrite zero_mul at H, exact H end theorem mul_lt_mul_of_pos_left {a b c : A} (Hab : a < b) (Hc : 0 < c) : c * a < c * b := !ordered_semiring.mul_lt_mul_of_pos_left Hab Hc theorem mul_lt_mul_of_pos_right {a b c : A} (Hab : a < b) (Hc : 0 < c) : a * c < b * c := !ordered_semiring.mul_lt_mul_of_pos_right Hab Hc -- TODO: once again, there are variations theorem mul_lt_mul {a b c d : A} (Hac : a < c) (Hbd : b ≤ d) (pos_b : 0 < b) (nn_c : 0 ≤ c) : a * b < c * d := calc a * b < c * b : mul_lt_mul_of_pos_right Hac pos_b ... ≤ c * d : mul_le_mul_of_nonneg_left Hbd nn_c theorem mul_pos {a b : A} (Ha : a > 0) (Hb : b > 0) : a * b > 0 := begin have H : 0 * b < a * b, from mul_lt_mul_of_pos_right Ha Hb, rewrite zero_mul at H, exact H end theorem mul_neg_of_pos_of_neg {a b : A} (Ha : a > 0) (Hb : b < 0) : a * b < 0 := begin have H : a * b < a * 0, from mul_lt_mul_of_pos_left Hb Ha, rewrite mul_zero at H, exact H end theorem mul_neg_of_neg_of_pos {a b : A} (Ha : a < 0) (Hb : b > 0) : a * b < 0 := begin have H : a * b < 0 * b, from mul_lt_mul_of_pos_right Ha Hb, rewrite zero_mul at H, exact H end end structure linear_ordered_semiring [class] (A : Type) extends ordered_semiring A, linear_strong_order_pair A := (zero_lt_one : lt zero one) section variable [s : linear_ordered_semiring A] variables {a b c : A} include s theorem zero_lt_one : 0 < (1:A) := linear_ordered_semiring.zero_lt_one A theorem lt_of_mul_lt_mul_left (H : c * a < c * b) (Hc : c ≥ 0) : a < b := lt_of_not_ge (assume H1 : b ≤ a, have H2 : c * b ≤ c * a, from mul_le_mul_of_nonneg_left H1 Hc, not_lt_of_ge H2 H) theorem lt_of_mul_lt_mul_right (H : a * c < b * c) (Hc : c ≥ 0) : a < b := lt_of_not_ge (assume H1 : b ≤ a, have H2 : b * c ≤ a * c, from mul_le_mul_of_nonneg_right H1 Hc, not_lt_of_ge H2 H) theorem le_of_mul_le_mul_left (H : c * a ≤ c * b) (Hc : c > 0) : a ≤ b := le_of_not_gt (assume H1 : b < a, have H2 : c * b < c * a, from mul_lt_mul_of_pos_left H1 Hc, not_le_of_gt H2 H) theorem le_of_mul_le_mul_right (H : a * c ≤ b * c) (Hc : c > 0) : a ≤ b := le_of_not_gt (assume H1 : b < a, have H2 : b * c < a * c, from mul_lt_mul_of_pos_right H1 Hc, not_le_of_gt H2 H) theorem le_iff_mul_le_mul_left (a b : A) {c : A} (H : c > 0) : a ≤ b ↔ c * a ≤ c * b := iff.intro (assume H', mul_le_mul_of_nonneg_left H' (le_of_lt H)) (assume H', le_of_mul_le_mul_left H' H) theorem le_iff_mul_le_mul_right (a b : A) {c : A} (H : c > 0) : a ≤ b ↔ a * c ≤ b * c := iff.intro (assume H', mul_le_mul_of_nonneg_right H' (le_of_lt H)) (assume H', le_of_mul_le_mul_right H' H) theorem pos_of_mul_pos_left (H : 0 < a * b) (H1 : 0 ≤ a) : 0 < b := lt_of_not_ge (assume H2 : b ≤ 0, have H3 : a * b ≤ 0, from mul_nonpos_of_nonneg_of_nonpos H1 H2, not_lt_of_ge H3 H) theorem pos_of_mul_pos_right (H : 0 < a * b) (H1 : 0 ≤ b) : 0 < a := lt_of_not_ge (assume H2 : a ≤ 0, have H3 : a * b ≤ 0, from mul_nonpos_of_nonpos_of_nonneg H2 H1, not_lt_of_ge H3 H) theorem nonneg_of_mul_nonneg_left (H : 0 ≤ a * b) (H1 : 0 < a) : 0 ≤ b := le_of_not_gt (assume H2 : b < 0, not_le_of_gt (mul_neg_of_pos_of_neg H1 H2) H) theorem nonneg_of_mul_nonneg_right (H : 0 ≤ a * b) (H1 : 0 < b) : 0 ≤ a := le_of_not_gt (assume H2 : a < 0, not_le_of_gt (mul_neg_of_neg_of_pos H2 H1) H) theorem neg_of_mul_neg_left (H : a * b < 0) (H1 : 0 ≤ a) : b < 0 := lt_of_not_ge (assume H2 : b ≥ 0, not_lt_of_ge (mul_nonneg H1 H2) H) theorem neg_of_mul_neg_right (H : a * b < 0) (H1 : 0 ≤ b) : a < 0 := lt_of_not_ge (assume H2 : a ≥ 0, not_lt_of_ge (mul_nonneg H2 H1) H) theorem nonpos_of_mul_nonpos_left (H : a * b ≤ 0) (H1 : 0 < a) : b ≤ 0 := le_of_not_gt (assume H2 : b > 0, not_le_of_gt (mul_pos H1 H2) H) theorem nonpos_of_mul_nonpos_right (H : a * b ≤ 0) (H1 : 0 < b) : a ≤ 0 := le_of_not_gt (assume H2 : a > 0, not_le_of_gt (mul_pos H2 H1) H) end structure decidable_linear_ordered_semiring [class] (A : Type) extends linear_ordered_semiring A, decidable_linear_order A /- ring structures -/ structure ordered_ring [class] (A : Type) extends ring A, ordered_comm_group A, zero_ne_one_class A := (mul_nonneg : ∀a b, le zero a → le zero b → le zero (mul a b)) (mul_pos : ∀a b, lt zero a → lt zero b → lt zero (mul a b)) theorem ordered_ring.mul_le_mul_of_nonneg_left [s : ordered_ring A] {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : c * a ≤ c * b := have H1 : 0 ≤ b - a, from iff.elim_right !sub_nonneg_iff_le Hab, assert H2 : 0 ≤ c * (b - a), from ordered_ring.mul_nonneg _ _ Hc H1, begin rewrite mul_sub_left_distrib at H2, exact (iff.mp !sub_nonneg_iff_le H2) end theorem ordered_ring.mul_le_mul_of_nonneg_right [s : ordered_ring A] {a b c : A} (Hab : a ≤ b) (Hc : 0 ≤ c) : a * c ≤ b * c := have H1 : 0 ≤ b - a, from iff.elim_right !sub_nonneg_iff_le Hab, assert H2 : 0 ≤ (b - a) * c, from ordered_ring.mul_nonneg _ _ H1 Hc, begin rewrite mul_sub_right_distrib at H2, exact (iff.mp !sub_nonneg_iff_le H2) end theorem ordered_ring.mul_lt_mul_of_pos_left [s : ordered_ring A] {a b c : A} (Hab : a < b) (Hc : 0 < c) : c * a < c * b := have H1 : 0 < b - a, from iff.elim_right !sub_pos_iff_lt Hab, assert H2 : 0 < c * (b - a), from ordered_ring.mul_pos _ _ Hc H1, begin rewrite mul_sub_left_distrib at H2, exact (iff.mp !sub_pos_iff_lt H2) end theorem ordered_ring.mul_lt_mul_of_pos_right [s : ordered_ring A] {a b c : A} (Hab : a < b) (Hc : 0 < c) : a * c < b * c := have H1 : 0 < b - a, from iff.elim_right !sub_pos_iff_lt Hab, assert H2 : 0 < (b - a) * c, from ordered_ring.mul_pos _ _ H1 Hc, begin rewrite mul_sub_right_distrib at H2, exact (iff.mp !sub_pos_iff_lt H2) end definition ordered_ring.to_ordered_semiring [trans-instance] [coercion] [reducible] [s : ordered_ring A] : ordered_semiring A := ⦃ ordered_semiring, s, mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add.left_cancel A s, add_right_cancel := @add.right_cancel A s, le_of_add_le_add_left := @le_of_add_le_add_left A s, mul_le_mul_of_nonneg_left := @ordered_ring.mul_le_mul_of_nonneg_left A s, mul_le_mul_of_nonneg_right := @ordered_ring.mul_le_mul_of_nonneg_right A s, mul_lt_mul_of_pos_left := @ordered_ring.mul_lt_mul_of_pos_left A s, mul_lt_mul_of_pos_right := @ordered_ring.mul_lt_mul_of_pos_right A s, lt_of_add_lt_add_left := @lt_of_add_lt_add_left A s⦄ section variable [s : ordered_ring A] variables {a b c : A} include s theorem mul_le_mul_of_nonpos_left (H : b ≤ a) (Hc : c ≤ 0) : c * a ≤ c * b := have Hc' : -c ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos Hc, assert H1 : -c * b ≤ -c * a, from mul_le_mul_of_nonneg_left H Hc', have H2 : -(c * b) ≤ -(c * a), begin rewrite [-*neg_mul_eq_neg_mul at H1], exact H1 end, iff.mp !neg_le_neg_iff_le H2 theorem mul_le_mul_of_nonpos_right (H : b ≤ a) (Hc : c ≤ 0) : a * c ≤ b * c := have Hc' : -c ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos Hc, assert H1 : b * -c ≤ a * -c, from mul_le_mul_of_nonneg_right H Hc', have H2 : -(b * c) ≤ -(a * c), begin rewrite [-*neg_mul_eq_mul_neg at H1], exact H1 end, iff.mp !neg_le_neg_iff_le H2 theorem mul_nonneg_of_nonpos_of_nonpos (Ha : a ≤ 0) (Hb : b ≤ 0) : 0 ≤ a * b := begin have H : 0 * b ≤ a * b, from mul_le_mul_of_nonpos_right Ha Hb, rewrite zero_mul at H, exact H end theorem mul_lt_mul_of_neg_left (H : b < a) (Hc : c < 0) : c * a < c * b := have Hc' : -c > 0, from iff.mpr !neg_pos_iff_neg Hc, assert H1 : -c * b < -c * a, from mul_lt_mul_of_pos_left H Hc', have H2 : -(c * b) < -(c * a), begin rewrite [-*neg_mul_eq_neg_mul at H1], exact H1 end, iff.mp !neg_lt_neg_iff_lt H2 theorem mul_lt_mul_of_neg_right (H : b < a) (Hc : c < 0) : a * c < b * c := have Hc' : -c > 0, from iff.mpr !neg_pos_iff_neg Hc, assert H1 : b * -c < a * -c, from mul_lt_mul_of_pos_right H Hc', have H2 : -(b * c) < -(a * c), begin rewrite [-*neg_mul_eq_mul_neg at H1], exact H1 end, iff.mp !neg_lt_neg_iff_lt H2 theorem mul_pos_of_neg_of_neg (Ha : a < 0) (Hb : b < 0) : 0 < a * b := begin have H : 0 * b < a * b, from mul_lt_mul_of_neg_right Ha Hb, rewrite zero_mul at H, exact H end end -- TODO: we can eliminate mul_pos_of_pos, but now it is not worth the effort to redeclare the -- class instance structure linear_ordered_ring [class] (A : Type) extends ordered_ring A, linear_strong_order_pair A := (zero_lt_one : lt zero one) definition linear_ordered_ring.to_linear_ordered_semiring [trans-instance] [coercion] [reducible] [s : linear_ordered_ring A] : linear_ordered_semiring A := ⦃ linear_ordered_semiring, s, mul_zero := mul_zero, zero_mul := zero_mul, add_left_cancel := @add.left_cancel A s, add_right_cancel := @add.right_cancel A s, le_of_add_le_add_left := @le_of_add_le_add_left A s, mul_le_mul_of_nonneg_left := @mul_le_mul_of_nonneg_left A s, mul_le_mul_of_nonneg_right := @mul_le_mul_of_nonneg_right A s, mul_lt_mul_of_pos_left := @mul_lt_mul_of_pos_left A s, mul_lt_mul_of_pos_right := @mul_lt_mul_of_pos_right A s, le_total := linear_ordered_ring.le_total, lt_of_add_lt_add_left := @lt_of_add_lt_add_left A s ⦄ structure linear_ordered_comm_ring [class] (A : Type) extends linear_ordered_ring A, comm_monoid A theorem linear_ordered_comm_ring.eq_zero_or_eq_zero_of_mul_eq_zero [s : linear_ordered_comm_ring A] {a b : A} (H : a * b = 0) : a = 0 ∨ b = 0 := lt.by_cases (assume Ha : 0 < a, lt.by_cases (assume Hb : 0 < b, begin have H1 : 0 < a * b, from mul_pos Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end) (assume Hb : 0 = b, or.inr (Hb⁻¹)) (assume Hb : 0 > b, begin have H1 : 0 > a * b, from mul_neg_of_pos_of_neg Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end)) (assume Ha : 0 = a, or.inl (Ha⁻¹)) (assume Ha : 0 > a, lt.by_cases (assume Hb : 0 < b, begin have H1 : 0 > a * b, from mul_neg_of_neg_of_pos Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end) (assume Hb : 0 = b, or.inr (Hb⁻¹)) (assume Hb : 0 > b, begin have H1 : 0 < a * b, from mul_pos_of_neg_of_neg Ha Hb, rewrite H at H1, apply absurd_a_lt_a H1 end)) -- Linearity implies no zero divisors. Doesn't need commutativity. definition linear_ordered_comm_ring.to_integral_domain [trans-instance] [coercion] [reducible] [s: linear_ordered_comm_ring A] : integral_domain A := ⦃ integral_domain, s, eq_zero_or_eq_zero_of_mul_eq_zero := @linear_ordered_comm_ring.eq_zero_or_eq_zero_of_mul_eq_zero A s ⦄ section variable [s : linear_ordered_ring A] variables (a b c : A) include s theorem mul_self_nonneg : a * a ≥ 0 := or.elim (le.total 0 a) (assume H : a ≥ 0, mul_nonneg H H) (assume H : a ≤ 0, mul_nonneg_of_nonpos_of_nonpos H H) theorem zero_le_one : 0 ≤ (1:A) := one_mul 1 ▸ mul_self_nonneg 1 theorem pos_and_pos_or_neg_and_neg_of_mul_pos {a b : A} (Hab : a * b > 0) : (a > 0 ∧ b > 0) ∨ (a < 0 ∧ b < 0) := lt.by_cases (assume Ha : 0 < a, lt.by_cases (assume Hb : 0 < b, or.inl (and.intro Ha Hb)) (assume Hb : 0 = b, begin rewrite [-Hb at Hab, mul_zero at Hab], apply absurd_a_lt_a Hab end) (assume Hb : b < 0, absurd Hab (lt.asymm (mul_neg_of_pos_of_neg Ha Hb)))) (assume Ha : 0 = a, begin rewrite [-Ha at Hab, zero_mul at Hab], apply absurd_a_lt_a Hab end) (assume Ha : a < 0, lt.by_cases (assume Hb : 0 < b, absurd Hab (lt.asymm (mul_neg_of_neg_of_pos Ha Hb))) (assume Hb : 0 = b, begin rewrite [-Hb at Hab, mul_zero at Hab], apply absurd_a_lt_a Hab end) (assume Hb : b < 0, or.inr (and.intro Ha Hb))) theorem gt_of_mul_lt_mul_neg_left {a b c : A} (H : c * a < c * b) (Hc : c ≤ 0) : a > b := have nhc : -c ≥ 0, from neg_nonneg_of_nonpos Hc, have H2 : -(c * b) < -(c * a), from iff.mpr (neg_lt_neg_iff_lt _ _) H, have H3 : (-c) * b < (-c) * a, from calc (-c) * b = - (c * b) : neg_mul_eq_neg_mul ... < -(c * a) : H2 ... = (-c) * a : neg_mul_eq_neg_mul, lt_of_mul_lt_mul_left H3 nhc theorem zero_gt_neg_one : -1 < (0:A) := neg_zero ▸ (neg_lt_neg zero_lt_one) theorem le_of_mul_le_of_ge_one {a b c : A} (H : a * c ≤ b) (Hb : b ≥ 0) (Hc : c ≥ 1) : a ≤ b := have H' : a * c ≤ b * c, from calc a * c ≤ b : H ... = b * 1 : mul_one ... ≤ b * c : mul_le_mul_of_nonneg_left Hc Hb, le_of_mul_le_mul_right H' (lt_of_lt_of_le zero_lt_one Hc) theorem nonneg_le_nonneg_of_squares_le {a b : A} (Ha : a ≥ 0) (Hb : b ≥ 0) (H : a * a ≤ b * b) : a ≤ b := begin apply le_of_not_gt, intro Hab, let Hposa := lt_of_le_of_lt Hb Hab, let H' := calc b * b ≤ a * b : mul_le_mul_of_nonneg_right (le_of_lt Hab) Hb ... < a * a : mul_lt_mul_of_pos_left Hab Hposa, apply (not_le_of_gt H') H end end /- TODO: Isabelle's library has all kinds of cancelation rules for the simplifier. Search on mult_le_cancel_right1 in Rings.thy. -/ structure decidable_linear_ordered_comm_ring [class] (A : Type) extends linear_ordered_comm_ring A, decidable_linear_ordered_comm_group A section variable [s : decidable_linear_ordered_comm_ring A] variables {a b c : A} include s definition sign (a : A) : A := lt.cases a 0 (-1) 0 1 theorem sign_of_neg (H : a < 0) : sign a = -1 := lt.cases_of_lt H theorem sign_zero : sign 0 = (0:A) := lt.cases_of_eq rfl theorem sign_of_pos (H : a > 0) : sign a = 1 := lt.cases_of_gt H theorem sign_one : sign 1 = (1:A) := sign_of_pos zero_lt_one theorem sign_neg_one : sign (-1) = -(1:A) := sign_of_neg (neg_neg_of_pos zero_lt_one) theorem sign_sign (a : A) : sign (sign a) = sign a := lt.by_cases (assume H : a > 0, calc sign (sign a) = sign 1 : by rewrite (sign_of_pos H) ... = 1 : by rewrite sign_one ... = sign a : by rewrite (sign_of_pos H)) (assume H : 0 = a, calc sign (sign a) = sign (sign 0) : by rewrite H ... = sign 0 : by rewrite sign_zero at {1} ... = sign a : by rewrite -H) (assume H : a < 0, calc sign (sign a) = sign (-1) : by rewrite (sign_of_neg H) ... = -1 : by rewrite sign_neg_one ... = sign a : by rewrite (sign_of_neg H)) theorem pos_of_sign_eq_one (H : sign a = 1) : a > 0 := lt.by_cases (assume H1 : 0 < a, H1) (assume H1 : 0 = a, begin rewrite [-H1 at H, sign_zero at H], apply absurd H zero_ne_one end) (assume H1 : 0 > a, have H2 : -1 = 1, from (sign_of_neg H1)⁻¹ ⬝ H, absurd ((eq_zero_of_neg_eq H2)⁻¹) zero_ne_one) theorem eq_zero_of_sign_eq_zero (H : sign a = 0) : a = 0 := lt.by_cases (assume H1 : 0 < a, absurd (H⁻¹ ⬝ sign_of_pos H1) zero_ne_one) (assume H1 : 0 = a, H1⁻¹) (assume H1 : 0 > a, have H2 : 0 = -1, from H⁻¹ ⬝ sign_of_neg H1, have H3 : 1 = 0, from eq_neg_of_eq_neg H2 ⬝ neg_zero, absurd (H3⁻¹) zero_ne_one) theorem neg_of_sign_eq_neg_one (H : sign a = -1) : a < 0 := lt.by_cases (assume H1 : 0 < a, have H2 : -1 = 1, from H⁻¹ ⬝ (sign_of_pos H1), absurd ((eq_zero_of_neg_eq H2)⁻¹) zero_ne_one) (assume H1 : 0 = a, have H2 : (0:A) = -1, begin rewrite [-H1 at H, sign_zero at H], exact H end, have H3 : 1 = 0, from eq_neg_of_eq_neg H2 ⬝ neg_zero, absurd (H3⁻¹) zero_ne_one) (assume H1 : 0 > a, H1) theorem sign_neg (a : A) : sign (-a) = -(sign a) := lt.by_cases (assume H1 : 0 < a, calc sign (-a) = -1 : sign_of_neg (neg_neg_of_pos H1) ... = -(sign a) : by rewrite (sign_of_pos H1)) (assume H1 : 0 = a, calc sign (-a) = sign (-0) : by rewrite H1 ... = sign 0 : by rewrite neg_zero ... = 0 : by rewrite sign_zero ... = -0 : by rewrite neg_zero ... = -(sign 0) : by rewrite sign_zero ... = -(sign a) : by rewrite -H1) (assume H1 : 0 > a, calc sign (-a) = 1 : sign_of_pos (neg_pos_of_neg H1) ... = -(-1) : by rewrite neg_neg ... = -(sign a) : sign_of_neg H1) theorem sign_mul (a b : A) : sign (a * b) = sign a * sign b := lt.by_cases (assume z_lt_a : 0 < a, lt.by_cases (assume z_lt_b : 0 < b, by rewrite [sign_of_pos z_lt_a, sign_of_pos z_lt_b, sign_of_pos (mul_pos z_lt_a z_lt_b), one_mul]) (assume z_eq_b : 0 = b, by rewrite [-z_eq_b, mul_zero, *sign_zero, mul_zero]) (assume z_gt_b : 0 > b, by rewrite [sign_of_pos z_lt_a, sign_of_neg z_gt_b, sign_of_neg (mul_neg_of_pos_of_neg z_lt_a z_gt_b), one_mul])) (assume z_eq_a : 0 = a, by rewrite [-z_eq_a, zero_mul, *sign_zero, zero_mul]) (assume z_gt_a : 0 > a, lt.by_cases (assume z_lt_b : 0 < b, by rewrite [sign_of_neg z_gt_a, sign_of_pos z_lt_b, sign_of_neg (mul_neg_of_neg_of_pos z_gt_a z_lt_b), mul_one]) (assume z_eq_b : 0 = b, by rewrite [-z_eq_b, mul_zero, *sign_zero, mul_zero]) (assume z_gt_b : 0 > b, by rewrite [sign_of_neg z_gt_a, sign_of_neg z_gt_b, sign_of_pos (mul_pos_of_neg_of_neg z_gt_a z_gt_b), neg_mul_neg, one_mul])) theorem abs_eq_sign_mul (a : A) : abs a = sign a * a := lt.by_cases (assume H1 : 0 < a, calc abs a = a : abs_of_pos H1 ... = 1 * a : by rewrite one_mul ... = sign a * a : by rewrite (sign_of_pos H1)) (assume H1 : 0 = a, calc abs a = abs 0 : by rewrite H1 ... = 0 : by rewrite abs_zero ... = 0 * a : by rewrite zero_mul ... = sign 0 * a : by rewrite sign_zero ... = sign a * a : by rewrite H1) (assume H1 : a < 0, calc abs a = -a : abs_of_neg H1 ... = -1 * a : by rewrite neg_eq_neg_one_mul ... = sign a * a : by rewrite (sign_of_neg H1)) theorem eq_sign_mul_abs (a : A) : a = sign a * abs a := lt.by_cases (assume H1 : 0 < a, calc a = abs a : abs_of_pos H1 ... = 1 * abs a : by rewrite one_mul ... = sign a * abs a : by rewrite (sign_of_pos H1)) (assume H1 : 0 = a, calc a = 0 : H1⁻¹ ... = 0 * abs a : by rewrite zero_mul ... = sign 0 * abs a : by rewrite sign_zero ... = sign a * abs a : by rewrite H1) (assume H1 : a < 0, calc a = -(-a) : by rewrite neg_neg ... = -abs a : by rewrite (abs_of_neg H1) ... = -1 * abs a : by rewrite neg_eq_neg_one_mul ... = sign a * abs a : by rewrite (sign_of_neg H1)) theorem abs_dvd_iff (a b : A) : abs a ∣ b ↔ a ∣ b := abs.by_cases !iff.refl !neg_dvd_iff_dvd theorem abs_dvd_of_dvd {a b : A} : a ∣ b → abs a ∣ b := iff.mpr !abs_dvd_iff theorem dvd_abs_iff (a b : A) : a ∣ abs b ↔ a ∣ b := abs.by_cases !iff.refl !dvd_neg_iff_dvd theorem dvd_abs_of_dvd {a b : A} : a ∣ b → a ∣ abs b := iff.mpr !dvd_abs_iff theorem abs_mul (a b : A) : abs (a * b) = abs a * abs b := or.elim (le.total 0 a) (assume H1 : 0 ≤ a, or.elim (le.total 0 b) (assume H2 : 0 ≤ b, calc abs (a * b) = a * b : abs_of_nonneg (mul_nonneg H1 H2) ... = abs a * b : by rewrite (abs_of_nonneg H1) ... = abs a * abs b : by rewrite (abs_of_nonneg H2)) (assume H2 : b ≤ 0, calc abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonneg_of_nonpos H1 H2) ... = a * -b : by rewrite neg_mul_eq_mul_neg ... = abs a * -b : by rewrite (abs_of_nonneg H1) ... = abs a * abs b : by rewrite (abs_of_nonpos H2))) (assume H1 : a ≤ 0, or.elim (le.total 0 b) (assume H2 : 0 ≤ b, calc abs (a * b) = -(a * b) : abs_of_nonpos (mul_nonpos_of_nonpos_of_nonneg H1 H2) ... = -a * b : by rewrite neg_mul_eq_neg_mul ... = abs a * b : by rewrite (abs_of_nonpos H1) ... = abs a * abs b : by rewrite (abs_of_nonneg H2)) (assume H2 : b ≤ 0, calc abs (a * b) = a * b : abs_of_nonneg (mul_nonneg_of_nonpos_of_nonpos H1 H2) ... = -a * -b : by rewrite neg_mul_neg ... = abs a * -b : by rewrite (abs_of_nonpos H1) ... = abs a * abs b : by rewrite (abs_of_nonpos H2))) theorem abs_mul_abs_self (a : A) : abs a * abs a = a * a := abs.by_cases rfl !neg_mul_neg theorem abs_mul_self (a : A) : abs (a * a) = a * a := by rewrite [abs_mul, abs_mul_abs_self] theorem sub_le_of_abs_sub_le_left (H : abs (a - b) ≤ c) : b - c ≤ a := if Hz : 0 ≤ a - b then (calc a ≥ b : (iff.mp !sub_nonneg_iff_le) Hz ... ≥ b - c : sub_le_of_nonneg _ (le.trans !abs_nonneg H)) else (have Habs : b - a ≤ c, by rewrite [abs_of_neg (lt_of_not_ge Hz) at H, neg_sub at H]; apply H, have Habs' : b ≤ c + a, from (iff.mpr !le_add_iff_sub_right_le) Habs, (iff.mp !le_add_iff_sub_left_le) Habs') theorem sub_le_of_abs_sub_le_right (H : abs (a - b) ≤ c) : a - c ≤ b := sub_le_of_abs_sub_le_left (!abs_sub ▸ H) theorem sub_lt_of_abs_sub_lt_left (H : abs (a - b) < c) : b - c < a := if Hz : 0 ≤ a - b then (calc a ≥ b : (iff.mp !sub_nonneg_iff_le) Hz ... > b - c : sub_lt_of_pos _ (lt_of_le_of_lt !abs_nonneg H)) else (have Habs : b - a < c, by rewrite [abs_of_neg (lt_of_not_ge Hz) at H, neg_sub at H]; apply H, have Habs' : b < c + a, from lt_add_of_sub_lt_right Habs, sub_lt_left_of_lt_add Habs') theorem sub_lt_of_abs_sub_lt_right (H : abs (a - b) < c) : a - c < b := sub_lt_of_abs_sub_lt_left (!abs_sub ▸ H) theorem abs_sub_square (a b : A) : abs (a - b) * abs (a - b) = a * a + b * b - (1 + 1) * a * b := by rewrite [abs_mul_abs_self, *mul_sub_left_distrib, *mul_sub_right_distrib, sub_add_eq_sub_sub, sub_neg_eq_add, *right_distrib, sub_add_eq_sub_sub, *one_mul, *add.assoc, {_ + b * b}add.comm, {_ + (b * b + _)}add.comm, mul.comm b a, *add.assoc] theorem abs_abs_sub_abs_le_abs_sub (a b : A) : abs (abs a - abs b) ≤ abs (a - b) := begin apply nonneg_le_nonneg_of_squares_le, repeat apply abs_nonneg, rewrite [*abs_sub_square, *abs_abs, *abs_mul_abs_self], apply sub_le_sub_left, rewrite *mul.assoc, apply mul_le_mul_of_nonneg_left, rewrite -abs_mul, apply le_abs_self, apply le_of_lt, apply add_pos, apply zero_lt_one, apply zero_lt_one end end /- TODO: Multiplication and one, starting with mult_right_le_one_le. -/ end algebra
d61d9f23912b4886bad42a9114ae141b4f6fcf29
efa51dd2edbbbbd6c34bd0ce436415eb405832e7
/20160406_UW/vec.lean
e8d48cae02f8202ed728cb838837d574a183f1e1
[ "Apache-2.0" ]
permissive
leanprover/presentations
dd031a05bcb12c8855676c77e52ed84246bd889a
3ce2d132d299409f1de269fa8e95afa1333d644e
refs/heads/master
1,688,703,388,796
1,686,838,383,000
1,687,465,742,000
29,750,158
12
9
Apache-2.0
1,540,211,670,000
1,422,042,683,000
Lean
UTF-8
Lean
false
false
198
lean
import data.vector data.list open nat list vector variable {A : Type} definition to_list [coercion] : ∀ {n : nat}, vector A n → list A | 0 nil := nil | (n+1) (a::v) := a::(to_list v)
bd81cb718d5453c0fcc6230a95b4d887c4bbf267
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/data/equiv/basic.lean
e45e7b38889a7686710f6d6491d4add80b225d49
[ "Apache-2.0" ]
permissive
EdAyers/mathlib
9ecfb2f14bd6caad748b64c9c131befbff0fb4e0
ca5d4c1f16f9c451cf7170b10105d0051db79e1b
refs/heads/master
1,626,189,395,845
1,555,284,396,000
1,555,284,396,000
144,004,030
0
0
Apache-2.0
1,533,727,664,000
1,533,727,663,000
null
UTF-8
Lean
false
false
32,996
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro In the standard library we cannot assume the univalence axiom. We say two types are equivalent if they are isomorphic. Two equivalent types have the same cardinality. -/ import logic.function logic.unique data.set.basic data.bool data.quot open function universes u v w variables {α : Sort u} {β : Sort v} {γ : Sort w} /-- `α ≃ β` is the type of functions from `α → β` with a two-sided inverse. -/ structure equiv (α : Sort*) (β : Sort*) := (to_fun : α → β) (inv_fun : β → α) (left_inv : left_inverse inv_fun to_fun) (right_inv : right_inverse inv_fun to_fun) namespace equiv /-- `perm α` is the type of bijections from `α` to itself. -/ @[reducible] def perm (α : Sort*) := equiv α α infix ` ≃ `:50 := equiv instance : has_coe_to_fun (α ≃ β) := ⟨_, to_fun⟩ @[simp] theorem coe_fn_mk (f : α → β) (g l r) : (equiv.mk f g l r : α → β) = f := rfl theorem eq_of_to_fun_eq : ∀ {e₁ e₂ : equiv α β}, (e₁ : α → β) = e₂ → e₁ = e₂ | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ h := have f₁ = f₂, from h, have g₁ = g₂, from funext $ assume x, have f₁ (g₁ x) = f₂ (g₂ x), from (r₁ x).trans (r₂ x).symm, have f₁ (g₁ x) = f₁ (g₂ x), by subst f₂; exact this, show g₁ x = g₂ x, from injective_of_left_inverse l₁ this, by simp * @[extensionality] lemma ext (f g : equiv α β) (H : ∀ x, f x = g x) : f = g := eq_of_to_fun_eq (funext H) @[extensionality] lemma perm.ext (σ τ : equiv.perm α) (H : ∀ x, σ x = τ x) : σ = τ := equiv.ext _ _ H @[refl] protected def refl (α : Sort*) : α ≃ α := ⟨id, id, λ x, rfl, λ x, rfl⟩ @[symm] protected def symm (e : α ≃ β) : β ≃ α := ⟨e.inv_fun, e.to_fun, e.right_inv, e.left_inv⟩ @[trans] protected def trans (e₁ : α ≃ β) (e₂ : β ≃ γ) : α ≃ γ := ⟨e₂.to_fun ∘ e₁.to_fun, e₁.inv_fun ∘ e₂.inv_fun, e₂.left_inv.comp e₁.left_inv, e₂.right_inv.comp e₁.right_inv⟩ protected theorem injective : ∀ f : α ≃ β, injective f | ⟨f, g, h₁, h₂⟩ := injective_of_left_inverse h₁ protected theorem surjective : ∀ f : α ≃ β, surjective f | ⟨f, g, h₁, h₂⟩ := surjective_of_has_right_inverse ⟨_, h₂⟩ protected theorem bijective (f : α ≃ β) : bijective f := ⟨f.injective, f.surjective⟩ protected theorem subsingleton (e : α ≃ β) : ∀ [subsingleton β], subsingleton α | ⟨H⟩ := ⟨λ a b, e.injective (H _ _)⟩ protected def decidable_eq (e : α ≃ β) [H : decidable_eq β] : decidable_eq α | a b := decidable_of_iff _ e.injective.eq_iff protected def cast {α β : Sort*} (h : α = β) : α ≃ β := ⟨cast h, cast h.symm, λ x, by cases h; refl, λ x, by cases h; refl⟩ @[simp] theorem coe_fn_symm_mk (f : α → β) (g l r) : ((equiv.mk f g l r).symm : β → α) = g := rfl @[simp] theorem refl_apply (x : α) : equiv.refl α x = x := rfl @[simp] theorem trans_apply (f : α ≃ β) (g : β ≃ γ) (a : α) : (f.trans g) a = g (f a) := rfl @[simp] theorem apply_symm_apply : ∀ (e : α ≃ β) (x : β), e (e.symm x) = x | ⟨f₁, g₁, l₁, r₁⟩ x := by simp [equiv.symm]; rw r₁ @[simp] theorem symm_apply_apply : ∀ (e : α ≃ β) (x : α), e.symm (e x) = x | ⟨f₁, g₁, l₁, r₁⟩ x := by simp [equiv.symm]; rw l₁ @[simp] lemma symm_trans_apply (f : α ≃ β) (g : β ≃ γ) (a : γ) : (f.trans g).symm a = f.symm (g.symm a) := rfl @[simp] theorem apply_eq_iff_eq : ∀ (f : α ≃ β) (x y : α), f x = f y ↔ x = y | ⟨f₁, g₁, l₁, r₁⟩ x y := (injective_of_left_inverse l₁).eq_iff @[simp] theorem cast_apply {α β} (h : α = β) (x : α) : equiv.cast h x = cast h x := rfl lemma symm_apply_eq {α β} (e : α ≃ β) {x y} : e.symm x = y ↔ x = e y := ⟨λ H, by simp [H.symm], λ H, by simp [H]⟩ lemma eq_symm_apply {α β} (e : α ≃ β) {x y} : y = e.symm x ↔ e y = x := (eq_comm.trans e.symm_apply_eq).trans eq_comm @[simp] theorem symm_symm (e : α ≃ β) : e.symm.symm = e := by cases e; refl @[simp] theorem trans_refl (e : α ≃ β) : e.trans (equiv.refl β) = e := by cases e; refl @[simp] theorem refl_trans (e : α ≃ β) : (equiv.refl α).trans e = e := by cases e; refl @[simp] theorem symm_trans (e : α ≃ β) : e.symm.trans e = equiv.refl β := ext _ _ (by simp) @[simp] theorem trans_symm (e : α ≃ β) : e.trans e.symm = equiv.refl α := ext _ _ (by simp) lemma trans_assoc {δ} (ab : α ≃ β) (bc : β ≃ γ) (cd : γ ≃ δ) : (ab.trans bc).trans cd = ab.trans (bc.trans cd) := equiv.ext _ _ $ assume a, rfl theorem left_inverse_symm (f : equiv α β) : left_inverse f.symm f := f.left_inv theorem right_inverse_symm (f : equiv α β) : function.right_inverse f.symm f := f.right_inv def equiv_congr {δ} (ab : α ≃ β) (cd : γ ≃ δ) : (α ≃ γ) ≃ (β ≃ δ) := ⟨ λac, (ab.symm.trans ac).trans cd, λbd, ab.trans $ bd.trans $ cd.symm, assume ac, begin simp [trans_assoc], rw [← trans_assoc], simp end, assume ac, begin simp [trans_assoc], rw [← trans_assoc], simp end, ⟩ def perm_congr {α : Type*} {β : Type*} (e : α ≃ β) : perm α ≃ perm β := equiv_congr e e protected lemma image_eq_preimage {α β} (e : α ≃ β) (s : set α) : e '' s = e.symm ⁻¹' s := set.ext $ assume x, set.mem_image_iff_of_inverse e.left_inv e.right_inv protected lemma subset_image {α β} (e : α ≃ β) (s : set α) (t : set β) : t ⊆ e '' s ↔ e.symm '' t ⊆ s := by rw [set.image_subset_iff, e.image_eq_preimage] lemma symm_image_image {α β} (f : equiv α β) (s : set α) : f.symm '' (f '' s) = s := by rw [← set.image_comp]; simpa using set.image_id s protected lemma image_compl {α β} (f : equiv α β) (s : set α) : f '' -s = -(f '' s) := set.image_compl_eq f.bijective /- The group of permutations (self-equivalences) of a type `α` -/ namespace perm instance perm_group {α : Type u} : group (perm α) := begin refine { mul := λ f g, equiv.trans g f, one := equiv.refl α, inv:= equiv.symm, ..}; intros; apply equiv.ext; try { apply trans_apply }, apply symm_apply_apply end @[simp] theorem mul_apply {α : Type u} (f g : perm α) (x) : (f * g) x = f (g x) := equiv.trans_apply _ _ _ @[simp] theorem one_apply {α : Type u} (x) : (1 : perm α) x = x := rfl @[simp] lemma inv_apply_self {α : Type u} (f : perm α) (x) : f⁻¹ (f x) = x := equiv.symm_apply_apply _ _ @[simp] lemma apply_inv_self {α : Type u} (f : perm α) (x) : f (f⁻¹ x) = x := equiv.apply_symm_apply _ _ lemma one_def {α : Type u} : (1 : perm α) = equiv.refl α := rfl lemma mul_def {α : Type u} (f g : perm α) : f * g = g.trans f := rfl lemma inv_def {α : Type u} (f : perm α) : f⁻¹ = f.symm := rfl end perm def equiv_empty (h : α → false) : α ≃ empty := ⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩ def false_equiv_empty : false ≃ empty := equiv_empty _root_.id def equiv_pempty (h : α → false) : α ≃ pempty := ⟨λ x, (h x).elim, λ e, e.rec _, λ x, (h x).elim, λ e, e.rec _⟩ def false_equiv_pempty : false ≃ pempty := equiv_pempty _root_.id def empty_equiv_pempty : empty ≃ pempty := equiv_pempty $ empty.rec _ def pempty_equiv_pempty : pempty.{v} ≃ pempty.{w} := equiv_pempty pempty.elim def empty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ empty := equiv_empty $ assume a, h ⟨a⟩ def pempty_of_not_nonempty {α : Sort*} (h : ¬ nonempty α) : α ≃ pempty := equiv_pempty $ assume a, h ⟨a⟩ def prop_equiv_punit {p : Prop} (h : p) : p ≃ punit := ⟨λ x, (), λ x, h, λ _, rfl, λ ⟨⟩, rfl⟩ def true_equiv_punit : true ≃ punit := prop_equiv_punit trivial protected def ulift {α : Type u} : ulift α ≃ α := ⟨ulift.down, ulift.up, ulift.up_down, λ a, rfl⟩ protected def plift : plift α ≃ α := ⟨plift.down, plift.up, plift.up_down, plift.down_up⟩ @[congr] def arrow_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → (α₁ → β₁) ≃ (α₂ → β₂) | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ := ⟨λ (h : α₁ → β₁) (a : α₂), f₂ (h (g₁ a)), λ (h : α₂ → β₂) (a : α₁), g₂ (h (f₁ a)), λ h, by funext a; dsimp; rw [l₁, l₂], λ h, by funext a; dsimp; rw [r₁, r₂]⟩ def punit_equiv_punit : punit.{v} ≃ punit.{w} := ⟨λ _, punit.star, λ _, punit.star, λ u, by cases u; refl, λ u, by cases u; reflexivity⟩ section @[simp] def arrow_punit_equiv_punit (α : Sort*) : (α → punit.{v}) ≃ punit.{w} := ⟨λ f, punit.star, λ u f, punit.star, λ f, by funext x; cases f x; refl, λ u, by cases u; reflexivity⟩ @[simp] def punit_arrow_equiv (α : Sort*) : (punit.{u} → α) ≃ α := ⟨λ f, f punit.star, λ a u, a, λ f, by funext x; cases x; refl, λ u, rfl⟩ @[simp] def empty_arrow_equiv_punit (α : Sort*) : (empty → α) ≃ punit.{u} := ⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by cases u; refl⟩ @[simp] def pempty_arrow_equiv_punit (α : Sort*) : (pempty → α) ≃ punit.{u} := ⟨λ f, punit.star, λ u e, e.rec _, λ f, funext $ λ x, x.rec _, λ u, by cases u; refl⟩ @[simp] def false_arrow_equiv_punit (α : Sort*) : (false → α) ≃ punit.{u} := calc (false → α) ≃ (empty → α) : arrow_congr false_equiv_empty (equiv.refl _) ... ≃ punit : empty_arrow_equiv_punit _ end @[congr] def prod_congr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ :β₁ ≃ β₂) : (α₁ × β₁) ≃ (α₂ × β₂) := ⟨λp, (e₁ p.1, e₂ p.2), λp, (e₁.symm p.1, e₂.symm p.2), λ ⟨a, b⟩, show (e₁.symm (e₁ a), e₂.symm (e₂ b)) = (a, b), by rw [symm_apply_apply, symm_apply_apply], λ ⟨a, b⟩, show (e₁ (e₁.symm a), e₂ (e₂.symm b)) = (a, b), by rw [apply_symm_apply, apply_symm_apply]⟩ @[simp] theorem prod_congr_apply {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) (b : β₁) : prod_congr e₁ e₂ (a, b) = (e₁ a, e₂ b) := rfl @[simp] def prod_comm (α β : Sort*) : (α × β) ≃ (β × α) := ⟨λ p, (p.2, p.1), λ p, (p.2, p.1), λ⟨a, b⟩, rfl, λ⟨a, b⟩, rfl⟩ @[simp] def prod_assoc (α β γ : Sort*) : ((α × β) × γ) ≃ (α × (β × γ)) := ⟨λ p, ⟨p.1.1, ⟨p.1.2, p.2⟩⟩, λp, ⟨⟨p.1, p.2.1⟩, p.2.2⟩, λ ⟨⟨a, b⟩, c⟩, rfl, λ ⟨a, ⟨b, c⟩⟩, rfl⟩ @[simp] theorem prod_assoc_apply {α β γ : Sort*} (p : (α × β) × γ) : prod_assoc α β γ p = ⟨p.1.1, ⟨p.1.2, p.2⟩⟩ := rfl section @[simp] def prod_punit (α : Sort*) : (α × punit.{u+1}) ≃ α := ⟨λ p, p.1, λ a, (a, punit.star), λ ⟨_, punit.star⟩, rfl, λ a, rfl⟩ @[simp] theorem prod_punit_apply {α : Sort*} (a : α × punit.{u+1}) : prod_punit α a = a.1 := rfl @[simp] def punit_prod (α : Sort*) : (punit.{u+1} × α) ≃ α := calc (punit × α) ≃ (α × punit) : prod_comm _ _ ... ≃ α : prod_punit _ @[simp] theorem punit_prod_apply {α : Sort*} (a : punit.{u+1} × α) : punit_prod α a = a.2 := rfl @[simp] def prod_empty (α : Sort*) : (α × empty) ≃ empty := equiv_empty (λ ⟨_, e⟩, e.rec _) @[simp] def empty_prod (α : Sort*) : (empty × α) ≃ empty := equiv_empty (λ ⟨e, _⟩, e.rec _) @[simp] def prod_pempty (α : Sort*) : (α × pempty) ≃ pempty := equiv_pempty (λ ⟨_, e⟩, e.rec _) @[simp] def pempty_prod (α : Sort*) : (pempty × α) ≃ pempty := equiv_pempty (λ ⟨e, _⟩, e.rec _) end section open sum def psum_equiv_sum (α β : Sort*) : psum α β ≃ (α ⊕ β) := ⟨λ s, psum.cases_on s inl inr, λ s, sum.cases_on s psum.inl psum.inr, λ s, by cases s; refl, λ s, by cases s; refl⟩ def sum_congr {α₁ β₁ α₂ β₂ : Sort*} : α₁ ≃ α₂ → β₁ ≃ β₂ → (α₁ ⊕ β₁) ≃ (α₂ ⊕ β₂) | ⟨f₁, g₁, l₁, r₁⟩ ⟨f₂, g₂, l₂, r₂⟩ := ⟨λ s, match s with inl a₁ := inl (f₁ a₁) | inr b₁ := inr (f₂ b₁) end, λ s, match s with inl a₂ := inl (g₁ a₂) | inr b₂ := inr (g₂ b₂) end, λ s, match s with inl a := congr_arg inl (l₁ a) | inr a := congr_arg inr (l₂ a) end, λ s, match s with inl a := congr_arg inl (r₁ a) | inr a := congr_arg inr (r₂ a) end⟩ @[simp] theorem sum_congr_apply_inl {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (a : α₁) : sum_congr e₁ e₂ (inl a) = inl (e₁ a) := by cases e₁; cases e₂; refl @[simp] theorem sum_congr_apply_inr {α₁ β₁ α₂ β₂ : Sort*} (e₁ : α₁ ≃ α₂) (e₂ : β₁ ≃ β₂) (b : β₁) : sum_congr e₁ e₂ (inr b) = inr (e₂ b) := by cases e₁; cases e₂; refl def bool_equiv_punit_sum_punit : bool ≃ (punit.{u+1} ⊕ punit.{v+1}) := ⟨λ b, cond b (inr punit.star) (inl punit.star), λ s, sum.rec_on s (λ_, ff) (λ_, tt), λ b, by cases b; refl, λ s, by rcases s with ⟨⟨⟩⟩ | ⟨⟨⟩⟩; refl⟩ noncomputable def Prop_equiv_bool : Prop ≃ bool := ⟨λ p, @to_bool p (classical.prop_decidable _), λ b, b, λ p, by simp, λ b, by simp⟩ @[simp] def sum_comm (α β : Sort*) : (α ⊕ β) ≃ (β ⊕ α) := ⟨λ s, match s with inl a := inr a | inr b := inl b end, λ s, match s with inl b := inr b | inr a := inl a end, λ s, by cases s; refl, λ s, by cases s; refl⟩ @[simp] def sum_assoc (α β γ : Sort*) : ((α ⊕ β) ⊕ γ) ≃ (α ⊕ (β ⊕ γ)) := ⟨λ s, match s with inl (inl a) := inl a | inl (inr b) := inr (inl b) | inr c := inr (inr c) end, λ s, match s with inl a := inl (inl a) | inr (inl b) := inl (inr b) | inr (inr c) := inr c end, λ s, by rcases s with ⟨_ | _⟩ | _; refl, λ s, by rcases s with _ | _ | _; refl⟩ @[simp] theorem sum_assoc_apply_in1 {α β γ} (a) : sum_assoc α β γ (inl (inl a)) = inl a := rfl @[simp] theorem sum_assoc_apply_in2 {α β γ} (b) : sum_assoc α β γ (inl (inr b)) = inr (inl b) := rfl @[simp] theorem sum_assoc_apply_in3 {α β γ} (c) : sum_assoc α β γ (inr c) = inr (inr c) := rfl @[simp] def sum_empty (α : Sort*) : (α ⊕ empty) ≃ α := ⟨λ s, match s with inl a := a | inr e := empty.rec _ e end, inl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl, λ a, rfl⟩ @[simp] def empty_sum (α : Sort*) : (empty ⊕ α) ≃ α := (sum_comm _ _).trans $ sum_empty _ @[simp] def sum_pempty (α : Sort*) : (α ⊕ pempty) ≃ α := ⟨λ s, match s with inl a := a | inr e := pempty.rec _ e end, inl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl, λ a, rfl⟩ @[simp] def pempty_sum (α : Sort*) : (pempty ⊕ α) ≃ α := (sum_comm _ _).trans $ sum_pempty _ @[simp] def option_equiv_sum_punit (α : Sort*) : option α ≃ (α ⊕ punit.{u+1}) := ⟨λ o, match o with none := inr punit.star | some a := inl a end, λ s, match s with inr _ := none | inl a := some a end, λ o, by cases o; refl, λ s, by rcases s with _ | ⟨⟨⟩⟩; refl⟩ def sum_equiv_sigma_bool (α β : Sort*) : (α ⊕ β) ≃ (Σ b: bool, cond b α β) := ⟨λ s, match s with inl a := ⟨tt, a⟩ | inr b := ⟨ff, b⟩ end, λ s, match s with ⟨tt, a⟩ := inl a | ⟨ff, b⟩ := inr b end, λ s, by cases s; refl, λ s, by rcases s with ⟨_|_, _⟩; refl⟩ def equiv_fib {α β : Type*} (f : α → β) : α ≃ Σ y : β, {x // f x = y} := ⟨λ x, ⟨f x, x, rfl⟩, λ x, x.2.1, λ x, rfl, λ ⟨y, x, rfl⟩, rfl⟩ end section def Pi_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : (Π a, β₁ a) ≃ (Π a, β₂ a) := ⟨λ H a, F a (H a), λ H a, (F a).symm (H a), λ H, funext $ by simp, λ H, funext $ by simp⟩ end section def psigma_equiv_sigma {α} (β : α → Sort*) : psigma β ≃ sigma β := ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ def sigma_congr_right {α} {β₁ β₂ : α → Sort*} (F : ∀ a, β₁ a ≃ β₂ a) : sigma β₁ ≃ sigma β₂ := ⟨λ ⟨a, b⟩, ⟨a, F a b⟩, λ ⟨a, b⟩, ⟨a, (F a).symm b⟩, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ symm_apply_apply (F a) b, λ ⟨a, b⟩, congr_arg (sigma.mk a) $ apply_symm_apply (F a) b⟩ def sigma_congr_left {α₁ α₂} {β : α₂ → Sort*} : ∀ f : α₁ ≃ α₂, (Σ a:α₁, β (f a)) ≃ (Σ a:α₂, β a) | ⟨f, g, l, r⟩ := ⟨λ ⟨a, b⟩, ⟨f a, b⟩, λ ⟨a, b⟩, ⟨g a, @@eq.rec β b (r a).symm⟩, λ ⟨a, b⟩, match g (f a), l a : ∀ a' (h : a' = a), @sigma.mk _ (β ∘ f) _ (@@eq.rec β b (congr_arg f h.symm)) = ⟨a, b⟩ with | _, rfl := rfl end, λ ⟨a, b⟩, match f (g a), _ : ∀ a' (h : a' = a), sigma.mk a' (@@eq.rec β b h.symm) = ⟨a, b⟩ with | _, rfl := rfl end⟩ def sigma_equiv_prod (α β : Sort*) : (Σ_:α, β) ≃ (α × β) := ⟨λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, ⟨a, b⟩, λ ⟨a, b⟩, rfl, λ ⟨a, b⟩, rfl⟩ def sigma_equiv_prod_of_equiv {α β} {β₁ : α → Sort*} (F : ∀ a, β₁ a ≃ β) : sigma β₁ ≃ (α × β) := (sigma_congr_right F).trans (sigma_equiv_prod α β) end section def arrow_prod_equiv_prod_arrow (α β γ : Type*) : (γ → α × β) ≃ ((γ → α) × (γ → β)) := ⟨λ f, (λ c, (f c).1, λ c, (f c).2), λ p c, (p.1 c, p.2 c), λ f, funext $ λ c, prod.mk.eta, λ p, by cases p; refl⟩ def arrow_arrow_equiv_prod_arrow (α β γ : Sort*) : (α → β → γ) ≃ (α × β → γ) := ⟨λ f, λ p, f p.1 p.2, λ f, λ a b, f (a, b), λ f, rfl, λ f, by funext p; cases p; refl⟩ open sum def sum_arrow_equiv_prod_arrow (α β γ : Type*) : ((α ⊕ β) → γ) ≃ ((α → γ) × (β → γ)) := ⟨λ f, (f ∘ inl, f ∘ inr), λ p s, sum.rec_on s p.1 p.2, λ f, by funext s; cases s; refl, λ p, by cases p; refl⟩ def sum_prod_distrib (α β γ : Sort*) : ((α ⊕ β) × γ) ≃ ((α × γ) ⊕ (β × γ)) := ⟨λ p, match p with (inl a, c) := inl (a, c) | (inr b, c) := inr (b, c) end, λ s, match s with inl (a, c) := (inl a, c) | inr (b, c) := (inr b, c) end, λ p, by rcases p with ⟨_ | _, _⟩; refl, λ s, by rcases s with ⟨_, _⟩ | ⟨_, _⟩; refl⟩ @[simp] theorem sum_prod_distrib_apply_left {α β γ} (a : α) (c : γ) : sum_prod_distrib α β γ (sum.inl a, c) = sum.inl (a, c) := rfl @[simp] theorem sum_prod_distrib_apply_right {α β γ} (b : β) (c : γ) : sum_prod_distrib α β γ (sum.inr b, c) = sum.inr (b, c) := rfl def prod_sum_distrib (α β γ : Sort*) : (α × (β ⊕ γ)) ≃ ((α × β) ⊕ (α × γ)) := calc (α × (β ⊕ γ)) ≃ ((β ⊕ γ) × α) : prod_comm _ _ ... ≃ ((β × α) ⊕ (γ × α)) : sum_prod_distrib _ _ _ ... ≃ ((α × β) ⊕ (α × γ)) : sum_congr (prod_comm _ _) (prod_comm _ _) @[simp] theorem prod_sum_distrib_apply_left {α β γ} (a : α) (b : β) : prod_sum_distrib α β γ (a, sum.inl b) = sum.inl (a, b) := rfl @[simp] theorem prod_sum_distrib_apply_right {α β γ} (a : α) (c : γ) : prod_sum_distrib α β γ (a, sum.inr c) = sum.inr (a, c) := rfl def bool_prod_equiv_sum (α : Type u) : (bool × α) ≃ (α ⊕ α) := calc (bool × α) ≃ ((unit ⊕ unit) × α) : prod_congr bool_equiv_punit_sum_punit (equiv.refl _) ... ≃ (α × (unit ⊕ unit)) : prod_comm _ _ ... ≃ ((α × unit) ⊕ (α × unit)) : prod_sum_distrib _ _ _ ... ≃ (α ⊕ α) : sum_congr (prod_punit _) (prod_punit _) end section open sum nat def nat_equiv_nat_sum_punit : ℕ ≃ (ℕ ⊕ punit.{u+1}) := ⟨λ n, match n with zero := inr punit.star | succ a := inl a end, λ s, match s with inl n := succ n | inr punit.star := zero end, λ n, begin cases n, repeat { refl } end, λ s, begin cases s with a u, { refl }, {cases u, { refl }} end⟩ @[simp] def nat_sum_punit_equiv_nat : (ℕ ⊕ punit.{u+1}) ≃ ℕ := nat_equiv_nat_sum_punit.symm def int_equiv_nat_sum_nat : ℤ ≃ (ℕ ⊕ ℕ) := by refine ⟨_, _, _, _⟩; intro z; {cases z; [left, right]; assumption} <|> {cases z; refl} end def list_equiv_of_equiv {α β : Type*} : α ≃ β → list α ≃ list β | ⟨f, g, l, r⟩ := by refine ⟨list.map f, list.map g, λ x, _, λ x, _⟩; simp [id_of_left_inverse l, id_of_right_inverse r] def fin_equiv_subtype (n : ℕ) : fin n ≃ {m // m < n} := ⟨λ x, ⟨x.1, x.2⟩, λ x, ⟨x.1, x.2⟩, λ ⟨a, b⟩, rfl,λ ⟨a, b⟩, rfl⟩ def decidable_eq_of_equiv [decidable_eq β] (e : α ≃ β) : decidable_eq α | a₁ a₂ := decidable_of_iff (e a₁ = e a₂) e.injective.eq_iff def inhabited_of_equiv [inhabited β] (e : α ≃ β) : inhabited α := ⟨e.symm (default _)⟩ def unique_of_equiv (e : α ≃ β) (h : unique β) : unique α := unique.of_surjective e.symm.surjective def unique_congr (e : α ≃ β) : unique α ≃ unique β := { to_fun := e.symm.unique_of_equiv, inv_fun := e.unique_of_equiv, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } section open subtype def subtype_congr {p : α → Prop} {q : β → Prop} (e : α ≃ β) (h : ∀ a, p a ↔ q (e a)) : {a : α // p a} ≃ {b : β // q b} := ⟨λ x, ⟨e x.1, (h _).1 x.2⟩, λ y, ⟨e.symm y.1, (h _).2 (by simp; exact y.2)⟩, λ ⟨x, h⟩, subtype.eq' $ by simp, λ ⟨y, h⟩, subtype.eq' $ by simp⟩ def subtype_equiv_of_subtype' {p : α → Prop} (e : α ≃ β) : {a : α // p a} ≃ {b : β // p (e.symm b)} := subtype_congr e $ by simp def subtype_congr_prop {α : Type*} {p q : α → Prop} (h : p = q) : subtype p ≃ subtype q := subtype_congr (equiv.refl α) (assume a, h ▸ iff.refl _) def set_congr {α : Type*} {s t : set α} (h : s = t) : s ≃ t := subtype_congr_prop h def subtype_subtype_equiv_subtype {α : Type u} (p : α → Prop) (q : subtype p → Prop) : subtype q ≃ {a : α // ∃h:p a, q ⟨a, h⟩ } := ⟨λ⟨⟨a, ha⟩, ha'⟩, ⟨a, ha, ha'⟩, λ⟨a, ha⟩, ⟨⟨a, ha.cases_on $ assume h _, h⟩, by cases ha; exact ha_h⟩, assume ⟨⟨a, ha⟩, h⟩, rfl, assume ⟨a, h₁, h₂⟩, rfl⟩ /-- aka coimage -/ def equiv_sigma_subtype {α : Type u} {β : Type v} (f : α → β) : α ≃ Σ b, {x : α // f x = b} := ⟨λ x, ⟨f x, x, rfl⟩, λ x, x.2.1, λ x, rfl, λ ⟨b, x, H⟩, sigma.eq H $ eq.drec_on H $ subtype.eq rfl⟩ def pi_equiv_subtype_sigma (ι : Type*) (π : ι → Type*) : (Πi, π i) ≃ {f : ι → Σi, π i | ∀i, (f i).1 = i } := ⟨ λf, ⟨λi, ⟨i, f i⟩, assume i, rfl⟩, λf i, begin rw ← f.2 i, exact (f.1 i).2 end, assume f, funext $ assume i, rfl, assume ⟨f, hf⟩, subtype.eq $ funext $ assume i, sigma.eq (hf i).symm $ eq_of_heq $ rec_heq_of_heq _ $ rec_heq_of_heq _ $ heq.refl _⟩ def subtype_pi_equiv_pi {α : Sort u} {β : α → Sort v} {p : Πa, β a → Prop} : {f : Πa, β a // ∀a, p a (f a) } ≃ Πa, { b : β a // p a b } := ⟨λf a, ⟨f.1 a, f.2 a⟩, λf, ⟨λa, (f a).1, λa, (f a).2⟩, by rintro ⟨f, h⟩; refl, by rintro f; funext a; exact subtype.eq' rfl⟩ end section local attribute [elab_with_expected_type] quot.lift def quot_equiv_of_quot' {r : α → α → Prop} {s : β → β → Prop} (e : α ≃ β) (h : ∀ a a', r a a' ↔ s (e a) (e a')) : quot r ≃ quot s := ⟨quot.lift (λ a, quot.mk _ (e a)) (λ a a' H, quot.sound ((h a a').mp H)), quot.lift (λ b, quot.mk _ (e.symm b)) (λ b b' H, quot.sound ((h _ _).mpr (by convert H; simp))), quot.ind $ by simp, quot.ind $ by simp⟩ def quot_equiv_of_quot {r : α → α → Prop} (e : α ≃ β) : quot r ≃ quot (λ b b', r (e.symm b) (e.symm b')) := quot_equiv_of_quot' e (by simp) end namespace set open set protected def univ (α) : @univ α ≃ α := ⟨subtype.val, λ a, ⟨a, trivial⟩, λ ⟨a, _⟩, rfl, λ a, rfl⟩ protected def empty (α) : (∅ : set α) ≃ empty := equiv_empty $ λ ⟨x, h⟩, not_mem_empty x h protected def pempty (α) : (∅ : set α) ≃ pempty := equiv_pempty $ λ ⟨x, h⟩, not_mem_empty x h protected def union' {α} {s t : set α} (p : α → Prop) [decidable_pred p] (hs : ∀ x ∈ s, p x) (ht : ∀ x ∈ t, ¬ p x) : (s ∪ t : set α) ≃ (s ⊕ t) := ⟨λ ⟨x, h⟩, if hp : p x then sum.inl ⟨_, h.resolve_right (λ xt, ht _ xt hp)⟩ else sum.inr ⟨_, h.resolve_left (λ xs, hp (hs _ xs))⟩, λ o, match o with | (sum.inl ⟨x, h⟩) := ⟨x, or.inl h⟩ | (sum.inr ⟨x, h⟩) := ⟨x, or.inr h⟩ end, λ ⟨x, h'⟩, by by_cases p x; simp [union'._match_1, union'._match_2, h]; congr, λ o, by rcases o with ⟨x, h⟩ | ⟨x, h⟩; simp [union'._match_1, union'._match_2, h]; [simp [hs _ h], simp [ht _ h]]⟩ protected def union {α} {s t : set α} [decidable_pred s] (H : s ∩ t = ∅) : (s ∪ t : set α) ≃ (s ⊕ t) := set.union' s (λ _, id) (λ x xt xs, subset_empty_iff.2 H ⟨xs, xt⟩) protected def singleton {α} (a : α) : ({a} : set α) ≃ punit.{u} := ⟨λ _, punit.star, λ _, ⟨a, mem_singleton _⟩, λ ⟨x, h⟩, by simp at h; subst x, λ ⟨⟩, rfl⟩ protected def insert {α} {s : set.{u} α} [decidable_pred s] {a : α} (H : a ∉ s) : (insert a s : set α) ≃ (s ⊕ punit.{u+1}) := by rw ← union_singleton; exact (set.union $ inter_singleton_eq_empty.2 H).trans (sum_congr (equiv.refl _) (set.singleton _)) protected def sum_compl {α} (s : set α) [decidable_pred s] : (s ⊕ (-s : set α)) ≃ α := (set.union (inter_compl_self _)).symm.trans (by rw union_compl_self; exact set.univ _) protected def union_sum_inter {α : Type u} (s t : set α) [decidable_pred s] : ((s ∪ t : set α) ⊕ (s ∩ t : set α)) ≃ (s ⊕ t) := calc ((s ∪ t : set α) ⊕ (s ∩ t : set α)) ≃ ((s ∪ t \ s : set α) ⊕ (s ∩ t : set α)) : by rw [union_diff_self] ... ≃ ((s ⊕ (t \ s : set α)) ⊕ (s ∩ t : set α)) : sum_congr (set.union (inter_diff_self _ _)) (equiv.refl _) ... ≃ (s ⊕ (t \ s : set α) ⊕ (s ∩ t : set α)) : sum_assoc _ _ _ ... ≃ (s ⊕ (t \ s ∪ s ∩ t : set α)) : sum_congr (equiv.refl _) begin refine (set.union' (∉ s) _ _).symm, exacts [λ x hx, hx.2, λ x hx, not_not_intro hx.1] end ... ≃ (s ⊕ t) : by rw (_ : t \ s ∪ s ∩ t = t); rw [union_comm, inter_comm, inter_union_diff] protected def prod {α β} (s : set α) (t : set β) : (s.prod t) ≃ (s × t) := ⟨λp, ⟨⟨p.1.1, p.2.1⟩, ⟨p.1.2, p.2.2⟩⟩, λp, ⟨⟨p.1.1, p.2.1⟩, ⟨p.1.2, p.2.2⟩⟩, λ ⟨⟨x, y⟩, ⟨h₁, h₂⟩⟩, rfl, λ ⟨⟨x, h₁⟩, ⟨y, h₂⟩⟩, rfl⟩ protected noncomputable def image {α β} (f : α → β) (s : set α) (H : injective f) : s ≃ (f '' s) := ⟨λ ⟨x, h⟩, ⟨f x, mem_image_of_mem _ h⟩, λ ⟨y, h⟩, ⟨classical.some h, (classical.some_spec h).1⟩, λ ⟨x, h⟩, subtype.eq (H (classical.some_spec (mem_image_of_mem f h)).2), λ ⟨y, h⟩, subtype.eq (classical.some_spec h).2⟩ @[simp] theorem image_apply {α β} (f : α → β) (s : set α) (H : injective f) (a h) : set.image f s H ⟨a, h⟩ = ⟨f a, mem_image_of_mem _ h⟩ := rfl protected noncomputable def range {α β} (f : α → β) (H : injective f) : α ≃ range f := (set.univ _).symm.trans $ (set.image f univ H).trans (equiv.cast $ by rw image_univ) @[simp] theorem range_apply {α β} (f : α → β) (H : injective f) (a) : set.range f H a = ⟨f a, set.mem_range_self _⟩ := by dunfold equiv.set.range equiv.set.univ; simp [set_coe_cast, -image_univ, image_univ.symm] end set noncomputable def of_bijective {α β} {f : α → β} (hf : bijective f) : α ≃ β := ⟨f, λ x, classical.some (hf.2 x), λ x, hf.1 (classical.some_spec (hf.2 (f x))), λ x, classical.some_spec (hf.2 x)⟩ @[simp] theorem of_bijective_to_fun {α β} {f : α → β} (hf : bijective f) : (of_bijective hf : α → β) = f := rfl lemma subtype_quotient_equiv_quotient_subtype (p₁ : α → Prop) [s₁ : setoid α] [s₂ : setoid (subtype p₁)] (p₂ : quotient s₁ → Prop) (hp₂ : ∀ a, p₁ a ↔ p₂ ⟦a⟧) (h : ∀ x y : subtype p₁, @setoid.r _ s₂ x y ↔ (x : α) ≈ y) : {x // p₂ x} ≃ quotient s₂ := { to_fun := λ a, quotient.hrec_on a.1 (λ a h, ⟦⟨a, (hp₂ _).2 h⟩⟧) (λ a b hab, hfunext (by rw quotient.sound hab) (λ h₁ h₂ _, heq_of_eq (quotient.sound ((h _ _).2 hab)))) a.2, inv_fun := λ a, quotient.lift_on a (λ a, (⟨⟦a.1⟧, (hp₂ _).1 a.2⟩ : {x // p₂ x})) (λ a b hab, subtype.eq' (quotient.sound ((h _ _).1 hab))), left_inv := λ ⟨a, ha⟩, quotient.induction_on a (λ a ha, rfl) ha, right_inv := λ a, quotient.induction_on a (λ ⟨a, ha⟩, rfl) } section swap variable [decidable_eq α] open decidable def swap_core (a b r : α) : α := if r = a then b else if r = b then a else r theorem swap_core_self (r a : α) : swap_core a a r = r := by unfold swap_core; split_ifs; cc theorem swap_core_swap_core (r a b : α) : swap_core a b (swap_core a b r) = r := by unfold swap_core; split_ifs; cc theorem swap_core_comm (r a b : α) : swap_core a b r = swap_core b a r := by unfold swap_core; split_ifs; cc /-- `swap a b` is the permutation that swaps `a` and `b` and leaves other values as is. -/ def swap (a b : α) : perm α := ⟨swap_core a b, swap_core a b, λr, swap_core_swap_core r a b, λr, swap_core_swap_core r a b⟩ theorem swap_self (a : α) : swap a a = equiv.refl _ := eq_of_to_fun_eq $ funext $ λ r, swap_core_self r a theorem swap_comm (a b : α) : swap a b = swap b a := eq_of_to_fun_eq $ funext $ λ r, swap_core_comm r _ _ theorem swap_apply_def (a b x : α) : swap a b x = if x = a then b else if x = b then a else x := rfl @[simp] theorem swap_apply_left (a b : α) : swap a b a = b := if_pos rfl @[simp] theorem swap_apply_right (a b : α) : swap a b b = a := by by_cases b = a; simp [swap_apply_def, *] theorem swap_apply_of_ne_of_ne {a b x : α} : x ≠ a → x ≠ b → swap a b x = x := by simp [swap_apply_def] {contextual := tt} @[simp] theorem swap_swap (a b : α) : (swap a b).trans (swap a b) = equiv.refl _ := eq_of_to_fun_eq $ funext $ λ x, swap_core_swap_core _ _ _ theorem swap_comp_apply {a b x : α} (π : perm α) : π.trans (swap a b) x = if π x = a then b else if π x = b then a else π x := by cases π; refl @[simp] lemma swap_inv {α : Type*} [decidable_eq α] (x y : α) : (swap x y)⁻¹ = swap x y := rfl @[simp] lemma symm_trans_swap_trans [decidable_eq α] [decidable_eq β] (a b : α) (e : α ≃ β) : (e.symm.trans (swap a b)).trans e = swap (e a) (e b) := equiv.ext _ _ (λ x, begin have : ∀ a, e.symm x = a ↔ x = e a := λ a, by rw @eq_comm _ (e.symm x); split; intros; simp * at *, simp [swap_apply_def, this], split_ifs; simp end) @[simp] lemma swap_mul_self {α : Type*} [decidable_eq α] (i j : α) : swap i j * swap i j = 1 := equiv.swap_swap i j @[simp] lemma swap_apply_self {α : Type*} [decidable_eq α] (i j a : α) : swap i j (swap i j a) = a := by rw [← perm.mul_apply, swap_mul_self, perm.one_apply] /-- Augment an equivalence with a prescribed mapping `f a = b` -/ def set_value (f : α ≃ β) (a : α) (b : β) : α ≃ β := (swap a (f.symm b)).trans f @[simp] theorem set_value_eq (f : α ≃ β) (a : α) (b : β) : set_value f a b a = b := by dsimp [set_value]; simp [swap_apply_left] end swap end equiv instance {α} [subsingleton α] : subsingleton (ulift α) := equiv.ulift.subsingleton instance {α} [subsingleton α] : subsingleton (plift α) := equiv.plift.subsingleton instance {α} [decidable_eq α] : decidable_eq (ulift α) := equiv.ulift.decidable_eq instance {α} [decidable_eq α] : decidable_eq (plift α) := equiv.plift.decidable_eq def unique_unique_equiv : unique (unique α) ≃ unique α := { to_fun := λ h, h.default, inv_fun := λ h, { default := h, uniq := λ _, subsingleton.elim _ _ }, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } def equiv_of_unique_of_unique [unique α] [unique β] : α ≃ β := { to_fun := λ _, default β, inv_fun := λ _, default α, left_inv := λ _, subsingleton.elim _ _, right_inv := λ _, subsingleton.elim _ _ } def equiv_punit_of_unique [unique α] : α ≃ punit.{v} := equiv_of_unique_of_unique namespace quot /-- Quotients are congruent on equivalences under equality of their relation. An alternative is just to use rewriting with `eq`, but then computational proofs get stuck. -/ protected def congr {α} {r r' : α → α → Prop} (eq : ∀a b, r a b ↔ r' a b) : quot r ≃ quot r' := ⟨quot.map r r' (assume a b, (eq a b).1), quot.map r' r (assume a b, (eq a b).2), by rintros ⟨a⟩; refl, by rintros ⟨a⟩; refl⟩ end quot namespace quotient protected def congr {α} {r r' : setoid α} (eq : ∀a b, @setoid.r α r a b ↔ @setoid.r α r' a b) : quotient r ≃ quotient r' := quot.congr eq end quotient
596911638a30111e244a05a4c43808a79a21fad6
7282d49021d38dacd06c4ce45a48d09627687fe0
/examples/lean/ex4.lean
e470b12d387aeccd665ae7f9cd5d6c3e22710013
[ "Apache-2.0" ]
permissive
steveluc/lean
5a0b4431acefaf77f15b25bbb49294c2449923ad
92ba4e8b2d040a799eda7deb8d2a7cdd3e69c496
refs/heads/master
1,611,332,256,930
1,391,013,244,000
1,391,013,244,000
16,361,079
1
0
null
null
null
null
UTF-8
Lean
false
false
239
lean
import Int import tactic definition a : Nat := 10 -- Trivial indicates a "proof by evaluation" theorem T1 : a > 0 := trivial theorem T2 : a - 5 > 3 := trivial -- The next one is commented because it fails -- theorem T3 : a > 11 := trivial
7d57b918d0a407bd3183b7e48c488ceb7e51adef
a721fe7446524f18ba361625fc01033d9c8b7a78
/src/principia/mynat/parity.lean
7b78722ad0b91309370c935dc7274e24175fd692
[]
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
6,759
lean
-- vim: ts=2 sw=0 sts=-1 et ai tw=70 import .prime import .induction namespace hidden namespace mynat def even (m: mynat) := 2 ∣ m def odd (m: mynat) := ¬even m variables {m n k p: mynat} theorem even_zero: even 0 := begin existsi (0: mynat), simp, end theorem odd_one: odd 1 := begin assume he1, have h21 := dvd_one he1, cases h21, end theorem two_only_even_prime: prime m → 2 ∣ m → m = 2 := begin assume hmpm h2dm, cases h2dm with n hn, cases m, rw zz at *, exfalso, from zero_nprime hmpm, have hndvds: n ∣ succ m, rw hn, apply dvd_mul, refl, cases hmpm with hsneq1 hdiv, have h₂ := hdiv n hndvds, cases h₂, rw [h₂, one_mul] at hn, assumption, exfalso, rw h₂ at hn, have hcancel := mul_cancel_to_one succ_ne_zero, cases hcancel hn, end theorem even_add_even: even m → even n → even (m + n) := begin assume hm hn, from dvd_sum hm hn, end theorem even_remainder (m k n : mynat): even m → even n → m + k = n → even k := begin assume hm hn h, from dvd_remainder _ _ _ _ hm hn h, end theorem even_add_odd: even m → odd n → odd (m + n) := begin assume hm hn heven, have : even n, { apply even_remainder m n (m + n) hm heven, refl, }, contradiction, end theorem odd_add_even: odd m → even n → odd (m + n) := begin assume hom hen, rw add_comm, from even_add_odd hen hom, end theorem succ_even_is_odd: even m → odd (succ m) := begin assume hem hesm, cases hem with a ha, cases hesm with b hb, rw ha at hb, have he1: even 1, { have h2dvda2: 2 ∣ a * 2 := dvd_multiple, have h2dvdb2: 2 ∣ b * 2 := dvd_multiple, from dvd_remainder _ 1 _ _ h2dvda2 h2dvdb2 hb, }, from odd_one he1, end theorem odd_periodic: odd m ↔ odd (m + 2) := begin split, { assume hom hem2, from hom (dvd_cancel hem2), }, { assume hom2 hem, from hom2 (dvd_add hem), }, end theorem even_periodic: even m ↔ even (m + 2) := begin split, { assume hem, from dvd_add hem, }, { assume hem2, from dvd_cancel hem2, }, end -- is this overkill? theorem succ_odd_is_even: odd m → even (succ m) := begin assume hom, apply strong_induction (λ m, odd m → even (succ m)), { assume ho0, exfalso, from ho0 even_zero, }, { intro n, assume h_ih, assume hosn, cases n, { existsi (1: mynat), refl, }, { have hon := odd_periodic.mpr hosn, have hesn := h_ih n (le_to_add: n ≤ n + 1) hon, from even_periodic.mp hesn, }, }, assumption, end instance even_decidable: ∀ m : mynat, decidable (even m) := begin intro m, induction m with m hm, { from is_true even_zero, }, { cases hm, { from is_true (succ_odd_is_even hm), }, { from is_false (succ_even_is_odd hm), }, }, end theorem cancel_succ_even: even (succ m) → odd m := begin assume hesm, cases m, { exfalso, from odd_one hesm, }, { apply succ_even_is_odd, rw even_periodic, assumption, }, end theorem cancel_succ_odd: odd (succ m) → even m := begin assume hosm, cases m, { from even_zero, }, { apply succ_odd_is_even, rw odd_periodic, assumption, }, end theorem odd_periodic_lots: even m → odd (n + m) → odd n := begin assume hem honm hen, from honm (even_add_even hen hem), end theorem even_periodic_lots: even m → even (n + m) → even n := begin assume hem honm, cases hem with k hk, rw hk at honm, rw mul_comm at honm, from dvd_cancel_lots honm, end theorem odd_add_odd: odd m → odd n → even (m + n) := begin assume hom hon, have hesm := succ_odd_is_even hom, have hesn := succ_odd_is_even hon, have hesmsn := even_add_even hesm hesn, simp at hesmsn, rw even_periodic, from hesmsn, end theorem even_mul: even m → even (m * n) := begin assume hm, cases hm with a ha, existsi a * n, rw ha, ac_refl, end theorem even_mul_even: even m → even n → even (m * n) := begin assume hem _, from even_mul hem, end theorem odd_mul_odd: odd m → odd n → odd (m*n) := begin assume hom hon heven, have hesm := succ_odd_is_even hom, have hesn := succ_odd_is_even hon, have hesmsn := even_mul_even hesm hesn, rw mul_succ at hesmsn, rw succ_mul at hesmsn, rw succ_add at hesmsn, have homn := cancel_succ_even hesmsn, rw ←add_assoc at homn, have hemn: even (m + n), { have hesmpsn := even_add_even hesm hesn, simp at hesmpsn, from even_periodic.mpr hesmpsn, }, rw add_comm m at homn, rw add_assoc at homn, have homn' := odd_periodic_lots hemn homn, from homn' heven, end -- basically we can do excluded middle without any of the classical theorem even_square: even (m * m) → even m := begin by_cases (even m), { assume _, assumption, }, { assume hem2, exfalso, from odd_mul_odd h h hem2, }, end -- this is awful theorem sqrt_2_irrational: ¬(m ≠ 0 ∧ ∃ n, n * n = 2 * m * m) := begin -- for some reason this is a recurring lemma here -- is there some way to just do this inline? have h20: (2: mynat) ≠ 0, { assume h, cases h, }, apply infinite_descent (λ m, m ≠ 0 ∧ ∃ n, n * n = 2 * m * m), intro k, assume h_desc, cases h_desc with hknz h_desc, cases h_desc with n hn2k2, -- this also comes up a lot have hnn0: n ≠ 0, { assume hn0, simp [hn0] at hn2k2, rw mul_comm at hn2k2, rw mul_comm 2 at hn2k2, from h20 (mul_integral hknz (mul_integral hknz hn2k2.symm)), }, have h2dvdn: 2 ∣ n, { have h2dvdn2: 2 ∣ n * n, { existsi k * k, rw hn2k2, ac_refl, }, from even_square h2dvdn2, }, cases h2dvdn with k' hk', existsi k', split, split, { assume hk'0, simp [hk'0] at hk', from hnn0 hk', }, { rw hk' at hn2k2, existsi k, apply mul_cancel h20, rw [←mul_assoc, ←hn2k2], rw mul_comm 2 _, conv { to_rhs, rw mul_assoc, congr, rw mul_comm, }, }, { conv at hn2k2 { rw hk', congr, rw mul_comm k', rw mul_assoc, skip, rw mul_assoc, }, have h₂ := mul_cancel h20 hn2k2, conv at h₂ { to_lhs, rw [mul_comm, mul_assoc], }, suffices : k'*k' < k*k, { apply lt_sqrt this, }, -- TODO: write a separate theorem here assume hk2k'2, cases hk2k'2 with d hd, rw hd at h₂, have hk2e0: k * k = 0, { have h211: (2: mynat) = 1 + 1, refl, rw [h211, add_mul, one_mul, add_assoc] at h₂, have h' := add_cancel_to_zero h₂.symm, rw [add_comm, add_assoc] at h', from add_integral h', }, from hknz (mul_integral hknz hk2e0), }, end end mynat end hidden
91b818935b2441f060dc0a723e64998e1fd8d98f
9028d228ac200bbefe3a711342514dd4e4458bff
/src/field_theory/splitting_field.lean
34aa09cf19b4d4018ee8e64ce2cf3a5b730bb40b
[ "Apache-2.0" ]
permissive
mcncm/mathlib
8d25099344d9d2bee62822cb9ed43aa3e09fa05e
fde3d78cadeec5ef827b16ae55664ef115e66f57
refs/heads/master
1,672,743,316,277
1,602,618,514,000
1,602,618,514,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
31,951
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes Definition of splitting fields, and definition of homomorphism into any field that splits -/ import ring_theory.adjoin_root import ring_theory.algebra_tower import ring_theory.algebraic import ring_theory.polynomial import field_theory.minimal_polynomial import linear_algebra.finite_dimensional noncomputable theory open_locale classical big_operators universes u v w variables {α : Type u} {β : Type v} {γ : Type w} namespace polynomial variables [field α] [field β] [field γ] open polynomial section splits variables (i : α →+* β) /-- a polynomial `splits` iff it is zero or all of its irreducible factors have `degree` 1 -/ def splits (f : polynomial α) : Prop := f = 0 ∨ ∀ {g : polynomial β}, irreducible g → g ∣ f.map i → degree g = 1 @[simp] lemma splits_zero : splits i (0 : polynomial α) := or.inl rfl @[simp] lemma splits_C (a : α) : splits i (C a) := if ha : a = 0 then ha.symm ▸ (@C_0 α _).symm ▸ splits_zero i else have hia : i a ≠ 0, from mt ((is_add_group_hom.injective_iff i).1 i.injective _) ha, or.inr $ λ g hg ⟨p, hp⟩, absurd hg.1 (not_not.2 (is_unit_iff_degree_eq_zero.2 $ by have := congr_arg degree hp; simp [degree_C hia, @eq_comm (with_bot ℕ) 0, nat.with_bot.add_eq_zero_iff] at this; clear _fun_match; tauto)) lemma splits_of_degree_eq_one {f : polynomial α} (hf : degree f = 1) : splits i f := or.inr $ λ g hg ⟨p, hp⟩, by have := congr_arg degree hp; simp [nat.with_bot.add_eq_one_iff, hf, @eq_comm (with_bot ℕ) 1, mt is_unit_iff_degree_eq_zero.2 hg.1] at this; clear _fun_match; tauto lemma splits_of_degree_le_one {f : polynomial α} (hf : degree f ≤ 1) : splits i f := begin cases h : degree f with n, { rw [degree_eq_bot.1 h]; exact splits_zero i }, { cases n with n, { rw [eq_C_of_degree_le_zero (trans_rel_right (≤) h (le_refl _))]; exact splits_C _ _ }, { have hn : n = 0, { rw h at hf, cases n, { refl }, { exact absurd hf dec_trivial } }, exact splits_of_degree_eq_one _ (by rw [h, hn]; refl) } } end lemma splits_mul {f g : polynomial α} (hf : splits i f) (hg : splits i g) : splits i (f * g) := if h : f * g = 0 then by simp [h] else or.inr $ λ p hp hpf, ((principal_ideal_ring.irreducible_iff_prime.1 hp).2.2 _ _ (show p ∣ map i f * map i g, by convert hpf; rw polynomial.map_mul)).elim (hf.resolve_left (λ hf, by simpa [hf] using h) hp) (hg.resolve_left (λ hg, by simpa [hg] using h) hp) lemma splits_of_splits_mul {f g : polynomial α} (hfg : f * g ≠ 0) (h : splits i (f * g)) : splits i f ∧ splits i g := ⟨or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw map_mul; exact dvd.trans hg (dvd_mul_right _ _)), or.inr $ λ g hgi hg, or.resolve_left h hfg hgi (by rw map_mul; exact dvd.trans hg (dvd_mul_left _ _))⟩ lemma splits_of_splits_of_dvd {f g : polynomial α} (hf0 : f ≠ 0) (hf : splits i f) (hgf : g ∣ f) : splits i g := by { obtain ⟨f, rfl⟩ := hgf, exact (splits_of_splits_mul i hf0 hf).1 } lemma splits_of_splits_gcd_left {f g : polynomial α} (hf0 : f ≠ 0) (hf : splits i f) : splits i (euclidean_domain.gcd f g) := polynomial.splits_of_splits_of_dvd i hf0 hf (euclidean_domain.gcd_dvd_left f g) lemma splits_of_splits_gcd_right {f g : polynomial α} (hg0 : g ≠ 0) (hg : splits i g) : splits i (euclidean_domain.gcd f g) := polynomial.splits_of_splits_of_dvd i hg0 hg (euclidean_domain.gcd_dvd_right f g) lemma splits_map_iff (j : β →+* γ) {f : polynomial α} : splits j (f.map i) ↔ splits (j.comp i) f := by simp [splits, polynomial.map_map] theorem splits_one : splits i 1 := splits_C i 1 theorem splits_of_is_unit {u : polynomial α} (hu : is_unit u) : u.splits i := splits_of_splits_of_dvd i one_ne_zero (splits_one _) $ is_unit_iff_dvd_one.1 hu theorem splits_X_sub_C {x : α} : (X - C x).splits i := splits_of_degree_eq_one _ $ degree_X_sub_C x theorem splits_id_iff_splits {f : polynomial α} : (f.map i).splits (ring_hom.id β) ↔ f.splits i := by rw [splits_map_iff, ring_hom.id_comp] theorem splits_mul_iff {f g : polynomial α} (hf : f ≠ 0) (hg : g ≠ 0) : (f * g).splits i ↔ f.splits i ∧ g.splits i := ⟨splits_of_splits_mul i (mul_ne_zero hf hg), λ ⟨hfs, hgs⟩, splits_mul i hfs hgs⟩ theorem splits_prod {ι : Type w} {s : ι → polynomial α} {t : finset ι} : (∀ j ∈ t, (s j).splits i) → (∏ x in t, s x).splits i := begin refine finset.induction_on t (λ _, splits_one i) (λ a t hat ih ht, _), rw finset.forall_mem_insert at ht, rw finset.prod_insert hat, exact splits_mul i ht.1 (ih ht.2) end theorem splits_prod_iff {ι : Type w} {s : ι → polynomial α} {t : finset ι} : (∀ j ∈ t, s j ≠ 0) → ((∏ x in t, s x).splits i ↔ ∀ j ∈ t, (s j).splits i) := begin refine finset.induction_on t (λ _, ⟨λ _ _ h, h.elim, λ _, splits_one i⟩) (λ a t hat ih ht, _), rw finset.forall_mem_insert at ht ⊢, rw [finset.prod_insert hat, splits_mul_iff i ht.1 (finset.prod_ne_zero_iff.2 ht.2), ih ht.2] end lemma degree_eq_one_of_irreducible_of_splits {p : polynomial β} (h_nz : p ≠ 0) (hp : irreducible p) (hp_splits : splits (ring_hom.id β) p) : p.degree = 1 := begin rcases hp_splits, { contradiction }, { apply hp_splits hp, simp } end lemma exists_root_of_splits {f : polynomial α} (hs : splits i f) (hf0 : degree f ≠ 0) : ∃ x, eval₂ i x f = 0 := if hf0 : f = 0 then ⟨37, by simp [hf0]⟩ else let ⟨g, hg⟩ := wf_dvd_monoid.exists_irreducible_factor (show ¬ is_unit (f.map i), from mt is_unit_iff_degree_eq_zero.1 (by rwa degree_map)) (map_ne_zero hf0) in let ⟨x, hx⟩ := exists_root_of_degree_eq_one (hs.resolve_left hf0 hg.1 hg.2) in let ⟨i, hi⟩ := hg.2 in ⟨x, by rw [← eval_map, hi, eval_mul, show _ = _, from hx, zero_mul]⟩ lemma exists_multiset_of_splits {f : polynomial α} : splits i f → ∃ (s : multiset β), f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod := suffices splits (ring_hom.id _) (f.map i) → ∃ s : multiset β, f.map i = (C (f.map i).leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod, by rwa [splits_map_iff, leading_coeff_map i] at this, wf_dvd_monoid.induction_on_irreducible (f.map i) (λ _, ⟨{37}, by simp [i.map_zero]⟩) (λ u hu _, ⟨0, by conv_lhs { rw eq_C_of_degree_eq_zero (is_unit_iff_degree_eq_zero.1 hu) }; simp [leading_coeff, nat_degree_eq_of_degree_eq_some (is_unit_iff_degree_eq_zero.1 hu)]⟩) (λ f p hf0 hp ih hfs, have hpf0 : p * f ≠ 0, from mul_ne_zero hp.ne_zero hf0, let ⟨s, hs⟩ := ih (splits_of_splits_mul _ hpf0 hfs).2 in ⟨-(p * norm_unit p).coeff 0 ::ₘ s, have hp1 : degree p = 1, from hfs.resolve_left hpf0 hp (by simp), begin rw [multiset.map_cons, multiset.prod_cons, leading_coeff_mul, C_mul, mul_assoc, mul_left_comm (C f.leading_coeff), ← hs, ← mul_assoc, mul_left_inj' hf0], conv_lhs {rw eq_X_add_C_of_degree_eq_one hp1}, simp only [mul_add, coe_norm_unit hp.ne_zero, mul_comm p, coeff_neg, C_neg, sub_eq_add_neg, neg_neg, coeff_C_mul, (mul_assoc _ _ _).symm, C_mul.symm, mul_inv_cancel (show p.leading_coeff ≠ 0, from mt leading_coeff_eq_zero.1 hp.ne_zero), one_mul], end⟩) /-- Pick a root of a polynomial that splits. -/ def root_of_splits {f : polynomial α} (hf : f.splits i) (hfd : f.degree ≠ 0) : β := classical.some $ exists_root_of_splits i hf hfd theorem map_root_of_splits {f : polynomial α} (hf : f.splits i) (hfd) : f.eval₂ i (root_of_splits i hf hfd) = 0 := classical.some_spec $ exists_root_of_splits i hf hfd theorem roots_map {f : polynomial α} (hf : f.splits $ ring_hom.id α) : (f.map i).roots = (f.roots).map i := if hf0 : f = 0 then by rw [hf0, map_zero, roots_zero, roots_zero, multiset.map_zero] else have hmf0 : f.map i ≠ 0 := map_ne_zero hf0, let ⟨m, hm⟩ := exists_multiset_of_splits _ hf in have h1 : ∀ p ∈ m.map (λ r, X - C r), (p : _) ≠ 0, from multiset.forall_mem_map_iff.2 $ λ _ _, X_sub_C_ne_zero _, have h2 : ∀ p ∈ m.map (λ r, X - C (i r)), (p : _) ≠ 0, from multiset.forall_mem_map_iff.2 $ λ _ _, X_sub_C_ne_zero _, begin rw map_id at hm, rw hm at hf0 hmf0 ⊢, rw map_mul at hmf0 ⊢, rw [roots_mul hf0, roots_mul hmf0, map_C, roots_C, zero_add, roots_C, zero_add, map_multiset_prod, multiset.map_map], simp_rw [(∘), map_sub, map_X, map_C], rw [roots_multiset_prod _ h2, multiset.bind_map, roots_multiset_prod _ h1, multiset.bind_map], simp_rw roots_X_sub_C, rw [multiset.bind_cons, multiset.bind_zero, add_zero, multiset.bind_cons, multiset.bind_zero, add_zero, multiset.map_id'] end lemma eq_prod_roots_of_splits {p : polynomial α} {i : α →+* β} (hsplit : splits i p) : p.map i = C (i p.leading_coeff) * ((p.map i).roots.map (λ a, X - C a)).prod := begin by_cases p_eq_zero : p = 0, { rw [p_eq_zero, map_zero, leading_coeff_zero, i.map_zero, C.map_zero, zero_mul] }, obtain ⟨s, hs⟩ := exists_multiset_of_splits i hsplit, have map_ne_zero : p.map i ≠ 0 := map_ne_zero (p_eq_zero), have prod_ne_zero : C (i p.leading_coeff) * (multiset.map (λ a, X - C a) s).prod ≠ 0 := by rwa hs at map_ne_zero, have ne_zero_of_mem : ∀ (p : polynomial β), p ∈ s.map (λ a, X - C a) → p ≠ 0, { intros p mem, obtain ⟨a, _, rfl⟩ := multiset.mem_map.mp mem, apply X_sub_C_ne_zero }, have map_bind_roots_eq : (s.map (λ a, X - C a)).bind (λ a, a.roots) = s, { refine multiset.induction_on s (by rw [multiset.map_zero, multiset.zero_bind]) _, intros a s ih, rw [multiset.map_cons, multiset.cons_bind, ih, roots_X_sub_C, multiset.cons_add, zero_add] }, rw [hs, roots_mul prod_ne_zero, roots_C, zero_add, roots_multiset_prod _ ne_zero_of_mem, map_bind_roots_eq] end lemma eq_X_sub_C_of_splits_of_single_root {x : α} {h : polynomial α} (h_splits : splits i h) (h_roots : (h.map i).roots = {i x}) : h = (C (leading_coeff h)) * (X - C x) := begin apply polynomial.map_injective _ i.injective, rw [eq_prod_roots_of_splits h_splits, h_roots], simp, end lemma nat_degree_multiset_prod {R : Type*} [integral_domain R] {s : multiset (polynomial R)} (h : ∀ p ∈ s, p ≠ (0 : polynomial R)) : nat_degree s.prod = (s.map nat_degree).sum := begin revert h, refine s.induction_on _ _, { simp }, intros p s ih h, have hs : ∀ p ∈ s, p ≠ (0 : polynomial R) := λ p hp, h p (multiset.mem_cons_of_mem hp), have hprod : s.prod ≠ 0 := multiset.prod_ne_zero (λ p hp, hs p hp), rw [multiset.prod_cons, nat_degree_mul (h p (multiset.mem_cons_self _ _)) hprod, ih hs, multiset.map_cons, multiset.sum_cons], end lemma nat_degree_eq_card_roots {p : polynomial α} {i : α →+* β} (hsplit : splits i p) : p.nat_degree = (p.map i).roots.card := begin by_cases p_eq_zero : p = 0, { rw [p_eq_zero, nat_degree_zero, map_zero, roots_zero, multiset.card_zero] }, have map_ne_zero : p.map i ≠ 0 := map_ne_zero (p_eq_zero), rw eq_prod_roots_of_splits hsplit at map_ne_zero, conv_lhs { rw [← nat_degree_map i, eq_prod_roots_of_splits hsplit] }, have : ∀ p' ∈ (map i p).roots.map (λ a, X - C a), p' ≠ (0 : polynomial β), { intros p hp, obtain ⟨a, ha, rfl⟩ := multiset.mem_map.mp hp, exact X_sub_C_ne_zero _ }, simp [nat_degree_mul (left_ne_zero_of_mul map_ne_zero) (right_ne_zero_of_mul map_ne_zero), nat_degree_multiset_prod this] end lemma degree_eq_card_roots {p : polynomial α} {i : α →+* β} (p_ne_zero : p ≠ 0) (hsplit : splits i p) : p.degree = (p.map i).roots.card := by rw [degree_eq_nat_degree p_ne_zero, nat_degree_eq_card_roots hsplit] section UFD local attribute [instance, priority 10] principal_ideal_ring.to_unique_factorization_monoid local infix ` ~ᵤ ` : 50 := associated open unique_factorization_monoid associates lemma splits_of_exists_multiset {f : polynomial α} {s : multiset β} (hs : f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod) : splits i f := if hf0 : f = 0 then or.inl hf0 else or.inr $ λ p hp hdp, have ht : multiset.rel associated (factors (f.map i)) (s.map (λ a : β, (X : polynomial β) - C a)) := factors_unique (λ p hp, irreducible_of_factor _ hp) (λ p' m, begin obtain ⟨a,m,rfl⟩ := multiset.mem_map.1 m, exact irreducible_of_degree_eq_one (degree_X_sub_C _), end) (associated.symm $ calc _ ~ᵤ f.map i : ⟨(units.map' C : units β →* units (polynomial β)) (units.mk0 (f.map i).leading_coeff (mt leading_coeff_eq_zero.1 (map_ne_zero hf0))), by conv_rhs {rw [hs, ← leading_coeff_map i, mul_comm]}; refl⟩ ... ~ᵤ _ : associated.symm (unique_factorization_monoid.factors_prod (by simpa using hf0))), let ⟨q, hq, hpq⟩ := exists_mem_factors_of_dvd (by simpa) hp hdp in let ⟨q', hq', hqq'⟩ := multiset.exists_mem_of_rel_of_mem ht hq in let ⟨a, ha⟩ := multiset.mem_map.1 hq' in by rw [← degree_X_sub_C a, ha.2]; exact degree_eq_degree_of_associated (hpq.trans hqq') lemma splits_of_splits_id {f : polynomial α} : splits (ring_hom.id _) f → splits i f := unique_factorization_monoid.induction_on_prime f (λ _, splits_zero _) (λ _ hu _, splits_of_degree_le_one _ ((is_unit_iff_degree_eq_zero.1 hu).symm ▸ dec_trivial)) (λ a p ha0 hp ih hfi, splits_mul _ (splits_of_degree_eq_one _ ((splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).1.resolve_left hp.1 (irreducible_of_prime hp) (by rw map_id))) (ih (splits_of_splits_mul _ (mul_ne_zero hp.1 ha0) hfi).2)) end UFD lemma splits_iff_exists_multiset {f : polynomial α} : splits i f ↔ ∃ (s : multiset β), f.map i = C (i f.leading_coeff) * (s.map (λ a : β, (X : polynomial β) - C a)).prod := ⟨exists_multiset_of_splits i, λ ⟨s, hs⟩, splits_of_exists_multiset i hs⟩ lemma splits_comp_of_splits (j : β →+* γ) {f : polynomial α} (h : splits i f) : splits (j.comp i) f := begin change i with ((ring_hom.id _).comp i) at h, rw [← splits_map_iff], rw [← splits_map_iff i] at h, exact splits_of_splits_id _ h end end splits end polynomial section embeddings variables (F : Type*) [field F] /-- If `p` is the minimal polynomial of `a` over `F` then `F[a] ≃ₐ[F] F[x]/(p)` -/ def alg_equiv.adjoin_singleton_equiv_adjoin_root_minimal_polynomial {R : Type*} [comm_ring R] [algebra F R] (x : R) (hx : is_integral F x) : algebra.adjoin F ({x} : set R) ≃ₐ[F] adjoin_root (minimal_polynomial hx) := alg_equiv.symm $ alg_equiv.of_bijective (alg_hom.cod_restrict (adjoin_root.alg_hom _ x $ minimal_polynomial.aeval hx) _ (λ p, adjoin_root.induction_on _ p $ λ p, (algebra.adjoin_singleton_eq_range F x).symm ▸ (polynomial.aeval _).mem_range.mpr ⟨p, rfl⟩)) ⟨(alg_hom.injective_cod_restrict _ _ _).2 $ (alg_hom.injective_iff _).2 $ λ p, adjoin_root.induction_on _ p $ λ p hp, ideal.quotient.eq_zero_iff_mem.2 $ ideal.mem_span_singleton.2 $ minimal_polynomial.dvd hx hp, λ y, let ⟨p, _, hp⟩ := (subalgebra.ext_iff.1 (algebra.adjoin_singleton_eq_range F x) y).1 y.2 in ⟨adjoin_root.mk _ p, subtype.eq hp⟩⟩ open finset -- Speed up the following proof. local attribute [irreducible] minimal_polynomial -- TODO: Why is this so slow? /-- If `K` and `L` are field extensions of `F` and we have `s : finset K` such that the minimal polynomial of each `x ∈ s` splits in `L` then `algebra.adjoin F s` embeds in `L`. -/ theorem lift_of_splits {F K L : Type*} [field F] [field K] [field L] [algebra F K] [algebra F L] (s : finset K) : (∀ x ∈ s, ∃ H : is_integral F x, polynomial.splits (algebra_map F L) (minimal_polynomial H)) → nonempty (algebra.adjoin F (↑s : set K) →ₐ[F] L) := begin refine finset.induction_on s (λ H, _) (λ a s has ih H, _), { rw [coe_empty, algebra.adjoin_empty], exact ⟨(algebra.of_id F L).comp (algebra.bot_equiv F K)⟩ }, rw forall_mem_insert at H, rcases H with ⟨⟨H1, H2⟩, H3⟩, cases ih H3 with f, choose H3 H4 using H3, rw [coe_insert, set.insert_eq, set.union_comm, algebra.adjoin_union], letI := (f : algebra.adjoin F (↑s : set K) →+* L).to_algebra, haveI : finite_dimensional F (algebra.adjoin F (↑s : set K)) := (submodule.fg_iff_finite_dimensional _).1 (fg_adjoin_of_finite (set.finite_mem_finset s) H3), letI := field_of_finite_dimensional F (algebra.adjoin F (↑s : set K)), have H5 : is_integral (algebra.adjoin F (↑s : set K)) a := is_integral_of_is_scalar_tower a H1, have H6 : (minimal_polynomial H5).splits (algebra_map (algebra.adjoin F (↑s : set K)) L), { refine polynomial.splits_of_splits_of_dvd _ (polynomial.map_ne_zero $ minimal_polynomial.ne_zero H1 : polynomial.map (algebra_map _ _) _ ≠ 0) ((polynomial.splits_map_iff _ _).2 _) (minimal_polynomial.dvd _ _), { rw ← is_scalar_tower.algebra_map_eq, exact H2 }, { rw [← is_scalar_tower.aeval_apply, minimal_polynomial.aeval H1] } }, obtain ⟨y, hy⟩ := polynomial.exists_root_of_splits _ H6 (minimal_polynomial.degree_ne_zero H5), exact ⟨subalgebra.of_under _ _ $ (adjoin_root.alg_hom (minimal_polynomial H5) y hy).comp $ alg_equiv.adjoin_singleton_equiv_adjoin_root_minimal_polynomial _ _ H5⟩ end end embeddings namespace polynomial variables [field α] [field β] [field γ] open polynomial section splitting_field /-- Non-computably choose an irreducible factor from a polynomial. -/ def factor (f : polynomial α) : polynomial α := if H : ∃ g, irreducible g ∧ g ∣ f then classical.some H else X instance irreducible_factor (f : polynomial α) : irreducible (factor f) := begin rw factor, split_ifs with H, { exact (classical.some_spec H).1 }, { exact irreducible_X } end theorem factor_dvd_of_not_is_unit {f : polynomial α} (hf1 : ¬is_unit f) : factor f ∣ f := begin by_cases hf2 : f = 0, { rw hf2, exact dvd_zero _ }, rw [factor, dif_pos (wf_dvd_monoid.exists_irreducible_factor hf1 hf2)], exact (classical.some_spec $ wf_dvd_monoid.exists_irreducible_factor hf1 hf2).2 end theorem factor_dvd_of_degree_ne_zero {f : polynomial α} (hf : f.degree ≠ 0) : factor f ∣ f := factor_dvd_of_not_is_unit (mt degree_eq_zero_of_is_unit hf) theorem factor_dvd_of_nat_degree_ne_zero {f : polynomial α} (hf : f.nat_degree ≠ 0) : factor f ∣ f := factor_dvd_of_degree_ne_zero (mt nat_degree_eq_of_degree_eq_some hf) /-- Divide a polynomial f by X - C r where r is a root of f in a bigger field extension. -/ def remove_factor (f : polynomial α) : polynomial (adjoin_root $ factor f) := map (adjoin_root.of f.factor) f /ₘ (X - C (adjoin_root.root f.factor)) theorem X_sub_C_mul_remove_factor (f : polynomial α) (hf : f.nat_degree ≠ 0) : (X - C (adjoin_root.root f.factor)) * f.remove_factor = map (adjoin_root.of f.factor) f := let ⟨g, hg⟩ := factor_dvd_of_nat_degree_ne_zero hf in mul_div_by_monic_eq_iff_is_root.2 $ by rw [is_root.def, eval_map, hg, eval₂_mul, ← hg, adjoin_root.eval₂_root, zero_mul] theorem nat_degree_remove_factor (f : polynomial α) : f.remove_factor.nat_degree = f.nat_degree - 1 := by rw [remove_factor, nat_degree_div_by_monic _ (monic_X_sub_C _), nat_degree_map, nat_degree_X_sub_C] theorem nat_degree_remove_factor' {f : polynomial α} {n : ℕ} (hfn : f.nat_degree = n+1) : f.remove_factor.nat_degree = n := by rw [nat_degree_remove_factor, hfn, n.add_sub_cancel] /-- Auxiliary construction to a splitting field of a polynomial. Uses induction on the degree. -/ def splitting_field_aux (n : ℕ) : Π {α : Type u} [field α], by exactI Π (f : polynomial α), f.nat_degree = n → Type u := nat.rec_on n (λ α _ _ _, α) $ λ n ih α _ f hf, by exactI ih f.remove_factor (nat_degree_remove_factor' hf) namespace splitting_field_aux theorem succ (n : ℕ) (f : polynomial α) (hfn : f.nat_degree = n + 1) : splitting_field_aux (n+1) f hfn = splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn) := rfl instance field (n : ℕ) : Π {α : Type u} [field α], by exactI Π {f : polynomial α} (hfn : f.nat_degree = n), field (splitting_field_aux n f hfn) := nat.rec_on n (λ α _ _ _, ‹field α›) $ λ n ih α _ f hf, ih _ instance inhabited {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n) : inhabited (splitting_field_aux n f hfn) := ⟨37⟩ instance algebra (n : ℕ) : Π {α : Type u} [field α], by exactI Π {f : polynomial α} (hfn : f.nat_degree = n), algebra α (splitting_field_aux n f hfn) := nat.rec_on n (λ α _ _ _, by exactI algebra.id α) $ λ n ih α _ f hfn, by exactI @@algebra.comap.algebra _ _ _ _ _ _ _ (ih _) instance algebra' {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n + 1) : algebra (adjoin_root f.factor) (splitting_field_aux _ _ hfn) := splitting_field_aux.algebra n _ instance algebra'' {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n + 1) : algebra α (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) := splitting_field_aux.algebra (n+1) hfn instance algebra''' {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n + 1) : algebra (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) := splitting_field_aux.algebra n _ instance scalar_tower {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n + 1) : is_scalar_tower α (adjoin_root f.factor) (splitting_field_aux _ _ hfn) := is_scalar_tower.of_algebra_map_eq $ λ x, rfl instance scalar_tower' {n : ℕ} {f : polynomial α} (hfn : f.nat_degree = n + 1) : is_scalar_tower α (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)) := is_scalar_tower.of_algebra_map_eq $ λ x, rfl theorem algebra_map_succ (n : ℕ) (f : polynomial α) (hfn : f.nat_degree = n + 1) : by exact algebra_map α (splitting_field_aux _ _ hfn) = (algebra_map (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn))).comp (adjoin_root.of f.factor) := rfl protected theorem splits (n : ℕ) : ∀ {α : Type u} [field α], by exactI ∀ (f : polynomial α) (hfn : f.nat_degree = n), splits (algebra_map α $ splitting_field_aux n f hfn) f := nat.rec_on n (λ α _ _ hf, by exactI splits_of_degree_le_one _ (le_trans degree_le_nat_degree $ hf.symm ▸ with_bot.coe_le_coe.2 zero_le_one)) $ λ n ih α _ f hf, by { resetI, rw [← splits_id_iff_splits, algebra_map_succ, ← map_map, splits_id_iff_splits, ← X_sub_C_mul_remove_factor f (λ h, by { rw h at hf, cases hf })], exact splits_mul _ (splits_X_sub_C _) (ih _ _) } theorem exists_lift (n : ℕ) : ∀ {α : Type u} [field α], by exactI ∀ (f : polynomial α) (hfn : f.nat_degree = n) {β : Type*} [field β], by exactI ∀ (j : α →+* β) (hf : splits j f), ∃ k : splitting_field_aux n f hfn →+* β, k.comp (algebra_map _ _) = j := nat.rec_on n (λ α _ _ _ β _ j _, by exactI ⟨j, j.comp_id⟩) $ λ n ih α _ f hf β _ j hj, by exactI have hndf : f.nat_degree ≠ 0, by { intro h, rw h at hf, cases hf }, have hfn0 : f ≠ 0, by { intro h, rw h at hndf, exact hndf rfl }, let ⟨r, hr⟩ := exists_root_of_splits _ (splits_of_splits_of_dvd j hfn0 hj (factor_dvd_of_nat_degree_ne_zero hndf)) (mt is_unit_iff_degree_eq_zero.2 f.irreducible_factor.1) in have hmf0 : map (adjoin_root.of f.factor) f ≠ 0, from map_ne_zero hfn0, have hsf : splits (adjoin_root.lift j r hr) f.remove_factor, by { rw ← X_sub_C_mul_remove_factor _ hndf at hmf0, refine (splits_of_splits_mul _ hmf0 _).2, rwa [X_sub_C_mul_remove_factor _ hndf, ← splits_id_iff_splits, map_map, adjoin_root.lift_comp_of, splits_id_iff_splits] }, let ⟨k, hk⟩ := ih f.remove_factor (nat_degree_remove_factor' hf) (adjoin_root.lift j r hr) hsf in ⟨k, by rw [algebra_map_succ, ← ring_hom.comp_assoc, hk, adjoin_root.lift_comp_of]⟩ theorem adjoin_roots (n : ℕ) : ∀ {α : Type u} [field α], by exactI ∀ (f : polynomial α) (hfn : f.nat_degree = n), algebra.adjoin α (↑(f.map $ algebra_map α $ splitting_field_aux n f hfn).roots.to_finset : set (splitting_field_aux n f hfn)) = ⊤ := nat.rec_on n (λ α _ f hf, by exactI algebra.eq_top_iff.2 (λ x, subalgebra.range_le _ ⟨x, rfl⟩)) $ λ n ih α _ f hfn, by exactI have hndf : f.nat_degree ≠ 0, by { intro h, rw h at hfn, cases hfn }, have hfn0 : f ≠ 0, by { intro h, rw h at hndf, exact hndf rfl }, have hmf0 : map (algebra_map α (splitting_field_aux n.succ f hfn)) f ≠ 0 := map_ne_zero hfn0, by { rw [algebra_map_succ, ← map_map, ← X_sub_C_mul_remove_factor _ hndf, map_mul] at hmf0 ⊢, rw [roots_mul hmf0, map_sub, map_X, map_C, roots_X_sub_C, multiset.to_finset_add, finset.coe_union, multiset.to_finset_cons, multiset.to_finset_zero, insert_emptyc_eq, finset.coe_singleton, algebra.adjoin_union, ← set.image_singleton, algebra.adjoin_algebra_map α (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)), adjoin_root.adjoin_root_eq_top, algebra.map_top, is_scalar_tower.range_under_adjoin α (adjoin_root f.factor) (splitting_field_aux n f.remove_factor (nat_degree_remove_factor' hfn)), ih, subalgebra.res_top] } end splitting_field_aux /-- A splitting field of a polynomial. -/ def splitting_field (f : polynomial α) := splitting_field_aux _ f rfl namespace splitting_field variables (f : polynomial α) instance : field (splitting_field f) := splitting_field_aux.field _ _ instance inhabited : inhabited (splitting_field f) := ⟨37⟩ instance : algebra α (splitting_field f) := splitting_field_aux.algebra _ _ protected theorem splits : splits (algebra_map α (splitting_field f)) f := splitting_field_aux.splits _ _ _ variables [algebra α β] (hb : splits (algebra_map α β) f) /-- Embeds the splitting field into any other field that splits the polynomial. -/ def lift : splitting_field f →ₐ[α] β := { commutes' := λ r, by { have := classical.some_spec (splitting_field_aux.exists_lift _ _ _ _ hb), exact ring_hom.ext_iff.1 this r }, .. classical.some (splitting_field_aux.exists_lift _ _ _ _ hb) } theorem adjoin_roots : algebra.adjoin α (↑(f.map (algebra_map α $ splitting_field f)).roots.to_finset : set (splitting_field f)) = ⊤ := splitting_field_aux.adjoin_roots _ _ _ end splitting_field variables (α β) [algebra α β] /-- Typeclass characterising splitting fields. -/ class is_splitting_field (f : polynomial α) : Prop := (splits [] : splits (algebra_map α β) f) (adjoin_roots [] : algebra.adjoin α (↑(f.map (algebra_map α β)).roots.to_finset : set β) = ⊤) namespace is_splitting_field variables {α} instance splitting_field (f : polynomial α) : is_splitting_field α (splitting_field f) f := ⟨splitting_field.splits f, splitting_field.adjoin_roots f⟩ section scalar_tower variables {α β γ} [algebra β γ] [algebra α γ] [is_scalar_tower α β γ] variables {α} instance map (f : polynomial α) [is_splitting_field α γ f] : is_splitting_field β γ (f.map $ algebra_map α β) := ⟨by { rw [splits_map_iff, ← is_scalar_tower.algebra_map_eq], exact splits γ f }, subalgebra.res_inj α $ by { rw [map_map, ← is_scalar_tower.algebra_map_eq, subalgebra.res_top, eq_top_iff, ← adjoin_roots γ f, algebra.adjoin_le_iff], exact λ x hx, @algebra.subset_adjoin β _ _ _ _ _ _ hx }⟩ variables {α} (β) theorem splits_iff (f : polynomial α) [is_splitting_field α β f] : polynomial.splits (ring_hom.id α) f ↔ (⊤ : subalgebra α β) = ⊥ := ⟨λ h, eq_bot_iff.2 $ adjoin_roots β f ▸ (roots_map (algebra_map α β) h).symm ▸ algebra.adjoin_le_iff.2 (λ y hy, let ⟨x, hxs, hxy⟩ := finset.mem_image.1 (by rwa multiset.to_finset_map at hy) in hxy ▸ subalgebra.algebra_map_mem _ _), λ h, @ring_equiv.to_ring_hom_refl α _ ▸ ring_equiv.trans_symm (ring_equiv.of_bijective _ $ algebra.bijective_algebra_map_iff.2 h) ▸ by { rw ring_equiv.to_ring_hom_trans, exact splits_comp_of_splits _ _ (splits β f) }⟩ theorem mul (f g : polynomial α) (hf : f ≠ 0) (hg : g ≠ 0) [is_splitting_field α β f] [is_splitting_field β γ (g.map $ algebra_map α β)] : is_splitting_field α γ (f * g) := ⟨(is_scalar_tower.algebra_map_eq α β γ).symm ▸ splits_mul _ (splits_comp_of_splits _ _ (splits β f)) ((splits_map_iff _ _).1 (splits γ $ g.map $ algebra_map α β)), by rw [map_mul, roots_mul (mul_ne_zero (map_ne_zero hf : f.map (algebra_map α γ) ≠ 0) (map_ne_zero hg)), multiset.to_finset_add, finset.coe_union, algebra.adjoin_union, is_scalar_tower.algebra_map_eq α β γ, ← map_map, roots_map (algebra_map β γ) ((splits_id_iff_splits $ algebra_map α β).2 $ splits β f), multiset.to_finset_map, finset.coe_image, algebra.adjoin_algebra_map, adjoin_roots, algebra.map_top, is_scalar_tower.range_under_adjoin, ← map_map, adjoin_roots, subalgebra.res_top]⟩ end scalar_tower /-- Splitting field of `f` embeds into any field that splits `f`. -/ def lift [algebra α γ] (f : polynomial α) [is_splitting_field α β f] (hf : polynomial.splits (algebra_map α γ) f) : β →ₐ[α] γ := if hf0 : f = 0 then (algebra.of_id α γ).comp $ (algebra.bot_equiv α β : (⊥ : subalgebra α β) →ₐ[α] α).comp $ by { rw ← (splits_iff β f).1 (show f.splits (ring_hom.id α), from hf0.symm ▸ splits_zero _), exact algebra.to_top } else alg_hom.comp (by { rw ← adjoin_roots β f, exact classical.choice (lift_of_splits _ $ λ y hy, have aeval y f = 0, from (eval₂_eq_eval_map _).trans $ (mem_roots $ by exact map_ne_zero hf0).1 (multiset.mem_to_finset.mp hy), ⟨(is_algebraic_iff_is_integral _).1 ⟨f, hf0, this⟩, splits_of_splits_of_dvd _ hf0 hf $ minimal_polynomial.dvd _ this⟩) }) algebra.to_top theorem finite_dimensional (f : polynomial α) [is_splitting_field α β f] : finite_dimensional α β := finite_dimensional.iff_fg.2 $ @algebra.coe_top α β _ _ _ ▸ adjoin_roots β f ▸ fg_adjoin_of_finite (set.finite_mem_finset _) (λ y hy, if hf : f = 0 then by { rw [hf, map_zero, roots_zero] at hy, cases hy } else (is_algebraic_iff_is_integral _).1 ⟨f, hf, (eval₂_eq_eval_map _).trans $ (mem_roots $ by exact map_ne_zero hf).1 (multiset.mem_to_finset.mp hy)⟩) /-- Any splitting field is isomorphic to `splitting_field f`. -/ def alg_equiv (f : polynomial α) [is_splitting_field α β f] : β ≃ₐ[α] splitting_field f := begin refine alg_equiv.of_bijective (lift β f $ splits (splitting_field f) f) ⟨ring_hom.injective (lift β f $ splits (splitting_field f) f).to_ring_hom, _⟩, haveI := finite_dimensional (splitting_field f) f, haveI := finite_dimensional β f, have : finite_dimensional.findim α β = finite_dimensional.findim α (splitting_field f) := le_antisymm (linear_map.findim_le_findim_of_injective (show function.injective (lift β f $ splits (splitting_field f) f).to_linear_map, from ring_hom.injective (lift β f $ splits (splitting_field f) f : β →+* f.splitting_field))) (linear_map.findim_le_findim_of_injective (show function.injective (lift (splitting_field f) f $ splits β f).to_linear_map, from ring_hom.injective (lift (splitting_field f) f $ splits β f : f.splitting_field →+* β))), change function.surjective (lift β f $ splits (splitting_field f) f).to_linear_map, refine (linear_map.injective_iff_surjective_of_findim_eq_findim this).1 _, exact ring_hom.injective (lift β f $ splits (splitting_field f) f : β →+* f.splitting_field) end end is_splitting_field end splitting_field end polynomial
8728fcde33c41f3521ae550ae887babf498ba391
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/coe.lean
e530f66867f6b22b4e8463478a1c75dcf72f4411
[ "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
263
lean
import logic set_option pp.notation false inductive Functor := mk : (Π (A B : Type), A → B) → Functor definition Functor.to_fun [coercion] (f : Functor) {A B : Type} : A → B := Functor.rec (λ f, f) f A B constant f : Functor check f (0:num) = (0:num)
2a1c4cf19cd5dc9072f51534615ac08e7909132c
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/tests/lean/run/meta5.lean
4d9055705af482180ab08d34908ac19b0277b00e
[ "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
636
lean
import Lean.Meta open Lean open Lean.Meta def tst1 : MetaM Unit := withLocalDeclD `y (mkConst `Nat) $ fun y => do withLetDecl `x (mkConst `Nat) (mkNatLit 0) $ fun x => do { let mvar ← mkFreshExprMVar (mkConst `Nat) MetavarKind.syntheticOpaque; trace[Meta.debug] mvar; let r ← mkLambdaFVars #[y, x] mvar; trace[Message.debug] r; let v := mkApp2 (mkConst `Nat.add) x y; assignExprMVar mvar.mvarId! v; trace[Meta.debug] mvar; trace[Meta.debug] r; let mctx ← getMCtx; mctx.decls.forM fun mvarId mvarDecl => do trace[Meta.debug] m!"?{mvarId} : {mvarDecl.type}" } set_option trace.Meta.debug true #eval tst1
5a68122582a0db3e5315b4008adc62cd435df4f8
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/polynomial/erase_lead.lean
22937302bd4e18537f46c5b126f6af5d1e0f6ae8
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
9,531
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.degree.definitions /-! # Erase the leading term of a univariate polynomial ## Definition * `erase_lead f`: the polynomial `f - leading term of f` `erase_lead` serves as reduction step in an induction, shaving off one monomial from a polynomial. The definition is set up so that it does not mention subtraction in the definition, and thus works for polynomials over semirings as well as rings. -/ noncomputable theory open_locale classical open polynomial finset namespace polynomial variables {R : Type*} [semiring R] {f : polynomial R} /-- `erase_lead f` for a polynomial `f` is the polynomial obtained by subtracting from `f` the leading term of `f`. -/ def erase_lead (f : polynomial R) : polynomial R := polynomial.erase f.nat_degree f section erase_lead lemma erase_lead_support (f : polynomial R) : f.erase_lead.support = f.support.erase f.nat_degree := by simp only [erase_lead, support_erase] lemma erase_lead_coeff (i : ℕ) : f.erase_lead.coeff i = if i = f.nat_degree then 0 else f.coeff i := by simp only [erase_lead, coeff_erase] @[simp] lemma erase_lead_coeff_nat_degree : f.erase_lead.coeff f.nat_degree = 0 := by simp [erase_lead_coeff] lemma erase_lead_coeff_of_ne (i : ℕ) (hi : i ≠ f.nat_degree) : f.erase_lead.coeff i = f.coeff i := by simp [erase_lead_coeff, hi] @[simp] lemma erase_lead_zero : erase_lead (0 : polynomial R) = 0 := by simp only [erase_lead, erase_zero] @[simp] lemma erase_lead_add_monomial_nat_degree_leading_coeff (f : polynomial R) : f.erase_lead + monomial f.nat_degree f.leading_coeff = f := begin ext i, simp only [erase_lead_coeff, coeff_monomial, coeff_add, @eq_comm _ _ i], split_ifs with h, { subst i, simp only [leading_coeff, zero_add] }, { exact add_zero _ } end @[simp] lemma erase_lead_add_C_mul_X_pow (f : polynomial R) : f.erase_lead + (C f.leading_coeff) * X ^ f.nat_degree = f := by rw [C_mul_X_pow_eq_monomial, erase_lead_add_monomial_nat_degree_leading_coeff] @[simp] lemma self_sub_monomial_nat_degree_leading_coeff {R : Type*} [ring R] (f : polynomial R) : f - monomial f.nat_degree f.leading_coeff = f.erase_lead := (eq_sub_iff_add_eq.mpr (erase_lead_add_monomial_nat_degree_leading_coeff f)).symm @[simp] lemma self_sub_C_mul_X_pow {R : Type*} [ring R] (f : polynomial R) : f - (C f.leading_coeff) * X ^ f.nat_degree = f.erase_lead := by rw [C_mul_X_pow_eq_monomial, self_sub_monomial_nat_degree_leading_coeff] lemma erase_lead_ne_zero (f0 : 2 ≤ f.support.card) : erase_lead f ≠ 0 := begin rw [ne.def, ← card_support_eq_zero, erase_lead_support], exact (zero_lt_one.trans_le $ (tsub_le_tsub_right f0 1).trans finset.pred_card_le_card_erase).ne.symm end @[simp] lemma nat_degree_not_mem_erase_lead_support : f.nat_degree ∉ (erase_lead f).support := by simp [not_mem_support_iff] lemma ne_nat_degree_of_mem_erase_lead_support {a : ℕ} (h : a ∈ (erase_lead f).support) : a ≠ f.nat_degree := by { rintro rfl, exact nat_degree_not_mem_erase_lead_support h } lemma erase_lead_support_card_lt (h : f ≠ 0) : (erase_lead f).support.card < f.support.card := begin rw erase_lead_support, exact card_lt_card (erase_ssubset $ nat_degree_mem_support_of_nonzero h) end lemma erase_lead_card_support {c : ℕ} (fc : f.support.card = c) : f.erase_lead.support.card = c - 1 := begin by_cases f0 : f = 0, { rw [← fc, f0, erase_lead_zero, support_zero, card_empty] }, { rw [erase_lead_support, card_erase_of_mem (nat_degree_mem_support_of_nonzero f0), fc], exact c.pred_eq_sub_one }, end lemma erase_lead_card_support' {c : ℕ} (fc : f.support.card = c + 1) : f.erase_lead.support.card = c := erase_lead_card_support fc @[simp] lemma erase_lead_monomial (i : ℕ) (r : R) : erase_lead (monomial i r) = 0 := begin by_cases hr : r = 0, { subst r, simp only [monomial_zero_right, erase_lead_zero] }, { rw [erase_lead, nat_degree_monomial, if_neg hr, erase_monomial] } end @[simp] lemma erase_lead_C (r : R) : erase_lead (C r) = 0 := erase_lead_monomial _ _ @[simp] lemma erase_lead_X : erase_lead (X : polynomial R) = 0 := erase_lead_monomial _ _ @[simp] lemma erase_lead_X_pow (n : ℕ) : erase_lead (X ^ n : polynomial R) = 0 := by rw [X_pow_eq_monomial, erase_lead_monomial] @[simp] lemma erase_lead_C_mul_X_pow (r : R) (n : ℕ) : erase_lead (C r * X ^ n) = 0 := by rw [C_mul_X_pow_eq_monomial, erase_lead_monomial] lemma erase_lead_degree_le : (erase_lead f).degree ≤ f.degree := begin rw degree_le_iff_coeff_zero, intros i hi, rw erase_lead_coeff, split_ifs with h, { refl }, apply coeff_eq_zero_of_degree_lt hi end lemma erase_lead_nat_degree_le : (erase_lead f).nat_degree ≤ f.nat_degree := nat_degree_le_nat_degree erase_lead_degree_le lemma erase_lead_nat_degree_lt (f0 : 2 ≤ f.support.card) : (erase_lead f).nat_degree < f.nat_degree := lt_of_le_of_ne erase_lead_nat_degree_le $ ne_nat_degree_of_mem_erase_lead_support $ nat_degree_mem_support_of_nonzero $ erase_lead_ne_zero f0 lemma erase_lead_nat_degree_lt_or_erase_lead_eq_zero (f : polynomial R) : (erase_lead f).nat_degree < f.nat_degree ∨ f.erase_lead = 0 := begin by_cases h : f.support.card ≤ 1, { right, rw ← C_mul_X_pow_eq_self h, simp }, { left, apply erase_lead_nat_degree_lt (lt_of_not_ge h) } end end erase_lead /-- An induction lemma for polynomials. It takes a natural number `N` as a parameter, that is required to be at least as big as the `nat_degree` of the polynomial. This is useful to prove results where you want to change each term in a polynomial to something else depending on the `nat_degree` of the polynomial itself and not on the specific `nat_degree` of each term. -/ lemma induction_with_nat_degree_le (P : polynomial R → Prop) (N : ℕ) (P_0 : P 0) (P_C_mul_pow : ∀ n : ℕ, ∀ r : R, r ≠ 0 → n ≤ N → P (C r * X ^ n)) (P_C_add : ∀ f g : polynomial R, f.nat_degree < g.nat_degree → g.nat_degree ≤ N → P f → P g → P (f + g)) : ∀ f : polynomial R, f.nat_degree ≤ N → P f := begin intros f df, generalize' hd : card f.support = c, revert f, induction c with c hc, { assume f df f0, convert P_0, simpa only [support_eq_empty, card_eq_zero] using f0 }, { intros f df f0, rw [← erase_lead_add_C_mul_X_pow f], cases c, { convert P_C_mul_pow f.nat_degree f.leading_coeff _ df, { convert zero_add _, rw [← card_support_eq_zero, erase_lead_card_support f0] }, { rw [leading_coeff_ne_zero, ne.def, ← card_support_eq_zero, f0], exact zero_ne_one.symm } }, refine P_C_add f.erase_lead _ _ _ _ _, { refine (erase_lead_nat_degree_lt _).trans_le (le_of_eq _), { exact (nat.succ_le_succ (nat.succ_le_succ (nat.zero_le _))).trans f0.ge }, { rw [nat_degree_C_mul_X_pow _ _ (leading_coeff_ne_zero.mpr _)], rintro rfl, simpa using f0 } }, { exact (nat_degree_C_mul_X_pow_le f.leading_coeff f.nat_degree).trans df }, { exact hc _ (erase_lead_nat_degree_le.trans df) (erase_lead_card_support f0) }, { refine P_C_mul_pow _ _ _ df, rw [ne.def, leading_coeff_eq_zero, ← card_support_eq_zero, f0], exact nat.succ_ne_zero _ } } end /-- Let `φ : R[x] → S[x]` be an additive map, `k : ℕ` a bound, and `fu : ℕ → ℕ` a "sufficiently monotone" map. Assume also that * `φ` maps to `0` all monomials of degree less than `k`, * `φ` maps each monomial `m` in `R[x]` to a polynomial `φ m` of degree `fu (deg m)`. Then, `φ` maps each polynomial `p` in `R[x]` to a polynomial of degree `fu (deg p)`. -/ lemma mono_map_nat_degree_eq {S F : Type*} [semiring S] [add_monoid_hom_class F (polynomial R) (polynomial S)] {φ : F} {p : polynomial R} (k : ℕ) (fu : ℕ → ℕ) (fu0 : ∀ {n}, n ≤ k → fu n = 0) (fc : ∀ {n m}, k ≤ n → n < m → fu n < fu m) (φ_k : ∀ {f : polynomial R}, f.nat_degree < k → φ f = 0) (φ_mon_nat : ∀ n c, c ≠ 0 → (φ (monomial n c)).nat_degree = fu n) : (φ p).nat_degree = fu p.nat_degree := begin refine induction_with_nat_degree_le (λ p, _ = fu _) p.nat_degree (by simp [fu0]) _ _ _ rfl.le, { intros n r r0 np, rw [nat_degree_C_mul_X_pow _ _ r0, ← monomial_eq_C_mul_X, φ_mon_nat _ _ r0] }, { intros f g fg gp fk gk, rw [nat_degree_add_eq_right_of_nat_degree_lt fg, _root_.map_add], by_cases FG : k ≤ f.nat_degree, { rw [nat_degree_add_eq_right_of_nat_degree_lt, gk], rw [fk, gk], exact fc FG fg }, { cases k, { exact (FG (nat.zero_le _)).elim }, { rwa [φ_k (not_le.mp FG), zero_add] } } } end lemma map_nat_degree_eq_sub {S F : Type*} [semiring S] [add_monoid_hom_class F (polynomial R) (polynomial S)] {φ : F} {p : polynomial R} {k : ℕ} (φ_k : ∀ f : polynomial R, f.nat_degree < k → φ f = 0) (φ_mon : ∀ n c, c ≠ 0 → (φ (monomial n c)).nat_degree = n - k) : (φ p).nat_degree = p.nat_degree - k := mono_map_nat_degree_eq k (λ j, j - k) (by simp) (λ m n h, (tsub_lt_tsub_iff_right h).mpr) φ_k φ_mon lemma map_nat_degree_eq_nat_degree {S F : Type*} [semiring S] [add_monoid_hom_class F (polynomial R) (polynomial S)] {φ : F} (p) (φ_mon_nat : ∀ n c, c ≠ 0 → (φ (monomial n c)).nat_degree = n) : (φ p).nat_degree = p.nat_degree := (map_nat_degree_eq_sub (λ f h, (nat.not_lt_zero _ h).elim) (by simpa)).trans p.nat_degree.sub_zero end polynomial
810157a811b9a097324985b4f2c9a0cae2d93a95
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/423.lean
2332ef6f677416e228912bf2ff187ebf2640fa38
[ "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
115
lean
universe u #check fun {T : Sort u} (a : T) => a + 0 #check fun {T : Sort u} (a : T) [Add T] [OfNat T 0] => a + 0
a878dd611fd9663861eba30bcfa6285385376ab1
ea5678cc400c34ff95b661fa26d15024e27ea8cd
/univariate_poly_dif.lean
3d4de222b0c1b041d47770fbb6e4e775271db931
[]
no_license
ChrisHughes24/leanstuff
dca0b5349c3ed893e8792ffbd98cbcadaff20411
9efa85f72efaccd1d540385952a6acc18fce8687
refs/heads/master
1,654,883,241,759
1,652,873,885,000
1,652,873,885,000
134,599,537
1
0
null
null
null
null
UTF-8
Lean
false
false
32,373
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes Theory of univariate polynomials, represented as finsupps, ℕ →₀ α, with α a comm_semiring -/ import data.finsupp algebra.euclidean_domain open finsupp finset lattice set_option old_structure_cmd true class nonzero_comm_ring (α : Type*) extends zero_ne_one_class α, comm_ring α instance integral_domain.to_nonzero_comm_ring (α : Type*) [hd : integral_domain α] : nonzero_comm_ring α := { ..hd } namespace finset lemma sup_lt_nat : ∀ {s t : finset ℕ}, s ⊆ t → t.sup id ∉ s → 0 < t.sup id → s.sup id < t.sup id := λ s, finset.induction_on s (λ _ _ _, id) begin assume a s has ih t hst hsup hpos, rw finset.sup_insert, exact max_lt_iff.2 ⟨lt_of_le_of_ne (finset.le_sup (hst (finset.mem_insert_self _ _))) (λ h, by simpa [h.symm] using hsup), ih (λ a ha, hst (finset.mem_insert_of_mem ha)) (hsup ∘ finset.mem_insert_of_mem) hpos⟩, end lemma sup_mem_nat {s : finset ℕ} : s ≠ ∅ → s.sup id ∈ s := finset.induction_on s (by simp * at *) $ begin assume a s has ih _, by_cases h₁ : s = ∅, { simp * }, { cases (le_total a (s.sup id)) with h₂ h₂, { simp [lattice.sup_of_le_right h₂, ih h₁] }, { simp [lattice.sup_of_le_left h₂] } } end end finset namespace finsupp @[simp] lemma erase_single {α β : Type*} [decidable_eq α] [decidable_eq β] [has_zero β] (a : α) (b : β) : (single a b).erase a = (0 : α →₀ β) := ext (λ x, begin by_cases hxa : x = a, { simp [hxa, erase_same] }, { simp [erase_ne hxa, single_apply, if_neg (ne.symm hxa)] }, end) end finsupp def polynomial (α : Type*) [comm_semiring α] := ℕ →₀ α namespace polynomial variables {α : Type*} {a b : α} {m n : ℕ} variables [decidable_eq α] section comm_semiring variables [comm_semiring α] {p q : polynomial α} instance : has_coe_to_fun (polynomial α) := finsupp.has_coe_to_fun instance : has_zero (polynomial α) := finsupp.has_zero instance : has_one (polynomial α) := finsupp.has_one instance : has_add (polynomial α) := finsupp.has_add instance : has_mul (polynomial α) := finsupp.has_mul instance : comm_semiring (polynomial α) := finsupp.to_comm_semiring local attribute [instance] finsupp.to_comm_semiring /-- `monomial n a` is the polynomial `a * X^n` -/ def monomial (n : ℕ) (a : α) : polynomial α := single n a /-- `C a` is the constant polynomial a -/ def C (a : α) : polynomial α := monomial 0 a /-- `X` is the polynomial whose evaluation is the identity funtion -/ def X : polynomial α := monomial 1 1 @[simp] lemma C_0 : C 0 = (0 : polynomial α) := by simp [C, monomial]; refl @[simp] lemma C_1 : C 1 = (1 : polynomial α) := rfl @[simp] lemma C_mul_monomial : C a * monomial n b = monomial n (a * b) := by simp [C, monomial, single_mul_single] @[simp] lemma C_mul_C : C a * C b = C (a * b) := by simp [C, monomial, single_mul_single] @[simp] lemma monomial_mul_monomial : monomial n a * monomial m b = monomial (n + m) (a * b) := single_mul_single @[simp] lemma monomial_zero_right (n : ℕ) : monomial n (0 : α) = 0 := finsupp.ext $ λ a, show ite _ _ _ = (0 : α), by split_ifs; simp lemma X_pow_eq_monomial : (X : polynomial α) ^ n = monomial n (1 : α) := by induction n; simp [X, C_1.symm, -C_1, C, pow_succ, *] at * lemma monomial_add_right : monomial (n + m) a = (monomial n a * X ^ m):= by rw [X_pow_eq_monomial, monomial, monomial, monomial, single_mul_single]; simp lemma monomial_add_left : monomial (m + n) a = (X ^ m * monomial n a):= by rw [X_pow_eq_monomial, monomial, monomial, monomial, single_mul_single]; simp lemma monomial_eq : monomial n a = C a * X ^ n := by rw [X_pow_eq_monomial, C_mul_monomial, mul_one] lemma erase_monomial : (monomial n a).erase n = 0 := finsupp.erase_single _ _ @[elab_as_eliminator] lemma induction_on {M : polynomial α → Prop} (p : polynomial α) (h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_X : ∀(n : ℕ) (a : α), M (monomial n a) → M (monomial n a * X)) : M p := have ∀n a, M (monomial n a), begin assume n a, induction n with n ih, { exact h_C _ }, { rw [← nat.add_one, monomial_add_right, pow_one], exact h_X _ _ ih } end, finsupp.induction p (show M (0 : polynomial α), by rw ← C_0; exact h_C 0) $ λ n a f hfn ha ih, (show M (monomial n a + f), from h_add _ _ (this _ _) ih) lemma monomial_apply : @coe_fn (polynomial α) polynomial.has_coe_to_fun (monomial n a) m = ite (n = m) a 0 := finsupp.single_apply lemma monomial_apply_self : @coe_fn (polynomial α) polynomial.has_coe_to_fun (monomial n a) n = a := by simp [monomial_apply] lemma C_apply : @coe_fn (polynomial α) polynomial.has_coe_to_fun (C a) n = ite (0 = n) a 0 := finsupp.single_apply lemma add_apply (p q : polynomial α) (n : ℕ) : (p + q) n = p n + q n := add_apply @[simp] lemma C_mul_apply (p : polynomial α) : (C a * p) n = a * p n := induction_on p (λ b, show (monomial 0 a * monomial 0 b) n = a * @coe_fn (polynomial α) polynomial.has_coe_to_fun (monomial 0 b) n, begin rw [monomial_mul_monomial, monomial_apply, monomial_apply], split_ifs; simp end) begin intros, rw [mul_add, add_apply, add_apply, mul_add], simp *, end begin intros, rw [X, monomial_mul_monomial, C, monomial_mul_monomial, monomial_apply, monomial_apply], split_ifs; simp * at *, end @[elab_as_eliminator] lemma monomial_induction_on {M : polynomial α → Prop} (p : polynomial α) (h0 : M 0) (h : ∀ (n : ℕ) (a : α) (p : polynomial α), p n = 0 → a ≠ 0 → M p → M (monomial n a + p)) : M p := finsupp.induction p h0 (λ n a p hpn, h n a p (by rwa [mem_support_iff, ne.def, not_not] at hpn)) section eval variable {x : α} /-- `eval x p` is the evaluation of the polynomial x at p -/ def eval (x : α) (p : polynomial α) : α := p.sum (λ e a, a * x ^ e) @[simp] lemma eval_zero : (0 : polynomial α).eval x = 0 := finsupp.sum_zero_index lemma eval_add : (p + q).eval x = p.eval x + q.eval x := finsupp.sum_add_index (by simp) (by simp [add_mul]) lemma eval_monomial : (monomial n a).eval x = a * x ^ n := finsupp.sum_single_index (zero_mul _) @[simp] lemma eval_C : (C a).eval x = a := by simp [eval_monomial, C, prod_zero_index] @[simp] lemma eval_X : X.eval x = x := by simp [eval_monomial, X, prod_single_index, pow_one] lemma eval_mul_monomial : ∀{n a}, (p * monomial n a).eval x = p.eval x * a * x ^ n := begin apply polynomial.induction_on p, { assume a' s a, by simp [C_mul_monomial, eval_monomial] }, { assume p q ih_p ih_q, simp [add_mul, eval_add, ih_p, ih_q] }, { assume m b ih n a, unfold X, rw [mul_assoc, ih, monomial_mul_monomial, ih, pow_add], simp [mul_assoc, mul_comm, mul_left_comm] } end lemma eval_mul : ∀{p}, (p * q).eval x = p.eval x * q.eval x := begin apply polynomial.induction_on q, { simp [C, eval_monomial, eval_mul_monomial, prod_zero_index] }, { simp [mul_add, eval_add] {contextual := tt} }, { simp [X, eval_monomial, eval_mul_monomial, (mul_assoc _ _ _).symm] { contextual := tt} } end /-- `is_root p x` implies `x` is a root of `p`. The evaluation of `p` at `x` is zero -/ def is_root (p : polynomial α) (a : α) : Prop := p.eval a = 0 instance : decidable (is_root p a) := by unfold is_root; apply_instance lemma is_root.def : is_root p a ↔ p.eval a = 0 := iff.rfl lemma root_mul_left_of_is_root (q : polynomial α) : is_root p a → is_root (q * p) a := by simp [is_root.def, eval_mul] {contextual := tt} lemma root_mul_right_of_is_root (q : polynomial α) : is_root p a → is_root (p * q) a := by simp [is_root.def, eval_mul] {contextual := tt} end eval /-- `degree p` gives the highest power of `X` that appears in `p` -/ def degree (p : polynomial α) : with_bot ℕ := p.support.sup some /-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/ def leading_coeff (p : polynomial α) : α := option.cases_on (degree p) 0 p /-- a polynomial is `monic` if its leading coefficient is 1 -/ def monic (p : polynomial α) := leading_coeff p = (1 : α) lemma monic.def : monic p ↔ leading_coeff p = 1 := iff.rfl instance monic.decidable : decidable (monic p) := by unfold monic; apply_instance @[simp] lemma degree_zero : degree (0 : polynomial α) = ⊥ := rfl lemma degree_C {a : α} (ha : a ≠ 0) : degree (C a) = (0 : with_bot ℕ) := begin unfold C single monomial degree finsupp.support, rw if_neg ha, refl end lemma degree_monomial_le (n : ℕ) (a : α) : degree (monomial n a) ≤ n := begin unfold single monomial degree finsupp.support, by_cases a = 0; simp [*, sup]; refl end @[simp] lemma degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (monomial n a) = n := begin unfold X single monomial degree finsupp.support, rw if_neg ha, simp [sup] end lemma le_degree_of_ne_zero (h : p n ≠ 0) : n ≤ degree p := show id n ≤ p.support.sup id, from finset.le_sup ((finsupp.mem_support_iff _ _).2 h) lemma eq_zero_of_degree_lt (h : degree p < n) : p n = 0 := not_not.1 (mt le_degree_of_ne_zero (not_le_of_gt h)) lemma eq_C_of_degree_eq_zero (h : degree p = 0) : p = C (p 0) := ext begin assume n, cases n, { refl }, { have h : degree p < nat.succ n := h.symm ▸ nat.succ_pos _, rw [eq_zero_of_degree_lt h, C_apply, if_neg], exact λ h, nat.no_confusion h } end lemma degree_add_le (p q : polynomial α) : degree (p + q) ≤ max (degree p) (degree q) := show _ ≤ (finset.sup (p.support) id) ⊔ (finset.sup (q.support) id), by rw ← finset.sup_union; exact finset.sup_mono support_add @[simp] lemma leading_coeff_zero : leading_coeff (0 : polynomial α) = 0 := rfl @[simp] lemma leading_coeff_eq_zero : leading_coeff p = 0 ↔ p = 0 := ⟨λ h, by_contradiction (λ h₁, (mem_support_iff _ _).1 (finset.sup_mem_nat (mt support_eq_empty.1 h₁)) h), by simp { contextual := tt }⟩ lemma degree_add_eq_of_degree_lt (h : degree p < degree q) : degree (p + q) = degree q := le_antisymm (max_eq_right_of_lt h ▸ degree_add_le _ _) (le_degree_of_ne_zero begin rw [add_apply, eq_zero_of_degree_lt h, zero_add], exact mt leading_coeff_eq_zero.1 (λ h₁, by simpa [h₁, nat.not_lt_zero] using h) end) lemma degree_add_eq_of_apply_ne_zero (h : leading_coeff p + q (degree p) ≠ 0) : degree (p + q) = max p.degree q.degree := le_antisymm (degree_add_le _ _) (le_degree_of_ne_zero begin rw add_apply, unfold max, split_ifs, { cases lt_or_eq_of_le h_1 with h₁ h₁, { rw [not_not.1 (mt le_degree_of_ne_zero (not_le_of_gt h₁)), zero_add], exact mt leading_coeff_eq_zero.1 (λ h, by simpa [h, nat.not_lt_zero] using h₁) }, { rwa ← h₁ } }, assumption end) lemma degree_erase_lt (h : 0 < degree p) : degree (p.erase (degree p)) < degree p := finset.sup_lt_nat (erase_subset _ _) (not_mem_erase _ _) h lemma degree_mul_le : ∀ (p q : polynomial α), degree (p * q) ≤ degree p + degree q := have hsup : ∀ {n : ℕ} {q : polynomial α} {a : α}, sup ((sum q (λ (m : ℕ) (x : α), single (n + m) (a * x))).support) id ≤ n + degree q := λ n q a, sup_le (λ b hb, begin rcases mem_bind.1 (finsupp.support_sum hb) with ⟨x, hx₁, hx₂⟩, rw mem_support_iff at hx₁ hx₂, rw single_apply at hx₂, by_cases hnx : n + x = b, { rw [← hnx, id.def], exact add_le_add_left (le_degree_of_ne_zero hx₁) _ }, { simpa [hnx] using hx₂ } end), λ p, monomial_induction_on p (by simp [nat.zero_le]) (assume n a p hpn ha ih q, calc degree ((single n a + p) * q) ≤ max (degree (single n a * q)) (degree (p * q)) : by rw add_mul; exact degree_add_le _ _ ... = max ((q.sum (λ m x, single (n + m) (a * x))).support.sup id) (degree (p * q)) : by rw [mul_def, sum_single_index, degree]; simp ... ≤ max (n + degree q) (degree p + degree q) : by exact max_le_max hsup (ih _) ... ≤ max n (degree p) + degree q : max_le (add_le_add_right (le_max_left _ _) _) (add_le_add_right (le_max_right _ _) _) ... = degree (monomial n a + p) + degree q : begin rw [degree_add_eq_of_apply_ne_zero, degree_monomial _ ha], rwa [leading_coeff, degree_monomial _ ha, monomial_apply_self, hpn, add_zero] end) lemma degree_erase_le (p : polynomial α) (n : ℕ) : degree (p.erase n) ≤ degree p := sup_mono (erase_subset _ _) @[simp] lemma leading_coeff_monomial (a : α) (n : ℕ) : leading_coeff (monomial n a) = a := begin by_cases ha : a = 0, { simp [ha] }, { simp [leading_coeff, degree_monomial _ ha, monomial_apply] }, end @[simp] lemma leading_coeff_C (a : α) : leading_coeff (C a) = a := leading_coeff_monomial _ _ @[simp] lemma monic_one : monic (1 : polynomial α) := leading_coeff_C _ lemma leading_coeff_add_of_lt (h : degree p < degree q) : leading_coeff (p + q) = leading_coeff q := by unfold leading_coeff; rw [degree_add_eq_of_degree_lt h, add_apply, eq_zero_of_degree_lt h, zero_add] @[simp] lemma mul_apply_degree_add_degree (p q : polynomial α) : (p * q) (degree p + degree q) = leading_coeff p * leading_coeff q := if hp : degree p = 0 then begin rw [eq_C_of_degree_eq_zero hp], simp [leading_coeff, C_apply] end else have h₁ : p * q = monomial (degree p + degree q) (p (degree p) * q (degree q)) + erase (degree p) p * monomial (degree q) (q (degree q)) + (erase (degree q) q * monomial (degree p) (p (degree p)) + erase (degree p) p * erase (degree q) q), begin unfold monomial, conv {to_lhs, rw [← @single_add_erase _ _ _ _ _ (degree p) p, ← @single_add_erase _ _ _ _ _ (degree q) q, mul_add, add_mul, add_mul, single_mul_single] }, simp [mul_comm], end, have h₂ : ∀ {p q r : polynomial α}, degree r ≤ degree q → (erase (degree p) p * r) (degree p + degree q) = 0, from λ p q r hr, if hp : degree p = 0 then by rw [hp, eq_C_of_degree_eq_zero hp, C, erase_monomial, zero_add, zero_mul, zero_apply] else eq_zero_of_degree_lt (calc degree (erase (degree p) p * r) ≤ _ : degree_mul_le _ _ ... < _ : add_lt_add_of_lt_of_le (degree_erase_lt (nat.pos_of_ne_zero hp)) hr), begin rw [h₁, add_apply, add_apply, add_apply, monomial_apply, if_pos rfl], rw [h₂ (degree_monomial_le _ _), h₂ (degree_erase_le _ _), add_comm (degree p), h₂ (degree_monomial_le _ _), add_zero, add_zero, add_zero], refl, end lemma degree_mul_eq' {p q : polynomial α} (h : leading_coeff p * leading_coeff q ≠ 0) : degree (p * q) = degree p + degree q := le_antisymm (degree_mul_le _ _) (le_degree_of_ne_zero (by rwa mul_apply_degree_add_degree)) end comm_semiring section comm_ring variables [comm_ring α] {p q : polynomial α} instance : comm_ring (polynomial α) := finsupp.to_comm_ring instance : has_scalar α (polynomial α) := finsupp.to_has_scalar instance : module α (polynomial α) := finsupp.to_module instance {x : α} : is_ring_hom (eval x) := ⟨λ x y, eval_add, λ x y, eval_mul, eval_C⟩ @[simp] lemma degree_neg (p : polynomial α) : degree (-p) = degree p := by unfold degree; rw support_neg @[simp] lemma neg_apply (p : polynomial α) (n : ℕ) : (-p) n = - p n := neg_apply lemma eval_neg (p : polynomial α) (x : α) : (-p).eval x = -p.eval x := is_ring_hom.map_neg _ lemma eval_sub (p q : polynomial α) (x : α) : (p - q).eval x = p.eval x - q.eval x := is_ring_hom.map_sub _ lemma degree_sub_lt (hd : degree p = degree q) (hpos : 0 < degree p) (hlc : leading_coeff p = leading_coeff q) : degree (p - q) < degree p := have hlc' : p (degree p) = q (degree q) := hlc, have hp : single (degree p) (p (degree p)) + p.erase (degree p) = p := finsupp.single_add_erase, have hq : single (degree q) (q (degree q)) + q.erase (degree q) = q := finsupp.single_add_erase, begin conv { to_lhs, rw [← hp, ← hq, hlc', hd, add_sub_add_left_eq_sub] }, exact calc degree (erase (degree q) p + -erase (degree q) q) ≤ max (degree (erase (degree q) p)) (degree (erase (degree q) q)) : by rw ← degree_neg (erase (degree q) q); exact degree_add_le _ _ ... < degree p : max_lt_iff.2 ⟨hd ▸ degree_erase_lt hpos, hd.symm ▸ degree_erase_lt (hd ▸ hpos)⟩ end def euclid_val_poly (p : polynomial α) := if p = 0 then 0 else degree p + 1 @[simp] lemma euclid_val_poly_zero : euclid_val_poly (0 : polynomial α) = 0 := rfl @[simp] lemma euclid_val_poly_eq_zero_iff : euclid_val_poly p = 0 ↔ p = 0 := ⟨λ h, if hp : p = 0 then hp else by rw [euclid_val_poly, if_neg hp] at h; exact (nat.succ_ne_zero _ h).elim, by simp {contextual := tt}⟩ lemma div_wf_lemma (h : euclid_val_poly q ≤ euclid_val_poly p ∧ p ≠ 0) (hq : monic q) : euclid_val_poly (p - monomial (degree p - degree q) (leading_coeff p) * q) < euclid_val_poly p := have hp : leading_coeff p ≠ 0 := mt leading_coeff_eq_zero.1 h.2, have hpq : leading_coeff (monomial (degree p - degree q) (leading_coeff p)) * leading_coeff q ≠ 0, by rwa [leading_coeff, degree_monomial _ hp, monomial_apply, if_pos rfl, monic.def.1 hq, mul_one], have hzq : leading_coeff (monomial (degree p - degree q) (p (degree p))) * leading_coeff q ≠ 0 := by rwa [monic.def.1 hq, leading_coeff_monomial, mul_one], if h0 : p - monomial (degree p - degree q) (leading_coeff p) * q = 0 then by rw [euclid_val_poly, euclid_val_poly, if_pos h0, if_neg h.2]; exact nat.succ_pos _ else if hq0 : degree p = 0 then begin simp [hq0], end else by rw [euclid_val_poly, euclid_val_poly, if_neg h0, if_neg h.2]; exact nat.succ_lt_succ ( degree_sub_lt (by rw [degree_mul_eq' hpq, degree_monomial _ hp, nat.sub_add_cancel h.1]) h.2 (by rw [leading_coeff, leading_coeff, degree_mul_eq' hzq, mul_apply_degree_add_degree, leading_coeff_monomial, monic.def.1 hq, mul_one]) def div_mod_by_monic_aux : Π (p : polynomial α) {q : polynomial α}, monic q → polynomial α × polynomial α | p := λ q hq, if h : degree q ≤ degree p ∧ 0 < degree p then have h : _ := div_wf_lemma h hq, let z := monomial (degree p - degree q) (leading_coeff p) in let dm := div_mod_by_monic_aux (p - z * q) hq in ⟨z + dm.1, dm.2⟩ else if degree p = 0 ∧ degree q = 0 then ⟨C (leading_coeff p), 0⟩ else ⟨0, p⟩ using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf degree⟩]} /-- `div_by_monic` gives the quotient of `p` by a monic polynomial `q`. -/ def div_by_monic (p q : polynomial α) : polynomial α := if hq : monic q then (div_mod_by_monic_aux p hq).1 else 0 /-- `mod_by_monic` gives the remainder of `p` by a monic polynomial `q` -/ def mod_by_monic (p q : polynomial α) : polynomial α := if hq : monic q then (div_mod_by_monic_aux p hq).2 else p notation p `/ₘ` q := div_by_monic p q notation p `%ₘ` q := mod_by_monic p q lemma degree_mod_by_monic_lt : ∀ (p : polynomial α) {q : polynomial α} (hq : monic q) (hq0 : 0 < degree q), degree (mod_by_monic p q) < degree q | p := λ q hq hq0, if h : degree q ≤ degree p ∧ 0 < degree p then have wf : _ := div_wf_lemma h hq, have degree (mod_by_monic (p - monomial (degree p - degree q) (leading_coeff p) * q) q) < degree q := degree_mod_by_monic_lt (p - monomial (degree p - degree q) (leading_coeff p) * q) hq hq0, begin unfold mod_by_monic at this ⊢, unfold div_mod_by_monic_aux, rw dif_pos hq at this ⊢, rw if_pos h, exact this end else have h₁ : ¬ (degree p = 0 ∧ degree q = 0) := λ h₁, by simpa [h₁.2, lt_irrefl] using hq0, begin unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, if_neg h₁], cases not_and_distrib.1 h with h₂ h₂, { exact lt_of_not_ge h₂ }, { simpa [nat.le_zero_iff.1 (le_of_not_gt h₂)] } end using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf degree⟩]} @[simp] lemma mod_by_monic_one : ∀ p : polynomial α, mod_by_monic p 1 = 0 | p := if hp0 : 0 < degree p then have hd : degree 1 ≤ degree p ∧ 0 < degree p := ⟨by rw @degree_one α _ _; exact nat.zero_le _, hp0⟩, have wf : degree (p + -monomial (degree p) (leading_coeff p)) < degree p := by have := div_wf_lemma hd monic_one; simpa using this, have h : _ := mod_by_monic_one (p - monomial (degree p - degree (1 : polynomial α)) (leading_coeff p) * 1), begin unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos monic_one, if_pos hd], rwa [mod_by_monic, dif_pos monic_one] at h end else have hp0' : degree p = 0 := not_not.1 $ mt nat.pos_of_ne_zero hp0, begin unfold mod_by_monic div_mod_by_monic_aux, simp [hp0, hp0'] end using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf degree⟩]} lemma degree_mod_by_monic_lt_or_eq_zero (p : polynomial α) {q : polynomial α} (hq : monic q) : degree (mod_by_monic p q) < degree q ∨ mod_by_monic p q = 0 := if hq0 : 0 < degree q then or.inl $ degree_mod_by_monic_lt p hq hq0 else have hq0 : degree q = 0 := not_not.1 $ mt nat.pos_of_ne_zero hq0, have hq : q = 1 := by rw [eq_C_of_degree_eq_zero hq0, ← hq0, (show q (degree q) = 1, from hq)]; refl, by subst hq; simp [mod_by_monic_one] lemma mod_by_monic_eq_sub_mul_div : ∀ (p : polynomial α) {q : polynomial α} (hq : monic q), mod_by_monic p q = p - q * div_by_monic p q | p := λ q hq, if h : degree q ≤ degree p ∧ 0 < degree p then have wf : _ := div_wf_lemma h hq, have ih : _ := mod_by_monic_eq_sub_mul_div (p - monomial (degree p - degree q) (leading_coeff p) * q) hq, begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_pos h], rw [mod_by_monic, dif_pos hq] at ih, refine ih.trans _, simp [mul_add, add_mul, mul_comm, hq, h, div_by_monic] end else if h₁ : degree p = 0 ∧ degree q = 0 then have hq0 : q 0 = 1 := h₁.2 ▸ hq, begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, if_pos h₁], rw [eq_C_of_degree_eq_zero h₁.1, eq_C_of_degree_eq_zero h₁.2] at *, conv {to_rhs, congr, rw eq_C_of_degree_eq_zero h₁.1}, simp [hq0, leading_coeff, h₁.1, h₁.2, h, hq, lt_irrefl, C_apply], end else begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, simp [hq, h, h₁] end using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf degree⟩]} lemma mod_by_monic_add_div (p : polynomial α) {q : polynomial α} (hq : monic q) : mod_by_monic p q + q * div_by_monic p q = p := eq_sub_iff_add_eq.1 (mod_by_monic_eq_sub_mul_div p hq) lemma degree_div_by_monic_lt (p : polynomial α) {q : polynomial α} (hq : monic q) (hq0 : 0 < degree q) (hp0 : 0 < degree p) : degree (div_by_monic p q) < degree p := if hdp : div_by_monic p q = 0 then by simpa [hdp] else have h₁ : leading_coeff q * leading_coeff (div_by_monic p q) ≠ 0 := by rw [monic.def.1 hq, one_mul]; exact mt leading_coeff_eq_zero.1 hdp, have h₂ : degree (mod_by_monic p q) < degree (q * div_by_monic p q) := by rw degree_mul_eq' h₁; exact calc degree (mod_by_monic p q) < degree q : degree_mod_by_monic_lt p hq hq0 ... ≤ degree q + _ : nat.le_add_right _ _, begin conv {to_rhs, rw ← mod_by_monic_add_div p hq}, rw [degree_add_eq_of_degree_lt h₂, degree_mul_eq' h₁], exact (lt_add_iff_pos_left _).2 hq0, end lemma dvd_iff_mod_by_monic_eq_zero (hq : monic q) : mod_by_monic p q = 0 ↔ q ∣ p := ⟨λ h, by rw [← mod_by_monic_add_div p hq, h, zero_add]; exact dvd_mul_right _ _, λ h, or.cases_on (degree_mod_by_monic_lt_or_eq_zero p hq) (λ hlt, let ⟨r, hr⟩ := exists_eq_mul_right_of_dvd h in have hr : mod_by_monic p q = q * (r - div_by_monic p q) := by rwa [← mod_by_monic_add_div p hq, ← eq_sub_iff_add_eq, ← mul_sub] at hr, have r - div_by_monic p q = 0 := classical.by_contradiction (λ h, have hlc : leading_coeff q * leading_coeff (r - div_by_monic p q) ≠ 0 := by rwa [monic.def.1 hq, one_mul, ne.def, leading_coeff_eq_zero], have hq : degree (q * (r - div_by_monic p q)) = degree q + degree (r - div_by_monic p q) := by rw degree_mul_eq' hlc, by rw [hr, hq] at hlt; exact not_lt_of_ge (nat.le_add_right _ _) hlt), by rwa [this, mul_zero] at hr) id⟩ end comm_ring section nonzero_comm_ring variables [nonzero_comm_ring α] {p q : polynomial α} instance : nonzero_comm_ring (polynomial α) := { zero_ne_one := λ (h : (0 : polynomial α) = 1), @zero_ne_one α _ $ calc (0 : α) = eval 0 0 : eval_zero.symm ... = eval 0 1 : congr_arg _ h ... = 1 : eval_C, ..polynomial.comm_ring } @[simp] lemma degree_one : degree (1 : polynomial α) = (0 : with_bot ℕ) := degree_C (show (1 : α) ≠ 0, from zero_ne_one.symm) @[simp] lemma not_monic_zero : ¬monic (0 : polynomial α) := by simp [monic, zero_ne_one] lemma degree_X : degree (X : polynomial α) = 1 := begin unfold X monomial degree single finsupp.support, rw if_neg (zero_ne_one).symm, simp [sup], end lemma degree_X_sub_C (a : α) : degree (X - C a) = 1 := begin rw [sub_eq_add_neg, add_comm, ← @degree_X α], exact degree_add_eq_of_degree_lt (by simp [degree_X, degree_neg, degree_C, nat.succ_pos]) end lemma monic_X_sub_C (a : α) : monic (X - C a) := begin unfold monic leading_coeff, rw [degree_X_sub_C, sub_eq_add_neg, add_apply, X, C, monomial_apply, neg_apply, monomial_apply], split_ifs; simp * at * end lemma root_X_sub_C : is_root (X - C a) b ↔ a = b := by rw [is_root.def, eval_sub, eval_X, eval_C, sub_eq_zero_iff_eq, eq_comm] lemma mod_by_monic_X_sub_C_eq_C_eval (p : polynomial α) (a : α) : mod_by_monic p (X - C a) = C (p.eval a) := have h : (mod_by_monic p (X - C a)).eval a = p.eval a := by rw [mod_by_monic_eq_sub_mul_div _ (monic_X_sub_C a), eval_sub, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul, sub_zero], have degree (mod_by_monic p (X - C a)) < 1 := degree_X_sub_C a ▸ degree_mod_by_monic_lt p (monic_X_sub_C a) ((degree_X_sub_C a).symm ▸ nat.succ_pos _), have degree (mod_by_monic p (X - C a)) = 0 := nat.eq_zero_of_le_zero (nat.le_of_lt_succ this), begin rw [eq_C_of_degree_eq_zero this, eval_C] at h, rw [eq_C_of_degree_eq_zero this, h] end lemma mul_div_eq_iff_is_root : (X - C a) * div_by_monic p (X - C a) = p ↔ is_root p a := ⟨λ h, by rw [← h, is_root.def, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul], λ h : p.eval a = 0, by conv{to_rhs, rw ← mod_by_monic_add_div p (monic_X_sub_C a)}; rw [mod_by_monic_X_sub_C_eq_C_eval, h, C_0, zero_add]⟩ end nonzero_comm_ring section integral_domain variables [integral_domain α] {p q : polynomial α} lemma degree_mul_eq (hp : p ≠ 0) (hq : q ≠ 0) : degree (p * q) = degree p + degree q := degree_mul_eq' $ mul_ne_zero (mt leading_coeff_eq_zero.1 hp) (mt leading_coeff_eq_zero.1 hq) lemma leading_coeff_mul (p q : polynomial α) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin by_cases hp : p = 0, { simp [hp] }, { by_cases hq : q = 0, { simp [hq] }, { rw [leading_coeff, degree_mul_eq hp hq, mul_apply_degree_add_degree] } }, end instance : integral_domain (polynomial α) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin have : leading_coeff 0 = leading_coeff a * leading_coeff b := h ▸ leading_coeff_mul a b, rw [leading_coeff_zero, eq_comm] at this, rw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero], exact eq_zero_or_eq_zero_of_mul_eq_zero this end, ..polynomial.nonzero_comm_ring } lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a := by rw [is_root, eval_mul] at h; exact eq_zero_or_eq_zero_of_mul_eq_zero h lemma exists_finset_roots : Π {p : polynomial α} (hp : p ≠ 0), ∃ s : finset α, s.card ≤ degree p ∧ ∀ x, x ∈ s ↔ is_root p x | 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 := nat.pos_of_ne_zero (λ h, begin rw [eq_C_of_degree_eq_zero h, is_root, eval_C] at hx, have h1 : p (degree p) ≠ 0 := mt leading_coeff_eq_zero.1 hp, rw h at h1, contradiction, end), have hd0 : div_by_monic p (X - C x) ≠ 0 := λ h, by have := mul_div_eq_iff_is_root.2 hx; simp * at *, have wf : degree (div_by_monic p _) < degree p := degree_div_by_monic_lt _ (monic_X_sub_C x) ((degree_X_sub_C x).symm ▸ nat.succ_pos _) hpd, let ⟨t, htd, htr⟩ := @exists_finset_roots (div_by_monic p (X - C x)) hd0 in ⟨insert x t, calc (insert x t).card ≤ t.card + 1 : finset.card_insert_le _ _ ... ≤ degree (div_by_monic p (X - C x)) + 1 : nat.succ_le_succ htd ... ≤ _ : nat.succ_le_of_lt wf, begin assume y, rw [mem_insert, htr, eq_comm, ← root_X_sub_C], conv {to_rhs, rw ← mul_div_eq_iff_is_root.2 hx}, exact ⟨λ h, or.cases_on h (root_mul_right_of_is_root _) (root_mul_left_of_is_root _), root_or_root_of_root_mul⟩ end⟩ else ⟨∅, nat.zero_le _, by clear exists_finset_roots; finish⟩ using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf degree⟩]} /-- `roots p` noncomputably gives a finset containing all the roots of `p` -/ noncomputable def roots (p : polynomial α) : finset α := if h : p = 0 then ∅ else classical.some (exists_finset_roots h) lemma card_roots (p : polynomial α) : (roots p).card ≤ degree p := begin unfold roots, split_ifs, { exact nat.zero_le _ }, { exact (classical.some_spec (exists_finset_roots h)).1 } end lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a := by unfold roots; rw dif_neg hp; exact (classical.some_spec (exists_finset_roots hp)).2 _ end integral_domain section field variables [field α] {p q : polynomial α} instance : vector_space α (polynomial α) := { ..finsupp.to_module } lemma monic_mul_leading_coeff_inv (h : p ≠ 0) : monic (p * C (leading_coeff p)⁻¹) := by rw [monic, leading_coeff_mul, leading_coeff_C, mul_inv_cancel (show leading_coeff p ≠ 0, from mt leading_coeff_eq_zero.1 h)] lemma degree_mul_leading_coeff_inv (h : p ≠ 0) : degree (p * C (leading_coeff p)⁻¹) = degree p := have C (leading_coeff p)⁻¹ ≠ 0 := mt leading_coeff_eq_zero.2 $ by rw [leading_coeff_C]; exact inv_ne_zero (mt leading_coeff_eq_zero.1 h), by rw [degree_mul_eq h this, degree_C, add_zero] def div_aux (p q : polynomial α) := C (leading_coeff q)⁻¹ * div_by_monic p (q * C (leading_coeff q)⁻¹) def mod_aux (p q : polynomial α) := mod_by_monic p (q * C (leading_coeff q)⁻¹) private lemma quotient_mul_add_remainder_eq_aux (p q : polynomial α) : q * div_aux p q + mod_aux p q = p := if h : q = 0 then by simp [h, mod_by_monic, div_aux, mod_aux] else begin conv {to_rhs, rw ← mod_by_monic_add_div p (monic_mul_leading_coeff_inv h)}, rw [mod_aux, div_aux, add_comm, mul_assoc] end /-- `euclid_val_poly` is the Euclidean size function, used in the proof that polynomials over a field are a Euclidean domain. `euclid_val_poly 0 = 0` and `euclid_val_poly p = degree p + 1` for `p ≠ 0`. -/ def euclid_val_poly (p : polynomial α) := if p = 0 then 0 else degree p + 1 lemma euclid_val_poly_lt_of_degree_lt (h : degree p < degree q) : euclid_val_poly p < euclid_val_poly q := begin unfold euclid_val_poly, split_ifs; simp [*, nat.succ_pos, -add_comm, nat.not_lt_zero, iff.intro nat.lt_of_succ_lt_succ nat.succ_lt_succ] at * end private lemma val_remainder_lt_aux (p : polynomial α) (hq : q ≠ 0) : euclid_val_poly (mod_aux p q) < euclid_val_poly q := or.cases_on (degree_mod_by_monic_lt_or_eq_zero p (monic_mul_leading_coeff_inv hq)) begin unfold mod_aux, rw [degree_mul_leading_coeff_inv hq], exact euclid_val_poly_lt_of_degree_lt end (λ h, begin rw [mod_aux, h, euclid_val_poly, if_pos rfl, euclid_val_poly, if_neg hq], exact nat.succ_pos _ end) instance : euclidean_domain (polynomial α) := { quotient := div_aux, remainder := mod_aux, quotient_mul_add_remainder_eq := quotient_mul_add_remainder_eq_aux, valuation := euclid_val_poly, val_remainder_lt := λ p q hq, val_remainder_lt_aux _ hq, val_le_mul_left := λ p q hq, if hp : p = 0 then begin unfold euclid_val_poly, rw [if_pos hp], exact nat.zero_le _ end else begin unfold euclid_val_poly, rw [if_neg hp, if_neg (mul_ne_zero hp hq), degree_mul_eq hp hq], exact nat.succ_le_succ (nat.le_add_right _ _), end } end field end polynomial
2dc2dae4f9f901c6d4172f4d623db1bf0863e498
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/metric_space/baire.lean
3195723329460e603326616ac0c14e665ad1ad13
[ "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,051
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.specific_limits import order.filter.countable_Inter import topology.G_delta /-! # Baire theorem In a complete metric space, a countable intersection of dense open subsets is dense. The good concept underlying the theorem is that of a Gδ set, i.e., a countable intersection of open sets. Then Baire theorem can also be formulated as the fact that a countable intersection of dense Gδ sets is a dense Gδ set. We prove Baire theorem, giving several different formulations that can be handy. We also prove the important consequence that, if the space is covered by a countable union of closed sets, then the union of their interiors is dense. The names of the theorems do not contain the string "Baire", but are instead built from the form of the statement. "Baire" is however in the docstring of all the theorems, to facilitate grep searches. We also define the filter `residual α` generated by dense `Gδ` sets and prove that this filter has the countable intersection property. -/ noncomputable theory open_locale classical topological_space filter ennreal open filter encodable set variables {α : Type*} {β : Type*} {γ : Type*} {ι : Type*} section Baire_theorem open emetric ennreal variables [emetric_space α] [complete_space α] /-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here when the source space is ℕ (and subsumed below by `dense_Inter_of_open` working with any encodable source space). -/ theorem dense_Inter_of_open_nat {f : ℕ → set α} (ho : ∀n, is_open (f n)) (hd : ∀n, dense (f n)) : dense (⋂n, f n) := begin let B : ℕ → ℝ≥0∞ := λn, 1/2^n, have Bpos : ∀n, 0 < B n, { intro n, simp only [B, one_div, one_mul, ennreal.inv_pos], exact pow_ne_top two_ne_top }, /- Translate the density assumption into two functions `center` and `radius` associating to any n, x, δ, δpos a center and a positive radius such that `closed_ball center radius` is included both in `f n` and in `closed_ball x δ`. We can also require `radius ≤ (1/2)^(n+1)`, to ensure we get a Cauchy sequence later. -/ have : ∀n x δ, δ ≠ 0 → ∃y r, 0 < r ∧ r ≤ B (n+1) ∧ closed_ball y r ⊆ (closed_ball x δ) ∩ f n, { assume n x δ δpos, have : x ∈ closure (f n) := hd n x, rcases emetric.mem_closure_iff.1 this (δ/2) (ennreal.half_pos δpos) with ⟨y, ys, xy⟩, rw edist_comm at xy, obtain ⟨r, rpos, hr⟩ : ∃ r > 0, closed_ball y r ⊆ f n := nhds_basis_closed_eball.mem_iff.1 (is_open_iff_mem_nhds.1 (ho n) y ys), refine ⟨y, min (min (δ/2) r) (B (n+1)), _, _, λz hz, ⟨_, _⟩⟩, show 0 < min (min (δ / 2) r) (B (n+1)), from lt_min (lt_min (ennreal.half_pos δpos) rpos) (Bpos (n+1)), show min (min (δ / 2) r) (B (n+1)) ≤ B (n+1), from min_le_right _ _, show z ∈ closed_ball x δ, from calc edist z x ≤ edist z y + edist y x : edist_triangle _ _ _ ... ≤ (min (min (δ / 2) r) (B (n+1))) + (δ/2) : add_le_add hz (le_of_lt xy) ... ≤ δ/2 + δ/2 : add_le_add (le_trans (min_le_left _ _) (min_le_left _ _)) (le_refl _) ... = δ : ennreal.add_halves δ, show z ∈ f n, from hr (calc edist z y ≤ min (min (δ / 2) r) (B (n+1)) : hz ... ≤ r : le_trans (min_le_left _ _) (min_le_right _ _)) }, choose! center radius Hpos HB Hball using this, refine λ x, (mem_closure_iff_nhds_basis nhds_basis_closed_eball).2 (λ ε εpos, _), /- `ε` is positive. We have to find a point in the ball of radius `ε` around `x` belonging to all `f n`. For this, we construct inductively a sequence `F n = (c n, r n)` such that the closed ball `closed_ball (c n) (r n)` is included in the previous ball and in `f n`, and such that `r n` is small enough to ensure that `c n` is a Cauchy sequence. Then `c n` converges to a limit which belongs to all the `f n`. -/ let F : ℕ → (α × ℝ≥0∞) := λn, nat.rec_on n (prod.mk x (min ε (B 0))) (λn p, prod.mk (center n p.1 p.2) (radius n p.1 p.2)), let c : ℕ → α := λn, (F n).1, let r : ℕ → ℝ≥0∞ := λn, (F n).2, have rpos : ∀ n, 0 < r n, { assume n, induction n with n hn, exact lt_min εpos (Bpos 0), exact Hpos n (c n) (r n) hn.ne' }, have r0 : ∀ n, r n ≠ 0 := λ n, (rpos n).ne', have rB : ∀n, r n ≤ B n, { assume n, induction n with n hn, exact min_le_right _ _, exact HB n (c n) (r n) (r0 n) }, have incl : ∀n, closed_ball (c (n+1)) (r (n+1)) ⊆ (closed_ball (c n) (r n)) ∩ (f n) := λ n, Hball n (c n) (r n) (r0 n), have cdist : ∀n, edist (c n) (c (n+1)) ≤ B n, { assume n, rw edist_comm, have A : c (n+1) ∈ closed_ball (c (n+1)) (r (n+1)) := mem_closed_ball_self, have I := calc closed_ball (c (n+1)) (r (n+1)) ⊆ closed_ball (c n) (r n) : subset.trans (incl n) (inter_subset_left _ _) ... ⊆ closed_ball (c n) (B n) : closed_ball_subset_closed_ball (rB n), exact I A }, have : cauchy_seq c := cauchy_seq_of_edist_le_geometric_two _ one_ne_top cdist, -- as the sequence `c n` is Cauchy in a complete space, it converges to a limit `y`. rcases cauchy_seq_tendsto_of_complete this with ⟨y, ylim⟩, -- this point `y` will be the desired point. We will check that it belongs to all -- `f n` and to `ball x ε`. use y, simp only [exists_prop, set.mem_Inter], have I : ∀n, ∀m ≥ n, closed_ball (c m) (r m) ⊆ closed_ball (c n) (r n), { assume n, refine nat.le_induction _ (λm hnm h, _), { exact subset.refl _ }, { exact subset.trans (incl m) (subset.trans (inter_subset_left _ _) h) }}, have yball : ∀n, y ∈ closed_ball (c n) (r n), { assume n, refine is_closed_ball.mem_of_tendsto ylim _, refine (filter.eventually_ge_at_top n).mono (λ m hm, _), exact I n m hm mem_closed_ball_self }, split, show ∀n, y ∈ f n, { assume n, have : closed_ball (c (n+1)) (r (n+1)) ⊆ f n := subset.trans (incl n) (inter_subset_right _ _), exact this (yball (n+1)) }, show edist y x ≤ ε, from le_trans (yball 0) (min_le_left _ _), end /-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here with ⋂₀. -/ theorem dense_sInter_of_open {S : set (set α)} (ho : ∀s∈S, is_open s) (hS : countable S) (hd : ∀s∈S, dense s) : dense (⋂₀S) := begin cases S.eq_empty_or_nonempty with h h, { simp [h] }, { rcases hS.exists_surjective h with ⟨f, hf⟩, have F : ∀n, f n ∈ S := λn, by rw hf; exact mem_range_self _, rw [hf, sInter_range], exact dense_Inter_of_open_nat (λn, ho _ (F n)) (λn, hd _ (F n)) } end /-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here with an index set which is a countable set in any type. -/ theorem dense_bInter_of_open {S : set β} {f : β → set α} (ho : ∀s∈S, is_open (f s)) (hS : countable S) (hd : ∀s∈S, dense (f s)) : dense (⋂s∈S, f s) := begin rw ← sInter_image, apply dense_sInter_of_open, { rwa ball_image_iff }, { exact hS.image _ }, { rwa ball_image_iff } end /-- Baire theorem: a countable intersection of dense open sets is dense. Formulated here with an index set which is an encodable type. -/ theorem dense_Inter_of_open [encodable β] {f : β → set α} (ho : ∀s, is_open (f s)) (hd : ∀s, dense (f s)) : dense (⋂s, f s) := begin rw ← sInter_range, apply dense_sInter_of_open, { rwa forall_range_iff }, { exact countable_range _ }, { rwa forall_range_iff } end /-- Baire theorem: a countable intersection of dense Gδ sets is dense. Formulated here with ⋂₀. -/ theorem dense_sInter_of_Gδ {S : set (set α)} (ho : ∀s∈S, is_Gδ s) (hS : countable S) (hd : ∀s∈S, dense s) : dense (⋂₀S) := begin -- the result follows from the result for a countable intersection of dense open sets, -- by rewriting each set as a countable intersection of open sets, which are of course dense. choose T hT using ho, have : ⋂₀ S = ⋂₀ (⋃s∈S, T s ‹_›) := (sInter_bUnion (λs hs, (hT s hs).2.2)).symm, rw this, refine dense_sInter_of_open _ (hS.bUnion (λs hs, (hT s hs).2.1)) _; simp only [set.mem_Union, exists_prop]; rintro t ⟨s, hs, tTs⟩, show is_open t, { exact (hT s hs).1 t tTs }, show dense t, { intro x, have := hd s hs x, rw (hT s hs).2.2 at this, exact closure_mono (sInter_subset_of_mem tTs) this } end /-- Baire theorem: a countable intersection of dense Gδ sets is dense. Formulated here with an index set which is an encodable type. -/ theorem dense_Inter_of_Gδ [encodable β] {f : β → set α} (ho : ∀s, is_Gδ (f s)) (hd : ∀s, dense (f s)) : dense (⋂s, f s) := begin rw ← sInter_range, exact dense_sInter_of_Gδ (forall_range_iff.2 ‹_›) (countable_range _) (forall_range_iff.2 ‹_›) end /-- Baire theorem: a countable intersection of dense Gδ sets is dense. Formulated here with an index set which is a countable set in any type. -/ theorem dense_bInter_of_Gδ {S : set β} {f : Π x ∈ S, set α} (ho : ∀s∈S, is_Gδ (f s ‹_›)) (hS : countable S) (hd : ∀s∈S, dense (f s ‹_›)) : dense (⋂s∈S, f s ‹_›) := begin rw bInter_eq_Inter, haveI := hS.to_encodable, exact dense_Inter_of_Gδ (λ s, ho s s.2) (λ s, hd s s.2) end /-- Baire theorem: the intersection of two dense Gδ sets is dense. -/ theorem dense.inter_of_Gδ {s t : set α} (hs : is_Gδ s) (ht : is_Gδ t) (hsc : dense s) (htc : dense t) : dense (s ∩ t) := begin rw [inter_eq_Inter], apply dense_Inter_of_Gδ; simp [bool.forall_bool, *] end /-- A property holds on a residual (comeagre) set if and only if it holds on some dense `Gδ` set. -/ lemma eventually_residual {p : α → Prop} : (∀ᶠ x in residual α, p x) ↔ ∃ (t : set α), is_Gδ t ∧ dense t ∧ ∀ x ∈ t, p x := calc (∀ᶠ x in residual α, p x) ↔ ∀ᶠ x in ⨅ (t : set α) (ht : is_Gδ t ∧ dense t), 𝓟 t, p x : by simp only [residual, infi_and] ... ↔ ∃ (t : set α) (ht : is_Gδ t ∧ dense t), ∀ᶠ x in 𝓟 t, p x : mem_binfi_of_directed (λ t₁ h₁ t₂ h₂, ⟨t₁ ∩ t₂, ⟨h₁.1.inter h₂.1, dense.inter_of_Gδ h₁.1 h₂.1 h₁.2 h₂.2⟩, by simp⟩) ⟨univ, is_Gδ_univ, dense_univ⟩ ... ↔ _ : by simp [and_assoc] /-- A set is residual (comeagre) if and only if it includes a dense `Gδ` set. -/ lemma mem_residual {s : set α} : s ∈ residual α ↔ ∃ t ⊆ s, is_Gδ t ∧ dense t := (@eventually_residual α _ _ (λ x, x ∈ s)).trans $ exists_congr $ λ t, by rw [exists_prop, and_comm (t ⊆ s), subset_def, and_assoc] lemma dense_of_mem_residual {s : set α} (hs : s ∈ residual α) : dense s := let ⟨t, hts, _, hd⟩ := mem_residual.1 hs in hd.mono hts instance : countable_Inter_filter (residual α) := ⟨begin intros S hSc hS, simp only [mem_residual] at *, choose T hTs hT using hS, refine ⟨⋂ s ∈ S, T s ‹_›, _, _, _⟩, { rw [sInter_eq_bInter], exact Inter_subset_Inter (λ s, Inter_subset_Inter $ hTs s) }, { exact is_Gδ_bInter hSc (λ s hs, (hT s hs).1) }, { exact dense_bInter_of_Gδ (λ s hs, (hT s hs).1) hSc (λ s hs, (hT s hs).2) } end⟩ /-- Baire theorem: if countably many closed sets cover the whole space, then their interiors are dense. Formulated here with an index set which is a countable set in any type. -/ theorem dense_bUnion_interior_of_closed {S : set β} {f : β → set α} (hc : ∀s∈S, is_closed (f s)) (hS : countable S) (hU : (⋃s∈S, f s) = univ) : dense (⋃s∈S, interior (f s)) := begin let g := λs, (frontier (f s))ᶜ, have : dense (⋂s∈S, g s), { refine dense_bInter_of_open (λs hs, _) hS (λs hs, _), show is_open (g s), from is_open_compl_iff.2 is_closed_frontier, show dense (g s), { intro x, simp [interior_frontier (hc s hs)] }}, refine this.mono _, show (⋂s∈S, g s) ⊆ (⋃s∈S, interior (f s)), assume x hx, have : x ∈ ⋃s∈S, f s, { have := mem_univ x, rwa ← hU at this }, rcases mem_bUnion_iff.1 this with ⟨s, hs, xs⟩, have : x ∈ g s := mem_bInter_iff.1 hx s hs, have : x ∈ interior (f s), { have : x ∈ f s \ (frontier (f s)) := mem_inter xs this, simpa [frontier, xs, (hc s hs).closure_eq] using this }, exact mem_bUnion_iff.2 ⟨s, ⟨hs, this⟩⟩ end /-- Baire theorem: if countably many closed sets cover the whole space, then their interiors are dense. Formulated here with `⋃₀`. -/ theorem dense_sUnion_interior_of_closed {S : set (set α)} (hc : ∀s∈S, is_closed s) (hS : countable S) (hU : (⋃₀ S) = univ) : dense (⋃s∈S, interior s) := by rw sUnion_eq_bUnion at hU; exact dense_bUnion_interior_of_closed hc hS hU /-- Baire theorem: if countably many closed sets cover the whole space, then their interiors are dense. Formulated here with an index set which is an encodable type. -/ theorem dense_Union_interior_of_closed [encodable β] {f : β → set α} (hc : ∀s, is_closed (f s)) (hU : (⋃s, f s) = univ) : dense (⋃s, interior (f s)) := begin rw ← bUnion_univ, apply dense_bUnion_interior_of_closed, { simp [hc] }, { apply countable_encodable }, { rwa ← bUnion_univ at hU } end /-- One of the most useful consequences of Baire theorem: if a countable union of closed sets covers the space, then one of the sets has nonempty interior. -/ theorem nonempty_interior_of_Union_of_closed [nonempty α] [encodable β] {f : β → set α} (hc : ∀s, is_closed (f s)) (hU : (⋃s, f s) = univ) : ∃s, (interior $ f s).nonempty := begin by_contradiction h, simp only [not_exists, not_nonempty_iff_eq_empty] at h, have := calc ∅ = closure (⋃s, interior (f s)) : by simp [h] ... = univ : (dense_Union_interior_of_closed hc hU).closure_eq, exact univ_nonempty.ne_empty this.symm end end Baire_theorem
9d752203d51c8002ba508223ce3b408dfd45143b
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/differential_object.lean
a3bf8be09629241ac49f7cf364df722632cf4034
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
3,671
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.shift import category_theory.concrete_category /-! # Differential objects in a category. A differential object in a category with zero morphisms and a shift is an object `X` equipped with a morphism `d : X ⟶ X⟦1⟧`, such that `d^2 = 0`. We build the category of differential objects, and some basic constructions such as the forgetful functor, and zero morphisms and zero objects. -/ open category_theory.limits universes v u namespace category_theory variables (C : Type u) [category.{v} C] variables [has_zero_morphisms.{v} C] [has_shift.{v} C] /-- A differential object in a category with zero morphisms and a shift is an object `X` equipped with a morphism `d : X ⟶ X⟦1⟧`, such that `d^2 = 0`. -/ @[nolint has_inhabited_instance] structure differential_object := (X : C) (d : X ⟶ X⟦1⟧) (d_squared' : d ≫ d⟦1⟧' = 0 . obviously) restate_axiom differential_object.d_squared' attribute [simp] differential_object.d_squared variables {C} namespace differential_object /-- A morphism of differential objects is a morphism commuting with the differentials. -/ @[ext, nolint has_inhabited_instance] structure hom (X Y : differential_object.{v} C) := (f : X.X ⟶ Y.X) (comm' : X.d ≫ f⟦1⟧' = f ≫ Y.d . obviously) restate_axiom hom.comm' attribute [simp, reassoc] hom.comm namespace hom /-- The identity morphism of a differential object. -/ @[simps] def id (X : differential_object.{v} C) : hom X X := { f := 𝟙 X.X } /-- The composition of morphisms of differential objects. -/ @[simps] def comp {X Y Z : differential_object.{v} C} (f : hom X Y) (g : hom Y Z) : hom X Z := { f := f.f ≫ g.f, } end hom instance category_of_differential_objects : category.{v} (differential_object.{v} C) := { hom := hom, id := hom.id, comp := λ X Y Z f g, hom.comp f g, } @[simp] lemma id_f (X : differential_object.{v} C) : ((𝟙 X) : X ⟶ X).f = 𝟙 (X.X) := rfl @[simp] lemma comp_f {X Y Z : differential_object.{v} C} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g).f = f.f ≫ g.f := rfl variables (C) /-- The forgetful functor taking a differential object to its underlying object. -/ def forget : (differential_object.{v} C) ⥤ C := { obj := λ X, X.X, map := λ X Y f, f.f, } instance forget_faithful : faithful (forget C) := { } instance has_zero_morphisms : has_zero_morphisms.{v} (differential_object.{v} C) := { has_zero := λ X Y, ⟨{ f := 0, }⟩} variables {C} @[simp] lemma zero_f (P Q : differential_object.{v} C) : (0 : P ⟶ Q).f = 0 := rfl end differential_object end category_theory namespace category_theory namespace differential_object variables (C : Type u) [category.{v} C] variables [has_zero_object.{v} C] [has_zero_morphisms.{v} C] [has_shift.{v} C] local attribute [instance] has_zero_object.has_zero instance has_zero_object : has_zero_object.{v} (differential_object.{v} C) := { zero := { X := (0 : C), d := 0, }, unique_to := λ X, ⟨⟨{ f := 0 }⟩, λ f, (by ext)⟩, unique_from := λ X, ⟨⟨{ f := 0 }⟩, λ f, (by ext)⟩, } end differential_object namespace differential_object variables (C : Type (u+1)) [large_category C] [concrete_category C] [has_zero_morphisms.{u} C] [has_shift.{u} C] instance concrete_category_of_differential_objects : concrete_category (differential_object.{u} C) := { forget := forget C ⋙ category_theory.forget C } instance : has_forget₂ (differential_object.{u} C) C := { forget₂ := forget C } end differential_object end category_theory
6640cc1a927eeb3a3640b06b0f3e9ae0673954ca
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/order/partial_sups.lean
2cd58d459948e312d9e2a1d8f7cd1d5f10eeebf2
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
5,787
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import data.finset.lattice import data.set.pairwise import order.hom.basic /-! # The monotone sequence of partial supremums of a sequence We define `partial_sups : (ℕ → α) → ℕ →o α` inductively. For `f : ℕ → α`, `partial_sups f` is the sequence `f 0 `, `f 0 ⊔ f 1`, `f 0 ⊔ f 1 ⊔ f 2`, ... The point of this definition is that * it doesn't need a `⨆`, as opposed to `⨆ (i ≤ n), f i`. * it doesn't need a `⊥`, as opposed to `(finset.range (n + 1)).sup f`. * it avoids needing to prove that `finset.range (n + 1)` is nonempty to use `finset.sup'`. Equivalence with those definitions is shown by `partial_sups_eq_bsupr`, `partial_sups_eq_sup_range`, `partial_sups_eq_sup'_range` and respectively. ## Notes One might dispute whether this sequence should start at `f 0` or `⊥`. We choose the former because : * Starting at `⊥` requires... having a bottom element. * `λ f n, (finset.range n).sup f` is already effectively the sequence starting at `⊥`. * If we started at `⊥` we wouldn't have the Galois insertion. See `partial_sups.gi`. ## TODO One could generalize `partial_sups` to any locally finite bot preorder domain, in place of `ℕ`. Necessary for the TODO in the module docstring of `order.disjointed`. -/ variables {α : Type*} section semilattice_sup variables [semilattice_sup α] /-- The monotone sequence whose value at `n` is the supremum of the `f m` where `m ≤ n`. -/ def partial_sups (f : ℕ → α) : ℕ →o α := ⟨@nat.rec (λ _, α) (f 0) (λ (n : ℕ) (a : α), a ⊔ f (n + 1)), monotone_nat_of_le_succ (λ n, le_sup_left)⟩ @[simp] lemma partial_sups_zero (f : ℕ → α) : partial_sups f 0 = f 0 := rfl @[simp] lemma partial_sups_succ (f : ℕ → α) (n : ℕ) : partial_sups f (n + 1) = partial_sups f n ⊔ f (n + 1) := rfl lemma le_partial_sups_of_le (f : ℕ → α) {m n : ℕ} (h : m ≤ n) : f m ≤ partial_sups f n := begin induction n with n ih, { cases h, exact le_rfl, }, { cases h with h h, { exact le_sup_right, }, { exact (ih h).trans le_sup_left, } }, end lemma le_partial_sups (f : ℕ → α) : f ≤ partial_sups f := λ n, le_partial_sups_of_le f le_rfl lemma partial_sups_le (f : ℕ → α) (n : ℕ) (a : α) (w : ∀ m, m ≤ n → f m ≤ a) : partial_sups f n ≤ a := begin induction n with n ih, { apply w 0 le_rfl, }, { exact sup_le (ih (λ m p, w m (nat.le_succ_of_le p))) (w (n + 1) le_rfl) } end lemma monotone.partial_sups_eq {f : ℕ → α} (hf : monotone f) : (partial_sups f : ℕ → α) = f := begin ext n, induction n with n ih, { refl }, { rw [partial_sups_succ, ih, sup_eq_right.2 (hf (nat.le_succ _))] } end lemma partial_sups_mono : monotone (partial_sups : (ℕ → α) → ℕ →o α) := begin rintro f g h n, induction n with n ih, { exact h 0 }, { exact sup_le_sup ih (h _) } end /-- `partial_sups` forms a Galois insertion with the coercion from monotone functions to functions. -/ def partial_sups.gi : galois_insertion (partial_sups : (ℕ → α) → ℕ →o α) coe_fn := { choice := λ f h, ⟨f, begin convert (partial_sups f).monotone, exact (le_partial_sups f).antisymm h, end⟩, gc := λ f g, begin refine ⟨(le_partial_sups f).trans, λ h, _⟩, convert partial_sups_mono h, exact order_hom.ext _ _ g.monotone.partial_sups_eq.symm, end, le_l_u := λ f, le_partial_sups f, choice_eq := λ f h, order_hom.ext _ _ ((le_partial_sups f).antisymm h) } lemma partial_sups_eq_sup'_range (f : ℕ → α) (n : ℕ) : partial_sups f n = (finset.range (n + 1)).sup' ⟨n, finset.self_mem_range_succ n⟩ f := begin induction n with n ih, { simp }, { dsimp [partial_sups] at ih ⊢, simp_rw @finset.range_succ n.succ, rw [ih, finset.sup'_insert, sup_comm] } end end semilattice_sup lemma partial_sups_eq_sup_range [semilattice_sup α] [order_bot α] (f : ℕ → α) (n : ℕ) : partial_sups f n = (finset.range (n + 1)).sup f := begin induction n with n ih, { simp }, { dsimp [partial_sups] at ih ⊢, rw [finset.range_succ, finset.sup_insert, sup_comm, ih] } end /- Note this lemma requires a distributive lattice, so is not useful (or true) in situations such as submodules. -/ lemma partial_sups_disjoint_of_disjoint [distrib_lattice α] [order_bot α] (f : ℕ → α) (h : pairwise (disjoint on f)) {m n : ℕ} (hmn : m < n) : disjoint (partial_sups f m) (f n) := begin induction m with m ih, { exact h 0 n hmn.ne, }, { rw [partial_sups_succ, disjoint_sup_left], exact ⟨ih (nat.lt_of_succ_lt hmn), h (m + 1) n hmn.ne⟩ } end section complete_lattice variables [complete_lattice α] lemma partial_sups_eq_bsupr (f : ℕ → α) (n : ℕ) : partial_sups f n = ⨆ (i ≤ n), f i := begin rw [partial_sups_eq_sup_range, finset.sup_eq_supr], congr, ext a, exact supr_congr_Prop (by rw [finset.mem_range, nat.lt_succ_iff]) (λ _, rfl), end @[simp] lemma supr_partial_sups_eq (f : ℕ → α) : (⨆ n, partial_sups f n) = ⨆ n, f n := begin refine (supr_le $ λ n, _).antisymm (supr_le_supr $ le_partial_sups f), rw partial_sups_eq_bsupr, exact bsupr_le_supr _ _, end lemma supr_le_supr_of_partial_sups_le_partial_sups {f g : ℕ → α} (h : partial_sups f ≤ partial_sups g) : (⨆ n, f n) ≤ ⨆ n, g n := begin rw [←supr_partial_sups_eq f, ←supr_partial_sups_eq g], exact supr_le_supr h, end lemma supr_eq_supr_of_partial_sups_eq_partial_sups {f g : ℕ → α} (h : partial_sups f = partial_sups g) : (⨆ n, f n) = ⨆ n, g n := by simp_rw [←supr_partial_sups_eq f, ←supr_partial_sups_eq g, h] end complete_lattice
199b92a8ca799f7cde6b480d693410f86ccef052
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Meta/Match/Basic.lean
ef7aa4212f98692347464b61d7ecf94a3c6c37a9
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,734
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.Check import Lean.Meta.Match.MatcherInfo import Lean.Meta.Match.CaseArraySizes namespace Lean.Meta.Match inductive Pattern : Type where | inaccessible (e : Expr) : Pattern | var (fvarId : FVarId) : Pattern | ctor (ctorName : Name) (us : List Level) (params : List Expr) (fields : List Pattern) : Pattern | val (e : Expr) : Pattern | arrayLit (type : Expr) (xs : List Pattern) : Pattern | as (varId : FVarId) (p : Pattern) : Pattern deriving Inhabited namespace Pattern partial def toMessageData : Pattern → MessageData | inaccessible e => m!".({e})" | var varId => mkFVar varId | ctor ctorName _ _ [] => ctorName | ctor ctorName _ _ pats => m!"({ctorName}{pats.foldl (fun (msg : MessageData) pat => msg ++ " " ++ toMessageData pat) Format.nil})" | val e => e | arrayLit _ pats => m!"#[{MessageData.joinSep (pats.map toMessageData) ", "}]" | as varId p => m!"{mkFVar varId}@{toMessageData p}" partial def toExpr (p : Pattern) (annotate := false) : MetaM Expr := visit p where visit (p : Pattern) := do match p with | inaccessible e => if annotate then pure (mkAnnotation `inaccessible e) else pure e | var fvarId => pure $ mkFVar fvarId | val e => pure e | as fvarId p => if annotate then mkAppM `namedPattern #[mkFVar fvarId, (← visit p)] else visit p | arrayLit type xs => let xs ← xs.mapM visit mkArrayLit type xs | ctor ctorName us params fields => let fields ← fields.mapM visit pure $ mkAppN (mkConst ctorName us) (params ++ fields).toArray /- Apply the free variable substitution `s` to the given pattern -/ partial def applyFVarSubst (s : FVarSubst) : Pattern → Pattern | inaccessible e => inaccessible $ s.apply e | ctor n us ps fs => ctor n us (ps.map s.apply) $ fs.map (applyFVarSubst s) | val e => val $ s.apply e | arrayLit t xs => arrayLit (s.apply t) $ xs.map (applyFVarSubst s) | var fvarId => match s.find? fvarId with | some e => inaccessible e | none => var fvarId | as fvarId p => match s.find? fvarId with | none => as fvarId $ applyFVarSubst s p | some _ => applyFVarSubst s p def replaceFVarId (fvarId : FVarId) (v : Expr) (p : Pattern) : Pattern := let s : FVarSubst := {} p.applyFVarSubst (s.insert fvarId v) partial def hasExprMVar : Pattern → Bool | inaccessible e => e.hasExprMVar | ctor _ _ ps fs => ps.any (·.hasExprMVar) || fs.any hasExprMVar | val e => e.hasExprMVar | as _ p => hasExprMVar p | arrayLit t xs => t.hasExprMVar || xs.any hasExprMVar | _ => false end Pattern partial def instantiatePatternMVars : Pattern → MetaM Pattern | Pattern.inaccessible e => return Pattern.inaccessible (← instantiateMVars e) | Pattern.val e => return Pattern.val (← instantiateMVars e) | Pattern.ctor n us ps fields => return Pattern.ctor n us (← ps.mapM instantiateMVars) (← fields.mapM instantiatePatternMVars) | Pattern.as x p => return Pattern.as x (← instantiatePatternMVars p) | Pattern.arrayLit t xs => return Pattern.arrayLit (← instantiateMVars t) (← xs.mapM instantiatePatternMVars) | p => return p structure AltLHS where ref : Syntax fvarDecls : List LocalDecl -- Free variables used in the patterns. patterns : List Pattern -- We use `List Pattern` since we have nary match-expressions. def instantiateAltLHSMVars (altLHS : AltLHS) : MetaM AltLHS := return { altLHS with fvarDecls := (← altLHS.fvarDecls.mapM instantiateLocalDeclMVars), patterns := (← altLHS.patterns.mapM instantiatePatternMVars) } structure Alt where ref : Syntax idx : Nat -- for generating error messages rhs : Expr fvarDecls : List LocalDecl patterns : List Pattern deriving Inhabited namespace Alt partial def toMessageData (alt : Alt) : MetaM MessageData := do withExistingLocalDecls alt.fvarDecls do let msg : List MessageData := alt.fvarDecls.map fun d => m!"{d.toExpr}:({d.type})" let msg : MessageData := m!"{msg} |- {alt.patterns.map Pattern.toMessageData} => {alt.rhs}" addMessageContext msg def applyFVarSubst (s : FVarSubst) (alt : Alt) : Alt := { alt with patterns := alt.patterns.map fun p => p.applyFVarSubst s, fvarDecls := alt.fvarDecls.map fun d => d.applyFVarSubst s, rhs := alt.rhs.applyFVarSubst s } def replaceFVarId (fvarId : FVarId) (v : Expr) (alt : Alt) : Alt := { alt with patterns := alt.patterns.map fun p => p.replaceFVarId fvarId v, fvarDecls := let decls := alt.fvarDecls.filter fun d => d.fvarId != fvarId decls.map $ replaceFVarIdAtLocalDecl fvarId v, rhs := alt.rhs.replaceFVarId fvarId v } /- Similar to `checkAndReplaceFVarId`, but ensures type of `v` is definitionally equal to type of `fvarId`. This extra check is necessary when performing dependent elimination and inaccessible terms have been used. For example, consider the following code fragment: ``` inductive Vec (α : Type u) : Nat → Type u where | nil : Vec α 0 | cons {n} (head : α) (tail : Vec α n) : Vec α (n+1) inductive VecPred {α : Type u} (P : α → Prop) : {n : Nat} → Vec α n → Prop where | nil : VecPred P Vec.nil | cons {n : Nat} {head : α} {tail : Vec α n} : P head → VecPred P tail → VecPred P (Vec.cons head tail) theorem ex {α : Type u} (P : α → Prop) : {n : Nat} → (v : Vec α (n+1)) → VecPred P v → Exists P | _, Vec.cons head _, VecPred.cons h (w : VecPred P Vec.nil) => ⟨head, h⟩ ``` Recall that `_` in a pattern can be elaborated into pattern variable or an inaccessible term. The elaborator uses an inaccessible term when typing constraints restrict its value. Thus, in the example above, the `_` at `Vec.cons head _` becomes the inaccessible pattern `.(Vec.nil)` because the type ascription `(w : VecPred P Vec.nil)` propagates typing constraints that restrict its value to be `Vec.nil`. After elaboration the alternative becomes: ``` | .(0), @Vec.cons .(α) .(0) head .(Vec.nil), @VecPred.cons .(α) .(P) .(0) .(head) .(Vec.nil) h w => ⟨head, h⟩ ``` where ``` (head : α), (h: P head), (w : VecPred P Vec.nil) ``` Then, when we process this alternative in this module, the following check will detect that `w` has type `VecPred P Vec.nil`, when it is supposed to have type `VecPred P tail`. Note that if we had written ``` theorem ex {α : Type u} (P : α → Prop) : {n : Nat} → (v : Vec α (n+1)) → VecPred P v → Exists P | _, Vec.cons head Vec.nil, VecPred.cons h (w : VecPred P Vec.nil) => ⟨head, h⟩ ``` we would get the easier to digest error message ``` missing cases: _, (Vec.cons _ _ (Vec.cons _ _ _)), _ ``` -/ def checkAndReplaceFVarId (fvarId : FVarId) (v : Expr) (alt : Alt) : MetaM Alt := do match alt.fvarDecls.find? fun (fvarDecl : LocalDecl) => fvarDecl.fvarId == fvarId with | none => throwErrorAt alt.ref "unknown free pattern variable" | some fvarDecl => do let vType ← inferType v unless (← isDefEqGuarded fvarDecl.type vType) do withExistingLocalDecls alt.fvarDecls do let (expectedType, givenType) ← addPPExplicitToExposeDiff vType fvarDecl.type throwErrorAt alt.ref $ m!"type mismatch during dependent match-elimination at pattern variable '{mkFVar fvarDecl.fvarId}' with type{indentExpr givenType}\nexpected type{indentExpr expectedType}" pure $ replaceFVarId fvarId v alt end Alt inductive Example where | var : FVarId → Example | underscore : Example | ctor : Name → List Example → Example | val : Expr → Example | arrayLit : List Example → Example namespace Example partial def replaceFVarId (fvarId : FVarId) (ex : Example) : Example → Example | var x => if x == fvarId then ex else var x | ctor n exs => ctor n $ exs.map (replaceFVarId fvarId ex) | arrayLit exs => arrayLit $ exs.map (replaceFVarId fvarId ex) | ex => ex partial def applyFVarSubst (s : FVarSubst) : Example → Example | var fvarId => match s.get fvarId with | Expr.fvar fvarId' _ => var fvarId' | _ => underscore | ctor n exs => ctor n $ exs.map (applyFVarSubst s) | arrayLit exs => arrayLit $ exs.map (applyFVarSubst s) | ex => ex partial def varsToUnderscore : Example → Example | var x => underscore | ctor n exs => ctor n $ exs.map varsToUnderscore | arrayLit exs => arrayLit $ exs.map varsToUnderscore | ex => ex partial def toMessageData : Example → MessageData | var fvarId => mkFVar fvarId | ctor ctorName [] => mkConst ctorName | ctor ctorName exs => m!"({mkConst ctorName}{exs.foldl (fun msg pat => m!"{msg} {toMessageData pat}") Format.nil})" | arrayLit exs => "#" ++ MessageData.ofList (exs.map toMessageData) | val e => e | underscore => "_" end Example def examplesToMessageData (cex : List Example) : MessageData := MessageData.joinSep (cex.map (Example.toMessageData ∘ Example.varsToUnderscore)) ", " structure Problem where mvarId : MVarId vars : List Expr alts : List Alt examples : List Example deriving Inhabited def withGoalOf {α} (p : Problem) (x : MetaM α) : MetaM α := withMVarContext p.mvarId x def Problem.toMessageData (p : Problem) : MetaM MessageData := withGoalOf p do let alts ← p.alts.mapM Alt.toMessageData let vars ← p.vars.mapM fun x => do let xType ← inferType x; pure m!"{x}:({xType})" return m!"remaining variables: {vars}\nalternatives:{indentD (MessageData.joinSep alts Format.line)}\nexamples:{examplesToMessageData p.examples}\n" abbrev CounterExample := List Example def counterExampleToMessageData (cex : CounterExample) : MessageData := examplesToMessageData cex def counterExamplesToMessageData (cexs : List CounterExample) : MessageData := MessageData.joinSep (cexs.map counterExampleToMessageData) Format.line structure MatcherResult where matcher : Expr -- The matcher. It is not just `Expr.const matcherName` because the type of the major premises may contain free variables. counterExamples : List CounterExample unusedAltIdxs : List Nat end Lean.Meta.Match
bd9755627eccded1fe329e6aab092acca902650c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/ProjFns.lean
e48f028e0c2a79cfe8f2cb27fcc6d40ee888be5c
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
2,477
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Environment namespace Lean /-- Given a structure `S`, Lean automatically creates an auxiliary definition (projection function) for each field. This structure caches information about these auxiliary definitions. -/ structure ProjectionFunctionInfo where /-- Constructor associated with the auxiliary projection function. -/ ctorName : Name /-- Number of parameters in the structure -/ numParams : Nat /-- The field index associated with the auxiliary projection function. -/ i : Nat /-- `true` if the structure is a class. -/ fromClass : Bool deriving Inhabited @[export lean_mk_projection_info] def mkProjectionInfoEx (ctorName : Name) (numParams : Nat) (i : Nat) (fromClass : Bool) : ProjectionFunctionInfo := { ctorName, numParams, i, fromClass } @[export lean_projection_info_from_class] def ProjectionFunctionInfo.fromClassEx (info : ProjectionFunctionInfo) : Bool := info.fromClass builtin_initialize projectionFnInfoExt : MapDeclarationExtension ProjectionFunctionInfo ← mkMapDeclarationExtension @[export lean_add_projection_info] def addProjectionFnInfo (env : Environment) (projName : Name) (ctorName : Name) (numParams : Nat) (i : Nat) (fromClass : Bool) : Environment := projectionFnInfoExt.insert env projName { ctorName, numParams, i, fromClass } namespace Environment @[export lean_get_projection_info] def getProjectionFnInfo? (env : Environment) (projName : Name) : Option ProjectionFunctionInfo := projectionFnInfoExt.find? env projName def isProjectionFn (env : Environment) (declName : Name) : Bool := projectionFnInfoExt.contains env declName /-- If `projName` is the name of a projection function, return the associated structure name -/ def getProjectionStructureName? (env : Environment) (projName : Name) : Option Name := match env.getProjectionFnInfo? projName with | none => none | some projInfo => match env.find? projInfo.ctorName with | some (ConstantInfo.ctorInfo val) => some val.induct | _ => none end Environment def isProjectionFn [MonadEnv m] [Monad m] (declName : Name) : m Bool := return (← getEnv).isProjectionFn declName def getProjectionFnInfo? [MonadEnv m] [Monad m] (declName : Name) : m (Option ProjectionFunctionInfo) := return (← getEnv).getProjectionFnInfo? declName end Lean
21e88fe4118112f3e46125a67710f855aa77a050
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Init/Control/Except.lean
53dba7e2098cb32e41a56b6026a9a3dbff2374e0
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,140
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jared Roesch, Sebastian Ullrich The Except monad transformer. -/ prelude import Init.Control.Basic import Init.Control.Id universes u v w u' namespace Except variables {ε : Type u} @[inline] protected def pure {α : Type v} (a : α) : Except ε α := Except.ok a @[inline] protected def map {α β : Type v} (f : α → β) : Except ε α → Except ε β | Except.error err => Except.error err | Except.ok v => Except.ok <| f v @[inline] protected def mapError {ε' : Type u} {α : Type v} (f : ε → ε') : Except ε α → Except ε' α | Except.error err => Except.error <| f err | Except.ok v => Except.ok v @[inline] protected def bind {α β : Type v} (ma : Except ε α) (f : α → Except ε β) : Except ε β := match ma with | Except.error err => Except.error err | Except.ok v => f v @[inline] protected def toBool {α : Type v} : Except ε α → Bool | Except.ok _ => true | Except.error _ => false @[inline] protected def toOption {α : Type v} : Except ε α → Option α | Except.ok a => some a | Except.error _ => none @[inline] protected def tryCatch {α : Type u} (ma : Except ε α) (handle : ε → Except ε α) : Except ε α := match ma with | Except.ok a => Except.ok a | Except.error e => handle e instance : Monad (Except ε) where pure := Except.pure bind := Except.bind map := Except.map end Except def ExceptT (ε : Type u) (m : Type u → Type v) (α : Type u) : Type v := m (Except ε α) @[inline] def ExceptT.mk {ε : Type u} {m : Type u → Type v} {α : Type u} (x : m (Except ε α)) : ExceptT ε m α := x @[inline] def ExceptT.run {ε : Type u} {m : Type u → Type v} {α : Type u} (x : ExceptT ε m α) : m (Except ε α) := x namespace ExceptT variables {ε : Type u} {m : Type u → Type v} [Monad m] @[inline] protected def pure {α : Type u} (a : α) : ExceptT ε m α := ExceptT.mk <| pure (Except.ok a) @[inline] protected def bindCont {α β : Type u} (f : α → ExceptT ε m β) : Except ε α → m (Except ε β) | Except.ok a => f a | Except.error e => pure (Except.error e) @[inline] protected def bind {α β : Type u} (ma : ExceptT ε m α) (f : α → ExceptT ε m β) : ExceptT ε m β := ExceptT.mk <| ma >>= ExceptT.bindCont f @[inline] protected def map {α β : Type u} (f : α → β) (x : ExceptT ε m α) : ExceptT ε m β := ExceptT.mk <| x >>= fun a => match a with | (Except.ok a) => pure <| Except.ok (f a) | (Except.error e) => pure <| Except.error e @[inline] protected def lift {α : Type u} (t : m α) : ExceptT ε m α := ExceptT.mk <| Except.ok <$> t instance : MonadLift (Except ε) (ExceptT ε m) := ⟨fun e => ExceptT.mk <| pure e⟩ instance : MonadLift m (ExceptT ε m) := ⟨ExceptT.lift⟩ @[inline] protected def tryCatch {α : Type u} (ma : ExceptT ε m α) (handle : ε → ExceptT ε m α) : ExceptT ε m α := ExceptT.mk <| ma >>= fun res => match res with | Except.ok a => pure (Except.ok a) | Except.error e => (handle e) instance : MonadFunctor m (ExceptT ε m) := ⟨fun f x => f x⟩ instance : Monad (ExceptT ε m) where pure := ExceptT.pure bind := ExceptT.bind map := ExceptT.map @[inline] protected def adapt {ε' α : Type u} (f : ε → ε') : ExceptT ε m α → ExceptT ε' m α := fun x => ExceptT.mk <| Except.mapError f <$> x end ExceptT instance (m : Type u → Type v) (ε₁ : Type u) (ε₂ : Type u) [Monad m] [MonadExceptOf ε₁ m] : MonadExceptOf ε₁ (ExceptT ε₂ m) where throw e := ExceptT.mk <| throwThe ε₁ e tryCatch x handle := ExceptT.mk <| tryCatchThe ε₁ x handle instance (m : Type u → Type v) (ε : Type u) [Monad m] : MonadExceptOf ε (ExceptT ε m) where throw e := ExceptT.mk <| pure (Except.error e) tryCatch := ExceptT.tryCatch instance [Monad m] [Inhabited ε] : Inhabited (ExceptT ε m α) where default := throw arbitrary instance (ε) : MonadExceptOf ε (Except ε) where throw := Except.error tryCatch := Except.tryCatch namespace MonadExcept variables {ε : Type u} {m : Type v → Type w} /-- Alternative orelse operator that allows to select which exception should be used. The default is to use the first exception since the standard `orelse` uses the second. -/ @[inline] def orelse' [MonadExcept ε m] {α : Type v} (t₁ t₂ : m α) (useFirstEx := true) : m α := tryCatch t₁ fun e₁ => tryCatch t₂ fun e₂ => throw (if useFirstEx = true then e₁ else e₂) end MonadExcept @[inline] def observing {ε α : Type u} {m : Type u → Type v} [Monad m] [MonadExcept ε m] (x : m α) : m (Except ε α) := tryCatch (do let a ← x; pure (Except.ok a)) (fun ex => pure (Except.error ex)) instance (ε : Type u) (m : Type u → Type v) [Monad m] : MonadControl m (ExceptT ε m) where stM := Except ε liftWith f := liftM <| f fun x => x.run restoreM x := x class MonadFinally (m : Type u → Type v) where tryFinally' {α β} : m α → (Option α → m β) → m (α × β) export MonadFinally (tryFinally') /-- Execute `x` and then execute `finalizer` even if `x` threw an exception -/ @[inline] abbrev tryFinally {m : Type u → Type v} {α β : Type u} [MonadFinally m] [Functor m] (x : m α) (finalizer : m β) : m α := let y := tryFinally' x (fun _ => finalizer) (·.1) <$> y instance Id.finally : MonadFinally Id where tryFinally' := fun x h => let a := x let b := h (some x) pure (a, b) instance ExceptT.finally {m : Type u → Type v} {ε : Type u} [MonadFinally m] [Monad m] : MonadFinally (ExceptT ε m) where tryFinally' := fun x h => ExceptT.mk do let r ← tryFinally' x fun e? => match e? with | some (Except.ok a) => h (some a) | _ => h none match r with | (Except.ok a, Except.ok b) => pure (Except.ok (a, b)) | (_, Except.error e) => pure (Except.error e) -- second error has precedence | (Except.error e, _) => pure (Except.error e)
0fd3a6f0f082b2db2cec4862370727c530f42ce0
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/ring/comp_typeclasses.lean
2a10e273aa4ffa674547ed4e477d2cbd760abaf8
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
6,479
lean
/- Copyright (c) 2021 Frédéric Dupuis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Frédéric Dupuis, Heather Macbeth -/ import algebra.ring.basic import data.equiv.ring /-! # Propositional typeclasses on several ring homs This file contains three typeclasses used in the definition of (semi)linear maps: * `ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃`, which expresses the fact that `σ₂₃.comp σ₁₂ = σ₁₃` * `ring_hom_inv_pair σ₁₂ σ₂₁`, which states that `σ₁₂` and `σ₂₁` are inverses of each other * `ring_hom_surjective σ`, which states that `σ` is surjective These typeclasses ensure that objects such as `σ₂₃.comp σ₁₂` never end up in the type of a semilinear map; instead, the typeclass system directly finds the appropriate `ring_hom` to use. A typical use-case is conjugate-linear maps, i.e. when `σ = complex.conj`; this system ensures that composing two conjugate-linear maps is a linear map, and not a `conj.comp conj`-linear map. Instances of these typeclasses mostly involving `ring_hom.id` are also provided: * `ring_hom_inv_pair (ring_hom.id R) (ring_hom.id R)` * `[ring_hom_inv_pair σ₁₂ σ₂₁] : ring_hom_comp_triple σ₁₂ σ₂₁ (ring_hom.id R₁)` * `ring_hom_comp_triple (ring_hom.id R₁) σ₁₂ σ₁₂` * `ring_hom_comp_triple σ₁₂ (ring_hom.id R₂) σ₁₂` * `ring_hom_surjective (ring_hom.id R)` * `[ring_hom_inv_pair σ₁ σ₂] : ring_hom_surjective σ₁` ## Implementation notes * For the typeclass `ring_hom_inv_pair σ₁₂ σ₂₁`, `σ₂₁` is marked as an `out_param`, as it must typically be found via the typeclass inference system. * Likewise, for `ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃`, `σ₁₃` is marked as an `out_param`, for the same reason. ## Tags `ring_hom_comp_triple`, `ring_hom_inv_pair`, `ring_hom_surjective` -/ variables {R₁ : Type*} {R₂ : Type*} {R₃ : Type*} variables [semiring R₁] [semiring R₂] [semiring R₃] /-- Class that expresses the fact that three ring homomorphisms form a composition triple. This is used to handle composition of semilinear maps. -/ class ring_hom_comp_triple (σ₁₂ : R₁ →+* R₂) (σ₂₃ : R₂ →+* R₃) (σ₁₃ : out_param (R₁ →+* R₃)) : Prop := (comp_eq : σ₂₃.comp σ₁₂ = σ₁₃) attribute [simp] ring_hom_comp_triple.comp_eq variables {σ₁₂ : R₁ →+* R₂} {σ₂₃ : R₂ →+* R₃} {σ₁₃ : R₁ →+* R₃} namespace ring_hom_comp_triple @[simp] lemma comp_apply [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] {x : R₁} : σ₂₃ (σ₁₂ x) = σ₁₃ x := ring_hom.congr_fun comp_eq x end ring_hom_comp_triple /-- Class that expresses the fact that two ring homomorphisms are inverses of each other. This is used to handle `symm` for semilinear equivalences. -/ class ring_hom_inv_pair (σ : R₁ →+* R₂) (σ' : out_param (R₂ →+* R₁)) : Prop := (comp_eq : σ'.comp σ = ring_hom.id R₁) (comp_eq₂ : σ.comp σ' = ring_hom.id R₂) attribute [simp] ring_hom_inv_pair.comp_eq attribute [simp] ring_hom_inv_pair.comp_eq₂ variables {σ : R₁ →+* R₂} {σ' : R₂ →+* R₁} namespace ring_hom_inv_pair variables [ring_hom_inv_pair σ σ'] @[simp] lemma comp_apply_eq {x : R₁} : σ' (σ x) = x := by { rw [← ring_hom.comp_apply, comp_eq], simp } @[simp] lemma comp_apply_eq₂ {x : R₂} : σ (σ' x) = x := by { rw [← ring_hom.comp_apply, comp_eq₂], simp } instance ids : ring_hom_inv_pair (ring_hom.id R₁) (ring_hom.id R₁) := ⟨rfl, rfl⟩ instance triples {σ₂₁ : R₂ →+* R₁} [ring_hom_inv_pair σ₁₂ σ₂₁] : ring_hom_comp_triple σ₁₂ σ₂₁ (ring_hom.id R₁) := ⟨by simp only [comp_eq]⟩ instance triples₂ {σ₂₁ : R₂ →+* R₁} [ring_hom_inv_pair σ₁₂ σ₂₁] : ring_hom_comp_triple σ₂₁ σ₁₂ (ring_hom.id R₂) := ⟨by simp only [comp_eq₂]⟩ /-- Construct a `ring_hom_inv_pair` from both directions of a ring equiv. This is not an instance, as for equivalences that are involutions, a better instance would be `ring_hom_inv_pair e e`. Indeed, this declaration is not currently used in mathlib. See note [reducible non-instances]. -/ @[reducible] lemma of_ring_equiv (e : R₁ ≃+* R₂) : ring_hom_inv_pair (↑e : R₁ →+* R₂) ↑e.symm := ⟨e.symm_to_ring_hom_comp_to_ring_hom, e.symm.symm_to_ring_hom_comp_to_ring_hom⟩ /-- Swap the direction of a `ring_hom_inv_pair`. This is not an instance as it would loop, and better instances are often available and may often be preferrable to using this one. Indeed, this declaration is not currently used in mathlib. See note [reducible non-instances]. -/ @[reducible] lemma symm (σ₁₂ : R₁ →+* R₂) (σ₂₁ : R₂ →+* R₁) [ring_hom_inv_pair σ₁₂ σ₂₁] : ring_hom_inv_pair σ₂₁ σ₁₂ := ⟨ring_hom_inv_pair.comp_eq₂, ring_hom_inv_pair.comp_eq⟩ end ring_hom_inv_pair namespace ring_hom_comp_triple instance ids : ring_hom_comp_triple (ring_hom.id R₁) σ₁₂ σ₁₂ := ⟨by { ext, simp }⟩ instance right_ids : ring_hom_comp_triple σ₁₂ (ring_hom.id R₂) σ₁₂ := ⟨by { ext, simp }⟩ end ring_hom_comp_triple /-- Class expressing the fact that a `ring_hom` is surjective. This is needed in the context of semilinear maps, where some lemmas require this. -/ class ring_hom_surjective (σ : R₁ →+* R₂) : Prop := (is_surjective : function.surjective σ) lemma ring_hom.is_surjective (σ : R₁ →+* R₂) [t : ring_hom_surjective σ] : function.surjective σ := t.is_surjective namespace ring_hom_surjective -- The linter gives a false positive, since `σ₂` is an out_param @[priority 100, nolint dangerous_instance] instance inv_pair {σ₁ : R₁ →+* R₂} {σ₂ : R₂ →+* R₁} [ring_hom_inv_pair σ₁ σ₂] : ring_hom_surjective σ₁ := ⟨λ x, ⟨σ₂ x, ring_hom_inv_pair.comp_apply_eq₂⟩⟩ instance ids : ring_hom_surjective (ring_hom.id R₁) := ⟨is_surjective⟩ /-- This cannot be an instance as there is no way to infer `σ₁₂` and `σ₂₃`. -/ lemma comp [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] [ring_hom_surjective σ₁₂] [ring_hom_surjective σ₂₃] : ring_hom_surjective σ₁₃ := { is_surjective := begin have := σ₂₃.is_surjective.comp σ₁₂.is_surjective, rwa [← ring_hom.coe_comp, ring_hom_comp_triple.comp_eq] at this, end } end ring_hom_surjective
a67e0bc2762bb3f79182f9eb7e8637c6f547f043
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/analysis/calculus/local_extr.lean
fc241387dfe4ead06b131ad4bcdb5f97a63e2b90
[ "Apache-2.0" ]
permissive
jdsalchow/mathlib
13ab43ef0d0515a17e550b16d09bd14b76125276
497e692b946d93906900bb33a51fd243e7649406
refs/heads/master
1,585,819,143,348
1,580,072,892,000
1,580,072,892,000
154,287,128
0
0
Apache-2.0
1,540,281,610,000
1,540,281,609,000
null
UTF-8
Lean
false
false
14,713
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import topology.local_extr analysis.calculus.deriv /-! # Local extrema of smooth functions ## Main definitions In a real normed space `E` we define `pos_tangent_cone_at (s : set E) (x : E)`. This would be the same as `tangent_cone_at ℝ≥0 s x` if we had a theory of normed semifields. This set is used in the proof of Fermat's Theorem (see below), and can be used to formalize [Lagrange multipliers](https://en.wikipedia.org/wiki/Lagrange_multiplier) and/or [Karush–Kuhn–Tucker conditions](https://en.wikipedia.org/wiki/Karush–Kuhn–Tucker_conditions). ## Main statements For each theorem name listed below, we also prove similar theorems for `min`, `extr` (if applicable)`, and `(f)deriv` instead of `has_fderiv`. * `is_local_max_on.has_fderiv_within_at_nonpos` : `f' y ≤ 0` whenever `a` is a local maximum of `f` on `s`, `f` has derivative `f'` at `a` within `s`, and `y` belongs to the positive tangent cone of `s` at `a`. * `is_local_max_on.has_fderiv_within_at_eq_zero` : In the settings of the previous theorem, if both `y` and `-y` belong to the positive tangent cone, then `f' y = 0`. * `is_local_max.has_fderiv_at_eq_zero` : [Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points)), the derivative of a differentiable function at a local extremum point equals zero. * `exists_has_deriv_at_eq_zero` : [Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem): given a function `f` continuous on `[a, b]` and differentiable on `(a, b)`, there exists `c ∈ (a, b)` such that `f' c = 0`. ## Implementation notes For each mathematical fact we prove several versions of its formalization: * for maxima and minima; * using `has_fderiv*`/`has_deriv*` or `fderiv*`/`deriv*`. For the `fderiv*`/`deriv*` versions we omit the differentiability condition whenever it is possible due to the fact that `fderiv` and `deriv` are defined to be zero for non-differentiable functions. ## References * [Fermat's Theorem](https://en.wikipedia.org/wiki/Fermat's_theorem_(stationary_points)); * [Rolle's Theorem](https://en.wikipedia.org/wiki/Rolle's_theorem); * [Tangent cone](https://en.wikipedia.org/wiki/Tangent_cone); ## Tags local extremum, Fermat's Theorem, Rolle's Theorem -/ universes u v open filter set open_locale topological_space classical section vector_space variables {E : Type u} [normed_group E] [normed_space ℝ E] {f : E → ℝ} {a : E} {f' : E →L[ℝ] ℝ} /-- "Positive" tangent cone to `s` at `x`; the only difference from `tangent_cone_at` is that we require `c n → ∞` instead of `∥c n∥ → ∞`. One can think about `pos_tangent_cone_at` as `tangent_cone_at nnreal` but we have no theory of normed semifields yet. -/ def pos_tangent_cone_at (s : set E) (x : E) : set E := {y : E | ∃(c : ℕ → ℝ) (d : ℕ → E), {n:ℕ | x + d n ∈ s} ∈ (at_top : filter ℕ) ∧ (tendsto c at_top at_top) ∧ (tendsto (λn, c n • d n) at_top (𝓝 y))} lemma pos_tangent_cone_at_mono : monotone (λ s, pos_tangent_cone_at s a) := begin rintros s t hst y ⟨c, d, hd, hc, hcd⟩, exact ⟨c, d, mem_sets_of_superset hd $ λ h hn, hst hn, hc, hcd⟩ end lemma mem_pos_tangent_cone_at_of_segment_subset {s : set E} {x y : E} (h : segment x y ⊆ s) : y - x ∈ pos_tangent_cone_at s x := begin let c := λn:ℕ, (2:ℝ)^n, let d := λn:ℕ, (c n)⁻¹ • (y-x), refine ⟨c, d, filter.univ_mem_sets' (λn, h _), _, _⟩, show x + d n ∈ segment x y, { refine ⟨(c n)⁻¹, ⟨_, _⟩, _⟩, { rw inv_nonneg, apply pow_nonneg, norm_num }, { apply inv_le_one, apply one_le_pow_of_one_le, norm_num }, { simp only [d], abel } }, show tendsto c at_top at_top, { exact tendsto_pow_at_top_at_top_of_gt_1 one_lt_two }, show filter.tendsto (λ (n : ℕ), c n • d n) filter.at_top (𝓝 (y - x)), { have : (λ (n : ℕ), c n • d n) = (λn, y - x), { ext n, simp only [d, smul_smul], rw [mul_inv_cancel, one_smul], exact pow_ne_zero _ (by norm_num) }, rw this, apply tendsto_const_nhds } end lemma pos_tangent_cone_at_univ : pos_tangent_cone_at univ a = univ := eq_univ_iff_forall.2 begin assume x, rw [← add_sub_cancel x a], exact mem_pos_tangent_cone_at_of_segment_subset (subset_univ _) end /-- If `f` has a local max on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and `y` belongs to the positive tangent cone of s at a, then `f' y ≤ 0`. -/ lemma is_local_max_on.has_fderiv_within_at_nonpos {s : set E} (h : is_local_max_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : f' y ≤ 0 := begin rcases hy with ⟨c, d, hd, hc, hcd⟩, have hc' : tendsto (λ n, ∥c n∥) at_top at_top, from tendsto_at_top_mono _ (λ n, le_abs_self _) hc, refine le_of_tendsto at_top_ne_bot (hf.lim at_top hd hc' hcd) _, replace hd : tendsto (λ n, a + d n) at_top (nhds_within (a + 0) s), from tendsto_inf.2 ⟨tendsto_const_nhds.add (tangent_cone_at.lim_zero _ hc' hcd), by rwa tendsto_principal⟩, rw [add_zero] at hd, replace h : {n : ℕ | f (a + d n) ≤ f a} ∈ at_top, from mem_map.1 (hd h), replace hc : {n | 0 ≤ c n} ∈ at_top, from mem_map.1 (hc (mem_at_top (0:ℝ))), filter_upwards [h, hc], simp only [mem_set_of_eq, smul_eq_mul, mem_preimage, subset_def], assume n hnf hn, exact mul_nonpos_of_nonneg_of_nonpos hn (sub_nonpos.2 hnf) end /-- If `f` has a local max on `s` at `a`, `f` is differentiable at `a` within `s`, and `y` belongs to the positive tangent cone of s at a, then `f' y ≤ 0`. -/ lemma is_local_max_on.fderiv_within_nonpos {s : set E} (h : is_local_max_on f s a) (hf : differentiable_within_at ℝ f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : (fderiv_within ℝ f s a : E → ℝ) y ≤ 0 := h.has_fderiv_within_at_nonpos hf.has_fderiv_within_at hy /-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and both `y` and `-y` belong to the positive tangent cone of s at a, then `f' y ≤ 0`. -/ lemma is_local_max_on.has_fderiv_within_at_eq_zero {s : set E} (h : is_local_max_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : f' y = 0 := le_antisymm (h.has_fderiv_within_at_nonpos hf hy) $ by simpa using h.has_fderiv_within_at_nonpos hf hy' /-- If `f` has a local max on `s` at `a` and both `y` and `-y` belong to the positive tangent cone of s at a, then `f' y = 0`. -/ lemma is_local_max_on.fderiv_within_eq_zero {s : set E} (h : is_local_max_on f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : (fderiv_within ℝ f s a : E → ℝ) y = 0 := if hf : differentiable_within_at ℝ f s a then h.has_fderiv_within_at_eq_zero hf.has_fderiv_within_at hy hy' else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl } /-- If `f` has a local min on `s` at `a`, `f'` is the derivative of `f` at `a` within `s`, and `y` belongs to the positive tangent cone of s at a, then `0 ≤ f' y`. -/ lemma is_local_min_on.has_fderiv_within_at_nonneg {s : set E} (h : is_local_min_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : 0 ≤ f' y := by simpa using h.neg.has_fderiv_within_at_nonpos hf.neg hy /-- If `f` has a local min on `s` at `a`, `f` is differentiable at `a` within `s`, and `y` belongs to the positive tangent cone of s at a, then `0 ≤ f' y`. -/ lemma is_local_min_on.fderiv_within_nonneg {s : set E} (h : is_local_min_on f s a) (hf : differentiable_within_at ℝ f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) : (0:ℝ) ≤ (fderiv_within ℝ f s a : E → ℝ) y := h.has_fderiv_within_at_nonneg hf.has_fderiv_within_at hy /-- If `f` has a local max on `s` at `a`, `f'` is a derivative of `f` at `a` within `s`, and both `y` and `-y` belong to the positive tangent cone of s at a, then `f' y ≤ 0`. -/ lemma is_local_min_on.has_fderiv_within_at_eq_zero {s : set E} (h : is_local_min_on f s a) (hf : has_fderiv_within_at f f' s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : f' y = 0 := by simpa using h.neg.has_fderiv_within_at_eq_zero hf.neg hy hy' /-- If `f` has a local min on `s` at `a` and both `y` and `-y` belong to the positive tangent cone of s at a, then `f' y = 0`. -/ lemma is_local_min_on.fderiv_within_eq_zero {s : set E} (h : is_local_min_on f s a) {y} (hy : y ∈ pos_tangent_cone_at s a) (hy' : -y ∈ pos_tangent_cone_at s a) : (fderiv_within ℝ f s a : E → ℝ) y = 0 := if hf : differentiable_within_at ℝ f s a then h.has_fderiv_within_at_eq_zero hf.has_fderiv_within_at hy hy' else by { rw fderiv_within_zero_of_not_differentiable_within_at hf, refl } /-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/ lemma is_local_min.has_fderiv_at_eq_zero (h : is_local_min f a) (hf : has_fderiv_at f f' a) : f' = 0 := begin ext y, apply (h.on univ).has_fderiv_within_at_eq_zero hf.has_fderiv_within_at; rw pos_tangent_cone_at_univ; apply mem_univ end /-- Fermat's Theorem: the derivative of a function at a local minimum equals zero. -/ lemma is_local_min.fderiv_eq_zero (h : is_local_min f a) : fderiv ℝ f a = 0 := if hf : differentiable_at ℝ f a then h.has_fderiv_at_eq_zero hf.has_fderiv_at else fderiv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/ lemma is_local_max.has_fderiv_at_eq_zero (h : is_local_max f a) (hf : has_fderiv_at f f' a) : f' = 0 := neg_eq_zero.1 $ h.neg.has_fderiv_at_eq_zero hf.neg /-- Fermat's Theorem: the derivative of a function at a local maximum equals zero. -/ lemma is_local_max.fderiv_eq_zero (h : is_local_max f a) : fderiv ℝ f a = 0 := if hf : differentiable_at ℝ f a then h.has_fderiv_at_eq_zero hf.has_fderiv_at else fderiv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.has_fderiv_at_eq_zero (h : is_local_extr f a) : has_fderiv_at f f' a → f' = 0 := h.elim is_local_min.has_fderiv_at_eq_zero is_local_max.has_fderiv_at_eq_zero /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.fderiv_eq_zero (h : is_local_extr f a) : fderiv ℝ f a = 0 := h.elim is_local_min.fderiv_eq_zero is_local_max.fderiv_eq_zero end vector_space section real variables {f : ℝ → ℝ} {f' : ℝ} {a b : ℝ} /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ lemma is_local_min.has_deriv_at_eq_zero (h : is_local_min f a) (hf : has_deriv_at f f' a) : f' = 0 := by simpa using continuous_linear_map.ext_iff.1 (h.has_fderiv_at_eq_zero (has_deriv_at_iff_has_fderiv_at.1 hf)) 1 /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ lemma is_local_min.deriv_eq_zero (h : is_local_min f a) : deriv f a = 0 := if hf : differentiable_at ℝ f a then h.has_deriv_at_eq_zero hf.has_deriv_at else deriv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ lemma is_local_max.has_deriv_at_eq_zero (h : is_local_max f a) (hf : has_deriv_at f f' a) : f' = 0 := neg_eq_zero.1 $ h.neg.has_deriv_at_eq_zero hf.neg /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ lemma is_local_max.deriv_eq_zero (h : is_local_max f a) : deriv f a = 0 := if hf : differentiable_at ℝ f a then h.has_deriv_at_eq_zero hf.has_deriv_at else deriv_zero_of_not_differentiable_at hf /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.has_deriv_at_eq_zero (h : is_local_extr f a) : has_deriv_at f f' a → f' = 0 := h.elim is_local_min.has_deriv_at_eq_zero is_local_max.has_deriv_at_eq_zero /-- Fermat's Theorem: the derivative of a function at a local extremum equals zero. -/ lemma is_local_extr.deriv_eq_zero (h : is_local_extr f a) : deriv f a = 0 := h.elim is_local_min.deriv_eq_zero is_local_max.deriv_eq_zero end real section Rolle variables (f f' : ℝ → ℝ) {a b : ℝ} (hab : a < b) (hfc : continuous_on f (Icc a b)) (hfI : f a = f b) include hab hfc hfI /-- A continuous function on a closed interval with `f a = f b` takes either its maximum or its minimum value at a point in the interior of the interval. -/ lemma exists_Ioo_extr_on_Icc : ∃ c ∈ Ioo a b, is_extr_on f (Icc a b) c := begin have ne : Icc a b ≠ ∅, from ne_empty_of_mem (left_mem_Icc.2 (le_of_lt hab)), -- Consider absolute min and max points obtain ⟨c, cmem, cle⟩ : ∃ c ∈ Icc a b, ∀ x ∈ Icc a b, f c ≤ f x, from compact_Icc.exists_forall_le ne hfc, obtain ⟨C, Cmem, Cge⟩ : ∃ C ∈ Icc a b, ∀ x ∈ Icc a b, f x ≤ f C, from compact_Icc.exists_forall_ge ne hfc, by_cases hc : f c = f a, { by_cases hC : f C = f a, { have : ∀ x ∈ Icc a b, f x = f a, from λ x hx, le_antisymm (hC ▸ Cge x hx) (hc ▸ cle x hx), -- `f` is a constant, so we can take any point in `Ioo a b` rcases dense hab with ⟨c', hc'⟩, refine ⟨c', hc', or.inl _⟩, assume x hx, rw [mem_set_of_eq, this x hx, ← hC], exact Cge c' ⟨le_of_lt hc'.1, le_of_lt hc'.2⟩ }, { refine ⟨C, ⟨lt_of_le_of_ne Cmem.1 $ mt _ hC, lt_of_le_of_ne Cmem.2 $ mt _ hC⟩, or.inr Cge⟩, exacts [λ h, by rw h, λ h, by rw [h, hfI]] } }, { refine ⟨c, ⟨lt_of_le_of_ne cmem.1 $ mt _ hc, lt_of_le_of_ne cmem.2 $ mt _ hc⟩, or.inl cle⟩, exacts [λ h, by rw h, λ h, by rw [h, hfI]] } end /-- A continuous function on a closed interval with `f a = f b` has a local extremum at some point of the corresponding open interval. -/ lemma exists_local_extr_Ioo : ∃ c ∈ Ioo a b, is_local_extr f c := let ⟨c, cmem, hc⟩ := exists_Ioo_extr_on_Icc f hab hfc hfI in ⟨c, cmem, hc.is_local_extr $ mem_nhds_sets_iff.2 ⟨Ioo a b, Ioo_subset_Icc_self, is_open_Ioo, cmem⟩⟩ /-- Rolle's Theorem `has_deriv_at` version -/ lemma exists_has_deriv_at_eq_zero (hff' : ∀ x ∈ Ioo a b, has_deriv_at f (f' x) x) : ∃ c ∈ Ioo a b, f' c = 0 := let ⟨c, cmem, hc⟩ := exists_local_extr_Ioo f hab hfc hfI in ⟨c, cmem, hc.has_deriv_at_eq_zero $ hff' c cmem⟩ /-- Rolle's Theorem `deriv` version -/ lemma exists_deriv_eq_zero : ∃ c ∈ Ioo a b, deriv f c = 0 := let ⟨c, cmem, hc⟩ := exists_local_extr_Ioo f hab hfc hfI in ⟨c, cmem, hc.deriv_eq_zero⟩ end Rolle
a7d44fae1b39ef7d899d6b075fef3adfdd706d6d
8b9f17008684d796c8022dab552e42f0cb6fb347
/tests/lean/run/vector_subterm_pred.lean
85c305118e6687a9dbfc1b9aa6b5e5074b9c3b37
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,762
lean
import logic data.nat.basic data.sigma open nat eq.ops sigma inductive vector (A : Type) : nat → Type := | nil : vector A zero | cons : A → (Π{n}, vector A n → vector A (succ n)) namespace vector definition vec (A : Type) : Type := Σ n : nat, vector A n definition to_vec {A : Type} {n : nat} (v : vector A n) : vec A := ⟨n, v⟩ inductive direct_subterm (A : Type) : vec A → vec A → Prop := cons : Π (n : nat) (a : A) (v : vector A n), direct_subterm A (to_vec v) (to_vec (cons a v)) definition direct_subterm.wf (A : Type) : well_founded (direct_subterm A) := well_founded.intro (λ (bv : vec A), sigma.rec_on bv (λ (n : nat) (v : vector A n), vector.rec_on v (show acc (direct_subterm A) (to_vec (nil A)), from acc.intro (to_vec (nil A)) (λ (v₂ : vec A) (H : direct_subterm A v₂ (to_vec (nil A))), have gen : ∀ (bv : vec A) (H : direct_subterm A v₂ bv) (Heq : bv = (to_vec (nil A))), acc (direct_subterm A) v₂, from λ bv H, direct_subterm.induction_on H (λ n₁ a₁ v₁ e, have e₁ : succ n₁ = zero, from sigma.no_confusion e (λ e₁ e₂, e₁), nat.no_confusion e₁), gen (to_vec (nil A)) H rfl)) (λ (a₁ : A) (n₁ : nat) (v₁ : vector A n₁) (ih : acc (direct_subterm A) (to_vec v₁)), acc.intro (to_vec (cons a₁ v₁)) (λ (w₁ : vec A) (lt₁ : direct_subterm A w₁ (to_vec (cons a₁ v₁))), have gen : ∀ (bv : vec A) (H : direct_subterm A w₁ bv) (Heq : bv = (to_vec (cons a₁ v₁))), acc (direct_subterm A) w₁, from λ bv H, direct_subterm.induction_on H (λ n₂ a₂ v₂ e, sigma.no_confusion e (λ (e₁ : succ n₂ = succ n₁) (e₂ : @cons A a₂ n₂ v₂ == @cons A a₁ n₁ v₁), nat.no_confusion e₁ (λ (e₃ : n₂ = n₁), have gen₂ : ∀ (m : nat) (Heq₁ : n₂ = m) (v : vector A m) (ih : acc (direct_subterm A) (to_vec v)) (Heq₂ : @cons A a₂ n₂ v₂ == @cons A a₁ m v), acc (direct_subterm A) (to_vec v₂), from λ m Heq₁, eq.rec_on Heq₁ (λ (v : vector A n₂) (ih : acc (direct_subterm A) (to_vec v)) (Heq₂ : @cons A a₂ n₂ v₂ == @cons A a₁ n₂ v), vector.no_confusion (heq.to_eq Heq₂) (λ (e₄ : a₂ = a₁) (e₅ : n₂ = n₂) (e₆ : v₂ == v), eq.rec_on (heq.to_eq (heq.symm e₆)) ih)), gen₂ n₁ e₃ v₁ ih e₂))), gen (to_vec (cons a₁ v₁)) lt₁ rfl)))) definition subterm (A : Type) := tc (direct_subterm A) definition subterm.wf (A : Type) : well_founded (subterm A) := tc.wf (direct_subterm.wf A) end vector
f2297a2e9c862557085cb49e8e33ca4ed61cb6fd
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/monoidal/functorial.lean
5e6bdb8f7225299b7a8ff52734203415a0c29f45
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,792
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 category_theory.monoidal.functor import category_theory.functor.functorial /-! # Unbundled lax monoidal functors > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Design considerations The essential problem I've encountered that requires unbundled functors is having an existing (non-monoidal) functor `F : C ⥤ D` between monoidal categories, and wanting to assert that it has an extension to a lax monoidal functor. The two options seem to be 1. Construct a separate `F' : lax_monoidal_functor C D`, and assert `F'.to_functor ≅ F`. 2. Introduce unbundled functors and unbundled lax monoidal functors, and construct `lax_monoidal F.obj`, then construct `F' := lax_monoidal_functor.of F.obj`. Both have costs, but as for option 2. the cost is in library design, while in option 1. the cost is users having to carry around additional isomorphisms forever, I wanted to introduce unbundled functors. TODO: later, we may want to do this for strong monoidal functors as well, but the immediate application, for enriched categories, only requires this notion. -/ open category_theory universes v₁ v₂ v₃ u₁ u₂ u₃ open category_theory.category open category_theory.functor namespace category_theory open monoidal_category variables {C : Type u₁} [category.{v₁} C] [monoidal_category.{v₁} C] {D : Type u₂} [category.{v₂} D] [monoidal_category.{v₂} D] /-- An unbundled description of lax monoidal functors. -/ -- Perhaps in the future we'll redefine `lax_monoidal_functor` in terms of this, -- but that isn't the immediate plan. class lax_monoidal (F : C → D) [functorial.{v₁ v₂} F] := -- unit morphism (ε [] : 𝟙_ D ⟶ F (𝟙_ C)) -- tensorator (μ [] : Π X Y : C, (F X) ⊗ (F Y) ⟶ F (X ⊗ Y)) (μ_natural' : ∀ {X Y X' Y' : C} (f : X ⟶ Y) (g : X' ⟶ Y'), ((map F f) ⊗ (map F g)) ≫ μ Y Y' = μ X X' ≫ map F (f ⊗ g) . obviously) -- associativity of the tensorator (associativity' : ∀ (X Y Z : C), (μ X Y ⊗ 𝟙 (F Z)) ≫ μ (X ⊗ Y) Z ≫ map F (α_ X Y Z).hom = (α_ (F X) (F Y) (F Z)).hom ≫ (𝟙 (F X) ⊗ μ Y Z) ≫ μ X (Y ⊗ Z) . obviously) -- unitality (left_unitality' : ∀ X : C, (λ_ (F X)).hom = (ε ⊗ 𝟙 (F X)) ≫ μ (𝟙_ C) X ≫ map F (λ_ X).hom . obviously) (right_unitality' : ∀ X : C, (ρ_ (F X)).hom = (𝟙 (F X) ⊗ ε) ≫ μ X (𝟙_ C) ≫ map F (ρ_ X).hom . obviously) restate_axiom lax_monoidal.μ_natural' attribute [simp] lax_monoidal.μ_natural restate_axiom lax_monoidal.left_unitality' restate_axiom lax_monoidal.right_unitality' -- The unitality axioms cannot be used as simp lemmas because they require -- higher-order matching to figure out the `F` and `X` from `F X`. restate_axiom lax_monoidal.associativity' attribute [simp] lax_monoidal.associativity namespace lax_monoidal_functor /-- Construct a bundled `lax_monoidal_functor` from the object level function and `functorial` and `lax_monoidal` typeclasses. -/ @[simps] def of (F : C → D) [I₁ : functorial.{v₁ v₂} F] [I₂ : lax_monoidal.{v₁ v₂} F] : lax_monoidal_functor.{v₁ v₂} C D := { obj := F, ..I₁, ..I₂ } end lax_monoidal_functor instance (F : lax_monoidal_functor.{v₁ v₂} C D) : lax_monoidal.{v₁ v₂} (F.obj) := { .. F } section instance lax_monoidal_id : lax_monoidal.{v₁ v₁} (id : C → C) := { ε := 𝟙 _, μ := λ X Y, 𝟙 _ } end -- TODO instances for composition, as required -- TODO `strong_monoidal`, as well as `lax_monoidal` end category_theory
1ba761301add6422c1443e91cae45160bfdc9682
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/normed_space/star/gelfand_duality.lean
236d6b2b7c563c300f0e1cdcb9a786c025d2c71f
[ "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
10,975
lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Reeased under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import analysis.normed_space.star.spectrum import analysis.normed.group.quotient import analysis.normed_space.algebra import topology.continuous_function.units import topology.continuous_function.compact import topology.algebra.algebra import topology.continuous_function.stone_weierstrass /-! # Gelfand Duality The `gelfand_transform` is an algebra homomorphism from a topological `𝕜`-algebra `A` to `C(character_space 𝕜 A, 𝕜)`. In the case where `A` is a commutative complex Banach algebra, then the Gelfand transform is actually spectrum-preserving (`spectrum.gelfand_transform_eq`). Moreover, when `A` is a commutative C⋆-algebra over `ℂ`, then the Gelfand transform is a surjective isometry, and even an equivalence between C⋆-algebras. ## Main definitions * `ideal.to_character_space` : constructs an element of the character space from a maximal ideal in a commutative complex Banach algebra * `weak_dual.character_space.comp_continuous_map`: The functorial map taking `ψ : A →⋆ₐ[ℂ] B` to a continuous function `character_space ℂ B → character_space ℂ A` given by pre-composition with `ψ`. ## Main statements * `spectrum.gelfand_transform_eq` : the Gelfand transform is spectrum-preserving when the algebra is a commutative complex Banach algebra. * `gelfand_transform_isometry` : the Gelfand transform is an isometry when the algebra is a commutative (unital) C⋆-algebra over `ℂ`. * `gelfand_transform_bijective` : the Gelfand transform is bijective when the algebra is a commutative (unital) C⋆-algebra over `ℂ`. ## TODO * After `star_alg_equiv` is defined, realize `gelfand_transform` as a `star_alg_equiv`. * Prove that if `A` is the unital C⋆-algebra over `ℂ` generated by a fixed normal element `x` in a larger C⋆-algebra `B`, then `character_space ℂ A` is homeomorphic to `spectrum ℂ x`. * From the previous result, construct the **continuous functional calculus**. * Show that if `X` is a compact Hausdorff space, then `X` is (canonically) homeomorphic to `character_space ℂ C(X, ℂ)`. * Conclude using the previous fact that the functors `C(⬝, ℂ)` and `character_space ℂ ⬝` along with the canonical homeomorphisms described above constitute a natural contravariant equivalence of the categories of compact Hausdorff spaces (with continuous maps) and commutative unital C⋆-algebras (with unital ⋆-algebra homomoprhisms); this is known as **Gelfand duality**. ## Tags Gelfand transform, character space, C⋆-algebra -/ open weak_dual open_locale nnreal section complex_banach_algebra open ideal variables {A : Type*} [normed_comm_ring A] [normed_algebra ℂ A] [complete_space A] (I : ideal A) [ideal.is_maximal I] /-- Every maximal ideal in a commutative complex Banach algebra gives rise to a character on that algebra. In particular, the character, which may be identified as an algebra homomorphism due to `weak_dual.character_space.equiv_alg_hom`, is given by the composition of the quotient map and the Gelfand-Mazur isomorphism `normed_ring.alg_equiv_complex_of_complete`. -/ noncomputable def ideal.to_character_space : character_space ℂ A := character_space.equiv_alg_hom.symm $ ((@normed_ring.alg_equiv_complex_of_complete (A ⧸ I) _ _ (by { letI := quotient.field I, exact @is_unit_iff_ne_zero (A ⧸ I) _ }) _).symm : A ⧸ I →ₐ[ℂ] ℂ).comp (quotient.mkₐ ℂ I) lemma ideal.to_character_space_apply_eq_zero_of_mem {a : A} (ha : a ∈ I) : I.to_character_space a = 0 := begin unfold ideal.to_character_space, simpa only [character_space.equiv_alg_hom_symm_coe, alg_hom.coe_comp, alg_equiv.coe_alg_hom, quotient.mkₐ_eq_mk, function.comp_app, quotient.eq_zero_iff_mem.mpr ha, spectrum.zero_eq, normed_ring.alg_equiv_complex_of_complete_symm_apply] using set.eq_of_mem_singleton (set.singleton_nonempty (0 : ℂ)).some_mem, end /-- If `a : A` is not a unit, then some character takes the value zero at `a`. This is equivlaent to `gelfand_transform ℂ A a` takes the value zero at some character. -/ lemma weak_dual.character_space.exists_apply_eq_zero {a : A} (ha : ¬ is_unit a) : ∃ f : character_space ℂ A, f a = 0 := begin unfreezingI { obtain ⟨M, hM, haM⟩ := (span {a}).exists_le_maximal (span_singleton_ne_top ha) }, exact ⟨M.to_character_space, M.to_character_space_apply_eq_zero_of_mem (haM (mem_span_singleton.mpr ⟨1, (mul_one a).symm⟩))⟩, end lemma weak_dual.character_space.mem_spectrum_iff_exists {a : A} {z : ℂ} : z ∈ spectrum ℂ a ↔ ∃ f : character_space ℂ A, f a = z := begin refine ⟨λ hz, _, _⟩, { obtain ⟨f, hf⟩ := weak_dual.character_space.exists_apply_eq_zero hz, simp only [map_sub, sub_eq_zero, alg_hom_class.commutes, algebra.id.map_eq_id, ring_hom.id_apply] at hf, exact (continuous_map.spectrum_eq_range (gelfand_transform ℂ A a)).symm ▸ ⟨f, hf.symm⟩ }, { rintro ⟨f, rfl⟩, exact alg_hom.apply_mem_spectrum f a, } end /-- The Gelfand transform is spectrum-preserving. -/ lemma spectrum.gelfand_transform_eq (a : A) : spectrum ℂ (gelfand_transform ℂ A a) = spectrum ℂ a := begin ext z, rw [continuous_map.spectrum_eq_range, weak_dual.character_space.mem_spectrum_iff_exists], exact iff.rfl, end instance [nontrivial A] : nonempty (character_space ℂ A) := ⟨classical.some $ weak_dual.character_space.exists_apply_eq_zero $ zero_mem_nonunits.2 zero_ne_one⟩ end complex_banach_algebra section complex_cstar_algebra variables {A : Type*} [normed_comm_ring A] [normed_algebra ℂ A] [complete_space A] variables [star_ring A] [cstar_ring A] [star_module ℂ A] lemma gelfand_transform_map_star (a : A) : gelfand_transform ℂ A (star a) = star (gelfand_transform ℂ A a) := continuous_map.ext $ λ φ, map_star φ a variable (A) /-- The Gelfand transform is an isometry when the algebra is a C⋆-algebra over `ℂ`. -/ lemma gelfand_transform_isometry : isometry (gelfand_transform ℂ A) := begin nontriviality A, refine add_monoid_hom_class.isometry_of_norm (gelfand_transform ℂ A) (λ a, _), /- By `spectrum.gelfand_transform_eq`, the spectra of `star a * a` and its `gelfand_transform` coincide. Therefore, so do their spectral radii, and since they are self-adjoint, so also do their norms. Applying the C⋆-property of the norm and taking square roots shows that the norm is preserved. -/ have : spectral_radius ℂ (gelfand_transform ℂ A (star a * a)) = spectral_radius ℂ (star a * a), { unfold spectral_radius, rw spectrum.gelfand_transform_eq, }, simp only [map_mul, (is_self_adjoint.star_mul_self _).spectral_radius_eq_nnnorm, gelfand_transform_map_star a, ennreal.coe_eq_coe, cstar_ring.nnnorm_star_mul_self, ←sq] at this, simpa only [function.comp_app, nnreal.sqrt_sq] using congr_arg ((coe : ℝ≥0 → ℝ) ∘ ⇑nnreal.sqrt) this, end /-- The Gelfand transform is bijective when the algebra is a C⋆-algebra over `ℂ`. -/ lemma gelfand_transform_bijective : function.bijective (gelfand_transform ℂ A) := begin refine ⟨(gelfand_transform_isometry A).injective, _⟩, suffices : (gelfand_transform ℂ A).range = ⊤, { exact λ x, this.symm ▸ (gelfand_transform ℂ A).mem_range.mp (this.symm ▸ algebra.mem_top) }, /- Because the `gelfand_transform ℂ A` is an isometry, it has closed range, and so by the Stone-Weierstrass theorem, it suffices to show that the image of the Gelfand transform separates points in `C(character_space ℂ A, ℂ)` and is closed under `star`. -/ have h : (gelfand_transform ℂ A).range.topological_closure = (gelfand_transform ℂ A).range, from le_antisymm (subalgebra.topological_closure_minimal _ le_rfl (gelfand_transform_isometry A).closed_embedding.closed_range) (subalgebra.le_topological_closure _), refine h ▸ continuous_map.subalgebra_is_R_or_C_topological_closure_eq_top_of_separates_points _ (λ _ _, _) (λ f hf, _), /- Separating points just means that elements of the `character_space` which agree at all points of `A` are the same functional, which is just extensionality. -/ { contrapose!, exact λ h, subtype.ext (continuous_linear_map.ext $ λ a, h (gelfand_transform ℂ A a) ⟨gelfand_transform ℂ A a, ⟨a, rfl⟩, rfl⟩), }, /- If `f = gelfand_transform ℂ A a`, then `star f` is also in the range of `gelfand_transform ℂ A` using the argument `star a`. The key lemma below may be hard to spot; it's `map_star` coming from `weak_dual.star_hom_class`, which is a nontrivial result. -/ { obtain ⟨f, ⟨a, rfl⟩, rfl⟩ := subalgebra.mem_map.mp hf, refine ⟨star a, continuous_map.ext $ λ ψ, _⟩, simpa only [gelfand_transform_map_star a, alg_hom.to_ring_hom_eq_coe, alg_hom.coe_to_ring_hom] } end /-- The Gelfand transform as a `star_alg_equiv` between a commutative unital C⋆-algebra over `ℂ` and the continuous functions on its `character_space`. -/ @[simps] noncomputable def gelfand_star_transform : A ≃⋆ₐ[ℂ] C(character_space ℂ A, ℂ) := star_alg_equiv.of_bijective (show A →⋆ₐ[ℂ] C(character_space ℂ A, ℂ), from { map_star' := λ x, gelfand_transform_map_star x, .. gelfand_transform ℂ A }) (gelfand_transform_bijective A) end complex_cstar_algebra section functoriality namespace weak_dual namespace character_space variables {A B C : Type*} variables [normed_ring A] [normed_algebra ℂ A] [complete_space A] [star_ring A] variables [normed_ring B] [normed_algebra ℂ B] [complete_space B] [star_ring B] variables [normed_ring C] [normed_algebra ℂ C] [complete_space C] [star_ring C] /-- The functorial map taking `ψ : A →⋆ₐ[ℂ] B` to a continuous function `character_space ℂ B → character_space ℂ A` obtained by pre-composition with `ψ`. -/ @[simps] noncomputable def comp_continuous_map (ψ : A →⋆ₐ[ℂ] B) : C(character_space ℂ B, character_space ℂ A) := { to_fun := λ φ, equiv_alg_hom.symm ((equiv_alg_hom φ).comp (ψ.to_alg_hom)), continuous_to_fun := continuous.subtype_mk (continuous_of_continuous_eval $ λ a, map_continuous $ gelfand_transform ℂ B (ψ a)) _ } variables (A) /-- `weak_dual.character_space.comp_continuous_map` sends the identity to the identity. -/ @[simp] lemma comp_continuous_map_id : comp_continuous_map (star_alg_hom.id ℂ A) = continuous_map.id (character_space ℂ A) := continuous_map.ext $ λ a, ext $ λ x, rfl variables {A} /-- `weak_dual.character_space.comp_continuous_map` is functorial. -/ @[simp] lemma comp_continuous_map_comp (ψ₂ : B →⋆ₐ[ℂ] C) (ψ₁ : A →⋆ₐ[ℂ] B) : comp_continuous_map (ψ₂.comp ψ₁) = (comp_continuous_map ψ₁).comp (comp_continuous_map ψ₂) := continuous_map.ext $ λ a, ext $ λ x, rfl end character_space end weak_dual end functoriality
55f95de187692eb015b25f2e60ff63dff9bf39cf
9dc8cecdf3c4634764a18254e94d43da07142918
/src/linear_algebra/quadratic_form/basic.lean
a934839a9de37034f9aac7f04d3bbe4814d8e0b9
[ "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,146
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 algebra.invertible import linear_algebra.matrix.determinant import linear_algebra.matrix.bilinear_form import linear_algebra.matrix.symmetric /-! # Quadratic forms This file defines quadratic forms over a `R`-module `M`. A quadratic form on a ring `R` is a map `Q : M → R` such that: * `quadratic_form.map_smul`: `Q (a • x) = a * a * Q x` * `quadratic_form.polar_add_left`, `quadratic_form.polar_add_right`, `quadratic_form.polar_smul_left`, `quadratic_form.polar_smul_right`: the map `quadratic_form.polar Q := λ x y, Q (x + y) - Q x - Q y` is bilinear. This notion generalizes to semirings using the approach in [izhakian2016][] which requires that there be a (possibly non-unique) companion bilinear form `B` such that `∀ x y, Q (x + y) = Q x + Q y + B x y`. Over a ring, this `B` is precisely `quadratic_form.polar Q`. To build a `quadratic_form` from the `polar` axioms, use `quadratic_form.of_polar`. Quadratic forms come with a scalar multiplication, `(a • Q) x = Q (a • x) = a * a * Q x`, and composition with linear maps `f`, `Q.comp f x = Q (f x)`. ## Main definitions * `quadratic_form.of_polar`: a more familiar constructor that works on rings * `quadratic_form.associated`: associated bilinear form * `quadratic_form.pos_def`: positive definite quadratic forms * `quadratic_form.anisotropic`: anisotropic quadratic forms * `quadratic_form.discr`: discriminant of a quadratic form ## Main statements * `quadratic_form.associated_left_inverse`, * `quadratic_form.associated_right_inverse`: in a commutative ring where 2 has an inverse, there is a correspondence between quadratic forms and symmetric bilinear forms * `bilin_form.exists_orthogonal_basis`: There exists an orthogonal basis with respect to any nondegenerate, symmetric bilinear form `B`. ## Notation In this file, the variable `R` is used when a `ring` structure is sufficient and `R₁` is used when specifically a `comm_ring` is required. This allows us to keep `[module R M]` and `[module R₁ M]` assumptions in the variables without confusion between `*` from `ring` and `*` from `comm_ring`. The variable `S` is used when `R` itself has a `•` action. ## References * https://en.wikipedia.org/wiki/Quadratic_form * https://en.wikipedia.org/wiki/Discriminant#Quadratic_forms ## Tags quadratic form, homogeneous polynomial, quadratic polynomial -/ universes u v w variables {S : Type*} variables {R R₁: Type*} {M : Type*} section polar variables [ring R] [comm_ring R₁] [add_comm_group M] namespace quadratic_form /-- Up to a factor 2, `Q.polar` is the associated bilinear form for a quadratic form `Q`. Source of this name: https://en.wikipedia.org/wiki/Quadratic_form#Generalization -/ def polar (f : M → R) (x y : M) := f (x + y) - f x - f y lemma polar_add (f g : M → R) (x y : M) : polar (f + g) x y = polar f x y + polar g x y := by { simp only [polar, pi.add_apply], abel } lemma polar_neg (f : M → R) (x y : M) : polar (-f) x y = - polar f x y := by { simp only [polar, pi.neg_apply, sub_eq_add_neg, neg_add] } lemma polar_smul [monoid S] [distrib_mul_action S R] (f : M → R) (s : S) (x y : M) : polar (s • f) x y = s • polar f x y := by { simp only [polar, pi.smul_apply, smul_sub] } lemma polar_comm (f : M → R) (x y : M) : polar f x y = polar f y x := by rw [polar, polar, add_comm, sub_sub, sub_sub, add_comm (f x) (f y)] /-- Auxiliary lemma to express bilinearity of `quadratic_form.polar` without subtraction. -/ lemma polar_add_left_iff {f : M → R} {x x' y : M} : polar f (x + x') y = polar f x y + polar f x' y ↔ f (x + x' + y) + (f x + f x' + f y) = f (x + x') + f (x' + y) + f (y + x) := begin simp only [←add_assoc], simp only [polar, sub_eq_iff_eq_add, eq_sub_iff_add_eq, sub_add_eq_add_sub, add_sub], simp only [add_right_comm _ (f y) _, add_right_comm _ (f x') (f x)], rw [add_comm y x, add_right_comm _ _ (f (x + y)), add_comm _ (f (x + y)), add_right_comm (f (x + y)), add_left_inj], end lemma polar_comp {F : Type*} [ring S] [add_monoid_hom_class F R S] (f : M → R) (g : F) (x y : M) : polar (g ∘ f) x y = g (polar f x y) := by simp only [polar, pi.smul_apply, function.comp_apply, map_sub] end quadratic_form end polar /-- A quadratic form over a module. For a more familiar constructor when `R` is a ring, see `quadratic_form.of_polar`. -/ structure quadratic_form (R : Type u) (M : Type v) [semiring R] [add_comm_monoid M] [module R M] := (to_fun : M → R) (to_fun_smul : ∀ (a : R) (x : M), to_fun (a • x) = a * a * to_fun x) (exists_companion' : ∃ B : bilin_form R M, ∀ x y, to_fun (x + y) = to_fun x + to_fun y + B x y) namespace quadratic_form section fun_like variables [semiring R] [add_comm_monoid M] [module R M] variables {Q Q' : quadratic_form R M} instance fun_like : fun_like (quadratic_form R M) M (λ _, R) := { coe := to_fun, coe_injective' := λ x y h, by cases x; cases y; congr' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (quadratic_form R M) (λ _, M → R) := ⟨to_fun⟩ variables (Q) /-- The `simp` normal form for a quadratic form is `coe_fn`, not `to_fun`. -/ @[simp] lemma to_fun_eq_coe : Q.to_fun = ⇑Q := rfl -- this must come after the coe_to_fun definition initialize_simps_projections quadratic_form (to_fun → apply) variables {Q} @[ext] lemma ext (H : ∀ (x : M), Q x = Q' x) : Q = Q' := fun_like.ext _ _ H lemma congr_fun (h : Q = Q') (x : M) : Q x = Q' x := fun_like.congr_fun h _ lemma ext_iff : Q = Q' ↔ (∀ x, Q x = Q' x) := fun_like.ext_iff /-- Copy of a `quadratic_form` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (Q : quadratic_form R M) (Q' : M → R) (h : Q' = ⇑Q) : quadratic_form R M := { to_fun := Q', to_fun_smul := h.symm ▸ Q.to_fun_smul, exists_companion' := h.symm ▸ Q.exists_companion' } end fun_like section semiring variables [semiring R] [add_comm_monoid M] [module R M] variables (Q : quadratic_form R M) lemma map_smul (a : R) (x : M) : Q (a • x) = a * a * Q x := Q.to_fun_smul a x lemma exists_companion : ∃ B : bilin_form R M, ∀ x y, Q (x + y) = Q x + Q y + B x y := Q.exists_companion' lemma map_add_add_add_map (x y z : M) : Q (x + y + z) + (Q x + Q y + Q z) = Q (x + y) + Q (y + z) + Q (z + x) := begin obtain ⟨B, h⟩ := Q.exists_companion, rw [add_comm z x], simp [h], abel, end lemma map_add_self (x : M) : Q (x + x) = 4 * Q x := by { rw [←one_smul R x, ←add_smul, map_smul], norm_num } @[simp] lemma map_zero : Q 0 = 0 := by rw [←@zero_smul R _ _ _ _ (0 : M), map_smul, zero_mul, zero_mul] instance zero_hom_class : zero_hom_class (quadratic_form R M) M R := { map_zero := map_zero, ..quadratic_form.fun_like } lemma map_smul_of_tower [comm_semiring S] [algebra S R] [module S M] [is_scalar_tower S R M] (a : S) (x : M) : Q (a • x) = (a * a) • Q x := by rw [←is_scalar_tower.algebra_map_smul R a x, map_smul, ←ring_hom.map_mul, algebra.smul_def] end semiring section ring variables [ring R] [comm_ring R₁] [add_comm_group M] variables [module R M] (Q : quadratic_form R M) @[simp] lemma map_neg (x : M) : Q (-x) = Q x := by rw [←@neg_one_smul R _ _ _ _ x, map_smul, neg_one_mul, neg_neg, one_mul] lemma map_sub (x y : M) : Q (x - y) = Q (y - x) := by rw [←neg_sub, map_neg] @[simp] lemma polar_zero_left (y : M) : polar Q 0 y = 0 := by simp only [polar, zero_add, quadratic_form.map_zero, sub_zero, sub_self] @[simp] lemma polar_add_left (x x' y : M) : polar Q (x + x') y = polar Q x y + polar Q x' y := polar_add_left_iff.mpr $ Q.map_add_add_add_map x x' y @[simp] lemma polar_smul_left (a : R) (x y : M) : polar Q (a • x) y = a * polar Q x y := begin obtain ⟨B, h⟩ := Q.exists_companion, simp_rw [polar, h, Q.map_smul, bilin_form.smul_left, sub_sub, add_sub_cancel'], end @[simp] lemma polar_neg_left (x y : M) : polar Q (-x) y = -polar Q x y := by rw [←neg_one_smul R x, polar_smul_left, neg_one_mul] @[simp] lemma polar_sub_left (x x' y : M) : polar Q (x - x') y = polar Q x y - polar Q x' y := by rw [sub_eq_add_neg, sub_eq_add_neg, polar_add_left, polar_neg_left] @[simp] lemma polar_zero_right (y : M) : polar Q y 0 = 0 := by simp only [add_zero, polar, quadratic_form.map_zero, sub_self] @[simp] lemma polar_add_right (x y y' : M) : polar Q x (y + y') = polar Q x y + polar Q x y' := by rw [polar_comm Q x, polar_comm Q x, polar_comm Q x, polar_add_left] @[simp] lemma polar_smul_right (a : R) (x y : M) : polar Q x (a • y) = a * polar Q x y := by rw [polar_comm Q x, polar_comm Q x, polar_smul_left] @[simp] lemma polar_neg_right (x y : M) : polar Q x (-y) = -polar Q x y := by rw [←neg_one_smul R y, polar_smul_right, neg_one_mul] @[simp] lemma polar_sub_right (x y y' : M) : polar Q x (y - y') = polar Q x y - polar Q x y' := by rw [sub_eq_add_neg, sub_eq_add_neg, polar_add_right, polar_neg_right] @[simp] lemma polar_self (x : M) : polar Q x x = 2 * Q x := begin rw [polar, map_add_self, sub_sub, sub_eq_iff_eq_add, ←two_mul, ←two_mul, ←mul_assoc], norm_num end /-- `quadratic_form.polar` as a bilinear form -/ @[simps] def polar_bilin : bilin_form R M := { bilin := polar Q, bilin_add_left := polar_add_left Q, bilin_smul_left := polar_smul_left Q, bilin_add_right := λ x y z, by simp_rw [polar_comm _ x, polar_add_left Q], bilin_smul_right := λ r x y, by simp_rw [polar_comm _ x, polar_smul_left Q] } variables [comm_semiring S] [algebra S R] [module S M] [is_scalar_tower S R M] @[simp] lemma polar_smul_left_of_tower (a : S) (x y : M) : polar Q (a • x) y = a • polar Q x y := by rw [←is_scalar_tower.algebra_map_smul R a x, polar_smul_left, algebra.smul_def] @[simp] lemma polar_smul_right_of_tower (a : S) (x y : M) : polar Q x (a • y) = a • polar Q x y := by rw [←is_scalar_tower.algebra_map_smul R a y, polar_smul_right, algebra.smul_def] /-- An alternative constructor to `quadratic_form.mk`, for rings where `polar` can be used. -/ @[simps] def of_polar (to_fun : M → R) (to_fun_smul : ∀ (a : R) (x : M), to_fun (a • x) = a * a * to_fun x) (polar_add_left : ∀ (x x' y : M), polar to_fun (x + x') y = polar to_fun x y + polar to_fun x' y) (polar_smul_left : ∀ (a : R) (x y : M), polar to_fun (a • x) y = a • polar to_fun x y) : quadratic_form R M := { to_fun := to_fun, to_fun_smul := to_fun_smul, exists_companion' := ⟨ { bilin := polar to_fun, bilin_add_left := polar_add_left, bilin_smul_left := polar_smul_left, bilin_add_right := λ x y z, by simp_rw [polar_comm _ x, polar_add_left], bilin_smul_right := λ r x y, by simp_rw [polar_comm _ x, polar_smul_left, smul_eq_mul] }, λ x y, by rw [bilin_form.coe_fn_mk, polar, sub_sub, add_sub_cancel'_right]⟩ } /-- In a ring the companion bilinear form is unique and equal to `quadratic_form.polar`. -/ lemma some_exists_companion : Q.exists_companion.some = polar_bilin Q := bilin_form.ext $ λ x y, by rw [polar_bilin_apply, polar, Q.exists_companion.some_spec, sub_sub, add_sub_cancel'] end ring section semiring_operators variables [semiring R] [add_comm_monoid M] [module R M] section has_smul variables [monoid S] [distrib_mul_action S R] [smul_comm_class S R R] /-- `quadratic_form R M` inherits the scalar action from any algebra over `R`. When `R` is commutative, this provides an `R`-action via `algebra.id`. -/ instance : has_smul S (quadratic_form R M) := ⟨ λ a Q, { to_fun := a • Q, to_fun_smul := λ b x, by rw [pi.smul_apply, map_smul, pi.smul_apply, mul_smul_comm], exists_companion' := let ⟨B, h⟩ := Q.exists_companion in ⟨a • B, by simp [h]⟩ } ⟩ @[simp] lemma coe_fn_smul (a : S) (Q : quadratic_form R M) : ⇑(a • Q) = a • Q := rfl @[simp] lemma smul_apply (a : S) (Q : quadratic_form R M) (x : M) : (a • Q) x = a • Q x := rfl end has_smul instance : has_zero (quadratic_form R M) := ⟨ { to_fun := λ x, 0, to_fun_smul := λ a x, by simp only [mul_zero], exists_companion' := ⟨0, λ x y, by simp only [add_zero, bilin_form.zero_apply]⟩ } ⟩ @[simp] lemma coe_fn_zero : ⇑(0 : quadratic_form R M) = 0 := rfl @[simp] lemma zero_apply (x : M) : (0 : quadratic_form R M) x = 0 := rfl instance : inhabited (quadratic_form R M) := ⟨0⟩ instance : has_add (quadratic_form R M) := ⟨ λ Q Q', { to_fun := Q + Q', to_fun_smul := λ a x, by simp only [pi.add_apply, map_smul, mul_add], exists_companion' := let ⟨B, h⟩ := Q.exists_companion, ⟨B', h'⟩ := Q'.exists_companion in ⟨B + B', λ x y, by simp_rw [pi.add_apply, h, h', bilin_form.add_apply, add_add_add_comm] ⟩ } ⟩ @[simp] lemma coe_fn_add (Q Q' : quadratic_form R M) : ⇑(Q + Q') = Q + Q' := rfl @[simp] lemma add_apply (Q Q' : quadratic_form R M) (x : M) : (Q + Q') x = Q x + Q' x := rfl instance : add_comm_monoid (quadratic_form R M) := fun_like.coe_injective.add_comm_monoid _ coe_fn_zero coe_fn_add (λ _ _, coe_fn_smul _ _) /-- `@coe_fn (quadratic_form R M)` as an `add_monoid_hom`. This API mirrors `add_monoid_hom.coe_fn`. -/ @[simps apply] def coe_fn_add_monoid_hom : quadratic_form R M →+ (M → R) := { to_fun := coe_fn, map_zero' := coe_fn_zero, map_add' := coe_fn_add } /-- Evaluation on a particular element of the module `M` is an additive map over quadratic forms. -/ @[simps apply] def eval_add_monoid_hom (m : M) : quadratic_form R M →+ R := (pi.eval_add_monoid_hom _ m).comp coe_fn_add_monoid_hom section sum open_locale big_operators @[simp] lemma coe_fn_sum {ι : Type*} (Q : ι → quadratic_form R M) (s : finset ι) : ⇑(∑ i in s, Q i) = ∑ i in s, Q i := (coe_fn_add_monoid_hom : _ →+ (M → R)).map_sum Q s @[simp] lemma sum_apply {ι : Type*} (Q : ι → quadratic_form R M) (s : finset ι) (x : M) : (∑ i in s, Q i) x = ∑ i in s, Q i x := (eval_add_monoid_hom x : _ →+ R).map_sum Q s end sum instance [monoid S] [distrib_mul_action S R] [smul_comm_class S R R] : distrib_mul_action S (quadratic_form R M) := { mul_smul := λ a b Q, ext (λ x, by simp only [smul_apply, mul_smul]), one_smul := λ Q, ext (λ x, by simp only [quadratic_form.smul_apply, one_smul]), smul_add := λ a Q Q', by { ext, simp only [add_apply, smul_apply, smul_add] }, smul_zero := λ a, by { ext, simp only [zero_apply, smul_apply, smul_zero] }, } instance [semiring S] [module S R] [smul_comm_class S R R] : module S (quadratic_form R M) := { zero_smul := λ Q, by { ext, simp only [zero_apply, smul_apply, zero_smul] }, add_smul := λ a b Q, by { ext, simp only [add_apply, smul_apply, add_smul] } } end semiring_operators section ring_operators variables [ring R] [add_comm_group M] [module R M] instance : has_neg (quadratic_form R M) := ⟨ λ Q, { to_fun := -Q, to_fun_smul := λ a x, by simp only [pi.neg_apply, map_smul, mul_neg], exists_companion' := let ⟨B, h⟩ := Q.exists_companion in ⟨-B, λ x y, by simp_rw [pi.neg_apply, h, bilin_form.neg_apply, neg_add] ⟩ } ⟩ @[simp] lemma coe_fn_neg (Q : quadratic_form R M) : ⇑(-Q) = -Q := rfl @[simp] lemma neg_apply (Q : quadratic_form R M) (x : M) : (-Q) x = -Q x := rfl instance : has_sub (quadratic_form R M) := ⟨ λ Q Q', (Q + -Q').copy (Q - Q') (sub_eq_add_neg _ _) ⟩ @[simp] lemma coe_fn_sub (Q Q' : quadratic_form R M) : ⇑(Q - Q') = Q - Q' := rfl @[simp] lemma sub_apply (Q Q' : quadratic_form R M) (x : M) : (Q - Q') x = Q x - Q' x := rfl instance : add_comm_group (quadratic_form R M) := fun_like.coe_injective.add_comm_group _ coe_fn_zero coe_fn_add coe_fn_neg coe_fn_sub (λ _ _, coe_fn_smul _ _) (λ _ _, coe_fn_smul _ _) end ring_operators section comp variables [semiring R] [add_comm_monoid M] [module R M] variables {N : Type v} [add_comm_monoid N] [module R N] /-- Compose the quadratic form with a linear function. -/ def comp (Q : quadratic_form R N) (f : M →ₗ[R] N) : quadratic_form R M := { to_fun := λ x, Q (f x), to_fun_smul := λ a x, by simp only [map_smul, f.map_smul], exists_companion' := let ⟨B, h⟩ := Q.exists_companion in ⟨B.comp f f, λ x y, by simp_rw [f.map_add, h, bilin_form.comp_apply]⟩ } @[simp] lemma comp_apply (Q : quadratic_form R N) (f : M →ₗ[R] N) (x : M) : (Q.comp f) x = Q (f x) := rfl /-- Compose a quadratic form with a linear function on the left. -/ @[simps {simp_rhs := tt}] def _root_.linear_map.comp_quadratic_form {S : Type*} [comm_semiring S] [algebra S R] [module S M] [is_scalar_tower S R M] (f : R →ₗ[S] S) (Q : quadratic_form R M) : quadratic_form S M := { to_fun := λ x, f (Q x), to_fun_smul := λ b x, by rw [Q.map_smul_of_tower b x, f.map_smul, smul_eq_mul], exists_companion' := let ⟨B, h⟩ := Q.exists_companion in ⟨f.comp_bilin_form B, λ x y, by simp_rw [h, f.map_add, linear_map.comp_bilin_form_apply]⟩ } end comp section comm_ring variables [comm_semiring R] [add_comm_monoid M] [module R M] /-- The product of linear forms is a quadratic form. -/ def lin_mul_lin (f g : M →ₗ[R] R) : quadratic_form R M := { to_fun := f * g, to_fun_smul := λ a x, by { simp only [smul_eq_mul, ring_hom.id_apply, pi.mul_apply, linear_map.map_smulₛₗ], ring }, exists_companion' := ⟨ bilin_form.lin_mul_lin f g + bilin_form.lin_mul_lin g f, λ x y, by { simp, ring }⟩ } @[simp] lemma lin_mul_lin_apply (f g : M →ₗ[R] R) (x) : lin_mul_lin f g x = f x * g x := rfl @[simp] lemma add_lin_mul_lin (f g h : M →ₗ[R] R) : lin_mul_lin (f + g) h = lin_mul_lin f h + lin_mul_lin g h := ext (λ x, add_mul _ _ _) @[simp] lemma lin_mul_lin_add (f g h : M →ₗ[R] R) : lin_mul_lin f (g + h) = lin_mul_lin f g + lin_mul_lin f h := ext (λ x, mul_add _ _ _) variables {N : Type v} [add_comm_monoid N] [module R N] @[simp] lemma lin_mul_lin_comp (f g : M →ₗ[R] R) (h : N →ₗ[R] M) : (lin_mul_lin f g).comp h = lin_mul_lin (f.comp h) (g.comp h) := rfl variables {n : Type*} /-- `sq` is the quadratic form mapping the vector `x : R₁` to `x * x` -/ @[simps] def sq : quadratic_form R R := lin_mul_lin linear_map.id linear_map.id /-- `proj i j` is the quadratic form mapping the vector `x : n → R₁` to `x i * x j` -/ def proj (i j : n) : quadratic_form R (n → R) := lin_mul_lin (@linear_map.proj _ _ _ (λ _, R) _ _ i) (@linear_map.proj _ _ _ (λ _, R) _ _ j) @[simp] lemma proj_apply (i j : n) (x : n → R) : proj i j x = x i * x j := rfl end comm_ring end quadratic_form /-! ### Associated bilinear forms Over a commutative ring with an inverse of 2, the theory of quadratic forms is basically identical to that of symmetric bilinear forms. The map from quadratic forms to bilinear forms giving this identification is called the `associated` quadratic form. -/ namespace bilin_form open quadratic_form section ring variables [ring R] [add_comm_group M] [module R M] variables {B : bilin_form R M} lemma polar_to_quadratic_form (x y : M) : polar (λ x, B x x) x y = B x y + B y x := by { simp only [add_assoc, add_sub_cancel', add_right, polar, add_left_inj, add_neg_cancel_left, add_left, sub_eq_add_neg _ (B y y), add_comm (B y x) _] } end ring variables [semiring R] [add_comm_monoid M] [module R M] variables {B : bilin_form R M} /-- A bilinear form gives a quadratic form by applying the argument twice. -/ def to_quadratic_form (B : bilin_form R M) : quadratic_form R M := { to_fun := λ x, B x x, to_fun_smul := λ a x, by simp only [mul_assoc, smul_right, smul_left], exists_companion' := ⟨B + bilin_form.flip_hom ℕ B, λ x y, by { simp [add_add_add_comm, add_comm] }⟩ } @[simp] lemma to_quadratic_form_apply (B : bilin_form R M) (x : M) : B.to_quadratic_form x = B x x := rfl section variables (R M) @[simp] lemma to_quadratic_form_zero : (0 : bilin_form R M).to_quadratic_form = 0 := rfl end end bilin_form namespace quadratic_form open bilin_form section associated_hom variables [ring R] [comm_ring R₁] [add_comm_group M] [module R M] [module R₁ M] variables (S) [comm_semiring S] [algebra S R] variables [invertible (2 : R)] {B₁ : bilin_form R M} /-- `associated_hom` is the map that sends a quadratic form on a module `M` over `R` to its associated symmetric bilinear form. As provided here, this has the structure of an `S`-linear map where `S` is a commutative subring of `R`. Over a commutative ring, use `associated`, which gives an `R`-linear map. Over a general ring with no nontrivial distinguished commutative subring, use `associated'`, which gives an additive homomorphism (or more precisely a `ℤ`-linear map.) -/ def associated_hom : quadratic_form R M →ₗ[S] bilin_form R M := { to_fun := λ Q, ((•) : submonoid.center R → bilin_form R M → bilin_form R M) (⟨⅟2, λ x, (commute.one_right x).bit0_right.inv_of_right⟩) Q.polar_bilin, map_add' := λ Q Q', by { ext, simp only [bilin_form.add_apply, bilin_form.smul_apply, coe_fn_mk, polar_bilin_apply, polar_add, coe_fn_add, smul_add] }, map_smul' := λ s Q, by { ext, simp only [ring_hom.id_apply, polar_smul, smul_comm s, polar_bilin_apply, coe_fn_mk, coe_fn_smul, bilin_form.smul_apply] } } variables (Q : quadratic_form R M) (S) @[simp] lemma associated_apply (x y : M) : associated_hom S Q x y = ⅟2 * (Q (x + y) - Q x - Q y) := rfl lemma associated_is_symm : (associated_hom S Q).is_symm := λ x y, by simp only [associated_apply, add_comm, add_left_comm, sub_eq_add_neg] @[simp] lemma associated_comp {N : Type v} [add_comm_group N] [module R N] (f : N →ₗ[R] M) : associated_hom S (Q.comp f) = (associated_hom S Q).comp f f := by { ext, simp only [quadratic_form.comp_apply, bilin_form.comp_apply, associated_apply, linear_map.map_add] } lemma associated_to_quadratic_form (B : bilin_form R M) (x y : M) : associated_hom S B.to_quadratic_form x y = ⅟2 * (B x y + B y x) := by simp only [associated_apply, ← polar_to_quadratic_form, polar, to_quadratic_form_apply] lemma associated_left_inverse (h : B₁.is_symm) : associated_hom S (B₁.to_quadratic_form) = B₁ := bilin_form.ext $ λ x y, by rw [associated_to_quadratic_form, is_symm.eq h x y, ←two_mul, ←mul_assoc, inv_of_mul_self, one_mul] lemma to_quadratic_form_associated : (associated_hom S Q).to_quadratic_form = Q := quadratic_form.ext $ λ x, calc (associated_hom S Q).to_quadratic_form x = ⅟2 * (Q x + Q x) : by simp only [add_assoc, add_sub_cancel', one_mul, to_quadratic_form_apply, add_mul, associated_apply, map_add_self, bit0] ... = Q x : by rw [← two_mul (Q x), ←mul_assoc, inv_of_mul_self, one_mul] -- note: usually `right_inverse` lemmas are named the other way around, but this is consistent -- with historical naming in this file. lemma associated_right_inverse : function.right_inverse (associated_hom S) (bilin_form.to_quadratic_form : _ → quadratic_form R M) := λ Q, to_quadratic_form_associated S Q lemma associated_eq_self_apply (x : M) : associated_hom S Q x x = Q x := begin rw [associated_apply, map_add_self], suffices : (⅟2) * (2 * Q x) = Q x, { convert this, simp only [bit0, add_mul, one_mul], abel }, simp only [← mul_assoc, one_mul, inv_of_mul_self], end /-- `associated'` is the `ℤ`-linear map that sends a quadratic form on a module `M` over `R` to its associated symmetric bilinear form. -/ abbreviation associated' : quadratic_form R M →ₗ[ℤ] bilin_form R M := associated_hom ℤ /-- Symmetric bilinear forms can be lifted to quadratic forms -/ instance : can_lift (bilin_form R M) (quadratic_form R M) := { coe := associated_hom ℕ, cond := bilin_form.is_symm, prf := λ B hB, ⟨B.to_quadratic_form, associated_left_inverse _ hB⟩ } /-- There exists a non-null vector with respect to any quadratic form `Q` whose associated bilinear form is non-zero, i.e. there exists `x` such that `Q x ≠ 0`. -/ lemma exists_quadratic_form_ne_zero {Q : quadratic_form R M} (hB₁ : Q.associated' ≠ 0) : ∃ x, Q x ≠ 0 := begin rw ←not_forall, intro h, apply hB₁, rw [(quadratic_form.ext h : Q = 0), linear_map.map_zero], end end associated_hom section associated variables [comm_ring R₁] [add_comm_group M] [module R₁ M] variables [invertible (2 : R₁)] -- Note: When possible, rather than writing lemmas about `associated`, write a lemma applying to -- the more general `associated_hom` and place it in the previous section. /-- `associated` is the linear map that sends a quadratic form over a commutative ring to its associated symmetric bilinear form. -/ abbreviation associated : quadratic_form R₁ M →ₗ[R₁] bilin_form R₁ M := associated_hom R₁ @[simp] lemma associated_lin_mul_lin (f g : M →ₗ[R₁] R₁) : (lin_mul_lin f g).associated = ⅟(2 : R₁) • (bilin_form.lin_mul_lin f g + bilin_form.lin_mul_lin g f) := by { ext, simp only [smul_add, algebra.id.smul_eq_mul, bilin_form.lin_mul_lin_apply, quadratic_form.lin_mul_lin_apply, bilin_form.smul_apply, associated_apply, bilin_form.add_apply, linear_map.map_add], ring } end associated section anisotropic section semiring variables [semiring R] [add_comm_monoid M] [module R M] /-- An anisotropic quadratic form is zero only on zero vectors. -/ def anisotropic (Q : quadratic_form R M) : Prop := ∀ x, Q x = 0 → x = 0 lemma not_anisotropic_iff_exists (Q : quadratic_form R M) : ¬anisotropic Q ↔ ∃ x ≠ 0, Q x = 0 := by simp only [anisotropic, not_forall, exists_prop, and_comm] lemma anisotropic.eq_zero_iff {Q : quadratic_form R M} (h : anisotropic Q) {x : M} : Q x = 0 ↔ x = 0 := ⟨h x, λ h, h.symm ▸ map_zero Q⟩ end semiring section ring variables [ring R] [add_comm_group M] [module R M] /-- The associated bilinear form of an anisotropic quadratic form is nondegenerate. -/ lemma nondegenerate_of_anisotropic [invertible (2 : R)] (Q : quadratic_form R M) (hB : Q.anisotropic) : Q.associated'.nondegenerate := begin intros x hx, refine hB _ _, rw ← hx x, exact (associated_eq_self_apply _ _ x).symm, end end ring end anisotropic section pos_def variables {R₂ : Type u} [ordered_ring R₂] [add_comm_monoid M] [module R₂ M] variables {Q₂ : quadratic_form R₂ M} /-- A positive definite quadratic form is positive on nonzero vectors. -/ def pos_def (Q₂ : quadratic_form R₂ M) : Prop := ∀ x ≠ 0, 0 < Q₂ x lemma pos_def.smul {R} [linear_ordered_comm_ring R] [module R M] {Q : quadratic_form R M} (h : pos_def Q) {a : R} (a_pos : 0 < a) : pos_def (a • Q) := λ x hx, mul_pos a_pos (h x hx) variables {n : Type*} lemma pos_def.nonneg {Q : quadratic_form R₂ M} (hQ : pos_def Q) (x : M) : 0 ≤ Q x := (eq_or_ne x 0).elim (λ h, h.symm ▸ (map_zero Q).symm.le) (λ h, (hQ _ h).le) lemma pos_def.anisotropic {Q : quadratic_form R₂ M} (hQ : Q.pos_def) : Q.anisotropic := λ x hQx, classical.by_contradiction $ λ hx, lt_irrefl (0 : R₂) $ begin have := hQ _ hx, rw hQx at this, exact this, end lemma pos_def_of_nonneg {Q : quadratic_form R₂ M} (h : ∀ x, 0 ≤ Q x) (h0 : Q.anisotropic) : pos_def Q := λ x hx, lt_of_le_of_ne (h x) (ne.symm $ λ hQx, hx $ h0 _ hQx) lemma pos_def_iff_nonneg {Q : quadratic_form R₂ M} : pos_def Q ↔ (∀ x, 0 ≤ Q x) ∧ Q.anisotropic := ⟨λ h, ⟨h.nonneg, h.anisotropic⟩, λ ⟨n, a⟩, pos_def_of_nonneg n a⟩ lemma pos_def.add (Q Q' : quadratic_form R₂ M) (hQ : pos_def Q) (hQ' : pos_def Q') : pos_def (Q + Q') := λ x hx, add_pos (hQ x hx) (hQ' x hx) lemma lin_mul_lin_self_pos_def {R} [linear_ordered_comm_ring R] [module R M] (f : M →ₗ[R] R) (hf : linear_map.ker f = ⊥) : pos_def (lin_mul_lin f f) := λ x hx, mul_self_pos.2 (λ h, hx $ linear_map.ker_eq_bot'.mp hf _ h) end pos_def end quadratic_form section /-! ### Quadratic forms and matrices Connect quadratic forms and matrices, in order to explicitly compute with them. The convention is twos out, so there might be a factor 2⁻¹ in the entries of the matrix. The determinant of the matrix is the discriminant of the quadratic form. -/ variables {n : Type w} [fintype n] [decidable_eq n] variables [comm_ring R₁] [add_comm_monoid M] [module R₁ M] /-- `M.to_quadratic_form` is the map `λ x, col x ⬝ M ⬝ row x` as a quadratic form. -/ def matrix.to_quadratic_form' (M : matrix n n R₁) : quadratic_form R₁ (n → R₁) := M.to_bilin'.to_quadratic_form variables [invertible (2 : R₁)] /-- A matrix representation of the quadratic form. -/ def quadratic_form.to_matrix' (Q : quadratic_form R₁ (n → R₁)) : matrix n n R₁ := Q.associated.to_matrix' open quadratic_form lemma quadratic_form.to_matrix'_smul (a : R₁) (Q : quadratic_form R₁ (n → R₁)) : (a • Q).to_matrix' = a • Q.to_matrix' := by simp only [to_matrix', linear_equiv.map_smul, linear_map.map_smul] lemma quadratic_form.is_symm_to_matrix' (Q : quadratic_form R₁ (n → R₁)) : Q.to_matrix'.is_symm := begin ext i j, rw [to_matrix', bilin_form.to_matrix'_apply, bilin_form.to_matrix'_apply, associated_is_symm] end end namespace quadratic_form variables {n : Type w} [fintype n] variables [comm_ring R₁] [decidable_eq n] [invertible (2 : R₁)] variables {m : Type w} [decidable_eq m] [fintype m] open_locale matrix @[simp] lemma to_matrix'_comp (Q : quadratic_form R₁ (m → R₁)) (f : (n → R₁) →ₗ[R₁] (m → R₁)) : (Q.comp f).to_matrix' = f.to_matrix'ᵀ ⬝ Q.to_matrix' ⬝ f.to_matrix' := by { ext, simp only [quadratic_form.associated_comp, bilin_form.to_matrix'_comp, to_matrix'] } section discriminant variables {Q : quadratic_form R₁ (n → R₁)} /-- The discriminant of a quadratic form generalizes the discriminant of a quadratic polynomial. -/ def discr (Q : quadratic_form R₁ (n → R₁)) : R₁ := Q.to_matrix'.det lemma discr_smul (a : R₁) : (a • Q).discr = a ^ fintype.card n * Q.discr := by simp only [discr, to_matrix'_smul, matrix.det_smul] lemma discr_comp (f : (n → R₁) →ₗ[R₁] (n → R₁)) : (Q.comp f).discr = f.to_matrix'.det * f.to_matrix'.det * Q.discr := by simp only [matrix.det_transpose, mul_left_comm, quadratic_form.to_matrix'_comp, mul_comm, matrix.det_mul, discr] end discriminant end quadratic_form namespace quadratic_form end quadratic_form namespace bilin_form section semiring variables [semiring R] [add_comm_monoid M] [module R M] /-- A bilinear form is nondegenerate if the quadratic form it is associated with is anisotropic. -/ lemma nondegenerate_of_anisotropic {B : bilin_form R M} (hB : B.to_quadratic_form.anisotropic) : B.nondegenerate := λ x hx, hB _ (hx x) end semiring variables [ring R] [add_comm_group M] [module R M] /-- There exists a non-null vector with respect to any symmetric, nonzero bilinear form `B` on a module `M` over a ring `R` with invertible `2`, i.e. there exists some `x : M` such that `B x x ≠ 0`. -/ lemma exists_bilin_form_self_ne_zero [htwo : invertible (2 : R)] {B : bilin_form R M} (hB₁ : B ≠ 0) (hB₂ : B.is_symm) : ∃ x, ¬ B.is_ortho x x := begin lift B to quadratic_form R M using hB₂ with Q, obtain ⟨x, hx⟩ := quadratic_form.exists_quadratic_form_ne_zero hB₁, exact ⟨x, λ h, hx (Q.associated_eq_self_apply ℕ x ▸ h)⟩, end open finite_dimensional variables {V : Type u} {K : Type v} [field K] [add_comm_group V] [module K V] variable [finite_dimensional K V] /-- Given a symmetric bilinear form `B` on some vector space `V` over a field `K` in which `2` is invertible, there exists an orthogonal basis with respect to `B`. -/ lemma exists_orthogonal_basis [hK : invertible (2 : K)] {B : bilin_form K V} (hB₂ : B.is_symm) : ∃ (v : basis (fin (finrank K V)) K V), B.is_Ortho v := begin unfreezingI { induction hd : finrank K V with d ih generalizing V }, { exact ⟨basis_of_finrank_zero hd, λ _ _ _, zero_left _⟩ }, haveI := finrank_pos_iff.1 (hd.symm ▸ nat.succ_pos d : 0 < finrank K V), -- either the bilinear form is trivial or we can pick a non-null `x` obtain rfl | hB₁ := eq_or_ne B 0, { let b := finite_dimensional.fin_basis K V, rw hd at b, refine ⟨b, λ i j hij, rfl⟩, }, obtain ⟨x, hx⟩ := exists_bilin_form_self_ne_zero hB₁ hB₂, rw [← submodule.finrank_add_eq_of_is_compl (is_compl_span_singleton_orthogonal hx).symm, finrank_span_singleton (ne_zero_of_not_is_ortho_self x hx)] at hd, let B' := B.restrict (B.orthogonal $ K ∙ x), obtain ⟨v', hv₁⟩ := ih (B.restrict_symm hB₂ _ : B'.is_symm) (nat.succ.inj hd), -- concatenate `x` with the basis obtained by induction let b := basis.mk_fin_cons x v' (begin rintros c y hy hc, rw add_eq_zero_iff_neg_eq at hc, rw [← hc, submodule.neg_mem_iff] at hy, have := (is_compl_span_singleton_orthogonal hx).disjoint, rw submodule.disjoint_def at this, have := this (c • x) (submodule.smul_mem _ _ $ submodule.mem_span_singleton_self _) hy, exact (smul_eq_zero.1 this).resolve_right (λ h, hx $ h.symm ▸ zero_left _), end) (begin intro y, refine ⟨-B x y/B x x, λ z hz, _⟩, obtain ⟨c, rfl⟩ := submodule.mem_span_singleton.1 hz, rw [is_ortho, smul_left, add_right, smul_right, div_mul_cancel _ hx, add_neg_self, mul_zero], end), refine ⟨b, _⟩, { rw basis.coe_mk_fin_cons, intros j i, refine fin.cases _ (λ i, _) i; refine fin.cases _ (λ j, _) j; intro hij; simp only [function.on_fun, fin.cons_zero, fin.cons_succ, function.comp_apply], { exact (hij rfl).elim }, { rw [is_ortho, hB₂], exact (v' j).prop _ (submodule.mem_span_singleton_self x) }, { exact (v' i).prop _ (submodule.mem_span_singleton_self x) }, { exact hv₁ _ _ (ne_of_apply_ne _ hij), }, } end end bilin_form namespace quadratic_form open_locale big_operators open finset bilin_form variables {M₁ : Type*} [semiring R] [comm_semiring R₁] [add_comm_monoid M] [add_comm_monoid M₁] variables [module R M] [module R M₁] variables {ι : Type*} [fintype ι] {v : basis ι R M} /-- Given a quadratic form `Q` and a basis, `basis_repr` is the basis representation of `Q`. -/ noncomputable def basis_repr (Q : quadratic_form R M) (v : basis ι R M) : quadratic_form R (ι → R) := Q.comp v.equiv_fun.symm @[simp] lemma basis_repr_apply (Q : quadratic_form R M) (w : ι → R) : Q.basis_repr v w = Q (∑ i : ι, w i • v i) := by { rw ← v.equiv_fun_symm_apply, refl } section variables (R₁) /-- The weighted sum of squares with respect to some weight as a quadratic form. The weights are applied using `•`; typically this definition is used either with `S = R₁` or `[algebra S R₁]`, although this is stated more generally. -/ def weighted_sum_squares [monoid S] [distrib_mul_action S R₁] [smul_comm_class S R₁ R₁] (w : ι → S) : quadratic_form R₁ (ι → R₁) := ∑ i : ι, w i • proj i i end @[simp] lemma weighted_sum_squares_apply [monoid S] [distrib_mul_action S R₁] [smul_comm_class S R₁ R₁] (w : ι → S) (v : ι → R₁) : weighted_sum_squares R₁ w v = ∑ i : ι, w i • (v i * v i) := quadratic_form.sum_apply _ _ _ /-- On an orthogonal basis, the basis representation of `Q` is just a sum of squares. -/ lemma basis_repr_eq_of_is_Ortho {R₁ M} [comm_ring R₁] [add_comm_group M] [module R₁ M] [invertible (2 : R₁)] (Q : quadratic_form R₁ M) (v : basis ι R₁ M) (hv₂ : (associated Q).is_Ortho v) : Q.basis_repr v = weighted_sum_squares _ (λ i, Q (v i)) := begin ext w, rw [basis_repr_apply, ←@associated_eq_self_apply R₁, sum_left, weighted_sum_squares_apply], refine sum_congr rfl (λ j hj, _), rw [←@associated_eq_self_apply R₁, sum_right, sum_eq_single_of_mem j hj], { rw [smul_left, smul_right, smul_eq_mul], ring }, { intros i _ hij, rw [smul_left, smul_right, show associated_hom R₁ Q (v j) (v i) = 0, from hv₂ j i hij.symm, mul_zero, mul_zero] }, end end quadratic_form
94e1c178ec66339c0c90f88e505681021bcaa6b7
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Init/Data/Hashable.lean
5fd1d9ce5a4d382887c54b2b0425cc606e7c5f00
[ "Apache-2.0" ]
permissive
williamdemeo/lean4
72161c58fe65c3ad955d6a3050bb7d37c04c0d54
6d00fcf1d6d873e195f9220c668ef9c58e9c4a35
refs/heads/master
1,678,305,356,877
1,614,708,995,000
1,614,708,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
968
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Data.UInt import Init.Data.String universes u instance : Hashable Nat where hash n := USize.ofNat n instance [Hashable α] [Hashable β] : Hashable (α × β) where hash | (a, b) => mixHash (hash a) (hash b) instance : Hashable Bool where hash | true => 11 | false => 13 protected def Option.hash [Hashable α] : Option α → USize | none => 11 | some a => mixHash (hash a) 13 instance [Hashable α] : Hashable (Option α) where hash | none => 11 | some a => mixHash (hash a) 13 instance [Hashable α] : Hashable (List α) where hash as := as.foldl (fun r a => mixHash r (hash a)) 7 instance : Hashable UInt32 where hash n := n.toUSize instance : Hashable UInt64 where hash n := n.toUSize instance : Hashable USize where hash n := n
48df1cfae1b818c6949b03de7a49e633d4458ee4
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/tactic/explode.lean
796f2253e902b559c0672b6699154086bf26fbb8
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
5,252
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro Displays a proof term in a line by line format somewhat akin to a Fitch style proof or the Metamath proof style. -/ import tactic.core meta.coinductive_predicates open expr tactic namespace tactic namespace explode -- TODO(Mario): move back to list.basic @[simp] def head' {α} : list α → option α | [] := none | (a :: l) := some a inductive status | reg | intro | lam | sintro meta structure entry := (expr : expr) (line : nat) (depth : nat) (status : status) (thm : string) (deps : list nat) meta def pad_right (l : list string) : list string := let n := l.foldl (λ r (s:string), max r s.length) 0 in l.map $ λ s, nat.iterate (λ s, s.push ' ') (n - s.length) s meta structure entries := mk' :: (s : expr_map entry) (l : list entry) meta def entries.find (es : entries) (e : expr) := es.s.find e meta def entries.size (es : entries) := es.s.size meta def entries.add : entries → entry → entries | es@⟨s, l⟩ e := if s.contains e.expr then es else ⟨s.insert e.expr e, e :: l⟩ meta def entries.head (es : entries) : option entry := head' es.l meta instance : inhabited entries := ⟨⟨expr_map.mk _, []⟩⟩ meta def format_aux : list string → list string → list string → list entry → tactic format | (line :: lines) (dep :: deps) (thm :: thms) (en :: es) := do fmt ← do { let margin := string.join (list.repeat " │" en.depth), let margin := match en.status with | status.sintro := " ├" ++ margin | status.intro := " │" ++ margin ++ " ┌" | status.reg := " │" ++ margin ++ "" | status.lam := " │" ++ margin ++ "" end, p ← infer_type en.expr >>= pp, let lhs := line ++ "│" ++ dep ++ "│ " ++ thm ++ margin ++ " ", return $ format.of_string lhs ++ to_string p ++ format.line }, (++ fmt) <$> format_aux lines deps thms es | _ _ _ _ := return format.nil meta instance : has_to_tactic_format entries := ⟨λ es : entries, let lines := pad_right $ es.l.map (λ en, to_string en.line), deps := pad_right $ es.l.map (λ en, string.intercalate "," (en.deps.map to_string)), thms := pad_right $ es.l.map entry.thm in format_aux lines deps thms es.l⟩ meta def append_dep (filter : expr → tactic unit) (es : entries) (e : expr) (deps : list nat) : tactic (list nat) := do { ei ← es.find e, filter ei.expr, return (ei.line :: deps) } <|> return deps meta def may_be_proof (e : expr) : tactic bool := do expr.sort u ← infer_type e >>= infer_type, return $ bnot u.nonzero end explode open explode meta mutual def explode.core, explode.args (filter : expr → tactic unit) with explode.core : expr → bool → nat → entries → tactic entries | e@(lam n bi d b) si depth es := do m ← mk_fresh_name, let l := local_const m n bi d, let b' := instantiate_var b l, if si then let en : entry := ⟨l, es.size, depth, status.sintro, to_string n, []⟩ in do es' ← explode.core b' si depth (es.add en), return $ es'.add ⟨e, es'.size, depth, status.lam, "∀I", [es.size, es'.size - 1]⟩ else do let en : entry := ⟨l, es.size, depth, status.intro, to_string n, []⟩, es' ← explode.core b' si (depth + 1) (es.add en), deps' ← explode.append_dep filter es' b' [], deps' ← explode.append_dep filter es' l deps', return $ es'.add ⟨e, es'.size, depth, status.lam, "∀I", deps'⟩ | e@(macro _ l) si depth es := explode.core l.head si depth es | e si depth es := filter e >> match get_app_fn_args e with | (const n _, args) := explode.args e args depth es (to_string n) [] | (fn, []) := do p ← pp fn, let en : entry := ⟨fn, es.size, depth, status.reg, to_string p, []⟩, return (es.add en) | (fn, args) := do es' ← explode.core fn ff depth es, deps ← explode.append_dep filter es' fn [], explode.args e args depth es' "∀E" deps end with explode.args : expr → list expr → nat → entries → string → list nat → tactic entries | e (arg :: args) depth es thm deps := do es' ← explode.core arg ff depth es <|> return es, deps' ← explode.append_dep filter es' arg deps, explode.args e args depth es' thm deps' | e [] depth es thm deps := return (es.add ⟨e, es.size, depth, status.reg, thm, deps.reverse⟩) meta def explode_expr (e : expr) (hide_non_prop := tt) : tactic entries := let filter := if hide_non_prop then λ e, may_be_proof e >>= guardb else λ _, skip in tactic.explode.core filter e tt 0 (default _) meta def explode (n : name) : tactic unit := do const n _ ← resolve_name n | fail "cannot resolve name", d ← get_decl n, v ← match d with | (declaration.defn _ _ _ v _ _) := return v | (declaration.thm _ _ _ v) := return v.get | _ := fail "not a definition" end, t ← pp d.type, explode_expr v <* trace (to_fmt n ++ " : " ++ t) >>= trace open interactive lean lean.parser interaction_monad.result @[user_command] meta def explode_cmd (_ : parse $ tk "#explode") : parser unit := do n ← ident, explode n . -- #explode iff_true_intro -- #explode nat.strong_rec_on end tactic
383817cf038f2c575d7bf9cf9c870e4aaee4dc3b
69d4931b605e11ca61881fc4f66db50a0a875e39
/src/algebra/module/projective.lean
07fc4e721977b5755fcb963c47f6e6c532cbdcc6
[ "Apache-2.0" ]
permissive
abentkamp/mathlib
d9a75d291ec09f4637b0f30cc3880ffb07549ee5
5360e476391508e092b5a1e5210bd0ed22dc0755
refs/heads/master
1,682,382,954,948
1,622,106,077,000
1,622,106,077,000
149,285,665
0
0
null
null
null
null
UTF-8
Lean
false
false
6,463
lean
/- Copyright (c) 2021 Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard -/ import algebra.module.basic import linear_algebra.finsupp import linear_algebra.basis /-! # Projective modules This file contains a definition of a projective module, the proof that our definition is equivalent to a lifting property, and the proof that all free modules are projective. ## Main definitions Let `R` be a ring (or a semiring) and let `M` be an `R`-module. * `is_projective R M` : the proposition saying that `M` is a projective `R`-module. ## Main theorems * `is_projective.lifting_property` : a map from a projective module can be lifted along a surjection. * `is_projective.of_lifting_property` : If for all R-module surjections `A →ₗ B`, all maps `M →ₗ B` lift to `M →ₗ A`, then `M` is projective. * `is_projective.of_free` : Free modules are projective ## Implementation notes The actual definition of projective we use is that the natural R-module map from the free R-module on the type M down to M splits. This is more convenient than certain other definitions which involve quantifying over universes, and also universe-polymorphic (the ring and module can be in different universes). We require that the module sits in at least as high a universe as the ring: without this, free modules don't even exist, and it's unclear if projective modules are even a useful notion. ## References https://en.wikipedia.org/wiki/Projective_module ## TODO - Direct sum of two projective modules is projective. - Arbitrary sum of projective modules is projective. - Any module admits a surjection from a projective module. All of these should be relatively straightforward. ## Tags projective module -/ universes u v /- The actual implementation we choose: `P` is projective if the natural surjection from the free `R`-module on `P` to `P` splits. -/ /-- An R-module is projective if it is a direct summand of a free module, or equivalently if maps from the module lift along surjections. There are several other equivalent definitions. -/ def is_projective (R : Type u) [semiring R] (P : Type (max u v)) [add_comm_monoid P] [module R P] : Prop := ∃ s : P →ₗ[R] (P →₀ R), function.left_inverse (finsupp.total P P R id) s namespace is_projective section semiring variables {R : Type u} [semiring R] {P : Type (max u v)} [add_comm_monoid P] [module R P] {M : Type (max u v)} [add_comm_group M] [module R M] {N : Type*} [add_comm_group N] [module R N] /-- A projective R-module has the property that maps from it lift along surjections. -/ theorem lifting_property (h : is_projective R P) (f : M →ₗ[R] N) (g : P →ₗ[R] N) (hf : function.surjective f) : ∃ (h : P →ₗ[R] M), f.comp h = g := begin /- Here's the first step of the proof. Recall that `X →₀ R` is Lean's way of talking about the free `R`-module on a type `X`. The universal property `finsupp.total` says that to a map `X → N` from a type to an `R`-module, we get an associated R-module map `(X →₀ R) →ₗ N`. Apply this to a (noncomputable) map `P → M` coming from the map `P →ₗ N` and a random splitting of the surjection `M →ₗ N`, and we get a map `φ : (P →₀ R) →ₗ M`. -/ let φ : (P →₀ R) →ₗ[R] M := finsupp.total _ _ _ (λ p, function.surj_inv hf (g p)), -- By projectivity we have a map `P →ₗ (P →₀ R)`; cases h with s hs, -- Compose to get `P →ₗ M`. This works. use φ.comp s, ext p, conv_rhs {rw ← hs p}, simp [φ, finsupp.total_apply, function.surj_inv_eq hf], end /-- A module which satisfies the universal property is projective. Note that the universe variables in `huniv` are somewhat restricted. -/ theorem of_lifting_property' -- If for all surjections of `R`-modules `M →ₗ N`, all maps `P →ₗ N` lift to `P →ₗ M`, (huniv : ∀ {M : Type (max v u)} {N : Type (max u v)} [add_comm_monoid M] [add_comm_monoid N], by exactI ∀ [module R M] [module R N], by exactI ∀ (f : M →ₗ[R] N) (g : P →ₗ[R] N), function.surjective f → ∃ (h : P →ₗ[R] M), f.comp h = g) : -- then `P` is projective. is_projective R P := begin -- let `s` be the universal map `(P →₀ R) →ₗ P` coming from the identity map `P →ₗ P`. obtain ⟨s, hs⟩ : ∃ (s : P →ₗ[R] P →₀ R), (finsupp.total P P R id).comp s = linear_map.id := huniv (finsupp.total P P R (id : P → P)) (linear_map.id : P →ₗ[R] P) _, -- This `s` works. { use s, rwa linear_map.ext_iff at hs }, { intro p, use finsupp.single p 1, simp }, end end semiring section ring variables {R : Type u} [ring R] {P : Type (max u v)} [add_comm_group P] [module R P] /-- A variant of `of_lifting_property'` when we're working over a `[ring R]`, which only requires quantifying over modules with an `add_comm_group` instance. -/ theorem of_lifting_property -- If for all surjections of `R`-modules `M →ₗ N`, all maps `P →ₗ N` lift to `P →ₗ M`, (huniv : ∀ {M : Type (max v u)} {N : Type (max u v)} [add_comm_group M] [add_comm_group N], by exactI ∀ [module R M] [module R N], by exactI ∀ (f : M →ₗ[R] N) (g : P →ₗ[R] N), function.surjective f → ∃ (h : P →ₗ[R] M), f.comp h = g) : -- then `P` is projective. is_projective R P := -- We could try and prove this *using* `of_lifting_property`, -- but this quickly leads to typeclass hell, -- so we just prove it over again. begin -- let `s` be the universal map `(P →₀ R) →ₗ P` coming from the identity map `P →ₗ P`. obtain ⟨s, hs⟩ : ∃ (s : P →ₗ[R] P →₀ R), (finsupp.total P P R id).comp s = linear_map.id := huniv (finsupp.total P P R (id : P → P)) (linear_map.id : P →ₗ[R] P) _, -- This `s` works. { use s, rwa linear_map.ext_iff at hs }, { intro p, use finsupp.single p 1, simp }, end /-- Free modules are projective. -/ theorem of_free {ι : Type*} (b : basis ι R P) : is_projective R P := begin -- need P →ₗ (P →₀ R) for definition of projective. -- get it from `ι → (P →₀ R)` coming from `b`. use b.constr ℕ (λ i, finsupp.single (b i) (1 : R)), intro m, simp only [b.constr_apply, mul_one, id.def, finsupp.smul_single', finsupp.total_single, linear_map.map_finsupp_sum], exact b.total_repr m, end end ring end is_projective
0a5cb7efc9ab74e9c6f8c08530c410e6fdbcf8b6
6b02ce66658141f3e0aa3dfa88cd30bbbb24d17b
/stage0/src/Lean/Elab/Frontend.lean
cebd5772c6099b7df68742e82b28f93da549b676
[ "Apache-2.0" ]
permissive
pbrinkmeier/lean4
d31991fd64095e64490cb7157bcc6803f9c48af4
32fd82efc2eaf1232299e930ec16624b370eac39
refs/heads/master
1,681,364,001,662
1,618,425,427,000
1,618,425,427,000
358,314,562
0
0
Apache-2.0
1,618,504,558,000
1,618,501,999,000
null
UTF-8
Lean
false
false
4,774
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.Elab.Import import Lean.Elab.Command import Lean.Util.Profile namespace Lean.Elab.Frontend structure State where commandState : Command.State parserState : Parser.ModuleParserState cmdPos : String.Pos commands : Array Syntax := #[] structure Context where inputCtx : Parser.InputContext abbrev FrontendM := ReaderT Context $ StateRefT State IO def setCommandState (commandState : Command.State) : FrontendM Unit := modify fun s => { s with commandState := commandState } @[inline] def runCommandElabM (x : Command.CommandElabM Unit) : FrontendM Unit := do let ctx ← read let s ← get let cmdCtx : Command.Context := { cmdPos := s.cmdPos, fileName := ctx.inputCtx.fileName, fileMap := ctx.inputCtx.fileMap } match ← liftM $ EIO.toIO' (do let (_, s) ← (x cmdCtx).run s.commandState; pure $ some s) with | Except.error e => throw <| IO.Error.userError s!"unexpected internal error: {← e.toMessageData.toString}" | Except.ok (some sNew) => setCommandState sNew | Except.ok none => pure () def elabCommandAtFrontend (stx : Syntax) : FrontendM Unit := do runCommandElabM do let infoTreeEnabled := (← getInfoState).enabled if checkTraceOption (← getOptions) `Elab.info then enableInfoTree Command.elabCommand stx enableInfoTree infoTreeEnabled def updateCmdPos : FrontendM Unit := do modify fun s => { s with cmdPos := s.parserState.pos } def getParserState : FrontendM Parser.ModuleParserState := do pure (← get).parserState def getCommandState : FrontendM Command.State := do pure (← get).commandState def setParserState (ps : Parser.ModuleParserState) : FrontendM Unit := modify fun s => { s with parserState := ps } def setMessages (msgs : MessageLog) : FrontendM Unit := modify fun s => { s with commandState := { s.commandState with messages := msgs } } def getInputContext : FrontendM Parser.InputContext := do pure (← read).inputCtx def processCommand : FrontendM Bool := do updateCmdPos let cmdState ← getCommandState let ictx ← getInputContext let pstate ← getParserState let scope := cmdState.scopes.head! let pmctx := { env := cmdState.env, options := scope.opts, currNamespace := scope.currNamespace, openDecls := scope.openDecls } let pos := ictx.fileMap.toPosition pstate.pos match profileit "parsing" scope.opts fun _ => Parser.parseCommand ictx pmctx pstate cmdState.messages with | (cmd, ps, messages) => modify fun s => { s with commands := s.commands.push cmd } setParserState ps setMessages messages if Parser.isEOI cmd || Parser.isExitCommand cmd then pure true -- Done else profileitM IO.Error "elaboration" scope.opts <| elabCommandAtFrontend cmd pure false partial def processCommands : FrontendM Unit := do let done ← processCommand unless done do processCommands end Frontend open Frontend def IO.processCommands (inputCtx : Parser.InputContext) (parserState : Parser.ModuleParserState) (commandState : Command.State) : IO State := do let (_, s) ← (Frontend.processCommands.run { inputCtx := inputCtx }).run { commandState := commandState, parserState := parserState, cmdPos := parserState.pos } pure s def process (input : String) (env : Environment) (opts : Options) (fileName : Option String := none) : IO (Environment × MessageLog) := do let fileName := fileName.getD "<input>" let inputCtx := Parser.mkInputContext input fileName let s ← IO.processCommands inputCtx { : Parser.ModuleParserState } (Command.mkState env {} opts) pure (s.commandState.env, s.commandState.messages) builtin_initialize registerOption `printMessageEndPos { defValue := false, descr := "print end position of each message in addition to start position" } registerTraceClass `Elab.info def getPrintMessageEndPos (opts : Options) : Bool := opts.getBool `printMessageEndPos false @[export lean_run_frontend] def runFrontend (input : String) (opts : Options) (fileName : String) (mainModuleName : Name) : IO (Environment × Bool) := do let inputCtx := Parser.mkInputContext input fileName let (header, parserState, messages) ← Parser.parseHeader inputCtx let (env, messages) ← processHeader header opts messages inputCtx let env := env.setMainModule mainModuleName let s ← IO.processCommands inputCtx parserState (Command.mkState env messages opts) for msg in s.commandState.messages.toList do IO.print (← msg.toString (includeEndPos := getPrintMessageEndPos opts)) pure (s.commandState.env, !s.commandState.messages.hasErrors) end Lean.Elab
874422cdb078b83eadf327471ea6a853b7787db0
1446f520c1db37e157b631385707cc28a17a595e
/stage0/src/Init/Lean/Eval.lean
a58779b2d884e12ee32c2da9733eb47591fa0580
[ "Apache-2.0" ]
permissive
bdbabiak/lean4
cab06b8a2606d99a168dd279efdd404edb4e825a
3f4d0d78b2ce3ef541cb643bbe21496bd6b057ac
refs/heads/master
1,615,045,275,530
1,583,793,696,000
1,583,793,696,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,045
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ prelude import Init.Control.Reader import Init.System.IO import Init.Lean.Environment namespace Lean universe u /-- `HasEval` extension that gives access to the current environment & options. The basic `HasEval` class is in the prelude and should not depend on these types. -/ class MetaHasEval (α : Type u) := (eval : Environment → Options → α → IO Unit) instance MetaHasEvalOfHasEval {α : Type u} [HasEval α] : MetaHasEval α := ⟨fun env opts a => HasEval.eval a⟩ abbrev MetaIO := ReaderT (Environment × Options) IO def MetaIO.getEnv : MetaIO Environment := do ctx ← read; pure ctx.1 def MetaIO.getOptions : MetaIO Options := do ctx ← read; pure ctx.2 instance MetaIO.metaHasEval : MetaHasEval (MetaIO Unit) := ⟨fun env opts x => x (env, opts)⟩ instance MetaIO.monadIO : MonadIO MetaIO := ⟨fun _ x _ => x⟩ end Lean
4f1ea4581fe4a287e9a1fa68842f8e744e40fdd3
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/clear.lean
60b4ea89de570332f4489b0491967582865fe888
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
3,483
lean
/- Copyright (c) 2020 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jannis Limperg -/ import tactic.core /-! # Better `clear` tactics We define two variants of the standard `clear` tactic: * `clear'` works like `clear` but the hypotheses that should be cleared can be given in any order. In contrast, `clear` can fail if hypotheses that depend on each other are given in the wrong order, even if all of them could be cleared. * `clear_dependent` works like `clear'` but also clears any hypotheses that depend on the given hypotheses. ## Implementation notes The implementation (ab)uses the native `revert_lst`, which can figure out dependencies between hypotheses. This implementation strategy was suggested by Simon Hudon. -/ open native tactic interactive lean.parser /-- Clears all the hypotheses in `hyps`. The tactic fails if any of the `hyps` is not a local or if the target depends on any of the `hyps`. It also fails if `hyps` contains duplicates. If there are local hypotheses or definitions, say `H`, which are not in `hyps` but depend on one of the `hyps`, what we do depends on `clear_dependent`. If it is true, `H` is implicitly also cleared. If it is false, `clear'` fails. -/ meta def tactic.clear' (clear_dependent : bool) (hyps : list expr) : tactic unit := do tgt ← target, -- Check if the target depends on any of the hyps. Doing this (instead of -- letting one of the later tactics fail) lets us give a much more informative -- error message. hyps.mmap' (λ h, do dep ← kdepends_on tgt h, when dep $ fail $ format!"Cannot clear hypothesis {h} since the target depends on it."), n ← revert_lst hyps, -- If revert_lst reverted more hypotheses than we wanted to clear, there must -- have been other hypotheses dependent on some of the hyps. when (! clear_dependent && (n ≠ hyps.length)) $ fail $ format.join [ "Some of the following hypotheses cannot be cleared because other " , "hypotheses depend on (some of) them:\n" , format.intercalate ", " (hyps.map to_fmt) ], v ← mk_meta_var tgt, intron n, exact v, gs ← get_goals, set_goals $ v :: gs namespace tactic.interactive /-- An improved version of the standard `clear` tactic. `clear` is sensitive to the order of its arguments: `clear x y` may fail even though both `x` and `y` could be cleared (if the type of `y` depends on `x`). `clear'` lifts this limitation. ```lean example {α} {β : α → Type} (a : α) (b : β a) : unit := begin try { clear a b }, -- fails since `b` depends on `a` clear' a b, -- succeeds exact () end ``` -/ meta def clear' (p : parse (many ident)) : tactic unit := do hyps ← p.mmap get_local, tactic.clear' false hyps /-- A variant of `clear'` which clears not only the given hypotheses, but also any other hypotheses depending on them. ```lean example {α} {β : α → Type} (a : α) (b : β a) : unit := begin try { clear' a }, -- fails since `b` depends on `a` clear_dependent a, -- succeeds, clearing `a` and `b` exact () end ``` -/ meta def clear_dependent (p : parse (many ident)) : tactic unit := do hyps ← p.mmap get_local, tactic.clear' true hyps add_tactic_doc { name := "clear'", category := doc_category.tactic, decl_names := [`tactic.interactive.clear', `tactic.interactive.clear_dependent], tags := ["context management"], inherit_description_from := `tactic.interactive.clear' } end tactic.interactive
20ff694822af41fb7cc51cb6a9d5a32ef0f07a55
94ec458bb9c7783744397f9a68d867bd7a765e18
/src/yoneda.lean
a6bd1a78d4c0b0bd57acc17ad284f5826ec45fc4
[]
no_license
myuon/lean-cate
b8fcfd7965a348155152b3fc7d5041b356721945
9e71e61c2a09d64b17ab3145ff6dde564387950a
refs/heads/master
1,611,236,436,038
1,462,408,916,000
1,462,408,916,000
47,414,605
0
0
null
null
null
null
UTF-8
Lean
false
false
3,167
lean
import category open category functor natrans open eq eq.ops definition homfunctor (C : category) (r : @obj C) : functor C Setoids := functor.mk (λx, setoido.mk (@hom C r x) (λf g, f = g) (mk_equivalence _ refl (λx y, symm) (λx y z, trans))) (λa b f, setoido_map.mk (λk, f ∘[C] k) (λx y xy, xy ▸ rfl)) (λa, setoido_map.equal (funext (λx, id_left))) (λa b c g f, setoido_map.equal (funext (λx, !assoc))) definition ophomfunctor (C : category) (r : @obj C) : functor (op C) Setoids := homfunctor (op C) r definition homnat (C : category) {a b : @obj C} (f : @hom C b a) : (homfunctor C a) ⇒ (homfunctor C b) := natrans.mk (λx, setoido_map.mk (λu, u ∘[C] f) (λx y xy, xy ▸ rfl)) (λa b f, setoido_map.equal (funext (λx, !assoc))) definition ophomnat (C : category) {a b : @obj C} (f : @hom C a b) : (ophomfunctor C a) ⇒ (ophomfunctor C b) := natrans.mk (λx, setoido_map.mk (λu, f ∘[C] u) (λx y xy, xy ▸ rfl)) (λa b f, setoido_map.equal (funext (λx, symm !assoc))) notation `Hom[` C `][` r `;-]` := homfunctor C r notation `Hom[` C `][-;` r `]` := ophomfunctor C r notation `HomNat[` C `][` f `;-]` := homnat C f notation `HomNat[` C `][-;` f `]` := ophomnat C f definition funcat (C D : category) : category := category.mk (functor C D) natrans (λx, natrans_id) (λa b c, natrans_comp) (λa b c d f g h, natrans_eq _ _ (λx, eqArrow.arr assoc)) (λa b f, natrans_eq _ _ (λx, eqArrow.arr id_left)) (λa b f, natrans_eq _ _ (λx, eqArrow.arr id_right)) notation `[` C `,` D `]` := funcat C D notation `PSh[` C `]` := [ op C, Setoids ] definition yoneda (C : category) : functor C PSh[C] := functor.mk (λx, ophomfunctor C x) (λa b f, ophomnat C f) (λa, natrans_eq _ _ (λx, !eqArrow.arr (setoido_map.equal (funext (λu, id_left))))) (λa b d g f, natrans_eq _ _ (λx, !eqArrow.arr (setoido_map.equal (funext (λu, assoc))))) lemma Yoneda (C : category) (F : functor (op C) Setoids) (r : @obj C) : @hom PSh[C] (fobj (yoneda C) r) F ≃[Types] setoido.carrier (fobj F r) := iso.mk (λα, setoido_map.map (component α r) (@id C r)) (λx, natrans.mk (λu, setoido_map.mk (λf, setoido_map.map (fmap F f) x) (λx y xy, xy ▸ setoido.refl)) (λa b f, setoido_map.equal (funext (λt, calc setoido_map.map (fmap F (t ∘[C] f)) x = setoido_map.map (fmap F f ∘[Setoids] fmap F t) x : congr (congr_arg _ (preserve_comp F)) rfl ... = setoido_map.map (fmap F f) (setoido_map.map (fmap F t) x) : rfl)))) (funext (λu, calc setoido_map.map (fmap F (@id C r)) u = setoido_map.map (@id Setoids (fobj F r)) u : congr (congr_arg _ (preserve_id F)) rfl ... = u : rfl)) (funext (λα, natrans_eq _ _ (λx, eqArrow.arr (setoido_map.equal (funext (λu, calc setoido_map.map (fmap F u) (setoido_map.map (component α r) id) = setoido_map.map (fmap F u ∘[Setoids] component α r) id : rfl ... = setoido_map.map (component α x ∘[Setoids] fmap (fobj (yoneda C) r) u) id : congr (congr_arg _ (naturality α)) rfl ... = setoido_map.map (component (id α) x) u : congr_arg _ (@id_left C _ _ _)))))))
282c68fccebad13928b5ab327da214bcab10f18b
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/ring_theory/noetherian.lean
eee14434753bc874bc29bb98654ecf287c90f529
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
21,393
lean
/- Copyright (c) 2018 Mario Carneiro and Kevin Buzzard. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Kevin Buzzard -/ import ring_theory.ideal.operations import linear_algebra.basis import order.order_iso_nat /-! # Noetherian rings and modules The following are equivalent for a module M over a ring R: 1. Every increasing chain of submodule M₁ ⊆ M₂ ⊆ M₃ ⊆ ⋯ eventually stabilises. 2. Every submodule is finitely generated. A module satisfying these equivalent conditions is said to be a *Noetherian* R-module. A ring is a *Noetherian ring* if it is Noetherian as a module over itself. ## Main definitions Let `R` be a ring and let `M` and `P` be `R`-modules. Let `N` be an `R`-submodule of `M`. * `fg N : Prop` is the assertion that `N` is finitely generated as an `R`-module. * `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module. It is a class, implemented as the predicate that all `R`-submodules of `M` are finitely generated. ## Main statements * `exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul` is Nakayama's lemma, in the following form: if N is a finitely generated submodule of an ambient R-module M and I is an ideal of R such that N ⊆ IN, then there exists r ∈ 1 + I such that rN = 0. * `is_noetherian_iff_well_founded` is the theorem that an R-module M is Noetherian iff `>` is well-founded on `submodule R M`. Note that the Hilbert basis theorem, that if a commutative ring R is Noetherian then so is R[X], is proved in `ring_theory.polynomial`. ## References * [M. F. Atiyah and I. G. Macdonald, *Introduction to commutative algebra*][atiyah-macdonald] ## Tags Noetherian, noetherian, Noetherian ring, Noetherian module, noetherian ring, noetherian module -/ open set open_locale big_operators namespace submodule variables {R : Type*} {M : Type*} [ring R] [add_comm_group M] [module R M] /-- A submodule of `M` is finitely generated if it is the span of a finite subset of `M`. -/ def fg (N : submodule R M) : Prop := ∃ S : finset M, submodule.span R ↑S = N theorem fg_def {N : submodule R M} : N.fg ↔ ∃ S : set M, finite S ∧ span R S = N := ⟨λ ⟨t, h⟩, ⟨_, finset.finite_to_set t, h⟩, begin rintro ⟨t', h, rfl⟩, rcases finite.exists_finset_coe h with ⟨t, rfl⟩, exact ⟨t, rfl⟩ end⟩ /-- Nakayama's Lemma. Atiyah-Macdonald 2.5, Eisenbud 4.7, Matsumura 2.2, Stacks 00DV -/ theorem exists_sub_one_mem_and_smul_eq_zero_of_fg_of_le_smul {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] (I : ideal R) (N : submodule R M) (hn : N.fg) (hin : N ≤ I • N) : ∃ r : R, r - 1 ∈ I ∧ ∀ n ∈ N, r • n = (0 : M) := begin rw fg_def at hn, rcases hn with ⟨s, hfs, hs⟩, have : ∃ r : R, r - 1 ∈ I ∧ N ≤ (I • span R s).comap (linear_map.lsmul R M r) ∧ s ⊆ N, { refine ⟨1, _, _, _⟩, { rw sub_self, exact I.zero_mem }, { rw [hs], intros n hn, rw [mem_comap], change (1:R) • n ∈ I • N, rw one_smul, exact hin hn }, { rw [← span_le, hs], exact le_refl N } }, clear hin hs, revert this, refine set.finite.dinduction_on hfs (λ H, _) (λ i s his hfs ih H, _), { rcases H with ⟨r, hr1, hrn, hs⟩, refine ⟨r, hr1, λ n hn, _⟩, specialize hrn hn, rwa [mem_comap, span_empty, smul_bot, mem_bot] at hrn }, apply ih, rcases H with ⟨r, hr1, hrn, hs⟩, rw [← set.singleton_union, span_union, smul_sup] at hrn, rw [set.insert_subset] at hs, have : ∃ c : R, c - 1 ∈ I ∧ c • i ∈ I • span R s, { specialize hrn hs.1, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • i at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨c, hci, rfl⟩, use r-c, split, { rw [sub_right_comm], exact I.sub_mem hr1 hci }, { rw [sub_smul, ← hyz, add_sub_cancel'], exact hz } }, rcases this with ⟨c, hc1, hci⟩, refine ⟨c * r, _, _, hs.2⟩, { rw [← ideal.quotient.eq, ring_hom.map_one] at hr1 hc1 ⊢, rw [ring_hom.map_mul, hc1, hr1, mul_one] }, { intros n hn, specialize hrn hn, rw [mem_comap, mem_sup] at hrn, rcases hrn with ⟨y, hy, z, hz, hyz⟩, change y + z = r • n at hyz, rw mem_smul_span_singleton at hy, rcases hy with ⟨d, hdi, rfl⟩, change _ • _ ∈ I • span R s, rw [mul_smul, ← hyz, smul_add, smul_smul, mul_comm, mul_smul], exact add_mem _ (smul_mem _ _ hci) (smul_mem _ _ hz) } end theorem fg_bot : (⊥ : submodule R M).fg := ⟨∅, by rw [finset.coe_empty, span_empty]⟩ theorem fg_sup {N₁ N₂ : submodule R M} (hN₁ : N₁.fg) (hN₂ : N₂.fg) : (N₁ ⊔ N₂).fg := let ⟨t₁, ht₁⟩ := fg_def.1 hN₁, ⟨t₂, ht₂⟩ := fg_def.1 hN₂ in fg_def.2 ⟨t₁ ∪ t₂, ht₁.1.union ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩ variables {P : Type*} [add_comm_group P] [module R P] variables {f : M →ₗ[R] P} theorem fg_map {N : submodule R M} (hs : N.fg) : (N.map f).fg := let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, ht.1.image _, by rw [span_image, ht.2]⟩ theorem fg_prod {sb : submodule R M} {sc : submodule R P} (hsb : sb.fg) (hsc : sc.fg) : (sb.prod sc).fg := let ⟨tb, htb⟩ := fg_def.1 hsb, ⟨tc, htc⟩ := fg_def.1 hsc in fg_def.2 ⟨linear_map.inl R M P '' tb ∪ linear_map.inr R M P '' tc, (htb.1.image _).union (htc.1.image _), by rw [linear_map.span_inl_union_inr, htb.2, htc.2]⟩ variable (f) /-- If 0 → M' → M → M'' → 0 is exact and M' and M'' are finitely generated then so is M. -/ theorem fg_of_fg_map_of_fg_inf_ker {s : submodule R M} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg := begin haveI := classical.dec_eq R, haveI := classical.dec_eq M, haveI := classical.dec_eq P, cases hs1 with t1 ht1, cases hs2 with t2 ht2, have : ∀ y ∈ t1, ∃ x ∈ s, f x = y, { intros y hy, have : y ∈ map f s, { rw ← ht1, exact subset_span hy }, rcases mem_map.1 this with ⟨x, hx1, hx2⟩, exact ⟨x, hx1, hx2⟩ }, have : ∃ g : P → M, ∀ y ∈ t1, g y ∈ s ∧ f (g y) = y, { choose g hg1 hg2, existsi λ y, if H : y ∈ t1 then g y H else 0, intros y H, split, { simp only [dif_pos H], apply hg1 }, { simp only [dif_pos H], apply hg2 } }, cases this with g hg, clear this, existsi t1.image g ∪ t2, rw [finset.coe_union, span_union, finset.coe_image], apply le_antisymm, { refine sup_le (span_le.2 $ image_subset_iff.2 _) (span_le.2 _), { intros y hy, exact (hg y hy).1 }, { intros x hx, have := subset_span hx, rw ht2 at this, exact this.1 } }, intros x hx, have : f x ∈ map f s, { rw mem_map, exact ⟨x, hx, rfl⟩ }, rw [← ht1,← set.image_id ↑t1, finsupp.mem_span_iff_total] at this, rcases this with ⟨l, hl1, hl2⟩, refine mem_sup.2 ⟨(finsupp.total M M R id).to_fun ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, x - finsupp.total M M R id ((finsupp.lmap_domain R R g : (P →₀ R) → M →₀ R) l), _, add_sub_cancel'_right _ _⟩, { rw [← set.image_id (g '' ↑t1), finsupp.mem_span_iff_total], refine ⟨_, _, rfl⟩, haveI : inhabited P := ⟨0⟩, rw [← finsupp.lmap_domain_supported _ _ g, mem_map], refine ⟨l, hl1, _⟩, refl, }, rw [ht2, mem_inf], split, { apply s.sub_mem hx, rw [finsupp.total_apply, finsupp.lmap_domain_apply, finsupp.sum_map_domain_index], refine s.sum_mem _, { intros y hy, exact s.smul_mem _ (hg y (hl1 hy)).1 }, { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } }, { rw [linear_map.mem_ker, f.map_sub, ← hl2], rw [finsupp.total_apply, finsupp.total_apply, finsupp.lmap_domain_apply], rw [finsupp.sum_map_domain_index, finsupp.sum, finsupp.sum, f.map_sum], rw sub_eq_zero, refine finset.sum_congr rfl (λ y hy, _), unfold id, rw [f.map_smul, (hg y (hl1 hy)).2], { exact zero_smul _ }, { exact λ _ _ _, add_smul _ _ _ } } end end submodule /-- `is_noetherian R M` is the proposition that `M` is a Noetherian `R`-module, implemented as the predicate that all `R`-submodules of `M` are finitely generated. -/ class is_noetherian (R M) [ring R] [add_comm_group M] [module R M] : Prop := (noetherian : ∀ (s : submodule R M), s.fg) section variables {R : Type*} {M : Type*} {P : Type*} variables [ring R] [add_comm_group M] [add_comm_group P] variables [module R M] [module R P] open is_noetherian include R theorem is_noetherian_submodule {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, s ≤ N → s.fg := ⟨λ ⟨hn⟩, λ s hs, have s ≤ N.subtype.range, from (N.range_subtype).symm ▸ hs, linear_map.map_comap_eq_self this ▸ submodule.fg_map (hn _), λ h, ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker N.subtype (h _ $ submodule.map_subtype_le _ _) $ by rw [submodule.ker_subtype, inf_bot_eq]; exact submodule.fg_bot⟩⟩ theorem is_noetherian_submodule_left {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (N ⊓ s).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_left, λ H s hs, (inf_of_le_right hs) ▸ H _⟩ theorem is_noetherian_submodule_right {N : submodule R M} : is_noetherian R N ↔ ∀ s : submodule R M, (s ⊓ N).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩ variable (M) theorem is_noetherian_of_surjective (f : M →ₗ[R] P) (hf : f.range = ⊤) [is_noetherian R M] : is_noetherian R P := ⟨λ s, have (s.comap f).map f = s, from linear_map.map_comap_eq_self $ hf.symm ▸ le_top, this ▸ submodule.fg_map $ noetherian _⟩ variable {M} theorem is_noetherian_of_linear_equiv (f : M ≃ₗ[R] P) [is_noetherian R M] : is_noetherian R P := is_noetherian_of_surjective _ f.to_linear_map f.range instance is_noetherian_prod [is_noetherian R M] [is_noetherian R P] : is_noetherian R (M × P) := ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd R M P) (noetherian _) $ have s ⊓ linear_map.ker (linear_map.snd R M P) ≤ linear_map.range (linear_map.inl R M P), from λ x ⟨hx1, hx2⟩, ⟨x.1, trivial, prod.ext rfl $ eq.symm $ linear_map.mem_ker.1 hx2⟩, linear_map.map_comap_eq_self this ▸ submodule.fg_map (noetherian _)⟩ instance is_noetherian_pi {R ι : Type*} {M : ι → Type*} [ring R] [Π i, add_comm_group (M i)] [Π i, module R (M i)] [fintype ι] [∀ i, is_noetherian R (M i)] : is_noetherian R (Π i, M i) := begin haveI := classical.dec_eq ι, suffices : ∀ s : finset ι, is_noetherian R (Π i : (↑s : set ι), M i), { letI := this finset.univ, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (this finset.univ), { exact λ f i, f ⟨i, finset.mem_univ _⟩ }, { intros, ext, refl }, { intros, ext, refl }, { exact λ f i, f i.1 }, { intro, ext ⟨⟩, refl }, { intro, ext i, refl } }, intro s, induction s using finset.induction with a s has ih, { split, intro s, convert submodule.fg_bot, apply eq_bot_iff.2, intros x hx, refine (submodule.mem_bot R).2 _, ext i, cases i.2 }, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (@is_noetherian_prod _ (M a) _ _ _ _ _ _ _ ih), { exact λ f i, or.by_cases (finset.mem_insert.1 i.2) (λ h : i.1 = a, show M i.1, from (eq.rec_on h.symm f.1)) (λ h : i.1 ∈ s, show M i.1, from f.2 ⟨i.1, h⟩) }, { intros f g, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = _ + _, simp only [dif_pos], refl }, { change _ = _ + _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { intros c f, ext i, unfold or.by_cases, cases i with i hi, rcases finset.mem_insert.1 hi with rfl | h, { change _ = c • _, simp only [dif_pos], refl }, { change _ = c • _, have : ¬i = a, { rintro rfl, exact has h }, simp only [dif_neg this, dif_pos h], refl } }, { exact λ f, (f ⟨a, finset.mem_insert_self _ _⟩, λ i, f ⟨i.1, finset.mem_insert_of_mem i.2⟩) }, { intro f, apply prod.ext, { simp only [or.by_cases, dif_pos] }, { ext ⟨i, his⟩, have : ¬i = a, { rintro rfl, exact has his }, dsimp only [or.by_cases], change i ∈ s at his, rw [dif_neg this, dif_pos his] } }, { intro f, ext ⟨i, hi⟩, rcases finset.mem_insert.1 hi with rfl | h, { simp only [or.by_cases, dif_pos], refl }, { have : ¬i = a, { rintro rfl, exact has h }, simp only [or.by_cases, dif_neg this, dif_pos h], refl } } end end open is_noetherian submodule function theorem is_noetherian_iff_well_founded {R M} [ring R] [add_comm_group M] [module R M] : is_noetherian R M ↔ well_founded ((>) : submodule R M → submodule R M → Prop) := ⟨λ h, begin apply rel_embedding.well_founded_iff_no_descending_seq.2, swap, { apply is_strict_order.swap }, rintro ⟨⟨N, hN⟩⟩, let Q := ⨆ n, N n, resetI, rcases submodule.fg_def.1 (noetherian Q) with ⟨t, h₁, h₂⟩, have hN' : ∀ {a b}, a ≤ b → N a ≤ N b := λ a b, (strict_mono.le_iff_le (λ _ _, hN.1)).2, have : t ⊆ ⋃ i, (N i : set M), { rw [← submodule.coe_supr_of_directed N _], { show t ⊆ Q, rw ← h₂, apply submodule.subset_span }, { exact λ i j, ⟨max i j, hN' (le_max_left _ _), hN' (le_max_right _ _)⟩ } }, simp [subset_def] at this, choose f hf using show ∀ x : t, ∃ (i : ℕ), x.1 ∈ N i, { simpa }, cases h₁ with h₁, let A := finset.sup (@finset.univ t h₁) f, have : Q ≤ N A, { rw ← h₂, apply submodule.span_le.2, exact λ x h, hN' (finset.le_sup (@finset.mem_univ t h₁ _)) (hf ⟨x, h⟩) }, exact not_le_of_lt (hN.1 (nat.lt_succ_self A)) (le_trans (le_supr _ _) this) end, begin assume h, split, assume N, suffices : ∀ P ≤ N, ∃ s, finite s ∧ P ⊔ submodule.span R s = N, { rcases this ⊥ bot_le with ⟨s, hs, e⟩, exact submodule.fg_def.2 ⟨s, hs, by simpa using e⟩ }, refine λ P, h.induction P _, intros P IH PN, letI := classical.dec, by_cases h : ∀ x, x ∈ N → x ∈ P, { cases le_antisymm PN h, exact ⟨∅, by simp⟩ }, { simp [not_forall] at h, rcases h with ⟨x, h, h₂⟩, have : ¬P ⊔ submodule.span R {x} ≤ P, { intro hn, apply h₂, have := le_trans le_sup_right hn, exact submodule.span_le.1 this (mem_singleton x) }, rcases IH (P ⊔ submodule.span R {x}) ⟨@le_sup_left _ _ P _, this⟩ (sup_le PN (submodule.span_le.2 (by simpa))) with ⟨s, hs, hs₂⟩, refine ⟨insert x s, hs.insert x, _⟩, rw [← hs₂, sup_assoc, ← submodule.span_union], simp } end⟩ lemma well_founded_submodule_gt (R M) [ring R] [add_comm_group M] [module R M] : ∀ [is_noetherian R M], well_founded ((>) : submodule R M → submodule R M → Prop) := is_noetherian_iff_well_founded.mp lemma finite_of_linear_independent {R M} [comm_ring R] [nontrivial R] [add_comm_group M] [module R M] [is_noetherian R M] {s : set M} (hs : linear_independent R (coe : s → M)) : s.finite := begin refine classical.by_contradiction (λ hf, rel_embedding.well_founded_iff_no_descending_seq.1 (well_founded_submodule_gt R M) ⟨_⟩), have f : ℕ ↪ s, from @infinite.nat_embedding s ⟨λ f, hf ⟨f⟩⟩, have : ∀ n, (coe ∘ f) '' {m | m ≤ n} ⊆ s, { rintros n x ⟨y, hy₁, hy₂⟩, subst hy₂, exact (f y).2 }, have : ∀ a b : ℕ, a ≤ b ↔ span R ((coe ∘ f) '' {m | m ≤ a}) ≤ span R ((coe ∘ f) '' {m | m ≤ b}), { assume a b, rw [span_le_span_iff hs (this a) (this b), set.image_subset_image_iff (subtype.coe_injective.comp f.injective), set.subset_def], exact ⟨λ hab x (hxa : x ≤ a), le_trans hxa hab, λ hx, hx a (le_refl a)⟩ }, exact ⟨⟨λ n, span R ((coe ∘ f) '' {m | m ≤ n}), λ x y, by simp [le_antisymm_iff, (this _ _).symm] {contextual := tt}⟩, by dsimp [gt]; simp only [lt_iff_le_not_le, (this _ _).symm]; tauto⟩ end /-- A module is Noetherian iff every nonempty set of submodules has a maximal submodule among them. -/ theorem set_has_maximal_iff_noetherian {R M} [ring R] [add_comm_group M] [module R M] : (∀ a : set $ submodule R M, a.nonempty → ∃ M' ∈ a, ∀ I ∈ a, M' ≤ I → I = M') ↔ is_noetherian R M := by rw [is_noetherian_iff_well_founded, well_founded.well_founded_iff_has_max'] /-- A ring is Noetherian if it is Noetherian as a module over itself, i.e. all its ideals are finitely generated. -/ @[class] def is_noetherian_ring (R) [ring R] : Prop := is_noetherian R R instance is_noetherian_ring.to_is_noetherian {R : Type*} [ring R] : ∀ [is_noetherian_ring R], is_noetherian R R := id @[priority 80] -- see Note [lower instance priority] instance ring.is_noetherian_of_fintype (R M) [fintype M] [ring R] [add_comm_group M] [module R M] : is_noetherian R M := by letI := classical.dec; exact ⟨assume s, ⟨to_finset s, by rw [set.coe_to_finset, submodule.span_eq]⟩⟩ theorem ring.is_noetherian_of_zero_eq_one {R} [ring R] (h01 : (0 : R) = 1) : is_noetherian_ring R := by haveI := subsingleton_of_zero_eq_one h01; haveI := fintype.of_subsingleton (0:R); exact ring.is_noetherian_of_fintype _ _ theorem is_noetherian_of_submodule_of_noetherian (R M) [ring R] [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.map_subtype.order_embedding N).dual h, end theorem is_noetherian_of_quotient_of_noetherian (R) [ring R] (M) [add_comm_group M] [module R M] (N : submodule R M) (h : is_noetherian R M) : is_noetherian R N.quotient := begin rw is_noetherian_iff_well_founded at h ⊢, exact order_embedding.well_founded (submodule.comap_mkq.order_embedding N).dual h, end theorem is_noetherian_of_fg_of_noetherian {R M} [ring R] [add_comm_group M] [module R M] (N : submodule R M) [is_noetherian_ring R] (hN : N.fg) : is_noetherian R N := let ⟨s, hs⟩ := hN in begin haveI := classical.dec_eq M, haveI := classical.dec_eq R, letI : is_noetherian R R := by apply_instance, have : ∀ x ∈ s, x ∈ N, from λ x hx, hs ▸ submodule.subset_span hx, refine @@is_noetherian_of_surjective ((↑s : set M) → R) _ _ _ (pi.semimodule _ _ _) _ _ _ is_noetherian_pi, { fapply linear_map.mk, { exact λ f, ⟨∑ i in s.attach, f i • i.1, N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change ∑ i in s.attach, (f i + g i) • _ = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change ∑ i in s.attach, (c • f i) • _ = _, simp only [smul_eq_mul, mul_smul], exact finset.smul_sum.symm } }, rw linear_map.range_eq_top, rintro ⟨n, hn⟩, change n ∈ N at hn, rw [← hs, ← set.image_id ↑s, finsupp.mem_span_iff_total] at hn, rcases hn with ⟨l, hl1, hl2⟩, refine ⟨λ x, l x, subtype.ext _⟩, change ∑ i in s.attach, l i • (i : M) = n, rw [@finset.sum_attach M M s _ (λ i, l i • i), ← hl2, finsupp.total_apply, finsupp.sum, eq_comm], refine finset.sum_subset hl1 (λ x _ hx, _), rw [finsupp.not_mem_support_iff.1 hx, zero_smul] end /-- In a module over a noetherian ring, the submodule generated by finitely many vectors is noetherian. -/ theorem is_noetherian_span_of_finite (R) {M} [ring R] [add_comm_group M] [module R M] [is_noetherian_ring R] {A : set M} (hA : finite A) : is_noetherian R (submodule.span R A) := is_noetherian_of_fg_of_noetherian _ (submodule.fg_def.mpr ⟨A, hA, rfl⟩) theorem is_noetherian_ring_of_surjective (R) [comm_ring R] (S) [comm_ring S] (f : R →+* S) (hf : function.surjective f) [H : is_noetherian_ring R] : is_noetherian_ring S := begin rw [is_noetherian_ring, is_noetherian_iff_well_founded] at H ⊢, exact order_embedding.well_founded (ideal.order_embedding_of_surjective f hf).dual H, end instance is_noetherian_ring_set_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring (set.range f) := is_noetherian_ring_of_surjective R (set.range f) (f.cod_restrict (set.range f) set.mem_range_self) set.surjective_onto_range instance is_noetherian_ring_range {R} [comm_ring R] {S} [comm_ring S] (f : R →+* S) [is_noetherian_ring R] : is_noetherian_ring f.range := is_noetherian_ring_of_surjective R f.range (f.cod_restrict' f.range f.mem_range_self) f.surjective_onto_range theorem is_noetherian_ring_of_ring_equiv (R) [comm_ring R] {S} [comm_ring S] (f : R ≃+* S) [is_noetherian_ring R] : is_noetherian_ring S := is_noetherian_ring_of_surjective R S f.to_ring_hom f.to_equiv.surjective namespace submodule variables {R : Type*} {A : Type*} [comm_ring R] [ring A] [algebra R A] variables (M N : submodule R A) theorem fg_mul (hm : M.fg) (hn : N.fg) : (M * N).fg := let ⟨m, hfm, hm⟩ := fg_def.1 hm, ⟨n, hfn, hn⟩ := fg_def.1 hn in fg_def.2 ⟨m * n, hfm.mul hfn, span_mul_span R m n ▸ hm ▸ hn ▸ rfl⟩ lemma fg_pow (h : M.fg) (n : ℕ) : (M ^ n).fg := nat.rec_on n (⟨{1}, by simp [one_eq_span]⟩) (λ n ih, by simpa [pow_succ] using fg_mul _ _ h ih) end submodule
a388fe3dbb4a14fe10360ad3e136220b94a88836
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/linear_algebra/bilinear_map.lean
bf1939354b150a89fafbb65e4f066965d649c709
[ "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,690
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 -/ import linear_algebra.basic /-! # Basics on bilinear maps This file provides basics on bilinear maps. ## Main declarations * `linear_map.mk₂`: a constructor for bilinear maps, taking an unbundled function together with proof witnesses of bilinearity * `linear_map.flip`: turns a bilinear map `M × N → P` into `N × M → P` * `linear_map.lcomp` and `linear_map.llcomp`: composition of linear maps as a bilinear map * `linear_map.compl₂`: composition of a bilinear map `M × N → P` with a linear map `Q → M` * `linear_map.compr₂`: composition of a bilinear map `M × N → P` with a linear map `Q → N` * `linear_map.lsmul`: scalar multiplication as a bilinear map `R × M → M` ## Tags bilinear -/ namespace linear_map section semiring variables {R : Type*} [semiring R] {S : Type*} [semiring S] variables {M : Type*} {N : Type*} {P : Type*} variables {M' : Type*} {N' : Type*} {P' : Type*} variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] variables [add_comm_group M'] [add_comm_group N'] [add_comm_group P'] variables [module R M] [module S N] [module R P] [module S P] variables [module R M'] [module S N'] [module R P'] [module S P'] variables [smul_comm_class S R P] [smul_comm_class S R P'] include R variables (R S) /-- Create a bilinear map from a function that is linear in each component. See `mk₂` for the special case where both arguments come from modules over the same ring. -/ def mk₂' (f : M → N → P) (H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n) (H2 : ∀ (c:R) m n, f (c • m) n = c • f m n) (H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂) (H4 : ∀ (c:S) m n, f m (c • n) = c • f m n) : M →ₗ[R] N →ₗ[S] P := { to_fun := λ m, { to_fun := f m, map_add' := H3 m, map_smul' := λ c, H4 c m}, map_add' := λ m₁ m₂, linear_map.ext $ H1 m₁ m₂, map_smul' := λ c m, linear_map.ext $ H2 c m } variables {R S} @[simp] theorem mk₂'_apply (f : M → N → P) {H1 H2 H3 H4} (m : M) (n : N) : (mk₂' R S f H1 H2 H3 H4 : M →ₗ[R] N →ₗ[S] P) m n = f m n := rfl theorem ext₂ {f g : M →ₗ[R] N →ₗ[S] P} (H : ∀ m n, f m n = g m n) : f = g := linear_map.ext (λ m, linear_map.ext $ λ n, H m n) section local attribute [instance] smul_comm_class.symm /-- Given a linear map from `M` to linear maps from `N` to `P`, i.e., a bilinear map from `M × N` to `P`, change the order of variables and get a linear map from `N` to linear maps from `M` to `P`. -/ def flip (f : M →ₗ[R] N →ₗ[S] P) : N →ₗ[S] M →ₗ[R] P := mk₂' S R (λ n m, f m n) (λ n₁ n₂ m, (f m).map_add _ _) (λ c n m, (f m).map_smul _ _) (λ n m₁ m₂, by rw f.map_add; refl) (λ c n m, by rw f.map_smul; refl) end @[simp] theorem flip_apply (f : M →ₗ[R] N →ₗ[S] P) (m : M) (n : N) : flip f n m = f m n := rfl open_locale big_operators variables {R} theorem flip_inj {f g : M →ₗ[R] N →ₗ[S] P} (H : flip f = flip g) : f = g := ext₂ $ λ m n, show flip f n m = flip g n m, by rw H theorem map_zero₂ (f : M →ₗ[R] N →ₗ[S] P) (y) : f 0 y = 0 := (flip f y).map_zero theorem map_neg₂ (f : M' →ₗ[R] N →ₗ[S] P') (x y) : f (-x) y = -f x y := (flip f y).map_neg _ theorem map_sub₂ (f : M' →ₗ[R] N →ₗ[S] P') (x y z) : f (x - y) z = f x z - f y z := (flip f z).map_sub _ _ theorem map_add₂ (f : M →ₗ[R] N →ₗ[S] P) (x₁ x₂ y) : f (x₁ + x₂) y = f x₁ y + f x₂ y := (flip f y).map_add _ _ theorem map_smul₂ (f : M →ₗ[R] N →ₗ[S] P) (r : R) (x y) : f (r • x) y = r • f x y := (flip f y).map_smul _ _ theorem map_sum₂ {ι : Type*} (f : M →ₗ[R] N →ₗ[S] P) (t : finset ι) (x : ι → M) (y) : f (∑ i in t, x i) y = ∑ i in t, f (x i) y := (flip f y).map_sum end semiring section comm_semiring variables {R : Type*} [comm_semiring R] variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] variables [module R M] [module R N] [module R P] [module R Q] variables (R) /-- Create a bilinear map from a function that is linear in each component. This is a shorthand for `mk₂'` for the common case when `R = S`. -/ def mk₂ (f : M → N → P) (H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n) (H2 : ∀ (c:R) m n, f (c • m) n = c • f m n) (H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂) (H4 : ∀ (c:R) m n, f m (c • n) = c • f m n) : M →ₗ[R] N →ₗ[R] P := mk₂' R R f H1 H2 H3 H4 @[simp] theorem mk₂_apply (f : M → N → P) {H1 H2 H3 H4} (m : M) (n : N) : (mk₂ R f H1 H2 H3 H4 : M →ₗ[R] N →ₗ[R] P) m n = f m n := rfl variables (R M N P) /-- Given a linear map from `M` to linear maps from `N` to `P`, i.e., a bilinear map `M → N → P`, change the order of variables and get a linear map from `N` to linear maps from `M` to `P`. -/ def lflip : (M →ₗ[R] N →ₗ[R] P) →ₗ[R] N →ₗ[R] M →ₗ[R] P := { to_fun := flip, map_add' := λ _ _, rfl, map_smul' := λ _ _, rfl } variables {R M N P} variables (f : M →ₗ[R] N →ₗ[R] P) @[simp] theorem lflip_apply (m : M) (n : N) : lflip R M N P f n m = f m n := rfl variables (R P) /-- Composing a linear map `M → N` and a linear map `N → P` to form a linear map `M → P`. -/ def lcomp (f : M →ₗ[R] N) : (N →ₗ[R] P) →ₗ[R] M →ₗ[R] P := flip $ linear_map.comp (flip id) f variables {R P} @[simp] theorem lcomp_apply (f : M →ₗ[R] N) (g : N →ₗ[R] P) (x : M) : lcomp R P f g x = g (f x) := rfl variables (R M N P) /-- Composing a linear map `M → N` and a linear map `N → P` to form a linear map `M → P`. -/ def llcomp : (N →ₗ[R] P) →ₗ[R] (M →ₗ[R] N) →ₗ[R] M →ₗ[R] P := flip { to_fun := lcomp R P, map_add' := λ f f', ext₂ $ λ g x, g.map_add _ _, map_smul' := λ (c : R) f, ext₂ $ λ g x, g.map_smul _ _ } variables {R M N P} section @[simp] theorem llcomp_apply (f : N →ₗ[R] P) (g : M →ₗ[R] N) (x : M) : llcomp R M N P f g x = f (g x) := rfl end /-- Composing a linear map `Q → N` and a bilinear map `M → N → P` to form a bilinear map `M → Q → P`. -/ def compl₂ (g : Q →ₗ[R] N) : M →ₗ[R] Q →ₗ[R] P := (lcomp R _ g).comp f @[simp] theorem compl₂_apply (g : Q →ₗ[R] N) (m : M) (q : Q) : f.compl₂ g m q = f m (g q) := rfl /-- Composing a linear map `P → Q` and a bilinear map `M → N → P` to form a bilinear map `M → N → Q`. -/ def compr₂ (g : P →ₗ[R] Q) : M →ₗ[R] N →ₗ[R] Q := linear_map.comp (llcomp R N P Q g) f @[simp] theorem compr₂_apply (g : P →ₗ[R] Q) (m : M) (n : N) : f.compr₂ g m n = g (f m n) := rfl variables (R M) /-- Scalar multiplication as a bilinear map `R → M → M`. -/ def lsmul : R →ₗ[R] M →ₗ[R] M := mk₂ R (•) add_smul (λ _ _ _, mul_smul _ _ _) smul_add (λ r s m, by simp only [smul_smul, smul_eq_mul, mul_comm]) variables {R M} @[simp] theorem lsmul_apply (r : R) (m : M) : lsmul R M r m = r • m := rfl end comm_semiring section comm_ring variables {R M : Type*} [comm_ring R] [add_comm_group M] [module R M] lemma lsmul_injective [no_zero_smul_divisors R M] {x : R} (hx : x ≠ 0) : function.injective (lsmul R M x) := smul_right_injective _ hx lemma ker_lsmul [no_zero_smul_divisors R M] {a : R} (ha : a ≠ 0) : (linear_map.lsmul R M a).ker = ⊥ := linear_map.ker_eq_bot_of_injective (linear_map.lsmul_injective ha) end comm_ring end linear_map
3240b2c38bc10cda45c4f3196965e2d9ece2f5bd
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/compiler/initUnboxed.lean
bfa03340587d782af1e8bf420ede3aff73c9a175
[ "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
309
lean
initialize test : UInt64 ← pure 0 initialize testb : Bool ← pure false initialize testu : USize ← pure 1 initialize testf : Float ← pure 0.5 initialize test32 : UInt32 ← pure 16 def main : IO Unit := do IO.println test IO.println testb IO.println testu IO.println testf IO.println test32
b52efb3501db4559916c7106f0d6e42faf04f336
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/continued_fractions/computation/correctness_terminating.lean
7f976b1e1d255100fc517c1cf11400df29be1065
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
12,418
lean
/- Copyright (c) 2020 Kevin Kappelmann. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Kappelmann -/ import algebra.continued_fractions.computation.translations import algebra.continued_fractions.terminated_stable import algebra.continued_fractions.continuants_recurrence import order.filter.at_top_bot import tactic.field_simp /-! # Correctness of Terminating Continued Fraction Computations (`generalized_continued_fraction.of`) ## Summary We show the correctness of the algorithm computing continued fractions (`generalized_continued_fraction.of`) in case of termination in the following sense: At every step `n : ℕ`, we can obtain the value `v` by adding a specific residual term to the last denominator of the fraction described by `(generalized_continued_fraction.of v).convergents' n`. The residual term will be zero exactly when the continued fraction terminated; otherwise, the residual term will be given by the fractional part stored in `generalized_continued_fraction.int_fract_pair.stream v n`. For an example, refer to `generalized_continued_fraction.comp_exact_value_correctness_of_stream_eq_some` and for more information about the computation process, refer to `algebra.continued_fraction.computation.basic`. ## Main definitions - `generalized_continued_fraction.comp_exact_value` can be used to compute the exact value approximated by the continued fraction `generalized_continued_fraction.of v` by adding a residual term as described in the summary. ## Main Theorems - `generalized_continued_fraction.comp_exact_value_correctness_of_stream_eq_some` shows that `generalized_continued_fraction.comp_exact_value` indeed returns the value `v` when given the convergent and fractional part as described in the summary. - `generalized_continued_fraction.of_correctness_of_terminated_at` shows the equality `v = (generalized_continued_fraction.of v).convergents n` if `generalized_continued_fraction.of v` terminated at position `n`. -/ namespace generalized_continued_fraction open generalized_continued_fraction (of) variables {K : Type*} [linear_ordered_field K] {v : K} {n : ℕ} /-- Given two continuants `pconts` and `conts` and a value `fr`, this function returns - `conts.a / conts.b` if `fr = 0` - `exact_conts.a / exact_conts.b` where `exact_conts = next_continuants 1 fr⁻¹ pconts conts` otherwise. This function can be used to compute the exact value approxmated by a continued fraction `generalized_continued_fraction.of v` as described in lemma `comp_exact_value_correctness_of_stream_eq_some`. -/ protected def comp_exact_value (pconts conts : pair K) (fr : K) : K := -- if the fractional part is zero, we exactly approximated the value by the last continuants if fr = 0 then conts.a / conts.b -- otherwise, we have to include the fractional part in a final continuants step. else let exact_conts := next_continuants 1 fr⁻¹ pconts conts in exact_conts.a / exact_conts.b variable [floor_ring K] /-- Just a computational lemma we need for the next main proof. -/ protected lemma comp_exact_value_correctness_of_stream_eq_some_aux_comp {a : K} (b c : K) (fract_a_ne_zero : int.fract a ≠ 0) : ((⌊a⌋ : K) * b + c) / (int.fract a) + b = (b * a + c) / int.fract a := by { field_simp [fract_a_ne_zero], rw int.fract, ring } open generalized_continued_fraction (comp_exact_value comp_exact_value_correctness_of_stream_eq_some_aux_comp) /-- Shows the correctness of `comp_exact_value` in case the continued fraction `generalized_continued_fraction.of v` did not terminate at position `n`. That is, we obtain the value `v` if we pass the two successive (auxiliary) continuants at positions `n` and `n + 1` as well as the fractional part at `int_fract_pair.stream n` to `comp_exact_value`. The correctness might be seen more readily if one uses `convergents'` to evaluate the continued fraction. Here is an example to illustrate the idea: Let `(v : ℚ) := 3.4`. We have - `generalized_continued_fraction.int_fract_pair.stream v 0 = some ⟨3, 0.4⟩`, and - `generalized_continued_fraction.int_fract_pair.stream v 1 = some ⟨2, 0.5⟩`. Now `(generalized_continued_fraction.of v).convergents' 1 = 3 + 1/2`, and our fractional term at position `2` is `0.5`. We hence have `v = 3 + 1/(2 + 0.5) = 3 + 1/2.5 = 3.4`. This computation corresponds exactly to the one using the recurrence equation in `comp_exact_value`. -/ lemma comp_exact_value_correctness_of_stream_eq_some : ∀ {ifp_n : int_fract_pair K}, int_fract_pair.stream v n = some ifp_n → v = comp_exact_value ((of v).continuants_aux n) ((of v).continuants_aux $ n + 1) ifp_n.fr := begin let g := of v, induction n with n IH, { assume ifp_zero stream_zero_eq, -- nat.zero have : int_fract_pair.of v = ifp_zero, by { have : int_fract_pair.stream v 0 = some (int_fract_pair.of v), from rfl, simpa only [this] using stream_zero_eq }, cases this, cases decidable.em (int.fract v = 0) with fract_eq_zero fract_ne_zero, -- int.fract v = 0; we must then have `v = ⌊v⌋` { suffices : v = ⌊v⌋, by simpa [continuants_aux, fract_eq_zero, comp_exact_value], calc v = int.fract v + ⌊v⌋ : by rw int.fract_add_floor ... = ⌊v⌋ : by simp [fract_eq_zero] }, -- int.fract v ≠ 0; the claim then easily follows by unfolding a single computation step { field_simp [continuants_aux, next_continuants, next_numerator, next_denominator, of_h_eq_floor, comp_exact_value, fract_ne_zero] } }, { assume ifp_succ_n succ_nth_stream_eq, -- nat.succ obtain ⟨ifp_n, nth_stream_eq, nth_fract_ne_zero, -⟩ : ∃ ifp_n, int_fract_pair.stream v n = some ifp_n ∧ ifp_n.fr ≠ 0 ∧ int_fract_pair.of ifp_n.fr⁻¹ = ifp_succ_n, from int_fract_pair.succ_nth_stream_eq_some_iff.elim_left succ_nth_stream_eq, -- introduce some notation let conts := g.continuants_aux (n + 2), set pconts := g.continuants_aux (n + 1) with pconts_eq, set ppconts := g.continuants_aux n with ppconts_eq, cases decidable.em (ifp_succ_n.fr = 0) with ifp_succ_n_fr_eq_zero ifp_succ_n_fr_ne_zero, -- ifp_succ_n.fr = 0 { suffices : v = conts.a / conts.b, by simpa [comp_exact_value, ifp_succ_n_fr_eq_zero], -- use the IH and the fact that ifp_n.fr⁻¹ = ⌊ifp_n.fr⁻¹⌋ to prove this case obtain ⟨ifp_n', nth_stream_eq', ifp_n_fract_inv_eq_floor⟩ : ∃ ifp_n, int_fract_pair.stream v n = some ifp_n ∧ ifp_n.fr⁻¹ = ⌊ifp_n.fr⁻¹⌋, from int_fract_pair.exists_succ_nth_stream_of_fr_zero succ_nth_stream_eq ifp_succ_n_fr_eq_zero, have : ifp_n' = ifp_n, by injection (eq.trans (nth_stream_eq').symm nth_stream_eq), cases this, have s_nth_eq : g.s.nth n = some ⟨1, ⌊ifp_n.fr⁻¹⌋⟩, from nth_of_eq_some_of_nth_int_fract_pair_stream_fr_ne_zero nth_stream_eq nth_fract_ne_zero, rw [←ifp_n_fract_inv_eq_floor] at s_nth_eq, suffices : v = comp_exact_value ppconts pconts ifp_n.fr, by simpa [conts, continuants_aux, s_nth_eq, comp_exact_value, nth_fract_ne_zero] using this, exact (IH nth_stream_eq) }, -- ifp_succ_n.fr ≠ 0 { -- use the IH to show that the following equality suffices suffices : comp_exact_value ppconts pconts ifp_n.fr = comp_exact_value pconts conts ifp_succ_n.fr, by { have : v = comp_exact_value ppconts pconts ifp_n.fr, from IH nth_stream_eq, conv_lhs { rw this }, assumption }, -- get the correspondence between ifp_n and ifp_succ_n obtain ⟨ifp_n', nth_stream_eq', ifp_n_fract_ne_zero, ⟨refl⟩⟩ : ∃ ifp_n, int_fract_pair.stream v n = some ifp_n ∧ ifp_n.fr ≠ 0 ∧ int_fract_pair.of ifp_n.fr⁻¹ = ifp_succ_n, from int_fract_pair.succ_nth_stream_eq_some_iff.elim_left succ_nth_stream_eq, have : ifp_n' = ifp_n, by injection (eq.trans (nth_stream_eq').symm nth_stream_eq), cases this, -- get the correspondence between ifp_n and g.s.nth n have s_nth_eq : g.s.nth n = some ⟨1, (⌊ifp_n.fr⁻¹⌋ : K)⟩, from nth_of_eq_some_of_nth_int_fract_pair_stream_fr_ne_zero nth_stream_eq ifp_n_fract_ne_zero, -- the claim now follows by unfolding the definitions and tedious calculations -- some shorthand notation let ppA := ppconts.a, let ppB := ppconts.b, let pA := pconts.a, let pB := pconts.b, have : comp_exact_value ppconts pconts ifp_n.fr = (ppA + ifp_n.fr⁻¹ * pA) / (ppB + ifp_n.fr⁻¹ * pB), by -- unfold comp_exact_value and the convergent computation once { field_simp [ifp_n_fract_ne_zero, comp_exact_value, next_continuants, next_numerator, next_denominator], ac_refl }, rw this, -- two calculations needed to show the claim have tmp_calc := comp_exact_value_correctness_of_stream_eq_some_aux_comp pA ppA ifp_succ_n_fr_ne_zero, have tmp_calc' := comp_exact_value_correctness_of_stream_eq_some_aux_comp pB ppB ifp_succ_n_fr_ne_zero, rw inv_eq_one_div at tmp_calc tmp_calc', have : int.fract (1 / ifp_n.fr) ≠ 0, by simpa using ifp_succ_n_fr_ne_zero, -- now unfold the recurrence one step and simplify both sides to arrive at the conclusion field_simp [conts, comp_exact_value, (continuants_aux_recurrence s_nth_eq ppconts_eq pconts_eq), next_continuants, next_numerator, next_denominator, this, tmp_calc, tmp_calc'], ac_refl } } end open generalized_continued_fraction (of_terminated_at_n_iff_succ_nth_int_fract_pair_stream_eq_none) /-- The convergent of `generalized_continued_fraction.of v` at step `n - 1` is exactly `v` if the `int_fract_pair.stream` of the corresponding continued fraction terminated at step `n`. -/ lemma of_correctness_of_nth_stream_eq_none (nth_stream_eq_none : int_fract_pair.stream v n = none) : v = (of v).convergents (n - 1) := begin induction n with n IH, case nat.zero { contradiction }, -- int_fract_pair.stream v 0 ≠ none case nat.succ { rename nth_stream_eq_none succ_nth_stream_eq_none, let g := of v, change v = g.convergents n, have : int_fract_pair.stream v n = none ∨ ∃ ifp, int_fract_pair.stream v n = some ifp ∧ ifp.fr = 0, from int_fract_pair.succ_nth_stream_eq_none_iff.elim_left succ_nth_stream_eq_none, rcases this with ⟨nth_stream_eq_none⟩ | ⟨ifp_n, nth_stream_eq, nth_stream_fr_eq_zero⟩, { cases n with n', { contradiction }, -- int_fract_pair.stream v 0 ≠ none { have : g.terminated_at n', from of_terminated_at_n_iff_succ_nth_int_fract_pair_stream_eq_none.elim_right nth_stream_eq_none, have : g.convergents (n' + 1) = g.convergents n', from convergents_stable_of_terminated n'.le_succ this, rw this, exact (IH nth_stream_eq_none) } }, { simpa [nth_stream_fr_eq_zero, comp_exact_value] using (comp_exact_value_correctness_of_stream_eq_some nth_stream_eq) } } end /-- If `generalized_continued_fraction.of v` terminated at step `n`, then the `n`th convergent is exactly `v`. -/ theorem of_correctness_of_terminated_at (terminated_at_n : (of v).terminated_at n) : v = (of v).convergents n := have int_fract_pair.stream v (n + 1) = none, from of_terminated_at_n_iff_succ_nth_int_fract_pair_stream_eq_none.elim_left terminated_at_n, of_correctness_of_nth_stream_eq_none this /-- If `generalized_continued_fraction.of v` terminates, then there is `n : ℕ` such that the `n`th convergent is exactly `v`. -/ lemma of_correctness_of_terminates (terminates : (of v).terminates) : ∃ (n : ℕ), v = (of v).convergents n := exists.elim terminates ( assume n terminated_at_n, exists.intro n (of_correctness_of_terminated_at terminated_at_n) ) open filter /-- If `generalized_continued_fraction.of v` terminates, then its convergents will eventually always be `v`. -/ lemma of_correctness_at_top_of_terminates (terminates : (of v).terminates) : ∀ᶠ n in at_top, v = (of v).convergents n := begin rw eventually_at_top, obtain ⟨n, terminated_at_n⟩ : ∃ n, (of v).terminated_at n, from terminates, use n, assume m m_geq_n, rw (convergents_stable_of_terminated m_geq_n terminated_at_n), exact of_correctness_of_terminated_at terminated_at_n end end generalized_continued_fraction
fbe71c445748de0586ea61ecb13500fb4686ffc8
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/data/set/function.lean
11f446e6fd841e210bae628bdf3a6c6c2fc920c9
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
18,225
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad, Andrew Zipperer, Haitao Zhang, Minchao Wu, Yury Kudryashov -/ import data.set.basic logic.function /-! # Functions over sets ## Main definitions ### Predicate * `eq_on f₁ f₂ s` : functions `f₁` and `f₂` are equal at every point of `s`; * `maps_to f s t` : `f` sends every point of `s` to a point of `t`; * `inj_on f s` : restriction of `f` to `s` is injective; * `surj_on f s t` : every point in `s` has a preimage in `s`; * `bij_on f s t` : `f` is a bijection between `s` and `t`; * `left_inv_on f' f s` : for every `x ∈ s` we have `f' (f x) = x`; * `right_inv_on f' f t` : for every `y ∈ t` we have `f (f' y) = y`; * `inv_on f' f s t` : `f'` is a two-side inverse of `f` on `s` and `t`, i.e. we have `left_inv_on f' f s` and `right_inv_on f' f t`. ### Functions * `restrict f s` : restrict the domain of `f` to the set `s`; * `cod_restrict f s h` : given `h : ∀ x, f x ∈ s`, restrict the codomain of `f` to the set `s`; * `maps_to.restrict f s t h`: given `h : maps_to f s t`, restrict the domain of `f` to `s` and the codomain to `t`. -/ universes u v w x y variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} open function namespace set /-! ### Restrict -/ /-- Restrict domain of a function `f` to a set `s`. Same as `subtype.restrict` but this version takes an argument `↥s` instead of `subtype s`. -/ def restrict (f : α → β) (s : set α) : s → β := λ x, f x lemma restrict_eq (f : α → β) (s : set α) : s.restrict f = f ∘ coe := rfl @[simp] lemma restrict_apply (f : α → β) (s : set α) (x : s) : restrict f s x = f x := rfl @[simp] lemma range_restrict (f : α → β) (s : set α) : set.range (restrict f s) = f '' s := range_comp.trans $ congr_arg (('') f) s.range_coe_subtype /-- Restrict codomain of a function `f` to a set `s`. Same as `subtype.coind` but this version has codomain `↥s` instead of `subtype s`. -/ def cod_restrict (f : α → β) (s : set β) (h : ∀ x, f x ∈ s) : α → s := λ x, ⟨f x, h x⟩ @[simp] lemma coe_cod_restrict_apply (f : α → β) (s : set β) (h : ∀ x, f x ∈ s) (x : α) : (cod_restrict f s h x : β) = f x := rfl variables {s s₁ s₂ : set α} {t t₁ t₂ : set β} {p : set γ} {f f₁ f₂ f₃ : α → β} {g : β → γ} {f' f₁' f₂' : β → α} {g' : γ → β} /-! ### Equality on a set -/ /-- Two functions `f₁ f₂ : α → β` are equal on `s` if `f₁ x = f₂ x` for all `x ∈ a`. -/ @[reducible] def eq_on (f₁ f₂ : α → β) (s : set α) : Prop := ∀ ⦃x⦄, x ∈ s → f₁ x = f₂ x @[symm] lemma eq_on.symm (h : eq_on f₁ f₂ s) : eq_on f₂ f₁ s := λ x hx, (h hx).symm lemma eq_on_comm : eq_on f₁ f₂ s ↔ eq_on f₂ f₁ s := ⟨eq_on.symm, eq_on.symm⟩ @[refl] lemma eq_on_refl (f : α → β) (s : set α) : eq_on f f s := λ _ _, rfl @[trans] lemma eq_on.trans (h₁ : eq_on f₁ f₂ s) (h₂ : eq_on f₂ f₃ s) : eq_on f₁ f₃ s := λ x hx, (h₁ hx).trans (h₂ hx) theorem eq_on.image_eq (heq : eq_on f₁ f₂ s) : f₁ '' s = f₂ '' s := image_congr heq lemma eq_on.mono (hs : s₁ ⊆ s₂) (hf : eq_on f₁ f₂ s₂) : eq_on f₁ f₂ s₁ := λ x hx, hf (hs hx) /-! ### maps to -/ /-- `maps_to f a b` means that the image of `a` is contained in `b`. -/ @[reducible] def maps_to (f : α → β) (s : set α) (t : set β) : Prop := s ⊆ f ⁻¹' t /-- Given a map `f` sending `s : set α` into `t : set β`, restrict domain of `f` to `s` and the codomain to `t`. Same as `subtype.map`. -/ def maps_to.restrict (f : α → β) (s : set α) (t : set β) (h : maps_to f s t) : s → t := subtype.map f h @[simp] lemma maps_to.coe_restrict_apply (h : maps_to f s t) (x : s) : (h.restrict f s t x : β) = f x := rfl theorem maps_to' : maps_to f s t ↔ f '' s ⊆ t := image_subset_iff.symm theorem maps_to_empty (f : α → β) (t : set β) : maps_to f ∅ t := empty_subset _ theorem maps_to.image_subset (h : maps_to f s t) : f '' s ⊆ t := maps_to'.1 h theorem maps_to.congr (h₁ : maps_to f₁ s t) (h : eq_on f₁ f₂ s) : maps_to f₂ s t := λ x hx, by rw [mem_preimage, ← h hx]; exact h₁ hx theorem eq_on.maps_to_iff (H : eq_on f₁ f₂ s) : maps_to f₁ s t ↔ maps_to f₂ s t := ⟨λ h, h.congr H, λ h, h.congr H.symm⟩ theorem maps_to.comp (h₁ : maps_to g t p) (h₂ : maps_to f s t) : maps_to (g ∘ f) s p := λ x h, h₁ (h₂ h) theorem maps_to.iterate {f : α → α} {s : set α} (h : maps_to f s s) : ∀ n, maps_to (f^[n]) s s | 0 := λ _, id | (n+1) := (maps_to.iterate n).comp h theorem maps_to.iterate_restrict {f : α → α} {s : set α} (h : maps_to f s s) (n : ℕ) : (h.restrict f s s^[n]) = (h.iterate n).restrict _ _ _ := begin funext x, rw [subtype.coe_ext, maps_to.coe_restrict_apply], induction n with n ihn generalizing x, { refl }, { simp [nat.iterate, ihn] } end theorem maps_to.mono (hs : s₂ ⊆ s₁) (ht : t₁ ⊆ t₂) (hf : maps_to f s₁ t₁) : maps_to f s₂ t₂ := λ x hx, ht (hf $ hs hx) theorem maps_to_univ (f : α → β) (s : set α) : maps_to f s univ := λ x h, trivial theorem maps_to_image (f : α → β) (s : set α) : maps_to f s (f '' s) := by rw maps_to' theorem maps_to_preimage (f : α → β) (t : set β) : maps_to f (f ⁻¹' t) t := subset.refl _ theorem maps_to_range (f : set α) (s : set α) : maps_to f s (range f) := (maps_to_image f s).mono (subset.refl s) (image_subset_range _ _) /-! ### Injectivity on a set -/ /-- `f` is injective on `a` if the restriction of `f` to `a` is injective. -/ @[reducible] def inj_on (f : α → β) (s : set α) : Prop := ∀⦃x₁ x₂ : α⦄, x₁ ∈ s → x₂ ∈ s → f x₁ = f x₂ → x₁ = x₂ theorem inj_on_empty (f : α → β) : inj_on f ∅ := λ _ _ h₁ _ _, false.elim h₁ theorem inj_on.congr (h₁ : inj_on f₁ s) (h : eq_on f₁ f₂ s) : inj_on f₂ s := λ x y hx hy, h hx ▸ h hy ▸ h₁ hx hy theorem eq_on.inj_on_iff (H : eq_on f₁ f₂ s) : inj_on f₁ s ↔ inj_on f₂ s := ⟨λ h, h.congr H, λ h, h.congr H.symm⟩ theorem inj_on.mono (h : s₁ ⊆ s₂) (ht : inj_on f s₂) : inj_on f s₁ := λ x y hx hy H, ht (h hx) (h hy) H lemma injective_iff_inj_on_univ : injective f ↔ inj_on f univ := ⟨λ h x y hx hy hxy, h hxy, λ h _ _ heq, h trivial trivial heq⟩ theorem inj_on.comp (hg : inj_on g t) (hf: inj_on f s) (h : maps_to f s t) : inj_on (g ∘ f) s := λ x y hx hy heq, hf hx hy $ hg (h hx) (h hy) heq lemma inj_on_iff_injective : inj_on f s ↔ injective (restrict f s) := ⟨λ H a b h, subtype.eq $ H a.2 b.2 h, λ H a b as bs h, congr_arg subtype.val $ @H ⟨a, as⟩ ⟨b, bs⟩ h⟩ lemma inj_on.inv_fun_on_image [nonempty α] (h : inj_on f s₂) (ht : s₁ ⊆ s₂) : (inv_fun_on f s₂) '' (f '' s₁) = s₁ := begin have : eq_on ((inv_fun_on f s₂) ∘ f) id s₁, from λz hz, inv_fun_on_eq' h (ht hz), rw [← image_comp, this.image_eq, image_id] end lemma inj_on_preimage {B : set (set β)} (hB : B ⊆ powerset (range f)) : inj_on (preimage f) B := begin intros s t hs ht hst, rw [←image_preimage_eq_of_subset (hB hs), ←image_preimage_eq_of_subset (hB ht), hst] end /-! ### Surjectivity on a set -/ /-- `f` is surjective from `a` to `b` if `b` is contained in the image of `a`. -/ @[reducible] def surj_on (f : α → β) (s : set α) (t : set β) : Prop := t ⊆ f '' s theorem surj_on_empty (f : α → β) (s : set α) : surj_on f s ∅ := empty_subset _ theorem surj_on.comap_nonempty (h : surj_on f s t) (ht : t.nonempty) : s.nonempty := (ht.mono h).of_image theorem surj_on.congr (h : surj_on f₁ s t) (H : eq_on f₁ f₂ s) : surj_on f₂ s t := by rwa [surj_on, ← H.image_eq] theorem eq_on.surj_on_iff (h : eq_on f₁ f₂ s) : surj_on f₁ s t ↔ surj_on f₂ s t := ⟨λ H, H.congr h, λ H, H.congr h.symm⟩ theorem surj_on.mono (hs : s₁ ⊆ s₂) (ht : t₁ ⊆ t₂) (hf : surj_on f s₁ t₂) : surj_on f s₂ t₁ := subset.trans ht $ subset.trans hf $ image_subset _ hs theorem surj_on.comp (hg : surj_on g t p) (hf : surj_on f s t) : surj_on (g ∘ f) s p := subset.trans hg $ subset.trans (image_subset g hf) $ (image_comp g f s) ▸ subset.refl _ lemma surjective_iff_surj_on_univ : surjective f ↔ surj_on f univ univ := by simp [surjective, surj_on, subset_def] lemma surj_on_iff_surjective : surj_on f s univ ↔ surjective (restrict f s) := ⟨λ H b, let ⟨a, as, e⟩ := @H b trivial in ⟨⟨a, as⟩, e⟩, λ H b _, let ⟨⟨a, as⟩, e⟩ := H b in ⟨a, as, e⟩⟩ lemma surj_on.image_eq_of_maps_to (h₁ : surj_on f s t) (h₂ : maps_to f s t) : f '' s = t := eq_of_subset_of_subset h₂.image_subset h₁ /-! ### Bijectivity -/ /-- `f` is bijective from `s` to `t` if `f` is injective on `s` and `f '' s = t`. -/ @[reducible] def bij_on (f : α → β) (s : set α) (t : set β) : Prop := maps_to f s t ∧ inj_on f s ∧ surj_on f s t lemma bij_on.maps_to (h : bij_on f s t) : maps_to f s t := h.left lemma bij_on.inj_on (h : bij_on f s t) : inj_on f s := h.right.left lemma bij_on.surj_on (h : bij_on f s t) : surj_on f s t := h.right.right lemma bij_on.mk (h₁ : maps_to f s t) (h₂ : inj_on f s) (h₃ : surj_on f s t) : bij_on f s t := ⟨h₁, h₂, h₃⟩ lemma bij_on_empty (f : α → β) : bij_on f ∅ ∅ := ⟨maps_to_empty f ∅, inj_on_empty f, surj_on_empty f ∅⟩ lemma inj_on.bij_on_image (h : inj_on f s) : bij_on f s (f '' s) := bij_on.mk (maps_to_image f s) h (subset.refl _) theorem bij_on.congr (h₁ : bij_on f₁ s t) (h : eq_on f₁ f₂ s) : bij_on f₂ s t := bij_on.mk (h₁.maps_to.congr h) (h₁.inj_on.congr h) (h₁.surj_on.congr h) theorem eq_on.bij_on_iff (H : eq_on f₁ f₂ s) : bij_on f₁ s t ↔ bij_on f₂ s t := ⟨λ h, h.congr H, λ h, h.congr H.symm⟩ lemma bij_on.image_eq (h : bij_on f s t) : f '' s = t := h.surj_on.image_eq_of_maps_to h.maps_to theorem bij_on.comp (hg : bij_on g t p) (hf : bij_on f s t) : bij_on (g ∘ f) s p := bij_on.mk (hg.maps_to.comp hf.maps_to) (hg.inj_on.comp hf.inj_on hf.maps_to) (hg.surj_on.comp hf.surj_on) lemma bijective_iff_bij_on_univ : bijective f ↔ bij_on f univ univ := iff.intro (λ h, let ⟨inj, surj⟩ := h in ⟨maps_to_univ f _, iff.mp injective_iff_inj_on_univ inj, iff.mp surjective_iff_surj_on_univ surj⟩) (λ h, let ⟨map, inj, surj⟩ := h in ⟨iff.mpr injective_iff_inj_on_univ inj, iff.mpr surjective_iff_surj_on_univ surj⟩) /-! ### left inverse -/ /-- `g` is a left inverse to `f` on `a` means that `g (f x) = x` for all `x ∈ a`. -/ @[reducible] def left_inv_on (f' : β → α) (f : α → β) (s : set α) : Prop := ∀ ⦃x⦄, x ∈ s → f' (f x) = x lemma left_inv_on.eq_on (h : left_inv_on f' f s) : eq_on (f' ∘ f) id s := h lemma left_inv_on.eq (h : left_inv_on f' f s) {x} (hx : x ∈ s) : f' (f x) = x := h hx lemma left_inv_on.congr_left (h₁ : left_inv_on f₁' f s) {t : set β} (h₁' : maps_to f s t) (heq : eq_on f₁' f₂' t) : left_inv_on f₂' f s := λ x hx, heq (h₁' hx) ▸ h₁ hx theorem left_inv_on.congr_right (h₁ : left_inv_on f₁' f₁ s) (heq : eq_on f₁ f₂ s) : left_inv_on f₁' f₂ s := λ x hx, heq hx ▸ h₁ hx theorem left_inv_on.inj_on (h : left_inv_on f₁' f s) : inj_on f s := λ x₁ x₂ h₁ h₂ heq, calc x₁ = f₁' (f x₁) : eq.symm $ h h₁ ... = f₁' (f x₂) : congr_arg f₁' heq ... = x₂ : h h₂ theorem left_inv_on.surj_on (h : left_inv_on f₁' f s) (hf : maps_to f s t) : surj_on f₁' t s := λ x hx, ⟨f x, hf hx, h hx⟩ theorem left_inv_on.comp (hf' : left_inv_on f' f s) (hg' : left_inv_on g' g t) (hf : maps_to f s t) : left_inv_on (f' ∘ g') (g ∘ f) s := λ x h, calc (f' ∘ g') ((g ∘ f) x) = f' (f x) : congr_arg f' (hg' (hf h)) ... = x : hf' h /-! ### Right inverse -/ /-- `g` is a right inverse to `f` on `b` if `f (g x) = x` for all `x ∈ b`. -/ @[reducible] def right_inv_on (f' : β → α) (f : α → β) (t : set β) : Prop := left_inv_on f f' t lemma right_inv_on.eq_on (h : right_inv_on f' f t) : eq_on (f ∘ f') id t := h lemma right_inv_on.eq (h : right_inv_on f' f t) {y} (hy : y ∈ t) : f (f' y) = y := h hy theorem right_inv_on.congr_left (h₁ : right_inv_on f₁' f t) (heq : eq_on f₁' f₂' t) : right_inv_on f₂' f t := h₁.congr_right heq theorem right_inv_on.congr_right (h₁ : right_inv_on f' f₁ t) (hg : maps_to f' t s) (heq : eq_on f₁ f₂ s) : right_inv_on f' f₂ t := left_inv_on.congr_left h₁ hg heq theorem right_inv_on.surj_on (hf : right_inv_on f' f t) (hf' : maps_to f' t s) : surj_on f s t := hf.surj_on hf' theorem right_inv_on.comp (hf : right_inv_on f' f t) (hg : right_inv_on g' g p) (g'pt : maps_to g' p t) : right_inv_on (f' ∘ g') (g ∘ f) p := hg.comp hf g'pt theorem inj_on.right_inv_on_of_left_inv_on (hf : inj_on f s) (hf' : left_inv_on f f' t) (h₁ : maps_to f s t) (h₂ : maps_to f' t s) : right_inv_on f f' s := λ x h, hf (h₂ $ h₁ h) h (hf' (h₁ h)) theorem eq_on_of_left_inv_of_right_inv (h₁ : left_inv_on f₁' f s) (h₂ : right_inv_on f₂' f t) (h : maps_to f₂' t s) : eq_on f₁' f₂' t := λ y hy, calc f₁' y = (f₁' ∘ f ∘ f₂') y : congr_arg f₁' (h₂ hy).symm ... = f₂' y : h₁ (h hy) theorem surj_on.left_inv_on_of_right_inv_on (hf : surj_on f s t) (hf' : right_inv_on f f' s) : left_inv_on f f' t := λ y hy, let ⟨x, hx, heq⟩ := hf hy in by rw [← heq, hf' hx] /-! ### Two-side inverses -/ /-- `g` is an inverse to `f` viewed as a map from `a` to `b` -/ @[reducible] def inv_on (g : β → α) (f : α → β) (s : set α) (t : set β) : Prop := left_inv_on g f s ∧ right_inv_on g f t lemma inv_on.symm (h : inv_on f' f s t) : inv_on f f' t s := ⟨h.right, h.left⟩ theorem inv_on.bij_on (h : inv_on f' f s t) (hf : maps_to f s t) (hf' : maps_to f' t s) : bij_on f s t := ⟨hf, h.left.inj_on, h.right.surj_on hf'⟩ /-! ### `inv_fun_on` is a left/right inverse -/ theorem inj_on.left_inv_on_inv_fun_on [nonempty α] (h : inj_on f s) : left_inv_on (inv_fun_on f s) f s := λ x hx, inv_fun_on_eq' h hx theorem surj_on.right_inv_on_inv_fun_on [nonempty α] (h : surj_on f s t) : right_inv_on (inv_fun_on f s) f t := λ y hy, inv_fun_on_eq $ mem_image_iff_bex.1 $ h hy theorem bij_on.inv_on_inv_fun_on [nonempty α] (h : bij_on f s t) : inv_on (inv_fun_on f s) f s t := ⟨h.inj_on.left_inv_on_inv_fun_on, h.surj_on.right_inv_on_inv_fun_on⟩ theorem surj_on.inv_on_inv_fun_on [nonempty α] (h : surj_on f s t) : inv_on (inv_fun_on f s) f (inv_fun_on f s '' t) t := begin refine ⟨_, h.right_inv_on_inv_fun_on⟩, rintros _ ⟨y, hy, rfl⟩, rw [h.right_inv_on_inv_fun_on hy] end theorem surj_on.maps_to_inv_fun_on [nonempty α] (h : surj_on f s t) : maps_to (inv_fun_on f s) t s := λ y hy, mem_preimage.2 $ inv_fun_on_mem $ mem_image_iff_bex.1 $ h hy theorem surj_on.bij_on_subset [nonempty α] (h : surj_on f s t) : bij_on f (inv_fun_on f s '' t) t := begin refine h.inv_on_inv_fun_on.bij_on _ (maps_to_image _ _), rintros _ ⟨y, hy, rfl⟩, rwa [mem_preimage, h.right_inv_on_inv_fun_on hy] end theorem surj_on_iff_exists_bij_on_subset : surj_on f s t ↔ ∃ s' ⊆ s, bij_on f s' t := begin split, { rcases eq_empty_or_nonempty t with rfl|ht, { exact λ _, ⟨∅, empty_subset _, bij_on_empty f⟩ }, { assume h, haveI : nonempty α := ⟨classical.some (h.comap_nonempty ht)⟩, exact ⟨_, h.maps_to_inv_fun_on.image_subset, h.bij_on_subset⟩ }}, { rintros ⟨s', hs', hfs'⟩, exact hfs'.surj_on.mono hs' (subset.refl _) } end end set /-! ### Piecewise defined function -/ namespace set variables {δ : α → Sort y} (s : set α) (f g : Πi, δ i) @[simp] lemma piecewise_empty [∀i : α, decidable (i ∈ (∅ : set α))] : piecewise ∅ f g = g := by { ext i, simp [piecewise] } @[simp] lemma piecewise_univ [∀i : α, decidable (i ∈ (set.univ : set α))] : piecewise set.univ f g = f := by { ext i, simp [piecewise] } @[simp] lemma piecewise_insert_self {j : α} [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g j = f j := by simp [piecewise] variable [∀j, decidable (j ∈ s)] lemma piecewise_insert [decidable_eq α] (j : α) [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g = function.update (s.piecewise f g) j (f j) := begin simp [piecewise], ext i, by_cases h : i = j, { rw h, simp }, { by_cases h' : i ∈ s; simp [h, h'] } end @[simp, priority 990] lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i := by simp [piecewise, hi] @[simp, priority 990] lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i := by simp [piecewise, hi] @[simp, priority 990] lemma piecewise_insert_of_ne {i j : α} (h : i ≠ j) [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g i = s.piecewise f g i := by simp [piecewise, h] end set namespace function open set variables {f : α → β} {g : β → γ} {s : set α} lemma injective.inj_on (h : injective f) (s : set α) : s.inj_on f := λ _ _ _ _ heq, h heq lemma injective.comp_inj_on (hg : injective g) (hf : s.inj_on f) : s.inj_on (g ∘ f) := (hg.inj_on univ).comp hf (maps_to_univ _ _) lemma surjective.surj_on (hf : surjective f) (s : set β) : surj_on f univ s := (surjective_iff_surj_on_univ.1 hf).mono (subset.refl _) (subset_univ _) lemma update_comp_eq_of_not_mem_range [decidable_eq β] (g : β → γ) {f : α → β} {i : β} (a : γ) (h : i ∉ set.range f) : (function.update g i a) ∘ f = g ∘ f := begin ext p, have : f p ≠ i, { by_contradiction H, push_neg at H, rw ← H at h, exact h (set.mem_range_self _) }, simp [this], end lemma update_comp_eq_of_injective [decidable_eq α] [decidable_eq β] (g : β → γ) {f : α → β} (hf : function.injective f) (i : α) (a : γ) : (function.update g (f i) a) ∘ f = function.update (g ∘ f) i a := begin ext j, by_cases h : j = i, { rw h, simp }, { have : f j ≠ f i := hf.ne h, simp [h, this] } end end function
9d87d6fa88d4c94a26732dd17baaad8ef8c78eee
fe84e287c662151bb313504482b218a503b972f3
/src/undergraduate/MAS114/closest_integer.lean
f506b78c19535164aa91ddd66e2792fb6d6811e0
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
3,893
lean
import data.rat import data.real.basic import tactic.ring lemma abs_neg_of_pos {α : Type*} [linear_ordered_add_comm_group α] (a : α) : a > 0 → abs (- a) = a := λ a_pos, (abs_of_neg (neg_neg_of_pos a_pos)).trans (neg_neg a) def half_Q : ℚ := 1 / 2 def neg_half_Q : ℚ := - half_Q lemma dist_neg_Q (n : ℤ) (h : n ≥ 0) : abs (neg_half_Q - ((- (1 + n)) : ℤ)) = (n : ℚ) + half_Q := begin let n_Q : ℚ := n, have e0 : neg_half_Q + 1 = half_Q := by { dsimp[neg_half_Q,half_Q], norm_num }, have e1 := calc neg_half_Q - ((- (1 + n)) : ℤ) = n + (neg_half_Q + 1) : by { rw[int.cast_neg, int.cast_add, int.cast_one, sub_neg_eq_add], ring, } ... = n_Q + half_Q : by rw[e0], have e2 : n_Q + half_Q > 0 := add_pos_of_nonneg_of_pos (int.cast_nonneg.mpr h) one_half_pos, rw[e1,abs_of_pos e2], end lemma dist_nonneg_Q (n : ℤ) (h : n ≥ 0) : abs (neg_half_Q - n) = (n : ℚ) + half_Q := begin let n_Q : ℚ := n, have e1 : neg_half_Q - n = - (n_Q + half_Q) := by {dsimp[neg_half_Q,half_Q], ring_nf }, have e2 : n_Q + half_Q > 0 := add_pos_of_nonneg_of_pos (int.cast_nonneg.mpr h) one_half_pos, have e3 : abs (- (n_Q + half_Q)) = n_Q + half_Q := @abs_neg_of_pos ℚ _ (n_Q + half_Q) e2, rw[e1,e3], end noncomputable def half_R : ℝ := half_Q noncomputable def neg_half_R : ℝ := neg_half_Q lemma dist_neg (n : ℤ) (h : n ≥ 0) : abs (neg_half_R - (-(1 + n) : ℤ)) = (n : ℝ) + half_R := begin let x_Q : ℚ := neg_half_Q - (-(1 + n) : ℤ), let x_R : ℝ := neg_half_R - (-(1 + n) : ℤ), let d_Q : ℚ := abs x_Q, let d_R : ℝ := abs x_R, have e0 : x_R = x_Q := by { dsimp[x_R,x_Q,neg_half_R,neg_half_Q,half_Q], norm_cast }, have e1 : d_R = d_Q := by { dsimp[d_R,d_Q],rw[e0,rat.cast_abs] }, have e2 : d_Q = (n : ℚ) + half_Q := dist_neg_Q n h, exact calc d_R = d_Q : e1 ... = (n : ℚ) + half_Q : by {rw[e2,rat.cast_add]} ... = (n : ℝ) + half_R : by {dsimp[half_R],rw[rat.cast_coe_int]} end lemma dist_nonneg (n : ℤ) (h : n ≥ 0) : abs(neg_half_R - n) = (n : ℝ) + half_R := begin let x_Q : ℚ := neg_half_Q - n, let x_R : ℝ := neg_half_R - n, let d_Q : ℚ := abs x_Q, let d_R : ℝ := abs x_R, have e0 : x_R = x_Q := by { dsimp[x_R,x_Q,neg_half_R,neg_half_Q,half_Q], norm_cast }, have e1 : d_R = d_Q := by { dsimp[d_R,d_Q],rw[e0,rat.cast_abs] }, have e2 : d_Q = (n : ℚ) + half_Q := dist_nonneg_Q n h, exact calc d_R = d_Q : e1 ... = (n : ℚ) + half_Q : by {rw[e2,rat.cast_add]} ... = (n : ℝ) + half_R : by {dsimp[half_R],rw[rat.cast_coe_int]} end def is_closest_integer (n : ℤ) (x : ℝ) := ∀ (m : ℤ), m ≠ n → abs(x - n) < abs (x - m) lemma no_closest_integer (n : ℤ) : ¬ (is_closest_integer n neg_half_R) := begin have hh : ∀ k : ℤ, k ≥ 0 → ¬ ((k : ℝ) + half_R < half_R) := begin intros k k_nonneg k_half_lt, have k_half_ge : (k : ℝ) + half_R ≥ half_R := le_add_of_nonneg_left (int.cast_nonneg.mpr k_nonneg), exact not_le_of_gt k_half_lt k_half_ge, end, intro h0, by_cases h1 : n ≥ 0, {let m : ℤ := -1, have : ¬ (m ≥ 0) := dec_trivial, have h2 : m ≠ n := λ e, this (e.symm.subst h1), let h3 := h0 (-1) h2, let h4 := dist_neg 0 (le_refl 0), rw[add_zero] at h4, rw[h4,dist_nonneg n h1,int.cast_zero,zero_add] at h3, exact hh n h1 h3, },{ have h1a : n < 0 := lt_of_not_ge h1, let m : ℤ := 0, have : ¬ (m < 0) := dec_trivial, have h2 : m ≠ n := λ e, this (e.symm.subst h1a), let h3 := h0 0 h2, let h4 := dist_nonneg 0 (le_refl 0), rw[h4,int.cast_zero,zero_add] at h3, let k := - (1 + n), have h5 : n = - (1 + k) := by {dsimp[k],ring}, let h6 := (neg_nonneg_of_nonpos (int.add_one_le_iff.mpr (lt_of_not_ge h1))), rw[add_comm n 1] at h6, have h6a : 0 ≤ k := h6, let h7 := dist_neg k h6a, rw[← h5] at h7, rw[h7] at h3, exact hh k h6a h3, } end
429f90e5abae45f7d53f213e9fb178b85563b2be
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/adjunction/reflective.lean
67ce6368ea73d684b22a7b4d95ff23d0c244585d
[ "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
7,850
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.adjunction.fully_faithful import category_theory.functor.reflects_isomorphisms import category_theory.epi_mono /-! # Reflective functors Basic properties of reflective functors, especially those relating to their essential image. Note properties of reflective functors relating to limits and colimits are included in `category_theory.monad.limits`. -/ universes v₁ v₂ v₃ u₁ u₂ u₃ noncomputable theory namespace category_theory open category adjunction variables {C : Type u₁} {D : Type u₂} {E : Type u₃} variables [category.{v₁} C] [category.{v₂} D] [category.{v₃} E] /-- A functor is *reflective*, or *a reflective inclusion*, if it is fully faithful and right adjoint. -/ class reflective (R : D ⥤ C) extends is_right_adjoint R, full R, faithful R. variables {i : D ⥤ C} /-- For a reflective functor `i` (with left adjoint `L`), with unit `η`, we have `η_iL = iL η`. -/ -- TODO: This holds more generally for idempotent adjunctions, not just reflective adjunctions. lemma unit_obj_eq_map_unit [reflective i] (X : C) : (of_right_adjoint i).unit.app (i.obj ((left_adjoint i).obj X)) = i.map ((left_adjoint i).map ((of_right_adjoint i).unit.app X)) := begin rw [←cancel_mono (i.map ((of_right_adjoint i).counit.app ((left_adjoint i).obj X))), ←i.map_comp], simp, end /-- When restricted to objects in `D` given by `i : D ⥤ C`, the unit is an isomorphism. In other words, `η_iX` is an isomorphism for any `X` in `D`. More generally this applies to objects essentially in the reflective subcategory, see `functor.ess_image.unit_iso`. -/ instance is_iso_unit_obj [reflective i] {B : D} : is_iso ((of_right_adjoint i).unit.app (i.obj B)) := begin have : (of_right_adjoint i).unit.app (i.obj B) = inv (i.map ((of_right_adjoint i).counit.app B)), { rw ← comp_hom_eq_id, apply (of_right_adjoint i).right_triangle_components }, rw this, exact is_iso.inv_is_iso, end /-- If `A` is essentially in the image of a reflective functor `i`, then `η_A` is an isomorphism. This gives that the "witness" for `A` being in the essential image can instead be given as the reflection of `A`, with the isomorphism as `η_A`. (For any `B` in the reflective subcategory, we automatically have that `ε_B` is an iso.) -/ lemma functor.ess_image.unit_is_iso [reflective i] {A : C} (h : A ∈ i.ess_image) : is_iso ((of_right_adjoint i).unit.app A) := begin suffices : (of_right_adjoint i).unit.app A = h.get_iso.inv ≫ (of_right_adjoint i).unit.app (i.obj h.witness) ≫ (left_adjoint i ⋙ i).map h.get_iso.hom, { rw this, apply_instance }, rw ← nat_trans.naturality, simp, end /-- If `η_A` is an isomorphism, then `A` is in the essential image of `i`. -/ lemma mem_ess_image_of_unit_is_iso [is_right_adjoint i] (A : C) [is_iso ((of_right_adjoint i).unit.app A)] : A ∈ i.ess_image := ⟨(left_adjoint i).obj A, ⟨(as_iso ((of_right_adjoint i).unit.app A)).symm⟩⟩ /-- If `η_A` is a split monomorphism, then `A` is in the reflective subcategory. -/ lemma mem_ess_image_of_unit_split_mono [reflective i] {A : C} [split_mono ((of_right_adjoint i).unit.app A)] : A ∈ i.ess_image := begin let η : 𝟭 C ⟶ left_adjoint i ⋙ i := (of_right_adjoint i).unit, haveI : is_iso (η.app (i.obj ((left_adjoint i).obj A))) := (i.obj_mem_ess_image _).unit_is_iso, have : epi (η.app A), { apply epi_of_epi (retraction (η.app A)) _, rw (show retraction _ ≫ η.app A = _, from η.naturality (retraction (η.app A))), apply epi_comp (η.app (i.obj ((left_adjoint i).obj A))) }, resetI, haveI := is_iso_of_epi_of_split_mono (η.app A), exact mem_ess_image_of_unit_is_iso A, end /-- Composition of reflective functors. -/ instance reflective.comp (F : C ⥤ D) (G : D ⥤ E) [Fr : reflective F] [Gr : reflective G] : reflective (F ⋙ G) := { to_faithful := faithful.comp F G, } /-- (Implementation) Auxiliary definition for `unit_comp_partial_bijective`. -/ def unit_comp_partial_bijective_aux [reflective i] (A : C) (B : D) : (A ⟶ i.obj B) ≃ (i.obj ((left_adjoint i).obj A) ⟶ i.obj B) := ((adjunction.of_right_adjoint i).hom_equiv _ _).symm.trans (equiv_of_fully_faithful i) /-- The description of the inverse of the bijection `unit_comp_partial_bijective_aux`. -/ lemma unit_comp_partial_bijective_aux_symm_apply [reflective i] {A : C} {B : D} (f : i.obj ((left_adjoint i).obj A) ⟶ i.obj B) : (unit_comp_partial_bijective_aux _ _).symm f = (of_right_adjoint i).unit.app A ≫ f := by simp [unit_comp_partial_bijective_aux] /-- If `i` has a reflector `L`, then the function `(i.obj (L.obj A) ⟶ B) → (A ⟶ B)` given by precomposing with `η.app A` is a bijection provided `B` is in the essential image of `i`. That is, the function `λ (f : i.obj (L.obj A) ⟶ B), η.app A ≫ f` is bijective, as long as `B` is in the essential image of `i`. This definition gives an equivalence: the key property that the inverse can be described nicely is shown in `unit_comp_partial_bijective_symm_apply`. This establishes there is a natural bijection `(A ⟶ B) ≃ (i.obj (L.obj A) ⟶ B)`. In other words, from the point of view of objects in `D`, `A` and `i.obj (L.obj A)` look the same: specifically that `η.app A` is an isomorphism. -/ def unit_comp_partial_bijective [reflective i] (A : C) {B : C} (hB : B ∈ i.ess_image) : (A ⟶ B) ≃ (i.obj ((left_adjoint i).obj A) ⟶ B) := calc (A ⟶ B) ≃ (A ⟶ i.obj hB.witness) : iso.hom_congr (iso.refl _) hB.get_iso.symm ... ≃ (i.obj _ ⟶ i.obj hB.witness) : unit_comp_partial_bijective_aux _ _ ... ≃ (i.obj ((left_adjoint i).obj A) ⟶ B) : iso.hom_congr (iso.refl _) hB.get_iso @[simp] lemma unit_comp_partial_bijective_symm_apply [reflective i] (A : C) {B : C} (hB : B ∈ i.ess_image) (f) : (unit_comp_partial_bijective A hB).symm f = (of_right_adjoint i).unit.app A ≫ f := by simp [unit_comp_partial_bijective, unit_comp_partial_bijective_aux_symm_apply] lemma unit_comp_partial_bijective_symm_natural [reflective i] (A : C) {B B' : C} (h : B ⟶ B') (hB : B ∈ i.ess_image) (hB' : B' ∈ i.ess_image) (f : i.obj ((left_adjoint i).obj A) ⟶ B) : (unit_comp_partial_bijective A hB').symm (f ≫ h) = (unit_comp_partial_bijective A hB).symm f ≫ h := by simp lemma unit_comp_partial_bijective_natural [reflective i] (A : C) {B B' : C} (h : B ⟶ B') (hB : B ∈ i.ess_image) (hB' : B' ∈ i.ess_image) (f : A ⟶ B) : (unit_comp_partial_bijective A hB') (f ≫ h) = unit_comp_partial_bijective A hB f ≫ h := by rw [←equiv.eq_symm_apply, unit_comp_partial_bijective_symm_natural A h, equiv.symm_apply_apply] /-- If `i : D ⥤ C` is reflective, the inverse functor of `i ≌ F.ess_image` can be explicitly defined by the reflector. -/ @[simps] def equiv_ess_image_of_reflective [reflective i] : D ≌ i.ess_image := { functor := i.to_ess_image, inverse := i.ess_image_inclusion ⋙ (left_adjoint i : _), unit_iso := nat_iso.of_components (λ X, (as_iso $ (of_right_adjoint i).counit.app X).symm) (by { intros X Y f, dsimp, simp only [is_iso.eq_inv_comp, is_iso.comp_inv_eq, category.assoc], exact ((of_right_adjoint i).counit.naturality _).symm }), counit_iso := nat_iso.of_components (λ X, by { refine (iso.symm $ as_iso _), exact (of_right_adjoint i).unit.app X, apply_with (is_iso_of_reflects_iso _ i.ess_image_inclusion) { instances := ff }, exact functor.ess_image.unit_is_iso X.prop }) (by { intros X Y f, dsimp, simp only [is_iso.eq_inv_comp, is_iso.comp_inv_eq, category.assoc], exact ((of_right_adjoint i).unit.naturality f).symm }) } end category_theory
3de4be17d40681dad79f8b1957c7d992681a5cad
367134ba5a65885e863bdc4507601606690974c1
/src/algebra/group/units.lean
2a43a5e00b87ee46e76200e4cef12b60fc1d0563
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
13,016
lean
/- Copyright (c) 2017 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro, Johannes Hölzl, Chris Hughes, Jens Wagemaker -/ import algebra.group.basic import logic.nontrivial /-! # Units (i.e., invertible elements) of a multiplicative monoid -/ universe u variable {α : Type u} /-- Units of a monoid, bundled version. An element of a `monoid` is a unit if it has a two-sided inverse. This version bundles the inverse element so that it can be computed. For a predicate see `is_unit`. -/ structure units (α : Type u) [monoid α] := (val : α) (inv : α) (val_inv : val * inv = 1) (inv_val : inv * val = 1) /-- Units of an add_monoid, bundled version. An element of an add_monoid is a unit if it has a two-sided additive inverse. This version bundles the inverse element so that it can be computed. For a predicate see `is_add_unit`. -/ structure add_units (α : Type u) [add_monoid α] := (val : α) (neg : α) (val_neg : val + neg = 0) (neg_val : neg + val = 0) attribute [to_additive add_units] units namespace units variables [monoid α] @[to_additive] instance : has_coe (units α) α := ⟨val⟩ @[simp, to_additive] lemma coe_mk (a : α) (b h₁ h₂) : ↑(units.mk a b h₁ h₂) = a := rfl @[ext, to_additive] theorem ext : function.injective (coe : units α → α) | ⟨v, i₁, vi₁, iv₁⟩ ⟨v', i₂, vi₂, iv₂⟩ e := by change v = v' at e; subst v'; congr; simpa only [iv₂, vi₁, one_mul, mul_one] using mul_assoc i₂ v i₁ @[norm_cast, to_additive] theorem eq_iff {a b : units α} : (a : α) = b ↔ a = b := ext.eq_iff @[to_additive] theorem ext_iff {a b : units α} : a = b ↔ (a : α) = b := eq_iff.symm @[to_additive] instance [decidable_eq α] : decidable_eq (units α) := λ a b, decidable_of_iff' _ ext_iff @[simp, to_additive] theorem mk_coe (u : units α) (y h₁ h₂) : mk (u : α) y h₁ h₂ = u := ext rfl /-- Units of a monoid form a group. -/ @[to_additive] instance : group (units α) := { mul := λ u₁ u₂, ⟨u₁.val * u₂.val, u₂.inv * u₁.inv, by rw [mul_assoc, ← mul_assoc u₂.val, val_inv, one_mul, val_inv], by rw [mul_assoc, ← mul_assoc u₁.inv, inv_val, one_mul, inv_val]⟩, one := ⟨1, 1, one_mul 1, one_mul 1⟩, mul_one := λ u, ext $ mul_one u, one_mul := λ u, ext $ one_mul u, mul_assoc := λ u₁ u₂ u₃, ext $ mul_assoc u₁ u₂ u₃, inv := λ u, ⟨u.2, u.1, u.4, u.3⟩, mul_left_inv := λ u, ext u.inv_val } variables (a b : units α) {c : units α} @[simp, norm_cast, to_additive] lemma coe_mul : (↑(a * b) : α) = a * b := rfl attribute [norm_cast] add_units.coe_add @[simp, norm_cast, to_additive] lemma coe_one : ((1 : units α) : α) = 1 := rfl attribute [norm_cast] add_units.coe_zero @[simp, norm_cast, to_additive] lemma coe_eq_one {a : units α} : (a : α) = 1 ↔ a = 1 := by rw [←units.coe_one, eq_iff] @[simp, to_additive] lemma inv_mk (x y : α) (h₁ h₂) : (mk x y h₁ h₂)⁻¹ = mk y x h₂ h₁ := rfl @[to_additive] lemma val_coe : (↑a : α) = a.val := rfl @[norm_cast, to_additive] lemma coe_inv : ((a⁻¹ : units α) : α) = a.inv := rfl attribute [norm_cast] add_units.coe_neg @[simp, to_additive] lemma inv_mul : (↑a⁻¹ * a : α) = 1 := inv_val _ @[simp, to_additive] lemma mul_inv : (a * ↑a⁻¹ : α) = 1 := val_inv _ @[to_additive] lemma inv_mul_of_eq {u : units α} {a : α} (h : ↑u = a) : ↑u⁻¹ * a = 1 := by { rw [←h, u.inv_mul], } @[to_additive] lemma mul_inv_of_eq {u : units α} {a : α} (h : ↑u = a) : a * ↑u⁻¹ = 1 := by { rw [←h, u.mul_inv], } @[simp, to_additive] lemma mul_inv_cancel_left (a : units α) (b : α) : (a:α) * (↑a⁻¹ * b) = b := by rw [← mul_assoc, mul_inv, one_mul] @[simp, to_additive] lemma inv_mul_cancel_left (a : units α) (b : α) : (↑a⁻¹:α) * (a * b) = b := by rw [← mul_assoc, inv_mul, one_mul] @[simp, to_additive] lemma mul_inv_cancel_right (a : α) (b : units α) : a * b * ↑b⁻¹ = a := by rw [mul_assoc, mul_inv, mul_one] @[simp, to_additive] lemma inv_mul_cancel_right (a : α) (b : units α) : a * ↑b⁻¹ * b = a := by rw [mul_assoc, inv_mul, mul_one] @[to_additive] instance : inhabited (units α) := ⟨1⟩ @[to_additive] instance {α} [comm_monoid α] : comm_group (units α) := { mul_comm := λ u₁ u₂, ext $ mul_comm _ _, ..units.group } @[to_additive] instance [has_repr α] : has_repr (units α) := ⟨repr ∘ val⟩ @[simp, to_additive] theorem mul_right_inj (a : units α) {b c : α} : (a:α) * b = a * c ↔ b = c := ⟨λ h, by simpa only [inv_mul_cancel_left] using congr_arg ((*) ↑(a⁻¹ : units α)) h, congr_arg _⟩ @[simp, to_additive] theorem mul_left_inj (a : units α) {b c : α} : b * a = c * a ↔ b = c := ⟨λ h, by simpa only [mul_inv_cancel_right] using congr_arg (* ↑(a⁻¹ : units α)) h, congr_arg _⟩ @[to_additive] theorem eq_mul_inv_iff_mul_eq {a b : α} : a = b * ↑c⁻¹ ↔ a * c = b := ⟨λ h, by rw [h, inv_mul_cancel_right], λ h, by rw [← h, mul_inv_cancel_right]⟩ @[to_additive] theorem eq_inv_mul_iff_mul_eq {a c : α} : a = ↑b⁻¹ * c ↔ ↑b * a = c := ⟨λ h, by rw [h, mul_inv_cancel_left], λ h, by rw [← h, inv_mul_cancel_left]⟩ @[to_additive] theorem inv_mul_eq_iff_eq_mul {b c : α} : ↑a⁻¹ * b = c ↔ b = a * c := ⟨λ h, by rw [← h, mul_inv_cancel_left], λ h, by rw [h, inv_mul_cancel_left]⟩ @[to_additive] theorem mul_inv_eq_iff_eq_mul {a c : α} : a * ↑b⁻¹ = c ↔ a = c * b := ⟨λ h, by rw [← h, inv_mul_cancel_right], λ h, by rw [h, mul_inv_cancel_right]⟩ lemma inv_eq_of_mul_eq_one {u : units α} {a : α} (h : ↑u * a = 1) : ↑u⁻¹ = a := calc ↑u⁻¹ = ↑u⁻¹ * 1 : by rw mul_one ... = ↑u⁻¹ * ↑u * a : by rw [←h, ←mul_assoc] ... = a : by rw [u.inv_mul, one_mul] lemma inv_unique {u₁ u₂ : units α} (h : (↑u₁ : α) = ↑u₂) : (↑u₁⁻¹ : α) = ↑u₂⁻¹ := suffices ↑u₁ * (↑u₂⁻¹ : α) = 1, by exact inv_eq_of_mul_eq_one this, by rw [h, u₂.mul_inv] end units /-- For `a, b` in a `comm_monoid` such that `a * b = 1`, makes a unit out of `a`. -/ @[to_additive "For `a, b` in an `add_comm_monoid` such that `a + b = 0`, makes an add_unit out of `a`."] def units.mk_of_mul_eq_one [comm_monoid α] (a b : α) (hab : a * b = 1) : units α := ⟨a, b, hab, (mul_comm b a).trans hab⟩ @[simp, to_additive] lemma units.coe_mk_of_mul_eq_one [comm_monoid α] {a b : α} (h : a * b = 1) : (units.mk_of_mul_eq_one a b h : α) = a := rfl section monoid variables [monoid α] {a b c : α} /-- Partial division. It is defined when the second argument is invertible, and unlike the division operator in `division_ring` it is not totalized at zero. -/ def divp (a : α) (u) : α := a * (u⁻¹ : units α) infix ` /ₚ `:70 := divp @[simp] theorem divp_self (u : units α) : (u : α) /ₚ u = 1 := units.mul_inv _ @[simp] theorem divp_one (a : α) : a /ₚ 1 = a := mul_one _ theorem divp_assoc (a b : α) (u : units α) : a * b /ₚ u = a * (b /ₚ u) := mul_assoc _ _ _ @[simp] theorem divp_inv (u : units α) : a /ₚ u⁻¹ = a * u := rfl @[simp] theorem divp_mul_cancel (a : α) (u : units α) : a /ₚ u * u = a := (mul_assoc _ _ _).trans $ by rw [units.inv_mul, mul_one] @[simp] theorem mul_divp_cancel (a : α) (u : units α) : (a * u) /ₚ u = a := (mul_assoc _ _ _).trans $ by rw [units.mul_inv, mul_one] @[simp] theorem divp_left_inj (u : units α) {a b : α} : a /ₚ u = b /ₚ u ↔ a = b := units.mul_left_inj _ theorem divp_divp_eq_divp_mul (x : α) (u₁ u₂ : units α) : (x /ₚ u₁) /ₚ u₂ = x /ₚ (u₂ * u₁) := by simp only [divp, mul_inv_rev, units.coe_mul, mul_assoc] theorem divp_eq_iff_mul_eq {x : α} {u : units α} {y : α} : x /ₚ u = y ↔ y * u = x := u.mul_left_inj.symm.trans $ by rw [divp_mul_cancel]; exact ⟨eq.symm, eq.symm⟩ theorem divp_eq_one_iff_eq {a : α} {u : units α} : a /ₚ u = 1 ↔ a = u := (units.mul_left_inj u).symm.trans $ by rw [divp_mul_cancel, one_mul] @[simp] theorem one_divp (u : units α) : 1 /ₚ u = ↑u⁻¹ := one_mul _ end monoid section comm_monoid variables [comm_monoid α] theorem divp_eq_divp_iff {x y : α} {ux uy : units α} : x /ₚ ux = y /ₚ uy ↔ x * uy = y * ux := by rw [divp_eq_iff_mul_eq, mul_comm, ← divp_assoc, divp_eq_iff_mul_eq, mul_comm y ux] theorem divp_mul_divp (x y : α) (ux uy : units α) : (x /ₚ ux) * (y /ₚ uy) = (x * y) /ₚ (ux * uy) := by rw [← divp_divp_eq_divp_mul, divp_assoc, mul_comm x, divp_assoc, mul_comm] end comm_monoid /-! # `is_unit` predicate In this file we define the `is_unit` predicate on a `monoid`, and prove a few basic properties. For the bundled version see `units`. See also `prime`, `associated`, and `irreducible` in `algebra/associated`. -/ section is_unit variables {M : Type*} {N : Type*} /-- An element `a : M` of a monoid is a unit if it has a two-sided inverse. The actual definition says that `a` is equal to some `u : units M`, where `units M` is a bundled version of `is_unit`. -/ @[to_additive is_add_unit "An element `a : M` of an add_monoid is an `add_unit` if it has a two-sided additive inverse. The actual definition says that `a` is equal to some `u : add_units M`, where `add_units M` is a bundled version of `is_add_unit`."] def is_unit [monoid M] (a : M) : Prop := ∃ u : units M, (u : M) = a @[nontriviality] lemma is_unit_of_subsingleton [monoid M] [subsingleton M] (a : M) : is_unit a := ⟨⟨a, a, subsingleton.elim _ _, subsingleton.elim _ _⟩, rfl⟩ @[simp, to_additive is_add_unit_add_unit] lemma is_unit_unit [monoid M] (u : units M) : is_unit (u : M) := ⟨u, rfl⟩ @[simp, to_additive is_add_unit_zero] theorem is_unit_one [monoid M] : is_unit (1:M) := ⟨1, rfl⟩ @[to_additive is_add_unit_of_add_eq_zero] theorem is_unit_of_mul_eq_one [comm_monoid M] (a b : M) (h : a * b = 1) : is_unit a := ⟨units.mk_of_mul_eq_one a b h, rfl⟩ @[to_additive is_add_unit_iff_exists_neg] theorem is_unit_iff_exists_inv [comm_monoid M] {a : M} : is_unit a ↔ ∃ b, a * b = 1 := ⟨by rintro ⟨⟨a, b, hab, _⟩, rfl⟩; exact ⟨b, hab⟩, λ ⟨b, hab⟩, is_unit_of_mul_eq_one _ b hab⟩ @[to_additive is_add_unit_iff_exists_neg'] theorem is_unit_iff_exists_inv' [comm_monoid M] {a : M} : is_unit a ↔ ∃ b, b * a = 1 := by simp [is_unit_iff_exists_inv, mul_comm] /-- Multiplication by a `u : units M` doesn't affect `is_unit`. -/ @[simp, to_additive is_add_unit_add_add_units "Addition of a `u : add_units M` doesn't affect `is_add_unit`."] theorem units.is_unit_mul_units [monoid M] (a : M) (u : units M) : is_unit (a * u) ↔ is_unit a := iff.intro (assume ⟨v, hv⟩, have is_unit (a * ↑u * ↑u⁻¹), by existsi v * u⁻¹; rw [←hv, units.coe_mul], by rwa [mul_assoc, units.mul_inv, mul_one] at this) (assume ⟨v, hv⟩, hv ▸ ⟨v * u, (units.coe_mul v u).symm⟩) lemma is_unit.mul [monoid M] {x y : M} : is_unit x → is_unit y → is_unit (x * y) := by { rintros ⟨x, rfl⟩ ⟨y, rfl⟩, exact ⟨x * y, units.coe_mul _ _⟩ } @[to_additive is_add_unit_of_add_is_add_unit_left] theorem is_unit_of_mul_is_unit_left [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit x := let ⟨z, hz⟩ := is_unit_iff_exists_inv.1 hu in is_unit_iff_exists_inv.2 ⟨y * z, by rwa ← mul_assoc⟩ @[to_additive] theorem is_unit_of_mul_is_unit_right [comm_monoid M] {x y : M} (hu : is_unit (x * y)) : is_unit y := @is_unit_of_mul_is_unit_left _ _ y x $ by rwa mul_comm @[to_additive] theorem is_unit.mul_right_inj [monoid M] {a b c : M} (ha : is_unit a) : a * b = a * c ↔ b = c := by cases ha with a ha; rw [←ha, units.mul_right_inj] @[to_additive] theorem is_unit.mul_left_inj [monoid M] {a b c : M} (ha : is_unit a) : b * a = c * a ↔ b = c := by cases ha with a ha; rw [←ha, units.mul_left_inj] /-- The element of the group of units, corresponding to an element of a monoid which is a unit. -/ noncomputable def is_unit.unit [monoid M] {a : M} (h : is_unit a) : units M := classical.some h lemma is_unit.unit_spec [monoid M] {a : M} (h : is_unit a) : ↑h.unit = a := classical.some_spec h end is_unit section noncomputable_defs variables {M : Type*} /-- Constructs a `group` structure on a `monoid` consisting only of units. -/ noncomputable def group_of_is_unit [hM : monoid M] (h : ∀ (a : M), is_unit a) : group M := { inv := λ a, ↑((h a).unit)⁻¹, mul_left_inv := λ a, by { change ↑((h a).unit)⁻¹ * a = 1, rw [units.inv_mul_eq_iff_eq_mul, (h a).unit_spec, mul_one] }, .. hM } /-- Constructs a `comm_group` structure on a `comm_monoid` consisting only of units. -/ noncomputable def comm_group_of_is_unit [hM : comm_monoid M] (h : ∀ (a : M), is_unit a) : comm_group M := { inv := λ a, ↑((h a).unit)⁻¹, mul_left_inv := λ a, by { change ↑((h a).unit)⁻¹ * a = 1, rw [units.inv_mul_eq_iff_eq_mul, (h a).unit_spec, mul_one] }, .. hM } end noncomputable_defs
ef7a5eea695c997bfd1351e95909bf44e968a11b
9dc8cecdf3c4634764a18254e94d43da07142918
/src/ring_theory/discriminant.lean
8e5e05041555aff7be788738aa6faaab63ba984b
[ "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
16,455
lean
/- Copyright (c) 2021 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import ring_theory.trace import ring_theory.norm import number_theory.number_field /-! # Discriminant of a family of vectors Given an `A`-algebra `B` and `b`, an `ι`-indexed family of elements of `B`, we define the *discriminant* of `b` as the determinant of the matrix whose `(i j)`-th element is the trace of `b i * b j`. ## Main definition * `algebra.discr A b` : the discriminant of `b : ι → B`. ## Main results * `algebra.discr_zero_of_not_linear_independent` : if `b` is not linear independent, then `algebra.discr A b = 0`. * `algebra.discr_of_matrix_vec_mul` and `discr_of_matrix_mul_vec` : formulas relating `algebra.discr A ι b` with `algebra.discr A ((P.map (algebra_map A B)).vec_mul b)` and `algebra.discr A ((P.map (algebra_map A B)).mul_vec b)`. * `algebra.discr_not_zero_of_basis` : over a field, if `b` is a basis, then `algebra.discr K b ≠ 0`. * `algebra.discr_eq_det_embeddings_matrix_reindex_pow_two` : if `L/K` is a field extension and `b : ι → L`, then `discr K b` is the square of the determinant of the matrix whose `(i, j)` coefficient is `σⱼ (b i)`, where `σⱼ : L →ₐ[K] E` is the embedding in an algebraically closed field `E` corresponding to `j : ι` via a bijection `e : ι ≃ (L →ₐ[K] E)`. * `algebra.discr_of_power_basis_eq_prod` : the discriminant of a power basis. * `discr_is_integral` : if `K` and `L` are fields and `is_scalar_tower R K L`, is `b : ι → L` satisfies ` ∀ i, is_integral R (b i)`, then `is_integral R (discr K b)`. * `discr_mul_is_integral_mem_adjoin` : let `K` be the fraction field of an integrally closed domain `R` and let `L` be a finite separable extension of `K`. Let `B : power_basis K L` be such that `is_integral R B.gen`. Then for all, `z : L` we have `(discr K B.basis) • z ∈ adjoin R ({B.gen} : set L)`. ## Implementation details Our definition works for any `A`-algebra `B`, but note that if `B` is not free as an `A`-module, then `trace A B = 0` by definition, so `discr A b = 0` for any `b`. -/ universes u v w z open_locale matrix big_operators open matrix finite_dimensional fintype polynomial finset intermediate_field namespace algebra variables (A : Type u) {B : Type v} (C : Type z) {ι : Type w} variables [comm_ring A] [comm_ring B] [algebra A B] [comm_ring C] [algebra A C] section discr /-- Given an `A`-algebra `B` and `b`, an `ι`-indexed family of elements of `B`, we define `discr A ι b` as the determinant of `trace_matrix A ι b`. -/ noncomputable def discr (A : Type u) {B : Type v} [comm_ring A] [comm_ring B] [algebra A B] [fintype ι] (b : ι → B) := by { classical, exact (trace_matrix A b).det } lemma discr_def [decidable_eq ι] [fintype ι] (b : ι → B) : discr A b = (trace_matrix A b).det := by convert rfl variables {ι' : Type*} [fintype ι'] [fintype ι] section basic @[simp] lemma discr_reindex (b : basis ι A B) (f : ι ≃ ι') : discr A (b ∘ ⇑(f.symm)) = discr A b := begin classical, rw [← basis.coe_reindex, discr_def, trace_matrix_reindex, det_reindex_self, ← discr_def] end /-- If `b` is not linear independent, then `algebra.discr A b = 0`. -/ lemma discr_zero_of_not_linear_independent [is_domain A] {b : ι → B} (hli : ¬linear_independent A b) : discr A b = 0 := begin classical, obtain ⟨g, hg, i, hi⟩ := fintype.not_linear_independent_iff.1 hli, have : (trace_matrix A b).mul_vec g = 0, { ext i, have : ∀ j, (trace A B) (b i * b j) * g j = (trace A B) (((g j) • (b j)) * b i), { intro j, simp [mul_comm], }, simp only [mul_vec, dot_product, trace_matrix, pi.zero_apply, trace_form_apply, λ j, this j, ← linear_map.map_sum, ← sum_mul, hg, zero_mul, linear_map.map_zero] }, by_contra h, rw discr_def at h, simpa [matrix.eq_zero_of_mul_vec_eq_zero h this] using hi, end variable {A} /-- Relation between `algebra.discr A ι b` and `algebra.discr A ((P.map (algebra_map A B)).vec_mul b)`. -/ lemma discr_of_matrix_vec_mul [decidable_eq ι] (b : ι → B) (P : matrix ι ι A) : discr A ((P.map (algebra_map A B)).vec_mul b) = P.det ^ 2 * discr A b := by rw [discr_def, trace_matrix_of_matrix_vec_mul, det_mul, det_mul, det_transpose, mul_comm, ← mul_assoc, discr_def, pow_two] /-- Relation between `algebra.discr A ι b` and `algebra.discr A ((P.map (algebra_map A B)).mul_vec b)`. -/ lemma discr_of_matrix_mul_vec [decidable_eq ι] (b : ι → B) (P : matrix ι ι A) : discr A ((P.map (algebra_map A B)).mul_vec b) = P.det ^ 2 * discr A b := by rw [discr_def, trace_matrix_of_matrix_mul_vec, det_mul, det_mul, det_transpose, mul_comm, ← mul_assoc, discr_def, pow_two] end basic section field variables (K : Type u) {L : Type v} (E : Type z) [field K] [field L] [field E] variables [algebra K L] [algebra K E] variables [module.finite K L] [is_alg_closed E] /-- Over a field, if `b` is a basis, then `algebra.discr K b ≠ 0`. -/ lemma discr_not_zero_of_basis [is_separable K L] (b : basis ι K L) : discr K b ≠ 0 := begin casesI is_empty_or_nonempty ι, { simp [discr] }, { have := span_eq_top_of_linear_independent_of_card_eq_finrank b.linear_independent (finrank_eq_card_basis b).symm, rw [discr_def, trace_matrix_def], simp_rw [← basis.mk_apply b.linear_independent this.ge], rw [← trace_matrix_def, trace_matrix_of_basis, ← bilin_form.nondegenerate_iff_det_ne_zero], exact trace_form_nondegenerate _ _ }, end /-- Over a field, if `b` is a basis, then `algebra.discr K b` is a unit. -/ lemma discr_is_unit_of_basis [is_separable K L] (b : basis ι K L) : is_unit (discr K b) := is_unit.mk0 _ (discr_not_zero_of_basis _ _) variables (b : ι → L) (pb : power_basis K L) /-- If `L/K` is a field extension and `b : ι → L`, then `discr K b` is the square of the determinant of the matrix whose `(i, j)` coefficient is `σⱼ (b i)`, where `σⱼ : L →ₐ[K] E` is the embedding in an algebraically closed field `E` corresponding to `j : ι` via a bijection `e : ι ≃ (L →ₐ[K] E)`. -/ lemma discr_eq_det_embeddings_matrix_reindex_pow_two [decidable_eq ι] [is_separable K L] (e : ι ≃ (L →ₐ[K] E)) : algebra_map K E (discr K b) = (embeddings_matrix_reindex K E b e).det ^ 2 := by rw [discr_def, ring_hom.map_det, ring_hom.map_matrix_apply, trace_matrix_eq_embeddings_matrix_reindex_mul_trans, det_mul, det_transpose, pow_two] /-- The discriminant of a power basis. -/ lemma discr_power_basis_eq_prod (e : fin pb.dim ≃ (L →ₐ[K] E)) [is_separable K L] : algebra_map K E (discr K pb.basis) = ∏ i : fin pb.dim, ∏ j in Ioi i, (e j pb.gen- (e i pb.gen)) ^ 2 := begin rw [discr_eq_det_embeddings_matrix_reindex_pow_two K E pb.basis e, embeddings_matrix_reindex_eq_vandermonde, det_transpose, det_vandermonde, ← prod_pow], congr, ext i, rw [← prod_pow] end /-- A variation of `of_power_basis_eq_prod`. -/ lemma discr_power_basis_eq_prod' [is_separable K L] (e : fin pb.dim ≃ (L →ₐ[K] E)) : algebra_map K E (discr K pb.basis) = ∏ i : fin pb.dim, ∏ j in Ioi i, -((e j pb.gen - e i pb.gen) * (e i pb.gen - e j pb.gen)) := begin rw [discr_power_basis_eq_prod _ _ _ e], congr, ext i, congr, ext j, ring end local notation `n` := finrank K L /-- A variation of `of_power_basis_eq_prod`. -/ lemma discr_power_basis_eq_prod'' [is_separable K L] (e : fin pb.dim ≃ (L →ₐ[K] E)) : algebra_map K E (discr K pb.basis) = (-1) ^ (n * (n - 1) / 2) * ∏ i : fin pb.dim, ∏ j in Ioi i, (e j pb.gen - e i pb.gen) * (e i pb.gen - e j pb.gen) := begin rw [discr_power_basis_eq_prod' _ _ _ e], simp_rw [λ i j, neg_eq_neg_one_mul ((e j pb.gen- (e i pb.gen)) * (e i pb.gen- (e j pb.gen))), prod_mul_distrib], congr, simp only [prod_pow_eq_pow_sum, prod_const], congr, rw [← @nat.cast_inj ℚ, nat.cast_sum], have : ∀ (x : fin pb.dim), (↑x + 1) ≤ pb.dim := by simp [nat.succ_le_iff, fin.is_lt], simp_rw [fin.card_Ioi, nat.sub_sub, add_comm 1], simp only [nat.cast_sub, this, finset.card_fin, nsmul_eq_mul, sum_const, sum_sub_distrib, nat.cast_add, nat.cast_one, sum_add_distrib, mul_one], rw [← nat.cast_sum, ← @finset.sum_range ℕ _ pb.dim (λ i, i), sum_range_id ], have hn : n = pb.dim, { rw [← alg_hom.card K L E, ← fintype.card_fin pb.dim], exact card_congr (equiv.symm e) }, have h₂ : 2 ∣ (pb.dim * (pb.dim - 1)) := even_iff_two_dvd.1 (nat.even_mul_self_pred _), have hne : ((2 : ℕ) : ℚ) ≠ 0 := by simp, have hle : 1 ≤ pb.dim, { rw [← hn, nat.one_le_iff_ne_zero, ← zero_lt_iff, finite_dimensional.finrank_pos_iff], apply_instance }, rw [hn, nat.cast_div h₂ hne, nat.cast_mul, nat.cast_sub hle], field_simp, ring, end /-- Formula for the discriminant of a power basis using the norm of the field extension. -/ lemma discr_power_basis_eq_norm [is_separable K L] : discr K pb.basis = (-1) ^ (n * (n - 1) / 2) * (norm K (aeval pb.gen (minpoly K pb.gen).derivative)) := begin let E := algebraic_closure L, letI := λ (a b : E), classical.prop_decidable (eq a b), have e : fin pb.dim ≃ (L →ₐ[K] E), { refine equiv_of_card_eq _, rw [fintype.card_fin, alg_hom.card], exact (power_basis.finrank pb).symm }, have hnodup : (map (algebra_map K E) (minpoly K pb.gen)).roots.nodup := nodup_roots (separable.map (is_separable.separable K pb.gen)), have hroots : ∀ σ : L →ₐ[K] E, σ pb.gen ∈ (map (algebra_map K E) (minpoly K pb.gen)).roots, { intro σ, rw [mem_roots, is_root.def, eval_map, ← aeval_def, aeval_alg_hom_apply], repeat { simp [minpoly.ne_zero (is_separable.is_integral K pb.gen)] } }, apply (algebra_map K E).injective, rw [ring_hom.map_mul, ring_hom.map_pow, ring_hom.map_neg, ring_hom.map_one, discr_power_basis_eq_prod'' _ _ _ e], congr, rw [norm_eq_prod_embeddings, prod_prod_Ioi_mul_eq_prod_prod_off_diag], conv_rhs { congr, skip, funext, rw [← aeval_alg_hom_apply, aeval_root_derivative_of_splits (minpoly.monic (is_separable.is_integral K pb.gen)) (is_alg_closed.splits_codomain _) (hroots σ), ← finset.prod_mk _ (hnodup.erase _)] }, rw [prod_sigma', prod_sigma'], refine prod_bij (λ i hi, ⟨e i.2, e i.1 pb.gen⟩) (λ i hi, _) (λ i hi, by simp at hi) (λ i j hi hj hij, _) (λ σ hσ, _), { simp only [true_and, finset.mem_mk, mem_univ, mem_sigma], rw [multiset.mem_erase_of_ne (λ h, _)], { exact hroots _ }, { simp only [true_and, mem_univ, ne.def, mem_sigma, mem_compl, mem_singleton] at hi, rw [← power_basis.lift_equiv_apply_coe, ← power_basis.lift_equiv_apply_coe] at h, exact hi (e.injective $ pb.lift_equiv.injective $ subtype.eq h.symm) } }, { simp only [equiv.apply_eq_iff_eq, heq_iff_eq] at hij, have h := hij.2, rw [← power_basis.lift_equiv_apply_coe, ← power_basis.lift_equiv_apply_coe] at h, refine sigma.eq (equiv.injective e (equiv.injective _ (subtype.eq h))) (by simp [hij.1]) }, { simp only [true_and, finset.mem_mk, mem_univ, mem_sigma] at ⊢ hσ, simp only [sigma.exists, exists_prop, mem_compl, mem_singleton, ne.def], refine ⟨e.symm (power_basis.lift pb σ.2 _), e.symm σ.1, ⟨λ h, _, sigma.eq _ _⟩⟩, { rw [aeval_def, eval₂_eq_eval_map, ← is_root.def, ← mem_roots], { exact multiset.erase_subset _ _ hσ }, { simp [minpoly.ne_zero (is_separable.is_integral K pb.gen)] } }, { replace h := alg_hom.congr_fun (equiv.injective _ h) pb.gen, rw [power_basis.lift_gen] at h, rw [← h] at hσ, exact hnodup.not_mem_erase hσ }, all_goals { simp } } end section integral variables {R : Type z} [comm_ring R] [algebra R K] [algebra R L] [is_scalar_tower R K L] local notation `is_integral` := _root_.is_integral /-- If `K` and `L` are fields and `is_scalar_tower R K L`, and `b : ι → L` satisfies ` ∀ i, is_integral R (b i)`, then `is_integral R (discr K b)`. -/ lemma discr_is_integral {b : ι → L} (h : ∀ i, is_integral R (b i)) : is_integral R (discr K b) := begin classical, rw [discr_def], exact is_integral.det (λ i j, is_integral_trace (is_integral_mul (h i) (h j))) end /-- If `b` and `b'` are `ℚ`-bases of a number field `K` such that `∀ i j, is_integral ℤ (b.to_matrix b' i j)` and `∀ i j, is_integral ℤ (b'.to_matrix b i j)` then `discr ℚ b = discr ℚ b'`. -/ lemma discr_eq_discr_of_to_matrix_coeff_is_integral [number_field K] {b : basis ι ℚ K} {b' : basis ι' ℚ K} (h : ∀ i j, is_integral ℤ (b.to_matrix b' i j)) (h' : ∀ i j, is_integral ℤ (b'.to_matrix b i j)) : discr ℚ b = discr ℚ b' := begin replace h' : ∀ i j, is_integral ℤ (b'.to_matrix ((b.reindex (b.index_equiv b'))) i j), { intros i j, convert h' i ((b.index_equiv b').symm j), simpa }, classical, rw [← (b.reindex (b.index_equiv b')).to_matrix_map_vec_mul b', discr_of_matrix_vec_mul, ← one_mul (discr ℚ b), basis.coe_reindex, discr_reindex], congr, have hint : is_integral ℤ (((b.reindex (b.index_equiv b')).to_matrix b').det) := is_integral.det (λ i j, h _ _), obtain ⟨r, hr⟩ := is_integrally_closed.is_integral_iff.1 hint, have hunit : is_unit r, { have : is_integral ℤ ((b'.to_matrix (b.reindex (b.index_equiv b'))).det) := is_integral.det (λ i j, h' _ _), obtain ⟨r', hr'⟩ := is_integrally_closed.is_integral_iff.1 this, refine is_unit_iff_exists_inv.2 ⟨r', _⟩, suffices : algebra_map ℤ ℚ (r * r') = 1, { rw [← ring_hom.map_one (algebra_map ℤ ℚ)] at this, exact (is_fraction_ring.injective ℤ ℚ) this }, rw [ring_hom.map_mul, hr, hr', ← det_mul, basis.to_matrix_mul_to_matrix_flip, det_one] }, rw [← ring_hom.map_one (algebra_map ℤ ℚ), ← hr], cases int.is_unit_iff.1 hunit with hp hm, { simp [hp] }, { simp [hm] } end /-- Let `K` be the fraction field of an integrally closed domain `R` and let `L` be a finite separable extension of `K`. Let `B : power_basis K L` be such that `is_integral R B.gen`. Then for all, `z : L` that are integral over `R`, we have `(discr K B.basis) • z ∈ adjoin R ({B.gen} : set L)`. -/ lemma discr_mul_is_integral_mem_adjoin [is_domain R] [is_separable K L] [is_integrally_closed R] [is_fraction_ring R K] {B : power_basis K L} (hint : is_integral R B.gen) {z : L} (hz : is_integral R z) : (discr K B.basis) • z ∈ adjoin R ({B.gen} : set L) := begin have hinv : is_unit (trace_matrix K B.basis).det := by simpa [← discr_def] using discr_is_unit_of_basis _ B.basis, have H : (trace_matrix K B.basis).det • (trace_matrix K B.basis).mul_vec (B.basis.equiv_fun z) = (trace_matrix K B.basis).det • (λ i, trace K L (z * B.basis i)), { congr, exact trace_matrix_of_basis_mul_vec _ _ }, have cramer := mul_vec_cramer (trace_matrix K B.basis) (λ i, trace K L (z * B.basis i)), suffices : ∀ i, ((trace_matrix K B.basis).det • (B.basis.equiv_fun z)) i ∈ (⊥ : subalgebra R K), { rw [← B.basis.sum_repr z, finset.smul_sum], refine subalgebra.sum_mem _ (λ i hi, _), replace this := this i, rw [← discr_def, pi.smul_apply, mem_bot] at this, obtain ⟨r, hr⟩ := this, rw [basis.equiv_fun_apply] at hr, rw [← smul_assoc, ← hr, algebra_map_smul], refine subalgebra.smul_mem _ _ _, rw [B.basis_eq_pow i], refine subalgebra.pow_mem _ (subset_adjoin (set.mem_singleton _)) _}, intro i, rw [← H, ← mul_vec_smul] at cramer, replace cramer := congr_arg (mul_vec (trace_matrix K B.basis)⁻¹) cramer, rw [mul_vec_mul_vec, nonsing_inv_mul _ hinv, mul_vec_mul_vec, nonsing_inv_mul _ hinv, one_mul_vec, one_mul_vec] at cramer, rw [← congr_fun cramer i, cramer_apply, det_apply], refine subalgebra.sum_mem _ (λ σ _, subalgebra.zsmul_mem _ (subalgebra.prod_mem _ (λ j _, _)) _), by_cases hji : j = i, { simp only [update_column_apply, hji, eq_self_iff_true, power_basis.coe_basis], exact mem_bot.2 (is_integrally_closed.is_integral_iff.1 $ is_integral_trace $ is_integral_mul hz $ is_integral.pow hint _) }, { simp only [update_column_apply, hji, power_basis.coe_basis], exact mem_bot.2 (is_integrally_closed.is_integral_iff.1 $ is_integral_trace $ is_integral_mul (is_integral.pow hint _) (is_integral.pow hint _)) } end end integral end field end discr end algebra
025b6456f1c7481786e72b96570ed2ed3cc82bba
6772a11d96d69b3f90d6eeaf7f9accddf2a7691d
/examples/monoids.lean
684ee647714688f73f4d52c391b7cca269329341
[]
no_license
lbordowitz/lean-category-theory
5397361f0f81037d65762da48de2c16ec85a5e4b
8c59893e44af3804eba4dbc5f7fa5928ed2e0ae6
refs/heads/master
1,611,310,752,156
1,487,070,172,000
1,487,070,172,000
82,003,141
0
0
null
1,487,118,553,000
1,487,118,553,000
null
UTF-8
Lean
false
false
2,709
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Stephen Morgan, Scott Morrison import ..category import ..functor import .semigroups namespace tqft.categories.examples.monoids open tqft.categories set_option pp.universes true structure monoid_morphism { α β : Type } ( s : monoid α ) ( t: monoid β ) := (map: α → β) (multiplicative : ∀ x y : α, map(x * y) = map(x) * map(y)) (unital : map(one) = one) attribute [simp] monoid_morphism.multiplicative attribute [simp] monoid_morphism.unital -- This defines a coercion so we can write `f x` for `map f x`. instance monoid_morphism_to_map { α β : Type } { s : monoid α } { t: monoid β } : has_coe_to_fun (monoid_morphism s t) := { F := λ f, Π x : α, β, coe := monoid_morphism.map } definition monoid_identity { α : Type } ( s: monoid α ) : monoid_morphism s s := ⟨ id, ♮, ♮ ⟩ definition monoid_morphism_composition { α β γ : Type } { s: monoid α } { t: monoid β } { u: monoid γ} ( f: monoid_morphism s t ) ( g: monoid_morphism t u ) : monoid_morphism s u := { map := λ x, g (f x), multiplicative := ♮, unital := ♮ } @[pointwise] lemma monoid_morphism_pointwise_equality { α β : Type } { s : monoid α } { t: monoid β } ( f g : monoid_morphism s t ) ( w : ∀ x : α, f x = g x) : f = g := /- -- This proof is identical to that of the lemma NaturalTransformations_componentwise_equal. -- TODO: automate! -/ begin induction f with fc, induction g with gc, have hc : fc = gc, from funext w, by subst hc end definition CategoryOfMonoids : Category := { Obj := Σ α : Type, monoid α, Hom := λ s t, monoid_morphism s.2 t.2, identity := λ s, monoid_identity s.2, compose := λ _ _ _ f g, monoid_morphism_composition f g, left_identity := ♮, right_identity := ♮, associativity := ♮ } open tqft.categories.functor open tqft.categories.examples.semigroups -- Sadly doesn't work: -- definition cast_monoid_to_semigroup' {α: Type} (s: monoid α) : semigroup α := s definition cast_monoid_to_semigroup {α: Type} (s: monoid α) : semigroup α := @monoid.to_semigroup α s definition ForgetfulFunctor_Monoids_to_Semigroups : Functor CategoryOfMonoids CategoryOfSemigroups := { onObjects := λ s, sigma.mk s.1 (@monoid.to_semigroup s.1 s.2), onMorphisms := λ s t, λ f : monoid_morphism s.2 t.2, { map := f^.map, multiplicative := f^.multiplicative }, identities := ♮, functoriality := ♮ } end tqft.categories.examples.monoids
3d1d641805f654bebf287450e7eb4a6edd2ad358
fecda8e6b848337561d6467a1e30cf23176d6ad0
/src/logic/nontrivial.lean
34ad9d5231608f81b7a47948becc11d72262af4b
[ "Apache-2.0" ]
permissive
spolu/mathlib
bacf18c3d2a561d00ecdc9413187729dd1f705ed
480c92cdfe1cf3c2d083abded87e82162e8814f4
refs/heads/master
1,671,684,094,325
1,600,736,045,000
1,600,736,045,000
297,564,749
1
0
null
1,600,758,368,000
1,600,758,367,000
null
UTF-8
Lean
false
false
4,422
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 logic.unique import logic.function.basic /-! # Nontrivial types A type is *nontrivial* if it contains at least two elements. This is useful in particular for rings (where it is equivalent to the fact that zero is different from one) and for vector spaces (where it is equivalent to the fact that the dimension is positive). We introduce a typeclass `nontrivial` formalizing this property. -/ variables {α : Type*} {β : Type*} open_locale classical /-- Predicate typeclass for expressing that a type is not reduced to a single element. In rings, this is equivalent to `0 ≠ 1`. In vector spaces, this is equivalent to positive dimension. -/ class nontrivial (α : Type*) : Prop := (exists_pair_ne : ∃ (x y : α), x ≠ y) lemma nontrivial_iff : nontrivial α ↔ ∃ (x y : α), x ≠ y := ⟨λ h, h.exists_pair_ne, λ h, ⟨h⟩⟩ lemma exists_pair_ne (α : Type*) [nontrivial α] : ∃ (x y : α), x ≠ y := nontrivial.exists_pair_ne lemma exists_ne [nontrivial α] (x : α) : ∃ y, y ≠ x := begin rcases exists_pair_ne α with ⟨y, y', h⟩, by_cases hx : x = y, { rw ← hx at h, exact ⟨y', h.symm⟩ }, { exact ⟨y, ne.symm hx⟩ } end lemma nontrivial_of_ne (x y : α) (h : x ≠ y) : nontrivial α := ⟨⟨x, y, h⟩⟩ @[priority 100] -- see Note [lower instance priority] instance nontrivial.to_nonempty [nontrivial α] : nonempty α := let ⟨x, _⟩ := exists_pair_ne α in ⟨x⟩ /-- An inhabited type is either nontrivial, or has a unique element. -/ noncomputable def nontrivial_psum_unique (α : Type*) [inhabited α] : psum (nontrivial α) (unique α) := if h : nontrivial α then psum.inl h else psum.inr { default := default α, uniq := λ (x : α), begin change x = default α, contrapose! h, use [x, default α] end } lemma subsingleton_iff : subsingleton α ↔ ∀ (x y : α), x = y := ⟨by { introsI h, exact subsingleton.elim }, λ h, ⟨h⟩⟩ lemma not_nontrivial_iff_subsingleton : ¬(nontrivial α) ↔ subsingleton α := by { rw [nontrivial_iff, subsingleton_iff], push_neg, refl } /-- A type is either a subsingleton or nontrivial. -/ lemma subsingleton_or_nontrivial (α : Type*) : subsingleton α ∨ nontrivial α := by { rw [← not_nontrivial_iff_subsingleton, or_comm], exact classical.em _ } instance nontrivial_prod_left [nontrivial α] [nonempty β] : nontrivial (α × β) := begin inhabit β, rcases exists_pair_ne α with ⟨x, y, h⟩, use [(x, default β), (y, default β)], contrapose! h, exact congr_arg prod.fst h end instance nontrivial_prod_right [nontrivial α] [nonempty β] : nontrivial (β × α) := begin inhabit β, rcases exists_pair_ne α with ⟨x, y, h⟩, use [(default β, x), (default β, y)], contrapose! h, exact congr_arg prod.snd h end instance option.nontrivial [nonempty α] : nontrivial (option α) := by { inhabit α, use [none, some (default α)] } instance function.nontrivial [nonempty α] [nontrivial β] : nontrivial (α → β) := begin rcases exists_pair_ne β with ⟨x, y, h⟩, use [λ _, x, λ _, y], contrapose! h, inhabit α, exact congr_fun h (default α) end /-- Pushforward a `nontrivial` instance along an injective function. -/ protected lemma function.injective.nontrivial [nontrivial α] {f : α → β} (hf : function.injective f) : nontrivial β := let ⟨x, y, h⟩ := exists_pair_ne α in ⟨⟨f x, f y, hf.ne h⟩⟩ /-- Pullback a `nontrivial` instance along a surjective function. -/ protected lemma function.surjective.nontrivial [nontrivial β] {f : α → β} (hf : function.surjective f) : nontrivial α := begin rcases exists_pair_ne β with ⟨x, y, h⟩, rcases hf x with ⟨x', hx'⟩, rcases hf y with ⟨y', hy'⟩, have : x' ≠ y', by { contrapose! h, rw [← hx', ← hy', h] }, exact ⟨⟨x', y', this⟩⟩ end /-- An injective function from a nontrivial type has an argument at which it does not take a given value. -/ protected lemma function.injective.exists_ne [nontrivial α] {f : α → β} (hf : function.injective f) (y : β) : ∃ x, f x ≠ y := begin rcases exists_pair_ne α with ⟨x₁, x₂, hx⟩, by_cases h : f x₂ = y, { exact ⟨x₁, (hf.ne_iff' h).2 hx⟩ }, { exact ⟨x₂, h⟩ } end
850d73ae7e0644d618a910d633bfbf7881a893d4
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/group/pi.lean
0a7cf960e5fee11709a228b8b6c78f0c064b7df6
[]
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,548
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.pi import Mathlib.tactic.pi_instances import Mathlib.algebra.group.defs import Mathlib.algebra.group.hom import Mathlib.PostPort universes u v u_1 u_2 u_3 namespace Mathlib /-! # Pi instances for groups and monoids This file defines instances for group, monoid, semigroup and related structures on Pi types. -/ namespace pi protected instance semigroup {I : Type u} {f : I → Type v} [(i : I) → semigroup (f i)] : semigroup ((i : I) → f i) := semigroup.mk Mul.mul sorry protected instance add_comm_semigroup {I : Type u} {f : I → Type v} [(i : I) → add_comm_semigroup (f i)] : add_comm_semigroup ((i : I) → f i) := add_comm_semigroup.mk Add.add sorry sorry protected instance monoid {I : Type u} {f : I → Type v} [(i : I) → monoid (f i)] : monoid ((i : I) → f i) := monoid.mk Mul.mul sorry 1 sorry sorry protected instance add_comm_monoid {I : Type u} {f : I → Type v} [(i : I) → add_comm_monoid (f i)] : add_comm_monoid ((i : I) → f i) := add_comm_monoid.mk Add.add sorry 0 sorry sorry sorry protected instance sub_neg_add_monoid {I : Type u} {f : I → Type v} [(i : I) → sub_neg_monoid (f i)] : sub_neg_monoid ((i : I) → f i) := sub_neg_monoid.mk add_monoid.add sorry add_monoid.zero sorry sorry Neg.neg Sub.sub protected instance group {I : Type u} {f : I → Type v} [(i : I) → group (f i)] : group ((i : I) → f i) := group.mk Mul.mul sorry 1 sorry sorry has_inv.inv Div.div sorry protected instance comm_group {I : Type u} {f : I → Type v} [(i : I) → comm_group (f i)] : comm_group ((i : I) → f i) := comm_group.mk Mul.mul sorry 1 sorry sorry has_inv.inv Div.div sorry sorry protected instance left_cancel_semigroup {I : Type u} {f : I → Type v} [(i : I) → left_cancel_semigroup (f i)] : left_cancel_semigroup ((i : I) → f i) := left_cancel_semigroup.mk Mul.mul sorry sorry protected instance right_cancel_semigroup {I : Type u} {f : I → Type v} [(i : I) → right_cancel_semigroup (f i)] : right_cancel_semigroup ((i : I) → f i) := right_cancel_semigroup.mk Mul.mul sorry sorry protected instance mul_zero_class {I : Type u} {f : I → Type v} [(i : I) → mul_zero_class (f i)] : mul_zero_class ((i : I) → f i) := mul_zero_class.mk Mul.mul 0 sorry sorry protected instance comm_monoid_with_zero {I : Type u} {f : I → Type v} [(i : I) → comm_monoid_with_zero (f i)] : comm_monoid_with_zero ((i : I) → f i) := comm_monoid_with_zero.mk Mul.mul sorry 1 sorry sorry sorry 0 sorry sorry @[simp] theorem const_zero {α : Type u_1} {β : Type u_2} [HasZero β] : function.const α 0 = 0 := rfl @[simp] theorem comp_one {α : Type u_1} {β : Type u_2} {γ : Type u_3} [HasOne β] {f : β → γ} : f ∘ 1 = function.const α (f 1) := rfl @[simp] theorem one_comp {α : Type u_1} {β : Type u_2} {γ : Type u_3} [HasOne γ] {f : α → β} : 1 ∘ f = 1 := rfl end pi /-- Evaluation of functions into an indexed collection of monoids at a point is a monoid homomorphism. -/ def add_monoid_hom.apply {I : Type u} (f : I → Type v) [(i : I) → add_monoid (f i)] (i : I) : ((i : I) → f i) →+ f i := add_monoid_hom.mk (fun (g : (i : I) → f i) => g i) sorry sorry @[simp] theorem add_monoid_hom.apply_apply {I : Type u} (f : I → Type v) [(i : I) → add_monoid (f i)] (i : I) (g : (i : I) → f i) : coe_fn (add_monoid_hom.apply f i) g = g i := rfl /-- Coercion of a `monoid_hom` into a function is itself a `monoid_hom`. See also `monoid_hom.eval`. -/ @[simp] theorem monoid_hom.coe_fn_apply (α : Type u_1) (β : Type u_2) [monoid α] [comm_monoid β] (g : α →* β) : ∀ (ᾰ : α), coe_fn (monoid_hom.coe_fn α β) g ᾰ = coe_fn g ᾰ := fun (ᾰ : α) => Eq.refl (coe_fn (monoid_hom.coe_fn α β) g ᾰ) /-- The additive monoid homomorphism including a single additive monoid into a dependent family of additive monoids, as functions supported at a point. -/ def add_monoid_hom.single {I : Type u} (f : I → Type v) [DecidableEq I] [(i : I) → add_monoid (f i)] (i : I) : f i →+ (i : I) → f i := add_monoid_hom.mk (fun (x : f i) => pi.single i x) sorry sorry @[simp] theorem add_monoid_hom.single_apply {I : Type u} (f : I → Type v) [DecidableEq I] [(i : I) → add_monoid (f i)] {i : I} (x : f i) : coe_fn (add_monoid_hom.single f i) x = pi.single i x := rfl
22130117f5cbc11da23a8ff9baf7be37fefef17d
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/tests/lean/run/CommandExtOverlap.lean
551984dfe507f83eb26c4765b7fb2d96766e31bb
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
333
lean
new_frontend syntax [mycheck] "#check" (sepBy term ",") : command open Lean macro_rules [mycheck] | `(#check $es*) => let cmds := es.getSepElems.map $ fun e => Syntax.node `Lean.Parser.Command.check #[Syntax.atom {} "#check", e]; pure $ mkNullNode cmds #check true #check true, true #check true, 1, 3, fun (x : Nat) => x + 1
f89884afc880d8c4a4ce4218247ff1fb804428a3
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/algebra/group/to_additive.lean
976736af71778e3fe573f249a628270dd1e3dfce
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
9,737
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Yury Kudryashov. -/ import tactic.basic tactic.transport tactic.algebra /-! # Transport multiplicative to additive This file defines an attribute `to_additive` that can be used to automatically transport theorems and definitions (but not inductive types and structures) from multiplicative theory to additive theory. To use this attribute, just write ``` @[to_additive] theorem mul_comm' {α} [comm_semigroup α] (x y : α) : x * y = y * x := comm_semigroup.mul_comm ``` This code will generate a theorem named `add_comm'`. It is also possible to manually specify the name of the new declaration, and provide a documentation string. The transport tries to do the right thing in most cases using several heuristics described below. However, in some cases it fails, and requires manual intervention. ## Implementation notes ### Handling of hidden definitions Before transporting the “main” declaration `src`, `to_additive` first scans its type and value for names starting with `src`, and transports them. This includes auxiliary definitions like `src._match_1`, `src._proof_1`. After transporting the “main” declaration, `to_additive` transports its equational lemmas. ### Structure fields and constructors If `src` is a structure, then `to_additive` automatically adds structure fields to its mapping, and similarly for constructors of inductive types. For new structures this means that `to_additive` automatically handles coercions, and for old structures it does the same, if ancestry information is present in `@[ancestor]` attributes. ### Name generation * If `@[to_additive]` is called without a `name` argument, then the new name is autogenerated. First, it takes the longest prefix of the source name that is already known to `to_additive`, and replaces this prefix with its additive counterpart. Second, it takes the last part of the name (i.e., after the last dot), and replaces common name parts (“mul”, “one”, “inv”, “prod”) with their additive versions. * If `@[to_additive]` is called with a `name` argument `new_name` /without a dot/, then `to_additive` updates the prefix as described above, then replaces the last part of the name with `new_name`. * If `@[to_additive]` is called with a `name` argument `new_namespace.new_name` /with a dot/, then `to_additive` uses this new name as is. As a safety check, in the first two cases `to_additive` double checks that the new name differs from the original one. ### Missing features * Automatically transport structures and other inductive types. * Handle `protected` attribute. Currently all new definitions are public. * For structures, automatically generate theorems like `group α ↔ add_group (additive α)`. * Mapping of prefixes that do not correspond to any definition, see `quotient_group`. * Rewrite rules for the last part of the name that work in more cases. E.g., we can replace `monoid` with `add_monoid` etc. -/ namespace to_additive open tactic exceptional @[user_attribute] meta def aux_attr : user_attribute (name_map name) name := { name := `to_additive_aux, descr := "Auxiliary attribute for `to_additive`. DON'T USE IT", cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n', let n := match n' with | name.mk_string s pre := if s = "_to_additive" then pre else n' | _ := n' end in dict.insert n <$> aux_attr.get_param n') mk_name_map, []⟩, parser := lean.parser.ident } meta def map_namespace (src tgt : name) : command := do decl ← get_decl `bool, -- random choice let n := src.mk_string "_to_additive", let decl := decl.update_name n, add_decl decl, aux_attr.set n tgt tt @[derive has_reflect] structure value_type := (tgt : name) (doc : option string) meta def tokens_dict : native.rb_map string string := native.rb_map.of_list $ [("mul", "add"), ("one", "zero"), ("inv", "neg"), ("prod", "sum")] meta def guess_name : string → string := string.map_tokens '_' $ list.map $ string.map_tokens ''' $ list.map $ λ s, (tokens_dict.find s).get_or_else s meta def target_name (src tgt : name) (dict : name_map name) : tactic name := (if tgt.get_prefix ≠ name.anonymous -- `tgt` is a full name then pure tgt else match src with | (name.mk_string s pre) := do let tgt_auto := guess_name s, guard (tgt.to_string ≠ tgt_auto) <|> trace ("`to_additive " ++ src.to_string ++ "`: remove `name` argument"), pure $ name.mk_string (if tgt = name.anonymous then tgt_auto else tgt.to_string) (pre.map_prefix dict.find) | _ := fail ("to_additive: can't transport " ++ src.to_string) end) >>= (λ res, if res = src then fail ("to_additive: can't transport " ++ src.to_string ++ " to itself") else pure res) meta def parser : lean.parser value_type := do tgt ← optional lean.parser.ident, e ← optional interactive.types.texpr, doc ← match e with | some pe := some <$> ((to_expr pe >>= eval_expr string) : tactic string) | none := pure none end, return ⟨tgt.get_or_else name.anonymous, doc⟩ private meta def proceed_fields_aux (src tgt : name) (prio : ℕ) (f : name → tactic (list string)) : command := do src_fields ← f src, tgt_fields ← f tgt, guard (src_fields.length = tgt_fields.length) <|> fail ("Failed to map fields of " ++ src.to_string), (src_fields.zip tgt_fields).mmap' $ λ names, guard (names.fst = names.snd) <|> aux_attr.set (src.append names.fst) (tgt.append names.snd) tt prio meta def proceed_fields (env : environment) (src tgt : name) (prio : ℕ) : command := let aux := proceed_fields_aux src tgt prio in do aux (λ n, pure $ list.map name.to_string $ (env.structure_fields n).get_or_else []) >> aux (λ n, (list.map (λ (x : name), "to_" ++ x.to_string) <$> (ancestor_attr.get_param n <|> pure []))) >> aux (λ n, (env.constructors_of n).mmap $ λ cs, match cs with | (name.mk_string s pre) := (guard (pre = n) <|> fail "Bad constructor name") >> pure s | _ := fail "Bad constructor name" end) @[user_attribute] protected meta def attr : user_attribute unit value_type := { name := `to_additive, descr := "Transport multiplicative to additive", parser := parser, after_set := some $ λ src prio persistent, do guard persistent <|> fail "`to_additive` can't be used as a local attribute", env ← get_env, val ← attr.get_param src, dict ← aux_attr.get_cache, tgt ← target_name src val.tgt dict, aux_attr.set src tgt tt, let dict := dict.insert src tgt, if env.contains tgt then proceed_fields env src tgt prio else do transport_with_prefix_dict dict src tgt [`reducible, `simp, `instance, `refl, `symm, `trans, `elab_as_eliminator], match val.doc with | some doc := add_doc_string tgt doc | none := skip end } end to_additive /- map operations -/ attribute [to_additive] has_mul has_one has_inv /- map structures -/ attribute [to_additive add_semigroup] semigroup attribute [to_additive add_comm_semigroup] comm_semigroup attribute [to_additive add_left_cancel_semigroup] left_cancel_semigroup attribute [to_additive add_right_cancel_semigroup] right_cancel_semigroup attribute [to_additive add_monoid] monoid attribute [to_additive add_comm_monoid] comm_monoid attribute [to_additive add_group] group attribute [to_additive add_comm_group] comm_group /- map theorems -/ attribute [to_additive] mul_assoc attribute [to_additive add_semigroup_to_is_eq_associative] semigroup_to_is_associative attribute [to_additive] mul_comm attribute [to_additive add_comm_semigroup_to_is_eq_commutative] comm_semigroup_to_is_commutative attribute [to_additive] mul_left_comm attribute [to_additive] mul_right_comm attribute [to_additive] mul_left_cancel attribute [to_additive] mul_right_cancel attribute [to_additive] mul_left_cancel_iff attribute [to_additive] mul_right_cancel_iff attribute [to_additive] one_mul attribute [to_additive] mul_one attribute [to_additive] mul_left_inv attribute [to_additive] inv_mul_self attribute [to_additive] inv_mul_cancel_left attribute [to_additive] inv_mul_cancel_right attribute [to_additive] inv_eq_of_mul_eq_one attribute [to_additive neg_zero] one_inv attribute [to_additive] inv_inv attribute [to_additive] mul_right_inv attribute [to_additive] mul_inv_self attribute [to_additive] inv_inj attribute [to_additive] group.mul_left_cancel attribute [to_additive] group.mul_right_cancel attribute [to_additive to_left_cancel_add_semigroup] group.to_left_cancel_semigroup attribute [to_additive to_right_cancel_add_semigroup] group.to_right_cancel_semigroup attribute [to_additive] mul_inv_cancel_left attribute [to_additive] mul_inv_cancel_right attribute [to_additive neg_add_rev] mul_inv_rev attribute [to_additive] eq_inv_of_eq_inv attribute [to_additive] eq_inv_of_mul_eq_one attribute [to_additive] eq_mul_inv_of_mul_eq attribute [to_additive] eq_inv_mul_of_mul_eq attribute [to_additive] inv_mul_eq_of_eq_mul attribute [to_additive] mul_inv_eq_of_eq_mul attribute [to_additive] eq_mul_of_mul_inv_eq attribute [to_additive] eq_mul_of_inv_mul_eq attribute [to_additive] mul_eq_of_eq_inv_mul attribute [to_additive] mul_eq_of_eq_mul_inv attribute [to_additive neg_add] mul_inv
c0024f1b1e57a91bb3dc3aafca12e9690ef97d79
82e44445c70db0f03e30d7be725775f122d72f3e
/src/analysis/convex/caratheodory.lean
3c377980e20b38a5d2b57f90110fda6c6c5859ac
[ "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,872
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin, Scott Morrison -/ import analysis.convex.basic /-! # Carathéodory's convexity theorem This file is devoted to proving Carathéodory's convexity theorem: The convex hull of a set `s` in ℝᵈ is the union of the convex hulls of the (d+1)-tuples in `s`. ## Main results: * `convex_hull_eq_union`: Carathéodory's convexity theorem ## Implementation details This theorem was formalized as part of the Sphere Eversion project. ## Tags convex hull, caratheodory -/ universes u open set finset finite_dimensional open_locale big_operators variables {E : Type u} [add_comm_group E] [module ℝ E] [finite_dimensional ℝ E] namespace caratheodory /-- If `x` is in the convex hull of some finset `t` with strictly more than `finrank + 1` elements, then it is in the union of the convex hulls of the finsets `t.erase y` for `y ∈ t`. -/ lemma mem_convex_hull_erase [decidable_eq E] {t : finset E} (h : finrank ℝ E + 1 < t.card) {x : E} (m : x ∈ convex_hull (↑t : set E)) : ∃ (y : (↑t : set E)), x ∈ convex_hull (↑(t.erase y) : set E) := begin simp only [finset.convex_hull_eq, mem_set_of_eq] at m ⊢, obtain ⟨f, fpos, fsum, rfl⟩ := m, obtain ⟨g, gcombo, gsum, gpos⟩ := exists_relation_sum_zero_pos_coefficient_of_dim_succ_lt_card h, clear h, let s := t.filter (λ z : E, 0 < g z), obtain ⟨i₀, mem, w⟩ : ∃ i₀ ∈ s, ∀ i ∈ s, f i₀ / g i₀ ≤ f i / g i, { apply s.exists_min_image (λ z, f z / g z), obtain ⟨x, hx, hgx⟩ : ∃ x ∈ t, 0 < g x := gpos, exact ⟨x, mem_filter.mpr ⟨hx, hgx⟩⟩, }, have hg : 0 < g i₀ := by { rw mem_filter at mem, exact mem.2 }, have hi₀ : i₀ ∈ t := filter_subset _ _ mem, let k : E → ℝ := λ z, f z - (f i₀ / g i₀) * g z, have hk : k i₀ = 0 := by field_simp [k, ne_of_gt hg], have ksum : ∑ e in t.erase i₀, k e = 1, { calc ∑ e in t.erase i₀, k e = ∑ e in t, k e : by conv_rhs { rw [← insert_erase hi₀, sum_insert (not_mem_erase i₀ t), hk, zero_add], } ... = ∑ e in t, (f e - f i₀ / g i₀ * g e) : rfl ... = 1 : by rw [sum_sub_distrib, fsum, ← mul_sum, gsum, mul_zero, sub_zero] }, refine ⟨⟨i₀, hi₀⟩, k, _, ksum, _⟩, { simp only [and_imp, sub_nonneg, mem_erase, ne.def, subtype.coe_mk], intros e hei₀ het, by_cases hes : e ∈ s, { have hge : 0 < g e := by { rw mem_filter at hes, exact hes.2 }, rw ← le_div_iff hge, exact w _ hes, }, { calc _ ≤ 0 : mul_nonpos_of_nonneg_of_nonpos _ _ -- prove two goals below ... ≤ f e : fpos e het, { apply div_nonneg (fpos i₀ (mem_of_subset (filter_subset _ t) mem)) (le_of_lt hg) }, { simpa only [mem_filter, het, true_and, not_lt] using hes }, } }, { simp only [subtype.coe_mk, center_mass_eq_of_sum_1 _ id ksum, id], calc ∑ e in t.erase i₀, k e • e = ∑ e in t, k e • e : sum_erase _ (by rw [hk, zero_smul]) ... = ∑ e in t, (f e - f i₀ / g i₀ * g e) • e : rfl ... = t.center_mass f id : _, simp only [sub_smul, mul_smul, sum_sub_distrib, ← smul_sum, gcombo, smul_zero, sub_zero, center_mass, fsum, inv_one, one_smul, id.def], }, end /-- The convex hull of a finset `t` with `finrank ℝ E + 1 < t.card` is equal to the union of the convex hulls of the finsets `t.erase x` for `x ∈ t`. -/ lemma step [decidable_eq E] (t : finset E) (h : finrank ℝ E + 1 < t.card) : convex_hull (↑t : set E) = ⋃ (x : (↑t : set E)), convex_hull ↑(t.erase x) := begin apply set.subset.antisymm, { intros x m', obtain ⟨y, m⟩ := mem_convex_hull_erase h m', exact mem_Union.2 ⟨y, m⟩, }, { refine Union_subset _, intro x, apply convex_hull_mono, apply erase_subset, } end /-- The convex hull of a finset `t` with `finrank ℝ E + 1 < t.card` is contained in the union of the convex hulls of the finsets `t' ⊆ t` with `t'.card ≤ finrank ℝ E + 1`. -/ lemma shrink' (t : finset E) (k : ℕ) (h : t.card = finrank ℝ E + 1 + k) : convex_hull (↑t : set E) ⊆ ⋃ (t' : finset E) (w : t' ⊆ t) (b : t'.card ≤ finrank ℝ E + 1), convex_hull ↑t' := begin induction k with k ih generalizing t, { apply subset_subset_Union t, apply subset_subset_Union (set.subset.refl _), exact subset_subset_Union (le_of_eq h) (subset.refl _), }, { classical, rw step _ (by { rw h, simp, } : finrank ℝ E + 1 < t.card), apply Union_subset, intro i, transitivity, { apply ih, rw [card_erase_of_mem, h, nat.pred_succ], exact i.2, }, { apply Union_subset_Union, intro t', apply Union_subset_Union_const, exact λ h, set.subset.trans h (erase_subset _ _), } } end /-- The convex hull of any finset `t` is contained in the union of the convex hulls of the finsets `t' ⊆ t` with `t'.card ≤ finrank ℝ E + 1`. -/ lemma shrink (t : finset E) : convex_hull (↑t : set E) ⊆ ⋃ (t' : finset E) (w : t' ⊆ t) (b : t'.card ≤ finrank ℝ E + 1), convex_hull ↑t' := begin by_cases h : t.card ≤ finrank ℝ E + 1, { apply subset_subset_Union t, apply subset_subset_Union (set.subset.refl _), exact subset_subset_Union h (set.subset.refl _), }, push_neg at h, obtain ⟨k, w⟩ := le_iff_exists_add.mp (le_of_lt h), clear h, exact shrink' _ _ w, end end caratheodory /-- One inclusion of **Carathéodory's convexity theorem**. The convex hull of a set `s` in ℝᵈ is contained in the union of the convex hulls of the (d+1)-tuples in `s`. -/ lemma convex_hull_subset_union (s : set E) : convex_hull s ⊆ ⋃ (t : finset E) (w : ↑t ⊆ s) (b : t.card ≤ finrank ℝ E + 1), convex_hull ↑t := begin -- First we replace `convex_hull s` with the union of the convex hulls of finite subsets, rw convex_hull_eq_union_convex_hull_finite_subsets, -- and prove the inclusion for each of those. apply Union_subset, intro r, apply Union_subset, intro h, -- Second, for each convex hull of a finite subset, we shrink it. refine subset.trans (caratheodory.shrink _) _, -- After that it's just shuffling unions around. refine Union_subset_Union (λ t, _), exact Union_subset_Union2 (λ htr, ⟨subset.trans htr h, subset.refl _⟩) end /-- **Carathéodory's convexity theorem**. The convex hull of a set `s` in ℝᵈ is the union of the convex hulls of the (d+1)-tuples in `s`. -/ theorem convex_hull_eq_union (s : set E) : convex_hull s = ⋃ (t : finset E) (w : ↑t ⊆ s) (b : t.card ≤ finrank ℝ E + 1), convex_hull ↑t := begin apply set.subset.antisymm, { apply convex_hull_subset_union, }, iterate 3 { convert Union_subset _, intro, }, exact convex_hull_mono ‹_›, end /-- A more explicit formulation of **Carathéodory's convexity theorem**, writing an element of a convex hull as the center of mass of an explicit `finset` with cardinality at most `dim + 1`. -/ theorem eq_center_mass_card_le_dim_succ_of_mem_convex_hull {s : set E} {x : E} (h : x ∈ convex_hull s) : ∃ (t : finset E) (w : ↑t ⊆ s) (b : t.card ≤ finrank ℝ E + 1) (f : E → ℝ), (∀ y ∈ t, 0 ≤ f y) ∧ t.sum f = 1 ∧ t.center_mass f id = x := begin rw convex_hull_eq_union at h, simp only [exists_prop, mem_Union] at h, obtain ⟨t, w, b, m⟩ := h, refine ⟨t, w, b, _⟩, rw finset.convex_hull_eq at m, simpa only [exists_prop] using m, end /-- A variation on **Carathéodory's convexity theorem**, writing an element of a convex hull as a center of mass of an explicit `finset` with cardinality at most `dim + 1`, where all coefficients in the center of mass formula are strictly positive. (This is proved using `eq_center_mass_card_le_dim_succ_of_mem_convex_hull`, and discarding any elements of the set with coefficient zero.) -/ theorem eq_pos_center_mass_card_le_dim_succ_of_mem_convex_hull {s : set E} {x : E} (h : x ∈ convex_hull s) : ∃ (t : finset E) (w : ↑t ⊆ s) (b : t.card ≤ finrank ℝ E + 1) (f : E → ℝ), (∀ y ∈ t, 0 < f y) ∧ t.sum f = 1 ∧ t.center_mass f id = x := begin obtain ⟨t, w, b, f, ⟨pos, sum, center⟩⟩ := eq_center_mass_card_le_dim_succ_of_mem_convex_hull h, let t' := t.filter (λ z, 0 < f z), have t'sum : t'.sum f = 1, { rw ← sum, exact sum_filter_of_ne (λ x hxt hfx, (pos x hxt).lt_of_ne hfx.symm) }, refine ⟨t', _, _, f, ⟨_, t'sum, _⟩⟩, { exact subset.trans (filter_subset _ t) w, }, { exact (card_filter_le _ _).trans b, }, { exact λ y H, (mem_filter.mp H).right, }, { rw ← center, simp only [center_mass, t'sum, sum, inv_one, one_smul, id.def], refine sum_filter_of_ne (λ x hxt hfx, (pos x hxt).lt_of_ne $ λ hf₀, _), rw [← hf₀, zero_smul] at hfx, exact hfx rfl }, end
e6f0a9ae70401f45751b308788c01fde622661ab
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/Elab/MutualDef.lean
b8f401223f91227472891c0a149f7fa7b0a6eb1a
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
26,324
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.Closure import Lean.Meta.Check import Lean.Elab.Command import Lean.Elab.DefView import Lean.Elab.PreDefinition namespace Lean.Elab /- DefView after elaborating the header. -/ structure DefViewElabHeader := (ref : Syntax) (modifiers : Modifiers) (kind : DefKind) (shortDeclName : Name) (declName : Name) (levelNames : List Name) (numParams : Nat) (type : Expr) -- including the parameters (valueStx : Syntax) instance : Inhabited DefViewElabHeader := ⟨⟨arbitrary _, {}, DefKind.«def», arbitrary _, arbitrary _, [], 0, arbitrary _, arbitrary _⟩⟩ namespace Term open Meta private def checkModifiers (m₁ m₂ : Modifiers) : TermElabM Unit := do unless m₁.isUnsafe == m₂.isUnsafe do throwError "cannot mix unsafe and safe definitions" unless m₁.isNoncomputable == m₂.isNoncomputable do throwError "cannot mix computable and non-computable definitions" unless m₁.isPartial == m₂.isPartial do throwError "cannot mix partial and non-partial definitions" private def checkKinds (k₁ k₂ : DefKind) : TermElabM Unit := do unless k₁.isExample == k₂.isExample do throwError "cannot mix examples and definitions" -- Reason: we should discard examples unless k₁.isTheorem == k₂.isTheorem do throwError "cannot mix theorems and definitions" -- Reason: we will eventually elaborate theorems in `Task`s. private def check (prevHeaders : Array DefViewElabHeader) (newHeader : DefViewElabHeader) : TermElabM Unit := do if newHeader.kind.isTheorem && newHeader.modifiers.isUnsafe then throwError "'unsafe' theorems are not allowed" if newHeader.kind.isTheorem && newHeader.modifiers.isPartial then throwError "'partial' theorems are not allowed, 'partial' is a code generation directive" if newHeader.kind.isTheorem && newHeader.modifiers.isNoncomputable then throwError "'theorem' subsumes 'noncomputable', code is not generated for theorems" if newHeader.modifiers.isNoncomputable && newHeader.modifiers.isUnsafe then throwError "'noncomputable unsafe' is not allowed" if newHeader.modifiers.isNoncomputable && newHeader.modifiers.isPartial then throwError "'noncomputable partial' is not allowed" if newHeader.modifiers.isPartial && newHeader.modifiers.isUnsafe then throwError "'unsafe' subsumes 'partial'" if h : 0 < prevHeaders.size then let firstHeader := prevHeaders.get ⟨0, h⟩ try unless newHeader.levelNames == firstHeader.levelNames do throwError "universe parameters mismatch" checkModifiers newHeader.modifiers firstHeader.modifiers checkKinds newHeader.kind firstHeader.kind catch | Exception.error ref msg => throw (Exception.error ref msg!"invalid mutually recursive definitions, {msg}") | ex => throw ex else pure () private def registerFailedToInferDefTypeInfo (type : Expr) (ref : Syntax) : TermElabM Unit := registerCustomErrorIfMVar type ref "failed to infer definition type" private def elabFunType (ref : Syntax) (xs : Array Expr) (view : DefView) : TermElabM Expr := do match view.type? with | some typeStx => let type ← elabType typeStx synthesizeSyntheticMVarsNoPostponing let type ← instantiateMVars type registerFailedToInferDefTypeInfo type typeStx mkForallFVars xs type | none => let hole := mkHole ref let type ← elabType hole registerFailedToInferDefTypeInfo type ref mkForallFVars xs type private def elabHeaders (views : Array DefView) : TermElabM (Array DefViewElabHeader) := do let mut headers := #[] for view in views do let newHeader ← withRef view.ref do let ⟨shortDeclName, declName, levelNames⟩ ← expandDeclId (← getCurrNamespace) (← getLevelNames) view.declId view.modifiers applyAttributesAt declName view.modifiers.attrs AttributeApplicationTime.beforeElaboration withLevelNames levelNames $ elabBinders view.binders.getArgs fun xs => do let refForElabFunType := view.value let type ← elabFunType refForElabFunType xs view let newHeader := { ref := view.ref, modifiers := view.modifiers, kind := view.kind, shortDeclName := shortDeclName, declName := declName, levelNames := levelNames, numParams := xs.size, type := type, valueStx := view.value : DefViewElabHeader } check headers newHeader pure newHeader headers := headers.push newHeader pure headers private partial def withFunLocalDecls {α} (headers : Array DefViewElabHeader) (k : Array Expr → TermElabM α) : TermElabM α := let rec loop (i : Nat) (fvars : Array Expr) := do if h : i < headers.size then let header := headers.get ⟨i, h⟩ withLocalDecl header.shortDeclName BinderInfo.auxDecl header.type fun fvar => loop (i+1) (fvars.push fvar) else k fvars loop 0 #[] /- Recall that ``` def matchAlts (optionalFirstBar := true) : Parser := withPosition $ fun pos => (if optionalFirstBar then optional "| " else "| ") >> sepBy1 matchAlt (checkColGe pos.column "alternatives must be indented" >> "|") def declValSimple := parser! " := " >> termParser def declValEqns := parser! Term.matchAlts false def declVal := declValSimple <|> declValEqns ``` -/ private def declValToTerm (declVal : Syntax) : MacroM Syntax := if declVal.isOfKind `Lean.Parser.Command.declValSimple then pure declVal[1] else if declVal.isOfKind `Lean.Parser.Command.declValEqns then expandMatchAltsIntoMatch declVal declVal[0] else Macro.throwError declVal "unexpected definition value" private def elabFunValues (headers : Array DefViewElabHeader) : TermElabM (Array Expr) := headers.mapM fun header => withDeclName header.declName $ withLevelNames header.levelNames do let valStx ← liftMacroM $ declValToTerm header.valueStx forallBoundedTelescope header.type header.numParams fun xs type => do let val ← elabTermEnsuringType valStx type mkLambdaFVars xs val private def collectUsed (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) : StateRefT CollectFVars.State TermElabM Unit := do headers.forM fun header => collectUsedFVars header.type values.forM collectUsedFVars toLift.forM fun letRecToLift => do collectUsedFVars letRecToLift.type collectUsedFVars letRecToLift.val private def removeUnusedVars (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) : TermElabM (LocalContext × LocalInstances × Array Expr) := do let (_, used) ← (collectUsed headers values toLift).run {} removeUnused vars used private def withUsed {α} (vars : Array Expr) (headers : Array DefViewElabHeader) (values : Array Expr) (toLift : List LetRecToLift) (k : Array Expr → TermElabM α) : TermElabM α := do let (lctx, localInsts, vars) ← removeUnusedVars vars headers values toLift withLCtx lctx localInsts $ k vars private def isExample (views : Array DefView) : Bool := views.any (·.kind.isExample) private def isTheorem (views : Array DefView) : Bool := views.any (·.kind.isTheorem) private def instantiateMVarsAtHeader (header : DefViewElabHeader) : TermElabM DefViewElabHeader := do let type ← instantiateMVars header.type pure { header with type := type } private def instantiateMVarsAtLetRecToLift (toLift : LetRecToLift) : TermElabM LetRecToLift := do let type ← instantiateMVars toLift.type let val ← instantiateMVars toLift.val pure { toLift with type := type, val := val } private def typeHasRecFun (type : Expr) (funFVars : Array Expr) (letRecsToLift : List LetRecToLift) : Option FVarId := let occ? := type.find? fun e => match e with | Expr.fvar fvarId _ => funFVars.contains e || letRecsToLift.any fun toLift => toLift.fvarId == fvarId | _ => false match occ? with | some (Expr.fvar fvarId _) => some fvarId | _ => none private def getFunName (fvarId : FVarId) (letRecsToLift : List LetRecToLift) : TermElabM Name := do match (← findLocalDecl? fvarId) with | some decl => pure decl.userName | none => /- Recall that the FVarId of nested let-recs are not in the current local context. -/ match letRecsToLift.findSome? fun toLift => if toLift.fvarId == fvarId then some toLift.shortDeclName else none with | none => throwError "unknown function" | some n => pure n /- Ensures that the of let-rec definition types do not contain functions being defined. In principle, this test can be improved. We could perform it after we separate the set of functions is strongly connected components. However, this extra complication doesn't seem worth it. -/ private def checkLetRecsToLiftTypes (funVars : Array Expr) (letRecsToLift : List LetRecToLift) : TermElabM Unit := letRecsToLift.forM fun toLift => match typeHasRecFun toLift.type funVars letRecsToLift with | none => pure () | some fvarId => do let fnName ← getFunName fvarId letRecsToLift throwErrorAt! toLift.ref "invalid type in 'let rec', it uses '{fnName}' which is being defined simultaneously" namespace MutualClosure /- A mapping from FVarId to Set of FVarIds. -/ abbrev UsedFVarsMap := NameMap NameSet /- Create the `UsedFVarsMap` mapping that takes the variable id for the mutually recursive functions being defined to the set of free variables in its definition. For `mainFVars`, this is just the set of section variables `sectionVars` used. For nested let-rec functions, we collect their free variables. Recall that a `let rec` expressions are encoded as follows in the elaborator. ```lean let rec f : A := t, g : B := s; body ``` is encoded as ```lean let f : A := ?m₁; let g : B := ?m₂; body ``` where `?m₁` and `?m₂` are synthetic opaque metavariables. That are assigned by this module. We may have nested `let rec`s. ```lean let rec f : A := let rec g : B := t; s; body ``` is encoded as ```lean let f : A := ?m₁; body ``` and the body of `f` is stored the field `val` of a `LetRecToLift`. For the example above, we would have a `LetRecToLift` containing: ``` { mvarId := m₁, val := `(let g : B := ?m₂; body) ... } ``` Note that `g` is not a free variable at `(let g : B := ?m₂; body)`. We recover the fact that `f` depends on `g` because it contains `m₂` -/ private def mkInitialUsedFVarsMap (mctx : MetavarContext) (sectionVars : Array Expr) (mainFVarIds : Array FVarId) (letRecsToLift : List LetRecToLift) : UsedFVarsMap := do let mut sectionVarSet := {} for var in sectionVars do sectionVarSet := sectionVarSet.insert var.fvarId! let mut usedFVarMap := {} for mainFVarId in mainFVarIds do usedFVarMap := usedFVarMap.insert mainFVarId sectionVarSet for toLift in letRecsToLift do let state := Lean.collectFVars {} toLift.val let state := Lean.collectFVars state toLift.type let mut set := state.fvarSet /- toLift.val may contain metavariables that are placeholders for nested let-recs. We should collect the fvarId for the associated let-rec because we need this information to compute the fixpoint later. -/ let mvarIds := (toLift.val.collectMVars {}).result for mvarId in mvarIds do match letRecsToLift.findSome? fun (toLift : LetRecToLift) => if toLift.mvarId == mctx.getDelayedRoot mvarId then some toLift.fvarId else none with | some fvarId => set := set.insert fvarId | none => pure () usedFVarMap := usedFVarMap.insert toLift.fvarId set pure usedFVarMap /- The let-recs may invoke each other. Example: ``` let rec f (x : Nat) := g x + y g : Nat → Nat | 0 => 1 | x+1 => f x + z ``` `y` is free variable in `f`, and `z` is a free variable in `g`. To close `f` and `g`, `y` and `z` must be in the closure of both. That is, we need to generate the top-level definitions. ``` def f (y z x : Nat) := g y z x + y def g (y z : Nat) : Nat → Nat | 0 => 1 | x+1 => f y z x + z ``` -/ namespace FixPoint structure State := (usedFVarsMap : UsedFVarsMap := {}) (modified : Bool := false) abbrev M := ReaderT (List FVarId) $ StateM State private def isModified : M Bool := do pure (← get).modified private def resetModified : M Unit := modify fun s => { s with modified := false } private def markModified : M Unit := modify fun s => { s with modified := true } private def getUsedFVarsMap : M UsedFVarsMap := do pure (← get).usedFVarsMap private def modifyUsedFVars (f : UsedFVarsMap → UsedFVarsMap) : M Unit := modify fun s => { s with usedFVarsMap := f s.usedFVarsMap } -- merge s₂ into s₁ private def merge (s₁ s₂ : NameSet) : M NameSet := s₂.foldM (init := s₁) fun s₁ k => do if s₁.contains k then pure s₁ else markModified pure $ s₁.insert k private def updateUsedVarsOf (fvarId : FVarId) : M Unit := do let usedFVarsMap ← getUsedFVarsMap match usedFVarsMap.find? fvarId with | none => pure () | some fvarIds => let fvarIdsNew ← fvarIds.foldM (init := fvarIds) fun fvarIdsNew fvarId' => if fvarId == fvarId' then pure fvarIdsNew else match usedFVarsMap.find? fvarId' with | none => pure fvarIdsNew /- We are being sloppy here `otherFVarIds` may contain free variables that are not in the context of the let-rec associated with fvarId. We filter these out-of-context free variables later. -/ | some otherFVarIds => merge fvarIdsNew otherFVarIds modifyUsedFVars fun usedFVars => usedFVars.insert fvarId fvarIdsNew private partial def fixpoint : Unit → M Unit | _ => do resetModified let letRecFVarIds ← read letRecFVarIds.forM updateUsedVarsOf if (← isModified) then fixpoint () def run (letRecFVarIds : List FVarId) (usedFVarsMap : UsedFVarsMap) : UsedFVarsMap := let (_, s) := ((fixpoint ()).run letRecFVarIds).run { usedFVarsMap := usedFVarsMap } s.usedFVarsMap end FixPoint abbrev FreeVarMap := NameMap (Array FVarId) private def mkFreeVarMap (mctx : MetavarContext) (sectionVars : Array Expr) (mainFVarIds : Array FVarId) (recFVarIds : Array FVarId) (letRecsToLift : List LetRecToLift) : FreeVarMap := do let usedFVarsMap := mkInitialUsedFVarsMap mctx sectionVars mainFVarIds letRecsToLift let letRecFVarIds := letRecsToLift.map fun toLift => toLift.fvarId let usedFVarsMap := FixPoint.run letRecFVarIds usedFVarsMap let mut freeVarMap := {} for toLift in letRecsToLift do let lctx := toLift.lctx let fvarIdsSet := (usedFVarsMap.find? toLift.fvarId).get! let fvarIds := fvarIdsSet.fold (init := #[]) fun fvarIds fvarId => if lctx.contains fvarId && !recFVarIds.contains fvarId then fvarIds.push fvarId else fvarIds freeVarMap := freeVarMap.insert toLift.fvarId fvarIds pure freeVarMap structure ClosureState := (newLocalDecls : Array LocalDecl := #[]) (localDecls : Array LocalDecl := #[]) (newLetDecls : Array LocalDecl := #[]) (exprArgs : Array Expr := #[]) private def pickMaxFVar? (lctx : LocalContext) (fvarIds : Array FVarId) : Option FVarId := fvarIds.getMax? fun fvarId₁ fvarId₂ => (lctx.get! fvarId₁).index < (lctx.get! fvarId₂).index private def preprocess (e : Expr) : TermElabM Expr := do let e ← instantiateMVars e -- which let-decls are dependent. We say a let-decl is dependent if its lambda abstraction is type incorrect. Meta.check e pure e /- Push free variables in `s` to `toProcess` if they are not already there. -/ private def pushNewVars (toProcess : Array FVarId) (s : CollectFVars.State) : Array FVarId := s.fvarSet.fold (init := toProcess) fun toProcess fvarId => if toProcess.contains fvarId then toProcess else toProcess.push fvarId private def pushLocalDecl (toProcess : Array FVarId) (fvarId : FVarId) (userName : Name) (type : Expr) (bi := BinderInfo.default) : StateRefT ClosureState TermElabM (Array FVarId) := do let type ← preprocess type modify fun s => { s with newLocalDecls := s.newLocalDecls.push $ LocalDecl.cdecl (arbitrary _) fvarId userName type bi, exprArgs := s.exprArgs.push (mkFVar fvarId) } pure $ pushNewVars toProcess (collectFVars {} type) private partial def mkClosureForAux (toProcess : Array FVarId) : StateRefT ClosureState TermElabM Unit := do let lctx ← getLCtx match pickMaxFVar? lctx toProcess with | none => pure () | some fvarId => trace[Elab.definition.mkClosure]! "toProcess: {toProcess.map mkFVar}, maxVar: {mkFVar fvarId}" let toProcess := toProcess.erase fvarId let localDecl ← getLocalDecl fvarId match localDecl with | LocalDecl.cdecl _ _ userName type bi => let toProcess ← pushLocalDecl toProcess fvarId userName type bi mkClosureForAux toProcess | LocalDecl.ldecl _ _ userName type val _ => let zetaFVarIds ← getZetaFVarIds if !zetaFVarIds.contains fvarId then /- Non-dependent let-decl. See comment at src/Lean/Meta/Closure.lean -/ let toProcess ← pushLocalDecl toProcess fvarId userName type mkClosureForAux toProcess else /- Dependent let-decl. -/ let type ← preprocess type let val ← preprocess val modify fun s => { s with newLetDecls := s.newLetDecls.push $ LocalDecl.ldecl (arbitrary _) fvarId userName type val false, /- We don't want to interleave let and lambda declarations in our closure. So, we expand any occurrences of fvarId at `newLocalDecls` and `localDecls` -/ newLocalDecls := s.newLocalDecls.map (replaceFVarIdAtLocalDecl fvarId val), localDecls := s.localDecls.map (replaceFVarIdAtLocalDecl fvarId val) } mkClosureForAux (pushNewVars toProcess (collectFVars (collectFVars {} type) val)) private partial def mkClosureFor (freeVars : Array FVarId) (localDecls : Array LocalDecl) : TermElabM ClosureState := do let (_, s) ← (mkClosureForAux freeVars).run { localDecls := localDecls } pure { s with newLocalDecls := s.newLocalDecls.reverse, newLetDecls := s.newLetDecls.reverse, exprArgs := s.exprArgs.reverse } structure LetRecClosure := (localDecls : Array LocalDecl) (closed : Expr) -- expression used to replace occurrences of the let-rec FVarId (toLift : LetRecToLift) private def mkLetRecClosureFor (toLift : LetRecToLift) (freeVars : Array FVarId) : TermElabM LetRecClosure := do let lctx := toLift.lctx withLCtx lctx toLift.localInstances do lambdaTelescope toLift.val fun xs val => do let type ← instantiateForall toLift.type xs let lctx ← getLCtx let s ← mkClosureFor freeVars $ xs.map fun x => lctx.get! x.fvarId! let type := Closure.mkForall s.localDecls $ Closure.mkForall s.newLetDecls type let val := Closure.mkLambda s.localDecls $ Closure.mkLambda s.newLetDecls val let c := mkAppN (Lean.mkConst toLift.declName) s.exprArgs assignExprMVar toLift.mvarId c pure ⟨s.newLocalDecls, c, { toLift with val := val, type := type }⟩ private def mkLetRecClosures (letRecsToLift : List LetRecToLift) (freeVarMap : FreeVarMap) : TermElabM (List LetRecClosure) := letRecsToLift.mapM fun toLift => mkLetRecClosureFor toLift (freeVarMap.find? toLift.fvarId).get! /- Mapping from FVarId of mutually recursive functions being defined to "closure" expression. -/ abbrev Replacement := NameMap Expr def insertReplacementForMainFns (r : Replacement) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) : Replacement := mainFVars.size.fold (init := r) fun i r => r.insert (mainFVars.get! i).fvarId! (mkAppN (Lean.mkConst (mainHeaders.get! i).declName) sectionVars) def insertReplacementForLetRecs (r : Replacement) (letRecClosures : List LetRecClosure) : Replacement := letRecClosures.foldl (init := r) fun r c => r.insert c.toLift.fvarId c.closed def Replacement.apply (r : Replacement) (e : Expr) : Expr := e.replace fun e => match e with | Expr.fvar fvarId _ => match r.find? fvarId with | some c => some c | _ => none | _ => none def pushMain (preDefs : Array PreDefinition) (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainVals : Array Expr) : TermElabM (Array PreDefinition) := mainHeaders.size.foldM (init := preDefs) fun i preDefs => do let header := mainHeaders[i] let val ← mkLambdaFVars sectionVars mainVals[i] let type ← mkForallFVars sectionVars header.type pure $ preDefs.push { kind := header.kind, declName := header.declName, lparams := [], -- we set it later modifiers := header.modifiers, type := type, value := val } def pushLetRecs (preDefs : Array PreDefinition) (letRecClosures : List LetRecClosure) (kind : DefKind) (modifiers : Modifiers) : Array PreDefinition := letRecClosures.foldl (init := preDefs) fun preDefs c => let type := Closure.mkForall c.localDecls c.toLift.type let val := Closure.mkLambda c.localDecls c.toLift.val preDefs.push { kind := kind, declName := c.toLift.declName, lparams := [], -- we set it later modifiers := { modifiers with attrs := c.toLift.attrs }, type := type, value := val } def getKindForLetRecs (mainHeaders : Array DefViewElabHeader) : DefKind := if mainHeaders.any fun h => h.kind.isTheorem then DefKind.«theorem» else DefKind.«def» def getModifiersForLetRecs (mainHeaders : Array DefViewElabHeader) : Modifiers := { isNoncomputable := mainHeaders.any fun h => h.modifiers.isNoncomputable, isPartial := mainHeaders.any fun h => h.modifiers.isPartial, isUnsafe := mainHeaders.any fun h => h.modifiers.isUnsafe } /- - `sectionVars`: The section variables used in the `mutual` block. - `mainHeaders`: The elaborated header of the top-level definitions being defined by the mutual block. - `mainFVars`: The auxiliary variables used to represent the top-level definitions being defined by the mutual block. - `mainVals`: The elaborated value for the top-level definitions - `letRecsToLift`: The let-rec's definitions that need to be lifted -/ def main (sectionVars : Array Expr) (mainHeaders : Array DefViewElabHeader) (mainFVars : Array Expr) (mainVals : Array Expr) (letRecsToLift : List LetRecToLift) : TermElabM (Array PreDefinition) := do -- Store in recFVarIds the fvarId of every function being defined by the mutual block. let mainFVarIds := mainFVars.map Expr.fvarId! let recFVarIds := (letRecsToLift.toArray.map fun toLift => toLift.fvarId) ++ mainFVarIds -- Compute the set of free variables (excluding `recFVarIds`) for each let-rec. let mctx ← getMCtx let freeVarMap := mkFreeVarMap mctx sectionVars mainFVarIds recFVarIds letRecsToLift resetZetaFVarIds withTrackingZeta do -- By checking `toLift.type` and `toLift.val` we populate `zetaFVarIds`. See comments at `src/Lean/Meta/Closure.lean`. letRecsToLift.forM fun toLift => withLCtx toLift.lctx toLift.localInstances do Meta.check toLift.type; Meta.check toLift.val let letRecClosures ← mkLetRecClosures letRecsToLift freeVarMap -- mkLetRecClosures assign metavariables that were placeholders for the lifted declarations. let mainVals ← mainVals.mapM instantiateMVars let mainHeaders ← mainHeaders.mapM instantiateMVarsAtHeader let letRecClosures ← letRecClosures.mapM fun closure => do pure { closure with toLift := (← instantiateMVarsAtLetRecToLift closure.toLift) } -- Replace fvarIds for functions being defined with closed terms let r := insertReplacementForMainFns {} sectionVars mainHeaders mainFVars let r := insertReplacementForLetRecs r letRecClosures let mainVals := mainVals.map r.apply let mainHeaders := mainHeaders.map fun h => { h with type := r.apply h.type } let letRecClosures := letRecClosures.map fun c => { c with toLift := { c.toLift with type := r.apply c.toLift.type, val := r.apply c.toLift.val } } let letRecKind := getKindForLetRecs mainHeaders let letRecMods := getModifiersForLetRecs mainHeaders pushMain (pushLetRecs #[] letRecClosures letRecKind letRecMods) sectionVars mainHeaders mainVals end MutualClosure private def getAllUserLevelNames (headers : Array DefViewElabHeader) : List Name := if h : 0 < headers.size then -- Recall that all top-level functions must have the same levels. See `check` method above (headers.get ⟨0, h⟩).levelNames else [] def elabMutualDef (vars : Array Expr) (views : Array DefView) : TermElabM Unit := do let scopeLevelNames ← getLevelNames let headers ← elabHeaders views let allUserLevelNames := getAllUserLevelNames headers withFunLocalDecls headers fun funFVars => do let values ← elabFunValues headers Term.synthesizeSyntheticMVarsNoPostponing if isExample views then pure () else let values ← values.mapM instantiateMVars let headers ← headers.mapM instantiateMVarsAtHeader let letRecsToLift ← getLetRecsToLift let letRecsToLift ← letRecsToLift.mapM instantiateMVarsAtLetRecToLift checkLetRecsToLiftTypes funFVars letRecsToLift withUsed vars headers values letRecsToLift fun vars => do let preDefs ← MutualClosure.main vars headers funFVars values letRecsToLift let preDefs ← levelMVarToParamPreDecls preDefs let preDefs ← instantiateMVarsAtPreDecls preDefs let preDefs ← fixLevelParams preDefs scopeLevelNames allUserLevelNames addPreDefinitions preDefs end Term namespace Command def elabMutualDef (ds : Array Syntax) : CommandElabM Unit := do let views ← ds.mapM fun d => do let modifiers ← elabModifiers d[0] mkDefView modifiers d[1] runTermElabM none fun vars => Term.elabMutualDef vars views end Command end Lean.Elab
95b67eb0578ba2f4d1cdc4f3e74a36d05115990e
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/finset/basic.lean
972364ef82459614461f8534c710b60ccd12f0d9
[ "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
131,282
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, Minchao Wu, Mario Carneiro -/ import data.multiset.finset_ops import tactic.apply import tactic.monotonicity import tactic.nth_rewrite /-! # Finite sets Terms of type `finset α` are one way of talking about finite subsets of `α` in mathlib. Below, `finset α` is defined as a structure with 2 fields: 1. `val` is a `multiset α` of elements; 2. `nodup` is a proof that `val` has no duplicates. Finsets in Lean are constructive in that they have an underlying `list` that enumerates their elements. In particular, any function that uses the data of the underlying list cannot depend on its ordering. This is handled on the `multiset` level by multiset API, so in most cases one needn't worry about it explicitly. Finsets give a basic foundation for defining finite sums and products over types: 1. `∑ i in (s : finset α), f i`; 2. `∏ i in (s : finset α), f i`. Lean refers to these operations as `big_operator`s. More information can be found in `algebra.big_operators.basic`. Finsets are directly used to define fintypes in Lean. A `fintype α` instance for a type `α` consists of a universal `finset α` containing every term of `α`, called `univ`. See `data.fintype.basic`. There is also `univ'`, the noncomputable partner to `univ`, which is defined to be `α` as a finset if `α` is finite, and the empty finset otherwise. See `data.fintype.basic`. ## Main declarations ### Main definitions * `finset`: Defines a type for the finite subsets of `α`. Constructing a `finset` requires two pieces of data: `val`, a `multiset α` of elements, and `nodup`, a proof that `val` has no duplicates. * `finset.has_mem`: Defines membership `a ∈ (s : finset α)`. * `finset.has_coe`: Provides a coercion `s : finset α` to `s : set α`. * `finset.has_coe_to_sort`: Coerce `s : finset α` to the type of all `x ∈ s`. * `finset.induction_on`: Induction on finsets. To prove a proposition about an arbitrary `finset α`, it suffices to prove it for the empty finset, and to show that if it holds for some `finset α`, then it holds for the finset obtained by inserting a new element. * `finset.choose`: Given a proof `h` of existence and uniqueness of a certain element satisfying a predicate, `choose s h` returns the element of `s` satisfying that predicate. * `finset.card`: `card s : ℕ` returns the cardinalilty of `s : finset α`. The API for `card`'s interaction with operations on finsets is extensive. TODO: The noncomputable sister `fincard` is about to be added into mathlib. ### Finset constructions * `singleton`: Denoted by `{a}`; the finset consisting of one element. * `finset.empty`: Denoted by `∅`. The finset associated to any type consisting of no elements. * `finset.range`: For any `n : ℕ`, `range n` is equal to `{0, 1, ... , n - 1} ⊆ ℕ`. This convention is consistent with other languages and normalizes `card (range n) = n`. Beware, `n` is not in `range n`. * `finset.diag`: Given `s`, `diag s` is the set of pairs `(a, a)` with `a ∈ s`. See also `finset.off_diag`: Given a finite set `s`, the off-diagonal, `s.off_diag` is the set of pairs `(a, b)` with `a ≠ b` for `a, b ∈ s`. * `finset.attach`: Given `s : finset α`, `attach s` forms a finset of elements of the subtype `{a // a ∈ s}`; in other words, it attaches elements to a proof of membership in the set. ### Finsets from functions * `finset.image`: Given a function `f : α → β`, `s.image f` is the image finset in `β`. * `finset.map`: Given an embedding `f : α ↪ β`, `s.map f` is the image finset in `β`. * `finset.filter`: Given a predicate `p : α → Prop`, `s.filter p` is the finset consisting of those elements in `s` satisfying the predicate `p`. ### The lattice structure on subsets of finsets There is a natural lattice structure on the subsets of a set. In Lean, we use lattice notation to talk about things involving unions and intersections. See `order.lattice`. For the lattice structure on finsets, `⊥` is called `bot` with `⊥ = ∅` and `⊤` is called `top` with `⊤ = univ`. * `finset.subset`: Lots of API about lattices, otherwise behaves exactly as one would expect. * `finset.union`: Defines `s ∪ t` (or `s ⊔ t`) as the union of `s` and `t`. See `finset.bUnion` for finite unions. * `finset.inter`: Defines `s ∩ t` (or `s ⊓ t`) as the intersection of `s` and `t`. TODO: `finset.bInter` for finite intersections. * `finset.disj_union`: Given a hypothesis `h` which states that finsets `s` and `t` are disjoint, `s.disj_union t h` is the set such that `a ∈ disj_union s t h` iff `a ∈ s` or `a ∈ t`; this does not require decidable equality on the type `α`. ### Operations on two or more finsets * `finset.insert` and `finset.cons`: For any `a : α`, `insert s a` returns `s ∪ {a}`. `cons s a h` returns the same except that it requires a hypothesis stating that `a` is not already in `s`. This does not require decidable equality on the type `α`. * `finset.union`: see "The lattice structure on subsets of finsets" * `finset.inter`: see "The lattice structure on subsets of finsets" * `finset.erase`: For any `a : α`, `erase s a` returns `s` with the element `a` removed. * `finset.sdiff`: Defines the set difference `s \ t` for finsets `s` and `t`. * `finset.prod`: Given finsets of `α` and `β`, defines finsets of `α × β`. For arbitrary dependent products, see `data.finset.pi`. * `finset.sigma`: Given finsets of `α` and `β`, defines finsets of the dependent sum type `Σ α, β` * `finset.bUnion`: Finite unions of finsets; given an indexing function `f : α → finset β` and a `s : finset α`, `s.bUnion f` is the union of all finsets of the form `f a` for `a ∈ s`. * `finset.bInter`: TODO: Implemement finite intersections. ### Maps constructed using finsets * `finset.piecewise`: Given two functions `f`, `g`, `s.piecewise f g` is a function which is equal to `f` on `s` and `g` on the complement. ### Predicates on finsets * `disjoint`: defined via the lattice structure on finsets; two sets are disjoint if their intersection is empty. * `finset.nonempty`: A finset is nonempty if it has elements. This is equivalent to saying `s ≠ ∅`. TODO: Decide on the simp normal form. ### Equivalences between finsets * The `data.equiv` files describe a general type of equivalence, so look in there for any lemmas. There is some API for rewriting sums and products from `s` to `t` given that `s ≃ t`. TODO: examples ## Tags finite sets, finset -/ open multiset subtype nat function variables {α : Type*} {β : Type*} {γ : Type*} /-- `finset α` is the type of finite sets of elements of `α`. It is implemented as a multiset (a list up to permutation) which has no duplicate elements. -/ structure finset (α : Type*) := (val : multiset α) (nodup : nodup val) namespace finset theorem eq_of_veq : ∀ {s t : finset α}, s.1 = t.1 → s = t | ⟨s, _⟩ ⟨t, _⟩ rfl := rfl @[simp] theorem val_inj {s t : finset α} : s.1 = t.1 ↔ s = t := ⟨eq_of_veq, congr_arg _⟩ @[simp] theorem erase_dup_eq_self [decidable_eq α] (s : finset α) : erase_dup s.1 = s.1 := s.2.erase_dup instance has_decidable_eq [decidable_eq α] : decidable_eq (finset α) | s₁ s₂ := decidable_of_iff _ val_inj /-! ### membership -/ instance : has_mem α (finset α) := ⟨λ a s, a ∈ s.1⟩ theorem mem_def {a : α} {s : finset α} : a ∈ s ↔ a ∈ s.1 := iff.rfl @[simp] theorem mem_mk {a : α} {s nd} : a ∈ @finset.mk α s nd ↔ a ∈ s := iff.rfl instance decidable_mem [h : decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ s) := multiset.decidable_mem _ _ /-! ### set coercion -/ /-- Convert a finset to a set in the natural way. -/ instance : has_coe_t (finset α) (set α) := ⟨λ s, {x | x ∈ s}⟩ @[simp, norm_cast] lemma mem_coe {a : α} {s : finset α} : a ∈ (s : set α) ↔ a ∈ s := iff.rfl @[simp] lemma set_of_mem {α} {s : finset α} : {a | a ∈ s} = s := rfl @[simp] lemma coe_mem {s : finset α} (x : (s : set α)) : ↑x ∈ s := x.2 @[simp] lemma mk_coe {s : finset α} (x : (s : set α)) {h} : (⟨x, h⟩ : (s : set α)) = x := subtype.coe_eta _ _ instance decidable_mem' [decidable_eq α] (a : α) (s : finset α) : decidable (a ∈ (s : set α)) := s.decidable_mem _ /-! ### extensionality -/ theorem ext_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ ∀ a, a ∈ s₁ ↔ a ∈ s₂ := val_inj.symm.trans $ nodup_ext s₁.2 s₂.2 @[ext] theorem ext {s₁ s₂ : finset α} : (∀ a, a ∈ s₁ ↔ a ∈ s₂) → s₁ = s₂ := ext_iff.2 @[simp, norm_cast] theorem coe_inj {s₁ s₂ : finset α} : (s₁ : set α) = s₂ ↔ s₁ = s₂ := set.ext_iff.trans ext_iff.symm lemma coe_injective {α} : injective (coe : finset α → set α) := λ s t, coe_inj.1 /-! ### type coercion -/ /-- Coercion from a finset to the corresponding subtype. -/ instance {α : Type*} : has_coe_to_sort (finset α) := ⟨_, λ s, {x // x ∈ s}⟩ instance pi_finset_coe.can_lift (ι : Type*) (α : Π i : ι, Type*) [ne : Π i, nonempty (α i)] (s : finset ι) : can_lift (Π i : s, α i) (Π i, α i) := { coe := λ f i, f i, .. pi_subtype.can_lift ι α (∈ s) } instance pi_finset_coe.can_lift' (ι α : Type*) [ne : nonempty α] (s : finset ι) : can_lift (s → α) (ι → α) := pi_finset_coe.can_lift ι (λ _, α) s instance finset_coe.can_lift (s : finset α) : can_lift α s := { coe := coe, cond := λ a, a ∈ s, prf := λ a ha, ⟨⟨a, ha⟩, rfl⟩ } @[simp, norm_cast] lemma coe_sort_coe (s : finset α) : ((s : set α) : Sort*) = s := rfl /-! ### subset -/ instance : has_subset (finset α) := ⟨λ s₁ s₂, ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂⟩ theorem subset_def {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ s₁.1 ⊆ s₂.1 := iff.rfl @[simp] theorem subset.refl (s : finset α) : s ⊆ s := subset.refl _ theorem subset_of_eq {s t : finset α} (h : s = t) : s ⊆ t := h ▸ subset.refl _ theorem subset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₂ ⊆ s₃ → s₁ ⊆ s₃ := subset.trans theorem superset.trans {s₁ s₂ s₃ : finset α} : s₁ ⊇ s₂ → s₂ ⊇ s₃ → s₁ ⊇ s₃ := λ h' h, subset.trans h h' -- TODO: these should be global attributes, but this will require fixing other files local attribute [trans] subset.trans superset.trans theorem mem_of_subset {s₁ s₂ : finset α} {a : α} : s₁ ⊆ s₂ → a ∈ s₁ → a ∈ s₂ := mem_of_subset theorem subset.antisymm {s₁ s₂ : finset α} (H₁ : s₁ ⊆ s₂) (H₂ : s₂ ⊆ s₁) : s₁ = s₂ := ext $ λ a, ⟨@H₁ a, @H₂ a⟩ theorem subset_iff {s₁ s₂ : finset α} : s₁ ⊆ s₂ ↔ ∀ ⦃x⦄, x ∈ s₁ → x ∈ s₂ := iff.rfl @[simp, norm_cast] theorem coe_subset {s₁ s₂ : finset α} : (s₁ : set α) ⊆ s₂ ↔ s₁ ⊆ s₂ := iff.rfl @[simp] theorem val_le_iff {s₁ s₂ : finset α} : s₁.1 ≤ s₂.1 ↔ s₁ ⊆ s₂ := le_iff_subset s₁.2 instance : has_ssubset (finset α) := ⟨λa b, a ⊆ b ∧ ¬ b ⊆ a⟩ instance : partial_order (finset α) := { le := (⊆), lt := (⊂), le_refl := subset.refl, le_trans := @subset.trans _, le_antisymm := @subset.antisymm _ } /-- Coercion to `set α` as an `order_embedding`. -/ def coe_emb : finset α ↪o set α := ⟨⟨coe, coe_injective⟩, λ s t, coe_subset⟩ @[simp] lemma coe_coe_emb : ⇑(coe_emb : finset α ↪o set α) = coe := rfl theorem subset.antisymm_iff {s₁ s₂ : finset α} : s₁ = s₂ ↔ s₁ ⊆ s₂ ∧ s₂ ⊆ s₁ := le_antisymm_iff theorem not_subset (s t : finset α) : ¬(s ⊆ t) ↔ ∃ x ∈ s, ¬(x ∈ t) := by simp only [←finset.coe_subset, set.not_subset, exists_prop, finset.mem_coe] @[simp] theorem le_eq_subset : ((≤) : finset α → finset α → Prop) = (⊆) := rfl @[simp] theorem lt_eq_subset : ((<) : finset α → finset α → Prop) = (⊂) := rfl theorem le_iff_subset {s₁ s₂ : finset α} : s₁ ≤ s₂ ↔ s₁ ⊆ s₂ := iff.rfl theorem lt_iff_ssubset {s₁ s₂ : finset α} : s₁ < s₂ ↔ s₁ ⊂ s₂ := iff.rfl @[simp, norm_cast] lemma coe_ssubset {s₁ s₂ : finset α} : (s₁ : set α) ⊂ s₂ ↔ s₁ ⊂ s₂ := show (s₁ : set α) ⊂ s₂ ↔ s₁ ⊆ s₂ ∧ ¬s₂ ⊆ s₁, by simp only [set.ssubset_def, finset.coe_subset] @[simp] theorem val_lt_iff {s₁ s₂ : finset α} : s₁.1 < s₂.1 ↔ s₁ ⊂ s₂ := and_congr val_le_iff $ not_congr val_le_iff lemma ssubset_iff_subset_ne {s t : finset α} : s ⊂ t ↔ s ⊆ t ∧ s ≠ t := @lt_iff_le_and_ne _ _ s t theorem ssubset_iff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ⊂ s₂ ↔ ∃ x ∈ s₂, x ∉ s₁ := set.ssubset_iff_of_subset h lemma ssubset_of_ssubset_of_subset {s₁ s₂ s₃ : finset α} (hs₁s₂ : s₁ ⊂ s₂) (hs₂s₃ : s₂ ⊆ s₃) : s₁ ⊂ s₃ := set.ssubset_of_ssubset_of_subset hs₁s₂ hs₂s₃ lemma ssubset_of_subset_of_ssubset {s₁ s₂ s₃ : finset α} (hs₁s₂ : s₁ ⊆ s₂) (hs₂s₃ : s₂ ⊂ s₃) : s₁ ⊂ s₃ := set.ssubset_of_subset_of_ssubset hs₁s₂ hs₂s₃ lemma exists_of_ssubset {s₁ s₂ : finset α} (h : s₁ ⊂ s₂) : ∃ x ∈ s₂, x ∉ s₁ := set.exists_of_ssubset h /-! ### Nonempty -/ /-- The property `s.nonempty` expresses the fact that the finset `s` is not empty. It should be used in theorem assumptions instead of `∃ x, x ∈ s` or `s ≠ ∅` as it gives access to a nice API thanks to the dot notation. -/ protected def nonempty (s : finset α) : Prop := ∃ x:α, x ∈ s @[simp, norm_cast] lemma coe_nonempty {s : finset α} : (s:set α).nonempty ↔ s.nonempty := iff.rfl @[simp] lemma nonempty_coe_sort (s : finset α) : nonempty ↥s ↔ s.nonempty := nonempty_subtype alias coe_nonempty ↔ _ finset.nonempty.to_set lemma nonempty.bex {s : finset α} (h : s.nonempty) : ∃ x:α, x ∈ s := h lemma nonempty.mono {s t : finset α} (hst : s ⊆ t) (hs : s.nonempty) : t.nonempty := set.nonempty.mono hst hs lemma nonempty.forall_const {s : finset α} (h : s.nonempty) {p : Prop} : (∀ x ∈ s, p) ↔ p := let ⟨x, hx⟩ := h in ⟨λ h, h x hx, λ h x hx, h⟩ /-! ### empty -/ /-- The empty finset -/ protected def empty : finset α := ⟨0, nodup_zero⟩ instance : has_emptyc (finset α) := ⟨finset.empty⟩ instance inhabited_finset : inhabited (finset α) := ⟨∅⟩ @[simp] theorem empty_val : (∅ : finset α).1 = 0 := rfl @[simp] theorem not_mem_empty (a : α) : a ∉ (∅ : finset α) := id @[simp] theorem not_nonempty_empty : ¬(∅ : finset α).nonempty := λ ⟨x, hx⟩, not_mem_empty x hx @[simp] theorem mk_zero : (⟨0, nodup_zero⟩ : finset α) = ∅ := rfl theorem ne_empty_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ≠ ∅ := λ e, not_mem_empty a $ e ▸ h theorem nonempty.ne_empty {s : finset α} (h : s.nonempty) : s ≠ ∅ := exists.elim h $ λ a, ne_empty_of_mem @[simp] theorem empty_subset (s : finset α) : ∅ ⊆ s := zero_subset _ theorem eq_empty_of_forall_not_mem {s : finset α} (H : ∀x, x ∉ s) : s = ∅ := eq_of_veq (eq_zero_of_forall_not_mem H) lemma eq_empty_iff_forall_not_mem {s : finset α} : s = ∅ ↔ ∀ x, x ∉ s := ⟨by rintro rfl x; exact id, λ h, eq_empty_of_forall_not_mem h⟩ @[simp] theorem val_eq_zero {s : finset α} : s.1 = 0 ↔ s = ∅ := @val_inj _ s ∅ theorem subset_empty {s : finset α} : s ⊆ ∅ ↔ s = ∅ := subset_zero.trans val_eq_zero @[simp] lemma not_ssubset_empty (s : finset α) : ¬s ⊂ ∅ := λ h, let ⟨x, he, hs⟩ := exists_of_ssubset h in he theorem nonempty_of_ne_empty {s : finset α} (h : s ≠ ∅) : s.nonempty := exists_mem_of_ne_zero (mt val_eq_zero.1 h) theorem nonempty_iff_ne_empty {s : finset α} : s.nonempty ↔ s ≠ ∅ := ⟨nonempty.ne_empty, nonempty_of_ne_empty⟩ @[simp] theorem not_nonempty_iff_eq_empty {s : finset α} : ¬s.nonempty ↔ s = ∅ := by { rw nonempty_iff_ne_empty, exact not_not, } theorem eq_empty_or_nonempty (s : finset α) : s = ∅ ∨ s.nonempty := classical.by_cases or.inl (λ h, or.inr (nonempty_of_ne_empty h)) @[simp, norm_cast] lemma coe_empty : ((∅ : finset α) : set α) = ∅ := rfl @[simp, norm_cast] lemma coe_eq_empty {s : finset α} : (s : set α) = ∅ ↔ s = ∅ := by rw [← coe_empty, coe_inj] /-- A `finset` for an empty type is empty. -/ lemma eq_empty_of_is_empty [is_empty α] (s : finset α) : s = ∅ := finset.eq_empty_of_forall_not_mem is_empty_elim /-! ### singleton -/ /-- `{a} : finset a` is the set `{a}` containing `a` and nothing else. This differs from `insert a ∅` in that it does not require a `decidable_eq` instance for `α`. -/ instance : has_singleton α (finset α) := ⟨λ a, ⟨{a}, nodup_singleton a⟩⟩ @[simp] theorem singleton_val (a : α) : ({a} : finset α).1 = {a} := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ ({a} : finset α) ↔ b = a := mem_singleton theorem not_mem_singleton {a b : α} : a ∉ ({b} : finset α) ↔ a ≠ b := not_congr mem_singleton theorem mem_singleton_self (a : α) : a ∈ ({a} : finset α) := or.inl rfl lemma singleton_injective : injective (singleton : α → finset α) := λ a b h, mem_singleton.1 (h ▸ mem_singleton_self _) theorem singleton_inj {a b : α} : ({a} : finset α) = {b} ↔ a = b := singleton_injective.eq_iff @[simp] theorem singleton_nonempty (a : α) : ({a} : finset α).nonempty := ⟨a, mem_singleton_self a⟩ @[simp] theorem singleton_ne_empty (a : α) : ({a} : finset α) ≠ ∅ := (singleton_nonempty a).ne_empty @[simp, norm_cast] lemma coe_singleton (a : α) : (({a} : finset α) : set α) = {a} := by { ext, simp } @[simp, norm_cast] lemma coe_eq_singleton {α : Type*} {s : finset α} {a : α} : (s : set α) = {a} ↔ s = {a} := by rw [←finset.coe_singleton, finset.coe_inj] lemma eq_singleton_iff_unique_mem {s : finset α} {a : α} : s = {a} ↔ a ∈ s ∧ ∀ x ∈ s, x = a := begin split; intro t, rw t, refine ⟨finset.mem_singleton_self _, λ _, finset.mem_singleton.1⟩, ext, rw finset.mem_singleton, refine ⟨t.right _, λ r, r.symm ▸ t.left⟩ end lemma eq_singleton_iff_nonempty_unique_mem {s : finset α} {a : α} : s = {a} ↔ s.nonempty ∧ ∀ x ∈ s, x = a := begin split, { intros h, subst h, simp, }, { rintros ⟨hne, h_uniq⟩, rw eq_singleton_iff_unique_mem, refine ⟨_, h_uniq⟩, rw ← h_uniq hne.some hne.some_spec, apply hne.some_spec, }, end lemma singleton_iff_unique_mem (s : finset α) : (∃ a, s = {a}) ↔ ∃! a, a ∈ s := by simp only [eq_singleton_iff_unique_mem, exists_unique] lemma singleton_subset_set_iff {s : set α} {a : α} : ↑({a} : finset α) ⊆ s ↔ a ∈ s := by rw [coe_singleton, set.singleton_subset_iff] @[simp] lemma singleton_subset_iff {s : finset α} {a : α} : {a} ⊆ s ↔ a ∈ s := singleton_subset_set_iff @[simp] lemma subset_singleton_iff {s : finset α} {a : α} : s ⊆ {a} ↔ s = ∅ ∨ s = {a} := begin split, { intro hs, apply or.imp_right _ s.eq_empty_or_nonempty, rintro ⟨t, ht⟩, apply subset.antisymm hs, rwa [singleton_subset_iff, ←mem_singleton.1 (hs ht)] }, rintro (rfl | rfl), { exact empty_subset _ }, exact subset.refl _, end @[simp] lemma ssubset_singleton_iff {s : finset α} {a : α} : s ⊂ {a} ↔ s = ∅ := by rw [←coe_ssubset, coe_singleton, set.ssubset_singleton_iff, coe_eq_empty] lemma eq_empty_of_ssubset_singleton {s : finset α} {x : α} (hs : s ⊂ {x}) : s = ∅ := ssubset_singleton_iff.1 hs /-! ### cons -/ /-- `cons a s h` is the set `{a} ∪ s` containing `a` and the elements of `s`. It is the same as `insert a s` when it is defined, but unlike `insert a s` it does not require `decidable_eq α`, and the union is guaranteed to be disjoint. -/ def cons {α} (a : α) (s : finset α) (h : a ∉ s) : finset α := ⟨a ::ₘ s.1, multiset.nodup_cons.2 ⟨h, s.2⟩⟩ @[simp] theorem mem_cons {a s h b} : b ∈ @cons α a s h ↔ b = a ∨ b ∈ s := by rcases s with ⟨⟨s⟩⟩; apply list.mem_cons_iff @[simp] theorem cons_val {a : α} {s : finset α} (h : a ∉ s) : (cons a s h).1 = a ::ₘ s.1 := rfl @[simp] theorem mk_cons {a : α} {s : multiset α} (h : (a ::ₘ s).nodup) : (⟨a ::ₘ s, h⟩ : finset α) = cons a ⟨s, (multiset.nodup_cons.1 h).2⟩ (multiset.nodup_cons.1 h).1 := rfl @[simp] theorem nonempty_cons {a : α} {s : finset α} (h : a ∉ s) : (cons a s h).nonempty := ⟨a, mem_cons.2 (or.inl rfl)⟩ @[simp] lemma nonempty_mk_coe : ∀ {l : list α} {hl}, (⟨↑l, hl⟩ : finset α).nonempty ↔ l ≠ [] | [] hl := by simp | (a::l) hl := by simp [← multiset.cons_coe] @[simp] lemma coe_cons {a s h} : (@cons α a s h : set α) = insert a s := by { ext, simp } @[simp] lemma cons_subset_cons {a s hs t ht} : @cons α a s hs ⊆ cons a t ht ↔ s ⊆ t := by rwa [← coe_subset, coe_cons, coe_cons, set.insert_subset_insert_iff, coe_subset] /-! ### disjoint union -/ /-- `disj_union s t h` is the set such that `a ∈ disj_union s t h` iff `a ∈ s` or `a ∈ t`. It is the same as `s ∪ t`, but it does not require decidable equality on the type. The hypothesis ensures that the sets are disjoint. -/ def disj_union {α} (s t : finset α) (h : ∀ a ∈ s, a ∉ t) : finset α := ⟨s.1 + t.1, multiset.nodup_add.2 ⟨s.2, t.2, h⟩⟩ @[simp] theorem mem_disj_union {α s t h a} : a ∈ @disj_union α s t h ↔ a ∈ s ∨ a ∈ t := by rcases s with ⟨⟨s⟩⟩; rcases t with ⟨⟨t⟩⟩; apply list.mem_append /-! ### insert -/ section decidable_eq variables [decidable_eq α] /-- `insert a s` is the set `{a} ∪ s` containing `a` and the elements of `s`. -/ instance : has_insert α (finset α) := ⟨λ a s, ⟨_, nodup_ndinsert a s.2⟩⟩ theorem insert_def (a : α) (s : finset α) : insert a s = ⟨_, nodup_ndinsert a s.2⟩ := rfl @[simp] theorem insert_val (a : α) (s : finset α) : (insert a s).1 = ndinsert a s.1 := rfl theorem insert_val' (a : α) (s : finset α) : (insert a s).1 = erase_dup (a ::ₘ s.1) := by rw [erase_dup_cons, erase_dup_eq_self]; refl theorem insert_val_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : (insert a s).1 = a ::ₘ s.1 := by rw [insert_val, ndinsert_of_not_mem h] @[simp] theorem mem_insert {a b : α} {s : finset α} : a ∈ insert b s ↔ a = b ∨ a ∈ s := mem_ndinsert theorem mem_insert_self (a : α) (s : finset α) : a ∈ insert a s := mem_ndinsert_self a s.1 theorem mem_insert_of_mem {a b : α} {s : finset α} (h : a ∈ s) : a ∈ insert b s := mem_ndinsert_of_mem h theorem mem_of_mem_insert_of_ne {a b : α} {s : finset α} (h : b ∈ insert a s) : b ≠ a → b ∈ s := (mem_insert.1 h).resolve_left @[simp] theorem cons_eq_insert {α} [decidable_eq α] (a s h) : @cons α a s h = insert a s := ext $ λ a, by simp @[simp, norm_cast] lemma coe_insert (a : α) (s : finset α) : ↑(insert a s) = (insert a s : set α) := set.ext $ λ x, by simp only [mem_coe, mem_insert, set.mem_insert_iff] lemma mem_insert_coe {s : finset α} {x y : α} : x ∈ insert y s ↔ x ∈ insert y (s : set α) := by simp instance : is_lawful_singleton α (finset α) := ⟨λ a, by { ext, simp }⟩ @[simp] theorem insert_eq_of_mem {a : α} {s : finset α} (h : a ∈ s) : insert a s = s := eq_of_veq $ ndinsert_of_mem h @[simp] theorem insert_singleton_self_eq (a : α) : ({a, a} : finset α) = {a} := insert_eq_of_mem $ mem_singleton_self _ theorem insert.comm (a b : α) (s : finset α) : insert a (insert b s) = insert b (insert a s) := ext $ λ x, by simp only [mem_insert, or.left_comm] theorem insert_singleton_comm (a b : α) : ({a, b} : finset α) = {b, a} := begin ext, simp [or.comm] end @[simp] theorem insert_idem (a : α) (s : finset α) : insert a (insert a s) = insert a s := ext $ λ x, by simp only [mem_insert, or.assoc.symm, or_self] @[simp] theorem insert_nonempty (a : α) (s : finset α) : (insert a s).nonempty := ⟨a, mem_insert_self a s⟩ @[simp] theorem insert_ne_empty (a : α) (s : finset α) : insert a s ≠ ∅ := (insert_nonempty a s).ne_empty section universe u /-! The universe annotation is required for the following instance, possibly this is a bug in Lean. See leanprover.zulipchat.com/#narrow/stream/113488-general/topic/strange.20error.20(universe.20issue.3F) -/ instance {α : Type u} [decidable_eq α] (i : α) (s : finset α) : nonempty.{u + 1} ((insert i s : finset α) : set α) := (finset.coe_nonempty.mpr (s.insert_nonempty i)).to_subtype end lemma ne_insert_of_not_mem (s t : finset α) {a : α} (h : a ∉ s) : s ≠ insert a t := by { contrapose! h, simp [h] } theorem insert_subset {a : α} {s t : finset α} : insert a s ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp only [subset_iff, mem_insert, forall_eq, or_imp_distrib, forall_and_distrib] theorem subset_insert (a : α) (s : finset α) : s ⊆ insert a s := λ b, mem_insert_of_mem theorem insert_subset_insert (a : α) {s t : finset α} (h : s ⊆ t) : insert a s ⊆ insert a t := insert_subset.2 ⟨mem_insert_self _ _, subset.trans h (subset_insert _ _)⟩ lemma ssubset_iff {s t : finset α} : s ⊂ t ↔ (∃a ∉ s, insert a s ⊆ t) := by exact_mod_cast @set.ssubset_iff_insert α s t lemma ssubset_insert {s : finset α} {a : α} (h : a ∉ s) : s ⊂ insert a s := ssubset_iff.mpr ⟨a, h, subset.refl _⟩ @[elab_as_eliminator] lemma cons_induction {α : Type*} {p : finset α → Prop} (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α} (h : a ∉ s), p s → p (cons a s h)) : ∀ s, p s | ⟨s, nd⟩ := multiset.induction_on s (λ _, h₁) (λ a s IH nd, begin cases nodup_cons.1 nd with m nd', rw [← (eq_of_veq _ : cons a (finset.mk s _) m = ⟨a ::ₘ s, nd⟩)], { exact h₂ (by exact m) (IH nd') }, { rw [cons_val] } end) nd @[elab_as_eliminator] lemma cons_induction_on {α : Type*} {p : finset α → Prop} (s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α} (h : a ∉ s), p s → p (cons a s h)) : p s := cons_induction h₁ h₂ s @[elab_as_eliminator] protected theorem induction {α : Type*} {p : finset α → Prop} [decidable_eq α] (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : ∀ s, p s := cons_induction h₁ $ λ a s ha, (s.cons_eq_insert a ha).symm ▸ h₂ ha /-- To prove a proposition about an arbitrary `finset α`, it suffices to prove it for the empty `finset`, and to show that if it holds for some `finset α`, then it holds for the `finset` obtained by inserting a new element. -/ @[elab_as_eliminator] protected theorem induction_on {α : Type*} {p : finset α → Prop} [decidable_eq α] (s : finset α) (h₁ : p ∅) (h₂ : ∀ ⦃a : α⦄ {s : finset α}, a ∉ s → p s → p (insert a s)) : p s := finset.induction h₁ h₂ s /-- To prove a proposition about `S : finset α`, it suffices to prove it for the empty `finset`, and to show that if it holds for some `finset α ⊆ S`, then it holds for the `finset` obtained by inserting a new element of `S`. -/ @[elab_as_eliminator] theorem induction_on' {α : Type*} {p : finset α → Prop} [decidable_eq α] (S : finset α) (h₁ : p ∅) (h₂ : ∀ {a s}, a ∈ S → s ⊆ S → a ∉ s → p s → p (insert a s)) : p S := @finset.induction_on α (λ T, T ⊆ S → p T) _ S (λ _, h₁) (λ a s has hqs hs, let ⟨hS, sS⟩ := finset.insert_subset.1 hs in h₂ hS sS has (hqs sS)) (finset.subset.refl S) /-- To prove a proposition about a nonempty `s : finset α`, it suffices to show it holds for all singletons and that if it holds for `t : finset α`, then it also holds for the `finset` obtained by inserting an element in `t`. -/ @[elab_as_eliminator] lemma nonempty.cons_induction {α : Type*} {s : finset α} (hs : s.nonempty) {p : finset α → Prop} (h₀ : ∀ a, p {a}) (h₁ : ∀ ⦃a⦄ s (h : a ∉ s), p s → p (finset.cons a s h)) : p s := begin induction s using finset.cons_induction with a t ha h, { exact (not_nonempty_empty hs).elim, }, obtain rfl | ht := t.eq_empty_or_nonempty, { exact h₀ a }, { exact h₁ t ha (h ht) } end /-- Inserting an element to a finite set is equivalent to the option type. -/ def subtype_insert_equiv_option {t : finset α} {x : α} (h : x ∉ t) : {i // i ∈ insert x t} ≃ option {i // i ∈ t} := begin refine { to_fun := λ y, if h : ↑y = x then none else some ⟨y, (mem_insert.mp y.2).resolve_left h⟩, inv_fun := λ y, y.elim ⟨x, mem_insert_self _ _⟩ $ λ z, ⟨z, mem_insert_of_mem z.2⟩, .. }, { intro y, by_cases h : ↑y = x, simp only [subtype.ext_iff, h, option.elim, dif_pos, subtype.coe_mk], simp only [h, option.elim, dif_neg, not_false_iff, subtype.coe_eta, subtype.coe_mk] }, { rintro (_|y), simp only [option.elim, dif_pos, subtype.coe_mk], have : ↑y ≠ x, { rintro ⟨⟩, exact h y.2 }, simp only [this, option.elim, subtype.eta, dif_neg, not_false_iff, subtype.coe_eta, subtype.coe_mk] }, end /-! ### union -/ /-- `s ∪ t` is the set such that `a ∈ s ∪ t` iff `a ∈ s` or `a ∈ t`. -/ instance : has_union (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndunion s₁.1 s₂.2⟩⟩ theorem union_val_nd (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = ndunion s₁.1 s₂.1 := rfl @[simp] theorem union_val (s₁ s₂ : finset α) : (s₁ ∪ s₂).1 = s₁.1 ∪ s₂.1 := ndunion_eq_union s₁.2 @[simp] theorem mem_union {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∪ s₂ ↔ a ∈ s₁ ∨ a ∈ s₂ := mem_ndunion @[simp] theorem disj_union_eq_union {α} [decidable_eq α] (s t h) : @disj_union α s t h = s ∪ t := ext $ λ a, by simp theorem mem_union_left {a : α} {s₁ : finset α} (s₂ : finset α) (h : a ∈ s₁) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inl h theorem mem_union_right {a : α} {s₂ : finset α} (s₁ : finset α) (h : a ∈ s₂) : a ∈ s₁ ∪ s₂ := mem_union.2 $ or.inr h theorem forall_mem_union {s₁ s₂ : finset α} {p : α → Prop} : (∀ ab ∈ (s₁ ∪ s₂), p ab) ↔ (∀ a ∈ s₁, p a) ∧ (∀ b ∈ s₂, p b) := ⟨λ h, ⟨λ a, h a ∘ mem_union_left _, λ b, h b ∘ mem_union_right _⟩, λ h ab hab, (mem_union.mp hab).elim (h.1 _) (h.2 _)⟩ theorem not_mem_union {a : α} {s₁ s₂ : finset α} : a ∉ s₁ ∪ s₂ ↔ a ∉ s₁ ∧ a ∉ s₂ := by rw [mem_union, not_or_distrib] @[simp, norm_cast] lemma coe_union (s₁ s₂ : finset α) : ↑(s₁ ∪ s₂) = (s₁ ∪ s₂ : set α) := set.ext $ λ x, mem_union theorem union_subset {s₁ s₂ s₃ : finset α} (h₁ : s₁ ⊆ s₃) (h₂ : s₂ ⊆ s₃) : s₁ ∪ s₂ ⊆ s₃ := val_le_iff.1 (ndunion_le.2 ⟨h₁, val_le_iff.2 h₂⟩) theorem subset_union_left (s₁ s₂ : finset α) : s₁ ⊆ s₁ ∪ s₂ := λ x, mem_union_left _ theorem subset_union_right (s₁ s₂ : finset α) : s₂ ⊆ s₁ ∪ s₂ := λ x, mem_union_right _ lemma union_subset_union {s₁ t₁ s₂ t₂ : finset α} (h₁ : s₁ ⊆ t₁) (h₂ : s₂ ⊆ t₂) : s₁ ∪ s₂ ⊆ t₁ ∪ t₂ := by { intros x hx, rw finset.mem_union at hx ⊢, tauto } theorem union_comm (s₁ s₂ : finset α) : s₁ ∪ s₂ = s₂ ∪ s₁ := ext $ λ x, by simp only [mem_union, or_comm] instance : is_commutative (finset α) (∪) := ⟨union_comm⟩ @[simp] theorem union_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = s₁ ∪ (s₂ ∪ s₃) := ext $ λ x, by simp only [mem_union, or_assoc] instance : is_associative (finset α) (∪) := ⟨union_assoc⟩ @[simp] theorem union_idempotent (s : finset α) : s ∪ s = s := ext $ λ _, mem_union.trans $ or_self _ instance : is_idempotent (finset α) (∪) := ⟨union_idempotent⟩ theorem union_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∪ (s₂ ∪ s₃) = s₂ ∪ (s₁ ∪ s₃) := ext $ λ _, by simp only [mem_union, or.left_comm] theorem union_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∪ s₂) ∪ s₃ = (s₁ ∪ s₃) ∪ s₂ := ext $ λ x, by simp only [mem_union, or_assoc, or_comm (x ∈ s₂)] theorem union_self (s : finset α) : s ∪ s = s := union_idempotent s @[simp] theorem union_empty (s : finset α) : s ∪ ∅ = s := ext $ λ x, mem_union.trans $ or_false _ @[simp] theorem empty_union (s : finset α) : ∅ ∪ s = s := ext $ λ x, mem_union.trans $ false_or _ theorem insert_eq (a : α) (s : finset α) : insert a s = {a} ∪ s := rfl @[simp] theorem insert_union (a : α) (s t : finset α) : insert a s ∪ t = insert a (s ∪ t) := by simp only [insert_eq, union_assoc] @[simp] theorem union_insert (a : α) (s t : finset α) : s ∪ insert a t = insert a (s ∪ t) := by simp only [insert_eq, union_left_comm] theorem insert_union_distrib (a : α) (s t : finset α) : insert a (s ∪ t) = insert a s ∪ insert a t := by simp only [insert_union, union_insert, insert_idem] @[simp] lemma union_eq_left_iff_subset {s t : finset α} : s ∪ t = s ↔ t ⊆ s := begin split, { assume h, have : t ⊆ s ∪ t := subset_union_right _ _, rwa h at this }, { assume h, exact subset.antisymm (union_subset (subset.refl _) h) (subset_union_left _ _) } end @[simp] lemma left_eq_union_iff_subset {s t : finset α} : s = s ∪ t ↔ t ⊆ s := by rw [← union_eq_left_iff_subset, eq_comm] @[simp] lemma union_eq_right_iff_subset {s t : finset α} : t ∪ s = s ↔ t ⊆ s := by rw [union_comm, union_eq_left_iff_subset] @[simp] lemma right_eq_union_iff_subset {s t : finset α} : s = t ∪ s ↔ t ⊆ s := by rw [← union_eq_right_iff_subset, eq_comm] /-- To prove a relation on pairs of `finset X`, it suffices to show that it is * symmetric, * it holds when one of the `finset`s is empty, * it holds for pairs of singletons, * if it holds for `[a, c]` and for `[b, c]`, then it holds for `[a ∪ b, c]`. -/ lemma induction_on_union (P : finset α → finset α → Prop) (symm : ∀ {a b}, P a b → P b a) (empty_right : ∀ {a}, P a ∅) (singletons : ∀ {a b}, P {a} {b}) (union_of : ∀ {a b c}, P a c → P b c → P (a ∪ b) c) : ∀ a b, P a b := begin intros a b, refine finset.induction_on b empty_right (λ x s xs hi, symm _), rw finset.insert_eq, apply union_of _ (symm hi), refine finset.induction_on a empty_right (λ a t ta hi, symm _), rw finset.insert_eq, exact union_of singletons (symm hi), end lemma exists_mem_subset_of_subset_bUnion_of_directed_on {α ι : Type*} {f : ι → set α} {c : set ι} {a : ι} (hac : a ∈ c) (hc : directed_on (λ i j, f i ⊆ f j) c) {s : finset α} (hs : (s : set α) ⊆ ⋃ i ∈ c, f i) : ∃ i ∈ c, (s : set α) ⊆ f i := begin classical, revert hs, apply s.induction_on, { intros, use [a, hac], simp }, { intros b t hbt htc hbtc, obtain ⟨i : ι , hic : i ∈ c, hti : (t : set α) ⊆ f i⟩ := htc (set.subset.trans (t.subset_insert b) hbtc), obtain ⟨j, hjc, hbj⟩ : ∃ j ∈ c, b ∈ f j, by simpa [set.mem_bUnion_iff] using hbtc (t.mem_insert_self b), rcases hc j hjc i hic with ⟨k, hkc, hk, hk'⟩, use [k, hkc], rw [coe_insert, set.insert_subset], exact ⟨hk hbj, trans hti hk'⟩ } end /-! ### inter -/ /-- `s ∩ t` is the set such that `a ∈ s ∩ t` iff `a ∈ s` and `a ∈ t`. -/ instance : has_inter (finset α) := ⟨λ s₁ s₂, ⟨_, nodup_ndinter s₂.1 s₁.2⟩⟩ -- TODO: some of these results may have simpler proofs, once there are enough results -- to obtain the `lattice` instance. theorem inter_val_nd (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = ndinter s₁.1 s₂.1 := rfl @[simp] theorem inter_val (s₁ s₂ : finset α) : (s₁ ∩ s₂).1 = s₁.1 ∩ s₂.1 := ndinter_eq_inter s₁.2 @[simp] theorem mem_inter {a : α} {s₁ s₂ : finset α} : a ∈ s₁ ∩ s₂ ↔ a ∈ s₁ ∧ a ∈ s₂ := mem_ndinter theorem mem_of_mem_inter_left {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₁ := (mem_inter.1 h).1 theorem mem_of_mem_inter_right {a : α} {s₁ s₂ : finset α} (h : a ∈ s₁ ∩ s₂) : a ∈ s₂ := (mem_inter.1 h).2 theorem mem_inter_of_mem {a : α} {s₁ s₂ : finset α} : a ∈ s₁ → a ∈ s₂ → a ∈ s₁ ∩ s₂ := and_imp.1 mem_inter.2 theorem inter_subset_left (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₁ := λ a, mem_of_mem_inter_left theorem inter_subset_right (s₁ s₂ : finset α) : s₁ ∩ s₂ ⊆ s₂ := λ a, mem_of_mem_inter_right theorem subset_inter {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ → s₁ ⊆ s₃ → s₁ ⊆ s₂ ∩ s₃ := by simp only [subset_iff, mem_inter] {contextual:=tt}; intros; split; trivial @[simp, norm_cast] lemma coe_inter (s₁ s₂ : finset α) : ↑(s₁ ∩ s₂) = (s₁ ∩ s₂ : set α) := set.ext $ λ _, mem_inter @[simp] theorem union_inter_cancel_left {s t : finset α} : (s ∪ t) ∩ s = s := by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_left] @[simp] theorem union_inter_cancel_right {s t : finset α} : (s ∪ t) ∩ t = t := by rw [← coe_inj, coe_inter, coe_union, set.union_inter_cancel_right] theorem inter_comm (s₁ s₂ : finset α) : s₁ ∩ s₂ = s₂ ∩ s₁ := ext $ λ _, by simp only [mem_inter, and_comm] @[simp] theorem inter_assoc (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = s₁ ∩ (s₂ ∩ s₃) := ext $ λ _, by simp only [mem_inter, and_assoc] theorem inter_left_comm (s₁ s₂ s₃ : finset α) : s₁ ∩ (s₂ ∩ s₃) = s₂ ∩ (s₁ ∩ s₃) := ext $ λ _, by simp only [mem_inter, and.left_comm] theorem inter_right_comm (s₁ s₂ s₃ : finset α) : (s₁ ∩ s₂) ∩ s₃ = (s₁ ∩ s₃) ∩ s₂ := ext $ λ _, by simp only [mem_inter, and.right_comm] @[simp] theorem inter_self (s : finset α) : s ∩ s = s := ext $ λ _, mem_inter.trans $ and_self _ @[simp] theorem inter_empty (s : finset α) : s ∩ ∅ = ∅ := ext $ λ _, mem_inter.trans $ and_false _ @[simp] theorem empty_inter (s : finset α) : ∅ ∩ s = ∅ := ext $ λ _, mem_inter.trans $ false_and _ @[simp] lemma inter_union_self (s t : finset α) : s ∩ (t ∪ s) = s := by rw [inter_comm, union_inter_cancel_right] @[simp] theorem insert_inter_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₂) : insert a s₁ ∩ s₂ = insert a (s₁ ∩ s₂) := ext $ λ x, have x = a ∨ x ∈ s₂ ↔ x ∈ s₂, from or_iff_right_of_imp $ by rintro rfl; exact h, by simp only [mem_inter, mem_insert, or_and_distrib_left, this] @[simp] theorem inter_insert_of_mem {s₁ s₂ : finset α} {a : α} (h : a ∈ s₁) : s₁ ∩ insert a s₂ = insert a (s₁ ∩ s₂) := by rw [inter_comm, insert_inter_of_mem h, inter_comm] @[simp] theorem insert_inter_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₂) : insert a s₁ ∩ s₂ = s₁ ∩ s₂ := ext $ λ x, have ¬ (x = a ∧ x ∈ s₂), by rintro ⟨rfl, H⟩; exact h H, by simp only [mem_inter, mem_insert, or_and_distrib_right, this, false_or] @[simp] theorem inter_insert_of_not_mem {s₁ s₂ : finset α} {a : α} (h : a ∉ s₁) : s₁ ∩ insert a s₂ = s₁ ∩ s₂ := by rw [inter_comm, insert_inter_of_not_mem h, inter_comm] @[simp] theorem singleton_inter_of_mem {a : α} {s : finset α} (H : a ∈ s) : {a} ∩ s = {a} := show insert a ∅ ∩ s = insert a ∅, by rw [insert_inter_of_mem H, empty_inter] @[simp] theorem singleton_inter_of_not_mem {a : α} {s : finset α} (H : a ∉ s) : {a} ∩ s = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_singleton]; rintro x ⟨rfl, h⟩; exact H h @[simp] theorem inter_singleton_of_mem {a : α} {s : finset α} (h : a ∈ s) : s ∩ {a} = {a} := by rw [inter_comm, singleton_inter_of_mem h] @[simp] theorem inter_singleton_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : s ∩ {a} = ∅ := by rw [inter_comm, singleton_inter_of_not_mem h] @[mono] lemma inter_subset_inter {x y s t : finset α} (h : x ⊆ y) (h' : s ⊆ t) : x ∩ s ⊆ y ∩ t := begin intros a a_in, rw finset.mem_inter at a_in ⊢, exact ⟨h a_in.1, h' a_in.2⟩ end lemma inter_subset_inter_right {x y s : finset α} (h : x ⊆ y) : x ∩ s ⊆ y ∩ s := finset.inter_subset_inter h (finset.subset.refl _) lemma inter_subset_inter_left {x y s : finset α} (h : x ⊆ y) : s ∩ x ⊆ s ∩ y := finset.inter_subset_inter (finset.subset.refl _) h /-! ### lattice laws -/ instance : lattice (finset α) := { sup := (∪), sup_le := assume a b c, union_subset, le_sup_left := subset_union_left, le_sup_right := subset_union_right, inf := (∩), le_inf := assume a b c, subset_inter, inf_le_left := inter_subset_left, inf_le_right := inter_subset_right, ..finset.partial_order } @[simp] theorem sup_eq_union : ((⊔) : finset α → finset α → finset α) = (∪) := rfl @[simp] theorem inf_eq_inter : ((⊓) : finset α → finset α → finset α) = (∩) := rfl instance : semilattice_inf_bot (finset α) := { bot := ∅, bot_le := empty_subset, ..finset.lattice } @[simp] lemma bot_eq_empty : (⊥ : finset α) = ∅ := rfl instance {α : Type*} [decidable_eq α] : semilattice_sup_bot (finset α) := { ..finset.semilattice_inf_bot, ..finset.lattice } instance : distrib_lattice (finset α) := { le_sup_inf := assume a b c, show (a ∪ b) ∩ (a ∪ c) ⊆ a ∪ b ∩ c, by simp only [subset_iff, mem_inter, mem_union, and_imp, or_imp_distrib] {contextual:=tt}; simp only [true_or, imp_true_iff, true_and, or_true], ..finset.lattice } theorem inter_distrib_left (s t u : finset α) : s ∩ (t ∪ u) = (s ∩ t) ∪ (s ∩ u) := inf_sup_left theorem inter_distrib_right (s t u : finset α) : (s ∪ t) ∩ u = (s ∩ u) ∪ (t ∩ u) := inf_sup_right theorem union_distrib_left (s t u : finset α) : s ∪ (t ∩ u) = (s ∪ t) ∩ (s ∪ u) := sup_inf_left theorem union_distrib_right (s t u : finset α) : (s ∩ t) ∪ u = (s ∪ u) ∩ (t ∪ u) := sup_inf_right lemma union_eq_empty_iff (A B : finset α) : A ∪ B = ∅ ↔ A = ∅ ∧ B = ∅ := sup_eq_bot_iff lemma union_subset_iff {s₁ s₂ s₃ : finset α} : s₁ ∪ s₂ ⊆ s₃ ↔ s₁ ⊆ s₃ ∧ s₂ ⊆ s₃ := (sup_le_iff : s₁ ⊔ s₂ ≤ s₃ ↔ s₁ ≤ s₃ ∧ s₂ ≤ s₃) lemma subset_inter_iff {s₁ s₂ s₃ : finset α} : s₁ ⊆ s₂ ∩ s₃ ↔ s₁ ⊆ s₂ ∧ s₁ ⊆ s₃ := (le_inf_iff : s₁ ≤ s₂ ⊓ s₃ ↔ s₁ ≤ s₂ ∧ s₁ ≤ s₃) theorem inter_eq_left_iff_subset (s t : finset α) : s ∩ t = s ↔ s ⊆ t := (inf_eq_left : s ⊓ t = s ↔ s ≤ t) theorem inter_eq_right_iff_subset (s t : finset α) : t ∩ s = s ↔ s ⊆ t := (inf_eq_right : t ⊓ s = s ↔ s ≤ t) /-! ### erase -/ /-- `erase s a` is the set `s - {a}`, that is, the elements of `s` which are not equal to `a`. -/ def erase (s : finset α) (a : α) : finset α := ⟨_, nodup_erase_of_nodup a s.2⟩ @[simp] theorem erase_val (s : finset α) (a : α) : (erase s a).1 = s.1.erase a := rfl @[simp] theorem mem_erase {a b : α} {s : finset α} : a ∈ erase s b ↔ a ≠ b ∧ a ∈ s := mem_erase_iff_of_nodup s.2 theorem not_mem_erase (a : α) (s : finset α) : a ∉ erase s a := mem_erase_of_nodup s.2 -- While this can be solved by `simp`, this lemma is eligible for `dsimp` @[nolint simp_nf, simp] theorem erase_empty (a : α) : erase ∅ a = ∅ := rfl theorem ne_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ≠ a := by simp only [mem_erase]; exact and.left theorem mem_of_mem_erase {a b : α} {s : finset α} : b ∈ erase s a → b ∈ s := mem_of_mem_erase theorem mem_erase_of_ne_of_mem {a b : α} {s : finset α} : a ≠ b → a ∈ s → a ∈ erase s b := by simp only [mem_erase]; exact and.intro /-- An element of `s` that is not an element of `erase s a` must be `a`. -/ lemma eq_of_mem_of_not_mem_erase {a b : α} {s : finset α} (hs : b ∈ s) (hsa : b ∉ s.erase a) : b = a := begin rw [mem_erase, not_and] at hsa, exact not_imp_not.mp hsa hs end theorem erase_insert {a : α} {s : finset α} (h : a ∉ s) : erase (insert a s) a = s := ext $ assume x, by simp only [mem_erase, mem_insert, and_or_distrib_left, not_and_self, false_or]; apply and_iff_right_of_imp; rintro H rfl; exact h H theorem insert_erase {a : α} {s : finset α} (h : a ∈ s) : insert a (erase s a) = s := ext $ assume x, by simp only [mem_insert, mem_erase, or_and_distrib_left, dec_em, true_and]; apply or_iff_right_of_imp; rintro rfl; exact h theorem erase_subset_erase (a : α) {s t : finset α} (h : s ⊆ t) : erase s a ⊆ erase t a := val_le_iff.1 $ erase_le_erase _ $ val_le_iff.2 h theorem erase_subset (a : α) (s : finset α) : erase s a ⊆ s := erase_subset _ _ @[simp, norm_cast] lemma coe_erase (a : α) (s : finset α) : ↑(erase s a) = (s \ {a} : set α) := set.ext $ λ _, mem_erase.trans $ by rw [and_comm, set.mem_diff, set.mem_singleton_iff]; refl lemma erase_ssubset {a : α} {s : finset α} (h : a ∈ s) : s.erase a ⊂ s := calc s.erase a ⊂ insert a (s.erase a) : ssubset_insert $ not_mem_erase _ _ ... = _ : insert_erase h @[simp] theorem erase_eq_of_not_mem {a : α} {s : finset α} (h : a ∉ s) : erase s a = s := eq_of_veq $ erase_of_not_mem h theorem subset_insert_iff {a : α} {s t : finset α} : s ⊆ insert a t ↔ erase s a ⊆ t := by simp only [subset_iff, or_iff_not_imp_left, mem_erase, mem_insert, and_imp]; exact forall_congr (λ x, forall_swap) theorem erase_insert_subset (a : α) (s : finset α) : erase (insert a s) a ⊆ s := subset_insert_iff.1 $ subset.refl _ theorem insert_erase_subset (a : α) (s : finset α) : s ⊆ insert a (erase s a) := subset_insert_iff.2 $ subset.refl _ lemma erase_inj {x y : α} (s : finset α) (hx : x ∈ s) : s.erase x = s.erase y ↔ x = y := begin refine ⟨λ h, _, congr_arg _⟩, rw eq_of_mem_of_not_mem_erase hx, rw ←h, simp, end lemma erase_inj_on (s : finset α) : set.inj_on s.erase s := λ _ _ _ _, (erase_inj s ‹_›).mp /-! ### sdiff -/ /-- `s \ t` is the set consisting of the elements of `s` that are not in `t`. -/ instance : has_sdiff (finset α) := ⟨λs₁ s₂, ⟨s₁.1 - s₂.1, nodup_of_le sub_le_self' s₁.2⟩⟩ @[simp] lemma sdiff_val (s₁ s₂ : finset α) : (s₁ \ s₂).val = s₁.val - s₂.val := rfl @[simp] theorem mem_sdiff {a : α} {s₁ s₂ : finset α} : a ∈ s₁ \ s₂ ↔ a ∈ s₁ ∧ a ∉ s₂ := mem_sub_of_nodup s₁.2 @[simp] theorem inter_sdiff_self (s₁ s₂ : finset α) : s₁ ∩ (s₂ \ s₁) = ∅ := eq_empty_of_forall_not_mem $ by simp only [mem_inter, mem_sdiff]; rintro x ⟨h, _, hn⟩; exact hn h instance : generalized_boolean_algebra (finset α) := { sup_inf_sdiff := λ x y, by { simp only [ext_iff, mem_union, mem_sdiff, inf_eq_inter, sup_eq_union, mem_inter], tauto }, inf_inf_sdiff := λ x y, by { simp only [ext_iff, inter_sdiff_self, inter_empty, inter_assoc, false_iff, inf_eq_inter, not_mem_empty], tauto }, ..finset.has_sdiff, ..finset.distrib_lattice, ..finset.semilattice_inf_bot } lemma not_mem_sdiff_of_mem_right {a : α} {s t : finset α} (h : a ∈ t) : a ∉ s \ t := by simp only [mem_sdiff, h, not_true, not_false_iff, and_false] theorem union_sdiff_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁ ∪ (s₂ \ s₁) = s₂ := sup_sdiff_of_le h theorem sdiff_union_of_subset {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : (s₂ \ s₁) ∪ s₁ = s₂ := (union_comm _ _).trans (union_sdiff_of_subset h) theorem inter_sdiff (s t u : finset α) : s ∩ (t \ u) = s ∩ t \ u := by { ext x, simp [and_assoc] } @[simp] theorem sdiff_inter_self (s₁ s₂ : finset α) : (s₂ \ s₁) ∩ s₁ = ∅ := inf_sdiff_self_left @[simp] theorem sdiff_self (s₁ : finset α) : s₁ \ s₁ = ∅ := sdiff_self theorem sdiff_inter_distrib_right (s₁ s₂ s₃ : finset α) : s₁ \ (s₂ ∩ s₃) = (s₁ \ s₂) ∪ (s₁ \ s₃) := sdiff_inf @[simp] theorem sdiff_inter_self_left (s₁ s₂ : finset α) : s₁ \ (s₁ ∩ s₂) = s₁ \ s₂ := sdiff_inf_self_left @[simp] theorem sdiff_inter_self_right (s₁ s₂ : finset α) : s₁ \ (s₂ ∩ s₁) = s₁ \ s₂ := sdiff_inf_self_right @[simp] theorem sdiff_empty {s₁ : finset α} : s₁ \ ∅ = s₁ := sdiff_bot @[mono] theorem sdiff_subset_sdiff {s₁ s₂ t₁ t₂ : finset α} (h₁ : t₁ ⊆ t₂) (h₂ : s₂ ⊆ s₁) : t₁ \ s₁ ⊆ t₂ \ s₂ := sdiff_le_sdiff ‹t₁ ≤ t₂› ‹s₂ ≤ s₁› @[simp, norm_cast] lemma coe_sdiff (s₁ s₂ : finset α) : ↑(s₁ \ s₂) = (s₁ \ s₂ : set α) := set.ext $ λ _, mem_sdiff @[simp] theorem union_sdiff_self_eq_union {s t : finset α} : s ∪ (t \ s) = s ∪ t := sup_sdiff_self_right @[simp] theorem sdiff_union_self_eq_union {s t : finset α} : (s \ t) ∪ t = s ∪ t := sup_sdiff_self_left lemma union_sdiff_symm {s t : finset α} : s ∪ (t \ s) = t ∪ (s \ t) := sup_sdiff_symm lemma sdiff_union_inter (s t : finset α) : (s \ t) ∪ (s ∩ t) = s := by { rw union_comm, exact sup_inf_sdiff _ _ } @[simp] lemma sdiff_idem (s t : finset α) : s \ t \ t = s \ t := sdiff_idem lemma sdiff_eq_empty_iff_subset {s t : finset α} : s \ t = ∅ ↔ s ⊆ t := sdiff_eq_bot_iff @[simp] lemma empty_sdiff (s : finset α) : ∅ \ s = ∅ := bot_sdiff lemma insert_sdiff_of_not_mem (s : finset α) {t : finset α} {x : α} (h : x ∉ t) : (insert x s) \ t = insert x (s \ t) := begin rw [← coe_inj, coe_insert, coe_sdiff, coe_sdiff, coe_insert], exact set.insert_diff_of_not_mem s h end lemma insert_sdiff_of_mem (s : finset α) {t : finset α} {x : α} (h : x ∈ t) : (insert x s) \ t = s \ t := begin rw [← coe_inj, coe_sdiff, coe_sdiff, coe_insert], exact set.insert_diff_of_mem s h end @[simp] lemma insert_sdiff_insert (s t : finset α) (x : α) : (insert x s) \ (insert x t) = s \ insert x t := insert_sdiff_of_mem _ (mem_insert_self _ _) lemma sdiff_insert_of_not_mem {s : finset α} {x : α} (h : x ∉ s) (t : finset α) : s \ (insert x t) = s \ t := begin refine subset.antisymm (sdiff_subset_sdiff (subset.refl _) (subset_insert _ _)) (λ y hy, _), simp only [mem_sdiff, mem_insert, not_or_distrib] at hy ⊢, exact ⟨hy.1, λ hxy, h $ hxy ▸ hy.1, hy.2⟩ end @[simp] lemma sdiff_subset (s t : finset α) : s \ t ⊆ s := show s \ t ≤ s, from sdiff_le lemma sdiff_ssubset {s t : finset α} (h : t ⊆ s) (ht : t.nonempty) : s \ t ⊂ s := sdiff_lt (le_iff_subset.2 h) ht.ne_empty lemma union_sdiff_distrib (s₁ s₂ t : finset α) : (s₁ ∪ s₂) \ t = s₁ \ t ∪ s₂ \ t := sup_sdiff lemma sdiff_union_distrib (s t₁ t₂ : finset α) : s \ (t₁ ∪ t₂) = (s \ t₁) ∩ (s \ t₂) := sdiff_sup lemma union_sdiff_self (s t : finset α) : (s ∪ t) \ t = s \ t := sup_sdiff_right_self lemma sdiff_singleton_eq_erase (a : α) (s : finset α) : s \ singleton a = erase s a := by { ext, rw [mem_erase, mem_sdiff, mem_singleton], tauto } @[simp] lemma sdiff_singleton_not_mem_eq_self (s : finset α) {a : α} (ha : a ∉ s) : s \ {a} = s := by simp only [sdiff_singleton_eq_erase, ha, erase_eq_of_not_mem, not_false_iff] lemma sdiff_sdiff_self_left (s t : finset α) : s \ (s \ t) = s ∩ t := sdiff_sdiff_right_self lemma sdiff_eq_sdiff_iff_inter_eq_inter {s t₁ t₂ : finset α} : s \ t₁ = s \ t₂ ↔ s ∩ t₁ = s ∩ t₂ := sdiff_eq_sdiff_iff_inf_eq_inf lemma union_eq_sdiff_union_sdiff_union_inter (s t : finset α) : s ∪ t = (s \ t) ∪ (t \ s) ∪ (s ∩ t) := sup_eq_sdiff_sup_sdiff_sup_inf end decidable_eq /-! ### attach -/ /-- `attach s` takes the elements of `s` and forms a new set of elements of the subtype `{x // x ∈ s}`. -/ def attach (s : finset α) : finset {x // x ∈ s} := ⟨attach s.1, nodup_attach.2 s.2⟩ theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : finset α} (hx : x ∈ s) : sizeof x < sizeof s := by { cases s, dsimp [sizeof, has_sizeof.sizeof, finset.sizeof], apply lt_add_left, exact multiset.sizeof_lt_sizeof_of_mem hx } @[simp] theorem attach_val (s : finset α) : s.attach.1 = s.1.attach := rfl @[simp] theorem mem_attach (s : finset α) : ∀ x, x ∈ s.attach := mem_attach _ @[simp] theorem attach_empty : attach (∅ : finset α) = ∅ := rfl @[simp] lemma attach_nonempty_iff (s : finset α) : s.attach.nonempty ↔ s.nonempty := by simp [finset.nonempty] @[simp] lemma attach_eq_empty_iff (s : finset α) : s.attach = ∅ ↔ s = ∅ := by simpa [eq_empty_iff_forall_not_mem] /-! ### piecewise -/ section piecewise /-- `s.piecewise f g` is the function equal to `f` on the finset `s`, and to `g` on its complement. -/ def piecewise {α : Type*} {δ : α → Sort*} (s : finset α) (f g : Πi, δ i) [∀j, decidable (j ∈ s)] : Πi, δ i := λi, if i ∈ s then f i else g i variables {δ : α → Sort*} (s : finset α) (f g : Πi, δ i) @[simp] lemma piecewise_insert_self [decidable_eq α] {j : α} [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g j = f j := by simp [piecewise] @[simp] lemma piecewise_empty [∀i : α, decidable (i ∈ (∅ : finset α))] : piecewise ∅ f g = g := by { ext i, simp [piecewise] } variable [∀j, decidable (j ∈ s)] @[norm_cast] lemma piecewise_coe [∀j, decidable (j ∈ (s : set α))] : (s : set α).piecewise f g = s.piecewise f g := by { ext, congr } @[simp, priority 980] lemma piecewise_eq_of_mem {i : α} (hi : i ∈ s) : s.piecewise f g i = f i := by simp [piecewise, hi] @[simp, priority 980] lemma piecewise_eq_of_not_mem {i : α} (hi : i ∉ s) : s.piecewise f g i = g i := by simp [piecewise, hi] lemma piecewise_congr {f f' g g' : Π i, δ i} (hf : ∀ i ∈ s, f i = f' i) (hg : ∀ i ∉ s, g i = g' i) : s.piecewise f g = s.piecewise f' g' := funext $ λ i, if_ctx_congr iff.rfl (hf i) (hg i) @[simp, priority 990] lemma piecewise_insert_of_ne [decidable_eq α] {i j : α} [∀i, decidable (i ∈ insert j s)] (h : i ≠ j) : (insert j s).piecewise f g i = s.piecewise f g i := by simp [piecewise, h] lemma piecewise_insert [decidable_eq α] (j : α) [∀i, decidable (i ∈ insert j s)] : (insert j s).piecewise f g = update (s.piecewise f g) j (f j) := begin classical, rw [← piecewise_coe, ← piecewise_coe, ← set.piecewise_insert, ← coe_insert j s], congr end lemma piecewise_cases {i} (p : δ i → Prop) (hf : p (f i)) (hg : p (g i)) : p (s.piecewise f g i) := by by_cases hi : i ∈ s; simpa [hi] lemma piecewise_mem_set_pi {δ : α → Type*} {t : set α} {t' : Π i, set (δ i)} {f g} (hf : f ∈ set.pi t t') (hg : g ∈ set.pi t t') : s.piecewise f g ∈ set.pi t t' := by { classical, rw ← piecewise_coe, exact set.piecewise_mem_pi ↑s hf hg } lemma piecewise_singleton [decidable_eq α] (i : α) : piecewise {i} f g = update g i (f i) := by rw [← insert_emptyc_eq, piecewise_insert, piecewise_empty] lemma piecewise_piecewise_of_subset_left {s t : finset α} [Π i, decidable (i ∈ s)] [Π i, decidable (i ∈ t)] (h : s ⊆ t) (f₁ f₂ g : Π a, δ a) : s.piecewise (t.piecewise f₁ f₂) g = s.piecewise f₁ g := s.piecewise_congr (λ i hi, piecewise_eq_of_mem _ _ _ (h hi)) (λ _ _, rfl) @[simp] lemma piecewise_idem_left (f₁ f₂ g : Π a, δ a) : s.piecewise (s.piecewise f₁ f₂) g = s.piecewise f₁ g := piecewise_piecewise_of_subset_left (subset.refl _) _ _ _ lemma piecewise_piecewise_of_subset_right {s t : finset α} [Π i, decidable (i ∈ s)] [Π i, decidable (i ∈ t)] (h : t ⊆ s) (f g₁ g₂ : Π a, δ a) : s.piecewise f (t.piecewise g₁ g₂) = s.piecewise f g₂ := s.piecewise_congr (λ _ _, rfl) (λ i hi, t.piecewise_eq_of_not_mem _ _ (mt (@h _) hi)) @[simp] lemma piecewise_idem_right (f g₁ g₂ : Π a, δ a) : s.piecewise f (s.piecewise g₁ g₂) = s.piecewise f g₂ := piecewise_piecewise_of_subset_right (subset.refl _) f g₁ g₂ lemma update_eq_piecewise {β : Type*} [decidable_eq α] (f : α → β) (i : α) (v : β) : update f i v = piecewise (singleton i) (λj, v) f := (piecewise_singleton _ _ _).symm lemma update_piecewise [decidable_eq α] (i : α) (v : δ i) : update (s.piecewise f g) i v = s.piecewise (update f i v) (update g i v) := begin ext j, rcases em (j = i) with (rfl|hj); by_cases hs : j ∈ s; simp * end lemma update_piecewise_of_mem [decidable_eq α] {i : α} (hi : i ∈ s) (v : δ i) : update (s.piecewise f g) i v = s.piecewise (update f i v) g := begin rw update_piecewise, refine s.piecewise_congr (λ _ _, rfl) (λ j hj, update_noteq _ _ _), exact λ h, hj (h.symm ▸ hi) end lemma update_piecewise_of_not_mem [decidable_eq α] {i : α} (hi : i ∉ s) (v : δ i) : update (s.piecewise f g) i v = s.piecewise f (update g i v) := begin rw update_piecewise, refine s.piecewise_congr (λ j hj, update_noteq _ _ _) (λ _ _, rfl), exact λ h, hi (h ▸ hj) end lemma piecewise_le_of_le_of_le {δ : α → Type*} [Π i, preorder (δ i)] {f g h : Π i, δ i} (Hf : f ≤ h) (Hg : g ≤ h) : s.piecewise f g ≤ h := λ x, piecewise_cases s f g (≤ h x) (Hf x) (Hg x) lemma le_piecewise_of_le_of_le {δ : α → Type*} [Π i, preorder (δ i)] {f g h : Π i, δ i} (Hf : h ≤ f) (Hg : h ≤ g) : h ≤ s.piecewise f g := λ x, piecewise_cases s f g (λ y, h x ≤ y) (Hf x) (Hg x) lemma piecewise_le_piecewise' {δ : α → Type*} [Π i, preorder (δ i)] {f g f' g' : Π i, δ i} (Hf : ∀ x ∈ s, f x ≤ f' x) (Hg : ∀ x ∉ s, g x ≤ g' x) : s.piecewise f g ≤ s.piecewise f' g' := λ x, by { by_cases hx : x ∈ s; simp [hx, *] } lemma piecewise_le_piecewise {δ : α → Type*} [Π i, preorder (δ i)] {f g f' g' : Π i, δ i} (Hf : f ≤ f') (Hg : g ≤ g') : s.piecewise f g ≤ s.piecewise f' g' := s.piecewise_le_piecewise' (λ x _, Hf x) (λ x _, Hg x) lemma piecewise_mem_Icc_of_mem_of_mem {δ : α → Type*} [Π i, preorder (δ i)] {f f₁ g g₁ : Π i, δ i} (hf : f ∈ set.Icc f₁ g₁) (hg : g ∈ set.Icc f₁ g₁) : s.piecewise f g ∈ set.Icc f₁ g₁ := ⟨le_piecewise_of_le_of_le _ hf.1 hg.1, piecewise_le_of_le_of_le _ hf.2 hg.2⟩ lemma piecewise_mem_Icc {δ : α → Type*} [Π i, preorder (δ i)] {f g : Π i, δ i} (h : f ≤ g) : s.piecewise f g ∈ set.Icc f g := piecewise_mem_Icc_of_mem_of_mem _ (set.left_mem_Icc.2 h) (set.right_mem_Icc.2 h) lemma piecewise_mem_Icc' {δ : α → Type*} [Π i, preorder (δ i)] {f g : Π i, δ i} (h : g ≤ f) : s.piecewise f g ∈ set.Icc g f := piecewise_mem_Icc_of_mem_of_mem _ (set.right_mem_Icc.2 h) (set.left_mem_Icc.2 h) end piecewise section decidable_pi_exists variables {s : finset α} instance decidable_dforall_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∀a (h : a ∈ s), p a h) := multiset.decidable_dforall_multiset /-- decidable equality for functions whose domain is bounded by finsets -/ instance decidable_eq_pi_finset {β : α → Type*} [h : ∀a, decidable_eq (β a)] : decidable_eq (Πa∈s, β a) := multiset.decidable_eq_pi_multiset instance decidable_dexists_finset {p : Πa∈s, Prop} [hp : ∀a (h : a ∈ s), decidable (p a h)] : decidable (∃a (h : a ∈ s), p a h) := multiset.decidable_dexists_multiset end decidable_pi_exists /-! ### filter -/ section filter variables (p q : α → Prop) [decidable_pred p] [decidable_pred q] /-- `filter p s` is the set of elements of `s` that satisfy `p`. -/ def filter (s : finset α) : finset α := ⟨_, nodup_filter p s.2⟩ @[simp] theorem filter_val (s : finset α) : (filter p s).1 = s.1.filter p := rfl @[simp] theorem filter_subset (s : finset α) : s.filter p ⊆ s := filter_subset _ _ variable {p} @[simp] theorem mem_filter {s : finset α} {a : α} : a ∈ s.filter p ↔ a ∈ s ∧ p a := mem_filter theorem filter_ssubset {s : finset α} : s.filter p ⊂ s ↔ ∃ x ∈ s, ¬ p x := ⟨λ h, let ⟨x, hs, hp⟩ := set.exists_of_ssubset h in ⟨x, hs, mt (λ hp, mem_filter.2 ⟨hs, hp⟩) hp⟩, λ ⟨x, hs, hp⟩, ⟨s.filter_subset _, λ h, hp (mem_filter.1 (h hs)).2⟩⟩ variable (p) theorem filter_filter (s : finset α) : (s.filter p).filter q = s.filter (λa, p a ∧ q a) := ext $ assume a, by simp only [mem_filter, and_comm, and.left_comm] lemma filter_true {s : finset α} [h : decidable_pred (λ _, true)] : @finset.filter α (λ _, true) h s = s := by ext; simp @[simp] theorem filter_false {h} (s : finset α) : @filter α (λa, false) h s = ∅ := ext $ assume a, by simp only [mem_filter, and_false]; refl variables {p q} /-- If all elements of a `finset` satisfy the predicate `p`, `s.filter p` is `s`. -/ @[simp] lemma filter_true_of_mem {s : finset α} (h : ∀ x ∈ s, p x) : s.filter p = s := ext $ λ x, ⟨λ h, (mem_filter.1 h).1, λ hx, mem_filter.2 ⟨hx, h x hx⟩⟩ /-- If all elements of a `finset` fail to satisfy the predicate `p`, `s.filter p` is `∅`. -/ lemma filter_false_of_mem {s : finset α} (h : ∀ x ∈ s, ¬ p x) : s.filter p = ∅ := eq_empty_of_forall_not_mem (by simpa) lemma filter_congr {s : finset α} (H : ∀ x ∈ s, p x ↔ q x) : filter p s = filter q s := eq_of_veq $ filter_congr H variables (p q) lemma filter_empty : filter p ∅ = ∅ := subset_empty.1 $ filter_subset _ _ lemma filter_subset_filter {s t : finset α} (h : s ⊆ t) : s.filter p ⊆ t.filter p := assume a ha, mem_filter.2 ⟨h (mem_filter.1 ha).1, (mem_filter.1 ha).2⟩ lemma monotone_filter_left (p : α → Prop) [decidable_pred p] : monotone (filter p) := λ _ _, filter_subset_filter p lemma monotone_filter_right (s : finset α) ⦃p q : α → Prop⦄ [decidable_pred p] [decidable_pred q] (h : p ≤ q) : s.filter p ≤ s.filter q := multiset.subset_of_le (multiset.monotone_filter_right s.val h) @[simp, norm_cast] lemma coe_filter (s : finset α) : ↑(s.filter p) = ({x ∈ ↑s | p x} : set α) := set.ext $ λ _, mem_filter theorem filter_singleton (a : α) : filter p (singleton a) = if p a then singleton a else ∅ := by { classical, ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } variable [decidable_eq α] theorem filter_union (s₁ s₂ : finset α) : (s₁ ∪ s₂).filter p = s₁.filter p ∪ s₂.filter p := ext $ λ _, by simp only [mem_filter, mem_union, or_and_distrib_right] theorem filter_union_right (s : finset α) : s.filter p ∪ s.filter q = s.filter (λx, p x ∨ q x) := ext $ λ x, by simp only [mem_filter, mem_union, and_or_distrib_left.symm] lemma filter_mem_eq_inter {s t : finset α} [Π i, decidable (i ∈ t)] : s.filter (λ i, i ∈ t) = s ∩ t := ext $ λ i, by rw [mem_filter, mem_inter] theorem filter_inter (s t : finset α) : filter p s ∩ t = filter p (s ∩ t) := by { ext, simp only [mem_inter, mem_filter, and.right_comm] } theorem inter_filter (s t : finset α) : s ∩ filter p t = filter p (s ∩ t) := by rw [inter_comm, filter_inter, inter_comm] theorem filter_insert (a : α) (s : finset α) : filter p (insert a s) = if p a then insert a (filter p s) else filter p s := by { ext x, simp, split_ifs with h; by_cases h' : x = a; simp [h, h'] } theorem filter_or [decidable_pred (λ a, p a ∨ q a)] (s : finset α) : s.filter (λ a, p a ∨ q a) = s.filter p ∪ s.filter q := ext $ λ _, by simp only [mem_filter, mem_union, and_or_distrib_left] theorem filter_and [decidable_pred (λ a, p a ∧ q a)] (s : finset α) : s.filter (λ a, p a ∧ q a) = s.filter p ∩ s.filter q := ext $ λ _, by simp only [mem_filter, mem_inter, and_comm, and.left_comm, and_self] theorem filter_not [decidable_pred (λ a, ¬ p a)] (s : finset α) : s.filter (λ a, ¬ p a) = s \ s.filter p := ext $ by simpa only [mem_filter, mem_sdiff, and_comm, not_and] using λ a, and_congr_right $ λ h : a ∈ s, (imp_iff_right h).symm.trans imp_not_comm theorem sdiff_eq_filter (s₁ s₂ : finset α) : s₁ \ s₂ = filter (∉ s₂) s₁ := ext $ λ _, by simp only [mem_sdiff, mem_filter] theorem sdiff_eq_self (s₁ s₂ : finset α) : s₁ \ s₂ = s₁ ↔ s₁ ∩ s₂ ⊆ ∅ := by { simp [subset.antisymm_iff], split; intro h, { transitivity' ((s₁ \ s₂) ∩ s₂), mono, simp }, { calc s₁ \ s₂ ⊇ s₁ \ (s₁ ∩ s₂) : by simp [(⊇)] ... ⊇ s₁ \ ∅ : by mono using [(⊇)] ... ⊇ s₁ : by simp [(⊇)] } } theorem filter_union_filter_neg_eq [decidable_pred (λ a, ¬ p a)] (s : finset α) : s.filter p ∪ s.filter (λa, ¬ p a) = s := by simp only [filter_not, union_sdiff_of_subset (filter_subset p s)] theorem filter_inter_filter_neg_eq [decidable_pred (λ a, ¬ p a)] (s : finset α) : s.filter p ∩ s.filter (λa, ¬ p a) = ∅ := by simp only [filter_not, inter_sdiff_self] lemma subset_union_elim {s : finset α} {t₁ t₂ : set α} (h : ↑s ⊆ t₁ ∪ t₂) : ∃s₁ s₂ : finset α, s₁ ∪ s₂ = s ∧ ↑s₁ ⊆ t₁ ∧ ↑s₂ ⊆ t₂ \ t₁ := begin classical, refine ⟨s.filter (∈ t₁), s.filter (∉ t₁), _, _ , _⟩, { simp [filter_union_right, em] }, { intro x, simp }, { intro x, simp, intros hx hx₂, refine ⟨or.resolve_left (h hx) hx₂, hx₂⟩ } end /- We can simplify an application of filter where the decidability is inferred in "the wrong way" -/ @[simp] lemma filter_congr_decidable {α} (s : finset α) (p : α → Prop) (h : decidable_pred p) [decidable_pred p] : @filter α p h s = s.filter p := by congr section classical open_locale classical /-- The following instance allows us to write `{x ∈ s | p x}` for `finset.filter p s`. Since the former notation requires us to define this for all propositions `p`, and `finset.filter` only works for decidable propositions, the notation `{x ∈ s | p x}` is only compatible with classical logic because it uses `classical.prop_decidable`. We don't want to redo all lemmas of `finset.filter` for `has_sep.sep`, so we make sure that `simp` unfolds the notation `{x ∈ s | p x}` to `finset.filter p s`. If `p` happens to be decidable, the simp-lemma `finset.filter_congr_decidable` will make sure that `finset.filter` uses the right instance for decidability. -/ noncomputable instance {α : Type*} : has_sep α (finset α) := ⟨λ p x, x.filter p⟩ @[simp] lemma sep_def {α : Type*} (s : finset α) (p : α → Prop) : {x ∈ s | p x} = s.filter p := rfl end classical /-- After filtering out everything that does not equal a given value, at most that value remains. This is equivalent to `filter_eq'` with the equality the other way. -/ -- This is not a good simp lemma, as it would prevent `finset.mem_filter` from firing -- on, e.g. `x ∈ s.filter(eq b)`. lemma filter_eq [decidable_eq β] (s : finset β) (b : β) : s.filter (eq b) = ite (b ∈ s) {b} ∅ := begin split_ifs, { ext, simp only [mem_filter, mem_singleton], exact ⟨λ h, h.2.symm, by { rintro ⟨h⟩, exact ⟨h, rfl⟩, }⟩ }, { ext, simp only [mem_filter, not_and, iff_false, not_mem_empty], rintros m ⟨e⟩, exact h m, } end /-- After filtering out everything that does not equal a given value, at most that value remains. This is equivalent to `filter_eq` with the equality the other way. -/ lemma filter_eq' [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, a = b) = ite (b ∈ s) {b} ∅ := trans (filter_congr (λ _ _, ⟨eq.symm, eq.symm⟩)) (filter_eq s b) lemma filter_ne [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, b ≠ a) = s.erase b := by { ext, simp only [mem_filter, mem_erase, ne.def], tauto, } lemma filter_ne' [decidable_eq β] (s : finset β) (b : β) : s.filter (λ a, a ≠ b) = s.erase b := trans (filter_congr (λ _ _, ⟨ne.symm, ne.symm⟩)) (filter_ne s b) end filter /-! ### range -/ section range variables {n m l : ℕ} /-- `range n` is the set of natural numbers less than `n`. -/ def range (n : ℕ) : finset ℕ := ⟨_, nodup_range n⟩ @[simp] theorem range_coe (n : ℕ) : (range n).1 = multiset.range n := rfl @[simp] theorem mem_range : m ∈ range n ↔ m < n := mem_range @[simp] theorem range_zero : range 0 = ∅ := rfl @[simp] theorem range_one : range 1 = {0} := rfl theorem range_succ : range (succ n) = insert n (range n) := eq_of_veq $ (range_succ n).trans $ (ndinsert_of_not_mem not_mem_range_self).symm theorem range_add_one : range (n + 1) = insert n (range n) := range_succ @[simp] theorem not_mem_range_self : n ∉ range n := not_mem_range_self @[simp] theorem self_mem_range_succ (n : ℕ) : n ∈ range (n + 1) := multiset.self_mem_range_succ n @[simp] theorem range_subset {n m} : range n ⊆ range m ↔ n ≤ m := range_subset theorem range_mono : monotone range := λ _ _, range_subset.2 lemma mem_range_succ_iff {a b : ℕ} : a ∈ finset.range b.succ ↔ a ≤ b := finset.mem_range.trans nat.lt_succ_iff lemma mem_range_le {n x : ℕ} (hx : x ∈ range n) : x ≤ n := (mem_range.1 hx).le lemma mem_range_sub_ne_zero {n x : ℕ} (hx : x ∈ range n) : n - x ≠ 0 := ne_of_gt $ nat.sub_pos_of_lt $ mem_range.1 hx @[simp] lemma nonempty_range_iff : (range n).nonempty ↔ n ≠ 0 := ⟨λ ⟨k, hk⟩, ((zero_le k).trans_lt $ mem_range.1 hk).ne', λ h, ⟨0, mem_range.2 $ pos_iff_ne_zero.2 h⟩⟩ @[simp] lemma range_eq_empty_iff : range n = ∅ ↔ n = 0 := by rw [← not_nonempty_iff_eq_empty, nonempty_range_iff, not_not] lemma nonempty_range_succ : (range $ n + 1).nonempty := nonempty_range_iff.2 n.succ_ne_zero end range /- useful rules for calculations with quantifiers -/ theorem exists_mem_empty_iff (p : α → Prop) : (∃ x, x ∈ (∅ : finset α) ∧ p x) ↔ false := by simp only [not_mem_empty, false_and, exists_false] theorem exists_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∃ x, x ∈ insert a s ∧ p x) ↔ p a ∨ (∃ x, x ∈ s ∧ p x) := by simp only [mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] theorem forall_mem_empty_iff (p : α → Prop) : (∀ x, x ∈ (∅ : finset α) → p x) ↔ true := iff_true_intro $ λ _, false.elim theorem forall_mem_insert [d : decidable_eq α] (a : α) (s : finset α) (p : α → Prop) : (∀ x, x ∈ insert a s → p x) ↔ p a ∧ (∀ x, x ∈ s → p x) := by simp only [mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] end finset /-- Equivalence between the set of natural numbers which are `≥ k` and `ℕ`, given by `n → n - k`. -/ def not_mem_range_equiv (k : ℕ) : {n // n ∉ range k} ≃ ℕ := { to_fun := λ i, i.1 - k, inv_fun := λ j, ⟨j + k, by simp⟩, left_inv := begin assume j, rw subtype.ext_iff_val, apply nat.sub_add_cancel, simpa using j.2 end, right_inv := λ j, nat.add_sub_cancel _ _ } @[simp] lemma coe_not_mem_range_equiv (k : ℕ) : (not_mem_range_equiv k : {n // n ∉ range k} → ℕ) = (λ i, i - k) := rfl @[simp] lemma coe_not_mem_range_equiv_symm (k : ℕ) : ((not_mem_range_equiv k).symm : ℕ → {n // n ∉ range k}) = λ j, ⟨j + k, by simp⟩ := rfl /-! ### erase_dup on list and multiset -/ namespace multiset variable [decidable_eq α] /-- `to_finset s` removes duplicates from the multiset `s` to produce a finset. -/ def to_finset (s : multiset α) : finset α := ⟨_, nodup_erase_dup s⟩ @[simp] theorem to_finset_val (s : multiset α) : s.to_finset.1 = s.erase_dup := rfl theorem to_finset_eq {s : multiset α} (n : nodup s) : finset.mk s n = s.to_finset := finset.val_inj.1 n.erase_dup.symm lemma nodup.to_finset_inj {l l' : multiset α} (hl : nodup l) (hl' : nodup l') (h : l.to_finset = l'.to_finset) : l = l' := by simpa [←to_finset_eq hl, ←to_finset_eq hl'] using h @[simp] theorem mem_to_finset {a : α} {s : multiset α} : a ∈ s.to_finset ↔ a ∈ s := mem_erase_dup @[simp] lemma to_finset_zero : to_finset (0 : multiset α) = ∅ := rfl @[simp] lemma to_finset_cons (a : α) (s : multiset α) : to_finset (a ::ₘ s) = insert a (to_finset s) := finset.eq_of_veq erase_dup_cons @[simp] lemma to_finset_singleton (a : α) : to_finset ({a} : multiset α) = {a} := by rw [singleton_eq_cons, to_finset_cons, to_finset_zero, is_lawful_singleton.insert_emptyc_eq] @[simp] lemma to_finset_add (s t : multiset α) : to_finset (s + t) = to_finset s ∪ to_finset t := finset.ext $ by simp @[simp] lemma to_finset_nsmul (s : multiset α) : ∀(n : ℕ) (hn : n ≠ 0), (n • s).to_finset = s.to_finset | 0 h := by contradiction | (n+1) h := begin by_cases n = 0, { rw [h, zero_add, one_nsmul] }, { rw [add_nsmul, to_finset_add, one_nsmul, to_finset_nsmul n h, finset.union_idempotent] } end @[simp] lemma to_finset_inter (s t : multiset α) : to_finset (s ∩ t) = to_finset s ∩ to_finset t := finset.ext $ by simp @[simp] lemma to_finset_union (s t : multiset α) : (s ∪ t).to_finset = s.to_finset ∪ t.to_finset := by ext; simp theorem to_finset_eq_empty {m : multiset α} : m.to_finset = ∅ ↔ m = 0 := finset.val_inj.symm.trans multiset.erase_dup_eq_zero @[simp] lemma to_finset_subset (m1 m2 : multiset α) : m1.to_finset ⊆ m2.to_finset ↔ m1 ⊆ m2 := by simp only [finset.subset_iff, multiset.subset_iff, multiset.mem_to_finset] end multiset namespace finset @[simp] lemma val_to_finset [decidable_eq α] (s : finset α) : s.val.to_finset = s := by { ext, rw [multiset.mem_to_finset, ←mem_def] } end finset namespace list variable [decidable_eq α] /-- `to_finset l` removes duplicates from the list `l` to produce a finset. -/ def to_finset (l : list α) : finset α := multiset.to_finset l @[simp] theorem to_finset_val (l : list α) : l.to_finset.1 = (l.erase_dup : multiset α) := rfl theorem to_finset_eq {l : list α} (n : nodup l) : @finset.mk α l n = l.to_finset := multiset.to_finset_eq n @[simp] theorem mem_to_finset {a : α} {l : list α} : a ∈ l.to_finset ↔ a ∈ l := mem_erase_dup @[simp] theorem to_finset_nil : to_finset (@nil α) = ∅ := rfl @[simp] theorem to_finset_cons {a : α} {l : list α} : to_finset (a :: l) = insert a (to_finset l) := finset.eq_of_veq $ by by_cases h : a ∈ l; simp [finset.insert_val', multiset.erase_dup_cons, h] lemma to_finset_surj_on : set.surj_on to_finset {l : list α | l.nodup} set.univ := begin rintro s -, cases s with t hl, induction t using quot.ind with l, refine ⟨l, hl, (to_finset_eq hl).symm⟩ end theorem to_finset_surjective : surjective (to_finset : list α → finset α) := by { intro s, rcases to_finset_surj_on (set.mem_univ s) with ⟨l, -, hls⟩, exact ⟨l, hls⟩ } lemma to_finset_eq_iff_perm_erase_dup {l l' : list α} : l.to_finset = l'.to_finset ↔ l.erase_dup ~ l'.erase_dup := by simp [finset.ext_iff, perm_ext (nodup_erase_dup _) (nodup_erase_dup _)] lemma to_finset_eq_of_perm (l l' : list α) (h : l ~ l') : l.to_finset = l'.to_finset := to_finset_eq_iff_perm_erase_dup.mpr h.erase_dup lemma perm_of_nodup_nodup_to_finset_eq {l l' : list α} (hl : nodup l) (hl' : nodup l') (h : l.to_finset = l'.to_finset) : l ~ l' := begin rw ←multiset.coe_eq_coe, exact multiset.nodup.to_finset_inj hl hl' h end @[simp] lemma to_finset_append {l l' : list α} : to_finset (l ++ l') = l.to_finset ∪ l'.to_finset := begin induction l with hd tl hl, { simp }, { simp [hl] } end @[simp] lemma to_finset_reverse {l : list α} : to_finset l.reverse = l.to_finset := to_finset_eq_of_perm _ _ (reverse_perm l) end list namespace finset /-! ### map -/ section map open function /-- When `f` is an embedding of `α` in `β` and `s` is a finset in `α`, then `s.map f` is the image finset in `β`. The embedding condition guarantees that there are no duplicates in the image. -/ def map (f : α ↪ β) (s : finset α) : finset β := ⟨s.1.map f, nodup_map f.2 s.2⟩ @[simp] theorem map_val (f : α ↪ β) (s : finset α) : (map f s).1 = s.1.map f := rfl @[simp] theorem map_empty (f : α ↪ β) : (∅ : finset α).map f = ∅ := rfl variables {f : α ↪ β} {s : finset α} @[simp] theorem mem_map {b : β} : b ∈ s.map f ↔ ∃ a ∈ s, f a = b := mem_map.trans $ by simp only [exists_prop]; refl @[simp] theorem mem_map_equiv {f : α ≃ β} {b : β} : b ∈ s.map f.to_embedding ↔ f.symm b ∈ s := by { rw mem_map, exact ⟨by { rintro ⟨a, H, rfl⟩, simpa }, λ h, ⟨_, h, by simp⟩⟩ } theorem mem_map' (f : α ↪ β) {a} {s : finset α} : f a ∈ s.map f ↔ a ∈ s := mem_map_of_injective f.2 theorem mem_map_of_mem (f : α ↪ β) {a} {s : finset α} : a ∈ s → f a ∈ s.map f := (mem_map' _).2 lemma apply_coe_mem_map (f : α ↪ β) (s : finset α) (x : s) : f x ∈ s.map f := mem_map_of_mem f x.prop @[simp, norm_cast] theorem coe_map (f : α ↪ β) (s : finset α) : (s.map f : set β) = f '' s := set.ext $ λ x, mem_map.trans set.mem_image_iff_bex.symm theorem coe_map_subset_range (f : α ↪ β) (s : finset α) : (s.map f : set β) ⊆ set.range f := calc ↑(s.map f) = f '' s : coe_map f s ... ⊆ set.range f : set.image_subset_range f ↑s theorem map_to_finset [decidable_eq α] [decidable_eq β] {s : multiset α} : s.to_finset.map f = (s.map f).to_finset := ext $ λ _, by simp only [mem_map, multiset.mem_map, exists_prop, multiset.mem_to_finset] @[simp] theorem map_refl : s.map (embedding.refl _) = s := ext $ λ _, by simpa only [mem_map, exists_prop] using exists_eq_right @[simp] theorem map_cast_heq {α β} (h : α = β) (s : finset α) : s.map (equiv.cast h).to_embedding == s := by { subst h, simp } theorem map_map {g : β ↪ γ} : (s.map f).map g = s.map (f.trans g) := eq_of_veq $ by simp only [map_val, multiset.map_map]; refl @[simp] theorem map_subset_map {s₁ s₂ : finset α} : s₁.map f ⊆ s₂.map f ↔ s₁ ⊆ s₂ := ⟨λ h x xs, (mem_map' _).1 $ h $ (mem_map' f).2 xs, λ h, by simp [subset_def, map_subset_map h]⟩ /-- Associate to an embedding `f` from `α` to `β` the order embedding that maps a finset to its image under `f`. -/ def map_embedding (f : α ↪ β) : finset α ↪o finset β := order_embedding.of_map_le_iff (map f) (λ _ _, map_subset_map) @[simp] theorem map_inj {s₁ s₂ : finset α} : s₁.map f = s₂.map f ↔ s₁ = s₂ := (map_embedding f).injective.eq_iff @[simp] theorem map_embedding_apply : map_embedding f s = map f s := rfl theorem map_filter {p : β → Prop} [decidable_pred p] : (s.map f).filter p = (s.filter (p ∘ f)).map f := eq_of_veq (map_filter _ _ _) theorem map_union [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).map f = s₁.map f ∪ s₂.map f := coe_injective $ by simp only [coe_map, coe_union, set.image_union] theorem map_inter [decidable_eq α] [decidable_eq β] {f : α ↪ β} (s₁ s₂ : finset α) : (s₁ ∩ s₂).map f = s₁.map f ∩ s₂.map f := coe_injective $ by simp only [coe_map, coe_inter, set.image_inter f.injective] @[simp] theorem map_singleton (f : α ↪ β) (a : α) : map f {a} = {f a} := coe_injective $ by simp only [coe_map, coe_singleton, set.image_singleton] @[simp] theorem map_insert [decidable_eq α] [decidable_eq β] (f : α ↪ β) (a : α) (s : finset α) : (insert a s).map f = insert (f a) (s.map f) := by simp only [insert_eq, map_union, map_singleton] @[simp] theorem map_eq_empty : s.map f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_map_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma attach_map_val {s : finset α} : s.attach.map (embedding.subtype _) = s := eq_of_veq $ by rw [map_val, attach_val]; exact attach_map_val _ lemma nonempty.map (h : s.nonempty) (f : α ↪ β) : (s.map f).nonempty := let ⟨a, ha⟩ := h in ⟨f a, (mem_map' f).mpr ha⟩ end map lemma range_add_one' (n : ℕ) : range (n + 1) = insert 0 ((range n).map ⟨λi, i + 1, assume i j, nat.succ.inj⟩) := by ext (⟨⟩ | ⟨n⟩); simp [nat.succ_eq_add_one, nat.zero_lt_succ n] /-! ### image -/ section image variables [decidable_eq β] /-- `image f s` is the forward image of `s` under `f`. -/ def image (f : α → β) (s : finset α) : finset β := (s.1.map f).to_finset @[simp] theorem image_val (f : α → β) (s : finset α) : (image f s).1 = (s.1.map f).erase_dup := rfl @[simp] theorem image_empty (f : α → β) : (∅ : finset α).image f = ∅ := rfl variables {f : α → β} {s : finset α} @[simp] theorem mem_image {b : β} : b ∈ s.image f ↔ ∃ a ∈ s, f a = b := by simp only [mem_def, image_val, mem_erase_dup, multiset.mem_map, exists_prop] theorem mem_image_of_mem (f : α → β) {a} {s : finset α} (h : a ∈ s) : f a ∈ s.image f := mem_image.2 ⟨_, h, rfl⟩ instance [can_lift β α] : can_lift (finset β) (finset α) := { cond := λ s, ∀ x ∈ s, can_lift.cond α x, coe := image can_lift.coe, prf := begin rintro ⟨⟨l⟩, hd : l.nodup⟩ hl, lift l to list α using hl, refine ⟨⟨l, list.nodup_of_nodup_map _ hd⟩, ext $ λ a, _⟩, simp end } lemma _root_.function.injective.mem_finset_image {f : α → β} (hf : function.injective f) {s : finset α} {x : α} : f x ∈ s.image f ↔ x ∈ s := begin refine ⟨λ h, _, finset.mem_image_of_mem f⟩, obtain ⟨y, hy, heq⟩ := mem_image.1 h, exact hf heq ▸ hy, end lemma filter_mem_image_eq_image (f : α → β) (s : finset α) (t : finset β) (h : ∀ x ∈ s, f x ∈ t) : t.filter (λ y, y ∈ s.image f) = s.image f := by { ext, rw [mem_filter, mem_image], simp only [and_imp, exists_prop, and_iff_right_iff_imp, exists_imp_distrib], rintros x xel rfl, exact h _ xel } lemma fiber_nonempty_iff_mem_image (f : α → β) (s : finset α) (y : β) : (s.filter (λ x, f x = y)).nonempty ↔ y ∈ s.image f := by simp [finset.nonempty] @[simp, norm_cast] lemma coe_image {f : α → β} : ↑(s.image f) = f '' ↑s := set.ext $ λ _, mem_image.trans set.mem_image_iff_bex.symm lemma nonempty.image (h : s.nonempty) (f : α → β) : (s.image f).nonempty := let ⟨a, ha⟩ := h in ⟨f a, mem_image_of_mem f ha⟩ @[simp] lemma nonempty.image_iff (f : α → β) : (s.image f).nonempty ↔ s.nonempty := ⟨λ ⟨y, hy⟩, let ⟨x, hx, _⟩ := mem_image.mp hy in ⟨x, hx⟩, λ h, h.image f⟩ theorem image_to_finset [decidable_eq α] {s : multiset α} : s.to_finset.image f = (s.map f).to_finset := ext $ λ _, by simp only [mem_image, multiset.mem_to_finset, exists_prop, multiset.mem_map] theorem image_val_of_inj_on (H : set.inj_on f s) : (image f s).1 = s.1.map f := (nodup_map_on H s.2).erase_dup @[simp] theorem image_id [decidable_eq α] : s.image id = s := ext $ λ _, by simp only [mem_image, exists_prop, id, exists_eq_right] @[simp] theorem image_id' [decidable_eq α] : s.image (λ x, x) = s := image_id theorem image_image [decidable_eq γ] {g : β → γ} : (s.image f).image g = s.image (g ∘ f) := eq_of_veq $ by simp only [image_val, erase_dup_map_erase_dup_eq, multiset.map_map] theorem image_subset_image {s₁ s₂ : finset α} (h : s₁ ⊆ s₂) : s₁.image f ⊆ s₂.image f := by simp only [subset_def, image_val, subset_erase_dup', erase_dup_subset', multiset.map_subset_map h] theorem image_subset_iff {s : finset α} {t : finset β} {f : α → β} : s.image f ⊆ t ↔ ∀ x ∈ s, f x ∈ t := calc s.image f ⊆ t ↔ f '' ↑s ⊆ ↑t : by norm_cast ... ↔ _ : set.image_subset_iff theorem image_mono (f : α → β) : monotone (finset.image f) := λ _ _, image_subset_image theorem coe_image_subset_range : ↑(s.image f) ⊆ set.range f := calc ↑(s.image f) = f '' ↑s : coe_image ... ⊆ set.range f : set.image_subset_range f ↑s theorem image_filter {p : β → Prop} [decidable_pred p] : (s.image f).filter p = (s.filter (p ∘ f)).image f := ext $ λ b, by simp only [mem_filter, mem_image, exists_prop]; exact ⟨by rintro ⟨⟨x, h1, rfl⟩, h2⟩; exact ⟨x, ⟨h1, h2⟩, rfl⟩, by rintro ⟨x, ⟨h1, h2⟩, rfl⟩; exact ⟨⟨x, h1, rfl⟩, h2⟩⟩ theorem image_union [decidable_eq α] {f : α → β} (s₁ s₂ : finset α) : (s₁ ∪ s₂).image f = s₁.image f ∪ s₂.image f := ext $ λ _, by simp only [mem_image, mem_union, exists_prop, or_and_distrib_right, exists_or_distrib] theorem image_inter [decidable_eq α] (s₁ s₂ : finset α) (hf : ∀x y, f x = f y → x = y) : (s₁ ∩ s₂).image f = s₁.image f ∩ s₂.image f := ext $ by simp only [mem_image, exists_prop, mem_inter]; exact λ b, ⟨λ ⟨a, ⟨m₁, m₂⟩, e⟩, ⟨⟨a, m₁, e⟩, ⟨a, m₂, e⟩⟩, λ ⟨⟨a, m₁, e₁⟩, ⟨a', m₂, e₂⟩⟩, ⟨a, ⟨m₁, hf _ _ (e₂.trans e₁.symm) ▸ m₂⟩, e₁⟩⟩. @[simp] theorem image_singleton (f : α → β) (a : α) : image f {a} = {f a} := ext $ λ x, by simpa only [mem_image, exists_prop, mem_singleton, exists_eq_left] using eq_comm @[simp] theorem image_insert [decidable_eq α] (f : α → β) (a : α) (s : finset α) : (insert a s).image f = insert (f a) (s.image f) := by simp only [insert_eq, image_singleton, image_union] @[simp] theorem image_eq_empty : s.image f = ∅ ↔ s = ∅ := ⟨λ h, eq_empty_of_forall_not_mem $ λ a m, ne_empty_of_mem (mem_image_of_mem _ m) h, λ e, e.symm ▸ rfl⟩ lemma mem_range_iff_mem_finset_range_of_mod_eq' [decidable_eq α] {f : ℕ → α} {a : α} {n : ℕ} (hn : 0 < n) (h : ∀i, f (i % n) = f i) : a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) := begin split, { rintros ⟨i, hi⟩, simp only [mem_image, exists_prop, mem_range], exact ⟨i % n, nat.mod_lt i hn, (rfl.congr hi).mp (h i)⟩ }, { rintro h, simp only [mem_image, exists_prop, set.mem_range, mem_range] at *, rcases h with ⟨i, hi, ha⟩, use ⟨i, ha⟩ }, end lemma mem_range_iff_mem_finset_range_of_mod_eq [decidable_eq α] {f : ℤ → α} {a : α} {n : ℕ} (hn : 0 < n) (h : ∀i, f (i % n) = f i) : a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) := suffices (∃i, f (i % n) = a) ↔ ∃i, i < n ∧ f ↑i = a, by simpa [h], have hn' : 0 < (n : ℤ), from int.coe_nat_lt.mpr hn, iff.intro (assume ⟨i, hi⟩, have 0 ≤ i % ↑n, from int.mod_nonneg _ (ne_of_gt hn'), ⟨int.to_nat (i % n), by rw [←int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos i hn', hi⟩⟩) (assume ⟨i, hi, ha⟩, ⟨i, by rw [int.mod_eq_of_lt (int.coe_zero_le _) (int.coe_nat_lt_coe_nat_of_lt hi), ha]⟩) @[simp] lemma attach_image_val [decidable_eq α] {s : finset α} : s.attach.image subtype.val = s := eq_of_veq $ by rw [image_val, attach_val, multiset.attach_map_val, erase_dup_eq_self] @[simp] lemma attach_image_coe [decidable_eq α] {s : finset α} : s.attach.image coe = s := finset.attach_image_val @[simp] lemma attach_insert [decidable_eq α] {a : α} {s : finset α} : attach (insert a s) = insert (⟨a, mem_insert_self a s⟩ : {x // x ∈ insert a s}) ((attach s).image (λx, ⟨x.1, mem_insert_of_mem x.2⟩)) := ext $ λ ⟨x, hx⟩, ⟨or.cases_on (mem_insert.1 hx) (λ h : x = a, λ _, mem_insert.2 $ or.inl $ subtype.eq h) (λ h : x ∈ s, λ _, mem_insert_of_mem $ mem_image.2 $ ⟨⟨x, h⟩, mem_attach _ _, subtype.eq rfl⟩), λ _, finset.mem_attach _ _⟩ theorem map_eq_image (f : α ↪ β) (s : finset α) : s.map f = s.image f := eq_of_veq (s.map f).2.erase_dup.symm lemma image_const {s : finset α} (h : s.nonempty) (b : β) : s.image (λa, b) = singleton b := ext $ assume b', by simp only [mem_image, exists_prop, exists_and_distrib_right, h.bex, true_and, mem_singleton, eq_comm] /-- Because `finset.image` requires a `decidable_eq` instances for the target type, we can only construct a `functor finset` when working classically. -/ instance [Π P, decidable P] : functor finset := { map := λ α β f s, s.image f, } instance [Π P, decidable P] : is_lawful_functor finset := { id_map := λ α x, image_id, comp_map := λ α β γ f g s, image_image.symm, } /-- Given a finset `s` and a predicate `p`, `s.subtype p` is the finset of `subtype p` whose elements belong to `s`. -/ protected def subtype {α} (p : α → Prop) [decidable_pred p] (s : finset α) : finset (subtype p) := (s.filter p).attach.map ⟨λ x, ⟨x.1, (finset.mem_filter.1 x.2).2⟩, λ x y H, subtype.eq $ subtype.mk.inj H⟩ @[simp] lemma mem_subtype {p : α → Prop} [decidable_pred p] {s : finset α} : ∀{a : subtype p}, a ∈ s.subtype p ↔ (a : α) ∈ s | ⟨a, ha⟩ := by simp [finset.subtype, ha] lemma subtype_eq_empty {p : α → Prop} [decidable_pred p] {s : finset α} : s.subtype p = ∅ ↔ ∀ x, p x → x ∉ s := by simp [ext_iff, subtype.forall, subtype.coe_mk]; refl @[mono] lemma subtype_mono {p : α → Prop} [decidable_pred p] : monotone (finset.subtype p) := λ s t h x hx, mem_subtype.2 $ h $ mem_subtype.1 hx /-- `s.subtype p` converts back to `s.filter p` with `embedding.subtype`. -/ @[simp] lemma subtype_map (p : α → Prop) [decidable_pred p] : (s.subtype p).map (embedding.subtype _) = s.filter p := begin ext x, simp [and_comm _ (_ = _), @and.left_comm _ (_ = _), and_comm (p x) (x ∈ s)] end /-- If all elements of a `finset` satisfy the predicate `p`, `s.subtype p` converts back to `s` with `embedding.subtype`. -/ lemma subtype_map_of_mem {p : α → Prop} [decidable_pred p] (h : ∀ x ∈ s, p x) : (s.subtype p).map (embedding.subtype _) = s := by rw [subtype_map, filter_true_of_mem h] /-- If a `finset` of a subtype is converted to the main type with `embedding.subtype`, all elements of the result have the property of the subtype. -/ lemma property_of_mem_map_subtype {p : α → Prop} (s : finset {x // p x}) {a : α} (h : a ∈ s.map (embedding.subtype _)) : p a := begin rcases mem_map.1 h with ⟨x, hx, rfl⟩, exact x.2 end /-- If a `finset` of a subtype is converted to the main type with `embedding.subtype`, the result does not contain any value that does not satisfy the property of the subtype. -/ lemma not_mem_map_subtype_of_not_property {p : α → Prop} (s : finset {x // p x}) {a : α} (h : ¬ p a) : a ∉ (s.map (embedding.subtype _)) := mt s.property_of_mem_map_subtype h /-- If a `finset` of a subtype is converted to the main type with `embedding.subtype`, the result is a subset of the set giving the subtype. -/ lemma map_subtype_subset {t : set α} (s : finset t) : ↑(s.map (embedding.subtype _)) ⊆ t := begin intros a ha, rw mem_coe at ha, convert property_of_mem_map_subtype s ha end lemma subset_image_iff {f : α → β} {s : finset β} {t : set α} : ↑s ⊆ f '' t ↔ ∃s' : finset α, ↑s' ⊆ t ∧ s'.image f = s := begin split, swap, { rintro ⟨s, hs, rfl⟩, rw [coe_image], exact set.image_subset f hs }, intro h, letI : can_lift β t := ⟨f ∘ coe, λ y, y ∈ f '' t, λ y ⟨x, hxt, hy⟩, ⟨⟨x, hxt⟩, hy⟩⟩, lift s to finset t using h, refine ⟨s.map (embedding.subtype _), map_subtype_subset _, _⟩, ext y, simp end end image end finset theorem multiset.to_finset_map [decidable_eq α] [decidable_eq β] (f : α → β) (m : multiset α) : (m.map f).to_finset = m.to_finset.image f := finset.val_inj.1 (multiset.erase_dup_map_erase_dup_eq _ _).symm namespace finset /-! ### card -/ section card /-- `card s` is the cardinality (number of elements) of `s`. -/ def card (s : finset α) : nat := s.1.card theorem card_def (s : finset α) : s.card = s.1.card := rfl @[simp] lemma card_mk {m nodup} : (⟨m, nodup⟩ : finset α).card = m.card := rfl @[simp] theorem card_empty : card (∅ : finset α) = 0 := rfl theorem card_le_of_subset {s t : finset α} : s ⊆ t → card s ≤ card t := multiset.card_le_of_le ∘ val_le_iff.mpr @[simp] theorem card_eq_zero {s : finset α} : card s = 0 ↔ s = ∅ := card_eq_zero.trans val_eq_zero theorem card_pos {s : finset α} : 0 < card s ↔ s.nonempty := pos_iff_ne_zero.trans $ (not_congr card_eq_zero).trans nonempty_iff_ne_empty.symm alias finset.card_pos ↔ _ finset.nonempty.card_pos theorem card_ne_zero_of_mem {s : finset α} {a : α} (h : a ∈ s) : card s ≠ 0 := (not_congr card_eq_zero).2 (ne_empty_of_mem h) theorem card_eq_one {s : finset α} : s.card = 1 ↔ ∃ a, s = {a} := by cases s; simp only [multiset.card_eq_one, finset.card, ← val_inj, singleton_val] theorem card_le_one {s : finset α} : s.card ≤ 1 ↔ ∀ (a ∈ s) (b ∈ s), a = b := begin rcases s.eq_empty_or_nonempty with rfl|⟨x, hx⟩, { simp }, refine (nat.succ_le_of_lt (card_pos.2 ⟨x, hx⟩)).le_iff_eq.trans (card_eq_one.trans ⟨_, _⟩), { rintro ⟨y, rfl⟩, simp }, { exact λ h, ⟨x, eq_singleton_iff_unique_mem.2 ⟨hx, λ y hy, h _ hy _ hx⟩⟩ } end theorem card_le_one_iff {s : finset α} : s.card ≤ 1 ↔ ∀ {a b}, a ∈ s → b ∈ s → a = b := by { rw card_le_one, tauto } lemma card_le_one_iff_subset_singleton [nonempty α] {s : finset α} : s.card ≤ 1 ↔ ∃ (x : α), s ⊆ {x} := begin split, { assume H, by_cases h : ∃ x, x ∈ s, { rcases h with ⟨x, hx⟩, refine ⟨x, λ y hy, _⟩, rw [card_le_one.1 H y hy x hx, mem_singleton] }, { push_neg at h, inhabit α, exact ⟨default α, λ y hy, (h y hy).elim⟩ } }, { rintros ⟨x, hx⟩, rw ← card_singleton x, exact card_le_of_subset hx } end /-- A `finset` of a subsingleton type has cardinality at most one. -/ lemma card_le_one_of_subsingleton [subsingleton α] (s : finset α) : s.card ≤ 1 := finset.card_le_one_iff.2 $ λ _ _ _ _, subsingleton.elim _ _ theorem one_lt_card {s : finset α} : 1 < s.card ↔ ∃ (a ∈ s) (b ∈ s), a ≠ b := by { rw ← not_iff_not, push_neg, exact card_le_one } lemma exists_ne_of_one_lt_card {s : finset α} (hs : 1 < s.card) (a : α) : ∃ b : α, b ∈ s ∧ b ≠ a := begin obtain ⟨x, hx, y, hy, hxy⟩ := finset.one_lt_card.mp hs, by_cases ha : y = a, { exact ⟨x, hx, ne_of_ne_of_eq hxy ha⟩ }, { exact ⟨y, hy, ha⟩ }, end lemma one_lt_card_iff {s : finset α} : 1 < s.card ↔ ∃ x y, (x ∈ s) ∧ (y ∈ s) ∧ x ≠ y := by { rw one_lt_card, simp only [exists_prop, exists_and_distrib_left] } @[simp] theorem card_cons {a : α} {s : finset α} (h : a ∉ s) : card (cons a s h) = card s + 1 := card_cons _ _ @[simp] theorem card_insert_of_not_mem [decidable_eq α] {a : α} {s : finset α} (h : a ∉ s) : card (insert a s) = card s + 1 := by rw [← cons_eq_insert _ _ h, card_cons] theorem card_insert_of_mem [decidable_eq α] {a : α} {s : finset α} (h : a ∈ s) : card (insert a s) = card s := by rw insert_eq_of_mem h theorem card_insert_le [decidable_eq α] (a : α) (s : finset α) : card (insert a s) ≤ card s + 1 := by by_cases a ∈ s; [{rw [insert_eq_of_mem h], apply nat.le_add_right}, rw [card_insert_of_not_mem h]] @[simp] theorem card_singleton (a : α) : card ({a} : finset α) = 1 := card_singleton _ lemma card_singleton_inter [decidable_eq α] {x : α} {s : finset α} : ({x} ∩ s).card ≤ 1 := begin cases (finset.decidable_mem x s), { simp [finset.singleton_inter_of_not_mem h] }, { simp [finset.singleton_inter_of_mem h] }, end @[simp] theorem card_erase_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) = pred (card s) := card_erase_of_mem theorem card_erase_lt_of_mem [decidable_eq α] {a : α} {s : finset α} : a ∈ s → card (erase s a) < card s := card_erase_lt_of_mem theorem card_erase_le [decidable_eq α] {a : α} {s : finset α} : card (erase s a) ≤ card s := card_erase_le theorem pred_card_le_card_erase [decidable_eq α] {a : α} {s : finset α} : card s - 1 ≤ card (erase s a) := begin by_cases h : a ∈ s, { rw [card_erase_of_mem h], refl }, { rw [erase_eq_of_not_mem h], apply nat.sub_le } end /-- If `a ∈ s` is known, see also `finset.card_erase_of_mem` and `finset.erase_eq_of_not_mem`. -/ theorem card_erase_eq_ite [decidable_eq α] {a : α} {s : finset α} : card (erase s a) = if a ∈ s then pred (card s) else card s := card_erase_eq_ite @[simp] theorem card_range (n : ℕ) : card (range n) = n := card_range n @[simp] theorem card_attach {s : finset α} : card (attach s) = card s := multiset.card_attach end card end finset theorem multiset.to_finset_card_le [decidable_eq α] (m : multiset α) : m.to_finset.card ≤ m.card := card_le_of_le (erase_dup_le _) lemma list.card_to_finset [decidable_eq α] (l : list α) : finset.card l.to_finset = l.erase_dup.length := rfl theorem list.to_finset_card_le [decidable_eq α] (l : list α) : l.to_finset.card ≤ l.length := multiset.to_finset_card_le ⟦l⟧ namespace finset section card theorem card_image_le [decidable_eq β] {f : α → β} {s : finset α} : card (image f s) ≤ card s := by simpa only [card_map] using (s.1.map f).to_finset_card_le theorem card_image_of_inj_on [decidable_eq β] {f : α → β} {s : finset α} (H : set.inj_on f s) : card (image f s) = card s := by simp only [card, image_val_of_inj_on H, card_map] theorem inj_on_of_card_image_eq [decidable_eq β] {f : α → β} {s : finset α} (H : card (image f s) = card s) : set.inj_on f s := begin change (s.1.map f).erase_dup.card = s.1.card at H, have : (s.1.map f).erase_dup = s.1.map f, { apply multiset.eq_of_le_of_card_le, { apply multiset.erase_dup_le }, rw H, simp only [multiset.card_map] }, rw multiset.erase_dup_eq_self at this, apply inj_on_of_nodup_map this, end theorem card_image_eq_iff_inj_on [decidable_eq β] {f : α → β} {s : finset α} : (s.image f).card = s.card ↔ set.inj_on f s := ⟨inj_on_of_card_image_eq, card_image_of_inj_on⟩ theorem card_image_of_injective [decidable_eq β] {f : α → β} (s : finset α) (H : injective f) : card (image f s) = card s := card_image_of_inj_on $ λ x _ y _ h, H h lemma fiber_card_ne_zero_iff_mem_image (s : finset α) (f : α → β) [decidable_eq β] (y : β) : (s.filter (λ x, f x = y)).card ≠ 0 ↔ y ∈ s.image f := by { rw [←pos_iff_ne_zero, card_pos, fiber_nonempty_iff_mem_image] } @[simp] lemma card_map {α β} (f : α ↪ β) {s : finset α} : (s.map f).card = s.card := multiset.card_map _ _ @[simp] lemma card_subtype (p : α → Prop) [decidable_pred p] (s : finset α) : (s.subtype p).card = (s.filter p).card := by simp [finset.subtype] lemma card_eq_of_bijective {s : finset α} {n : ℕ} (f : ∀i, i < n → α) (hf : ∀a∈s, ∃i, ∃h:i<n, f i h = a) (hf' : ∀i (h : i < n), f i h ∈ s) (f_inj : ∀i j (hi : i < n) (hj : j < n), f i hi = f j hj → i = j) : card s = n := begin classical, have : ∀ (a : α), a ∈ s ↔ ∃i (hi : i ∈ range n), f i (mem_range.1 hi) = a, from assume a, ⟨assume ha, let ⟨i, hi, eq⟩ := hf a ha in ⟨i, mem_range.2 hi, eq⟩, assume ⟨i, hi, eq⟩, eq ▸ hf' i (mem_range.1 hi)⟩, have : s = ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)), by simpa only [ext_iff, mem_image, exists_prop, subtype.exists, mem_attach, true_and], calc card s = card ((range n).attach.image $ λi, f i.1 (mem_range.1 i.2)) : by rw [this] ... = card ((range n).attach) : card_image_of_injective _ $ assume ⟨i, hi⟩ ⟨j, hj⟩ eq, subtype.eq $ f_inj i j (mem_range.1 hi) (mem_range.1 hj) eq ... = card (range n) : card_attach ... = n : card_range n end lemma card_eq_succ [decidable_eq α] {s : finset α} {n : ℕ} : s.card = n + 1 ↔ (∃a t, a ∉ t ∧ insert a t = s ∧ card t = n) := iff.intro (assume eq, have 0 < card s, from eq.symm ▸ nat.zero_lt_succ _, let ⟨a, has⟩ := card_pos.mp this in ⟨a, s.erase a, s.not_mem_erase a, insert_erase has, by simp only [eq, card_erase_of_mem has, pred_succ]⟩) (assume ⟨a, t, hat, s_eq, n_eq⟩, s_eq ▸ n_eq ▸ card_insert_of_not_mem hat) theorem card_filter_le (s : finset α) (p : α → Prop) [decidable_pred p] : card (s.filter p) ≤ card s := card_le_of_subset $ filter_subset _ _ theorem eq_of_subset_of_card_le {s t : finset α} (h : s ⊆ t) (h₂ : card t ≤ card s) : s = t := eq_of_veq $ multiset.eq_of_le_of_card_le (val_le_iff.mpr h) h₂ lemma filter_card_eq {s : finset α} {p : α → Prop} [decidable_pred p] (h : (s.filter p).card = s.card) (x : α) (hx : x ∈ s) : p x := begin rw [←eq_of_subset_of_card_le (s.filter_subset p) h.ge, mem_filter] at hx, exact hx.2, end lemma card_lt_card {s t : finset α} (h : s ⊂ t) : s.card < t.card := card_lt_of_lt (val_lt_iff.2 h) lemma card_le_card_of_inj_on {s : finset α} {t : finset β} (f : α → β) (hf : ∀a∈s, f a ∈ t) (f_inj : ∀a₁∈s, ∀a₂∈s, f a₁ = f a₂ → a₁ = a₂) : card s ≤ card t := begin classical, calc card s = card (s.image f) : by rw [card_image_of_inj_on f_inj] ... ≤ card t : card_le_of_subset $ image_subset_iff.2 hf end /-- If there are more pigeons than pigeonholes, then there are two pigeons in the same pigeonhole. -/ lemma exists_ne_map_eq_of_card_lt_of_maps_to {s : finset α} {t : finset β} (hc : t.card < s.card) {f : α → β} (hf : ∀ a ∈ s, f a ∈ t) : ∃ (x ∈ s) (y ∈ s), x ≠ y ∧ f x = f y := begin classical, by_contra hz, push_neg at hz, refine hc.not_le (card_le_card_of_inj_on f hf _), intros x hx y hy, contrapose, exact hz x hx y hy, end lemma le_card_of_inj_on_range {n} {s : finset α} (f : ℕ → α) (hf : ∀i<n, f i ∈ s) (f_inj : ∀ (i<n) (j<n), f i = f j → i = j) : n ≤ card s := calc n = card (range n) : (card_range n).symm ... ≤ card s : card_le_card_of_inj_on f (by simpa only [mem_range]) (by simpa only [mem_range]) /-- Suppose that, given objects defined on all strict subsets of any finset `s`, one knows how to define an object on `s`. Then one can inductively define an object on all finsets, starting from the empty set and iterating. This can be used either to define data, or to prove properties. -/ def strong_induction {p : finset α → Sort*} (H : ∀ s, (∀ t ⊂ s, p t) → p s) : ∀ (s : finset α), p s | s := H s (λ t h, have card t < card s, from card_lt_card h, strong_induction t) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]} lemma strong_induction_eq {p : finset α → Sort*} (H : ∀ s, (∀ t ⊂ s, p t) → p s) (s : finset α) : strong_induction H s = H s (λ t h, strong_induction H t) := by rw strong_induction /-- Analogue of `strong_induction` with order of arguments swapped. -/ @[elab_as_eliminator] def strong_induction_on {p : finset α → Sort*} : ∀ (s : finset α), (∀s, (∀ t ⊂ s, p t) → p s) → p s := λ s H, strong_induction H s lemma strong_induction_on_eq {p : finset α → Sort*} (s : finset α) (H : ∀ s, (∀ t ⊂ s, p t) → p s) : s.strong_induction_on H = H s (λ t h, t.strong_induction_on H) := by { dunfold strong_induction_on, rw strong_induction } @[elab_as_eliminator] lemma case_strong_induction_on [decidable_eq α] {p : finset α → Prop} (s : finset α) (h₀ : p ∅) (h₁ : ∀ a s, a ∉ s → (∀ t ⊆ s, p t) → p (insert a s)) : p s := finset.strong_induction_on s $ λ s, finset.induction_on s (λ _, h₀) $ λ a s n _ ih, h₁ a s n $ λ t ss, ih _ (lt_of_le_of_lt ss (ssubset_insert n) : t < _) /-- Suppose that, given that `p t` can be defined on all supersets of `s` of cardinality less than `n`, one knows how to define `p s`. Then one can inductively define `p s` for all finsets `s` of cardinality less than `n`, starting from finsets of card `n` and iterating. This can be used either to define data, or to prove properties. -/ def strong_downward_induction {p : finset α → Sort*} {n : ℕ} (H : ∀ t₁, (∀ {t₂ : finset α}, t₂.card ≤ n → t₁ ⊂ t₂ → p t₂) → t₁.card ≤ n → p t₁) : ∀ (s : finset α), s.card ≤ n → p s | s := H s (λ t ht h, have n - card t < n - card s, from (sub_lt_sub_iff_left_of_le ht).2 (finset.card_lt_card h), strong_downward_induction t ht) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ (t : finset α), n - t.card)⟩]} lemma strong_downward_induction_eq {p : finset α → Sort*} {n : ℕ} (H : ∀ t₁, (∀ {t₂ : finset α}, t₂.card ≤ n → t₁ ⊂ t₂ → p t₂) → t₁.card ≤ n → p t₁) (s : finset α) : strong_downward_induction H s = H s (λ t ht hst, strong_downward_induction H t ht) := by rw strong_downward_induction /-- Analogue of `strong_downward_induction` with order of arguments swapped. -/ @[elab_as_eliminator] def strong_downward_induction_on {p : finset α → Sort*} {n : ℕ} : ∀ (s : finset α), (∀ t₁, (∀ {t₂ : finset α}, t₂.card ≤ n → t₁ ⊂ t₂ → p t₂) → t₁.card ≤ n → p t₁) → s.card ≤ n → p s := λ s H, strong_downward_induction H s lemma strong_downward_induction_on_eq {p : finset α → Sort*} (s : finset α) {n : ℕ} (H : ∀ t₁, (∀ {t₂ : finset α}, t₂.card ≤ n → t₁ ⊂ t₂ → p t₂) → t₁.card ≤ n → p t₁) : s.strong_downward_induction_on H = H s (λ t ht h, t.strong_downward_induction_on H ht) := by { dunfold strong_downward_induction_on, rw strong_downward_induction } lemma card_congr {s : finset α} {t : finset β} (f : Π a ∈ s, β) (h₁ : ∀ a ha, f a ha ∈ t) (h₂ : ∀ a b ha hb, f a ha = f b hb → a = b) (h₃ : ∀ b ∈ t, ∃ a ha, f a ha = b) : s.card = t.card := by haveI := classical.prop_decidable; exact calc s.card = s.attach.card : card_attach.symm ... = (s.attach.image (λ (a : {a // a ∈ s}), f a.1 a.2)).card : eq.symm (card_image_of_injective _ (λ a b h, subtype.eq (h₂ _ _ _ _ h))) ... = t.card : congr_arg card (finset.ext $ λ b, ⟨λ h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ h₁ _ _, λ h, let ⟨a, ha₁, ha₂⟩ := h₃ b h in mem_image.2 ⟨⟨a, ha₁⟩, by simp [ha₂]⟩⟩) lemma card_union_add_card_inter [decidable_eq α] (s t : finset α) : (s ∪ t).card + (s ∩ t).card = s.card + t.card := finset.induction_on t (by simp) $ λ a r har, by by_cases a ∈ s; simp *; cc lemma card_union_le [decidable_eq α] (s t : finset α) : (s ∪ t).card ≤ s.card + t.card := card_union_add_card_inter s t ▸ nat.le_add_right _ _ lemma card_union_eq [decidable_eq α] {s t : finset α} (h : disjoint s t) : (s ∪ t).card = s.card + t.card := begin rw [← card_union_add_card_inter], convert (add_zero _).symm, rw [card_eq_zero], rwa [disjoint_iff] at h end lemma surj_on_of_inj_on_of_card_le {s : finset α} {t : finset β} (f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hinj : ∀ a₁ a₂ ha₁ ha₂, f a₁ ha₁ = f a₂ ha₂ → a₁ = a₂) (hst : card t ≤ card s) : (∀ b ∈ t, ∃ a ha, b = f a ha) := by haveI := classical.dec_eq β; exact λ b hb, have h : card (image (λ (a : {a // a ∈ s}), f a a.prop) (attach s)) = card s, from @card_attach _ s ▸ card_image_of_injective _ (λ ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ h, subtype.eq $ hinj _ _ _ _ h), have h₁ : image (λ a : {a // a ∈ s}, f a a.prop) s.attach = t := eq_of_subset_of_card_le (λ b h, let ⟨a, ha₁, ha₂⟩ := mem_image.1 h in ha₂ ▸ hf _ _) (by simp [hst, h]), begin rw ← h₁ at hb, rcases mem_image.1 hb with ⟨a, ha₁, ha₂⟩, exact ⟨a, a.2, ha₂.symm⟩, end open function lemma inj_on_of_surj_on_of_card_le {s : finset α} {t : finset β} (f : Π a ∈ s, β) (hf : ∀ a ha, f a ha ∈ t) (hsurj : ∀ b ∈ t, ∃ a ha, b = f a ha) (hst : card s ≤ card t) ⦃a₁ a₂⦄ (ha₁ : a₁ ∈ s) (ha₂ : a₂ ∈ s) (ha₁a₂: f a₁ ha₁ = f a₂ ha₂) : a₁ = a₂ := by haveI : inhabited {x // x ∈ s} := ⟨⟨a₁, ha₁⟩⟩; exact let f' : {x // x ∈ s} → {x // x ∈ t} := λ x, ⟨f x.1 x.2, hf x.1 x.2⟩ in let g : {x // x ∈ t} → {x // x ∈ s} := @surj_inv _ _ f' (λ x, let ⟨y, hy₁, hy₂⟩ := hsurj x.1 x.2 in ⟨⟨y, hy₁⟩, subtype.eq hy₂.symm⟩) in have hg : injective g, from injective_surj_inv _, have hsg : surjective g, from λ x, let ⟨y, hy⟩ := surj_on_of_inj_on_of_card_le (λ (x : {x // x ∈ t}) (hx : x ∈ t.attach), g x) (λ x _, show (g x) ∈ s.attach, from mem_attach _ _) (λ x y _ _ hxy, hg hxy) (by simpa) x (mem_attach _ _) in ⟨y, hy.snd.symm⟩, have hif : injective f', from (left_inverse_of_surjective_of_right_inverse hsg (right_inverse_surj_inv _)).injective, subtype.ext_iff_val.1 (@hif ⟨a₁, ha₁⟩ ⟨a₂, ha₂⟩ (subtype.eq ha₁a₂)) end card section to_list /-- Produce a list of the elements in the finite set using choice. -/ @[reducible] noncomputable def to_list (s : finset α) : list α := s.1.to_list lemma nodup_to_list (s : finset α) : s.to_list.nodup := by { rw [to_list, ←multiset.coe_nodup, multiset.coe_to_list], exact s.nodup } @[simp] lemma mem_to_list {a : α} (s : finset α) : a ∈ s.to_list ↔ a ∈ s := by { rw [to_list, ←multiset.mem_coe, multiset.coe_to_list], exact iff.rfl } @[simp] lemma length_to_list (s : finset α) : s.to_list.length = s.card := by { rw [to_list, ←multiset.coe_card, multiset.coe_to_list], refl } @[simp] lemma to_list_empty : (∅ : finset α).to_list = [] := by simp [to_list] @[simp, norm_cast] lemma coe_to_list (s : finset α) : (s.to_list : multiset α) = s.val := by { classical, ext, simp } @[simp] lemma to_list_to_finset [decidable_eq α] (s : finset α) : s.to_list.to_finset = s := by { ext, simp } lemma exists_list_nodup_eq [decidable_eq α] (s : finset α) : ∃ (l : list α), l.nodup ∧ l.to_finset = s := ⟨s.to_list, s.nodup_to_list, s.to_list_to_finset⟩ end to_list section bUnion /-! ### bUnion This section is about the bounded union of an indexed family `t : α → finset β` of finite sets over a finite set `s : finset α`. -/ variables [decidable_eq β] {s : finset α} {t : α → finset β} /-- `bUnion s t` is the union of `t x` over `x ∈ s`. (This was formerly `bind` due to the monad structure on types with `decidable_eq`.) -/ protected def bUnion (s : finset α) (t : α → finset β) : finset β := (s.1.bind (λ a, (t a).1)).to_finset @[simp] theorem bUnion_val (s : finset α) (t : α → finset β) : (s.bUnion t).1 = (s.1.bind (λ a, (t a).1)).erase_dup := rfl @[simp] theorem bUnion_empty : finset.bUnion ∅ t = ∅ := rfl @[simp] theorem mem_bUnion {b : β} : b ∈ s.bUnion t ↔ ∃a∈s, b ∈ t a := by simp only [mem_def, bUnion_val, mem_erase_dup, mem_bind, exists_prop] @[simp] theorem bUnion_insert [decidable_eq α] {a : α} : (insert a s).bUnion t = t a ∪ s.bUnion t := ext $ λ x, by simp only [mem_bUnion, exists_prop, mem_union, mem_insert, or_and_distrib_right, exists_or_distrib, exists_eq_left] -- ext $ λ x, by simp [or_and_distrib_right, exists_or_distrib] theorem bUnion_congr {s₁ s₂ : finset α} {t₁ t₂ : α → finset β} (hs : s₁ = s₂) (ht : ∀ a ∈ s₁, t₁ a = t₂ a) : s₁.bUnion t₁ = s₂.bUnion t₂ := ext $ λ x, by simp [hs, ht] { contextual := tt } @[simp] lemma singleton_bUnion {a : α} : finset.bUnion {a} t = t a := begin classical, rw [← insert_emptyc_eq, bUnion_insert, bUnion_empty, union_empty] end theorem bUnion_inter (s : finset α) (f : α → finset β) (t : finset β) : s.bUnion f ∩ t = s.bUnion (λ x, f x ∩ t) := begin ext x, simp only [mem_bUnion, mem_inter], tauto end theorem inter_bUnion (t : finset β) (s : finset α) (f : α → finset β) : t ∩ s.bUnion f = s.bUnion (λ x, t ∩ f x) := by rw [inter_comm, bUnion_inter]; simp [inter_comm] theorem image_bUnion [decidable_eq γ] {f : α → β} {s : finset α} {t : β → finset γ} : (s.image f).bUnion t = s.bUnion (λa, t (f a)) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [image_insert, bUnion_insert, ih]) theorem bUnion_image [decidable_eq γ] {s : finset α} {t : α → finset β} {f : β → γ} : (s.bUnion t).image f = s.bUnion (λa, (t a).image f) := by haveI := classical.dec_eq α; exact finset.induction_on s rfl (λ a s has ih, by simp only [bUnion_insert, image_union, ih]) lemma bUnion_bUnion [decidable_eq γ] (s : finset α) (f : α → finset β) (g : β → finset γ) : (s.bUnion f).bUnion g = s.bUnion (λ a, (f a).bUnion g) := begin ext, simp only [finset.mem_bUnion, exists_prop], simp_rw [←exists_and_distrib_right, ←exists_and_distrib_left, and_assoc], rw exists_comm, end theorem bind_to_finset [decidable_eq α] (s : multiset α) (t : α → multiset β) : (s.bind t).to_finset = s.to_finset.bUnion (λa, (t a).to_finset) := ext $ λ x, by simp only [multiset.mem_to_finset, mem_bUnion, multiset.mem_bind, exists_prop] lemma bUnion_mono {t₁ t₂ : α → finset β} (h : ∀a∈s, t₁ a ⊆ t₂ a) : s.bUnion t₁ ⊆ s.bUnion t₂ := have ∀b a, a ∈ s → b ∈ t₁ a → (∃ (a : α), a ∈ s ∧ b ∈ t₂ a), from assume b a ha hb, ⟨a, ha, finset.mem_of_subset (h a ha) hb⟩, by simpa only [subset_iff, mem_bUnion, exists_imp_distrib, and_imp, exists_prop] lemma bUnion_subset_bUnion_of_subset_left {α : Type*} {s₁ s₂ : finset α} (t : α → finset β) (h : s₁ ⊆ s₂) : s₁.bUnion t ⊆ s₂.bUnion t := begin intro x, simp only [and_imp, mem_bUnion, exists_prop], exact Exists.imp (λ a ha, ⟨h ha.1, ha.2⟩) end lemma subset_bUnion_of_mem {s : finset α} (u : α → finset β) {x : α} (xs : x ∈ s) : u x ⊆ s.bUnion u := begin apply subset.trans _ (bUnion_subset_bUnion_of_subset_left u (singleton_subset_iff.2 xs)), exact subset_of_eq singleton_bUnion.symm, end @[simp] lemma bUnion_subset_iff_forall_subset {α β : Type*} [decidable_eq β] {s : finset α} {t : finset β} {f : α → finset β} : s.bUnion f ⊆ t ↔ ∀ x ∈ s, f x ⊆ t := ⟨λ h x hx, (subset_bUnion_of_mem f hx).trans h, λ h x hx, let ⟨a, ha₁, ha₂⟩ := mem_bUnion.mp hx in h _ ha₁ ha₂⟩ lemma bUnion_singleton {f : α → β} : s.bUnion (λa, {f a}) = s.image f := ext $ λ x, by simp only [mem_bUnion, mem_image, mem_singleton, eq_comm] @[simp] lemma bUnion_singleton_eq_self [decidable_eq α] : s.bUnion (singleton : α → finset α) = s := by { rw bUnion_singleton, exact image_id } lemma bUnion_filter_eq_of_maps_to [decidable_eq α] {s : finset α} {t : finset β} {f : α → β} (h : ∀ x ∈ s, f x ∈ t) : t.bUnion (λa, s.filter $ (λc, f c = a)) = s := ext $ λ b, by simpa using h b lemma image_bUnion_filter_eq [decidable_eq α] (s : finset β) (g : β → α) : (s.image g).bUnion (λa, s.filter $ (λc, g c = a)) = s := bUnion_filter_eq_of_maps_to (λ x, mem_image_of_mem g) lemma erase_bUnion (f : α → finset β) (s : finset α) (b : β) : (s.bUnion f).erase b = s.bUnion (λ x, (f x).erase b) := by { ext, simp only [finset.mem_bUnion, iff_self, exists_and_distrib_left, finset.mem_erase] } @[simp] lemma bUnion_nonempty : (s.bUnion t).nonempty ↔ ∃ x ∈ s, (t x).nonempty := by simp [finset.nonempty, ← exists_and_distrib_left, @exists_swap α] lemma nonempty.bUnion (hs : s.nonempty) (ht : ∀ x ∈ s, (t x).nonempty) : (s.bUnion t).nonempty := bUnion_nonempty.2 $ hs.imp $ λ x hx, ⟨hx, ht x hx⟩ end bUnion /-! ### prod -/ section prod variables {s : finset α} {t : finset β} /-- `product s t` is the set of pairs `(a, b)` such that `a ∈ s` and `b ∈ t`. -/ protected def product (s : finset α) (t : finset β) : finset (α × β) := ⟨_, nodup_product s.2 t.2⟩ @[simp] theorem product_val : (s.product t).1 = s.1.product t.1 := rfl @[simp] theorem mem_product {p : α × β} : p ∈ s.product t ↔ p.1 ∈ s ∧ p.2 ∈ t := mem_product theorem subset_product [decidable_eq α] [decidable_eq β] {s : finset (α × β)} : s ⊆ (s.image prod.fst).product (s.image prod.snd) := λ p hp, mem_product.2 ⟨mem_image_of_mem _ hp, mem_image_of_mem _ hp⟩ theorem product_eq_bUnion [decidable_eq α] [decidable_eq β] (s : finset α) (t : finset β) : s.product t = s.bUnion (λa, t.image $ λb, (a, b)) := ext $ λ ⟨x, y⟩, by simp only [mem_product, mem_bUnion, mem_image, exists_prop, prod.mk.inj_iff, and.left_comm, exists_and_distrib_left, exists_eq_right, exists_eq_left] @[simp] lemma product_bUnion {β γ : Type*} [decidable_eq γ] (s : finset α) (t : finset β) (f : α × β → finset γ) : (s.product t).bUnion f = s.bUnion (λ a, t.bUnion (λ b, f (a, b))) := by { classical, simp_rw [product_eq_bUnion, bUnion_bUnion, image_bUnion] } @[simp] theorem card_product (s : finset α) (t : finset β) : card (s.product t) = card s * card t := multiset.card_product _ _ theorem filter_product (p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] : (s.product t).filter (λ (x : α × β), p x.1 ∧ q x.2) = (s.filter p).product (t.filter q) := by { ext ⟨a, b⟩, simp only [mem_filter, mem_product], finish, } lemma filter_product_card (s : finset α) (t : finset β) (p : α → Prop) (q : β → Prop) [decidable_pred p] [decidable_pred q] : ((s.product t).filter (λ (x : α × β), p x.1 ↔ q x.2)).card = (s.filter p).card * (t.filter q).card + (s.filter (not ∘ p)).card * (t.filter (not ∘ q)).card := begin classical, rw [← card_product, ← card_product, ← filter_product, ← filter_product, ← card_union_eq], { apply congr_arg, ext ⟨a, b⟩, simp only [filter_union_right, mem_filter, mem_product], split; intros; finish, }, { rw disjoint_iff, change _ ∩ _ = ∅, ext ⟨a, b⟩, rw mem_inter, finish, }, end lemma empty_product (t : finset β) : (∅ : finset α).product t = ∅ := rfl lemma product_empty (s : finset α) : s.product (∅ : finset β) = ∅ := eq_empty_of_forall_not_mem (λ x h, (finset.mem_product.1 h).2) end prod /-! ### sigma -/ section sigma variables {σ : α → Type*} {s : finset α} {t : Πa, finset (σ a)} /-- `sigma s t` is the set of dependent pairs `⟨a, b⟩` such that `a ∈ s` and `b ∈ t a`. -/ protected def sigma (s : finset α) (t : Πa, finset (σ a)) : finset (Σa, σ a) := ⟨_, nodup_sigma s.2 (λ a, (t a).2)⟩ @[simp] theorem mem_sigma {p : sigma σ} : p ∈ s.sigma t ↔ p.1 ∈ s ∧ p.2 ∈ t (p.1) := mem_sigma @[simp] theorem sigma_nonempty : (s.sigma t).nonempty ↔ ∃ x ∈ s, (t x).nonempty := by simp [finset.nonempty] @[simp] theorem sigma_eq_empty : s.sigma t = ∅ ↔ ∀ x ∈ s, t x = ∅ := by simp only [← not_nonempty_iff_eq_empty, sigma_nonempty, not_exists] @[mono] theorem sigma_mono {s₁ s₂ : finset α} {t₁ t₂ : Πa, finset (σ a)} (H1 : s₁ ⊆ s₂) (H2 : ∀a, t₁ a ⊆ t₂ a) : s₁.sigma t₁ ⊆ s₂.sigma t₂ := λ ⟨x, sx⟩ H, let ⟨H3, H4⟩ := mem_sigma.1 H in mem_sigma.2 ⟨H1 H3, H2 x H4⟩ theorem sigma_eq_bUnion [decidable_eq (Σ a, σ a)] (s : finset α) (t : Πa, finset (σ a)) : s.sigma t = s.bUnion (λa, (t a).map $ embedding.sigma_mk a) := by { ext ⟨x, y⟩, simp [and.left_comm] } end sigma /-! ### disjoint -/ section disjoint variable [decidable_eq α] theorem disjoint_left {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := by simp only [_root_.disjoint, inf_eq_inter, le_iff_subset, subset_iff, mem_inter, not_and, and_imp]; refl theorem disjoint_val {s t : finset α} : disjoint s t ↔ s.1.disjoint t.1 := disjoint_left theorem disjoint_iff_inter_eq_empty {s t : finset α} : disjoint s t ↔ s ∩ t = ∅ := disjoint_iff instance decidable_disjoint (U V : finset α) : decidable (disjoint U V) := decidable_of_decidable_of_iff (by apply_instance) eq_bot_iff theorem disjoint_right {s t : finset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := by rw [disjoint.comm, disjoint_left] theorem disjoint_iff_ne {s t : finset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp only [disjoint_left, imp_not_comm, forall_eq'] lemma not_disjoint_iff {s t : finset α} : ¬disjoint s t ↔ ∃ a, a ∈ s ∧ a ∈ t := not_forall.trans $ exists_congr $ λ a, begin rw [finset.inf_eq_inter, finset.mem_inter], exact not_not, end theorem disjoint_of_subset_left {s t u : finset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t := disjoint_left.2 (λ x m₁, (disjoint_left.1 d) (h m₁)) theorem disjoint_of_subset_right {s t u : finset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t := disjoint_right.2 (λ x m₁, (disjoint_right.1 d) (h m₁)) @[simp] theorem disjoint_empty_left (s : finset α) : disjoint ∅ s := disjoint_bot_left @[simp] theorem disjoint_empty_right (s : finset α) : disjoint s ∅ := disjoint_bot_right @[simp] theorem disjoint_singleton_left {s : finset α} {a : α} : disjoint (singleton a) s ↔ a ∉ s := by simp only [disjoint_left, mem_singleton, forall_eq] @[simp] theorem disjoint_singleton_right {s : finset α} {a : α} : disjoint s (singleton a) ↔ a ∉ s := disjoint.comm.trans disjoint_singleton_left @[simp] lemma disjoint_singleton {a b : α} : disjoint ({a} : finset α) {b} ↔ a ≠ b := by rw [disjoint_singleton_left, mem_singleton] @[simp] theorem disjoint_insert_left {a : α} {s t : finset α} : disjoint (insert a s) t ↔ a ∉ t ∧ disjoint s t := by simp only [disjoint_left, mem_insert, or_imp_distrib, forall_and_distrib, forall_eq] @[simp] theorem disjoint_insert_right {a : α} {s t : finset α} : disjoint s (insert a t) ↔ a ∉ s ∧ disjoint s t := disjoint.comm.trans $ by rw [disjoint_insert_left, disjoint.comm] @[simp] theorem disjoint_union_left {s t u : finset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp only [disjoint_left, mem_union, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right {s t u : finset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp only [disjoint_right, mem_union, or_imp_distrib, forall_and_distrib] lemma sdiff_disjoint {s t : finset α} : disjoint (t \ s) s := disjoint_left.2 $ assume a ha, (mem_sdiff.1 ha).2 lemma disjoint_sdiff {s t : finset α} : disjoint s (t \ s) := sdiff_disjoint.symm lemma disjoint_sdiff_inter (s t : finset α) : disjoint (s \ t) (s ∩ t) := disjoint_of_subset_right (inter_subset_right _ _) sdiff_disjoint lemma sdiff_eq_self_iff_disjoint {s t : finset α} : s \ t = s ↔ disjoint s t := by rw [sdiff_eq_self, subset_empty, disjoint_iff_inter_eq_empty] lemma sdiff_eq_self_of_disjoint {s t : finset α} (h : disjoint s t) : s \ t = s := sdiff_eq_self_iff_disjoint.2 h lemma disjoint_self_iff_empty (s : finset α) : disjoint s s ↔ s = ∅ := disjoint_self lemma disjoint_bUnion_left {ι : Type*} (s : finset ι) (f : ι → finset α) (t : finset α) : disjoint (s.bUnion f) t ↔ (∀i∈s, disjoint (f i) t) := begin classical, refine s.induction _ _, { simp only [forall_mem_empty_iff, bUnion_empty, disjoint_empty_left] }, { assume i s his ih, simp only [disjoint_union_left, bUnion_insert, his, forall_mem_insert, ih] } end lemma disjoint_bUnion_right {ι : Type*} (s : finset α) (t : finset ι) (f : ι → finset α) : disjoint s (t.bUnion f) ↔ (∀i∈t, disjoint s (f i)) := by simpa only [disjoint.comm] using disjoint_bUnion_left t f s @[simp] theorem card_disjoint_union {s t : finset α} (h : disjoint s t) : card (s ∪ t) = card s + card t := by rw [← card_union_add_card_inter, disjoint_iff_inter_eq_empty.1 h, card_empty, add_zero] theorem card_sdiff {s t : finset α} (h : s ⊆ t) : card (t \ s) = card t - card s := suffices card (t \ s) = card ((t \ s) ∪ s) - card s, by rwa sdiff_union_of_subset h at this, by rw [card_disjoint_union sdiff_disjoint, nat.add_sub_cancel] lemma card_sdiff_add_card {s t : finset α} : (s \ t).card + t.card = (s ∪ t).card := by rw [← card_disjoint_union sdiff_disjoint, sdiff_union_self_eq_union] lemma disjoint_filter {s : finset α} {p q : α → Prop} [decidable_pred p] [decidable_pred q] : disjoint (s.filter p) (s.filter q) ↔ (∀ x ∈ s, p x → ¬ q x) := by split; simp [disjoint_left] {contextual := tt} lemma disjoint_filter_filter {s t : finset α} {p q : α → Prop} [decidable_pred p] [decidable_pred q] : (disjoint s t) → disjoint (s.filter p) (t.filter q) := disjoint.mono (filter_subset _ _) (filter_subset _ _) lemma disjoint_iff_disjoint_coe {α : Type*} {a b : finset α} [decidable_eq α] : disjoint a b ↔ disjoint (↑a : set α) (↑b : set α) := by { rw [finset.disjoint_left, set.disjoint_left], refl } lemma filter_card_add_filter_neg_card_eq_card {α : Type*} {s : finset α} (p : α → Prop) [decidable_pred p] : (s.filter p).card + (s.filter (not ∘ p)).card = s.card := by { classical, simp [← card_union_eq, filter_union_filter_neg_eq, disjoint_filter], } end disjoint section self_prod variables (s : finset α) [decidable_eq α] /-- Given a finite set `s`, the diagonal, `s.diag` is the set of pairs of the form `(a, a)` for `a ∈ s`. -/ def diag := (s.product s).filter (λ (a : α × α), a.fst = a.snd) /-- Given a finite set `s`, the off-diagonal, `s.off_diag` is the set of pairs `(a, b)` with `a ≠ b` for `a, b ∈ s`. -/ def off_diag := (s.product s).filter (λ (a : α × α), a.fst ≠ a.snd) @[simp] lemma mem_diag (x : α × α) : x ∈ s.diag ↔ x.1 ∈ s ∧ x.1 = x.2 := by { simp only [diag, mem_filter, mem_product], split; intros; finish, } @[simp] lemma mem_off_diag (x : α × α) : x ∈ s.off_diag ↔ x.1 ∈ s ∧ x.2 ∈ s ∧ x.1 ≠ x.2 := by { simp only [off_diag, mem_filter, mem_product], split; intros; finish, } @[simp] lemma diag_card : (diag s).card = s.card := begin suffices : diag s = s.image (λ a, (a, a)), { rw this, apply card_image_of_inj_on, finish, }, ext ⟨a₁, a₂⟩, rw mem_diag, split; intros; finish, end @[simp] lemma off_diag_card : (off_diag s).card = s.card * s.card - s.card := begin suffices : (diag s).card + (off_diag s).card = s.card * s.card, { nth_rewrite 2 ← s.diag_card, finish, }, rw ← card_product, apply filter_card_add_filter_neg_card_eq_card, end end self_prod /-- Given a set A and a set B inside it, we can shrink A to any appropriate size, and keep B inside it. -/ lemma exists_intermediate_set {A B : finset α} (i : ℕ) (h₁ : i + card B ≤ card A) (h₂ : B ⊆ A) : ∃ (C : finset α), B ⊆ C ∧ C ⊆ A ∧ card C = i + card B := begin classical, rcases nat.le.dest h₁ with ⟨k, _⟩, clear h₁, induction k with k ih generalizing A, { exact ⟨A, h₂, subset.refl _, h.symm⟩ }, { have : (A \ B).nonempty, { rw [← card_pos, card_sdiff h₂, ← h, nat.add_right_comm, nat.add_sub_cancel, nat.add_succ], apply nat.succ_pos }, rcases this with ⟨a, ha⟩, have z : i + card B + k = card (erase A a), { rw [card_erase_of_mem, ← h, nat.add_succ, nat.pred_succ], rw mem_sdiff at ha, exact ha.1 }, rcases ih _ z with ⟨B', hB', B'subA', cards⟩, { exact ⟨B', hB', trans B'subA' (erase_subset _ _), cards⟩ }, { rintros t th, apply mem_erase_of_ne_of_mem _ (h₂ th), rintro rfl, exact not_mem_sdiff_of_mem_right th ha } } end /-- We can shrink A to any smaller size. -/ lemma exists_smaller_set (A : finset α) (i : ℕ) (h₁ : i ≤ card A) : ∃ (B : finset α), B ⊆ A ∧ card B = i := let ⟨B, _, x₁, x₂⟩ := exists_intermediate_set i (by simpa) (empty_subset A) in ⟨B, x₁, x₂⟩ /-- `finset.fin_range k` is the finset `{0, 1, ..., k-1}`, as a `finset (fin k)`. -/ def fin_range (k : ℕ) : finset (fin k) := ⟨list.fin_range k, list.nodup_fin_range k⟩ @[simp] lemma fin_range_card {k : ℕ} : (fin_range k).card = k := by simp [fin_range] @[simp] lemma mem_fin_range {k : ℕ} (m : fin k) : m ∈ fin_range k := list.mem_fin_range m @[simp] lemma coe_fin_range (k : ℕ) : (fin_range k : set (fin k)) = set.univ := set.eq_univ_of_forall mem_fin_range /-- Given a finset `s` of `ℕ` contained in `{0,..., n-1}`, the corresponding finset in `fin n` is `s.attach_fin h` where `h` is a proof that all elements of `s` are less than `n`. -/ def attach_fin (s : finset ℕ) {n : ℕ} (h : ∀ m ∈ s, m < n) : finset (fin n) := ⟨s.1.pmap (λ a ha, ⟨a, ha⟩) h, multiset.nodup_pmap (λ _ _ _ _, fin.veq_of_eq) s.2⟩ @[simp] lemma mem_attach_fin {n : ℕ} {s : finset ℕ} (h : ∀ m ∈ s, m < n) {a : fin n} : a ∈ s.attach_fin h ↔ (a : ℕ) ∈ s := ⟨λ h, let ⟨b, hb₁, hb₂⟩ := multiset.mem_pmap.1 h in hb₂ ▸ hb₁, λ h, multiset.mem_pmap.2 ⟨a, h, fin.eta _ _⟩⟩ @[simp] lemma card_attach_fin {n : ℕ} (s : finset ℕ) (h : ∀ m ∈ s, m < n) : (s.attach_fin h).card = s.card := multiset.card_pmap _ _ _ /-! ### choose -/ section choose variables (p : α → Prop) [decidable_pred p] (l : finset α) /-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of `l` satisfying `p` this unique element, as an element of the corresponding subtype. -/ def choose_x (hp : (∃! a, a ∈ l ∧ p a)) : { a // a ∈ l ∧ p a } := multiset.choose_x p l.val hp /-- Given a finset `l` and a predicate `p`, associate to a proof that there is a unique element of `l` satisfying `p` this unique element, as an element of the ambient type. -/ def choose (hp : ∃! a, a ∈ l ∧ p a) : α := choose_x p l hp lemma choose_spec (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l ∧ p (choose p l hp) := (choose_x p l hp).property lemma choose_mem (hp : ∃! a, a ∈ l ∧ p a) : choose p l hp ∈ l := (choose_spec _ _ _).1 lemma choose_property (hp : ∃! a, a ∈ l ∧ p a) : p (choose p l hp) := (choose_spec _ _ _).2 end choose theorem lt_wf {α} : well_founded (@has_lt.lt (finset α) _) := have H : subrelation (@has_lt.lt (finset α) _) (inv_image (<) card), from λ x y hxy, card_lt_card hxy, subrelation.wf H $ inv_image.wf _ $ nat.lt_wf end finset namespace equiv /-- Given an equivalence `α` to `β`, produce an equivalence between `finset α` and `finset β`. -/ protected def finset_congr (e : α ≃ β) : finset α ≃ finset β := { to_fun := λ s, s.map e.to_embedding, inv_fun := λ s, s.map e.symm.to_embedding, left_inv := λ s, by simp [finset.map_map], right_inv := λ s, by simp [finset.map_map] } @[simp] lemma finset_congr_apply (e : α ≃ β) (s : finset α) : e.finset_congr s = s.map e.to_embedding := rfl @[simp] lemma finset_congr_refl : (equiv.refl α).finset_congr = equiv.refl _ := by { ext, simp } @[simp] lemma finset_congr_symm (e : α ≃ β) : e.finset_congr.symm = e.symm.finset_congr := rfl @[simp] lemma finset_congr_trans (e : α ≃ β) (e' : β ≃ γ) : e.finset_congr.trans (e'.finset_congr) = (e.trans e').finset_congr := by { ext, simp [-finset.mem_map, -equiv.trans_to_embedding] } end equiv namespace multiset variable [decidable_eq α] theorem to_finset_card_of_nodup {l : multiset α} (h : l.nodup) : l.to_finset.card = l.card := congr_arg card $ multiset.erase_dup_eq_self.mpr h lemma disjoint_to_finset {m1 m2 : multiset α} : _root_.disjoint m1.to_finset m2.to_finset ↔ m1.disjoint m2 := begin rw finset.disjoint_iff_ne, split, { intro h, intros a ha1 ha2, rw ← multiset.mem_to_finset at ha1 ha2, exact h _ ha1 _ ha2 rfl }, { rintros h a ha b hb rfl, rw multiset.mem_to_finset at ha hb, exact h ha hb } end end multiset namespace list variable [decidable_eq α] theorem to_finset_card_of_nodup {l : list α} (h : l.nodup) : l.to_finset.card = l.length := multiset.to_finset_card_of_nodup h lemma disjoint_to_finset_iff_disjoint {l l' : list α} : _root_.disjoint l.to_finset l'.to_finset ↔ l.disjoint l' := multiset.disjoint_to_finset end list
07fb4ee90ea1bd17e7b27e592c56f8b2ae19572d
94e33a31faa76775069b071adea97e86e218a8ee
/src/combinatorics/simple_graph/coloring.lean
a4a1289fd61b2541dba61bf15045e12dd7dbd6eb
[ "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
15,530
lean
/- Copyright (c) 2021 Arthur Paulino. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Arthur Paulino, Kyle Miller -/ import combinatorics.simple_graph.subgraph import combinatorics.simple_graph.clique import data.nat.lattice import data.setoid.partition import order.antichain /-! # Graph Coloring This module defines colorings of simple graphs (also known as proper colorings in the literature). A graph coloring is the attribution of "colors" to all of its vertices such that adjacent vertices have different colors. A coloring can be represented as a homomorphism into a complete graph, whose vertices represent the colors. ## Main definitions * `G.coloring α` is the type of `α`-colorings of a simple graph `G`, with `α` being the set of available colors. The type is defined to be homomorphisms from `G` into the complete graph on `α`, and colorings have a coercion to `V → α`. * `G.colorable n` is the proposition that `G` is `n`-colorable, which is whether there exists a coloring with at most *n* colors. * `G.chromatic_number` is the minimal `n` such that `G` is `n`-colorable, or `0` if it cannot be colored with finitely many colors. * `C.color_class c` is the set of vertices colored by `c : α` in the coloring `C : G.coloring α`. * `C.color_classes` is the set containing all color classes. ## Todo: * Gather material from: * https://github.com/leanprover-community/mathlib/blob/simple_graph_matching/src/combinatorics/simple_graph/coloring.lean * https://github.com/kmill/lean-graphcoloring/blob/master/src/graph.lean * Trees * Planar graphs * Chromatic polynomials * develop API for partial colorings, likely as colorings of subgraphs (`H.coe.coloring α`) -/ universes u v namespace simple_graph variables {V : Type u} (G : simple_graph V) /-- An `α`-coloring of a simple graph `G` is a homomorphism of `G` into the complete graph on `α`. This is also known as a proper coloring. -/ abbreviation coloring (α : Type v) := G →g (⊤ : simple_graph α) variables {G} {α : Type v} (C : G.coloring α) lemma coloring.valid {v w : V} (h : G.adj v w) : C v ≠ C w := C.map_rel h /-- Construct a term of `simple_graph.coloring` using a function that assigns vertices to colors and a proof that it is as proper coloring. (Note: this is a definitionally the constructor for `simple_graph.hom`, but with a syntactically better proper coloring hypothesis.) -/ @[pattern] def coloring.mk (color : V → α) (valid : ∀ {v w : V}, G.adj v w → color v ≠ color w) : G.coloring α := ⟨color, @valid⟩ /-- The color class of a given color. -/ def coloring.color_class (c : α) : set V := {v : V | C v = c} /-- The set containing all color classes. -/ def coloring.color_classes : set (set V) := (setoid.ker C).classes lemma coloring.mem_color_class (v : V) : v ∈ C.color_class (C v) := by exact rfl lemma coloring.color_classes_is_partition : setoid.is_partition C.color_classes := setoid.is_partition_classes (setoid.ker C) lemma coloring.mem_color_classes {v : V} : C.color_class (C v) ∈ C.color_classes := ⟨v, rfl⟩ lemma coloring.color_classes_finite_of_fintype [fintype α] : C.color_classes.finite := by { rw set.finite_def, apply setoid.nonempty_fintype_classes_ker, } lemma coloring.card_color_classes_le [fintype α] [fintype C.color_classes] : fintype.card C.color_classes ≤ fintype.card α := setoid.card_classes_ker_le C lemma coloring.not_adj_of_mem_color_class {c : α} {v w : V} (hv : v ∈ C.color_class c) (hw : w ∈ C.color_class c) : ¬G.adj v w := λ h, C.valid h (eq.trans hv (eq.symm hw)) lemma coloring.color_classes_independent (c : α) : is_antichain G.adj (C.color_class c) := λ v hv w hw h, C.not_adj_of_mem_color_class hv hw -- TODO make this computable noncomputable instance [fintype V] [fintype α] : fintype (coloring G α) := begin classical, change fintype (rel_hom G.adj (⊤ : simple_graph α).adj), apply fintype.of_injective _ rel_hom.coe_fn_injective, apply_instance, end variables (G) /-- Whether a graph can be colored by at most `n` colors. -/ def colorable (n : ℕ) : Prop := nonempty (G.coloring (fin n)) /-- The coloring of an empty graph. -/ def coloring_of_is_empty [is_empty V] : G.coloring α := coloring.mk is_empty_elim (λ v, is_empty_elim) lemma colorable_of_is_empty [is_empty V] (n : ℕ) : G.colorable n := ⟨G.coloring_of_is_empty⟩ lemma is_empty_of_colorable_zero (h : G.colorable 0) : is_empty V := begin split, intro v, obtain ⟨i, hi⟩ := h.some v, exact nat.not_lt_zero _ hi, end /-- The "tautological" coloring of a graph, using the vertices of the graph as colors. -/ def self_coloring : G.coloring V := coloring.mk id (λ v w, G.ne_of_adj) /-- The chromatic number of a graph is the minimal number of colors needed to color it. If `G` isn't colorable with finitely many colors, this will be 0. -/ noncomputable def chromatic_number : ℕ := Inf { n : ℕ | G.colorable n } /-- Given an embedding, there is an induced embedding of colorings. -/ def recolor_of_embedding {α β : Type*} (f : α ↪ β) : G.coloring α ↪ G.coloring β := { to_fun := λ C, (embedding.complete_graph f).to_hom.comp C, inj' := begin -- this was strangely painful; seems like missing lemmas about embeddings intros C C' h, dsimp only at h, ext v, apply (embedding.complete_graph f).inj', change ((embedding.complete_graph f).to_hom.comp C) v = _, rw h, refl, end } /-- Given an equivalence, there is an induced equivalence between colorings. -/ def recolor_of_equiv {α β : Type*} (f : α ≃ β) : G.coloring α ≃ G.coloring β := { to_fun := G.recolor_of_embedding f.to_embedding, inv_fun := G.recolor_of_embedding f.symm.to_embedding, left_inv := λ C, by { ext v, apply equiv.symm_apply_apply }, right_inv := λ C, by { ext v, apply equiv.apply_symm_apply } } /-- There is a noncomputable embedding of `α`-colorings to `β`-colorings if `β` has at least as large a cardinality as `α`. -/ noncomputable def recolor_of_card_le {α β : Type*} [fintype α] [fintype β] (hn : fintype.card α ≤ fintype.card β) : G.coloring α ↪ G.coloring β := G.recolor_of_embedding $ (function.embedding.nonempty_of_card_le hn).some variables {G} lemma colorable.mono {n m : ℕ} (h : n ≤ m) (hc : G.colorable n) : G.colorable m := ⟨G.recolor_of_card_le (by simp [h]) hc.some⟩ lemma coloring.to_colorable [fintype α] (C : G.coloring α) : G.colorable (fintype.card α) := ⟨G.recolor_of_card_le (by simp) C⟩ lemma colorable_of_fintype (G : simple_graph V) [fintype V] : G.colorable (fintype.card V) := G.self_coloring.to_colorable /-- Noncomputably get a coloring from colorability. -/ noncomputable def colorable.to_coloring [fintype α] {n : ℕ} (hc : G.colorable n) (hn : n ≤ fintype.card α) : G.coloring α := begin rw ←fintype.card_fin n at hn, exact G.recolor_of_card_le hn hc.some, end lemma colorable.of_embedding {V' : Type*} {G' : simple_graph V'} (f : G ↪g G') {n : ℕ} (h : G'.colorable n) : G.colorable n := ⟨(h.to_coloring (by simp)).comp f⟩ lemma colorable_iff_exists_bdd_nat_coloring (n : ℕ) : G.colorable n ↔ ∃ (C : G.coloring ℕ), ∀ v, C v < n := begin split, { rintro hc, have C : G.coloring (fin n) := hc.to_coloring (by simp), let f := embedding.complete_graph (fin.coe_embedding n).to_embedding, use f.to_hom.comp C, intro v, cases C with color valid, exact fin.is_lt (color v), }, { rintro ⟨C, Cf⟩, refine ⟨coloring.mk _ _⟩, { exact λ v, ⟨C v, Cf v⟩, }, { rintro v w hvw, simp only [subtype.mk_eq_mk, ne.def], exact C.valid hvw, } } end lemma colorable_set_nonempty_of_colorable {n : ℕ} (hc : G.colorable n) : {n : ℕ | G.colorable n}.nonempty := ⟨n, hc⟩ lemma chromatic_number_bdd_below : bdd_below {n : ℕ | G.colorable n} := ⟨0, λ _ _, zero_le _⟩ lemma chromatic_number_le_of_colorable {n : ℕ} (hc : G.colorable n) : G.chromatic_number ≤ n := begin rw chromatic_number, apply cInf_le chromatic_number_bdd_below, fsplit, exact classical.choice hc, end lemma chromatic_number_le_card [fintype α] (C : G.coloring α) : G.chromatic_number ≤ fintype.card α := cInf_le chromatic_number_bdd_below C.to_colorable lemma colorable_chromatic_number {m : ℕ} (hc : G.colorable m) : G.colorable G.chromatic_number := begin dsimp only [chromatic_number], rw nat.Inf_def, apply nat.find_spec, exact colorable_set_nonempty_of_colorable hc, end lemma colorable_chromatic_number_of_fintype (G : simple_graph V) [fintype V] : G.colorable G.chromatic_number := colorable_chromatic_number G.colorable_of_fintype lemma chromatic_number_le_one_of_subsingleton (G : simple_graph V) [subsingleton V] : G.chromatic_number ≤ 1 := begin rw chromatic_number, apply cInf_le chromatic_number_bdd_below, fsplit, refine coloring.mk (λ _, 0) _, intros v w, rw subsingleton.elim v w, simp, end lemma chromatic_number_eq_zero_of_isempty (G : simple_graph V) [is_empty V] : G.chromatic_number = 0 := begin rw ←nonpos_iff_eq_zero, apply cInf_le chromatic_number_bdd_below, apply colorable_of_is_empty, end lemma is_empty_of_chromatic_number_eq_zero (G : simple_graph V) [fintype V] (h : G.chromatic_number = 0) : is_empty V := begin have h' := G.colorable_chromatic_number_of_fintype, rw h at h', exact G.is_empty_of_colorable_zero h', end lemma chromatic_number_pos [nonempty V] {n : ℕ} (hc : G.colorable n) : 0 < G.chromatic_number := begin apply le_cInf (colorable_set_nonempty_of_colorable hc), intros m hm, by_contra h', simp only [not_le, nat.lt_one_iff] at h', subst h', obtain ⟨i, hi⟩ := hm.some (classical.arbitrary V), exact nat.not_lt_zero _ hi, end lemma colorable_of_chromatic_number_pos (h : 0 < G.chromatic_number) : G.colorable G.chromatic_number := begin obtain ⟨h, hn⟩ := nat.nonempty_of_pos_Inf h, exact colorable_chromatic_number hn, end lemma colorable.mono_left {G' : simple_graph V} (h : G ≤ G') {n : ℕ} (hc : G'.colorable n) : G.colorable n := ⟨hc.some.comp (hom.map_spanning_subgraphs h)⟩ lemma colorable.chromatic_number_le_of_forall_imp {V' : Type*} {G' : simple_graph V'} {m : ℕ} (hc : G'.colorable m) (h : ∀ n, G'.colorable n → G.colorable n) : G.chromatic_number ≤ G'.chromatic_number := begin apply cInf_le chromatic_number_bdd_below, apply h, apply colorable_chromatic_number hc, end lemma colorable.chromatic_number_mono (G' : simple_graph V) {m : ℕ} (hc : G'.colorable m) (h : G ≤ G') : G.chromatic_number ≤ G'.chromatic_number := hc.chromatic_number_le_of_forall_imp (λ n, colorable.mono_left h) lemma colorable.chromatic_number_mono_of_embedding {V' : Type*} {G' : simple_graph V'} {n : ℕ} (h : G'.colorable n) (f : G ↪g G') : G.chromatic_number ≤ G'.chromatic_number := h.chromatic_number_le_of_forall_imp (λ _, colorable.of_embedding f) lemma chromatic_number_eq_card_of_forall_surj [fintype α] (C : G.coloring α) (h : ∀ (C' : G.coloring α), function.surjective C') : G.chromatic_number = fintype.card α := begin apply le_antisymm, { apply chromatic_number_le_card C, }, { by_contra hc, rw not_le at hc, obtain ⟨n, cn, hc⟩ := exists_lt_of_cInf_lt (colorable_set_nonempty_of_colorable C.to_colorable) hc, rw ←fintype.card_fin n at hc, have f := (function.embedding.nonempty_of_card_le (le_of_lt hc)).some, have C' := cn.some, specialize h (G.recolor_of_embedding f C'), change function.surjective (f ∘ C') at h, have h1 : function.surjective f := function.surjective.of_comp h, have h2 := fintype.card_le_of_surjective _ h1, exact nat.lt_le_antisymm hc h2, }, end lemma chromatic_number_bot [nonempty V] : (⊥ : simple_graph V).chromatic_number = 1 := begin let C : (⊥ : simple_graph V).coloring (fin 1) := coloring.mk (λ _, 0) (λ v w h, false.elim h), apply le_antisymm, { exact chromatic_number_le_card C, }, { exact chromatic_number_pos C.to_colorable, }, end @[simp] lemma chromatic_number_top [fintype V] : (⊤ : simple_graph V).chromatic_number = fintype.card V := begin apply chromatic_number_eq_card_of_forall_surj (self_coloring _), intro C, rw ←fintype.injective_iff_surjective, intros v w, contrapose, intro h, exact C.valid h, end lemma chromatic_number_top_eq_zero_of_infinite (V : Type*) [infinite V] : (⊤ : simple_graph V).chromatic_number = 0 := begin let n := (⊤ : simple_graph V).chromatic_number, by_contra hc, replace hc := pos_iff_ne_zero.mpr hc, apply nat.not_succ_le_self n, convert_to (⊤ : simple_graph {m | m < n + 1}).chromatic_number ≤ _, { simp, }, refine (colorable_of_chromatic_number_pos hc).chromatic_number_mono_of_embedding _, apply embedding.complete_graph, exact (function.embedding.subtype _).trans (infinite.nat_embedding V), end /-- The bicoloring of a complete bipartite graph using whether a vertex is on the left or on the right. -/ def complete_bipartite_graph.bicoloring (V W : Type*) : (complete_bipartite_graph V W).coloring bool := coloring.mk (λ v, v.is_right) begin intros v w, cases v; cases w; simp, end lemma complete_bipartite_graph.chromatic_number {V W : Type*} [nonempty V] [nonempty W] : (complete_bipartite_graph V W).chromatic_number = 2 := begin apply chromatic_number_eq_card_of_forall_surj (complete_bipartite_graph.bicoloring V W), intros C b, have v := classical.arbitrary V, have w := classical.arbitrary W, have h : (complete_bipartite_graph V W).adj (sum.inl v) (sum.inr w) := by simp, have hn := C.valid h, by_cases he : C (sum.inl v) = b, { exact ⟨_, he⟩ }, { by_cases he' : C (sum.inr w) = b, { exact ⟨_, he'⟩ }, { exfalso, cases b; simp only [eq_tt_eq_not_eq_ff, eq_ff_eq_not_eq_tt] at he he'; rw [he, he'] at hn; contradiction }, }, end /-! ### Cliques -/ lemma is_clique.card_le_of_coloring {s : finset V} (h : G.is_clique s) [fintype α] (C : G.coloring α) : s.card ≤ fintype.card α := begin rw is_clique_iff_induce_eq at h, have f : G.induce ↑s ↪g G := embedding.induce ↑s, rw h at f, convert fintype.card_le_of_injective _ (C.comp f.to_hom).injective_of_top_hom using 1, simp, end lemma is_clique.card_le_of_colorable {s : finset V} (h : G.is_clique s) {n : ℕ} (hc : G.colorable n) : s.card ≤ n := begin convert h.card_le_of_coloring hc.some, simp, end -- TODO eliminate `fintype V` constraint once chromatic numbers are refactored. -- This is just to ensure the chromatic number exists. lemma is_clique.card_le_chromatic_number [fintype V] {s : finset V} (h : G.is_clique s) : s.card ≤ G.chromatic_number := h.card_le_of_colorable G.colorable_chromatic_number_of_fintype protected lemma colorable.clique_free {n m : ℕ} (hc : G.colorable n) (hm : n < m) : G.clique_free m := begin by_contra h, simp only [clique_free, is_n_clique_iff, not_forall, not_not] at h, obtain ⟨s, h, rfl⟩ := h, exact nat.lt_le_antisymm hm (h.card_le_of_colorable hc), end -- TODO eliminate `fintype V` constraint once chromatic numbers are refactored. -- This is just to ensure the chromatic number exists. lemma clique_free_of_chromatic_number_lt [fintype V] {n : ℕ} (hc : G.chromatic_number < n) : G.clique_free n := G.colorable_chromatic_number_of_fintype.clique_free hc end simple_graph
2f701db2d329cecd70872ec8808163e58f504ec8
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/tactic/rename.lean
158951aaa476a89f61f58caed872d5a98dffd33a
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
4,284
lean
/- Copyright (c) 2020 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jannis Limperg -/ import tactic.core /-! # Better `rename` tactic This module defines a variant of the standard `rename` tactic, with the following improvements: * You can rename multiple hypotheses at the same time. * Renaming a hypothesis does not change its location in the context. -/ open lean lean.parser interactive native namespace tactic /-- Get the revertible part of the local context. These are the hypotheses that appear after the last frozen local instance in the local context. We call them revertible because `revert` can revert them, unlike those hypotheses which occur before a frozen instance. -/ meta def revertible_local_context : tactic (list expr) := do ctx ← local_context, frozen ← frozen_local_instances, pure $ match frozen with | none := ctx | some [] := ctx | some (h :: _) := ctx.after (eq h) end /-- Rename local hypotheses according to the given `name_map`. The `name_map` contains as keys those hypotheses that should be renamed; the associated values are the new names. This tactic can only rename hypotheses which occur after the last frozen local instance. If you need to rename earlier hypotheses, try `unfreeze_local_instances`. If `strict` is true, we fail if `name_map` refers to hypotheses that do not appear in the local context or that appear before a frozen local instance. Conversely, if `strict` is false, some entries of `name_map` may be silently ignored. Note that we allow shadowing, so renamed hypotheses may have the same name as other hypotheses in the context. -/ meta def rename' (renames : name_map name) (strict := tt) : tactic unit := do ctx ← revertible_local_context, when strict (do let ctx_names := rb_map.set_of_list (ctx.map expr.local_pp_name), let invalid_renames := (renames.to_list.map prod.fst).filter (λ h, ¬ ctx_names.contains h), when ¬ invalid_renames.empty $ fail $ format.join [ "Cannot rename these hypotheses:\n" , format.intercalate ", " (invalid_renames.map to_fmt) , format.line , "This is because these hypotheses either do not occur in the\n" , "context or they occur before a frozen local instance.\n" , "In the latter case, try `tactic.unfreeze_local_instances`." ]), let new_name := λ current_name, (renames.find current_name).get_or_else current_name, let intro_names := list.map (new_name ∘ expr.local_pp_name) ctx, revert_lst ctx, intro_lst intro_names, pure () end tactic namespace tactic.interactive /-- Parse a current name and new name for `rename'`. -/ meta def rename'_arg_parser : parser (name × name) := prod.mk <$> ident <*> (optional (tk "->") *> ident) /-- Parse the arguments of `rename'`. -/ meta def rename'_args_parser : parser (list (name × name)) := (functor.map (λ x, [x]) rename'_arg_parser) <|> (tk "[" *> sep_by (tk ",") rename'_arg_parser <* tk "]") /-- Rename one or more local hypotheses. The renamings are given as follows: ``` rename' x y -- rename x to y rename' x → y -- ditto rename' [x y, a b] -- rename x to y and a to b rename' [x → y, a → b] -- ditto ``` Brackets are necessary if multiple hypotheses should be renamed in parallel. --- Renames one or more hypotheses in the context. ```lean example {α β} (a : α) (b : β) : unit := begin rename' a a', -- result: a' : α, b : β rename' a' → a, -- a : α, b : β rename' [a a', b b'], -- a' : α, b' : β rename' [a' → a, b' → b], -- a : α, b : β exact () end ``` Compared to the standard `rename` tactic, this tactic makes the following improvements: - You can rename multiple hypotheses at once. - Renaming a hypothesis always preserves its location in the context (whereas `rename` may reorder hypotheses). -/ meta def rename' (renames : parse rename'_args_parser) : tactic unit := tactic.rename' (rb_map.of_list renames) add_tactic_doc { name := "rename'", category := doc_category.tactic, decl_names := [`tactic.interactive.rename'], tags := ["renaming"] } end tactic.interactive
598c08ebbd27039f3b22e9b35f9374172dbc1fd2
df561f413cfe0a88b1056655515399c546ff32a5
/4-proposition-world/l8.lean
34f1f48590ef8bd0b24be9ca70ee1d52ff7ba0ce
[]
no_license
nicholaspun/natural-number-game-solutions
31d5158415c6f582694680044c5c6469032c2a06
1e2aed86d2e76a3f4a275c6d99e795ad30cf6df0
refs/heads/main
1,675,123,625,012
1,607,633,548,000
1,607,633,548,000
318,933,860
3
1
null
null
null
null
UTF-8
Lean
false
false
143
lean
lemma contrapositive (P Q : Prop) : (P → Q) → (¬ Q → ¬ P) := begin repeat {rw not_iff_imp_false}, intros f g p, apply g, exact f p, end
0275fbd463068f2222960b2d03bb56dfaf6ed813
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/269.lean
e4cf1999df1a606586ccb80cc22d96ab5737a943
[ "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
320
lean
theorem haveWithSubgoals {a b : α} : a = b ↔ b = a := by apply Iff.intro intro h have h' := h.symm exact h' intro h exact h.symm theorem haveWithSubgoals2 {a b : α} : a = b ↔ b = a := by { apply Iff.intro; intro h; have h' := h.symm; exact h'; intro h; exact h.symm; }
867077eeb64fc0b946d2cf6c325ea3ad9873fc3e
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/where.lean
30ac9bcafbff72d3459f326fbc9a8e58ecf04bc2
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
3,095
lean
/- Copyright (c) 2019 Keeley Hoek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Keeley Hoek -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.tactic.core import Mathlib.PostPort namespace Mathlib /-! # The `where` command When working in a Lean file with namespaces, parameters, and variables, it can be confusing to identify what the current "parser context" is. The command `#where` identifies and prints information about the current location, including the active namespace, open namespaces, and declared variables. It is a bug for `#where` to incorrectly report this information (this was not formerly the case); please file an issue on GitHub if you observe a failure. -/ namespace where /-- Assigns a priority to each binder for determining the order in which variables are traced. -/ /-- The relation on binder priorities. -/ /-- Selects the elements of the given `list α` which under the image of `p : α → β × γ` have `β` component equal to `b'`. Returns the `γ` components of the selected elements under the image of `p`, and the elements of the original `list α` which were not selected. -/ def select_for_which {α : Type} {β : Type} {γ : Type} (p : α → β × γ) [DecidableEq β] (b' : β) : List α → List γ × List α := sorry /-- Helper function for `collect_by`. -/ /-- Returns the elements of `l` under the image of `p`, collecting together elements with the same `β` component, deleting duplicates. -/ /-- Sort the variables by their priority as defined by `where.binder_priority`. -/ /-- Separate out the names of implicit variables (commonly instances with no name). -/ /-- Format an individual variable definition for printing. -/ /-- Turn a list of triples of variable names, binder info, and types, into a pretty list. -/ /-- Strips the namespace prefix `ns` from `n`. -/ /-- `get_open_namespaces ns` returns a list of the open namespaces, given that we are currently in the namespace `ns` (which we do not include). -/ /-- Give a slightly friendlier name for `name.anonymous` in the context of your current namespace. -/ /-- `#where` output helper which traces the current namespace. -/ /-- `#where` output helper which traces the open namespaces. -/ /-- `#where` output helper which traces the variables. -/ /-- `#where` output helper which traces the includes. -/ /-- `#where` output helper which traces the namespace end. -/ /-- `#where` output helper which traces newlines. -/ /-- `#where` output helper which traces lines, adding a newline if nonempty. -/ /-- `#where` output main function. -/ /-- When working in a Lean file with namespaces, parameters, and variables, it can be confusing to identify what the current "parser context" is. The command `#where` identifies and prints information about the current location, including the active namespace, open namespaces, and declared variables. It is a bug for `#where` to incorrectly report this information (this was not formerly the case); please file an issue on GitHub if you observe a failure. -/
5ad154aa8b63a90d7767eb42b92a4ea6607b6133
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/shadow.lean
0ce3d00fbff98200f43fef99be5376c282678d87
[ "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
194
lean
open nat variable a : nat -- The variable 'a' in the following definition is not the variable 'a' above definition tadd : nat → nat → nat | 0 b := b | (succ a) b := succ (tadd a b)
4f33b5441cb2b79587d8119d10f63f6911016871
4727251e0cd73359b15b664c3170e5d754078599
/src/measure_theory/covering/besicovitch_vector_space.lean
51ec7115bc341e051e3035fd27d1a06f53a32869
[ "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
26,098
lean
/- Copyright (c) 2021 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import measure_theory.measure.haar_lebesgue import measure_theory.covering.besicovitch /-! # Satellite configurations for Besicovitch covering lemma in vector spaces The Besicovitch covering theorem ensures that, in a nice metric space, there exists a number `N` such that, from any family of balls with bounded radii, one can extract `N` families, each made of disjoint balls, covering together all the centers of the initial family. A key tool in the proof of this theorem is the notion of a satellite configuration, i.e., a family of `N + 1` balls, where the first `N` balls all intersect the last one, but none of them contains the center of another one and their radii are controlled. This is a technical notion, but it shows up naturally in the proof of the Besicovitch theorem (which goes through a greedy algorithm): to ensure that in the end one needs at most `N` families of balls, the crucial property of the underlying metric space is that there should be no satellite configuration of `N + 1` points. This file is devoted to the study of this property in vector spaces: we prove the main result of [Füredi and Loeb, On the best constant for the Besicovitch covering theorem][furedi-loeb1994], which shows that the optimal such `N` in a vector space coincides with the maximal number of points one can put inside the unit ball of radius `2` under the condition that their distances are bounded below by `1`. In particular, this number is bounded by `5 ^ dim` by a straightforward measure argument. ## Main definitions and results * `multiplicity E` is the maximal number of points one can put inside the unit ball of radius `2` in the vector space `E`, under the condition that their distances are bounded below by `1`. * `multiplicity_le E` shows that `multiplicity E ≤ 5 ^ (dim E)`. * `good_τ E` is a constant `> 1`, but close enough to `1` that satellite configurations with this parameter `τ` are not worst than for `τ = 1`. * `is_empty_satellite_config_multiplicity` is the main theorem, saying that there are no satellite configurations of `(multiplicity E) + 1` points, for the parameter `good_τ E`. -/ universe u open metric set finite_dimensional measure_theory filter fin open_locale ennreal topological_space noncomputable theory namespace besicovitch variables {E : Type*} [normed_group E] namespace satellite_config variables [normed_space ℝ E] {N : ℕ} {τ : ℝ} (a : satellite_config E N τ) /-- Rescaling a satellite configuration in a vector space, to put the basepoint at `0` and the base radius at `1`. -/ def center_and_rescale : satellite_config E N τ := { c := λ i, (a.r (last N))⁻¹ • (a.c i - a.c (last N)), r := λ i, (a.r (last N))⁻¹ * a.r i, rpos := λ i, mul_pos (inv_pos.2 (a.rpos _)) (a.rpos _), h := λ i j hij, begin rcases a.h i j hij with H|H, { left, split, { rw [dist_eq_norm, ← smul_sub, norm_smul, real.norm_eq_abs, abs_of_nonneg (inv_nonneg.2 ((a.rpos _)).le)], refine mul_le_mul_of_nonneg_left _ (inv_nonneg.2 ((a.rpos _)).le), rw [dist_eq_norm] at H, convert H.1 using 2, abel }, { rw [← mul_assoc, mul_comm τ, mul_assoc], refine mul_le_mul_of_nonneg_left _ (inv_nonneg.2 ((a.rpos _)).le), exact H.2 } }, { right, split, { rw [dist_eq_norm, ← smul_sub, norm_smul, real.norm_eq_abs, abs_of_nonneg (inv_nonneg.2 ((a.rpos _)).le)], refine mul_le_mul_of_nonneg_left _ (inv_nonneg.2 ((a.rpos _)).le), rw [dist_eq_norm] at H, convert H.1 using 2, abel }, { rw [← mul_assoc, mul_comm τ, mul_assoc], refine mul_le_mul_of_nonneg_left _ (inv_nonneg.2 ((a.rpos _)).le), exact H.2 } }, end, hlast := λ i hi, begin have H := a.hlast i hi, split, { rw [dist_eq_norm, ← smul_sub, norm_smul, real.norm_eq_abs, abs_of_nonneg (inv_nonneg.2 ((a.rpos _)).le)], refine mul_le_mul_of_nonneg_left _ (inv_nonneg.2 ((a.rpos _)).le), rw [dist_eq_norm] at H, convert H.1 using 2, abel }, { rw [← mul_assoc, mul_comm τ, mul_assoc], refine mul_le_mul_of_nonneg_left _ (inv_nonneg.2 ((a.rpos _)).le), exact H.2 } end, inter := λ i hi, begin have H := a.inter i hi, rw [dist_eq_norm, ← smul_sub, norm_smul, real.norm_eq_abs, abs_of_nonneg (inv_nonneg.2 ((a.rpos _)).le), ← mul_add], refine mul_le_mul_of_nonneg_left _ (inv_nonneg.2 ((a.rpos _)).le), rw dist_eq_norm at H, convert H using 2, abel end } lemma center_and_rescale_center : a.center_and_rescale.c (last N) = 0 := by simp [satellite_config.center_and_rescale] lemma center_and_rescale_radius {N : ℕ} {τ : ℝ} (a : satellite_config E N τ) : a.center_and_rescale.r (last N) = 1 := by simp [satellite_config.center_and_rescale, inv_mul_cancel (a.rpos _).ne'] end satellite_config /-! ### Disjoint balls of radius close to `1` in the radius `2` ball. -/ /-- The maximum cardinality of a `1`-separated set in the ball of radius `2`. This is also the optimal number of families in the Besicovitch covering theorem. -/ def multiplicity (E : Type*) [normed_group E] := Sup {N | ∃ s : finset E, s.card = N ∧ (∀ c ∈ s, ∥c∥ ≤ 2) ∧ (∀ c ∈ s, ∀ d ∈ s, c ≠ d → 1 ≤ ∥c - d∥)} section variables [normed_space ℝ E] [finite_dimensional ℝ E] /-- Any `1`-separated set in the ball of radius `2` has cardinality at most `5 ^ dim`. This is useful to show that the supremum in the definition of `besicovitch.multiplicity E` is well behaved. -/ lemma card_le_of_separated (s : finset E) (hs : ∀ c ∈ s, ∥c∥ ≤ 2) (h : ∀ (c ∈ s) (d ∈ s), c ≠ d → 1 ≤ ∥c - d∥) : s.card ≤ 5 ^ (finrank ℝ E) := begin /- We consider balls of radius `1/2` around the points in `s`. They are disjoint, and all contained in the ball of radius `5/2`. A volume argument gives `s.card * (1/2)^dim ≤ (5/2)^dim`, i.e., `s.card ≤ 5^dim`. -/ borelize E, let μ : measure E := measure.add_haar, let δ : ℝ := (1 : ℝ)/2, let ρ : ℝ := (5 : ℝ)/2, have ρpos : 0 < ρ := by norm_num [ρ], set A := ⋃ (c ∈ s), ball (c : E) δ with hA, have D : set.pairwise (s : set E) (disjoint on (λ c, ball (c : E) δ)), { rintros c hc d hd hcd, apply ball_disjoint_ball, rw dist_eq_norm, convert h c hc d hd hcd, norm_num }, have A_subset : A ⊆ ball (0 : E) ρ, { refine Union₂_subset (λ x hx, _), apply ball_subset_ball', calc δ + dist x 0 ≤ δ + 2 : by { rw dist_zero_right, exact add_le_add le_rfl (hs x hx) } ... = 5 / 2 : by norm_num [δ] }, have I : (s.card : ℝ≥0∞) * ennreal.of_real (δ ^ (finrank ℝ E)) * μ (ball 0 1) ≤ ennreal.of_real (ρ ^ (finrank ℝ E)) * μ (ball 0 1) := calc (s.card : ℝ≥0∞) * ennreal.of_real (δ ^ (finrank ℝ E)) * μ (ball 0 1) = μ A : begin rw [hA, measure_bUnion_finset D (λ c hc, measurable_set_ball)], have I : 0 < δ, by norm_num [δ], simp only [μ.add_haar_ball_of_pos _ I, one_div, one_pow, finset.sum_const, nsmul_eq_mul, div_pow, mul_assoc] end ... ≤ μ (ball (0 : E) ρ) : measure_mono A_subset ... = ennreal.of_real (ρ ^ (finrank ℝ E)) * μ (ball 0 1) : by simp only [μ.add_haar_ball_of_pos _ ρpos], have J : (s.card : ℝ≥0∞) * ennreal.of_real (δ ^ (finrank ℝ E)) ≤ ennreal.of_real (ρ ^ (finrank ℝ E)) := (ennreal.mul_le_mul_right (measure_ball_pos _ _ zero_lt_one).ne' measure_ball_lt_top.ne).1 I, have K : (s.card : ℝ) ≤ (5 : ℝ) ^ finrank ℝ E, by simpa [ennreal.to_real_mul, div_eq_mul_inv] using ennreal.to_real_le_of_le_of_real (pow_nonneg ρpos.le _) J, exact_mod_cast K, end lemma multiplicity_le : multiplicity E ≤ 5 ^ (finrank ℝ E) := begin apply cSup_le, { refine ⟨0, ⟨∅, by simp⟩⟩ }, { rintros _ ⟨s, ⟨rfl, h⟩⟩, exact besicovitch.card_le_of_separated s h.1 h.2 } end lemma card_le_multiplicity {s : finset E} (hs : ∀ c ∈ s, ∥c∥ ≤ 2) (h's : ∀ (c ∈ s) (d ∈ s), c ≠ d → 1 ≤ ∥c - d∥) : s.card ≤ multiplicity E := begin apply le_cSup, { refine ⟨5 ^ (finrank ℝ E), _⟩, rintros _ ⟨s, ⟨rfl, h⟩⟩, exact besicovitch.card_le_of_separated s h.1 h.2 }, { simp only [mem_set_of_eq, ne.def], exact ⟨s, rfl, hs, h's⟩ } end variable (E) /-- If `δ` is small enough, a `(1-δ)`-separated set in the ball of radius `2` also has cardinality at most `multiplicity E`. -/ lemma exists_good_δ : ∃ (δ : ℝ), 0 < δ ∧ δ < 1 ∧ ∀ (s : finset E), (∀ c ∈ s, ∥c∥ ≤ 2) → (∀ (c ∈ s) (d ∈ s), c ≠ d → 1 - δ ≤ ∥c - d∥) → s.card ≤ multiplicity E := begin /- This follows from a compactness argument: otherwise, one could extract a converging subsequence, to obtain a `1`-separated set in the ball of radius `2` with cardinality `N = multiplicity E + 1`. To formalize this, we work with functions `fin N → E`. -/ classical, by_contra' h, set N := multiplicity E + 1 with hN, have : ∀ (δ : ℝ), 0 < δ → ∃ f : fin N → E, (∀ (i : fin N), ∥f i∥ ≤ 2) ∧ (∀ i j, i ≠ j → 1 - δ ≤ ∥f i - f j∥), { assume δ hδ, rcases lt_or_le δ 1 with hδ'|hδ', { rcases h δ hδ hδ' with ⟨s, hs, h's, s_card⟩, obtain ⟨f, f_inj, hfs⟩ : ∃ (f : fin N → E), function.injective f ∧ range f ⊆ ↑s, { have : fintype.card (fin N) ≤ s.card, { simp only [fintype.card_fin], exact s_card }, rcases function.embedding.exists_of_card_le_finset this with ⟨f, hf⟩, exact ⟨f, f.injective, hf⟩ }, simp only [range_subset_iff, finset.mem_coe] at hfs, refine ⟨f, λ i, hs _ (hfs i), λ i j hij, h's _ (hfs i) _ (hfs j) (f_inj.ne hij)⟩ }, { exact ⟨λ i, 0, λ i, by simp, λ i j hij, by simpa only [norm_zero, sub_nonpos, sub_self]⟩ } }, -- For `δ > 0`, `F δ` is a function from `fin N` to the ball of radius `2` for which two points -- in the image are separated by `1 - δ`. choose! F hF using this, -- Choose a converging subsequence when `δ → 0`. have : ∃ f : fin N → E, (∀ (i : fin N), ∥f i∥ ≤ 2) ∧ (∀ i j, i ≠ j → 1 ≤ ∥f i - f j∥), { obtain ⟨u, u_mono, zero_lt_u, hu⟩ : ∃ (u : ℕ → ℝ), (∀ (m n : ℕ), m < n → u n < u m) ∧ (∀ (n : ℕ), 0 < u n) ∧ filter.tendsto u filter.at_top (𝓝 0) := exists_seq_strict_anti_tendsto (0 : ℝ), have A : ∀ n, F (u n) ∈ closed_ball (0 : fin N → E) 2, { assume n, simp only [pi_norm_le_iff zero_le_two, mem_closed_ball, dist_zero_right, (hF (u n) (zero_lt_u n)).left, forall_const], }, obtain ⟨f, fmem, φ, φ_mono, hf⟩ : ∃ (f ∈ closed_ball (0 : fin N → E) 2) (φ : ℕ → ℕ), strict_mono φ ∧ tendsto ((F ∘ u) ∘ φ) at_top (𝓝 f) := is_compact.tendsto_subseq (is_compact_closed_ball _ _) A, refine ⟨f, λ i, _, λ i j hij, _⟩, { simp only [pi_norm_le_iff zero_le_two, mem_closed_ball, dist_zero_right] at fmem, exact fmem i }, { have A : tendsto (λ n, ∥F (u (φ n)) i - F (u (φ n)) j∥) at_top (𝓝 (∥f i - f j∥)) := ((hf.apply i).sub (hf.apply j)).norm, have B : tendsto (λ n, 1 - u (φ n)) at_top (𝓝 (1 - 0)) := tendsto_const_nhds.sub (hu.comp φ_mono.tendsto_at_top), rw sub_zero at B, exact le_of_tendsto_of_tendsto' B A (λ n, (hF (u (φ n)) (zero_lt_u _)).2 i j hij) } }, rcases this with ⟨f, hf, h'f⟩, -- the range of `f` contradicts the definition of `multiplicity E`. have finj : function.injective f, { assume i j hij, by_contra, have : 1 ≤ ∥f i - f j∥ := h'f i j h, simp only [hij, norm_zero, sub_self] at this, exact lt_irrefl _ (this.trans_lt zero_lt_one) }, let s := finset.image f finset.univ, have s_card : s.card = N, by { rw finset.card_image_of_injective _ finj, exact finset.card_fin N }, have hs : ∀ c ∈ s, ∥c∥ ≤ 2, by simp only [hf, forall_apply_eq_imp_iff', forall_const, forall_exists_index, finset.mem_univ, finset.mem_image], have h's : ∀ (c ∈ s) (d ∈ s), c ≠ d → 1 ≤ ∥c - d∥, { simp only [s, forall_apply_eq_imp_iff', forall_exists_index, finset.mem_univ, finset.mem_image, ne.def, exists_true_left, forall_apply_eq_imp_iff', forall_true_left], assume i j hij, have : i ≠ j := λ h, by { rw h at hij, exact hij rfl }, exact h'f i j this }, have : s.card ≤ multiplicity E := card_le_multiplicity hs h's, rw [s_card, hN] at this, exact lt_irrefl _ ((nat.lt_succ_self (multiplicity E)).trans_le this), end /-- A small positive number such that any `1 - δ`-separated set in the ball of radius `2` has cardinality at most `besicovitch.multiplicity E`. -/ def good_δ : ℝ := (exists_good_δ E).some lemma good_δ_lt_one : good_δ E < 1 := (exists_good_δ E).some_spec.2.1 /-- A number `τ > 1`, but chosen close enough to `1` so that the construction in the Besicovitch covering theorem using this parameter `τ` will give the smallest possible number of covering families. -/ def good_τ : ℝ := 1 + (good_δ E) / 4 lemma one_lt_good_τ : 1 < good_τ E := by { dsimp [good_τ, good_δ], linarith [(exists_good_δ E).some_spec.1] } variable {E} lemma card_le_multiplicity_of_δ {s : finset E} (hs : ∀ c ∈ s, ∥c∥ ≤ 2) (h's : ∀ (c ∈ s) (d ∈ s), c ≠ d → 1 - good_δ E ≤ ∥c - d∥) : s.card ≤ multiplicity E := (classical.some_spec (exists_good_δ E)).2.2 s hs h's lemma le_multiplicity_of_δ_of_fin {n : ℕ} (f : fin n → E) (h : ∀ i, ∥f i∥ ≤ 2) (h' : ∀ i j, i ≠ j → 1 - good_δ E ≤ ∥f i - f j∥) : n ≤ multiplicity E := begin classical, have finj : function.injective f, { assume i j hij, by_contra, have : 1 - good_δ E ≤ ∥f i - f j∥ := h' i j h, simp only [hij, norm_zero, sub_self] at this, linarith [good_δ_lt_one E] }, let s := finset.image f finset.univ, have s_card : s.card = n, by { rw finset.card_image_of_injective _ finj, exact finset.card_fin n }, have hs : ∀ c ∈ s, ∥c∥ ≤ 2, by simp only [h, forall_apply_eq_imp_iff', forall_const, forall_exists_index, finset.mem_univ, finset.mem_image, implies_true_iff], have h's : ∀ (c ∈ s) (d ∈ s), c ≠ d → 1 - good_δ E ≤ ∥c - d∥, { simp only [s, forall_apply_eq_imp_iff', forall_exists_index, finset.mem_univ, finset.mem_image, ne.def, exists_true_left, forall_apply_eq_imp_iff', forall_true_left], assume i j hij, have : i ≠ j := λ h, by { rw h at hij, exact hij rfl }, exact h' i j this }, have : s.card ≤ multiplicity E := card_le_multiplicity_of_δ hs h's, rwa [s_card] at this, end end namespace satellite_config /-! ### Relating satellite configurations to separated points in the ball of radius `2`. We prove that the number of points in a satellite configuration is bounded by the maximal number of `1`-separated points in the ball of radius `2`. For this, start from a satellite congifuration `c`. Without loss of generality, one can assume that the last ball is centered at `0` and of radius `1`. Define `c' i = c i` if `∥c i∥ ≤ 2`, and `c' i = (2/∥c i∥) • c i` if `∥c i∥ > 2`. It turns out that these points are `1 - δ`-separated, where `δ` is arbitrarily small if `τ` is close enough to `1`. The number of such configurations is bounded by `multiplicity E` if `δ` is suitably small. To check that the points `c' i` are `1 - δ`-separated, one treats separately the cases where both `∥c i∥` and `∥c j∥` are `≤ 2`, where one of them is `≤ 2` and the other one is `> 2`, and where both of them are `> 2`. -/ lemma exists_normalized_aux1 {N : ℕ} {τ : ℝ} (a : satellite_config E N τ) (lastr : a.r (last N) = 1) (hτ : 1 ≤ τ) (δ : ℝ) (hδ1 : τ ≤ 1 + δ / 4) (hδ2 : δ ≤ 1) (i j : fin N.succ) (inej : i ≠ j) : 1 - δ ≤ ∥a.c i - a.c j∥ := begin have ah : ∀ i j, i ≠ j → (a.r i ≤ ∥a.c i - a.c j∥ ∧ a.r j ≤ τ * a.r i) ∨ (a.r j ≤ ∥a.c j - a.c i∥ ∧ a.r i ≤ τ * a.r j), by simpa only [dist_eq_norm] using a.h, have δnonneg : 0 ≤ δ := by linarith only [hτ, hδ1], have D : 0 ≤ 1 - δ / 4, by linarith only [hδ2], have τpos : 0 < τ := _root_.zero_lt_one.trans_le hτ, have I : (1 - δ / 4) * τ ≤ 1 := calc (1 - δ / 4) * τ ≤ (1 - δ / 4) * (1 + δ / 4) : mul_le_mul_of_nonneg_left hδ1 D ... = 1 - δ^2 / 16 : by ring ... ≤ 1 : (by linarith only [sq_nonneg δ]), have J : 1 - δ ≤ 1 - δ / 4, by linarith only [δnonneg], have K : 1 - δ / 4 ≤ τ⁻¹, by { rw [inv_eq_one_div, le_div_iff τpos], exact I }, suffices L : τ⁻¹ ≤ ∥a.c i - a.c j∥, by linarith only [J, K, L], have hτ' : ∀ k, τ⁻¹ ≤ a.r k, { assume k, rw [inv_eq_one_div, div_le_iff τpos, ← lastr, mul_comm], exact a.hlast' k hτ }, rcases ah i j inej with H|H, { apply le_trans _ H.1, exact hτ' i }, { rw norm_sub_rev, apply le_trans _ H.1, exact hτ' j } end variable [normed_space ℝ E] lemma exists_normalized_aux2 {N : ℕ} {τ : ℝ} (a : satellite_config E N τ) (lastc : a.c (last N) = 0) (lastr : a.r (last N) = 1) (hτ : 1 ≤ τ) (δ : ℝ) (hδ1 : τ ≤ 1 + δ / 4) (hδ2 : δ ≤ 1) (i j : fin N.succ) (inej : i ≠ j) (hi : ∥a.c i∥ ≤ 2) (hj : 2 < ∥a.c j∥) : 1 - δ ≤ ∥a.c i - (2 / ∥a.c j∥) • a.c j∥ := begin have ah : ∀ i j, i ≠ j → (a.r i ≤ ∥a.c i - a.c j∥ ∧ a.r j ≤ τ * a.r i) ∨ (a.r j ≤ ∥a.c j - a.c i∥ ∧ a.r i ≤ τ * a.r j), by simpa only [dist_eq_norm] using a.h, have δnonneg : 0 ≤ δ := by linarith only [hτ, hδ1], have D : 0 ≤ 1 - δ / 4, by linarith only [hδ2], have τpos : 0 < τ := _root_.zero_lt_one.trans_le hτ, have hcrj : ∥a.c j∥ ≤ a.r j + 1, by simpa only [lastc, lastr, dist_zero_right] using a.inter' j, have I : a.r i ≤ 2, { rcases lt_or_le i (last N) with H|H, { apply (a.hlast i H).1.trans, simpa only [dist_eq_norm, lastc, sub_zero] using hi }, { have : i = last N := top_le_iff.1 H, rw [this, lastr], exact one_le_two } }, have J : (1 - δ / 4) * τ ≤ 1 := calc (1 - δ / 4) * τ ≤ (1 - δ / 4) * (1 + δ / 4) : mul_le_mul_of_nonneg_left hδ1 D ... = 1 - δ^2 / 16 : by ring ... ≤ 1 : (by linarith only [sq_nonneg δ]), have A : a.r j - δ ≤ ∥a.c i - a.c j∥, { rcases ah j i inej.symm with H|H, { rw norm_sub_rev, linarith [H.1] }, have C : a.r j ≤ 4 := calc a.r j ≤ τ * a.r i : H.2 ... ≤ τ * 2 : mul_le_mul_of_nonneg_left I τpos.le ... ≤ (5/4) * 2 : mul_le_mul_of_nonneg_right (by linarith only [hδ1, hδ2]) zero_le_two ... ≤ 4 : by norm_num, calc a.r j - δ ≤ a.r j - (a.r j / 4) * δ : begin refine sub_le_sub le_rfl _, refine mul_le_of_le_one_left δnonneg _, linarith only [C], end ... = (1 - δ / 4) * a.r j : by ring ... ≤ (1 - δ / 4) * (τ * a.r i) : mul_le_mul_of_nonneg_left (H.2) D ... ≤ 1 * a.r i : by { rw [← mul_assoc], apply mul_le_mul_of_nonneg_right J (a.rpos _).le } ... ≤ ∥a.c i - a.c j∥ : by { rw [one_mul], exact H.1 } }, set d := (2 / ∥a.c j∥) • a.c j with hd, have : a.r j - δ ≤ ∥a.c i - d∥ + (a.r j - 1) := calc a.r j - δ ≤ ∥a.c i - a.c j∥ : A ... ≤ ∥a.c i - d∥ + ∥d - a.c j∥ : by simp only [← dist_eq_norm, dist_triangle] ... ≤ ∥a.c i - d∥ + (a.r j - 1) : begin apply add_le_add_left, have A : 0 ≤ 1 - 2 / ∥a.c j∥, by simpa [div_le_iff (zero_le_two.trans_lt hj)] using hj.le, rw [← one_smul ℝ (a.c j), hd, ← sub_smul, norm_smul, norm_sub_rev, real.norm_eq_abs, abs_of_nonneg A, sub_mul], field_simp [(zero_le_two.trans_lt hj).ne'], linarith only [hcrj] end, linarith only [this] end lemma exists_normalized_aux3 {N : ℕ} {τ : ℝ} (a : satellite_config E N τ) (lastc : a.c (last N) = 0) (lastr : a.r (last N) = 1) (hτ : 1 ≤ τ) (δ : ℝ) (hδ1 : τ ≤ 1 + δ / 4) (i j : fin N.succ) (inej : i ≠ j) (hi : 2 < ∥a.c i∥) (hij : ∥a.c i∥ ≤ ∥a.c j∥) : 1 - δ ≤ ∥(2 / ∥a.c i∥) • a.c i - (2 / ∥a.c j∥) • a.c j∥ := begin have ah : ∀ i j, i ≠ j → (a.r i ≤ ∥a.c i - a.c j∥ ∧ a.r j ≤ τ * a.r i) ∨ (a.r j ≤ ∥a.c j - a.c i∥ ∧ a.r i ≤ τ * a.r j), by simpa only [dist_eq_norm] using a.h, have δnonneg : 0 ≤ δ := by linarith only [hτ, hδ1], have τpos : 0 < τ := _root_.zero_lt_one.trans_le hτ, have hcrj : ∥a.c j∥ ≤ a.r j + 1, by simpa only [lastc, lastr, dist_zero_right] using a.inter' j, have A : a.r i ≤ ∥a.c i∥, { have : i < last N, { apply lt_top_iff_ne_top.2, assume iN, change i = last N at iN, rw [iN, lastc, norm_zero] at hi, exact lt_irrefl _ (zero_le_two.trans_lt hi) }, convert (a.hlast i this).1, rw [dist_eq_norm, lastc, sub_zero] }, have hj : 2 < ∥a.c j∥ := hi.trans_le hij, set s := ∥a.c i∥ with hs, have spos : 0 < s := zero_lt_two.trans hi, set d := (s/∥a.c j∥) • a.c j with hd, have I : ∥a.c j - a.c i∥ ≤ ∥a.c j∥ - s + ∥d - a.c i∥ := calc ∥a.c j - a.c i∥ ≤ ∥a.c j - d∥ + ∥d - a.c i∥ : by simp [← dist_eq_norm, dist_triangle] ... = ∥a.c j∥ - ∥a.c i∥ + ∥d - a.c i∥ : begin nth_rewrite 0 ← one_smul ℝ (a.c j), rw [add_left_inj, hd, ← sub_smul, norm_smul, real.norm_eq_abs, abs_of_nonneg, sub_mul, one_mul, div_mul_cancel _ (zero_le_two.trans_lt hj).ne'], rwa [sub_nonneg, div_le_iff (zero_lt_two.trans hj), one_mul], end, have J : a.r j - ∥a.c j - a.c i∥ ≤ s / 2 * δ := calc a.r j - ∥a.c j - a.c i∥ ≤ s * (τ - 1) : begin rcases ah j i inej.symm with H|H, { calc a.r j - ∥a.c j - a.c i∥ ≤ 0 : sub_nonpos.2 H.1 ... ≤ s * (τ - 1) : mul_nonneg spos.le (sub_nonneg.2 hτ) }, { rw norm_sub_rev at H, calc a.r j - ∥a.c j - a.c i∥ ≤ τ * a.r i - a.r i : sub_le_sub H.2 H.1 ... = a.r i * (τ - 1) : by ring ... ≤ s * (τ - 1) : mul_le_mul_of_nonneg_right A (sub_nonneg.2 hτ) } end ... ≤ s * (δ / 2) : mul_le_mul_of_nonneg_left (by linarith only [δnonneg, hδ1]) spos.le ... = s / 2 * δ : by ring, have invs_nonneg : 0 ≤ 2 / s := (div_nonneg zero_le_two (zero_le_two.trans hi.le)), calc 1 - δ = (2 / s) * (s / 2 - (s / 2) * δ) : by { field_simp [spos.ne'], ring } ... ≤ (2 / s) * ∥d - a.c i∥ : mul_le_mul_of_nonneg_left (by linarith only [hcrj, I, J, hi]) invs_nonneg ... = ∥(2 / s) • a.c i - (2 / ∥a.c j∥) • a.c j∥ : begin conv_lhs { rw [norm_sub_rev, ← abs_of_nonneg invs_nonneg] }, rw [← real.norm_eq_abs, ← norm_smul, smul_sub, hd, smul_smul], congr' 3, field_simp [spos.ne'], end end lemma exists_normalized {N : ℕ} {τ : ℝ} (a : satellite_config E N τ) (lastc : a.c (last N) = 0) (lastr : a.r (last N) = 1) (hτ : 1 ≤ τ) (δ : ℝ) (hδ1 : τ ≤ 1 + δ / 4) (hδ2 : δ ≤ 1) : ∃ (c' : fin N.succ → E), (∀ n, ∥c' n∥ ≤ 2) ∧ (∀ i j, i ≠ j → 1 - δ ≤ ∥c' i - c' j∥) := begin let c' : fin N.succ → E := λ i, if ∥a.c i∥ ≤ 2 then a.c i else (2 / ∥a.c i∥) • a.c i, have norm_c'_le : ∀ i, ∥c' i∥ ≤ 2, { assume i, simp only [c'], split_ifs, { exact h }, by_cases hi : ∥a.c i∥ = 0; field_simp [norm_smul, hi] }, refine ⟨c', λ n, norm_c'_le n, λ i j inej, _⟩, -- up to exchanging `i` and `j`, one can assume `∥c i∥ ≤ ∥c j∥`. wlog hij : ∥a.c i∥ ≤ ∥a.c j∥ := le_total (∥a.c i∥) (∥a.c j∥) using [i j, j i] tactic.skip, swap, { assume i_ne_j, rw norm_sub_rev, exact this i_ne_j.symm }, rcases le_or_lt (∥a.c j∥) 2 with Hj|Hj, -- case `∥c j∥ ≤ 2` (and therefore also `∥c i∥ ≤ 2`) { simp_rw [c', Hj, hij.trans Hj, if_true], exact exists_normalized_aux1 a lastr hτ δ hδ1 hδ2 i j inej }, -- case `2 < ∥c j∥` { have H'j : (∥a.c j∥ ≤ 2) ↔ false, by simpa only [not_le, iff_false] using Hj, rcases le_or_lt (∥a.c i∥) 2 with Hi|Hi, { -- case `∥c i∥ ≤ 2` simp_rw [c', Hi, if_true, H'j, if_false], exact exists_normalized_aux2 a lastc lastr hτ δ hδ1 hδ2 i j inej Hi Hj }, { -- case `2 < ∥c i∥` have H'i : (∥a.c i∥ ≤ 2) ↔ false, by simpa only [not_le, iff_false] using Hi, simp_rw [c', H'i, if_false, H'j, if_false], exact exists_normalized_aux3 a lastc lastr hτ δ hδ1 i j inej Hi hij } } end end satellite_config variables (E) [normed_space ℝ E] [finite_dimensional ℝ E] /-- In a normed vector space `E`, there can be no satellite configuration with `multiplicity E + 1` points and the parameter `good_τ E`. This will ensure that in the inductive construction to get the Besicovitch covering families, there will never be more than `multiplicity E` nonempty families. -/ theorem is_empty_satellite_config_multiplicity : is_empty (satellite_config E (multiplicity E) (good_τ E)) := ⟨begin assume a, let b := a.center_and_rescale, rcases b.exists_normalized (a.center_and_rescale_center) (a.center_and_rescale_radius) (one_lt_good_τ E).le (good_δ E) le_rfl (good_δ_lt_one E).le with ⟨c', c'_le_two, hc'⟩, exact lt_irrefl _ ((nat.lt_succ_self _).trans_le (le_multiplicity_of_δ_of_fin c' c'_le_two hc')) end⟩ @[priority 100] instance : has_besicovitch_covering E := ⟨⟨multiplicity E, good_τ E, one_lt_good_τ E, is_empty_satellite_config_multiplicity E⟩⟩ end besicovitch
7b40a865864a78cfc809b5aab439d5ed8ab7cc29
38bf3fd2bb651ab70511408fcf70e2029e2ba310
/src/data/nat/totient.lean
bd7a77991b16848d3f3f6ad3c3eff8f4c110acb4
[ "Apache-2.0" ]
permissive
JaredCorduan/mathlib
130392594844f15dad65a9308c242551bae6cd2e
d5de80376088954d592a59326c14404f538050a1
refs/heads/master
1,595,862,206,333
1,570,816,457,000
1,570,816,457,000
209,134,499
0
0
Apache-2.0
1,568,746,811,000
1,568,746,811,000
null
UTF-8
Lean
false
false
3,593
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import algebra.big_operators data.nat.gcd open finset namespace nat def totient (n : ℕ) : ℕ := ((range n).filter (nat.coprime n)).card localized "notation `φ` := nat.totient" in nat lemma totient_le (n : ℕ) : φ n ≤ n := calc totient n ≤ (range n).card : card_le_of_subset (filter_subset _) ... = n : card_range _ lemma totient_pos : ∀ {n : ℕ}, 0 < n → 0 < φ n | 0 := dec_trivial | 1 := dec_trivial | (n+2) := λ h, card_pos.2 (mt eq_empty_iff_forall_not_mem.1 (not_forall_of_exists_not ⟨1, not_not.2 $ mem_filter.2 ⟨mem_range.2 dec_trivial, by simp [coprime]⟩⟩)) lemma sum_totient (n : ℕ) : ((range n.succ).filter (∣ n)).sum φ = n := if hn0 : n = 0 then by rw hn0; refl else calc ((range n.succ).filter (∣ n)).sum φ = ((range n.succ).filter (∣ n)).sum (λ d, ((range (n / d)).filter (λ m, gcd (n / d) m = 1)).card) : eq.symm $ sum_bij (λ d _, n / d) (λ d hd, mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ nat.div_le_self _ _, by conv {to_rhs, rw ← nat.mul_div_cancel' (mem_filter.1 hd).2}; simp⟩) (λ _ _, rfl) (λ a b ha hb h, have ha : a * (n / a) = n, from nat.mul_div_cancel' (mem_filter.1 ha).2, have 0 < (n / a), from nat.pos_of_ne_zero (λ h, by simp [*, lt_irrefl] at *), by rw [← nat.mul_right_inj this, ha, h, nat.mul_div_cancel' (mem_filter.1 hb).2]) (λ b hb, have hb : b < n.succ ∧ b ∣ n, by simpa [-range_succ] using hb, have hbn : (n / b) ∣ n, from ⟨b, by rw nat.div_mul_cancel hb.2⟩, have hnb0 : (n / b) ≠ 0, from λ h, by simpa [h, ne.symm hn0] using nat.div_mul_cancel hbn, ⟨n / b, mem_filter.2 ⟨mem_range.2 $ lt_succ_of_le $ nat.div_le_self _ _, hbn⟩, by rw [← nat.mul_right_inj (nat.pos_of_ne_zero hnb0), nat.mul_div_cancel' hb.2, nat.div_mul_cancel hbn]⟩) ... = ((range n.succ).filter (∣ n)).sum (λ d, ((range n).filter (λ m, gcd n m = d)).card) : sum_congr rfl (λ d hd, have hd : d ∣ n, from (mem_filter.1 hd).2, have hd0 : 0 < d, from nat.pos_of_ne_zero (λ h, hn0 (eq_zero_of_zero_dvd $ h ▸ hd)), card_congr (λ m hm, d * m) (λ m hm, have hm : m < n / d ∧ gcd (n / d) m = 1, by simpa using hm, mem_filter.2 ⟨mem_range.2 $ nat.mul_div_cancel' hd ▸ (mul_lt_mul_left hd0).2 hm.1, by rw [← nat.mul_div_cancel' hd, gcd_mul_left, hm.2, mul_one]⟩) (λ a b ha hb h, (nat.mul_left_inj hd0).1 h) (λ b hb, have hb : b < n ∧ gcd n b = d, by simpa using hb, ⟨b / d, mem_filter.2 ⟨mem_range.2 ((mul_lt_mul_left (show 0 < d, from hb.2 ▸ hb.2.symm ▸ hd0)).1 (by rw [← hb.2, nat.mul_div_cancel' (gcd_dvd_left _ _), nat.mul_div_cancel' (gcd_dvd_right _ _)]; exact hb.1)), hb.2 ▸ coprime_div_gcd_div_gcd (hb.2.symm ▸ hd0)⟩, hb.2 ▸ nat.mul_div_cancel' (gcd_dvd_right _ _)⟩)) ... = ((filter (∣ n) (range n.succ)).bind (λ d, (range n).filter (λ m, gcd n m = d))).card : (card_bind (by intros; apply disjoint_filter; cc)).symm ... = (range n).card : congr_arg card (finset.ext.2 (λ m, ⟨by finish, λ hm, have h : m < n, from mem_range.1 hm, mem_bind.2 ⟨gcd n m, mem_filter.2 ⟨mem_range.2 (lt_succ_of_le (le_of_dvd (lt_of_le_of_lt (nat.zero_le _) h) (gcd_dvd_left _ _))), gcd_dvd_left _ _⟩, mem_filter.2 ⟨hm, rfl⟩⟩⟩)) ... = n : card_range _ end nat
214e6ddded4f109a6bfdd2ad5b528e1d76fee3e4
27a31d06bcfc7c5d379fd04a08a9f5ed3f5302d4
/tests/lean/interactive/hover.lean
580c7cc8efa2c4b1db151beb19ee90e19e6bc5d2
[ "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
joehendrix/lean4
0d1486945f7ca9fe225070374338f4f7e74bab03
1221bdd3c7d5395baa451ce8fdd2c2f8a00cbc8f
refs/heads/master
1,640,573,727,861
1,639,662,710,000
1,639,665,515,000
198,893,504
0
0
Apache-2.0
1,564,084,645,000
1,564,084,644,000
null
UTF-8
Lean
false
false
2,581
lean
import Lean example : True := by apply True.intro --^ textDocument/hover example : True := by simp [True.intro] --^ textDocument/hover example (n : Nat) : True := by match n with | Nat.zero => _ --^ textDocument/hover | n + 1 => _ /-- My tactic -/ macro "mytac" o:"only"? e:term : tactic => `(exact $e) example : True := by mytac only True.intro --^ textDocument/hover --^ textDocument/hover --^ textDocument/hover /-- My way better tactic -/ macro_rules | `(tactic| mytac $[only]? $e) => `(apply $e) example : True := by mytac only True.intro --^ textDocument/hover /-- My ultimate tactic -/ elab_rules : tactic | `(tactic| mytac $[only]? $e) => `(tactic| refine $e) >>= Lean.Elab.Tactic.evalTactic example : True := by mytac only True.intro --^ textDocument/hover /-- My notation -/ macro "mynota" e:term : term => e #check mynota 1 --^ textDocument/hover /-- My way better notation -/ macro_rules | `(mynota $e) => `(2 * $e) #check mynota 1 --^ textDocument/hover -- macro_rules take precedence over elab_rules for term/command, so use new syntax syntax "mynota'" term : term /-- My ultimate notation -/ elab_rules : term | `(mynota' $e) => `($e * $e) >>= (Lean.Elab.Term.elabTerm · none) #check mynota' 1 --^ textDocument/hover /-- My command -/ macro "mycmd" e:term : command => `(def hi := $e) mycmd 1 --^ textDocument/hover /-- My way better command -/ macro_rules | `(mycmd $e) => `(@[inline] def hi := $e) mycmd 1 --^ textDocument/hover syntax "mycmd'" term : command /-- My ultimate command -/ elab_rules : command | `(mycmd' $e) => `(/-- hi -/ @[inline] def hi := $e) >>= Lean.Elab.Command.elabCommand mycmd' 1 --^ textDocument/hover #check ({ a := }) -- should not show `sorry` --^ textDocument/hover example : True := by simp [id True.intro] --^ textDocument/hover --^ textDocument/hover example : Id Nat := do let mut n := 1 n := 2 --^ textDocument/hover n constant foo : Nat #check _root_.foo --^ textDocument/hover namespace Bar constant foo : Nat --^ textDocument/hover #check _root_.foo --^ textDocument/hover def bar := 1 --^ textDocument/hover structure Foo := mk :: --^ textDocument/hover --^ textDocument/hover hi : Nat --^ textDocument/hover inductive Bar --^ textDocument/hover | mk : Bar --^ textDocument/hover instance : ToString Nat := ⟨toString⟩ --^ textDocument/hover instance f : ToString Nat := ⟨toString⟩ --^ textDocument/hover
6281c69b1294c9947459910b0e538e707810994f
ea5678cc400c34ff95b661fa26d15024e27ea8cd
/rationalpowers.lean
93b645da3b3ba4d4f870e16ad92b44c365007b15
[]
no_license
ChrisHughes24/leanstuff
dca0b5349c3ed893e8792ffbd98cbcadaff20411
9efa85f72efaccd1d540385952a6acc18fce8687
refs/heads/master
1,654,883,241,759
1,652,873,885,000
1,652,873,885,000
134,599,537
1
0
null
null
null
null
UTF-8
Lean
false
false
5,734
lean
-- let's define the real numbers to be a number system which satisfies -- the basic properties of the real numbers which we will need. noncomputable theory constant real : Type @[instance] constant real_field : linear_ordered_field real -- This piece of magic means that "real" now behaves a lot like -- the real numbers. In particular we now have a bunch -- of theorems: example : ∀ x y : real, x * y = y * x := mul_comm variable x : real variable n : nat -- We do _not_ have powers though. So we need to make them. open nat definition natural_power : real → nat → real | x 0 := 1 | x (succ n) := (natural_power x n) * x theorem T1 : ∀ x:real, ∀ m n:nat, natural_power x (m+n) = natural_power x m *natural_power x n := begin assume x m n, induction n with n H, unfold natural_power, rw [add_zero, mul_one], unfold natural_power, rw [H, mul_assoc], end theorem T2 : ∀ x: real, ∀ m n : nat, natural_power (natural_power x m) n = natural_power x (m*n) := begin assume x m n, induction n with n H, unfold natural_power, rw [mul_zero, eq_comm], unfold natural_power, rw [succ_eq_add_one,mul_add,mul_one,add_one], unfold natural_power, rw [T1,H] end theorem T3 : ∀ x y: real, ∀ n : nat, natural_power x n * natural_power y n = natural_power (x*y) n := begin assume x y n, induction n with n H, unfold natural_power, exact mul_one 1, rw[succ_eq_add_one], rw[T1], unfold natural_power, rw[one_mul], cc, end constant nth_root (x : real) (n : nat) : (x>0) → (n>0) → real axiom is_nth_root (x : real) (n : nat) (Hx : x>0) (Hn : n>0) : natural_power (nth_root x n Hx Hn) n = x definition rational_power_v0 (x : real) (n : nat) (d : nat) (Hx : x > 0) (Hd : d > 0) : real := natural_power (nth_root x d Hx Hd) n theorem T4 (x:real) (n:ℕ) (Hx:x≥0): 0 ≤ natural_power x n:= begin induction n with n H, unfold natural_power, exact zero_le_one, unfold natural_power, exact calc 0 = 0*x:by rw[zero_mul] ... ≤ natural_power x n * x:mul_le_mul_of_nonneg_right H Hx, end theorem T5 (x y:real) (n:ℕ) (Hx:x≥0) (Hy:y≥0) (Hn:n≥1): natural_power x n = natural_power y n → x = y := begin have H1: ∀ (s t:real), ∀ (Hs : s ≥ 0), ∀ (Ht : t ≥ 0) , s < t → natural_power s n < natural_power t n, assume s t Hs Ht Hslt, cases n with k, exfalso, have Htemp : 0 < 0, exact calc 0 < 1 : zero_lt_one ... ≤ 0 : Hn, have Htemp2 : ¬ (0=0), exact ne_of_lt Htemp, apply Htemp2, trivial, clear Hn, induction k with k Hk, unfold natural_power, rwa[one_mul,one_mul], unfold natural_power, exact calc natural_power s k * s * s = natural_power s (succ k) * s:rfl ... ≤ natural_power s (succ k) * t:mul_le_mul_of_nonneg_left (le_of_lt Hslt) (T4 s (succ k) Hs) -- (sorry) ... < natural_power t (succ k) * t: mul_lt_mul_of_pos_right Hk (calc 0≤s : Hs ... <t : Hslt) ... = natural_power t k * t * t : rfl, intro Hnp, cases lt_or_ge x y with H2 H3, exfalso, exact ne_of_lt (H1 x y Hx Hy H2) Hnp, cases lt_or_eq_of_le H3 with H4 H5, tactic.swap, exact eq.symm H5, exfalso, exact ne_of_lt (H1 y x Hy Hx H4) (eq.symm Hnp), end axiom positive_nth_root (x:real) (n:ℕ) (Hx:x>0) (Hn:n>0):0<nth_root x n Hx Hn theorem T6 (x:real) (m n k l:ℕ) (Hx:x>0) (Hm:m≥0) (Hn:n>0) (Hk:k≥0) (Hl:l>0) (Hmnkl:m*l=k*n): rational_power_v0 x m n Hx Hn=rational_power_v0 x k l Hx Hl:= begin have H2:natural_power (rational_power_v0 x m n Hx Hn) (n*l)=natural_power (rational_power_v0 x k l Hx Hl) (n*l):= begin have H2_1:natural_power (rational_power_v0 x k l Hx Hl) (n*l) = natural_power (rational_power_v0 x k l Hx Hl) (l*n):= begin rw[mul_comm] end, rw[H2_1], clear H2_1, rw[←T2,←T2], unfold rational_power_v0, rw[T2 (nth_root x l Hx Hl), mul_comm,←T2, is_nth_root], rw[T2 (nth_root x n Hx Hn), mul_comm,←T2, is_nth_root], rw[T2,T2,Hmnkl] end, have Hxmn:rational_power_v0 x m n Hx Hn≥0:= begin unfold rational_power_v0, have Hxmn_1:0≤nth_root x n Hx Hn:= le_of_lt (positive_nth_root x n Hx Hn), exact T4 (nth_root x n Hx Hn) m Hxmn_1, end, have Hxkl:rational_power_v0 x k l Hx Hl≥0:= begin unfold rational_power_v0, have Hxkl_1:0≤nth_root x l Hx Hl:= le_of_lt (positive_nth_root x l Hx Hl), exact T4 (nth_root x l Hx Hl) k Hxkl_1, end, have Hnl:n*l≥1:= begin have Hnl_1:0<n*l:=mul_pos Hn Hl, have Hnl_2:1<1+(n*l):=add_lt_add_left Hnl_1 1, have Hnl_3:1<succ(n*l):= begin rw[succ_eq_add_one,add_comm], exact Hnl_2, end, have Hnl_4:1≤(n*l):=le_of_lt_succ Hnl_3, exact(Hnl_4), end, exact T5 (rational_power_v0 x m n Hx Hn) (rational_power_v0 x k l Hx Hl) (n*l) Hxmn Hxkl Hnl H2, end theorem T7 (x:real) (m n k l:ℕ) (Hx:x>0) (Hm:m≥0) (Hn:n>0) (Hk:k≥0) (Hl:l>0) (Hmnkl:m*l=k*n): T6 x m n k l Hx Hm Hn Hk Hl Hmnkl = T6 x m n k l Hx Hm Hn Hk Hl Hmnkl := begin unfold T6, end
3728e7031a08de15539ee608f0b42bea26baf47f
827a8a5c2041b1d7f55e128581f583dfbd65ecf6
/concat_fun.hlean
936033aeb6a105d4e2dfa681e62989a46ab07b23
[ "Apache-2.0" ]
permissive
fpvandoorn/leansnippets
6af0499f6f3fd2c07e4b580734d77b67574e7c27
601bafbe07e9534af76f60994d6bdf741996ef93
refs/heads/master
1,590,063,910,882
1,545,093,878,000
1,545,093,878,000
36,044,957
2
2
null
1,442,619,708,000
1,432,256,875,000
Lean
UTF-8
Lean
false
false
2,801
hlean
open eq definition concat₁ {A : Type} {a₁ a₂ a₃ : A} (p : a₁ = a₂) (q : a₂ = a₃) : a₁ = a₃ := by induction q; assumption definition concat₂ {A : Type} {a₁ a₂ a₃ : A} (p : a₁ = a₂) (q : a₂ = a₃) : a₁ = a₃ := by induction p; assumption definition concat₃ {A : Type} {a₁ a₂ a₃ : A} (p : a₁ = a₂) (q : a₂ = a₃) : a₁ = a₃ := by induction q; induction p; reflexivity definition concat₄ {A : Type} {a₁ a₂ a₃ : A} (p : a₁ = a₂) (q : a₂ = a₃) : a₁ = a₃ := by induction p; induction q; reflexivity example {A : Type} {a a' : A} (p : a = a') : ap id p = concat₁ idp p := idp example {A : Type} {a a' : A} (p : a = a') : p = concat₂ idp p := idp example {A : Type} {a a' : A} (p : a = a') : ap id p = concat₃ idp p := idp example {A : Type} {a a' : A} (p : a = a') : ap id p = concat₄ idp p := idp example {A : Type} {a a' : A} (p : a = a') : p = concat₁ p idp := idp example {A : Type} {a a' : A} (p : a = a') : ap id p = concat₂ p idp := sorry example {A : Type} {a a' : A} (p : a = a') : ap id p = concat₃ p idp := idp example {A : Type} {a a' : A} (p : a = a') : ap id p = concat₄ p idp := sorry example {A : Type} {a a' : A} (p : a = a') : concat₃ idp p = concat₃ p idp := idp eval λ(A : Type) (a a' : A) (p : a = a'), concat₁ p idp eval λ(A : Type) (a a' : A) (p : a = a'), concat₂ p idp eval λ(A : Type) (a a' : A) (p : a = a'), concat₃ p idp eval λ(A : Type) (a a' : A) (p : a = a'), concat₄ p idp eval λ(A : Type) (a a' : A) (p : a = a'), concat₁ idp p eval λ(A : Type) (a a' : A) (p : a = a'), concat₂ idp p eval λ(A : Type) (a a' : A) (p : a = a'), concat₃ idp p eval λ(A : Type) (a a' : A) (p : a = a'), concat₄ idp p eval λ{A : Type} {a₁ a₂ a₃ : A} (p : a₁ = a₂) (q : a₂ = a₃), concat₁ p q eval λ{A : Type} {a₁ a₂ a₃ : A} (p : a₁ = a₂) (q : a₂ = a₃), concat₂ p q eval λ{A : Type} {a₁ a₂ a₃ : A} (p : a₁ = a₂) (q : a₂ = a₃), concat₃ p q eval λ{A : Type} {a₁ a₂ a₃ : A} (p : a₁ = a₂) (q : a₂ = a₃), concat₄ p q example {A B : Type} (f : A → B) {a a' : A} (p : a = a') : ap f p = ap f (idp ⬝ p) := ap_compose f id p example {A B : Type} (f : A → B) {a a' : A} (p : a = a') : ap f (ap id p) = ap f (idp ⬝ p) := idp example {A : Type} {a a' : A} (p : a = a') : ap id p = idp ⬝ p := idp example {A : Type} {a a' : A} (p : a = a') : ap_id p = idp_con p := idp example : @ap_id = @idp_con := idp definition idp_con_rev {A : Type} {a a' : A} (p : a = a') : p = idp ⬝ p := by induction p; reflexivity eval λ{A B : Type} (f : A → B) {a a' : A} (p : a = a'), ap_compose' f id p = ap02 f (idp_con_rev p)
9c2dd2129d0518609bb21e35b1f0f0962564b2ba
94e33a31faa76775069b071adea97e86e218a8ee
/src/ring_theory/polynomial/bernstein.lean
ecac38edff1b240a328f74ce3c45b61ae174581d
[ "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
15,845
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.polynomial.derivative import data.nat.choose.sum import ring_theory.polynomial.pochhammer import data.polynomial.algebra_map import linear_algebra.linear_independent import data.mv_polynomial.pderiv /-! # Bernstein polynomials The definition of the Bernstein polynomials ``` bernstein_polynomial (R : Type*) [comm_ring R] (n ν : ℕ) : R[X] := (choose n ν) * X^ν * (1 - X)^(n - ν) ``` and the fact that for `ν : fin (n+1)` these are linearly independent over `ℚ`. We prove the basic identities * `(finset.range (n + 1)).sum (λ ν, bernstein_polynomial R n ν) = 1` * `(finset.range (n + 1)).sum (λ ν, ν • bernstein_polynomial R n ν) = n • X` * `(finset.range (n + 1)).sum (λ ν, (ν * (ν-1)) • bernstein_polynomial R n ν) = (n * (n-1)) • X^2` ## Notes See also `analysis.special_functions.bernstein`, which defines the Bernstein approximations of a continuous function `f : C([0,1], ℝ)`, and shows that these converge uniformly to `f`. -/ noncomputable theory open nat (choose) open polynomial (X) open_locale big_operators polynomial variables (R : Type*) [comm_ring R] /-- `bernstein_polynomial R n ν` is `(choose n ν) * X^ν * (1 - X)^(n - ν)`. Although the coefficients are integers, it is convenient to work over an arbitrary commutative ring. -/ def bernstein_polynomial (n ν : ℕ) : R[X] := choose n ν * X^ν * (1 - X)^(n - ν) example : bernstein_polynomial ℤ 3 2 = 3 * X^2 - 3 * X^3 := begin norm_num [bernstein_polynomial, choose], ring, end namespace bernstein_polynomial lemma eq_zero_of_lt {n ν : ℕ} (h : n < ν) : bernstein_polynomial R n ν = 0 := by simp [bernstein_polynomial, nat.choose_eq_zero_of_lt h] section variables {R} {S : Type*} [comm_ring S] @[simp] lemma map (f : R →+* S) (n ν : ℕ) : (bernstein_polynomial R n ν).map f = bernstein_polynomial S n ν := by simp [bernstein_polynomial] end lemma flip (n ν : ℕ) (h : ν ≤ n) : (bernstein_polynomial R n ν).comp (1-X) = bernstein_polynomial R n (n-ν) := begin dsimp [bernstein_polynomial], simp [h, tsub_tsub_assoc, mul_right_comm], end lemma flip' (n ν : ℕ) (h : ν ≤ n) : bernstein_polynomial R n ν = (bernstein_polynomial R n (n-ν)).comp (1-X) := begin rw [←flip _ _ _ h, polynomial.comp_assoc], simp, end lemma eval_at_0 (n ν : ℕ) : (bernstein_polynomial R n ν).eval 0 = if ν = 0 then 1 else 0 := begin dsimp [bernstein_polynomial], split_ifs, { subst h, simp, }, { simp [zero_pow (nat.pos_of_ne_zero h)], }, end lemma eval_at_1 (n ν : ℕ) : (bernstein_polynomial R n ν).eval 1 = if ν = n then 1 else 0 := begin dsimp [bernstein_polynomial], split_ifs, { subst h, simp, }, { obtain w | w := (n - ν).eq_zero_or_pos, { simp [nat.choose_eq_zero_of_lt ((tsub_eq_zero_iff_le.mp w).lt_of_ne (ne.symm h))] }, { simp [zero_pow w] } }, end. lemma derivative_succ_aux (n ν : ℕ) : (bernstein_polynomial R (n+1) (ν+1)).derivative = (n+1) * (bernstein_polynomial R n ν - bernstein_polynomial R n (ν + 1)) := begin dsimp [bernstein_polynomial], suffices : ↑((n + 1).choose (ν + 1)) * ((↑ν + 1) * X ^ ν) * (1 - X) ^ (n - ν) -(↑((n + 1).choose (ν + 1)) * X ^ (ν + 1) * (↑(n - ν) * (1 - X) ^ (n - ν - 1))) = (↑n + 1) * (↑(n.choose ν) * X ^ ν * (1 - X) ^ (n - ν) - ↑(n.choose (ν + 1)) * X ^ (ν + 1) * (1 - X) ^ (n - (ν + 1))), { simpa [polynomial.derivative_pow, ←sub_eq_add_neg], }, conv_rhs { rw mul_sub, }, -- We'll prove the two terms match up separately. refine congr (congr_arg has_sub.sub _) _, { simp only [←mul_assoc], refine congr (congr_arg (*) (congr (congr_arg (*) _) rfl)) rfl, -- Now it's just about binomial coefficients exact_mod_cast congr_arg (λ m : ℕ, (m : R[X])) (nat.succ_mul_choose_eq n ν).symm, }, { rw [← tsub_add_eq_tsub_tsub, ← mul_assoc, ← mul_assoc], congr' 1, rw mul_comm , rw [←mul_assoc,←mul_assoc], congr' 1, norm_cast, congr' 1, convert (nat.choose_mul_succ_eq n (ν + 1)).symm using 1, { convert mul_comm _ _ using 2, simp, }, { apply mul_comm, }, }, end lemma derivative_succ (n ν : ℕ) : (bernstein_polynomial R n (ν+1)).derivative = n * (bernstein_polynomial R (n-1) ν - bernstein_polynomial R (n-1) (ν+1)) := begin cases n, { simp [bernstein_polynomial], }, { rw nat.cast_succ, apply derivative_succ_aux, } end lemma derivative_zero (n : ℕ) : (bernstein_polynomial R n 0).derivative = -n * bernstein_polynomial R (n-1) 0 := begin dsimp [bernstein_polynomial], simp [polynomial.derivative_pow], end lemma iterate_derivative_at_0_eq_zero_of_lt (n : ℕ) {ν k : ℕ} : k < ν → (polynomial.derivative^[k] (bernstein_polynomial R n ν)).eval 0 = 0 := begin cases ν, { rintro ⟨⟩, }, { rw nat.lt_succ_iff, induction k with k ih generalizing n ν, { simp [eval_at_0], }, { simp only [derivative_succ, int.coe_nat_eq_zero, mul_eq_zero, function.comp_app, function.iterate_succ, polynomial.iterate_derivative_sub, polynomial.iterate_derivative_cast_nat_mul, polynomial.eval_mul, polynomial.eval_nat_cast, polynomial.eval_sub], intro h, apply mul_eq_zero_of_right, rw [ih _ _ (nat.le_of_succ_le h), sub_zero], convert ih _ _ (nat.pred_le_pred h), exact (nat.succ_pred_eq_of_pos (k.succ_pos.trans_le h)).symm } }, end @[simp] lemma iterate_derivative_succ_at_0_eq_zero (n ν : ℕ) : (polynomial.derivative^[ν] (bernstein_polynomial R n (ν+1))).eval 0 = 0 := iterate_derivative_at_0_eq_zero_of_lt R n (lt_add_one ν) open polynomial @[simp] lemma iterate_derivative_at_0 (n ν : ℕ) : (polynomial.derivative^[ν] (bernstein_polynomial R n ν)).eval 0 = (pochhammer R ν).eval (n - (ν - 1) : ℕ) := begin by_cases h : ν ≤ n, { induction ν with ν ih generalizing n h, { simp [eval_at_0], }, { have h' : ν ≤ n-1 := le_tsub_of_add_le_right h, simp only [derivative_succ, ih (n-1) h', iterate_derivative_succ_at_0_eq_zero, nat.succ_sub_succ_eq_sub, tsub_zero, sub_zero, iterate_derivative_sub, iterate_derivative_cast_nat_mul, eval_one, eval_mul, eval_add, eval_sub, eval_X, eval_comp, eval_nat_cast, function.comp_app, function.iterate_succ, pochhammer_succ_left], obtain rfl | h'' := ν.eq_zero_or_pos, { simp }, { have : n - 1 - (ν - 1) = n - ν, { rw ←nat.succ_le_iff at h'', rw [← tsub_add_eq_tsub_tsub, add_comm, tsub_add_cancel_of_le h''] }, rw [this, pochhammer_eval_succ], rw_mod_cast tsub_add_cancel_of_le (h'.trans n.pred_le) } } }, { simp only [not_le] at h, rw [tsub_eq_zero_iff_le.mpr (nat.le_pred_of_lt h), eq_zero_of_lt R h], simp [pos_iff_ne_zero.mp (pos_of_gt h)] }, end lemma iterate_derivative_at_0_ne_zero [char_zero R] (n ν : ℕ) (h : ν ≤ n) : (polynomial.derivative^[ν] (bernstein_polynomial R n ν)).eval 0 ≠ 0 := begin simp only [int.coe_nat_eq_zero, bernstein_polynomial.iterate_derivative_at_0, ne.def, nat.cast_eq_zero], simp only [←pochhammer_eval_cast], norm_cast, apply ne_of_gt, obtain rfl|h' := nat.eq_zero_or_pos ν, { simp, }, { rw ← nat.succ_pred_eq_of_pos h' at h, exact pochhammer_pos _ _ (tsub_pos_of_lt (nat.lt_of_succ_le h)) } end /-! Rather than redoing the work of evaluating the derivatives at 1, we use the symmetry of the Bernstein polynomials. -/ lemma iterate_derivative_at_1_eq_zero_of_lt (n : ℕ) {ν k : ℕ} : k < n - ν → (polynomial.derivative^[k] (bernstein_polynomial R n ν)).eval 1 = 0 := begin intro w, rw flip' _ _ _ (tsub_pos_iff_lt.mp (pos_of_gt w)).le, simp [polynomial.eval_comp, iterate_derivative_at_0_eq_zero_of_lt R n w], end @[simp] lemma iterate_derivative_at_1 (n ν : ℕ) (h : ν ≤ n) : (polynomial.derivative^[n-ν] (bernstein_polynomial R n ν)).eval 1 = (-1)^(n-ν) * (pochhammer R (n - ν)).eval (ν + 1) := begin rw flip' _ _ _ h, simp [polynomial.eval_comp, h], obtain rfl | h' := h.eq_or_lt, { simp, }, { congr, norm_cast, rw [← tsub_add_eq_tsub_tsub, tsub_tsub_cancel_of_le (nat.succ_le_iff.mpr h')] }, end lemma iterate_derivative_at_1_ne_zero [char_zero R] (n ν : ℕ) (h : ν ≤ n) : (polynomial.derivative^[n-ν] (bernstein_polynomial R n ν)).eval 1 ≠ 0 := begin rw [bernstein_polynomial.iterate_derivative_at_1 _ _ _ h, ne.def, neg_one_pow_mul_eq_zero_iff, ←nat.cast_succ, ←pochhammer_eval_cast, ←nat.cast_zero, nat.cast_inj], exact (pochhammer_pos _ _ (nat.succ_pos ν)).ne', end open submodule lemma linear_independent_aux (n k : ℕ) (h : k ≤ n + 1): linear_independent ℚ (λ ν : fin k, bernstein_polynomial ℚ n ν) := begin induction k with k ih, { apply linear_independent_empty_type, }, { apply linear_independent_fin_succ'.mpr, fsplit, { exact ih (le_of_lt h), }, { -- The actual work! -- We show that the (n-k)-th derivative at 1 doesn't vanish, -- but vanishes for everything in the span. clear ih, simp only [nat.succ_eq_add_one, add_le_add_iff_right] at h, simp only [fin.coe_last, fin.init_def], dsimp, apply not_mem_span_of_apply_not_mem_span_image ((@polynomial.derivative ℚ _)^(n-k)), simp only [not_exists, not_and, submodule.mem_map, submodule.span_image], intros p m, apply_fun (polynomial.eval (1 : ℚ)), simp only [linear_map.pow_apply], -- The right hand side is nonzero, -- so it will suffice to show the left hand side is always zero. suffices : (polynomial.derivative^[n-k] p).eval 1 = 0, { rw [this], exact (iterate_derivative_at_1_ne_zero ℚ n k h).symm, }, apply span_induction m, { simp, rintro ⟨a, w⟩, simp only [fin.coe_mk], rw [iterate_derivative_at_1_eq_zero_of_lt ℚ n ((tsub_lt_tsub_iff_left_of_le h).mpr w)] }, { simp, }, { intros x y hx hy, simp [hx, hy], }, { intros a x h, simp [h], }, }, }, end /-- The Bernstein polynomials are linearly independent. We prove by induction that the collection of `bernstein_polynomial n ν` for `ν = 0, ..., k` are linearly independent. The inductive step relies on the observation that the `(n-k)`-th derivative, evaluated at 1, annihilates `bernstein_polynomial n ν` for `ν < k`, but has a nonzero value at `ν = k`. -/ lemma linear_independent (n : ℕ) : linear_independent ℚ (λ ν : fin (n+1), bernstein_polynomial ℚ n ν) := linear_independent_aux n (n+1) le_rfl lemma sum (n : ℕ) : ∑ ν in finset.range (n + 1), bernstein_polynomial R n ν = 1 := calc ∑ ν in finset.range (n + 1), bernstein_polynomial R n ν = (X + (1 - X)) ^ n : by { rw add_pow, simp only [bernstein_polynomial, mul_comm, mul_assoc, mul_left_comm] } ... = 1 : by simp open polynomial open mv_polynomial lemma sum_smul (n : ℕ) : ∑ ν in finset.range (n + 1), ν • bernstein_polynomial R n ν = n • X := begin -- We calculate the `x`-derivative of `(x+y)^n`, evaluated at `y=(1-x)`, -- either directly or by using the binomial theorem. -- We'll work in `mv_polynomial bool R`. let x : mv_polynomial bool R := mv_polynomial.X tt, let y : mv_polynomial bool R := mv_polynomial.X ff, have pderiv_tt_x : pderiv tt x = 1, { simp [x], }, have pderiv_tt_y : pderiv tt y = 0, { simp [pderiv_X, y], }, let e : bool → R[X] := λ i, cond i X (1-X), -- Start with `(x+y)^n = (x+y)^n`, -- take the `x`-derivative, evaluate at `x=X, y=1-X`, and multiply by `X`: have h : (x+y)^n = (x+y)^n := rfl, apply_fun (pderiv tt) at h, apply_fun (aeval e) at h, apply_fun (λ p, p * X) at h, -- On the left hand side we'll use the binomial theorem, then simplify. -- We first prepare a tedious rewrite: have w : ∀ k : ℕ, ↑k * polynomial.X ^ (k - 1) * (1 - polynomial.X) ^ (n - k) * ↑(n.choose k) * polynomial.X = k • bernstein_polynomial R n k, { rintro (_|k), { simp, }, { dsimp [bernstein_polynomial], simp only [←nat_cast_mul, nat.succ_eq_add_one, nat.add_succ_sub_one, add_zero, pow_succ], push_cast, ring, }, }, conv at h { to_lhs, rw [add_pow, (pderiv tt).map_sum, (mv_polynomial.aeval e).map_sum, finset.sum_mul], -- Step inside the sum: apply_congr, skip, simp [pderiv_mul, pderiv_tt_x, pderiv_tt_y, e, w], }, -- On the right hand side, we'll just simplify. conv at h { to_rhs, rw [(pderiv tt).leibniz_pow, (pderiv tt).map_add, pderiv_tt_x, pderiv_tt_y], simp [e] }, simpa using h, end lemma sum_mul_smul (n : ℕ) : ∑ ν in finset.range (n + 1), (ν * (ν-1)) • bernstein_polynomial R n ν = (n * (n-1)) • X^2 := begin -- We calculate the second `x`-derivative of `(x+y)^n`, evaluated at `y=(1-x)`, -- either directly or by using the binomial theorem. -- We'll work in `mv_polynomial bool R`. let x : mv_polynomial bool R := mv_polynomial.X tt, let y : mv_polynomial bool R := mv_polynomial.X ff, have pderiv_tt_x : pderiv tt x = 1, { simp [x], }, have pderiv_tt_y : pderiv tt y = 0, { simp [pderiv_X, y], }, let e : bool → R[X] := λ i, cond i X (1-X), -- Start with `(x+y)^n = (x+y)^n`, -- take the second `x`-derivative, evaluate at `x=X, y=1-X`, and multiply by `X`: have h : (x+y)^n = (x+y)^n := rfl, apply_fun (pderiv tt) at h, apply_fun (pderiv tt) at h, apply_fun (aeval e) at h, apply_fun (λ p, p * X^2) at h, -- On the left hand side we'll use the binomial theorem, then simplify. -- We first prepare a tedious rewrite: have w : ∀ k : ℕ, ↑k * (↑(k-1) * polynomial.X ^ (k - 1 - 1)) * (1 - polynomial.X) ^ (n - k) * ↑(n.choose k) * polynomial.X^2 = (k * (k-1)) • bernstein_polynomial R n k, { rintro (_|k), { simp, }, { rcases k with (_|k), { simp, }, { dsimp [bernstein_polynomial], simp only [←nat_cast_mul, nat.succ_eq_add_one, nat.add_succ_sub_one, add_zero, pow_succ], push_cast, ring, }, }, }, conv at h { to_lhs, rw [add_pow, (pderiv tt).map_sum, (pderiv tt).map_sum, (mv_polynomial.aeval e).map_sum, finset.sum_mul], -- Step inside the sum: apply_congr, skip, simp [pderiv_mul, pderiv_tt_x, pderiv_tt_y, e, w] }, -- On the right hand side, we'll just simplify. conv at h { to_rhs, simp only [pderiv_one, pderiv_mul, (pderiv _).leibniz_pow, (pderiv _).map_coe_nat, (pderiv tt).map_add, pderiv_tt_x, pderiv_tt_y], simp [e, smul_smul] }, simpa using h, end /-- A certain linear combination of the previous three identities, which we'll want later. -/ lemma variance (n : ℕ) : ∑ ν in finset.range (n+1), (n • polynomial.X - ν)^2 * bernstein_polynomial R n ν = n • polynomial.X * (1 - polynomial.X) := begin have p : (finset.range (n+1)).sum (λ ν, (ν * (ν-1)) • bernstein_polynomial R n ν) + (1 - (2 * n) • polynomial.X) * (finset.range (n+1)).sum (λ ν, ν • bernstein_polynomial R n ν) + (n^2 • X^2) * (finset.range (n+1)).sum (λ ν, bernstein_polynomial R n ν) = _ := rfl, conv at p { to_lhs, rw [finset.mul_sum, finset.mul_sum, ←finset.sum_add_distrib, ←finset.sum_add_distrib], simp only [←nat_cast_mul], simp only [←mul_assoc], simp only [←add_mul], }, conv at p { to_rhs, rw [sum, sum_smul, sum_mul_smul, ←nat_cast_mul], }, calc _ = _ : finset.sum_congr rfl (λ k m, _) ... = _ : p ... = _ : _, { congr' 1, simp only [←nat_cast_mul] with push_cast, cases k; { simp, ring, }, }, { simp only [←nat_cast_mul] with push_cast, cases n, { simp, }, { simp, ring, }, }, end end bernstein_polynomial
a58a18a18bdd2fd9e3a9a636572be45321db6fdb
aa101d73b1a3173c7ec56de02b96baa8ca64c42e
/src/solutions/01_equality_rewriting.lean
30d7678564132454da2115c66a64594d1410bf0b
[ "Apache-2.0" ]
permissive
gihanmarasingha/tutorials
b554d4d53866c493c4341dc13e914b01444e95a6
56617114ef0f9f7b808476faffd11e22e4380918
refs/heads/master
1,671,141,758,153
1,599,173,318,000
1,599,173,318,000
282,405,870
0
0
Apache-2.0
1,595,666,751,000
1,595,666,750,000
null
UTF-8
Lean
false
false
5,602
lean
import data.real.basic /- One of the earliest kind of proofs one encounters while learning mathematics is proving by a calculation. It may not sound like a proof, but this is actually using lemmas expressing properties of operations on numbers. It also uses the fundamental property of equality: if two mathematical objects A and B are equal then, in any statement involving A, one can replace A by B. This operation is called rewriting, and the Lean "tactic" for this is `rw`. In the following exercises, we will use the following two lemmas: mul_assoc a b c : a * b * c = a * (b * c) mul_comm a b : a*b = b*a Hence the command rw mul_assoc a b c, will replace a*b*c by a*(b*c) in the current goal. In order to replace backward, we use rw ← mul_assoc a b c, replacing a*(b*c) by a*b*c in the current goal. Of course we don't want to constantly invoke those lemmas, and we will eventually introduce more powerful solutions. -/ example (a b c : ℝ) : (a * b) * c = b * (a * c) := begin rw mul_comm a b, rw mul_assoc b a c, end -- 0001 example (a b c : ℝ) : (c * b) * a = b * (a * c) := begin -- sorry rw mul_comm c b, rw mul_assoc b c a, rw mul_comm c a, -- sorry end -- 0002 example (a b c : ℝ) : a * (b * c) = b * (a * c) := begin -- sorry rw ← mul_assoc a b c, rw mul_comm a b, rw mul_assoc b a c, -- sorry end /- Now let's return to the preceding example to experiment with what happens if we don't give arguments to mul_assoc or mul_comm. For instance, you can start the next proof with rw ← mul_assoc, Try to figure out what happens. -/ -- 0003 example (a b c : ℝ) : a * (b * c) = b * (a * c) := begin -- sorry rw ← mul_assoc, -- "rw mul_comm," doesn't do what we want. rw mul_comm a b, rw mul_assoc, -- sorry end /- We can also perform rewriting in an assumption of the local context, using for instance rw mul_comm a b at hyp, in order to replace a*b by b*a in assumption hyp. The next example will use a third lemma: two_mul a : 2*a = a + a Also we use the `exact` tactic, which allows to provide a direct proof term. -/ example (a b c d : ℝ) (hyp : c = d*a + b) (hyp' : b = a*d) : c = 2*a*d := begin rw hyp' at hyp, rw mul_comm d a at hyp, rw ← two_mul (a*d) at hyp, rw ← mul_assoc 2 a d at hyp, exact hyp, -- Our assumption hyp is now exactly what we have to prove end /- And the next one can use: sub_self x : x - x = 0 -/ -- 0004 example (a b c d : ℝ) (hyp : c = b*a - d) (hyp' : d = a*b) : c = 0 := begin -- sorry rw hyp' at hyp, rw mul_comm b a at hyp, rw sub_self (a*b) at hyp, exact hyp, -- sorry end /- What is written in the two preceding example is very far away from what we would write on paper. Let's now see how to get a more natural layout. Inside each pair of curly braces below, the goal is to prove equality with the preceding line. -/ example (a b c d : ℝ) (hyp : c = d*a + b) (hyp' : b = a*d) : c = 2*a*d := begin calc c = d*a + b : by { rw hyp } ... = d*a + a*d : by { rw hyp' } ... = a*d + a*d : by { rw mul_comm d a } ... = 2*(a*d) : by { rw two_mul } ... = 2*a*d : by { rw mul_assoc }, end /- Let's note there is no comma at the end of each line of calculation. `calc` is really one command, and the comma comes only after it's fully done. From a practical point of view, when writing such a proof, it is convenient to: * pause the tactic state view update in VScode by clicking the Pause icon button in the top right corner of the Lean Goal buffer * write the full calculation, ending each line with ": by {}" * resume tactic state update by clicking the Play icon button and fill in proofs between curly braces. Let's return to the other example using this method. -/ -- 0005 example (a b c d : ℝ) (hyp : c = b*a - d) (hyp' : d = a*b) : c = 0 := begin -- sorry calc c = b*a - d : by { rw hyp } ... = b*a - a*b : by { rw hyp' } ... = a*b - a*b : by { rw mul_comm a b } ... = 0 : by { rw sub_self (a*b) }, -- sorry end /- The preceding proofs have exhausted our supply of "mul_comm" patience. Now it's time to get the computer to work harder. The `ring` tactic will prove any goal that follows by applying only the axioms of commutative (semi-)rings, in particular commutativity and associativity of addition and multiplication, as well as distributivity. We also note that curly braces are not necessary when we write a single tactic proof, so let's get rid of them. -/ example (a b c d : ℝ) (hyp : c = d*a + b) (hyp' : b = a*d) : c = 2*a*d := begin calc c = d*a + b : by rw hyp ... = d*a + a*d : by rw hyp' ... = 2*a*d : by ring, end /- Of course we can use `ring` outside of `calc`. Let's do the next one in one line. -/ -- 0006 example (a b c : ℝ) : a * (b * c) = b * (a * c) := begin -- sorry ring, -- sorry end /- This is too much fun. Let's do it again. -/ -- 0007 example (a b : ℝ) : (a + b) + a = 2*a + b := begin -- sorry ring, -- sorry end /- Maybe this is cheating. Let's try to do the next computation without ring. We could use: pow_two x : x^2 = x*x mul_sub a b c : a*(b-c) = a*b - a*c add_mul a b c : (a+b)*c = a*c + b*c add_sub a b c : a + (b - c) = (a + b) - c sub_sub a b c : a - b - c = a - (b + c) add_zero a : a + 0 = a -/ -- 0008 example (a b : ℝ) : (a + b)*(a - b) = a^2 - b^2 := begin -- sorry rw pow_two a, rw pow_two b, rw mul_sub (a+b) a b, rw add_mul a b a, rw add_mul a b b, rw mul_comm b a, rw ← sub_sub, rw ← add_sub, rw sub_self, rw add_zero, -- sorry end /- Let's stick to ring in the end. -/
eee2669a006afdfa9f89dba276f642d317b743fb
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/tactic/lint.lean
f83a2533ae998f5c6e193eb485f9d437f4126f80
[ "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
46,843
lean
/- Copyright (c) 2019 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Robert Y. Lewis -/ import tactic.core /-! # lint commands This file defines the following user commands to spot common mistakes in the code. * `#lint`: check all declarations in the current file * `#lint_mathlib`: check all declarations in mathlib (so excluding core or other projects, and also excluding the current file) * `#lint_all`: check all declarations in the environment (the current file and all imported files) For a list of default / non-default linters, see the "Linting Commands" user command doc entry. The command `#list_linters` prints a list of the names of all available linters. You can append a `*` to any command (e.g. `#lint_mathlib*`) to omit the slow tests (4). You can append a `-` to any command (e.g. `#lint_mathlib-`) to run a silent lint that suppresses the output of passing checks. A silent lint will fail if any test fails. You can append a sequence of linter names to any command to run extra tests, in addition to the default ones. e.g. `#lint doc_blame_thm` will run all default tests and `doc_blame_thm`. You can append `only name1 name2 ...` to any command to run a subset of linters, e.g. `#lint only unused_arguments` You can add custom linters by defining a term of type `linter` in the `linter` namespace. A linter defined with the name `linter.my_new_check` can be run with `#lint my_new_check` or `lint only my_new_check`. If you add the attribute `@[linter]` to `linter.my_new_check` it will run by default. Adding the attribute `@[nolint doc_blame unused_arguments]` to a declaration omits it from only the specified linter checks. ## Tags sanity check, lint, cleanup, command, tactic -/ universe variable u open expr tactic native reserve notation `#lint` reserve notation `#lint_mathlib` reserve notation `#lint_all` reserve notation `#list_linters` setup_tactic_parser -- Manual constant subexpression elimination for performance. private meta def linter_ns := `linter private meta def nolint_infix := `_nolint /-- Computes the declaration name used to store the nolint attribute data. Retrieving the parameters for user attributes is *extremely* slow. Hence we store the parameters of the nolint attribute as declarations in the environment. E.g. for `@[nolint foo] def bar := _` we add the following declaration: ```lean meta def bar._nolint.foo : unit := () ``` -/ private meta def mk_nolint_decl_name (decl : name) (linter : name) : name := (decl ++ nolint_infix) ++ linter /-- Defines the user attribute `nolint` for skipping `#lint` -/ @[user_attribute] meta def nolint_attr : user_attribute _ (list name) := { name := "nolint", descr := "Do not report this declaration in any of the tests of `#lint`", after_set := some $ λ n _ _, (do ls@(_::_) ← nolint_attr.get_param n | fail "you need to specify at least one linter to disable", ls.mmap' $ λ l, do get_decl (linter_ns ++ l) <|> fail ("unknown linter: " ++ to_string l), try $ add_decl $ declaration.defn (mk_nolint_decl_name n l) [] `(unit) `(unit.star) (default _) ff), parser := ident* } add_tactic_doc { name := "nolint", category := doc_category.attr, decl_names := [`nolint_attr], tags := ["linting"] } /-- A linting test for the `#lint` command. `test` defines a test to perform on every declaration. It should never fail. Returning `none` signifies a passing test. Returning `some msg` reports a failing test with error `msg`. `no_errors_found` is the message printed when all tests are negative, and `errors_found` is printed when at least one test is positive. If `is_fast` is false, this test will be omitted from `#lint-`. If `auto_decls` is true, this test will also be executed on automatically generated declarations. -/ meta structure linter := (test : declaration → tactic (option string)) (no_errors_found : string) (errors_found : string) (is_fast : bool := tt) (auto_decls : bool := ff) /-- Takes a list of names that resolve to declarations of type `linter`, and produces a list of linters. -/ meta def get_linters (l : list name) : tactic (list (name × linter)) := l.mmap (λ n, prod.mk n.last <$> (mk_const n >>= eval_expr linter) <|> fail format!"invalid linter: {n}") /-- Defines the user attribute `linter` for adding a linter to the default set. Linters should be defined in the `linter` namespace. A linter `linter.my_new_linter` is referred to as `my_new_linter` (without the `linter` namespace) when used in `#lint`. -/ @[user_attribute] meta def linter_attr : user_attribute unit unit := { name := "linter", descr := "Use this declaration as a linting test in #lint", after_set := some $ λ nm _ _, mk_const nm >>= infer_type >>= unify `(linter) } add_tactic_doc { name := "linter", category := doc_category.attr, decl_names := [`linter_attr], tags := ["linting"] } /-- Pretty prints a list of arguments of a declaration. Assumes `l` is a list of argument positions and binders (or any other element that can be pretty printed). `l` can be obtained e.g. by applying `list.indexes_values` to a list obtained by `get_pi_binders`. -/ meta def print_arguments {α} [has_to_tactic_format α] (l : list (ℕ × α)) : tactic string := do fs ← l.mmap (λ ⟨n, b⟩, (λ s, to_fmt "argument " ++ to_fmt (n+1) ++ ": " ++ s) <$> pp b), return $ fs.to_string_aux tt /-! ### Implementation of the linters -/ /-- Auxilliary definition for `check_unused_arguments` -/ meta def check_unused_arguments_aux : list ℕ → ℕ → ℕ → expr → list ℕ | l n n_max e := if n > n_max then l else if ¬ is_lambda e ∧ ¬ is_pi e then l else let b := e.binding_body in let l' := if b.has_var_idx 0 then l else n :: l in check_unused_arguments_aux l' (n+1) n_max b /-- Check which arguments of a declaration are not used. Prints a list of natural numbers corresponding to which arguments are not used (e.g. this outputs [1, 4] if the first and fourth arguments are unused). Checks both the type and the value of `d` for whether the argument is used (in rare cases an argument is used in the type but not in the value). We return [] if the declaration was automatically generated. We print arguments that are larger than the arity of the type of the declaration (without unfolding definitions). -/ meta def check_unused_arguments (d : declaration) : option (list ℕ) := let l := check_unused_arguments_aux [] 1 d.type.pi_arity d.value in if l = [] then none else let l2 := check_unused_arguments_aux [] 1 d.type.pi_arity d.type in (l.filter $ λ n, n ∈ l2).reverse /-- Check for unused arguments, and print them with their position, variable name, type and whether the argument is a duplicate. See also `check_unused_arguments`. This tactic additionally filters out all unused arguments of type `parse _`. -/ meta def unused_arguments (d : declaration) : tactic (option string) := do let ns := check_unused_arguments d, if ¬ ns.is_some then return none else do let ns := ns.iget, (ds, _) ← get_pi_binders d.type, let ns := ns.map (λ n, (n, (ds.nth $ n - 1).iget)), let ns := ns.filter (λ x, x.2.type.get_app_fn ≠ const `interactive.parse []), if ns = [] then return none else do ds' ← ds.mmap pp, ns ← ns.mmap (λ ⟨n, b⟩, (λ s, to_fmt "argument " ++ to_fmt n ++ ": " ++ s ++ (if ds.countp (λ b', b.type = b'.type) ≥ 2 then " (duplicate)" else "")) <$> pp b), return $ some $ ns.to_string_aux tt /-- A linter object for checking for unused arguments. This is in the default linter set. -/ @[linter, priority 1500] meta def linter.unused_arguments : linter := { test := unused_arguments, no_errors_found := "No unused arguments", errors_found := "UNUSED ARGUMENTS" } /-- Checks whether the correct declaration constructor (definition or theorem) by comparing it to its sort. Instances will not be printed. -/ /- This test is not very quick: maybe we can speed-up testing that something is a proposition? This takes almost all of the execution time. -/ meta def incorrect_def_lemma (d : declaration) : tactic (option string) := if d.is_constant ∨ d.is_axiom then return none else do is_instance_d ← is_instance d.to_name, if is_instance_d then return none else do -- the following seems to be a little quicker than `is_prop d.type`. expr.sort n ← infer_type d.type, return $ if d.is_theorem ↔ n = level.zero then none else if (d.is_definition : bool) then "is a def, should be a lemma/theorem" else "is a lemma/theorem, should be a def" /-- A linter for checking whether the correct declaration constructor (definition or theorem) has been used. -/ @[linter, priority 1490] meta def linter.def_lemma : linter := { test := incorrect_def_lemma, no_errors_found := "All declarations correctly marked as def/lemma", errors_found := "INCORRECT DEF/LEMMA" } /-- Checks whether a declaration has a namespace twice consecutively in its name -/ meta def dup_namespace (d : declaration) : tactic (option string) := is_instance d.to_name >>= λ is_inst, return $ let nm := d.to_name.components in if nm.chain' (≠) ∨ is_inst then none else let s := (nm.find $ λ n, nm.count n ≥ 2).iget.to_string in some $ "The namespace `" ++ s ++ "` is duplicated in the name" /-- A linter for checking whether a declaration has a namespace twice consecutively in its name. -/ @[linter, priority 1480] meta def linter.dup_namespace : linter := { test := dup_namespace, no_errors_found := "No declarations have a duplicate namespace", errors_found := "DUPLICATED NAMESPACES IN NAME" } /-- Checks whether a `>`/`≥` is used in the statement of `d`. Currently it checks only the conclusion of the declaration, to eliminate false positive from binders such as `∀ ε > 0, ...` -/ meta def ge_or_gt_in_statement (d : declaration) : tactic (option string) := return $ let illegal := [`gt, `ge] in if d.type.pi_codomain.contains_constant (λ n, n ∈ illegal) then some "the type contains ≥/>. Use ≤/< instead." else none -- TODO: the commented out code also checks for classicality in statements, but needs fixing -- TODO: this probably needs to also check whether the argument is a variable or @eq <var> _ _ -- meta def illegal_constants_in_statement (d : declaration) : tactic (option string) := -- return $ if d.type.contains_constant (λ n, (n.get_prefix = `classical ∧ -- n.last ∈ ["prop_decidable", "dec", "dec_rel", "dec_eq"]) ∨ n ∈ [`gt, `ge]) -- then -- let illegal1 := [`classical.prop_decidable, `classical.dec, `classical.dec_rel, `classical.dec_eq], -- illegal2 := [`gt, `ge], -- occur1 := illegal1.filter (λ n, d.type.contains_constant (eq n)), -- occur2 := illegal2.filter (λ n, d.type.contains_constant (eq n)) in -- some $ sformat!"the type contains the following declarations: {occur1 ++ occur2}." ++ -- (if occur1 = [] then "" else " Add decidability type-class arguments instead.") ++ -- (if occur2 = [] then "" else " Use ≤/< instead.") -- else none /-- A linter for checking whether illegal constants (≥, >) appear in a declaration's type. -/ @[linter, priority 1470] meta def linter.ge_or_gt : linter := { test := ge_or_gt_in_statement, no_errors_found := "Not using ≥/> in declarations", errors_found := "USING ≥/> IN DECLARATIONS", is_fast := ff } /-- Currently, the linter forbids the use of `>` and `≥` in definitions and statements, as they cause problems in rewrites. However, we still allow them in some contexts, for instance when expressing properties of the operator (as in `cobounded (≥)`), or in quantifiers such as `∀ ε > 0`. Such statements should be marked with the attribute `nolint` to avoid linter failures. -/ library_note "nolint_ge" /-- checks whether an instance that always applies has priority ≥ 1000. -/ meta def instance_priority (d : declaration) : tactic (option string) := do let nm := d.to_name, b ← is_instance nm, /- return `none` if `d` is not an instance -/ if ¬ b then return none else do (is_persistent, prio) ← has_attribute `instance nm, /- return `none` if `d` is has low priority -/ if prio < 1000 then return none else do let (fn, args) := d.type.pi_codomain.get_app_fn_args, cls ← get_decl fn.const_name, let (pi_args, _) := cls.type.pi_binders, guard (args.length = pi_args.length), /- List all the arguments of the class that block type-class inference from firing (if they are metavariables). These are all the arguments except instance-arguments and out-params. -/ let relevant_args := (args.zip pi_args).filter_map $ λ⟨e, ⟨_, info, tp⟩⟩, if info = binder_info.inst_implicit ∨ tp.get_app_fn.is_constant_of `out_param then none else some e, let always_applies := relevant_args.all expr.is_var ∧ relevant_args.nodup, if always_applies then return $ some "set priority below 1000" else return none /-- Certain instances always apply during type-class resolution. For example, the instance `add_comm_group.to_add_group {α} [add_comm_group α] : add_group α` applies to all type-class resolution problems of the form `add_group _`, and type-class inference will then do an exhaustive search to find a commutative group. These instances take a long time to fail. Other instances will only apply if the goal has a certain shape. For example `int.add_group : add_group ℤ` or `add_group.prod {α β} [add_group α] [add_group β] : add_group (α × β)`. Usually these instances will fail quickly, and when they apply, they are almost the desired instance. For this reason, we want the instances of the second type (that only apply in specific cases) to always have higher priority than the instances of the first type (that always apply). See also #1561. Therefore, if we create an instance that always applies, we set the priority of these instances to 100 (or something similar, which is below the default value of 1000). -/ library_note "lower instance priority" /-- Instances that always apply should be applied after instances that only apply in specific cases, see note [lower instance priority] above. Classes that use the `extends` keyword automatically generate instances that always apply. Therefore, we set the priority of these instances to 100 (or something similar, which is below the default value of 1000) using `set_option default_priority 100`. We have to put this option inside a section, so that the default priority is the default 1000 outside the section. -/ library_note "default priority" /-- A linter object for checking instance priorities of instances that always apply. This is in the default linter set. -/ @[linter, priority 1460] meta def linter.instance_priority : linter := { test := instance_priority, no_errors_found := "All instance priorities are good", errors_found := "DANGEROUS INSTANCE PRIORITIES. The following instances always apply, and therefore should have a priority < 1000. If you don't know what priority to choose, use priority 100. If this is an automatically generated instance (using the keywords `class` and `extends`), see note [lower instance priority] and see note [default priority] for instructions to change the priority", auto_decls := tt } /-- Reports definitions and constants that are missing doc strings -/ meta def doc_blame_report_defn : declaration → tactic (option string) | (declaration.defn n _ _ _ _ _) := doc_string n >> return none <|> return "def missing doc string" | (declaration.cnst n _ _ _) := doc_string n >> return none <|> return "constant missing doc string" | _ := return none /-- Reports definitions and constants that are missing doc strings -/ meta def doc_blame_report_thm : declaration → tactic (option string) | (declaration.thm n _ _ _) := doc_string n >> return none <|> return "theorem missing doc string" | _ := return none /-- A linter for checking definition doc strings -/ @[linter, priority 1450] meta def linter.doc_blame : linter := { test := λ d, mcond (bnot <$> has_attribute' `instance d.to_name) (doc_blame_report_defn d) (return none), no_errors_found := "No definitions are missing documentation.", errors_found := "DEFINITIONS ARE MISSING DOCUMENTATION STRINGS" } /-- A linter for checking theorem doc strings. This is not in the default linter set. -/ meta def linter.doc_blame_thm : linter := { test := doc_blame_report_thm, no_errors_found := "No theorems are missing documentation.", errors_found := "THEOREMS ARE MISSING DOCUMENTATION STRINGS", is_fast := ff } /-- Reports declarations of types that do not have an associated `inhabited` instance. -/ meta def has_inhabited_instance (d : declaration) : tactic (option string) := do tt ← pure d.is_trusted | pure none, ff ← has_attribute' `reducible d.to_name | pure none, ff ← has_attribute' `class d.to_name | pure none, (_, ty) ← mk_local_pis d.type, ty ← whnf ty, if ty = `(Prop) then pure none else do `(Sort _) ← whnf ty | pure none, insts ← attribute.get_instances `instance, insts_tys ← insts.mmap $ λ i, expr.pi_codomain <$> declaration.type <$> get_decl i, let inhabited_insts := insts_tys.filter (λ i, i.app_fn.const_name = ``inhabited ∨ i.app_fn.const_name = `unique), let inhabited_tys := inhabited_insts.map (λ i, i.app_arg.get_app_fn.const_name), if d.to_name ∈ inhabited_tys then pure none else pure "inhabited instance missing" /-- A linter for missing `inhabited` instances. -/ @[linter, priority 1440] meta def linter.has_inhabited_instance : linter := { test := has_inhabited_instance, no_errors_found := "No types have missing inhabited instances", errors_found := "TYPES ARE MISSING INHABITED INSTANCES", is_fast := ff } /-- Checks whether an instance can never be applied. -/ meta def impossible_instance (d : declaration) : tactic (option string) := do tt ← is_instance d.to_name | return none, (binders, _) ← get_pi_binders_dep d.type, let bad_arguments := binders.filter $ λ nb, nb.2.info ≠ binder_info.inst_implicit, _ :: _ ← return bad_arguments | return none, (λ s, some $ "Impossible to infer " ++ s) <$> print_arguments bad_arguments /-- A linter object for `impossible_instance`. -/ @[linter, priority 1430] meta def linter.impossible_instance : linter := { test := impossible_instance, no_errors_found := "All instances are applicable", errors_found := "IMPOSSIBLE INSTANCES FOUND. These instances have an argument that cannot be found during type-class resolution, and therefore can never succeed. Either mark the arguments with square brackets (if it is a class), or don't make it an instance" } /-- Checks whether an instance can never be applied. -/ meta def incorrect_type_class_argument (d : declaration) : tactic (option string) := do (binders, _) ← get_pi_binders d.type, let instance_arguments := binders.indexes_values $ λ b : binder, b.info = binder_info.inst_implicit, /- the head of the type should either unfold to a class, or be a local constant. A local constant is allowed, because that could be a class when applied to the proper arguments. -/ bad_arguments ← instance_arguments.mfilter (λ ⟨_, b⟩, do (_, head) ← mk_local_pis b.type, if head.get_app_fn.is_local_constant then return ff else do bnot <$> is_class head), _ :: _ ← return bad_arguments | return none, (λ s, some $ "These are not classes. " ++ s) <$> print_arguments bad_arguments /-- A linter object for `incorrect_type_class_argument`. -/ @[linter, priority 1420] meta def linter.incorrect_type_class_argument : linter := { test := incorrect_type_class_argument, no_errors_found := "All declarations have correct type-class arguments", errors_found := "INCORRECT TYPE-CLASS ARGUMENTS. Some declarations have non-classes between [square brackets]" } /-- Checks whether an instance is dangerous: it creates a new type-class problem with metavariable arguments. -/ meta def dangerous_instance (d : declaration) : tactic (option string) := do tt ← is_instance d.to_name | return none, (local_constants, target) ← mk_local_pis d.type, let instance_arguments := local_constants.indexes_values $ λ e : expr, e.local_binding_info = binder_info.inst_implicit, let bad_arguments := local_constants.indexes_values $ λ x, !target.has_local_constant x && (x.local_binding_info ≠ binder_info.inst_implicit) && instance_arguments.any (λ nb, nb.2.local_type.has_local_constant x), let bad_arguments : list (ℕ × binder) := bad_arguments.map $ λ ⟨n, e⟩, ⟨n, e.to_binder⟩, _ :: _ ← return bad_arguments | return none, (λ s, some $ "The following arguments become metavariables. " ++ s) <$> print_arguments bad_arguments /-- A linter object for `dangerous_instance`. -/ @[linter, priority 1410] meta def linter.dangerous_instance : linter := { test := dangerous_instance, no_errors_found := "No dangerous instances", errors_found := "DANGEROUS INSTANCES FOUND.\nThese instances are recursive, and create a new type-class problem which will have metavariables. Possible solution: remove the instance attribute or make it a local instance instead. Currently this linter does not check whether the metavariables only occur in arguments marked with `out_param`, in which case this linter gives a false positive.", auto_decls := tt } /-- Applies expression `e` to local constants, but lifts all the arguments that are `Sort`-valued to `Type`-valued sorts. -/ meta def apply_to_fresh_variables (e : expr) : tactic expr := do t ← infer_type e, (xs, b) ← mk_local_pis t, xs.mmap' $ λ x, try $ do { u ← mk_meta_univ, tx ← infer_type x, ttx ← infer_type tx, unify ttx (expr.sort u.succ) }, return $ e.app_of_list xs /-- Tests whether type-class inference search for a class will end quickly when applied to variables. This tactic succeeds if `mk_instance` succeeds quickly or fails quickly with the error message that it cannot find an instance. It fails if the tactic takes too long, or if any other error message is raised. We make sure that we apply the tactic to variables living in `Type u` instead of `Sort u`, because many instances only apply in that special case, and we do want to catch those loops. -/ meta def fails_quickly (max_steps : ℕ) (d : declaration) : tactic (option string) := do e ← mk_const d.to_name, tt ← is_class e | return none, e' ← apply_to_fresh_variables e, sum.inr msg ← retrieve_or_report_error $ tactic.try_for max_steps $ succeeds_or_fails_with_msg (mk_instance e') $ λ s, "tactic.mk_instance failed to generate instance for".is_prefix_of s | return none, return $ some $ if msg = "try_for tactic failed, timeout" then "type-class inference timed out" else msg /-- A linter object for `fails_quickly`. If we want to increase the maximum number of steps type-class inference is allowed to take, we can increase the number `3000` in the definition. As of 5 Mar 2020 the longest trace (for `is_add_hom`) takes 2900-3000 "heartbeats". -/ @[linter, priority 1408] meta def linter.fails_quickly : linter := { test := fails_quickly 3000, no_errors_found := "No type-class searches timed out", errors_found := "TYPE CLASS SEARCHES TIMED OUT. For the following classes, there is an instance that causes a loop, or an excessively long search.", is_fast := ff } /-- Tests whether there is no instance of type `has_coe α t` where `α` is a variable. See note [use has_coe_t]. -/ meta def has_coe_variable (d : declaration) : tactic (option string) := do tt ← is_instance d.to_name | return none, `(has_coe %%a _) ← return d.type.pi_codomain | return none, tt ← return a.is_var | return none, return $ some $ "illegal instance" /-- A linter object for `has_coe_variable`. -/ @[linter, priority 1405] meta def linter.has_coe_variable : linter := { test := has_coe_variable, no_errors_found := "No invalid `has_coe` instances", errors_found := "INVALID `has_coe` INSTANCES. Make the following declarations instances of the class `has_coe_t` instead of `has_coe`." } /-- Checks whether a declaration is prop-valued and takes an `inhabited _` argument that is unused elsewhere in the type. In this case, that argument can be replaced with `nonempty _`. -/ meta def inhabited_nonempty (d : declaration) : tactic (option string) := do tt ← is_prop d.type | return none, (binders, _) ← get_pi_binders_dep d.type, let inhd_binders := binders.filter $ λ pr, pr.2.type.is_app_of `inhabited, if inhd_binders.length = 0 then return none else (λ s, some $ "The following `inhabited` instances should be `nonempty`. " ++ s) <$> print_arguments inhd_binders /-- A linter object for `inhabited_nonempty`. -/ @[linter, priority 1400] meta def linter.inhabited_nonempty : linter := { test := inhabited_nonempty, no_errors_found := "No uses of `inhabited` arguments should be replaced with `nonempty`", errors_found := "USES OF `inhabited` SHOULD BE REPLACED WITH `nonempty`." } /-- `simp_lhs_rhs ty` returns the left-hand and right-hand side of a simp lemma with type `ty`. -/ private meta def simp_lhs_rhs : expr → tactic (expr × expr) | ty := do ty ← whnf ty transparency.reducible, -- We only detect a fixed set of simp relations here. -- This is somewhat justified since for a custom simp relation R, -- the simp lemma `R a b` is implicitly converted to `R a b ↔ true` as well. match ty with | `(¬ %%lhs) := pure (lhs, `(false)) | `(%%lhs = %%rhs) := pure (lhs, rhs) | `(%%lhs ↔ %%rhs) := pure (lhs, rhs) | (expr.pi n bi a b) := do l ← mk_local' n bi a, simp_lhs_rhs (b.instantiate_var l) | ty := pure (ty, `(true)) end /-- `simp_lhs ty` returns the left-hand side of a simp lemma with type `ty`. -/ private meta def simp_lhs (ty : expr): tactic expr := prod.fst <$> simp_lhs_rhs ty /-- `simp_is_conditional ty` returns true iff the simp lemma with type `ty` is conditional. -/ private meta def simp_is_conditional : expr → tactic bool | ty := do ty ← whnf ty transparency.semireducible, match ty with | `(¬ %%lhs) := pure ff | `(%%lhs = _) := pure ff | `(%%lhs ↔ _) := pure ff | (expr.pi n bi a b) := if bi ≠ binder_info.inst_implicit ∧ ¬ b.has_var then pure tt else do l ← mk_local' n bi a, simp_is_conditional (b.instantiate_var l) | ty := pure ff end private meta def heuristic_simp_lemma_extraction (prf : expr) : tactic (list name) := prf.list_constant.to_list.mfilter is_simp_lemma /-- Reports declarations that are simp lemmas whose left-hand side is not in simp-normal form. -/ meta def simp_nf_linter (timeout := 200000) (d : declaration) : tactic (option string) := do tt ← is_simp_lemma d.to_name | pure none, -- Sometimes, a definition is tagged @[simp] to add the equational lemmas to the simp set. -- In this case, ignore the declaration if it is not a valid simp lemma by itself. tt ← is_valid_simp_lemma_cnst d.to_name | pure none, (λ tac, tactic.try_for timeout tac <|> pure (some "timeout")) $ -- last resort (λ tac : tactic _, tac <|> pure none) $ -- tc resolution depth retrieve $ do reset_instance_cache, g ← mk_meta_var d.type, set_goals [g], intros, (lhs, rhs) ← target >>= simp_lhs_rhs, sls ← simp_lemmas.mk_default, let sls' := sls.erase [d.to_name], -- TODO: should we do something special about rfl-lemmas? (lhs', prf1) ← simplify sls [] lhs {fail_if_unchanged := ff}, prf1_lems ← heuristic_simp_lemma_extraction prf1, if d.to_name ∈ prf1_lems then pure none else do (rhs', prf2) ← simplify sls [] rhs {fail_if_unchanged := ff}, lhs'_eq_rhs' ← succeeds (is_def_eq lhs' rhs' transparency.reducible), lhs_in_nf ← succeeds (is_def_eq lhs' lhs transparency.reducible), if lhs'_eq_rhs' ∧ lhs'.get_app_fn.const_name = rhs'.get_app_fn.const_name then do used_lemmas ← heuristic_simp_lemma_extraction (prf1 prf2), pure $ pure $ "simp can prove this:\n" ++ " by simp only " ++ to_string used_lemmas ++ "\n" ++ "One of the lemmas above could be a duplicate.\n" ++ "If that's not the case try reordering lemmas or adding @[priority].\n" else if ¬ lhs_in_nf then do lhs ← pp lhs, lhs' ← pp lhs', pure $ format.to_string $ to_fmt "Left-hand side simplifies from" ++ lhs.group.indent 2 ++ format.line ++ "to" ++ lhs'.group.indent 2 ++ format.line ++ "using " ++ (to_fmt prf1_lems).group.indent 2 ++ format.line ++ "Try to change the left-hand side to the simplified term!\n" else pure none /-- A linter for simp lemmas whose lhs is not in simp-normal form, and which hence never fire. -/ @[linter, priority 1390] meta def linter.simp_nf : linter := { test := simp_nf_linter, no_errors_found := "All left-hand sides of simp lemmas are in simp-normal form", errors_found := "SOME SIMP LEMMAS ARE REDUNDANT. That is, their left-hand side is not in simp-normal form. These lemmas are hence never used by the simplifier. This linter gives you a list of other simp lemmas, look at them! Here are some guidelines to get you started: 1. 'the left-hand side reduces to XYZ': you should probably use XYZ as the left-hand side. 2. 'simp can prove this': This typically means that lemma is a duplicate, or is shadowed by another lemma: 2a. Always put more general lemmas after specific ones: @[simp] lemma zero_add_zero : 0 + 0 = 0 := rfl @[simp] lemma add_zero : x + 0 = x := rfl And not the other way around! The simplifier always picks the last matching lemma. 2b. You can also use @[priority] instead of moving simp-lemmas around in the file. Tip: the default priority is 1000. Use `@[priority 1100]` instead of moving a lemma down, and `@[priority 900]` instead of moving a lemma up. 2c. Conditional simp lemmas are tried last, if they are shadowed just remove the simp attribute. 2d. If two lemmas are duplicates, the linter will complain about the first one. Try to fix the second one instead! (You can find it among the other simp lemmas the linter prints out!) " } private meta def simp_var_head (d : declaration) : tactic (option string) := do tt ← is_simp_lemma d.to_name | pure none, -- Sometimes, a definition is tagged @[simp] to add the equational lemmas to the simp set. -- In this case, ignore the declaration if it is not a valid simp lemma by itself. tt ← is_valid_simp_lemma_cnst d.to_name | pure none, lhs ← simp_lhs d.type, head_sym@(expr.local_const _ _ _ _) ← pure lhs.get_app_fn | pure none, head_sym ← pp head_sym, pure $ format.to_string $ "Left-hand side has variable as head symbol: " ++ head_sym /-- A linter for simp lemmas whose lhs has a variable as head symbol, and which hence never fire. -/ @[linter, priority 1389] meta def linter.simp_var_head : linter := { test := simp_var_head, no_errors_found := "No left-hand sides of a simp lemma has a variable as head symbol", errors_found := "LEFT-HAND SIDE HAS VARIABLE AS HEAD SYMBOL.\n" ++ "Some simp lemmas have a variable as head symbol of the left-hand side" } private meta def simp_comm (d : declaration) : tactic (option string) := do tt ← is_simp_lemma d.to_name | pure none, -- Sometimes, a definition is tagged @[simp] to add the equational lemmas to the simp set. -- In this case, ignore the declaration if it is not a valid simp lemma by itself. tt ← is_valid_simp_lemma_cnst d.to_name | pure none, (lhs, rhs) ← simp_lhs_rhs d.type, if lhs.get_app_fn.const_name ≠ rhs.get_app_fn.const_name then pure none else do (lhs', rhs') ← (prod.snd <$> mk_meta_pis d.type) >>= simp_lhs_rhs, tt ← succeeds $ unify rhs' lhs transparency.reducible | pure none, tt ← succeeds $ is_def_eq rhs lhs' transparency.reducible | pure none, -- ensure that the second application makes progress: ff ← succeeds $ is_def_eq lhs' rhs' transparency.reducible | pure none, pure $ "should not be marked simp" /-- A linter for commutativity lemmas that are marked simp. -/ @[linter, priority 1385] meta def linter.simp_comm : linter := { test := simp_comm, no_errors_found := "No commutativity lemma is marked simp", errors_found := "COMMUTATIVITY LEMMA IS SIMP.\n" ++ "Some commutativity lemmas are simp lemmas" } /-! ### Implementation of the frontend -/ /-- `get_checks slow extra use_only` produces a list of linters. `extras` is a list of names that should resolve to declarations with type `linter`. If `use_only` is true, it only uses the linters in `extra`. Otherwise, it uses all linters in the environment tagged with `@[linter]`. If `slow` is false, it only uses the fast default tests. -/ meta def get_checks (slow : bool) (extra : list name) (use_only : bool) : tactic (list (name × linter)) := do default ← if use_only then return [] else attribute.get_instances `linter >>= get_linters, let default := if slow then default else default.filter (λ l, l.2.is_fast), list.append default <$> get_linters extra /-- `should_be_linted linter decl` returns true if `decl` should be checked using `linter`, i.e., if there is no `nolint` attribute. -/ meta def should_be_linted (linter : name) (decl : name) : tactic bool := do e ← get_env, pure $ ¬ e.contains (mk_nolint_decl_name decl linter) /-- `lint_core all_decls non_auto_decls checks` applies the linters `checks` to the list of declarations. If `auto_decls` is false for a linter (default) the linter is applied to `non_auto_decls`. If `auto_decls` is true, then it is applied to `all_decls`. The resulting list has one element for each linter, containing the linter as well as a map from declaration name to warning. -/ meta def lint_core (all_decls non_auto_decls : list declaration) (checks : list (name × linter)) : tactic (list (name × linter × rb_map name string)) := do checks.mmap $ λ ⟨linter_name, linter⟩, do let test_decls := if linter.auto_decls then all_decls else non_auto_decls, results ← test_decls.mfoldl (λ (results : rb_map name string) decl, do tt ← should_be_linted linter_name decl.to_name | pure results, some linter_warning ← linter.test decl | pure results, pure $ results.insert decl.to_name linter_warning) mk_rb_map, pure (linter_name, linter, results) /-- Sorts a map with declaration keys as names by line number. -/ meta def sort_results {α} (e : environment) (results : rb_map name α) : list (name × α) := list.reverse $ rb_lmap.values $ rb_lmap.of_list $ results.fold [] $ λ decl linter_warning results, (((e.decl_pos decl).get_or_else ⟨0,0⟩).line, (decl, linter_warning)) :: results /-- Formats a linter warning as `#print` command with comment. -/ meta def print_warning (decl_name : name) (warning : string) : format := "#print " ++ to_fmt decl_name ++ " /- " ++ warning ++ " -/" /-- Formats a map of linter warnings using `print_warning`, sorted by line number. -/ meta def print_warnings (env : environment) (results : rb_map name string) : format := format.intercalate format.line $ (sort_results env results).map $ λ ⟨decl_name, warning⟩, print_warning decl_name warning /-- Formats a map of linter warnings grouped by filename with `-- filename` comments. The first `drop_fn_chars` characters are stripped from the filename. -/ meta def grouped_by_filename (e : environment) (results : rb_map name string) (drop_fn_chars := 0) (formatter: rb_map name string → format) : format := let results := results.fold (rb_map.mk string (rb_map name string)) $ λ decl_name linter_warning results, let fn := (e.decl_olean decl_name).get_or_else "" in results.insert fn (((results.find fn).get_or_else mk_rb_map).insert decl_name linter_warning) in let l := results.to_list.reverse.map (λ ⟨fn, results⟩, ("-- " ++ fn.popn drop_fn_chars ++ "\n" ++ formatter results : format)) in format.intercalate "\n\n" l ++ "\n" /-- Formats the linter results as Lean code with comments and `#print` commands. -/ meta def format_linter_results (env : environment) (results : list (name × linter × rb_map name string)) (decls non_auto_decls : list declaration) (group_by_filename : option nat) (where_desc : string) (slow verbose : bool) : format := do let formatted_results := results.map $ λ ⟨linter_name, linter, results⟩, let report_str : format := to_fmt "/- The `" ++ to_fmt linter_name ++ "` linter reports: -/\n" in if ¬ results.empty then do let warnings := match group_by_filename with | none := print_warnings env results | some dropped := grouped_by_filename env results dropped (print_warnings env) end in report_str ++ "/- " ++ linter.errors_found ++ ": -/\n" ++ warnings ++ "\n" else if verbose then "/- OK: " ++ linter.no_errors_found ++ ". -/" else format.nil, let s := format.intercalate "\n" (formatted_results.filter (λ f, ¬ f.is_nil)), let s := if ¬ verbose then s else format!"/- Checking {non_auto_decls.length} declarations (plus {decls.length - non_auto_decls.length} automatically generated ones) {where_desc} -/\n\n" ++ s, let s := if slow then s else s ++ "/- (slow tests skipped) -/\n", s /-- The common denominator of `#lint[|mathlib|all]`. The different commands have different configurations for `l`, `group_by_filename` and `where_desc`. If `slow` is false, doesn't do the checks that take a lot of time. If `verbose` is false, it will suppress messages from passing checks. By setting `checks` you can customize which checks are performed. Returns a `name_set` containing the names of all declarations that fail any check in `check`, and a `format` object describing the failures. -/ meta def lint_aux (decls : list declaration) (group_by_filename : option nat) (where_desc : string) (slow verbose : bool) (checks : list (name × linter)) : tactic (name_set × format) := do e ← get_env, let non_auto_decls := decls.filter (λ d, ¬ d.is_auto_or_internal e), results ← lint_core decls non_auto_decls checks, let s := format_linter_results e results decls non_auto_decls group_by_filename where_desc slow verbose, let ns := name_set.of_list (do (_,_,rs) ← results, rs.keys), pure (ns, s) /-- Return the message printed by `#lint` and a `name_set` containing all declarations that fail. -/ meta def lint (slow : bool := tt) (verbose : bool := tt) (extra : list name := []) (use_only : bool := ff) : tactic (name_set × format) := do checks ← get_checks slow extra use_only, e ← get_env, let l := e.filter (λ d, e.in_current_file' d.to_name), lint_aux l none "in the current file" slow verbose checks /-- Returns the declarations considered by the mathlib linter. -/ meta def lint_mathlib_decls : tactic (list declaration) := do e ← get_env, ml ← get_mathlib_dir, pure $ e.filter $ λ d, e.is_prefix_of_file ml d.to_name /-- Return the message printed by `#lint_mathlib` and a `name_set` containing all declarations that fail. -/ meta def lint_mathlib (slow : bool := tt) (verbose : bool := tt) (extra : list name := []) (use_only : bool := ff) : tactic (name_set × format) := do checks ← get_checks slow extra use_only, decls ← lint_mathlib_decls, mathlib_path_len ← string.length <$> get_mathlib_dir, lint_aux decls mathlib_path_len "in mathlib (only in imported files)" slow verbose checks /-- Return the message printed by `#lint_all` and a `name_set` containing all declarations that fail. -/ meta def lint_all (slow : bool := tt) (verbose : bool := tt) (extra : list name := []) (use_only : bool := ff) : tactic (name_set × format) := do checks ← get_checks slow extra use_only, e ← get_env, let l := e.get_decls, lint_aux l (some 0) "in all imported files (including this one)" slow verbose checks /-- Parses an optional `only`, followed by a sequence of zero or more identifiers. Prepends `linter.` to each of these identifiers. -/ private meta def parse_lint_additions : parser (bool × list name) := prod.mk <$> only_flag <*> (list.map (name.append `linter) <$> ident_*) /-- The common denominator of `lint_cmd`, `lint_mathlib_cmd`, `lint_all_cmd` -/ private meta def lint_cmd_aux (scope : bool → bool → list name → bool → tactic (name_set × format)) : parser unit := do silent ← optional (tk "-"), fast_only ← optional (tk "*"), silent ← if silent.is_some then return silent else optional (tk "-"), -- allow either order of *- (use_only, extra) ← parse_lint_additions, (failed, s) ← scope fast_only.is_none silent.is_none extra use_only, when (¬ s.is_nil) $ trace s, when (silent.is_some ∧ ¬ failed.empty) $ fail "Linting did not succeed" /-- The command `#lint` at the bottom of a file will warn you about some common mistakes in that file. Usage: `#lint`, `#lint linter_1 linter_2`, `#lint only linter_1 linter_2`. `#lint-` will suppress the output of passing checks. Use the command `#list_linters` to see all available linters. -/ @[user_command] meta def lint_cmd (_ : parse $ tk "#lint") : parser unit := lint_cmd_aux @lint /-- The command `#lint_mathlib` checks all of mathlib for certain mistakes. Usage: `#lint_mathlib`, `#lint_mathlib linter_1 linter_2`, `#lint_mathlib only linter_1 linter_2`. `#lint_mathlib-` will suppress the output of passing checks. Use the command `#list_linters` to see all available linters. -/ @[user_command] meta def lint_mathlib_cmd (_ : parse $ tk "#lint_mathlib") : parser unit := lint_cmd_aux @lint_mathlib /-- The default linters used in mathlib CI. -/ meta def mathlib_linters : list name := by do ls ← get_checks tt [] ff, let ls := ls.map (λ ⟨n, _⟩, `linter ++ n), exact (reflect ls) /-- The command `#lint_all` checks all imported files for certain mistakes. Usage: `#lint_all`, `#lint_all linter_1 linter_2`, `#lint_all only linter_1 linter_2`. `#lint_all-` will suppress the output of passing checks. Use the command `#list_linters` to see all available linters. -/ @[user_command] meta def lint_all_cmd (_ : parse $ tk "#lint_all") : parser unit := lint_cmd_aux @lint_all /-- The command `#list_linters` prints a list of all available linters. -/ @[user_command] meta def list_linters (_ : parse $ tk "#list_linters") : parser unit := do env ← get_env, let ns := env.decl_filter_map $ λ dcl, if (dcl.to_name.get_prefix = `linter) && (dcl.type = `(linter)) then some dcl.to_name else none, trace "Available linters:\n linters marked with (*) are in the default lint set\n", ns.mmap' $ λ n, do b ← has_attribute' `linter n, trace $ n.pop_prefix.to_string ++ if b then " (*)" else "" add_tactic_doc { name := "linting commands", category := doc_category.cmd, decl_names := [`lint_cmd, `lint_mathlib_cmd, `lint_all_cmd, `list_linters], tags := ["linting"], description := "User commands to spot common mistakes in the code * `#lint`: check all declarations in the current file * `#lint_mathlib`: check all declarations in mathlib (so excluding core or other projects, and also excluding the current file) * `#lint_all`: check all declarations in the environment (the current file and all imported files) The following linters are run by default: 1. `unused_arguments` checks for unused arguments in declarations. 2. `def_lemma` checks whether a declaration is incorrectly marked as a def/lemma. 3. `dup_namespce` checks whether a namespace is duplicated in the name of a declaration. 4. `ge_or_gt` checks whether ≥/> is used in the declaration. 5. `instance_priority` checks that instances that always apply have priority below default. 6. `doc_blame` checks for missing doc strings on definitions and constants. 7. `has_inhabited_instance` checks whether every type has an associated `inhabited` instance. 8. `impossible_instance` checks for instances that can never fire. 9. `incorrect_type_class_argument` checks for arguments in [square brackets] that are not classes. 10. `dangerous_instance` checks for instances that generate type-class problems with metavariables. 11. `fails_quickly` tests that type-class inference ends (relatively) quickly when applied to variables. 12. `has_coe_variable` tests that there are no instances of type `has_coe α t` for a variable `α`. 13. `inhabited_nonempty` checks for `inhabited` instance arguments that should be changed to `nonempty`. 14. `simp_nf` checks that the left-hand side of simp lemmas is in simp-normal form. 15. `simp_var_head` checks that there are no variables as head symbol of left-hand sides of simp lemmas. 16. `simp_comm` checks that no commutativity lemmas (such as `add_comm`) are marked simp. Another linter, `doc_blame_thm`, checks for missing doc strings on lemmas and theorems. This is not run by default. The command `#list_linters` prints a list of the names of all available linters. You can append a `*` to any command (e.g. `#lint_mathlib*`) to omit the slow tests (4). You can append a `-` to any command (e.g. `#lint_mathlib-`) to run a silent lint that suppresses the output of passing checks. A silent lint will fail if any test fails. You can append a sequence of linter names to any command to run extra tests, in addition to the default ones. e.g. `#lint doc_blame_thm` will run all default tests and `doc_blame_thm`. You can append `only name1 name2 ...` to any command to run a subset of linters, e.g. `#lint only unused_arguments` You can add custom linters by defining a term of type `linter` in the `linter` namespace. A linter defined with the name `linter.my_new_check` can be run with `#lint my_new_check` or `lint only my_new_check`. If you add the attribute `@[linter]` to `linter.my_new_check` it will run by default. Adding the attribute `@[nolint doc_blame unused_arguments]` to a declaration omits it from only the specified linter checks." } attribute [nolint unused_arguments] imp_intro attribute [nolint def_lemma] classical.dec classical.dec_pred classical.dec_rel classical.dec_eq attribute [nolint has_inhabited_instance] pempty /-- Invoking the hole command `lint` ("Find common mistakes in current file") will print text that indicates mistakes made in the file above the command. It is equivalent to copying and pasting the output of `#lint`. On large files, it may take some time before the output appears. -/ @[hole_command] meta def lint_hole_cmd : hole_command := { name := "Lint", descr := "Lint: Find common mistakes in current file.", action := λ es, do (_, s) ← lint, return [(s.to_string,"")] } add_tactic_doc { name := "Lint", category := doc_category.hole_cmd, decl_names := [`lint_hole_cmd], tags := ["linting"] }
f335ad0a97b1baeba292554376812db1743e0509
fef48cac17c73db8662678da38fd75888db97560
/src/mathlib_someday.lean
7d5bafb41f9309b0c0ec20e99c231537baef7aab
[]
no_license
kbuzzard/lean-squares-in-fibonacci
6c0d924f799d6751e19798bb2530ee602ec7087e
8cea20e5ce88ab7d17b020932d84d316532a84a8
refs/heads/master
1,584,524,504,815
1,582,387,156,000
1,582,387,156,000
134,576,655
3
1
null
1,541,538,497,000
1,527,083,406,000
Lean
UTF-8
Lean
false
false
2,034
lean
import algebra.group_power import data.nat.gcd import data.nat.modeq import number_theory.pell attribute [elab_as_eliminator] nat.strong_induction_on attribute [refl] dvd_refl attribute [trans] dvd_trans attribute [symm] nat.coprime.symm open nat lemma nat.gcd_add_mul_left (a b n : ℕ) : gcd (a + b * n) b = gcd a b := by rw [nat.gcd_comm, gcd_rec, add_mul_mod_self_left, ← gcd_rec, nat.gcd_comm] lemma nat.gcd_add_mul_right (a b n : ℕ) : gcd (a + n * b) b = gcd a b := by rw [nat.gcd_comm, gcd_rec, add_mul_mod_self_right, ← gcd_rec, nat.gcd_comm] lemma nat.gcd_add (a b : ℕ) : gcd (a + b) b = gcd a b := by rw [← nat.gcd_add_mul_left a b 1, mul_one] @[elab_as_eliminator] lemma nat.mod_rec (m n : ℕ) {X : Sort*} {C : ℕ → X} (H : ∀ n, C n = C (n+m)) : C n = C (n%m) := have H1 : ∀ q r, C (r + m * q) = C r, from λ q, nat.rec_on q (λ r, by rw [mul_zero]; refl) $ λ n ih r, by rw [mul_succ, ← add_assoc, ← H, ih], by conv in (C n) { rw [← mod_add_div n m, H1] } def nat.mod_add (a b m : ℕ) : (a % m + b % m) % m = (a + b) % m := nat.modeq.modeq_add (nat.mod_mod _ _) (nat.mod_mod _ _) -- modeq -- needs data.nat.modeq -- #check 2 ≡ 5 [MOD 5] -- notation instance nonsquare_five : zsqrtd.nonsquare 5 := ⟨λ n, nat.cases_on n dec_trivial $ λ n, nat.cases_on n dec_trivial $ λ n, nat.cases_on n dec_trivial $ λ n, ne_of_lt $ calc 5 < 3 * 3 : dec_trivial ... ≤ 3 * (n+3) : nat.mul_le_mul_left _ (nat.le_add_left _ _) ... ≤ (n+3) * (n+3) : nat.mul_le_mul_right _ (nat.le_add_left _ _)⟩ @[simp] lemma is_ring_hom.map_int {α : Type*} {β : Type*} [ring α] [ring β] (f : α → β) [is_ring_hom f] (i : ℤ) : f i = i := int.induction_on i (is_ring_hom.map_zero f) (λ j H, by simp [is_ring_hom.map_add f, is_ring_hom.map_one f, H]; exact H) (λ j H, by simp_rw [int.cast_sub, is_ring_hom.map_sub f, H, int.cast_one, is_ring_hom.map_one f]) @[simp] lemma units.neg_coe {α : Type*} [ring α] (x : units α) : ((-x : units α) : α) = -↑x := rfl
ce3c303045e23e539ef547f15ec4468c65e3e6a8
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/polynomial/big_operators.lean
27bbec5a49037ed63c16ad4a5b426c5fe416595c
[ "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
13,364
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 algebra.order.with_zero import data.polynomial.monic /-! # Lemmas for the interaction between polynomials and `∑` and `∏`. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. Recall that `∑` and `∏` are notation for `finset.sum` and `finset.prod` respectively. ## Main results - `polynomial.nat_degree_prod_of_monic` : the degree of a product of monic polynomials is the product of degrees. We prove this only for `[comm_semiring R]`, but it ought to be true for `[semiring R]` and `list.prod`. - `polynomial.nat_degree_prod` : for polynomials over an integral domain, the degree of the product is the sum of degrees. - `polynomial.leading_coeff_prod` : for polynomials over an integral domain, the leading coefficient is the product of leading coefficients. - `polynomial.prod_X_sub_C_coeff_card_pred` carries most of the content for computing the second coefficient of the characteristic polynomial. -/ open finset open multiset open_locale big_operators polynomial universes u w variables {R : Type u} {ι : Type w} namespace polynomial variables (s : finset ι) section semiring variables {S : Type*} [semiring S] lemma nat_degree_list_sum_le (l : list S[X]) : nat_degree l.sum ≤ (l.map nat_degree).foldr max 0 := list.sum_le_foldr_max nat_degree (by simp) nat_degree_add_le _ lemma nat_degree_multiset_sum_le (l : multiset S[X]) : nat_degree l.sum ≤ (l.map nat_degree).foldr max max_left_comm 0 := quotient.induction_on l (by simpa using nat_degree_list_sum_le) lemma nat_degree_sum_le (f : ι → S[X]) : nat_degree (∑ i in s, f i) ≤ s.fold max 0 (nat_degree ∘ f) := by simpa using nat_degree_multiset_sum_le (s.val.map f) lemma degree_list_sum_le (l : list S[X]) : degree l.sum ≤ (l.map nat_degree).maximum := begin by_cases h : l.sum = 0, { simp [h] }, { rw degree_eq_nat_degree h, suffices : (l.map nat_degree).maximum = ((l.map nat_degree).foldr max 0 : ℕ), { rw this, simpa [this] using nat_degree_list_sum_le l }, rw ← list.foldr_max_of_ne_nil, { congr }, contrapose! h, rw [list.map_eq_nil] at h, simp [h] } end lemma nat_degree_list_prod_le (l : list S[X]) : nat_degree l.prod ≤ (l.map nat_degree).sum := begin induction l with hd tl IH, { simp }, { simpa using nat_degree_mul_le.trans (add_le_add_left IH _) } end lemma degree_list_prod_le (l : list S[X]) : degree l.prod ≤ (l.map degree).sum := begin induction l with hd tl IH, { simp }, { simpa using (degree_mul_le _ _).trans (add_le_add_left IH _) } end lemma coeff_list_prod_of_nat_degree_le (l : list S[X]) (n : ℕ) (hl : ∀ p ∈ l, nat_degree p ≤ n) : coeff (list.prod l) (l.length * n) = (l.map (λ p, coeff p n)).prod := begin induction l with hd tl IH, { simp }, { have hl' : ∀ (p ∈ tl), nat_degree p ≤ n := λ p hp, hl p (list.mem_cons_of_mem _ hp), simp only [list.prod_cons, list.map, list.length], rw [add_mul, one_mul, add_comm, ←IH hl', mul_comm tl.length], have h : nat_degree tl.prod ≤ n * tl.length, { refine (nat_degree_list_prod_le _).trans _, rw [←tl.length_map nat_degree, mul_comm], refine list.sum_le_card_nsmul _ _ _, simpa using hl' }, have hdn : nat_degree hd ≤ n := hl _ (list.mem_cons_self _ _), rcases hdn.eq_or_lt with rfl|hdn', { cases h.eq_or_lt with h' h', { rw [←h', coeff_mul_degree_add_degree, leading_coeff, leading_coeff] }, { rw [coeff_eq_zero_of_nat_degree_lt, coeff_eq_zero_of_nat_degree_lt h', mul_zero], exact nat_degree_mul_le.trans_lt (add_lt_add_left h' _) } }, { rw [coeff_eq_zero_of_nat_degree_lt hdn', coeff_eq_zero_of_nat_degree_lt, zero_mul], exact nat_degree_mul_le.trans_lt (add_lt_add_of_lt_of_le hdn' h) } } end end semiring section comm_semiring variables [comm_semiring R] (f : ι → R[X]) (t : multiset R[X]) lemma nat_degree_multiset_prod_le : t.prod.nat_degree ≤ (t.map nat_degree).sum := quotient.induction_on t (by simpa using nat_degree_list_prod_le) lemma nat_degree_prod_le : (∏ i in s, f i).nat_degree ≤ ∑ i in s, (f i).nat_degree := by simpa using nat_degree_multiset_prod_le (s.1.map f) /-- The degree of a product of polynomials is at most the sum of the degrees, where the degree of the zero polynomial is ⊥. -/ lemma degree_multiset_prod_le : t.prod.degree ≤ (t.map polynomial.degree).sum := quotient.induction_on t (by simpa using degree_list_prod_le) lemma degree_prod_le : (∏ i in s, f i).degree ≤ ∑ i in s, (f i).degree := by simpa only [multiset.map_map] using degree_multiset_prod_le (s.1.map f) /-- The leading coefficient of a product of polynomials is equal to the product of the leading coefficients, provided that this product is nonzero. See `polynomial.leading_coeff_multiset_prod` (without the `'`) for a version for integral domains, where this condition is automatically satisfied. -/ lemma leading_coeff_multiset_prod' (h : (t.map leading_coeff).prod ≠ 0) : t.prod.leading_coeff = (t.map leading_coeff).prod := begin induction t using multiset.induction_on with a t ih, { simp }, simp only [multiset.map_cons, multiset.prod_cons] at h ⊢, rw polynomial.leading_coeff_mul'; { rwa ih, apply right_ne_zero_of_mul h } end /-- The leading coefficient of a product of polynomials is equal to the product of the leading coefficients, provided that this product is nonzero. See `polynomial.leading_coeff_prod` (without the `'`) for a version for integral domains, where this condition is automatically satisfied. -/ lemma leading_coeff_prod' (h : ∏ i in s, (f i).leading_coeff ≠ 0) : (∏ i in s, f i).leading_coeff = ∏ i in s, (f i).leading_coeff := by simpa using leading_coeff_multiset_prod' (s.1.map f) (by simpa using h) /-- The degree of a product of polynomials is equal to the sum of the degrees, provided that the product of leading coefficients is nonzero. See `polynomial.nat_degree_multiset_prod` (without the `'`) for a version for integral domains, where this condition is automatically satisfied. -/ lemma nat_degree_multiset_prod' (h : (t.map (λ f, leading_coeff f)).prod ≠ 0) : t.prod.nat_degree = (t.map (λ f, nat_degree f)).sum := begin revert h, refine multiset.induction_on t _ (λ a t ih ht, _), { simp }, rw [multiset.map_cons, multiset.prod_cons] at ht ⊢, rw [multiset.sum_cons, polynomial.nat_degree_mul', ih], { apply right_ne_zero_of_mul ht }, { rwa polynomial.leading_coeff_multiset_prod', apply right_ne_zero_of_mul ht }, end /-- The degree of a product of polynomials is equal to the sum of the degrees, provided that the product of leading coefficients is nonzero. See `polynomial.nat_degree_prod` (without the `'`) for a version for integral domains, where this condition is automatically satisfied. -/ lemma nat_degree_prod' (h : ∏ i in s, (f i).leading_coeff ≠ 0) : (∏ i in s, f i).nat_degree = ∑ i in s, (f i).nat_degree := by simpa using nat_degree_multiset_prod' (s.1.map f) (by simpa using h) lemma nat_degree_multiset_prod_of_monic (h : ∀ f ∈ t, monic f) : t.prod.nat_degree = (t.map nat_degree).sum := begin nontriviality R, apply nat_degree_multiset_prod', suffices : (t.map (λ f, leading_coeff f)).prod = 1, { rw this, simp }, convert prod_replicate t.card (1 : R), { simp only [eq_replicate, multiset.card_map, eq_self_iff_true, true_and], rintros i hi, obtain ⟨i, hi, rfl⟩ := multiset.mem_map.mp hi, apply h, assumption }, { simp } end lemma nat_degree_prod_of_monic (h : ∀ i ∈ s, (f i).monic) : (∏ i in s, f i).nat_degree = ∑ i in s, (f i).nat_degree := by simpa using nat_degree_multiset_prod_of_monic (s.1.map f) (by simpa using h) lemma coeff_multiset_prod_of_nat_degree_le (n : ℕ) (hl : ∀ p ∈ t, nat_degree p ≤ n) : coeff t.prod (t.card * n) = (t.map (λ p, coeff p n)).prod := begin induction t using quotient.induction_on, simpa using coeff_list_prod_of_nat_degree_le _ _ hl end lemma coeff_prod_of_nat_degree_le (f : ι → R[X]) (n : ℕ) (h : ∀ p ∈ s, nat_degree (f p) ≤ n) : coeff (∏ i in s, f i) (s.card * n) = ∏ i in s, coeff (f i) n := begin cases s with l hl, convert coeff_multiset_prod_of_nat_degree_le (l.map f) _ _, { simp }, { simp }, { simpa using h } end lemma coeff_zero_multiset_prod : t.prod.coeff 0 = (t.map (λ f, coeff f 0)).prod := begin refine multiset.induction_on t _ (λ a t ht, _), { simp }, rw [multiset.prod_cons, multiset.map_cons, multiset.prod_cons, polynomial.mul_coeff_zero, ht] end lemma coeff_zero_prod : (∏ i in s, f i).coeff 0 = ∏ i in s, (f i).coeff 0 := by simpa using coeff_zero_multiset_prod (s.1.map f) end comm_semiring section comm_ring variables [comm_ring R] open monic -- Eventually this can be generalized with Vieta's formulas -- plus the connection between roots and factorization. lemma multiset_prod_X_sub_C_next_coeff (t : multiset R) : next_coeff (t.map (λ x, X - C x)).prod = -t.sum := begin rw next_coeff_multiset_prod, { simp only [next_coeff_X_sub_C], exact t.sum_hom (-add_monoid_hom.id R) }, { intros, apply monic_X_sub_C } end lemma prod_X_sub_C_next_coeff {s : finset ι} (f : ι → R) : next_coeff ∏ i in s, (X - C (f i)) = -∑ i in s, f i := by simpa using multiset_prod_X_sub_C_next_coeff (s.1.map f) lemma multiset_prod_X_sub_C_coeff_card_pred (t : multiset R) (ht : 0 < t.card) : (t.map (λ x, (X - C x))).prod.coeff (t.card - 1) = -t.sum := begin nontriviality R, convert multiset_prod_X_sub_C_next_coeff (by assumption), rw next_coeff, split_ifs, { rw nat_degree_multiset_prod_of_monic at h; simp only [multiset.mem_map] at *, swap, { rintros _ ⟨_, _, rfl⟩, apply monic_X_sub_C }, simp_rw [multiset.sum_eq_zero_iff, multiset.mem_map] at h, contrapose! h, obtain ⟨x, hx⟩ := card_pos_iff_exists_mem.mp ht, exact ⟨_, ⟨_, ⟨x, hx, rfl⟩, nat_degree_X_sub_C _⟩, one_ne_zero⟩ }, congr, rw nat_degree_multiset_prod_of_monic; { simp [nat_degree_X_sub_C, monic_X_sub_C] }, end lemma prod_X_sub_C_coeff_card_pred (s : finset ι) (f : ι → R) (hs : 0 < s.card) : (∏ i in s, (X - C (f i))).coeff (s.card - 1) = - ∑ i in s, f i := by simpa using multiset_prod_X_sub_C_coeff_card_pred (s.1.map f) (by simpa using hs) end comm_ring section no_zero_divisors section semiring variables [semiring R] [no_zero_divisors R] /-- The degree of a product of polynomials is equal to the sum of the degrees, where the degree of the zero polynomial is ⊥. `[nontrivial R]` is needed, otherwise for `l = []` we have `⊥` in the LHS and `0` in the RHS. -/ lemma degree_list_prod [nontrivial R] (l : list R[X]) : l.prod.degree = (l.map degree).sum := map_list_prod (@degree_monoid_hom R _ _ _) l end semiring section comm_semiring variables [comm_semiring R] [no_zero_divisors R] (f : ι → R[X]) (t : multiset R[X]) /-- The degree of a product of polynomials is equal to the sum of the degrees. See `polynomial.nat_degree_prod'` (with a `'`) for a version for commutative semirings, where additionally, the product of the leading coefficients must be nonzero. -/ lemma nat_degree_prod (h : ∀ i ∈ s, f i ≠ 0) : (∏ i in s, f i).nat_degree = ∑ i in s, (f i).nat_degree := begin nontriviality R, apply nat_degree_prod', rw prod_ne_zero_iff, intros x hx, simp [h x hx] end lemma nat_degree_multiset_prod (h : (0 : R[X]) ∉ t) : nat_degree t.prod = (t.map nat_degree).sum := begin nontriviality R, rw nat_degree_multiset_prod', simp_rw [ne.def, multiset.prod_eq_zero_iff, multiset.mem_map, leading_coeff_eq_zero], rintro ⟨_, h, rfl⟩, contradiction end /-- The degree of a product of polynomials is equal to the sum of the degrees, where the degree of the zero polynomial is ⊥. -/ lemma degree_multiset_prod [nontrivial R] : t.prod.degree = (t.map (λ f, degree f)).sum := map_multiset_prod (@degree_monoid_hom R _ _ _) _ /-- The degree of a product of polynomials is equal to the sum of the degrees, where the degree of the zero polynomial is ⊥. -/ lemma degree_prod [nontrivial R] : (∏ i in s, f i).degree = ∑ i in s, (f i).degree := map_prod (@degree_monoid_hom R _ _ _) _ _ /-- The leading coefficient of a product of polynomials is equal to the product of the leading coefficients. See `polynomial.leading_coeff_multiset_prod'` (with a `'`) for a version for commutative semirings, where additionally, the product of the leading coefficients must be nonzero. -/ lemma leading_coeff_multiset_prod : t.prod.leading_coeff = (t.map (λ f, leading_coeff f)).prod := by { rw [← leading_coeff_hom_apply, monoid_hom.map_multiset_prod], refl } /-- The leading coefficient of a product of polynomials is equal to the product of the leading coefficients. See `polynomial.leading_coeff_prod'` (with a `'`) for a version for commutative semirings, where additionally, the product of the leading coefficients must be nonzero. -/ lemma leading_coeff_prod : (∏ i in s, f i).leading_coeff = ∏ i in s, (f i).leading_coeff := by simpa using leading_coeff_multiset_prod (s.1.map f) end comm_semiring end no_zero_divisors end polynomial
d8618f7131e769f2029f7f9d4f6741689620184c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/geometry/euclidean/angle/oriented/rotation.lean
8ca7a0bcff9401ef219bb29649cabd8a5956c043
[ "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
20,847
lean
/- Copyright (c) 2022 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Heather Macbeth -/ import analysis.special_functions.complex.circle import geometry.euclidean.angle.oriented.basic /-! # Rotations by oriented angles. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines rotations by oriented angles in real inner product spaces. ## Main definitions * `orientation.rotation` is the rotation by an oriented angle with respect to an orientation. -/ noncomputable theory open finite_dimensional complex open_locale real real_inner_product_space complex_conjugate namespace orientation local attribute [instance] fact_finite_dimensional_of_finrank_eq_succ local attribute [instance] complex.finrank_real_complex_fact variables {V V' : Type*} variables [normed_add_comm_group V] [normed_add_comm_group V'] variables [inner_product_space ℝ V] [inner_product_space ℝ V'] variables [fact (finrank ℝ V = 2)] [fact (finrank ℝ V' = 2)] (o : orientation ℝ V (fin 2)) local notation `J` := o.right_angle_rotation /-- Auxiliary construction to build a rotation by the oriented angle `θ`. -/ def rotation_aux (θ : real.angle) : V →ₗᵢ[ℝ] V := linear_map.isometry_of_inner (real.angle.cos θ • linear_map.id + real.angle.sin θ • ↑(linear_isometry_equiv.to_linear_equiv J)) begin intros x y, simp only [is_R_or_C.conj_to_real, id.def, linear_map.smul_apply, linear_map.add_apply, linear_map.id_coe, linear_equiv.coe_coe, linear_isometry_equiv.coe_to_linear_equiv, orientation.area_form_right_angle_rotation_left, orientation.inner_right_angle_rotation_left, orientation.inner_right_angle_rotation_right, inner_add_left, inner_smul_left, inner_add_right, inner_smul_right], linear_combination inner x y * θ.cos_sq_add_sin_sq, end @[simp] lemma rotation_aux_apply (θ : real.angle) (x : V) : o.rotation_aux θ x = real.angle.cos θ • x + real.angle.sin θ • J x := rfl /-- A rotation by the oriented angle `θ`. -/ def rotation (θ : real.angle) : V ≃ₗᵢ[ℝ] V := linear_isometry_equiv.of_linear_isometry (o.rotation_aux θ) (real.angle.cos θ • linear_map.id - real.angle.sin θ • ↑(linear_isometry_equiv.to_linear_equiv J)) begin ext x, convert congr_arg (λ t : ℝ, t • x) θ.cos_sq_add_sin_sq using 1, { simp only [o.right_angle_rotation_right_angle_rotation, o.rotation_aux_apply, function.comp_app, id.def, linear_equiv.coe_coe, linear_isometry.coe_to_linear_map, linear_isometry_equiv.coe_to_linear_equiv, map_smul, map_sub, linear_map.coe_comp, linear_map.id_coe, linear_map.smul_apply, linear_map.sub_apply, ← mul_smul, add_smul, smul_add, smul_neg, smul_sub, mul_comm, sq], abel }, { simp }, end begin ext x, convert congr_arg (λ t : ℝ, t • x) θ.cos_sq_add_sin_sq using 1, { simp only [o.right_angle_rotation_right_angle_rotation, o.rotation_aux_apply, function.comp_app, id.def, linear_equiv.coe_coe, linear_isometry.coe_to_linear_map, linear_isometry_equiv.coe_to_linear_equiv, map_add, map_smul, linear_map.coe_comp, linear_map.id_coe, linear_map.smul_apply, linear_map.sub_apply, add_smul, ← mul_smul, mul_comm, smul_add, smul_neg, sq], abel }, { simp }, end lemma rotation_apply (θ : real.angle) (x : V) : o.rotation θ x = real.angle.cos θ • x + real.angle.sin θ • J x := rfl lemma rotation_symm_apply (θ : real.angle) (x : V) : (o.rotation θ).symm x = real.angle.cos θ • x - real.angle.sin θ • J x := rfl attribute [irreducible] rotation lemma rotation_eq_matrix_to_lin (θ : real.angle) {x : V} (hx : x ≠ 0) : (o.rotation θ).to_linear_map = matrix.to_lin (o.basis_right_angle_rotation x hx) (o.basis_right_angle_rotation x hx) !![θ.cos, -θ.sin; θ.sin, θ.cos] := begin apply (o.basis_right_angle_rotation x hx).ext, intros i, fin_cases i, { rw matrix.to_lin_self, simp [rotation_apply, fin.sum_univ_succ] }, { rw matrix.to_lin_self, simp [rotation_apply, fin.sum_univ_succ, add_comm] }, end /-- The determinant of `rotation` (as a linear map) is equal to `1`. -/ @[simp] lemma det_rotation (θ : real.angle) : (o.rotation θ).to_linear_map.det = 1 := begin haveI : nontrivial V := finite_dimensional.nontrivial_of_finrank_eq_succ (fact.out (finrank ℝ V = 2)), obtain ⟨x, hx⟩ : ∃ x, x ≠ (0:V) := exists_ne (0:V), rw o.rotation_eq_matrix_to_lin θ hx, simpa [sq] using θ.cos_sq_add_sin_sq, end /-- The determinant of `rotation` (as a linear equiv) is equal to `1`. -/ @[simp] lemma linear_equiv_det_rotation (θ : real.angle) : (o.rotation θ).to_linear_equiv.det = 1 := units.ext $ o.det_rotation θ /-- The inverse of `rotation` is rotation by the negation of the angle. -/ @[simp] lemma rotation_symm (θ : real.angle) : (o.rotation θ).symm = o.rotation (-θ) := by ext; simp [o.rotation_apply, o.rotation_symm_apply, sub_eq_add_neg] /-- Rotation by 0 is the identity. -/ @[simp] lemma rotation_zero : o.rotation 0 = linear_isometry_equiv.refl ℝ V := by ext; simp [rotation] /-- Rotation by π is negation. -/ @[simp] lemma rotation_pi : o.rotation π = linear_isometry_equiv.neg ℝ := begin ext x, simp [rotation] end /-- Rotation by π is negation. -/ lemma rotation_pi_apply (x : V) : o.rotation π x = -x := by simp /-- Rotation by π / 2 is the "right-angle-rotation" map `J`. -/ lemma rotation_pi_div_two : o.rotation (π / 2 : ℝ) = J := begin ext x, simp [rotation], end /-- Rotating twice is equivalent to rotating by the sum of the angles. -/ @[simp] lemma rotation_rotation (θ₁ θ₂ : real.angle) (x : V) : o.rotation θ₁ (o.rotation θ₂ x) = o.rotation (θ₁ + θ₂) x := begin simp only [o.rotation_apply, ←mul_smul, real.angle.cos_add, real.angle.sin_add, add_smul, sub_smul, linear_isometry_equiv.trans_apply, smul_add, linear_isometry_equiv.map_add, linear_isometry_equiv.map_smul, right_angle_rotation_right_angle_rotation, smul_neg], ring_nf, abel, end /-- Rotating twice is equivalent to rotating by the sum of the angles. -/ @[simp] lemma rotation_trans (θ₁ θ₂ : real.angle) : (o.rotation θ₁).trans (o.rotation θ₂) = o.rotation (θ₂ + θ₁) := linear_isometry_equiv.ext $ λ _, by rw [←rotation_rotation, linear_isometry_equiv.trans_apply] /-- Rotating the first of two vectors by `θ` scales their Kahler form by `cos θ - sin θ * I`. -/ @[simp] lemma kahler_rotation_left (x y : V) (θ : real.angle) : o.kahler (o.rotation θ x) y = conj (θ.exp_map_circle : ℂ) * o.kahler x y := begin simp only [o.rotation_apply, map_add, map_mul, linear_map.map_smulₛₗ, ring_hom.id_apply, linear_map.add_apply, linear_map.smul_apply, real_smul, kahler_right_angle_rotation_left, real.angle.coe_exp_map_circle, is_R_or_C.conj_of_real, conj_I], ring, end /-- Negating a rotation is equivalent to rotation by π plus the angle. -/ lemma neg_rotation (θ : real.angle) (x : V) : -o.rotation θ x = o.rotation (π + θ) x := by rw [←o.rotation_pi_apply, rotation_rotation] /-- Negating a rotation by -π / 2 is equivalent to rotation by π / 2. -/ @[simp] lemma neg_rotation_neg_pi_div_two (x : V) : -o.rotation (-π / 2 : ℝ) x = o.rotation (π / 2 : ℝ) x := by rw [neg_rotation, ←real.angle.coe_add, neg_div, ←sub_eq_add_neg, sub_half] /-- Negating a rotation by π / 2 is equivalent to rotation by -π / 2. -/ lemma neg_rotation_pi_div_two (x : V) : -o.rotation (π / 2 : ℝ) x = o.rotation (-π / 2 : ℝ) x := (neg_eq_iff_eq_neg.mp $ o.neg_rotation_neg_pi_div_two _).symm /-- Rotating the first of two vectors by `θ` scales their Kahler form by `cos (-θ) + sin (-θ) * I`. -/ lemma kahler_rotation_left' (x y : V) (θ : real.angle) : o.kahler (o.rotation θ x) y = (-θ).exp_map_circle * o.kahler x y := by simpa [coe_inv_circle_eq_conj, -kahler_rotation_left] using o.kahler_rotation_left x y θ /-- Rotating the second of two vectors by `θ` scales their Kahler form by `cos θ + sin θ * I`. -/ @[simp] lemma kahler_rotation_right (x y : V) (θ : real.angle) : o.kahler x (o.rotation θ y) = θ.exp_map_circle * o.kahler x y := begin simp only [o.rotation_apply, map_add, linear_map.map_smulₛₗ, ring_hom.id_apply, real_smul, kahler_right_angle_rotation_right, real.angle.coe_exp_map_circle], ring, end /-- Rotating the first vector by `θ` subtracts `θ` from the angle between two vectors. -/ @[simp] lemma oangle_rotation_left {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : o.oangle (o.rotation θ x) y = o.oangle x y - θ := begin simp only [oangle, o.kahler_rotation_left'], rw [complex.arg_mul_coe_angle, real.angle.arg_exp_map_circle], { abel }, { exact ne_zero_of_mem_circle _ }, { exact o.kahler_ne_zero hx hy }, end /-- Rotating the second vector by `θ` adds `θ` to the angle between two vectors. -/ @[simp] lemma oangle_rotation_right {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : o.oangle x (o.rotation θ y) = o.oangle x y + θ := begin simp only [oangle, o.kahler_rotation_right], rw [complex.arg_mul_coe_angle, real.angle.arg_exp_map_circle], { abel }, { exact ne_zero_of_mem_circle _ }, { exact o.kahler_ne_zero hx hy }, end /-- The rotation of a vector by `θ` has an angle of `-θ` from that vector. -/ @[simp] lemma oangle_rotation_self_left {x : V} (hx : x ≠ 0) (θ : real.angle) : o.oangle (o.rotation θ x) x = -θ := by simp [hx] /-- A vector has an angle of `θ` from the rotation of that vector by `θ`. -/ @[simp] lemma oangle_rotation_self_right {x : V} (hx : x ≠ 0) (θ : real.angle) : o.oangle x (o.rotation θ x) = θ := by simp [hx] /-- Rotating the first vector by the angle between the two vectors results an an angle of 0. -/ @[simp] lemma oangle_rotation_oangle_left (x y : V) : o.oangle (o.rotation (o.oangle x y) x) y = 0 := begin by_cases hx : x = 0, { simp [hx] }, { by_cases hy : y = 0, { simp [hy] }, { simp [hx, hy] } } end /-- Rotating the first vector by the angle between the two vectors and swapping the vectors results an an angle of 0. -/ @[simp] lemma oangle_rotation_oangle_right (x y : V) : o.oangle y (o.rotation (o.oangle x y) x) = 0 := begin rw [oangle_rev], simp end /-- Rotating both vectors by the same angle does not change the angle between those vectors. -/ @[simp] lemma oangle_rotation (x y : V) (θ : real.angle) : o.oangle (o.rotation θ x) (o.rotation θ y) = o.oangle x y := begin by_cases hx : x = 0; by_cases hy : y = 0; simp [hx, hy] end /-- A rotation of a nonzero vector equals that vector if and only if the angle is zero. -/ @[simp] lemma rotation_eq_self_iff_angle_eq_zero {x : V} (hx : x ≠ 0) (θ : real.angle) : o.rotation θ x = x ↔ θ = 0 := begin split, { intro h, rw eq_comm, simpa [hx, h] using o.oangle_rotation_right hx hx θ }, { intro h, simp [h] } end /-- A nonzero vector equals a rotation of that vector if and only if the angle is zero. -/ @[simp] lemma eq_rotation_self_iff_angle_eq_zero {x : V} (hx : x ≠ 0) (θ : real.angle) : x = o.rotation θ x ↔ θ = 0 := by rw [←o.rotation_eq_self_iff_angle_eq_zero hx, eq_comm] /-- A rotation of a vector equals that vector if and only if the vector or the angle is zero. -/ lemma rotation_eq_self_iff (x : V) (θ : real.angle) : o.rotation θ x = x ↔ x = 0 ∨ θ = 0 := begin by_cases h : x = 0; simp [h] end /-- A vector equals a rotation of that vector if and only if the vector or the angle is zero. -/ lemma eq_rotation_self_iff (x : V) (θ : real.angle) : x = o.rotation θ x ↔ x = 0 ∨ θ = 0 := by rw [←rotation_eq_self_iff, eq_comm] /-- Rotating a vector by the angle to another vector gives the second vector if and only if the norms are equal. -/ @[simp] lemma rotation_oangle_eq_iff_norm_eq (x y : V) : o.rotation (o.oangle x y) x = y ↔ ‖x‖ = ‖y‖ := begin split, { intro h, rw [←h, linear_isometry_equiv.norm_map] }, { intro h, rw o.eq_iff_oangle_eq_zero_of_norm_eq; simp [h] } end /-- The angle between two nonzero vectors is `θ` if and only if the second vector is the first rotated by `θ` and scaled by the ratio of the norms. -/ lemma oangle_eq_iff_eq_norm_div_norm_smul_rotation_of_ne_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : o.oangle x y = θ ↔ y = (‖y‖ / ‖x‖) • o.rotation θ x := begin have hp := div_pos (norm_pos_iff.2 hy) (norm_pos_iff.2 hx), split, { rintro rfl, rw [←linear_isometry_equiv.map_smul, ←o.oangle_smul_left_of_pos x y hp, eq_comm, rotation_oangle_eq_iff_norm_eq, norm_smul, real.norm_of_nonneg hp.le, div_mul_cancel _ (norm_ne_zero_iff.2 hx)] }, { intro hye, rw [hye, o.oangle_smul_right_of_pos _ _ hp, o.oangle_rotation_self_right hx] } end /-- The angle between two nonzero vectors is `θ` if and only if the second vector is the first rotated by `θ` and scaled by a positive real. -/ lemma oangle_eq_iff_eq_pos_smul_rotation_of_ne_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : o.oangle x y = θ ↔ ∃ r : ℝ, 0 < r ∧ y = r • o.rotation θ x := begin split, { intro h, rw o.oangle_eq_iff_eq_norm_div_norm_smul_rotation_of_ne_zero hx hy at h, exact ⟨‖y‖ / ‖x‖, div_pos (norm_pos_iff.2 hy) (norm_pos_iff.2 hx), h⟩ }, { rintro ⟨r, hr, rfl⟩, rw [o.oangle_smul_right_of_pos _ _ hr, o.oangle_rotation_self_right hx] } end /-- The angle between two vectors is `θ` if and only if they are nonzero and the second vector is the first rotated by `θ` and scaled by the ratio of the norms, or `θ` and at least one of the vectors are zero. -/ lemma oangle_eq_iff_eq_norm_div_norm_smul_rotation_or_eq_zero {x y : V} (θ : real.angle) : o.oangle x y = θ ↔ (x ≠ 0 ∧ y ≠ 0 ∧ y = (‖y‖ / ‖x‖) • o.rotation θ x) ∨ (θ = 0 ∧ (x = 0 ∨ y = 0)) := begin by_cases hx : x = 0, { simp [hx, eq_comm] }, { by_cases hy : y = 0, { simp [hy, eq_comm] }, { rw o.oangle_eq_iff_eq_norm_div_norm_smul_rotation_of_ne_zero hx hy, simp [hx, hy] } } end /-- The angle between two vectors is `θ` if and only if they are nonzero and the second vector is the first rotated by `θ` and scaled by a positive real, or `θ` and at least one of the vectors are zero. -/ lemma oangle_eq_iff_eq_pos_smul_rotation_or_eq_zero {x y : V} (θ : real.angle) : o.oangle x y = θ ↔ (x ≠ 0 ∧ y ≠ 0 ∧ ∃ r : ℝ, 0 < r ∧ y = r • o.rotation θ x) ∨ (θ = 0 ∧ (x = 0 ∨ y = 0)) := begin by_cases hx : x = 0, { simp [hx, eq_comm] }, { by_cases hy : y = 0, { simp [hy, eq_comm] }, { rw o.oangle_eq_iff_eq_pos_smul_rotation_of_ne_zero hx hy, simp [hx, hy] } } end /-- Any linear isometric equivalence in `V` with positive determinant is `rotation`. -/ lemma exists_linear_isometry_equiv_eq_of_det_pos {f : V ≃ₗᵢ[ℝ] V} (hd : 0 < (f.to_linear_equiv : V →ₗ[ℝ] V).det) : ∃ θ : real.angle, f = o.rotation θ := begin haveI : nontrivial V := finite_dimensional.nontrivial_of_finrank_eq_succ (fact.out (finrank ℝ V = 2)), obtain ⟨x, hx⟩ : ∃ x, x ≠ (0:V) := exists_ne (0:V), use o.oangle x (f x), apply linear_isometry_equiv.to_linear_equiv_injective, apply linear_equiv.to_linear_map_injective, apply (o.basis_right_angle_rotation x hx).ext, intros i, symmetry, fin_cases i, { simp }, have : o.oangle (J x) (f (J x)) = o.oangle x (f x), { simp only [oangle, o.linear_isometry_equiv_comp_right_angle_rotation f hd, o.kahler_comp_right_angle_rotation] }, simp [← this], end lemma rotation_map (θ : real.angle) (f : V ≃ₗᵢ[ℝ] V') (x : V') : (orientation.map (fin 2) f.to_linear_equiv o).rotation θ x = f (o.rotation θ (f.symm x)) := by simp [rotation_apply, o.right_angle_rotation_map] @[simp] protected lemma _root_.complex.rotation (θ : real.angle) (z : ℂ) : complex.orientation.rotation θ z = θ.exp_map_circle * z := begin simp only [rotation_apply, complex.right_angle_rotation, real.angle.coe_exp_map_circle, real_smul], ring end /-- Rotation in an oriented real inner product space of dimension 2 can be evaluated in terms of a complex-number representation of the space. -/ lemma rotation_map_complex (θ : real.angle) (f : V ≃ₗᵢ[ℝ] ℂ) (hf : (orientation.map (fin 2) f.to_linear_equiv o) = complex.orientation) (x : V) : f (o.rotation θ x) = θ.exp_map_circle * f x := begin rw [← complex.rotation, ← hf, o.rotation_map], simp, end /-- Negating the orientation negates the angle in `rotation`. -/ lemma rotation_neg_orientation_eq_neg (θ : real.angle) : (-o).rotation θ = o.rotation (-θ) := linear_isometry_equiv.ext $ by simp [rotation_apply] /-- The inner product between a `π / 2` rotation of a vector and that vector is zero. -/ @[simp] lemma inner_rotation_pi_div_two_left (x : V) : ⟪o.rotation (π / 2 : ℝ) x, x⟫ = 0 := by rw [rotation_pi_div_two, inner_right_angle_rotation_self] /-- The inner product between a vector and a `π / 2` rotation of that vector is zero. -/ @[simp] lemma inner_rotation_pi_div_two_right (x : V) : ⟪x, o.rotation (π / 2 : ℝ) x⟫ = 0 := by rw [real_inner_comm, inner_rotation_pi_div_two_left] /-- The inner product between a multiple of a `π / 2` rotation of a vector and that vector is zero. -/ @[simp] lemma inner_smul_rotation_pi_div_two_left (x : V) (r : ℝ) : ⟪r • o.rotation (π / 2 : ℝ) x, x⟫ = 0 := by rw [inner_smul_left, inner_rotation_pi_div_two_left, mul_zero] /-- The inner product between a vector and a multiple of a `π / 2` rotation of that vector is zero. -/ @[simp] lemma inner_smul_rotation_pi_div_two_right (x : V) (r : ℝ) : ⟪x, r • o.rotation (π / 2 : ℝ) x⟫ = 0 := by rw [real_inner_comm, inner_smul_rotation_pi_div_two_left] /-- The inner product between a `π / 2` rotation of a vector and a multiple of that vector is zero. -/ @[simp] lemma inner_rotation_pi_div_two_left_smul (x : V) (r : ℝ) : ⟪o.rotation (π / 2 : ℝ) x, r • x⟫ = 0 := by rw [inner_smul_right, inner_rotation_pi_div_two_left, mul_zero] /-- The inner product between a multiple of a vector and a `π / 2` rotation of that vector is zero. -/ @[simp] lemma inner_rotation_pi_div_two_right_smul (x : V) (r : ℝ) : ⟪r • x, o.rotation (π / 2 : ℝ) x⟫ = 0 := by rw [real_inner_comm, inner_rotation_pi_div_two_left_smul] /-- The inner product between a multiple of a `π / 2` rotation of a vector and a multiple of that vector is zero. -/ @[simp] lemma inner_smul_rotation_pi_div_two_smul_left (x : V) (r₁ r₂ : ℝ) : ⟪r₁ • o.rotation (π / 2 : ℝ) x, r₂ • x⟫ = 0 := by rw [inner_smul_right, inner_smul_rotation_pi_div_two_left, mul_zero] /-- The inner product between a multiple of a vector and a multiple of a `π / 2` rotation of that vector is zero. -/ @[simp] lemma inner_smul_rotation_pi_div_two_smul_right (x : V) (r₁ r₂ : ℝ) : ⟪r₂ • x, r₁ • o.rotation (π / 2 : ℝ) x⟫ = 0 := by rw [real_inner_comm, inner_smul_rotation_pi_div_two_smul_left] /-- The inner product between two vectors is zero if and only if the first vector is zero or the second is a multiple of a `π / 2` rotation of that vector. -/ lemma inner_eq_zero_iff_eq_zero_or_eq_smul_rotation_pi_div_two {x y : V} : ⟪x, y⟫ = 0 ↔ (x = 0 ∨ ∃ r : ℝ, r • o.rotation (π / 2 : ℝ) x = y) := begin rw ←o.eq_zero_or_oangle_eq_iff_inner_eq_zero, refine ⟨λ h, _, λ h, _⟩, { rcases h with rfl | rfl | h | h, { exact or.inl rfl }, { exact or.inr ⟨0, zero_smul _ _⟩ }, { obtain ⟨r, hr, rfl⟩ := (o.oangle_eq_iff_eq_pos_smul_rotation_of_ne_zero (o.left_ne_zero_of_oangle_eq_pi_div_two h) (o.right_ne_zero_of_oangle_eq_pi_div_two h) _).1 h, exact or.inr ⟨r, rfl⟩ }, { obtain ⟨r, hr, rfl⟩ := (o.oangle_eq_iff_eq_pos_smul_rotation_of_ne_zero (o.left_ne_zero_of_oangle_eq_neg_pi_div_two h) (o.right_ne_zero_of_oangle_eq_neg_pi_div_two h) _).1 h, refine or.inr ⟨-r, _⟩, rw [neg_smul, ←smul_neg, o.neg_rotation_pi_div_two] } }, { rcases h with rfl | ⟨r, rfl⟩, { exact or.inl rfl }, { by_cases hx : x = 0, { exact or.inl hx }, rcases lt_trichotomy r 0 with hr | rfl | hr, { refine or.inr (or.inr (or.inr _)), rw [o.oangle_smul_right_of_neg _ _ hr, o.neg_rotation_pi_div_two, o.oangle_rotation_self_right hx] }, { exact or.inr (or.inl (zero_smul _ _)) }, { refine or.inr (or.inr (or.inl _)), rw [o.oangle_smul_right_of_pos _ _ hr, o.oangle_rotation_self_right hx] } } } end end orientation
94e1ebe3a7c69718df21d8b7c9926580ba59b509
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/order/filter/partial.lean
cfacfae4517eeeb5f63eddc87e657e809becbb14
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
8,437
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad Extends `tendsto` to relations and partial functions. -/ import .basic universes u v w namespace filter variables {α : Type u} {β : Type v} {γ : Type w} /- Relations. -/ def rmap (r : rel α β) (f : filter α) : filter β := { sets := r.core ⁻¹' f.sets, univ_sets := by { simp [rel.core], apply univ_mem_sets }, sets_of_superset := assume s t hs st, mem_sets_of_superset hs $ rel.core_mono _ st, inter_sets := by { simp [set.preimage, rel.core_inter], exact λ s t, inter_mem_sets } } theorem rmap_sets (r : rel α β) (f : filter α) : (rmap r f).sets = r.core ⁻¹' f.sets := rfl @[simp] theorem mem_rmap (r : rel α β) (l : filter α) (s : set β) : s ∈ l.rmap r ↔ r.core s ∈ l := iff.refl _ @[simp] theorem rmap_rmap (r : rel α β) (s : rel β γ) (l : filter α) : rmap s (rmap r l) = rmap (r.comp s) l := filter_eq $ by simp [rmap_sets, set.preimage, rel.core_comp] @[simp] lemma rmap_compose (r : rel α β) (s : rel β γ) : rmap s ∘ rmap r = rmap (r.comp s) := funext $ rmap_rmap _ _ def rtendsto (r : rel α β) (l₁ : filter α) (l₂ : filter β) := l₁.rmap r ≤ l₂ theorem rtendsto_def (r : rel α β) (l₁ : filter α) (l₂ : filter β) : rtendsto r l₁ l₂ ↔ ∀ s ∈ l₂, r.core s ∈ l₁ := iff.refl _ def rcomap (r : rel α β) (f : filter β) : filter α := { sets := rel.image (λ s t, r.core s ⊆ t) f.sets, univ_sets := ⟨set.univ, univ_mem_sets, set.subset_univ _⟩, sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', set.subset.trans ma'a ab⟩, inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, set.subset.trans (by rw rel.core_inter) (set.inter_subset_inter ha₂ hb₂)⟩ } theorem rcomap_sets (r : rel α β) (f : filter β) : (rcomap r f).sets = rel.image (λ s t, r.core s ⊆ t) f.sets := rfl @[simp] theorem rcomap_rcomap (r : rel α β) (s : rel β γ) (l : filter γ) : rcomap r (rcomap s l) = rcomap (r.comp s) l := filter_eq $ begin ext t, simp [rcomap_sets, rel.image, rel.core_comp], split, { rintros ⟨u, ⟨v, vsets, hv⟩, h⟩, exact ⟨v, vsets, set.subset.trans (rel.core_mono _ hv) h⟩ }, rintros ⟨t, tsets, ht⟩, exact ⟨rel.core s t, ⟨t, tsets, set.subset.refl _⟩, ht⟩ end @[simp] lemma rcomap_compose (r : rel α β) (s : rel β γ) : rcomap r ∘ rcomap s = rcomap (r.comp s) := funext $ rcomap_rcomap _ _ theorem rtendsto_iff_le_comap (r : rel α β) (l₁ : filter α) (l₂ : filter β) : rtendsto r l₁ l₂ ↔ l₁ ≤ l₂.rcomap r := begin rw rtendsto_def, change (∀ (s : set β), s ∈ l₂.sets → rel.core r s ∈ l₁) ↔ l₁ ≤ rcomap r l₂, simp [filter.le_def, rcomap, rel.mem_image], split, intros h s t tl₂ h', { exact mem_sets_of_superset (h t tl₂) h' }, intros h t tl₂, apply h _ t tl₂ (set.subset.refl _), end -- Interestingly, there does not seem to be a way to express this relation using a forward map. -- Given a filter `f` on `α`, we want a filter `f'` on `β` such that `r.preimage s ∈ f` if -- and only if `s ∈ f'`. But the intersection of two sets satsifying the lhs may be empty. def rcomap' (r : rel α β) (f : filter β) : filter α := { sets := rel.image (λ s t, r.preimage s ⊆ t) f.sets, univ_sets := ⟨set.univ, univ_mem_sets, set.subset_univ _⟩, sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', set.subset.trans ma'a ab⟩, inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, set.subset.trans (@rel.preimage_inter _ _ r _ _) (set.inter_subset_inter ha₂ hb₂)⟩ } @[simp] def mem_rcomap' (r : rel α β) (l : filter β) (s : set α) : s ∈ l.rcomap' r ↔ ∃ t ∈ l, rel.preimage r t ⊆ s := iff.refl _ theorem rcomap'_sets (r : rel α β) (f : filter β) : (rcomap' r f).sets = rel.image (λ s t, r.preimage s ⊆ t) f.sets := rfl @[simp] theorem rcomap'_rcomap' (r : rel α β) (s : rel β γ) (l : filter γ) : rcomap' r (rcomap' s l) = rcomap' (r.comp s) l := filter_eq $ begin ext t, simp [rcomap'_sets, rel.image, rel.preimage_comp], split, { rintros ⟨u, ⟨v, vsets, hv⟩, h⟩, exact ⟨v, vsets, set.subset.trans (rel.preimage_mono _ hv) h⟩ }, rintros ⟨t, tsets, ht⟩, exact ⟨rel.preimage s t, ⟨t, tsets, set.subset.refl _⟩, ht⟩ end @[simp] lemma rcomap'_compose (r : rel α β) (s : rel β γ) : rcomap' r ∘ rcomap' s = rcomap' (r.comp s) := funext $ rcomap'_rcomap' _ _ def rtendsto' (r : rel α β) (l₁ : filter α) (l₂ : filter β) := l₁ ≤ l₂.rcomap' r theorem rtendsto'_def (r : rel α β) (l₁ : filter α) (l₂ : filter β) : rtendsto' r l₁ l₂ ↔ ∀ s ∈ l₂, r.preimage s ∈ l₁ := begin unfold rtendsto', unfold rcomap', simp [le_def, rel.mem_image], split, { intros h s hs, apply (h _ _ hs (set.subset.refl _)) }, intros h s t ht h', apply mem_sets_of_superset (h t ht) h' end theorem tendsto_iff_rtendsto (l₁ : filter α) (l₂ : filter β) (f : α → β) : tendsto f l₁ l₂ ↔ rtendsto (function.graph f) l₁ l₂ := by { simp [tendsto_def, function.graph, rtendsto_def, rel.core, set.preimage] } theorem tendsto_iff_rtendsto' (l₁ : filter α) (l₂ : filter β) (f : α → β) : tendsto f l₁ l₂ ↔ rtendsto' (function.graph f) l₁ l₂ := by { simp [tendsto_def, function.graph, rtendsto'_def, rel.preimage_def, set.preimage] } /- Partial functions. -/ def pmap (f : α →. β) (l : filter α) : filter β := filter.rmap f.graph' l @[simp] def mem_pmap (f : α →. β) (l : filter α) (s : set β) : s ∈ l.pmap f ↔ f.core s ∈ l := iff.refl _ def ptendsto (f : α →. β) (l₁ : filter α) (l₂ : filter β) := l₁.pmap f ≤ l₂ theorem ptendsto_def (f : α →. β) (l₁ : filter α) (l₂ : filter β) : ptendsto f l₁ l₂ ↔ ∀ s ∈ l₂, f.core s ∈ l₁ := iff.refl _ theorem ptendsto_iff_rtendsto (l₁ : filter α) (l₂ : filter β) (f : α →. β) : ptendsto f l₁ l₂ ↔ rtendsto f.graph' l₁ l₂ := iff.refl _ theorem pmap_res (l : filter α) (s : set α) (f : α → β) : pmap (pfun.res f s) l = map f (l ⊓ principal s) := filter_eq $ begin apply set.ext, intro t, simp [pfun.core_res], split, { intro h, constructor, split, { exact h }, constructor, split, { reflexivity }, simp [set.inter_distrib_right], apply set.inter_subset_left }, rintro ⟨t₁, h₁, t₂, h₂, h₃⟩, apply mem_sets_of_superset h₁, rw ← set.inter_subset, exact set.subset.trans (set.inter_subset_inter_right _ h₂) h₃ end theorem tendsto_iff_ptendsto (l₁ : filter α) (l₂ : filter β) (s : set α) (f : α → β) : tendsto f (l₁ ⊓ principal s) l₂ ↔ ptendsto (pfun.res f s) l₁ l₂ := by simp only [tendsto, ptendsto, pmap_res] theorem tendsto_iff_ptendsto_univ (l₁ : filter α) (l₂ : filter β) (f : α → β) : tendsto f l₁ l₂ ↔ ptendsto (pfun.res f set.univ) l₁ l₂ := by { rw ← tendsto_iff_ptendsto, simp [principal_univ] } def pcomap' (f : α →. β) (l : filter β) : filter α := filter.rcomap' f.graph' l def ptendsto' (f : α →. β) (l₁ : filter α) (l₂ : filter β) := l₁ ≤ l₂.rcomap' f.graph' theorem ptendsto'_def (f : α →. β) (l₁ : filter α) (l₂ : filter β) : ptendsto' f l₁ l₂ ↔ ∀ s ∈ l₂, f.preimage s ∈ l₁ := rtendsto'_def _ _ _ theorem ptendsto_of_ptendsto' {f : α →. β} {l₁ : filter α} {l₂ : filter β} : ptendsto' f l₁ l₂ → ptendsto f l₁ l₂ := begin rw [ptendsto_def, ptendsto'_def], assume h s sl₂, exacts mem_sets_of_superset (h s sl₂) (pfun.preimage_subset_core _ _), end theorem ptendsto'_of_ptendsto {f : α →. β} {l₁ : filter α} {l₂ : filter β} (h : f.dom ∈ l₁) : ptendsto f l₁ l₂ → ptendsto' f l₁ l₂ := begin rw [ptendsto_def, ptendsto'_def], assume h' s sl₂, rw pfun.preimage_eq, show pfun.core f s ∩ pfun.dom f ∈ l₁, exact inter_mem_sets (h' s sl₂) h end end filter
aedfb4c049eac89d7a3f3376bd2d3e3816a54f69
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/linear_algebra/dimension.lean
551ad63201b6ac0c7fc49f990c3b320f63dc961b
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
53,500
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl, Sander Dahmen, Scott Morrison -/ import linear_algebra.dfinsupp import linear_algebra.invariant_basis_number import linear_algebra.isomorphisms import linear_algebra.std_basis import set_theory.cardinal.cofinality /-! # Dimension of modules and vector spaces ## Main definitions * The rank of a module is defined as `module.rank : cardinal`. This is defined as the supremum of the cardinalities of linearly independent subsets. * The rank of a linear map is defined as the rank of its range. ## Main statements * `linear_map.dim_le_of_injective`: the source of an injective linear map has dimension at most that of the target. * `linear_map.dim_le_of_surjective`: the target of a surjective linear map has dimension at most that of that source. * `basis_fintype_of_finite_spans`: the existence of a finite spanning set implies that any basis is finite. * `infinite_basis_le_maximal_linear_independent`: if `b` is an infinite basis for a module `M`, and `s` is a maximal linearly independent set, then the cardinality of `b` is bounded by the cardinality of `s`. For modules over rings satisfying the rank condition * `basis.le_span`: the cardinality of a basis is bounded by the cardinality of any spanning set For modules over rings satisfying the strong rank condition * `linear_independent_le_span`: For any linearly independent family `v : ι → M` and any finite spanning set `w : set M`, the cardinality of `ι` is bounded by the cardinality of `w`. * `linear_independent_le_basis`: If `b` is a basis for a module `M`, and `s` is a linearly independent set, then the cardinality of `s` is bounded by the cardinality of `b`. For modules over rings with invariant basis number (including all commutative rings and all noetherian rings) * `mk_eq_mk_of_basis`: the dimension theorem, any two bases of the same vector space have the same cardinality. For vector spaces (i.e. modules over a field), we have * `dim_quotient_add_dim`: if `V₁` is a submodule of `V`, then `module.rank (V/V₁) + module.rank V₁ = module.rank V`. * `dim_range_add_dim_ker`: the rank-nullity theorem. ## Implementation notes There is a naming discrepancy: most of the theorem names refer to `dim`, even though the definition is of `module.rank`. This reflects that `module.rank` was originally called `dim`, and only defined for vector spaces. Many theorems in this file are not universe-generic when they relate dimensions in different universes. They should be as general as they can be without inserting `lift`s. The types `V`, `V'`, ... all live in different universes, and `V₁`, `V₂`, ... all live in the same universe. -/ noncomputable theory universes u v v' v'' u₁' w w' variables {K : Type u} {V V₁ V₂ V₃ : Type v} {V' V'₁ : Type v'} {V'' : Type v''} variables {ι : Type w} {ι' : Type w'} {η : Type u₁'} {φ : η → Type*} open_locale classical big_operators cardinal open basis submodule function set section module section variables [semiring K] [add_comm_monoid V] [module K V] include K variables (K V) /-- The rank of a module, defined as a term of type `cardinal`. We define this as the supremum of the cardinalities of linearly independent subsets. For a free module over any ring satisfying the strong rank condition (e.g. left-noetherian rings, commutative rings, and in particular division rings and fields), this is the same as the dimension of the space (i.e. the cardinality of any basis). In particular this agrees with the usual notion of the dimension of a vector space. The definition is marked as protected to avoid conflicts with `_root_.rank`, the rank of a linear map. -/ protected def module.rank : cardinal := ⨆ ι : {s : set V // linear_independent K (coe : s → V)}, #ι.1 end section variables {R : Type u} [ring R] variables {M : Type v} [add_comm_group M] [module R M] variables {M' : Type v'} [add_comm_group M'] [module R M'] variables {M₁ : Type v} [add_comm_group M₁] [module R M₁] theorem linear_map.lift_dim_le_of_injective (f : M →ₗ[R] M') (i : injective f) : cardinal.lift.{v'} (module.rank R M) ≤ cardinal.lift.{v} (module.rank R M') := begin dsimp [module.rank], rw [cardinal.lift_supr (cardinal.bdd_above_range.{v' v'} _), cardinal.lift_supr (cardinal.bdd_above_range.{v v} _)], apply csupr_mono' (cardinal.bdd_above_range.{v' v} _), rintro ⟨s, li⟩, refine ⟨⟨f '' s, _⟩, cardinal.lift_mk_le'.mpr ⟨(equiv.set.image f s i).to_embedding⟩⟩, exact (li.map' _ $ linear_map.ker_eq_bot.mpr i).image, end theorem linear_map.dim_le_of_injective (f : M →ₗ[R] M₁) (i : injective f) : module.rank R M ≤ module.rank R M₁ := cardinal.lift_le.1 (f.lift_dim_le_of_injective i) theorem dim_le {n : ℕ} (H : ∀ s : finset M, linear_independent R (λ i : s, (i : M)) → s.card ≤ n) : module.rank R M ≤ n := begin apply csupr_le', rintro ⟨s, li⟩, exact linear_independent_bounded_of_finset_linear_independent_bounded H _ li, end lemma lift_dim_range_le (f : M →ₗ[R] M') : cardinal.lift.{v} (module.rank R f.range) ≤ cardinal.lift.{v'} (module.rank R M) := begin dsimp [module.rank], rw [cardinal.lift_supr (cardinal.bdd_above_range.{v' v'} _)], apply csupr_le', rintro ⟨s, li⟩, apply le_trans, swap 2, apply cardinal.lift_le.mpr, refine (le_csupr (cardinal.bdd_above_range.{v v} _) ⟨range_splitting f '' s, _⟩), { apply linear_independent.of_comp f.range_restrict, convert li.comp (equiv.set.range_splitting_image_equiv f s) (equiv.injective _) using 1, }, { exact (cardinal.lift_mk_eq'.mpr ⟨equiv.set.range_splitting_image_equiv f s⟩).ge, }, end lemma dim_range_le (f : M →ₗ[R] M₁) : module.rank R f.range ≤ module.rank R M := by simpa using lift_dim_range_le f lemma lift_dim_map_le (f : M →ₗ[R] M') (p : submodule R M) : cardinal.lift.{v} (module.rank R (p.map f)) ≤ cardinal.lift.{v'} (module.rank R p) := begin have h := lift_dim_range_le (f.comp (submodule.subtype p)), rwa [linear_map.range_comp, range_subtype] at h, end lemma dim_map_le (f : M →ₗ[R] M₁) (p : submodule R M) : module.rank R (p.map f) ≤ module.rank R p := by simpa using lift_dim_map_le f p lemma dim_le_of_submodule (s t : submodule R M) (h : s ≤ t) : module.rank R s ≤ module.rank R t := (of_le h).dim_le_of_injective $ assume ⟨x, hx⟩ ⟨y, hy⟩ eq, subtype.eq $ show x = y, from subtype.ext_iff_val.1 eq /-- Two linearly equivalent vector spaces have the same dimension, a version with different universes. -/ theorem linear_equiv.lift_dim_eq (f : M ≃ₗ[R] M') : cardinal.lift.{v'} (module.rank R M) = cardinal.lift.{v} (module.rank R M') := begin apply le_antisymm, { exact f.to_linear_map.lift_dim_le_of_injective f.injective, }, { exact f.symm.to_linear_map.lift_dim_le_of_injective f.symm.injective, }, end /-- Two linearly equivalent vector spaces have the same dimension. -/ theorem linear_equiv.dim_eq (f : M ≃ₗ[R] M₁) : module.rank R M = module.rank R M₁ := cardinal.lift_inj.1 f.lift_dim_eq lemma dim_eq_of_injective (f : M →ₗ[R] M₁) (h : injective f) : module.rank R M = module.rank R f.range := (linear_equiv.of_injective f h).dim_eq /-- Pushforwards of submodules along a `linear_equiv` have the same dimension. -/ lemma linear_equiv.dim_map_eq (f : M ≃ₗ[R] M₁) (p : submodule R M) : module.rank R (p.map (f : M →ₗ[R] M₁)) = module.rank R p := (f.submodule_map p).dim_eq.symm variables (R M) @[simp] lemma dim_top : module.rank R (⊤ : submodule R M) = module.rank R M := begin have : (⊤ : submodule R M) ≃ₗ[R] M := linear_equiv.of_top ⊤ rfl, rw this.dim_eq, end variables {R M} lemma dim_range_of_surjective (f : M →ₗ[R] M') (h : surjective f) : module.rank R f.range = module.rank R M' := by rw [linear_map.range_eq_top.2 h, dim_top] lemma dim_submodule_le (s : submodule R M) : module.rank R s ≤ module.rank R M := begin rw ←dim_top R M, exact dim_le_of_submodule _ _ le_top, end lemma linear_map.dim_le_of_surjective (f : M →ₗ[R] M₁) (h : surjective f) : module.rank R M₁ ≤ module.rank R M := begin rw ←dim_range_of_surjective f h, apply dim_range_le, end theorem dim_quotient_le (p : submodule R M) : module.rank R (M ⧸ p) ≤ module.rank R M := (mkq p).dim_le_of_surjective (surjective_quot_mk _) variables [nontrivial R] lemma {m} cardinal_lift_le_dim_of_linear_independent {ι : Type w} {v : ι → M} (hv : linear_independent R v) : cardinal.lift.{max v m} (#ι) ≤ cardinal.lift.{max w m} (module.rank R M) := begin apply le_trans, { exact cardinal.lift_mk_le.mpr ⟨(equiv.of_injective _ hv.injective).to_embedding⟩, }, { simp only [cardinal.lift_le], apply le_trans, swap, exact le_csupr (cardinal.bdd_above_range.{v v} _) ⟨range v, hv.coe_range⟩, exact le_rfl, }, end lemma cardinal_lift_le_dim_of_linear_independent' {ι : Type w} {v : ι → M} (hv : linear_independent R v) : cardinal.lift.{v} (#ι) ≤ cardinal.lift.{w} (module.rank R M) := cardinal_lift_le_dim_of_linear_independent.{u v w 0} hv lemma cardinal_le_dim_of_linear_independent {ι : Type v} {v : ι → M} (hv : linear_independent R v) : #ι ≤ module.rank R M := by simpa using cardinal_lift_le_dim_of_linear_independent hv lemma cardinal_le_dim_of_linear_independent' {s : set M} (hs : linear_independent R (λ x, x : s → M)) : #s ≤ module.rank R M := cardinal_le_dim_of_linear_independent hs variables (R M) @[simp] lemma dim_punit : module.rank R punit = 0 := begin apply le_bot_iff.mp, apply csupr_le', rintro ⟨s, li⟩, apply le_bot_iff.mpr, apply cardinal.mk_emptyc_iff.mpr, simp only [subtype.coe_mk], by_contradiction h, have ne : s.nonempty := ne_empty_iff_nonempty.mp h, simpa using linear_independent.ne_zero (⟨_, ne.some_mem⟩ : s) li, end @[simp] lemma dim_bot : module.rank R (⊥ : submodule R M) = 0 := begin have : (⊥ : submodule R M) ≃ₗ[R] punit := bot_equiv_punit, rw [this.dim_eq, dim_punit], end variables {R M} /-- A linearly-independent family of vectors in a module over a non-trivial ring must be finite if the module is Noetherian. -/ lemma linear_independent.finite_of_is_noetherian [is_noetherian R M] {v : ι → M} (hv : linear_independent R v) : finite ι := begin have hwf := is_noetherian_iff_well_founded.mp (by apply_instance : is_noetherian R M), refine complete_lattice.well_founded.finite_of_independent hwf hv.independent_span_singleton (λ i contra, _), apply hv.ne_zero i, have : v i ∈ R ∙ v i := submodule.mem_span_singleton_self (v i), rwa [contra, submodule.mem_bot] at this, end lemma linear_independent.set_finite_of_is_noetherian [is_noetherian R M] {s : set M} (hi : linear_independent R (coe : s → M)) : s.finite := @set.to_finite _ _ hi.finite_of_is_noetherian /-- Over any nontrivial ring, the existence of a finite spanning set implies that any basis is finite. -/ -- One might hope that a finite spanning set implies that any linearly independent set is finite. -- While this is true over a division ring -- (simply because any linearly independent set can be extended to a basis), -- I'm not certain what more general statements are possible. def basis_fintype_of_finite_spans (w : set M) [fintype w] (s : span R w = ⊤) {ι : Type w} (b : basis ι R M) : fintype ι := begin -- We'll work by contradiction, assuming `ι` is infinite. apply fintype_of_not_infinite _, introI i, -- Let `S` be the union of the supports of `x ∈ w` expressed as linear combinations of `b`. -- This is a finite set since `w` is finite. let S : finset ι := finset.univ.sup (λ x : w, (b.repr x).support), let bS : set M := b '' S, have h : ∀ x ∈ w, x ∈ span R bS, { intros x m, rw [←b.total_repr x, finsupp.span_image_eq_map_total, submodule.mem_map], use b.repr x, simp only [and_true, eq_self_iff_true, finsupp.mem_supported], change (b.repr x).support ≤ S, convert (finset.le_sup (by simp : (⟨x, m⟩ : w) ∈ finset.univ)), refl, }, -- Thus this finite subset of the basis elements spans the entire module. have k : span R bS = ⊤ := eq_top_iff.2 (le_trans s.ge (span_le.2 h)), -- Now there is some `x : ι` not in `S`, since `ι` is infinite. obtain ⟨x, nm⟩ := infinite.exists_not_mem_finset S, -- However it must be in the span of the finite subset, have k' : b x ∈ span R bS, { rw k, exact mem_top, }, -- giving the desire contradiction. refine b.linear_independent.not_mem_span_image _ k', exact nm, end /-- Over any ring `R`, if `b` is a basis for a module `M`, and `s` is a maximal linearly independent set, then the union of the supports of `x ∈ s` (when written out in the basis `b`) is all of `b`. -/ -- From [Les familles libres maximales d'un module ont-elles le meme cardinal?][lazarus1973] lemma union_support_maximal_linear_independent_eq_range_basis {ι : Type w} (b : basis ι R M) {κ : Type w'} (v : κ → M) (i : linear_independent R v) (m : i.maximal) : (⋃ k, ((b.repr (v k)).support : set ι)) = univ := begin -- If that's not the case, by_contradiction h, simp only [←ne.def, ne_univ_iff_exists_not_mem, mem_Union, not_exists_not, finsupp.mem_support_iff, finset.mem_coe] at h, -- We have some basis element `b b'` which is not in the support of any of the `v i`. obtain ⟨b', w⟩ := h, -- Using this, we'll construct a linearly independent family strictly larger than `v`, -- by also using this `b b'`. let v' : option κ → M := λ o, o.elim (b b') v, have r : range v ⊆ range v', { rintro - ⟨k, rfl⟩, use some k, refl, }, have r' : b b' ∉ range v, { rintro ⟨k, p⟩, simpa [w] using congr_arg (λ m, (b.repr m) b') p, }, have r'' : range v ≠ range v', { intro e, have p : b b' ∈ range v', { use none, refl, }, rw ←e at p, exact r' p, }, have inj' : injective v', { rintros (_|k) (_|k) z, { refl, }, { exfalso, exact r' ⟨k, z.symm⟩, }, { exfalso, exact r' ⟨k, z⟩, }, { congr, exact i.injective z, }, }, -- The key step in the proof is checking that this strictly larger family is linearly independent. have i' : linear_independent R (coe : range v' → M), { rw [linear_independent_subtype_range inj', linear_independent_iff], intros l z, rw [finsupp.total_option] at z, simp only [v', option.elim] at z, change _ + finsupp.total κ M R v l.some = 0 at z, -- We have some linear combination of `b b'` and the `v i`, which we want to show is trivial. -- We'll first show the coefficient of `b b'` is zero, -- by expressing the `v i` in the basis `b`, and using that the `v i` have no `b b'` term. have l₀ : l none = 0, { rw ←eq_neg_iff_add_eq_zero at z, replace z := eq_neg_of_eq_neg z, apply_fun (λ x, b.repr x b') at z, simp only [repr_self, linear_equiv.map_smul, mul_one, finsupp.single_eq_same, pi.neg_apply, finsupp.smul_single', linear_equiv.map_neg, finsupp.coe_neg] at z, erw finsupp.congr_fun (finsupp.apply_total R (b.repr : M →ₗ[R] ι →₀ R) v l.some) b' at z, simpa [finsupp.total_apply, w] using z, }, -- Then all the other coefficients are zero, because `v` is linear independent. have l₁ : l.some = 0, { rw [l₀, zero_smul, zero_add] at z, exact linear_independent_iff.mp i _ z, }, -- Finally we put those facts together to show the linear combination is trivial. ext (_|a), { simp only [l₀, finsupp.coe_zero, pi.zero_apply], }, { erw finsupp.congr_fun l₁ a, simp only [finsupp.coe_zero, pi.zero_apply], }, }, dsimp [linear_independent.maximal] at m, specialize m (range v') i' r, exact r'' m, end /-- Over any ring `R`, if `b` is an infinite basis for a module `M`, and `s` is a maximal linearly independent set, then the cardinality of `b` is bounded by the cardinality of `s`. -/ lemma infinite_basis_le_maximal_linear_independent' {ι : Type w} (b : basis ι R M) [infinite ι] {κ : Type w'} (v : κ → M) (i : linear_independent R v) (m : i.maximal) : cardinal.lift.{w'} (#ι) ≤ cardinal.lift.{w} (#κ) := begin let Φ := λ k : κ, (b.repr (v k)).support, have w₁ : #ι ≤ #(set.range Φ), { apply cardinal.le_range_of_union_finset_eq_top, exact union_support_maximal_linear_independent_eq_range_basis b v i m, }, have w₂ : cardinal.lift.{w'} (#(set.range Φ)) ≤ cardinal.lift.{w} (#κ) := cardinal.mk_range_le_lift, exact (cardinal.lift_le.mpr w₁).trans w₂, end /-- Over any ring `R`, if `b` is an infinite basis for a module `M`, and `s` is a maximal linearly independent set, then the cardinality of `b` is bounded by the cardinality of `s`. -/ -- (See `infinite_basis_le_maximal_linear_independent'` for the more general version -- where the index types can live in different universes.) lemma infinite_basis_le_maximal_linear_independent {ι : Type w} (b : basis ι R M) [infinite ι] {κ : Type w} (v : κ → M) (i : linear_independent R v) (m : i.maximal) : #ι ≤ #κ := cardinal.lift_le.mp (infinite_basis_le_maximal_linear_independent' b v i m) lemma complete_lattice.independent.subtype_ne_bot_le_rank [no_zero_smul_divisors R M] {V : ι → submodule R M} (hV : complete_lattice.independent V) : cardinal.lift.{v} (#{i : ι // V i ≠ ⊥}) ≤ cardinal.lift.{w} (module.rank R M) := begin set I := {i : ι // V i ≠ ⊥}, have hI : ∀ i : I, ∃ v ∈ V i, v ≠ (0:M), { intros i, rw ← submodule.ne_bot_iff, exact i.prop }, choose v hvV hv using hI, have : linear_independent R v, { exact (hV.comp subtype.coe_injective).linear_independent _ hvV hv }, exact cardinal_lift_le_dim_of_linear_independent' this end end section rank_zero variables {R : Type u} {M : Type v} variables [ring R] [nontrivial R] [add_comm_group M] [module R M] [no_zero_smul_divisors R M] lemma dim_zero_iff_forall_zero : module.rank R M = 0 ↔ ∀ x : M, x = 0 := begin refine ⟨λ h, _, λ h, _⟩, { contrapose! h, obtain ⟨x, hx⟩ := h, suffices : 1 ≤ module.rank R M, { intro h, exact lt_irrefl _ (lt_of_lt_of_le cardinal.zero_lt_one (h ▸ this)) }, suffices : linear_independent R (λ (y : ({x} : set M)), ↑y), { simpa using (cardinal_le_dim_of_linear_independent this), }, exact linear_independent_singleton hx }, { have : (⊤ : submodule R M) = ⊥, { ext x, simp [h x] }, rw [←dim_top, this, dim_bot] } end lemma dim_zero_iff : module.rank R M = 0 ↔ subsingleton M := dim_zero_iff_forall_zero.trans (subsingleton_iff_forall_eq 0).symm lemma dim_pos_iff_exists_ne_zero : 0 < module.rank R M ↔ ∃ x : M, x ≠ 0 := begin rw ←not_iff_not, simpa using dim_zero_iff_forall_zero end lemma dim_pos_iff_nontrivial : 0 < module.rank R M ↔ nontrivial M := dim_pos_iff_exists_ne_zero.trans (nontrivial_iff_exists_ne 0).symm lemma dim_pos [h : nontrivial M] : 0 < module.rank R M := dim_pos_iff_nontrivial.2 h end rank_zero section invariant_basis_number variables {R : Type u} [ring R] [invariant_basis_number R] variables {M : Type v} [add_comm_group M] [module R M] /-- The dimension theorem: if `v` and `v'` are two bases, their index types have the same cardinalities. -/ theorem mk_eq_mk_of_basis (v : basis ι R M) (v' : basis ι' R M) : cardinal.lift.{w'} (#ι) = cardinal.lift.{w} (#ι') := begin haveI := nontrivial_of_invariant_basis_number R, casesI fintype_or_infinite ι, { -- `v` is a finite basis, so by `basis_fintype_of_finite_spans` so is `v'`. haveI : fintype (range v) := set.fintype_range v, haveI := basis_fintype_of_finite_spans _ v.span_eq v', -- We clean up a little: rw [cardinal.mk_fintype, cardinal.mk_fintype], simp only [cardinal.lift_nat_cast, cardinal.nat_cast_inj], -- Now we can use invariant basis number to show they have the same cardinality. apply card_eq_of_lequiv R, exact (((finsupp.linear_equiv_fun_on_fintype R R ι).symm.trans v.repr.symm) ≪≫ₗ v'.repr) ≪≫ₗ (finsupp.linear_equiv_fun_on_fintype R R ι'), }, { -- `v` is an infinite basis, -- so by `infinite_basis_le_maximal_linear_independent`, `v'` is at least as big, -- and then applying `infinite_basis_le_maximal_linear_independent` again -- we see they have the same cardinality. have w₁ := infinite_basis_le_maximal_linear_independent' v _ v'.linear_independent v'.maximal, rcases cardinal.lift_mk_le'.mp w₁ with ⟨f⟩, haveI : infinite ι' := infinite.of_injective f f.2, have w₂ := infinite_basis_le_maximal_linear_independent' v' _ v.linear_independent v.maximal, exact le_antisymm w₁ w₂, } end /-- Given two bases indexed by `ι` and `ι'` of an `R`-module, where `R` satisfies the invariant basis number property, an equiv `ι ≃ ι' `. -/ def basis.index_equiv (v : basis ι R M) (v' : basis ι' R M) : ι ≃ ι' := nonempty.some (cardinal.lift_mk_eq.1 (cardinal.lift_umax_eq.2 (mk_eq_mk_of_basis v v'))) theorem mk_eq_mk_of_basis' {ι' : Type w} (v : basis ι R M) (v' : basis ι' R M) : #ι = #ι' := cardinal.lift_inj.1 $ mk_eq_mk_of_basis v v' end invariant_basis_number section rank_condition variables {R : Type u} [ring R] [rank_condition R] variables {M : Type v} [add_comm_group M] [module R M] /-- An auxiliary lemma for `basis.le_span`. If `R` satisfies the rank condition, then for any finite basis `b : basis ι R M`, and any finite spanning set `w : set M`, the cardinality of `ι` is bounded by the cardinality of `w`. -/ lemma basis.le_span'' {ι : Type*} [fintype ι] (b : basis ι R M) {w : set M} [fintype w] (s : span R w = ⊤) : fintype.card ι ≤ fintype.card w := begin -- We construct an surjective linear map `(w → R) →ₗ[R] (ι → R)`, -- by expressing a linear combination in `w` as a linear combination in `ι`. fapply card_le_of_surjective' R, { exact b.repr.to_linear_map.comp (finsupp.total w M R coe), }, { apply surjective.comp, apply linear_equiv.surjective, rw [←linear_map.range_eq_top, finsupp.range_total], simpa using s, }, end /-- Another auxiliary lemma for `basis.le_span`, which does not require assuming the basis is finite, but still assumes we have a finite spanning set. -/ lemma basis_le_span' {ι : Type*} (b : basis ι R M) {w : set M} [fintype w] (s : span R w = ⊤) : #ι ≤ fintype.card w := begin haveI := nontrivial_of_invariant_basis_number R, haveI := basis_fintype_of_finite_spans w s b, rw cardinal.mk_fintype ι, simp only [cardinal.nat_cast_le], exact basis.le_span'' b s, end /-- If `R` satisfies the rank condition, then the cardinality of any basis is bounded by the cardinality of any spanning set. -/ -- Note that if `R` satisfies the strong rank condition, -- this also follows from `linear_independent_le_span` below. theorem basis.le_span {J : set M} (v : basis ι R M) (hJ : span R J = ⊤) : #(range v) ≤ #J := begin haveI := nontrivial_of_invariant_basis_number R, casesI fintype_or_infinite J, { rw [←cardinal.lift_le, cardinal.mk_range_eq_of_injective v.injective, cardinal.mk_fintype J], convert cardinal.lift_le.{w v}.2 (basis_le_span' v hJ), simp, }, { have := cardinal.mk_range_eq_of_injective v.injective, let S : J → set ι := λ j, ↑(v.repr j).support, let S' : J → set M := λ j, v '' S j, have hs : range v ⊆ ⋃ j, S' j, { intros b hb, rcases mem_range.1 hb with ⟨i, hi⟩, have : span R J ≤ comap v.repr.to_linear_map (finsupp.supported R R (⋃ j, S j)) := span_le.2 (λ j hj x hx, ⟨_, ⟨⟨j, hj⟩, rfl⟩, hx⟩), rw hJ at this, replace : v.repr (v i) ∈ (finsupp.supported R R (⋃ j, S j)) := this trivial, rw [v.repr_self, finsupp.mem_supported, finsupp.support_single_ne_zero _ one_ne_zero] at this, { subst b, rcases mem_Union.1 (this (finset.mem_singleton_self _)) with ⟨j, hj⟩, exact mem_Union.2 ⟨j, (mem_image _ _ _).2 ⟨i, hj, rfl⟩⟩ }, { apply_instance } }, refine le_of_not_lt (λ IJ, _), suffices : #(⋃ j, S' j) < #(range v), { exact not_le_of_lt this ⟨set.embedding_of_subset _ _ hs⟩ }, refine lt_of_le_of_lt (le_trans cardinal.mk_Union_le_sum_mk (cardinal.sum_le_sum _ (λ _, ℵ₀) _)) _, { exact λ j, (cardinal.lt_aleph_0_of_finite _).le }, { simpa } }, end end rank_condition section strong_rank_condition variables {R : Type u} [ring R] [strong_rank_condition R] variables {M : Type v} [add_comm_group M] [module R M] open submodule -- An auxiliary lemma for `linear_independent_le_span'`, -- with the additional assumption that the linearly independent family is finite. lemma linear_independent_le_span_aux' {ι : Type*} [fintype ι] (v : ι → M) (i : linear_independent R v) (w : set M) [fintype w] (s : range v ≤ span R w) : fintype.card ι ≤ fintype.card w := begin -- We construct an injective linear map `(ι → R) →ₗ[R] (w → R)`, -- by thinking of `f : ι → R` as a linear combination of the finite family `v`, -- and expressing that (using the axiom of choice) as a linear combination over `w`. -- We can do this linearly by constructing the map on a basis. fapply card_le_of_injective' R, { apply finsupp.total, exact λ i, span.repr R w ⟨v i, s (mem_range_self i)⟩, }, { intros f g h, apply_fun finsupp.total w M R coe at h, simp only [finsupp.total_total, submodule.coe_mk, span.finsupp_total_repr] at h, rw [←sub_eq_zero, ←linear_map.map_sub] at h, exact sub_eq_zero.mp (linear_independent_iff.mp i _ h), }, end /-- If `R` satisfies the strong rank condition, then any linearly independent family `v : ι → M` contained in the span of some finite `w : set M`, is itself finite. -/ def linear_independent_fintype_of_le_span_fintype {ι : Type*} (v : ι → M) (i : linear_independent R v) (w : set M) [fintype w] (s : range v ≤ span R w) : fintype ι := fintype_of_finset_card_le (fintype.card w) (λ t, begin let v' := λ x : (t : set ι), v x, have i' : linear_independent R v' := i.comp _ subtype.val_injective, have s' : range v' ≤ span R w := (range_comp_subset_range _ _).trans s, simpa using linear_independent_le_span_aux' v' i' w s', end) /-- If `R` satisfies the strong rank condition, then for any linearly independent family `v : ι → M` contained in the span of some finite `w : set M`, the cardinality of `ι` is bounded by the cardinality of `w`. -/ lemma linear_independent_le_span' {ι : Type*} (v : ι → M) (i : linear_independent R v) (w : set M) [fintype w] (s : range v ≤ span R w) : #ι ≤ fintype.card w := begin haveI : fintype ι := linear_independent_fintype_of_le_span_fintype v i w s, rw cardinal.mk_fintype, simp only [cardinal.nat_cast_le], exact linear_independent_le_span_aux' v i w s, end /-- If `R` satisfies the strong rank condition, then for any linearly independent family `v : ι → M` and any finite spanning set `w : set M`, the cardinality of `ι` is bounded by the cardinality of `w`. -/ lemma linear_independent_le_span {ι : Type*} (v : ι → M) (i : linear_independent R v) (w : set M) [fintype w] (s : span R w = ⊤) : #ι ≤ fintype.card w := begin apply linear_independent_le_span' v i w, rw s, exact le_top, end /-- An auxiliary lemma for `linear_independent_le_basis`: we handle the case where the basis `b` is infinite. -/ lemma linear_independent_le_infinite_basis {ι : Type*} (b : basis ι R M) [infinite ι] {κ : Type*} (v : κ → M) (i : linear_independent R v) : #κ ≤ #ι := begin by_contradiction, rw [not_le, ← cardinal.mk_finset_of_infinite ι] at h, let Φ := λ k : κ, (b.repr (v k)).support, obtain ⟨s, w : infinite ↥(Φ ⁻¹' {s})⟩ := cardinal.exists_infinite_fiber Φ h (by apply_instance), let v' := λ k : Φ ⁻¹' {s}, v k, have i' : linear_independent R v' := i.comp _ subtype.val_injective, have w' : fintype (Φ ⁻¹' {s}), { apply linear_independent_fintype_of_le_span_fintype v' i' (s.image b), rintros m ⟨⟨p,⟨rfl⟩⟩,rfl⟩, simp only [set_like.mem_coe, subtype.coe_mk, finset.coe_image], apply basis.mem_span_repr_support, }, exactI w.false, end /-- Over any ring `R` satisfying the strong rank condition, if `b` is a basis for a module `M`, and `s` is a linearly independent set, then the cardinality of `s` is bounded by the cardinality of `b`. -/ lemma linear_independent_le_basis {ι : Type*} (b : basis ι R M) {κ : Type*} (v : κ → M) (i : linear_independent R v) : #κ ≤ #ι := begin -- We split into cases depending on whether `ι` is infinite. cases fintype_or_infinite ι; resetI, { -- When `ι` is finite, we have `linear_independent_le_span`, rw cardinal.mk_fintype ι, haveI : nontrivial R := nontrivial_of_invariant_basis_number R, rw fintype.card_congr (equiv.of_injective b b.injective), exact linear_independent_le_span v i (range b) b.span_eq, }, { -- and otherwise we have `linear_indepedent_le_infinite_basis`. exact linear_independent_le_infinite_basis b v i, }, end /-- In an `n`-dimensional space, the rank is at most `m`. -/ lemma basis.card_le_card_of_linear_independent_aux {R : Type*} [ring R] [strong_rank_condition R] (n : ℕ) {m : ℕ} (v : fin m → fin n → R) : linear_independent R v → m ≤ n := λ h, by simpa using (linear_independent_le_basis (pi.basis_fun R (fin n)) v h) /-- Over any ring `R` satisfying the strong rank condition, if `b` is an infinite basis for a module `M`, then every maximal linearly independent set has the same cardinality as `b`. This proof (along with some of the lemmas above) comes from [Les familles libres maximales d'un module ont-elles le meme cardinal?][lazarus1973] -/ -- When the basis is not infinite this need not be true! lemma maximal_linear_independent_eq_infinite_basis {ι : Type*} (b : basis ι R M) [infinite ι] {κ : Type*} (v : κ → M) (i : linear_independent R v) (m : i.maximal) : #κ = #ι := begin apply le_antisymm, { exact linear_independent_le_basis b v i, }, { haveI : nontrivial R := nontrivial_of_invariant_basis_number R, exact infinite_basis_le_maximal_linear_independent b v i m, } end theorem basis.mk_eq_dim'' {ι : Type v} (v : basis ι R M) : #ι = module.rank R M := begin haveI := nontrivial_of_invariant_basis_number R, apply le_antisymm, { transitivity, swap, apply le_csupr (cardinal.bdd_above_range.{v v} _), exact ⟨set.range v, by { convert v.reindex_range.linear_independent, ext, simp }⟩, exact (cardinal.mk_range_eq v v.injective).ge, }, { apply csupr_le', rintro ⟨s, li⟩, apply linear_independent_le_basis v _ li, }, end -- By this stage we want to have a complete API for `module.rank`, -- so we set it `irreducible` here, to keep ourselves honest. attribute [irreducible] module.rank theorem basis.mk_range_eq_dim (v : basis ι R M) : #(range v) = module.rank R M := v.reindex_range.mk_eq_dim'' /-- If a vector space has a finite basis, then its dimension (seen as a cardinal) is equal to the cardinality of the basis. -/ lemma dim_eq_card_basis {ι : Type w} [fintype ι] (h : basis ι R M) : module.rank R M = fintype.card ι := by {haveI := nontrivial_of_invariant_basis_number R, rw [←h.mk_range_eq_dim, cardinal.mk_fintype, set.card_range_of_injective h.injective] } lemma basis.card_le_card_of_linear_independent {ι : Type*} [fintype ι] (b : basis ι R M) {ι' : Type*} [fintype ι'] {v : ι' → M} (hv : linear_independent R v) : fintype.card ι' ≤ fintype.card ι := begin letI := nontrivial_of_invariant_basis_number R, simpa [dim_eq_card_basis b, cardinal.mk_fintype] using cardinal_lift_le_dim_of_linear_independent' hv end lemma basis.card_le_card_of_submodule (N : submodule R M) [fintype ι] (b : basis ι R M) [fintype ι'] (b' : basis ι' R N) : fintype.card ι' ≤ fintype.card ι := b.card_le_card_of_linear_independent (b'.linear_independent.map' N.subtype N.ker_subtype) lemma basis.card_le_card_of_le {N O : submodule R M} (hNO : N ≤ O) [fintype ι] (b : basis ι R O) [fintype ι'] (b' : basis ι' R N) : fintype.card ι' ≤ fintype.card ι := b.card_le_card_of_linear_independent (b'.linear_independent.map' (submodule.of_le hNO) (N.ker_of_le O _)) theorem basis.mk_eq_dim (v : basis ι R M) : cardinal.lift.{v} (#ι) = cardinal.lift.{w} (module.rank R M) := begin haveI := nontrivial_of_invariant_basis_number R, rw [←v.mk_range_eq_dim, cardinal.mk_range_eq_of_injective v.injective] end theorem {m} basis.mk_eq_dim' (v : basis ι R M) : cardinal.lift.{max v m} (#ι) = cardinal.lift.{max w m} (module.rank R M) := by simpa using v.mk_eq_dim /-- If a module has a finite dimension, all bases are indexed by a finite type. -/ lemma basis.nonempty_fintype_index_of_dim_lt_aleph_0 {ι : Type*} (b : basis ι R M) (h : module.rank R M < ℵ₀) : nonempty (fintype ι) := by rwa [← cardinal.lift_lt, ← b.mk_eq_dim, -- ensure `aleph_0` has the correct universe cardinal.lift_aleph_0, ← cardinal.lift_aleph_0.{u_1 v}, cardinal.lift_lt, cardinal.lt_aleph_0_iff_fintype] at h /-- If a module has a finite dimension, all bases are indexed by a finite type. -/ noncomputable def basis.fintype_index_of_dim_lt_aleph_0 {ι : Type*} (b : basis ι R M) (h : module.rank R M < ℵ₀) : fintype ι := classical.choice (b.nonempty_fintype_index_of_dim_lt_aleph_0 h) /-- If a module has a finite dimension, all bases are indexed by a finite set. -/ lemma basis.finite_index_of_dim_lt_aleph_0 {ι : Type*} {s : set ι} (b : basis s R M) (h : module.rank R M < ℵ₀) : s.finite := finite_def.2 (b.nonempty_fintype_index_of_dim_lt_aleph_0 h) lemma dim_span {v : ι → M} (hv : linear_independent R v) : module.rank R ↥(span R (range v)) = #(range v) := begin haveI := nontrivial_of_invariant_basis_number R, rw [←cardinal.lift_inj, ← (basis.span hv).mk_eq_dim, cardinal.mk_range_eq_of_injective (@linear_independent.injective ι R M v _ _ _ _ hv)] end lemma dim_span_set {s : set M} (hs : linear_independent R (λ x, x : s → M)) : module.rank R ↥(span R s) = #s := by { rw [← @set_of_mem_eq _ s, ← subtype.range_coe_subtype], exact dim_span hs } /-- If `N` is a submodule in a free, finitely generated module, do induction on adjoining a linear independent element to a submodule. -/ def submodule.induction_on_rank [is_domain R] [fintype ι] (b : basis ι R M) (P : submodule R M → Sort*) (ih : ∀ (N : submodule R M), (∀ (N' ≤ N) (x ∈ N), (∀ (c : R) (y ∈ N'), c • x + y = (0 : M) → c = 0) → P N') → P N) (N : submodule R M) : P N := submodule.induction_on_rank_aux b P ih (fintype.card ι) N (λ s hs hli, by simpa using b.card_le_card_of_linear_independent hli) /-- If `S` a finite-dimensional ring extension of `R` which is free as an `R`-module, then the rank of an ideal `I` of `S` over `R` is the same as the rank of `S`. -/ lemma ideal.rank_eq {R S : Type*} [comm_ring R] [strong_rank_condition R] [ring S] [is_domain S] [algebra R S] {n m : Type*} [fintype n] [fintype m] (b : basis n R S) {I : ideal S} (hI : I ≠ ⊥) (c : basis m R I) : fintype.card m = fintype.card n := begin obtain ⟨a, ha⟩ := submodule.nonzero_mem_of_bot_lt (bot_lt_iff_ne_bot.mpr hI), have : linear_independent R (λ i, b i • a), { have hb := b.linear_independent, rw fintype.linear_independent_iff at ⊢ hb, intros g hg, apply hb g, simp only [← smul_assoc, ← finset.sum_smul, smul_eq_zero] at hg, exact hg.resolve_right ha }, exact le_antisymm (b.card_le_card_of_linear_independent (c.linear_independent.map' (submodule.subtype I) (linear_map.ker_eq_bot.mpr subtype.coe_injective))) (c.card_le_card_of_linear_independent this), end variables (R) @[simp] lemma dim_self : module.rank R R = 1 := by rw [←cardinal.lift_inj, ← (basis.singleton punit R).mk_eq_dim, cardinal.mk_punit] end strong_rank_condition section division_ring variables [division_ring K] [add_comm_group V] [module K V] [add_comm_group V₁] [module K V₁] variables {K V} /-- If a vector space has a finite dimension, the index set of `basis.of_vector_space` is finite. -/ lemma basis.finite_of_vector_space_index_of_dim_lt_aleph_0 (h : module.rank K V < ℵ₀) : (basis.of_vector_space_index K V).finite := finite_def.2 $ (basis.of_vector_space K V).nonempty_fintype_index_of_dim_lt_aleph_0 h variables [add_comm_group V'] [module K V'] /-- Two vector spaces are isomorphic if they have the same dimension. -/ theorem nonempty_linear_equiv_of_lift_dim_eq (cond : cardinal.lift.{v'} (module.rank K V) = cardinal.lift.{v} (module.rank K V')) : nonempty (V ≃ₗ[K] V') := begin let B := basis.of_vector_space K V, let B' := basis.of_vector_space K V', have : cardinal.lift.{v' v} (#_) = cardinal.lift.{v v'} (#_), by rw [B.mk_eq_dim'', cond, B'.mk_eq_dim''], exact (cardinal.lift_mk_eq.{v v' 0}.1 this).map (B.equiv B') end /-- Two vector spaces are isomorphic if they have the same dimension. -/ theorem nonempty_linear_equiv_of_dim_eq (cond : module.rank K V = module.rank K V₁) : nonempty (V ≃ₗ[K] V₁) := nonempty_linear_equiv_of_lift_dim_eq $ congr_arg _ cond section variables (V V' V₁) /-- Two vector spaces are isomorphic if they have the same dimension. -/ def linear_equiv.of_lift_dim_eq (cond : cardinal.lift.{v'} (module.rank K V) = cardinal.lift.{v} (module.rank K V')) : V ≃ₗ[K] V' := classical.choice (nonempty_linear_equiv_of_lift_dim_eq cond) /-- Two vector spaces are isomorphic if they have the same dimension. -/ def linear_equiv.of_dim_eq (cond : module.rank K V = module.rank K V₁) : V ≃ₗ[K] V₁ := classical.choice (nonempty_linear_equiv_of_dim_eq cond) end /-- Two vector spaces are isomorphic if and only if they have the same dimension. -/ theorem linear_equiv.nonempty_equiv_iff_lift_dim_eq : nonempty (V ≃ₗ[K] V') ↔ cardinal.lift.{v'} (module.rank K V) = cardinal.lift.{v} (module.rank K V') := ⟨λ ⟨h⟩, linear_equiv.lift_dim_eq h, λ h, nonempty_linear_equiv_of_lift_dim_eq h⟩ /-- Two vector spaces are isomorphic if and only if they have the same dimension. -/ theorem linear_equiv.nonempty_equiv_iff_dim_eq : nonempty (V ≃ₗ[K] V₁) ↔ module.rank K V = module.rank K V₁ := ⟨λ ⟨h⟩, linear_equiv.dim_eq h, λ h, nonempty_linear_equiv_of_dim_eq h⟩ -- TODO how far can we generalise this? -- When `s` is finite, we could prove this for any ring satisfying the strong rank condition -- using `linear_independent_le_span'` lemma dim_span_le (s : set V) : module.rank K (span K s) ≤ #s := begin obtain ⟨b, hb, hsab, hlib⟩ := exists_linear_independent K s, convert cardinal.mk_le_mk_of_subset hb, rw [← hsab, dim_span_set hlib] end lemma dim_span_of_finset (s : finset V) : module.rank K (span K (↑s : set V)) < ℵ₀ := calc module.rank K (span K (↑s : set V)) ≤ #(↑s : set V) : dim_span_le ↑s ... = s.card : by rw [finset.coe_sort_coe, cardinal.mk_coe_finset] ... < ℵ₀ : cardinal.nat_lt_aleph_0 _ theorem dim_prod : module.rank K (V × V₁) = module.rank K V + module.rank K V₁ := begin let b := basis.of_vector_space K V, let c := basis.of_vector_space K V₁, rw [← cardinal.lift_inj, ← (basis.prod b c).mk_eq_dim, cardinal.lift_add, ← cardinal.mk_ulift, ← b.mk_eq_dim, ← c.mk_eq_dim, ← cardinal.mk_ulift, ← cardinal.mk_ulift, cardinal.add_def (ulift _)], exact cardinal.lift_inj.1 (cardinal.lift_mk_eq.2 ⟨equiv.ulift.trans (equiv.sum_congr equiv.ulift equiv.ulift).symm ⟩), end section fintype variable [fintype η] variables [∀i, add_comm_group (φ i)] [∀i, module K (φ i)] open linear_map lemma dim_pi : module.rank K (Πi, φ i) = cardinal.sum (λi, module.rank K (φ i)) := begin let b := assume i, basis.of_vector_space K (φ i), let this : basis (Σ j, _) K (Π j, φ j) := pi.basis b, rw [← cardinal.lift_inj, ← this.mk_eq_dim], simp [← (b _).mk_range_eq_dim] end lemma dim_fun {V η : Type u} [fintype η] [add_comm_group V] [module K V] : module.rank K (η → V) = fintype.card η * module.rank K V := by rw [dim_pi, cardinal.sum_const', cardinal.mk_fintype] lemma dim_fun_eq_lift_mul : module.rank K (η → V) = (fintype.card η : cardinal.{max u₁' v}) * cardinal.lift.{u₁'} (module.rank K V) := by rw [dim_pi, cardinal.sum_const, cardinal.mk_fintype, cardinal.lift_nat_cast] lemma dim_fun' : module.rank K (η → K) = fintype.card η := by rw [dim_fun_eq_lift_mul, dim_self, cardinal.lift_one, mul_one, cardinal.nat_cast_inj] lemma dim_fin_fun (n : ℕ) : module.rank K (fin n → K) = n := by simp [dim_fun'] end fintype end division_ring section field variables [field K] [add_comm_group V] [module K V] [add_comm_group V₁] [module K V₁] variables [add_comm_group V'] [module K V'] theorem dim_quotient_add_dim (p : submodule K V) : module.rank K (V ⧸ p) + module.rank K p = module.rank K V := by classical; exact let ⟨f⟩ := quotient_prod_linear_equiv p in dim_prod.symm.trans f.dim_eq /-- rank-nullity theorem -/ theorem dim_range_add_dim_ker (f : V →ₗ[K] V₁) : module.rank K f.range + module.rank K f.ker = module.rank K V := begin haveI := λ (p : submodule K V), classical.dec_eq (V ⧸ p), rw [← f.quot_ker_equiv_range.dim_eq, dim_quotient_add_dim] end lemma dim_eq_of_surjective (f : V →ₗ[K] V₁) (h : surjective f) : module.rank K V = module.rank K V₁ + module.rank K f.ker := by rw [← dim_range_add_dim_ker f, ← dim_range_of_surjective f h] section variables [add_comm_group V₂] [module K V₂] variables [add_comm_group V₃] [module K V₃] open linear_map /-- This is mostly an auxiliary lemma for `dim_sup_add_dim_inf_eq`. -/ lemma dim_add_dim_split (db : V₂ →ₗ[K] V) (eb : V₃ →ₗ[K] V) (cd : V₁ →ₗ[K] V₂) (ce : V₁ →ₗ[K] V₃) (hde : ⊤ ≤ db.range ⊔ eb.range) (hgd : ker cd = ⊥) (eq : db.comp cd = eb.comp ce) (eq₂ : ∀d e, db d = eb e → (∃c, cd c = d ∧ ce c = e)) : module.rank K V + module.rank K V₁ = module.rank K V₂ + module.rank K V₃ := have hf : surjective (coprod db eb), by rwa [←range_eq_top, range_coprod, eq_top_iff], begin conv {to_rhs, rw [← dim_prod, dim_eq_of_surjective _ hf] }, congr' 1, apply linear_equiv.dim_eq, refine linear_equiv.of_bijective _ _ _, { refine cod_restrict _ (prod cd (- ce)) _, { assume c, simp only [add_eq_zero_iff_eq_neg, linear_map.prod_apply, mem_ker, pi.prod, coprod_apply, neg_neg, map_neg, neg_apply], exact linear_map.ext_iff.1 eq c } }, { rw [← ker_eq_bot, ker_cod_restrict, ker_prod, hgd, bot_inf_eq] }, { rw [← range_eq_top, eq_top_iff, range_cod_restrict, ← map_le_iff_le_comap, map_top, range_subtype], rintros ⟨d, e⟩, have h := eq₂ d (-e), simp only [add_eq_zero_iff_eq_neg, linear_map.prod_apply, mem_ker, set_like.mem_coe, prod.mk.inj_iff, coprod_apply, map_neg, neg_apply, linear_map.mem_range, pi.prod] at ⊢ h, assume hde, rcases h hde with ⟨c, h₁, h₂⟩, refine ⟨c, h₁, _⟩, rw [h₂, _root_.neg_neg] } end lemma dim_sup_add_dim_inf_eq (s t : submodule K V) : module.rank K (s ⊔ t : submodule K V) + module.rank K (s ⊓ t : submodule K V) = module.rank K s + module.rank K t := dim_add_dim_split (of_le le_sup_left) (of_le le_sup_right) (of_le inf_le_left) (of_le inf_le_right) begin rw [← map_le_map_iff' (ker_subtype $ s ⊔ t), map_sup, map_top, ← linear_map.range_comp, ← linear_map.range_comp, subtype_comp_of_le, subtype_comp_of_le, range_subtype, range_subtype, range_subtype], exact le_rfl end (ker_of_le _ _ _) begin ext ⟨x, hx⟩, refl end begin rintros ⟨b₁, hb₁⟩ ⟨b₂, hb₂⟩ eq, obtain rfl : b₁ = b₂ := congr_arg subtype.val eq, exact ⟨⟨b₁, hb₁, hb₂⟩, rfl, rfl⟩ end lemma dim_add_le_dim_add_dim (s t : submodule K V) : module.rank K (s ⊔ t : submodule K V) ≤ module.rank K s + module.rank K t := by { rw [← dim_sup_add_dim_inf_eq], exact self_le_add_right _ _ } end lemma exists_mem_ne_zero_of_dim_pos {s : submodule K V} (h : 0 < module.rank K s) : ∃ b : V, b ∈ s ∧ b ≠ 0 := exists_mem_ne_zero_of_ne_bot $ assume eq, by rw [eq, dim_bot] at h; exact lt_irrefl _ h end field section rank section variables [ring K] [add_comm_group V] [module K V] [add_comm_group V₁] [module K V₁] variables [add_comm_group V'] [module K V'] /-- `rank f` is the rank of a `linear_map f`, defined as the dimension of `f.range`. -/ def rank (f : V →ₗ[K] V') : cardinal := module.rank K f.range lemma rank_le_range (f : V →ₗ[K] V₁) : rank f ≤ module.rank K V₁ := dim_submodule_le _ @[simp] lemma rank_zero [nontrivial K] : rank (0 : V →ₗ[K] V') = 0 := by rw [rank, linear_map.range_zero, dim_bot] variables [add_comm_group V''] [module K V''] lemma rank_comp_le1 (g : V →ₗ[K] V') (f : V' →ₗ[K] V'') : rank (f.comp g) ≤ rank f := begin refine dim_le_of_submodule _ _ _, rw [linear_map.range_comp], exact linear_map.map_le_range, end variables [add_comm_group V'₁] [module K V'₁] lemma rank_comp_le2 (g : V →ₗ[K] V') (f : V' →ₗ[K] V'₁) : rank (f.comp g) ≤ rank g := by rw [rank, rank, linear_map.range_comp]; exact dim_map_le _ _ end section field variables [field K] [add_comm_group V] [module K V] [add_comm_group V₁] [module K V₁] variables [add_comm_group V'] [module K V'] lemma rank_le_domain (f : V →ₗ[K] V₁) : rank f ≤ module.rank K V := by { rw [← dim_range_add_dim_ker f], exact self_le_add_right _ _ } lemma rank_add_le (f g : V →ₗ[K] V') : rank (f + g) ≤ rank f + rank g := calc rank (f + g) ≤ module.rank K (f.range ⊔ g.range : submodule K V') : begin refine dim_le_of_submodule _ _ _, exact (linear_map.range_le_iff_comap.2 $ eq_top_iff'.2 $ assume x, show f x + g x ∈ (f.range ⊔ g.range : submodule K V'), from mem_sup.2 ⟨_, ⟨x, rfl⟩, _, ⟨x, rfl⟩, rfl⟩) end ... ≤ rank f + rank g : dim_add_le_dim_add_dim _ _ lemma rank_finset_sum_le {η} (s : finset η) (f : η → V →ₗ[K] V') : rank (∑ d in s, f d) ≤ ∑ d in s, rank (f d) := @finset.sum_hom_rel _ _ _ _ _ (λa b, rank a ≤ b) f (λ d, rank (f d)) s (le_of_eq rank_zero) (λ i g c h, le_trans (rank_add_le _ _) (add_le_add_left h _)) end field end rank section division_ring variables [division_ring K] [add_comm_group V] [module K V] [add_comm_group V'] [module K V'] /-- The `ι` indexed basis on `V`, where `ι` is an empty type and `V` is zero-dimensional. See also `finite_dimensional.fin_basis`. -/ def basis.of_dim_eq_zero {ι : Type*} [is_empty ι] (hV : module.rank K V = 0) : basis ι K V := begin haveI : subsingleton V := dim_zero_iff.1 hV, exact basis.empty _ end @[simp] lemma basis.of_dim_eq_zero_apply {ι : Type*} [is_empty ι] (hV : module.rank K V = 0) (i : ι) : basis.of_dim_eq_zero hV i = 0 := rfl lemma le_dim_iff_exists_linear_independent {c : cardinal} : c ≤ module.rank K V ↔ ∃ s : set V, #s = c ∧ linear_independent K (coe : s → V) := begin split, { intro h, let t := basis.of_vector_space K V, rw [← t.mk_eq_dim'', cardinal.le_mk_iff_exists_subset] at h, rcases h with ⟨s, hst, hsc⟩, exact ⟨s, hsc, (of_vector_space_index.linear_independent K V).mono hst⟩ }, { rintro ⟨s, rfl, si⟩, exact cardinal_le_dim_of_linear_independent si } end lemma le_dim_iff_exists_linear_independent_finset {n : ℕ} : ↑n ≤ module.rank K V ↔ ∃ s : finset V, s.card = n ∧ linear_independent K (coe : (s : set V) → V) := begin simp only [le_dim_iff_exists_linear_independent, cardinal.mk_eq_nat_iff_finset], split, { rintro ⟨s, ⟨t, rfl, rfl⟩, si⟩, exact ⟨t, rfl, si⟩ }, { rintro ⟨s, rfl, si⟩, exact ⟨s, ⟨s, rfl, rfl⟩, si⟩ } end /-- A vector space has dimension at most `1` if and only if there is a single vector of which all vectors are multiples. -/ lemma dim_le_one_iff : module.rank K V ≤ 1 ↔ ∃ v₀ : V, ∀ v, ∃ r : K, r • v₀ = v := begin let b := basis.of_vector_space K V, split, { intro hd, rw [← b.mk_eq_dim'', cardinal.le_one_iff_subsingleton, subsingleton_coe] at hd, rcases eq_empty_or_nonempty (of_vector_space_index K V) with hb | ⟨⟨v₀, hv₀⟩⟩, { use 0, have h' : ∀ v : V, v = 0, { simpa [hb, submodule.eq_bot_iff] using b.span_eq.symm }, intro v, simp [h' v] }, { use v₀, have h' : (K ∙ v₀) = ⊤, { simpa [hd.eq_singleton_of_mem hv₀] using b.span_eq }, intro v, have hv : v ∈ (⊤ : submodule K V) := mem_top, rwa [←h', mem_span_singleton] at hv } }, { rintros ⟨v₀, hv₀⟩, have h : (K ∙ v₀) = ⊤, { ext, simp [mem_span_singleton, hv₀] }, rw [←dim_top, ←h], convert dim_span_le _, simp } end /-- A submodule has dimension at most `1` if and only if there is a single vector in the submodule such that the submodule is contained in its span. -/ lemma dim_submodule_le_one_iff (s : submodule K V) : module.rank K s ≤ 1 ↔ ∃ v₀ ∈ s, s ≤ K ∙ v₀ := begin simp_rw [dim_le_one_iff, le_span_singleton_iff], split, { rintro ⟨⟨v₀, hv₀⟩, h⟩, use [v₀, hv₀], intros v hv, obtain ⟨r, hr⟩ := h ⟨v, hv⟩, use r, simp_rw [subtype.ext_iff, coe_smul, submodule.coe_mk] at hr, exact hr }, { rintro ⟨v₀, hv₀, h⟩, use ⟨v₀, hv₀⟩, rintro ⟨v, hv⟩, obtain ⟨r, hr⟩ := h v hv, use r, simp_rw [subtype.ext_iff, coe_smul, submodule.coe_mk], exact hr } end /-- A submodule has dimension at most `1` if and only if there is a single vector, not necessarily in the submodule, such that the submodule is contained in its span. -/ lemma dim_submodule_le_one_iff' (s : submodule K V) : module.rank K s ≤ 1 ↔ ∃ v₀, s ≤ K ∙ v₀ := begin rw dim_submodule_le_one_iff, split, { rintros ⟨v₀, hv₀, h⟩, exact ⟨v₀, h⟩ }, { rintros ⟨v₀, h⟩, by_cases hw : ∃ w : V, w ∈ s ∧ w ≠ 0, { rcases hw with ⟨w, hw, hw0⟩, use [w, hw], rcases mem_span_singleton.1 (h hw) with ⟨r', rfl⟩, have h0 : r' ≠ 0, { rintro rfl, simpa using hw0 }, rwa span_singleton_smul_eq (is_unit.mk0 _ h0) _ }, { push_neg at hw, rw ←submodule.eq_bot_iff at hw, simp [hw] } } end lemma submodule.rank_le_one_iff_is_principal (W : submodule K V) : module.rank K W ≤ 1 ↔ W.is_principal := begin simp only [dim_le_one_iff, submodule.is_principal_iff, le_antisymm_iff, le_span_singleton_iff, span_singleton_le_iff_mem], split, { rintro ⟨⟨m, hm⟩, hm'⟩, choose f hf using hm', exact ⟨m, ⟨λ v hv, ⟨f ⟨v, hv⟩, congr_arg coe (hf ⟨v, hv⟩)⟩, hm⟩⟩ }, { rintro ⟨a, ⟨h, ha⟩⟩, choose f hf using h, exact ⟨⟨a, ha⟩, λ v, ⟨f v.1 v.2, subtype.ext (hf v.1 v.2)⟩⟩ } end lemma module.rank_le_one_iff_top_is_principal : module.rank K V ≤ 1 ↔ (⊤ : submodule K V).is_principal := by rw [← submodule.rank_le_one_iff_is_principal, dim_top] end division_ring section field variables [field K] [add_comm_group V] [module K V] [add_comm_group V'] [module K V'] lemma le_rank_iff_exists_linear_independent {c : cardinal} {f : V →ₗ[K] V'} : c ≤ rank f ↔ ∃ s : set V, cardinal.lift.{v'} (#s) = cardinal.lift.{v} c ∧ linear_independent K (λ x : s, f x) := begin rcases f.range_restrict.exists_right_inverse_of_surjective f.range_range_restrict with ⟨g, hg⟩, have fg : left_inverse f.range_restrict g, from linear_map.congr_fun hg, refine ⟨λ h, _, _⟩, { rcases le_dim_iff_exists_linear_independent.1 h with ⟨s, rfl, si⟩, refine ⟨g '' s, cardinal.mk_image_eq_lift _ _ fg.injective, _⟩, replace fg : ∀ x, f (g x) = x, by { intro x, convert congr_arg subtype.val (fg x) }, replace si : linear_independent K (λ x : s, f (g x)), by simpa only [fg] using si.map' _ (ker_subtype _), exact si.image_of_comp s g f }, { rintro ⟨s, hsc, si⟩, have : linear_independent K (λ x : s, f.range_restrict x), from linear_independent.of_comp (f.range.subtype) (by convert si), convert cardinal_le_dim_of_linear_independent this.image, rw [← cardinal.lift_inj, ← hsc, cardinal.mk_image_eq_of_inj_on_lift], exact inj_on_iff_injective.2 this.injective } end lemma le_rank_iff_exists_linear_independent_finset {n : ℕ} {f : V →ₗ[K] V'} : ↑n ≤ rank f ↔ ∃ s : finset V, s.card = n ∧ linear_independent K (λ x : (s : set V), f x) := begin simp only [le_rank_iff_exists_linear_independent, cardinal.lift_nat_cast, cardinal.lift_eq_nat_iff, cardinal.mk_eq_nat_iff_finset], split, { rintro ⟨s, ⟨t, rfl, rfl⟩, si⟩, exact ⟨t, rfl, si⟩ }, { rintro ⟨s, rfl, si⟩, exact ⟨s, ⟨s, rfl, rfl⟩, si⟩ } end end field end module
c6162d6f14b0bdf39de33e9eaa9daa06ba69f1b9
367134ba5a65885e863bdc4507601606690974c1
/src/ring_theory/flat.lean
6cd8b28961f26e94ffcaf890449273b14bc66c80
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
2,638
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import linear_algebra.dimension import ring_theory.noetherian import ring_theory.algebra_tower /-! # Flat modules A module `M` over a commutative ring `R` is *flat* if for all finitely generated ideals `I` of `R`, the canonical map `I ⊗ M →ₗ M` is injective. This is equivalent to the claim that for all injective `R`-linear maps `f : M₁ → M₂` the induced map `M₁ ⊗ M → M₂ ⊗ M` is injective. See <https://stacks.math.columbia.edu/tag/00HD>. This result is not yet formalised. ## Main declaration * `module.flat`: the predicate asserting that an `R`-module `M` is flat. ## TODO * Show that tensoring with a flat module preserves injective morphisms. Show that this is equivalent to be flat. See <https://stacks.math.columbia.edu/tag/00HD>. To do this, it is probably a good idea to think about a suitable categorical induction principle that should be applied to the category of `R`-modules, and that will take care of the administrative side of the proof. * Define flat `R`-algebras * Define flat ring homomorphisms - Show that the identity is flat - Show that composition of flat morphisms is flat * Show that flatness is stable under base change (aka extension of scalars) For base change, it will be very useful to have a "characteristic predicate" instead of relying on the construction `A ⊗ B`. Indeed, such a predicate should allow us to treat both `polynomial A` and `A ⊗ polynomial R` as the base change of `polynomial R` to `A`. (Similar examples exist with `fin n → R`, `R × R`, `ℤ[i] ⊗ ℝ`, etc...) * Generalize flatness to noncommutative rings. -/ namespace module open function (injective) open linear_map (lsmul) open_locale tensor_product /-- An `R`-module `M` is flat if for all finitely generated ideals `I` of `R`, the canonical map `I ⊗ M →ₗ M` is injective. -/ @[class] def flat (R M : Type*) [comm_ring R] [add_comm_group M] [module R M] : Prop := ∀ ⦃I : ideal R⦄ (hI : I.fg), injective (tensor_product.lift ((lsmul R M).comp I.subtype)) namespace flat open tensor_product linear_map submodule instance self (R : Type*) [comm_ring R] : flat R R := begin intros I hI, rw ← equiv.injective_comp (tensor_product.rid R I).symm.to_equiv, convert subtype.coe_injective using 1, ext x, simp only [function.comp_app, linear_equiv.coe_to_equiv, rid_symm_apply, comp_apply, mul_one, lift.tmul, subtype_apply, algebra.id.smul_eq_mul, lsmul_apply] end end flat end module
c50d8037d1575b6c2efa2aedecbbf7f50df42350
0845ae2ca02071debcfd4ac24be871236c01784f
/tests/lean/run/coroutine.lean
fabd2fca3e6d57df18259036d8460ba9de227433
[ "Apache-2.0" ]
permissive
GaloisInc/lean4
74c267eb0e900bfaa23df8de86039483ecbd60b7
228ddd5fdcd98dd4e9c009f425284e86917938aa
refs/heads/master
1,643,131,356,301
1,562,715,572,000
1,562,715,572,000
192,390,898
0
0
null
1,560,792,750,000
1,560,792,749,000
null
UTF-8
Lean
false
false
7,515
lean
universes u v w r s inductive coroutineResultCore (coroutine : Type (max u v w)) (α : Type u) (δ : Type v) (β : Type w) : Type (max u v w) | done {} : β → coroutineResultCore | yielded {} : δ → coroutine → coroutineResultCore /-- Asymmetric coroutines `coroutine α δ β` takes inputs of Type `α`, yields elements of Type `δ`, and produces an element of Type `β`. Asymmetric coroutines are so called because they involve two types of control transfer operations: one for resuming/invoking a coroutine and one for suspending it, the latter returning control to the coroutine invoker. An asymmetric coroutine can be regarded as subordinate to its caller, the relationship between them being similar to that between a called and a calling routine. -/ inductive coroutine (α : Type u) (δ : Type v) (β : Type w) : Type (max u v w) | mk {} : (α → coroutineResultCore coroutine α δ β) → coroutine abbreviation coroutineResult (α : Type u) (δ : Type v) (β : Type w) : Type (max u v w) := coroutineResultCore (coroutine α δ β) α δ β namespace coroutine variables {α : Type u} {δ : Type v} {β γ : Type w} export coroutineResultCore (done yielded) /-- `resume c a` resumes/invokes the coroutine `c` with input `a`. -/ @[inline] def resume : coroutine α δ β → α → coroutineResult α δ β | (mk k) a := k a @[inline] protected def pure (b : β) : coroutine α δ β := mk $ fun _ => done b /-- Read the input argument passed to the coroutine. Remark: should we use a different Name? I added an instance [MonadReader] later. -/ @[inline] protected def read : coroutine α δ α := mk $ fun a => done a /-- Run nested coroutine with transformed input argument. Like `ReaderT.adapt`, but cannot change the input Type. -/ @[inline] protected def adapt (f : α → α) (c : coroutine α δ β) : coroutine α δ β := mk $ fun a => c.resume (f a) /-- Return the control to the invoker with Result `d` -/ @[inline] protected def yield (d : δ) : coroutine α δ PUnit := mk $ fun a => yielded d (coroutine.pure ⟨⟩) /- TODO(Leo): following relations have been commented because Lean4 is currently accepting non-terminating programs. /-- Auxiliary relation for showing that bind/pipe terminate -/ inductive directSubcoroutine : coroutine α δ β → coroutine α δ β → Prop | mk : ∀ (k : α → coroutineResult α δ β) (a : α) (d : δ) (c : coroutine α δ β), k a = yielded d c → directSubcoroutine c (mk k) theorem directSubcoroutineWf : WellFounded (@directSubcoroutine α δ β) := begin Constructor, intro c, apply @coroutine.ind _ _ _ (fun c => Acc directSubcoroutine c) (fun r => ∀ (d : δ) (c : coroutine α δ β), r = yielded d c → Acc directSubcoroutine c), { intros k ih, dsimp at ih, Constructor, intros c' h, cases h, apply ih hA hD, assumption }, { intros, contradiction }, { intros d c ih d₁ c₁ Heq, injection Heq, subst c, assumption } end /-- Transitive closure of directSubcoroutine. It is not used here, but may be useful when defining more complex procedures. -/ def subcoroutine : coroutine α δ β → coroutine α δ β → Prop := Tc directSubcoroutine theorem subcoroutineWf : WellFounded (@subcoroutine α δ β) := Tc.wf directSubcoroutineWf -- Local instances for proving termination by well founded relation def bindWfInst : HasWellFounded (Σ' a : coroutine α δ β, (β → coroutine α δ γ)) := { r := Psigma.Lex directSubcoroutine (fun _ => emptyRelation), wf := Psigma.lexWf directSubcoroutineWf (fun _ => emptyWf) } def pipeWfInst : HasWellFounded (Σ' a : coroutine α δ β, coroutine δ γ β) := { r := Psigma.Lex directSubcoroutine (fun _ => emptyRelation), wf := Psigma.lexWf directSubcoroutineWf (fun _ => emptyWf) } local attribute [instance] wfInst₁ wfInst₂ open wellFoundedTactics -/ /- TODO: remove `unsafe` keyword after we restore well-founded recursion -/ @[inlineIfReduce] protected unsafe def bind : coroutine α δ β → (β → coroutine α δ γ) → coroutine α δ γ | (mk k) f := mk $ fun a => match k a, rfl : ∀ (n : _), n = k a → _ with | done b, _ => coroutine.resume (f b) a | yielded d c, h => -- have directSubcoroutine c (mk k), { apply directSubcoroutine.mk k a d, rw h }, yielded d (bind c f) -- usingWellFounded { decTac := unfoldWfRel >> processLex (tactic.assumption) } unsafe def pipe : coroutine α δ β → coroutine δ γ β → coroutine α γ β | (mk k₁) (mk k₂) := mk $ fun a => match k₁ a, rfl : ∀ (n : _), n = k₁ a → _ with | done b, h => done b | yielded d k₁', h => match k₂ d with | done b => done b | yielded r k₂' => -- have directSubcoroutine k₁' (mk k₁), { apply directSubcoroutine.mk k₁ a d, rw h }, yielded r (pipe k₁' k₂') -- usingWellFounded { decTac := unfoldWfRel >> processLex (tactic.assumption) } private unsafe def finishAux (f : δ → α) : coroutine α δ β → α → List δ → List δ × β | (mk k) a ds := match k a with | done b => (ds.reverse, b) | yielded d k' => finishAux k' (f d) (d::ds) /-- Run a coroutine to completion, feeding back yielded items after transforming them with `f`. -/ unsafe def finish (f : δ → α) : coroutine α δ β → α → List δ × β := fun k a => finishAux f k a [] unsafe instance : Monad (coroutine α δ) := { pure := @coroutine.pure _ _, bind := @coroutine.bind _ _ } unsafe instance : MonadReader α (coroutine α δ) := { read := @coroutine.read _ _ } end coroutine /-- Auxiliary class for lifiting `yield` -/ class monadCoroutine (α : outParam (Type u)) (δ : outParam (Type v)) (m : Type w → Type r) := (yield {} : δ → m PUnit) instance (α : Type u) (δ : Type v) : monadCoroutine α δ (coroutine α δ) := { yield := coroutine.yield } instance monadCoroutineTrans (α : Type u) (δ : Type v) (m : Type w → Type r) (n : Type w → Type s) [HasMonadLift m n] [monadCoroutine α δ m] : monadCoroutine α δ n := { yield := fun d => monadLift (monadCoroutine.yield d : m _) } export monadCoroutine (yield) open coroutine namespace ex1 inductive tree (α : Type u) | leaf {} : tree | Node : tree → α → tree → tree /-- Coroutine as generators/iterators -/ unsafe def visit {α : Type v} : tree α → coroutine Unit α Unit | tree.leaf := pure () | (tree.Node l a r) := do visit l; yield a; visit r unsafe def tst {α : Type} [HasToString α] (t : tree α) : ExceptT String IO Unit := do c ← pure $ visit t; (yielded v₁ c) ← pure $ resume c (); (yielded v₂ c) ← pure $ resume c (); IO.println $ toString v₁; IO.println $ toString v₂; pure () -- #eval tst (tree.Node (tree.Node (tree.Node tree.leaf 5 tree.leaf) 10 (tree.Node tree.leaf 20 tree.leaf)) 30 tree.leaf) end ex1 namespace ex2 unsafe def ex : StateT Nat (coroutine Nat String) Unit := do x ← read; y ← get; set (y+5); yield ("1) val: " ++ toString (x+y)); x ← read; y ← get; yield ("2) val: " ++ toString (x+y)); pure () unsafe def tst2 : ExceptT String IO Unit := do let c := StateT.run ex 5; (yielded r c₁) ← pure $ resume c 10; IO.println r; (yielded r c₂) ← pure $ resume c₁ 20; IO.println r; (done _) ← pure $ resume c₂ 30; (yielded r c₃) ← pure $ resume c₁ 100; IO.println r; IO.println "done"; pure () -- #eval tst2 end ex2
bc13f4503bfea5ddddeae02e3d75fba8431d7e5b
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/option/basic.lean
05ce14a3248184eb1dd0c5acf2dc60e73836bbc4
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
7,418
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 tactic.basic namespace option variables {α : Type*} {β : Type*} {γ : Type*} lemma some_ne_none (x : α) : some x ≠ none := λ h, option.no_confusion h @[simp] theorem get_mem : ∀ {o : option α} (h : is_some o), option.get h ∈ o | (some a) _ := rfl theorem get_of_mem {a : α} : ∀ {o : option α} (h : is_some o), a ∈ o → option.get h = a | _ _ rfl := rfl @[simp] lemma not_mem_none (a : α) : a ∉ (none : option α) := λ h, option.no_confusion h @[simp] lemma some_get : ∀ {x : option α} (h : is_some x), some (option.get h) = x | (some x) hx := rfl @[simp] lemma get_some (x : α) (h : is_some (some x)) : option.get h = x := rfl @[simp] lemma get_or_else_some (x y : α) : option.get_or_else (some x) y = x := rfl lemma get_or_else_of_ne_none {x : option α} (hx : x ≠ none) (y : α) : some (x.get_or_else y) = x := by cases x; [contradiction, rw get_or_else_some] theorem mem_unique {o : option α} {a b : α} (ha : a ∈ o) (hb : b ∈ o) : a = b := option.some.inj $ ha.symm.trans hb theorem some_injective (α : Type*) : function.injective (@some α) := λ _ _, some_inj.mp /-- `option.map f` is injective if `f` is injective. -/ theorem map_injective {f : α → β} (Hf : function.injective f) : function.injective (option.map f) | none none H := rfl | (some a₁) (some a₂) H := by rw Hf (option.some.inj H) @[ext] theorem ext : ∀ {o₁ o₂ : option α}, (∀ a, a ∈ o₁ ↔ a ∈ o₂) → o₁ = o₂ | none none H := rfl | (some a) o H := ((H _).1 rfl).symm | o (some b) H := (H _).2 rfl theorem eq_none_iff_forall_not_mem {o : option α} : o = none ↔ (∀ a, a ∉ o) := ⟨λ e a h, by rw e at h; cases h, λ h, ext $ by simpa⟩ @[simp] theorem none_bind {α β} (f : α → option β) : none >>= f = none := rfl @[simp] theorem some_bind {α β} (a : α) (f : α → option β) : some a >>= f = f a := rfl @[simp] theorem none_bind' (f : α → option β) : none.bind f = none := rfl @[simp] theorem some_bind' (a : α) (f : α → option β) : (some a).bind f = f a := rfl @[simp] theorem bind_some : ∀ x : option α, x >>= some = x := @bind_pure α option _ _ @[simp] theorem bind_eq_some {α β} {x : option α} {f : α → option β} {b : β} : x >>= f = some b ↔ ∃ a, x = some a ∧ f a = some b := by cases x; simp @[simp] theorem bind_eq_some' {x : option α} {f : α → option β} {b : β} : x.bind f = some b ↔ ∃ a, x = some a ∧ f a = some b := by cases x; simp @[simp] theorem bind_eq_none' {o : option α} {f : α → option β} : o.bind f = none ↔ (∀ b a, a ∈ o → b ∉ f a) := by simp only [eq_none_iff_forall_not_mem, not_exists, not_and, mem_def, bind_eq_some'] @[simp] theorem bind_eq_none {α β} {o : option α} {f : α → option β} : o >>= f = none ↔ (∀ b a, a ∈ o → b ∉ f a) := bind_eq_none' lemma bind_comm {α β γ} {f : α → β → option γ} (a : option α) (b : option β) : a.bind (λx, b.bind (f x)) = b.bind (λy, a.bind (λx, f x y)) := by cases a; cases b; refl lemma bind_assoc (x : option α) (f : α → option β) (g : β → option γ) : (x.bind f).bind g = x.bind (λ y, (f y).bind g) := by cases x; refl @[simp] theorem map_none {α β} {f : α → β} : f <$> none = none := rfl @[simp] theorem map_some {α β} {a : α} {f : α → β} : f <$> some a = some (f a) := rfl @[simp] theorem map_none' {f : α → β} : option.map f none = none := rfl @[simp] theorem map_some' {a : α} {f : α → β} : option.map f (some a) = some (f a) := rfl @[simp] theorem map_eq_some {α β} {x : option α} {f : α → β} {b : β} : f <$> x = some b ↔ ∃ a, x = some a ∧ f a = b := by cases x; simp @[simp] theorem map_eq_some' {x : option α} {f : α → β} {b : β} : x.map f = some b ↔ ∃ a, x = some a ∧ f a = b := by cases x; simp @[simp] theorem map_id' : option.map (@id α) = id := map_id @[simp] theorem seq_some {α β} {a : α} {f : α → β} : some f <*> some a = some (f a) := rfl @[simp] theorem some_orelse' (a : α) (x : option α) : (some a).orelse x = some a := rfl @[simp] theorem some_orelse (a : α) (x : option α) : (some a <|> x) = some a := rfl @[simp] theorem none_orelse' (x : option α) : none.orelse x = x := by cases x; refl @[simp] theorem none_orelse (x : option α) : (none <|> x) = x := none_orelse' x @[simp] theorem orelse_none' (x : option α) : x.orelse none = x := by cases x; refl @[simp] theorem orelse_none (x : option α) : (x <|> none) = x := orelse_none' x @[simp] theorem is_some_none : @is_some α none = ff := rfl @[simp] theorem is_some_some {a : α} : is_some (some a) = tt := rfl theorem is_some_iff_exists {x : option α} : is_some x ↔ ∃ a, x = some a := by cases x; simp [is_some]; exact ⟨_, rfl⟩ @[simp] theorem is_none_none : @is_none α none = tt := rfl @[simp] theorem is_none_some {a : α} : is_none (some a) = ff := rfl @[simp] theorem not_is_some {a : option α} : is_some a = ff ↔ a.is_none = tt := by cases a; simp lemma eq_some_iff_get_eq {o : option α} {a : α} : o = some a ↔ ∃ h : o.is_some, option.get h = a := by cases o; simp lemma not_is_some_iff_eq_none {o : option α} : ¬o.is_some ↔ o = none := by cases o; simp lemma ne_none_iff_is_some {o : option α} : o ≠ none ↔ o.is_some := by cases o; simp lemma bex_ne_none {p : option α → Prop} : (∃ x ≠ none, p x) ↔ ∃ x, p (some x) := ⟨λ ⟨x, hx, hp⟩, ⟨get $ ne_none_iff_is_some.1 hx, by rwa [some_get]⟩, λ ⟨x, hx⟩, ⟨some x, some_ne_none x, hx⟩⟩ lemma ball_ne_none {p : option α → Prop} : (∀ x ≠ none, p x) ↔ ∀ x, p (some x) := ⟨λ h x, h (some x) (some_ne_none x), λ h x hx, by simpa only [some_get] using h (get $ ne_none_iff_is_some.1 hx)⟩ theorem iget_mem [inhabited α] : ∀ {o : option α}, is_some o → o.iget ∈ o | (some a) _ := rfl theorem iget_of_mem [inhabited α] {a : α} : ∀ {o : option α}, a ∈ o → o.iget = a | _ rfl := rfl @[simp] theorem guard_eq_some {p : α → Prop} [decidable_pred p] {a b : α} : guard p a = some b ↔ a = b ∧ p a := by by_cases p a; simp [option.guard, h]; intro; contradiction @[simp] theorem guard_eq_some' {p : Prop} [decidable p] : ∀ u, _root_.guard p = some u ↔ p | () := by by_cases p; simp [guard, h, pure]; intro; contradiction theorem lift_or_get_choice {f : α → α → α} (h : ∀ a b, f a b = a ∨ f a b = b) : ∀ o₁ o₂, lift_or_get f o₁ o₂ = o₁ ∨ lift_or_get f o₁ o₂ = o₂ | none none := or.inl rfl | (some a) none := or.inl rfl | none (some b) := or.inr rfl | (some a) (some b) := by simpa [lift_or_get] using h a b @[simp] lemma lift_or_get_none_left {f} {b : option α} : lift_or_get f none b = b := by cases b; refl @[simp] lemma lift_or_get_none_right {f} {a : option α} : lift_or_get f a none = a := by cases a; refl @[simp] lemma lift_or_get_some_some {f} {a b : α} : lift_or_get f (some a) (some b) = f a b := rfl /-- given an element of `a : option α`, a default element `b : β` and a function `α → β`, apply this function to `a` if it comes from `α`, and return `b` otherwise. -/ def cases_on' : option α → β → (α → β) → β | none n s := n | (some a) n s := s a end option
9ad896f456b709819e953b9ee6fd7a084c5417df
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/mv_polynomial/tower.lean
ddfee025e79096a0cd6eff3bf48f80c0b44912ad
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
2,569
lean
/- Copyright (c) 2022 Yuyang Zhao. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yuyang Zhao -/ import algebra.algebra.tower import data.mv_polynomial.basic /-! # Algebra towers for multivariate polynomial > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file proves some basic results about the algebra tower structure for the type `mv_polynomial σ R`. This structure itself is provided elsewhere as `mv_polynomial.is_scalar_tower` When you update this file, you can also try to make a corresponding update in `ring_theory.polynomial.tower`. -/ variables (R A B : Type*) {σ : Type*} namespace mv_polynomial section semiring variables [comm_semiring R] [comm_semiring A] [comm_semiring B] variables [algebra R A] [algebra A B] [algebra R B] variables [is_scalar_tower R A B] variables {R B} theorem aeval_map_algebra_map (x : σ → B) (p : mv_polynomial σ R) : aeval x (map (algebra_map R A) p) = aeval x p := by rw [aeval_def, aeval_def, eval₂_map, is_scalar_tower.algebra_map_eq R A B] end semiring section comm_semiring variables [comm_semiring R] [comm_semiring A] [comm_semiring B] variables [algebra R A] [algebra A B] [algebra R B] [is_scalar_tower R A B] variables {R A} lemma aeval_algebra_map_apply (x : σ → A) (p : mv_polynomial σ R) : aeval (algebra_map A B ∘ x) p = algebra_map A B (mv_polynomial.aeval x p) := by rw [aeval_def, aeval_def, ← coe_eval₂_hom, ← coe_eval₂_hom, map_eval₂_hom, ←is_scalar_tower.algebra_map_eq] lemma aeval_algebra_map_eq_zero_iff [no_zero_smul_divisors A B] [nontrivial B] (x : σ → A) (p : mv_polynomial σ R) : aeval (algebra_map A B ∘ x) p = 0 ↔ aeval x p = 0 := by rw [aeval_algebra_map_apply, algebra.algebra_map_eq_smul_one, smul_eq_zero, iff_false_intro (one_ne_zero' B), or_false] lemma aeval_algebra_map_eq_zero_iff_of_injective {x : σ → A} {p : mv_polynomial σ R} (h : function.injective (algebra_map A B)) : aeval (algebra_map A B ∘ x) p = 0 ↔ aeval x p = 0 := by rw [aeval_algebra_map_apply, ← (algebra_map A B).map_zero, h.eq_iff] end comm_semiring end mv_polynomial namespace subalgebra open mv_polynomial section comm_semiring variables {R A} [comm_semiring R] [comm_semiring A] [algebra R A] @[simp] lemma mv_polynomial_aeval_coe (S : subalgebra R A) (x : σ → S) (p : mv_polynomial σ R) : aeval (λ i, (x i : A)) p = aeval x p := by convert aeval_algebra_map_apply A x p end comm_semiring end subalgebra
04c7dd30463caba876c18827fe27162ab8867111
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/elab8.lean
bd447c76a56beca63a05ca40a076b78170fe724b
[ "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
379
lean
set_option pp.notation false set_option pp.implicit true set_option pp.numerals false set_option pp.binder_types true #check λ (A : Type*) [has_add A] [has_one A] [has_lt A] (a : A), a + 1 #check λ (A : Type*) [has_add A] [has_one A] [has_lt A] (a : A) (H : a > 1), a + 1 #check λ (A : Type*) [has_add A] [has_one A] [has_lt A] (a : A) (H₁ : a > 1) (H₂ : a < 5), a + 1
038cf6421c82e46695d404e59c850d55a7fcab17
7cef822f3b952965621309e88eadf618da0c8ae9
/src/category_theory/monad/types.lean
c7063af322bb075ad9d65889f5bdca0bf59e2232
[ "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
956
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 -/ import category_theory.monad.basic import category_theory.types /-! # Convert from `monad` (i.e. Lean's `Type`-based monads) to `category_theory.monad` This allows us to use these monads in category theory. -/ namespace category_theory section universes u variables (m : Type u → Type u) [_root_.monad m] [is_lawful_monad m] instance : monad (of_type_functor m) := { η := ⟨@pure m _, assume α β f, (is_lawful_applicative.map_comp_pure m f).symm ⟩, μ := ⟨@mjoin m _, assume α β (f : α → β), funext $ assume a, mjoin_map_map f a ⟩, assoc' := assume α, funext $ assume a, mjoin_map_mjoin a, left_unit' := assume α, funext $ assume a, mjoin_pure a, right_unit' := assume α, funext $ assume a, mjoin_map_pure a } end end category_theory
1d099c2cb89b57aa0dd80a7596756cd9be9002ec
d1bbf1801b3dcb214451d48214589f511061da63
/src/data/zsqrtd/gaussian_int.lean
6a42e6909c7e7ee2f4882efc613f9f730e13cf59
[ "Apache-2.0" ]
permissive
cheraghchi/mathlib
5c366f8c4f8e66973b60c37881889da8390cab86
f29d1c3038422168fbbdb2526abf7c0ff13e86db
refs/heads/master
1,676,577,831,283
1,610,894,638,000
1,610,894,638,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,726
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Chris Hughes -/ import data.zsqrtd.basic import data.complex.basic import ring_theory.principal_ideal_domain import number_theory.quadratic_reciprocity /-! # Gaussian integers The Gaussian integers are complex integer, complex numbers whose real and imaginary parts are both integers. ## Main definitions The Euclidean domain structure on `ℤ[i]` is defined in this file. The homomorphism `to_complex` into the complex numbers is also defined in this file. ## Main statements `prime_iff_mod_four_eq_three_of_nat_prime` A prime natural number is prime in `ℤ[i]` if and only if it is `3` mod `4` ## Notations This file uses the local notation `ℤ[i]` for `gaussian_int` ## Implementation notes Gaussian integers are implemented using the more general definition `zsqrtd`, the type of integers adjoined a square root of `d`, in this case `-1`. The definition is reducible, so that properties and definitions about `zsqrtd` can easily be used. -/ open zsqrtd complex @[reducible] def gaussian_int : Type := zsqrtd (-1) local notation `ℤ[i]` := gaussian_int namespace gaussian_int instance : has_repr ℤ[i] := ⟨λ x, "⟨" ++ repr x.re ++ ", " ++ repr x.im ++ "⟩"⟩ instance : comm_ring ℤ[i] := zsqrtd.comm_ring section local attribute [-instance] complex.field -- Avoid making things noncomputable unnecessarily. /-- The embedding of the Gaussian integers into the complex numbers, as a ring homomorphism. -/ def to_complex : ℤ[i] →+* ℂ := begin refine_struct { to_fun := λ x : ℤ[i], (x.re + x.im * I : ℂ), .. }; intros; apply complex.ext; dsimp; norm_cast; simp; abel end end instance : has_coe (ℤ[i]) ℂ := ⟨to_complex⟩ lemma to_complex_def (x : ℤ[i]) : (x : ℂ) = x.re + x.im * I := rfl lemma to_complex_def' (x y : ℤ) : ((⟨x, y⟩ : ℤ[i]) : ℂ) = x + y * I := by simp [to_complex_def] lemma to_complex_def₂ (x : ℤ[i]) : (x : ℂ) = ⟨x.re, x.im⟩ := by apply complex.ext; simp [to_complex_def] @[simp] lemma to_real_re (x : ℤ[i]) : ((x.re : ℤ) : ℝ) = (x : ℂ).re := by simp [to_complex_def] @[simp] lemma to_real_im (x : ℤ[i]) : ((x.im : ℤ) : ℝ) = (x : ℂ).im := by simp [to_complex_def] @[simp] lemma to_complex_re (x y : ℤ) : ((⟨x, y⟩ : ℤ[i]) : ℂ).re = x := by simp [to_complex_def] @[simp] lemma to_complex_im (x y : ℤ) : ((⟨x, y⟩ : ℤ[i]) : ℂ).im = y := by simp [to_complex_def] @[simp] lemma to_complex_add (x y : ℤ[i]) : ((x + y : ℤ[i]) : ℂ) = x + y := to_complex.map_add _ _ @[simp] lemma to_complex_mul (x y : ℤ[i]) : ((x * y : ℤ[i]) : ℂ) = x * y := to_complex.map_mul _ _ @[simp] lemma to_complex_one : ((1 : ℤ[i]) : ℂ) = 1 := to_complex.map_one @[simp] lemma to_complex_zero : ((0 : ℤ[i]) : ℂ) = 0 := to_complex.map_zero @[simp] lemma to_complex_neg (x : ℤ[i]) : ((-x : ℤ[i]) : ℂ) = -x := to_complex.map_neg _ @[simp] lemma to_complex_sub (x y : ℤ[i]) : ((x - y : ℤ[i]) : ℂ) = x - y := to_complex.map_sub _ _ @[simp] lemma to_complex_inj {x y : ℤ[i]} : (x : ℂ) = y ↔ x = y := by cases x; cases y; simp [to_complex_def₂] @[simp] lemma to_complex_eq_zero {x : ℤ[i]} : (x : ℂ) = 0 ↔ x = 0 := by rw [← to_complex_zero, to_complex_inj] @[simp] lemma nat_cast_real_norm (x : ℤ[i]) : (x.norm : ℝ) = (x : ℂ).norm_sq := by rw [norm, norm_sq]; simp @[simp] lemma nat_cast_complex_norm (x : ℤ[i]) : (x.norm : ℂ) = (x : ℂ).norm_sq := by cases x; rw [norm, norm_sq]; simp lemma norm_nonneg (x : ℤ[i]) : 0 ≤ norm x := norm_nonneg (by norm_num) _ @[simp] lemma norm_eq_zero {x : ℤ[i]} : norm x = 0 ↔ x = 0 := by rw [← @int.cast_inj ℝ _ _ _]; simp lemma norm_pos {x : ℤ[i]} : 0 < norm x ↔ x ≠ 0 := by rw [lt_iff_le_and_ne, ne.def, eq_comm, norm_eq_zero]; simp [norm_nonneg] @[simp] lemma coe_nat_abs_norm (x : ℤ[i]) : (x.norm.nat_abs : ℤ) = x.norm := int.nat_abs_of_nonneg (norm_nonneg _) @[simp] lemma nat_cast_nat_abs_norm {α : Type*} [ring α] (x : ℤ[i]) : (x.norm.nat_abs : α) = x.norm := by rw [← int.cast_coe_nat, coe_nat_abs_norm] lemma nat_abs_norm_eq (x : ℤ[i]) : x.norm.nat_abs = x.re.nat_abs * x.re.nat_abs + x.im.nat_abs * x.im.nat_abs := int.coe_nat_inj $ begin simp, simp [norm] end protected def div (x y : ℤ[i]) : ℤ[i] := let n := (rat.of_int (norm y))⁻¹ in let c := y.conj in ⟨round (rat.of_int (x * c).re * n : ℚ), round (rat.of_int (x * c).im * n : ℚ)⟩ instance : has_div ℤ[i] := ⟨gaussian_int.div⟩ lemma div_def (x y : ℤ[i]) : x / y = ⟨round ((x * conj y).re / norm y : ℚ), round ((x * conj y).im / norm y : ℚ)⟩ := show zsqrtd.mk _ _ = _, by simp [rat.of_int_eq_mk, rat.mk_eq_div, div_eq_mul_inv] lemma to_complex_div_re (x y : ℤ[i]) : ((x / y : ℤ[i]) : ℂ).re = round ((x / y : ℂ).re) := by rw [div_def, ← @rat.cast_round ℝ _ _]; simp [-rat.cast_round, mul_assoc, div_eq_mul_inv, mul_add, add_mul] lemma to_complex_div_im (x y : ℤ[i]) : ((x / y : ℤ[i]) : ℂ).im = round ((x / y : ℂ).im) := by rw [div_def, ← @rat.cast_round ℝ _ _, ← @rat.cast_round ℝ _ _]; simp [-rat.cast_round, mul_assoc, div_eq_mul_inv, mul_add, add_mul] local notation `abs'` := _root_.abs lemma norm_sq_le_norm_sq_of_re_le_of_im_le {x y : ℂ} (hre : abs' x.re ≤ abs' y.re) (him : abs' x.im ≤ abs' y.im) : x.norm_sq ≤ y.norm_sq := by rw [norm_sq_apply, norm_sq_apply, ← _root_.abs_mul_self, _root_.abs_mul, ← _root_.abs_mul_self y.re, _root_.abs_mul y.re, ← _root_.abs_mul_self x.im, _root_.abs_mul x.im, ← _root_.abs_mul_self y.im, _root_.abs_mul y.im]; exact (add_le_add (mul_self_le_mul_self (abs_nonneg _) hre) (mul_self_le_mul_self (abs_nonneg _) him)) lemma norm_sq_div_sub_div_lt_one (x y : ℤ[i]) : ((x / y : ℂ) - ((x / y : ℤ[i]) : ℂ)).norm_sq < 1 := calc ((x / y : ℂ) - ((x / y : ℤ[i]) : ℂ)).norm_sq = ((x / y : ℂ).re - ((x / y : ℤ[i]) : ℂ).re + ((x / y : ℂ).im - ((x / y : ℤ[i]) : ℂ).im) * I : ℂ).norm_sq : congr_arg _ $ by apply complex.ext; simp ... ≤ (1 / 2 + 1 / 2 * I).norm_sq : have abs' (2⁻¹ : ℝ) = 2⁻¹, from _root_.abs_of_nonneg (by norm_num), norm_sq_le_norm_sq_of_re_le_of_im_le (by rw [to_complex_div_re]; simp [norm_sq, this]; simpa using abs_sub_round (x / y : ℂ).re) (by rw [to_complex_div_im]; simp [norm_sq, this]; simpa using abs_sub_round (x / y : ℂ).im) ... < 1 : by simp [norm_sq]; norm_num protected def mod (x y : ℤ[i]) : ℤ[i] := x - y * (x / y) instance : has_mod ℤ[i] := ⟨gaussian_int.mod⟩ lemma mod_def (x y : ℤ[i]) : x % y = x - y * (x / y) := rfl lemma norm_mod_lt (x : ℤ[i]) {y : ℤ[i]} (hy : y ≠ 0) : (x % y).norm < y.norm := have (y : ℂ) ≠ 0, by rwa [ne.def, ← to_complex_zero, to_complex_inj], (@int.cast_lt ℝ _ _ _ _).1 $ calc ↑(norm (x % y)) = (x - y * (x / y : ℤ[i]) : ℂ).norm_sq : by simp [mod_def] ... = (y : ℂ).norm_sq * (((x / y) - (x / y : ℤ[i])) : ℂ).norm_sq : by rw [← norm_sq_mul, mul_sub, mul_div_cancel' _ this] ... < (y : ℂ).norm_sq * 1 : mul_lt_mul_of_pos_left (norm_sq_div_sub_div_lt_one _ _) (norm_sq_pos.2 this) ... = norm y : by simp lemma nat_abs_norm_mod_lt (x : ℤ[i]) {y : ℤ[i]} (hy : y ≠ 0) : (x % y).norm.nat_abs < y.norm.nat_abs := int.coe_nat_lt.1 (by simp [-int.coe_nat_lt, norm_mod_lt x hy]) lemma norm_le_norm_mul_left (x : ℤ[i]) {y : ℤ[i]} (hy : y ≠ 0) : (norm x).nat_abs ≤ (norm (x * y)).nat_abs := by rw [norm_mul, int.nat_abs_mul]; exact le_mul_of_one_le_right (nat.zero_le _) (int.coe_nat_le.1 (by rw [coe_nat_abs_norm]; exact int.add_one_le_of_lt (norm_pos.2 hy))) instance : nontrivial ℤ[i] := ⟨⟨0, 1, dec_trivial⟩⟩ instance : euclidean_domain ℤ[i] := { quotient := (/), remainder := (%), quotient_zero := λ _, by simp [div_def]; refl, quotient_mul_add_remainder_eq := λ _ _, by simp [mod_def], r := _, r_well_founded := measure_wf (int.nat_abs ∘ norm), remainder_lt := nat_abs_norm_mod_lt, mul_left_not_lt := λ a b hb0, not_lt_of_ge $ norm_le_norm_mul_left a hb0, .. gaussian_int.comm_ring, .. gaussian_int.nontrivial } open principal_ideal_ring lemma mod_four_eq_three_of_nat_prime_of_prime (p : ℕ) [hp : fact p.prime] (hpi : prime (p : ℤ[i])) : p % 4 = 3 := hp.eq_two_or_odd.elim (λ hp2, absurd hpi (mt irreducible_iff_prime.2 $ λ ⟨hu, h⟩, begin have := h ⟨1, 1⟩ ⟨1, -1⟩ (hp2.symm ▸ rfl), rw [← norm_eq_one_iff, ← norm_eq_one_iff] at this, exact absurd this dec_trivial end)) (λ hp1, by_contradiction $ λ hp3 : p % 4 ≠ 3, have hp41 : p % 4 = 1, begin rw [← nat.mod_mul_left_mod p 2 2, show 2 * 2 = 4, from rfl] at hp1, have := nat.mod_lt p (show 0 < 4, from dec_trivial), revert this hp3 hp1, generalize : p % 4 = m, dec_trivial!, end, let ⟨k, hk⟩ := (zmod.exists_pow_two_eq_neg_one_iff_mod_four_ne_three p).2 $ by rw hp41; exact dec_trivial in begin obtain ⟨k, k_lt_p, rfl⟩ : ∃ (k' : ℕ) (h : k' < p), (k' : zmod p) = k, { refine ⟨k.val, k.val_lt, zmod.cast_val k⟩ }, have hpk : p ∣ k ^ 2 + 1, by rw [← char_p.cast_eq_zero_iff (zmod p) p]; simp *, have hkmul : (k ^ 2 + 1 : ℤ[i]) = ⟨k, 1⟩ * ⟨k, -1⟩ := by simp [pow_two, zsqrtd.ext], have hpne1 : p ≠ 1, from (ne_of_lt (hp.one_lt)).symm, have hkltp : 1 + k * k < p * p, from calc 1 + k * k ≤ k + k * k : add_le_add_right (nat.pos_of_ne_zero (λ hk0, by clear_aux_decl; simp [*, pow_succ'] at *)) _ ... = k * (k + 1) : by simp [add_comm, mul_add] ... < p * p : mul_lt_mul k_lt_p k_lt_p (nat.succ_pos _) (nat.zero_le _), have hpk₁ : ¬ (p : ℤ[i]) ∣ ⟨k, -1⟩ := λ ⟨x, hx⟩, lt_irrefl (p * x : ℤ[i]).norm.nat_abs $ calc (norm (p * x : ℤ[i])).nat_abs = (norm ⟨k, -1⟩).nat_abs : by rw hx ... < (norm (p : ℤ[i])).nat_abs : by simpa [add_comm, norm] using hkltp ... ≤ (norm (p * x : ℤ[i])).nat_abs : norm_le_norm_mul_left _ (λ hx0, (show (-1 : ℤ) ≠ 0, from dec_trivial) $ by simpa [hx0] using congr_arg zsqrtd.im hx), have hpk₂ : ¬ (p : ℤ[i]) ∣ ⟨k, 1⟩ := λ ⟨x, hx⟩, lt_irrefl (p * x : ℤ[i]).norm.nat_abs $ calc (norm (p * x : ℤ[i])).nat_abs = (norm ⟨k, 1⟩).nat_abs : by rw hx ... < (norm (p : ℤ[i])).nat_abs : by simpa [add_comm, norm] using hkltp ... ≤ (norm (p * x : ℤ[i])).nat_abs : norm_le_norm_mul_left _ (λ hx0, (show (1 : ℤ) ≠ 0, from dec_trivial) $ by simpa [hx0] using congr_arg zsqrtd.im hx), have hpu : ¬ is_unit (p : ℤ[i]), from mt norm_eq_one_iff.2 (by rw [norm_nat_cast, int.nat_abs_mul, nat.mul_eq_one_iff]; exact λ h, (ne_of_lt hp.one_lt).symm h.1), obtain ⟨y, hy⟩ := hpk, have := hpi.2.2 ⟨k, 1⟩ ⟨k, -1⟩ ⟨y, by rw [← hkmul, ← nat.cast_mul p, ← hy]; simp⟩, clear_aux_decl, tauto end) lemma sum_two_squares_of_nat_prime_of_not_irreducible (p : ℕ) [hp : fact p.prime] (hpi : ¬irreducible (p : ℤ[i])) : ∃ a b, a^2 + b^2 = p := have hpu : ¬ is_unit (p : ℤ[i]), from mt norm_eq_one_iff.2 $ by rw [norm_nat_cast, int.nat_abs_mul, nat.mul_eq_one_iff]; exact λ h, (ne_of_lt hp.one_lt).symm h.1, have hab : ∃ a b, (p : ℤ[i]) = a * b ∧ ¬ is_unit a ∧ ¬ is_unit b, by simpa [irreducible, hpu, not_forall, not_or_distrib] using hpi, let ⟨a, b, hpab, hau, hbu⟩ := hab in have hnap : (norm a).nat_abs = p, from ((hp.mul_eq_prime_pow_two_iff (mt norm_eq_one_iff.1 hau) (mt norm_eq_one_iff.1 hbu)).1 $ by rw [← int.coe_nat_inj', int.coe_nat_pow, pow_two, ← @norm_nat_cast (-1), hpab]; simp).1, ⟨a.re.nat_abs, a.im.nat_abs, by simpa [nat_abs_norm_eq, pow_two] using hnap⟩ lemma prime_of_nat_prime_of_mod_four_eq_three (p : ℕ) [hp : fact p.prime] (hp3 : p % 4 = 3) : prime (p : ℤ[i]) := irreducible_iff_prime.1 $ classical.by_contradiction $ λ hpi, let ⟨a, b, hab⟩ := sum_two_squares_of_nat_prime_of_not_irreducible p hpi in have ∀ a b : zmod 4, a^2 + b^2 ≠ p, by erw [← zmod.cast_mod_nat 4 p, hp3]; exact dec_trivial, this a b (hab ▸ by simp) /-- A prime natural number is prime in `ℤ[i]` if and only if it is `3` mod `4` -/ lemma prime_iff_mod_four_eq_three_of_nat_prime (p : ℕ) [hp : fact p.prime] : prime (p : ℤ[i]) ↔ p % 4 = 3 := ⟨mod_four_eq_three_of_nat_prime_of_prime p, prime_of_nat_prime_of_mod_four_eq_three p⟩ end gaussian_int
c6ca478911d0858c5d7516f7f20909a83f759a09
e9dbaaae490bc072444e3021634bf73664003760
/src/Problems/2015/IMO_2015_P3.lean
f7ae0e45b2f4ffc320ae7f522b0386e6a85b1bf2
[ "Apache-2.0" ]
permissive
liaofei1128/geometry
566d8bfe095ce0c0113d36df90635306c60e975b
3dd128e4eec8008764bb94e18b932f9ffd66e6b3
refs/heads/master
1,678,996,510,399
1,581,454,543,000
1,583,337,839,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
765
lean
import Geo.Geo.Core namespace Geo open Triangle def IMO_2015_P3 : Prop := ∀ (A B C : Point), acute ⟨A, B, C⟩ → ulen (Seg.mk A B) > ulen (Seg.mk A C) → let Γ := Triangle.circumcircle ⟨A, B, C⟩; let H := orthocenter ⟨A, B, C⟩; let F := (altitudes ⟨A, B, C⟩).A.dst; -- is the same as foot A ⟨B, C⟩ let M := (Seg.mk B C).midp; /- Note that in the problem statement, K and Q have 0 df. The function that would have to be introduced to reflect this would be a bit awkward. -/ ∀ (K Q : Point), on Q Γ → Angle.isRight ⟨H, Q, A⟩ → on K Γ → Angle.isRight ⟨H, K, Q⟩ → [A, B, C, K, Q].allDistinct → inOrderOn [A, B, C, K, Q] Γ → tangent (Triangle.circumcircle ⟨K, Q, H⟩) (Triangle.circumcircle ⟨F, K, M⟩) end Geo
bbe7b404472ffcf19ec757cc2c99c05d2b996664
c8af905dcd8475f414868d303b2eb0e9d3eb32f9
/src/data/cpi/semantics/ode.lean
157b7c259ba49671f40b250d650713b198b15f2d
[ "BSD-3-Clause" ]
permissive
continuouspi/lean-cpi
81480a13842d67ff5f3698643210d8ed5dd08de4
443bf2cb236feadc45a01387099c236ab2b78237
refs/heads/master
1,650,307,316,582
1,587,033,364,000
1,587,033,364,000
207,499,661
1
0
null
null
null
null
UTF-8
Lean
false
false
2,353
lean
import data.cpi.semantics.basic data.fin_poly namespace cpi variables {ℍ : Type} {ω : context} [half_ring ℍ] [cpi_equiv_prop ℍ ω] [decidable_eq ℍ] /-- All species which may occur within the transition graph of a process. As the transition graph may be infinite, we visit the graph with a finite amount of gas. If we run out of gas, we return an incomplete set, otherwise we return a complete one. -/ @[nolint has_inhabited_instance] inductive all_species (M : affinity ℍ) (ℓ : lookup ℍ ω (context.extend M.arity context.nil)) : Type | incomplete {} : finset (prime_species' ℍ ω (context.extend M.arity context.nil)) → all_species | complete : ∀ (As : finset (prime_species' ℍ ω (context.extend M.arity context.nil))) , (process_immediate.quot M ℓ fin_poly.C.embed (process.from_prime_multiset fin_poly.X As.val)) .support ⊆ As → all_species /-- Get all species in the transition graph for a finset of prime species. -/ def all_species.finset (M : affinity ℍ) (ℓ : lookup ℍ ω (context.extend M.arity context.nil)) : ℕ → finset (prime_species' ℍ ω (context.extend M.arity context.nil)) → all_species M ℓ | 0 As := all_species.incomplete As | (nat.succ n) As := let As' := (process_immediate.quot M ℓ fin_poly.C.embed (process.from_prime_multiset fin_poly.X As.val)).support in if eq : As' ⊆ As then all_species.complete As eq else all_species.finset n (As ∪ As') /-- Get all species in the transition graph for a process. -/ def all_species.process (M : affinity ℍ) (ℓ : lookup ℍ ω (context.extend M.arity context.nil)) : ℕ → process ℍ ℍ ω (context.extend M.arity context.nil) → all_species M ℓ | fuel P := all_species.finset M ℓ fuel (process.to_space P).support /-- Get a finite set of species (such as those provided by all_species and convert it to an ODE) -/ def as_ode (M : affinity ℍ) (ℓ : lookup ℍ ω (context.extend M.arity context.nil)) : finset (prime_species' ℍ ω (context.extend M.arity context.nil)) → process_space (fin_poly (prime_species' ℍ ω (context.extend M.arity context.nil)) ℍ) ℍ ω (context.extend M.arity context.nil) | As := process_immediate.quot M ℓ fin_poly.C.embed (process.from_prime_multiset (λ x, fin_poly.X x) As.val) end cpi #lint-
60d9bb29dde7d1b84f6a9ff94e6e0fc2af396cd8
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/lie/subalgebra.lean
5dfce2b1c28945d70933fe7bba92d38873f2e18a
[ "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
23,020
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.basic import ring_theory.noetherian /-! # Lie subalgebras This file defines Lie subalgebras of a Lie algebra and provides basic related definitions and results. ## Main definitions * `lie_subalgebra` * `lie_subalgebra.incl` * `lie_subalgebra.map` * `lie_hom.range` * `lie_equiv.of_injective` * `lie_equiv.of_eq` * `lie_equiv.of_subalgebra` * `lie_equiv.of_subalgebras` ## Tags lie algebra, lie subalgebra -/ universes u v w w₁ w₂ section lie_subalgebra variables (R : Type u) (L : Type v) [comm_ring R] [lie_ring L] [lie_algebra R L] /-- A Lie subalgebra of a Lie algebra is submodule that is closed under the Lie bracket. This is a sufficient condition for the subset itself to form a Lie algebra. -/ structure lie_subalgebra extends submodule R L := (lie_mem' : ∀ {x y}, x ∈ carrier → y ∈ carrier → ⁅x, y⁆ ∈ carrier) attribute [nolint doc_blame] lie_subalgebra.to_submodule /-- The zero algebra is a subalgebra of any Lie algebra. -/ instance : has_zero (lie_subalgebra R L) := ⟨{ lie_mem' := λ x y hx hy, by { rw [((submodule.mem_bot R).1 hx), zero_lie], exact submodule.zero_mem (0 : submodule R L), }, ..(0 : submodule R L) }⟩ instance : inhabited (lie_subalgebra R L) := ⟨0⟩ instance : has_coe (lie_subalgebra R L) (submodule R L) := ⟨lie_subalgebra.to_submodule⟩ namespace lie_subalgebra instance : set_like (lie_subalgebra R L) L := { coe := λ L', L', coe_injective' := λ L' L'' h, by { rcases L' with ⟨⟨⟩⟩, rcases L'' with ⟨⟨⟩⟩, congr' } } instance : add_subgroup_class (lie_subalgebra R L) L := { add_mem := λ L', L'.add_mem', zero_mem := λ L', L'.zero_mem', neg_mem := λ L' x hx, show -x ∈ (L' : submodule R L), from neg_mem hx } /-- A Lie subalgebra forms a new Lie ring. -/ instance (L' : lie_subalgebra R L) : lie_ring L' := { bracket := λ x y, ⟨⁅x.val, y.val⁆, L'.lie_mem' x.property y.property⟩, lie_add := by { intros, apply set_coe.ext, apply lie_add, }, add_lie := by { intros, apply set_coe.ext, apply add_lie, }, lie_self := by { intros, apply set_coe.ext, apply lie_self, }, leibniz_lie := by { intros, apply set_coe.ext, apply leibniz_lie, } } section variables {R₁ : Type*} [semiring R₁] /-- A Lie subalgebra inherits module structures from `L`. -/ instance [has_scalar R₁ R] [module R₁ L] [is_scalar_tower R₁ R L] (L' : lie_subalgebra R L) : module R₁ L' := L'.to_submodule.module' instance [has_scalar R₁ R] [has_scalar R₁ᵐᵒᵖ R] [module R₁ L] [module R₁ᵐᵒᵖ L] [is_scalar_tower R₁ R L] [is_scalar_tower R₁ᵐᵒᵖ R L] [is_central_scalar R₁ L] (L' : lie_subalgebra R L) : is_central_scalar R₁ L' := L'.to_submodule.is_central_scalar instance [has_scalar R₁ R] [module R₁ L] [is_scalar_tower R₁ R L] (L' : lie_subalgebra R L) : is_scalar_tower R₁ R L' := L'.to_submodule.is_scalar_tower end /-- A Lie subalgebra forms a new Lie algebra. -/ instance (L' : lie_subalgebra R L) : lie_algebra R L' := { lie_smul := by { intros, apply set_coe.ext, apply lie_smul } } variables {R L} (L' : lie_subalgebra R L) @[simp] protected lemma zero_mem : (0 : L) ∈ L' := zero_mem L' protected lemma add_mem {x y : L} : x ∈ L' → y ∈ L' → (x + y : L) ∈ L' := add_mem protected lemma sub_mem {x y : L} : x ∈ L' → y ∈ L' → (x - y : L) ∈ L' := sub_mem lemma smul_mem (t : R) {x : L} (h : x ∈ L') : t • x ∈ L' := (L' : submodule R L).smul_mem t h lemma lie_mem {x y : L} (hx : x ∈ L') (hy : y ∈ L') : (⁅x, y⁆ : L) ∈ L' := L'.lie_mem' hx hy @[simp] lemma mem_carrier {x : L} : x ∈ L'.carrier ↔ x ∈ (L' : set L) := iff.rfl @[simp] lemma mem_mk_iff (S : set L) (h₁ h₂ h₃ h₄) {x : L} : x ∈ (⟨⟨S, h₁, h₂, h₃⟩, h₄⟩ : lie_subalgebra R L) ↔ x ∈ S := iff.rfl @[simp] lemma mem_coe_submodule {x : L} : x ∈ (L' : submodule R L) ↔ x ∈ L' := iff.rfl lemma mem_coe {x : L} : x ∈ (L' : set L) ↔ x ∈ L' := iff.rfl @[simp, norm_cast] lemma coe_bracket (x y : L') : (↑⁅x, y⁆ : L) = ⁅(↑x : L), ↑y⁆ := rfl lemma ext_iff (x y : L') : x = y ↔ (x : L) = y := subtype.ext_iff lemma coe_zero_iff_zero (x : L') : (x : L) = 0 ↔ x = 0 := (ext_iff L' x 0).symm @[ext] lemma ext (L₁' L₂' : lie_subalgebra R L) (h : ∀ x, x ∈ L₁' ↔ x ∈ L₂') : L₁' = L₂' := set_like.ext h lemma ext_iff' (L₁' L₂' : lie_subalgebra R L) : L₁' = L₂' ↔ ∀ x, x ∈ L₁' ↔ x ∈ L₂' := set_like.ext_iff @[simp] lemma mk_coe (S : set L) (h₁ h₂ h₃ h₄) : ((⟨⟨S, h₁, h₂, h₃⟩, h₄⟩ : lie_subalgebra R L) : set L) = S := rfl @[simp] lemma coe_to_submodule_mk (p : submodule R L) (h) : (({lie_mem' := h, ..p} : lie_subalgebra R L) : submodule R L) = p := by { cases p, refl, } lemma coe_injective : function.injective (coe : lie_subalgebra R L → set L) := set_like.coe_injective @[norm_cast] theorem coe_set_eq (L₁' L₂' : lie_subalgebra R L) : (L₁' : set L) = L₂' ↔ L₁' = L₂' := set_like.coe_set_eq lemma to_submodule_injective : function.injective (coe : lie_subalgebra R L → submodule R L) := λ L₁' L₂' h, by { rw set_like.ext'_iff at h, rw ← coe_set_eq, exact h, } @[simp] lemma coe_to_submodule_eq_iff (L₁' L₂' : lie_subalgebra R L) : (L₁' : submodule R L) = (L₂' : submodule R L) ↔ L₁' = L₂' := to_submodule_injective.eq_iff @[norm_cast] lemma coe_to_submodule : ((L' : submodule R L) : set L) = L' := rfl section lie_module variables {M : Type w} [add_comm_group M] [lie_ring_module L M] variables {N : Type w₁} [add_comm_group N] [lie_ring_module L N] [module R N] [lie_module R L N] /-- Given a Lie algebra `L` containing a Lie subalgebra `L' ⊆ L`, together with a Lie ring module `M` of `L`, we may regard `M` as a Lie ring module of `L'` by restriction. -/ instance : lie_ring_module L' M := { bracket := λ x m, ⁅(x : L), m⁆, add_lie := λ x y m, add_lie x y m, lie_add := λ x y m, lie_add x y m, leibniz_lie := λ x y m, leibniz_lie x y m, } @[simp] lemma coe_bracket_of_module (x : L') (m : M) : ⁅x, m⁆ = ⁅(x : L), m⁆ := rfl variables [module R M] [lie_module R L M] /-- Given a Lie algebra `L` containing a Lie subalgebra `L' ⊆ L`, together with a Lie module `M` of `L`, we may regard `M` as a Lie module of `L'` by restriction. -/ instance : lie_module R L' M := { smul_lie := λ t x m, by simp only [coe_bracket_of_module, smul_lie, submodule.coe_smul_of_tower], lie_smul := λ t x m, by simp only [coe_bracket_of_module, lie_smul], } /-- An `L`-equivariant map of Lie modules `M → N` is `L'`-equivariant for any Lie subalgebra `L' ⊆ L`. -/ def _root_.lie_module_hom.restrict_lie (f : M →ₗ⁅R,L⁆ N) (L' : lie_subalgebra R L) : M →ₗ⁅R,L'⁆ N := { map_lie' := λ x m, f.map_lie ↑x m, .. (f : M →ₗ[R] N)} @[simp] lemma _root_.lie_module_hom.coe_restrict_lie (f : M →ₗ⁅R,L⁆ N) : ⇑(f.restrict_lie L') = f := rfl end lie_module /-- The embedding of a Lie subalgebra into the ambient space as a morphism of Lie algebras. -/ def incl : L' →ₗ⁅R⁆ L := { map_lie' := λ x y, by { simp only [linear_map.to_fun_eq_coe, submodule.subtype_apply], refl, }, .. (L' : submodule R L).subtype, } @[simp] lemma coe_incl : ⇑L'.incl = coe := rfl /-- The embedding of a Lie subalgebra into the ambient space as a morphism of Lie modules. -/ def incl' : L' →ₗ⁅R,L'⁆ L := { map_lie' := λ x y, by simp only [coe_bracket_of_module, linear_map.to_fun_eq_coe, submodule.subtype_apply, coe_bracket], .. (L' : submodule R L).subtype, } @[simp] lemma coe_incl' : ⇑L'.incl' = coe := rfl end lie_subalgebra variables {R L} {L₂ : Type w} [lie_ring L₂] [lie_algebra R L₂] variables (f : L →ₗ⁅R⁆ L₂) namespace lie_hom /-- The range of a morphism of Lie algebras is a Lie subalgebra. -/ def range : lie_subalgebra R L₂ := { lie_mem' := λ x y, show x ∈ f.to_linear_map.range → y ∈ f.to_linear_map.range → ⁅x, y⁆ ∈ f.to_linear_map.range, by { repeat { rw linear_map.mem_range }, rintros ⟨x', hx⟩ ⟨y', hy⟩, refine ⟨⁅x', y'⁆, _⟩, rw [←hx, ←hy], change f ⁅x', y'⁆ = ⁅f x', f y'⁆, rw map_lie, }, ..(f : L →ₗ[R] L₂).range } @[simp] lemma range_coe : (f.range : set L₂) = set.range f := linear_map.range_coe ↑f @[simp] lemma mem_range (x : L₂) : x ∈ f.range ↔ ∃ (y : L), f y = x := linear_map.mem_range lemma mem_range_self (x : L) : f x ∈ f.range := linear_map.mem_range_self f x /-- We can restrict a morphism to a (surjective) map to its range. -/ def range_restrict : L →ₗ⁅R⁆ f.range := { map_lie' := λ x y, by { apply subtype.ext, exact f.map_lie x y, }, ..(f : L →ₗ[R] L₂).range_restrict, } @[simp] lemma range_restrict_apply (x : L) : f.range_restrict x = ⟨f x, f.mem_range_self x⟩ := rfl lemma surjective_range_restrict : function.surjective (f.range_restrict) := begin rintros ⟨y, hy⟩, erw mem_range at hy, obtain ⟨x, rfl⟩ := hy, use x, simp only [subtype.mk_eq_mk, range_restrict_apply], end /-- A Lie algebra is equivalent to its range under an injective Lie algebra morphism. -/ noncomputable def equiv_range_of_injective (h : function.injective f) : L ≃ₗ⁅R⁆ f.range := lie_equiv.of_bijective f.range_restrict (λ x y hxy, begin simp only [subtype.mk_eq_mk, range_restrict_apply] at hxy, exact h hxy, end) f.surjective_range_restrict @[simp] lemma equiv_range_of_injective_apply (h : function.injective f) (x : L) : f.equiv_range_of_injective h x = ⟨f x, mem_range_self f x⟩ := rfl end lie_hom lemma submodule.exists_lie_subalgebra_coe_eq_iff (p : submodule R L) : (∃ (K : lie_subalgebra R L), ↑K = p) ↔ ∀ (x y : L), x ∈ p → y ∈ p → ⁅x, y⁆ ∈ p := begin split, { rintros ⟨K, rfl⟩, exact K.lie_mem', }, { intros h, use { lie_mem' := h, ..p }, exact lie_subalgebra.coe_to_submodule_mk p _, }, end namespace lie_subalgebra variables (K K' : lie_subalgebra R L) (K₂ : lie_subalgebra R L₂) @[simp] lemma incl_range : K.incl.range = K := by { rw ← coe_to_submodule_eq_iff, exact (K : submodule R L).range_subtype, } /-- The image of a Lie subalgebra under a Lie algebra morphism is a Lie subalgebra of the codomain. -/ def map : lie_subalgebra R L₂ := { lie_mem' := λ x y hx hy, by { erw submodule.mem_map at hx, rcases hx with ⟨x', hx', hx⟩, rw ←hx, erw submodule.mem_map at hy, rcases hy with ⟨y', hy', hy⟩, rw ←hy, erw submodule.mem_map, exact ⟨⁅x', y'⁆, K.lie_mem hx' hy', f.map_lie x' y'⟩, }, ..((K : submodule R L).map (f : L →ₗ[R] L₂)) } @[simp] lemma mem_map (x : L₂) : x ∈ K.map f ↔ ∃ (y : L), y ∈ K ∧ f y = x := submodule.mem_map -- TODO Rename and state for homs instead of equivs. @[simp] lemma mem_map_submodule (e : L ≃ₗ⁅R⁆ L₂) (x : L₂) : x ∈ K.map (e : L →ₗ⁅R⁆ L₂) ↔ x ∈ (K : submodule R L).map (e : L →ₗ[R] L₂) := iff.rfl /-- The preimage of a Lie subalgebra under a Lie algebra morphism is a Lie subalgebra of the domain. -/ def comap : lie_subalgebra R L := { lie_mem' := λ x y hx hy, by { suffices : ⁅f x, f y⁆ ∈ K₂, by { simp [this], }, exact K₂.lie_mem hx hy, }, ..((K₂ : submodule R L₂).comap (f : L →ₗ[R] L₂)), } section lattice_structure open set instance : partial_order (lie_subalgebra R L) := { le := λ N N', ∀ ⦃x⦄, x ∈ N → x ∈ N', -- Overriding `le` like this gives a better defeq. ..partial_order.lift (coe : lie_subalgebra R L → set L) coe_injective } lemma le_def : K ≤ K' ↔ (K : set L) ⊆ K' := iff.rfl @[simp, norm_cast] lemma coe_submodule_le_coe_submodule : (K : submodule R L) ≤ K' ↔ K ≤ K' := iff.rfl instance : has_bot (lie_subalgebra R L) := ⟨0⟩ @[simp] lemma bot_coe : ((⊥ : lie_subalgebra R L) : set L) = {0} := rfl @[simp] lemma bot_coe_submodule : ((⊥ : lie_subalgebra R L) : submodule R L) = ⊥ := rfl @[simp] lemma mem_bot (x : L) : x ∈ (⊥ : lie_subalgebra R L) ↔ x = 0 := mem_singleton_iff instance : has_top (lie_subalgebra R L) := ⟨{ lie_mem' := λ x y hx hy, mem_univ ⁅x, y⁆, ..(⊤ : submodule R L) }⟩ @[simp] lemma top_coe : ((⊤ : lie_subalgebra R L) : set L) = univ := rfl @[simp] lemma top_coe_submodule : ((⊤ : lie_subalgebra R L) : submodule R L) = ⊤ := rfl @[simp] lemma mem_top (x : L) : x ∈ (⊤ : lie_subalgebra R L) := mem_univ x lemma _root_.lie_hom.range_eq_map : f.range = map f ⊤ := by { ext, simp } instance : has_inf (lie_subalgebra R L) := ⟨λ K K', { lie_mem' := λ x y hx hy, mem_inter (K.lie_mem hx.1 hy.1) (K'.lie_mem hx.2 hy.2), ..(K ⊓ K' : submodule R L) }⟩ instance : has_Inf (lie_subalgebra R L) := ⟨λ S, { lie_mem' := λ x y hx hy, by { simp only [submodule.mem_carrier, mem_Inter, submodule.Inf_coe, mem_set_of_eq, forall_apply_eq_imp_iff₂, exists_imp_distrib] at *, intros K hK, exact K.lie_mem (hx K hK) (hy K hK), }, ..Inf {(s : submodule R L) | s ∈ S} }⟩ @[simp] theorem inf_coe : (↑(K ⊓ K') : set L) = K ∩ K' := rfl @[simp] lemma Inf_coe_to_submodule (S : set (lie_subalgebra R L)) : (↑(Inf S) : submodule R L) = Inf {(s : submodule R L) | s ∈ S} := rfl @[simp] lemma Inf_coe (S : set (lie_subalgebra R L)) : (↑(Inf S) : set L) = ⋂ s ∈ S, (s : set L) := begin rw [← coe_to_submodule, Inf_coe_to_submodule, submodule.Inf_coe], ext x, simpa only [mem_Inter, mem_set_of_eq, forall_apply_eq_imp_iff₂, exists_imp_distrib], end lemma Inf_glb (S : set (lie_subalgebra R L)) : is_glb S (Inf S) := begin have h : ∀ (K K' : lie_subalgebra R L), (K : set L) ≤ K' ↔ K ≤ K', { intros, exact iff.rfl, }, apply is_glb.of_image h, simp only [Inf_coe], exact is_glb_binfi end /-- The set of Lie subalgebras of a Lie algebra form a complete lattice. We provide explicit values for the fields `bot`, `top`, `inf` to get more convenient definitions than we would otherwise obtain from `complete_lattice_of_Inf`. -/ instance : complete_lattice (lie_subalgebra R L) := { bot := ⊥, bot_le := λ N _ h, by { rw mem_bot at h, rw h, exact N.zero_mem', }, top := ⊤, le_top := λ _ _ _, trivial, inf := (⊓), le_inf := λ N₁ N₂ N₃ h₁₂ h₁₃ m hm, ⟨h₁₂ hm, h₁₃ hm⟩, inf_le_left := λ _ _ _, and.left, inf_le_right := λ _ _ _, and.right, ..complete_lattice_of_Inf _ Inf_glb } instance : add_comm_monoid (lie_subalgebra R L) := { add := (⊔), add_assoc := λ _ _ _, sup_assoc, zero := ⊥, zero_add := λ _, bot_sup_eq, add_zero := λ _, sup_bot_eq, add_comm := λ _ _, sup_comm, } @[simp] lemma add_eq_sup : K + K' = K ⊔ K' := rfl @[norm_cast, simp] lemma inf_coe_to_submodule : (↑(K ⊓ K') : submodule R L) = (K : submodule R L) ⊓ (K' : submodule R L) := rfl @[simp] lemma mem_inf (x : L) : x ∈ K ⊓ K' ↔ x ∈ K ∧ x ∈ K' := by rw [← mem_coe_submodule, ← mem_coe_submodule, ← mem_coe_submodule, inf_coe_to_submodule, submodule.mem_inf] lemma eq_bot_iff : K = ⊥ ↔ ∀ (x : L), x ∈ K → x = 0 := by { rw eq_bot_iff, exact iff.rfl, } -- TODO[gh-6025]: make this an instance once safe to do so lemma subsingleton_of_bot : subsingleton (lie_subalgebra R ↥(⊥ : lie_subalgebra R L)) := begin apply subsingleton_of_bot_eq_top, ext ⟨x, hx⟩, change x ∈ ⊥ at hx, rw submodule.mem_bot at hx, subst hx, simp only [true_iff, eq_self_iff_true, submodule.mk_eq_zero, mem_bot], end lemma subsingleton_bot : subsingleton ↥(⊥ : lie_subalgebra R L) := show subsingleton ((⊥ : lie_subalgebra R L) : set L), by simp variables (R L) lemma well_founded_of_noetherian [is_noetherian R L] : well_founded ((>) : lie_subalgebra R L → lie_subalgebra R L → Prop) := let f : ((>) : lie_subalgebra R L → lie_subalgebra R L → Prop) →r ((>) : submodule R L → submodule R L → Prop) := { to_fun := coe, map_rel' := λ N N' h, h, } in rel_hom_class.well_founded f (is_noetherian_iff_well_founded.mp infer_instance) variables {R L K K' f} section nested_subalgebras variables (h : K ≤ K') /-- Given two nested Lie subalgebras `K ⊆ K'`, the inclusion `K ↪ K'` is a morphism of Lie algebras. -/ def hom_of_le : K →ₗ⁅R⁆ K' := { map_lie' := λ x y, rfl, ..submodule.of_le h } @[simp] lemma coe_hom_of_le (x : K) : (hom_of_le h x : L) = x := rfl lemma hom_of_le_apply (x : K) : hom_of_le h x = ⟨x.1, h x.2⟩ := rfl lemma hom_of_le_injective : function.injective (hom_of_le h) := λ x y, by simp only [hom_of_le_apply, imp_self, subtype.mk_eq_mk, set_like.coe_eq_coe, subtype.val_eq_coe] /-- Given two nested Lie subalgebras `K ⊆ K'`, we can view `K` as a Lie subalgebra of `K'`, regarded as Lie algebra in its own right. -/ def of_le : lie_subalgebra R K' := (hom_of_le h).range @[simp] lemma mem_of_le (x : K') : x ∈ of_le h ↔ (x : L) ∈ K := begin simp only [of_le, hom_of_le_apply, lie_hom.mem_range], split, { rintros ⟨y, rfl⟩, exact y.property, }, { intros h, use ⟨(x : L), h⟩, simp, }, end lemma of_le_eq_comap_incl : of_le h = K.comap K'.incl := by { ext, rw mem_of_le, refl, } @[simp] lemma coe_of_le : (of_le h : submodule R K') = (submodule.of_le h).range := rfl /-- Given nested Lie subalgebras `K ⊆ K'`, there is a natural equivalence from `K` to its image in `K'`. -/ noncomputable def equiv_of_le : K ≃ₗ⁅R⁆ of_le h := (hom_of_le h).equiv_range_of_injective (hom_of_le_injective h) @[simp] lemma equiv_of_le_apply (x : K) : equiv_of_le h x = ⟨hom_of_le h x, (hom_of_le h).mem_range_self x⟩ := rfl end nested_subalgebras lemma map_le_iff_le_comap {K : lie_subalgebra R L} {K' : lie_subalgebra R L₂} : map f K ≤ K' ↔ K ≤ comap f K' := set.image_subset_iff lemma gc_map_comap : galois_connection (map f) (comap f) := λ K K', map_le_iff_le_comap end lattice_structure section lie_span variables (R L) (s : set L) /-- The Lie subalgebra of a Lie algebra `L` generated by a subset `s ⊆ L`. -/ def lie_span : lie_subalgebra R L := Inf {N | s ⊆ N} variables {R L s} lemma mem_lie_span {x : L} : x ∈ lie_span R L s ↔ ∀ K : lie_subalgebra R L, s ⊆ K → x ∈ K := by { change x ∈ (lie_span R L s : set L) ↔ _, erw Inf_coe, exact set.mem_Inter₂, } lemma subset_lie_span : s ⊆ lie_span R L s := by { intros m hm, erw mem_lie_span, intros K hK, exact hK hm, } lemma submodule_span_le_lie_span : submodule.span R s ≤ lie_span R L s := by { rw submodule.span_le, apply subset_lie_span, } lemma lie_span_le {K} : lie_span R L s ≤ K ↔ s ⊆ K := begin split, { exact set.subset.trans subset_lie_span, }, { intros hs m hm, rw mem_lie_span at hm, exact hm _ hs, }, end lemma lie_span_mono {t : set L} (h : s ⊆ t) : lie_span R L s ≤ lie_span R L t := by { rw lie_span_le, exact set.subset.trans h subset_lie_span, } lemma lie_span_eq : lie_span R L (K : set L) = K := le_antisymm (lie_span_le.mpr rfl.subset) subset_lie_span lemma coe_lie_span_submodule_eq_iff {p : submodule R L} : (lie_span R L (p : set L) : submodule R L) = p ↔ ∃ (K : lie_subalgebra R L), ↑K = p := begin rw p.exists_lie_subalgebra_coe_eq_iff, split; intros h, { intros x m hm, rw [← h, mem_coe_submodule], exact lie_mem _ (subset_lie_span hm), }, { rw [← coe_to_submodule_mk p h, coe_to_submodule, coe_to_submodule_eq_iff, lie_span_eq], }, end variables (R L) /-- `lie_span` forms a Galois insertion with the coercion from `lie_subalgebra` to `set`. -/ protected def gi : galois_insertion (lie_span R L : set L → lie_subalgebra R L) coe := { choice := λ s _, lie_span R L s, gc := λ s t, lie_span_le, le_l_u := λ s, subset_lie_span, choice_eq := λ s h, rfl } @[simp] lemma span_empty : lie_span R L (∅ : set L) = ⊥ := (lie_subalgebra.gi R L).gc.l_bot @[simp] lemma span_univ : lie_span R L (set.univ : set L) = ⊤ := eq_top_iff.2 $ set_like.le_def.2 $ subset_lie_span variables {L} lemma span_union (s t : set L) : lie_span R L (s ∪ t) = lie_span R L s ⊔ lie_span R L t := (lie_subalgebra.gi R L).gc.l_sup lemma span_Union {ι} (s : ι → set L) : lie_span R L (⋃ i, s i) = ⨆ i, lie_span R L (s i) := (lie_subalgebra.gi R L).gc.l_supr end lie_span end lie_subalgebra end lie_subalgebra namespace lie_equiv variables {R : Type u} {L₁ : Type v} {L₂ : Type w} variables [comm_ring R] [lie_ring L₁] [lie_ring L₂] [lie_algebra R L₁] [lie_algebra R L₂] /-- An injective Lie algebra morphism is an equivalence onto its range. -/ noncomputable def of_injective (f : L₁ →ₗ⁅R⁆ L₂) (h : function.injective f) : L₁ ≃ₗ⁅R⁆ f.range := { map_lie' := λ x y, by { apply set_coe.ext, simpa }, .. linear_equiv.of_injective (f : L₁ →ₗ[R] L₂) $ by rwa [lie_hom.coe_to_linear_map] } @[simp] lemma of_injective_apply (f : L₁ →ₗ⁅R⁆ L₂) (h : function.injective f) (x : L₁) : ↑(of_injective f h x) = f x := rfl variables (L₁' L₁'' : lie_subalgebra R L₁) (L₂' : lie_subalgebra R L₂) /-- Lie subalgebras that are equal as sets are equivalent as Lie algebras. -/ def of_eq (h : (L₁' : set L₁) = L₁'') : L₁' ≃ₗ⁅R⁆ L₁'' := { map_lie' := λ x y, by { apply set_coe.ext, simp, }, ..(linear_equiv.of_eq ↑L₁' ↑L₁'' (by {ext x, change x ∈ (L₁' : set L₁) ↔ x ∈ (L₁'' : set L₁), rw h, } )) } @[simp] lemma of_eq_apply (L L' : lie_subalgebra R L₁) (h : (L : set L₁) = L') (x : L) : (↑(of_eq L L' h x) : L₁) = x := rfl variables (e : L₁ ≃ₗ⁅R⁆ L₂) /-- An equivalence of Lie algebras restricts to an equivalence from any Lie subalgebra onto its image. -/ def lie_subalgebra_map : L₁'' ≃ₗ⁅R⁆ (L₁''.map e : lie_subalgebra R L₂) := { map_lie' := λ x y, by { apply set_coe.ext, exact lie_hom.map_lie (↑e : L₁ →ₗ⁅R⁆ L₂) ↑x ↑y, } ..(linear_equiv.submodule_map (e : L₁ ≃ₗ[R] L₂) ↑L₁'') } @[simp] lemma lie_subalgebra_map_apply (x : L₁'') : ↑(e.lie_subalgebra_map _ x) = e x := rfl /-- An equivalence of Lie algebras restricts to an equivalence from any Lie subalgebra onto its image. -/ def of_subalgebras (h : L₁'.map ↑e = L₂') : L₁' ≃ₗ⁅R⁆ L₂' := { map_lie' := λ x y, by { apply set_coe.ext, exact lie_hom.map_lie (↑e : L₁ →ₗ⁅R⁆ L₂) ↑x ↑y, }, ..(linear_equiv.of_submodules (e : L₁ ≃ₗ[R] L₂) ↑L₁' ↑L₂' (by { rw ←h, refl, })) } @[simp] lemma of_subalgebras_apply (h : L₁'.map ↑e = L₂') (x : L₁') : ↑(e.of_subalgebras _ _ h x) = e x := rfl @[simp] lemma of_subalgebras_symm_apply (h : L₁'.map ↑e = L₂') (x : L₂') : ↑((e.of_subalgebras _ _ h).symm x) = e.symm x := rfl end lie_equiv
02bcbfd217f6eb6ddecd1d9406cb8d15a86db5f6
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/data/matrix/pequiv.lean
ae8f37cc24fb02e82e0e1e7b4fe8087ab72fb589
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
5,746
lean
/- Copyright (c) 2019 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.matrix.basic import data.pequiv /- # partial equivalences for matrices Using partial equivalences to represent matrices. This file introduces the function `pequiv.to_matrix`, which returns a matrix containing ones and zeros. For any partial equivalence `f`, `f.to_matrix i j = 1 ↔ f i = some j`. The following important properties of this function are proved `to_matrix_trans : (f.trans g).to_matrix = f.to_matrix ⬝ g.to_matrix` `to_matrix_symm : f.symm.to_matrix = f.to_matrixᵀ` `to_matrix_refl : (pequiv.refl n).to_matrix = 1` `to_matrix_bot : ⊥.to_matrix = 0` This theory gives the matrix representation of projection linear maps, and their right inverses. For example, the matrix `(single (0 : fin 1) (i : fin n)).to_matrix` corresponds to the the ith projection map from R^n to R. Any injective function `fin m → fin n` gives rise to a `pequiv`, whose matrix is the projection map from R^m → R^n represented by the same function. The transpose of this matrix is the right inverse of this map, sending anything not in the image to zero. ## notations This file uses the notation ` ⬝ ` for `matrix.mul` and `ᵀ` for `matrix.transpose`. -/ namespace pequiv open matrix universes u v variables {k l m n : Type*} variables [fintype k] [fintype l] [fintype m] [fintype n] variables {α : Type v} open_locale matrix /-- `to_matrix` returns a matrix containing ones and zeros. `f.to_matrix i j` is `1` if `f i = some j` and `0` otherwise -/ def to_matrix [decidable_eq n] [has_zero α] [has_one α] (f : m ≃. n) : matrix m n α | i j := if j ∈ f i then 1 else 0 lemma mul_matrix_apply [decidable_eq m] [semiring α] (f : l ≃. m) (M : matrix m n α) (i j) : (f.to_matrix ⬝ M) i j = option.cases_on (f i) 0 (λ fi, M fi j) := begin dsimp [to_matrix, matrix.mul_apply], cases h : f i with fi, { simp [h] }, { rw finset.sum_eq_single fi; simp [h, eq_comm] {contextual := tt} } end lemma to_matrix_symm [decidable_eq m] [decidable_eq n] [has_zero α] [has_one α] (f : m ≃. n) : (f.symm.to_matrix : matrix n m α) = f.to_matrixᵀ := by ext; simp only [transpose, mem_iff_mem f, to_matrix]; congr @[simp] lemma to_matrix_refl [decidable_eq n] [has_zero α] [has_one α] : ((pequiv.refl n).to_matrix : matrix n n α) = 1 := by ext; simp [to_matrix, one_apply]; congr lemma matrix_mul_apply [semiring α] [decidable_eq n] (M : matrix l m α) (f : m ≃. n) (i j) : (M ⬝ f.to_matrix) i j = option.cases_on (f.symm j) 0 (λ fj, M i fj) := begin dsimp [to_matrix, matrix.mul_apply], cases h : f.symm j with fj, { simp [h, f.eq_some_iff.symm] }, { conv in (_ ∈ _) { rw ← f.mem_iff_mem }, rw finset.sum_eq_single fj, { simp [h, f.eq_some_iff.symm], }, { intros b H n, simp [h, f.eq_some_iff.symm, n.symm], }, { simp, } } end lemma to_pequiv_mul_matrix [decidable_eq m] [semiring α] (f : m ≃ m) (M : matrix m n α) : (f.to_pequiv.to_matrix ⬝ M) = λ i, M (f i) := by { ext i j, rw [mul_matrix_apply, equiv.to_pequiv_apply] } lemma to_matrix_trans [decidable_eq m] [decidable_eq n] [semiring α] (f : l ≃. m) (g : m ≃. n) : ((f.trans g).to_matrix : matrix l n α) = f.to_matrix ⬝ g.to_matrix := begin ext i j, rw [mul_matrix_apply], dsimp [to_matrix, pequiv.trans], cases f i; simp end @[simp] lemma to_matrix_bot [decidable_eq n] [has_zero α] [has_one α] : ((⊥ : pequiv m n).to_matrix : matrix m n α) = 0 := rfl lemma to_matrix_injective [decidable_eq n] [monoid_with_zero α] [nontrivial α] : function.injective (@to_matrix m n _ _ α _ _ _) := begin classical, assume f g, refine not_imp_not.1 _, simp only [matrix.ext_iff.symm, to_matrix, pequiv.ext_iff, not_forall, exists_imp_distrib], assume i hi, use i, cases hf : f i with fi, { cases hg : g i with gi, { cc }, { use gi, simp, } }, { use fi, simp [hf.symm, ne.symm hi] } end lemma to_matrix_swap [decidable_eq n] [ring α] (i j : n) : (equiv.swap i j).to_pequiv.to_matrix = (1 : matrix n n α) - (single i i).to_matrix - (single j j).to_matrix + (single i j).to_matrix + (single j i).to_matrix := begin ext, dsimp [to_matrix, single, equiv.swap_apply_def, equiv.to_pequiv, one_apply], split_ifs; simp * at * end @[simp] lemma single_mul_single [decidable_eq k] [decidable_eq m] [decidable_eq n] [semiring α] (a : m) (b : n) (c : k) : ((single a b).to_matrix : matrix _ _ α) ⬝ (single b c).to_matrix = (single a c).to_matrix := by rw [← to_matrix_trans, single_trans_single] lemma single_mul_single_of_ne [decidable_eq k] [decidable_eq m] [decidable_eq n] [semiring α] {b₁ b₂ : n} (hb : b₁ ≠ b₂) (a : m) (c : k) : ((single a b₁).to_matrix : matrix _ _ α) ⬝ (single b₂ c).to_matrix = 0 := by rw [← to_matrix_trans, single_trans_single_of_ne hb, to_matrix_bot] /-- Restatement of `single_mul_single`, which will simplify expressions in `simp` normal form, when associativity may otherwise need to be carefully applied. -/ @[simp] lemma single_mul_single_right [decidable_eq k] [decidable_eq m] [decidable_eq n] [semiring α] (a : m) (b : n) (c : k) (M : matrix k l α) : (single a b).to_matrix ⬝ ((single b c).to_matrix ⬝ M) = (single a c).to_matrix ⬝ M := by rw [← matrix.mul_assoc, single_mul_single] /-- We can also define permutation matrices by permuting the rows of the identity matrix. -/ lemma equiv_to_pequiv_to_matrix [decidable_eq n] [has_zero α] [has_one α] (σ : equiv n n) (i j : n) : σ.to_pequiv.to_matrix i j = (1 : matrix n n α) (σ i) j := if_congr option.some_inj rfl rfl end pequiv