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
a89d8ac0a9514a4c69256451c86fa85000bc9e43
4727251e0cd73359b15b664c3170e5d754078599
/src/measure_theory/group/fundamental_domain.lean
1f5b9a0fbb8cfa46a1a86f7f733ec7bd6013476f
[ "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
17,346
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import measure_theory.group.action import measure_theory.group.pointwise import measure_theory.integral.set_integral /-! # Fundamental domain of a group action A set `s` is said to be a *fundamental domain* of an action of a group `G` on a measurable space `α` with respect to a measure `μ` if * `s` is a measurable set; * the sets `g • s` over all `g : G` cover almost all points of the whole space; * the sets `g • s`, are pairwise a.e. disjoint, i.e., `μ (g₁ • s ∩ g₂ • s) = 0` whenever `g₁ ≠ g₂`; we require this for `g₂ = 1` in the definition, then deduce it for any two `g₁ ≠ g₂`. In this file we prove that in case of a countable group `G` and a measure preserving action, any two fundamental domains have the same measure, and for a `G`-invariant function, its integrals over any two fundamental domains are equal to each other. We also generate additive versions of all theorems in this file using the `to_additive` attribute. -/ open_locale ennreal pointwise topological_space nnreal ennreal measure_theory open measure_theory measure_theory.measure set function topological_space filter namespace measure_theory /-- A measurable set `s` is a *fundamental domain* for an additive action of an additive group `G` on a measurable space `α` with respect to a measure `α` if the sets `g +ᵥ s`, `g : G`, are pairwise a.e. disjoint and cover the whole space. -/ @[protect_proj] structure is_add_fundamental_domain (G : Type*) {α : Type*} [has_zero G] [has_vadd G α] [measurable_space α] (s : set α) (μ : measure α . volume_tac) : Prop := (null_measurable_set : null_measurable_set s μ) (ae_covers : ∀ᵐ x ∂μ, ∃ g : G, g +ᵥ x ∈ s) (ae_disjoint : ∀ g ≠ (0 : G), ae_disjoint μ (g +ᵥ s) s) /-- A measurable set `s` is a *fundamental domain* for an action of a group `G` on a measurable space `α` with respect to a measure `α` if the sets `g • s`, `g : G`, are pairwise a.e. disjoint and cover the whole space. -/ @[protect_proj, to_additive is_add_fundamental_domain] structure is_fundamental_domain (G : Type*) {α : Type*} [has_one G] [has_scalar G α] [measurable_space α] (s : set α) (μ : measure α . volume_tac) : Prop := (null_measurable_set : null_measurable_set s μ) (ae_covers : ∀ᵐ x ∂μ, ∃ g : G, g • x ∈ s) (ae_disjoint : ∀ g ≠ (1 : G), ae_disjoint μ (g • s) s) namespace is_fundamental_domain variables {G α E : Type*} [group G] [mul_action G α] [measurable_space α] [normed_group E] {s t : set α} {μ : measure α} /-- If for each `x : α`, exactly one of `g • x`, `g : G`, belongs to a measurable set `s`, then `s` is a fundamental domain for the action of `G` on `α`. -/ @[to_additive "If for each `x : α`, exactly one of `g +ᵥ x`, `g : G`, belongs to a measurable set `s`, then `s` is a fundamental domain for the additive action of `G` on `α`."] lemma mk' (h_meas : null_measurable_set s μ) (h_exists : ∀ x : α, ∃! g : G, g • x ∈ s) : is_fundamental_domain G s μ := { null_measurable_set := h_meas, ae_covers := eventually_of_forall $ λ x, (h_exists x).exists, ae_disjoint := λ g hne, disjoint.ae_disjoint $ disjoint_left.2 begin rintro _ ⟨x, hx, rfl⟩ hgx, rw ← one_smul G x at hx, exact hne ((h_exists x).unique hgx hx) end } @[to_additive] lemma Union_smul_ae_eq (h : is_fundamental_domain G s μ) : (⋃ g : G, g • s) =ᵐ[μ] univ := eventually_eq_univ.2 $ h.ae_covers.mono $ λ x ⟨g, hg⟩, mem_Union.2 ⟨g⁻¹, _, hg, inv_smul_smul _ _⟩ @[to_additive] lemma mono (h : is_fundamental_domain G s μ) {ν : measure α} (hle : ν ≪ μ) : is_fundamental_domain G s ν := ⟨h.1.mono_ac hle, hle h.2, λ g hg, hle (h.3 g hg)⟩ variables [measurable_space G] [has_measurable_smul G α] [smul_invariant_measure G α μ] @[to_additive] lemma null_measurable_set_smul (h : is_fundamental_domain G s μ) (g : G) : null_measurable_set (g • s) μ := h.null_measurable_set.smul g @[to_additive] lemma restrict_restrict (h : is_fundamental_domain G s μ) (g : G) (t : set α) : (μ.restrict t).restrict (g • s) = μ.restrict (g • s ∩ t) := restrict_restrict₀ ((h.null_measurable_set_smul g).mono restrict_le_self) @[to_additive] lemma pairwise_ae_disjoint (h : is_fundamental_domain G s μ) : pairwise (λ g₁ g₂ : G, ae_disjoint μ (g₁ • s) (g₂ • s)) := λ g₁ g₂ hne, calc μ (g₁ • s ∩ g₂ • s) = μ (g₂ • ((g₂⁻¹ * g₁) • s ∩ s)) : by rw [smul_set_inter, smul_smul, mul_inv_cancel_left] ... = μ ((g₂⁻¹ * g₁) • s ∩ s) : measure_smul_set _ _ _ ... = 0 : h.ae_disjoint _ $ mt inv_mul_eq_one.1 hne.symm @[to_additive] lemma pairwise_ae_disjoint_of_ac {ν} (h : is_fundamental_domain G s μ) (hν : ν ≪ μ) : pairwise (λ g₁ g₂ : G, ae_disjoint ν (g₁ • s) (g₂ • s)) := h.pairwise_ae_disjoint.mono $ λ g₁ g₂ H, hν H @[to_additive] lemma preimage_of_equiv (h : is_fundamental_domain G s μ) {f : α → α} (hf : quasi_measure_preserving f μ μ) {e : G → G} (he : bijective e) (hef : ∀ g, semiconj f ((•) (e g)) ((•) g)) : is_fundamental_domain G (f ⁻¹' s) μ := { null_measurable_set := h.null_measurable_set.preimage hf, ae_covers := (hf.ae h.ae_covers).mono $ λ x ⟨g, hg⟩, ⟨e g, by rwa [mem_preimage, hef g x]⟩, ae_disjoint := λ g hg, begin lift e to G ≃ G using he, have : (e.symm g⁻¹)⁻¹ ≠ (e.symm 1)⁻¹, by simp [hg], convert (h.pairwise_ae_disjoint _ _ this).preimage hf using 1, { simp only [← preimage_smul_inv, preimage_preimage, ← hef _ _, e.apply_symm_apply, inv_inv] }, { ext1 x, simp only [mem_preimage, ← preimage_smul, ← hef _ _, e.apply_symm_apply, one_smul] } end } @[to_additive] lemma image_of_equiv (h : is_fundamental_domain G s μ) (f : α ≃ᵐ α) (hfμ : measure_preserving f μ μ) (e : equiv.perm G) (hef : ∀ g, semiconj f ((•) (e g)) ((•) g)) : is_fundamental_domain G (f '' s) μ := begin rw f.image_eq_preimage, refine h.preimage_of_equiv (hfμ.symm f).quasi_measure_preserving e.symm.bijective (λ g x, _), rcases f.surjective x with ⟨x, rfl⟩, rw [← hef _ _, f.symm_apply_apply, f.symm_apply_apply, e.apply_symm_apply] end @[to_additive] lemma smul (h : is_fundamental_domain G s μ) (g : G) : is_fundamental_domain G (g • s) μ := h.image_of_equiv (measurable_equiv.smul g) (measure_preserving_smul _ _) ⟨λ g', g⁻¹ * g' * g, λ g', g * g' * g⁻¹, λ g', by simp [mul_assoc], λ g', by simp [mul_assoc]⟩ $ λ g' x, by simp [smul_smul, mul_assoc] @[to_additive] lemma smul_of_comm {G' : Type*} [group G'] [mul_action G' α] [measurable_space G'] [has_measurable_smul G' α] [smul_invariant_measure G' α μ] [smul_comm_class G' G α] (h : is_fundamental_domain G s μ) (g : G') : is_fundamental_domain G (g • s) μ := h.image_of_equiv (measurable_equiv.smul g) (measure_preserving_smul _ _) (equiv.refl _) $ smul_comm g variables [encodable G] {ν : measure α} @[to_additive] lemma sum_restrict_of_ac (h : is_fundamental_domain G s μ) (hν : ν ≪ μ) : sum (λ g : G, ν.restrict (g • s)) = ν := by rw [← restrict_Union_ae (h.pairwise_ae_disjoint.mono $ λ i j h, hν h) (λ g, (h.null_measurable_set_smul g).mono_ac hν), restrict_congr_set (hν h.Union_smul_ae_eq), restrict_univ] @[to_additive] lemma lintegral_eq_tsum_of_ac (h : is_fundamental_domain G s μ) (hν : ν ≪ μ) (f : α → ℝ≥0∞) : ∫⁻ x, f x ∂ν = ∑' g : G, ∫⁻ x in g • s, f x ∂ν := by rw [← lintegral_sum_measure, h.sum_restrict_of_ac hν] @[to_additive] lemma sum_restrict (h : is_fundamental_domain G s μ) : sum (λ g : G, μ.restrict (g • s)) = μ := h.sum_restrict_of_ac (refl _) @[to_additive] lemma lintegral_eq_tsum (h : is_fundamental_domain G s μ) (f : α → ℝ≥0∞) : ∫⁻ x, f x ∂μ = ∑' g : G, ∫⁻ x in g • s, f x ∂μ := h.lintegral_eq_tsum_of_ac (refl _) f @[to_additive] lemma set_lintegral_eq_tsum' (h : is_fundamental_domain G s μ) (f : α → ℝ≥0∞) (t : set α) : ∫⁻ x in t, f x ∂μ = ∑' g : G, ∫⁻ x in t ∩ g • s, f x ∂μ := calc ∫⁻ x in t, f x ∂μ = ∑' g : G, ∫⁻ x in g • s, f x ∂(μ.restrict t) : h.lintegral_eq_tsum_of_ac restrict_le_self.absolutely_continuous _ ... = ∑' g : G, ∫⁻ x in t ∩ g • s, f x ∂μ : by simp only [h.restrict_restrict, inter_comm] @[to_additive] lemma set_lintegral_eq_tsum (h : is_fundamental_domain G s μ) (f : α → ℝ≥0∞) (t : set α) : ∫⁻ x in t, f x ∂μ = ∑' g : G, ∫⁻ x in g • t ∩ s, f (g⁻¹ • x) ∂μ := calc ∫⁻ x in t, f x ∂μ = ∑' g : G, ∫⁻ x in t ∩ g • s, f x ∂μ : h.set_lintegral_eq_tsum' f t ... = ∑' g : G, ∫⁻ x in t ∩ g⁻¹ • s, f x ∂μ : ((equiv.inv G).tsum_eq _).symm ... = ∑' g : G, ∫⁻ x in g⁻¹ • (g • t ∩ s), f (x) ∂μ : by simp only [smul_set_inter, inv_smul_smul] ... = ∑' g : G, ∫⁻ x in g • t ∩ s, f (g⁻¹ • x) ∂μ : tsum_congr $ λ g, ((measure_preserving_smul g⁻¹ μ).set_lintegral_comp_emb (measurable_embedding_const_smul _) _ _).symm @[to_additive] lemma measure_eq_tsum_of_ac (h : is_fundamental_domain G s μ) (hν : ν ≪ μ) (t : set α) : ν t = ∑' g : G, ν (t ∩ g • s) := have H : ν.restrict t ≪ μ, from measure.restrict_le_self.absolutely_continuous.trans hν, by simpa only [set_lintegral_one, pi.one_def, measure.restrict_apply₀ ((h.null_measurable_set_smul _).mono_ac H), inter_comm] using h.lintegral_eq_tsum_of_ac H 1 @[to_additive] lemma measure_eq_tsum' (h : is_fundamental_domain G s μ) (t : set α) : μ t = ∑' g : G, μ (t ∩ g • s) := h.measure_eq_tsum_of_ac absolutely_continuous.rfl t @[to_additive] lemma measure_eq_tsum (h : is_fundamental_domain G s μ) (t : set α) : μ t = ∑' g : G, μ (g • t ∩ s) := by simpa only [set_lintegral_one] using h.set_lintegral_eq_tsum (λ _, 1) t @[to_additive] lemma measure_zero_of_invariant (h : is_fundamental_domain G s μ) (t : set α) (ht : ∀ g : G, g • t = t) (hts : μ (t ∩ s) = 0) : μ t = 0 := by simp [measure_eq_tsum h, ht, hts] @[to_additive] protected lemma set_lintegral_eq (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) (f : α → ℝ≥0∞) (hf : ∀ (g : G) x, f (g • x) = f x) : ∫⁻ x in s, f x ∂μ = ∫⁻ x in t, f x ∂μ := calc ∫⁻ x in s, f x ∂μ = ∑' g : G, ∫⁻ x in s ∩ g • t, f x ∂μ : ht.set_lintegral_eq_tsum' _ _ ... = ∑' g : G, ∫⁻ x in g • t ∩ s, f (g⁻¹ • x) ∂μ : by simp only [hf, inter_comm] ... = ∫⁻ x in t, f x ∂μ : (hs.set_lintegral_eq_tsum _ _).symm @[to_additive] lemma measure_set_eq (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) {A : set α} (hA₀ : measurable_set A) (hA : ∀ (g : G), (λ x, g • x) ⁻¹' A = A) : μ (A ∩ s) = μ (A ∩ t) := begin have : ∫⁻ x in s, A.indicator 1 x ∂μ = ∫⁻ x in t, A.indicator 1 x ∂μ, { refine hs.set_lintegral_eq ht (set.indicator A (λ _, 1)) _, intros g x, convert (set.indicator_comp_right (λ x : α, g • x)).symm, rw hA g }, simpa [measure.restrict_apply hA₀, lintegral_indicator _ hA₀] using this end /-- If `s` and `t` are two fundamental domains of the same action, then their measures are equal. -/ @[to_additive "If `s` and `t` are two fundamental domains of the same action, then their measures are equal."] protected lemma measure_eq (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) : μ s = μ t := by simpa only [set_lintegral_one] using hs.set_lintegral_eq ht (λ _, 1) (λ _ _, rfl) @[to_additive] protected lemma ae_strongly_measurable_on_iff {β : Type*} [topological_space β] [metrizable_space β] (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) {f : α → β} (hf : ∀ (g : G) x, f (g • x) = f x) : ae_strongly_measurable f (μ.restrict s) ↔ ae_strongly_measurable f (μ.restrict t) := calc ae_strongly_measurable f (μ.restrict s) ↔ ae_strongly_measurable f (measure.sum $ λ g : G, (μ.restrict (g • t ∩ s))) : by simp only [← ht.restrict_restrict, ht.sum_restrict_of_ac restrict_le_self.absolutely_continuous] ... ↔ ∀ g : G, ae_strongly_measurable f (μ.restrict (g • (g⁻¹ • s ∩ t))) : by simp only [smul_set_inter, inter_comm, smul_inv_smul, ae_strongly_measurable_sum_measure_iff] ... ↔ ∀ g : G, ae_strongly_measurable f (μ.restrict (g⁻¹ • (g⁻¹⁻¹ • s ∩ t))) : inv_surjective.forall ... ↔ ∀ g : G, ae_strongly_measurable f (μ.restrict (g⁻¹ • (g • s ∩ t))) : by simp only [inv_inv] ... ↔ ∀ g : G, ae_strongly_measurable f (μ.restrict (g • s ∩ t)) : begin refine forall_congr (λ g, _), have he : measurable_embedding ((•) g⁻¹ : α → α) := measurable_embedding_const_smul _, rw [← image_smul, ← ((measure_preserving_smul g⁻¹ μ).restrict_image_emb he _).ae_strongly_measurable_comp_iff he], simp only [(∘), hf] end ... ↔ ae_strongly_measurable f (μ.restrict t) : by simp only [← ae_strongly_measurable_sum_measure_iff, ← hs.restrict_restrict, hs.sum_restrict_of_ac restrict_le_self.absolutely_continuous] @[to_additive] protected lemma has_finite_integral_on_iff (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) {f : α → E} (hf : ∀ (g : G) x, f (g • x) = f x) : has_finite_integral f (μ.restrict s) ↔ has_finite_integral f (μ.restrict t) := begin dunfold has_finite_integral, rw hs.set_lintegral_eq ht, intros g x, rw hf end @[to_additive] protected lemma integrable_on_iff (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) {f : α → E} (hf : ∀ (g : G) x, f (g • x) = f x) : integrable_on f s μ ↔ integrable_on f t μ := and_congr (hs.ae_strongly_measurable_on_iff ht hf) (hs.has_finite_integral_on_iff ht hf) variables [normed_space ℝ E] [complete_space E] @[to_additive] protected lemma set_integral_eq (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) {f : α → E} (hf : ∀ (g : G) x, f (g • x) = f x) : ∫ x in s, f x ∂μ = ∫ x in t, f x ∂μ := begin by_cases hfs : integrable_on f s μ, { have hft : integrable_on f t μ, by rwa ht.integrable_on_iff hs hf, have hac : ∀ {u}, μ.restrict u ≪ μ := λ u, restrict_le_self.absolutely_continuous, calc ∫ x in s, f x ∂μ = ∫ x in ⋃ g : G, g • t, f x ∂(μ.restrict s) : by rw [restrict_congr_set (hac ht.Union_smul_ae_eq), restrict_univ] ... = ∑' g : G, ∫ x in g • t, f x ∂(μ.restrict s) : integral_Union_ae (λ g, (ht.null_measurable_set_smul g).mono_ac hac) (ht.pairwise_ae_disjoint_of_ac hac) hfs.integrable.integrable_on ... = ∑' g : G, ∫ x in s ∩ g • t, f x ∂μ : by simp only [ht.restrict_restrict, inter_comm] ... = ∑' g : G, ∫ x in s ∩ g⁻¹ • t, f x ∂μ : ((equiv.inv G).tsum_eq _).symm ... = ∑' g : G, ∫ x in g⁻¹ • (g • s ∩ t), f x ∂μ : by simp only [smul_set_inter, inv_smul_smul] ... = ∑' g : G, ∫ x in g • s ∩ t, f (g⁻¹ • x) ∂μ : tsum_congr $ λ g, (measure_preserving_smul g⁻¹ μ).set_integral_image_emb (measurable_embedding_const_smul _) _ _ ... = ∑' g : G, ∫ x in g • s, f x ∂(μ.restrict t) : by simp only [hf, hs.restrict_restrict] ... = ∫ x in ⋃ g : G, g • s, f x ∂(μ.restrict t) : (integral_Union_ae (λ g, (hs.null_measurable_set_smul g).mono_ac hac) (hs.pairwise_ae_disjoint.mono $ λ i j h, hac h) hft.integrable.integrable_on).symm ... = ∫ x in t, f x ∂μ : by rw [restrict_congr_set (hac hs.Union_smul_ae_eq), restrict_univ] }, { rw [integral_undef hfs, integral_undef], rwa [hs.integrable_on_iff ht hf] at hfs } end /-- If `f` is invariant under the action of a countable group `G`, and `μ` is a `G`-invariant measure with a fundamental domain `s`, then the `ess_sup` of `f` restricted to `s` is the same as that of `f` on all of its domain. -/ @[to_additive "If `f` is invariant under the action of a countable additive group `G`, and `μ` is a `G`-invariant measure with a fundamental domain `s`, then the `ess_sup` of `f` restricted to `s` is the same as that of `f` on all of its domain."] lemma ess_sup_measure_restrict (hs : is_fundamental_domain G s μ) {f : α → ℝ≥0∞} (hf : ∀ γ : G, ∀ x: α, f (γ • x) = f x) : ess_sup f (μ.restrict s) = ess_sup f μ := begin refine le_antisymm (ess_sup_mono_measure' measure.restrict_le_self) _, rw [ess_sup_eq_Inf (μ.restrict s) f, ess_sup_eq_Inf μ f], refine Inf_le_Inf _, rintro a (ha : (μ.restrict s) {x : α | a < f x} = 0), rw measure.restrict_apply₀' hs.null_measurable_set at ha, refine measure_zero_of_invariant hs _ _ ha, intros γ, ext x, rw mem_smul_set_iff_inv_smul_mem, simp only [mem_set_of_eq, hf (γ⁻¹) x], end end is_fundamental_domain end measure_theory
68fce6bb936b9087000d1450ec6c049eb00913ec
4727251e0cd73359b15b664c3170e5d754078599
/src/linear_algebra/trace.lean
ddc990b3906895a9a541d47a6a0b2a899e837c2d
[ "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,399
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, Patrick Massot, Casper Putz, Anne Baanen, Antoine Labelle -/ import linear_algebra.matrix.to_lin import linear_algebra.matrix.trace import linear_algebra.contraction import linear_algebra.tensor_product_basis import linear_algebra.free_module.strong_rank_condition /-! # Trace of a linear map This file defines the trace of a linear map. See also `linear_algebra/matrix/trace.lean` for the trace of a matrix. ## Tags linear_map, trace, diagonal -/ noncomputable theory universes u v w namespace linear_map open_locale big_operators open_locale matrix open finite_dimensional open_locale tensor_product section variables (R : Type u) [comm_ring R] {M : Type v} [add_comm_group M] [module R M] variables {ι : Type w} [decidable_eq ι] [fintype ι] variables {κ : Type*} [decidable_eq κ] [fintype κ] variables (b : basis ι R M) (c : basis κ R M) /-- The trace of an endomorphism given a basis. -/ def trace_aux : (M →ₗ[R] M) →ₗ[R] R := (matrix.trace_linear_map ι R R) ∘ₗ ↑(linear_map.to_matrix b b) -- Can't be `simp` because it would cause a loop. lemma trace_aux_def (b : basis ι R M) (f : M →ₗ[R] M) : trace_aux R b f = matrix.trace (linear_map.to_matrix b b f) := rfl theorem trace_aux_eq : trace_aux R b = trace_aux R c := linear_map.ext $ λ f, calc matrix.trace (linear_map.to_matrix b b f) = matrix.trace (linear_map.to_matrix b b ((linear_map.id.comp f).comp linear_map.id)) : by rw [linear_map.id_comp, linear_map.comp_id] ... = matrix.trace (linear_map.to_matrix c b linear_map.id ⬝ linear_map.to_matrix c c f ⬝ linear_map.to_matrix b c linear_map.id) : by rw [linear_map.to_matrix_comp _ c, linear_map.to_matrix_comp _ c] ... = matrix.trace (linear_map.to_matrix c c f ⬝ linear_map.to_matrix b c linear_map.id ⬝ linear_map.to_matrix c b linear_map.id) : by rw [matrix.mul_assoc, matrix.trace_mul_comm] ... = matrix.trace (linear_map.to_matrix c c ((f.comp linear_map.id).comp linear_map.id)) : by rw [linear_map.to_matrix_comp _ b, linear_map.to_matrix_comp _ c] ... = matrix.trace (linear_map.to_matrix c c f) : by rw [linear_map.comp_id, linear_map.comp_id] open_locale classical variables (R) (M) /-- Trace of an endomorphism independent of basis. -/ def trace : (M →ₗ[R] M) →ₗ[R] R := if H : ∃ (s : finset M), nonempty (basis s R M) then trace_aux R H.some_spec.some else 0 variables (R) {M} /-- Auxiliary lemma for `trace_eq_matrix_trace`. -/ theorem trace_eq_matrix_trace_of_finset {s : finset M} (b : basis s R M) (f : M →ₗ[R] M) : trace R M f = matrix.trace (linear_map.to_matrix b b f) := have ∃ (s : finset M), nonempty (basis s R M), from ⟨s, ⟨b⟩⟩, by { rw [trace, dif_pos this, ← trace_aux_def], congr' 1, apply trace_aux_eq } theorem trace_eq_matrix_trace (f : M →ₗ[R] M) : trace R M f = matrix.trace (linear_map.to_matrix b b f) := by rw [trace_eq_matrix_trace_of_finset R b.reindex_finset_range, ← trace_aux_def, ← trace_aux_def, trace_aux_eq R b] theorem trace_mul_comm (f g : M →ₗ[R] M) : trace R M (f * g) = trace R M (g * f) := if H : ∃ (s : finset M), nonempty (basis s R M) then let ⟨s, ⟨b⟩⟩ := H in by { simp_rw [trace_eq_matrix_trace R b, linear_map.to_matrix_mul], apply matrix.trace_mul_comm } else by rw [trace, dif_neg H, linear_map.zero_apply, linear_map.zero_apply] /-- The trace of an endomorphism is invariant under conjugation -/ @[simp] theorem trace_conj (g : M →ₗ[R] M) (f : (M →ₗ[R] M)ˣ) : trace R M (↑f * g * ↑f⁻¹) = trace R M g := by { rw trace_mul_comm, simp } end section variables {R : Type*} [comm_ring R] {M : Type*} [add_comm_group M] [module R M] variables (N : Type*) [add_comm_group N] [module R N] variables {ι : Type*} [fintype ι] /-- The trace of a linear map correspond to the contraction pairing under the isomorphism `End(M) ≃ M* ⊗ M`-/ lemma trace_eq_contract_of_basis (b : basis ι R M) : (linear_map.trace R M) ∘ₗ (dual_tensor_hom R M M) = contract_left R M := begin classical, apply basis.ext (basis.tensor_product (basis.dual_basis b) b), rintros ⟨i, j⟩, simp only [function.comp_app, basis.tensor_product_apply, basis.coe_dual_basis, coe_comp], rw [trace_eq_matrix_trace R b, to_matrix_dual_tensor_hom], by_cases hij : i = j, { rw [hij], simp }, rw matrix.std_basis_matrix.trace_zero j i (1:R) hij, simp [finsupp.single_eq_pi_single, hij], end /-- The trace of a linear map correspond to the contraction pairing under the isomorphism `End(M) ≃ M* ⊗ M`-/ lemma trace_eq_contract_of_basis' [decidable_eq ι] (b : basis ι R M) : (linear_map.trace R M) = (contract_left R M) ∘ₗ (dual_tensor_hom_equiv_of_basis b).symm.to_linear_map := by simp [linear_equiv.eq_comp_to_linear_map_symm, trace_eq_contract_of_basis b] variables (R M) variables [module.free R M] [module.finite R M] [module.free R N] [module.finite R N] [nontrivial R] /-- When `M` is finite free, the trace of a linear map correspond to the contraction pairing under the isomorphism `End(M) ≃ M* ⊗ M`-/ @[simp] theorem trace_eq_contract : (linear_map.trace R M) ∘ₗ (dual_tensor_hom R M M) = contract_left R M := trace_eq_contract_of_basis (module.free.choose_basis R M) @[simp] theorem trace_eq_contract_apply (x : module.dual R M ⊗[R] M) : (linear_map.trace R M) ((dual_tensor_hom R M M) x) = contract_left R M x := by rw [←comp_apply, trace_eq_contract] open_locale classical /-- When `M` is finite free, the trace of a linear map correspond to the contraction pairing under the isomorphism `End(M) ≃ M* ⊗ M`-/ theorem trace_eq_contract' : (linear_map.trace R M) = (contract_left R M) ∘ₗ (dual_tensor_hom_equiv R M M).symm.to_linear_map := trace_eq_contract_of_basis' (module.free.choose_basis R M) /-- The trace of the identity endomorphism is the dimension of the free module -/ @[simp] theorem trace_one : trace R M 1 = (finrank R M : R) := begin have b := module.free.choose_basis R M, rw [trace_eq_matrix_trace R b, to_matrix_one, module.free.finrank_eq_card_choose_basis_index], simp, end variables (M) theorem trace_comp_comm : compr₂ (llcomp R M N M) (trace R M) = compr₂ (llcomp R N M N).flip (trace R N) := begin apply (compl₁₂_inj (dual_tensor_hom_equiv R N M).surjective (dual_tensor_hom_equiv R M N).surjective).1, ext g m f n, simp only [tensor_product.algebra_tensor_module.curry_apply, to_fun_eq_coe, tensor_product.curry_apply, coe_restrict_scalars_eq_coe, compl₁₂_apply, compr₂_apply, flip_apply, llcomp_apply', comp_dual_tensor_hom, map_smul, trace_eq_contract_apply, contract_left_apply, smul_eq_mul, mul_comm], end variables {R M} theorem trace_comp_comm' (f : M →ₗ[R] N) (g : N →ₗ[R] M) : trace R M (g ∘ₗ f) = trace R N (f ∘ₗ g) := begin have h := ext_iff.1 (ext_iff.1 (trace_comp_comm R M N) g) f, simp only [llcomp_apply', compr₂_apply, flip_apply] at h, exact h, end @[simp] theorem trace_conj' (f : M →ₗ[R] M) (e : M ≃ₗ[R] N) : trace R N (e.conj f) = trace R M f := by rw [e.conj_apply, trace_comp_comm', ←comp_assoc, linear_equiv.comp_coe, linear_equiv.self_trans_symm, linear_equiv.refl_to_linear_map, id_comp] end end linear_map
e94769b7d318cdfa2b57ec965e659cf580f6de09
c777c32c8e484e195053731103c5e52af26a25d1
/src/ring_theory/valuation/valuation_ring.lean
e52900b6e6bfa319963d07acc4bbbce3f6b7a498
[ "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
17,210
lean
/- Copyright (c) 2022 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Adam Topaz -/ import ring_theory.valuation.integers import ring_theory.ideal.local_ring import ring_theory.localization.fraction_ring import ring_theory.localization.integer import ring_theory.discrete_valuation_ring.basic import ring_theory.bezout import tactic.field_simp /-! # Valuation Rings A valuation ring is a domain such that for every pair of elements `a b`, either `a` divides `b` or vice-versa. Any valuation ring induces a natural valuation on its fraction field, as we show in this file. Namely, given the following instances: `[comm_ring A] [is_domain A] [valuation_ring A] [field K] [algebra A K] [is_fraction_ring A K]`, there is a natural valuation `valuation A K` on `K` with values in `value_group A K` where the image of `A` under `algebra_map A K` agrees with `(valuation A K).integer`. We also provide the equivalence of the following notions for a domain `R` in `valuation_ring.tfae`. 1. `R` is a valuation ring. 2. For each `x : fraction_ring K`, either `x` or `x⁻¹` is in `R`. 3. "divides" is a total relation on the elements of `R`. 4. "contains" is a total relation on the ideals of `R`. 5. `R` is a local bezout domain. -/ universes u v w /-- An integral domain is called a `valuation ring` provided that for any pair of elements `a b : A`, either `a` divides `b` or vice versa. -/ class valuation_ring (A : Type u) [comm_ring A] [is_domain A] : Prop := (cond [] : ∀ a b : A, ∃ c : A, a * c = b ∨ b * c = a) namespace valuation_ring section variables (A : Type u) [comm_ring A] variables (K : Type v) [field K] [algebra A K] /-- The value group of the valuation ring `A`. Note: this is actually a group with zero. -/ def value_group : Type v := quotient (mul_action.orbit_rel Aˣ K) instance : inhabited (value_group A K) := ⟨quotient.mk' 0⟩ instance : has_le (value_group A K) := has_le.mk $ λ x y, quotient.lift_on₂' x y (λ a b, ∃ c : A, c • b = a) begin rintros _ _ a b ⟨c,rfl⟩ ⟨d,rfl⟩, ext, split, { rintros ⟨e,he⟩, use ((c⁻¹ : Aˣ) * e * d), apply_fun (λ t, c⁻¹ • t) at he, simpa [mul_smul] using he }, { rintros ⟨e,he⟩, dsimp, use (d⁻¹ : Aˣ) * c * e, erw [← he, ← mul_smul, ← mul_smul], congr' 1, rw mul_comm, simp only [← mul_assoc, ← units.coe_mul, mul_inv_self, one_mul] } end instance : has_zero (value_group A K) := ⟨quotient.mk' 0⟩ instance : has_one (value_group A K) := ⟨quotient.mk' 1⟩ instance : has_mul (value_group A K) := has_mul.mk $ λ x y, quotient.lift_on₂' x y (λ a b, quotient.mk' $ a * b) begin rintros _ _ a b ⟨c,rfl⟩ ⟨d,rfl⟩, apply quotient.sound', dsimp, use c * d, simp only [mul_smul, algebra.smul_def, units.smul_def, ring_hom.map_mul, units.coe_mul], ring, end instance : has_inv (value_group A K) := has_inv.mk $ λ x, quotient.lift_on' x (λ a, quotient.mk' a⁻¹) begin rintros _ a ⟨b,rfl⟩, apply quotient.sound', use b⁻¹, dsimp, rw [units.smul_def, units.smul_def, algebra.smul_def, algebra.smul_def, mul_inv, map_units_inv], end variables [is_domain A] [valuation_ring A] [is_fraction_ring A K] protected lemma le_total (a b : value_group A K) : a ≤ b ∨ b ≤ a := begin rcases a with ⟨a⟩, rcases b with ⟨b⟩, obtain ⟨xa,ya,hya,rfl⟩ : ∃ (a b : A), _ := is_fraction_ring.div_surjective a, obtain ⟨xb,yb,hyb,rfl⟩ : ∃ (a b : A), _ := is_fraction_ring.div_surjective b, have : (algebra_map A K) ya ≠ 0 := is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors hya, have : (algebra_map A K) yb ≠ 0 := is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors hyb, obtain ⟨c,(h|h)⟩ := valuation_ring.cond (xa * yb) (xb * ya), { right, use c, rw algebra.smul_def, field_simp, simp only [← ring_hom.map_mul, ← h], congr' 1, ring }, { left, use c, rw algebra.smul_def, field_simp, simp only [← ring_hom.map_mul, ← h], congr' 1, ring } end noncomputable instance : linear_ordered_comm_group_with_zero (value_group A K) := { le_refl := by { rintro ⟨⟩, use 1, rw one_smul }, le_trans := by { rintros ⟨a⟩ ⟨b⟩ ⟨c⟩ ⟨e,rfl⟩ ⟨f,rfl⟩, use (e * f), rw mul_smul }, le_antisymm := begin rintros ⟨a⟩ ⟨b⟩ ⟨e,rfl⟩ ⟨f,hf⟩, by_cases hb : b = 0, { simp [hb] }, have : is_unit e, { apply is_unit_of_dvd_one, use f, rw mul_comm, rw [← mul_smul, algebra.smul_def] at hf, nth_rewrite 1 ← one_mul b at hf, rw ← (algebra_map A K).map_one at hf, exact is_fraction_ring.injective _ _ (mul_right_cancel₀ hb hf).symm }, apply quotient.sound', use [this.unit, rfl], end, le_total := valuation_ring.le_total _ _, decidable_le := by { classical, apply_instance }, mul_assoc := by { rintros ⟨a⟩ ⟨b⟩ ⟨c⟩, apply quotient.sound', rw mul_assoc, apply setoid.refl' }, one_mul := by { rintros ⟨a⟩, apply quotient.sound', rw one_mul, apply setoid.refl' }, mul_one := by { rintros ⟨a⟩, apply quotient.sound', rw mul_one, apply setoid.refl' }, mul_comm := by { rintros ⟨a⟩ ⟨b⟩, apply quotient.sound', rw mul_comm, apply setoid.refl' }, mul_le_mul_left := begin rintros ⟨a⟩ ⟨b⟩ ⟨c,rfl⟩ ⟨d⟩, use c, simp only [algebra.smul_def], ring, end, zero_mul := by { rintros ⟨a⟩, apply quotient.sound', rw zero_mul, apply setoid.refl' }, mul_zero := by { rintros ⟨a⟩, apply quotient.sound', rw mul_zero, apply setoid.refl' }, zero_le_one := ⟨0, by rw zero_smul⟩, exists_pair_ne := begin use [0,1], intro c, obtain ⟨d,hd⟩ := quotient.exact' c, apply_fun (λ t, d⁻¹ • t) at hd, simpa using hd, end, inv_zero := by { apply quotient.sound', rw inv_zero, apply setoid.refl' }, mul_inv_cancel := begin rintros ⟨a⟩ ha, apply quotient.sound', use 1, simp only [one_smul], apply (mul_inv_cancel _).symm, contrapose ha, simp only [not_not] at ha ⊢, rw ha, refl, end, ..(infer_instance : has_le (value_group A K)), ..(infer_instance : has_mul (value_group A K)), ..(infer_instance : has_inv (value_group A K)), ..(infer_instance : has_zero (value_group A K)), ..(infer_instance : has_one (value_group A K)) } /-- Any valuation ring induces a valuation on its fraction field. -/ def valuation : valuation K (value_group A K) := { to_fun := quotient.mk', map_zero' := rfl, map_one' := rfl, map_mul' := λ _ _, rfl, map_add_le_max' := begin intros a b, obtain ⟨xa,ya,hya,rfl⟩ : ∃ (a b : A), _ := is_fraction_ring.div_surjective a, obtain ⟨xb,yb,hyb,rfl⟩ : ∃ (a b : A), _ := is_fraction_ring.div_surjective b, have : (algebra_map A K) ya ≠ 0 := is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors hya, have : (algebra_map A K) yb ≠ 0 := is_fraction_ring.to_map_ne_zero_of_mem_non_zero_divisors hyb, obtain ⟨c,(h|h)⟩ := valuation_ring.cond (xa * yb) (xb * ya), dsimp, { apply le_trans _ (le_max_left _ _), use (c + 1), rw algebra.smul_def, field_simp, simp only [← ring_hom.map_mul, ← ring_hom.map_add, ← (algebra_map A K).map_one, ← h], congr' 1, ring }, { apply le_trans _ (le_max_right _ _), use (c + 1), rw algebra.smul_def, field_simp, simp only [← ring_hom.map_mul, ← ring_hom.map_add, ← (algebra_map A K).map_one, ← h], congr' 1, ring } end } lemma mem_integer_iff (x : K) : x ∈ (valuation A K).integer ↔ ∃ a : A, algebra_map A K a = x := begin split, { rintros ⟨c,rfl⟩, use c, rw [algebra.smul_def, mul_one] }, { rintro ⟨c,rfl⟩, use c, rw [algebra.smul_def, mul_one] } end /-- The valuation ring `A` is isomorphic to the ring of integers of its associated valuation. -/ noncomputable def equiv_integer : A ≃+* (valuation A K).integer := ring_equiv.of_bijective (show A →ₙ+* (valuation A K).integer, from { to_fun := λ a, ⟨algebra_map A K a, (mem_integer_iff _ _ _).mpr ⟨a,rfl⟩⟩, map_mul' := λ _ _, by { ext1, exact (algebra_map A K).map_mul _ _ }, map_zero' := by { ext1, exact (algebra_map A K).map_zero }, map_add' := λ _ _, by { ext1, exact (algebra_map A K).map_add _ _ } }) begin split, { intros x y h, apply_fun (coe : _ → K) at h, dsimp at h, exact is_fraction_ring.injective _ _ h }, { rintros ⟨a,(ha : a ∈ (valuation A K).integer)⟩, rw mem_integer_iff at ha, obtain ⟨a,rfl⟩ := ha, use [a, rfl] } end @[simp] lemma coe_equiv_integer_apply (a : A) : (equiv_integer A K a : K) = algebra_map A K a := rfl lemma range_algebra_map_eq : (valuation A K).integer = (algebra_map A K).range := by { ext, exact mem_integer_iff _ _ _ } end section variables (A : Type u) [comm_ring A] [is_domain A] [valuation_ring A] @[priority 100] instance : local_ring A := local_ring.of_is_unit_or_is_unit_one_sub_self begin intros a, obtain ⟨c,(h|h)⟩ := valuation_ring.cond a (1-a), { left, apply is_unit_of_mul_eq_one _ (c+1), simp [mul_add, h] }, { right, apply is_unit_of_mul_eq_one _ (c+1), simp [mul_add, h] } end instance [decidable_rel ((≤) : ideal A → ideal A → Prop)] : linear_order (ideal A) := { le_total := begin intros α β, by_cases h : α ≤ β, { exact or.inl h }, erw not_forall at h, push_neg at h, obtain ⟨a,h₁,h₂⟩ := h, right, intros b hb, obtain ⟨c,(h|h)⟩ := valuation_ring.cond a b, { rw ← h, exact ideal.mul_mem_right _ _ h₁ }, { exfalso, apply h₂, rw ← h, apply ideal.mul_mem_right _ _ hb }, end, decidable_le := infer_instance, ..(infer_instance : complete_lattice (ideal A)) } end section variables {R : Type*} [comm_ring R] [is_domain R] {K : Type*} variables [field K] [algebra R K] [is_fraction_ring R K] lemma iff_dvd_total : valuation_ring R ↔ is_total R (∣) := begin classical, refine ⟨λ H, ⟨λ a b, _⟩, λ H, ⟨λ a b, _⟩⟩; resetI, { obtain ⟨c,rfl|rfl⟩ := @@valuation_ring.cond _ _ H a b; simp }, { obtain (⟨c, rfl⟩|⟨c, rfl⟩) := @is_total.total _ _ H a b; use c; simp } end lemma iff_ideal_total : valuation_ring R ↔ is_total (ideal R) (≤) := begin classical, refine ⟨λ _, by exactI ⟨le_total⟩, λ H, iff_dvd_total.mpr ⟨λ a b, _⟩⟩, have := @is_total.total _ _ H (ideal.span {a}) (ideal.span {b}), simp_rw ideal.span_singleton_le_span_singleton at this, exact this.symm end variables {R} (K) lemma dvd_total [h : valuation_ring R] (x y : R) : x ∣ y ∨ y ∣ x := @@is_total.total _ (iff_dvd_total.mp h) x y lemma unique_irreducible [valuation_ring R] ⦃p q : R⦄ (hp : irreducible p) (hq : irreducible q) : associated p q := begin have := dvd_total p q, rw [irreducible.dvd_comm hp hq, or_self] at this, exact associated_of_dvd_dvd (irreducible.dvd_symm hq hp this) this, end variable (R) lemma iff_is_integer_or_is_integer : valuation_ring R ↔ ∀ x : K, is_localization.is_integer R x ∨ is_localization.is_integer R x⁻¹ := begin split, { introsI H x, obtain ⟨x : R, y, hy, rfl⟩ := is_fraction_ring.div_surjective x, any_goals { apply_instance }, have := (map_ne_zero_iff _ (is_fraction_ring.injective R K)).mpr (non_zero_divisors.ne_zero hy), obtain ⟨s, rfl|rfl⟩ := valuation_ring.cond x y, { exact or.inr ⟨s, eq_inv_of_mul_eq_one_left $ by rwa [mul_div, div_eq_one_iff_eq, map_mul, mul_comm]⟩ }, { exact or.inl ⟨s, by rwa [eq_div_iff, map_mul, mul_comm]⟩ } }, { intro H, constructor, intros a b, by_cases ha : a = 0, { subst ha, exact ⟨0, or.inr $ mul_zero b⟩ }, by_cases hb : b = 0, { subst hb, exact ⟨0, or.inl $ mul_zero a⟩ }, replace ha := (map_ne_zero_iff _ (is_fraction_ring.injective R K)).mpr ha, replace hb := (map_ne_zero_iff _ (is_fraction_ring.injective R K)).mpr hb, obtain ⟨c, e⟩|⟨c, e⟩ := H (algebra_map R K a / algebra_map R K b), { rw [eq_div_iff hb, ← map_mul, (is_fraction_ring.injective R K).eq_iff, mul_comm] at e, exact ⟨c, or.inr e⟩ }, { rw [inv_div, eq_div_iff ha, ← map_mul, (is_fraction_ring.injective R K).eq_iff, mul_comm c] at e, exact ⟨c, or.inl e⟩ } } end variable {K} lemma is_integer_or_is_integer [h : valuation_ring R] (x : K) : is_localization.is_integer R x ∨ is_localization.is_integer R x⁻¹ := (iff_is_integer_or_is_integer R K).mp h x variable {R} -- This implies that valuation rings are integrally closed through typeclass search. @[priority 100] instance [valuation_ring R] : is_bezout R := begin classical, rw is_bezout.iff_span_pair_is_principal, intros x y, rw ideal.span_insert, cases le_total (ideal.span {x} : ideal R) (ideal.span {y}), { erw sup_eq_right.mpr h, exact ⟨⟨_, rfl⟩⟩ }, { erw sup_eq_left.mpr h, exact ⟨⟨_, rfl⟩⟩ } end lemma iff_local_bezout_domain : valuation_ring R ↔ local_ring R ∧ is_bezout R := begin classical, refine ⟨λ H, by exactI ⟨infer_instance, infer_instance⟩, _⟩, rintro ⟨h₁, h₂⟩, resetI, refine iff_dvd_total.mpr ⟨λ a b, _⟩, obtain ⟨g, e : _ = ideal.span _⟩ := is_bezout.span_pair_is_principal a b, obtain ⟨a, rfl⟩ := ideal.mem_span_singleton'.mp (show a ∈ ideal.span {g}, by { rw [← e], exact ideal.subset_span (by simp) }), obtain ⟨b, rfl⟩ := ideal.mem_span_singleton'.mp (show b ∈ ideal.span {g}, by { rw [← e], exact ideal.subset_span (by simp) }), obtain ⟨x, y, e'⟩ := ideal.mem_span_pair.mp (show g ∈ ideal.span {a * g, b * g}, by { rw e, exact ideal.subset_span (by simp) }), cases eq_or_ne g 0 with h h, { simp [h] }, have : x * a + y * b = 1, { apply mul_left_injective₀ h, convert e'; ring_nf }, cases local_ring.is_unit_or_is_unit_of_add_one this with h' h', left, swap, right, all_goals { exact mul_dvd_mul_right (is_unit_iff_forall_dvd.mp (is_unit_of_mul_is_unit_right h') _) _ }, end protected lemma tfae (R : Type u) [comm_ring R] [is_domain R] : tfae [valuation_ring R, ∀ x : fraction_ring R, is_localization.is_integer R x ∨ is_localization.is_integer R x⁻¹, is_total R (∣), is_total (ideal R) (≤), local_ring R ∧ is_bezout R] := begin tfae_have : 1 ↔ 2, { exact iff_is_integer_or_is_integer R _ }, tfae_have : 1 ↔ 3, { exact iff_dvd_total }, tfae_have : 1 ↔ 4, { exact iff_ideal_total }, tfae_have : 1 ↔ 5, { exact iff_local_bezout_domain }, tfae_finish end end lemma _root_.function.surjective.valuation_ring {R S : Type*} [comm_ring R] [is_domain R] [valuation_ring R] [comm_ring S] [is_domain S] (f : R →+* S) (hf : function.surjective f) : valuation_ring S := ⟨λ a b, begin obtain ⟨⟨a, rfl⟩, ⟨b, rfl⟩⟩ := ⟨hf a, hf b⟩, obtain ⟨c, rfl|rfl⟩ := valuation_ring.cond a b, exacts [⟨f c, or.inl $ (map_mul _ _ _).symm⟩, ⟨f c, or.inr $ (map_mul _ _ _).symm⟩], end⟩ section variables {𝒪 : Type u} {K : Type v} {Γ : Type w} [comm_ring 𝒪] [is_domain 𝒪] [field K] [algebra 𝒪 K] [linear_ordered_comm_group_with_zero Γ] (v : _root_.valuation K Γ) (hh : v.integers 𝒪) include hh /-- If `𝒪` satisfies `v.integers 𝒪` where `v` is a valuation on a field, then `𝒪` is a valuation ring. -/ lemma of_integers : valuation_ring 𝒪 := begin constructor, intros a b, cases le_total (v (algebra_map 𝒪 K a)) (v (algebra_map 𝒪 K b)), { obtain ⟨c,hc⟩ := valuation.integers.dvd_of_le hh h, use c, exact or.inr hc.symm }, { obtain ⟨c,hc⟩ := valuation.integers.dvd_of_le hh h, use c, exact or.inl hc.symm } end end section variables (K : Type u) [field K] /-- A field is a valuation ring. -/ @[priority 100] instance of_field : valuation_ring K := begin constructor, intros a b, by_cases b = 0, { use 0, left, simp [h] }, { use a * b⁻¹, right, field_simp, rw mul_comm } end end section variables (A : Type u) [comm_ring A] [is_domain A] [discrete_valuation_ring A] /-- A DVR is a valuation ring. -/ @[priority 100] instance of_discrete_valuation_ring : valuation_ring A := begin constructor, intros a b, by_cases ha : a = 0, { use 0, right, simp [ha] }, by_cases hb : b = 0, { use 0, left, simp [hb] }, obtain ⟨ϖ,hϖ⟩ := discrete_valuation_ring.exists_irreducible A, obtain ⟨m,u,rfl⟩ := discrete_valuation_ring.eq_unit_mul_pow_irreducible ha hϖ, obtain ⟨n,v,rfl⟩ := discrete_valuation_ring.eq_unit_mul_pow_irreducible hb hϖ, cases le_total m n with h h, { use (u⁻¹ * v : Aˣ) * ϖ^(n-m), left, simp_rw [mul_comm (u : A), units.coe_mul, ← mul_assoc, mul_assoc _ (u : A)], simp only [units.mul_inv, mul_one, mul_comm _ (v : A), mul_assoc, ← pow_add], congr' 2, linarith }, { use (v⁻¹ * u : Aˣ) * ϖ^(m-n), right, simp_rw [mul_comm (v : A), units.coe_mul, ← mul_assoc, mul_assoc _ (v : A)], simp only [units.mul_inv, mul_one, mul_comm _ (u : A), mul_assoc, ← pow_add], congr' 2, linarith } end end end valuation_ring
0d76dcda348214ad6ae3a4f07b09bafacf5b4816
a9d0fb7b0e4f802bd3857b803e6c5c23d87fef91
/tests/lean/list_monad1.lean
47b708eb9b0deb238ad48dbdacd05ad71734f456
[ "Apache-2.0" ]
permissive
soonhokong/lean-osx
4a954262c780e404c1369d6c06516161d07fcb40
3670278342d2f4faa49d95b46d86642d7875b47c
refs/heads/master
1,611,410,334,552
1,474,425,686,000
1,474,425,686,000
12,043,103
5
1
null
null
null
null
UTF-8
Lean
false
false
170
lean
vm_eval (do { a : nat ← [1, 2, 3, 4], b : nat ← [4, 5, 6], (guard $ 2 * a ≥ b : list unit), (guard $ b < 6 : list unit), return (a, b) } : list (nat × nat) )
8d76385ceff05ca16b83c1ca577eef6e18f566e7
96338d06deb5f54f351493a71d6ecf6c546089a2
/priv/Lean/Functor.lean
2820eaf860e03d09b7277797fb8462d86a29dbf9
[]
no_license
silky/exe
5f9e4eea772d74852a1a2fac57d8d20588282d2b
e81690d6e16f2a83c105cce446011af6ae905b81
refs/heads/master
1,609,385,766,412
1,472,164,223,000
1,472,164,223,000
66,610,224
1
0
null
1,472,178,919,000
1,472,178,919,000
null
UTF-8
Lean
false
false
13,931
lean
/- Functor -/ import Setoid import Cat import Mor set_option pp.universes true set_option pp.metavar_args false namespace EXE /- - The category of functors -/ namespace Functor -- axioms of functor section withOnHom variables (C D : CatType) (onOb : Π(c : C), D) variables (onHom : Π{X Y : C}, (X ⇒C⇒ Y)⥤(onOb X ⇒D⇒ onOb Y)) definition OnIdProp : Prop := ∀{X : C}, (onHom ①) ≡(onOb X ⇒D⇒ onOb X)≡ ① definition OnIdInvProp : Prop := ∀{X : C}, ① ≡(onOb X ⇒D⇒ onOb X)≡ (onHom ①) definition OnMulProp : Prop := ∀{X Y Z : C}, ∀(g : Y ⇒C⇒ Z), ∀(f : X ⇒C⇒ Y), (onHom (g ⊙C⊙ f)) ≡(onOb X ⇒D⇒ onOb Z)≡ ((onHom g) ⊙D⊙ (onHom f)) definition OnMulInvProp : Prop := ∀{X Y Z : C}, ∀(g : Y ⇒C⇒ Z), ∀(f : X ⇒C⇒ Y), ((onHom g) ⊙D⊙ (onHom f)) ≡(onOb X ⇒D⇒ onOb Z)≡ (onHom (g ⊙C⊙ f)) end withOnHom end Functor -- functor as an object of the category `Functor` record FunctorType (C D : CatType) : Type := (onOb : Π(c : C), D) (onHom : Π{X Y : C}, (X ⇒C⇒ Y)⥤(onOb X ⇒D⇒ onOb Y)) (onId : Functor.OnIdProp C D onOb @onHom) (onMul : Functor.OnMulProp C D onOb @onHom) abbreviation Functor.MkOb {C D : CatType} := @FunctorType.mk C D print FunctorType abbreviation FunctorType.onIdInv {C D : CatType} (F : FunctorType C D) : Functor.OnIdInvProp C D (@FunctorType.onOb _ _ F) (@FunctorType.onHom _ _ F) := λ X, SetoidType.Sym _ (@FunctorType.onId _ _ F X) abbreviation FunctorType.onMulInv {C D : CatType} (F : FunctorType C D) : Functor.OnMulInvProp C D (@FunctorType.onOb _ _ F) (@FunctorType.onHom _ _ F) := λ X Y Z, λ f g, SetoidType.Sym _ (@FunctorType.onMul _ _ F X Y Z f g) -- action on carrier attribute FunctorType.onOb [coercion] infixl ` $$ `:100 := FunctorType.onOb definition cat_hom.onHom {C D : CatType} (F : FunctorType C D) {X Y : C} (m : X ⇒C⇒ Y) := (FunctorType.onHom F) $ m attribute cat_hom.onHom [coercion] infixl ` $$/ `:100 := cat_hom.onHom definition cat_hom.onEqu {C D : CatType} (F : FunctorType C D) {X Y : C} {m1 m2 : X ⇒C⇒ Y} (e : m1 ≡_≡ m2) := (FunctorType.onHom F) $/ e attribute cat_hom.onEqu [coercion] infixl ` $$// `:100 := cat_hom.onEqu definition cat_hom.onSquare {C D : CatType} (F : FunctorType C D) {X11 X12 X21 X22 : C} {m1x : X11 ⇒C⇒ X12} {m2x : X21 ⇒C⇒ X22} {mx1 : X11 ⇒C⇒ X21} {mx2 : X12 ⇒C⇒ X22} (sq : Mor.SquareProp C m1x m2x mx1 mx2) : Mor.SquareProp D (F m1x) (F m2x) (F mx1) (F mx2) := (FunctorType.onMulInv F mx2 m1x) ⊡((F X11) ⇒D⇒ (F X22))⊡ (F $$// sq) ⊡((F X11) ⇒D⇒ (F X22))⊡ (FunctorType.onMul F m2x mx1) attribute cat_hom.onSquare [coercion] infixl ` $$/// `:100 := cat_hom.onSquare namespace Functor -- morphisms between functors are natural transformations record HomType {C D : CatType} (F G : FunctorType C D) : Type := (onOb : Π(X : C), F X ⇒D⇒ G X) (onHom : ∀{X Y : C}, ∀(m : X ⇒C⇒ Y), Mor.SquareProp D (F m) (G m) (onOb X) (onOb Y)) abbreviation MkHom {C D : CatType} {F G : FunctorType C D} := @HomType.mk C D F G abbreviation HomType.onHomInv {C D : CatType} {F G : FunctorType C D} (nat : HomType F G) {X Y : C} (m : X ⇒C⇒ Y) := SetoidType.Sym (F X ⇒D⇒ G Y) (HomType.onHom nat m) end Functor -- action attribute Functor.HomType.onOb [coercion] infixl ` /$$ `:100 := Functor.HomType.onOb infixl ` /$$/ `:100 := Functor.HomType.onHom infixl ` /$/$/ `:100 := Functor.HomType.onHomInv namespace Functor -- setoid of natural transformations definition HomSet {C D : CatType} : Cat.HomType (FunctorType C D) := λ(F G : FunctorType C D), Setoid.MkOb /- El -/ (HomType F G) /- Equ -/ (λ(f g : HomType F G), ∀ X, f X ≡(F X ⇒D⇒ G X)≡ g X) /- Refl-/ (λ f, λ X, ⊜) /- Trans -/ (λ f g h, λ fg gh, λ X, (fg X) ⊡(F X ⇒D⇒ G X)⊡ (gh X)) /- Sym -/ (λ f g, λ fg, λ X, SetoidType.Sym (F X ⇒D⇒ G X) (fg X)) print HomSet end Functor -- the dedicated arrow for morphisms of functors (nat.tr.) infixr ` ⟹ `:10 := Functor.HomSet namespace Functor -- identity in functor category (identity natural transformation) definition Id {C D : CatType} : Cat.IdType (@Functor.HomSet C D) := λ(F : FunctorType C D), Functor.MkHom /- onOb -/ (λ X, ①) /- onHom -/ (λ X Y, λ m, Mor.SquareId1 D (F m)) -- multiplication in functor category (composition of natural transformations) definition Mul {C D : CatType} : Cat.MulType (@Functor.HomSet C D) := λ(F G H : FunctorType C D), Setoid.MkHom -- :[Hom G H ⥤ Hom F G ⥤ Hom F H] /- onEl -/ (λ(a : G⟹H), Setoid.MkHom -- :[Hom F G ⥤ Hom F H] /- onEl -/ (λ(b : F⟹G), Functor.MkHom -- :[Hom F H] /- onOb -/ (λ(o : C), a o ⊙D⊙ b o) /- onHom -/ (λ(o1 o2 : C), λ(m12 : o1 ⇒C⇒ o2), Mor.SquareMul1 D (b /$$/ m12) (a /$$/ m12) )) /- onEqu -/ (λ(b1 b2 : F⟹G), λ(b12 : b1 ≡(F⟹G)≡ b2), λ(o : C), ((CatType.Mul D) (a o)) $/ (b12 o) /- Equ in Hom F H -/ )) /- onEqu -/ (λ(a1 a2 : G⟹H), λ(a12 : a1 ≡(G⟹H)≡ a2), λ(b : F⟹G), λ(o : C), ((CatType.Mul D) $/ (a12 o)) (b o) /-Equ in Hom F H -/ ) definition UnitL {C D : CatType} : Cat.UnitLProp (@Id C D) (@Mul C D) := λ(A B : FunctorType C D), λ(f : A⟹B), λ(o : C), CatType.UnitL D (f o) definition UnitR {C D : CatType} : Cat.UnitRProp (@Id C D) (@Mul C D) := λ(A B : FunctorType C D), λ(f : A⟹B), λ(o : C), CatType.UnitR D (f o) definition Assoc {C D : CatType} : Cat.AssocProp (@Mul C D) := λ(F G H I: FunctorType C D), λ(f : H⟹I), λ(g : G⟹H), λ(h : F⟹G), λ(o : C), CatType.Assoc D (f o) (g o) (h o) end Functor -- the category of functors (between categories C and D) definition FunctorCat (C D : CatType) : CatType := Cat.MkOb (FunctorType C D) (@Functor.HomSet C D) (@Functor.Id C D) (@Functor.Mul C D) (@Functor.UnitL C D) (@Functor.UnitR C D) (@Functor.Assoc C D) print FunctorCat -- the dedicated arrow for morphisms of categories (functors) infixr ` ⟶ `:100 := FunctorCat -- constant functor namespace Cat namespace Delta definition onOb (C D : CatType) (d : D) : C ⟶ D := Functor.MkOb /- onOb -/ ( λ(c : C), d) /- onHom -/ ( λ(c1 c2 : C), Setoid.Const (c1 ⇒C⇒ c2) (d ⇒D⇒ d) ① ) /- onId -/ ( λ(c : C), ⊜) /- onMul -/ ( λ(c1 c2 c3 : C), λ(g : c2 ⇒C⇒ c3), λ(f : c1 ⇒C⇒ c2), CatType.UnitCInv D) definition onHom.onEl (C D : CatType) {d1 d2 : D} (f : d1 ⇒D⇒ d2) : (onOb C D d1) ⟹ (onOb C D d2) := Functor.MkHom ( λ(c : C), f) ( λ(c1 c2 : C), λ(c12 : c1 ⇒C⇒ c2), Mor.SquareId2 D f) definition onHom.onEqu (C D : CatType) {d1 d2 : D} {f1 f2 : d1 ⇒D⇒ d2} (e : f1 ≡(d1 ⇒D⇒ d2)≡ f2 ) : (onHom.onEl C D f1) ≡((onOb C D d1) ⟹ (onOb C D d2))≡ (onHom.onEl C D f2) := λ(c : C), e definition onHom (C D : CatType) {d1 d2 : D} : (d1 ⇒D⇒ d2)⥤(onOb C D d1 ⟹ onOb C D d2) := Setoid.MkHom (@onHom.onEl C D d1 d2) (@onHom.onEqu C D d1 d2) definition onId (C D : CatType) : Functor.OnIdProp D (C ⟶ D) (@onOb C D) (@onHom C D) := λ (d : D), λ (c : C), ⊜ definition onMul (C D : CatType) : Functor.OnMulProp D (C ⟶ D) (@onOb C D) (@onHom C D) := λ(d1 d2 d3 : D), λ(g : d2 ⇒D⇒ d3), λ(f : d1 ⇒D⇒ d2), λ (c : C), ⊜ end Delta definition Delta (C D : CatType) : D ⟶ (C ⟶ D) := Functor.MkOb (@Delta.onOb C D) (@Delta.onHom C D) (@Delta.onId C D) (@Delta.onMul C D) end Cat namespace Functor abbreviation ConeType {C D : CatType} (X : D) (F : C ⟶ D) : Type := Π(Y : C), (X ⇒D⇒ F Y) abbreviation CoconeType {C D : CatType} (F : C ⟶ D) (X : D) : Type := Π(Y : C), (F Y ⇒D⇒ X) abbreviation IsConeProp {C D : CatType} (X : D) (F : C ⟶ D) (arrow : ConeType X F) : Prop := ∀{A B : C}, ∀(m : A ⇒C⇒ B), (arrow B) ≡(X ⇒D⇒ F B)≡ ((F m) ⊙D⊙ (arrow A)) abbreviation IsCoconeProp {C D : CatType} (F : C ⟶ D) (X : D) (arrow : CoconeType F X) : Prop := ∀{A B : C}, ∀(m : A ⇒C⇒ B), ((arrow B) ⊙D⊙ (F m)) ≡(F A ⇒D⇒ X)≡ (arrow A) definition NatFromCone {C D : CatType} {X : D} {F : C ⟶ D} (arrow : ConeType X F) (cone : IsConeProp X F arrow) : (Cat.Delta C D X) ⟹ F := MkHom /- onOb -/ arrow /- onHom -/ ( λ(A B: C), λ(m : A ⇒C⇒ B), (CatType.UnitR D (arrow B))⊡(X ⇒D⇒ F B)⊡(cone m)) definition ConeFromNat {C D : CatType} {X : D} {F : C ⟶ D} (nat : (Cat.Delta C D X) ⟹ F) : ConeType X F := λ X, nat /$$ X definition IsConeFromNat {C D : CatType} {X : D} {F : C ⟶ D} (nat : (Cat.Delta C D X) ⟹ F) : IsConeProp X F (ConeFromNat nat) := λ(A B: C), λ(m : A ⇒C⇒ B), proof (CatType.UnitRInv D (nat /$$ B)) ⊡(X ⇒D⇒ F B)⊡ (nat /$$/ m) qed definition NatFromCocone {C D : CatType} {F : C ⟶ D} {X : D} (arrow : CoconeType F X) (cocone : IsCoconeProp F X arrow) : F ⟹ (Cat.Delta C D X) := MkHom /- onOb -/ arrow /- onHom -/ ( λ(A B: C), λ(m : A ⇒C⇒ B), (cocone m)⊡(F A ⇒D⇒ X)⊡(CatType.UnitLInv D (arrow A))) definition CoconeFromNat {C D : CatType} {F : C ⟶ D} {X : D} (nat : F ⟹ (Cat.Delta C D X)) : CoconeType F X := λ X, nat /$$ X definition IsCoconeFromNat {C D : CatType} {F : C ⟶ D} {X : D} (nat : F ⟹ (Cat.Delta C D X)) : IsCoconeProp F X (CoconeFromNat nat) := λ(A B: C), λ(m : A ⇒C⇒ B), proof (nat /$$/ m) ⊡(F A ⇒D⇒ X)⊡ (CatType.UnitL D (nat /$$ A)) qed end Functor -- the identity functor (1 in Cat) definition Cat.Id {C : CatType} : C ⟶ C := Functor.MkOb /- onOb -/ ( λ(X : C), X) /- onHom -/ ( λ(X Y : C), Setoid.Id) /- onId -/ ( λ(X : C), ⊜) /- onMul -/ ( λ(X Y Z : C), λ(g : Y ⇒C⇒ Z), λ(f : X ⇒C⇒ Y), ⊜) notation ` 𝟙 ` := Cat.Id -- multiplication of functors definition Cat.MulFF.{o1 h1 o2 h2 o3 h3} {C : CatType.{o1 h1}} {D : CatType.{o2 h2}} {E : CatType.{o3 h3}} (F : D ⟶ E) (G : C ⟶ D) : C ⟶ E := Functor.MkOb /- onOb -/ ( λ(X : C), (F (G X))) /- onHom -/ ( λ(X Y : C), (@FunctorType.onHom D E F (G X) (G Y)) ∙ (@FunctorType.onHom C D G X Y)) /- onId -/ ( λ(X : C), (F (@FunctorType.onId C D G X)) ⊡((F (G X)) ⇒E⇒ (F (G X)))⊡ (@FunctorType.onId D E F (G X))) /- onMul -/ ( λ(X Y Z : C), λ(g : Y ⇒C⇒ Z), λ(f : X ⇒C⇒ Y), (F (@FunctorType.onMul C D G X Y Z g f)) ⊡((F (G X)) ⇒E⇒ (F (G Z)))⊡ (@FunctorType.onMul D E F (G X) (G Y) (G Z) (G g) (G f))) print Cat.MulFF notation F ` ⊗ ` G : 100 := Cat.MulFF F G definition Cat.MulFN {C D E : CatType} (F : D ⟶ E) {G1 G2 : C ⟶ D} (g : G1 ⟹ G2) : (F ⊗ G1) ⟹ (F ⊗ G2) := Functor.MkHom /- onOb -/ ( λ(X : C), (F $$/ (g /$$ X))) /- onHom -/ ( λ(X Y : C), λ(m : X ⇒C⇒ Y), (F $$/// (g /$$/ m)) ) notation F ` ⊗/ ` g : 100 := Cat.MulFN F g definition Cat.MulNF {C D E : CatType} {F1 F2 : D ⟶ E} (f : F1 ⟹ F2) (G : C ⟶ D) : (F1 ⊗ G) ⟹ (F2 ⊗ G) := Functor.MkHom /- onOb -/ ( λ(X : C), (f /$$ (G $$ X))) /- onHom -/ ( λ(X Y : C), λ(m : X ⇒C⇒ Y), (f /$$/ (G $$/ m)) ) notation f ` /⊗ ` G : 100 := Cat.MulNF f G definition Cat.Assoc {C1 C2 C3 C4 : CatType} (F34 : C3 ⟶ C4) (F23 : C2 ⟶ C3) (F12 : C1 ⟶ C2) : ((F34 ⊗ F23) ⊗ F12) ⟹ (F34 ⊗ (F23 ⊗ F12)) := Functor.MkHom /- onOb -/ (λ X, ①) /- onHom -/ (λ X Y, λ m, Mor.SquareId1 C4 (F34 $$/ (F23 $$/ (F12 $$/ m)))) definition Cat.AssocInv {C1 C2 C3 C4 : CatType} (F34 : C3 ⟶ C4) (F23 : C2 ⟶ C3) (F12 : C1 ⟶ C2) : (F34 ⊗ (F23 ⊗ F12)) ⟹ ((F34 ⊗ F23) ⊗ F12) := Functor.MkHom /- onOb -/ (λ X, ①) /- onHom -/ (λ X Y, λ m, Mor.SquareId1 C4 (F34 $$/ (F23 $$/ (F12 $$/ m)))) definition Cat.UnitL {C1 C2 : CatType} (F : C1 ⟶ C2) : (𝟙 ⊗ F) ⟹ F := Functor.MkHom ( λ X, ①) (λ X Y, λ m, Mor.SquareId1 C2 (F $$/ m)) definition Cat.UnitLInv {C1 C2 : CatType} (F : C1 ⟶ C2) : F ⟹ (𝟙 ⊗ F) := Functor.MkHom ( λ X, ①) (λ X Y, λ m, Mor.SquareId1 C2 (F $$/ m)) definition Cat.UnitR {C1 C2 : CatType} (F : C1 ⟶ C2) : (F ⊗ 𝟙) ⟹ F := Functor.MkHom ( λ X, ①) (λ X Y, λ m, Mor.SquareId1 C2 (F $$/ m)) definition Cat.UnitRInv {C1 C2 : CatType} (F : C1 ⟶ C2) : F ⟹ (F ⊗ 𝟙) := Functor.MkHom ( λ X, ①) (λ X Y, λ m, Mor.SquareId1 C2 (F $$/ m)) abbreviation Cat.FullEqu {C D : CatType} {F G : C ⟶ D} : EquType [F ⟹ G] := SetoidType.Equ (F ⟹ G) infix `≣` : 10 := Cat.FullEqu abbreviation Cat.Vertical {C D : CatType} {F G H : C ⟶ D} (b : G ⟹ H) (a : F ⟹ G) : (F ⟹ H) := b ⊙(C ⟶ D)⊙ a infixl ` ○ ` : 100 := Cat.Vertical -- TODO: Cat.Mul, Cat,UnitorLR, Cat.Associator, Cat.TriangleLCREqu, Cat.PentagonEqu end EXE
421b21334e803b6760587467073e2f8f0f4cfb67
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/ring_theory/noetherian.lean
1a3a71e5d60ea17869750e927d56fdb849a4e11e
[ "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
21,454
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 linear_algebra.finsupp import ring_theory.ideal_operations import ring_theory.subring import linear_algebra.basis open set namespace submodule variables {α : Type*} {β : Type*} [ring α] [add_comm_group β] [module α β] def fg (s : submodule α β) : Prop := ∃ t : finset β, submodule.span α ↑t = s theorem fg_def {s : submodule α β} : s.fg ↔ ∃ t : set β, finite t ∧ span α t = s := ⟨λ ⟨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_coe, 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_coe, 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_coe, 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, ideal.quotient.mk_one] at hr1 hc1 ⊢, rw [ideal.quotient.mk_mul, hc1, hr1, mul_one] }, { intros n hn, specialize hrn hn, rw [mem_coe, 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 α β).fg := ⟨∅, by rw [finset.coe_empty, span_empty]⟩ theorem fg_sup {s₁ s₂ : submodule α β} (hs₁ : s₁.fg) (hs₂ : s₂.fg) : (s₁ ⊔ s₂).fg := let ⟨t₁, ht₁⟩ := fg_def.1 hs₁, ⟨t₂, ht₂⟩ := fg_def.1 hs₂ in fg_def.2 ⟨t₁ ∪ t₂, finite_union ht₁.1 ht₂.1, by rw [span_union, ht₁.2, ht₂.2]⟩ variables {γ : Type*} [add_comm_group γ] [module α γ] variables {f : β →ₗ[α] γ} theorem fg_map {s : submodule α β} (hs : s.fg) : (s.map f).fg := let ⟨t, ht⟩ := fg_def.1 hs in fg_def.2 ⟨f '' t, finite_image _ ht.1, by rw [span_image, ht.2]⟩ theorem fg_prod {sb : submodule α β} {sc : submodule α γ} (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 ⟨prod.inl '' tb ∪ prod.inr '' tc, finite_union (finite_image _ htb.1) (finite_image _ htc.1), 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 α β} (hs1 : (s.map f).fg) (hs2 : (s ⊓ f.ker).fg) : s.fg := begin haveI := classical.dec_eq α, haveI := classical.dec_eq β, haveI := classical.dec_eq γ, 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 : γ → β, ∀ 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 β β α id).to_fun ((finsupp.lmap_domain α α g : (γ →₀ α) → β →₀ α) l), _, x - finsupp.total β β α id ((finsupp.lmap_domain α α g : (γ →₀ α) → β →₀ α) l), _, add_sub_cancel'_right _ _⟩, { rw [← set.image_id (g '' ↑t1), finsupp.mem_span_iff_total], refine ⟨_, _, rfl⟩, haveI : inhabited γ := ⟨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 class is_noetherian (α β) [ring α] [add_comm_group β] [module α β] : Prop := (noetherian : ∀ (s : submodule α β), s.fg) section variables {α : Type*} {β : Type*} {γ : Type*} variables [ring α] [add_comm_group β] [add_comm_group γ] variables [module α β] [module α γ] open is_noetherian include α theorem is_noetherian_submodule {N : submodule α β} : is_noetherian α N ↔ ∀ s : submodule α β, 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 α β} : is_noetherian α N ↔ ∀ s : submodule α β, (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 α β} : is_noetherian α N ↔ ∀ s : submodule α β, (s ⊓ N).fg := is_noetherian_submodule.trans ⟨λ H s, H _ inf_le_right, λ H s hs, (inf_of_le_left hs) ▸ H _⟩ variable (β) theorem is_noetherian_of_surjective (f : β →ₗ[α] γ) (hf : f.range = ⊤) [is_noetherian α β] : is_noetherian α γ := ⟨λ 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 {β} theorem is_noetherian_of_linear_equiv (f : β ≃ₗ[α] γ) [is_noetherian α β] : is_noetherian α γ := is_noetherian_of_surjective _ f.to_linear_map f.range instance is_noetherian_prod [is_noetherian α β] [is_noetherian α γ] : is_noetherian α (β × γ) := ⟨λ s, submodule.fg_of_fg_map_of_fg_inf_ker (linear_map.snd α β γ) (noetherian _) $ have s ⊓ linear_map.ker (linear_map.snd α β γ) ≤ linear_map.range (linear_map.inl α β γ), 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 {α ι : Type*} {β : ι → Type*} [ring α] [Π i, add_comm_group (β i)] [Π i, module α (β i)] [fintype ι] [∀ i, is_noetherian α (β i)] : is_noetherian α (Π i, β i) := begin haveI := classical.dec_eq ι, suffices : ∀ s : finset ι, is_noetherian α (Π i : (↑s : set ι), β 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 i, cases i, 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 α).2 _, ext i, cases i.2 }, refine @is_noetherian_of_linear_equiv _ _ _ _ _ _ _ _ ⟨_, _, _, _, _, _⟩ (@is_noetherian_prod _ (β a) _ _ _ _ _ _ _ ih), { exact λ f i, or.by_cases (finset.mem_insert.1 i.2) (λ h : i.1 = a, show β i.1, from (eq.rec_on h.symm f.1)) (λ h : i.1 ∈ s, show β 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, cases i with 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, cases i with 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 {α β} [ring α] [add_comm_group β] [module α β] : is_noetherian α β ↔ well_founded ((>) : submodule α β → submodule α β → Prop) := ⟨λ h, begin apply order_embedding.well_founded_iff_no_descending_seq.2, swap, { apply is_strict_order.swap }, rintro ⟨⟨N, hN⟩⟩, let M := ⨆ n, N n, resetI, rcases submodule.fg_def.1 (noetherian M) 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 β), { rw [← submodule.coe_supr_of_directed N _], { show t ⊆ M, 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 : M ≤ 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 : ∀ M ≤ N, ∃ s, finite s ∧ M ⊔ submodule.span α s = N, { rcases this ⊥ bot_le with ⟨s, hs, e⟩, exact submodule.fg_def.2 ⟨s, hs, by simpa using e⟩ }, refine λ M, h.induction M _, intros M IH MN, letI := classical.dec, by_cases h : ∀ x, x ∈ N → x ∈ M, { cases le_antisymm MN h, exact ⟨∅, by simp⟩ }, { simp [not_forall] at h, rcases h with ⟨x, h, h₂⟩, have : ¬M ⊔ submodule.span α {x} ≤ M, { intro hn, apply h₂, have := le_trans le_sup_right hn, exact submodule.span_le.1 this (mem_singleton x) }, rcases IH (M ⊔ submodule.span α {x}) ⟨@le_sup_left _ _ M _, this⟩ (sup_le MN (submodule.span_le.2 (by simpa))) with ⟨s, hs, hs₂⟩, refine ⟨insert x s, finite_insert _ hs, _⟩, rw [← hs₂, sup_assoc, ← submodule.span_union], simp } end⟩ lemma well_founded_submodule_gt (α β) [ring α] [add_comm_group β] [module α β] : ∀ [is_noetherian α β], well_founded ((>) : submodule α β → submodule α β → Prop) := is_noetherian_iff_well_founded.mp lemma finite_of_linear_independent {α β} [nonzero_comm_ring α] [add_comm_group β] [module α β] [is_noetherian α β] {s : set β} (hs : linear_independent α (subtype.val : s → β)) : s.finite := begin refine classical.by_contradiction (λ hf, order_embedding.well_founded_iff_no_descending_seq.1 (well_founded_submodule_gt α β) ⟨_⟩), have f : ℕ ↪ s, from @infinite.nat_embedding s ⟨λ f, hf ⟨f⟩⟩, have : ∀ n, (subtype.val ∘ f) '' {m | m ≤ n} ⊆ s, { rintros n x ⟨y, hy₁, hy₂⟩, subst hy₂, exact (f y).2 }, have : ∀ a b : ℕ, a ≤ b ↔ span α ((subtype.val ∘ f) '' {m | m ≤ a}) ≤ span α ((subtype.val ∘ f) '' {m | m ≤ b}), { assume a b, rw [span_le_span_iff (@zero_ne_one α _) hs (this a) (this b), set.image_subset_image_iff (injective_comp subtype.val_injective f.inj'), set.subset_def], exact ⟨λ hab x (hxa : x ≤ a), le_trans hxa hab, λ hx, hx a (le_refl a)⟩ }, exact ⟨⟨λ n, span α ((subtype.val ∘ 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 @[class] def is_noetherian_ring (α) [ring α] : Prop := is_noetherian α α instance is_noetherian_ring.to_is_noetherian {α : Type*} [ring α] : ∀ [is_noetherian_ring α], is_noetherian α α := 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 [finset.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 R 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 ⊢, convert order_embedding.well_founded (order_embedding.rsymm (submodule.map_subtype.lt_order_embedding N)) 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 ⊢, convert order_embedding.well_founded (order_embedding.rsymm (submodule.comap_mkq.lt_order_embedding N)) 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.module _) _ _ _ is_noetherian_pi, { fapply linear_map.mk, { exact λ f, ⟨s.attach.sum (λ i, f i • i.1), N.sum_mem (λ c _, N.smul_mem _ $ this _ c.2)⟩ }, { intros f g, apply subtype.eq, change s.attach.sum (λ i, (f i + g i) • _) = _, simp only [add_smul, finset.sum_add_distrib], refl }, { intros c f, apply subtype.eq, change s.attach.sum (λ i, (c • f i) • _) = _, simp only [smul_eq_mul, mul_smul], exact s.attach.sum_hom _ } }, 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.1, subtype.eq _⟩, change s.attach.sum (λ i, l i.1 • i.1) = 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 unfold is_noetherian_ring at H ⊢, rw is_noetherian_iff_well_founded at H ⊢, convert order_embedding.well_founded (order_embedding.rsymm (ideal.lt_order_embedding_of_surjective f hf)) H end instance is_noetherian_ring_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 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 is_noetherian_ring variables {α : Type*} [integral_domain α] [is_noetherian_ring α] open associates nat local attribute [elab_as_eliminator] well_founded.fix lemma well_founded_dvd_not_unit : well_founded (λ a b : α, a ≠ 0 ∧ ∃ x, ¬is_unit x ∧ b = a * x ) := by simp only [ideal.span_singleton_lt_span_singleton.symm]; exact inv_image.wf (λ a, ideal.span ({a} : set α)) (well_founded_submodule_gt _ _) lemma exists_irreducible_factor {a : α} (ha : ¬ is_unit a) (ha0 : a ≠ 0) : ∃ i, irreducible i ∧ i ∣ a := (irreducible_or_factor a ha).elim (λ hai, ⟨a, hai, dvd_refl _⟩) (well_founded.fix well_founded_dvd_not_unit (λ a ih ha ha0 ⟨x, y, hx, hy, hxy⟩, have hx0 : x ≠ 0, from λ hx0, ha0 (by rw [← hxy, hx0, zero_mul]), (irreducible_or_factor x hx).elim (λ hxi, ⟨x, hxi, hxy ▸ by simp⟩) (λ hxf, let ⟨i, hi⟩ := ih x ⟨hx0, y, hy, hxy.symm⟩ hx hx0 hxf in ⟨i, hi.1, dvd.trans hi.2 (hxy ▸ by simp)⟩)) a ha ha0) @[elab_as_eliminator] lemma irreducible_induction_on {P : α → Prop} (a : α) (h0 : P 0) (hu : ∀ u : α, is_unit u → P u) (hi : ∀ a i : α, a ≠ 0 → irreducible i → P a → P (i * a)) : P a := by haveI := classical.dec; exact well_founded.fix well_founded_dvd_not_unit (λ a ih, if ha0 : a = 0 then ha0.symm ▸ h0 else if hau : is_unit a then hu a hau else let ⟨i, hii, ⟨b, hb⟩⟩ := exists_irreducible_factor hau ha0 in have hb0 : b ≠ 0, from λ hb0, by simp * at *, hb.symm ▸ hi _ _ hb0 hii (ih _ ⟨hb0, i, hii.1, by rw [hb, mul_comm]⟩)) a lemma exists_factors (a : α) : a ≠ 0 → ∃f:multiset α, (∀b∈f, irreducible b) ∧ associated a f.prod := is_noetherian_ring.irreducible_induction_on a (λ h, (h rfl).elim) (λ u hu _, ⟨0, by simp [associated_one_iff_is_unit, hu]⟩) (λ a i ha0 hii ih hia0, let ⟨s, hs⟩ := ih ha0 in ⟨i::s, ⟨by clear _let_match; finish, by rw multiset.prod_cons; exact associated_mul_mul (by refl) hs.2⟩⟩) end is_noetherian_ring namespace submodule variables {R : Type*} {A : Type*} [comm_ring R] [ring A] [algebra R A] variables (M N : submodule R A) local attribute [instance] set.pointwise_mul_semiring 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, set.pointwise_mul_finite hfm hfn, span_mul_span R m n ▸ hm ▸ hn ▸ rfl⟩ lemma fg_pow (h : M.fg) (n : ℕ) : (M^n).fg := nat.rec_on n (⟨finset.singleton 1, by simp [one_eq_span]⟩) (λ n ih, by simpa [pow_succ] using fg_mul _ _ h ih) end submodule
81e79a268f6765f888c1c194f38a8026f4ad83de
4727251e0cd73359b15b664c3170e5d754078599
/test/matrix.lean
84343f9a2bf2410348f4bc55efd73c852bcf9a43
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
3,614
lean
import data.matrix.notation import linear_algebra.matrix.determinant import group_theory.perm.fin import tactic.norm_swap variables {α β : Type} [semiring α] [ring β] namespace matrix open_locale matrix example {a a' b b' c c' d d' : α} : ![![a, b], ![c, d]] + ![![a', b'], ![c', d']] = ![![a + a', b + b'], ![c + c', d + d']] := by simp example {a a' b b' c c' d d' : β} : ![![a, b], ![c, d]] - ![![a', b'], ![c', d']] = ![![a - a', b - b'], ![c - c', d - d']] := by simp example {a a' b b' c c' d d' : α} : ![![a, b], ![c, d]] ⬝ ![![a', b'], ![c', d']] = ![![a * a' + b * c', a * b' + b * d'], ![c * a' + d * c', c * b' + d * d']] := by simp example {a b c d x y : α} : mul_vec ![![a, b], ![c, d]] ![x, y] = ![a * x + b * y, c * x + d * y] := by simp example {a b c d : α} : minor ![![a, b], ![c, d]] ![1, 0] ![0] = ![![c], ![a]] := by { ext, simp } example {a b c : α} : ![a, b, c] 0 = a := by simp example {a b c : α} : ![a, b, c] 1 = b := by simp example {a b c : α} : ![a, b, c] 2 = c := by simp example {a b c d : α} : ![a, b, c, d] 0 = a := by simp example {a b c d : α} : ![a, b, c, d] 1 = b := by simp example {a b c d : α} : ![a, b, c, d] 2 = c := by simp example {a b c d : α} : ![a, b, c, d] 3 = d := by simp example {a b c d : α} : ![a, b, c, d] 42 = c := by simp example {a b c d e : α} : ![a, b, c, d, e] 0 = a := by simp example {a b c d e : α} : ![a, b, c, d, e] 1 = b := by simp example {a b c d e : α} : ![a, b, c, d, e] 2 = c := by simp example {a b c d e : α} : ![a, b, c, d, e] 3 = d := by simp example {a b c d e : α} : ![a, b, c, d, e] 4 = e := by simp example {a b c d e : α} : ![a, b, c, d, e] 5 = a := by simp example {a b c d e : α} : ![a, b, c, d, e] 6 = b := by simp example {a b c d e : α} : ![a, b, c, d, e] 7 = c := by simp example {a b c d e : α} : ![a, b, c, d, e] 8 = d := by simp example {a b c d e : α} : ![a, b, c, d, e] 9 = e := by simp example {a b c d e : α} : ![a, b, c, d, e] 123 = d := by simp example {a b c d e : α} : ![a, b, c, d, e] 123456789 = e := by simp example {a b c d e f g h : α} : ![a, b, c, d, e, f, g, h] 5 = f := by simp example {a b c d e f g h : α} : ![a, b, c, d, e, f, g, h] 7 = h := by simp example {a b c d e f g h : α} : ![a, b, c, d, e, f, g, h] 37 = f := by simp example {a b c d e f g h : α} : ![a, b, c, d, e, f, g, h] 99 = d := by simp example {α : Type*} [comm_ring α] {a b c d : α} : matrix.det ![![a, b], ![c, d]] = a * d - b * c := begin simp [matrix.det_succ_row_zero, fin.sum_univ_succ], /- Try this: simp only [det_succ_row_zero, fin.sum_univ_succ, neg_mul, mul_one, fin.default_eq_zero, fin.coe_zero, one_mul, cons_val_one, fin.coe_succ, univ_unique, minor_apply, pow_one, fin.zero_succ_above, fin.succ_succ_above_zero, finset.sum_singleton, cons_val_zero, cons_val_succ, det_fin_zero, pow_zero] -/ ring end example {α : Type*} [comm_ring α] {a b c d e f g h i : α} : matrix.det ![![a, b, c], ![d, e, f], ![g, h, i]] = a * e * i - a * f * h - b * d * i + b * f * g + c * d * h - c * e * g := begin simp [matrix.det_succ_row_zero, fin.sum_univ_succ], /- Try this: simp only [det_succ_row_zero, fin.sum_univ_succ, neg_mul, cons_append, mul_one, fin.default_eq_zero, fin.coe_zero, cons_vec_bit0_eq_alt0, one_mul, cons_val_one, cons_vec_alt0, fin.succ_succ_above_one, fin.coe_succ, univ_unique, minor_apply, pow_one, fin.zero_succ_above, fin.succ_zero_eq_one, fin.succ_succ_above_zero, nat.neg_one_sq, finset.sum_singleton, cons_val_zero, cons_val_succ, det_fin_zero, head_cons, pow_zero] -/ ring end end matrix
efb42ac99d53cf9f2dcbf3aae8d1570b3d009b3d
9dc8cecdf3c4634764a18254e94d43da07142918
/test/to_additive.lean
ca99623d2f5bf75a3e373f86edb1ec6f096dea04
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
3,656
lean
import algebra.group.to_additive import algebra.group.units import tactic -- work in a namespace so that it doesn't matter if names clash namespace test @[to_additive bar0] def foo0 {α} [has_mul α] [has_one α] (x y : α) : α := x * y * 1 class {u v} my_has_pow (α : Type u) (β : Type v) := (pow : α → β → α) class my_has_smul (M : Type*) (α : Type*) := (smul : M → α → α) attribute [to_additive_reorder 1] my_has_pow attribute [to_additive_reorder 1 4] my_has_pow.pow attribute [to_additive test.my_has_smul] my_has_pow attribute [to_additive test.my_has_smul.smul] my_has_pow.pow -- set_option pp.universes true -- set_option pp.implicit true -- set_option pp.notation false @[priority 10000] local infix (name := pow) ` ^ `:80 := my_has_pow.pow @[to_additive bar1] def foo1 {α} [my_has_pow α ℕ] (x : α) (n : ℕ) : α := @my_has_pow.pow α ℕ _ x n instance dummy : my_has_pow ℕ $ plift ℤ := ⟨λ _ _, 0⟩ set_option pp.universes true @[to_additive bar2] def foo2 {α} [my_has_pow α ℕ] (x : α) (n : ℕ) (m : plift ℤ) : α := x ^ (n ^ m) @[to_additive bar3] def foo3 {α} [my_has_pow α ℕ] (x : α) : ℕ → α := @my_has_pow.pow α ℕ _ x @[to_additive bar4] def {a b} foo4 {α : Type a} : Type b → Type (max a b) := @my_has_pow α @[to_additive bar4_test] lemma foo4_test {α β : Type*} : @foo4 α β = @my_has_pow α β := rfl @[to_additive bar5] def foo5 {α} [my_has_pow α ℕ] [my_has_pow ℕ ℤ] : true := trivial @[to_additive bar6] def foo6 {α} [my_has_pow α ℕ] : α → ℕ → α := @my_has_pow.pow α ℕ _ @[to_additive bar7] def foo7 := @my_has_pow.pow open tactic /- test the eta-expansion applied on `foo6`. -/ run_cmd do env ← get_env, reorder ← to_additive.reorder_attr.get_cache, d ← get_decl `test.foo6, let e := d.value.eta_expand env reorder, let t := d.type.eta_expand env reorder, let decl := declaration.defn `test.barr6 d.univ_params t e d.reducibility_hints d.is_trusted, add_decl decl, skip /-! Test the namespace bug (#8733). This code should *not* generate a lemma `add_some_def.in_namespace`. -/ def some_def.in_namespace : bool := ff def some_def {α : Type*} [has_mul α] (x : α) : α := if some_def.in_namespace then x * x else x -- cannot apply `@[to_additive]` to `some_def` if `some_def.in_namespace` doesn't have the attribute run_cmd do dict ← to_additive.aux_attr.get_cache, success_if_fail (transform_decl_with_prefix_dict dict ff tt mk_name_map mk_name_map mk_name_map `some_def `add_some_def []), skip attribute [to_additive some_other_name] some_def.in_namespace attribute [to_additive add_some_def] some_def run_cmd success_if_fail (get_decl `add_some_def.in_namespace) example : (add_units.mk_of_add_eq_zero 0 0 (by simp) : ℕ) = (add_units.mk_of_add_eq_zero 0 0 (by simp) : ℕ) := by norm_cast -- TODO test alias -- test @[to_additive_relevant_args] and to_additive.first_multiplicative_arg -- first multiplicative argument: f def foo_mul {I J K : Type*} (n : ℕ) {f : I → Type*} (L : Type*) [∀ i (n : ℕ), bool → has_one (f i)] [has_add I] [has_mul L] : true := trivial @[to_additive] instance pi.has_one {I : Type*} {f : I → Type*} [∀ i, has_one $ f i] : has_one (Π i : I, f i) := ⟨λ _, 1⟩ run_cmd do n ← to_additive.first_multiplicative_arg `test.pi.has_one, guard $ n = 2, n ← to_additive.first_multiplicative_arg `test.foo_mul, guard $ n = 5 @[to_additive] def nat_pi_has_one {α : Type*} [has_one α] : has_one (Π x : ℕ, α) := by apply_instance @[to_additive] def pi_nat_has_one {I : Type*} : has_one (Π x : I, ℕ) := by apply_instance end test
c7f471d4fc9de2f7bf10ec744a0db0509e3feb9c
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/data/zsqrtd/basic.lean
42d3164085d0a0a346573d6a653d34073ef439a7
[ "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
26,831
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.int.basic algebra.associated data.nat.gcd /-- The ring of integers adjoined with a square root of `d`. These have the form `a + b √d` where `a b : ℤ`. The components are called `re` and `im` by analogy to the negative `d` case, but of course both parts are real here since `d` is nonnegative. -/ structure zsqrtd (d : ℤ) := mk {} :: (re : ℤ) (im : ℤ) prefix `ℤ√`:100 := zsqrtd namespace zsqrtd section parameters {d : ℤ} instance : decidable_eq ℤ√d := by tactic.mk_dec_eq_instance theorem ext : ∀ {z w : ℤ√d}, z = w ↔ z.re = w.re ∧ z.im = w.im | ⟨x, y⟩ ⟨x', y'⟩ := ⟨λ h, by injection h; split; assumption, λ ⟨h₁, h₂⟩, by congr; assumption⟩ /-- Convert an integer to a `ℤ√d` -/ def of_int (n : ℤ) : ℤ√d := ⟨n, 0⟩ @[simp] theorem of_int_re (n : ℤ) : (of_int n).re = n := rfl @[simp] theorem of_int_im (n : ℤ) : (of_int n).im = 0 := rfl /-- The zero of the ring -/ def zero : ℤ√d := of_int 0 instance : has_zero ℤ√d := ⟨zsqrtd.zero⟩ @[simp] theorem zero_re : (0 : ℤ√d).re = 0 := rfl @[simp] theorem zero_im : (0 : ℤ√d).im = 0 := rfl /-- The one of the ring -/ def one : ℤ√d := of_int 1 instance : has_one ℤ√d := ⟨zsqrtd.one⟩ @[simp] theorem one_re : (1 : ℤ√d).re = 1 := rfl @[simp] theorem one_im : (1 : ℤ√d).im = 0 := rfl /-- The representative of `√d` in the ring -/ def sqrtd : ℤ√d := ⟨0, 1⟩ @[simp] theorem sqrtd_re : (sqrtd : ℤ√d).re = 0 := rfl @[simp] theorem sqrtd_im : (sqrtd : ℤ√d).im = 1 := rfl /-- Addition of elements of `ℤ√d` -/ def add : ℤ√d → ℤ√d → ℤ√d | ⟨x, y⟩ ⟨x', y'⟩ := ⟨x + x', y + y'⟩ instance : has_add ℤ√d := ⟨zsqrtd.add⟩ @[simp] theorem add_def (x y x' y' : ℤ) : (⟨x, y⟩ + ⟨x', y'⟩ : ℤ√d) = ⟨x + x', y + y'⟩ := rfl @[simp] theorem add_re : ∀ z w : ℤ√d, (z + w).re = z.re + w.re | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem add_im : ∀ z w : ℤ√d, (z + w).im = z.im + w.im | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem bit0_re (z) : (bit0 z : ℤ√d).re = bit0 z.re := add_re _ _ @[simp] theorem bit0_im (z) : (bit0 z : ℤ√d).im = bit0 z.im := add_im _ _ @[simp] theorem bit1_re (z) : (bit1 z : ℤ√d).re = bit1 z.re := by simp [bit1] @[simp] theorem bit1_im (z) : (bit1 z : ℤ√d).im = bit0 z.im := by simp [bit1] /-- Negation in `ℤ√d` -/ def neg : ℤ√d → ℤ√d | ⟨x, y⟩ := ⟨-x, -y⟩ instance : has_neg ℤ√d := ⟨zsqrtd.neg⟩ @[simp] theorem neg_re : ∀ z : ℤ√d, (-z).re = -z.re | ⟨x, y⟩ := rfl @[simp] theorem neg_im : ∀ z : ℤ√d, (-z).im = -z.im | ⟨x, y⟩ := rfl /-- Conjugation in `ℤ√d`. The conjugate of `a + b √d` is `a - b √d`. -/ def conj : ℤ√d → ℤ√d | ⟨x, y⟩ := ⟨x, -y⟩ @[simp] theorem conj_re : ∀ z : ℤ√d, (conj z).re = z.re | ⟨x, y⟩ := rfl @[simp] theorem conj_im : ∀ z : ℤ√d, (conj z).im = -z.im | ⟨x, y⟩ := rfl /-- Multiplication in `ℤ√d` -/ def mul : ℤ√d → ℤ√d → ℤ√d | ⟨x, y⟩ ⟨x', y'⟩ := ⟨x * x' + d * y * y', x * y' + y * x'⟩ instance : has_mul ℤ√d := ⟨zsqrtd.mul⟩ @[simp] theorem mul_re : ∀ z w : ℤ√d, (z * w).re = z.re * w.re + d * z.im * w.im | ⟨x, y⟩ ⟨x', y'⟩ := rfl @[simp] theorem mul_im : ∀ z w : ℤ√d, (z * w).im = z.re * w.im + z.im * w.re | ⟨x, y⟩ ⟨x', y'⟩ := rfl instance : comm_ring ℤ√d := by refine { add := (+), zero := 0, neg := has_neg.neg, mul := (*), one := 1, ..}; { intros, simp [ext, add_mul, mul_add, mul_comm, mul_left_comm] } instance : add_comm_monoid ℤ√d := by apply_instance instance : add_monoid ℤ√d := by apply_instance instance : monoid ℤ√d := by apply_instance instance : comm_monoid ℤ√d := by apply_instance instance : comm_semigroup ℤ√d := by apply_instance instance : semigroup ℤ√d := by apply_instance instance : add_comm_semigroup ℤ√d := by apply_instance instance : add_semigroup ℤ√d := by apply_instance instance : comm_semiring ℤ√d := by apply_instance instance : semiring ℤ√d := by apply_instance instance : ring ℤ√d := by apply_instance instance : distrib ℤ√d := by apply_instance instance : zero_ne_one_class ℤ√d := { zero := 0, one := 1, zero_ne_one := dec_trivial } instance : nonzero_comm_ring ℤ√d := { ..zsqrtd.comm_ring, ..zsqrtd.zero_ne_one_class } @[simp] theorem coe_nat_re (n : ℕ) : (n : ℤ√d).re = n := by induction n; simp * @[simp] theorem coe_nat_im (n : ℕ) : (n : ℤ√d).im = 0 := by induction n; simp * theorem coe_nat_val (n : ℕ) : (n : ℤ√d) = ⟨n, 0⟩ := by simp [ext] @[simp] theorem coe_int_re (n : ℤ) : (n : ℤ√d).re = n := by cases n; simp [*, int.of_nat_eq_coe, int.neg_succ_of_nat_eq] @[simp] theorem coe_int_im (n : ℤ) : (n : ℤ√d).im = 0 := by cases n; simp * theorem coe_int_val (n : ℤ) : (n : ℤ√d) = ⟨n, 0⟩ := by simp [ext] instance : char_zero ℤ√d := { cast_inj := λ m n, ⟨by simp [zsqrtd.ext], congr_arg _⟩ } @[simp] theorem of_int_eq_coe (n : ℤ) : (of_int n : ℤ√d) = n := by simp [ext] @[simp] theorem smul_val (n x y : ℤ) : (n : ℤ√d) * ⟨x, y⟩ = ⟨n * x, n * y⟩ := by simp [ext] @[simp] theorem muld_val (x y : ℤ) : sqrtd * ⟨x, y⟩ = ⟨d * y, x⟩ := by simp [ext] @[simp] theorem smuld_val (n x y : ℤ) : sqrtd * (n : ℤ√d) * ⟨x, y⟩ = ⟨d * n * y, n * x⟩ := by simp [ext] theorem decompose {x y : ℤ} : (⟨x, y⟩ : ℤ√d) = x + sqrtd * y := by simp [ext] theorem mul_conj {x y : ℤ} : (⟨x, y⟩ * conj ⟨x, y⟩ : ℤ√d) = x * x - d * y * y := by simp [ext, mul_comm] theorem conj_mul : Π {a b : ℤ√d}, conj (a * b) = conj a * conj b := by simp [ext] protected lemma coe_int_add (m n : ℤ) : (↑(m + n) : ℤ√d) = ↑m + ↑n := by simp [ext] protected lemma coe_int_sub (m n : ℤ) : (↑(m - n) : ℤ√d) = ↑m - ↑n := by simp [ext] protected lemma coe_int_mul (m n : ℤ) : (↑(m * n) : ℤ√d) = ↑m * ↑n := by simp [ext] protected lemma coe_int_inj {m n : ℤ} (h : (↑m : ℤ√d) = ↑n) : m = n := by simpa using congr_arg re h /-- Read `sq_le a c b d` as `a √c ≤ b √d` -/ def sq_le (a c b d : ℕ) : Prop := c*a*a ≤ d*b*b theorem sq_le_of_le {c d x y z w : ℕ} (xz : z ≤ x) (yw : y ≤ w) (xy : sq_le x c y d) : sq_le z c w d := le_trans (mul_le_mul (nat.mul_le_mul_left _ xz) xz (nat.zero_le _) (nat.zero_le _)) $ le_trans xy (mul_le_mul (nat.mul_le_mul_left _ yw) yw (nat.zero_le _) (nat.zero_le _)) theorem sq_le_add_mixed {c d x y z w : ℕ} (xy : sq_le x c y d) (zw : sq_le z c w d) : c * (x * z) ≤ d * (y * w) := nat.mul_self_le_mul_self_iff.2 $ by simpa [mul_comm, mul_left_comm] using mul_le_mul xy zw (nat.zero_le _) (nat.zero_le _) theorem sq_le_add {c d x y z w : ℕ} (xy : sq_le x c y d) (zw : sq_le z c w d) : sq_le (x + z) c (y + w) d := begin have xz := sq_le_add_mixed xy zw, simp [sq_le, mul_assoc] at xy zw, simp [sq_le, mul_add, mul_comm, mul_left_comm, add_le_add, *] end theorem sq_le_cancel {c d x y z w : ℕ} (zw : sq_le y d x c) (h : sq_le (x + z) c (y + w) d) : sq_le z c w d := begin apply le_of_not_gt, intro l, refine not_le_of_gt _ h, simp [sq_le, mul_add, mul_comm, mul_left_comm], have hm := sq_le_add_mixed zw (le_of_lt l), simp [sq_le, mul_assoc] at l zw, exact lt_of_le_of_lt (add_le_add_right zw _) (add_lt_add_left (add_lt_add_of_le_of_lt hm (add_lt_add_of_le_of_lt hm l)) _) end theorem sq_le_smul {c d x y : ℕ} (n : ℕ) (xy : sq_le x c y d) : sq_le (n * x) c (n * y) d := by simpa [sq_le, mul_left_comm, mul_assoc] using nat.mul_le_mul_left (n * n) xy theorem sq_le_mul {d x y z w : ℕ} : (sq_le x 1 y d → sq_le z 1 w d → sq_le (x * w + y * z) d (x * z + d * y * w) 1) ∧ (sq_le x 1 y d → sq_le w d z 1 → sq_le (x * z + d * y * w) 1 (x * w + y * z) d) ∧ (sq_le y d x 1 → sq_le z 1 w d → sq_le (x * z + d * y * w) 1 (x * w + y * z) d) ∧ (sq_le y d x 1 → sq_le w d z 1 → sq_le (x * w + y * z) d (x * z + d * y * w) 1) := by refine ⟨_, _, _, _⟩; { intros xy zw, have := int.mul_nonneg (sub_nonneg_of_le (int.coe_nat_le_coe_nat_of_le xy)) (sub_nonneg_of_le (int.coe_nat_le_coe_nat_of_le zw)), refine int.le_of_coe_nat_le_coe_nat (le_of_sub_nonneg _), simpa [mul_add, mul_left_comm, mul_comm] } /-- "Generalized" `nonneg`. `nonnegg c d x y` means `a √c + b √d ≥ 0`; we are interested in the case `c = 1` but this is more symmetric -/ def nonnegg (c d : ℕ) : ℤ → ℤ → Prop | (a : ℕ) (b : ℕ) := true | (a : ℕ) -[1+ b] := sq_le (b+1) c a d | -[1+ a] (b : ℕ) := sq_le (a+1) d b c | -[1+ a] -[1+ b] := false theorem nonnegg_comm {c d : ℕ} {x y : ℤ} : nonnegg c d x y = nonnegg d c y x := by induction x; induction y; refl theorem nonnegg_neg_pos {c d} : Π {a b : ℕ}, nonnegg c d (-a) b ↔ sq_le a d b c | 0 b := ⟨by simp [sq_le, nat.zero_le], λa, trivial⟩ | (a+1) b := by rw ← int.neg_succ_of_nat_coe; refl theorem nonnegg_pos_neg {c d} {a b : ℕ} : nonnegg c d a (-b) ↔ sq_le b c a d := by rw nonnegg_comm; exact nonnegg_neg_pos theorem nonnegg_cases_right {c d} {a : ℕ} : Π {b : ℤ}, (Π x : ℕ, b = -x → sq_le x c a d) → nonnegg c d a b | (b:nat) h := trivial | -[1+ b] h := h (b+1) rfl theorem nonnegg_cases_left {c d} {b : ℕ} {a : ℤ} (h : Π x : ℕ, a = -x → sq_le x d b c) : nonnegg c d a b := cast nonnegg_comm (nonnegg_cases_right h) section norm def norm (n : ℤ√d) : ℤ := n.re * n.re - d * n.im * n.im @[simp] lemma norm_zero : norm 0 = 0 := by simp [norm] @[simp] lemma norm_one : norm 1 = 1 := by simp [norm] @[simp] lemma norm_int_cast (n : ℤ) : norm n = n * n := by simp [norm] @[simp] lemma norm_nat_cast (n : ℕ) : norm n = n * n := norm_int_cast n @[simp] lemma norm_mul (n m : ℤ√d) : norm (n * m) = norm n * norm m := by simp [norm, mul_add, add_mul, mul_comm, mul_assoc, mul_left_comm] lemma norm_eq_mul_conj (n : ℤ√d) : (norm n : ℤ√d) = n * n.conj := by cases n; simp [norm, conj, zsqrtd.ext, mul_comm] instance : is_monoid_hom norm := { map_one := norm_one, map_mul := norm_mul } lemma norm_nonneg (hd : d ≤ 0) (n : ℤ√d) : 0 ≤ n.norm := add_nonneg (mul_self_nonneg _) (by rw [mul_assoc, neg_mul_eq_neg_mul]; exact (mul_nonneg (neg_nonneg.2 hd) (mul_self_nonneg _))) lemma norm_eq_one_iff {x : ℤ√d} : x.norm.nat_abs = 1 ↔ is_unit x := ⟨λ h, is_unit_iff_dvd_one.2 $ (le_total 0 (norm x)).cases_on (λ hx, show x ∣ 1, from ⟨x.conj, by rwa [← int.coe_nat_inj', int.nat_abs_of_nonneg hx, ← @int.cast_inj (ℤ√d) _ _, norm_eq_mul_conj, eq_comm] at h⟩) (λ hx, show x ∣ 1, from ⟨- x.conj, by rwa [← int.coe_nat_inj', int.of_nat_nat_abs_of_nonpos hx, ← @int.cast_inj (ℤ√d) _ _, int.cast_neg, norm_eq_mul_conj, neg_mul_eq_mul_neg, eq_comm] at h⟩), λ h, let ⟨y, hy⟩ := is_unit_iff_dvd_one.1 h in begin have := congr_arg (int.nat_abs ∘ norm) hy, rw [function.comp_app, function.comp_app, norm_mul, int.nat_abs_mul, norm_one, int.nat_abs_one, eq_comm, nat.mul_eq_one_iff] at this, exact this.1 end⟩ end norm end section parameter {d : ℕ} /-- Nonnegativity of an element of `ℤ√d`. -/ def nonneg : ℤ√d → Prop | ⟨a, b⟩ := nonnegg d 1 a b protected def le (a b : ℤ√d) : Prop := nonneg (b - a) instance : has_le ℤ√d := ⟨zsqrtd.le⟩ protected def lt (a b : ℤ√d) : Prop := ¬(b ≤ a) instance : has_lt ℤ√d := ⟨zsqrtd.lt⟩ instance decidable_nonnegg (c d a b) : decidable (nonnegg c d a b) := by cases a; cases b; repeat {rw int.of_nat_eq_coe}; unfold nonnegg sq_le; apply_instance instance decidable_nonneg : Π (a : ℤ√d), decidable (nonneg a) | ⟨a, b⟩ := zsqrtd.decidable_nonnegg _ _ _ _ instance decidable_le (a b : ℤ√d) : decidable (a ≤ b) := decidable_nonneg _ theorem nonneg_cases : Π {a : ℤ√d}, nonneg a → ∃ x y : ℕ, a = ⟨x, y⟩ ∨ a = ⟨x, -y⟩ ∨ a = ⟨-x, y⟩ | ⟨(x : ℕ), (y : ℕ)⟩ h := ⟨x, y, or.inl rfl⟩ | ⟨(x : ℕ), -[1+ y]⟩ h := ⟨x, y+1, or.inr $ or.inl rfl⟩ | ⟨-[1+ x], (y : ℕ)⟩ h := ⟨x+1, y, or.inr $ or.inr rfl⟩ | ⟨-[1+ x], -[1+ y]⟩ h := false.elim h lemma nonneg_add_lem {x y z w : ℕ} (xy : nonneg ⟨x, -y⟩) (zw : nonneg ⟨-z, w⟩) : nonneg (⟨x, -y⟩ + ⟨-z, w⟩) := have nonneg ⟨int.sub_nat_nat x z, int.sub_nat_nat w y⟩, from int.sub_nat_nat_elim x z (λm n i, sq_le y d m 1 → sq_le n 1 w d → nonneg ⟨i, int.sub_nat_nat w y⟩) (λj k, int.sub_nat_nat_elim w y (λm n i, sq_le n d (k + j) 1 → sq_le k 1 m d → nonneg ⟨int.of_nat j, i⟩) (λm n xy zw, trivial) (λm n xy zw, sq_le_cancel zw xy)) (λj k, int.sub_nat_nat_elim w y (λm n i, sq_le n d k 1 → sq_le (k + j + 1) 1 m d → nonneg ⟨-[1+ j], i⟩) (λm n xy zw, sq_le_cancel xy zw) (λm n xy zw, let t := nat.le_trans zw (sq_le_of_le (nat.le_add_right n (m+1)) (le_refl _) xy) in have k + j + 1 ≤ k, from nat.mul_self_le_mul_self_iff.2 (by repeat{rw one_mul at t}; exact t), absurd this (not_le_of_gt $ nat.succ_le_succ $ nat.le_add_right _ _))) (nonnegg_pos_neg.1 xy) (nonnegg_neg_pos.1 zw), show nonneg ⟨_, _⟩, by rw [neg_add_eq_sub]; rwa [int.sub_nat_nat_eq_coe,int.sub_nat_nat_eq_coe] at this theorem nonneg_add {a b : ℤ√d} (ha : nonneg a) (hb : nonneg b) : nonneg (a + b) := begin rcases nonneg_cases ha with ⟨x, y, rfl|rfl|rfl⟩; rcases nonneg_cases hb with ⟨z, w, rfl|rfl|rfl⟩; dsimp [add, nonneg] at ha hb ⊢, { trivial }, { refine nonnegg_cases_right (λi h, sq_le_of_le _ _ (nonnegg_pos_neg.1 hb)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ y (by simp *))) }, { apply nat.le_add_left } }, { refine nonnegg_cases_left (λi h, sq_le_of_le _ _ (nonnegg_neg_pos.1 hb)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ x (by simp *))) }, { apply nat.le_add_left } }, { refine nonnegg_cases_right (λi h, sq_le_of_le _ _ (nonnegg_pos_neg.1 ha)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ w (by simp *))) }, { apply nat.le_add_right } }, { simpa using nonnegg_pos_neg.2 (sq_le_add (nonnegg_pos_neg.1 ha) (nonnegg_pos_neg.1 hb)) }, { exact nonneg_add_lem ha hb }, { refine nonnegg_cases_left (λi h, sq_le_of_le _ _ (nonnegg_neg_pos.1 ha)), { exact int.coe_nat_le.1 (le_of_neg_le_neg (@int.le.intro _ _ z (by simp *))) }, { apply nat.le_add_right } }, { rw [add_comm, add_comm ↑y], exact nonneg_add_lem hb ha }, { simpa using nonnegg_neg_pos.2 (sq_le_add (nonnegg_neg_pos.1 ha) (nonnegg_neg_pos.1 hb)) }, end theorem le_refl (a : ℤ√d) : a ≤ a := show nonneg (a - a), by simp protected theorem le_trans {a b c : ℤ√d} (ab : a ≤ b) (bc : b ≤ c) : a ≤ c := have nonneg (b - a + (c - b)), from nonneg_add ab bc, by simpa theorem nonneg_iff_zero_le {a : ℤ√d} : nonneg a ↔ 0 ≤ a := show _ ↔ nonneg _, by simp theorem le_of_le_le {x y z w : ℤ} (xz : x ≤ z) (yw : y ≤ w) : (⟨x, y⟩ : ℤ√d) ≤ ⟨z, w⟩ := show nonneg ⟨z - x, w - y⟩, from match z - x, w - y, int.le.dest_sub xz, int.le.dest_sub yw with ._, ._, ⟨a, rfl⟩, ⟨b, rfl⟩ := trivial end theorem le_arch (a : ℤ√d) : ∃n : ℕ, a ≤ n := let ⟨x, y, (h : a ≤ ⟨x, y⟩)⟩ := show ∃x y : ℕ, nonneg (⟨x, y⟩ + -a), from match -a with | ⟨int.of_nat x, int.of_nat y⟩ := ⟨0, 0, trivial⟩ | ⟨int.of_nat x, -[1+ y]⟩ := ⟨0, y+1, by simp [int.neg_succ_of_nat_coe]⟩ | ⟨-[1+ x], int.of_nat y⟩ := ⟨x+1, 0, by simp [int.neg_succ_of_nat_coe]⟩ | ⟨-[1+ x], -[1+ y]⟩ := ⟨x+1, y+1, by simp [int.neg_succ_of_nat_coe]⟩ end in begin refine ⟨x + d*y, zsqrtd.le_trans h _⟩, rw [← int.cast_coe_nat, ← of_int_eq_coe], change nonneg ⟨(↑x + d*y) - ↑x, 0-↑y⟩, cases y with y, { simp }, have h : ∀y, sq_le y d (d * y) 1 := λ y, by simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_right (y * y) (nat.le_mul_self d), rw [show (x:ℤ) + d * nat.succ y - x = d * nat.succ y, by simp], exact h (y+1) end protected theorem nonneg_total : Π (a : ℤ√d), nonneg a ∨ nonneg (-a) | ⟨(x : ℕ), (y : ℕ)⟩ := or.inl trivial | ⟨-[1+ x], -[1+ y]⟩ := or.inr trivial | ⟨0, -[1+ y]⟩ := or.inr trivial | ⟨-[1+ x], 0⟩ := or.inr trivial | ⟨(x+1:ℕ), -[1+ y]⟩ := nat.le_total | ⟨-[1+ x], (y+1:ℕ)⟩ := nat.le_total protected theorem le_total (a b : ℤ√d) : a ≤ b ∨ b ≤ a := let t := nonneg_total (b - a) in by rw [show -(b-a) = a-b, from neg_sub b a] at t; exact t instance : preorder ℤ√d := { le := zsqrtd.le, le_refl := zsqrtd.le_refl, le_trans := @zsqrtd.le_trans, lt := zsqrtd.lt, lt_iff_le_not_le := λ a b, (and_iff_right_of_imp (zsqrtd.le_total _ _).resolve_left).symm } protected theorem add_le_add_left (a b : ℤ√d) (ab : a ≤ b) (c : ℤ√d) : c + a ≤ c + b := show nonneg _, by rw add_sub_add_left_eq_sub; exact ab protected theorem le_of_add_le_add_left (a b c : ℤ√d) (h : c + a ≤ c + b) : a ≤ b := by simpa using zsqrtd.add_le_add_left _ _ h (-c) protected theorem add_lt_add_left (a b : ℤ√d) (h : a < b) (c) : c + a < c + b := λ h', h (zsqrtd.le_of_add_le_add_left _ _ _ h') theorem nonneg_smul {a : ℤ√d} {n : ℕ} (ha : nonneg a) : nonneg (n * a) := by rw ← int.cast_coe_nat; exact match a, nonneg_cases ha, ha with | ._, ⟨x, y, or.inl rfl⟩, ha := by rw smul_val; trivial | ._, ⟨x, y, or.inr $ or.inl rfl⟩, ha := by rw smul_val; simpa using nonnegg_pos_neg.2 (sq_le_smul n $ nonnegg_pos_neg.1 ha) | ._, ⟨x, y, or.inr $ or.inr rfl⟩, ha := by rw smul_val; simpa using nonnegg_neg_pos.2 (sq_le_smul n $ nonnegg_neg_pos.1 ha) end theorem nonneg_muld {a : ℤ√d} (ha : nonneg a) : nonneg (sqrtd * a) := by refine match a, nonneg_cases ha, ha with | ._, ⟨x, y, or.inl rfl⟩, ha := trivial | ._, ⟨x, y, or.inr $ or.inl rfl⟩, ha := by simp; apply nonnegg_neg_pos.2; simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_left d (nonnegg_pos_neg.1 ha) | ._, ⟨x, y, or.inr $ or.inr rfl⟩, ha := by simp; apply nonnegg_pos_neg.2; simpa [sq_le, mul_comm, mul_left_comm] using nat.mul_le_mul_left d (nonnegg_neg_pos.1 ha) end theorem nonneg_mul_lem {x y : ℕ} {a : ℤ√d} (ha : nonneg a) : nonneg (⟨x, y⟩ * a) := have (⟨x, y⟩ * a : ℤ√d) = x * a + sqrtd * (y * a), by rw [decompose, right_distrib, mul_assoc]; refl, by rw this; exact nonneg_add (nonneg_smul ha) (nonneg_muld $ nonneg_smul ha) theorem nonneg_mul {a b : ℤ√d} (ha : nonneg a) (hb : nonneg b) : nonneg (a * b) := match a, b, nonneg_cases ha, nonneg_cases hb, ha, hb with | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := trivial | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := nonneg_mul_lem hb | ._, ._, ⟨x, y, or.inl rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := nonneg_mul_lem hb | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := by rw mul_comm; exact nonneg_mul_lem ha | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inl rfl⟩, ha, hb := by rw mul_comm; exact nonneg_mul_lem ha | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := by rw [calc (⟨-x, y⟩ * ⟨-z, w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨x * z + d * y * w, -(x * w + y * z)⟩ : by simp]; exact nonnegg_pos_neg.2 (sq_le_mul.left (nonnegg_neg_pos.1 ha) (nonnegg_neg_pos.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inr rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := by rw [calc (⟨-x, y⟩ * ⟨z, -w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨-(x * z + d * y * w), x * w + y * z⟩ : by simp]; exact nonnegg_neg_pos.2 (sq_le_mul.right.left (nonnegg_neg_pos.1 ha) (nonnegg_pos_neg.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inr $ or.inr rfl⟩, ha, hb := by rw [calc (⟨x, -y⟩ * ⟨-z, w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨-(x * z + d * y * w), x * w + y * z⟩ : by simp]; exact nonnegg_neg_pos.2 (sq_le_mul.right.right.left (nonnegg_pos_neg.1 ha) (nonnegg_neg_pos.1 hb)) | ._, ._, ⟨x, y, or.inr $ or.inl rfl⟩, ⟨z, w, or.inr $ or.inl rfl⟩, ha, hb := by rw [calc (⟨x, -y⟩ * ⟨z, -w⟩ : ℤ√d) = ⟨_, _⟩ : rfl ... = ⟨x * z + d * y * w, -(x * w + y * z)⟩ : by simp]; exact nonnegg_pos_neg.2 (sq_le_mul.right.right.right (nonnegg_pos_neg.1 ha) (nonnegg_pos_neg.1 hb)) end protected theorem mul_nonneg (a b : ℤ√d) : 0 ≤ a → 0 ≤ b → 0 ≤ a * b := by repeat {rw ← nonneg_iff_zero_le}; exact nonneg_mul theorem not_sq_le_succ (c d y) (h : c > 0) : ¬sq_le (y + 1) c 0 d := not_le_of_gt $ mul_pos (mul_pos h $ nat.succ_pos _) $ nat.succ_pos _ /-- A nonsquare is a natural number that is not equal to the square of an integer. This is implemented as a typeclass because it's a necessary condition for much of the Pell equation theory. -/ class nonsquare (x : ℕ) : Prop := (ns : ∀n : ℕ, x ≠ n*n) parameter [dnsq : nonsquare d] include dnsq theorem d_pos : 0 < d := lt_of_le_of_ne (nat.zero_le _) $ ne.symm $ (nonsquare.ns d 0) theorem divides_sq_eq_zero {x y} (h : x * x = d * y * y) : x = 0 ∧ y = 0 := let g := x.gcd y in or.elim g.eq_zero_or_pos (λH, ⟨nat.eq_zero_of_gcd_eq_zero_left H, nat.eq_zero_of_gcd_eq_zero_right H⟩) (λgpos, false.elim $ let ⟨m, n, co, (hx : x = m * g), (hy : y = n * g)⟩ := nat.exists_coprime gpos in begin rw [hx, hy] at h, have : m * m = d * (n * n) := nat.eq_of_mul_eq_mul_left (mul_pos gpos gpos) (by simpa [mul_comm, mul_left_comm] using h), have co2 := let co1 := co.mul_right co in co1.mul co1, exact nonsquare.ns d m (nat.dvd_antisymm (by rw this; apply dvd_mul_right) $ co2.dvd_of_dvd_mul_right $ by simp [this]) end) theorem divides_sq_eq_zero_z {x y : ℤ} (h : x * x = d * y * y) : x = 0 ∧ y = 0 := by rw [mul_assoc, ← int.nat_abs_mul_self, ← int.nat_abs_mul_self, ← int.coe_nat_mul, ← mul_assoc] at h; exact let ⟨h1, h2⟩ := divides_sq_eq_zero (int.coe_nat_inj h) in ⟨int.eq_zero_of_nat_abs_eq_zero h1, int.eq_zero_of_nat_abs_eq_zero h2⟩ theorem not_divides_square (x y) : (x + 1) * (x + 1) ≠ d * (y + 1) * (y + 1) := λe, by have t := (divides_sq_eq_zero e).left; contradiction theorem nonneg_antisymm : Π {a : ℤ√d}, nonneg a → nonneg (-a) → a = 0 | ⟨0, 0⟩ xy yx := rfl | ⟨-[1+ x], -[1+ y]⟩ xy yx := false.elim xy | ⟨(x+1:nat), (y+1:nat)⟩ xy yx := false.elim yx | ⟨-[1+ x], 0⟩ xy yx := absurd xy (not_sq_le_succ _ _ _ dec_trivial) | ⟨(x+1:nat), 0⟩ xy yx := absurd yx (not_sq_le_succ _ _ _ dec_trivial) | ⟨0, -[1+ y]⟩ xy yx := absurd xy (not_sq_le_succ _ _ _ d_pos) | ⟨0, (y+1:nat)⟩ _ yx := absurd yx (not_sq_le_succ _ _ _ d_pos) | ⟨(x+1:nat), -[1+ y]⟩ (xy : sq_le _ _ _ _) (yx : sq_le _ _ _ _) := let t := le_antisymm yx xy in by rw[one_mul] at t; exact absurd t (not_divides_square _ _) | ⟨-[1+ x], (y+1:nat)⟩ (xy : sq_le _ _ _ _) (yx : sq_le _ _ _ _) := let t := le_antisymm xy yx in by rw[one_mul] at t; exact absurd t (not_divides_square _ _) theorem le_antisymm {a b : ℤ√d} (ab : a ≤ b) (ba : b ≤ a) : a = b := eq_of_sub_eq_zero $ nonneg_antisymm ba (by rw neg_sub; exact ab) instance : decidable_linear_order ℤ√d := { le_antisymm := @zsqrtd.le_antisymm, le_total := zsqrtd.le_total, decidable_le := zsqrtd.decidable_le, ..zsqrtd.preorder } protected theorem eq_zero_or_eq_zero_of_mul_eq_zero : Π {a b : ℤ√d}, a * b = 0 → a = 0 ∨ b = 0 | ⟨x, y⟩ ⟨z, w⟩ h := by injection h with h1 h2; exact have h1 : x*z = -(d*y*w), from eq_neg_of_add_eq_zero h1, have h2 : x*w = -(y*z), from eq_neg_of_add_eq_zero h2, have fin : x*x = d*y*y → (⟨x, y⟩:ℤ√d) = 0, from λe, match x, y, divides_sq_eq_zero_z e with ._, ._, ⟨rfl, rfl⟩ := rfl end, if z0 : z = 0 then if w0 : w = 0 then or.inr (match z, w, z0, w0 with ._, ._, rfl, rfl := rfl end) else or.inl $ fin $ eq_of_mul_eq_mul_right w0 $ calc x * x * w = -y * (x * z) : by simp [h2, mul_assoc, mul_left_comm] ... = d * y * y * w : by simp [h1, mul_assoc, mul_left_comm] else or.inl $ fin $ eq_of_mul_eq_mul_right z0 $ calc x * x * z = d * -y * (x * w) : by simp [h1, mul_assoc, mul_left_comm] ... = d * y * y * z : by simp [h2, mul_assoc, mul_left_comm] instance : integral_domain ℤ√d := { zero_ne_one := zero_ne_one, eq_zero_or_eq_zero_of_mul_eq_zero := @zsqrtd.eq_zero_or_eq_zero_of_mul_eq_zero, ..zsqrtd.comm_ring } protected theorem mul_pos (a b : ℤ√d) (a0 : 0 < a) (b0 : 0 < b) : 0 < a * b := λab, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero (le_antisymm ab (mul_nonneg _ _ (le_of_lt a0) (le_of_lt b0)))) (λe, ne_of_gt a0 e) (λe, ne_of_gt b0 e) instance : decidable_linear_ordered_comm_ring ℤ√d := { add_le_add_left := @zsqrtd.add_le_add_left, add_lt_add_left := @zsqrtd.add_lt_add_left, zero_ne_one := zero_ne_one, mul_nonneg := @zsqrtd.mul_nonneg, mul_pos := @zsqrtd.mul_pos, zero_lt_one := dec_trivial, ..zsqrtd.comm_ring, ..zsqrtd.decidable_linear_order } instance : decidable_linear_ordered_semiring ℤ√d := by apply_instance instance : linear_ordered_semiring ℤ√d := by apply_instance instance : ordered_semiring ℤ√d := by apply_instance end end zsqrtd
cb5195e1ff5b99b65daeb01336e5592bb8e97a67
4727251e0cd73359b15b664c3170e5d754078599
/src/group_theory/subgroup/pointwise.lean
210cb0ae7059d3f6be43acabb2f3b5731d1dfd36
[ "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
8,832
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import group_theory.subgroup.basic import group_theory.submonoid.pointwise /-! # Pointwise instances on `subgroup` and `add_subgroup`s This file provides the actions * `subgroup.pointwise_mul_action` * `add_subgroup.pointwise_mul_action` which matches the action of `mul_action_set`. These actions are available in the `pointwise` locale. ## Implementation notes This file is almost identical to `group_theory/submonoid/pointwise.lean`. Where possible, try to keep them in sync. -/ variables {α : Type*} {G : Type*} {A : Type*} [group G] [add_group A] namespace subgroup section monoid variables [monoid α] [mul_distrib_mul_action α G] /-- The action on a subgroup corresponding to applying the action to every element. This is available as an instance in the `pointwise` locale. -/ protected def pointwise_mul_action : mul_action α (subgroup G) := { smul := λ a S, S.map (mul_distrib_mul_action.to_monoid_End _ _ a), one_smul := λ S, (congr_arg (λ f, S.map f) (monoid_hom.map_one _)).trans S.map_id, mul_smul := λ a₁ a₂ S, (congr_arg (λ f, S.map f) (monoid_hom.map_mul _ _ _)).trans (S.map_map _ _).symm,} localized "attribute [instance] subgroup.pointwise_mul_action" in pointwise open_locale pointwise lemma pointwise_smul_def {a : α} (S : subgroup G) : a • S = S.map (mul_distrib_mul_action.to_monoid_End _ _ a) := rfl @[simp] lemma coe_pointwise_smul (a : α) (S : subgroup G) : ↑(a • S) = a • (S : set G) := rfl @[simp] lemma pointwise_smul_to_submonoid (a : α) (S : subgroup G) : (a • S).to_submonoid = a • S.to_submonoid := rfl lemma smul_mem_pointwise_smul (m : G) (a : α) (S : subgroup G) : m ∈ S → a • m ∈ a • S := (set.smul_mem_smul_set : _ → _ ∈ a • (S : set G)) lemma mem_smul_pointwise_iff_exists (m : G) (a : α) (S : subgroup G) : m ∈ a • S ↔ ∃ (s : G), s ∈ S ∧ a • s = m := (set.mem_smul_set : m ∈ a • (S : set G) ↔ _) instance pointwise_central_scalar [mul_distrib_mul_action αᵐᵒᵖ G] [is_central_scalar α G] : is_central_scalar α (subgroup G) := ⟨λ a S, congr_arg (λ f, S.map f) $ monoid_hom.ext $ by exact op_smul_eq_smul _⟩ end monoid section group variables [group α] [mul_distrib_mul_action α G] open_locale pointwise @[simp] lemma smul_mem_pointwise_smul_iff {a : α} {S : subgroup G} {x : G} : a • x ∈ a • S ↔ x ∈ S := smul_mem_smul_set_iff lemma mem_pointwise_smul_iff_inv_smul_mem {a : α} {S : subgroup G} {x : G} : x ∈ a • S ↔ a⁻¹ • x ∈ S := mem_smul_set_iff_inv_smul_mem lemma mem_inv_pointwise_smul_iff {a : α} {S : subgroup G} {x : G} : x ∈ a⁻¹ • S ↔ a • x ∈ S := mem_inv_smul_set_iff @[simp] lemma pointwise_smul_le_pointwise_smul_iff {a : α} {S T : subgroup G} : a • S ≤ a • T ↔ S ≤ T := set_smul_subset_set_smul_iff lemma pointwise_smul_subset_iff {a : α} {S T : subgroup G} : a • S ≤ T ↔ S ≤ a⁻¹ • T := set_smul_subset_iff lemma subset_pointwise_smul_iff {a : α} {S T : subgroup G} : S ≤ a • T ↔ a⁻¹ • S ≤ T := subset_set_smul_iff /-- Applying a `mul_distrib_mul_action` results in an isomorphic subgroup -/ @[simps] def equiv_smul (a : α) (H : subgroup G) : H ≃* (a • H : subgroup G) := (mul_distrib_mul_action.to_mul_equiv G a).subgroup_map H lemma subgroup_mul_singleton {H : subgroup G} {h : G} (hh : h ∈ H) : (H : set G) * {h} = H := begin refine le_antisymm _ (λ h' hh', ⟨h' * h⁻¹, h, H.mul_mem hh' (H.inv_mem hh), rfl, inv_mul_cancel_right h' h⟩), rintros _ ⟨h', h, hh', rfl : _ = _, rfl⟩, exact H.mul_mem hh' hh, end lemma singleton_mul_subgroup {H : subgroup G} {h : G} (hh : h ∈ H) : {h} * (H : set G) = H := begin refine le_antisymm _ (λ h' hh', ⟨h, h⁻¹ * h', rfl, H.mul_mem (H.inv_mem hh) hh', mul_inv_cancel_left h h'⟩), rintros _ ⟨h, h', rfl : _ = _, hh', rfl⟩, exact H.mul_mem hh hh', end end group section group_with_zero variables [group_with_zero α] [mul_distrib_mul_action α G] open_locale pointwise @[simp] lemma smul_mem_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) (S : subgroup G) (x : G) : a • x ∈ a • S ↔ x ∈ S := smul_mem_smul_set_iff₀ ha (S : set G) x lemma mem_pointwise_smul_iff_inv_smul_mem₀ {a : α} (ha : a ≠ 0) (S : subgroup G) (x : G) : x ∈ a • S ↔ a⁻¹ • x ∈ S := mem_smul_set_iff_inv_smul_mem₀ ha (S : set G) x lemma mem_inv_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) (S : subgroup G) (x : G) : x ∈ a⁻¹ • S ↔ a • x ∈ S := mem_inv_smul_set_iff₀ ha (S : set G) x @[simp] lemma pointwise_smul_le_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) {S T : subgroup G} : a • S ≤ a • T ↔ S ≤ T := set_smul_subset_set_smul_iff₀ ha lemma pointwise_smul_le_iff₀ {a : α} (ha : a ≠ 0) {S T : subgroup G} : a • S ≤ T ↔ S ≤ a⁻¹ • T := set_smul_subset_iff₀ ha lemma le_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) {S T : subgroup G} : S ≤ a • T ↔ a⁻¹ • S ≤ T := subset_set_smul_iff₀ ha end group_with_zero end subgroup namespace add_subgroup section monoid variables [monoid α] [distrib_mul_action α A] /-- The action on an additive subgroup corresponding to applying the action to every element. This is available as an instance in the `pointwise` locale. -/ protected def pointwise_mul_action : mul_action α (add_subgroup A) := { smul := λ a S, S.map (distrib_mul_action.to_add_monoid_End _ _ a), one_smul := λ S, (congr_arg (λ f, S.map f) (monoid_hom.map_one _)).trans S.map_id, mul_smul := λ a₁ a₂ S, (congr_arg (λ f, S.map f) (monoid_hom.map_mul _ _ _)).trans (S.map_map _ _).symm,} localized "attribute [instance] add_subgroup.pointwise_mul_action" in pointwise open_locale pointwise @[simp] lemma coe_pointwise_smul (a : α) (S : add_subgroup A) : ↑(a • S) = a • (S : set A) := rfl @[simp] lemma pointwise_smul_to_add_submonoid (a : α) (S : add_subgroup A) : (a • S).to_add_submonoid = a • S.to_add_submonoid := rfl lemma smul_mem_pointwise_smul (m : A) (a : α) (S : add_subgroup A) : m ∈ S → a • m ∈ a • S := (set.smul_mem_smul_set : _ → _ ∈ a • (S : set A)) lemma mem_smul_pointwise_iff_exists (m : A) (a : α) (S : add_subgroup A) : m ∈ a • S ↔ ∃ (s : A), s ∈ S ∧ a • s = m := (set.mem_smul_set : m ∈ a • (S : set A) ↔ _) instance pointwise_central_scalar [distrib_mul_action αᵐᵒᵖ A] [is_central_scalar α A] : is_central_scalar α (add_subgroup A) := ⟨λ a S, congr_arg (λ f, S.map f) $ add_monoid_hom.ext $ by exact op_smul_eq_smul _⟩ end monoid section group variables [group α] [distrib_mul_action α A] open_locale pointwise @[simp] lemma smul_mem_pointwise_smul_iff {a : α} {S : add_subgroup A} {x : A} : a • x ∈ a • S ↔ x ∈ S := smul_mem_smul_set_iff lemma mem_pointwise_smul_iff_inv_smul_mem {a : α} {S : add_subgroup A} {x : A} : x ∈ a • S ↔ a⁻¹ • x ∈ S := mem_smul_set_iff_inv_smul_mem lemma mem_inv_pointwise_smul_iff {a : α} {S : add_subgroup A} {x : A} : x ∈ a⁻¹ • S ↔ a • x ∈ S := mem_inv_smul_set_iff @[simp] lemma pointwise_smul_le_pointwise_smul_iff {a : α} {S T : add_subgroup A} : a • S ≤ a • T ↔ S ≤ T := set_smul_subset_set_smul_iff lemma pointwise_smul_le_iff {a : α} {S T : add_subgroup A} : a • S ≤ T ↔ S ≤ a⁻¹ • T := set_smul_subset_iff lemma le_pointwise_smul_iff {a : α} {S T : add_subgroup A} : S ≤ a • T ↔ a⁻¹ • S ≤ T := subset_set_smul_iff end group section group_with_zero variables [group_with_zero α] [distrib_mul_action α A] open_locale pointwise @[simp] lemma smul_mem_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) (S : add_subgroup A) (x : A) : a • x ∈ a • S ↔ x ∈ S := smul_mem_smul_set_iff₀ ha (S : set A) x lemma mem_pointwise_smul_iff_inv_smul_mem₀ {a : α} (ha : a ≠ 0) (S : add_subgroup A) (x : A) : x ∈ a • S ↔ a⁻¹ • x ∈ S := mem_smul_set_iff_inv_smul_mem₀ ha (S : set A) x lemma mem_inv_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) (S : add_subgroup A) (x : A) : x ∈ a⁻¹ • S ↔ a • x ∈ S := mem_inv_smul_set_iff₀ ha (S : set A) x @[simp] lemma pointwise_smul_le_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) {S T : add_subgroup A} : a • S ≤ a • T ↔ S ≤ T := set_smul_subset_set_smul_iff₀ ha lemma pointwise_smul_le_iff₀ {a : α} (ha : a ≠ 0) {S T : add_subgroup A} : a • S ≤ T ↔ S ≤ a⁻¹ • T := set_smul_subset_iff₀ ha lemma le_pointwise_smul_iff₀ {a : α} (ha : a ≠ 0) {S T : add_subgroup A} : S ≤ a • T ↔ a⁻¹ • S ≤ T := subset_set_smul_iff₀ ha end group_with_zero end add_subgroup
60cca3f9d646389db745c3b21fbaad40f3689328
ff5230333a701471f46c57e8c115a073ebaaa448
/library/init/data/nat/default.lean
00050a942365f91266ba55e6c48766c6b9270a5f
[ "Apache-2.0" ]
permissive
stanford-cs242/lean
f81721d2b5d00bc175f2e58c57b710d465e6c858
7bd861261f4a37326dcf8d7a17f1f1f330e4548c
refs/heads/master
1,600,957,431,849
1,576,465,093,000
1,576,465,093,000
225,779,423
0
3
Apache-2.0
1,575,433,936,000
1,575,433,935,000
null
UTF-8
Lean
false
false
267
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.nat.basic init.data.nat.div init.data.nat.lemmas init.data.nat.bitwise
01ad575e682caa20e5fee2f4c858e3a07154423a
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/Data/Lsp/TextSync.lean
04ef80c83b8dda829099ea4ff2b3bd9d87c86900
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,633
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Lean.Data.Json import Lean.Data.Lsp.Basic /-! Section "Text Document Synchronization" of the LSP spec. -/ namespace Lean namespace Lsp open Json inductive TextDocumentSyncKind := | none | full | incremental instance : FromJson TextDocumentSyncKind := ⟨fun j => match j.getNat? with | some 0 => TextDocumentSyncKind.none | some 1 => TextDocumentSyncKind.full | some 2 => TextDocumentSyncKind.incremental | _ => none⟩ instance : ToJson TextDocumentSyncKind := ⟨fun o => match o with | TextDocumentSyncKind.none => 0 | TextDocumentSyncKind.full => 1 | TextDocumentSyncKind.incremental => 2⟩ structure DidOpenTextDocumentParams := (textDocument : TextDocumentItem) instance : FromJson DidOpenTextDocumentParams := ⟨fun j => DidOpenTextDocumentParams.mk <$> j.getObjValAs? TextDocumentItem "textDocument"⟩ instance : ToJson DidOpenTextDocumentParams := ⟨fun o => mkObj $ [⟨"textDocument", toJson o.textDocument⟩]⟩ structure TextDocumentChangeRegistrationOptions := (documentSelector? : Option DocumentSelector := none) (syncKind : TextDocumentSyncKind) instance : FromJson TextDocumentChangeRegistrationOptions := ⟨fun j => do let documentSelector? := j.getObjValAs? DocumentSelector "documentSelector"; let syncKind ← j.getObjValAs? TextDocumentSyncKind "syncKind"; pure ⟨documentSelector?, syncKind⟩⟩ inductive TextDocumentContentChangeEvent := -- omitted: deprecated rangeLength | rangeChange (range : Range) (text : String) | fullChange (text : String) instance : FromJson TextDocumentContentChangeEvent := ⟨fun j => (do let range ← j.getObjValAs? Range "range" let text ← j.getObjValAs? String "text" pure $ TextDocumentContentChangeEvent.rangeChange range text) <|> (TextDocumentContentChangeEvent.fullChange <$> j.getObjValAs? String "text")⟩ structure DidChangeTextDocumentParams := (textDocument : VersionedTextDocumentIdentifier) (contentChanges : Array TextDocumentContentChangeEvent) instance : FromJson DidChangeTextDocumentParams := ⟨fun j => do let textDocument ← j.getObjValAs? VersionedTextDocumentIdentifier "textDocument" let contentChanges ← j.getObjValAs? (Array TextDocumentContentChangeEvent) "contentChanges" pure ⟨textDocument, contentChanges⟩⟩ -- TODO: missing: -- WillSaveTextDocumentParams, TextDocumentSaveReason, -- TextDocumentSaveRegistrationOptions, DidSaveTextDocumentParams structure SaveOptions := (includeText : Bool) instance : ToJson SaveOptions := ⟨fun o => mkObj $ [⟨"includeText", o.includeText⟩]⟩ structure DidCloseTextDocumentParams := (textDocument : TextDocumentIdentifier) instance : FromJson DidCloseTextDocumentParams := ⟨fun j => DidCloseTextDocumentParams.mk <$> j.getObjValAs? TextDocumentIdentifier "textDocument"⟩ -- TODO: TextDocumentSyncClientCapabilities /- NOTE: This is defined twice in the spec. The latter version has more fields. -/ structure TextDocumentSyncOptions := (openClose : Bool) (change : TextDocumentSyncKind) (willSave : Bool) (willSaveWaitUntil : Bool) (save? : Option SaveOptions := none) instance : ToJson TextDocumentSyncOptions := ⟨fun o => mkObj $ opt "save" o.save? ++ [ ⟨"openClose", toJson o.openClose⟩, ⟨"change", toJson o.change⟩, ⟨"willSave", toJson o.willSave⟩, ⟨"willSaveWaitUntil", toJson o.willSaveWaitUntil⟩]⟩ end Lsp end Lean
1414497a6dd9fde86bd5d8ed2861ff98ae1d565f
40ad357bbd0d327dd1e3e7f7beb868bd4e5b0a9d
/test/benchmark.lean
715644ca4c93fef3d7aec7d8d707867ad877eca9
[]
no_license
unitb/temporal-logic
9966424f015976d5997a9ffa30cbd77cc3a9cb1c
accec04d1b09ca841be065511c9e206b725b16e9
refs/heads/master
1,633,868,382,769
1,541,072,223,000
1,541,072,223,000
114,790,987
5
3
null
null
null
null
UTF-8
Lean
false
false
689
lean
import temporal_logic set_option profiler true open temporal predicate variables Γ : cpred variables P Q R S : ℕ → cpred include P Q R S example : Γ ⊢ True := begin [temporal] iterate 100 { have : ∀∀ x, P x ⟶ Q x ⟶ R x ⟶ S x, { intros, guard_target S x, admit }, clear this }, trivial end lemma leads_to_trans {p q r : cpred} {Γ} (Hpq : Γ ⊢ p ~> q) (Hqr : Γ ⊢ q ~> r) : Γ ⊢ True := begin [temporal] iterate 10 { have : p ~> r, { henceforth, intros hp, have := Hpq hp, revert this, rw ← eventually_eventually r, clear hp, monotonicity, apply Hqr }, clear this }, trivial end
91450cd3ce2cb8254118d2c1d3f18bc3430bddc8
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/category/monad/cont.lean
f325da1743c1e317d6c5bc525e3eb1c0b0835a35
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
8,762
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon Monad encapsulating continuation passing programming style, similar to Haskell's `Cont`, `ContT` and `MonadCont`: http://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-Cont.html -/ import tactic.ext import category.monad.basic category.monad.writer universes u v w structure monad_cont.label (α : Type w) (m : Type u → Type v) (β : Type u) := (apply : α → m β) def monad_cont.goto {α β} {m : Type u → Type v} (f : monad_cont.label α m β) (x : α) := f.apply x class monad_cont (m : Type u → Type v) := (call_cc : Π {α β}, ((monad_cont.label α m β) → m α) → m α) open monad_cont class is_lawful_monad_cont (m : Type u → Type v) [monad m] [monad_cont m] extends is_lawful_monad m := (call_cc_bind_right {α ω γ} (cmd : m α) (next : (label ω m γ) → α → m ω) : call_cc (λ f, cmd >>= next f) = cmd >>= λ x, call_cc (λ f, next f x)) (call_cc_bind_left {α} (β) (x : α) (dead : label α m β → β → m α) : call_cc (λ f : label α m β, goto f x >>= dead f) = pure x) (call_cc_dummy {α β} (dummy : m α) : call_cc (λ f : label α m β, dummy) = dummy) export is_lawful_monad_cont def cont_t (r : Type u) (m : Type u → Type v) (α : Type w) := (α → m r) → m r @[reducible] def cont (r : Type u) (α : Type w) := cont_t r id α namespace cont_t export monad_cont (label goto) variables {r : Type u} {m : Type u → Type v} {α β γ ω : Type w} def run : cont_t r m α → (α → m r) → m r := id def map (f : m r → m r) (x : cont_t r m α) : cont_t r m α := f ∘ x lemma run_cont_t_map_cont_t (f : m r → m r) (x : cont_t r m α) : run (map f x) = f ∘ run x := rfl def with_cont_t (f : (β → m r) → α → m r) (x : cont_t r m α) : cont_t r m β := λ g, x $ f g lemma run_with_cont_t (f : (β → m r) → α → m r) (x : cont_t r m α) : run (with_cont_t f x) = run x ∘ f := rfl @[ext] protected lemma ext {x y : cont_t r m α} (h : ∀ f, x.run f = y.run f) : x = y := by { ext; apply h } instance : monad (cont_t r m) := { pure := λ α x f, f x, bind := λ α β x f g, x $ λ i, f i g } instance : is_lawful_monad (cont_t r m) := { id_map := by { intros, refl }, pure_bind := by { intros, ext, refl }, bind_assoc := by { intros, ext, refl } } def monad_lift [monad m] {α} : m α → cont_t r m α := λ x f, x >>= f instance [monad m] : has_monad_lift m (cont_t r m) := { monad_lift := λ α, cont_t.monad_lift } lemma monad_lift_bind [monad m] [is_lawful_monad m] {α β} (x : m α) (f : α → m β) : (monad_lift (x >>= f) : cont_t r m β) = monad_lift x >>= monad_lift ∘ f := by { ext, simp only [monad_lift,has_monad_lift.monad_lift,(∘),(>>=),bind_assoc,id.def,run,cont_t.monad_lift] } instance : monad_cont (cont_t r m) := { call_cc := λ α β f g, f ⟨λ x h, g x⟩ g } instance : is_lawful_monad_cont (cont_t r m) := { call_cc_bind_right := by intros; ext; refl, call_cc_bind_left := by intros; ext; refl, call_cc_dummy := by intros; ext; refl } instance (ε) [monad_except ε m] : monad_except ε (cont_t r m) := { throw := λ x e f, throw e, catch := λ α act h f, catch (act f) (λ e, h e f) } instance : monad_run (λ α, (α → m r) → ulift.{u v} (m r)) (cont_t.{u v u} r m) := { run := λ α f x, ⟨ f x ⟩ } end cont_t variables {m : Type u → Type v} [monad m] def except_t.mk_label {α β ε} : label (except.{u u} ε α) m β → label α (except_t ε m) β | ⟨ f ⟩ := ⟨ λ a, monad_lift $ f (except.ok a) ⟩ lemma except_t.goto_mk_label {α β ε : Type*} (x : label (except.{u u} ε α) m β) (i : α) : goto (except_t.mk_label x) i = ⟨ except.ok <$> goto x (except.ok i) ⟩ := by cases x; refl def except_t.call_cc {ε} [monad_cont m] {α β : Type*} (f : label α (except_t ε m) β → except_t ε m α) : except_t ε m α := except_t.mk (call_cc $ λ x : label _ m β, except_t.run $ f (except_t.mk_label x) : m (except ε α)) instance {ε} [monad_cont m] : monad_cont (except_t ε m) := { call_cc := λ α β, except_t.call_cc } instance {ε} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (except_t ε m) := { call_cc_bind_right := by { intros, simp [call_cc,except_t.call_cc,call_cc_bind_right], ext, dsimp, congr, ext ⟨ ⟩; simp [except_t.bind_cont,@call_cc_dummy m _], }, call_cc_bind_left := by { intros, simp [call_cc,except_t.call_cc,call_cc_bind_right,except_t.goto_mk_label,map_eq_bind_pure_comp,bind_assoc,@call_cc_bind_left m _], ext, refl }, call_cc_dummy := by { intros, simp [call_cc,except_t.call_cc,@call_cc_dummy m _], ext, refl }, } def option_t.mk_label {α β} : label (option.{u} α) m β → label α (option_t m) β | ⟨ f ⟩ := ⟨ λ a, monad_lift $ f (some a) ⟩ lemma option_t.goto_mk_label {α β : Type*} (x : label (option.{u} α) m β) (i : α) : goto (option_t.mk_label x) i = ⟨ some <$> goto x (some i) ⟩ := by cases x; refl def option_t.call_cc [monad_cont m] {α β : Type*} (f : label α (option_t m) β → option_t m α) : option_t m α := option_t.mk (call_cc $ λ x : label _ m β, option_t.run $ f (option_t.mk_label x) : m (option α)) instance [monad_cont m] : monad_cont (option_t m) := { call_cc := λ α β, option_t.call_cc } instance [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (option_t m) := { call_cc_bind_right := by { intros, simp [call_cc,option_t.call_cc,call_cc_bind_right], ext, dsimp, congr, ext ⟨ ⟩; simp [option_t.bind_cont,@call_cc_dummy m _], }, call_cc_bind_left := by { intros, simp [call_cc,option_t.call_cc,call_cc_bind_right,option_t.goto_mk_label,map_eq_bind_pure_comp,bind_assoc,@call_cc_bind_left m _], ext, refl }, call_cc_dummy := by { intros, simp [call_cc,option_t.call_cc,@call_cc_dummy m _], ext, refl }, } def writer_t.mk_label {α β ω} [has_one ω] : label (α × ω) m β → label α (writer_t ω m) β | ⟨ f ⟩ := ⟨ λ a, monad_lift $ f (a,1) ⟩ lemma writer_t.goto_mk_label {α β ω : Type*} [has_one ω] (x : label (α × ω) m β) (i : α) : goto (writer_t.mk_label x) i = monad_lift (goto x (i,1)) := by cases x; refl def writer_t.call_cc [monad_cont m] {α β ω : Type*} [has_one ω] (f : label α (writer_t ω m) β → writer_t ω m α) : writer_t ω m α := ⟨ call_cc (writer_t.run ∘ f ∘ writer_t.mk_label : label (α × ω) m β → m (α × ω)) ⟩ instance (ω) [monad m] [has_one ω] [monad_cont m] : monad_cont (writer_t ω m) := { call_cc := λ α β, writer_t.call_cc } def state_t.mk_label {α β σ : Type u} : label (α × σ) m (β × σ) → label α (state_t σ m) β | ⟨ f ⟩ := ⟨ λ a, ⟨ λ s, f (a,s) ⟩ ⟩ lemma state_t.goto_mk_label {α β σ : Type u} (x : label (α × σ) m (β × σ)) (i : α) : goto (state_t.mk_label x) i = ⟨ λ s, (goto x (i,s)) ⟩ := by cases x; refl def state_t.call_cc {σ} [monad_cont m] {α β : Type*} (f : label α (state_t σ m) β → state_t σ m α) : state_t σ m α := ⟨ λ r, call_cc (λ f', (f $ state_t.mk_label f').run r) ⟩ instance {σ} [monad_cont m] : monad_cont (state_t σ m) := { call_cc := λ α β, state_t.call_cc } instance {σ} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (state_t σ m) := { call_cc_bind_right := by { intros, simp [call_cc,state_t.call_cc,call_cc_bind_right,(>>=),state_t.bind], ext, dsimp, congr, ext ⟨x₀,x₁⟩, refl }, call_cc_bind_left := by { intros, simp [call_cc,state_t.call_cc,call_cc_bind_left,(>>=),state_t.bind,state_t.goto_mk_label], ext, refl }, call_cc_dummy := by { intros, simp [call_cc,state_t.call_cc,call_cc_bind_right,(>>=),state_t.bind,@call_cc_dummy m _], ext, refl }, } def reader_t.mk_label {α β} (ρ) : label α m β → label α (reader_t ρ m) β | ⟨ f ⟩ := ⟨ monad_lift ∘ f ⟩ lemma reader_t.goto_mk_label {α ρ β} (x : label α m β) (i : α) : goto (reader_t.mk_label ρ x) i = monad_lift (goto x i) := by cases x; refl def reader_t.call_cc {ε} [monad_cont m] {α β : Type*} (f : label α (reader_t ε m) β → reader_t ε m α) : reader_t ε m α := ⟨ λ r, call_cc (λ f', (f $ reader_t.mk_label _ f').run r) ⟩ instance {ρ} [monad_cont m] : monad_cont (reader_t ρ m) := { call_cc := λ α β, reader_t.call_cc } instance {ρ} [monad_cont m] [is_lawful_monad_cont m] : is_lawful_monad_cont (reader_t ρ m) := { call_cc_bind_right := by { intros, simp [call_cc,reader_t.call_cc,call_cc_bind_right], ext, refl }, call_cc_bind_left := by { intros, simp [call_cc,reader_t.call_cc,call_cc_bind_left,reader_t.goto_mk_label], ext, refl }, call_cc_dummy := by { intros, simp [call_cc,reader_t.call_cc,@call_cc_dummy m _], ext, refl } }
840207a874934d119e734d2e10638244787d352e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/liminf_limsup.lean
ff6dd40b3ec183990eb97d6fe5450e9b3b961fa8
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
41,643
lean
/- Copyright (c) 2018 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel, Johannes Hölzl, Rémy Degenne -/ import order.filter.cofinite import order.hom.complete_lattice /-! # liminfs and limsups of functions and filters Defines the Liminf/Limsup of a function taking values in a conditionally complete lattice, with respect to an arbitrary filter. We define `Limsup f` (`Liminf f`) where `f` is a filter taking values in a conditionally complete lattice. `Limsup f` is the smallest element `a` such that, eventually, `u ≤ a` (and vice versa for `Liminf f`). To work with the Limsup along a function `u` use `Limsup (map u f)`. Usually, one defines the Limsup as `Inf (Sup s)` where the Inf is taken over all sets in the filter. For instance, in ℕ along a function `u`, this is `Inf_n (Sup_{k ≥ n} u k)` (and the latter quantity decreases with `n`, so this is in fact a limit.). There is however a difficulty: it is well possible that `u` is not bounded on the whole space, only eventually (think of `Limsup (λx, 1/x)` on ℝ. Then there is no guarantee that the quantity above really decreases (the value of the `Sup` beforehand is not really well defined, as one can not use ∞), so that the Inf could be anything. So one can not use this `Inf Sup ...` definition in conditionally complete lattices, and one has to use a less tractable definition. In conditionally complete lattices, the definition is only useful for filters which are eventually bounded above (otherwise, the Limsup would morally be +∞, which does not belong to the space) and which are frequently bounded below (otherwise, the Limsup would morally be -∞, which is not in the space either). We start with definitions of these concepts for arbitrary filters, before turning to the definitions of Limsup and Liminf. In complete lattices, however, it coincides with the `Inf Sup` definition. -/ open filter set open_locale filter variables {α β γ ι : Type*} namespace filter section relation /-- `f.is_bounded (≺)`: the filter `f` is eventually bounded w.r.t. the relation `≺`, i.e. eventually, it is bounded by some uniform bound. `r` will be usually instantiated with `≤` or `≥`. -/ def is_bounded (r : α → α → Prop) (f : filter α) := ∃ b, ∀ᶠ x in f, r x b /-- `f.is_bounded_under (≺) u`: the image of the filter `f` under `u` is eventually bounded w.r.t. the relation `≺`, i.e. eventually, it is bounded by some uniform bound. -/ def is_bounded_under (r : α → α → Prop) (f : filter β) (u : β → α) := (map u f).is_bounded r variables {r : α → α → Prop} {f g : filter α} /-- `f` is eventually bounded if and only if, there exists an admissible set on which it is bounded. -/ lemma is_bounded_iff : f.is_bounded r ↔ (∃s∈f.sets, ∃b, s ⊆ {x | r x b}) := iff.intro (assume ⟨b, hb⟩, ⟨{a | r a b}, hb, b, subset.refl _⟩) (assume ⟨s, hs, b, hb⟩, ⟨b, mem_of_superset hs hb⟩) /-- A bounded function `u` is in particular eventually bounded. -/ lemma is_bounded_under_of {f : filter β} {u : β → α} : (∃b, ∀x, r (u x) b) → f.is_bounded_under r u | ⟨b, hb⟩ := ⟨b, show ∀ᶠ x in f, r (u x) b, from eventually_of_forall hb⟩ lemma is_bounded_bot : is_bounded r ⊥ ↔ nonempty α := by simp [is_bounded, exists_true_iff_nonempty] lemma is_bounded_top : is_bounded r ⊤ ↔ (∃t, ∀x, r x t) := by simp [is_bounded, eq_univ_iff_forall] lemma is_bounded_principal (s : set α) : is_bounded r (𝓟 s) ↔ (∃t, ∀x∈s, r x t) := by simp [is_bounded, subset_def] lemma is_bounded_sup [is_trans α r] (hr : ∀b₁ b₂, ∃b, r b₁ b ∧ r b₂ b) : is_bounded r f → is_bounded r g → is_bounded r (f ⊔ g) | ⟨b₁, h₁⟩ ⟨b₂, h₂⟩ := let ⟨b, rb₁b, rb₂b⟩ := hr b₁ b₂ in ⟨b, eventually_sup.mpr ⟨h₁.mono (λ x h, trans h rb₁b), h₂.mono (λ x h, trans h rb₂b)⟩⟩ lemma is_bounded.mono (h : f ≤ g) : is_bounded r g → is_bounded r f | ⟨b, hb⟩ := ⟨b, h hb⟩ lemma is_bounded_under.mono {f g : filter β} {u : β → α} (h : f ≤ g) : g.is_bounded_under r u → f.is_bounded_under r u := λ hg, hg.mono (map_mono h) lemma is_bounded_under.mono_le [preorder β] {l : filter α} {u v : α → β} (hu : is_bounded_under (≤) l u) (hv : v ≤ᶠ[l] u) : is_bounded_under (≤) l v := hu.imp $ λ b hb, (eventually_map.1 hb).mp $ hv.mono $ λ x, le_trans lemma is_bounded_under.mono_ge [preorder β] {l : filter α} {u v : α → β} (hu : is_bounded_under (≥) l u) (hv : u ≤ᶠ[l] v) : is_bounded_under (≥) l v := @is_bounded_under.mono_le α βᵒᵈ _ _ _ _ hu hv lemma is_bounded_under_const [is_refl α r] {l : filter β} {a : α} : is_bounded_under r l (λ _, a) := ⟨a, eventually_map.2 $ eventually_of_forall $ λ _, refl _⟩ lemma is_bounded.is_bounded_under {q : β → β → Prop} {u : α → β} (hf : ∀a₀ a₁, r a₀ a₁ → q (u a₀) (u a₁)) : f.is_bounded r → f.is_bounded_under q u | ⟨b, h⟩ := ⟨u b, show ∀ᶠ x in f, q (u x) (u b), from h.mono (λ x, hf x b)⟩ lemma not_is_bounded_under_of_tendsto_at_top [preorder β] [no_max_order β] {f : α → β} {l : filter α} [l.ne_bot] (hf : tendsto f l at_top) : ¬ is_bounded_under (≤) l f := begin rintro ⟨b, hb⟩, rw eventually_map at hb, obtain ⟨b', h⟩ := exists_gt b, have hb' := (tendsto_at_top.mp hf) b', have : {x : α | f x ≤ b} ∩ {x : α | b' ≤ f x} = ∅ := eq_empty_of_subset_empty (λ x hx, (not_le_of_lt h) (le_trans hx.2 hx.1)), exact (nonempty_of_mem (hb.and hb')).ne_empty this end lemma not_is_bounded_under_of_tendsto_at_bot [preorder β] [no_min_order β] {f : α → β} {l : filter α} [l.ne_bot](hf : tendsto f l at_bot) : ¬ is_bounded_under (≥) l f := @not_is_bounded_under_of_tendsto_at_top α βᵒᵈ _ _ _ _ _ hf lemma is_bounded_under.bdd_above_range_of_cofinite [semilattice_sup β] {f : α → β} (hf : is_bounded_under (≤) cofinite f) : bdd_above (range f) := begin rcases hf with ⟨b, hb⟩, haveI : nonempty β := ⟨b⟩, rw [← image_univ, ← union_compl_self {x | f x ≤ b}, image_union, bdd_above_union], exact ⟨⟨b, ball_image_iff.2 $ λ x, id⟩, (hb.image f).bdd_above⟩ end lemma is_bounded_under.bdd_below_range_of_cofinite [semilattice_inf β] {f : α → β} (hf : is_bounded_under (≥) cofinite f) : bdd_below (range f) := @is_bounded_under.bdd_above_range_of_cofinite α βᵒᵈ _ _ hf lemma is_bounded_under.bdd_above_range [semilattice_sup β] {f : ℕ → β} (hf : is_bounded_under (≤) at_top f) : bdd_above (range f) := by { rw ← nat.cofinite_eq_at_top at hf, exact hf.bdd_above_range_of_cofinite } lemma is_bounded_under.bdd_below_range [semilattice_inf β] {f : ℕ → β} (hf : is_bounded_under (≥) at_top f) : bdd_below (range f) := @is_bounded_under.bdd_above_range βᵒᵈ _ _ hf /-- `is_cobounded (≺) f` states that the filter `f` does not tend to infinity w.r.t. `≺`. This is also called frequently bounded. Will be usually instantiated with `≤` or `≥`. There is a subtlety in this definition: we want `f.is_cobounded` to hold for any `f` in the case of complete lattices. This will be relevant to deduce theorems on complete lattices from their versions on conditionally complete lattices with additional assumptions. We have to be careful in the edge case of the trivial filter containing the empty set: the other natural definition `¬ ∀ a, ∀ᶠ n in f, a ≤ n` would not work as well in this case. -/ def is_cobounded (r : α → α → Prop) (f : filter α) := ∃b, ∀a, (∀ᶠ x in f, r x a) → r b a /-- `is_cobounded_under (≺) f u` states that the image of the filter `f` under the map `u` does not tend to infinity w.r.t. `≺`. This is also called frequently bounded. Will be usually instantiated with `≤` or `≥`. -/ def is_cobounded_under (r : α → α → Prop) (f : filter β) (u : β → α) := (map u f).is_cobounded r /-- To check that a filter is frequently bounded, it suffices to have a witness which bounds `f` at some point for every admissible set. This is only an implication, as the other direction is wrong for the trivial filter.-/ lemma is_cobounded.mk [is_trans α r] (a : α) (h : ∀s∈f, ∃x∈s, r a x) : f.is_cobounded r := ⟨a, assume y s, let ⟨x, h₁, h₂⟩ := h _ s in trans h₂ h₁⟩ /-- A filter which is eventually bounded is in particular frequently bounded (in the opposite direction). At least if the filter is not trivial. -/ lemma is_bounded.is_cobounded_flip [is_trans α r] [ne_bot f] : f.is_bounded r → f.is_cobounded (flip r) | ⟨a, ha⟩ := ⟨a, assume b hb, let ⟨x, rxa, rbx⟩ := (ha.and hb).exists in show r b a, from trans rbx rxa⟩ lemma is_bounded.is_cobounded_ge [preorder α] [ne_bot f] (h : f.is_bounded (≤)) : f.is_cobounded (≥) := h.is_cobounded_flip lemma is_bounded.is_cobounded_le [preorder α] [ne_bot f] (h : f.is_bounded (≥)) : f.is_cobounded (≤) := h.is_cobounded_flip lemma is_cobounded_bot : is_cobounded r ⊥ ↔ (∃b, ∀x, r b x) := by simp [is_cobounded] lemma is_cobounded_top : is_cobounded r ⊤ ↔ nonempty α := by simp [is_cobounded, eq_univ_iff_forall, exists_true_iff_nonempty] {contextual := tt} lemma is_cobounded_principal (s : set α) : (𝓟 s).is_cobounded r ↔ (∃b, ∀a, (∀x∈s, r x a) → r b a) := by simp [is_cobounded, subset_def] lemma is_cobounded.mono (h : f ≤ g) : f.is_cobounded r → g.is_cobounded r | ⟨b, hb⟩ := ⟨b, assume a ha, hb a (h ha)⟩ end relation lemma is_cobounded_le_of_bot [preorder α] [order_bot α] {f : filter α} : f.is_cobounded (≤) := ⟨⊥, assume a h, bot_le⟩ lemma is_cobounded_ge_of_top [preorder α] [order_top α] {f : filter α} : f.is_cobounded (≥) := ⟨⊤, assume a h, le_top⟩ lemma is_bounded_le_of_top [preorder α] [order_top α] {f : filter α} : f.is_bounded (≤) := ⟨⊤, eventually_of_forall $ λ _, le_top⟩ lemma is_bounded_ge_of_bot [preorder α] [order_bot α] {f : filter α} : f.is_bounded (≥) := ⟨⊥, eventually_of_forall $ λ _, bot_le⟩ @[simp] lemma _root_.order_iso.is_bounded_under_le_comp [preorder α] [preorder β] (e : α ≃o β) {l : filter γ} {u : γ → α} : is_bounded_under (≤) l (λ x, e (u x)) ↔ is_bounded_under (≤) l u := e.surjective.exists.trans $ exists_congr $ λ a, by simp only [eventually_map, e.le_iff_le] @[simp] lemma _root_.order_iso.is_bounded_under_ge_comp [preorder α] [preorder β] (e : α ≃o β) {l : filter γ} {u : γ → α} : is_bounded_under (≥) l (λ x, e (u x)) ↔ is_bounded_under (≥) l u := e.dual.is_bounded_under_le_comp @[simp, to_additive] lemma is_bounded_under_le_inv [ordered_comm_group α] {l : filter β} {u : β → α} : is_bounded_under (≤) l (λ x, (u x)⁻¹) ↔ is_bounded_under (≥) l u := (order_iso.inv α).is_bounded_under_ge_comp @[simp, to_additive] lemma is_bounded_under_ge_inv [ordered_comm_group α] {l : filter β} {u : β → α} : is_bounded_under (≥) l (λ x, (u x)⁻¹) ↔ is_bounded_under (≤) l u := (order_iso.inv α).is_bounded_under_le_comp lemma is_bounded_under.sup [semilattice_sup α] {f : filter β} {u v : β → α} : f.is_bounded_under (≤) u → f.is_bounded_under (≤) v → f.is_bounded_under (≤) (λa, u a ⊔ v a) | ⟨bu, (hu : ∀ᶠ x in f, u x ≤ bu)⟩ ⟨bv, (hv : ∀ᶠ x in f, v x ≤ bv)⟩ := ⟨bu ⊔ bv, show ∀ᶠ x in f, u x ⊔ v x ≤ bu ⊔ bv, by filter_upwards [hu, hv] with _ using sup_le_sup⟩ @[simp] lemma is_bounded_under_le_sup [semilattice_sup α] {f : filter β} {u v : β → α} : f.is_bounded_under (≤) (λ a, u a ⊔ v a) ↔ f.is_bounded_under (≤) u ∧ f.is_bounded_under (≤) v := ⟨λ h, ⟨h.mono_le $ eventually_of_forall $ λ _, le_sup_left, h.mono_le $ eventually_of_forall $ λ _, le_sup_right⟩, λ h, h.1.sup h.2⟩ lemma is_bounded_under.inf [semilattice_inf α] {f : filter β} {u v : β → α} : f.is_bounded_under (≥) u → f.is_bounded_under (≥) v → f.is_bounded_under (≥) (λa, u a ⊓ v a) := @is_bounded_under.sup αᵒᵈ β _ _ _ _ @[simp] lemma is_bounded_under_ge_inf [semilattice_inf α] {f : filter β} {u v : β → α} : f.is_bounded_under (≥) (λ a, u a ⊓ v a) ↔ f.is_bounded_under (≥) u ∧ f.is_bounded_under (≥) v := @is_bounded_under_le_sup αᵒᵈ _ _ _ _ _ lemma is_bounded_under_le_abs [linear_ordered_add_comm_group α] {f : filter β} {u : β → α} : f.is_bounded_under (≤) (λ a, |u a|) ↔ f.is_bounded_under (≤) u ∧ f.is_bounded_under (≥) u := is_bounded_under_le_sup.trans $ and_congr iff.rfl is_bounded_under_le_neg /-- Filters are automatically bounded or cobounded in complete lattices. To use the same statements in complete and conditionally complete lattices but let automation fill automatically the boundedness proofs in complete lattices, we use the tactic `is_bounded_default` in the statements, in the form `(hf : f.is_bounded (≥) . is_bounded_default)`. -/ meta def is_bounded_default : tactic unit := tactic.applyc ``is_cobounded_le_of_bot <|> tactic.applyc ``is_cobounded_ge_of_top <|> tactic.applyc ``is_bounded_le_of_top <|> tactic.applyc ``is_bounded_ge_of_bot section conditionally_complete_lattice variables [conditionally_complete_lattice α] /-- The `Limsup` of a filter `f` is the infimum of the `a` such that, eventually for `f`, holds `x ≤ a`. -/ def Limsup (f : filter α) : α := Inf { a | ∀ᶠ n in f, n ≤ a } /-- The `Liminf` of a filter `f` is the supremum of the `a` such that, eventually for `f`, holds `x ≥ a`. -/ def Liminf (f : filter α) : α := Sup { a | ∀ᶠ n in f, a ≤ n } /-- The `limsup` of a function `u` along a filter `f` is the infimum of the `a` such that, eventually for `f`, holds `u x ≤ a`. -/ def limsup (u : β → α) (f : filter β) : α := Limsup (map u f) /-- The `liminf` of a function `u` along a filter `f` is the supremum of the `a` such that, eventually for `f`, holds `u x ≥ a`. -/ def liminf (u : β → α) (f : filter β) : α := Liminf (map u f) /-- The `blimsup` of a function `u` along a filter `f`, bounded by a predicate `p`, is the infimum of the `a` such that, eventually for `f`, `u x ≤ a` whenever `p x` holds. -/ def blimsup (u : β → α) (f : filter β) (p : β → Prop) := Inf { a | ∀ᶠ x in f, p x → u x ≤ a } /-- The `bliminf` of a function `u` along a filter `f`, bounded by a predicate `p`, is the supremum of the `a` such that, eventually for `f`, `a ≤ u x` whenever `p x` holds. -/ def bliminf (u : β → α) (f : filter β) (p : β → Prop) := Sup { a | ∀ᶠ x in f, p x → a ≤ u x } section variables {f : filter β} {u : β → α} {p : β → Prop} theorem limsup_eq : limsup u f = Inf { a | ∀ᶠ n in f, u n ≤ a } := rfl theorem liminf_eq : liminf u f = Sup { a | ∀ᶠ n in f, a ≤ u n } := rfl theorem blimsup_eq : blimsup u f p = Inf { a | ∀ᶠ x in f, p x → u x ≤ a } := rfl theorem bliminf_eq : bliminf u f p = Sup { a | ∀ᶠ x in f, p x → a ≤ u x } := rfl end @[simp] lemma blimsup_true (f : filter β) (u : β → α) : blimsup u f (λ x, true) = limsup u f := by simp [blimsup_eq, limsup_eq] @[simp] lemma bliminf_true (f : filter β) (u : β → α) : bliminf u f (λ x, true) = liminf u f := by simp [bliminf_eq, liminf_eq] lemma blimsup_eq_limsup_subtype {f : filter β} {u : β → α} {p : β → Prop} : blimsup u f p = limsup (u ∘ (coe : {x | p x} → β)) (comap coe f) := begin simp only [blimsup_eq, limsup_eq, function.comp_app, eventually_comap, set_coe.forall, subtype.coe_mk, mem_set_of_eq], congr, ext a, exact eventually_congr (eventually_of_forall (λ x, ⟨λ hx y hy hxy, hxy.symm ▸ (hx (hxy ▸ hy)), λ hx hx', hx x hx' rfl⟩)), end lemma bliminf_eq_liminf_subtype {f : filter β} {u : β → α} {p : β → Prop} : bliminf u f p = liminf (u ∘ (coe : {x | p x} → β)) (comap coe f) := @blimsup_eq_limsup_subtype αᵒᵈ β _ f u p theorem Limsup_le_of_le {f : filter α} {a} (hf : f.is_cobounded (≤) . is_bounded_default) (h : ∀ᶠ n in f, n ≤ a) : Limsup f ≤ a := cInf_le hf h theorem le_Liminf_of_le {f : filter α} {a} (hf : f.is_cobounded (≥) . is_bounded_default) (h : ∀ᶠ n in f, a ≤ n) : a ≤ Liminf f := le_cSup hf h theorem limsup_le_of_le {f : filter β} {u : β → α} {a} (hf : f.is_cobounded_under (≤) u . is_bounded_default) (h : ∀ᶠ n in f, u n ≤ a) : limsup u f ≤ a := cInf_le hf h theorem le_liminf_of_le {f : filter β} {u : β → α} {a} (hf : f.is_cobounded_under (≥) u . is_bounded_default) (h : ∀ᶠ n in f, a ≤ u n) : a ≤ liminf u f := le_cSup hf h theorem le_Limsup_of_le {f : filter α} {a} (hf : f.is_bounded (≤) . is_bounded_default) (h : ∀ b, (∀ᶠ n in f, n ≤ b) → a ≤ b) : a ≤ Limsup f := le_cInf hf h theorem Liminf_le_of_le {f : filter α} {a} (hf : f.is_bounded (≥) . is_bounded_default) (h : ∀ b, (∀ᶠ n in f, b ≤ n) → b ≤ a) : Liminf f ≤ a := cSup_le hf h theorem le_limsup_of_le {f : filter β} {u : β → α} {a} (hf : f.is_bounded_under (≤) u . is_bounded_default) (h : ∀ b, (∀ᶠ n in f, u n ≤ b) → a ≤ b) : a ≤ limsup u f := le_cInf hf h theorem liminf_le_of_le {f : filter β} {u : β → α} {a} (hf : f.is_bounded_under (≥) u . is_bounded_default) (h : ∀ b, (∀ᶠ n in f, b ≤ u n) → b ≤ a) : liminf u f ≤ a := cSup_le hf h theorem Liminf_le_Limsup {f : filter α} [ne_bot f] (h₁ : f.is_bounded (≤) . is_bounded_default) (h₂ : f.is_bounded (≥) . is_bounded_default) : Liminf f ≤ Limsup f := Liminf_le_of_le h₂ $ assume a₀ ha₀, le_Limsup_of_le h₁ $ assume a₁ ha₁, show a₀ ≤ a₁, from let ⟨b, hb₀, hb₁⟩ := (ha₀.and ha₁).exists in le_trans hb₀ hb₁ lemma liminf_le_limsup {f : filter β} [ne_bot f] {u : β → α} (h : f.is_bounded_under (≤) u . is_bounded_default) (h' : f.is_bounded_under (≥) u . is_bounded_default) : liminf u f ≤ limsup u f := Liminf_le_Limsup h h' lemma Limsup_le_Limsup {f g : filter α} (hf : f.is_cobounded (≤) . is_bounded_default) (hg : g.is_bounded (≤) . is_bounded_default) (h : ∀ a, (∀ᶠ n in g, n ≤ a) → ∀ᶠ n in f, n ≤ a) : Limsup f ≤ Limsup g := cInf_le_cInf hf hg h lemma Liminf_le_Liminf {f g : filter α} (hf : f.is_bounded (≥) . is_bounded_default) (hg : g.is_cobounded (≥) . is_bounded_default) (h : ∀ a, (∀ᶠ n in f, a ≤ n) → ∀ᶠ n in g, a ≤ n) : Liminf f ≤ Liminf g := cSup_le_cSup hg hf h lemma limsup_le_limsup {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β} (h : u ≤ᶠ[f] v) (hu : f.is_cobounded_under (≤) u . is_bounded_default) (hv : f.is_bounded_under (≤) v . is_bounded_default) : limsup u f ≤ limsup v f := Limsup_le_Limsup hu hv $ assume b, h.trans lemma liminf_le_liminf {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β} (h : ∀ᶠ a in f, u a ≤ v a) (hu : f.is_bounded_under (≥) u . is_bounded_default) (hv : f.is_cobounded_under (≥) v . is_bounded_default) : liminf u f ≤ liminf v f := @limsup_le_limsup βᵒᵈ α _ _ _ _ h hv hu lemma Limsup_le_Limsup_of_le {f g : filter α} (h : f ≤ g) (hf : f.is_cobounded (≤) . is_bounded_default) (hg : g.is_bounded (≤) . is_bounded_default) : Limsup f ≤ Limsup g := Limsup_le_Limsup hf hg (assume a ha, h ha) lemma Liminf_le_Liminf_of_le {f g : filter α} (h : g ≤ f) (hf : f.is_bounded (≥) . is_bounded_default) (hg : g.is_cobounded (≥) . is_bounded_default) : Liminf f ≤ Liminf g := Liminf_le_Liminf hf hg (assume a ha, h ha) lemma limsup_le_limsup_of_le {α β} [conditionally_complete_lattice β] {f g : filter α} (h : f ≤ g) {u : α → β} (hf : f.is_cobounded_under (≤) u . is_bounded_default) (hg : g.is_bounded_under (≤) u . is_bounded_default) : limsup u f ≤ limsup u g := Limsup_le_Limsup_of_le (map_mono h) hf hg lemma liminf_le_liminf_of_le {α β} [conditionally_complete_lattice β] {f g : filter α} (h : g ≤ f) {u : α → β} (hf : f.is_bounded_under (≥) u . is_bounded_default) (hg : g.is_cobounded_under (≥) u . is_bounded_default) : liminf u f ≤ liminf u g := Liminf_le_Liminf_of_le (map_mono h) hf hg theorem Limsup_principal {s : set α} (h : bdd_above s) (hs : s.nonempty) : Limsup (𝓟 s) = Sup s := by simp [Limsup]; exact cInf_upper_bounds_eq_cSup h hs theorem Liminf_principal {s : set α} (h : bdd_below s) (hs : s.nonempty) : Liminf (𝓟 s) = Inf s := @Limsup_principal αᵒᵈ _ s h hs lemma limsup_congr {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β} (h : ∀ᶠ a in f, u a = v a) : limsup u f = limsup v f := begin rw limsup_eq, congr' with b, exact eventually_congr (h.mono $ λ x hx, by simp [hx]) end lemma liminf_congr {α : Type*} [conditionally_complete_lattice β] {f : filter α} {u v : α → β} (h : ∀ᶠ a in f, u a = v a) : liminf u f = liminf v f := @limsup_congr βᵒᵈ _ _ _ _ _ h lemma limsup_const {α : Type*} [conditionally_complete_lattice β] {f : filter α} [ne_bot f] (b : β) : limsup (λ x, b) f = b := by simpa only [limsup_eq, eventually_const] using cInf_Ici lemma liminf_const {α : Type*} [conditionally_complete_lattice β] {f : filter α} [ne_bot f] (b : β) : liminf (λ x, b) f = b := @limsup_const βᵒᵈ α _ f _ b end conditionally_complete_lattice section complete_lattice variables [complete_lattice α] @[simp] theorem Limsup_bot : Limsup (⊥ : filter α) = ⊥ := bot_unique $ Inf_le $ by simp @[simp] theorem Liminf_bot : Liminf (⊥ : filter α) = ⊤ := top_unique $ le_Sup $ by simp @[simp] theorem Limsup_top : Limsup (⊤ : filter α) = ⊤ := top_unique $ le_Inf $ by simp [eq_univ_iff_forall]; exact assume b hb, (top_unique $ hb _) @[simp] theorem Liminf_top : Liminf (⊤ : filter α) = ⊥ := bot_unique $ Sup_le $ by simp [eq_univ_iff_forall]; exact assume b hb, (bot_unique $ hb _) @[simp] lemma blimsup_false {f : filter β} {u : β → α} : blimsup u f (λ x, false) = ⊥ := by simp [blimsup_eq] @[simp] lemma bliminf_false {f : filter β} {u : β → α} : bliminf u f (λ x, false) = ⊤ := by simp [bliminf_eq] /-- Same as limsup_const applied to `⊥` but without the `ne_bot f` assumption -/ lemma limsup_const_bot {f : filter β} : limsup (λ x : β, (⊥ : α)) f = (⊥ : α) := begin rw [limsup_eq, eq_bot_iff], exact Inf_le (eventually_of_forall (λ x, le_rfl)), end /-- Same as limsup_const applied to `⊤` but without the `ne_bot f` assumption -/ lemma liminf_const_top {f : filter β} : liminf (λ x : β, (⊤ : α)) f = (⊤ : α) := @limsup_const_bot αᵒᵈ β _ _ theorem has_basis.Limsup_eq_infi_Sup {ι} {p : ι → Prop} {s} {f : filter α} (h : f.has_basis p s) : Limsup f = ⨅ i (hi : p i), Sup (s i) := le_antisymm (le_infi₂ $ λ i hi, Inf_le $ h.eventually_iff.2 ⟨i, hi, λ x, le_Sup⟩) (le_Inf $ assume a ha, let ⟨i, hi, ha⟩ := h.eventually_iff.1 ha in infi₂_le_of_le _ hi $ Sup_le ha) theorem has_basis.Liminf_eq_supr_Inf {p : ι → Prop} {s : ι → set α} {f : filter α} (h : f.has_basis p s) : Liminf f = ⨆ i (hi : p i), Inf (s i) := @has_basis.Limsup_eq_infi_Sup αᵒᵈ _ _ _ _ _ h theorem Limsup_eq_infi_Sup {f : filter α} : Limsup f = ⨅ s ∈ f, Sup s := f.basis_sets.Limsup_eq_infi_Sup theorem Liminf_eq_supr_Inf {f : filter α} : Liminf f = ⨆ s ∈ f, Inf s := @Limsup_eq_infi_Sup αᵒᵈ _ _ theorem limsup_le_supr {f : filter β} {u : β → α} : limsup u f ≤ ⨆ n, u n := limsup_le_of_le (by is_bounded_default) (eventually_of_forall (le_supr u)) theorem infi_le_liminf {f : filter β} {u : β → α} : (⨅ n, u n) ≤ liminf u f := le_liminf_of_le (by is_bounded_default) (eventually_of_forall (infi_le u)) /-- In a complete lattice, the limsup of a function is the infimum over sets `s` in the filter of the supremum of the function over `s` -/ theorem limsup_eq_infi_supr {f : filter β} {u : β → α} : limsup u f = ⨅ s ∈ f, ⨆ a ∈ s, u a := (f.basis_sets.map u).Limsup_eq_infi_Sup.trans $ by simp only [Sup_image, id] lemma limsup_eq_infi_supr_of_nat {u : ℕ → α} : limsup u at_top = ⨅ n : ℕ, ⨆ i ≥ n, u i := (at_top_basis.map u).Limsup_eq_infi_Sup.trans $ by simp only [Sup_image, infi_const]; refl lemma limsup_eq_infi_supr_of_nat' {u : ℕ → α} : limsup u at_top = ⨅ n : ℕ, ⨆ i : ℕ, u (i + n) := by simp only [limsup_eq_infi_supr_of_nat, supr_ge_eq_supr_nat_add] theorem has_basis.limsup_eq_infi_supr {p : ι → Prop} {s : ι → set β} {f : filter β} {u : β → α} (h : f.has_basis p s) : limsup u f = ⨅ i (hi : p i), ⨆ a ∈ s i, u a := (h.map u).Limsup_eq_infi_Sup.trans $ by simp only [Sup_image, id] lemma blimsup_eq_infi_bsupr {f : filter β} {p : β → Prop} {u : β → α} : blimsup u f p = ⨅ s ∈ f, ⨆ b (hb : p b ∧ b ∈ s), u b := begin refine le_antisymm (Inf_le_Inf _) (infi_le_iff.mpr $ λ a ha, le_Inf_iff.mpr $ λ a' ha', _), { rintros - ⟨s, rfl⟩, simp only [mem_set_of_eq, le_infi_iff], conv { congr, funext, rw imp.swap, }, refine eventually_imp_distrib_left.mpr (λ h, eventually_iff_exists_mem.2 ⟨s, h, λ x h₁ h₂, _⟩), exact @le_supr₂ α β (λ b, p b ∧ b ∈ s) _ (λ b hb, u b) x ⟨h₂, h₁⟩, }, { obtain ⟨s, hs, hs'⟩ := eventually_iff_exists_mem.mp ha', simp_rw imp.swap at hs', exact (le_infi_iff.mp (ha s) hs).trans (by simpa only [supr₂_le_iff, and_imp]), }, end /-- In a complete lattice, the liminf of a function is the infimum over sets `s` in the filter of the supremum of the function over `s` -/ theorem liminf_eq_supr_infi {f : filter β} {u : β → α} : liminf u f = ⨆ s ∈ f, ⨅ a ∈ s, u a := @limsup_eq_infi_supr αᵒᵈ β _ _ _ lemma liminf_eq_supr_infi_of_nat {u : ℕ → α} : liminf u at_top = ⨆ n : ℕ, ⨅ i ≥ n, u i := @limsup_eq_infi_supr_of_nat αᵒᵈ _ u lemma liminf_eq_supr_infi_of_nat' {u : ℕ → α} : liminf u at_top = ⨆ n : ℕ, ⨅ i : ℕ, u (i + n) := @limsup_eq_infi_supr_of_nat' αᵒᵈ _ _ theorem has_basis.liminf_eq_supr_infi {p : ι → Prop} {s : ι → set β} {f : filter β} {u : β → α} (h : f.has_basis p s) : liminf u f = ⨆ i (hi : p i), ⨅ a ∈ s i, u a := @has_basis.limsup_eq_infi_supr αᵒᵈ _ _ _ _ _ _ _ h lemma bliminf_eq_supr_binfi {f : filter β} {p : β → Prop} {u : β → α} : bliminf u f p = ⨆ s ∈ f, ⨅ b (hb : p b ∧ b ∈ s), u b := @blimsup_eq_infi_bsupr αᵒᵈ β _ f p u lemma limsup_eq_Inf_Sup {ι R : Type*} (F : filter ι) [complete_lattice R] (a : ι → R) : limsup a F = Inf ((λ I, Sup (a '' I)) '' F.sets) := begin refine le_antisymm _ _, { rw limsup_eq, refine Inf_le_Inf (λ x hx, _), rcases (mem_image _ F.sets x).mp hx with ⟨I, ⟨I_mem_F, hI⟩⟩, filter_upwards [I_mem_F] with i hi, exact hI ▸ le_Sup (mem_image_of_mem _ hi), }, { refine le_Inf_iff.mpr (λ b hb, Inf_le_of_le (mem_image_of_mem _ $ filter.mem_sets.mpr hb) $ Sup_le _), rintros _ ⟨_, h, rfl⟩, exact h, }, end lemma liminf_eq_Sup_Inf {ι R : Type*} (F : filter ι) [complete_lattice R] (a : ι → R) : liminf a F = Sup ((λ I, Inf (a '' I)) '' F.sets) := @filter.limsup_eq_Inf_Sup ι (order_dual R) _ _ a @[simp] lemma liminf_nat_add (f : ℕ → α) (k : ℕ) : liminf (λ i, f (i + k)) at_top = liminf f at_top := by { simp_rw liminf_eq_supr_infi_of_nat, exact supr_infi_ge_nat_add f k } @[simp] lemma limsup_nat_add (f : ℕ → α) (k : ℕ) : limsup (λ i, f (i + k)) at_top = limsup f at_top := @liminf_nat_add αᵒᵈ _ f k lemma liminf_le_of_frequently_le' {α β} [complete_lattice β] {f : filter α} {u : α → β} {x : β} (h : ∃ᶠ a in f, u a ≤ x) : liminf u f ≤ x := begin rw liminf_eq, refine Sup_le (λ b hb, _), have hbx : ∃ᶠ a in f, b ≤ x, { revert h, rw [←not_imp_not, not_frequently, not_frequently], exact λ h, hb.mp (h.mono (λ a hbx hba hax, hbx (hba.trans hax))), }, exact hbx.exists.some_spec, end lemma le_limsup_of_frequently_le' {α β} [complete_lattice β] {f : filter α} {u : α → β} {x : β} (h : ∃ᶠ a in f, x ≤ u a) : x ≤ limsup u f := @liminf_le_of_frequently_le' _ βᵒᵈ _ _ _ _ h /-- If `f : α → α` is a morphism of complete lattices, then the limsup of its iterates of any `a : α` is a fixed point. -/ @[simp] lemma complete_lattice_hom.apply_limsup_iterate (f : complete_lattice_hom α α) (a : α) : f (limsup (λ n, f^[n] a) at_top) = limsup (λ n, f^[n] a) at_top := begin rw [limsup_eq_infi_supr_of_nat', map_infi], simp_rw [_root_.map_supr, ← function.comp_apply f, ← function.iterate_succ' f, ← nat.add_succ], conv_rhs { rw infi_split _ ((<) (0 : ℕ)), }, simp only [not_lt, le_zero_iff, infi_infi_eq_left, add_zero, infi_nat_gt_zero_eq, left_eq_inf], refine (infi_le (λ i, ⨆ j, (f^[j + (i + 1)]) a) 0).trans _, simp only [zero_add, function.comp_app, supr_le_iff], exact λ i, le_supr (λ i, (f^[i] a)) (i + 1), end /-- If `f : α → α` is a morphism of complete lattices, then the liminf of its iterates of any `a : α` is a fixed point. -/ lemma complete_lattice_hom.apply_liminf_iterate (f : complete_lattice_hom α α) (a : α) : f (liminf (λ n, f^[n] a) at_top) = liminf (λ n, f^[n] a) at_top := (complete_lattice_hom.dual f).apply_limsup_iterate _ variables {f g : filter β} {p q : β → Prop} {u v : β → α} lemma blimsup_mono (h : ∀ x, p x → q x) : blimsup u f p ≤ blimsup u f q := Inf_le_Inf $ λ a ha, ha.mono $ by tauto lemma bliminf_antitone (h : ∀ x, p x → q x) : bliminf u f q ≤ bliminf u f p := Sup_le_Sup $ λ a ha, ha.mono $ by tauto lemma mono_blimsup' (h : ∀ᶠ x in f, u x ≤ v x) : blimsup u f p ≤ blimsup v f p := Inf_le_Inf $ λ a ha, (ha.and h).mono $ λ x hx hx', hx.2.trans (hx.1 hx') lemma mono_blimsup (h : ∀ x, u x ≤ v x) : blimsup u f p ≤ blimsup v f p := mono_blimsup' $ eventually_of_forall h lemma mono_bliminf' (h : ∀ᶠ x in f, u x ≤ v x) : bliminf u f p ≤ bliminf v f p := Sup_le_Sup $ λ a ha, (ha.and h).mono $ λ x hx hx', (hx.1 hx').trans hx.2 lemma mono_bliminf (h : ∀ x, u x ≤ v x) : bliminf u f p ≤ bliminf v f p := mono_bliminf' $ eventually_of_forall h lemma bliminf_antitone_filter (h : f ≤ g) : bliminf u g p ≤ bliminf u f p := Sup_le_Sup $ λ a ha, ha.filter_mono h lemma blimsup_monotone_filter (h : f ≤ g) : blimsup u f p ≤ blimsup u g p := Inf_le_Inf $ λ a ha, ha.filter_mono h @[simp] lemma blimsup_and_le_inf : blimsup u f (λ x, p x ∧ q x) ≤ blimsup u f p ⊓ blimsup u f q := le_inf (blimsup_mono $ by tauto) (blimsup_mono $ by tauto) @[simp] lemma bliminf_sup_le_and : bliminf u f p ⊔ bliminf u f q ≤ bliminf u f (λ x, p x ∧ q x) := @blimsup_and_le_inf αᵒᵈ β _ f p q u /-- See also `filter.blimsup_or_eq_sup`. -/ @[simp] lemma blimsup_sup_le_or : blimsup u f p ⊔ blimsup u f q ≤ blimsup u f (λ x, p x ∨ q x) := sup_le (blimsup_mono $ by tauto) (blimsup_mono $ by tauto) /-- See also `filter.bliminf_or_eq_inf`. -/ @[simp] lemma bliminf_or_le_inf : bliminf u f (λ x, p x ∨ q x) ≤ bliminf u f p ⊓ bliminf u f q := @blimsup_sup_le_or αᵒᵈ β _ f p q u end complete_lattice section complete_distrib_lattice variables [complete_distrib_lattice α] {f : filter β} {p q : β → Prop} {u : β → α} @[simp] lemma blimsup_or_eq_sup : blimsup u f (λ x, p x ∨ q x) = blimsup u f p ⊔ blimsup u f q := begin refine le_antisymm _ blimsup_sup_le_or, simp only [blimsup_eq, Inf_sup_eq, sup_Inf_eq, le_infi₂_iff, mem_set_of_eq], refine λ a' ha' a ha, Inf_le ((ha.and ha').mono $ λ b h hb, _), exact or.elim hb (λ hb, le_sup_of_le_left $ h.1 hb) (λ hb, le_sup_of_le_right $ h.2 hb), end @[simp] lemma bliminf_or_eq_inf : bliminf u f (λ x, p x ∨ q x) = bliminf u f p ⊓ bliminf u f q := @blimsup_or_eq_sup αᵒᵈ β _ f p q u lemma sup_limsup [ne_bot f] (a : α) : a ⊔ limsup u f = limsup (λ x, a ⊔ u x) f := begin simp only [limsup_eq_infi_supr, supr_sup_eq, sup_binfi_eq], congr, ext s, congr, ext hs, congr, exact (bsupr_const (nonempty_of_mem hs)).symm, end lemma inf_liminf [ne_bot f] (a : α) : a ⊓ liminf u f = liminf (λ x, a ⊓ u x) f := @sup_limsup αᵒᵈ β _ f _ _ _ lemma sup_liminf (a : α) : a ⊔ liminf u f = liminf (λ x, a ⊔ u x) f := begin simp only [liminf_eq_supr_infi], rw [sup_comm, bsupr_sup (⟨univ, univ_mem⟩ : ∃ (i : set β), i ∈ f)], simp_rw [binfi_sup_eq, @sup_comm _ _ a], end lemma inf_limsup (a : α) : a ⊓ limsup u f = limsup (λ x, a ⊓ u x) f := @sup_liminf αᵒᵈ β _ f _ _ end complete_distrib_lattice section complete_boolean_algebra variables [complete_boolean_algebra α] (f : filter β) (u : β → α) lemma limsup_compl : (limsup u f)ᶜ = liminf (compl ∘ u) f := by simp only [limsup_eq_infi_supr, liminf_eq_supr_infi, compl_infi, compl_supr] lemma liminf_compl : (liminf u f)ᶜ = limsup (compl ∘ u) f := by simp only [limsup_eq_infi_supr, liminf_eq_supr_infi, compl_infi, compl_supr] lemma limsup_sdiff (a : α) : (limsup u f) \ a = limsup (λ b, (u b) \ a) f := begin simp only [limsup_eq_infi_supr, sdiff_eq], rw binfi_inf (⟨univ, univ_mem⟩ : ∃ (i : set β), i ∈ f), simp_rw [inf_comm, inf_bsupr_eq, inf_comm], end lemma liminf_sdiff [ne_bot f] (a : α) : (liminf u f) \ a = liminf (λ b, (u b) \ a) f := by simp only [sdiff_eq, @inf_comm _ _ _ aᶜ, inf_liminf] lemma sdiff_limsup [ne_bot f] (a : α) : a \ limsup u f = liminf (λ b, a \ u b) f := begin rw ← compl_inj_iff, simp only [sdiff_eq, liminf_compl, (∘), compl_inf, compl_compl, sup_limsup], end lemma sdiff_liminf (a : α) : a \ liminf u f = limsup (λ b, a \ u b) f := begin rw ← compl_inj_iff, simp only [sdiff_eq, limsup_compl, (∘), compl_inf, compl_compl, sup_liminf], end end complete_boolean_algebra section set_lattice variables {p : ι → Prop} {s : ι → set α} lemma cofinite.blimsup_set_eq : blimsup s cofinite p = { x | { n | p n ∧ x ∈ s n }.infinite } := begin simp only [blimsup_eq, le_eq_subset, eventually_cofinite, not_forall, Inf_eq_sInter, exists_prop], ext x, refine ⟨λ h, _, λ hx t h, _⟩; contrapose! h, { simp only [mem_sInter, mem_set_of_eq, not_forall, exists_prop], exact ⟨{x}ᶜ, by simpa using h, by simp⟩, }, { exact hx.mono (λ i hi, ⟨hi.1, λ hit, h (hit hi.2)⟩), }, end lemma cofinite.bliminf_set_eq : bliminf s cofinite p = { x | { n | p n ∧ x ∉ s n }.finite } := begin rw ← compl_inj_iff, simpa only [bliminf_eq_supr_binfi, compl_infi, compl_supr, ← blimsup_eq_infi_bsupr, cofinite.blimsup_set_eq], end /-- In other words, `limsup cofinite s` is the set of elements lying inside the family `s` infinitely often. -/ lemma cofinite.limsup_set_eq : limsup s cofinite = { x | { n | x ∈ s n }.infinite } := by simp only [← cofinite.blimsup_true s, cofinite.blimsup_set_eq, true_and] /-- In other words, `liminf cofinite s` is the set of elements lying outside the family `s` finitely often. -/ lemma cofinite.liminf_set_eq : liminf s cofinite = { x | { n | x ∉ s n }.finite } := by simp only [← cofinite.bliminf_true s, cofinite.bliminf_set_eq, true_and] end set_lattice section conditionally_complete_linear_order lemma frequently_lt_of_lt_Limsup {f : filter α} [conditionally_complete_linear_order α] {a : α} (hf : f.is_cobounded (≤) . is_bounded_default) (h : a < Limsup f) : ∃ᶠ n in f, a < n := begin contrapose! h, simp only [not_frequently, not_lt] at h, exact Limsup_le_of_le hf h, end lemma frequently_lt_of_Liminf_lt {f : filter α} [conditionally_complete_linear_order α] {a : α} (hf : f.is_cobounded (≥) . is_bounded_default) (h : Liminf f < a) : ∃ᶠ n in f, n < a := @frequently_lt_of_lt_Limsup (order_dual α) f _ a hf h lemma eventually_lt_of_lt_liminf {f : filter α} [conditionally_complete_linear_order β] {u : α → β} {b : β} (h : b < liminf u f) (hu : f.is_bounded_under (≥) u . is_bounded_default) : ∀ᶠ a in f, b < u a := begin obtain ⟨c, hc, hbc⟩ : ∃ (c : β) (hc : c ∈ {c : β | ∀ᶠ (n : α) in f, c ≤ u n}), b < c := exists_lt_of_lt_cSup hu h, exact hc.mono (λ x hx, lt_of_lt_of_le hbc hx) end lemma eventually_lt_of_limsup_lt {f : filter α} [conditionally_complete_linear_order β] {u : α → β} {b : β} (h : limsup u f < b) (hu : f.is_bounded_under (≤) u . is_bounded_default) : ∀ᶠ a in f, u a < b := @eventually_lt_of_lt_liminf _ βᵒᵈ _ _ _ _ h hu lemma le_limsup_of_frequently_le {α β} [conditionally_complete_linear_order β] {f : filter α} {u : α → β} {b : β} (hu_le : ∃ᶠ x in f, b ≤ u x) (hu : f.is_bounded_under (≤) u . is_bounded_default) : b ≤ limsup u f := begin revert hu_le, rw [←not_imp_not, not_frequently], simp_rw ←lt_iff_not_ge, exact λ h, eventually_lt_of_limsup_lt h hu, end lemma liminf_le_of_frequently_le {α β} [conditionally_complete_linear_order β] {f : filter α} {u : α → β} {b : β} (hu_le : ∃ᶠ x in f, u x ≤ b) (hu : f.is_bounded_under (≥) u . is_bounded_default) : liminf u f ≤ b := @le_limsup_of_frequently_le _ βᵒᵈ _ f u b hu_le hu lemma frequently_lt_of_lt_limsup {α β} [conditionally_complete_linear_order β] {f : filter α} {u : α → β} {b : β} (hu : f.is_cobounded_under (≤) u . is_bounded_default) (h : b < limsup u f) : ∃ᶠ x in f, b < u x := begin contrapose! h, apply Limsup_le_of_le hu, simpa using h, end lemma frequently_lt_of_liminf_lt {α β} [conditionally_complete_linear_order β] {f : filter α} {u : α → β} {b : β} (hu : f.is_cobounded_under (≥) u . is_bounded_default) (h : liminf u f < b) : ∃ᶠ x in f, u x < b := @frequently_lt_of_lt_limsup _ βᵒᵈ _ f u b hu h end conditionally_complete_linear_order end filter section order open filter lemma monotone.is_bounded_under_le_comp [nonempty β] [linear_order β] [preorder γ] [no_max_order γ] {g : β → γ} {f : α → β} {l : filter α} (hg : monotone g) (hg' : tendsto g at_top at_top) : is_bounded_under (≤) l (g ∘ f) ↔ is_bounded_under (≤) l f := begin refine ⟨_, λ h, h.is_bounded_under hg⟩, rintro ⟨c, hc⟩, rw eventually_map at hc, obtain ⟨b, hb⟩ : ∃ b, ∀ a ≥ b, c < g a := eventually_at_top.1 (hg'.eventually_gt_at_top c), exact ⟨b, hc.mono $ λ x hx, not_lt.1 (λ h, (hb _ h.le).not_le hx)⟩ end lemma monotone.is_bounded_under_ge_comp [nonempty β] [linear_order β] [preorder γ] [no_min_order γ] {g : β → γ} {f : α → β} {l : filter α} (hg : monotone g) (hg' : tendsto g at_bot at_bot) : is_bounded_under (≥) l (g ∘ f) ↔ is_bounded_under (≥) l f := hg.dual.is_bounded_under_le_comp hg' lemma antitone.is_bounded_under_le_comp [nonempty β] [linear_order β] [preorder γ] [no_max_order γ] {g : β → γ} {f : α → β} {l : filter α} (hg : antitone g) (hg' : tendsto g at_bot at_top) : is_bounded_under (≤) l (g ∘ f) ↔ is_bounded_under (≥) l f := hg.dual_right.is_bounded_under_ge_comp hg' lemma antitone.is_bounded_under_ge_comp [nonempty β] [linear_order β] [preorder γ] [no_min_order γ] {g : β → γ} {f : α → β} {l : filter α} (hg : antitone g) (hg' : tendsto g at_top at_bot) : is_bounded_under (≥) l (g ∘ f) ↔ is_bounded_under (≤) l f := hg.dual_right.is_bounded_under_le_comp hg' lemma galois_connection.l_limsup_le [conditionally_complete_lattice β] [conditionally_complete_lattice γ] {f : filter α} {v : α → β} {l : β → γ} {u : γ → β} (gc : galois_connection l u) (hlv : f.is_bounded_under (≤) (λ x, l (v x)) . is_bounded_default) (hv_co : f.is_cobounded_under (≤) v . is_bounded_default) : l (limsup v f) ≤ limsup (λ x, l (v x)) f := begin refine le_Limsup_of_le hlv (λ c hc, _), rw filter.eventually_map at hc, simp_rw (gc _ _) at hc ⊢, exact Limsup_le_of_le hv_co hc, end lemma order_iso.limsup_apply {γ} [conditionally_complete_lattice β] [conditionally_complete_lattice γ] {f : filter α} {u : α → β} (g : β ≃o γ) (hu : f.is_bounded_under (≤) u . is_bounded_default) (hu_co : f.is_cobounded_under (≤) u . is_bounded_default) (hgu : f.is_bounded_under (≤) (λ x, g (u x)) . is_bounded_default) (hgu_co : f.is_cobounded_under (≤) (λ x, g (u x)) . is_bounded_default) : g (limsup u f) = limsup (λ x, g (u x)) f := begin refine le_antisymm (g.to_galois_connection.l_limsup_le hgu hu_co) _, rw [←(g.symm.symm_apply_apply $ limsup (λ x, g (u x)) f), g.symm_symm], refine g.monotone _, have hf : u = λ i, g.symm (g (u i)), from funext (λ i, (g.symm_apply_apply (u i)).symm), nth_rewrite 0 hf, refine g.symm.to_galois_connection.l_limsup_le _ hgu_co, simp_rw g.symm_apply_apply, exact hu, end lemma order_iso.liminf_apply {γ} [conditionally_complete_lattice β] [conditionally_complete_lattice γ] {f : filter α} {u : α → β} (g : β ≃o γ) (hu : f.is_bounded_under (≥) u . is_bounded_default) (hu_co : f.is_cobounded_under (≥) u . is_bounded_default) (hgu : f.is_bounded_under (≥) (λ x, g (u x)) . is_bounded_default) (hgu_co : f.is_cobounded_under (≥) (λ x, g (u x)) . is_bounded_default) : g (liminf u f) = liminf (λ x, g (u x)) f := @order_iso.limsup_apply α βᵒᵈ γᵒᵈ _ _ f u g.dual hu hu_co hgu hgu_co end order
a5b1469552a4c8e79244ae550757d2068c87eaac
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/finset/sort.lean
9727fe08bb25c2128c91b8e7cbdcc73e952ff4bd
[ "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
10,498
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.fintype.basic import data.multiset.sort import data.list.nodup_equiv_fin /-! # Construct a sorted list from a finset. -/ namespace finset open multiset nat variables {α β : Type*} /-! ### sort -/ section sort variables (r : α → α → Prop) [decidable_rel r] [is_trans α r] [is_antisymm α r] [is_total α r] /-- `sort s` constructs a sorted list from the unordered set `s`. (Uses merge sort algorithm.) -/ def sort (s : finset α) : list α := sort r s.1 @[simp] theorem sort_sorted (s : finset α) : list.sorted r (sort r s) := sort_sorted _ _ @[simp] theorem sort_eq (s : finset α) : ↑(sort r s) = s.1 := sort_eq _ _ @[simp] theorem sort_nodup (s : finset α) : (sort r s).nodup := (by rw sort_eq; exact s.2 : @multiset.nodup α (sort r s)) @[simp] theorem sort_to_finset [decidable_eq α] (s : finset α) : (sort r s).to_finset = s := list.to_finset_eq (sort_nodup r s) ▸ eq_of_veq (sort_eq r s) @[simp] theorem mem_sort {s : finset α} {a : α} : a ∈ sort r s ↔ a ∈ s := multiset.mem_sort _ @[simp] theorem length_sort {s : finset α} : (sort r s).length = s.card := multiset.length_sort _ lemma sort_perm_to_list (s : finset α) : sort r s ~ s.to_list := by { rw ←multiset.coe_eq_coe, simp only [coe_to_list, sort_eq] } end sort section sort_linear_order variables [linear_order α] theorem sort_sorted_lt (s : finset α) : list.sorted (<) (sort (≤) s) := (sort_sorted _ _).imp₂ (@lt_of_le_of_ne _ _) (sort_nodup _ _) lemma sorted_zero_eq_min'_aux (s : finset α) (h : 0 < (s.sort (≤)).length) (H : s.nonempty) : (s.sort (≤)).nth_le 0 h = s.min' H := begin let l := s.sort (≤), apply le_antisymm, { have : s.min' H ∈ l := (finset.mem_sort (≤)).mpr (s.min'_mem H), obtain ⟨i, i_lt, hi⟩ : ∃ i (hi : i < l.length), l.nth_le i hi = s.min' H := list.mem_iff_nth_le.1 this, rw ← hi, exact (s.sort_sorted (≤)).rel_nth_le_of_le _ _ (nat.zero_le i) }, { have : l.nth_le 0 h ∈ s := (finset.mem_sort (≤)).1 (list.nth_le_mem l 0 h), exact s.min'_le _ this } end lemma sorted_zero_eq_min' {s : finset α} {h : 0 < (s.sort (≤)).length} : (s.sort (≤)).nth_le 0 h = s.min' (card_pos.1 $ by rwa length_sort at h) := sorted_zero_eq_min'_aux _ _ _ lemma min'_eq_sorted_zero {s : finset α} {h : s.nonempty} : s.min' h = (s.sort (≤)).nth_le 0 (by { rw length_sort, exact card_pos.2 h }) := (sorted_zero_eq_min'_aux _ _ _).symm lemma sorted_last_eq_max'_aux (s : finset α) (h : (s.sort (≤)).length - 1 < (s.sort (≤)).length) (H : s.nonempty) : (s.sort (≤)).nth_le ((s.sort (≤)).length - 1) h = s.max' H := begin let l := s.sort (≤), apply le_antisymm, { have : l.nth_le ((s.sort (≤)).length - 1) h ∈ s := (finset.mem_sort (≤)).1 (list.nth_le_mem l _ h), exact s.le_max' _ this }, { have : s.max' H ∈ l := (finset.mem_sort (≤)).mpr (s.max'_mem H), obtain ⟨i, i_lt, hi⟩ : ∃ i (hi : i < l.length), l.nth_le i hi = s.max' H := list.mem_iff_nth_le.1 this, rw ← hi, have : i ≤ l.length - 1 := nat.le_pred_of_lt i_lt, exact (s.sort_sorted (≤)).rel_nth_le_of_le _ _ (nat.le_pred_of_lt i_lt) }, end lemma sorted_last_eq_max' {s : finset α} {h : (s.sort (≤)).length - 1 < (s.sort (≤)).length} : (s.sort (≤)).nth_le ((s.sort (≤)).length - 1) h = s.max' (by { rw length_sort at h, exact card_pos.1 (lt_of_le_of_lt bot_le h) }) := sorted_last_eq_max'_aux _ _ _ lemma max'_eq_sorted_last {s : finset α} {h : s.nonempty} : s.max' h = (s.sort (≤)).nth_le ((s.sort (≤)).length - 1) (by simpa using nat.sub_lt (card_pos.mpr h) zero_lt_one) := (sorted_last_eq_max'_aux _ _ _).symm /-- Given a finset `s` of cardinality `k` in a linear order `α`, the map `order_iso_of_fin s h` is the increasing bijection between `fin k` and `s` as an `order_iso`. Here, `h` is a proof that the cardinality of `s` is `k`. We use this instead of an iso `fin s.card ≃o s` to avoid casting issues in further uses of this function. -/ def order_iso_of_fin (s : finset α) {k : ℕ} (h : s.card = k) : fin k ≃o s := order_iso.trans (fin.cast ((length_sort (≤)).trans h).symm) $ (s.sort_sorted_lt.nth_le_iso _).trans $ order_iso.set_congr _ _ $ set.ext $ λ x, mem_sort _ /-- Given a finset `s` of cardinality `k` in a linear order `α`, the map `order_emb_of_fin s h` is the increasing bijection between `fin k` and `s` as an order embedding into `α`. Here, `h` is a proof that the cardinality of `s` is `k`. We use this instead of an embedding `fin s.card ↪o α` to avoid casting issues in further uses of this function. -/ def order_emb_of_fin (s : finset α) {k : ℕ} (h : s.card = k) : fin k ↪o α := (order_iso_of_fin s h).to_order_embedding.trans (order_embedding.subtype _) @[simp] lemma coe_order_iso_of_fin_apply (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) : ↑(order_iso_of_fin s h i) = order_emb_of_fin s h i := rfl lemma order_iso_of_fin_symm_apply (s : finset α) {k : ℕ} (h : s.card = k) (x : s) : ↑((s.order_iso_of_fin h).symm x) = (s.sort (≤)).index_of x := rfl lemma order_emb_of_fin_apply (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) : s.order_emb_of_fin h i = (s.sort (≤)).nth_le i (by { rw [length_sort, h], exact i.2 }) := rfl @[simp] lemma order_emb_of_fin_mem (s : finset α) {k : ℕ} (h : s.card = k) (i : fin k) : s.order_emb_of_fin h i ∈ s := (s.order_iso_of_fin h i).2 @[simp] lemma range_order_emb_of_fin (s : finset α) {k : ℕ} (h : s.card = k) : set.range (s.order_emb_of_fin h) = s := by simp [order_emb_of_fin, set.range_comp coe (s.order_iso_of_fin h)] /-- The bijection `order_emb_of_fin s h` sends `0` to the minimum of `s`. -/ lemma order_emb_of_fin_zero {s : finset α} {k : ℕ} (h : s.card = k) (hz : 0 < k) : order_emb_of_fin s h ⟨0, hz⟩ = s.min' (card_pos.mp (h.symm ▸ hz)) := by simp only [order_emb_of_fin_apply, subtype.coe_mk, sorted_zero_eq_min'] /-- The bijection `order_emb_of_fin s h` sends `k-1` to the maximum of `s`. -/ lemma order_emb_of_fin_last {s : finset α} {k : ℕ} (h : s.card = k) (hz : 0 < k) : order_emb_of_fin s h ⟨k-1, buffer.lt_aux_2 hz⟩ = s.max' (card_pos.mp (h.symm ▸ hz)) := by simp [order_emb_of_fin_apply, max'_eq_sorted_last, h] /-- `order_emb_of_fin {a} h` sends any argument to `a`. -/ @[simp] lemma order_emb_of_fin_singleton (a : α) (i : fin 1) : order_emb_of_fin {a} (card_singleton a) i = a := by rw [subsingleton.elim i ⟨0, zero_lt_one⟩, order_emb_of_fin_zero _ zero_lt_one, min'_singleton] /-- Any increasing map `f` from `fin k` to a finset of cardinality `k` has to coincide with the increasing bijection `order_emb_of_fin s h`. -/ lemma order_emb_of_fin_unique {s : finset α} {k : ℕ} (h : s.card = k) {f : fin k → α} (hfs : ∀ x, f x ∈ s) (hmono : strict_mono f) : f = s.order_emb_of_fin h := begin apply fin.strict_mono_unique hmono (s.order_emb_of_fin h).strict_mono, rw [range_order_emb_of_fin, ← set.image_univ, ← coe_fin_range, ← coe_image, coe_inj], refine eq_of_subset_of_card_le (λ x hx, _) _, { rcases mem_image.1 hx with ⟨x, hx, rfl⟩, exact hfs x }, { rw [h, card_image_of_injective _ hmono.injective, fin_range_card] } end /-- An order embedding `f` from `fin k` to a finset of cardinality `k` has to coincide with the increasing bijection `order_emb_of_fin s h`. -/ lemma order_emb_of_fin_unique' {s : finset α} {k : ℕ} (h : s.card = k) {f : fin k ↪o α} (hfs : ∀ x, f x ∈ s) : f = s.order_emb_of_fin h := rel_embedding.ext $ function.funext_iff.1 $ order_emb_of_fin_unique h hfs f.strict_mono /-- Two parametrizations `order_emb_of_fin` of the same set take the same value on `i` and `j` if and only if `i = j`. Since they can be defined on a priori not defeq types `fin k` and `fin l` (although necessarily `k = l`), the conclusion is rather written `(i : ℕ) = (j : ℕ)`. -/ @[simp] lemma order_emb_of_fin_eq_order_emb_of_fin_iff {k l : ℕ} {s : finset α} {i : fin k} {j : fin l} {h : s.card = k} {h' : s.card = l} : s.order_emb_of_fin h i = s.order_emb_of_fin h' j ↔ (i : ℕ) = (j : ℕ) := begin substs k l, exact (s.order_emb_of_fin rfl).eq_iff_eq.trans (fin.ext_iff _ _) end /-- Given a finset `s` of size at least `k` in a linear order `α`, the map `order_emb_of_card_le` is an order embedding from `fin k` to `α` whose image is contained in `s`. Specifically, it maps `fin k` to an initial segment of `s`. -/ def order_emb_of_card_le (s : finset α) {k : ℕ} (h : k ≤ s.card) : fin k ↪o α := (fin.cast_le h).trans (s.order_emb_of_fin rfl) lemma order_emb_of_card_le_mem (s : finset α) {k : ℕ} (h : k ≤ s.card) (a) : order_emb_of_card_le s h a ∈ s := by simp only [order_emb_of_card_le, rel_embedding.coe_trans, finset.order_emb_of_fin_mem] lemma card_le_of_interleaved {s t : finset α} (h : ∀ x y ∈ s, x < y → ∃ z ∈ t, x < z ∧ z < y) : s.card ≤ t.card + 1 := begin have h1 : ∀ i : fin (s.card - 1), ↑i + 1 < (s.sort (≤)).length, { intro i, rw [finset.length_sort, ←lt_tsub_iff_right], exact i.2 }, have h0 : ∀ i : fin (s.card - 1), ↑i < (s.sort (≤)).length := λ i, lt_of_le_of_lt (nat.le_succ i) (h1 i), have p := λ i : fin (s.card - 1), h ((s.sort (≤)).nth_le i (h0 i)) ((finset.mem_sort (≤)).mp (list.nth_le_mem _ _ (h0 i))) ((s.sort (≤)).nth_le (i + 1) (h1 i)) ((finset.mem_sort (≤)).mp (list.nth_le_mem _ _ (h1 i))) (s.sort_sorted_lt.rel_nth_le_of_lt (h0 i) (h1 i) (nat.lt_succ_self i)), let f : fin (s.card - 1) → t := λ i, ⟨classical.some (p i), (exists_prop.mp (classical.some_spec (p i))).1⟩, have hf : ∀ i j : fin (s.card - 1), i < j → f i < f j := λ i j hij, subtype.coe_lt_coe.mp ((exists_prop.mp (classical.some_spec (p i))).2.2.trans (lt_of_le_of_lt ((s.sort_sorted (≤)).rel_nth_le_of_le (h1 i) (h0 j) (nat.succ_le_iff.mpr hij)) (exists_prop.mp (classical.some_spec (p j))).2.1)), have key := fintype.card_le_of_embedding (function.embedding.mk f (λ i j hij, le_antisymm (not_lt.mp (mt (hf j i) (not_lt.mpr (le_of_eq hij)))) (not_lt.mp (mt (hf i j) (not_lt.mpr (ge_of_eq hij)))))), rwa [fintype.card_fin, fintype.card_coe, tsub_le_iff_right] at key, end end sort_linear_order instance [has_repr α] : has_repr (finset α) := ⟨λ s, repr s.1⟩ end finset
21eb63591bcc49533380df55645ec79f3f08a372
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/geometry/euclidean/angle/oriented/basic.lean
b5de68815a179ff0eaf5ca04c4067cccdf2f2d21
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
48,443
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.inner_product_space.two_dim import geometry.euclidean.angle.unoriented.basic /-! # Oriented angles. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines oriented angles in real inner product spaces. ## Main definitions * `orientation.oangle` is the oriented angle between two vectors with respect to an orientation. ## Implementation notes The definitions here use the `real.angle` type, angles modulo `2 * π`. For some purposes, angles modulo `π` are more convenient, because results are true for such angles with less configuration dependence. Results that are only equalities modulo `π` can be represented modulo `2 * π` as equalities of `(2 : ℤ) • θ`. ## References * Evan Chen, Euclidean Geometry in Mathematical Olympiads. -/ 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 `ω` := o.area_form /-- The oriented angle from `x` to `y`, modulo `2 * π`. If either vector is 0, this is 0. See `inner_product_geometry.angle` for the corresponding unoriented angle definition. -/ def oangle (x y : V) : real.angle := complex.arg (o.kahler x y) /-- Oriented angles are continuous when the vectors involved are nonzero. -/ lemma continuous_at_oangle {x : V × V} (hx1 : x.1 ≠ 0) (hx2 : x.2 ≠ 0) : continuous_at (λ y : V × V, o.oangle y.1 y.2) x := begin refine (complex.continuous_at_arg_coe_angle _).comp _, { exact o.kahler_ne_zero hx1 hx2 }, exact ((continuous_of_real.comp continuous_inner).add ((continuous_of_real.comp o.area_form'.continuous₂).mul continuous_const)).continuous_at, end /-- If the first vector passed to `oangle` is 0, the result is 0. -/ @[simp] lemma oangle_zero_left (x : V) : o.oangle 0 x = 0 := by simp [oangle] /-- If the second vector passed to `oangle` is 0, the result is 0. -/ @[simp] lemma oangle_zero_right (x : V) : o.oangle x 0 = 0 := by simp [oangle] /-- If the two vectors passed to `oangle` are the same, the result is 0. -/ @[simp] lemma oangle_self (x : V) : o.oangle x x = 0 := begin simp only [oangle, kahler_apply_self, ← complex.of_real_pow], convert quotient_add_group.coe_zero _, apply arg_of_real_of_nonneg, positivity, end /-- If the angle between two vectors is nonzero, the first vector is nonzero. -/ lemma left_ne_zero_of_oangle_ne_zero {x y : V} (h : o.oangle x y ≠ 0) : x ≠ 0 := by { rintro rfl, simpa using h } /-- If the angle between two vectors is nonzero, the second vector is nonzero. -/ lemma right_ne_zero_of_oangle_ne_zero {x y : V} (h : o.oangle x y ≠ 0) : y ≠ 0 := by { rintro rfl, simpa using h } /-- If the angle between two vectors is nonzero, the vectors are not equal. -/ lemma ne_of_oangle_ne_zero {x y : V} (h : o.oangle x y ≠ 0) : x ≠ y := by { rintro rfl, simpa using h } /-- If the angle between two vectors is `π`, the first vector is nonzero. -/ lemma left_ne_zero_of_oangle_eq_pi {x y : V} (h : o.oangle x y = π) : x ≠ 0 := o.left_ne_zero_of_oangle_ne_zero (h.symm ▸ real.angle.pi_ne_zero : o.oangle x y ≠ 0) /-- If the angle between two vectors is `π`, the second vector is nonzero. -/ lemma right_ne_zero_of_oangle_eq_pi {x y : V} (h : o.oangle x y = π) : y ≠ 0 := o.right_ne_zero_of_oangle_ne_zero (h.symm ▸ real.angle.pi_ne_zero : o.oangle x y ≠ 0) /-- If the angle between two vectors is `π`, the vectors are not equal. -/ lemma ne_of_oangle_eq_pi {x y : V} (h : o.oangle x y = π) : x ≠ y := o.ne_of_oangle_ne_zero (h.symm ▸ real.angle.pi_ne_zero : o.oangle x y ≠ 0) /-- If the angle between two vectors is `π / 2`, the first vector is nonzero. -/ lemma left_ne_zero_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = (π / 2 : ℝ)) : x ≠ 0 := o.left_ne_zero_of_oangle_ne_zero (h.symm ▸ real.angle.pi_div_two_ne_zero : o.oangle x y ≠ 0) /-- If the angle between two vectors is `π / 2`, the second vector is nonzero. -/ lemma right_ne_zero_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = (π / 2 : ℝ)) : y ≠ 0 := o.right_ne_zero_of_oangle_ne_zero (h.symm ▸ real.angle.pi_div_two_ne_zero : o.oangle x y ≠ 0) /-- If the angle between two vectors is `π / 2`, the vectors are not equal. -/ lemma ne_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = (π / 2 : ℝ)) : x ≠ y := o.ne_of_oangle_ne_zero (h.symm ▸ real.angle.pi_div_two_ne_zero : o.oangle x y ≠ 0) /-- If the angle between two vectors is `-π / 2`, the first vector is nonzero. -/ lemma left_ne_zero_of_oangle_eq_neg_pi_div_two {x y : V} (h : o.oangle x y = (-π / 2 : ℝ)) : x ≠ 0 := o.left_ne_zero_of_oangle_ne_zero (h.symm ▸ real.angle.neg_pi_div_two_ne_zero : o.oangle x y ≠ 0) /-- If the angle between two vectors is `-π / 2`, the second vector is nonzero. -/ lemma right_ne_zero_of_oangle_eq_neg_pi_div_two {x y : V} (h : o.oangle x y = (-π / 2 : ℝ)) : y ≠ 0 := o.right_ne_zero_of_oangle_ne_zero (h.symm ▸ real.angle.neg_pi_div_two_ne_zero : o.oangle x y ≠ 0) /-- If the angle between two vectors is `-π / 2`, the vectors are not equal. -/ lemma ne_of_oangle_eq_neg_pi_div_two {x y : V} (h : o.oangle x y = (-π / 2 : ℝ)) : x ≠ y := o.ne_of_oangle_ne_zero (h.symm ▸ real.angle.neg_pi_div_two_ne_zero : o.oangle x y ≠ 0) /-- If the sign of the angle between two vectors is nonzero, the first vector is nonzero. -/ lemma left_ne_zero_of_oangle_sign_ne_zero {x y : V} (h : (o.oangle x y).sign ≠ 0) : x ≠ 0 := o.left_ne_zero_of_oangle_ne_zero (real.angle.sign_ne_zero_iff.1 h).1 /-- If the sign of the angle between two vectors is nonzero, the second vector is nonzero. -/ lemma right_ne_zero_of_oangle_sign_ne_zero {x y : V} (h : (o.oangle x y).sign ≠ 0) : y ≠ 0 := o.right_ne_zero_of_oangle_ne_zero (real.angle.sign_ne_zero_iff.1 h).1 /-- If the sign of the angle between two vectors is nonzero, the vectors are not equal. -/ lemma ne_of_oangle_sign_ne_zero {x y : V} (h : (o.oangle x y).sign ≠ 0) : x ≠ y := o.ne_of_oangle_ne_zero (real.angle.sign_ne_zero_iff.1 h).1 /-- If the sign of the angle between two vectors is positive, the first vector is nonzero. -/ lemma left_ne_zero_of_oangle_sign_eq_one {x y : V} (h : (o.oangle x y).sign = 1) : x ≠ 0 := o.left_ne_zero_of_oangle_sign_ne_zero (h.symm ▸ dec_trivial : (o.oangle x y).sign ≠ 0) /-- If the sign of the angle between two vectors is positive, the second vector is nonzero. -/ lemma right_ne_zero_of_oangle_sign_eq_one {x y : V} (h : (o.oangle x y).sign = 1) : y ≠ 0 := o.right_ne_zero_of_oangle_sign_ne_zero (h.symm ▸ dec_trivial : (o.oangle x y).sign ≠ 0) /-- If the sign of the angle between two vectors is positive, the vectors are not equal. -/ lemma ne_of_oangle_sign_eq_one {x y : V} (h : (o.oangle x y).sign = 1) : x ≠ y := o.ne_of_oangle_sign_ne_zero (h.symm ▸ dec_trivial : (o.oangle x y).sign ≠ 0) /-- If the sign of the angle between two vectors is negative, the first vector is nonzero. -/ lemma left_ne_zero_of_oangle_sign_eq_neg_one {x y : V} (h : (o.oangle x y).sign = -1) : x ≠ 0 := o.left_ne_zero_of_oangle_sign_ne_zero (h.symm ▸ dec_trivial : (o.oangle x y).sign ≠ 0) /-- If the sign of the angle between two vectors is negative, the second vector is nonzero. -/ lemma right_ne_zero_of_oangle_sign_eq_neg_one {x y : V} (h : (o.oangle x y).sign = -1) : y ≠ 0 := o.right_ne_zero_of_oangle_sign_ne_zero (h.symm ▸ dec_trivial : (o.oangle x y).sign ≠ 0) /-- If the sign of the angle between two vectors is negative, the vectors are not equal. -/ lemma ne_of_oangle_sign_eq_neg_one {x y : V} (h : (o.oangle x y).sign = -1) : x ≠ y := o.ne_of_oangle_sign_ne_zero (h.symm ▸ dec_trivial : (o.oangle x y).sign ≠ 0) /-- Swapping the two vectors passed to `oangle` negates the angle. -/ lemma oangle_rev (x y : V) : o.oangle y x = -o.oangle x y := by simp only [oangle, o.kahler_swap y x, complex.arg_conj_coe_angle] /-- Adding the angles between two vectors in each order results in 0. -/ @[simp] lemma oangle_add_oangle_rev (x y : V) : o.oangle x y + o.oangle y x = 0 := by simp [o.oangle_rev y x] /-- Negating the first vector passed to `oangle` adds `π` to the angle. -/ lemma oangle_neg_left {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : o.oangle (-x) y = o.oangle x y + π := begin simp only [oangle, map_neg], convert complex.arg_neg_coe_angle _, exact o.kahler_ne_zero hx hy, end /-- Negating the second vector passed to `oangle` adds `π` to the angle. -/ lemma oangle_neg_right {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : o.oangle x (-y) = o.oangle x y + π := begin simp only [oangle, map_neg], convert complex.arg_neg_coe_angle _, exact o.kahler_ne_zero hx hy, end /-- Negating the first vector passed to `oangle` does not change twice the angle. -/ @[simp] lemma two_zsmul_oangle_neg_left (x y : V) : (2 : ℤ) • o.oangle (-x) y = (2 : ℤ) • o.oangle x y := begin by_cases hx : x = 0, { simp [hx] }, { by_cases hy : y = 0, { simp [hy] }, { simp [o.oangle_neg_left hx hy] } } end /-- Negating the second vector passed to `oangle` does not change twice the angle. -/ @[simp] lemma two_zsmul_oangle_neg_right (x y : V) : (2 : ℤ) • o.oangle x (-y) = (2 : ℤ) • o.oangle x y := begin by_cases hx : x = 0, { simp [hx] }, { by_cases hy : y = 0, { simp [hy] }, { simp [o.oangle_neg_right hx hy] } } end /-- Negating both vectors passed to `oangle` does not change the angle. -/ @[simp] lemma oangle_neg_neg (x y : V) : o.oangle (-x) (-y) = o.oangle x y := by simp [oangle] /-- Negating the first vector produces the same angle as negating the second vector. -/ lemma oangle_neg_left_eq_neg_right (x y : V) : o.oangle (-x) y = o.oangle x (-y) := by rw [←neg_neg y, oangle_neg_neg, neg_neg] /-- The angle between the negation of a nonzero vector and that vector is `π`. -/ @[simp] lemma oangle_neg_self_left {x : V} (hx : x ≠ 0) : o.oangle (-x) x = π := by simp [oangle_neg_left, hx] /-- The angle between a nonzero vector and its negation is `π`. -/ @[simp] lemma oangle_neg_self_right {x : V} (hx : x ≠ 0) : o.oangle x (-x) = π := by simp [oangle_neg_right, hx] /-- Twice the angle between the negation of a vector and that vector is 0. -/ @[simp] lemma two_zsmul_oangle_neg_self_left (x : V) : (2 : ℤ) • o.oangle (-x) x = 0 := begin by_cases hx : x = 0; simp [hx] end /-- Twice the angle between a vector and its negation is 0. -/ @[simp] lemma two_zsmul_oangle_neg_self_right (x : V) : (2 : ℤ) • o.oangle x (-x) = 0 := begin by_cases hx : x = 0; simp [hx] end /-- Adding the angles between two vectors in each order, with the first vector in each angle negated, results in 0. -/ @[simp] lemma oangle_add_oangle_rev_neg_left (x y : V) : o.oangle (-x) y + o.oangle (-y) x = 0 := by rw [oangle_neg_left_eq_neg_right, oangle_rev, add_left_neg] /-- Adding the angles between two vectors in each order, with the second vector in each angle negated, results in 0. -/ @[simp] lemma oangle_add_oangle_rev_neg_right (x y : V) : o.oangle x (-y) + o.oangle y (-x) = 0 := by rw [o.oangle_rev (-x), oangle_neg_left_eq_neg_right, add_neg_self] /-- Multiplying the first vector passed to `oangle` by a positive real does not change the angle. -/ @[simp] lemma oangle_smul_left_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : o.oangle (r • x) y = o.oangle x y := by simp [oangle, complex.arg_real_mul _ hr] /-- Multiplying the second vector passed to `oangle` by a positive real does not change the angle. -/ @[simp] lemma oangle_smul_right_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : o.oangle x (r • y) = o.oangle x y := by simp [oangle, complex.arg_real_mul _ hr] /-- Multiplying the first vector passed to `oangle` by a negative real produces the same angle as negating that vector. -/ @[simp] lemma oangle_smul_left_of_neg (x y : V) {r : ℝ} (hr : r < 0) : o.oangle (r • x) y = o.oangle (-x) y := by rw [←neg_neg r, neg_smul, ←smul_neg, o.oangle_smul_left_of_pos _ _ (neg_pos_of_neg hr)] /-- Multiplying the second vector passed to `oangle` by a negative real produces the same angle as negating that vector. -/ @[simp] lemma oangle_smul_right_of_neg (x y : V) {r : ℝ} (hr : r < 0) : o.oangle x (r • y) = o.oangle x (-y) := by rw [←neg_neg r, neg_smul, ←smul_neg, o.oangle_smul_right_of_pos _ _ (neg_pos_of_neg hr)] /-- The angle between a nonnegative multiple of a vector and that vector is 0. -/ @[simp] lemma oangle_smul_left_self_of_nonneg (x : V) {r : ℝ} (hr : 0 ≤ r) : o.oangle (r • x) x = 0 := begin rcases hr.lt_or_eq with (h|h), { simp [h] }, { simp [h.symm] } end /-- The angle between a vector and a nonnegative multiple of that vector is 0. -/ @[simp] lemma oangle_smul_right_self_of_nonneg (x : V) {r : ℝ} (hr : 0 ≤ r) : o.oangle x (r • x) = 0 := begin rcases hr.lt_or_eq with (h|h), { simp [h] }, { simp [h.symm] } end /-- The angle between two nonnegative multiples of the same vector is 0. -/ @[simp] lemma oangle_smul_smul_self_of_nonneg (x : V) {r₁ r₂ : ℝ} (hr₁ : 0 ≤ r₁) (hr₂ : 0 ≤ r₂) : o.oangle (r₁ • x) (r₂ • x) = 0 := begin rcases hr₁.lt_or_eq with (h|h), { simp [h, hr₂] }, { simp [h.symm] } end /-- Multiplying the first vector passed to `oangle` by a nonzero real does not change twice the angle. -/ @[simp] lemma two_zsmul_oangle_smul_left_of_ne_zero (x y : V) {r : ℝ} (hr : r ≠ 0) : (2 : ℤ) • o.oangle (r • x) y = (2 : ℤ) • o.oangle x y := begin rcases hr.lt_or_lt with (h|h); simp [h] end /-- Multiplying the second vector passed to `oangle` by a nonzero real does not change twice the angle. -/ @[simp] lemma two_zsmul_oangle_smul_right_of_ne_zero (x y : V) {r : ℝ} (hr : r ≠ 0) : (2 : ℤ) • o.oangle x (r • y) = (2 : ℤ) • o.oangle x y := begin rcases hr.lt_or_lt with (h|h); simp [h] end /-- Twice the angle between a multiple of a vector and that vector is 0. -/ @[simp] lemma two_zsmul_oangle_smul_left_self (x : V) {r : ℝ} : (2 : ℤ) • o.oangle (r • x) x = 0 := begin rcases lt_or_le r 0 with (h|h); simp [h] end /-- Twice the angle between a vector and a multiple of that vector is 0. -/ @[simp] lemma two_zsmul_oangle_smul_right_self (x : V) {r : ℝ} : (2 : ℤ) • o.oangle x (r • x) = 0 := begin rcases lt_or_le r 0 with (h|h); simp [h] end /-- Twice the angle between two multiples of a vector is 0. -/ @[simp] lemma two_zsmul_oangle_smul_smul_self (x : V) {r₁ r₂ : ℝ} : (2 : ℤ) • o.oangle (r₁ • x) (r₂ • x) = 0 := begin by_cases h : r₁ = 0; simp [h] end /-- If the spans of two vectors are equal, twice angles with those vectors on the left are equal. -/ lemma two_zsmul_oangle_left_of_span_eq {x y : V} (z : V) (h : (ℝ ∙ x) = ℝ ∙ y) : (2 : ℤ) • o.oangle x z = (2 : ℤ) • o.oangle y z := begin rw submodule.span_singleton_eq_span_singleton at h, rcases h with ⟨r, rfl⟩, exact (o.two_zsmul_oangle_smul_left_of_ne_zero _ _ (units.ne_zero _)).symm end /-- If the spans of two vectors are equal, twice angles with those vectors on the right are equal. -/ lemma two_zsmul_oangle_right_of_span_eq (x : V) {y z : V} (h : (ℝ ∙ y) = ℝ ∙ z) : (2 : ℤ) • o.oangle x y = (2 : ℤ) • o.oangle x z := begin rw submodule.span_singleton_eq_span_singleton at h, rcases h with ⟨r, rfl⟩, exact (o.two_zsmul_oangle_smul_right_of_ne_zero _ _ (units.ne_zero _)).symm end /-- If the spans of two pairs of vectors are equal, twice angles between those vectors are equal. -/ lemma two_zsmul_oangle_of_span_eq_of_span_eq {w x y z : V} (hwx : (ℝ ∙ w) = ℝ ∙ x) (hyz : (ℝ ∙ y) = ℝ ∙ z) : (2 : ℤ) • o.oangle w y = (2 : ℤ) • o.oangle x z := by rw [(o).two_zsmul_oangle_left_of_span_eq y hwx, (o).two_zsmul_oangle_right_of_span_eq x hyz] /-- The oriented angle between two vectors is zero if and only if the angle with the vectors swapped is zero. -/ lemma oangle_eq_zero_iff_oangle_rev_eq_zero {x y : V} : o.oangle x y = 0 ↔ o.oangle y x = 0 := by rw [oangle_rev, neg_eq_zero] /-- The oriented angle between two vectors is zero if and only if they are on the same ray. -/ lemma oangle_eq_zero_iff_same_ray {x y : V} : o.oangle x y = 0 ↔ same_ray ℝ x y := begin rw [oangle, kahler_apply_apply, complex.arg_coe_angle_eq_iff_eq_to_real, real.angle.to_real_zero, complex.arg_eq_zero_iff], simpa using o.nonneg_inner_and_area_form_eq_zero_iff_same_ray x y, end /-- The oriented angle between two vectors is `π` if and only if the angle with the vectors swapped is `π`. -/ lemma oangle_eq_pi_iff_oangle_rev_eq_pi {x y : V} : o.oangle x y = π ↔ o.oangle y x = π := by rw [oangle_rev, neg_eq_iff_eq_neg, real.angle.neg_coe_pi] /-- The oriented angle between two vectors is `π` if and only they are nonzero and the first is on the same ray as the negation of the second. -/ lemma oangle_eq_pi_iff_same_ray_neg {x y : V} : o.oangle x y = π ↔ x ≠ 0 ∧ y ≠ 0 ∧ same_ray ℝ x (-y) := begin rw [←o.oangle_eq_zero_iff_same_ray], split, { intro h, by_cases hx : x = 0, { simpa [hx, real.angle.pi_ne_zero.symm] using h }, by_cases hy : y = 0, { simpa [hy, real.angle.pi_ne_zero.symm] using h }, refine ⟨hx, hy, _⟩, rw [o.oangle_neg_right hx hy, h, real.angle.coe_pi_add_coe_pi] }, { rintro ⟨hx, hy, h⟩, rwa [o.oangle_neg_right hx hy, ←real.angle.sub_coe_pi_eq_add_coe_pi, sub_eq_zero] at h } end /-- The oriented angle between two vectors is zero or `π` if and only if those two vectors are not linearly independent. -/ lemma oangle_eq_zero_or_eq_pi_iff_not_linear_independent {x y : V} : (o.oangle x y = 0 ∨ o.oangle x y = π) ↔ ¬ linear_independent ℝ ![x, y] := by rw [oangle_eq_zero_iff_same_ray, oangle_eq_pi_iff_same_ray_neg, same_ray_or_ne_zero_and_same_ray_neg_iff_not_linear_independent] /-- The oriented angle between two vectors is zero or `π` if and only if the first vector is zero or the second is a multiple of the first. -/ lemma oangle_eq_zero_or_eq_pi_iff_right_eq_smul {x y : V} : (o.oangle x y = 0 ∨ o.oangle x y = π) ↔ (x = 0 ∨ ∃ r : ℝ, y = r • x) := begin rw [oangle_eq_zero_iff_same_ray, oangle_eq_pi_iff_same_ray_neg], refine ⟨λ h, _, λ h, _⟩, { rcases h with h|⟨-, -, h⟩, { by_cases hx : x = 0, { simp [hx] }, obtain ⟨r, -, rfl⟩ := h.exists_nonneg_left hx, exact or.inr ⟨r, rfl⟩ }, { by_cases hx : x = 0, { simp [hx] }, obtain ⟨r, -, hy⟩ := h.exists_nonneg_left hx, refine or.inr ⟨-r, _⟩, simp [hy] } }, { rcases h with rfl|⟨r, rfl⟩, { simp }, by_cases hx : x = 0, { simp [hx] }, rcases lt_trichotomy r 0 with hr|hr|hr, { rw ←neg_smul, exact or.inr ⟨hx, smul_ne_zero hr.ne hx, same_ray_pos_smul_right x (left.neg_pos_iff.2 hr)⟩ }, { simp [hr] }, { exact or.inl (same_ray_pos_smul_right x hr) } } end /-- The oriented angle between two vectors is not zero or `π` if and only if those two vectors are linearly independent. -/ lemma oangle_ne_zero_and_ne_pi_iff_linear_independent {x y : V} : (o.oangle x y ≠ 0 ∧ o.oangle x y ≠ π) ↔ linear_independent ℝ ![x, y] := by rw [←not_or_distrib, ←not_iff_not, not_not, oangle_eq_zero_or_eq_pi_iff_not_linear_independent] /-- Two vectors are equal if and only if they have equal norms and zero angle between them. -/ lemma eq_iff_norm_eq_and_oangle_eq_zero (x y : V) : x = y ↔ ‖x‖ = ‖y‖ ∧ o.oangle x y = 0 := begin rw oangle_eq_zero_iff_same_ray, split, { rintros rfl, simp }, { rcases eq_or_ne y 0 with rfl | hy, { simp }, rintros ⟨h₁, h₂⟩, obtain ⟨r, hr, rfl⟩ := h₂.exists_nonneg_right hy, have : ‖y‖ ≠ 0 := by simpa using hy, obtain rfl : r = 1, { apply mul_right_cancel₀ this, simpa [norm_smul, _root_.abs_of_nonneg hr] using h₁ }, simp }, end /-- Two vectors with equal norms are equal if and only if they have zero angle between them. -/ lemma eq_iff_oangle_eq_zero_of_norm_eq {x y : V} (h : ‖x‖ = ‖y‖) : x = y ↔ o.oangle x y = 0 := ⟨λ he, ((o.eq_iff_norm_eq_and_oangle_eq_zero x y).1 he).2, λ ha, (o.eq_iff_norm_eq_and_oangle_eq_zero x y).2 ⟨h, ha⟩⟩ /-- Two vectors with zero angle between them are equal if and only if they have equal norms. -/ lemma eq_iff_norm_eq_of_oangle_eq_zero {x y : V} (h : o.oangle x y = 0) : x = y ↔ ‖x‖ = ‖y‖ := ⟨λ he, ((o.eq_iff_norm_eq_and_oangle_eq_zero x y).1 he).1, λ hn, (o.eq_iff_norm_eq_and_oangle_eq_zero x y).2 ⟨hn, h⟩⟩ /-- Given three nonzero vectors, the angle between the first and the second plus the angle between the second and the third equals the angle between the first and the third. -/ @[simp] lemma oangle_add {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : o.oangle x y + o.oangle y z = o.oangle x z := begin simp_rw [oangle], rw [←complex.arg_mul_coe_angle, o.kahler_mul y x z], congr' 1, convert complex.arg_real_mul _ (_ : 0 < ‖y‖ ^ 2) using 2, { norm_cast }, { have : 0 < ‖y‖ := by simpa using hy, positivity }, { exact o.kahler_ne_zero hx hy, }, { exact o.kahler_ne_zero hy hz } end /-- Given three nonzero vectors, the angle between the second and the third plus the angle between the first and the second equals the angle between the first and the third. -/ @[simp] lemma oangle_add_swap {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : o.oangle y z + o.oangle x y = o.oangle x z := by rw [add_comm, o.oangle_add hx hy hz] /-- Given three nonzero vectors, the angle between the first and the third minus the angle between the first and the second equals the angle between the second and the third. -/ @[simp] lemma oangle_sub_left {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : o.oangle x z - o.oangle x y = o.oangle y z := by rw [sub_eq_iff_eq_add, o.oangle_add_swap hx hy hz] /-- Given three nonzero vectors, the angle between the first and the third minus the angle between the second and the third equals the angle between the first and the second. -/ @[simp] lemma oangle_sub_right {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : o.oangle x z - o.oangle y z = o.oangle x y := by rw [sub_eq_iff_eq_add, o.oangle_add hx hy hz] /-- Given three nonzero vectors, adding the angles between them in cyclic order results in 0. -/ @[simp] lemma oangle_add_cyc3 {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : o.oangle x y + o.oangle y z + o.oangle z x = 0 := by simp [hx, hy, hz] /-- Given three nonzero vectors, adding the angles between them in cyclic order, with the first vector in each angle negated, results in π. If the vectors add to 0, this is a version of the sum of the angles of a triangle. -/ @[simp] lemma oangle_add_cyc3_neg_left {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : o.oangle (-x) y + o.oangle (-y) z + o.oangle (-z) x = π := by rw [o.oangle_neg_left hx hy, o.oangle_neg_left hy hz, o.oangle_neg_left hz hx, (show o.oangle x y + π + (o.oangle y z + π) + (o.oangle z x + π) = o.oangle x y + o.oangle y z + o.oangle z x + (π + π + π : real.angle), by abel), o.oangle_add_cyc3 hx hy hz, real.angle.coe_pi_add_coe_pi, zero_add, zero_add] /-- Given three nonzero vectors, adding the angles between them in cyclic order, with the second vector in each angle negated, results in π. If the vectors add to 0, this is a version of the sum of the angles of a triangle. -/ @[simp] lemma oangle_add_cyc3_neg_right {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : o.oangle x (-y) + o.oangle y (-z) + o.oangle z (-x) = π := by simp_rw [←oangle_neg_left_eq_neg_right, o.oangle_add_cyc3_neg_left hx hy hz] /-- Pons asinorum, oriented vector angle form. -/ lemma oangle_sub_eq_oangle_sub_rev_of_norm_eq {x y : V} (h : ‖x‖ = ‖y‖) : o.oangle x (x - y) = o.oangle (y - x) y := by simp [oangle, h] /-- The angle at the apex of an isosceles triangle is `π` minus twice a base angle, oriented vector angle form. -/ lemma oangle_eq_pi_sub_two_zsmul_oangle_sub_of_norm_eq {x y : V} (hn : x ≠ y) (h : ‖x‖ = ‖y‖) : o.oangle y x = π - (2 : ℤ) • o.oangle (y - x) y := begin rw two_zsmul, rw [←o.oangle_sub_eq_oangle_sub_rev_of_norm_eq h] { occs := occurrences.pos [1] }, rw [eq_sub_iff_add_eq, ←oangle_neg_neg, ←add_assoc], have hy : y ≠ 0, { rintro rfl, rw [norm_zero, norm_eq_zero] at h, exact hn h }, have hx : x ≠ 0 := norm_ne_zero_iff.1 (h.symm ▸ norm_ne_zero_iff.2 hy), convert o.oangle_add_cyc3_neg_right (neg_ne_zero.2 hy) hx (sub_ne_zero_of_ne hn.symm); simp end /-- The angle between two vectors, with respect to an orientation given by `orientation.map` with a linear isometric equivalence, equals the angle between those two vectors, transformed by the inverse of that equivalence, with respect to the original orientation. -/ @[simp] lemma oangle_map (x y : V') (f : V ≃ₗᵢ[ℝ] V') : (orientation.map (fin 2) f.to_linear_equiv o).oangle x y = o.oangle (f.symm x) (f.symm y) := by simp [oangle, o.kahler_map] @[simp] protected lemma _root_.complex.oangle (w z : ℂ) : complex.orientation.oangle w z = complex.arg (conj w * z) := by simp [oangle] /-- The oriented angle on an oriented real inner product space of dimension 2 can be evaluated in terms of a complex-number representation of the space. -/ lemma oangle_map_complex (f : V ≃ₗᵢ[ℝ] ℂ) (hf : (orientation.map (fin 2) f.to_linear_equiv o) = complex.orientation) (x y : V) : o.oangle x y = complex.arg (conj (f x) * f y) := begin rw [← complex.oangle, ← hf, o.oangle_map], simp, end /-- Negating the orientation negates the value of `oangle`. -/ lemma oangle_neg_orientation_eq_neg (x y : V) : (-o).oangle x y = -(o.oangle x y) := by simp [oangle] /-- The inner product of two vectors is the product of the norms and the cosine of the oriented angle between the vectors. -/ lemma inner_eq_norm_mul_norm_mul_cos_oangle (x y : V) : ⟪x, y⟫ = ‖x‖ * ‖y‖ * real.angle.cos (o.oangle x y) := begin by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, have : ‖x‖ ≠ 0 := by simpa using hx, have : ‖y‖ ≠ 0 := by simpa using hy, rw [oangle, real.angle.cos_coe, complex.cos_arg, o.abs_kahler], { simp only [kahler_apply_apply, real_smul, add_re, of_real_re, mul_re, I_re, of_real_im], field_simp, ring }, { exact o.kahler_ne_zero hx hy } end /-- The cosine of the oriented angle between two nonzero vectors is the inner product divided by the product of the norms. -/ lemma cos_oangle_eq_inner_div_norm_mul_norm {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : real.angle.cos (o.oangle x y) = ⟪x, y⟫ / (‖x‖ * ‖y‖) := begin rw o.inner_eq_norm_mul_norm_mul_cos_oangle, field_simp [norm_ne_zero_iff.2 hx, norm_ne_zero_iff.2 hy], ring end /-- The cosine of the oriented angle between two nonzero vectors equals that of the unoriented angle. -/ lemma cos_oangle_eq_cos_angle {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : real.angle.cos (o.oangle x y) = real.cos (inner_product_geometry.angle x y) := by rw [o.cos_oangle_eq_inner_div_norm_mul_norm hx hy, inner_product_geometry.cos_angle] /-- The oriented angle between two nonzero vectors is plus or minus the unoriented angle. -/ lemma oangle_eq_angle_or_eq_neg_angle {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : o.oangle x y = inner_product_geometry.angle x y ∨ o.oangle x y = -inner_product_geometry.angle x y := real.angle.cos_eq_real_cos_iff_eq_or_eq_neg.1 $ o.cos_oangle_eq_cos_angle hx hy /-- The unoriented angle between two nonzero vectors is the absolute value of the oriented angle, converted to a real. -/ lemma angle_eq_abs_oangle_to_real {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : inner_product_geometry.angle x y = |(o.oangle x y).to_real| := begin have h0 := inner_product_geometry.angle_nonneg x y, have hpi := inner_product_geometry.angle_le_pi x y, rcases o.oangle_eq_angle_or_eq_neg_angle hx hy with (h|h), { rw [h, eq_comm, real.angle.abs_to_real_coe_eq_self_iff], exact ⟨h0, hpi⟩ }, { rw [h, eq_comm, real.angle.abs_to_real_neg_coe_eq_self_iff], exact ⟨h0, hpi⟩ } end /-- If the sign of the oriented angle between two vectors is zero, either one of the vectors is zero or the unoriented angle is 0 or π. -/ lemma eq_zero_or_angle_eq_zero_or_pi_of_sign_oangle_eq_zero {x y : V} (h : (o.oangle x y).sign = 0) : x = 0 ∨ y = 0 ∨ inner_product_geometry.angle x y = 0 ∨ inner_product_geometry.angle x y = π := begin by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, rw o.angle_eq_abs_oangle_to_real hx hy, rw real.angle.sign_eq_zero_iff at h, rcases h with h|h; simp [h, real.pi_pos.le] end /-- If two unoriented angles are equal, and the signs of the corresponding oriented angles are equal, then the oriented angles are equal (even in degenerate cases). -/ lemma oangle_eq_of_angle_eq_of_sign_eq {w x y z : V} (h : inner_product_geometry.angle w x = inner_product_geometry.angle y z) (hs : (o.oangle w x).sign = (o.oangle y z).sign) : o.oangle w x = o.oangle y z := begin by_cases h0 : (w = 0 ∨ x = 0) ∨ (y = 0 ∨ z = 0), { have hs' : (o.oangle w x).sign = 0 ∧ (o.oangle y z).sign = 0, { rcases h0 with (rfl|rfl)|rfl|rfl, { simpa using hs.symm }, { simpa using hs.symm }, { simpa using hs }, { simpa using hs } }, rcases hs' with ⟨hswx, hsyz⟩, have h' : inner_product_geometry.angle w x = π / 2 ∧ inner_product_geometry.angle y z = π / 2, { rcases h0 with (rfl|rfl)|rfl|rfl, { simpa using h.symm }, { simpa using h.symm }, { simpa using h }, { simpa using h } }, rcases h' with ⟨hwx, hyz⟩, have hpi : π / 2 ≠ π, { intro hpi, rw [div_eq_iff, eq_comm, ←sub_eq_zero, mul_two, add_sub_cancel] at hpi, { exact real.pi_pos.ne.symm hpi }, { exact two_ne_zero } }, have h0wx : (w = 0 ∨ x = 0), { have h0' := o.eq_zero_or_angle_eq_zero_or_pi_of_sign_oangle_eq_zero hswx, simpa [hwx, real.pi_pos.ne.symm, hpi] using h0' }, have h0yz : (y = 0 ∨ z = 0), { have h0' := o.eq_zero_or_angle_eq_zero_or_pi_of_sign_oangle_eq_zero hsyz, simpa [hyz, real.pi_pos.ne.symm, hpi] using h0' }, rcases h0wx with h0wx|h0wx; rcases h0yz with h0yz|h0yz; simp [h0wx, h0yz] }, { push_neg at h0, rw real.angle.eq_iff_abs_to_real_eq_of_sign_eq hs, rwa [o.angle_eq_abs_oangle_to_real h0.1.1 h0.1.2, o.angle_eq_abs_oangle_to_real h0.2.1 h0.2.2] at h } end /-- If the signs of two oriented angles between nonzero vectors are equal, the oriented angles are equal if and only if the unoriented angles are equal. -/ lemma angle_eq_iff_oangle_eq_of_sign_eq {w x y z : V} (hw : w ≠ 0) (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) (hs : (o.oangle w x).sign = (o.oangle y z).sign) : inner_product_geometry.angle w x = inner_product_geometry.angle y z ↔ o.oangle w x = o.oangle y z := begin refine ⟨λ h, o.oangle_eq_of_angle_eq_of_sign_eq h hs, λ h, _⟩, rw [o.angle_eq_abs_oangle_to_real hw hx, o.angle_eq_abs_oangle_to_real hy hz, h] end /-- The oriented angle between two vectors equals the unoriented angle if the sign is positive. -/ lemma oangle_eq_angle_of_sign_eq_one {x y : V} (h : (o.oangle x y).sign = 1) : o.oangle x y = inner_product_geometry.angle x y := begin by_cases hx : x = 0, { exfalso, simpa [hx] using h }, by_cases hy : y = 0, { exfalso, simpa [hy] using h }, refine (o.oangle_eq_angle_or_eq_neg_angle hx hy).resolve_right _, intro hxy, rw [hxy, real.angle.sign_neg, neg_eq_iff_eq_neg, ←sign_type.neg_iff, ←not_le] at h, exact h (real.angle.sign_coe_nonneg_of_nonneg_of_le_pi (inner_product_geometry.angle_nonneg _ _) (inner_product_geometry.angle_le_pi _ _)) end /-- The oriented angle between two vectors equals minus the unoriented angle if the sign is negative. -/ lemma oangle_eq_neg_angle_of_sign_eq_neg_one {x y : V} (h : (o.oangle x y).sign = -1) : o.oangle x y = -inner_product_geometry.angle x y := begin by_cases hx : x = 0, { exfalso, simpa [hx] using h }, by_cases hy : y = 0, { exfalso, simpa [hy] using h }, refine (o.oangle_eq_angle_or_eq_neg_angle hx hy).resolve_left _, intro hxy, rw [hxy, ←sign_type.neg_iff, ←not_le] at h, exact h (real.angle.sign_coe_nonneg_of_nonneg_of_le_pi (inner_product_geometry.angle_nonneg _ _) (inner_product_geometry.angle_le_pi _ _)) end /-- The oriented angle between two nonzero vectors is zero if and only if the unoriented angle is zero. -/ lemma oangle_eq_zero_iff_angle_eq_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : o.oangle x y = 0 ↔ inner_product_geometry.angle x y = 0 := begin refine ⟨λ h, _, λ h, _⟩, { simpa [o.angle_eq_abs_oangle_to_real hx hy] }, { have ha := o.oangle_eq_angle_or_eq_neg_angle hx hy, rw h at ha, simpa using ha } end /-- The oriented angle between two vectors is `π` if and only if the unoriented angle is `π`. -/ lemma oangle_eq_pi_iff_angle_eq_pi {x y : V} : o.oangle x y = π ↔ inner_product_geometry.angle x y = π := begin by_cases hx : x = 0, { simp [hx, real.angle.pi_ne_zero.symm, div_eq_mul_inv, mul_right_eq_self₀, not_or_distrib, real.pi_ne_zero], norm_num }, by_cases hy : y = 0, { simp [hy, real.angle.pi_ne_zero.symm, div_eq_mul_inv, mul_right_eq_self₀, not_or_distrib, real.pi_ne_zero], norm_num }, refine ⟨λ h, _, λ h, _⟩, { rw [o.angle_eq_abs_oangle_to_real hx hy, h], simp [real.pi_pos.le] }, { have ha := o.oangle_eq_angle_or_eq_neg_angle hx hy, rw h at ha, simpa using ha } end /-- One of two vectors is zero or the oriented angle between them is plus or minus `π / 2` if and only if the inner product of those vectors is zero. -/ lemma eq_zero_or_oangle_eq_iff_inner_eq_zero {x y : V} : (x = 0 ∨ y = 0 ∨ o.oangle x y = (π / 2 : ℝ) ∨ o.oangle x y = (-π / 2 : ℝ)) ↔ ⟪x, y⟫ = 0 := begin by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, rw [inner_product_geometry.inner_eq_zero_iff_angle_eq_pi_div_two, or_iff_right hx, or_iff_right hy], refine ⟨λ h, _, λ h, _⟩, { rwa [o.angle_eq_abs_oangle_to_real hx hy, real.angle.abs_to_real_eq_pi_div_two_iff] }, { convert o.oangle_eq_angle_or_eq_neg_angle hx hy; rw [h], exact neg_div _ _ } end /-- If the oriented angle between two vectors is `π / 2`, the inner product of those vectors is zero. -/ lemma inner_eq_zero_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = (π / 2 : ℝ)) : ⟪x, y⟫ = 0 := o.eq_zero_or_oangle_eq_iff_inner_eq_zero.1 $ or.inr $ or.inr $ or.inl h /-- If the oriented angle between two vectors is `π / 2`, the inner product of those vectors (reversed) is zero. -/ lemma inner_rev_eq_zero_of_oangle_eq_pi_div_two {x y : V} (h : o.oangle x y = (π / 2 : ℝ)) : ⟪y, x⟫ = 0 := by rw [real_inner_comm, o.inner_eq_zero_of_oangle_eq_pi_div_two h] /-- If the oriented angle between two vectors is `-π / 2`, the inner product of those vectors is zero. -/ lemma inner_eq_zero_of_oangle_eq_neg_pi_div_two {x y : V} (h : o.oangle x y = (-π / 2 : ℝ)) : ⟪x, y⟫ = 0 := o.eq_zero_or_oangle_eq_iff_inner_eq_zero.1 $ or.inr $ or.inr $ or.inr h /-- If the oriented angle between two vectors is `-π / 2`, the inner product of those vectors (reversed) is zero. -/ lemma inner_rev_eq_zero_of_oangle_eq_neg_pi_div_two {x y : V} (h : o.oangle x y = (-π / 2 : ℝ)) : ⟪y, x⟫ = 0 := by rw [real_inner_comm, o.inner_eq_zero_of_oangle_eq_neg_pi_div_two h] /-- Negating the first vector passed to `oangle` negates the sign of the angle. -/ @[simp] lemma oangle_sign_neg_left (x y : V) : (o.oangle (-x) y).sign = -((o.oangle x y).sign) := begin by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, rw [o.oangle_neg_left hx hy, real.angle.sign_add_pi] end /-- Negating the second vector passed to `oangle` negates the sign of the angle. -/ @[simp] lemma oangle_sign_neg_right (x y : V) : (o.oangle x (-y)).sign = -((o.oangle x y).sign) := begin by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, rw [o.oangle_neg_right hx hy, real.angle.sign_add_pi] end /-- Multiplying the first vector passed to `oangle` by a real multiplies the sign of the angle by the sign of the real. -/ @[simp] lemma oangle_sign_smul_left (x y : V) (r : ℝ) : (o.oangle (r • x) y).sign = sign r * (o.oangle x y).sign := begin rcases lt_trichotomy r 0 with h|h|h; simp [h] end /-- Multiplying the second vector passed to `oangle` by a real multiplies the sign of the angle by the sign of the real. -/ @[simp] lemma oangle_sign_smul_right (x y : V) (r : ℝ) : (o.oangle x (r • y)).sign = sign r * (o.oangle x y).sign := begin rcases lt_trichotomy r 0 with h|h|h; simp [h] end /-- Auxiliary lemma for the proof of `oangle_sign_smul_add_right`; not intended to be used outside of that proof. -/ lemma oangle_smul_add_right_eq_zero_or_eq_pi_iff {x y : V} (r : ℝ) : (o.oangle x (r • x + y) = 0 ∨ o.oangle x (r • x + y) = π) ↔ (o.oangle x y = 0 ∨ o.oangle x y = π) := begin simp_rw [oangle_eq_zero_or_eq_pi_iff_not_linear_independent, fintype.not_linear_independent_iff, fin.sum_univ_two, fin.exists_fin_two], refine ⟨λ h, _, λ h, _⟩, { rcases h with ⟨m, h, hm⟩, change m 0 • x + m 1 • (r • x + y) = 0 at h, refine ⟨![m 0 + m 1 * r, m 1], _⟩, change (m 0 + m 1 * r) • x + m 1 • y = 0 ∧ (m 0 + m 1 * r ≠ 0 ∨ m 1 ≠ 0), rw [smul_add, smul_smul, ←add_assoc, ←add_smul] at h, refine ⟨h, not_and_distrib.1 (λ h0, _)⟩, obtain ⟨h0, h1⟩ := h0, rw h1 at h0 hm, rw [zero_mul, add_zero] at h0, simpa [h0] using hm }, { rcases h with ⟨m, h, hm⟩, change m 0 • x + m 1 • y = 0 at h, refine ⟨![m 0 - m 1 * r, m 1], _⟩, change (m 0 - m 1 * r) • x + m 1 • (r • x + y) = 0 ∧ (m 0 - m 1 * r ≠ 0 ∨ m 1 ≠ 0), rw [sub_smul, smul_add, smul_smul, ←add_assoc, sub_add_cancel], refine ⟨h, not_and_distrib.1 (λ h0, _)⟩, obtain ⟨h0, h1⟩ := h0, rw h1 at h0 hm, rw [zero_mul, sub_zero] at h0, simpa [h0] using hm } end /-- Adding a multiple of the first vector passed to `oangle` to the second vector does not change the sign of the angle. -/ @[simp] lemma oangle_sign_smul_add_right (x y : V) (r : ℝ) : (o.oangle x (r • x + y)).sign = (o.oangle x y).sign := begin by_cases h : o.oangle x y = 0 ∨ o.oangle x y = π, { rwa [real.angle.sign_eq_zero_iff.2 h, real.angle.sign_eq_zero_iff, oangle_smul_add_right_eq_zero_or_eq_pi_iff] }, have h' : ∀ r' : ℝ, o.oangle x (r' • x + y) ≠ 0 ∧ o.oangle x (r' • x + y) ≠ π, { intro r', rwa [←o.oangle_smul_add_right_eq_zero_or_eq_pi_iff r', not_or_distrib] at h }, let s : set (V × V) := (λ r' : ℝ, (x, r' • x + y)) '' set.univ, have hc : is_connected s := is_connected_univ.image _ ((continuous_const.prod_mk ((continuous_id.smul continuous_const).add continuous_const)).continuous_on), have hf : continuous_on (λ z : V × V, o.oangle z.1 z.2) s, { refine continuous_at.continuous_on (λ z hz, o.continuous_at_oangle _ _), all_goals { simp_rw [s, set.mem_image] at hz, obtain ⟨r', -, rfl⟩ := hz, simp only [prod.fst, prod.snd], intro hz }, { simpa [hz] using (h' 0).1 }, { simpa [hz] using (h' r').1 } }, have hs : ∀ z : V × V, z ∈ s → o.oangle z.1 z.2 ≠ 0 ∧ o.oangle z.1 z.2 ≠ π, { intros z hz, simp_rw [s, set.mem_image] at hz, obtain ⟨r', -, rfl⟩ := hz, exact h' r' }, have hx : (x, y) ∈ s, { convert set.mem_image_of_mem (λ r' : ℝ, (x, r' • x + y)) (set.mem_univ 0), simp }, have hy : (x, r • x + y) ∈ s := set.mem_image_of_mem _ (set.mem_univ _), convert real.angle.sign_eq_of_continuous_on hc hf hs hx hy end /-- Adding a multiple of the second vector passed to `oangle` to the first vector does not change the sign of the angle. -/ @[simp] lemma oangle_sign_add_smul_left (x y : V) (r : ℝ) : (o.oangle (x + r • y) y).sign = (o.oangle x y).sign := by simp_rw [o.oangle_rev y, real.angle.sign_neg, add_comm x, oangle_sign_smul_add_right] /-- Subtracting a multiple of the first vector passed to `oangle` from the second vector does not change the sign of the angle. -/ @[simp] lemma oangle_sign_sub_smul_right (x y : V) (r : ℝ) : (o.oangle x (y - r • x)).sign = (o.oangle x y).sign := by rw [sub_eq_add_neg, ←neg_smul, add_comm, oangle_sign_smul_add_right] /-- Subtracting a multiple of the second vector passed to `oangle` from the first vector does not change the sign of the angle. -/ @[simp] lemma oangle_sign_sub_smul_left (x y : V) (r : ℝ) : (o.oangle (x - r • y) y).sign = (o.oangle x y).sign := by rw [sub_eq_add_neg, ←neg_smul, oangle_sign_add_smul_left] /-- Adding the first vector passed to `oangle` to the second vector does not change the sign of the angle. -/ @[simp] lemma oangle_sign_add_right (x y : V) : (o.oangle x (x + y)).sign = (o.oangle x y).sign := by rw [←o.oangle_sign_smul_add_right x y 1, one_smul] /-- Adding the second vector passed to `oangle` to the first vector does not change the sign of the angle. -/ @[simp] lemma oangle_sign_add_left (x y : V) : (o.oangle (x + y) y).sign = (o.oangle x y).sign := by rw [←o.oangle_sign_add_smul_left x y 1, one_smul] /-- Subtracting the first vector passed to `oangle` from the second vector does not change the sign of the angle. -/ @[simp] lemma oangle_sign_sub_right (x y : V) : (o.oangle x (y - x)).sign = (o.oangle x y).sign := by rw [←o.oangle_sign_sub_smul_right x y 1, one_smul] /-- Subtracting the second vector passed to `oangle` from the first vector does not change the sign of the angle. -/ @[simp] lemma oangle_sign_sub_left (x y : V) : (o.oangle (x - y) y).sign = (o.oangle x y).sign := by rw [←o.oangle_sign_sub_smul_left x y 1, one_smul] /-- Subtracting the second vector passed to `oangle` from a multiple of the first vector negates the sign of the angle. -/ @[simp] lemma oangle_sign_smul_sub_right (x y : V) (r : ℝ) : (o.oangle x (r • x - y)).sign = -(o.oangle x y).sign := by rw [←oangle_sign_neg_right, sub_eq_add_neg, oangle_sign_smul_add_right] /-- Subtracting the first vector passed to `oangle` from a multiple of the second vector negates the sign of the angle. -/ @[simp] lemma oangle_sign_smul_sub_left (x y : V) (r : ℝ) : (o.oangle (r • y - x) y).sign = -(o.oangle x y).sign := by rw [←oangle_sign_neg_left, sub_eq_neg_add, oangle_sign_add_smul_left] /-- Subtracting the second vector passed to `oangle` from the first vector negates the sign of the angle. -/ lemma oangle_sign_sub_right_eq_neg (x y : V) : (o.oangle x (x - y)).sign = -(o.oangle x y).sign := by rw [←o.oangle_sign_smul_sub_right x y 1, one_smul] /-- Subtracting the first vector passed to `oangle` from the second vector negates the sign of the angle. -/ lemma oangle_sign_sub_left_eq_neg (x y : V) : (o.oangle (y - x) y).sign = -(o.oangle x y).sign := by rw [←o.oangle_sign_smul_sub_left x y 1, one_smul] /-- Subtracting the first vector passed to `oangle` from the second vector then swapping the vectors does not change the sign of the angle. -/ @[simp] lemma oangle_sign_sub_right_swap (x y : V) : (o.oangle y (y - x)).sign = (o.oangle x y).sign := by rw [oangle_sign_sub_right_eq_neg, o.oangle_rev y x, real.angle.sign_neg] /-- Subtracting the second vector passed to `oangle` from the first vector then swapping the vectors does not change the sign of the angle. -/ @[simp] lemma oangle_sign_sub_left_swap (x y : V) : (o.oangle (x - y) x).sign = (o.oangle x y).sign := by rw [oangle_sign_sub_left_eq_neg, o.oangle_rev y x, real.angle.sign_neg] /-- The sign of the angle between a vector, and a linear combination of that vector with a second vector, is the sign of the factor by which the second vector is multiplied in that combination multiplied by the sign of the angle between the two vectors. -/ @[simp] lemma oangle_sign_smul_add_smul_right (x y : V) (r₁ r₂ : ℝ) : (o.oangle x (r₁ • x + r₂ • y)).sign = sign r₂ * (o.oangle x y).sign := begin rw ←o.oangle_sign_smul_add_right x (r₁ • x + r₂ • y) (-r₁), simp end /-- The sign of the angle between a linear combination of two vectors and the second vector is the sign of the factor by which the first vector is multiplied in that combination multiplied by the sign of the angle between the two vectors. -/ @[simp] lemma oangle_sign_smul_add_smul_left (x y : V) (r₁ r₂ : ℝ) : (o.oangle (r₁ • x + r₂ • y) y).sign = sign r₁ * (o.oangle x y).sign := by simp_rw [o.oangle_rev y, real.angle.sign_neg, add_comm (r₁ • x), oangle_sign_smul_add_smul_right, mul_neg] /-- The sign of the angle between two linear combinations of two vectors is the sign of the determinant of the factors in those combinations multiplied by the sign of the angle between the two vectors. -/ lemma oangle_sign_smul_add_smul_smul_add_smul (x y : V) (r₁ r₂ r₃ r₄ : ℝ) : (o.oangle (r₁ • x + r₂ • y) (r₃ • x + r₄ • y)).sign = sign (r₁ * r₄ - r₂ * r₃) * (o.oangle x y).sign := begin by_cases hr₁ : r₁ = 0, { rw [hr₁, zero_smul, zero_mul, zero_add, zero_sub, left.sign_neg, oangle_sign_smul_left, add_comm, oangle_sign_smul_add_smul_right, oangle_rev, real.angle.sign_neg, sign_mul, mul_neg, mul_neg, neg_mul, mul_assoc] }, { rw [←o.oangle_sign_smul_add_right (r₁ • x + r₂ • y) (r₃ • x + r₄ • y) (-r₃ / r₁), smul_add, smul_smul, smul_smul, div_mul_cancel _ hr₁, neg_smul, ←add_assoc, add_comm (-(r₃ • x)), ←sub_eq_add_neg, sub_add_cancel, ←add_smul, oangle_sign_smul_right, oangle_sign_smul_add_smul_left, ←mul_assoc, ←sign_mul, add_mul, mul_assoc, mul_comm r₂ r₁, ←mul_assoc, div_mul_cancel _ hr₁, add_comm, neg_mul, ←sub_eq_add_neg, mul_comm r₄, mul_comm r₃] } end /-- A base angle of an isosceles triangle is acute, oriented vector angle form. -/ lemma abs_oangle_sub_left_to_real_lt_pi_div_two {x y : V} (h : ‖x‖ = ‖y‖) : |(o.oangle (y - x) y).to_real| < π / 2 := begin by_cases hn : x = y, { simp [hn, div_pos, real.pi_pos] }, have hs : ((2 : ℤ) • (o.oangle (y - x) y)).sign = (o.oangle (y - x) y).sign, { conv_rhs { rw oangle_sign_sub_left_swap }, rw [o.oangle_eq_pi_sub_two_zsmul_oangle_sub_of_norm_eq hn h, real.angle.sign_pi_sub] }, rw real.angle.sign_two_zsmul_eq_sign_iff at hs, rcases hs with hs | hs, { rw [oangle_eq_pi_iff_oangle_rev_eq_pi, oangle_eq_pi_iff_same_ray_neg, neg_sub] at hs, rcases hs with ⟨hy, -, hr⟩, rw ←exists_nonneg_left_iff_same_ray hy at hr, rcases hr with ⟨r, hr0, hr⟩, rw [eq_sub_iff_add_eq] at hr, nth_rewrite 1 ←one_smul ℝ y at hr, rw ←add_smul at hr, rw [←hr, norm_smul, real.norm_eq_abs, abs_of_pos (left.add_pos_of_nonneg_of_pos hr0 one_pos), mul_left_eq_self₀, or_iff_left (norm_ne_zero_iff.2 hy), add_left_eq_self] at h, rw [h, zero_add, one_smul] at hr, exact false.elim (hn hr.symm) }, { exact hs } end /-- A base angle of an isosceles triangle is acute, oriented vector angle form. -/ lemma abs_oangle_sub_right_to_real_lt_pi_div_two {x y : V} (h : ‖x‖ = ‖y‖) : |(o.oangle x (x - y)).to_real| < π / 2 := (o.oangle_sub_eq_oangle_sub_rev_of_norm_eq h).symm ▸ o.abs_oangle_sub_left_to_real_lt_pi_div_two h end orientation
889d386bde6f6ce0e5ac4991125c73407aba6cf9
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/category/Mon/colimits_auto.lean
6ee30278e4b4b93c4690aa5cc16ca7bba8912953
[]
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
8,475
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.category.Mon.basic import Mathlib.category_theory.limits.limits import Mathlib.category_theory.limits.concrete_category import Mathlib.PostPort universes v l u_1 namespace Mathlib /-! # The category of monoids has all colimits. We do this construction knowing nothing about monoids. In particular, I want to claim that this file could be produced by a python script that just looks at the output of `#print monoid`: -- structure monoid : Type u → Type u -- fields: -- monoid.mul : Π {α : Type u} [c : monoid α], α → α → α -- monoid.mul_assoc : ∀ {α : Type u} [c : monoid α] (a b c_1 : α), a * b * c_1 = a * (b * c_1) -- monoid.one : Π (α : Type u) [c : monoid α], α -- monoid.one_mul : ∀ {α : Type u} [c : monoid α] (a : α), 1 * a = a -- monoid.mul_one : ∀ {α : Type u} [c : monoid α] (a : α), a * 1 = a and if we'd fed it the output of `#print comm_ring`, this file would instead build colimits of commutative rings. A slightly bolder claim is that we could do this with tactics, as well. -/ namespace Mon.colimits /-! We build the colimit of a diagram in `Mon` by constructing the free monoid on the disjoint union of all the monoids in the diagram, then taking the quotient by the monoid laws within each monoid, and the identifications given by the morphisms in the diagram. -/ /-- An inductive type representing all monoid expressions (without relations) on a collection of types indexed by the objects of `J`. -/ -- There's always `of` inductive prequotient {J : Type v} [category_theory.small_category J] (F : J ⥤ Mon) where | of : (j : J) → ↥(category_theory.functor.obj F j) → prequotient F | one : prequotient F | mul : prequotient F → prequotient F → prequotient F -- Then one generator for each operation protected instance prequotient.inhabited {J : Type v} [category_theory.small_category J] (F : J ⥤ Mon) : Inhabited (prequotient F) := { default := prequotient.one } /-- The relation on `prequotient` saying when two expressions are equal because of the monoid laws, or because one element is mapped to another by a morphism in the diagram. -/ -- Make it an equivalence relation: inductive relation {J : Type v} [category_theory.small_category J] (F : J ⥤ Mon) : prequotient F → prequotient F → Prop where | refl : ∀ (x : prequotient F), relation F x x | symm : ∀ (x y : prequotient F), relation F x y → relation F y x | trans : ∀ (x y z : prequotient F), relation F x y → relation F y z → relation F x z | map : ∀ (j j' : J) (f : j ⟶ j') (x : ↥(category_theory.functor.obj F j)), relation F (prequotient.of j' (coe_fn (category_theory.functor.map F f) x)) (prequotient.of j x) | mul : ∀ (j : J) (x y : ↥(category_theory.functor.obj F j)), relation F (prequotient.of j (x * y)) (prequotient.mul (prequotient.of j x) (prequotient.of j y)) | one : ∀ (j : J), relation F (prequotient.of j 1) prequotient.one | mul_1 : ∀ (x x' y : prequotient F), relation F x x' → relation F (prequotient.mul x y) (prequotient.mul x' y) | mul_2 : ∀ (x y y' : prequotient F), relation F y y' → relation F (prequotient.mul x y) (prequotient.mul x y') | mul_assoc : ∀ (x y z : prequotient F), relation F (prequotient.mul (prequotient.mul x y) z) (prequotient.mul x (prequotient.mul y z)) | one_mul : ∀ (x : prequotient F), relation F (prequotient.mul prequotient.one x) x | mul_one : ∀ (x : prequotient F), relation F (prequotient.mul x prequotient.one) x -- There's always a `map` relation -- Then one relation per operation, describing the interaction with `of` -- Then one relation per argument of each operation -- And one relation per axiom /-- The setoid corresponding to monoid expressions modulo monoid relations and identifications. -/ instance colimit_setoid {J : Type v} [category_theory.small_category J] (F : J ⥤ Mon) : setoid (prequotient F) := setoid.mk (relation F) sorry /-- The underlying type of the colimit of a diagram in `Mon`. -/ def colimit_type {J : Type v} [category_theory.small_category J] (F : J ⥤ Mon) := quotient (colimit_setoid F) protected instance monoid_colimit_type {J : Type v} [category_theory.small_category J] (F : J ⥤ Mon) : monoid (colimit_type F) := monoid.mk (Quot.lift (fun (x : prequotient F) => Quot.lift (fun (y : prequotient F) => Quot.mk setoid.r (prequotient.mul x y)) sorry) sorry) sorry (Quot.mk setoid.r prequotient.one) sorry sorry @[simp] theorem quot_one {J : Type v} [category_theory.small_category J] (F : J ⥤ Mon) : Quot.mk setoid.r prequotient.one = 1 := rfl @[simp] theorem quot_mul {J : Type v} [category_theory.small_category J] (F : J ⥤ Mon) (x : prequotient F) (y : prequotient F) : Quot.mk setoid.r (prequotient.mul x y) = Quot.mk setoid.r x * Quot.mk setoid.r y := rfl /-- The bundled monoid giving the colimit of a diagram. -/ def colimit {J : Type v} [category_theory.small_category J] (F : J ⥤ Mon) : Mon := category_theory.bundled.mk (colimit_type F) /-- The function from a given monoid in the diagram to the colimit monoid. -/ def cocone_fun {J : Type v} [category_theory.small_category J] (F : J ⥤ Mon) (j : J) (x : ↥(category_theory.functor.obj F j)) : colimit_type F := Quot.mk setoid.r (prequotient.of j x) /-- The monoid homomorphism from a given monoid in the diagram to the colimit monoid. -/ def cocone_morphism {J : Type v} [category_theory.small_category J] (F : J ⥤ Mon) (j : J) : category_theory.functor.obj F j ⟶ colimit F := monoid_hom.mk (cocone_fun F j) sorry sorry @[simp] theorem cocone_naturality {J : Type v} [category_theory.small_category J] (F : J ⥤ Mon) {j : J} {j' : J} (f : j ⟶ j') : category_theory.functor.map F f ≫ cocone_morphism F j' = cocone_morphism F j := monoid_hom.ext fun (x : ↥(category_theory.functor.obj F j)) => quot.sound (relation.map j j' f x) @[simp] theorem cocone_naturality_components {J : Type v} [category_theory.small_category J] (F : J ⥤ Mon) (j : J) (j' : J) (f : j ⟶ j') (x : ↥(category_theory.functor.obj F j)) : coe_fn (cocone_morphism F j') (coe_fn (category_theory.functor.map F f) x) = coe_fn (cocone_morphism F j) x := sorry /-- The cocone over the proposed colimit monoid. -/ def colimit_cocone {J : Type v} [category_theory.small_category J] (F : J ⥤ Mon) : category_theory.limits.cocone F := category_theory.limits.cocone.mk (colimit F) (category_theory.nat_trans.mk (cocone_morphism F)) /-- The function from the free monoid on the diagram to the cone point of any other cocone. -/ @[simp] def desc_fun_lift {J : Type v} [category_theory.small_category J] (F : J ⥤ Mon) (s : category_theory.limits.cocone F) : prequotient F → ↥(category_theory.limits.cocone.X s) := sorry /-- The function from the colimit monoid to the cone point of any other cocone. -/ def desc_fun {J : Type v} [category_theory.small_category J] (F : J ⥤ Mon) (s : category_theory.limits.cocone F) : colimit_type F → ↥(category_theory.limits.cocone.X s) := Quot.lift (desc_fun_lift F s) sorry /-- The monoid homomorphism from the colimit monoid to the cone point of any other cocone. -/ def desc_morphism {J : Type v} [category_theory.small_category J] (F : J ⥤ Mon) (s : category_theory.limits.cocone F) : colimit F ⟶ category_theory.limits.cocone.X s := monoid_hom.mk (desc_fun F s) sorry sorry /-- Evidence that the proposed colimit is the colimit. -/ def colimit_is_colimit {J : Type v} [category_theory.small_category J] (F : J ⥤ Mon) : category_theory.limits.is_colimit (colimit_cocone F) := category_theory.limits.is_colimit.mk fun (s : category_theory.limits.cocone F) => desc_morphism F s protected instance has_colimits_Mon : category_theory.limits.has_colimits Mon := category_theory.limits.has_colimits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.has_colimits_of_shape.mk fun (F : J ⥤ Mon) => category_theory.limits.has_colimit.mk (category_theory.limits.colimit_cocone.mk (colimit_cocone F) (colimit_is_colimit F)) end Mathlib
3c0608ff5e1231cf6fb5e55c188f69c73d86ca7c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/order/group/inj_surj.lean
e26c1fe0f031d2ea5ca56481b109ee5f288363e4
[ "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,298
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Mario Carneiro, Johannes Hölzl -/ import algebra.order.group.defs import algebra.order.monoid.basic import algebra.order.group.instances /-! # Pull back ordered groups along injective maps. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ variables {α β : Type*} /-- Pullback an `ordered_comm_group` under an injective map. See note [reducible non-instances]. -/ @[reducible, to_additive function.injective.ordered_add_comm_group "Pullback an `ordered_add_comm_group` under an injective map."] def function.injective.ordered_comm_group [ordered_comm_group α] {β : Type*} [has_one β] [has_mul β] [has_inv β] [has_div β] [has_pow β ℕ] [has_pow β ℤ] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ x (n : ℤ), f (x ^ n) = f x ^ n) : ordered_comm_group β := { ..partial_order.lift f hf, ..hf.ordered_comm_monoid f one mul npow, ..hf.comm_group f one mul inv div npow zpow } /-- Pullback a `linear_ordered_comm_group` under an injective map. See note [reducible non-instances]. -/ @[reducible, to_additive function.injective.linear_ordered_add_comm_group "Pullback a `linear_ordered_add_comm_group` under an injective map."] def function.injective.linear_ordered_comm_group [linear_ordered_comm_group α] {β : Type*} [has_one β] [has_mul β] [has_inv β] [has_div β] [has_pow β ℕ] [has_pow β ℤ] [has_sup β] [has_inf β] (f : β → α) (hf : function.injective f) (one : f 1 = 1) (mul : ∀ x y, f (x * y) = f x * f y) (inv : ∀ x, f (x⁻¹) = (f x)⁻¹) (div : ∀ x y, f (x / y) = f x / f y) (npow : ∀ x (n : ℕ), f (x ^ n) = f x ^ n) (zpow : ∀ x (n : ℤ), f (x ^ n) = f x ^ n) (hsup : ∀ x y, f (x ⊔ y) = max (f x) (f y)) (hinf : ∀ x y, f (x ⊓ y) = min (f x) (f y)) : linear_ordered_comm_group β := { ..linear_order.lift f hf hsup hinf, ..hf.ordered_comm_group f one mul inv div npow zpow }
a4b8d2c332c2fce5e6248484479bb301b0684543
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/data/nat/parity.lean
ada084b20aea1ed0f74f1b19ffdc9938430bf868
[ "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,984
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Benjamin Davidson -/ import data.nat.modeq /-! # Parity of natural numbers This file contains theorems about the `even` and `odd` predicates on the natural numbers. ## Tags even, odd -/ namespace nat variables {m n : ℕ} @[simp] theorem mod_two_ne_one : ¬ n % 2 = 1 ↔ n % 2 = 0 := by cases mod_two_eq_zero_or_one n with h h; simp [h] @[simp] theorem mod_two_ne_zero : ¬ n % 2 = 0 ↔ n % 2 = 1 := by cases mod_two_eq_zero_or_one n with h h; simp [h] theorem even_iff : even n ↔ n % 2 = 0 := ⟨λ ⟨m, hm⟩, by simp [hm], λ h, ⟨n / 2, (mod_add_div n 2).symm.trans (by simp [h])⟩⟩ theorem odd_iff : odd n ↔ n % 2 = 1 := ⟨λ ⟨m, hm⟩, by norm_num [hm, add_mod], λ h, ⟨n / 2, (mod_add_div n 2).symm.trans (by rw [h, add_comm])⟩⟩ lemma not_even_iff : ¬ even n ↔ n % 2 = 1 := by rw [even_iff, mod_two_ne_zero] lemma not_odd_iff : ¬ odd n ↔ n % 2 = 0 := by rw [odd_iff, mod_two_ne_one] lemma even_iff_not_odd : even n ↔ ¬ odd n := by rw [not_odd_iff, even_iff] @[simp] lemma odd_iff_not_even : odd n ↔ ¬ even n := by rw [not_even_iff, odd_iff] lemma is_compl_even_odd : is_compl {n : ℕ | even n} {n | odd n} := by simp [← set.compl_set_of, is_compl_compl] lemma even_or_odd (n : ℕ) : even n ∨ odd n := or.imp_right odd_iff_not_even.2 $ em $ even n lemma even_or_odd' (n : ℕ) : ∃ k, n = 2 * k ∨ n = 2 * k + 1 := by simpa only [exists_or_distrib, ← odd, ← even] using even_or_odd n lemma even_xor_odd (n : ℕ) : xor (even n) (odd n) := begin cases even_or_odd n with h, { exact or.inl ⟨h, even_iff_not_odd.mp h⟩ }, { exact or.inr ⟨h, odd_iff_not_even.mp h⟩ }, end lemma even_xor_odd' (n : ℕ) : ∃ k, xor (n = 2 * k) (n = 2 * k + 1) := begin rcases even_or_odd n with ⟨k, rfl⟩ | ⟨k, rfl⟩; use k, { simpa only [xor, true_and, eq_self_iff_true, not_true, or_false, and_false] using (succ_ne_self (2*k)).symm }, { simp only [xor, add_right_eq_self, false_or, eq_self_iff_true, not_true, not_false_iff, one_ne_zero, and_self] }, end lemma odd_gt_zero (h : odd n) : 0 < n := by { obtain ⟨k, rfl⟩ := h, exact succ_pos' } @[simp] theorem two_dvd_ne_zero : ¬ 2 ∣ n ↔ n % 2 = 1 := not_even_iff instance : decidable_pred (even : ℕ → Prop) := λ n, decidable_of_decidable_of_iff (by apply_instance) even_iff.symm instance decidable_pred_odd : decidable_pred (odd : ℕ → Prop) := λ n, decidable_of_decidable_of_iff (by apply_instance) odd_iff_not_even.symm mk_simp_attribute parity_simps "Simp attribute for lemmas about `even`" @[simp] theorem even_zero : even 0 := ⟨0, dec_trivial⟩ @[simp] theorem not_even_one : ¬ even 1 := by rw even_iff; norm_num @[simp] theorem even_bit0 (n : ℕ) : even (bit0 n) := ⟨n, by rw [bit0, two_mul]⟩ @[parity_simps] theorem even_add : even (m + n) ↔ (even m ↔ even n) := by cases mod_two_eq_zero_or_one m with h₁ h₁; cases mod_two_eq_zero_or_one n with h₂ h₂; simp [even_iff, h₁, h₂, nat.add_mod]; norm_num theorem even.add_even (hm : even m) (hn : even n) : even (m + n) := even_add.2 $ iff_of_true hm hn theorem even_add' : even (m + n) ↔ (odd m ↔ odd n) := by rw [even_add, even_iff_not_odd, even_iff_not_odd, not_iff_not] theorem odd.add_odd (hm : odd m) (hn : odd n) : even (m + n) := even_add'.2 $ iff_of_true hm hn @[simp] theorem not_even_bit1 (n : ℕ) : ¬ even (bit1 n) := by simp [bit1] with parity_simps lemma two_not_dvd_two_mul_add_one (n : ℕ) : ¬(2 ∣ 2 * n + 1) := by convert not_even_bit1 n; exact two_mul n lemma two_not_dvd_two_mul_sub_one : Π {n} (w : 0 < n), ¬(2 ∣ 2 * n - 1) | (n + 1) _ := two_not_dvd_two_mul_add_one n @[parity_simps] theorem even_sub (h : n ≤ m) : even (m - n) ↔ (even m ↔ even n) := begin conv { to_rhs, rw [←tsub_add_cancel_of_le h, even_add] }, by_cases h : even n; simp [h] end theorem even.sub_even (hm : even m) (hn : even n) : even (m - n) := (le_total n m).elim (λ h, by simp only [even_sub h, *]) (λ h, by simp only [tsub_eq_zero_iff_le.mpr h, even_zero]) theorem even_sub' (h : n ≤ m) : even (m - n) ↔ (odd m ↔ odd n) := by rw [even_sub h, even_iff_not_odd, even_iff_not_odd, not_iff_not] theorem odd.sub_odd (hm : odd m) (hn : odd n) : even (m - n) := (le_total n m).elim (λ h, by simp only [even_sub' h, *]) (λ h, by simp only [tsub_eq_zero_iff_le.mpr h, even_zero]) @[parity_simps] theorem even_succ : even (succ n) ↔ ¬ even n := by rw [succ_eq_add_one, even_add]; simp [not_even_one] @[parity_simps] theorem even_mul : even (m * n) ↔ even m ∨ even n := by cases mod_two_eq_zero_or_one m with h₁ h₁; cases mod_two_eq_zero_or_one n with h₂ h₂; simp [even_iff, h₁, h₂, nat.mul_mod]; norm_num theorem odd_mul : odd (m * n) ↔ odd m ∧ odd n := by simp [not_or_distrib] with parity_simps theorem even.mul_left (hm : even m) (n) : even (m * n) := even_mul.mpr $ or.inl hm theorem even.mul_right (m) (hn : even n) : even (m * n) := even_mul.mpr $ or.inr hn theorem odd.mul (hm : odd m) (hn : odd n) : odd (m * n) := odd_mul.mpr ⟨hm, hn⟩ theorem odd.of_mul_left (h : odd (m * n)) : odd m := (odd_mul.mp h).1 theorem odd.of_mul_right (h : odd (m * n)) : odd n := (odd_mul.mp h).2 /-- If `m` and `n` are natural numbers, then the natural number `m^n` is even if and only if `m` is even and `n` is positive. -/ @[parity_simps] theorem even_pow : even (m ^ n) ↔ even m ∧ n ≠ 0 := by { induction n with n ih; simp [*, pow_succ', even_mul], tauto } theorem even_pow' (h : n ≠ 0) : even (m ^ n) ↔ even m := even_pow.trans $ and_iff_left h theorem even_div : even (m / n) ↔ m % (2 * n) / n = 0 := by rw [even_iff_two_dvd, dvd_iff_mod_eq_zero, nat.div_mod_eq_mod_mul_div, mul_comm] @[parity_simps] theorem odd_add : odd (m + n) ↔ (odd m ↔ even n) := by rw [odd_iff_not_even, even_add, not_iff, odd_iff_not_even] theorem odd.add_even (hm : odd m) (hn : even n) : odd (m + n) := odd_add.2 $ iff_of_true hm hn theorem odd_add' : odd (m + n) ↔ (odd n ↔ even m) := by rw [add_comm, odd_add] theorem even.add_odd (hm : even m) (hn : odd n) : odd (m + n) := odd_add'.2 $ iff_of_true hn hm lemma ne_of_odd_add (h : odd (m + n)) : m ≠ n := λ hnot, by simpa [hnot] with parity_simps using h @[parity_simps] theorem odd_sub (h : n ≤ m) : odd (m - n) ↔ (odd m ↔ even n) := by rw [odd_iff_not_even, even_sub h, not_iff, odd_iff_not_even] theorem odd.sub_even (h : n ≤ m) (hm : odd m) (hn : even n) : odd (m - n) := (odd_sub h).mpr $ iff_of_true hm hn theorem odd_sub' (h : n ≤ m) : odd (m - n) ↔ (odd n ↔ even m) := by rw [odd_iff_not_even, even_sub h, not_iff, not_iff_comm, odd_iff_not_even] theorem even.sub_odd (h : n ≤ m) (hm : even m) (hn : odd n) : odd (m - n) := (odd_sub' h).mpr $ iff_of_true hn hm lemma even_mul_succ_self (n : ℕ) : even (n * (n + 1)) := begin rw even_mul, convert n.even_or_odd, simp with parity_simps end variables {R : Type*} [ring R] theorem neg_one_pow_eq_one_iff_even (h1 : (-1 : R) ≠ 1) : (-1 : R) ^ n = 1 ↔ even n := ⟨λ h, n.mod_two_eq_zero_or_one.elim (dvd_iff_mod_eq_zero _ _).2 (λ hn, by rw [neg_one_pow_eq_pow_mod_two, hn, pow_one] at h; exact (h1 h).elim), λ ⟨m, hm⟩, by rw [neg_one_pow_eq_pow_mod_two, hm]; simp⟩ @[simp] theorem neg_one_sq : (-1 : R) ^ 2 = 1 := by simp alias nat.neg_one_sq ← nat.neg_one_pow_two theorem neg_one_pow_of_even : even n → (-1 : R) ^ n = 1 := by { rintro ⟨c, rfl⟩, simp [pow_mul] } theorem neg_one_pow_of_odd : odd n → (-1 : R) ^ n = -1 := by { rintro ⟨c, rfl⟩, simp [pow_add, pow_mul] } -- Here are examples of how `parity_simps` can be used with `nat`. example (m n : ℕ) (h : even m) : ¬ even (n + 3) ↔ even (m^2 + m + n) := by simp [*, (dec_trivial : ¬ 2 = 0)] with parity_simps example : ¬ even 25394535 := by simp end nat
1fb87beab15191a6986f8fbe21d476b532071273
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/list/prime.lean
277c6e3743e4ed7d3fd192f2d38ccc7c9c2a9cfb
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
3,037
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jens Wagemaker, Anne Baanen -/ import algebra.associated import data.list.big_operators.lemmas import data.list.perm /-! # Products of lists of prime elements. This file contains some theorems relating `prime` and products of `list`s. -/ open list section comm_monoid_with_zero variables {M : Type*} [comm_monoid_with_zero M] /-- Prime `p` divides the product of a list `L` iff it divides some `a ∈ L` -/ lemma prime.dvd_prod_iff {p : M} {L : list M} (pp : prime p) : p ∣ L.prod ↔ ∃ a ∈ L, p ∣ a := begin split, { intros h, induction L with L_hd L_tl L_ih, { rw prod_nil at h, exact absurd h pp.not_dvd_one }, { rw prod_cons at h, cases pp.dvd_or_dvd h with hd hd, { exact ⟨L_hd, mem_cons_self L_hd L_tl, hd⟩ }, { obtain ⟨x, hx1, hx2⟩ := L_ih hd, exact ⟨x, mem_cons_of_mem L_hd hx1, hx2⟩ } } }, { exact λ ⟨a, ha1, ha2⟩, dvd_trans ha2 (dvd_prod ha1) }, end lemma prime.not_dvd_prod {p : M} {L : list M} (pp : prime p) (hL : ∀ a ∈ L, ¬ p ∣ a) : ¬ p ∣ L.prod := mt (prime.dvd_prod_iff pp).mp $ not_bex.mpr hL end comm_monoid_with_zero section cancel_comm_monoid_with_zero variables {M : Type*} [cancel_comm_monoid_with_zero M] [unique (units M)] lemma mem_list_primes_of_dvd_prod {p : M} (hp : prime p) {L : list M} (hL : ∀ q ∈ L, prime q) (hpL : p ∣ L.prod) : p ∈ L := begin obtain ⟨x, hx1, hx2⟩ := hp.dvd_prod_iff.mp hpL, rwa (prime_dvd_prime_iff_eq hp (hL x hx1)).mp hx2 end lemma perm_of_prod_eq_prod : ∀ {l₁ l₂ : list M}, l₁.prod = l₂.prod → (∀ p ∈ l₁, prime p) → (∀ p ∈ l₂, prime p) → perm l₁ l₂ | [] [] _ _ _ := perm.nil | [] (a :: l) h₁ h₂ h₃ := have ha : a ∣ 1 := @prod_nil M _ ▸ h₁.symm ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _, absurd ha (prime.not_dvd_one (h₃ a (mem_cons_self _ _))) | (a :: l) [] h₁ h₂ h₃ := have ha : a ∣ 1 := @prod_nil M _ ▸ h₁ ▸ (@prod_cons _ _ l a).symm ▸ dvd_mul_right _ _, absurd ha (prime.not_dvd_one (h₂ a (mem_cons_self _ _))) | (a :: l₁) (b :: l₂) h hl₁ hl₂ := begin classical, have hl₁' : ∀ p ∈ l₁, prime p := λ p hp, hl₁ p (mem_cons_of_mem _ hp), have hl₂' : ∀ p ∈ (b :: l₂).erase a, prime p := λ p hp, hl₂ p (mem_of_mem_erase hp), have ha : a ∈ (b :: l₂) := mem_list_primes_of_dvd_prod (hl₁ a (mem_cons_self _ _)) hl₂ (h ▸ by rw prod_cons; exact dvd_mul_right _ _), have hb : b :: l₂ ~ a :: (b :: l₂).erase a := perm_cons_erase ha, have hl : prod l₁ = prod ((b :: l₂).erase a) := ((mul_right_inj' (hl₁ a (mem_cons_self _ _)).ne_zero).1 $ by rwa [← prod_cons, ← prod_cons, ← hb.prod_eq]), exact perm.trans ((perm_of_prod_eq_prod hl hl₁' hl₂').cons _) hb.symm end end cancel_comm_monoid_with_zero
2569bbfff392f9d4e64db676ce9f4c642691f988
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/adjunction/mates.lean
9e261a837a06e934a958697b61abfab59b8fbd89
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
11,217
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.basic import category_theory.conj /-! # Mate of natural transformations > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file establishes the bijection between the 2-cells L₁ R₁ C --→ D C ←-- D G ↓ ↗ ↓ H G ↓ ↘ ↓ H E --→ F E ←-- F L₂ R₂ where `L₁ ⊣ R₁` and `L₂ ⊣ R₂`, and shows that in the special case where `G,H` are identity then the bijection preserves and reflects isomorphisms (i.e. we have bijections `(L₂ ⟶ L₁) ≃ (R₁ ⟶ R₂)`, and if either side is an iso then the other side is as well). On its own, this bijection is not particularly useful but it includes a number of interesting cases as specializations. For instance, this generalises the fact that adjunctions are unique (since if `L₁ ≅ L₂` then we deduce `R₁ ≅ R₂`). Another example arises from considering the square representing that a functor `H` preserves products, in particular the morphism `HA ⨯ H- ⟶ H(A ⨯ -)`. Then provided `(A ⨯ -)` and `HA ⨯ -` have left adjoints (for instance if the relevant categories are cartesian closed), the transferred natural transformation is the exponential comparison morphism: `H(A ^ -) ⟶ HA ^ H-`. Furthermore if `H` has a left adjoint `L`, this morphism is an isomorphism iff its mate `L(HA ⨯ -) ⟶ A ⨯ L-` is an isomorphism, see https://ncatlab.org/nlab/show/Frobenius+reciprocity#InCategoryTheory. This also relates to Grothendieck's yoga of six operations, though this is not spelled out in mathlib: https://ncatlab.org/nlab/show/six+operations. -/ universes v₁ v₂ v₃ v₄ u₁ u₂ u₃ u₄ namespace category_theory open category variables {C : Type u₁} {D : Type u₂} [category.{v₁} C] [category.{v₂} D] section square variables {E : Type u₃} {F : Type u₄} [category.{v₃} E] [category.{v₄} F] variables {G : C ⥤ E} {H : D ⥤ F} {L₁ : C ⥤ D} {R₁ : D ⥤ C} {L₂ : E ⥤ F} {R₂ : F ⥤ E} variables (adj₁ : L₁ ⊣ R₁) (adj₂ : L₂ ⊣ R₂) include adj₁ adj₂ /-- Suppose we have a square of functors (where the top and bottom are adjunctions `L₁ ⊣ R₁` and `L₂ ⊣ R₂` respectively). C ↔ D G ↓ ↓ H E ↔ F Then we have a bijection between natural transformations `G ⋙ L₂ ⟶ L₁ ⋙ H` and `R₁ ⋙ G ⟶ H ⋙ R₂`. This can be seen as a bijection of the 2-cells: L₁ R₁ C --→ D C ←-- D G ↓ ↗ ↓ H G ↓ ↘ ↓ H E --→ F E ←-- F L₂ R₂ Note that if one of the transformations is an iso, it does not imply the other is an iso. -/ def transfer_nat_trans : (G ⋙ L₂ ⟶ L₁ ⋙ H) ≃ (R₁ ⋙ G ⟶ H ⋙ R₂) := { to_fun := λ h, { app := λ X, adj₂.unit.app _ ≫ R₂.map (h.app _ ≫ H.map (adj₁.counit.app _)), naturality' := λ X Y f, begin dsimp, rw [assoc, ← R₂.map_comp, assoc, ← H.map_comp, ← adj₁.counit_naturality, H.map_comp, ←functor.comp_map L₁, ←h.naturality_assoc], simp, end }, inv_fun := λ h, { app := λ X, L₂.map (G.map (adj₁.unit.app _) ≫ h.app _) ≫ adj₂.counit.app _, naturality' := λ X Y f, begin dsimp, rw [← L₂.map_comp_assoc, ← G.map_comp_assoc, ← adj₁.unit_naturality, G.map_comp_assoc, ← functor.comp_map, h.naturality], simp, end }, left_inv := λ h, begin ext X, dsimp, simp only [L₂.map_comp, assoc, adj₂.counit_naturality, adj₂.left_triangle_components_assoc, ←functor.comp_map G L₂, h.naturality_assoc, functor.comp_map L₁, ←H.map_comp, adj₁.left_triangle_components], dsimp, simp, -- See library note [dsimp, simp]. end, right_inv := λ h, begin ext X, dsimp, simp [-functor.comp_map, ←functor.comp_map H, functor.comp_map R₁, -nat_trans.naturality, ←h.naturality, -functor.map_comp, ←functor.map_comp_assoc G, R₂.map_comp], end } lemma transfer_nat_trans_counit (f : G ⋙ L₂ ⟶ L₁ ⋙ H) (Y : D) : L₂.map ((transfer_nat_trans adj₁ adj₂ f).app _) ≫ adj₂.counit.app _ = f.app _ ≫ H.map (adj₁.counit.app Y) := by { erw functor.map_comp, simp } lemma unit_transfer_nat_trans (f : G ⋙ L₂ ⟶ L₁ ⋙ H) (X : C) : G.map (adj₁.unit.app X) ≫ (transfer_nat_trans adj₁ adj₂ f).app _ = adj₂.unit.app _ ≫ R₂.map (f.app _) := begin dsimp [transfer_nat_trans], rw [←adj₂.unit_naturality_assoc, ←R₂.map_comp, ← functor.comp_map G L₂, f.naturality_assoc, functor.comp_map, ← H.map_comp], dsimp, simp, -- See library note [dsimp, simp] end end square section self variables {L₁ L₂ L₃ : C ⥤ D} {R₁ R₂ R₃ : D ⥤ C} variables (adj₁ : L₁ ⊣ R₁) (adj₂ : L₂ ⊣ R₂) (adj₃ : L₃ ⊣ R₃) /-- Given two adjunctions `L₁ ⊣ R₁` and `L₂ ⊣ R₂` both between categories `C`, `D`, there is a bijection between natural transformations `L₂ ⟶ L₁` and natural transformations `R₁ ⟶ R₂`. This is defined as a special case of `transfer_nat_trans`, where the two "vertical" functors are identity. TODO: Generalise to when the two vertical functors are equivalences rather than being exactly `𝟭`. Furthermore, this bijection preserves (and reflects) isomorphisms, i.e. a transformation is an iso iff its image under the bijection is an iso, see eg `category_theory.transfer_nat_trans_self_iso`. This is in contrast to the general case `transfer_nat_trans` which does not in general have this property. -/ def transfer_nat_trans_self : (L₂ ⟶ L₁) ≃ (R₁ ⟶ R₂) := calc (L₂ ⟶ L₁) ≃ _ : (iso.hom_congr L₂.left_unitor L₁.right_unitor).symm ... ≃ _ : transfer_nat_trans adj₁ adj₂ ... ≃ (R₁ ⟶ R₂) : R₁.right_unitor.hom_congr R₂.left_unitor lemma transfer_nat_trans_self_counit (f : L₂ ⟶ L₁) (X) : L₂.map ((transfer_nat_trans_self adj₁ adj₂ f).app _) ≫ adj₂.counit.app X = f.app _ ≫ adj₁.counit.app X := begin dsimp [transfer_nat_trans_self], rw [id_comp, comp_id], have := transfer_nat_trans_counit adj₁ adj₂ (L₂.left_unitor.hom ≫ f ≫ L₁.right_unitor.inv) X, dsimp at this, rw this, simp, end lemma unit_transfer_nat_trans_self (f : L₂ ⟶ L₁) (X) : adj₁.unit.app _ ≫ (transfer_nat_trans_self adj₁ adj₂ f).app _ = adj₂.unit.app X ≫ functor.map _ (f.app _) := begin dsimp [transfer_nat_trans_self], rw [id_comp, comp_id], have := unit_transfer_nat_trans adj₁ adj₂ (L₂.left_unitor.hom ≫ f ≫ L₁.right_unitor.inv) X, dsimp at this, rw this, simp end @[simp] lemma transfer_nat_trans_self_id : transfer_nat_trans_self adj₁ adj₁ (𝟙 _) = 𝟙 _ := by { ext, dsimp [transfer_nat_trans_self, transfer_nat_trans], simp } -- See library note [dsimp, simp] @[simp] lemma transfer_nat_trans_self_symm_id : (transfer_nat_trans_self adj₁ adj₁).symm (𝟙 _) = 𝟙 _ := by { rw equiv.symm_apply_eq, simp } lemma transfer_nat_trans_self_comp (f g) : transfer_nat_trans_self adj₁ adj₂ f ≫ transfer_nat_trans_self adj₂ adj₃ g = transfer_nat_trans_self adj₁ adj₃ (g ≫ f) := begin ext, dsimp [transfer_nat_trans_self, transfer_nat_trans], simp only [id_comp, comp_id], rw [←adj₃.unit_naturality_assoc, ←R₃.map_comp, g.naturality_assoc, L₂.map_comp, assoc, adj₂.counit_naturality, adj₂.left_triangle_components_assoc, assoc], end lemma transfer_nat_trans_self_adjunction_id {L R : C ⥤ C} (adj : L ⊣ R) (f : 𝟭 C ⟶ L) (X : C) : (transfer_nat_trans_self adj adjunction.id f).app X = f.app (R.obj X) ≫ adj.counit.app X := begin dsimp [transfer_nat_trans_self, transfer_nat_trans, adjunction.id], simp only [comp_id, id_comp], end lemma transfer_nat_trans_self_adjunction_id_symm {L R : C ⥤ C} (adj : L ⊣ R) (g : R ⟶ 𝟭 C) (X : C) : ((transfer_nat_trans_self adj adjunction.id).symm g).app X = adj.unit.app X ≫ (g.app (L.obj X)) := begin dsimp [transfer_nat_trans_self, transfer_nat_trans, adjunction.id], simp only [comp_id, id_comp], end lemma transfer_nat_trans_self_symm_comp (f g) : (transfer_nat_trans_self adj₂ adj₁).symm f ≫ (transfer_nat_trans_self adj₃ adj₂).symm g = (transfer_nat_trans_self adj₃ adj₁).symm (g ≫ f) := by { rw [equiv.eq_symm_apply, ← transfer_nat_trans_self_comp _ adj₂], simp } lemma transfer_nat_trans_self_comm {f g} (gf : g ≫ f = 𝟙 _) : transfer_nat_trans_self adj₁ adj₂ f ≫ transfer_nat_trans_self adj₂ adj₁ g = 𝟙 _ := by rw [transfer_nat_trans_self_comp, gf, transfer_nat_trans_self_id] lemma transfer_nat_trans_self_symm_comm {f g} (gf : g ≫ f = 𝟙 _) : (transfer_nat_trans_self adj₁ adj₂).symm f ≫ (transfer_nat_trans_self adj₂ adj₁).symm g = 𝟙 _ := by rw [transfer_nat_trans_self_symm_comp, gf, transfer_nat_trans_self_symm_id] /-- If `f` is an isomorphism, then the transferred natural transformation is an isomorphism. The converse is given in `transfer_nat_trans_self_of_iso`. -/ instance transfer_nat_trans_self_iso (f : L₂ ⟶ L₁) [is_iso f] : is_iso (transfer_nat_trans_self adj₁ adj₂ f) := ⟨⟨transfer_nat_trans_self adj₂ adj₁ (inv f), ⟨transfer_nat_trans_self_comm _ _ (by simp), transfer_nat_trans_self_comm _ _ (by simp)⟩⟩⟩ /-- If `f` is an isomorphism, then the un-transferred natural transformation is an isomorphism. The converse is given in `transfer_nat_trans_self_symm_of_iso`. -/ instance transfer_nat_trans_self_symm_iso (f : R₁ ⟶ R₂) [is_iso f] : is_iso ((transfer_nat_trans_self adj₁ adj₂).symm f) := ⟨⟨(transfer_nat_trans_self adj₂ adj₁).symm (inv f), ⟨transfer_nat_trans_self_symm_comm _ _ (by simp), transfer_nat_trans_self_symm_comm _ _ (by simp)⟩⟩⟩ /-- If `f` is a natural transformation whose transferred natural transformation is an isomorphism, then `f` is an isomorphism. The converse is given in `transfer_nat_trans_self_iso`. -/ lemma transfer_nat_trans_self_of_iso (f : L₂ ⟶ L₁) [is_iso (transfer_nat_trans_self adj₁ adj₂ f)] : is_iso f := begin suffices : is_iso ((transfer_nat_trans_self adj₁ adj₂).symm (transfer_nat_trans_self adj₁ adj₂ f)), { simpa using this }, apply_instance, end /-- If `f` is a natural transformation whose un-transferred natural transformation is an isomorphism, then `f` is an isomorphism. The converse is given in `transfer_nat_trans_self_symm_iso`. -/ lemma transfer_nat_trans_self_symm_of_iso (f : R₁ ⟶ R₂) [is_iso ((transfer_nat_trans_self adj₁ adj₂).symm f)] : is_iso f := begin suffices : is_iso ((transfer_nat_trans_self adj₁ adj₂) ((transfer_nat_trans_self adj₁ adj₂).symm f)), { simpa using this }, apply_instance, end end self end category_theory
ed8a8358a48ed27cf2a4a02a874a9a4bb4fc9ab0
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/monoidal/types/coyoneda.lean
9d1b1fa6ae7dbe78188274e54f5456f2705784fe
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,532
lean
/- Copyright (c) 2018 Michael Jendrusch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Jendrusch, Scott Morrison -/ import category_theory.monoidal.types.basic import category_theory.monoidal.coherence_lemmas /-! # `(𝟙_ C ⟶ -)` is a lax monoidal functor to `Type` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. -/ open category_theory open category_theory.limits open tactic universes v u namespace category_theory open opposite open monoidal_category /-- `(𝟙_ C ⟶ -)` is a lax monoidal functor to `Type`. -/ def coyoneda_tensor_unit (C : Type u) [category.{v} C] [monoidal_category C] : lax_monoidal_functor C (Type v) := { ε := λ p, 𝟙 _, μ := λ X Y p, (λ_ (𝟙_ C)).inv ≫ (p.1 ⊗ p.2), μ_natural' := by tidy, associativity' := λ X Y Z, begin ext ⟨⟨f, g⟩, h⟩, dsimp at f g h, dsimp, simp only [iso.cancel_iso_inv_left, category.assoc], conv_lhs { rw [←category.id_comp h, tensor_comp, category.assoc, associator_naturality, ←category.assoc, unitors_inv_equal, triangle_assoc_comp_right_inv], }, conv_rhs { rw [←category.id_comp f, tensor_comp], }, end, left_unitality' := by tidy, right_unitality' := λ X, begin ext ⟨f, ⟨⟩⟩, dsimp at f, dsimp, simp only [category.assoc], rw [right_unitor_naturality, unitors_inv_equal, iso.inv_hom_id_assoc], end, ..coyoneda.obj (op (𝟙_ C)) }. end category_theory
0c2e7b342f554d90534f7bfbc525718292e74fbc
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/control/basic_auto.lean
f3a1cf26e92f2ba649ed21c5f82042d0e4054edb
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
6,816
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 Extends the theory on functors, applicatives and monads. -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.PostPort universes u v u_1 u_2 u_3 w l namespace Mathlib theorem functor.map_map {α : Type u} {β : Type u} {γ : Type u} {f : Type u → Type v} [Functor f] [is_lawful_functor f] (m : α → β) (g : β → γ) (x : f α) : g <$> m <$> x = (g ∘ m) <$> x := Eq.symm (comp_map m g x) @[simp] theorem id_map' {α : Type u} {f : Type u → Type v} [Functor f] [is_lawful_functor f] (x : f α) : (fun (a : α) => a) <$> x = x := id_map x def mzip_with {F : Type u → Type v} [Applicative F] {α₁ : Type u} {α₂ : Type u} {φ : Type u} (f : α₁ → α₂ → F φ) (ma₁ : List α₁) (ma₂ : List α₂) : F (List φ) := sorry def mzip_with' {α : Type u} {β : Type u} {γ : Type u} {F : Type u → Type v} [Applicative F] (f : α → β → F γ) : List α → List β → F PUnit := sorry @[simp] theorem pure_id'_seq {α : Type u} {F : Type u → Type v} [Applicative F] [is_lawful_applicative F] (x : F α) : (pure fun (x : α) => x) <*> x = x := pure_id_seq x theorem seq_map_assoc {α : Type u} {β : Type u} {γ : Type u} {F : Type u → Type v} [Applicative F] [is_lawful_applicative F] (x : F (α → β)) (f : γ → α) (y : F γ) : x <*> f <$> y = (fun (m : α → β) => m ∘ f) <$> x <*> y := sorry theorem map_seq {α : Type u} {β : Type u} {γ : Type u} {F : Type u → Type v} [Applicative F] [is_lawful_applicative F] (f : β → γ) (x : F (α → β)) (y : F α) : f <$> (x <*> y) = function.comp f <$> x <*> y := sorry -- TODO: setup `functor_norm` for `monad` laws def list.mpartition {f : Type → Type} [Monad f] {α : Type} (p : α → f Bool) : List α → f (List α × List α) := sorry theorem map_bind {α : Type u} {β : Type u} {γ : Type u} {m : Type u → Type v} [Monad m] [is_lawful_monad m] (x : m α) {g : α → m β} {f : β → γ} : f <$> (x >>= g) = do let a ← x f <$> g a := sorry theorem seq_bind_eq {α : Type u} {β : Type u} {γ : Type u} {m : Type u → Type v} [Monad m] [is_lawful_monad m] (x : m α) {g : β → m γ} {f : α → β} : f <$> x >>= g = x >>= g ∘ f := sorry theorem seq_eq_bind_map {α : Type u} {β : Type u} {m : Type u → Type v} [Monad m] [is_lawful_monad m] {x : m α} {f : m (α → β)} : f <*> x = do let _x ← f _x <$> x := Eq.symm (bind_map_eq_seq f x) /-- This is the Kleisli composition -/ def fish {m : Type u_1 → Type u_2} [Monad m] {α : Sort u_3} {β : Type u_1} {γ : Type u_1} (f : α → m β) (g : β → m γ) (x : α) : m γ := f x >>= g infixl:55 " >=> " => Mathlib.fish -- >=> is already defined in the core library but it is unusable -- because of its precedence (it is defined with precedence 2) and -- because it is defined as a lambda instead of having a named -- function theorem fish_pure {m : Type u → Type v} [Monad m] [is_lawful_monad m] {α : Sort u_1} {β : Type u} (f : α → m β) : f >=> pure = f := sorry theorem fish_pipe {m : Type u → Type v} [Monad m] [is_lawful_monad m] {α : Type u} {β : Type u} (f : α → m β) : pure >=> f = f := sorry theorem fish_assoc {m : Type u → Type v} [Monad m] [is_lawful_monad m] {α : Sort u_1} {β : Type u} {γ : Type u} {φ : Type u} (f : α → m β) (g : β → m γ) (h : γ → m φ) : f >=> g >=> h = f >=> (g >=> h) := sorry def list.mmap_accumr {α : Type u} {β' : Type v} {γ' : Type v} {m' : Type v → Type w} [Monad m'] (f : α → β' → m' (β' × γ')) : β' → List α → m' (β' × List γ') := sorry def list.mmap_accuml {α : Type u} {β' : Type v} {γ' : Type v} {m' : Type v → Type w} [Monad m'] (f : β' → α → m' (β' × γ')) : β' → List α → m' (β' × List γ') := sorry theorem mjoin_map_map {m : Type u → Type u} [Monad m] [is_lawful_monad m] {α : Type u} {β : Type u} (f : α → β) (a : m (m α)) : mjoin (Functor.map f <$> a) = f <$> mjoin a := sorry theorem mjoin_map_mjoin {m : Type u → Type u} [Monad m] [is_lawful_monad m] {α : Type u} (a : m (m (m α))) : mjoin (mjoin <$> a) = mjoin (mjoin a) := sorry @[simp] theorem mjoin_map_pure {m : Type u → Type u} [Monad m] [is_lawful_monad m] {α : Type u} (a : m α) : mjoin (pure <$> a) = a := sorry @[simp] theorem mjoin_pure {m : Type u → Type u} [Monad m] [is_lawful_monad m] {α : Type u} (a : m α) : mjoin (pure a) = a := pure_bind a id def succeeds {F : Type → Type v} [alternative F] {α : Type} (x : F α) : F Bool := x $> tt <|> pure false def mtry {F : Type → Type v} [alternative F] {α : Type} (x : F α) : F Unit := x $> Unit.unit <|> pure Unit.unit @[simp] theorem guard_true {F : Type → Type v} [alternative F] {h : Decidable True} : guard True = pure Unit.unit := sorry @[simp] theorem guard_false {F : Type → Type v} [alternative F] {h : Decidable False} : guard False = failure := sorry namespace sum protected def bind {e : Type v} {α : Type u_1} {β : Type u_2} : e ⊕ α → (α → e ⊕ β) → e ⊕ β := sorry protected instance monad {e : Type v} : Monad (sum e) := sorry protected instance is_lawful_functor {e : Type v} : is_lawful_functor (sum e) := is_lawful_functor.mk (fun (α : Type u) (x : e ⊕ α) => sum.cases_on x (fun (x : e) => Eq.refl (id <$> inl x)) fun (x : α) => Eq.refl (id <$> inr x)) fun (α β γ : Type u) (g : α → β) (h : β → γ) (x : e ⊕ α) => sum.cases_on x (fun (x : e) => Eq.refl ((h ∘ g) <$> inl x)) fun (x : α) => Eq.refl ((h ∘ g) <$> inr x) protected instance is_lawful_monad {e : Type v} : is_lawful_monad (sum e) := is_lawful_monad.mk (fun (α β : Type u) (x : α) (f : α → e ⊕ β) => Eq.refl (pure x >>= f)) fun (α β γ : Type u) (x : e ⊕ α) (f : α → e ⊕ β) (g : β → e ⊕ γ) => sum.cases_on x (fun (x : e) => Eq.refl (inl x >>= f >>= g)) fun (x : α) => Eq.refl (inr x >>= f >>= g) end sum class is_comm_applicative (m : Type u_1 → Type u_2) [Applicative m] extends is_lawful_applicative m where commutative_prod : ∀ {α β : Type u_1} (a : m α) (b : m β), Prod.mk <$> a <*> b = (fun (b : β) (a : α) => (a, b)) <$> b <*> a theorem is_comm_applicative.commutative_map {m : Type u_1 → Type u_2} [Applicative m] [is_comm_applicative m] {α : Type u_1} {β : Type u_1} {γ : Type u_1} (a : m α) (b : m β) {f : α → β → γ} : f <$> a <*> b = flip f <$> b <*> a := sorry end Mathlib
79d0b5b5dae88cbfe7b2dc1a1a6aee25513d3a64
799b5de27cebaa6eaa49ff982110d59bbd6c6693
/mechanized/theorems.lean
36de657188a7b1d8ab464aa022063f7c535a3c35
[ "MIT" ]
permissive
philnguyen/soft-contract
263efdbc9ca2f35234b03f0d99233a66accda78b
13e7d99e061509f0a45605508dd1a27a51f4648e
refs/heads/master
1,625,975,131,435
1,617,775,585,000
1,617,775,704,000
17,326,137
33
7
MIT
1,613,722,535,000
1,393,714,126,000
Racket
UTF-8
Lean
false
false
3,116
lean
import definitions lemmas lemma reduction_preserves_approximation -- Symbolic state `s₁'`, in 0+ steps, -- continues to approximate the next step of any state `s₁` it currently approximates {s₁ s₂ s₁' : s} (s₁'_wellformed: s_wellformed s₁') (concrete_reduction: s₁ ~> s₂ ) (approximation : s₁ ⊑ s₁'): ∃ s₂', s₁' ~>* s₂' ∧ s₂ ⊑ s₂' := begin cases approximation with F sim_s, cases sim_s, cases ‹inst_E F E E'›, -- structural case `ev` {apply ev_reduction_preserves_approximation, repeat {assumption}}, -- structural case `rt` {apply rt_reduction_preserves_approximation, repeat {assumption}}, -- non-structural case `hv` {apply hv_reduction_preserves_approximation, repeat {assumption}} end -- Another indirect lemma proving `~>*` preserves `⊑`, just b/c Lean is weird... lemma refl_tran_reduction_preserves_approximation {s₁ s₂: s} (concrete_trace: s₁ ~>* s₂): ∀ (s₁': s) (s₁'_wellformed: s_wellformed s₁') (approximation : s₁ ⊑ s₁'), ∃ s₂', s₁' ~>* s₂' ∧ s₂ ⊑ s₂' := begin induction concrete_trace, -- Base case of length-0 trace {intros, exact ⟨s₁', ⟨rr.rfl, approximation⟩⟩}, -- Step case {intros, have first_step_simulated: ∃ s₂', s₁' ~>* s₂' ∧ s₂ ⊑ s₂', from reduction_preserves_approximation s₁'_wellformed ‹s₁ ~> s₂› approximation, exists.elim first_step_simulated (take s₂', assume ⟨steps₁, simulation₁⟩, have s₂'_wellformed: _, from reduction_preserves_wellformedness s₁'_wellformed steps₁, have result: _, from ih_1 s₂' s₂'_wellformed simulation₁, exists.elim result (take sₐ', assume ⟨steps₂, simulation₂⟩, ⟨sₐ', ⟨rr_tran steps₁ steps₂, simulation₂⟩⟩))} end theorem symbolic_discovers_blame -- Running symbolic program `e'` (by first loading it to initial state with `inj`) -- results in a blame `(blm ℓₖₙ)` on the transparent component -- if running any instantiation `e` of `e'` can do so. (e e': e) (approx: e ⊑ₑ e'): (∃ σ κ , inj e ~>* ⟨E.rt (A.blm ℓ.kn), κ , σ ⟩) → (∃ σ' κ', inj' e' ~>* ⟨E.rt (A.blm ℓ.kn), κ', σ'⟩) := assume exists_error_trace, exists.elim exists_error_trace (take σ, assume h, exists.elim h (take κ, assume concrete_error_trace, begin note symbolic_error_trace := refl_tran_reduction_preserves_approximation concrete_error_trace (inj' e') (s_wellformed.ev map_to.fnd) ⟨[], inst_s.of (inst_E.ev approx inst_ρ.mt) inst_κ.mt inst_σ.mt⟩, cases symbolic_error_trace with sₐ' h, cases h with stepsₐ approxₐ, cases approxₐ with F approx_sₐ, cases approx_sₐ with F Eₐ Eₐ' κₐ κₐ' σₐ σₐ' approx_Eₐ approx_κₐ approx_σₐ, cases approx_Eₐ, cases ‹inst_A F (A.blm ℓ.kn) A'›, exact ⟨_, _, stepsₐ⟩ end))
909113be53a4259670e45fc03ee7ae5afe824c0c
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/pkg/prv/lakefile.lean
b43c239bc39093491ba04634356b2e1156535ca6
[ "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
77
lean
import Lake open System Lake DSL package prv @[default_target] lean_lib Prv
b30359594dac89ebfcf01fcdfc76ddfeb27663bb
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/tactic/reassoc_axiom.lean
9dc5418ad51ad79e83a1d1cced620764c0bc4725
[ "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
8,050
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Simon Hudon -/ import category_theory.category /-! # Tools to reformulate category-theoretic axioms in a more associativity-friendly way ## The `reassoc` attribute The `reassoc` attribute can be applied to a lemma ```lean @[reassoc] lemma some_lemma : foo ≫ bar = baz := ... ``` and produce ```lean lemma some_lemma_assoc {Y : C} (f : X ⟶ Y) : foo ≫ bar ≫ f = baz ≫ f := ... ``` The name of the produced lemma can be specified with `@[reassoc other_lemma_name]`. If `simp` is added first, the generated lemma will also have the `simp` attribute. ## The `reassoc_axiom` command When declaring a class of categories, the axioms can be reformulated to be more amenable to manipulation in right associated expressions: ```lean class some_class (C : Type) [category C] := (foo : Π X : C, X ⟶ X) (bar : ∀ {X Y : C} (f : X ⟶ Y), foo X ≫ f = f ≫ foo Y) reassoc_axiom some_class.bar ``` Here too, the `reassoc` attribute can be used instead. It works well when combined with `simp`: ```lean attribute [simp, reassoc] some_class.bar ``` -/ namespace tactic open interactive lean.parser category_theory /-- From an expression `f ≫ g`, extract the expression representing the category instance. -/ meta def get_cat_inst : expr → tactic expr | `(@category_struct.comp _ %%struct_inst _ _ _ _ _) := pure struct_inst | _ := failed /-- (internals for `@[reassoc]`) Given a lemma of the form `f ≫ g = h`, proves a new lemma of the form `h : ∀ {W} (k), f ≫ (g ≫ k) = h ≫ k`, and returns the type and proof of this lemma. -/ meta def prove_reassoc (h : expr) : tactic (expr × expr) := do (vs,t) ← infer_type h >>= mk_local_pis, (vs',t) ← whnf t >>= mk_local_pis, let vs := vs ++ vs', (lhs,rhs) ← match_eq t, struct_inst ← get_cat_inst lhs <|> get_cat_inst rhs <|> fail "no composition found in statement", `(@has_hom.hom _ %%hom_inst %%X %%Y) ← infer_type lhs, C ← infer_type X, X' ← mk_local' `X' binder_info.implicit C, ft ← to_expr ``(@has_hom.hom _ %%hom_inst %%Y %%X'), f' ← mk_local_def `f' ft, t' ← to_expr ``(@category_struct.comp _ %%struct_inst _ _ _%%lhs %%f' = @category_struct.comp _ %%struct_inst _ _ _ %%rhs %%f'), let c' := h.mk_app vs, (_,pr) ← solve_aux t' (rewrite_target c'; reflexivity), pr ← instantiate_mvars pr, let s := simp_lemmas.mk, s ← s.add_simp ``category.assoc, s ← s.add_simp ``category.id_comp, s ← s.add_simp ``category.comp_id, (t'',pr') ← simplify s [] t', pr' ← mk_eq_mp pr' pr, t'' ← pis (vs ++ [X',f']) t'', pr' ← lambdas (vs ++ [X',f']) pr', pure (t'',pr') /-- (implementation for `@[reassoc]`) Given a declaration named `n` of the form `f ≫ g = h`, proves a new lemma named `n'` of the form `∀ {W} (k), f ≫ (g ≫ k) = h ≫ k`. -/ meta def reassoc_axiom (n : name) (n' : name := n.append_suffix "_assoc") : tactic unit := do d ← get_decl n, let ls := d.univ_params.map level.param, let c := @expr.const tt n ls, (t'',pr') ← prove_reassoc c, add_decl $ declaration.thm n' d.univ_params t'' (pure pr'), copy_attribute `simp n n' /-- The `reassoc` attribute can be applied to a lemma ```lean @[reassoc] lemma some_lemma : foo ≫ bar = baz := ... ``` to produce ```lean lemma some_lemma_assoc {Y : C} (f : X ⟶ Y) : foo ≫ bar ≫ f = baz ≫ f := ... ``` The name of the produced lemma can be specified with `@[reassoc other_lemma_name]`. If `simp` is added first, the generated lemma will also have the `simp` attribute. -/ @[user_attribute] meta def reassoc_attr : user_attribute unit (option name) := { name := `reassoc, descr := "create a companion lemma for associativity-aware rewriting", parser := optional ident, after_set := some (λ n _ _, do some n' ← reassoc_attr.get_param n | reassoc_axiom n (n.append_suffix "_assoc"), reassoc_axiom n $ n.get_prefix ++ n' ) } add_tactic_doc { name := "reassoc", category := doc_category.attr, decl_names := [`tactic.reassoc_attr], tags := ["category theory"] } /-- When declaring a class of categories, the axioms can be reformulated to be more amenable to manipulation in right associated expressions: ```lean class some_class (C : Type) [category C] := (foo : Π X : C, X ⟶ X) (bar : ∀ {X Y : C} (f : X ⟶ Y), foo X ≫ f = f ≫ foo Y) reassoc_axiom some_class.bar ``` The above will produce: ```lean lemma some_class.bar_assoc {Z : C} (g : Y ⟶ Z) : foo X ≫ f ≫ g = f ≫ foo Y ≫ g := ... ``` Here too, the `reassoc` attribute can be used instead. It works well when combined with `simp`: ```lean attribute [simp, reassoc] some_class.bar ``` -/ @[user_command] meta def reassoc_cmd (_ : parse $ tk "reassoc_axiom") : lean.parser unit := do n ← ident, of_tactic $ do n ← resolve_constant n, reassoc_axiom n add_tactic_doc { name := "reassoc_axiom", category := doc_category.cmd, decl_names := [`tactic.reassoc_cmd], tags := ["category theory"] } namespace interactive setup_tactic_parser /-- `reassoc h`, for assumption `h : x ≫ y = z`, creates a new assumption `h : ∀ {W} (f : Z ⟶ W), x ≫ y ≫ f = z ≫ f`. `reassoc! h`, does the same but deletes the initial `h` assumption. (You can also add the attribute `@[reassoc]` to lemmas to generate new declarations generalized in this way.) -/ meta def reassoc (del : parse (tk "!")?) (ns : parse ident*) : tactic unit := do ns.mmap' (λ n, do h ← get_local n, (t,pr) ← prove_reassoc h, assertv n t pr, when del.is_some (tactic.clear h) ) end interactive def calculated_Prop {α} (β : Prop) (hh : α) := β meta def derive_reassoc_proof : tactic unit := do `(calculated_Prop %%v %%h) ← target, (t,pr) ← prove_reassoc h, unify v t, exact pr end tactic /-- With `h : x ≫ y ≫ z = x` (with universal quantifiers tolerated), `reassoc_of h : ∀ {X'} (f : W ⟶ X'), x ≫ y ≫ z ≫ f = x ≫ f`. The type and proof of `reassoc_of h` is generated by `tactic.derive_reassoc_proof` which make `reassoc_of` meta-programming adjacent. It is not called as a tactic but as an expression. The goal is to avoid creating assumptions that are dismissed after one use: ```lean example (X Y Z W : C) (x : X ⟶ Y) (y : Y ⟶ Z) (z z' : Z ⟶ W) (w : X ⟶ Z) (h : x ≫ y = w) (h' : y ≫ z = y ≫ z') : x ≫ y ≫ z = w ≫ z' := begin rw [h',reassoc_of h], end ``` --- `reassoc_of h` takes local assumption `h` and add a ` ≫ f` term on the right of both sides of the equality. Instead of creating a new assumption from the result, `reassoc_of h` stands for the proof of that reassociated statement. This keeps complicated assumptions that are used only once or twice from polluting the local context. In the following, assumption `h` is needed in a reassociated form. Instead of proving it as a new goal and adding it as an assumption, we use `reassoc_of h` as a rewrite rule which works just as well. ```lean example (X Y Z W : C) (x : X ⟶ Y) (y : Y ⟶ Z) (z z' : Z ⟶ W) (w : X ⟶ Z) (h : x ≫ y = w) (h' : y ≫ z = y ≫ z') : x ≫ y ≫ z = w ≫ z' := begin -- reassoc_of h : ∀ {X' : C} (f : W ⟶ X'), x ≫ y ≫ f = w ≫ f rw [h',reassoc_of h], end ``` Although `reassoc_of` is not a tactic or a meta program, its type is generated through meta-programming to make it usable inside normal expressions. -/ theorem category_theory.reassoc_of {α} (hh : α) {β} (x : tactic.calculated_Prop β hh . tactic.derive_reassoc_proof) : β := x add_tactic_doc { name := "category_theory.reassoc_of", category := doc_category.tactic, decl_names := [`category_theory.reassoc_of], tags := ["category theory"] }
dfd8e22909e636c3e9367188e9cdae90b4a29e15
a4673261e60b025e2c8c825dfa4ab9108246c32e
/stage0/src/Lean/PrettyPrinter.lean
d44e3f4393ac4b533bd89f166a1177643172dd9e
[ "Apache-2.0" ]
permissive
jcommelin/lean4
c02dec0cc32c4bccab009285475f265f17d73228
2909313475588cc20ac0436e55548a4502050d0a
refs/heads/master
1,674,129,550,893
1,606,415,348,000
1,606,415,348,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,359
lean
/- Copyright (c) 2020 Sebastian Ullrich. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import Lean.Delaborator import Lean.PrettyPrinter.Parenthesizer import Lean.PrettyPrinter.Formatter import Lean.Parser.Module import Lean.ParserCompiler namespace Lean def PPContext.runCoreM {α : Type} (ppCtx : PPContext) (x : CoreM α) : IO α := Prod.fst <$> x.toIO { options := ppCtx.opts, currNamespace := ppCtx.currNamespace, openDecls := ppCtx.openDecls } { env := ppCtx.env } def PPContext.runMetaM {α : Type} (ppCtx : PPContext) (x : MetaM α) : IO α := ppCtx.runCoreM <| x.run' { lctx := ppCtx.lctx } { mctx := ppCtx.mctx } namespace PrettyPrinter def ppTerm (stx : Syntax) : CoreM Format := do let opts ← getOptions let stx := (sanitizeSyntax stx).run' { options := opts } parenthesizeTerm stx >>= formatTerm def ppExpr (currNamespace : Name) (openDecls : List OpenDecl) (e : Expr) : MetaM Format := do let lctx ← getLCtx let opts ← getOptions let lctx := lctx.sanitizeNames.run' { options := opts } Meta.withLCtx lctx #[] do let stx ← delab currNamespace openDecls e ppTerm stx @[export lean_pp_expr] def ppExprLegacy (env : Environment) (mctx : MetavarContext) (lctx : LocalContext) (opts : Options) (e : Expr) : IO Format := Prod.fst <$> ((ppExpr Name.anonymous [] e).run' { lctx := lctx } { mctx := mctx }).toIO { options := opts } { env := env } def ppCommand (stx : Syntax) : CoreM Format := parenthesizeCommand stx >>= formatCommand def ppModule (stx : Syntax) : CoreM Format := do parenthesize Lean.Parser.Module.module.parenthesizer stx >>= format Lean.Parser.Module.module.formatter private partial def noContext : MessageData → MessageData | MessageData.withContext ctx msg => noContext msg | MessageData.withNamingContext ctx msg => MessageData.withNamingContext ctx (noContext msg) | MessageData.nest n msg => MessageData.nest n (noContext msg) | MessageData.group msg => MessageData.group (noContext msg) | MessageData.compose msg₁ msg₂ => MessageData.compose (noContext msg₁) (noContext msg₂) | MessageData.tagged tag msg => MessageData.tagged tag (noContext msg) | MessageData.node msgs => MessageData.node (msgs.map noContext) | msg => msg -- strip context (including environments with registered pretty printers) to prevent infinite recursion when pretty printing pretty printer error private def withoutContext {m} [MonadExcept Exception m] (x : m Format) : m Format := tryCatch x fun | Exception.error ref msg => throw $ Exception.error ref (noContext msg) | ex => throw ex builtin_initialize ppFnsRef.set { ppExpr := fun ctx e => ctx.runMetaM $ withoutContext $ ppExpr ctx.currNamespace ctx.openDecls e, ppTerm := fun ctx stx => ctx.runCoreM $ withoutContext $ ppTerm stx, ppGoal := fun ctx mvarId => ctx.runMetaM $ withoutContext $ Meta.ppGoal mvarId } builtin_initialize registerTraceClass `PrettyPrinter @[builtinInit] unsafe def registerParserCompilers : IO Unit := do ParserCompiler.registerParserCompiler ⟨`parenthesizer, parenthesizerAttribute, combinatorParenthesizerAttribute⟩ ParserCompiler.registerParserCompiler ⟨`formatter, formatterAttribute, combinatorFormatterAttribute⟩ end PrettyPrinter end Lean
cf66bdf474d2655e42373b80a9a80a1825b6239f
5ca7b1b12d14c4742e29366312ba2c2ef8201b21
/src/game/world10/level6.lean
b2ab8338a40dfdf71830dfff2496b1723e548ec2
[ "Apache-2.0" ]
permissive
MatthiasHu/natural_number_game
2e464482ef3001863430b0336133b6697b275ba3
2d764f72669ae30861f6a1057fce0257f3e466c4
refs/heads/master
1,609,719,110,419
1,576,345,737,000
1,576,345,737,000
240,296,314
0
0
Apache-2.0
1,581,608,357,000
1,581,608,356,000
null
UTF-8
Lean
false
false
844
lean
import game.world10.level5 -- hide namespace mynat -- hide /- # Inequality world. ## Level 6: `le_antisymm` In Advanced Addition World you proved `eq_zero_of_add_right_eq_self (a b : mynat) : a + b = a → b = 0`. This might be useful in this level. -/ /- Lemma ≤ is antisymmetric. In other words, if a ≤ b and b ≤ a then a = b. -/ theorem le_antisymm (a b : mynat) (hab : a ≤ b) (hba : b ≤ a) : a = b := begin [nat_num_game] cases hab with c hc, cases hba with d hd, rw hc at hd, rw add_assoc at hd, symmetry at hd, have h := eq_zero_of_add_right_eq_self _ _ hd, have h2 := add_right_eq_zero _ _ h, rw h2 at hc, rw hc, exact add_zero a, end /- Congratulations -- you just proved that the natural numbers are a partial order! -/ instance : partial_order mynat := by structure_helper end mynat -- hide
6b9278d53a2eea4b1c284345decbe17093e2a04d
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/eq20.lean
390eff2273718646a34e4551d1f1309022e0e62a
[ "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
775
lean
import data.list open nat list section parameter {A : Type} parameter (p : A → Prop) parameter [H : decidable_pred p] include H definition filter : list A → list A | filter nil := nil | filter (a :: l) := if p a then a :: filter l else filter l theorem filter_nil : filter nil = nil := rfl theorem filter_cons (a : A) (l : list A) : filter (a :: l) = if p a then a :: filter l else filter l := rfl open eq.ops theorem filter_cons_of_pos {a : A} (l : list A) (h : p a) : filter (a :: l) = a :: filter l := if_pos h ▸ filter_cons a l theorem filter_cons_of_neg {a : A} (l : list A) (h : ¬ p a) : filter (a :: l) = filter l := if_neg h ▸ filter_cons a l end check @filter check @filter_cons_of_pos check @filter_cons_of_neg
9e2a74a264dee630500c5e9fa48059607347d5c0
4727251e0cd73359b15b664c3170e5d754078599
/src/ring_theory/polynomial/cyclotomic/basic.lean
1aea80bb1b45f8d661f93b37a5bb540838d79cb5
[ "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
48,104
lean
/- Copyright (c) 2020 Riccardo Brasca. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Riccardo Brasca -/ import algebra.polynomial.big_operators import analysis.complex.roots_of_unity import data.polynomial.lifts import field_theory.separable import field_theory.splitting_field import number_theory.arithmetic_function import ring_theory.roots_of_unity import field_theory.ratfunc import algebra.ne_zero /-! # Cyclotomic polynomials. For `n : ℕ` and an integral domain `R`, we define a modified version of the `n`-th cyclotomic polynomial with coefficients in `R`, denoted `cyclotomic' n R`, as `∏ (X - μ)`, where `μ` varies over the primitive `n`th roots of unity. If there is a primitive `n`th root of unity in `R` then this the standard definition. We then define the standard cyclotomic polynomial `cyclotomic n R` with coefficients in any ring `R`. ## Main definition * `cyclotomic n R` : the `n`-th cyclotomic polynomial with coefficients in `R`. ## Main results * `int_coeff_of_cycl` : If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K` comes from a polynomial with integer coefficients. * `deg_of_cyclotomic` : The degree of `cyclotomic n` is `totient n`. * `prod_cyclotomic_eq_X_pow_sub_one` : `X ^ n - 1 = ∏ (cyclotomic i)`, where `i` divides `n`. * `cyclotomic_eq_prod_X_pow_sub_one_pow_moebius` : The Möbius inversion formula for `cyclotomic n R` over an abstract fraction field for `polynomial R`. * `cyclotomic.irreducible` : `cyclotomic n ℤ` is irreducible. ## Implementation details Our definition of `cyclotomic' n R` makes sense in any integral domain `R`, but the interesting results hold if there is a primitive `n`-th root of unity in `R`. In particular, our definition is not the standard one unless there is a primitive `n`th root of unity in `R`. For example, `cyclotomic' 3 ℤ = 1`, since there are no primitive cube roots of unity in `ℤ`. The main example is `R = ℂ`, we decided to work in general since the difficulties are essentially the same. To get the standard cyclotomic polynomials, we use `int_coeff_of_cycl`, with `R = ℂ`, to get a polynomial with integer coefficients and then we map it to `polynomial R`, for any ring `R`. To prove `cyclotomic.irreducible`, the irreducibility of `cyclotomic n ℤ`, we show in `cyclotomic_eq_minpoly` that `cyclotomic n ℤ` is the minimal polynomial of any `n`-th primitive root of unity `μ : K`, where `K` is a field of characteristic `0`. -/ open_locale classical big_operators polynomial noncomputable theory universe u namespace polynomial section cyclotomic' section is_domain variables {R : Type*} [comm_ring R] [is_domain R] /-- The modified `n`-th cyclotomic polynomial with coefficients in `R`, it is the usual cyclotomic polynomial if there is a primitive `n`-th root of unity in `R`. -/ def cyclotomic' (n : ℕ) (R : Type*) [comm_ring R] [is_domain R] : R[X] := ∏ μ in primitive_roots n R, (X - C μ) /-- The zeroth modified cyclotomic polyomial is `1`. -/ @[simp] lemma cyclotomic'_zero (R : Type*) [comm_ring R] [is_domain R] : cyclotomic' 0 R = 1 := by simp only [cyclotomic', finset.prod_empty, is_primitive_root.primitive_roots_zero] /-- The first modified cyclotomic polyomial is `X - 1`. -/ @[simp] lemma cyclotomic'_one (R : Type*) [comm_ring R] [is_domain R] : cyclotomic' 1 R = X - 1 := begin simp only [cyclotomic', finset.prod_singleton, ring_hom.map_one, is_primitive_root.primitive_roots_one] end /-- The second modified cyclotomic polyomial is `X + 1` if the characteristic of `R` is not `2`. -/ @[simp] lemma cyclotomic'_two (R : Type*) [comm_ring R] [is_domain R] (p : ℕ) [char_p R p] (hp : p ≠ 2) : cyclotomic' 2 R = X + 1 := begin rw [cyclotomic'], have prim_root_two : primitive_roots 2 R = {(-1 : R)}, { apply finset.eq_singleton_iff_unique_mem.2, split, { simp only [is_primitive_root.neg_one p hp, nat.succ_pos', mem_primitive_roots] }, { intros x hx, rw [mem_primitive_roots zero_lt_two] at hx, exact is_primitive_root.eq_neg_one_of_two_right hx } }, simp only [prim_root_two, finset.prod_singleton, ring_hom.map_neg, ring_hom.map_one, sub_neg_eq_add] end /-- `cyclotomic' n R` is monic. -/ lemma cyclotomic'.monic (n : ℕ) (R : Type*) [comm_ring R] [is_domain R] : (cyclotomic' n R).monic := monic_prod_of_monic _ _ $ λ z hz, monic_X_sub_C _ /-- `cyclotomic' n R` is different from `0`. -/ lemma cyclotomic'_ne_zero (n : ℕ) (R : Type*) [comm_ring R] [is_domain R] : cyclotomic' n R ≠ 0 := (cyclotomic'.monic n R).ne_zero /-- The natural degree of `cyclotomic' n R` is `totient n` if there is a primitive root of unity in `R`. -/ lemma nat_degree_cyclotomic' {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (cyclotomic' n R).nat_degree = nat.totient n := begin rw [cyclotomic'], rw nat_degree_prod (primitive_roots n R) (λ (z : R), (X - C z)), simp only [is_primitive_root.card_primitive_roots h, mul_one, nat_degree_X_sub_C, nat.cast_id, finset.sum_const, nsmul_eq_mul], intros z hz, exact X_sub_C_ne_zero z end /-- The degree of `cyclotomic' n R` is `totient n` if there is a primitive root of unity in `R`. -/ lemma degree_cyclotomic' {ζ : R} {n : ℕ} (h : is_primitive_root ζ n) : (cyclotomic' n R).degree = nat.totient n := by simp only [degree_eq_nat_degree (cyclotomic'_ne_zero n R), nat_degree_cyclotomic' h] /-- The roots of `cyclotomic' n R` are the primitive `n`-th roots of unity. -/ lemma roots_of_cyclotomic (n : ℕ) (R : Type*) [comm_ring R] [is_domain R] : (cyclotomic' n R).roots = (primitive_roots n R).val := by { rw cyclotomic', exact roots_prod_X_sub_C (primitive_roots n R) } /-- If there is a primitive `n`th root of unity in `K`, then `X ^ n - 1 = ∏ (X - μ)`, where `μ` varies over the `n`-th roots of unity. -/ lemma X_pow_sub_one_eq_prod {ζ : R} {n : ℕ} (hpos : 0 < n) (h : is_primitive_root ζ n) : X ^ n - 1 = ∏ ζ in nth_roots_finset n R, (X - C ζ) := begin rw [nth_roots_finset, ← multiset.to_finset_eq (is_primitive_root.nth_roots_nodup h)], simp only [finset.prod_mk, ring_hom.map_one], rw [nth_roots], have hmonic : (X ^ n - C (1 : R)).monic := monic_X_pow_sub_C (1 : R) (ne_of_lt hpos).symm, symmetry, apply prod_multiset_X_sub_C_of_monic_of_roots_card_eq hmonic, rw [@nat_degree_X_pow_sub_C R _ _ n 1, ← nth_roots], exact is_primitive_root.card_nth_roots h end end is_domain section field variables {K : Type*} [field K] /-- `cyclotomic' n K` splits. -/ lemma cyclotomic'_splits (n : ℕ) : splits (ring_hom.id K) (cyclotomic' n K) := begin apply splits_prod (ring_hom.id K), intros z hz, simp only [splits_X_sub_C (ring_hom.id K)] end /-- If there is a primitive `n`-th root of unity in `K`, then `X ^ n - 1`splits. -/ lemma X_pow_sub_one_splits {ζ : K} {n : ℕ} (h : is_primitive_root ζ n) : splits (ring_hom.id K) (X ^ n - C (1 : K)) := by rw [splits_iff_card_roots, ← nth_roots, is_primitive_root.card_nth_roots h, nat_degree_X_pow_sub_C] /-- If there is a primitive `n`-th root of unity in `K`, then `∏ i in nat.divisors n, cyclotomic' i K = X ^ n - 1`. -/ lemma prod_cyclotomic'_eq_X_pow_sub_one {K : Type*} [comm_ring K] [is_domain K] {ζ : K} {n : ℕ} (hpos : 0 < n) (h : is_primitive_root ζ n) : ∏ i in nat.divisors n, cyclotomic' i K = X ^ n - 1 := begin rw [X_pow_sub_one_eq_prod hpos h], have rwcyc : ∀ i ∈ nat.divisors n, cyclotomic' i K = ∏ μ in primitive_roots i K, (X - C μ), { intros i hi, simp only [cyclotomic'] }, conv_lhs { apply_congr, skip, simp [rwcyc, H] }, rw ← finset.prod_bUnion, { simp only [is_primitive_root.nth_roots_one_eq_bUnion_primitive_roots h] }, intros x hx y hy hdiff, exact is_primitive_root.disjoint hdiff, end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K = (X ^ k - 1) /ₘ (∏ i in nat.proper_divisors k, cyclotomic' i K)`. -/ lemma cyclotomic'_eq_X_pow_sub_one_div {K : Type*} [comm_ring K] [is_domain K] {ζ : K} {n : ℕ} (hpos : 0 < n) (h : is_primitive_root ζ n) : cyclotomic' n K = (X ^ n - 1) /ₘ (∏ i in nat.proper_divisors n, cyclotomic' i K) := begin rw [←prod_cyclotomic'_eq_X_pow_sub_one hpos h, nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem], have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic' i K).monic, { apply monic_prod_of_monic, intros i hi, exact cyclotomic'.monic i K }, rw (div_mod_by_monic_unique (cyclotomic' n K) 0 prod_monic _).1, simp only [degree_zero, zero_add], refine ⟨by rw mul_comm, _⟩, rw [bot_lt_iff_ne_bot], intro h, exact monic.ne_zero prod_monic (degree_eq_bot.1 h) end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic' n K` comes from a monic polynomial with integer coefficients. -/ lemma int_coeff_of_cyclotomic' {K : Type*} [comm_ring K] [is_domain K] {ζ : K} {n : ℕ} (h : is_primitive_root ζ n) : (∃ (P : ℤ[X]), map (int.cast_ring_hom K) P = cyclotomic' n K ∧ P.degree = (cyclotomic' n K).degree ∧ P.monic) := begin refine lifts_and_degree_eq_and_monic _ (cyclotomic'.monic n K), induction n using nat.strong_induction_on with k hk generalizing ζ h, cases nat.eq_zero_or_pos k with hzero hpos, { use 1, simp only [hzero, cyclotomic'_zero, set.mem_univ, subsemiring.coe_top, eq_self_iff_true, coe_map_ring_hom, polynomial.map_one, and_self] }, let B : K[X] := ∏ i in nat.proper_divisors k, cyclotomic' i K, have Bmo : B.monic, { apply monic_prod_of_monic, intros i hi, exact (cyclotomic'.monic i K) }, have Bint : B ∈ lifts (int.cast_ring_hom K), { refine subsemiring.prod_mem (lifts (int.cast_ring_hom K)) _, intros x hx, have xsmall := (nat.mem_proper_divisors.1 hx).2, obtain ⟨d, hd⟩ := (nat.mem_proper_divisors.1 hx).1, rw [mul_comm] at hd, exact hk x xsmall (is_primitive_root.pow hpos h hd) }, replace Bint := lifts_and_degree_eq_and_monic Bint Bmo, obtain ⟨B₁, hB₁, hB₁deg, hB₁mo⟩ := Bint, let Q₁ : ℤ[X] := (X ^ k - 1) /ₘ B₁, have huniq : 0 + B * cyclotomic' k K = X ^ k - 1 ∧ (0 : K[X]).degree < B.degree, { split, { rw [zero_add, mul_comm, ←(prod_cyclotomic'_eq_X_pow_sub_one hpos h), nat.divisors_eq_proper_divisors_insert_self_of_pos hpos], simp only [true_and, finset.prod_insert, not_lt, nat.mem_proper_divisors, dvd_refl] }, rw [degree_zero, bot_lt_iff_ne_bot], intro habs, exact (monic.ne_zero Bmo) (degree_eq_bot.1 habs) }, replace huniq := div_mod_by_monic_unique (cyclotomic' k K) (0 : K[X]) Bmo huniq, simp only [lifts, ring_hom.mem_srange], use Q₁, rw [coe_map_ring_hom, (map_div_by_monic (int.cast_ring_hom K) hB₁mo), hB₁, ← huniq.1], simp end /-- If `K` is of characteristic `0` and there is a primitive `n`-th root of unity in `K`, then `cyclotomic n K` comes from a unique polynomial with integer coefficients. -/ lemma unique_int_coeff_of_cycl {K : Type*} [comm_ring K] [is_domain K] [char_zero K] {ζ : K} {n : ℕ+} (h : is_primitive_root ζ n) : (∃! (P : ℤ[X]), map (int.cast_ring_hom K) P = cyclotomic' n K) := begin obtain ⟨P, hP⟩ := int_coeff_of_cyclotomic' h, refine ⟨P, hP.1, λ Q hQ, _⟩, apply (map_injective (int.cast_ring_hom K) int.cast_injective), rw [hP.1, hQ] end end field end cyclotomic' section cyclotomic /-- The `n`-th cyclotomic polynomial with coefficients in `R`. -/ def cyclotomic (n : ℕ) (R : Type*) [ring R] : R[X] := if h : n = 0 then 1 else map (int.cast_ring_hom R) ((int_coeff_of_cyclotomic' (complex.is_primitive_root_exp n h)).some) lemma int_cyclotomic_rw {n : ℕ} (h : n ≠ 0) : cyclotomic n ℤ = (int_coeff_of_cyclotomic' (complex.is_primitive_root_exp n h)).some := begin simp only [cyclotomic, h, dif_neg, not_false_iff], ext i, simp only [coeff_map, int.cast_id, ring_hom.eq_int_cast] end /-- `cyclotomic n R` comes from `cyclotomic n ℤ`. -/ lemma map_cyclotomic_int (n : ℕ) (R : Type*) [ring R] : map (int.cast_ring_hom R) (cyclotomic n ℤ) = cyclotomic n R := begin by_cases hzero : n = 0, { simp only [hzero, cyclotomic, dif_pos, polynomial.map_one] }, simp only [cyclotomic, int_cyclotomic_rw, hzero, ne.def, dif_neg, not_false_iff] end lemma int_cyclotomic_spec (n : ℕ) : map (int.cast_ring_hom ℂ) (cyclotomic n ℤ) = cyclotomic' n ℂ ∧ (cyclotomic n ℤ).degree = (cyclotomic' n ℂ).degree ∧ (cyclotomic n ℤ).monic := begin by_cases hzero : n = 0, { simp only [hzero, cyclotomic, degree_one, monic_one, cyclotomic'_zero, dif_pos, eq_self_iff_true, polynomial.map_one, and_self] }, rw int_cyclotomic_rw hzero, exact (int_coeff_of_cyclotomic' (complex.is_primitive_root_exp n hzero)).some_spec end lemma int_cyclotomic_unique {n : ℕ} {P : ℤ[X]} (h : map (int.cast_ring_hom ℂ) P = cyclotomic' n ℂ) : P = cyclotomic n ℤ := begin apply map_injective (int.cast_ring_hom ℂ) int.cast_injective, rw [h, (int_cyclotomic_spec n).1] end /-- The definition of `cyclotomic n R` commutes with any ring homomorphism. -/ @[simp] lemma map_cyclotomic (n : ℕ) {R S : Type*} [ring R] [ring S] (f : R →+* S) : map f (cyclotomic n R) = cyclotomic n S := begin rw [←map_cyclotomic_int n R, ←map_cyclotomic_int n S], ext i, simp only [coeff_map, ring_hom.eq_int_cast, ring_hom.map_int_cast] end lemma cyclotomic.eval_apply {R S : Type*} (q : R) (n : ℕ) [ring R] [ring S] (f : R →+* S) : eval (f q) (cyclotomic n S) = f (eval q (cyclotomic n R)) := by rw [← map_cyclotomic n f, eval_map, eval₂_at_apply] /-- The zeroth cyclotomic polyomial is `1`. -/ @[simp] lemma cyclotomic_zero (R : Type*) [ring R] : cyclotomic 0 R = 1 := by simp only [cyclotomic, dif_pos] /-- The first cyclotomic polyomial is `X - 1`. -/ @[simp] lemma cyclotomic_one (R : Type*) [ring R] : cyclotomic 1 R = X - 1 := begin have hspec : map (int.cast_ring_hom ℂ) (X - 1) = cyclotomic' 1 ℂ, { simp only [cyclotomic'_one, pnat.one_coe, map_X, polynomial.map_one, polynomial.map_sub] }, symmetry, rw [←map_cyclotomic_int, ←(int_cyclotomic_unique hspec)], simp only [map_X, polynomial.map_one, polynomial.map_sub] end /-- The second cyclotomic polyomial is `X + 1`. -/ @[simp] lemma cyclotomic_two (R : Type*) [ring R] : cyclotomic 2 R = X + 1 := begin have hspec : map (int.cast_ring_hom ℂ) (X + 1) = cyclotomic' 2 ℂ, { simp only [cyclotomic'_two ℂ 0 two_ne_zero.symm, polynomial.map_add, map_X, polynomial.map_one], }, symmetry, rw [←map_cyclotomic_int, ←(int_cyclotomic_unique hspec)], simp only [polynomial.map_add, map_X, polynomial.map_one] end /-- `cyclotomic n` is monic. -/ lemma cyclotomic.monic (n : ℕ) (R : Type*) [ring R] : (cyclotomic n R).monic := begin rw ←map_cyclotomic_int, exact (int_cyclotomic_spec n).2.2.map _, end /-- `cyclotomic n` is primitive. -/ lemma cyclotomic.is_primitive (n : ℕ) (R : Type*) [comm_ring R] : (cyclotomic n R).is_primitive := (cyclotomic.monic n R).is_primitive /-- `cyclotomic n R` is different from `0`. -/ lemma cyclotomic_ne_zero (n : ℕ) (R : Type*) [ring R] [nontrivial R] : cyclotomic n R ≠ 0 := (cyclotomic.monic n R).ne_zero /-- The degree of `cyclotomic n` is `totient n`. -/ lemma degree_cyclotomic (n : ℕ) (R : Type*) [ring R] [nontrivial R] : (cyclotomic n R).degree = nat.totient n := begin rw ←map_cyclotomic_int, rw degree_map_eq_of_leading_coeff_ne_zero (int.cast_ring_hom R) _, { cases n with k, { simp only [cyclotomic, degree_one, dif_pos, nat.totient_zero, with_top.coe_zero]}, rw [←degree_cyclotomic' (complex.is_primitive_root_exp k.succ (nat.succ_ne_zero k))], exact (int_cyclotomic_spec k.succ).2.1 }, simp only [(int_cyclotomic_spec n).right.right, ring_hom.eq_int_cast, monic.leading_coeff, int.cast_one, ne.def, not_false_iff, one_ne_zero] end /-- The natural degree of `cyclotomic n` is `totient n`. -/ lemma nat_degree_cyclotomic (n : ℕ) (R : Type*) [ring R] [nontrivial R] : (cyclotomic n R).nat_degree = nat.totient n := begin have hdeg := degree_cyclotomic n R, rw degree_eq_nat_degree (cyclotomic_ne_zero n R) at hdeg, exact_mod_cast hdeg end /-- The degree of `cyclotomic n R` is positive. -/ lemma degree_cyclotomic_pos (n : ℕ) (R : Type*) (hpos : 0 < n) [ring R] [nontrivial R] : 0 < (cyclotomic n R).degree := by { rw degree_cyclotomic n R, exact_mod_cast (nat.totient_pos hpos) } /-- `∏ i in nat.divisors n, cyclotomic i R = X ^ n - 1`. -/ lemma prod_cyclotomic_eq_X_pow_sub_one {n : ℕ} (hpos : 0 < n) (R : Type*) [comm_ring R] : ∏ i in nat.divisors n, cyclotomic i R = X ^ n - 1 := begin have integer : ∏ i in nat.divisors n, cyclotomic i ℤ = X ^ n - 1, { apply map_injective (int.cast_ring_hom ℂ) int.cast_injective, rw polynomial.map_prod (int.cast_ring_hom ℂ) (λ i, cyclotomic i ℤ), simp only [int_cyclotomic_spec, polynomial.map_pow, nat.cast_id, map_X, polynomial.map_one, polynomial.map_sub], exact prod_cyclotomic'_eq_X_pow_sub_one hpos (complex.is_primitive_root_exp n (ne_of_lt hpos).symm) }, have coerc : X ^ n - 1 = map (int.cast_ring_hom R) (X ^ n - 1), { simp only [polynomial.map_pow, polynomial.map_X, polynomial.map_one, polynomial.map_sub] }, have h : ∀ i ∈ n.divisors, cyclotomic i R = map (int.cast_ring_hom R) (cyclotomic i ℤ), { intros i hi, exact (map_cyclotomic_int i R).symm }, rw [finset.prod_congr (refl n.divisors) h, coerc, ← polynomial.map_prod (int.cast_ring_hom R) (λ i, cyclotomic i ℤ), integer] end lemma cyclotomic.dvd_X_pow_sub_one (n : ℕ) (R : Type*) [comm_ring R] : (cyclotomic n R) ∣ X ^ n - 1 := begin rcases n.eq_zero_or_pos with rfl | hn, { simp }, refine ⟨∏ i in n.proper_divisors, cyclotomic i R, _⟩, rw [←prod_cyclotomic_eq_X_pow_sub_one hn, nat.divisors_eq_proper_divisors_insert_self_of_pos hn, finset.prod_insert], exact nat.proper_divisors.not_self_mem end lemma prod_cyclotomic_eq_geom_sum {n : ℕ} (h : 0 < n) (R) [comm_ring R] [is_domain R] : ∏ i in n.divisors \ {1}, cyclotomic i R = geom_sum X n := begin apply_fun (* cyclotomic 1 R) using mul_left_injective₀ (cyclotomic_ne_zero 1 R), have : ∏ i in {1}, cyclotomic i R = cyclotomic 1 R := finset.prod_singleton, simp_rw [←this, finset.prod_sdiff $ show {1} ⊆ n.divisors, by simp [h.ne'], this, cyclotomic_one, geom_sum_mul, prod_cyclotomic_eq_X_pow_sub_one h] end lemma cyclotomic_dvd_geom_sum_of_dvd (R) [comm_ring R] {d n : ℕ} (hdn : d ∣ n) (hd : d ≠ 1) : cyclotomic d R ∣ geom_sum X n := begin suffices : (cyclotomic d ℤ).map (int.cast_ring_hom R) ∣ (geom_sum X n).map (int.cast_ring_hom R), { have key := (map_ring_hom (int.cast_ring_hom R)).map_geom_sum X n, simp only [coe_map_ring_hom, map_X] at key, rwa [map_cyclotomic, key] at this }, apply map_dvd, rcases n.eq_zero_or_pos with rfl | hn, { simp }, rw ←prod_cyclotomic_eq_geom_sum hn, apply finset.dvd_prod_of_mem, simp [hd, hdn, hn.ne'] end lemma X_pow_sub_one_mul_prod_cyclotomic_eq_X_pow_sub_one_of_dvd (R) [comm_ring R] {d n : ℕ} (h : d ∈ n.proper_divisors) : (X ^ d - 1) * ∏ x in n.divisors \ d.divisors, cyclotomic x R = X ^ n - 1 := begin obtain ⟨hd, hdn⟩ := nat.mem_proper_divisors.mp h, have h0n := pos_of_gt hdn, rcases d.eq_zero_or_pos with rfl | h0d, { exfalso, linarith [eq_zero_of_zero_dvd hd] }, rw [←prod_cyclotomic_eq_X_pow_sub_one h0d, ←prod_cyclotomic_eq_X_pow_sub_one h0n, mul_comm, finset.prod_sdiff (nat.divisors_subset_of_dvd h0n.ne' hd)] end lemma X_pow_sub_one_mul_cyclotomic_dvd_X_pow_sub_one_of_dvd (R) [comm_ring R] {d n : ℕ} (h : d ∈ n.proper_divisors) : (X ^ d - 1) * cyclotomic n R ∣ X ^ n - 1 := begin have hdn := (nat.mem_proper_divisors.mp h).2, use ∏ x in n.proper_divisors \ d.divisors, cyclotomic x R, symmetry, convert X_pow_sub_one_mul_prod_cyclotomic_eq_X_pow_sub_one_of_dvd R h using 1, rw mul_assoc, congr' 1, rw [nat.divisors_eq_proper_divisors_insert_self_of_pos $ pos_of_gt hdn, finset.insert_sdiff_of_not_mem, finset.prod_insert], { exact finset.not_mem_sdiff_of_not_mem_left nat.proper_divisors.not_self_mem }, { exact λ hk, hdn.not_le $ nat.divisor_le hk } end lemma _root_.is_root_of_unity_iff {n : ℕ} (h : 0 < n) (R : Type*) [comm_ring R] [is_domain R] {ζ : R} : ζ ^ n = 1 ↔ ∃ i ∈ n.divisors, (cyclotomic i R).is_root ζ := by rw [←mem_nth_roots h, nth_roots, mem_roots $ X_pow_sub_C_ne_zero h _, C_1, ←prod_cyclotomic_eq_X_pow_sub_one h, is_root_prod]; apply_instance lemma is_root_of_unity_of_root_cyclotomic {n : ℕ} {R} [comm_ring R] {ζ : R} {i : ℕ} (hi : i ∈ n.divisors) (h : (cyclotomic i R).is_root ζ) : ζ ^ n = 1 := begin rcases n.eq_zero_or_pos with rfl | hn, { exact pow_zero _ }, have := congr_arg (eval ζ) (prod_cyclotomic_eq_X_pow_sub_one hn R).symm, rw [eval_sub, eval_pow, eval_X, eval_one] at this, convert eq_add_of_sub_eq' this, convert (add_zero _).symm, apply eval_eq_zero_of_dvd_of_eval_eq_zero _ h, exact finset.dvd_prod_of_mem _ hi end section arithmetic_function open nat.arithmetic_function open_locale arithmetic_function /-- `cyclotomic n R` can be expressed as a product in a fraction field of `polynomial R` using Möbius inversion. -/ lemma cyclotomic_eq_prod_X_pow_sub_one_pow_moebius {n : ℕ} (R : Type*) [comm_ring R] [is_domain R] : algebra_map _ (ratfunc R) (cyclotomic n R) = ∏ i in n.divisors_antidiagonal, (algebra_map R[X] _ (X ^ i.snd - 1)) ^ μ i.fst := begin rcases n.eq_zero_or_pos with rfl | hpos, { simp }, have h : ∀ (n : ℕ), 0 < n → ∏ i in nat.divisors n, algebra_map _ (ratfunc R) (cyclotomic i R) = algebra_map _ _ (X ^ n - 1), { intros n hn, rw [← prod_cyclotomic_eq_X_pow_sub_one hn R, ring_hom.map_prod] }, rw (prod_eq_iff_prod_pow_moebius_eq_of_nonzero (λ n hn, _) (λ n hn, _)).1 h n hpos; rw [ne.def, is_fraction_ring.to_map_eq_zero_iff], { apply cyclotomic_ne_zero }, { apply monic.ne_zero, apply monic_X_pow_sub_C _ (ne_of_gt hn) } end end arithmetic_function /-- We have `cyclotomic n R = (X ^ k - 1) /ₘ (∏ i in nat.proper_divisors k, cyclotomic i K)`. -/ lemma cyclotomic_eq_X_pow_sub_one_div {R : Type*} [comm_ring R] {n : ℕ} (hpos: 0 < n) : cyclotomic n R = (X ^ n - 1) /ₘ (∏ i in nat.proper_divisors n, cyclotomic i R) := begin nontriviality R, rw [←prod_cyclotomic_eq_X_pow_sub_one hpos, nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem], have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic i R).monic, { apply monic_prod_of_monic, intros i hi, exact cyclotomic.monic i R }, rw (div_mod_by_monic_unique (cyclotomic n R) 0 prod_monic _).1, simp only [degree_zero, zero_add], split, { rw mul_comm }, rw [bot_lt_iff_ne_bot], intro h, exact monic.ne_zero prod_monic (degree_eq_bot.1 h) end /-- If `m` is a proper divisor of `n`, then `X ^ m - 1` divides `∏ i in nat.proper_divisors n, cyclotomic i R`. -/ lemma X_pow_sub_one_dvd_prod_cyclotomic (R : Type*) [comm_ring R] {n m : ℕ} (hpos : 0 < n) (hm : m ∣ n) (hdiff : m ≠ n) : X ^ m - 1 ∣ ∏ i in nat.proper_divisors n, cyclotomic i R := begin replace hm := nat.mem_proper_divisors.2 ⟨hm, lt_of_le_of_ne (nat.divisor_le (nat.mem_divisors.2 ⟨hm, (ne_of_lt hpos).symm⟩)) hdiff⟩, rw [← finset.sdiff_union_of_subset (nat.divisors_subset_proper_divisors (ne_of_lt hpos).symm (nat.mem_proper_divisors.1 hm).1 (ne_of_lt (nat.mem_proper_divisors.1 hm).2)), finset.prod_union finset.sdiff_disjoint, prod_cyclotomic_eq_X_pow_sub_one (nat.pos_of_mem_proper_divisors hm)], exact ⟨(∏ (x : ℕ) in n.proper_divisors \ m.divisors, cyclotomic x R), by rw mul_comm⟩ end /-- If there is a primitive `n`-th root of unity in `K`, then `cyclotomic n K = ∏ μ in primitive_roots n R, (X - C μ)`. In particular, `cyclotomic n K = cyclotomic' n K` -/ lemma cyclotomic_eq_prod_X_sub_primitive_roots {K : Type*} [comm_ring K] [is_domain K] {ζ : K} {n : ℕ} (hz : is_primitive_root ζ n) : cyclotomic n K = ∏ μ in primitive_roots n K, (X - C μ) := begin rw ←cyclotomic', induction n using nat.strong_induction_on with k hk generalizing ζ hz, obtain hzero | hpos := k.eq_zero_or_pos, { simp only [hzero, cyclotomic'_zero, cyclotomic_zero] }, have h : ∀ i ∈ k.proper_divisors, cyclotomic i K = cyclotomic' i K, { intros i hi, obtain ⟨d, hd⟩ := (nat.mem_proper_divisors.1 hi).1, rw mul_comm at hd, exact hk i (nat.mem_proper_divisors.1 hi).2 (is_primitive_root.pow hpos hz hd) }, rw [@cyclotomic_eq_X_pow_sub_one_div _ _ _ hpos, cyclotomic'_eq_X_pow_sub_one_div hpos hz, finset.prod_congr (refl k.proper_divisors) h] end section roots variables {R : Type*} {n : ℕ} [comm_ring R] [is_domain R] /-- Any `n`-th primitive root of unity is a root of `cyclotomic n K`.-/ lemma _root_.is_primitive_root.is_root_cyclotomic (hpos : 0 < n) {μ : R} (h : is_primitive_root μ n) : is_root (cyclotomic n R) μ := begin rw [← mem_roots (cyclotomic_ne_zero n R), cyclotomic_eq_prod_X_sub_primitive_roots h, roots_prod_X_sub_C, ← finset.mem_def], rwa [← mem_primitive_roots hpos] at h, end private lemma is_root_cyclotomic_iff' {n : ℕ} {K : Type*} [field K] {μ : K} [ne_zero (n : K)] : is_root (cyclotomic n K) μ ↔ is_primitive_root μ n := begin -- in this proof, `o` stands for `order_of μ` have hnpos : 0 < n := (ne_zero.of_ne_zero_coe K).out.bot_lt, refine ⟨λ hμ, _, is_primitive_root.is_root_cyclotomic hnpos⟩, have hμn : μ ^ n = 1, { rw is_root_of_unity_iff hnpos, exact ⟨n, n.mem_divisors_self hnpos.ne', hμ⟩ }, by_contra hnμ, have ho : 0 < order_of μ, { apply order_of_pos', rw is_of_fin_order_iff_pow_eq_one, exact ⟨n, hnpos, hμn⟩ }, have := pow_order_of_eq_one μ, rw is_root_of_unity_iff ho at this, obtain ⟨i, hio, hiμ⟩ := this, replace hio := nat.dvd_of_mem_divisors hio, rw is_primitive_root.not_iff at hnμ, rw ←order_of_dvd_iff_pow_eq_one at hμn, have key : i < n := (nat.le_of_dvd ho hio).trans_lt ((nat.le_of_dvd hnpos hμn).lt_of_ne hnμ), have key' : i ∣ n := hio.trans hμn, rw ←polynomial.dvd_iff_is_root at hμ hiμ, have hni : {i, n} ⊆ n.divisors, { simpa [finset.insert_subset, key'] using hnpos.ne' }, obtain ⟨k, hk⟩ := hiμ, obtain ⟨j, hj⟩ := hμ, have := prod_cyclotomic_eq_X_pow_sub_one hnpos K, rw [←finset.prod_sdiff hni, finset.prod_pair key.ne, hk, hj] at this, have hn := (X_pow_sub_one_separable_iff.mpr $ ne_zero.ne' n K).squarefree, rw [←this, squarefree] at hn, contrapose! hn, refine ⟨X - C μ, ⟨(∏ x in n.divisors \ {i, n}, cyclotomic x K) * k * j, by ring⟩, _⟩, simp [polynomial.is_unit_iff_degree_eq_zero] end lemma is_root_cyclotomic_iff [ne_zero (n : R)] {μ : R} : is_root (cyclotomic n R) μ ↔ is_primitive_root μ n := begin have hf : function.injective _ := is_fraction_ring.injective R (fraction_ring R), haveI : ne_zero (n : fraction_ring R) := ne_zero.nat_of_injective hf, rw [←is_root_map_iff hf, ←is_primitive_root.map_iff_of_injective hf, map_cyclotomic, ←is_root_cyclotomic_iff'] end lemma roots_cyclotomic_nodup [ne_zero (n : R)] : (cyclotomic n R).roots.nodup := begin obtain h | ⟨ζ, hζ⟩ := (cyclotomic n R).roots.empty_or_exists_mem, { exact h.symm ▸ multiset.nodup_zero }, rw [mem_roots $ cyclotomic_ne_zero n R, is_root_cyclotomic_iff] at hζ, refine multiset.nodup_of_le (roots.le_of_dvd (X_pow_sub_C_ne_zero (ne_zero.pos_of_ne_zero_coe R) 1) $ cyclotomic.dvd_X_pow_sub_one n R) hζ.nth_roots_nodup, end lemma cyclotomic.roots_to_finset_eq_primitive_roots [ne_zero (n : R)] : (⟨(cyclotomic n R).roots, roots_cyclotomic_nodup⟩ : finset _) = primitive_roots n R := by { ext, simp [cyclotomic_ne_zero n R, is_root_cyclotomic_iff, mem_primitive_roots, ne_zero.pos_of_ne_zero_coe R] } lemma cyclotomic.roots_eq_primitive_roots_val [ne_zero (n : R)] : (cyclotomic n R).roots = (primitive_roots n R).val := by rw ←cyclotomic.roots_to_finset_eq_primitive_roots end roots /-- If `R` is of characteristic zero, then `ζ` is a root of `cyclotomic n R` if and only if it is a primitive `n`-th root of unity. -/ lemma is_root_cyclotomic_iff_char_zero {n : ℕ} {R : Type*} [comm_ring R] [is_domain R] [char_zero R] {μ : R} (hn : 0 < n) : (polynomial.cyclotomic n R).is_root μ ↔ is_primitive_root μ n := by { letI := ne_zero.of_gt hn, exact is_root_cyclotomic_iff } /-- Over a ring `R` of characteristic zero, `λ n, cyclotomic n R` is injective. -/ lemma cyclotomic_injective {R : Type*} [comm_ring R] [char_zero R] : function.injective (λ n, cyclotomic n R) := begin intros n m hnm, simp only at hnm, rcases eq_or_ne n 0 with rfl | hzero, { rw [cyclotomic_zero] at hnm, replace hnm := congr_arg nat_degree hnm, rw [nat_degree_one, nat_degree_cyclotomic] at hnm, by_contra, exact (nat.totient_pos (zero_lt_iff.2 (ne.symm h))).ne hnm }, { haveI := ne_zero.mk hzero, rw [← map_cyclotomic_int _ R, ← map_cyclotomic_int _ R] at hnm, replace hnm := map_injective (int.cast_ring_hom R) int.cast_injective hnm, replace hnm := congr_arg (map (int.cast_ring_hom ℂ)) hnm, rw [map_cyclotomic_int, map_cyclotomic_int] at hnm, have hprim := complex.is_primitive_root_exp _ hzero, have hroot := is_root_cyclotomic_iff.2 hprim, rw hnm at hroot, haveI hmzero : ne_zero m := ⟨λ h, by simpa [h] using hroot⟩, rw is_root_cyclotomic_iff at hroot, replace hprim := hprim.eq_order_of, rwa [← is_primitive_root.eq_order_of hroot] at hprim} end lemma eq_cyclotomic_iff {R : Type*} [comm_ring R] {n : ℕ} (hpos: 0 < n) (P : R[X]) : P = cyclotomic n R ↔ P * (∏ i in nat.proper_divisors n, polynomial.cyclotomic i R) = X ^ n - 1 := begin nontriviality R, refine ⟨λ hcycl, _, λ hP, _⟩, { rw [hcycl, ← finset.prod_insert (@nat.proper_divisors.not_self_mem n), ← nat.divisors_eq_proper_divisors_insert_self_of_pos hpos], exact prod_cyclotomic_eq_X_pow_sub_one hpos R }, { have prod_monic : (∏ i in nat.proper_divisors n, cyclotomic i R).monic, { apply monic_prod_of_monic, intros i hi, exact cyclotomic.monic i R }, rw [@cyclotomic_eq_X_pow_sub_one_div R _ _ hpos, (div_mod_by_monic_unique P 0 prod_monic _).1], refine ⟨by rwa [zero_add, mul_comm], _⟩, rw [degree_zero, bot_lt_iff_ne_bot], intro h, exact monic.ne_zero prod_monic (degree_eq_bot.1 h) }, end /-- If `p` is prime, then `cyclotomic p R = geom_sum X p`. -/ lemma cyclotomic_eq_geom_sum {R : Type*} [comm_ring R] {p : ℕ} (hp : nat.prime p) : cyclotomic p R = geom_sum X p := begin refine ((eq_cyclotomic_iff hp.pos _).mpr _).symm, simp only [nat.prime.proper_divisors hp, geom_sum_mul, finset.prod_singleton, cyclotomic_one], end lemma cyclotomic_prime_mul_X_sub_one (R : Type*) [comm_ring R] (p : ℕ) [hn : fact (nat.prime p)] : (cyclotomic p R) * (X - 1) = X ^ p - 1 := by rw [cyclotomic_eq_geom_sum hn.out, geom_sum_mul] /-- If `p ^ k` is a prime power, then `cyclotomic (p ^ (n + 1)) R = geom_sum (X ^ p ^ n) p`. -/ lemma cyclotomic_prime_pow_eq_geom_sum {R : Type*} [comm_ring R] {p n : ℕ} (hp : nat.prime p) : cyclotomic (p ^ (n + 1)) R = geom_sum (X ^ p ^ n) p := begin have : ∀ m, cyclotomic (p ^ (m + 1)) R = geom_sum (X ^ (p ^ m)) p ↔ geom_sum (X ^ p ^ m) p * ∏ (x : ℕ) in finset.range (m + 1), cyclotomic (p ^ x) R = X ^ p ^ (m + 1) - 1, { intro m, have := eq_cyclotomic_iff (pow_pos hp.pos (m + 1)) _, rw eq_comm at this, rw [this, nat.prod_proper_divisors_prime_pow hp], }, induction n with n_n n_ih, { simp [cyclotomic_eq_geom_sum hp], }, rw ((eq_cyclotomic_iff (pow_pos hp.pos (n_n.succ + 1)) _).mpr _).symm, rw [nat.prod_proper_divisors_prime_pow hp, finset.prod_range_succ, n_ih], rw this at n_ih, rw [mul_comm _ (geom_sum _ _), n_ih, geom_sum_mul, sub_left_inj, ← pow_mul, pow_add, pow_one], end lemma cyclotomic_prime_pow_mul_X_pow_sub_one (R : Type*) [comm_ring R] (p k : ℕ) [hn : fact (nat.prime p)] : (cyclotomic (p ^ (k + 1)) R) * (X ^ (p ^ k) - 1) = X ^ (p ^ (k + 1)) - 1 := by rw [cyclotomic_prime_pow_eq_geom_sum hn.out, geom_sum_mul, ← pow_mul, pow_succ, mul_comm] /-- The constant term of `cyclotomic n R` is `1` if `2 ≤ n`. -/ lemma cyclotomic_coeff_zero (R : Type*) [comm_ring R] {n : ℕ} (hn : 2 ≤ n) : (cyclotomic n R).coeff 0 = 1 := begin induction n using nat.strong_induction_on with n hi, have hprod : (∏ i in nat.proper_divisors n, (polynomial.cyclotomic i R).coeff 0) = -1, { rw [←finset.insert_erase (nat.one_mem_proper_divisors_iff_one_lt.2 (lt_of_lt_of_le one_lt_two hn)), finset.prod_insert (finset.not_mem_erase 1 _), cyclotomic_one R], have hleq : ∀ j ∈ n.proper_divisors.erase 1, 2 ≤ j, { intros j hj, apply nat.succ_le_of_lt, exact (ne.le_iff_lt ((finset.mem_erase.1 hj).1).symm).mp (nat.succ_le_of_lt (nat.pos_of_mem_proper_divisors (finset.mem_erase.1 hj).2)) }, have hcongr : ∀ j ∈ n.proper_divisors.erase 1, (cyclotomic j R).coeff 0 = 1, { intros j hj, exact hi j (nat.mem_proper_divisors.1 (finset.mem_erase.1 hj).2).2 (hleq j hj) }, have hrw : ∏ (x : ℕ) in n.proper_divisors.erase 1, (cyclotomic x R).coeff 0 = 1, { rw finset.prod_congr (refl (n.proper_divisors.erase 1)) hcongr, simp only [finset.prod_const_one] }, simp only [hrw, mul_one, zero_sub, coeff_one_zero, coeff_X_zero, coeff_sub] }, have heq : (X ^ n - 1).coeff 0 = -(cyclotomic n R).coeff 0, { rw [←prod_cyclotomic_eq_X_pow_sub_one (lt_of_lt_of_le zero_lt_two hn), nat.divisors_eq_proper_divisors_insert_self_of_pos (lt_of_lt_of_le zero_lt_two hn), finset.prod_insert nat.proper_divisors.not_self_mem, mul_coeff_zero, coeff_zero_prod, hprod, mul_neg, mul_one] }, have hzero : (X ^ n - 1).coeff 0 = (-1 : R), { rw coeff_zero_eq_eval_zero _, simp only [zero_pow (lt_of_lt_of_le zero_lt_two hn), eval_X, eval_one, zero_sub, eval_pow, eval_sub] }, rw hzero at heq, exact neg_inj.mp (eq.symm heq) end /-- If `(a : ℕ)` is a root of `cyclotomic n (zmod p)`, where `p` is a prime, then `a` and `p` are coprime. -/ lemma coprime_of_root_cyclotomic {n : ℕ} (hpos : 0 < n) {p : ℕ} [hprime : fact p.prime] {a : ℕ} (hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) : a.coprime p := begin apply nat.coprime.symm, rw [hprime.1.coprime_iff_not_dvd], intro h, replace h := (zmod.nat_coe_zmod_eq_zero_iff_dvd a p).2 h, rw [is_root.def, eq_nat_cast, h, ← coeff_zero_eq_eval_zero] at hroot, by_cases hone : n = 1, { simp only [hone, cyclotomic_one, zero_sub, coeff_one_zero, coeff_X_zero, neg_eq_zero, one_ne_zero, coeff_sub] at hroot, exact hroot }, rw [cyclotomic_coeff_zero (zmod p) (nat.succ_le_of_lt (lt_of_le_of_ne (nat.succ_le_of_lt hpos) (ne.symm hone)))] at hroot, exact one_ne_zero hroot end end cyclotomic section order /-- If `(a : ℕ)` is a root of `cyclotomic n (zmod p)`, then the multiplicative order of `a` modulo `p` divides `n`. -/ lemma order_of_root_cyclotomic_dvd {n : ℕ} (hpos : 0 < n) {p : ℕ} [fact p.prime] {a : ℕ} (hroot : is_root (cyclotomic n (zmod p)) (nat.cast_ring_hom (zmod p) a)) : order_of (zmod.unit_of_coprime a (coprime_of_root_cyclotomic hpos hroot)) ∣ n := begin apply order_of_dvd_of_pow_eq_one, suffices hpow : eval (nat.cast_ring_hom (zmod p) a) (X ^ n - 1 : (zmod p)[X]) = 0, { simp only [eval_X, eval_one, eval_pow, eval_sub, eq_nat_cast] at hpow, apply units.coe_eq_one.1, simp only [sub_eq_zero.mp hpow, zmod.coe_unit_of_coprime, units.coe_pow] }, rw [is_root.def] at hroot, rw [← prod_cyclotomic_eq_X_pow_sub_one hpos (zmod p), nat.divisors_eq_proper_divisors_insert_self_of_pos hpos, finset.prod_insert nat.proper_divisors.not_self_mem, eval_mul, hroot, zero_mul] end end order section minpoly open is_primitive_root complex /-- The minimal polynomial of a primitive `n`-th root of unity `μ` divides `cyclotomic n ℤ`. -/ lemma _root_.is_primitive_root.minpoly_dvd_cyclotomic {n : ℕ} {K : Type*} [field K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n) [char_zero K] : minpoly ℤ μ ∣ cyclotomic n ℤ := begin apply minpoly.gcd_domain_dvd ℚ (is_integral h hpos) (cyclotomic.monic n ℤ).is_primitive, simpa [aeval_def, eval₂_eq_eval_map, is_root.def] using is_root_cyclotomic hpos h end lemma _root_.is_primitive_root.minpoly_eq_cyclotomic_of_irreducible {K : Type*} [field K] {R : Type*} [comm_ring R] [is_domain R] {μ : R} {n : ℕ} [algebra K R] (hμ : is_primitive_root μ n) (h : irreducible $ cyclotomic n K) [ne_zero (n : K)] : cyclotomic n K = minpoly K μ := begin haveI := ne_zero.of_no_zero_smul_divisors K R n, refine minpoly.eq_of_irreducible_of_monic h _ (cyclotomic.monic n K), rwa [aeval_def, eval₂_eq_eval_map, map_cyclotomic, ←is_root.def, is_root_cyclotomic_iff] end /-- `cyclotomic n ℤ` is the minimal polynomial of a primitive `n`-th root of unity `μ`. -/ lemma cyclotomic_eq_minpoly {n : ℕ} {K : Type*} [field K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n) [char_zero K] : cyclotomic n ℤ = minpoly ℤ μ := begin refine eq_of_monic_of_dvd_of_nat_degree_le (minpoly.monic (is_integral h hpos)) (cyclotomic.monic n ℤ) (h.minpoly_dvd_cyclotomic hpos) _, simpa [nat_degree_cyclotomic n ℤ] using totient_le_degree_minpoly h end /-- `cyclotomic n ℚ` is the minimal polynomial of a primitive `n`-th root of unity `μ`. -/ lemma cyclotomic_eq_minpoly_rat {n : ℕ} {K : Type*} [field K] {μ : K} (h : is_primitive_root μ n) (hpos : 0 < n) [char_zero K] : cyclotomic n ℚ = minpoly ℚ μ := begin rw [← map_cyclotomic_int, cyclotomic_eq_minpoly h hpos], exact (minpoly.gcd_domain_eq_field_fractions _ (is_integral h hpos)).symm end /-- `cyclotomic n ℤ` is irreducible. -/ lemma cyclotomic.irreducible {n : ℕ} (hpos : 0 < n) : irreducible (cyclotomic n ℤ) := begin rw [cyclotomic_eq_minpoly (is_primitive_root_exp n hpos.ne') hpos], apply minpoly.irreducible, exact (is_primitive_root_exp n hpos.ne').is_integral hpos, end /-- `cyclotomic n ℚ` is irreducible. -/ lemma cyclotomic.irreducible_rat {n : ℕ} (hpos : 0 < n) : irreducible (cyclotomic n ℚ) := begin rw [← map_cyclotomic_int], exact (is_primitive.int.irreducible_iff_irreducible_map_cast (cyclotomic.is_primitive n ℤ)).1 (cyclotomic.irreducible hpos), end /-- If `n ≠ m`, then `(cyclotomic n ℚ)` and `(cyclotomic m ℚ)` are coprime. -/ lemma cyclotomic.is_coprime_rat {n m : ℕ} (h : n ≠ m) : is_coprime (cyclotomic n ℚ) (cyclotomic m ℚ) := begin rcases n.eq_zero_or_pos with rfl | hnzero, { exact is_coprime_one_left }, rcases m.eq_zero_or_pos with rfl | hmzero, { exact is_coprime_one_right }, rw (irreducible.coprime_iff_not_dvd $ cyclotomic.irreducible_rat $ hnzero), exact (λ hdiv, h $ cyclotomic_injective $ eq_of_monic_of_associated (cyclotomic.monic n ℚ) (cyclotomic.monic m ℚ) $ irreducible.associated_of_dvd (cyclotomic.irreducible_rat hnzero) (cyclotomic.irreducible_rat hmzero) hdiv), end end minpoly section expand /-- If `p` is a prime such that `¬ p ∣ n`, then `expand R p (cyclotomic n R) = (cyclotomic (n * p) R) * (cyclotomic n R)`. -/ @[simp] lemma cyclotomic_expand_eq_cyclotomic_mul {p n : ℕ} (hp : nat.prime p) (hdiv : ¬p ∣ n) (R : Type*) [comm_ring R] : expand R p (cyclotomic n R) = (cyclotomic (n * p) R) * (cyclotomic n R) := begin rcases nat.eq_zero_or_pos n with rfl | hnpos, { simp }, haveI := ne_zero.of_pos hnpos, suffices : expand ℤ p (cyclotomic n ℤ) = (cyclotomic (n * p) ℤ) * (cyclotomic n ℤ), { rw [← map_cyclotomic_int, ← map_expand, this, polynomial.map_mul, map_cyclotomic_int] }, refine eq_of_monic_of_dvd_of_nat_degree_le ((cyclotomic.monic _ _).mul (cyclotomic.monic _ _)) ((cyclotomic.monic n ℤ).expand hp.pos) _ _, { refine (is_primitive.int.dvd_iff_map_cast_dvd_map_cast _ _ (is_primitive.mul (cyclotomic.is_primitive (n * p) ℤ) (cyclotomic.is_primitive n ℤ)) ((cyclotomic.monic n ℤ).expand hp.pos).is_primitive).2 _, rw [polynomial.map_mul, map_cyclotomic_int, map_cyclotomic_int, map_expand, map_cyclotomic_int], refine is_coprime.mul_dvd (cyclotomic.is_coprime_rat (λ h, _)) _ _, { replace h : n * p = n * 1 := by simp [h], exact nat.prime.ne_one hp (nat.eq_of_mul_eq_mul_left hnpos h) }, { have hpos : 0 < n * p := mul_pos hnpos hp.pos, have hprim := complex.is_primitive_root_exp _ hpos.ne', rw [cyclotomic_eq_minpoly_rat hprim hpos], refine @minpoly.dvd ℚ ℂ _ _ algebra_rat _ _ _, rw [aeval_def, ← eval_map, map_expand, map_cyclotomic, expand_eval, ← is_root.def, is_root_cyclotomic_iff], convert is_primitive_root.pow_of_dvd hprim hp.ne_zero (dvd_mul_left p n), rw [nat.mul_div_cancel _ (nat.prime.pos hp)] }, { have hprim := complex.is_primitive_root_exp _ hnpos.ne.symm, rw [cyclotomic_eq_minpoly_rat hprim hnpos], refine @minpoly.dvd ℚ ℂ _ _ algebra_rat _ _ _, rw [aeval_def, ← eval_map, map_expand, expand_eval, ← is_root.def, ← cyclotomic_eq_minpoly_rat hprim hnpos, map_cyclotomic, is_root_cyclotomic_iff], exact is_primitive_root.pow_of_prime hprim hp hdiv,} }, { rw [nat_degree_expand, nat_degree_cyclotomic, nat_degree_mul (cyclotomic_ne_zero _ ℤ) (cyclotomic_ne_zero _ ℤ), nat_degree_cyclotomic, nat_degree_cyclotomic, mul_comm n, nat.totient_mul ((nat.prime.coprime_iff_not_dvd hp).2 hdiv), nat.totient_prime hp, mul_comm (p - 1), ← nat.mul_succ, nat.sub_one, nat.succ_pred_eq_of_pos hp.pos] } end /-- If `p` is a prime such that `p ∣ n`, then `expand R p (cyclotomic n R) = cyclotomic (p * n) R`. -/ @[simp] lemma cyclotomic_expand_eq_cyclotomic {p n : ℕ} (hp : nat.prime p) (hdiv : p ∣ n) (R : Type*) [comm_ring R] : expand R p (cyclotomic n R) = cyclotomic (n * p) R := begin rcases n.eq_zero_or_pos with rfl | hzero, { simp }, haveI := ne_zero.of_pos hzero, suffices : expand ℤ p (cyclotomic n ℤ) = cyclotomic (n * p) ℤ, { rw [← map_cyclotomic_int, ← map_expand, this, map_cyclotomic_int] }, refine eq_of_monic_of_dvd_of_nat_degree_le (cyclotomic.monic _ _) ((cyclotomic.monic n ℤ).expand hp.pos) _ _, { have hpos := nat.mul_pos hzero hp.pos, have hprim := complex.is_primitive_root_exp _ hpos.ne.symm, rw [cyclotomic_eq_minpoly hprim hpos], refine @minpoly.gcd_domain_dvd ℤ ℂ ℚ _ _ _ _ _ _ _ _ complex.algebra (algebra_int ℂ) _ _ (is_primitive_root.is_integral hprim hpos) _ ((cyclotomic.monic n ℤ).expand hp.pos).is_primitive _, rw [aeval_def, ← eval_map, map_expand, map_cyclotomic, expand_eval, ← is_root.def, is_root_cyclotomic_iff], { convert is_primitive_root.pow_of_dvd hprim hp.ne_zero (dvd_mul_left p n), rw [nat.mul_div_cancel _ hp.pos] } }, { rw [nat_degree_expand, nat_degree_cyclotomic, nat_degree_cyclotomic, mul_comm n, nat.totient_mul_of_prime_of_dvd hp hdiv, mul_comm] } end /-- If the `p ^ n`th cyclotomic polynomial is irreducible, so is the `p ^ m`th, for `m ≤ n`. -/ lemma cyclotomic_irreducible_pow_of_irreducible_pow {p : ℕ} (hp : nat.prime p) {R} [comm_ring R] [is_domain R] {n m : ℕ} (hmn : m ≤ n) (h : irreducible (cyclotomic (p ^ n) R)) : irreducible (cyclotomic (p ^ m) R) := begin unfreezingI { rcases m.eq_zero_or_pos with rfl | hm, { simpa using irreducible_X_sub_C (1 : R) }, obtain ⟨k, rfl⟩ := nat.exists_eq_add_of_le hmn, induction k with k hk }, { simpa using h }, have : m + k ≠ 0 := (add_pos_of_pos_of_nonneg hm k.zero_le).ne', rw [nat.add_succ, pow_succ', ←cyclotomic_expand_eq_cyclotomic hp $ dvd_pow_self p this] at h, exact hk (by linarith) (of_irreducible_expand hp.ne_zero h) end /-- If `irreducible (cyclotomic (p ^ n) R)` then `irreducible (cyclotomic p R).` -/ lemma cyclotomic_irreducible_of_irreducible_pow {p : ℕ} (hp : nat.prime p) {R} [comm_ring R] [is_domain R] {n : ℕ} (hn : n ≠ 0) (h : irreducible (cyclotomic (p ^ n) R)) : irreducible (cyclotomic p R) := pow_one p ▸ cyclotomic_irreducible_pow_of_irreducible_pow hp hn.bot_lt h end expand section char_p /-- If `R` is of characteristic `p` and `¬p ∣ n`, then `cyclotomic (n * p) R = (cyclotomic n R) ^ (p - 1)`. -/ lemma cyclotomic_mul_prime_eq_pow_of_not_dvd (R : Type*) {p n : ℕ} [hp : fact (nat.prime p)] [ring R] [char_p R p] (hn : ¬p ∣ n) : cyclotomic (n * p) R = (cyclotomic n R) ^ (p - 1) := begin suffices : cyclotomic (n * p) (zmod p) = (cyclotomic n (zmod p)) ^ (p - 1), { rw [← map_cyclotomic _ (algebra_map (zmod p) R), ← map_cyclotomic _ (algebra_map (zmod p) R), this, polynomial.map_pow] }, apply mul_right_injective₀ (cyclotomic_ne_zero n $ zmod p), rw [←pow_succ, tsub_add_cancel_of_le hp.out.one_lt.le, mul_comm, ← zmod.expand_card], nth_rewrite 2 [← map_cyclotomic_int], rw [← map_expand, cyclotomic_expand_eq_cyclotomic_mul hp.out hn, polynomial.map_mul, map_cyclotomic, map_cyclotomic] end /-- If `R` is of characteristic `p` and `p ∣ n`, then `cyclotomic (n * p) R = (cyclotomic n R) ^ p`. -/ lemma cyclotomic_mul_prime_dvd_eq_pow (R : Type*) {p n : ℕ} [hp : fact (nat.prime p)] [ring R] [char_p R p] (hn : p ∣ n) : cyclotomic (n * p) R = (cyclotomic n R) ^ p := begin suffices : cyclotomic (n * p) (zmod p) = (cyclotomic n (zmod p)) ^ p, { rw [← map_cyclotomic _ (algebra_map (zmod p) R), ← map_cyclotomic _ (algebra_map (zmod p) R), this, polynomial.map_pow] }, rw [← zmod.expand_card, ← map_cyclotomic_int n, ← map_expand, cyclotomic_expand_eq_cyclotomic hp.out hn, map_cyclotomic, mul_comm] end /-- If `R` is of characteristic `p` and `¬p ∣ m`, then `cyclotomic (p ^ k * m) R = (cyclotomic m R) ^ (p ^ k - p ^ (k - 1))`. -/ lemma cyclotomic_mul_prime_pow_eq (R : Type*) {p m : ℕ} [fact (nat.prime p)] [ring R] [char_p R p] (hm : ¬p ∣ m) : ∀ {k}, 0 < k → cyclotomic (p ^ k * m) R = (cyclotomic m R) ^ (p ^ k - p ^ (k - 1)) | 1 _ := by rw [pow_one, nat.sub_self, pow_zero, mul_comm, cyclotomic_mul_prime_eq_pow_of_not_dvd R hm] | (a + 2) _ := begin have hdiv : p ∣ p ^ a.succ * m := ⟨p ^ a * m, by rw [← mul_assoc, pow_succ]⟩, rw [pow_succ, mul_assoc, mul_comm, cyclotomic_mul_prime_dvd_eq_pow R hdiv, cyclotomic_mul_prime_pow_eq a.succ_pos, ← pow_mul], congr' 1, simp only [tsub_zero, nat.succ_sub_succ_eq_sub], rw [nat.mul_sub_right_distrib, mul_comm, pow_succ'] end /-- If `R` is of characteristic `p` and `¬p ∣ m`, then `ζ` is a root of `cyclotomic (p ^ k * m) R` if and only if it is a primitive `m`-th root of unity. -/ lemma is_root_cyclotomic_prime_pow_mul_iff_of_char_p {m k p : ℕ} {R : Type*} [comm_ring R] [is_domain R] [hp : fact (nat.prime p)] [hchar : char_p R p] {μ : R} [ne_zero (m : R)] : (polynomial.cyclotomic (p ^ k * m) R).is_root μ ↔ is_primitive_root μ m := begin rcases k.eq_zero_or_pos with rfl | hk, { rw [pow_zero, one_mul, is_root_cyclotomic_iff] }, refine ⟨λ h, _, λ h, _⟩, { rw [is_root.def, cyclotomic_mul_prime_pow_eq R (ne_zero.not_char_dvd R p m) hk, eval_pow] at h, replace h := pow_eq_zero h, rwa [← is_root.def, is_root_cyclotomic_iff] at h }, { rw [← is_root_cyclotomic_iff, is_root.def] at h, rw [cyclotomic_mul_prime_pow_eq R (ne_zero.not_char_dvd R p m) hk, is_root.def, eval_pow, h, zero_pow], simp only [tsub_pos_iff_lt], apply strict_mono_pow hp.out.one_lt (nat.pred_lt hk.ne') } end end char_p end polynomial
d7b53c8e8634b4b2700bbad0e6a39e07858b24a1
6b45072eb2b3db3ecaace2a7a0241ce81f815787
/data/list/perm.lean
28a76ebfee53e218395cac9d01c654112a6b0472
[]
no_license
avigad/library_dev
27b47257382667b5eb7e6476c4f5b0d685dd3ddc
9d8ac7c7798ca550874e90fed585caad030bbfac
refs/heads/master
1,610,452,468,791
1,500,712,839,000
1,500,713,478,000
69,311,142
1
0
null
1,474,942,903,000
1,474,942,902,000
null
UTF-8
Lean
false
false
39,426
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 List permutations. -/ import .basic .comb .set -- TODO(Jeremy): Here is a common idiom: after simplifying, we have a goal 1 + t = nat.succ t -- and need to say rw [add_comm, reflexivity]. Can we get the simplifier to finish this off? namespace list universe variables uu vv variables {α : Type uu} {β : Type vv} inductive perm : list α → list α → Prop | nil : perm [] [] | skip : Π (x : α) {l₁ l₂ : list α}, perm l₁ l₂ → perm (x::l₁) (x::l₂) | swap : Π (x y : α) (l : list α), perm (y::x::l) (x::y::l) | trans : Π {l₁ l₂ l₃ : list α}, perm l₁ l₂ → perm l₂ l₃ → perm l₁ l₃ namespace perm infix ~ := perm @[refl] protected theorem refl : ∀ (l : list α), l ~ l | [] := nil | (x::xs) := skip x (refl xs) @[symm] protected theorem symm {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₂ ~ l₁ := perm.rec_on p nil (λ x l₁ l₂ p₁ r₁, skip x r₁) (λ x y l, swap y x l) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₂ r₁) attribute [trans] perm.trans theorem eqv (α : Type) : equivalence (@perm α) := mk_equivalence (@perm α) (@perm.refl α) (@perm.symm α) (@perm.trans α) attribute [instance] protected definition is_setoid (α : Type) : setoid (list α) := setoid.mk (@perm α) (perm.eqv α) theorem mem_of_perm {a : α} {l₁ l₂ : list α} (p : l₁ ~ l₂) : a ∈ l₁ → a ∈ l₂ := perm.rec_on p (λ h, h) (λ x l₁ l₂ p₁ r₁ i, or.elim i (λ ax, by simp [ax]) (λ al₁, or.inr (r₁ al₁))) (λ x y l ayxl, or.elim ayxl (λ ay, by simp [ay]) (λ axl, or.elim axl (λ ax, by simp [ax]) (λ al, or.inr (or.inr al)))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂ ainl₁, r₂ (r₁ ainl₁)) theorem not_mem_of_perm {a : α} {l₁ l₂ : list α} : l₁ ~ l₂ → a ∉ l₁ → a ∉ l₂ := assume p nainl₁ ainl₂, nainl₁ (mem_of_perm p.symm ainl₂) theorem mem_iff_mem_of_perm {a : α} {l₁ l₂ : list α} (h : l₁ ~ l₂) : a ∈ l₁ ↔ a ∈ l₂ := iff.intro (mem_of_perm h) (mem_of_perm h.symm) theorem perm_app_left {l₁ l₂ : list α} (t₁ : list α) (p : l₁ ~ l₂) : (l₁++t₁) ~ (l₂++t₁) := perm.rec_on p (perm.refl ([] ++ t₁)) (λ x l₁ l₂ p₁ r₁, skip x r₁) (λ x y l, swap x y _) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) theorem perm_app_right {t₁ t₂ : list α} : ∀ (l : list α), t₁ ~ t₂ → (l++t₁) ~ (l++t₂) | [] p := p | (x::xs) p := skip x (perm_app_right xs p) theorem perm_app {l₁ l₂ t₁ t₂ : list α} : l₁ ~ l₂ → t₁ ~ t₂ → (l₁++t₁) ~ (l₂++t₂) := assume p₁ p₂, trans (perm_app_left t₁ p₁) (perm_app_right l₂ p₂) --theorem perm_app_cons (a : α) {h₁ h₂ t₁ t₂ : list α} : -- h₁ ~ h₂ → t₁ ~ t₂ → (h₁ ++ (a::t₁)) ~ (h₂ ++ (a::t₂)) := --assume p₁ p₂, perm_app p₁ (skip a p₂) theorem perm_cons_app (a : α) : ∀ (l : list α), (a::l) ~ (l ++ [a]) | [] := perm.refl _ | (x::xs) := trans (swap x a xs) $ skip x (perm_cons_app xs) @[simp] theorem perm_cons_app_simp (a : α) (l : list α) : (l ++ [a]) ~ (a::l) := perm.symm (perm_cons_app a l) @[simp] theorem perm_app_comm : ∀ {l₁ l₂ : list α}, (l₁++l₂) ~ (l₂++l₁) | [] l₂ := by simp | (a::t) l₂ := calc a::(t++l₂) ~ a::(l₂++t) : skip a perm_app_comm ... ~ l₂++t++[a] : perm_cons_app _ _ ... = l₂++(t++[a]) : by rw append.assoc ... ~ l₂++(a::t) : perm_app_right l₂ (perm.symm (perm_cons_app a t)) theorem length_eq_length_of_perm {l₁ l₂ : list α} (p : l₁ ~ l₂) : length l₁ = length l₂ := perm.rec_on p rfl (λ x l₁ l₂ p r, by simp[r]) (λ x y l, by simp) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, eq.trans r₁ r₂) theorem eq_nil_of_perm_nil {l₁ : list α} (p : ([] : list α) ~ l₁) : l₁ = ([] : list α) := eq_nil_of_length_eq_zero (length_eq_length_of_perm p).symm theorem not_perm_nil_cons (x : α) (l : list α) : ¬ [] ~ (x::l) := assume p, by have h := eq_nil_of_perm_nil p; contradiction theorem eq_singleton_of_perm {a b : α} (p : [a] ~ [b]) : a = b := have a ∈ [b], from mem_of_perm p (by simp), by simp at this; simp [*] theorem eq_singleton_of_perm_inv {a : α} {l : list α} (p : [a] ~ l) : l = [a] := match l, length_eq_length_of_perm p, p with | [a'], rfl, p := by simp [eq_singleton_of_perm p] end theorem perm_rev : ∀ (l : list α), l ~ (reverse l) | [] := nil | (x::xs) := calc x::xs ~ x::reverse xs : skip x (perm_rev xs) ... ~ reverse xs ++ [x] : perm_cons_app _ _ ... = reverse (x::xs) : by rw [reverse_cons, concat_eq_append] @[simp] theorem perm_rev_simp (l : list α) : (reverse l) ~ l := perm.symm (perm_rev l) theorem perm_middle (a : α) (l₁ l₂ : list α) : (a::l₁)++l₂ ~ l₁++(a::l₂) := have a::l₁++l₂ ~ l₁++[a]++l₂, from perm_app_left l₂ (perm_cons_app a l₁), by simp at this; exact this attribute [simp] theorem perm_middle_simp (a : α) (l₁ l₂ : list α) : l₁++(a::l₂) ~ (a::l₁)++l₂ := perm.symm $ perm_middle a l₁ l₂ theorem perm_cons_app_cons {l l₁ l₂ : list α} (a : α) (p : l ~ l₁++l₂) : a::l ~ l₁++(a::l₂) := trans (skip a p) $ perm_middle a l₁ l₂ open decidable theorem perm_erase [decidable_eq α] {a : α} : ∀ {l : list α}, a ∈ l → l ~ a:: l.erase a | [] h := false.elim h | (x::t) h := if ax : x = a then by rw [ax, erase_cons_head] else by rw [erase_cons_tail _ ax]; exact have aint : a ∈ t, from mem_of_ne_of_mem (assume h, ax h.symm) h, trans (skip _ $ perm_erase aint) (swap _ _ _) @[elab_as_eliminator] theorem perm_induction_on {P : list α → list α → Prop} {l₁ l₂ : list α} (p : l₁ ~ l₂) (h₁ : P [] []) (h₂ : ∀ x l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (x::l₁) (x::l₂)) (h₃ : ∀ x y l₁ l₂, l₁ ~ l₂ → P l₁ l₂ → P (y::x::l₁) (x::y::l₂)) (h₄ : ∀ l₁ l₂ l₃, l₁ ~ l₂ → l₂ ~ l₃ → P l₁ l₂ → P l₂ l₃ → P l₁ l₃) : P l₁ l₂ := have P_refl : ∀ l, P l l, from assume l, list.rec_on l h₁ (λ x xs ih, h₂ x xs xs (perm.refl xs) ih), perm.rec_on p h₁ h₂ (λ x y l, h₃ x y l l (perm.refl l) (P_refl l)) h₄ theorem xswap {l₁ l₂ : list α} (x y : α) : l₁ ~ l₂ → x::y::l₁ ~ y::x::l₂ := assume p, calc x::y::l₁ ~ y::x::l₁ : swap y x l₁ ... ~ y::x::l₂ : skip y (skip x p) @[congr] theorem perm_map (f : α → β) {l₁ l₂ : list α} : l₁ ~ l₂ → map f l₁ ~ map f l₂ := assume p, perm_induction_on p nil (λ x l₁ l₂ p r, skip (f x) r) (λ x y l₁ l₂ p r, xswap (f y) (f x) r) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) /- TODO(Jeremy) In the next section, the decidability proof works, but gave the following error: equation compiler failed to generate bytecode for auxiliary declaration 'list.perm.decidable_perm_aux._main' nested exception message: code generation failed, inductive predicate 'eq' is not supported So I will comment it out and give another decidability proof below. -/ /- /- permutation is decidable if α has decidable equality -/ section dec open decidable variable [Ha : decidable_eq α] include Ha def decidable_perm_aux : ∀ (n : nat) (l₁ l₂ : list α), length l₁ = n → length l₂ = n → decidable (l₁ ~ l₂) | 0 l₁ l₂ H₁ H₂ := have l₁n : l₁ = [], from eq_nil_of_length_eq_zero H₁, have l₂n : l₂ = [], from eq_nil_of_length_eq_zero H₂, begin rw [l₁n, l₂n], exact (is_true perm.nil) end | (n+1) (x::t₁) l₂ H₁ H₂ := by_cases (assume xinl₂ : x ∈ l₂, -- TODO(Jeremy): it seems the equation editor abstracts t₂, and loses the definition, so -- I had to expand it manually -- let t₂ : list α := erase x l₂ in have len_t₁ : length t₁ = n, begin simp at H₁, have H₁' : nat.succ (length t₁) = nat.succ n, exact H₁, injection H₁' with e, exact e end, have length (erase x l₂) = nat.pred (length l₂), from length_erase_of_mem xinl₂, have length (erase x l₂) = n, begin rw [this, H₂], reflexivity end, match decidable_perm_aux n t₁ (erase x l₂) len_t₁ this with | is_true p := is_true (calc x::t₁ ~ x::erase x l₂ : skip x p ... ~ l₂ : perm.symm (perm_erase xinl₂)) | is_false np := is_false (λ p : x::t₁ ~ l₂, have erase x (x::t₁) ~ erase x l₂, from erase_perm_erase_of_perm x p, have t₁ ~ erase x l₂, begin rw [erase_cons_head] at this, exact this end, absurd this np) end) (assume nxinl₂ : x ∉ l₂, is_false (λ p : x::t₁ ~ l₂, absurd (mem_of_perm p (mem_cons_self _ _)) nxinl₂)) attribute [instance] definition decidable_perm : ∀ (l₁ l₂ : list α), decidable (l₁ ~ l₂) := λ l₁ l₂, by_cases (assume eql : length l₁ = length l₂, decidable_perm_aux (length l₂) l₁ l₂ eql rfl) (assume neql : length l₁ ≠ length l₂, is_false (λ p : l₁ ~ l₂, absurd (length_eq_length_of_perm p) neql)) end dec -/ section count variable [decα : decidable_eq α] include decα theorem count_eq_count_of_perm {l₁ l₂ : list α} : l₁ ~ l₂ → ∀ a, count a l₁ = count a l₂ := assume : l₁ ~ l₂, perm.rec_on this (λ a, rfl) (λ x l₁ l₂ p h a, begin simp [count_cons', h a] end) (λ x y l a, begin simp [count_cons'] end) (λ l₁ l₂ l₃ p₁ p₂ h₁ h₂ a, eq.trans (h₁ a) (h₂ a)) theorem perm_of_forall_count_eq : ∀ {l₁ l₂ : list α}, (∀ a, count a l₁ = count a l₂) → l₁ ~ l₂ | [] := assume l₂, assume h : ∀ a, count a [] = count a l₂, have ∀ a, a ∉ l₂, from assume a, not_mem_of_count_eq_zero (by simp [(h a).symm]), have l₂ = [], from eq_nil_of_forall_not_mem this, show [] ~ l₂, by rw this | (b :: l) := assume l₂, assume h : ∀ a, count a (b :: l) = count a l₂, have b ∈ l₂, from mem_of_count_pos (begin rw [←(h b)], simp, apply nat.succ_pos end), have l₂ ~ b :: l₂.erase b, from perm_erase this, have ∀ a, count a l = count a (l₂.erase b), from assume a, if h' : a = b then nat.succ_inj (calc count a l + 1 = count a (b :: l) : begin simp [h'], rw add_comm end ... = count a l₂ : by rw h ... = count a (b :: l₂.erase b) : count_eq_count_of_perm (by assumption) a ... = count a (l₂.erase b) + 1 : begin simp [h'], rw add_comm end) else calc count a l = count a (b :: l) : by simp [h'] ... = count a l₂ : by rw h ... = count a (b :: l₂.erase b) : count_eq_count_of_perm (by assumption) a ... = count a (l₂.erase b) : by simp [h'], have l ~ l₂.erase b, from perm_of_forall_count_eq this, calc b :: l ~ b :: l₂.erase b : skip b this ... ~ l₂ : perm.symm (by assumption) theorem perm_iff_forall_count_eq_count (l₁ l₂ : list α) : l₁ ~ l₂ ↔ ∀ a, count a l₁ = count a l₂ := iff.intro count_eq_count_of_perm perm_of_forall_count_eq -- This next theorem shows that perm is equivalent to a decidable (and efficiently checkable) -- property. theorem perm_iff_forall_mem_count_eq_count (l₁ l₂ : list α) : l₁ ~ l₂ ↔ ∀ a ∈ erase_dup (l₁ ∪ l₂), count a l₁ = count a l₂ := iff.intro (assume h : l₁ ~ l₂, assume a, assume ha, count_eq_count_of_perm h a) (assume h, have ∀ a, count a l₁ = count a l₂, from assume a, if hl₁ : a ∈ l₁ then have a ∈ erase_dup (l₁ ∪ l₂), from mem_erase_dup (mem_union_left hl₁ l₂), h a this else if hl₂ : a ∈ l₂ then have a ∈ erase_dup (l₁ ∪ l₂), from mem_erase_dup (mem_union_right l₁ hl₂), h a this else by simp [hl₁, hl₂], perm_of_forall_count_eq this) instance : ∀ (l₁ l₂ : list α), decidable (l₁ ~ l₂) := assume l₁ l₂, decidable_of_decidable_of_iff (decidable_forall_mem _) (perm_iff_forall_mem_count_eq_count l₁ l₂).symm end count -- Auxiliary theorem for performing cases-analysis on l₂. -- We use it to prove perm_inv_core. private theorem discr {P : Prop} {a b : α} {l₁ l₂ l₃ : list α} : a::l₁ = l₂++(b::l₃) → (l₂ = [] → a = b → l₁ = l₃ → P) → (∀ t, l₂ = a::t → l₁ = t++(b::l₃) → P) → P := match l₂ with | [] := λ e h₁ h₂, begin simp at e, injection e with e₁ e₂, exact h₁ rfl e₁ e₂ end | h::t := λ e h₁ h₂, begin simp at e, injection e with e₁ e₂, rw e₁ at h₂, exact h₂ t rfl e₂ end end -- Auxiliary theorem for performing cases-analysis on l₂. -- We use it to prove perm_inv_core. private theorem discr₂ {P : Prop} {a b c : α} {l₁ l₂ l₃ : list α} (e : a::b::l₁ = l₂++(c::l₃)) (H₁ : l₂ = [] → l₃ = b::l₁ → a = c → P) (H₂ : l₂ = [a] → b = c → l₁ = l₃ → P) (H₃ : ∀ t, l₂ = a::b::t → l₁ = t++(c::l₃) → P) : P := discr e (λh₁ h₂ h₃, H₁ h₁ h₃.symm h₂) $ λt h₁ h₂, discr h₂ (λh₃ h₄, match t, h₃, h₁ with ._, rfl, h₁ := H₂ h₁ h₄ end) (λt' h₃ h₄, match t, h₃, h₁ with ._, rfl, h₁ := H₃ t' h₁ h₄ end) /- quasiequal a l l' means that l' is exactly l, with a added once somewhere -/ section qeq inductive qeq (a : α) : list α → list α → Prop | qhead : ∀ l, qeq l (a::l) | qcons : ∀ (b : α) {l l' : list α}, qeq l l' → qeq (b::l) (b::l') open qeq notation l' `≈`:50 a `|` l:50 := qeq a l l' lemma perm_of_qeq {a : α} {l₁ l₂ : list α} : l₁≈a|l₂ → l₁~a::l₂ := assume q, qeq.rec_on q (λ h, perm.refl (a :: h)) (λ b t₁ t₂ q₁ r₁, calc b::t₂ ~ b::a::t₁ : skip b r₁ ... ~ a::b::t₁ : swap a b t₁) theorem qeq_app : ∀ (l₁ : list α) (a : α) (l₂ : list α), l₁ ++ (a :: l₂) ≈ a | l₁ ++ l₂ | ([] : list α) b l₂ := qhead b l₂ | (a::ains) b l₂ := qcons a (qeq_app ains b l₂) theorem mem_head_of_qeq {a : α} : ∀ {l₁ l₂ : list α}, l₁ ≈ a | l₂ → a ∈ l₁ | ._ ._ (qhead .(a) l) := mem_cons_self a l | ._ ._ (@qcons .(α) .(a) b l l' q) := mem_cons_of_mem b (mem_head_of_qeq q) theorem mem_tail_of_qeq {a : α} : ∀ {l₁ l₂ : list α}, l₁ ≈ a | l₂ → ∀ {b}, b ∈ l₂ → b ∈ l₁ | ._ ._ (qhead .(a) l) b bl := mem_cons_of_mem a bl | ._ ._ (@qcons .(α) .(a) c l l' q) b bcl := or.elim (eq_or_mem_of_mem_cons bcl) (assume bc : b = c, begin rw bc, apply mem_cons_self end) (assume bl : b ∈ l, have bl' : b ∈ l', from mem_tail_of_qeq q bl, mem_cons_of_mem c bl') theorem mem_cons_of_qeq {a : α} : ∀ {l₁ l₂ : list α}, l₁≈a|l₂ → ∀ {b}, b ∈ l₁ → b ∈ a::l₂ | ._ ._ (qhead ._ l) b bal := bal | ._ ._ (@qcons ._ ._ c l l' q) b (bcl' : b ∈ c :: l') := show b ∈ a :: c :: l, from or.elim (eq_or_mem_of_mem_cons bcl') (assume bc : b = c, begin rw bc, apply mem_cons_of_mem, apply mem_cons_self end) (assume bl' : b ∈ l', have b ∈ a :: l, from mem_cons_of_qeq q bl', or.elim (eq_or_mem_of_mem_cons this) (assume ba : b = a, begin rw ba, apply mem_cons_self end) (assume bl : b ∈ l, mem_cons_of_mem a (mem_cons_of_mem c bl))) theorem length_eq_of_qeq {a : α} {l₁ l₂ : list α} : l₁ ≈ a | l₂ → length l₁ = nat.succ (length l₂) := begin intro q, induction q with l b l l' q ih, simp[nat.one_add], simp [*] end theorem qeq_of_mem {a : α} {l : list α} : a ∈ l → (∃ l', l ≈ a | l') := list.rec_on l (λ h : a ∈ ([] : list α), absurd h (not_mem_nil a)) (λ b bs r ainbbs, or.elim (eq_or_mem_of_mem_cons ainbbs) (λ aeqb : a = b, have ∃ l, b::bs ≈ b | l, from exists.intro bs (qhead b bs), begin rw aeqb, exact this end) (λ ainbs : a ∈ bs, have ∃ l', bs ≈ a|l', from r ainbs, exists.elim this (assume (l' : list α) (q : bs ≈ a|l'), have b::bs ≈ a | b::l', from qcons b q, exists.intro (b::l') this))) theorem qeq_split {a : α} : ∀ {l l' : list α}, l'≈a|l → ∃ l₁ l₂, l = l₁ ++ l₂ ∧ l' = l₁ ++ (a::l₂) | ._ ._ (qhead ._ l) := ⟨[], l, by simp⟩ | ._ ._ (@qcons ._ ._ c l l' q) := match (qeq_split q) with | ⟨l₁, l₂, h₁, h₂⟩ := ⟨c :: l₁, l₂, by simp [h₁, h₂]⟩ end --theorem subset_of_mem_of_subset_of_qeq {a : α} {l : list α} {u v : list α} : -- a ∉ l → a::l ⊆ v → v≈a|u → l ⊆ u := --λ (nainl : a ∉ l) (s : a::l ⊆ v) (q : v≈a|u) (b : α) (binl : b ∈ l), -- have b ∈ v, from s (or.inr binl), -- have b ∈ a::u, from mem_cons_of_qeq q this, -- or.elim (eq_or_mem_of_mem_cons this) -- (assume : b = a, begin subst b, contradiction end) -- (assume : b ∈ u, this) --end qeq theorem perm_inv_core {l₁ l₂ : list α} (p' : l₁ ~ l₂) : ∀ {a s₁ s₂}, l₁≈a|s₁ → l₂≈a|s₂ → s₁ ~ s₂ := perm_induction_on p' (λ a s₁ s₂ e₁ e₂, match e₁ with end) (λ x t₁ t₂ p (r : ∀{a s₁ s₂}, t₁≈a|s₁ → t₂≈a|s₂ → s₁ ~ s₂) a s₁ s₂ e₁ e₂, match s₁, s₂, qeq_split e₁, qeq_split e₂ with ._, ._, ⟨s₁₁, s₁₂, rfl, C₁⟩, ⟨s₂₁, s₂₂, rfl, C₂⟩ := discr C₁ (λe₁ xa, match s₁₁, x, e₁, xa, C₂ with ._, ._, rfl, rfl, C₂ := discr C₂ (λe₁ _ e₂ e₃, match s₁₂, s₂₁, s₂₂, e₁, e₂, e₃ with | ._, ._, ._, rfl, rfl, rfl := p end) (λt₃ e₁ e₂ e₃, match s₂₁, s₁₂, t₂, e₁, e₂, e₃, p with | ._, ._, ._, rfl, rfl, rfl, p := trans p (perm_middle _ _ _).symm end) end) (λt₃ e₁ e₂, match s₁₁, t₁, e₁, e₂, C₂, p, @r with ._, ._, rfl, rfl, C₂, p, r := discr C₂ (λe₁ xa e₂, match x, s₂₁, s₂₂, xa, e₁, e₂ with | ._, ._, ._, rfl, rfl, rfl := trans (perm_middle _ _ _) p end) (λt₃ e₁ e₂, match s₂₁, t₂, e₁, e₂, @r with | ._, ._, rfl, rfl, r := skip x (r (qeq_app _ _ _) (qeq_app _ _ _)) end) end) end) (λ x y t₁ t₂ p (r : ∀{a s₁ s₂}, t₁≈a|s₁ → t₂≈a|s₂ → s₁ ~ s₂) a s₁ s₂ e₁ e₂, match s₁, s₂, qeq_split e₁, qeq_split e₂ with ._, ._, ⟨s₁₁, s₁₂, rfl, C₁⟩, ⟨s₂₁, s₂₂, rfl, C₂⟩ := discr₂ C₁ (λe₁ e₂ ya, match s₁₁, s₁₂, y, e₁, e₂, ya, C₂ with ._, ._, ._, rfl, rfl, rfl, C₂ := discr₂ C₂ (λe₁ e₂ xa, match s₂₁, s₂₂, x, e₁, e₂, xa with | ._, ._, ._, rfl, rfl, rfl := skip a p end) (λe₁ _ e₂, match s₂₁, s₂₂, e₁, e₂ with | ._, ._, rfl, rfl := skip x p end) (λt₃ e₁ e₂, match s₂₁, t₂, e₁, e₂, p with | ._, ._, rfl, rfl, p := skip x (trans p (perm_middle _ _ _).symm) end) end) (λe₁ xa e₂, match s₁₁, s₁₂, x, e₁, e₂, xa, C₂ with ._, ._, ._, rfl, rfl, rfl, C₂ := discr₂ C₂ (λe₁ e₂ _, match s₂₁, s₂₂, e₁, e₂ with | ._, ._, rfl, rfl := skip y p end) (λe₁ ya e₂, match s₂₁, s₂₂, y, e₁, e₂, ya with | ._, ._, ._, rfl, rfl, rfl := skip a p end) (λt₃ e₁ e₂, match s₂₁, t₂, e₁, e₂, p with | ._, ._, rfl, rfl, p := trans (skip y $ trans p (perm_middle _ _ _).symm) (swap _ _ _) end) end) (λt₃ e₁ e₂, match s₁₁, t₁, e₁, e₂, C₂, p, @r with ._, ._, rfl, rfl, C₂, p, r := discr₂ C₂ (λe₁ e₂ xa, match s₂₁, s₂₂, x, e₁, e₂, xa with | ._, ._, ._, rfl, rfl, rfl := skip y (trans (perm_middle _ _ _) p) end) (λe₁ ya e₂, match s₂₁, s₂₂, y, e₁, e₂, ya with | ._, ._, ._, rfl, rfl, rfl := trans (swap _ _ _) (skip x $ trans (perm_middle _ _ _) p) end) (λt₄ e₁ e₂, match s₂₁, t₂, e₁, e₂, @r with | ._, ._, rfl, rfl, r := trans (swap _ _ _) (skip x $ skip y $ r (qeq_app _ _ _) (qeq_app _ _ _)) end) end) end) (λ t₁ t₂ t₃ p₁ p₂ (r₁ : ∀{a s₁ s₂}, t₁ ≈ a|s₁ → t₂≈a|s₂ → s₁ ~ s₂) (r₂ : ∀{a s₁ s₂}, t₂ ≈ a|s₁ → t₃≈a|s₂ → s₁ ~ s₂) a s₁ s₂ e₁ e₂, let ⟨t₂', e₂'⟩ := qeq_of_mem $ mem_of_perm p₁ $ mem_head_of_qeq e₁ in trans (r₁ e₁ e₂') (r₂ e₂' e₂)) end qeq theorem perm_cons_inv {a : α} {l₁ l₂ : list α} (p : a::l₁ ~ a::l₂) : l₁ ~ l₂ := perm_inv_core p (qeq.qhead a l₁) (qeq.qhead a l₂) theorem perm_app_inv_left {l₁ l₂ : list α} : ∀ {l}, l++l₁ ~ l++l₂ → l₁ ~ l₂ | [] p := p | (a::l) p := perm_app_inv_left (perm_cons_inv p) theorem perm_app_inv_right {l₁ l₂ l : list α} (p : l₁++l ~ l₂++l) : l₁ ~ l₂ := perm_app_inv_left $ trans perm_app_comm $ trans p perm_app_comm theorem perm_app_inv {a : α} {l₁ l₂ l₃ l₄ : list α} (p : l₁++(a::l₂) ~ l₃++(a::l₄)) : l₁++l₂ ~ l₃++l₄ := perm_cons_inv $ trans (perm_middle _ _ _) $ trans p $ (perm_middle _ _ _).symm theorem foldl_eq_of_perm {f : β → α → β} {l₁ l₂ : list α} (rcomm : right_commutative f) (p : l₁ ~ l₂) : ∀ b, foldl f b l₁ = foldl f b l₂ := perm_induction_on p (λ b, rfl) (λ x t₁ t₂ p r b, r (f b x)) (λ x y t₁ t₂ p r b, by simp; rw rcomm; exact r (f (f b x) y)) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ b, eq.trans (r₁ b) (r₂ b)) theorem foldr_eq_of_perm {f : α → β → β} {l₁ l₂ : list α} (lcomm : left_commutative f) (p : l₁ ~ l₂) : ∀ b, foldr f b l₁ = foldr f b l₂ := perm_induction_on p (λ b, rfl) (λ x t₁ t₂ p r b, by simp; rw [r b]) (λ x y t₁ t₂ p r b, by simp; rw [lcomm, r b]) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂ a, eq.trans (r₁ a) (r₂ a)) -- attribute [congr] theorem erase_perm_erase_of_perm [decidable_eq α] (a : α) {l₁ l₂ : list α} (p : l₁ ~ l₂) : l₁.erase a ~ l₂.erase a := if h₁ : a ∈ l₁ then have h₂ : a ∈ l₂, from mem_of_perm p h₁, perm_cons_inv $ trans (perm_erase h₁).symm $ trans p (perm_erase h₂) else have h₂ : a ∉ l₂, from not_mem_of_perm p h₁, by rw [erase_of_not_mem h₁, erase_of_not_mem h₂]; exact p -- attribute [congr] theorem perm_erase_dup_of_perm [H : decidable_eq α] {l₁ l₂ : list α} : l₁ ~ l₂ → erase_dup l₁ ~ erase_dup l₂ := assume p, perm_induction_on p nil (λ x t₁ t₂ p r, by_cases (λ xint₁ : x ∈ t₁, have xint₂ : x ∈ t₂, from mem_of_mem_erase_dup (mem_of_perm r (mem_erase_dup xint₁)), begin rw [erase_dup_cons_of_mem xint₁, erase_dup_cons_of_mem xint₂], exact r end) (λ nxint₁ : x ∉ t₁, have nxint₂ : x ∉ t₂, from assume xint₂ : x ∈ t₂, absurd (mem_of_mem_erase_dup (mem_of_perm (perm.symm r) (mem_erase_dup xint₂))) nxint₁, begin rw [erase_dup_cons_of_not_mem nxint₂, erase_dup_cons_of_not_mem nxint₁], exact (skip x r) end)) (λ y x t₁ t₂ p r, by_cases (λ xinyt₁ : x ∈ y::t₁, by_cases (λ yint₁ : y ∈ t₁, have yint₂ : y ∈ t₂, from mem_of_mem_erase_dup (mem_of_perm r (mem_erase_dup yint₁)), have yinxt₂ : y ∈ x::t₂, from or.inr (yint₂), or.elim (eq_or_mem_of_mem_cons xinyt₁) (λ xeqy : x = y, have xint₂ : x ∈ t₂, begin rw [←xeqy] at yint₂, exact yint₂ end, begin rw [erase_dup_cons_of_mem xinyt₁, erase_dup_cons_of_mem yinxt₂, erase_dup_cons_of_mem yint₁, erase_dup_cons_of_mem xint₂], exact r end) (λ xint₁ : x ∈ t₁, have xint₂ : x ∈ t₂, from mem_of_mem_erase_dup (mem_of_perm r (mem_erase_dup xint₁)), begin rw [erase_dup_cons_of_mem xinyt₁, erase_dup_cons_of_mem yinxt₂, erase_dup_cons_of_mem yint₁, erase_dup_cons_of_mem xint₂], exact r end)) (λ nyint₁ : y ∉ t₁, have nyint₂ : y ∉ t₂, from assume yint₂ : y ∈ t₂, absurd (mem_of_mem_erase_dup (mem_of_perm (perm.symm r) (mem_erase_dup yint₂))) nyint₁, by_cases (λ xeqy : x = y, have nxint₂ : x ∉ t₂, begin rw [←xeqy] at nyint₂, exact nyint₂ end, have yinxt₂ : y ∈ x::t₂, begin rw [xeqy], apply mem_cons_self end, begin rw [erase_dup_cons_of_mem xinyt₁, erase_dup_cons_of_mem yinxt₂, erase_dup_cons_of_not_mem nyint₁, erase_dup_cons_of_not_mem nxint₂, xeqy], exact skip y r end) (λ xney : x ≠ y, have x ∈ t₁, from or_resolve_right xinyt₁ xney, have x ∈ t₂, from mem_of_mem_erase_dup (mem_of_perm r (mem_erase_dup this)), have y ∉ x::t₂, from assume : y ∈ x::t₂, or.elim (eq_or_mem_of_mem_cons this) (λ h, absurd h (ne.symm xney)) (λ h, absurd h nyint₂), begin rw [erase_dup_cons_of_mem xinyt₁, erase_dup_cons_of_not_mem ‹y ∉ x::t₂›, erase_dup_cons_of_not_mem nyint₁, erase_dup_cons_of_mem ‹x ∈ t₂›], exact skip y r end))) (λ nxinyt₁ : x ∉ y::t₁, have xney : x ≠ y, from ne_of_not_mem_cons nxinyt₁, have nxint₁ : x ∉ t₁, from not_mem_of_not_mem_cons nxinyt₁, have nxint₂ : x ∉ t₂, from assume xint₂ : x ∈ t₂, absurd (mem_of_mem_erase_dup (mem_of_perm (perm.symm r) (mem_erase_dup xint₂))) nxint₁, by_cases (λ yint₁ : y ∈ t₁, have yinxt₂ : y ∈ x::t₂, from or.inr (mem_of_mem_erase_dup (mem_of_perm r (mem_erase_dup yint₁))), begin rw [erase_dup_cons_of_not_mem nxinyt₁, erase_dup_cons_of_mem yinxt₂, erase_dup_cons_of_mem yint₁, erase_dup_cons_of_not_mem nxint₂], exact skip x r end) (λ nyint₁ : y ∉ t₁, have nyinxt₂ : y ∉ x::t₂, from assume yinxt₂ : y ∈ x::t₂, or.elim (eq_or_mem_of_mem_cons yinxt₂) (λ h, absurd h (ne.symm xney)) (λ h, absurd (mem_of_mem_erase_dup (mem_of_perm (r.symm) (mem_erase_dup h))) nyint₁), begin rw [erase_dup_cons_of_not_mem nxinyt₁, erase_dup_cons_of_not_mem nyinxt₂, erase_dup_cons_of_not_mem nyint₁, erase_dup_cons_of_not_mem nxint₂], exact xswap x y r end))) (λ t₁ t₂ t₃ p₁ p₂ r₁ r₂, trans r₁ r₂) section perm_union variable [decidable_eq α] theorem perm_union_left {l₁ l₂ : list α} (t₁ : list α) (h : l₁ ~ l₂) : (l₁ ∪ t₁) ~ (l₂ ∪ t₁) := begin induction t₁ with a t ih generalizing l₁ l₂, { exact h }, exact if ha₁ : a ∈ l₁ then have ha₂ : a ∈ l₂, from mem_of_perm h ha₁, begin simp [ha₁, ha₂], apply ih h end else have ha₂ : a ∉ l₂, from assume otherwise, ha₁ (mem_of_perm h.symm otherwise), begin simp [ha₁, ha₂], apply ih, apply perm_app_left, exact h end end lemma perm_insert_insert (x y : α) (l : list α) : insert x (insert y l) ~ insert y (insert x l) := if yl : y ∈ l then if xl : x ∈ l then by simp [xl, yl] else by simp [xl, yl] else if xl : x ∈ l then by simp [xl, yl] else if xy : x = y then by simp [xy, xl, yl] else have h₁ : x ∉ l ++ [y], begin intro h, simp at h, cases h, repeat { contradiction } end, have h₂ : y ∉ l ++ [x], begin intro h, simp at h, cases h with h₃, exact xy h₃.symm, contradiction end, begin simp [xl, yl, h₁, h₂], apply perm_app_right, apply perm.swap end theorem perm_union_right (l : list α) {t₁ t₂ : list α} (h : t₁ ~ t₂) : (l ∪ t₁) ~ (l ∪ t₂) := begin induction h using list.perm.rec_on generalizing l, { refl }, { apply ih_1 }, { simp, apply perm_union_left, apply perm_insert_insert }, { exact perm.trans (ih_1 l) (ih_2 l) } end -- attribute [congr] theorem perm_union {l₁ l₂ t₁ t₂ : list α} : l₁ ~ l₂ → t₁ ~ t₂ → (l₁ ∪ t₁) ~ (l₂ ∪ t₂) := assume p₁ p₂, trans (perm_union_left t₁ p₁) (perm_union_right l₂ p₂) end perm_union section perm_insert variable [H : decidable_eq α] include H -- attribute [congr] theorem perm_insert (a : α) {l₁ l₂ : list α} : l₁ ~ l₂ → (insert a l₁) ~ (insert a l₂) := assume p, if al₁ : a ∈ l₁ then have al₂ : a ∈ l₂, from mem_of_perm p al₁, begin simp [al₁, al₂], exact p end else have al₂ : a ∉ l₂, from assume otherwise, al₁ (mem_of_perm p.symm otherwise), begin simp [al₁, al₂], exact perm_app_left _ p end end perm_insert section perm_inter variable [decidable_eq α] theorem perm_inter_left {l₁ l₂ : list α} (t₁ : list α) : l₁ ~ l₂ → (l₁ ∩ t₁) ~ (l₂ ∩ t₁) := assume p, perm.rec_on p (perm.refl _) (λ x l₁ l₂ p₁ r₁, by_cases (λ xint₁ : x ∈ t₁, begin rw [inter_cons_of_mem _ xint₁, inter_cons_of_mem _ xint₁], exact (skip x r₁) end) (λ nxint₁ : x ∉ t₁, begin rw [inter_cons_of_not_mem _ nxint₁, inter_cons_of_not_mem _ nxint₁], exact r₁ end)) (λ x y l, by_cases (λ yint : y ∈ t₁, by_cases (λ xint : x ∈ t₁, begin rw [inter_cons_of_mem _ xint, inter_cons_of_mem _ yint, inter_cons_of_mem _ yint, inter_cons_of_mem _ xint], apply swap end) (λ nxint : x ∉ t₁, begin rw [inter_cons_of_mem _ yint, inter_cons_of_not_mem _ nxint, inter_cons_of_not_mem _ nxint, inter_cons_of_mem _ yint] end)) (λ nyint : y ∉ t₁, by_cases (λ xint : x ∈ t₁, by rw [inter_cons_of_mem _ xint, inter_cons_of_not_mem _ nyint, inter_cons_of_not_mem _ nyint, inter_cons_of_mem _ xint]) (λ nxint : x ∉ t₁, by rw [inter_cons_of_not_mem _ nxint, inter_cons_of_not_mem _ nyint, inter_cons_of_not_mem _ nyint, inter_cons_of_not_mem _ nxint]))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) theorem perm_inter_right (l : list α) {t₁ t₂ : list α} : t₁ ~ t₂ → (l ∩ t₁) ~ (l ∩ t₂) := list.rec_on l (λ p, by simp [inter_nil]) (λ x xs r p, by_cases (λ xint₁ : x ∈ t₁, have xint₂ : x ∈ t₂, from mem_of_perm p xint₁, begin rw [inter_cons_of_mem _ xint₁, inter_cons_of_mem _ xint₂], exact (skip _ (r p)) end) (λ nxint₁ : x ∉ t₁, have nxint₂ : x ∉ t₂, from not_mem_of_perm p nxint₁, begin rw [inter_cons_of_not_mem _ nxint₁, inter_cons_of_not_mem _ nxint₂], exact (r p) end)) -- attribute [congr] theorem perm_inter {l₁ l₂ t₁ t₂ : list α} : l₁ ~ l₂ → t₁ ~ t₂ → (l₁ ∩ t₁) ~ (l₂ ∩ t₂) := assume p₁ p₂, trans (perm_inter_left t₁ p₁) (perm_inter_right l₂ p₂) end perm_inter /- extensionality -/ section ext theorem perm_ext : ∀ {l₁ l₂ : list α}, nodup l₁ → nodup l₂ → (∀a, a ∈ l₁ ↔ a ∈ l₂) → l₁ ~ l₂ | [] [] d₁ d₂ e := perm.nil | [] (a₂::t₂) d₁ d₂ e := absurd (iff.mpr (e a₂) (mem_cons_self _ _)) (not_mem_nil a₂) | (a₁::t₁) [] d₁ d₂ e := absurd (iff.mp (e a₁) (mem_cons_self _ _)) (not_mem_nil a₁) | (a₁::t₁) (a₂::t₂) d₁ d₂ e := have a₁ ∈ a₂::t₂, from iff.mp (e a₁) (mem_cons_self _ _), have ∃ s₁ s₂, a₂::t₂ = s₁++(a₁::s₂), from mem_split this, -- obtain (s₁ s₂ : list α) (t₂_eq : a₂::t₂ = s₁++(a₁::s₂)), from this, match this with | ⟨ s₁, s₂, (t₂_eq : a₂::t₂ = s₁++(a₁::s₂)) ⟩ := have dt₂' : nodup (a₁::(s₁++s₂)), from nodup_head (begin rw [t₂_eq] at d₂, exact d₂ end), have eqv : ∀a, a ∈ t₁ ↔ a ∈ s₁++s₂, from assume a, iff.intro (assume : a ∈ t₁, have a ∈ a₂::t₂, from iff.mp (e a) (mem_cons_of_mem _ this), have a ∈ s₁++(a₁::s₂), begin rw [t₂_eq] at this, exact this end, or.elim (mem_or_mem_of_mem_append this) (assume : a ∈ s₁, mem_append_left s₂ this) (assume : a ∈ a₁::s₂, or.elim (eq_or_mem_of_mem_cons this) (assume : a = a₁, have a₁ ∉ t₁, from not_mem_of_nodup_cons d₁, begin subst a, contradiction end) (assume : a ∈ s₂, mem_append_right s₁ this))) (assume : a ∈ s₁ ++ s₂, or.elim (mem_or_mem_of_mem_append this) (assume : a ∈ s₁, have a ∈ a₂::t₂, from begin rw [t₂_eq], exact (mem_append_left _ this) end, have a ∈ a₁::t₁, from iff.mpr (e a) this, or.elim (eq_or_mem_of_mem_cons this) (assume : a = a₁, have a₁ ∉ s₁++s₂, from not_mem_of_nodup_cons dt₂', have a₁ ∉ s₁, from not_mem_of_not_mem_append_left this, begin subst a, contradiction end) (assume : a ∈ t₁, this)) (assume : a ∈ s₂, have a ∈ a₂::t₂, from begin rw [t₂_eq], exact (mem_append_right _ (mem_cons_of_mem _ this)) end, have a ∈ a₁::t₁, from iff.mpr (e a) this, or.elim (eq_or_mem_of_mem_cons this) (assume : a = a₁, have a₁ ∉ s₁++s₂, from not_mem_of_nodup_cons dt₂', have a₁ ∉ s₂, from not_mem_of_not_mem_append_right this, begin subst a, contradiction end) (assume : a ∈ t₁, this))), have ds₁s₂ : nodup (s₁++s₂), from nodup_of_nodup_cons dt₂', have nodup t₁, from nodup_of_nodup_cons d₁, calc a₁::t₁ ~ a₁::(s₁++s₂) : skip a₁ (perm_ext this ds₁s₂ eqv) ... ~ s₁++(a₁::s₂) : perm_middle _ _ _ ... = a₂::t₂ : by rw t₂_eq end end ext theorem nodup_of_perm_of_nodup {l₁ l₂ : list α} : l₁ ~ l₂ → nodup l₁ → nodup l₂ := assume h, perm.rec_on h (λ h, h) (λ a l₁ l₂ p ih nd, have nodup l₁, from nodup_of_nodup_cons nd, have nodup l₂, from ih this, have a ∉ l₁, from not_mem_of_nodup_cons nd, have a ∉ l₂, from assume : a ∈ l₂, absurd (mem_of_perm (perm.symm p) this) ‹a ∉ l₁›, nodup_cons ‹a ∉ l₂› ‹nodup l₂›) (λ x y l₁ nd, have nodup (x::l₁), from nodup_of_nodup_cons nd, have nodup l₁, from nodup_of_nodup_cons this, have x ∉ l₁, from not_mem_of_nodup_cons ‹nodup (x::l₁)›, have y ∉ x::l₁, from not_mem_of_nodup_cons nd, have x ≠ y, from assume : x = y, begin subst x, apply absurd (mem_cons_self _ _), apply ‹y ∉ y::l₁› end, -- this line used to be "exact absurd (mem_cons_self _ _) ‹y ∉ y::l₁›, but it's now a syntax error have y ∉ l₁, from not_mem_of_not_mem_cons ‹y ∉ x::l₁›, have x ∉ y::l₁, from not_mem_cons_of_ne_of_not_mem ‹x ≠ y› ‹x ∉ l₁›, have nodup (y::l₁), from nodup_cons ‹y ∉ l₁› ‹nodup l₁›, show nodup (x::y::l₁), from nodup_cons ‹x ∉ y::l₁› ‹nodup (y::l₁)›) (λ l₁ l₂ l₃ p₁ p₂ ih₁ ih₂ nd, ih₂ (ih₁ nd)) /- product -/ section product theorem perm_product_left {l₁ l₂ : list α} (t₁ : list β) : l₁ ~ l₂ → (product l₁ t₁) ~ (product l₂ t₁) := assume p : l₁ ~ l₂, perm.rec_on p (perm.refl _) (λ x l₁ l₂ p r, perm_app (perm.refl (map _ t₁)) r) (λ x y l, let m₁ := map (λ b, (x, b)) t₁ in let m₂ := map (λ b, (y, b)) t₁ in let c := product l t₁ in calc m₂ ++ (m₁ ++ c) = (m₂ ++ m₁) ++ c : by rw append.assoc ... ~ (m₁ ++ m₂) ++ c : perm_app perm_app_comm (perm.refl _) ... = m₁ ++ (m₂ ++ c) : by rw append.assoc) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) theorem perm_product_right (l : list α) {t₁ t₂ : list β} : t₁ ~ t₂ → (product l t₁) ~ (product l t₂) := list.rec_on l (λ p, by simp [nil_product]) (λ (a : α) (t : list α) (r : t₁ ~ t₂ → product t t₁ ~ product t t₂) (p : t₁ ~ t₂), perm_app (perm_map (λ b : β, (a, b)) p) (r p)) attribute [congr] theorem perm_product {l₁ l₂ : list α} {t₁ t₂ : list β} : l₁ ~ l₂ → t₁ ~ t₂ → (product l₁ t₁) ~ (product l₂ t₂) := assume p₁ p₂, trans (perm_product_left t₁ p₁) (perm_product_right l₂ p₂) end product /- filter -/ -- attribute [congr] theorem perm_filter {l₁ l₂ : list α} {p : α → Prop} [decidable_pred p] : l₁ ~ l₂ → (filter p l₁) ~ (filter p l₂) := assume u, perm.rec_on u perm.nil (assume x l₁' l₂', assume u' : l₁' ~ l₂', assume u'' : filter p l₁' ~ filter p l₂', decidable.by_cases (assume : p x, begin rw [filter_cons_of_pos _ this, filter_cons_of_pos _ this], apply perm.skip, apply u'' end) (assume : ¬ p x, begin rw [filter_cons_of_neg _ this, filter_cons_of_neg _ this], apply u'' end)) (assume x y l, decidable.by_cases (assume H1 : p x, decidable.by_cases (assume H2 : p y, begin rw [filter_cons_of_pos _ H1, filter_cons_of_pos _ H2, filter_cons_of_pos _ H2, filter_cons_of_pos _ H1], apply perm.swap end) (assume H2 : ¬ p y, by rw [filter_cons_of_pos _ H1, filter_cons_of_neg _ H2, filter_cons_of_neg _ H2, filter_cons_of_pos _ H1])) (assume H1 : ¬ p x, decidable.by_cases (assume H2 : p y, by rw [filter_cons_of_neg _ H1, filter_cons_of_pos _ H2, filter_cons_of_pos _ H2, filter_cons_of_neg _ H1]) (assume H2 : ¬ p y, by rw [filter_cons_of_neg _ H1, filter_cons_of_neg _ H2, filter_cons_of_neg _ H2, filter_cons_of_neg _ H1]))) (λ l₁ l₂ l₃ p₁ p₂ r₁ r₂, trans r₁ r₂) end perm end list
a724672aa4a00ed81ac5435bcd40206f8b7e8ecd
90edd5cdcf93124fe15627f7304069fdce3442dd
/tests/lean/run/aesop_tactic_config.lean
a9df71f8f640b98f62781457c3fc0dd3a64cb8ee
[ "Apache-2.0" ]
permissive
JLimperg/lean4-aesop
8a9d9cd3ee484a8e67fda2dd9822d76708098712
5c4b9a3e05c32f69a4357c3047c274f4b94f9c71
refs/heads/master
1,689,415,944,104
1,627,383,284,000
1,627,383,284,000
377,536,770
0
0
null
null
null
null
UTF-8
Lean
false
false
1,067
lean
/- Copyright (c) 2021 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jannis Limperg -/ -- TODO clean up this test case import Lean.Aesop inductive Even : Nat → Prop | zero : Even Nat.zero | plus_two {n} : Even n → Even (Nat.succ (Nat.succ n)) inductive Odd : Nat → Prop | one : Odd (Nat.succ Nat.zero) | plus_two {n} : Odd n → Odd (Nat.succ (Nat.succ n)) inductive EvenOrOdd : Nat → Prop | even {n} : Even n → EvenOrOdd n | odd {n} : Odd n → EvenOrOdd n set_option pp.all false set_option trace.Aesop.RuleSet false set_option trace.Aesop.Steps false -- We can add constants as rules. example : EvenOrOdd 3 := by aesop (safe [Even.zero, Even.plus_two, Odd.one, Odd.plus_two]) (unsafe [EvenOrOdd.even 50% (builder apply), EvenOrOdd.odd 50%]) -- Same with local hypotheses, or a mix. example : EvenOrOdd 3 := by have h₂ : ∀ n, Odd n → EvenOrOdd n := λ _ p => EvenOrOdd.odd p aesop (safe [Odd.one, Odd.plus_two]) (unsafe [EvenOrOdd.even 50%, h₂ 50%])
e0a781e6674ffa8644eb4f3d44e17b4d04124488
82e44445c70db0f03e30d7be725775f122d72f3e
/src/ring_theory/laurent_series.lean
b91618ab7b928818a80d65eff4c5dc0cb0781058
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
6,536
lean
/- Copyright (c) 2021 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import ring_theory.hahn_series import ring_theory.localization /-! # Laurent Series ## Main Definitions * Defines `laurent_series` as an abbreviation for `hahn_series ℤ`. * Provides a coercion `power_series R` into `laurent_series R` given by `hahn_series.of_power_series`. * Defines `laurent_series.power_series_part` * Defines the localization map `laurent_series.of_power_series_localization` which evaluates to `hahn_series.of_power_series`. -/ open hahn_series open_locale big_operators classical noncomputable theory /-- A `laurent_series` is implemented as a `hahn_series` with value group `ℤ`. -/ abbreviation laurent_series (R : Type*) [has_zero R] := hahn_series ℤ R variables {R : Type*} namespace laurent_series section semiring variable [semiring R] instance : has_coe (power_series R) (laurent_series R) := ⟨hahn_series.of_power_series ℤ R⟩ lemma coe_power_series (x : power_series R) : (x : laurent_series R) = hahn_series.of_power_series ℤ R x := rfl @[simp] lemma coeff_coe_power_series (x : power_series R) (n : ℕ) : hahn_series.coeff (x : laurent_series R) n = power_series.coeff R n x := by rw [← int.nat_cast_eq_coe_nat, coe_power_series, of_power_series_apply_coeff] /-- This is a power series that can be multiplied by an integer power of `X` to give our Laurent series. If the Laurent series is nonzero, `power_series_part` has a nonzero constant term. -/ def power_series_part (x : laurent_series R) : power_series R := power_series.mk (λ n, x.coeff (x.order + n)) @[simp] lemma power_series_part_coeff (x : laurent_series R) (n : ℕ) : power_series.coeff R n x.power_series_part = x.coeff (x.order + n) := power_series.coeff_mk _ _ @[simp] lemma power_series_part_zero : power_series_part (0 : laurent_series R) = 0 := by { ext, simp } @[simp] lemma power_series_part_eq_zero (x : laurent_series R) : x.power_series_part = 0 ↔ x = 0 := begin split, { contrapose!, intro h, rw [power_series.ext_iff, not_forall], refine ⟨0, _⟩, simp [coeff_order_ne_zero h] }, { rintro rfl, simp } end @[simp] lemma single_order_mul_power_series_part (x : laurent_series R) : (single x.order 1 : laurent_series R) * x.power_series_part = x := begin ext n, rw [← sub_add_cancel n x.order, single_mul_coeff_add, sub_add_cancel, one_mul], by_cases h : x.order ≤ n, { rw [int.eq_nat_abs_of_zero_le (sub_nonneg_of_le h), coeff_coe_power_series, power_series_part_coeff, ← int.eq_nat_abs_of_zero_le (sub_nonneg_of_le h), add_sub_cancel'_right] }, { rw [coe_power_series, of_power_series_apply, emb_domain_notin_range], { contrapose! h, exact order_le_of_coeff_ne_zero h.symm }, { contrapose! h, simp only [set.mem_range, rel_embedding.coe_fn_mk, function.embedding.coe_fn_mk, int.nat_cast_eq_coe_nat] at h, obtain ⟨m, hm⟩ := h, rw [← sub_nonneg, ← hm], exact int.zero_le_of_nat _ } } end lemma of_power_series_power_series_part (x : laurent_series R) : of_power_series ℤ R x.power_series_part = single (-x.order) 1 * x := begin refine eq.trans _ (congr rfl x.single_order_mul_power_series_part), rw [← mul_assoc, single_mul_single, neg_add_self, mul_one, ← C_apply, C_one, one_mul, coe_power_series], end @[simp] lemma of_power_series_X : of_power_series ℤ R power_series.X = single 1 1 := begin ext n, cases n, { rw [int.of_nat_eq_coe, ← int.nat_cast_eq_coe_nat, of_power_series_apply_coeff], by_cases h1 : n = 1, { simp [h1] }, { rw [power_series.coeff_X, single_coeff, if_neg h1, if_neg], contrapose! h1, rw [← nat.cast_one] at h1, exact nat.cast_injective h1 } }, { rw [of_power_series_apply, emb_domain_notin_range, single_coeff_of_ne], { dec_trivial }, rw [set.mem_range, not_exists], intro m, simp only [rel_embedding.coe_fn_mk, function.embedding.coe_fn_mk, int.nat_cast_eq_coe_nat], dec_trivial } end end semiring @[simp] lemma of_power_series_X_pow [comm_semiring R] (n : ℕ) : of_power_series ℤ R (power_series.X ^ n) = single (n : ℤ) 1 := begin rw ring_hom.map_pow, induction n with n ih, { refl }, rw [pow_succ, int.coe_nat_succ, ih, of_power_series_X, mul_comm, single_mul_single, one_mul], end instance [comm_semiring R] : algebra (power_series R) (laurent_series R) := (hahn_series.of_power_series ℤ R).to_algebra @[simp] lemma coe_algebra_map [comm_semiring R] : ⇑(algebra_map (power_series R) (laurent_series R)) = hahn_series.of_power_series ℤ R := rfl /-- The localization map from power series to Laurent series. -/ @[simps] instance of_power_series_localization [comm_ring R] : is_localization (submonoid.powers (power_series.X : power_series R)) (laurent_series R) := { map_units := (begin rintro ⟨_, n, rfl⟩, refine ⟨⟨single (n : ℤ) 1, single (-n : ℤ) 1, _, _⟩, _⟩, { simp only [single_mul_single, mul_one, add_right_neg], refl }, { simp only [single_mul_single, mul_one, add_left_neg], refl }, { simp } end), surj := (begin intro z, by_cases h : 0 ≤ z.order, { refine ⟨⟨power_series.X ^ (int.nat_abs z.order) * power_series_part z, 1⟩, _⟩, simp only [ring_hom.map_one, mul_one, ring_hom.map_mul, coe_algebra_map, of_power_series_X_pow, submonoid.coe_one], rw [int.nat_abs_of_nonneg h, ← coe_power_series, single_order_mul_power_series_part] }, { refine ⟨⟨power_series_part z, power_series.X ^ (int.nat_abs z.order), ⟨_, rfl⟩⟩, _⟩, simp only [coe_algebra_map, of_power_series_power_series_part], rw [mul_comm _ z], refine congr rfl _, rw [subtype.coe_mk, of_power_series_X_pow, int.of_nat_nat_abs_of_nonpos], exact le_of_not_ge h } end), eq_iff_exists := (begin intros x y, rw [coe_algebra_map, of_power_series_injective.eq_iff], split, { rintro rfl, exact ⟨1, rfl⟩ }, { rintro ⟨⟨_, n, rfl⟩, hc⟩, rw [← sub_eq_zero, ← sub_mul, power_series.ext_iff] at hc, rw [← sub_eq_zero, power_series.ext_iff], intro m, have h := hc (m + n), rw [linear_map.map_zero, subtype.coe_mk, power_series.X_pow_eq, power_series.monomial, power_series.coeff, finsupp.single_add, mv_power_series.coeff_add_mul_monomial, mul_one] at h, exact h } end) } end laurent_series
063ab25d861ac606283546f2f8b8791b0a8799dd
271e26e338b0c14544a889c31c30b39c989f2e0f
/stage0/src/Init/Lean/Parser/Level.lean
39aac716476d6ebd4189c52c73ccb754bfe9a0ae
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,448
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.Lean.Parser.Parser namespace Lean namespace Parser @[init mkBuiltinParsingTablesRef] constant builtinLevelParsingTable : IO.Ref ParsingTables := arbitrary _ @[init] def regBuiltinLevelParserAttr : IO Unit := registerBuiltinParserAttribute `builtinLevelParser `Lean.Parser.builtinLevelParsingTable def mkLevelParserAttribute : IO ParserAttribute := registerParserAttribute `levelParser "level" "universe level parser" (some builtinLevelParsingTable) @[init mkLevelParserAttribute] constant levelParserAttribute : ParserAttribute := arbitrary _ @[inline] def levelParser {k : ParserKind} (rbp : Nat := 0) : Parser k := { fn := fun _ => levelParserAttribute.runParserFn rbp } namespace Level @[builtinLevelParser] def paren := parser! symbol "(" appPrec >> levelParser >> ")" @[builtinLevelParser] def max := parser! symbolOrIdent "max" >> many1 (levelParser appPrec) @[builtinLevelParser] def imax := parser! symbolOrIdent "imax" >> many1 (levelParser appPrec) @[builtinLevelParser] def hole := parser! "_" @[builtinLevelParser] def num := parser! numLit @[builtinLevelParser] def ident := parser! ident @[builtinLevelParser] def addLit := tparser! pushLeading >> symbol "+" (65:Nat) >> numLit end Level end Parser end Lean
17be43a3e854cf5e93a8022458776351082c5a08
0003047346476c031128723dfd16fe273c6bc605
/src/analysis/normed_space/operator_norm.lean
346e6e6d7efcbfa0b15eebd3437d2be747c5e088
[ "Apache-2.0" ]
permissive
ChandanKSingh/mathlib
d2bf4724ccc670bf24915c12c475748281d3fb73
d60d1616958787ccb9842dc943534f90ea0bab64
refs/heads/master
1,588,238,823,679
1,552,867,469,000
1,552,867,469,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,816
lean
/- Copyright (c) 2019 Jan-David Salchow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow The space of bounded linear maps Define the set of bounded linear maps between normed spaces and show basic facts about it. In particular (*) define a set L(E,F) of bounded linear maps between k normed spaces, (*) show that L(E,F) is a vector subspace of E → F, (*) define the 'operator norm' on L(E,F) and show that it induces the structure of a normed space on L(E,F). -/ import algebra.module import analysis.normed_space.bounded_linear_maps variables {k : Type*} variables {E : Type*} {F : Type*} -- Define the subspace of bounded linear maps, introduce the notation L(E,F) for the set of bounded linear maps. section bounded_linear_maps variables [hnfk : normed_field k] [normed_space k E] [normed_space k F] include hnfk def bounded_linear_maps : subspace k (E → F) := { carrier := {A : E → F | is_bounded_linear_map A}, zero := is_bounded_linear_map.zero, add := assume A B, is_bounded_linear_map.add, smul := assume c A, is_bounded_linear_map.smul c } local notation `L(` E `,` F `)` := @bounded_linear_maps _ E F _ _ _ /-- Coerce bounded linear maps to functions. -/ instance bounded_linear_maps.to_fun : has_coe_to_fun $ L(E,F) := {F := λ _, (E → F), coe := (λ f, f.val)} @[extensionality] theorem ext {A B : L(E,F)} (H : ∀ x, A x = B x) : A = B := set_coe.ext $ funext H /-- Bounded linear maps are ... bounded -/ lemma exists_bound (A : L(E,F)) : ∃ c, c > 0 ∧ ∀ x : E, ∥A x∥ ≤ c * ∥x∥ := A.property.bound /-- Bounded linear maps are conveniently bounded on the unit ball. -/ lemma exists_bound' (A : L(E,F)) : ∃ c, c > 0 ∧ ∀ x : E, ∥x∥ ≤ 1 → ∥A x∥ ≤ c := let ⟨c, _, H⟩ := exists_bound A in exists.intro c ⟨‹c > 0›, assume x _, calc ∥A x∥ ≤ c * ∥x∥ : H x ... ≤ c * 1 : (mul_le_mul_left ‹c > 0›).mpr ‹∥x∥ ≤ 1› ... = c : mul_one c⟩ end bounded_linear_maps /- Now define the operator norm. We only do this for normed spaces over ℝ, since we need a scalar multiplication with reals to prove that ∥A x∥ ≤ ∥A∥ * ∥x∥. It would be enough to have a vector space over a normed field k with a real scalar multiplication and certain compatibility conditions. The main task is to show that the operator norm is definite, homogeneous, and satisfies the triangle inequality. This is done after a few preliminary lemmas necessary to deal with cSup. -/ section operator_norm variables [normed_space ℝ E] [normed_space ℝ F] open lattice set local notation `L(` E `,` F `)` := @bounded_linear_maps _ E F _ _ _ noncomputable def to_linear_map (A : L(E, F)) : linear_map _ E F := {to_fun := A.val, ..A.property} /-- The operator norm of a bounded linear map A : E → F is the sup of the set ∥A x∥ with ∥x∥ ≤ 1. If E = {0} we set ∥A∥ = 0. -/ noncomputable def operator_norm (A : L(E, F)) : ℝ := Sup (image (λ x, ∥A x∥) {x | ∥x∥ ≤ 1}) noncomputable instance bounded_linear_maps.to_has_norm : has_norm L(E,F) := {norm := operator_norm} lemma norm_of_unit_ball_bdd_above (A : L(E,F)) : bdd_above (image (norm ∘ A) {x | ∥x∥ ≤ 1}) := let ⟨c, _, H⟩ := (exists_bound' A : ∃ c, c > 0 ∧ ∀ x : E, ∥x∥ ≤ 1 → ∥A x∥ ≤ c) in bdd_above.mk c (assume r ⟨x, (_ : ∥x∥ ≤ 1), (_ : ∥A x∥ = r)⟩, show r ≤ c, from calc r = ∥A x∥ : eq.symm ‹∥A x∥ = r› ... ≤ c : H x ‹∥x∥ ≤ 1›) lemma zero_in_im_ball (A : L(E,F)) : (0:ℝ) ∈ {r : ℝ | ∃ (x : E), ∥x∥ ≤ 1 ∧ ∥A x∥ = r} := have A 0 = 0, from (to_linear_map A).map_zero, exists.intro (0:E) $ and.intro (by rw[norm_zero]; exact zero_le_one) (by rw[‹A 0 = 0›]; simp) lemma operator_norm_nonneg (A : L(E,F)) : 0 ≤ ∥A∥ := have (0:ℝ) ∈ _, from zero_in_im_ball A, show 0 ≤ Sup (image (norm ∘ A) {x | ∥x∥ ≤ 1}), from let ⟨c, _, H⟩ := (exists_bound' A : ∃ c, c > 0 ∧ ∀ x : E, ∥x∥ ≤ 1 → ∥A x∥ ≤ c) in le_cSup (norm_of_unit_ball_bdd_above A) ‹(0:ℝ) ∈ _› lemma bounded_by_operator_norm_on_unit_vector (A : L(E, F)) {x : E} (_ : ∥x∥ = 1) : ∥A x∥ ≤ ∥A∥ := show ∥A x∥ ≤ Sup (image (norm ∘ A) {x | ∥x∥ ≤ 1}), from let ⟨c, _, _⟩ := (exists_bound A : ∃ c, c > 0 ∧ ∀ x : E, ∥ A x ∥ ≤ c * ∥ x ∥) in have ∥A x∥ ∈ (image (norm ∘ A) {x | ∥x∥ ≤ 1}), from mem_image_of_mem _ $ le_of_eq ‹∥x∥ = 1›, le_cSup (norm_of_unit_ball_bdd_above A) ‹∥A x∥ ∈ _› /-- This is the fundamental property of the operator norm: ∥A x∥ ≤ ∥A∥ * ∥x∥. -/ theorem bounded_by_operator_norm {A : L(E,F)} {x : E} : ∥A x∥ ≤ ∥A∥ * ∥x∥ := have A 0 = 0, from (to_linear_map A).map_zero, classical.by_cases (assume : x = (0:E), show ∥A x∥ ≤ ∥A∥ * ∥x∥, by rw[‹x = 0›, ‹A 0 = 0›, norm_zero, norm_zero, mul_zero]; exact le_refl 0) (assume : x ≠ (0:E), have ∥x∥ ≠ 0, from ne_of_gt $ (norm_pos_iff x).mpr ‹x ≠ 0›, have ∥∥x∥⁻¹∥ = ∥x∥⁻¹, from abs_of_nonneg $ inv_nonneg.mpr $ norm_nonneg x, have ∥∥x∥⁻¹•x∥ = 1, begin rw[norm_smul, ‹∥∥x∥⁻¹∥ = ∥x∥⁻¹›], exact inv_mul_cancel ‹∥x∥ ≠ 0› end, calc ∥A x∥ = (∥x∥ * ∥x∥⁻¹) * ∥A x∥ : by rw[mul_inv_cancel ‹∥x∥ ≠ 0›]; ring ... = ∥∥x∥⁻¹∥ * ∥A x∥ * ∥x∥ : by rw[‹∥∥x∥⁻¹∥ = ∥x∥⁻¹›]; ring ... = ∥∥x∥⁻¹• A x ∥ * ∥x∥ : by rw[←normed_space.norm_smul ∥x∥⁻¹ (A x)] ... = ∥A (∥x∥⁻¹• x)∥ * ∥x∥ : by { change ∥∥x∥⁻¹ • A.val x∥ * ∥x∥ = ∥A.val (∥x∥⁻¹ • x)∥ * ∥x∥, rw A.property.smul} ... ≤ ∥A∥ * ∥x∥ : (mul_le_mul_right ((norm_pos_iff x).mpr ‹x ≠ 0›)).mpr (bounded_by_operator_norm_on_unit_vector A ‹∥∥x∥⁻¹•x∥ = 1›)) lemma bounded_by_operator_norm_on_unit_ball (A : L(E, F)) {x : E} (_ : ∥x∥ ≤ 1) : ∥A x∥ ≤ ∥A∥ := calc ∥A x∥ ≤ ∥A∥ * ∥x∥ : bounded_by_operator_norm ... ≤ ∥A∥ * 1 : mul_le_mul_of_nonneg_left ‹∥x∥ ≤ 1› (operator_norm_nonneg A) ... = ∥A∥ : mul_one ∥A∥ lemma operator_norm_bounded_by {A : L(E,F)} (c : nnreal) : (∀ x : E, ∥x∥ ≤ 1 → ∥A x∥ ≤ (c:ℝ)) → ∥A∥ ≤ c := assume H : ∀ x : E, ∥x∥ ≤ 1 → ∥A x∥ ≤ c, suffices Sup (image (norm ∘ A) {x | ∥x∥ ≤ 1}) ≤ c, by assumption, cSup_le (set.ne_empty_of_mem $ zero_in_im_ball A) (show ∀ (r : ℝ), r ∈ (image (norm ∘ A) {x | ∥x∥ ≤ 1}) → r ≤ c, from assume r ⟨x, _, _⟩, calc r = ∥A x∥ : eq.symm ‹_› ... ≤ c : H x ‹_›) theorem operator_norm_triangle (A : L(E,F)) (B : L(E,F)) : ∥A + B∥ ≤ ∥A∥ + ∥B∥ := operator_norm_bounded_by (⟨∥A∥, operator_norm_nonneg A⟩ + ⟨∥B∥, operator_norm_nonneg B⟩) (assume x _, by exact calc ∥(A + B) x∥ = ∥A x + B x∥ : by refl ... ≤ ∥A x∥ + ∥B x∥ : by exact norm_triangle _ _ ... ≤ ∥A∥ + ∥B∥ : by exact add_le_add (bounded_by_operator_norm_on_unit_ball A ‹_›) (bounded_by_operator_norm_on_unit_ball B ‹_›)) theorem operator_norm_zero_iff (A : L(E,F)) : ∥A∥ = 0 ↔ A = 0 := have A 0 = 0, from (to_linear_map A).map_zero, iff.intro (assume : ∥A∥ = 0, suffices ∀ x, A x = 0, from ext this, assume x, have ∥A x∥ ≤ 0, from calc ∥A x∥ ≤ ∥A∥ * ∥x∥ : bounded_by_operator_norm ... = 0 : by rw[‹∥A∥ = 0›]; ring, (norm_le_zero_iff (A x)).mp this) (assume : A = 0, let M := {r : ℝ | ∃ (x : E), ∥x∥ ≤ 1 ∧ ∥A x∥ = r} in -- note that we have M = (image (norm ∘ A) {x | ∥x∥ ≤ 1}), from rfl suffices Sup M = 0, by assumption, suffices M = {0}, by rw[this]; exact cSup_singleton 0, (set.ext_iff M {0}).mpr $ assume r, iff.intro (assume : ∃ (x : E), ∥x∥ ≤ 1 ∧ ∥A x∥ = r, let ⟨x, _, _⟩ := this in have h : ∥(0:F)∥ = r, by rwa[‹A=0›] at *, by finish) (assume : r ∈ {0}, have r = 0, from set.eq_of_mem_singleton this, exists.intro (0:E) $ ⟨by rw[norm_zero]; exact zero_le_one, by rw[this, ‹A 0 = 0›]; simp⟩)) theorem operator_norm_homogeneous (c : ℝ) (A : L(E, F)) : ∥c • A∥ = ∥c∥ * ∥A∥ := -- ∥c • A∥ is the supremum of the image of the map x ↦ ∥c • A x∥ on the unit ball in E -- we show that this is the same as ∥c∥ * ∥A∥ by showing 1) and 2): -- 1) ∥c∥ * ∥A∥ is an upper bound for the image of x ↦ ∥c • A x∥ on the unit ball -- 2) any w < ∥c∥ * ∥A∥ is not an upper bound (this is equivalent to showing that every upper bound is ≥ ∥c∥ * ∥A∥) suffices (∀ a ∈ _, a ≤ ∥c∥ * ∥A∥) ∧ (∀ (ub : ℝ), (∀ a ∈ _, a ≤ ub) → ∥c∥ * ∥A∥ ≤ ub), from cSup_intro' (show _ ≠ ∅, from set.ne_empty_of_mem $ zero_in_im_ball _) this.1 this.2, and.intro (show ∀ a ∈ image (λ x, ∥(c • A) x∥) {x : E | ∥x∥ ≤ 1}, a ≤ ∥c∥ * ∥A∥, from assume a (hₐ : ∃ (x : E), ∥x∥ ≤ 1 ∧ ∥(c • A) x∥ = a), let ⟨x, _, _⟩ := hₐ in calc a = ∥c • A x∥ : eq.symm ‹_› ... = ∥c∥ * ∥A x∥ : by rw[←norm_smul c (A x)]; refl ... ≤ ∥c∥ * ∥A∥ : mul_le_mul_of_nonneg_left (bounded_by_operator_norm_on_unit_ball A ‹∥x∥ ≤ 1›) (norm_nonneg c)) (show ∀ (ub : ℝ), (∀ a ∈ image (λ (x : E), ∥(c • A) x∥) {x : E | ∥x∥ ≤ 1}, a ≤ ub) → ∥c∥ * ∥A∥ ≤ ub, from assume u u_is_ub, classical.by_cases (assume : c = 0, calc ∥c∥ * ∥A∥ = 0 : by rw[‹c=0›, norm_zero, zero_mul] ... ≤ u : u_is_ub (0:ℝ) $ zero_in_im_ball _) (assume : c ≠ 0, have ∥c∥ ≠ 0, from ne_of_gt $ (norm_pos_iff c).mpr ‹c ≠ 0›, have bla : u = ∥c∥ * (∥c∥⁻¹ * u), by rw[←mul_assoc, mul_inv_cancel ‹∥c∥ ≠ 0›, one_mul], suffices ∥A∥ ≤ ∥c∥⁻¹ * u, from have u = ∥c∥ * (∥c∥⁻¹ * u), by rw[←mul_assoc, mul_inv_cancel ‹∥c∥ ≠ 0›, one_mul], by rw[this]; exact mul_le_mul_of_nonneg_left ‹_› (norm_nonneg c), cSup_le (set.ne_empty_of_mem $ zero_in_im_ball _) (assume n (H : ∃ (x : E), ∥x∥ ≤ 1 ∧ ∥A x∥ = n), let ⟨x, _, _⟩ := H in calc n = ∥A x∥ : eq.symm ‹∥A x∥ = n› ... = ∥c∥⁻¹ * ∥c • A x∥ : by rw[norm_smul, ←mul_assoc, inv_mul_cancel ‹∥c∥ ≠ 0›, one_mul] ... ≤ ∥c∥⁻¹ * u : mul_le_mul_of_nonneg_left (u_is_ub ∥c • A x∥ ⟨x, ‹∥x∥ ≤ 1›, rfl⟩) $ inv_nonneg.mpr $ norm_nonneg c))) /-- Expose L(E,F) equipped with the operator norm as normed space. -/ noncomputable instance bounded_linear_maps.to_normed_space : normed_space ℝ L(E,F) := normed_space.of_core ℝ L(E,F) { norm_eq_zero_iff := operator_norm_zero_iff, norm_smul := operator_norm_homogeneous, triangle := operator_norm_triangle } end operator_norm
6450d4d6b462f1e923f8878f9de6bad401f421d0
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/group_theory/solvable.lean
70a58348d303378c069fa5736b2ab72e6e53481a
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,085
lean
/- Copyright (c) 2021 Jordan Brown, Thomas Browning, Patrick Lutz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jordan Brown, Thomas Browning, Patrick Lutz -/ import group_theory.abelianization import data.bracket /-! # Solvable Groups In this file we introduce the notion of a solvable group. We define a solvable group as one whose derived series is eventually trivial. This requires defining the commutator of two subgroups and the derived series of a group. ## Main definitions * `general_commutator H₁ H₂` : the commutator of the subgroups `H₁` and `H₂` * `derived_series G n` : the `n`th term in the derived series of `G`, defined by iterating `general_commutator` starting with the top subgroup * `is_solvable G` : the group `G` is solvable -/ open subgroup variables {G : Type*} [group G] section general_commutator /-- The commutator of two subgroups `H₁` and `H₂`. -/ instance general_commutator : has_bracket (subgroup G) (subgroup G) := ⟨λ H₁ H₂, closure {x | ∃ (p ∈ H₁) (q ∈ H₂), p * q * p⁻¹ * q⁻¹ = x}⟩ lemma general_commutator_def (H₁ H₂ : subgroup G) : ⁅H₁, H₂⁆ = closure {x | ∃ (p ∈ H₁) (q ∈ H₂), p * q * p⁻¹ * q⁻¹ = x} := rfl instance general_commutator_normal (H₁ H₂ : subgroup G) [h₁ : H₁.normal] [h₂ : H₂.normal] : normal ⁅H₁, H₂⁆ := begin let base : set G := {x | ∃ (p ∈ H₁) (q ∈ H₂), p * q * p⁻¹ * q⁻¹ = x}, suffices h_base : base = group.conjugates_of_set base, { dsimp only [general_commutator_def, ←base], rw h_base, exact subgroup.normal_closure_normal }, apply set.subset.antisymm group.subset_conjugates_of_set, intros a h, rw group.mem_conjugates_of_set_iff at h, rcases h with ⟨b, ⟨c, hc, e, he, rfl⟩, d, rfl⟩, exact ⟨d * c * d⁻¹, h₁.conj_mem c hc d, d * e * d⁻¹, h₂.conj_mem e he d, by group⟩, end lemma general_commutator_mono {H₁ H₂ K₁ K₂ : subgroup G} (h₁ : H₁ ≤ K₁) (h₂ : H₂ ≤ K₂) : ⁅H₁, H₂⁆ ≤ ⁅K₁, K₂⁆ := begin apply closure_mono, rintros x ⟨p, hp, q, hq, rfl⟩, exact ⟨p, h₁ hp, q, h₂ hq, rfl⟩, end lemma general_commutator_def' (H₁ H₂ : subgroup G) [H₁.normal] [H₂.normal] : ⁅H₁, H₂⁆ = normal_closure {x | ∃ (p ∈ H₁) (q ∈ H₂), p * q * p⁻¹ * q⁻¹ = x} := by rw [← normal_closure_eq_self ⁅H₁, H₂⁆, general_commutator_def, normal_closure_closure_eq_normal_closure] lemma general_commutator_le (H₁ H₂ : subgroup G) (K : subgroup G) : ⁅H₁, H₂⁆ ≤ K ↔ ∀ (p ∈ H₁) (q ∈ H₂), p * q * p⁻¹ * q⁻¹ ∈ K := begin rw [general_commutator, closure_le], split, { intros h p hp q hq, exact h ⟨p, hp, q, hq, rfl⟩, }, { rintros h x ⟨p, hp, q, hq, rfl⟩, exact h p hp q hq, } end lemma general_commutator_comm (H₁ H₂ : subgroup G) : ⁅H₁, H₂⁆ = ⁅H₂, H₁⁆ := begin suffices : ∀ H₁ H₂ : subgroup G, ⁅H₁, H₂⁆ ≤ ⁅H₂, H₁⁆, { exact le_antisymm (this _ _) (this _ _) }, intros H₁ H₂, rw general_commutator_le, intros p hp q hq, have h : (p * q * p⁻¹ * q⁻¹)⁻¹ ∈ ⁅H₂, H₁⁆ := subset_closure ⟨q, hq, p, hp, by group⟩, convert inv_mem ⁅H₂, H₁⁆ h, group, end lemma general_commutator_le_right (H₁ H₂ : subgroup G) [h : normal H₂] : ⁅H₁, H₂⁆ ≤ H₂ := begin rw general_commutator_le, intros p hp q hq, exact mul_mem H₂ (h.conj_mem q hq p) (inv_mem H₂ hq), end lemma general_commutator_le_left (H₁ H₂ : subgroup G) [h : normal H₁] : ⁅H₁, H₂⁆ ≤ H₁ := begin rw general_commutator_comm, exact general_commutator_le_right H₂ H₁, end @[simp] lemma general_commutator_bot (H : subgroup G) : ⁅H, ⊥⁆ = (⊥ : subgroup G) := by { rw eq_bot_iff, exact general_commutator_le_right H ⊥ } @[simp] lemma bot_general_commutator (H : subgroup G) : ⁅(⊥ : subgroup G), H⁆ = (⊥ : subgroup G) := by { rw eq_bot_iff, exact general_commutator_le_left ⊥ H } lemma general_commutator_le_inf (H₁ H₂ : subgroup G) [normal H₁] [normal H₂] : ⁅H₁, H₂⁆ ≤ H₁ ⊓ H₂ := by simp only [general_commutator_le_left, general_commutator_le_right, le_inf_iff, and_self] end general_commutator section derived_series variables (G) /-- The derived series of the group `G`, obtained by starting from the subgroup `⊤` and repeatedly taking the commutator of the previous subgroup with itself for `n` times. -/ def derived_series : ℕ → subgroup G | 0 := ⊤ | (n + 1) := ⁅(derived_series n), (derived_series n)⁆ @[simp] lemma derived_series_zero : derived_series G 0 = ⊤ := rfl @[simp] lemma derived_series_succ (n : ℕ) : derived_series G (n + 1) = ⁅(derived_series G n), (derived_series G n)⁆ := rfl lemma derived_series_normal (n : ℕ) : (derived_series G n).normal := begin induction n with n ih, { exact subgroup.top_normal, }, { rw derived_series_succ, exactI general_commutator_normal (derived_series G n) (derived_series G n), } end @[simp] lemma general_commutator_eq_commutator : ⁅(⊤ : subgroup G), (⊤ : subgroup G)⁆ = commutator G := begin rw [commutator, general_commutator_def'], apply le_antisymm; apply normal_closure_mono, { exact λ x ⟨p, _, q, _, h⟩, ⟨p, q, h⟩, }, { exact λ x ⟨p, q, h⟩, ⟨p, mem_top p, q, mem_top q, h⟩, } end lemma commutator_def' : commutator G = subgroup.closure {x : G | ∃ p q, p * q * p⁻¹ * q⁻¹ = x} := begin rw [← general_commutator_eq_commutator, general_commutator], apply le_antisymm; apply closure_mono, { exact λ x ⟨p, _, q, _, h⟩, ⟨p, q, h⟩ }, { exact λ x ⟨p, q, h⟩, ⟨p, mem_top p, q, mem_top q, h⟩ } end @[simp] lemma derived_series_one : derived_series G 1 = commutator G := general_commutator_eq_commutator G end derived_series section commutator_map variables {G} {G' : Type*} [group G'] {f : G →* G'} lemma map_commutator_eq_commutator_map (H₁ H₂ : subgroup G) : ⁅H₁, H₂⁆.map f = ⁅H₁.map f, H₂.map f⁆ := begin rw [general_commutator, general_commutator, monoid_hom.map_closure], apply le_antisymm; apply closure_mono, { rintros _ ⟨x, ⟨p, hp, q, hq, rfl⟩, rfl⟩, refine ⟨f p, mem_map.mpr ⟨p, hp, rfl⟩, f q, mem_map.mpr ⟨q, hq, rfl⟩, by simp *⟩, }, { rintros x ⟨_, ⟨p, hp, rfl⟩, _, ⟨q, hq, rfl⟩, rfl⟩, refine ⟨p * q * p⁻¹ * q⁻¹, ⟨p, hp, q, hq, rfl⟩, by simp *⟩, }, end lemma commutator_le_map_commutator {H₁ H₂ : subgroup G} {K₁ K₂ : subgroup G'} (h₁ : K₁ ≤ H₁.map f) (h₂ : K₂ ≤ H₂.map f) : ⁅K₁, K₂⁆ ≤ ⁅H₁, H₂⁆.map f := by { rw map_commutator_eq_commutator_map, exact general_commutator_mono h₁ h₂ } section derived_series_map variables (f) lemma map_derived_series_le_derived_series (n : ℕ) : (derived_series G n).map f ≤ derived_series G' n := begin induction n with n ih, { simp only [derived_series_zero, le_top], }, { simp only [derived_series_succ, map_commutator_eq_commutator_map, general_commutator_mono, *], } end variables {f} lemma derived_series_le_map_derived_series (hf : function.surjective f) (n : ℕ) : derived_series G' n ≤ (derived_series G n).map f := begin induction n with n ih, { rwa [derived_series_zero, derived_series_zero, top_le_iff, ← monoid_hom.range_eq_map, ← monoid_hom.range_top_iff_surjective.mpr], }, { simp only [*, derived_series_succ, commutator_le_map_commutator], } end lemma map_derived_series_eq (hf : function.surjective f) (n : ℕ) : (derived_series G n).map f = derived_series G' n := le_antisymm (map_derived_series_le_derived_series f n) (derived_series_le_map_derived_series hf n) end derived_series_map end commutator_map section solvable variables (G) /-- A group `G` is solvable if its derived series is eventually trivial. We use this definition because it's the most convenient one to work with. -/ class is_solvable : Prop := (solvable : ∃ n : ℕ, derived_series G n = ⊥) lemma is_solvable_def : is_solvable G ↔ ∃ n : ℕ, derived_series G n = ⊥ := ⟨λ h, h.solvable, λ h, ⟨h⟩⟩ @[priority 100] instance comm_group.is_solvable {G : Type*} [comm_group G] : is_solvable G := begin use 1, rw [eq_bot_iff, derived_series_one], calc commutator G ≤ (monoid_hom.id G).ker : abelianization.commutator_subset_ker (monoid_hom.id G) ... = ⊥ : rfl, end lemma is_solvable_of_comm {G : Type*} [hG : group G] (h : ∀ a b : G, a * b = b * a) : is_solvable G := begin letI hG' : comm_group G := { mul_comm := h .. hG }, tactic.unfreeze_local_instances, cases hG, exact comm_group.is_solvable, end lemma is_solvable_of_top_eq_bot (h : (⊤ : subgroup G) = ⊥) : is_solvable G := ⟨⟨0, h⟩⟩ @[priority 100] instance is_solvable_of_subsingleton [subsingleton G] : is_solvable G := is_solvable_of_top_eq_bot G (by ext; simp at *) variables {G} {G' : Type*} [group G'] {f : G →* G'} lemma solvable_of_solvable_injective (hf : function.injective f) [h : is_solvable G'] : is_solvable G := begin rw is_solvable_def at *, cases h with n hn, use n, rw ← map_eq_bot_iff_of_injective _ hf, rw eq_bot_iff at *, calc map f (derived_series G n) ≤ derived_series G' n : map_derived_series_le_derived_series f n ... ≤ ⊥ : hn, end instance subgroup_solvable_of_solvable (H : subgroup G) [h : is_solvable G] : is_solvable H := solvable_of_solvable_injective (show function.injective (subtype H), from subtype.val_injective) lemma solvable_of_surjective (hf : function.surjective f) [h : is_solvable G] : is_solvable G' := begin rw is_solvable_def at *, cases h with n hn, use n, calc derived_series G' n = (derived_series G n).map f : eq.symm (map_derived_series_eq hf n) ... = (⊥ : subgroup G).map f : by rw hn ... = ⊥ : map_bot f, end instance solvable_quotient_of_solvable (H : subgroup G) [H.normal] [h : is_solvable G] : is_solvable (quotient_group.quotient H) := solvable_of_surjective (show function.surjective (quotient_group.mk' H), by tidy) lemma solvable_of_ker_le_range {G' G'' : Type*} [group G'] [group G''] (f : G' →* G) (g : G →* G'') (hfg : g.ker ≤ f.range) [hG' : is_solvable G'] [hG'' : is_solvable G''] : is_solvable G := begin tactic.unfreeze_local_instances, obtain ⟨n, hn⟩ := hG'', suffices : ∀ k : ℕ, derived_series G (n + k) ≤ (derived_series G' k).map f, { obtain ⟨m, hm⟩ := hG', use n + m, specialize this m, rwa [hm, map_bot, le_bot_iff] at this }, intro k, induction k with k hk, { rw [add_zero, derived_series_zero, ←monoid_hom.range_eq_map], refine le_trans _ hfg, rw [←map_eq_bot_iff, eq_bot_iff, ←hn], exact map_derived_series_le_derived_series g n }, { rw [nat.add_succ, derived_series_succ, derived_series_succ], exact commutator_le_map_commutator hk hk }, end instance solvable_prod {G' : Type*} [group G'] [h : is_solvable G] [h' : is_solvable G'] : is_solvable (G × G') := solvable_of_ker_le_range (monoid_hom.inl G G') (monoid_hom.snd G G') (λ x hx, ⟨x.1, prod.ext rfl hx.symm⟩) end solvable section is_simple_group variable [is_simple_group G] lemma is_simple_group.derived_series_succ {n : ℕ} : derived_series G n.succ = commutator G := begin induction n with n ih, { exact derived_series_one _ }, rw [derived_series_succ, ih], cases (commutator.normal G).eq_bot_or_eq_top with h h; simp [h] end lemma is_simple_group.comm_iff_is_solvable : (∀ a b : G, a * b = b * a) ↔ is_solvable G := ⟨is_solvable_of_comm, λ ⟨⟨n, hn⟩⟩, begin cases n, { rw derived_series_zero at hn, intros a b, refine (mem_bot.1 _).trans (mem_bot.1 _).symm; { rw ← hn, exact mem_top _ } }, { rw is_simple_group.derived_series_succ at hn, intros a b, rw [← mul_inv_eq_one, mul_inv_rev, ← mul_assoc, ← mem_bot, ← hn], exact subset_normal_closure ⟨a, b, rfl⟩ } end⟩ end is_simple_group
d4592814daa337e8941268e697d8f7715e3a5d26
4fa161becb8ce7378a709f5992a594764699e268
/src/algebra/pi_instances.lean
bf2ab51b841a1b1ae3cc52f5bbd855f13e0916df
[ "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
18,424
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 algebra.module import ring_theory.subring import ring_theory.prod open_locale big_operators /-! # Pi instances for algebraic structures -/ namespace pi universes u v w variable {I : Type u} -- The indexing type variable {f : I → Type v} -- The family of types already equipped with instances variables (x y : Π i, f i) (i : I) instance has_zero [∀ i, has_zero $ f i] : has_zero (Π i : I, f i) := ⟨λ i, 0⟩ @[simp] lemma zero_apply [∀ i, has_zero $ f i] : (0 : Π i, f i) i = 0 := rfl instance has_one [∀ i, has_one $ f i] : has_one (Π i : I, f i) := ⟨λ i, 1⟩ @[simp] lemma one_apply [∀ i, has_one $ f i] : (1 : Π i, f i) i = 1 := rfl attribute [to_additive] pi.has_one attribute [to_additive] pi.one_apply instance has_add [∀ i, has_add $ f i] : has_add (Π i : I, f i) := ⟨λ x y, λ i, x i + y i⟩ @[simp] lemma add_apply [∀ i, has_add $ f i] : (x + y) i = x i + y i := rfl instance has_mul [∀ i, has_mul $ f i] : has_mul (Π i : I, f i) := ⟨λ x y, λ i, x i * y i⟩ @[simp] lemma mul_apply [∀ i, has_mul $ f i] : (x * y) i = x i * y i := rfl attribute [to_additive] pi.has_mul attribute [to_additive] pi.mul_apply instance has_inv [∀ i, has_inv $ f i] : has_inv (Π i : I, f i) := ⟨λ x, λ i, (x i)⁻¹⟩ @[simp] lemma inv_apply [∀ i, has_inv $ f i] : x⁻¹ i = (x i)⁻¹ := rfl instance has_neg [∀ i, has_neg $ f i] : has_neg (Π i : I, f i) := ⟨λ x, λ i, -(x i)⟩ @[simp] lemma neg_apply [∀ i, has_neg $ f i] : (-x) i = -x i := rfl attribute [to_additive] pi.has_inv attribute [to_additive] pi.inv_apply instance has_scalar {α : Type*} [∀ i, has_scalar α $ f i] : has_scalar α (Π i : I, f i) := ⟨λ s x, λ i, s • (x i)⟩ @[simp] lemma smul_apply {α : Type*} [∀ i, has_scalar α $ f i] (s : α) : (s • x) i = s • x i := rfl instance semigroup [∀ i, semigroup $ f i] : semigroup (Π i : I, f i) := by pi_instance instance comm_semigroup [∀ i, comm_semigroup $ f i] : comm_semigroup (Π i : I, f i) := by pi_instance instance monoid [∀ i, monoid $ f i] : monoid (Π i : I, f i) := by pi_instance instance comm_monoid [∀ i, comm_monoid $ f i] : comm_monoid (Π i : I, f i) := by pi_instance instance group [∀ i, group $ f i] : group (Π i : I, f i) := by pi_instance instance comm_group [∀ i, comm_group $ f i] : comm_group (Π i : I, f i) := by pi_instance instance add_semigroup [∀ i, add_semigroup $ f i] : add_semigroup (Π i : I, f i) := by pi_instance instance add_comm_semigroup [∀ i, add_comm_semigroup $ f i] : add_comm_semigroup (Π i : I, f i) := by pi_instance instance add_monoid [∀ i, add_monoid $ f i] : add_monoid (Π i : I, f i) := by pi_instance instance add_comm_monoid [∀ i, add_comm_monoid $ f i] : add_comm_monoid (Π i : I, f i) := by pi_instance instance add_group [∀ i, add_group $ f i] : add_group (Π i : I, f i) := by pi_instance instance add_comm_group [∀ i, add_comm_group $ f i] : add_comm_group (Π i : I, f i) := by pi_instance instance semiring [∀ i, semiring $ f i] : semiring (Π i : I, f i) := by pi_instance instance ring [∀ i, ring $ f i] : ring (Π i : I, f i) := by pi_instance instance comm_ring [∀ i, comm_ring $ f i] : comm_ring (Π i : I, f i) := by pi_instance instance mul_action (α) {m : monoid α} [∀ i, mul_action α $ f i] : @mul_action α (Π i : I, f i) m := { smul := λ c f i, c • f i, mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _, one_smul := λ f, funext $ λ i, one_smul α _ } instance distrib_mul_action (α) {m : monoid α} {n : ∀ i, add_monoid $ f i} [∀ i, distrib_mul_action α $ f i] : @distrib_mul_action α (Π i : I, f i) m (@pi.add_monoid I f n) := { smul_zero := λ c, funext $ λ i, smul_zero _, smul_add := λ c f g, funext $ λ i, smul_add _ _ _, ..pi.mul_action _ } variables (I f) instance semimodule (α) {r : semiring α} {m : ∀ i, add_comm_monoid $ f i} [∀ i, semimodule α $ f i] : @semimodule α (Π i : I, f i) r (@pi.add_comm_monoid I f m) := { add_smul := λ c f g, funext $ λ i, add_smul _ _ _, zero_smul := λ f, funext $ λ i, zero_smul α _, ..pi.distrib_mul_action _ } variables {I f} instance left_cancel_semigroup [∀ i, left_cancel_semigroup $ f i] : left_cancel_semigroup (Π i : I, f i) := by pi_instance instance add_left_cancel_semigroup [∀ i, add_left_cancel_semigroup $ f i] : add_left_cancel_semigroup (Π i : I, f i) := by pi_instance instance right_cancel_semigroup [∀ i, right_cancel_semigroup $ f i] : right_cancel_semigroup (Π i : I, f i) := by pi_instance instance add_right_cancel_semigroup [∀ i, add_right_cancel_semigroup $ f i] : add_right_cancel_semigroup (Π i : I, f i) := by pi_instance instance ordered_cancel_comm_monoid [∀ i, ordered_cancel_add_comm_monoid $ f i] : ordered_cancel_add_comm_monoid (Π i : I, f i) := by pi_instance instance ordered_add_comm_group [∀ i, ordered_add_comm_group $ f i] : ordered_add_comm_group (Π i : I, f i) := { add_le_add_left := λ x y hxy c i, add_le_add_left (hxy i) _, ..pi.add_comm_group, ..pi.partial_order } attribute [to_additive add_semigroup] pi.semigroup attribute [to_additive add_comm_semigroup] pi.comm_semigroup attribute [to_additive add_monoid] pi.monoid attribute [to_additive add_comm_monoid] pi.comm_monoid attribute [to_additive add_group] pi.group attribute [to_additive add_comm_group] pi.comm_group attribute [to_additive add_left_cancel_semigroup] pi.left_cancel_semigroup attribute [to_additive add_right_cancel_semigroup] pi.right_cancel_semigroup @[simp] lemma sub_apply [∀ i, add_group $ f i] : (x - y) i = x i - y i := rfl @[to_additive] lemma list_prod_apply {α : Type*} {β : α → Type*} [∀a, monoid (β a)] (a : α) : ∀ (l : list (Πa, β a)), l.prod a = (l.map (λf:Πa, β a, f a)).prod | [] := rfl | (f :: l) := by simp [mul_apply f l.prod a, list_prod_apply l] @[to_additive] lemma multiset_prod_apply {α : Type*} {β : α → Type*} [∀a, comm_monoid (β a)] (a : α) (s : multiset (Πa, β a)) : s.prod a = (s.map (λf:Πa, β a, f a)).prod := quotient.induction_on s $ assume l, begin simp [list_prod_apply a l] end @[to_additive] lemma finset_prod_apply {α : Type*} {β : α → Type*} {γ} [∀a, comm_monoid (β a)] (a : α) (s : finset γ) (g : γ → Πa, β a) : (∏ c in s, g c) a = ∏ c in s, g c a := show (s.val.map g).prod a = (s.val.map (λc, g c a)).prod, by rw [multiset_prod_apply, multiset.map_map] /-- A family of ring homomorphisms `f a : γ →+* β a` defines a ring homomorphism `pi.ring_hom f : γ →+* Π a, β a` given by `pi.ring_hom f x b = f b x`. -/ protected def ring_hom {α : Type u} {β : α → Type v} [R : Π a : α, semiring (β a)] {γ : Type w} [semiring γ] (f : Π a : α, γ →+* β a) : γ →+* Π a, β a := { to_fun := λ x b, f b x, map_add' := λ x y, funext $ λ z, (f z).map_add x y, map_mul' := λ x y, funext $ λ z, (f z).map_mul x y, map_one' := funext $ λ z, (f z).map_one, map_zero' := funext $ λ z, (f z).map_zero } instance is_ring_hom_pi {α : Type u} {β : α → Type v} [R : Π a : α, ring (β a)] {γ : Type w} [ring γ] (f : Π a : α, γ → β a) [Rh : Π a : α, is_ring_hom (f a)] : is_ring_hom (λ x b, f b x) := (show γ →+* Π a, β a, from pi.ring_hom (λ a, ring_hom.of (f a))).is_ring_hom -- Note that we only define `single` here for dependent functions with additive fibres. section variables [decidable_eq I] variables [Π i, has_zero (f i)] /-- The function supported at `i`, with value `x` there. -/ def single (i : I) (x : f i) : Π i, f i := λ i', if h : i' = i then (by { subst h, exact x }) else 0 @[simp] lemma single_eq_same (i : I) (x : f i) : single i x i = x := begin dsimp [single], split_ifs, { refl, }, { exfalso, exact h rfl, } end @[simp] lemma single_eq_of_ne {i i' : I} (h : i' ≠ i) (x : f i) : single i x i' = 0 := begin dsimp [single], split_ifs with h', { exfalso, exact h h', }, { refl, } end end end pi section universes u v variable {I : Type u} -- The indexing type variable (f : I → Type v) -- The family of types already equipped with instances variables [Π i, monoid (f i)] /-- Evaluation of functions into an indexed collection of monoids at a point is a monoid homomorphism. -/ @[to_additive "Evaluation of functions into an indexed collection of additive monoids at a point is an additive monoid homomorphism."] def monoid_hom.apply (i : I) : (Π i, f i) →* f i := { to_fun := λ g, g i, map_one' := rfl, map_mul' := λ x y, rfl, } @[simp, to_additive] lemma monoid_hom.apply_apply (i : I) (g : Π i, f i) : (monoid_hom.apply f i) g = g i := rfl end section universes u v variable {I : Type u} -- The indexing type variable (f : I → Type v) -- The family of types already equipped with instances variables [Π i, semiring (f i)] /-- Evaluation of functions into an indexed collection of monoids at a point is a monoid homomorphism. -/ def ring_hom.apply (i : I) : (Π i, f i) →+* f i := { ..(monoid_hom.apply f i), ..(add_monoid_hom.apply f i) } @[simp] lemma ring_hom.apply_apply (i : I) (g : Π i, f i) : (ring_hom.apply f i) g = g i := rfl end section variables {I : Type*} (Z : I → Type*) variables [Π i, comm_monoid (Z i)] @[simp, to_additive] lemma finset.prod_apply {γ : Type*} {s : finset γ} (h : γ → (Π i, Z i)) (i : I) : (∏ g in s, h g) i = ∏ g in s, h g i := begin classical, induction s using finset.induction_on with b s nmem ih, { simp only [finset.prod_empty], refl }, { simp only [nmem, finset.prod_insert, not_false_iff], rw pi.mul_apply (h b) _ i, rw ih, } end end section -- As we only defined `single` into `add_monoid`, we only prove the `finset.sum` version here. variables {I : Type*} [decidable_eq I] {Z : I → Type*} variables [Π i, add_comm_monoid (Z i)] lemma finset.univ_sum_single [fintype I] (f : Π i, Z i) : ∑ i, pi.single i (f i) = f := begin ext a, rw [finset.sum_apply, finset.sum_eq_single a], { simp, }, { intros b _ h, simp [h.symm], }, { intro h, exfalso, simpa using h, }, end end section open pi variables {I : Type*} [decidable_eq I] variable (f : I → Type*) section variables [Π i, add_monoid (f i)] /-- 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 : I) : f i →+ Π i, f i := { to_fun := λ x, single i x, map_zero' := begin ext i', by_cases h : i' = i, { subst h, simp only [single_eq_same], refl, }, { simp only [h, single_eq_of_ne, ne.def, not_false_iff], refl, }, end, map_add' := λ x y, begin ext i', by_cases h : i' = i, -- FIXME in the next two `simp only`s, -- it would be really nice to not have to provide the arguments to `add_apply`. { subst h, simp only [single_eq_same, add_apply (single i' x) (single i' y) i'], }, { simp only [h, add_zero, single_eq_of_ne, add_apply (single i x) (single i y) i', ne.def, not_false_iff], }, end, } @[simp] lemma add_monoid_hom.single_apply {i : I} (x : f i) : (add_monoid_hom.single f i) x = single i x := rfl end section variables {f} variables [Π i, add_comm_monoid (f i)] @[ext] lemma add_monoid_hom.functions_ext [fintype I] (G : Type*) [add_comm_monoid G] (g h : (Π i, f i) →+ G) (w : ∀ (i : I) (x : f i), g (single i x) = h (single i x)) : g = h := begin ext k, rw [←finset.univ_sum_single k, add_monoid_hom.map_sum, add_monoid_hom.map_sum], apply finset.sum_congr rfl, intros, apply w, end end section variables {f} variables [Π i, semiring (f i)] -- it is somewhat unfortunate that we can't easily use `add_monoid_hom.functions_ext` here @[ext] lemma ring_hom.functions_ext [fintype I] (G : Type*) [semiring G] (g h : (Π i, f i) →+* G) (w : ∀ (i : I) (x : f i), g (single i x) = h (single i x)) : g = h := begin ext k, rw [←finset.univ_sum_single k, ring_hom.map_sum, ring_hom.map_sum], apply finset.sum_congr rfl, intros, apply w, end end end namespace prod variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {p q : α × β} @[to_additive is_add_monoid_hom] lemma fst.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.fst : α × β → α) := { map_mul := λ _ _, rfl, map_one := rfl } @[to_additive is_add_monoid_hom] lemma snd.is_monoid_hom [monoid α] [monoid β] : is_monoid_hom (prod.snd : α × β → β) := { map_mul := λ _ _, rfl, map_one := rfl } @[to_additive is_add_group_hom] lemma fst.is_group_hom [group α] [group β] : is_group_hom (prod.fst : α × β → α) := { map_mul := λ _ _, rfl } @[to_additive is_add_group_hom] lemma snd.is_group_hom [group α] [group β] : is_group_hom (prod.snd : α × β → β) := { map_mul := λ _ _, rfl } attribute [instance] fst.is_monoid_hom fst.is_add_monoid_hom snd.is_monoid_hom snd.is_add_monoid_hom fst.is_group_hom fst.is_add_group_hom snd.is_group_hom snd.is_add_group_hom @[to_additive] lemma fst_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} : (∏ c in t, f c).1 = ∏ c in t, (f c).1 := (monoid_hom.fst α β).map_prod f t @[to_additive] lemma snd_prod [comm_monoid α] [comm_monoid β] {t : finset γ} {f : γ → α × β} : (∏ c in t, f c).2 = ∏ c in t, (f c).2 := (monoid_hom.snd α β).map_prod f t instance fst.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.fst : α × β → α) := (ring_hom.fst α β).is_semiring_hom instance snd.is_semiring_hom [semiring α] [semiring β] : is_semiring_hom (prod.snd : α × β → β) := (ring_hom.snd α β).is_semiring_hom instance fst.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.fst : α × β → α) := (ring_hom.fst α β).is_ring_hom instance snd.is_ring_hom [ring α] [ring β] : is_ring_hom (prod.snd : α × β → β) := (ring_hom.snd α β).is_ring_hom /-- Left injection function for the inner product From a vector space (and also group and module) perspective the product is the same as the sum of two vector spaces. `inl` and `inr` provide the corresponding injection functions. -/ def inl [has_zero β] (a : α) : α × β := (a, 0) /-- Right injection function for the inner product -/ def inr [has_zero α] (b : β) : α × β := (0, b) lemma inl_injective [has_zero β] : function.injective (inl : α → α × β) := assume x y h, (prod.mk.inj_iff.mp h).1 lemma inr_injective [has_zero α] : function.injective (inr : β → α × β) := assume x y h, (prod.mk.inj_iff.mp h).2 @[simp] lemma inl_eq_inl [has_zero β] {a₁ a₂ : α} : (inl a₁ : α × β) = inl a₂ ↔ a₁ = a₂ := iff.intro (assume h, inl_injective h) (assume h, h ▸ rfl) @[simp] lemma inr_eq_inr [has_zero α] {b₁ b₂ : β} : (inr b₁ : α × β) = inr b₂ ↔ b₁ = b₂ := iff.intro (assume h, inr_injective h) (assume h, h ▸ rfl) @[simp] lemma inl_eq_inr [has_zero α] [has_zero β] {a : α} {b : β} : inl a = inr b ↔ a = 0 ∧ b = 0 := by constructor; simp [inl, inr] {contextual := tt} @[simp] lemma inr_eq_inl [has_zero α] [has_zero β] {a : α} {b : β} : inr b = inl a ↔ a = 0 ∧ b = 0 := by constructor; simp [inl, inr] {contextual := tt} @[simp] lemma fst_inl [has_zero β] (a : α) : (inl a : α × β).1 = a := rfl @[simp] lemma snd_inl [has_zero β] (a : α) : (inl a : α × β).2 = 0 := rfl @[simp] lemma fst_inr [has_zero α] (b : β) : (inr b : α × β).1 = 0 := rfl @[simp] lemma snd_inr [has_zero α] (b : β) : (inr b : α × β).2 = b := rfl instance [has_scalar α β] [has_scalar α γ] : has_scalar α (β × γ) := ⟨λa p, (a • p.1, a • p.2)⟩ @[simp] theorem smul_fst [has_scalar α β] [has_scalar α γ] (a : α) (x : β × γ) : (a • x).1 = a • x.1 := rfl @[simp] theorem smul_snd [has_scalar α β] [has_scalar α γ] (a : α) (x : β × γ) : (a • x).2 = a • x.2 := rfl @[simp] theorem smul_mk [has_scalar α β] [has_scalar α γ] (a : α) (b : β) (c : γ) : a • (b, c) = (a • b, a • c) := rfl instance {r : semiring α} [add_comm_monoid β] [add_comm_monoid γ] [semimodule α β] [semimodule α γ] : semimodule α (β × γ) := { smul_add := assume a p₁ p₂, mk.inj_iff.mpr ⟨smul_add _ _ _, smul_add _ _ _⟩, add_smul := assume a p₁ p₂, mk.inj_iff.mpr ⟨add_smul _ _ _, add_smul _ _ _⟩, mul_smul := assume a₁ a₂ p, mk.inj_iff.mpr ⟨mul_smul _ _ _, mul_smul _ _ _⟩, one_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨one_smul _ _, one_smul _ _⟩, zero_smul := assume ⟨b, c⟩, mk.inj_iff.mpr ⟨zero_smul _ _, zero_smul _ _⟩, smul_zero := assume a, mk.inj_iff.mpr ⟨smul_zero _, smul_zero _⟩, .. prod.has_scalar } section substructures variables (s : set α) (t : set β) @[to_additive is_add_submonoid] instance [monoid α] [monoid β] [is_submonoid s] [is_submonoid t] : is_submonoid (s.prod t) := { one_mem := by rw set.mem_prod; split; apply is_submonoid.one_mem, mul_mem := by intros; rw set.mem_prod at *; split; apply is_submonoid.mul_mem; tauto } @[to_additive prod.is_add_subgroup.prod] instance is_subgroup.prod [group α] [group β] [is_subgroup s] [is_subgroup t] : is_subgroup (s.prod t) := { inv_mem := by intros; rw set.mem_prod at *; split; apply is_subgroup.inv_mem; tauto, .. prod.is_submonoid s t } instance is_subring.prod [ring α] [ring β] [is_subring s] [is_subring t] : is_subring (s.prod t) := { .. prod.is_submonoid s t, .. prod.is_add_subgroup.prod s t } end substructures end prod namespace finset @[to_additive prod_mk_sum] lemma prod_mk_prod {α β γ : Type*} [comm_monoid α] [comm_monoid β] (s : finset γ) (f : γ → α) (g : γ → β) : (∏ x in s, f x, ∏ x in s, g x) = ∏ x in s, (f x, g x) := by haveI := classical.dec_eq γ; exact finset.induction_on s rfl (by simp [prod.ext_iff] {contextual := tt}) end finset
7df8da0307ca094c37de7ae3a68987ea66818195
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/1639.lean
333023544b63f7082be1762a35536fc139c67a73
[ "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
605
lean
def some_lets : ℕ → ℕ → ℕ | 0 v := v | (nat.succ n) v := let k := some_lets n v + some_lets n v in some_lets n k def some_unfolded_lets (n : ℕ) : Σ' v : ℕ , v = some_lets 5 n := begin econstructor; dunfold some_lets; econstructor end meta def foo : tactic unit := do [g] <- tactic.get_goals, tactic.to_expr (``(1)) >>= tactic.unify g def some_lifted_lets (n : ℕ) : Σ' (v : ℕ), v = psigma.fst (some_unfolded_lets n) := begin econstructor; dunfold some_unfolded_lets psigma.fst; symmetry; transitivity; symmetry; { foo -- unify_reify_rhs_to_let_in } end
3f78bc2dfbc69d49db0df37f3acee7767aa6cd9c
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/eq11.lean
c1f123f56c6b61b3edd470930c6da5bd30cedc18
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
896
lean
inductive day := monday, tuesday, wednesday, thursday, friday, saturday, sunday open day definition next_weekday : day → day, next_weekday monday := tuesday, next_weekday tuesday := wednesday, next_weekday wednesday := thursday, next_weekday thursday := friday, next_weekday _ := monday theorem next_weekday_monday : next_weekday monday = tuesday := rfl theorem next_weekday_tuesday : next_weekday tuesday = wednesday := rfl theorem next_weekday_wednesday : next_weekday wednesday = thursday := rfl theorem next_weekday_thursday : next_weekday thursday = friday := rfl theorem next_weekday_friday : next_weekday friday = monday := rfl theorem next_weekday_sat : next_weekday saturday = monday := rfl theorem next_weekday_sunday : next_weekday sunday = monday := rfl example : next_weekday (next_weekday monday) = wednesday := rfl
8c9f12c27e322fdc584b7dc056e4a23e19964e88
fe84e287c662151bb313504482b218a503b972f3
/src/data/rat_extra.lean
05af3efa47dc0869a9a6e131ac0657271939ec7f
[]
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
1,156
lean
import data.rat namespace rat lemma mk_with_one_eq_cast (n : ℤ) : mk n 1 = n := by {rw[← of_int_eq_mk n,← coe_int_eq_of_int],} lemma mk_nat_with_one_eq_cast (n : ℤ) : mk_nat n 1 = n := calc mk_nat n 1 = mk n (int.of_nat 1) : rfl ... = n : mk_with_one_eq_cast n lemma mk_pnat_with_one_eq_cast (n : ℤ) : mk_pnat n 1 = n := mk_nat_with_one_eq_cast n lemma of_int_eq_cast (n : ℤ) : of_int n = n := (coe_int_eq_of_int n).symm lemma nat_mk_with_one_eq_cast (n : ℕ) : mk n 1 = n := by {rw[mk_with_one_eq_cast,int.cast_coe_nat],} lemma nat_mk_nat_with_one_eq_cast (n : ℕ) : mk_nat n 1 = n := by {rw[mk_nat_with_one_eq_cast,int.cast_coe_nat],} lemma nat_mk_pnat_with_one_eq_cast (n : ℕ) : mk_pnat n 1 = n := by {rw[mk_pnat_with_one_eq_cast,int.cast_coe_nat],} theorem num_denom'' (q : ℚ) : q = (q.num : ℚ) / (q.denom : ℚ) := begin have dnz : (q.denom : ℚ) ≠ 0 := ne_of_gt (nat.cast_pos.mpr q.pos), rw[eq_div_iff_mul_eq dnz], have : q * q.denom = (mk q.num q.denom) * q.denom := by {congr' 1,exact num_denom.symm}, rw[mk_eq_div,int.cast_coe_nat,div_mul_cancel _ dnz] at this, exact this, end end rat
703822c3eae706cb37dd2da7b86d294b106025d7
aa3f8992ef7806974bc1ffd468baa0c79f4d6643
/tests/lean/run/coe11.lean
095b41d7ce87d557d60c6028fc0d76090c5c3a0a
[ "Apache-2.0" ]
permissive
codyroux/lean
7f8dff750722c5382bdd0a9a9275dc4bb2c58dd3
0cca265db19f7296531e339192e9b9bae4a31f8b
refs/heads/master
1,610,909,964,159
1,407,084,399,000
1,416,857,075,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
958
lean
import algebra.category.basic open category inductive my_functor {obC obD : Type} (C : category obC) (D : category obD) : Type := mk : Π (obF : obC → obD) (homF : Π{A B : obC}, hom A B → hom (obF A) (obF B)), (Π {A : obC}, homF (ID A) = ID (obF A)) → (Π {A B C : obC} {f : hom A B} {g : hom B C}, homF (g ∘ f) = homF g ∘ homF f) → my_functor C D definition my_object [coercion] {obC obD : Type} {C : category obC} {D : category obD} (F : my_functor C D) : obC → obD := my_functor.rec (λ obF homF Hid Hcomp, obF) F definition my_homphism [coercion] {obC obD : Type} {C : category obC} {D : category obD} (F : my_functor C D) : Π{A B : obC}, hom A B → hom (my_object F A) (my_object F B) := my_functor.rec (λ obF homF Hid Hcomp, homF) F constants obC obD : Type constants a b : obC constant C : category obC instance C constant D : category obD constant F : my_functor C D constant m : hom a b check F a check F m
ef5e2f6e0605a79aef8fbb61fa40bc91c8a5c67d
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/parsePrelude.lean
4fb3588542302f83eda27e87c1623891ea35a148
[ "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
341
lean
import Lean.Parser def test : IO Unit := if System.Platform.isWindows then pure () -- TODO investigate why the following doesn't work on Windows else do let env ← Lean.mkEmptyEnvironment; discard <| Lean.Parser.testParseFile env (System.mkFilePath ["..", "..", "..", "src", "Init", "Prelude.lean"]); IO.println "done" #eval test
60e606ff662a7f673d8e734bcd3276cfd47d20f1
9dc8cecdf3c4634764a18254e94d43da07142918
/src/probability/variance.lean
cb59ffa0df42e5cd41ea2a6e738dc1089c1a5bc7
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
10,749
lean
/- Copyright (c) 2022 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import probability.notation import probability.integration /-! # Variance of random variables We define the variance of a real-valued random variable as `Var[X] = 𝔼[(X - 𝔼[X])^2]` (in the `probability_theory` locale). We prove the basic properties of the variance: * `variance_le_expectation_sq`: the inequality `Var[X] ≤ 𝔼[X^2]`. * `meas_ge_le_variance_div_sq`: Chebyshev's inequality, i.e., `ℙ {ω | c ≤ |X ω - 𝔼[X]|} ≤ ennreal.of_real (Var[X] / c ^ 2)`. * `indep_fun.variance_add`: the variance of the sum of two independent random variables is the sum of the variances. * `indep_fun.variance_sum`: the variance of a finite sum of pairwise independent random variables is the sum of the variances. -/ open measure_theory filter finset noncomputable theory open_locale big_operators measure_theory probability_theory ennreal nnreal namespace probability_theory /-- The variance of a random variable is `𝔼[X^2] - 𝔼[X]^2` or, equivalently, `𝔼[(X - 𝔼[X])^2]`. We use the latter as the definition, to ensure better behavior even in garbage situations. -/ def variance {Ω : Type*} {m : measurable_space Ω} (f : Ω → ℝ) (μ : measure Ω) : ℝ := μ[(f - (λ ω, μ[f])) ^ 2] @[simp] lemma variance_zero {Ω : Type*} {m : measurable_space Ω} (μ : measure Ω) : variance 0 μ = 0 := by simp [variance] lemma variance_nonneg {Ω : Type*} {m : measurable_space Ω} (f : Ω → ℝ) (μ : measure Ω) : 0 ≤ variance f μ := integral_nonneg (λ ω, sq_nonneg _) lemma variance_mul {Ω : Type*} {m : measurable_space Ω} (c : ℝ) (f : Ω → ℝ) (μ : measure Ω) : variance (λ ω, c * f ω) μ = c^2 * variance f μ := calc variance (λ ω, c * f ω) μ = ∫ x, (c * f x - ∫ y, c * f y ∂μ) ^ 2 ∂μ : rfl ... = ∫ x, (c * (f x - ∫ y, f y ∂μ)) ^ 2 ∂μ : by { congr' 1 with x, simp_rw [integral_mul_left, mul_sub] } ... = c^2 * variance f μ : by { simp_rw [mul_pow, integral_mul_left], refl } lemma variance_smul {Ω : Type*} {m : measurable_space Ω} (c : ℝ) (f : Ω → ℝ) (μ : measure Ω) : variance (c • f) μ = c^2 * variance f μ := variance_mul c f μ lemma variance_smul' {A : Type*} [comm_semiring A] [algebra A ℝ] {Ω : Type*} {m : measurable_space Ω} (c : A) (f : Ω → ℝ) (μ : measure Ω) : variance (c • f) μ = c^2 • variance f μ := begin convert variance_smul (algebra_map A ℝ c) f μ, { ext1 x, simp only [algebra_map_smul], }, { simp only [algebra.smul_def, map_pow], } end localized "notation (name := probability_theory.variance) `Var[` X `]` := probability_theory.variance X measure_theory.measure_space.volume" in probability_theory variables {Ω : Type*} [measure_space Ω] [is_probability_measure (volume : measure Ω)] lemma variance_def' {X : Ω → ℝ} (hX : mem_ℒp X 2) : Var[X] = 𝔼[X^2] - 𝔼[X]^2 := begin rw [variance, sub_sq', integral_sub', integral_add'], rotate, { exact hX.integrable_sq }, { convert integrable_const (𝔼[X] ^ 2), apply_instance }, { apply hX.integrable_sq.add, convert integrable_const (𝔼[X] ^ 2), apply_instance }, { exact ((hX.integrable one_le_two).const_mul 2).mul_const' _ }, simp only [integral_mul_right, pi.pow_apply, pi.mul_apply, pi.bit0_apply, pi.one_apply, integral_const (integral ℙ X ^ 2), integral_mul_left (2 : ℝ), one_mul, variance, pi.pow_apply, measure_univ, ennreal.one_to_real, algebra.id.smul_eq_mul], ring, end lemma variance_le_expectation_sq {X : Ω → ℝ} : Var[X] ≤ 𝔼[X^2] := begin by_cases h_int : integrable X, swap, { simp only [variance, integral_undef h_int, pi.pow_apply, pi.sub_apply, sub_zero] }, by_cases hX : mem_ℒp X 2, { rw variance_def' hX, simp only [sq_nonneg, sub_le_self_iff] }, { rw [variance, integral_undef], { exact integral_nonneg (λ a, sq_nonneg _) }, { assume h, have A : mem_ℒp (X - λ (ω : Ω), 𝔼[X]) 2 ℙ := (mem_ℒp_two_iff_integrable_sq (h_int.ae_strongly_measurable.sub ae_strongly_measurable_const)).2 h, have B : mem_ℒp (λ (ω : Ω), 𝔼[X]) 2 ℙ := mem_ℒp_const _, apply hX, convert A.add B, simp } } end /-- *Chebyshev's inequality* : one can control the deviation probability of a real random variable from its expectation in terms of the variance. -/ theorem meas_ge_le_variance_div_sq {X : Ω → ℝ} (hX : mem_ℒp X 2) {c : ℝ} (hc : 0 < c) : ℙ {ω | c ≤ |X ω - 𝔼[X]|} ≤ ennreal.of_real (Var[X] / c ^ 2) := begin have A : (ennreal.of_real c : ℝ≥0∞) ≠ 0, by simp only [hc, ne.def, ennreal.of_real_eq_zero, not_le], have B : ae_strongly_measurable (λ (ω : Ω), 𝔼[X]) ℙ := ae_strongly_measurable_const, convert meas_ge_le_mul_pow_snorm ℙ ennreal.two_ne_zero ennreal.two_ne_top (hX.ae_strongly_measurable.sub B) A, { ext ω, set d : ℝ≥0 := ⟨c, hc.le⟩ with hd, have cd : c = d, by simp only [subtype.coe_mk], simp only [pi.sub_apply, ennreal.coe_le_coe, ← real.norm_eq_abs, ← coe_nnnorm, nnreal.coe_le_coe, cd, ennreal.of_real_coe_nnreal] }, { rw (hX.sub (mem_ℒp_const _)).snorm_eq_integral_rpow_norm ennreal.two_ne_zero ennreal.two_ne_top, simp only [pi.sub_apply, ennreal.to_real_bit0, ennreal.one_to_real], rw ennreal.of_real_rpow_of_nonneg _ zero_le_two, rotate, { apply real.rpow_nonneg_of_nonneg, exact integral_nonneg (λ x, real.rpow_nonneg_of_nonneg (norm_nonneg _) _) }, rw [variance, ← real.rpow_mul, inv_mul_cancel], rotate, { exact two_ne_zero }, { exact integral_nonneg (λ x, real.rpow_nonneg_of_nonneg (norm_nonneg _) _) }, simp only [pi.pow_apply, pi.sub_apply, real.rpow_two, real.rpow_one, real.norm_eq_abs, pow_bit0_abs, ennreal.of_real_inv_of_pos hc, ennreal.rpow_two], rw [← ennreal.of_real_pow (inv_nonneg.2 hc.le), ← ennreal.of_real_mul (sq_nonneg _), div_eq_inv_mul, inv_pow] } end /-- The variance of the sum of two independent random variables is the sum of the variances. -/ theorem indep_fun.variance_add {X Y : Ω → ℝ} (hX : mem_ℒp X 2) (hY : mem_ℒp Y 2) (h : indep_fun X Y) : Var[X + Y] = Var[X] + Var[Y] := calc Var[X + Y] = 𝔼[λ a, (X a)^2 + (Y a)^2 + 2 * X a * Y a] - 𝔼[X+Y]^2 : by simp [variance_def' (hX.add hY), add_sq'] ... = (𝔼[X^2] + 𝔼[Y^2] + 2 * 𝔼[X * Y]) - (𝔼[X] + 𝔼[Y])^2 : begin simp only [pi.add_apply, pi.pow_apply, pi.mul_apply, mul_assoc], rw [integral_add, integral_add, integral_add, integral_mul_left], { exact hX.integrable one_le_two }, { exact hY.integrable one_le_two }, { exact hX.integrable_sq }, { exact hY.integrable_sq }, { exact hX.integrable_sq.add hY.integrable_sq }, { apply integrable.const_mul, exact h.integrable_mul (hX.integrable one_le_two) (hY.integrable one_le_two) } end ... = (𝔼[X^2] + 𝔼[Y^2] + 2 * (𝔼[X] * 𝔼[Y])) - (𝔼[X] + 𝔼[Y])^2 : begin congr, exact h.integral_mul_of_integrable (hX.integrable one_le_two) (hY.integrable one_le_two), end ... = Var[X] + Var[Y] : by { simp only [variance_def', hX, hY, pi.pow_apply], ring } /-- The variance of a finite sum of pairwise independent random variables is the sum of the variances. -/ theorem indep_fun.variance_sum {ι : Type*} {X : ι → Ω → ℝ} {s : finset ι} (hs : ∀ i ∈ s, mem_ℒp (X i) 2) (h : set.pairwise ↑s (λ i j, indep_fun (X i) (X j))) : Var[∑ i in s, X i] = ∑ i in s, Var[X i] := begin classical, induction s using finset.induction_on with k s ks IH, { simp only [finset.sum_empty, variance_zero] }, rw [variance_def' (mem_ℒp_finset_sum' _ hs), sum_insert ks, sum_insert ks], simp only [add_sq'], calc 𝔼[X k ^ 2 + (∑ i in s, X i) ^ 2 + 2 * X k * ∑ i in s, X i] - 𝔼[X k + ∑ i in s, X i] ^ 2 = (𝔼[X k ^ 2] + 𝔼[(∑ i in s, X i) ^ 2] + 𝔼[2 * X k * ∑ i in s, X i]) - (𝔼[X k] + 𝔼[∑ i in s, X i]) ^ 2 : begin rw [integral_add', integral_add', integral_add'], { exact mem_ℒp.integrable one_le_two (hs _ (mem_insert_self _ _)) }, { apply integrable_finset_sum' _ (λ i hi, _), exact mem_ℒp.integrable one_le_two (hs _ (mem_insert_of_mem hi)) }, { exact mem_ℒp.integrable_sq (hs _ (mem_insert_self _ _)) }, { apply mem_ℒp.integrable_sq, exact mem_ℒp_finset_sum' _ (λ i hi, (hs _ (mem_insert_of_mem hi))) }, { apply integrable.add, { exact mem_ℒp.integrable_sq (hs _ (mem_insert_self _ _)) }, { apply mem_ℒp.integrable_sq, exact mem_ℒp_finset_sum' _ (λ i hi, (hs _ (mem_insert_of_mem hi))) } }, { rw mul_assoc, apply integrable.const_mul _ 2, simp only [mul_sum, sum_apply, pi.mul_apply], apply integrable_finset_sum _ (λ i hi, _), apply indep_fun.integrable_mul _ (mem_ℒp.integrable one_le_two (hs _ (mem_insert_self _ _))) (mem_ℒp.integrable one_le_two (hs _ (mem_insert_of_mem hi))), apply h (mem_insert_self _ _) (mem_insert_of_mem hi), exact (λ hki, ks (hki.symm ▸ hi)) } end ... = Var[X k] + Var[∑ i in s, X i] + (𝔼[2 * X k * ∑ i in s, X i] - 2 * 𝔼[X k] * 𝔼[∑ i in s, X i]) : begin rw [variance_def' (hs _ (mem_insert_self _ _)), variance_def' (mem_ℒp_finset_sum' _ (λ i hi, (hs _ (mem_insert_of_mem hi))))], ring, end ... = Var[X k] + Var[∑ i in s, X i] : begin simp only [mul_assoc, integral_mul_left, pi.mul_apply, pi.bit0_apply, pi.one_apply, sum_apply, add_right_eq_self, mul_sum], rw integral_finset_sum s (λ i hi, _), swap, { apply integrable.const_mul _ 2, apply indep_fun.integrable_mul _ (mem_ℒp.integrable one_le_two (hs _ (mem_insert_self _ _))) (mem_ℒp.integrable one_le_two (hs _ (mem_insert_of_mem hi))), apply h (mem_insert_self _ _) (mem_insert_of_mem hi), exact (λ hki, ks (hki.symm ▸ hi)) }, rw [integral_finset_sum s (λ i hi, (mem_ℒp.integrable one_le_two (hs _ (mem_insert_of_mem hi)))), mul_sum, mul_sum, ← sum_sub_distrib], apply finset.sum_eq_zero (λ i hi, _), rw [integral_mul_left, indep_fun.integral_mul', sub_self], { apply h (mem_insert_self _ _) (mem_insert_of_mem hi), exact (λ hki, ks (hki.symm ▸ hi)) }, { exact mem_ℒp.ae_strongly_measurable (hs _ (mem_insert_self _ _)) }, { exact mem_ℒp.ae_strongly_measurable (hs _ (mem_insert_of_mem hi)) } end ... = Var[X k] + ∑ i in s, Var[X i] : by rw IH (λ i hi, hs i (mem_insert_of_mem hi)) (h.mono (by simp only [coe_insert, set.subset_insert])) end end probability_theory
90fc79138aadd9e084b81dcc90c3773bb959fc6e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/continuous_on.lean
8af2282f3e25d2f78e421e00e548abddf1cae724
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
55,893
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.constructions /-! # Neighborhoods and continuity relative to a subset This file defines relative versions * `nhds_within` of `nhds` * `continuous_on` of `continuous` * `continuous_within_at` of `continuous_at` and proves their basic properties, including the relationships between these restricted notions and the corresponding notions for the subtype equipped with the subspace topology. ## Notation * `𝓝 x`: the filter of neighborhoods of a point `x`; * `𝓟 s`: the principal filter of a set `s`; * `𝓝[s] x`: the filter `nhds_within x s` of neighborhoods of a point `x` within a set `s`. -/ open set filter function open_locale topological_space filter variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [topological_space α] @[simp] lemma nhds_bind_nhds_within {a : α} {s : set α} : (𝓝 a).bind (λ x, 𝓝[s] x) = 𝓝[s] a := bind_inf_principal.trans $ congr_arg2 _ nhds_bind_nhds rfl @[simp] lemma eventually_nhds_nhds_within {a : α} {s : set α} {p : α → Prop} : (∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝[s] y, p x) ↔ ∀ᶠ x in 𝓝[s] a, p x := filter.ext_iff.1 nhds_bind_nhds_within {x | p x} lemma eventually_nhds_within_iff {a : α} {s : set α} {p : α → Prop} : (∀ᶠ x in 𝓝[s] a, p x) ↔ ∀ᶠ x in 𝓝 a, x ∈ s → p x := eventually_inf_principal lemma frequently_nhds_within_iff {z : α} {s : set α} {p : α → Prop} : (∃ᶠ x in 𝓝[s] z, p x) ↔ (∃ᶠ x in 𝓝 z, p x ∧ x ∈ s) := iff.not (by simp [eventually_nhds_within_iff, not_and']) lemma mem_closure_ne_iff_frequently_within {z : α} {s : set α} : z ∈ closure (s \ {z}) ↔ ∃ᶠ x in 𝓝[≠] z, x ∈ s := by simp [mem_closure_iff_frequently, frequently_nhds_within_iff] @[simp] lemma eventually_nhds_within_nhds_within {a : α} {s : set α} {p : α → Prop} : (∀ᶠ y in 𝓝[s] a, ∀ᶠ x in 𝓝[s] y, p x) ↔ ∀ᶠ x in 𝓝[s] a, p x := begin refine ⟨λ h, _, λ h, (eventually_nhds_nhds_within.2 h).filter_mono inf_le_left⟩, simp only [eventually_nhds_within_iff] at h ⊢, exact h.mono (λ x hx hxs, (hx hxs).self_of_nhds hxs) end theorem nhds_within_eq (a : α) (s : set α) : 𝓝[s] a = ⨅ t ∈ {t : set α | a ∈ t ∧ is_open t}, 𝓟 (t ∩ s) := ((nhds_basis_opens a).inf_principal s).eq_binfi theorem nhds_within_univ (a : α) : 𝓝[set.univ] a = 𝓝 a := by rw [nhds_within, principal_univ, inf_top_eq] lemma nhds_within_has_basis {p : β → Prop} {s : β → set α} {a : α} (h : (𝓝 a).has_basis p s) (t : set α) : (𝓝[t] a).has_basis p (λ i, s i ∩ t) := h.inf_principal t lemma nhds_within_basis_open (a : α) (t : set α) : (𝓝[t] a).has_basis (λ u, a ∈ u ∧ is_open u) (λ u, u ∩ t) := nhds_within_has_basis (nhds_basis_opens a) t theorem mem_nhds_within {t : set α} {a : α} {s : set α} : t ∈ 𝓝[s] a ↔ ∃ u, is_open u ∧ a ∈ u ∧ u ∩ s ⊆ t := by simpa only [exists_prop, and_assoc, and_comm] using (nhds_within_basis_open a s).mem_iff lemma mem_nhds_within_iff_exists_mem_nhds_inter {t : set α} {a : α} {s : set α} : t ∈ 𝓝[s] a ↔ ∃ u ∈ 𝓝 a, u ∩ s ⊆ t := (nhds_within_has_basis (𝓝 a).basis_sets s).mem_iff lemma diff_mem_nhds_within_compl {x : α} {s : set α} (hs : s ∈ 𝓝 x) (t : set α) : s \ t ∈ 𝓝[tᶜ] x := diff_mem_inf_principal_compl hs t lemma diff_mem_nhds_within_diff {x : α} {s t : set α} (hs : s ∈ 𝓝[t] x) (t' : set α) : s \ t' ∈ 𝓝[t \ t'] x := begin rw [nhds_within, diff_eq, diff_eq, ← inf_principal, ← inf_assoc], exact inter_mem_inf hs (mem_principal_self _) end lemma nhds_of_nhds_within_of_nhds {s t : set α} {a : α} (h1 : s ∈ 𝓝 a) (h2 : t ∈ 𝓝[s] a) : (t ∈ 𝓝 a) := begin rcases mem_nhds_within_iff_exists_mem_nhds_inter.mp h2 with ⟨_, Hw, hw⟩, exact (nhds a).sets_of_superset ((nhds a).inter_sets Hw h1) hw, end lemma mem_nhds_within_iff_eventually {s t : set α} {x : α} : t ∈ 𝓝[s] x ↔ ∀ᶠ y in 𝓝 x, y ∈ s → y ∈ t := begin rw [mem_nhds_within_iff_exists_mem_nhds_inter], split, { rintro ⟨u, hu, hut⟩, exact eventually_of_mem hu (λ x hxu hxs, hut ⟨hxu, hxs⟩) }, { refine λ h, ⟨_, h, λ y hy, hy.1 hy.2⟩ } end lemma mem_nhds_within_iff_eventually_eq {s t : set α} {x : α} : t ∈ 𝓝[s] x ↔ s =ᶠ[𝓝 x] (s ∩ t : set α) := by simp_rw [mem_nhds_within_iff_eventually, eventually_eq_set, mem_inter_iff, iff_self_and] lemma nhds_within_eq_iff_eventually_eq {s t : set α} {x : α} : 𝓝[s] x = 𝓝[t] x ↔ s =ᶠ[𝓝 x] t := begin simp_rw [filter.ext_iff, mem_nhds_within_iff_eventually, eventually_eq_set], split, { intro h, filter_upwards [(h t).mpr (eventually_of_forall $ λ x, id), (h s).mp (eventually_of_forall $ λ x, id)], exact λ x, iff.intro, }, { refine λ h u, eventually_congr (h.mono $ λ x h, _), rw [h] } end lemma nhds_within_le_iff {s t : set α} {x : α} : 𝓝[s] x ≤ 𝓝[t] x ↔ t ∈ 𝓝[s] x := begin simp_rw [filter.le_def, mem_nhds_within_iff_eventually], split, { exact λ h, (h t $ eventually_of_forall (λ x, id)).mono (λ x, id) }, { exact λ h u hu, (h.and hu).mono (λ x hx h, hx.2 $ hx.1 h) } end lemma preimage_nhds_within_coinduced' {π : α → β} {s : set β} {t : set α} {a : α} (h : a ∈ t) (ht : is_open t) (hs : s ∈ @nhds β (topological_space.coinduced (λ x : t, π x) subtype.topological_space) (π a)) : π ⁻¹' s ∈ 𝓝[t] a := begin letI := topological_space.coinduced (λ x : t, π x) subtype.topological_space, rcases mem_nhds_iff.mp hs with ⟨V, hVs, V_op, mem_V⟩, refine mem_nhds_within_iff_exists_mem_nhds_inter.mpr ⟨π ⁻¹' V, mem_nhds_iff.mpr ⟨t ∩ π ⁻¹' V, inter_subset_right t (π ⁻¹' V), _, mem_sep h mem_V⟩, subset.trans (inter_subset_left _ _) (preimage_mono hVs)⟩, obtain ⟨u, hu1, hu2⟩ := is_open_induced_iff.mp (is_open_coinduced.1 V_op), rw [preimage_comp] at hu2, rw [set.inter_comm, ←(subtype.preimage_coe_eq_preimage_coe_iff.mp hu2)], exact hu1.inter ht, end lemma mem_nhds_within_of_mem_nhds {s t : set α} {a : α} (h : s ∈ 𝓝 a) : s ∈ 𝓝[t] a := mem_inf_of_left h theorem self_mem_nhds_within {a : α} {s : set α} : s ∈ 𝓝[s] a := mem_inf_of_right (mem_principal_self s) theorem eventually_mem_nhds_within {a : α} {s : set α} : ∀ᶠ x in 𝓝[s] a, x ∈ s := self_mem_nhds_within theorem inter_mem_nhds_within (s : set α) {t : set α} {a : α} (h : t ∈ 𝓝 a) : s ∩ t ∈ 𝓝[s] a := inter_mem self_mem_nhds_within (mem_inf_of_left h) theorem nhds_within_mono (a : α) {s t : set α} (h : s ⊆ t) : 𝓝[s] a ≤ 𝓝[t] a := inf_le_inf_left _ (principal_mono.mpr h) lemma pure_le_nhds_within {a : α} {s : set α} (ha : a ∈ s) : pure a ≤ 𝓝[s] a := le_inf (pure_le_nhds a) (le_principal_iff.2 ha) lemma mem_of_mem_nhds_within {a : α} {s t : set α} (ha : a ∈ s) (ht : t ∈ 𝓝[s] a) : a ∈ t := pure_le_nhds_within ha ht lemma filter.eventually.self_of_nhds_within {p : α → Prop} {s : set α} {x : α} (h : ∀ᶠ y in 𝓝[s] x, p y) (hx : x ∈ s) : p x := mem_of_mem_nhds_within hx h lemma tendsto_const_nhds_within {l : filter β} {s : set α} {a : α} (ha : a ∈ s) : tendsto (λ x : β, a) l (𝓝[s] a) := tendsto_const_pure.mono_right $ pure_le_nhds_within ha theorem nhds_within_restrict'' {a : α} (s : set α) {t : set α} (h : t ∈ 𝓝[s] a) : 𝓝[s] a = 𝓝[s ∩ t] a := le_antisymm (le_inf inf_le_left (le_principal_iff.mpr (inter_mem self_mem_nhds_within h))) (inf_le_inf_left _ (principal_mono.mpr (set.inter_subset_left _ _))) theorem nhds_within_restrict' {a : α} (s : set α) {t : set α} (h : t ∈ 𝓝 a) : 𝓝[s] a = 𝓝[s ∩ t] a := nhds_within_restrict'' s $ mem_inf_of_left h theorem nhds_within_restrict {a : α} (s : set α) {t : set α} (h₀ : a ∈ t) (h₁ : is_open t) : 𝓝[s] a = 𝓝[s ∩ t] a := nhds_within_restrict' s (is_open.mem_nhds h₁ h₀) theorem nhds_within_le_of_mem {a : α} {s t : set α} (h : s ∈ 𝓝[t] a) : 𝓝[t] a ≤ 𝓝[s] a := nhds_within_le_iff.mpr h theorem nhds_within_le_nhds {a : α} {s : set α} : 𝓝[s] a ≤ 𝓝 a := by { rw ← nhds_within_univ, apply nhds_within_le_of_mem, exact univ_mem } lemma nhds_within_eq_nhds_within' {a : α} {s t u : set α} (hs : s ∈ 𝓝 a) (h₂ : t ∩ s = u ∩ s) : 𝓝[t] a = 𝓝[u] a := by rw [nhds_within_restrict' t hs, nhds_within_restrict' u hs, h₂] theorem nhds_within_eq_nhds_within {a : α} {s t u : set α} (h₀ : a ∈ s) (h₁ : is_open s) (h₂ : t ∩ s = u ∩ s) : 𝓝[t] a = 𝓝[u] a := by rw [nhds_within_restrict t h₀ h₁, nhds_within_restrict u h₀ h₁, h₂] theorem is_open.nhds_within_eq {a : α} {s : set α} (h : is_open s) (ha : a ∈ s) : 𝓝[s] a = 𝓝 a := inf_eq_left.2 $ le_principal_iff.2 $ is_open.mem_nhds h ha lemma preimage_nhds_within_coinduced {π : α → β} {s : set β} {t : set α} {a : α} (h : a ∈ t) (ht : is_open t) (hs : s ∈ @nhds β (topological_space.coinduced (λ x : t, π x) subtype.topological_space) (π a)) : π ⁻¹' s ∈ 𝓝 a := by { rw ← ht.nhds_within_eq h, exact preimage_nhds_within_coinduced' h ht hs } @[simp] theorem nhds_within_empty (a : α) : 𝓝[∅] a = ⊥ := by rw [nhds_within, principal_empty, inf_bot_eq] theorem nhds_within_union (a : α) (s t : set α) : 𝓝[s ∪ t] a = 𝓝[s] a ⊔ 𝓝[t] a := by { delta nhds_within, rw [←inf_sup_left, sup_principal] } theorem nhds_within_inter (a : α) (s t : set α) : 𝓝[s ∩ t] a = 𝓝[s] a ⊓ 𝓝[t] a := by { delta nhds_within, rw [inf_left_comm, inf_assoc, inf_principal, ←inf_assoc, inf_idem] } theorem nhds_within_inter' (a : α) (s t : set α) : 𝓝[s ∩ t] a = (𝓝[s] a) ⊓ 𝓟 t := by { delta nhds_within, rw [←inf_principal, inf_assoc] } theorem nhds_within_inter_of_mem {a : α} {s t : set α} (h : s ∈ 𝓝[t] a) : 𝓝[s ∩ t] a = 𝓝[t] a := by { rw [nhds_within_inter, inf_eq_right], exact nhds_within_le_of_mem h } @[simp] theorem nhds_within_singleton (a : α) : 𝓝[{a}] a = pure a := by rw [nhds_within, principal_singleton, inf_eq_right.2 (pure_le_nhds a)] @[simp] theorem nhds_within_insert (a : α) (s : set α) : 𝓝[insert a s] a = pure a ⊔ 𝓝[s] a := by rw [← singleton_union, nhds_within_union, nhds_within_singleton] lemma mem_nhds_within_insert {a : α} {s t : set α} : t ∈ 𝓝[insert a s] a ↔ a ∈ t ∧ t ∈ 𝓝[s] a := by simp lemma insert_mem_nhds_within_insert {a : α} {s t : set α} (h : t ∈ 𝓝[s] a) : insert a t ∈ 𝓝[insert a s] a := by simp [mem_of_superset h] lemma insert_mem_nhds_iff {a : α} {s : set α} : insert a s ∈ 𝓝 a ↔ s ∈ 𝓝[≠] a := by simp only [nhds_within, mem_inf_principal, mem_compl_iff, mem_singleton_iff, or_iff_not_imp_left, insert_def] @[simp] theorem nhds_within_compl_singleton_sup_pure (a : α) : 𝓝[≠] a ⊔ pure a = 𝓝 a := by rw [← nhds_within_singleton, ← nhds_within_union, compl_union_self, nhds_within_univ] lemma nhds_within_prod_eq {α : Type*} [topological_space α] {β : Type*} [topological_space β] (a : α) (b : β) (s : set α) (t : set β) : 𝓝[s ×ˢ t] (a, b) = 𝓝[s] a ×ᶠ 𝓝[t] b := by { delta nhds_within, rw [nhds_prod_eq, ←filter.prod_inf_prod, filter.prod_principal_principal] } lemma nhds_within_prod {α : Type*} [topological_space α] {β : Type*} [topological_space β] {s u : set α} {t v : set β} {a : α} {b : β} (hu : u ∈ 𝓝[s] a) (hv : v ∈ 𝓝[t] b) : (u ×ˢ v) ∈ 𝓝[s ×ˢ t] (a, b) := by { rw nhds_within_prod_eq, exact prod_mem_prod hu hv, } lemma nhds_within_pi_eq' {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] {I : set ι} (hI : I.finite) (s : Π i, set (α i)) (x : Π i, α i) : 𝓝[pi I s] x = ⨅ i, comap (λ x, x i) (𝓝 (x i) ⊓ ⨅ (hi : i ∈ I), 𝓟 (s i)) := by simp only [nhds_within, nhds_pi, filter.pi, comap_inf, comap_infi, pi_def, comap_principal, ← infi_principal_finite hI, ← infi_inf_eq] lemma nhds_within_pi_eq {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] {I : set ι} (hI : I.finite) (s : Π i, set (α i)) (x : Π i, α i) : 𝓝[pi I s] x = (⨅ i ∈ I, comap (λ x, x i) (𝓝[s i] (x i))) ⊓ ⨅ (i ∉ I), comap (λ x, x i) (𝓝 (x i)) := begin simp only [nhds_within, nhds_pi, filter.pi, pi_def, ← infi_principal_finite hI, comap_inf, comap_principal, eval], rw [infi_split _ (λ i, i ∈ I), inf_right_comm], simp only [infi_inf_eq] end lemma nhds_within_pi_univ_eq {ι : Type*} {α : ι → Type*} [finite ι] [Π i, topological_space (α i)] (s : Π i, set (α i)) (x : Π i, α i) : 𝓝[pi univ s] x = ⨅ i, comap (λ x, x i) 𝓝[s i] (x i) := by simpa [nhds_within] using nhds_within_pi_eq finite_univ s x lemma nhds_within_pi_eq_bot {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] {I : set ι} {s : Π i, set (α i)} {x : Π i, α i} : 𝓝[pi I s] x = ⊥ ↔ ∃ i ∈ I, 𝓝[s i] (x i) = ⊥ := by simp only [nhds_within, nhds_pi, pi_inf_principal_pi_eq_bot] lemma nhds_within_pi_ne_bot {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] {I : set ι} {s : Π i, set (α i)} {x : Π i, α i} : (𝓝[pi I s] x).ne_bot ↔ ∀ i ∈ I, (𝓝[s i] (x i)).ne_bot := by simp [ne_bot_iff, nhds_within_pi_eq_bot] theorem filter.tendsto.piecewise_nhds_within {f g : α → β} {t : set α} [∀ x, decidable (x ∈ t)] {a : α} {s : set α} {l : filter β} (h₀ : tendsto f (𝓝[s ∩ t] a) l) (h₁ : tendsto g (𝓝[s ∩ tᶜ] a) l) : tendsto (piecewise t f g) (𝓝[s] a) l := by apply tendsto.piecewise; rwa ← nhds_within_inter' theorem filter.tendsto.if_nhds_within {f g : α → β} {p : α → Prop} [decidable_pred p] {a : α} {s : set α} {l : filter β} (h₀ : tendsto f (𝓝[s ∩ {x | p x}] a) l) (h₁ : tendsto g (𝓝[s ∩ {x | ¬ p x}] a) l) : tendsto (λ x, if p x then f x else g x) (𝓝[s] a) l := h₀.piecewise_nhds_within h₁ lemma map_nhds_within (f : α → β) (a : α) (s : set α) : map f (𝓝[s] a) = ⨅ t ∈ {t : set α | a ∈ t ∧ is_open t}, 𝓟 (f '' (t ∩ s)) := ((nhds_within_basis_open a s).map f).eq_binfi theorem tendsto_nhds_within_mono_left {f : α → β} {a : α} {s t : set α} {l : filter β} (hst : s ⊆ t) (h : tendsto f (𝓝[t] a) l) : tendsto f (𝓝[s] a) l := h.mono_left $ nhds_within_mono a hst theorem tendsto_nhds_within_mono_right {f : β → α} {l : filter β} {a : α} {s t : set α} (hst : s ⊆ t) (h : tendsto f l (𝓝[s] a)) : tendsto f l (𝓝[t] a) := h.mono_right (nhds_within_mono a hst) theorem tendsto_nhds_within_of_tendsto_nhds {f : α → β} {a : α} {s : set α} {l : filter β} (h : tendsto f (𝓝 a) l) : tendsto f (𝓝[s] a) l := h.mono_left inf_le_left lemma eventually_mem_of_tendsto_nhds_within {f : β → α} {a : α} {s : set α} {l : filter β} (h : tendsto f l (𝓝[s] a)) : ∀ᶠ i in l, f i ∈ s := begin simp_rw [nhds_within_eq, tendsto_infi, mem_set_of_eq, tendsto_principal, mem_inter_iff, eventually_and] at h, exact (h univ ⟨mem_univ a, is_open_univ⟩).2, end lemma tendsto_nhds_of_tendsto_nhds_within {f : β → α} {a : α} {s : set α} {l : filter β} (h : tendsto f l (𝓝[s] a)) : tendsto f l (𝓝 a) := h.mono_right nhds_within_le_nhds theorem principal_subtype {α : Type*} (s : set α) (t : set {x // x ∈ s}) : 𝓟 t = comap coe (𝓟 ((coe : s → α) '' t)) := by rw [comap_principal, set.preimage_image_eq _ subtype.coe_injective] lemma nhds_within_ne_bot_of_mem {s : set α} {x : α} (hx : x ∈ s) : ne_bot (𝓝[s] x) := mem_closure_iff_nhds_within_ne_bot.1 $ subset_closure hx lemma is_closed.mem_of_nhds_within_ne_bot {s : set α} (hs : is_closed s) {x : α} (hx : ne_bot $ 𝓝[s] x) : x ∈ s := by simpa only [hs.closure_eq] using mem_closure_iff_nhds_within_ne_bot.2 hx lemma dense_range.nhds_within_ne_bot {ι : Type*} {f : ι → α} (h : dense_range f) (x : α) : ne_bot (𝓝[range f] x) := mem_closure_iff_cluster_pt.1 (h x) lemma mem_closure_pi {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] {I : set ι} {s : Π i, set (α i)} {x : Π i, α i} : x ∈ closure (pi I s) ↔ ∀ i ∈ I, x i ∈ closure (s i) := by simp only [mem_closure_iff_nhds_within_ne_bot, nhds_within_pi_ne_bot] lemma closure_pi_set {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] (I : set ι) (s : Π i, set (α i)) : closure (pi I s) = pi I (λ i, closure (s i)) := set.ext $ λ x, mem_closure_pi lemma dense_pi {ι : Type*} {α : ι → Type*} [Π i, topological_space (α i)] {s : Π i, set (α i)} (I : set ι) (hs : ∀ i ∈ I, dense (s i)) : dense (pi I s) := by simp only [dense_iff_closure_eq, closure_pi_set, pi_congr rfl (λ i hi, (hs i hi).closure_eq), pi_univ] lemma eventually_eq_nhds_within_iff {f g : α → β} {s : set α} {a : α} : (f =ᶠ[𝓝[s] a] g) ↔ ∀ᶠ x in 𝓝 a, x ∈ s → f x = g x := mem_inf_principal lemma eventually_eq_nhds_within_of_eq_on {f g : α → β} {s : set α} {a : α} (h : eq_on f g s) : f =ᶠ[𝓝[s] a] g := mem_inf_of_right h lemma set.eq_on.eventually_eq_nhds_within {f g : α → β} {s : set α} {a : α} (h : eq_on f g s) : f =ᶠ[𝓝[s] a] g := eventually_eq_nhds_within_of_eq_on h lemma tendsto_nhds_within_congr {f g : α → β} {s : set α} {a : α} {l : filter β} (hfg : ∀ x ∈ s, f x = g x) (hf : tendsto f (𝓝[s] a) l) : tendsto g (𝓝[s] a) l := (tendsto_congr' $ eventually_eq_nhds_within_of_eq_on hfg).1 hf lemma eventually_nhds_within_of_forall {s : set α} {a : α} {p : α → Prop} (h : ∀ x ∈ s, p x) : ∀ᶠ x in 𝓝[s] a, p x := mem_inf_of_right h lemma tendsto_nhds_within_of_tendsto_nhds_of_eventually_within {a : α} {l : filter β} {s : set α} (f : β → α) (h1 : tendsto f l (𝓝 a)) (h2 : ∀ᶠ x in l, f x ∈ s) : tendsto f l (𝓝[s] a) := tendsto_inf.2 ⟨h1, tendsto_principal.2 h2⟩ lemma tendsto_nhds_within_iff {a : α} {l : filter β} {s : set α} {f : β → α} : tendsto f l (𝓝[s] a) ↔ tendsto f l (𝓝 a) ∧ ∀ᶠ n in l, f n ∈ s := ⟨λ h, ⟨tendsto_nhds_of_tendsto_nhds_within h, eventually_mem_of_tendsto_nhds_within h⟩, λ h, tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ h.1 h.2⟩ @[simp] lemma tendsto_nhds_within_range {a : α} {l : filter β} {f : β → α} : tendsto f l (𝓝[range f] a) ↔ tendsto f l (𝓝 a) := ⟨λ h, h.mono_right inf_le_left, λ h, tendsto_inf.2 ⟨h, tendsto_principal.2 $ eventually_of_forall mem_range_self⟩⟩ lemma filter.eventually_eq.eq_of_nhds_within {s : set α} {f g : α → β} {a : α} (h : f =ᶠ[𝓝[s] a] g) (hmem : a ∈ s) : f a = g a := h.self_of_nhds_within hmem lemma eventually_nhds_within_of_eventually_nhds {α : Type*} [topological_space α] {s : set α} {a : α} {p : α → Prop} (h : ∀ᶠ x in 𝓝 a, p x) : ∀ᶠ x in 𝓝[s] a, p x := mem_nhds_within_of_mem_nhds h /-! ### `nhds_within` and subtypes -/ theorem mem_nhds_within_subtype {s : set α} {a : {x // x ∈ s}} {t u : set {x // x ∈ s}} : t ∈ 𝓝[u] a ↔ t ∈ comap (coe : s → α) (𝓝[coe '' u] a) := by rw [nhds_within, nhds_subtype, principal_subtype, ←comap_inf, ←nhds_within] theorem nhds_within_subtype (s : set α) (a : {x // x ∈ s}) (t : set {x // x ∈ s}) : 𝓝[t] a = comap (coe : s → α) (𝓝[coe '' t] a) := filter.ext $ λ u, mem_nhds_within_subtype theorem nhds_within_eq_map_subtype_coe {s : set α} {a : α} (h : a ∈ s) : 𝓝[s] a = map (coe : s → α) (𝓝 ⟨a, h⟩) := by simpa only [subtype.range_coe] using (embedding_subtype_coe.map_nhds_eq ⟨a, h⟩).symm theorem mem_nhds_subtype_iff_nhds_within {s : set α} {a : s} {t : set s} : t ∈ 𝓝 a ↔ coe '' t ∈ 𝓝[s] (a : α) := by rw [nhds_within_eq_map_subtype_coe a.coe_prop, mem_map, preimage_image_eq _ subtype.coe_injective, subtype.coe_eta] theorem preimage_coe_mem_nhds_subtype {s t : set α} {a : s} : coe ⁻¹' t ∈ 𝓝 a ↔ t ∈ 𝓝[s] ↑a := by simp only [mem_nhds_subtype_iff_nhds_within, subtype.image_preimage_coe, inter_mem_iff, self_mem_nhds_within, and_true] theorem tendsto_nhds_within_iff_subtype {s : set α} {a : α} (h : a ∈ s) (f : α → β) (l : filter β) : tendsto f (𝓝[s] a) l ↔ tendsto (s.restrict f) (𝓝 ⟨a, h⟩) l := by simp only [tendsto, nhds_within_eq_map_subtype_coe h, filter.map_map, restrict] variables [topological_space β] [topological_space γ] [topological_space δ] /-- A function between topological spaces is continuous at a point `x₀` within a subset `s` if `f x` tends to `f x₀` when `x` tends to `x₀` while staying within `s`. -/ def continuous_within_at (f : α → β) (s : set α) (x : α) : Prop := tendsto f (𝓝[s] x) (𝓝 (f x)) /-- If a function is continuous within `s` at `x`, then it tends to `f x` within `s` by definition. We register this fact for use with the dot notation, especially to use `tendsto.comp` as `continuous_within_at.comp` will have a different meaning. -/ lemma continuous_within_at.tendsto {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) : tendsto f (𝓝[s] x) (𝓝 (f x)) := h /-- A function between topological spaces is continuous on a subset `s` when it's continuous at every point of `s` within `s`. -/ def continuous_on (f : α → β) (s : set α) : Prop := ∀ x ∈ s, continuous_within_at f s x lemma continuous_on.continuous_within_at {f : α → β} {s : set α} {x : α} (hf : continuous_on f s) (hx : x ∈ s) : continuous_within_at f s x := hf x hx theorem continuous_within_at_univ (f : α → β) (x : α) : continuous_within_at f set.univ x ↔ continuous_at f x := by rw [continuous_at, continuous_within_at, nhds_within_univ] theorem continuous_within_at_iff_continuous_at_restrict (f : α → β) {x : α} {s : set α} (h : x ∈ s) : continuous_within_at f s x ↔ continuous_at (s.restrict f) ⟨x, h⟩ := tendsto_nhds_within_iff_subtype h f _ theorem continuous_within_at.tendsto_nhds_within {f : α → β} {x : α} {s : set α} {t : set β} (h : continuous_within_at f s x) (ht : maps_to f s t) : tendsto f (𝓝[s] x) (𝓝[t] (f x)) := tendsto_inf.2 ⟨h, tendsto_principal.2 $ mem_inf_of_right $ mem_principal.2 $ ht⟩ theorem continuous_within_at.tendsto_nhds_within_image {f : α → β} {x : α} {s : set α} (h : continuous_within_at f s x) : tendsto f (𝓝[s] x) (𝓝[f '' s] (f x)) := h.tendsto_nhds_within (maps_to_image _ _) lemma continuous_within_at.prod_map {f : α → γ} {g : β → δ} {s : set α} {t : set β} {x : α} {y : β} (hf : continuous_within_at f s x) (hg : continuous_within_at g t y) : continuous_within_at (prod.map f g) (s ×ˢ t) (x, y) := begin unfold continuous_within_at at *, rw [nhds_within_prod_eq, prod.map, nhds_prod_eq], exact hf.prod_map hg, end lemma continuous_within_at_pi {ι : Type*} {π : ι → Type*} [∀ i, topological_space (π i)] {f : α → Π i, π i} {s : set α} {x : α} : continuous_within_at f s x ↔ ∀ i, continuous_within_at (λ y, f y i) s x := tendsto_pi_nhds lemma continuous_on_pi {ι : Type*} {π : ι → Type*} [∀ i, topological_space (π i)] {f : α → Π i, π i} {s : set α} : continuous_on f s ↔ ∀ i, continuous_on (λ y, f y i) s := ⟨λ h i x hx, tendsto_pi_nhds.1 (h x hx) i, λ h x hx, tendsto_pi_nhds.2 (λ i, h i x hx)⟩ lemma continuous_within_at.fin_insert_nth {n} {π : fin (n + 1) → Type*} [Π i, topological_space (π i)] (i : fin (n + 1)) {f : α → π i} {a : α} {s : set α} (hf : continuous_within_at f s a) {g : α → Π j : fin n, π (i.succ_above j)} (hg : continuous_within_at g s a) : continuous_within_at (λ a, i.insert_nth (f a) (g a)) s a := hf.fin_insert_nth i hg lemma continuous_on.fin_insert_nth {n} {π : fin (n + 1) → Type*} [Π i, topological_space (π i)] (i : fin (n + 1)) {f : α → π i} {s : set α} (hf : continuous_on f s) {g : α → Π j : fin n, π (i.succ_above j)} (hg : continuous_on g s) : continuous_on (λ a, i.insert_nth (f a) (g a)) s := λ a ha, (hf a ha).fin_insert_nth i (hg a ha) theorem continuous_on_iff {f : α → β} {s : set α} : continuous_on f s ↔ ∀ x ∈ s, ∀ t : set β, is_open t → f x ∈ t → ∃ u, is_open u ∧ x ∈ u ∧ u ∩ s ⊆ f ⁻¹' t := by simp only [continuous_on, continuous_within_at, tendsto_nhds, mem_nhds_within] theorem continuous_on_iff_continuous_restrict {f : α → β} {s : set α} : continuous_on f s ↔ continuous (s.restrict f) := begin rw [continuous_on, continuous_iff_continuous_at], split, { rintros h ⟨x, xs⟩, exact (continuous_within_at_iff_continuous_at_restrict f xs).mp (h x xs) }, intros h x xs, exact (continuous_within_at_iff_continuous_at_restrict f xs).mpr (h ⟨x, xs⟩) end theorem continuous_on_iff' {f : α → β} {s : set α} : continuous_on f s ↔ ∀ t : set β, is_open t → ∃ u, is_open u ∧ f ⁻¹' t ∩ s = u ∩ s := have ∀ t, is_open (s.restrict f ⁻¹' t) ↔ ∃ (u : set α), is_open u ∧ f ⁻¹' t ∩ s = u ∩ s, begin intro t, rw [is_open_induced_iff, set.restrict_eq, set.preimage_comp], simp only [subtype.preimage_coe_eq_preimage_coe_iff], split; { rintros ⟨u, ou, useq⟩, exact ⟨u, ou, useq.symm⟩ } end, by rw [continuous_on_iff_continuous_restrict, continuous_def]; simp only [this] /-- If a function is continuous on a set for some topologies, then it is continuous on the same set with respect to any finer topology on the source space. -/ lemma continuous_on.mono_dom {α β : Type*} {t₁ t₂ : topological_space α} {t₃ : topological_space β} (h₁ : t₂ ≤ t₁) {s : set α} {f : α → β} (h₂ : @continuous_on α β t₁ t₃ f s) : @continuous_on α β t₂ t₃ f s := begin rw continuous_on_iff' at h₂ ⊢, assume t ht, rcases h₂ t ht with ⟨u, hu, h'u⟩, exact ⟨u, h₁ u hu, h'u⟩ end /-- If a function is continuous on a set for some topologies, then it is continuous on the same set with respect to any coarser topology on the target space. -/ lemma continuous_on.mono_rng {α β : Type*} {t₁ : topological_space α} {t₂ t₃ : topological_space β} (h₁ : t₂ ≤ t₃) {s : set α} {f : α → β} (h₂ : @continuous_on α β t₁ t₂ f s) : @continuous_on α β t₁ t₃ f s := begin rw continuous_on_iff' at h₂ ⊢, assume t ht, exact h₂ t (h₁ t ht) end theorem continuous_on_iff_is_closed {f : α → β} {s : set α} : continuous_on f s ↔ ∀ t : set β, is_closed t → ∃ u, is_closed u ∧ f ⁻¹' t ∩ s = u ∩ s := have ∀ t, is_closed (s.restrict f ⁻¹' t) ↔ ∃ (u : set α), is_closed u ∧ f ⁻¹' t ∩ s = u ∩ s, begin intro t, rw [is_closed_induced_iff, set.restrict_eq, set.preimage_comp], simp only [subtype.preimage_coe_eq_preimage_coe_iff, eq_comm] end, by rw [continuous_on_iff_continuous_restrict, continuous_iff_is_closed]; simp only [this] lemma continuous_on.prod_map {f : α → γ} {g : β → δ} {s : set α} {t : set β} (hf : continuous_on f s) (hg : continuous_on g t) : continuous_on (prod.map f g) (s ×ˢ t) := λ ⟨x, y⟩ ⟨hx, hy⟩, continuous_within_at.prod_map (hf x hx) (hg y hy) lemma continuous_on_empty (f : α → β) : continuous_on f ∅ := λ x, false.elim lemma continuous_on_singleton (f : α → β) (a : α) : continuous_on f {a} := forall_eq.2 $ by simpa only [continuous_within_at, nhds_within_singleton, tendsto_pure_left] using λ s, mem_of_mem_nhds lemma set.subsingleton.continuous_on {s : set α} (hs : s.subsingleton) (f : α → β) : continuous_on f s := hs.induction_on (continuous_on_empty f) (continuous_on_singleton f) theorem nhds_within_le_comap {x : α} {s : set α} {f : α → β} (ctsf : continuous_within_at f s x) : 𝓝[s] x ≤ comap f (𝓝[f '' s] (f x)) := ctsf.tendsto_nhds_within_image.le_comap @[simp] lemma comap_nhds_within_range {α} (f : α → β) (y : β) : comap f (𝓝[range f] y) = comap f (𝓝 y) := comap_inf_principal_range theorem continuous_within_at_iff_ptendsto_res (f : α → β) {x : α} {s : set α} : continuous_within_at f s x ↔ ptendsto (pfun.res f s) (𝓝 x) (𝓝 (f x)) := tendsto_iff_ptendsto _ _ _ _ lemma continuous_iff_continuous_on_univ {f : α → β} : continuous f ↔ continuous_on f univ := by simp [continuous_iff_continuous_at, continuous_on, continuous_at, continuous_within_at, nhds_within_univ] lemma continuous_within_at.mono {f : α → β} {s t : set α} {x : α} (h : continuous_within_at f t x) (hs : s ⊆ t) : continuous_within_at f s x := h.mono_left (nhds_within_mono x hs) lemma continuous_within_at.mono_of_mem {f : α → β} {s t : set α} {x : α} (h : continuous_within_at f t x) (hs : t ∈ 𝓝[s] x) : continuous_within_at f s x := h.mono_left (nhds_within_le_of_mem hs) lemma continuous_within_at_inter' {f : α → β} {s t : set α} {x : α} (h : t ∈ 𝓝[s] x) : continuous_within_at f (s ∩ t) x ↔ continuous_within_at f s x := by simp [continuous_within_at, nhds_within_restrict'' s h] lemma continuous_within_at_inter {f : α → β} {s t : set α} {x : α} (h : t ∈ 𝓝 x) : continuous_within_at f (s ∩ t) x ↔ continuous_within_at f s x := by simp [continuous_within_at, nhds_within_restrict' s h] lemma continuous_within_at_union {f : α → β} {s t : set α} {x : α} : continuous_within_at f (s ∪ t) x ↔ continuous_within_at f s x ∧ continuous_within_at f t x := by simp only [continuous_within_at, nhds_within_union, tendsto_sup] lemma continuous_within_at.union {f : α → β} {s t : set α} {x : α} (hs : continuous_within_at f s x) (ht : continuous_within_at f t x) : continuous_within_at f (s ∪ t) x := continuous_within_at_union.2 ⟨hs, ht⟩ lemma continuous_within_at.mem_closure_image {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (hx : x ∈ closure s) : f x ∈ closure (f '' s) := by haveI := (mem_closure_iff_nhds_within_ne_bot.1 hx); exact (mem_closure_of_tendsto h $ mem_of_superset self_mem_nhds_within (subset_preimage_image f s)) lemma continuous_within_at.mem_closure {f : α → β} {s : set α} {x : α} {A : set β} (h : continuous_within_at f s x) (hx : x ∈ closure s) (hA : maps_to f s A) : f x ∈ closure A := closure_mono (image_subset_iff.2 hA) (h.mem_closure_image hx) lemma set.maps_to.closure_of_continuous_within_at {f : α → β} {s : set α} {t : set β} (h : maps_to f s t) (hc : ∀ x ∈ closure s, continuous_within_at f s x) : maps_to f (closure s) (closure t) := λ x hx, (hc x hx).mem_closure hx h lemma set.maps_to.closure_of_continuous_on {f : α → β} {s : set α} {t : set β} (h : maps_to f s t) (hc : continuous_on f (closure s)) : maps_to f (closure s) (closure t) := h.closure_of_continuous_within_at $ λ x hx, (hc x hx).mono subset_closure lemma continuous_within_at.image_closure {f : α → β} {s : set α} (hf : ∀ x ∈ closure s, continuous_within_at f s x) : f '' (closure s) ⊆ closure (f '' s) := maps_to'.1 $ (maps_to_image f s).closure_of_continuous_within_at hf lemma continuous_on.image_closure {f : α → β} {s : set α} (hf : continuous_on f (closure s)) : f '' (closure s) ⊆ closure (f '' s) := continuous_within_at.image_closure $ λ x hx, (hf x hx).mono subset_closure @[simp] lemma continuous_within_at_singleton {f : α → β} {x : α} : continuous_within_at f {x} x := by simp only [continuous_within_at, nhds_within_singleton, tendsto_pure_nhds] @[simp] lemma continuous_within_at_insert_self {f : α → β} {x : α} {s : set α} : continuous_within_at f (insert x s) x ↔ continuous_within_at f s x := by simp only [← singleton_union, continuous_within_at_union, continuous_within_at_singleton, true_and] alias continuous_within_at_insert_self ↔ _ continuous_within_at.insert_self lemma continuous_within_at.diff_iff {f : α → β} {s t : set α} {x : α} (ht : continuous_within_at f t x) : continuous_within_at f (s \ t) x ↔ continuous_within_at f s x := ⟨λ h, (h.union ht).mono $ by simp only [diff_union_self, subset_union_left], λ h, h.mono (diff_subset _ _)⟩ @[simp] lemma continuous_within_at_diff_self {f : α → β} {s : set α} {x : α} : continuous_within_at f (s \ {x}) x ↔ continuous_within_at f s x := continuous_within_at_singleton.diff_iff @[simp] lemma continuous_within_at_compl_self {f : α → β} {a : α} : continuous_within_at f {a}ᶜ a ↔ continuous_at f a := by rw [compl_eq_univ_diff, continuous_within_at_diff_self, continuous_within_at_univ] @[simp] lemma continuous_within_at_update_same [decidable_eq α] {f : α → β} {s : set α} {x : α} {y : β} : continuous_within_at (update f x y) s x ↔ tendsto f (𝓝[s \ {x}] x) (𝓝 y) := calc continuous_within_at (update f x y) s x ↔ tendsto (update f x y) (𝓝[s \ {x}] x) (𝓝 y) : by rw [← continuous_within_at_diff_self, continuous_within_at, function.update_same] ... ↔ tendsto f (𝓝[s \ {x}] x) (𝓝 y) : tendsto_congr' $ eventually_nhds_within_iff.2 $ eventually_of_forall $ λ z hz, update_noteq hz.2 _ _ @[simp] lemma continuous_at_update_same [decidable_eq α] {f : α → β} {x : α} {y : β} : continuous_at (function.update f x y) x ↔ tendsto f (𝓝[≠] x) (𝓝 y) := by rw [← continuous_within_at_univ, continuous_within_at_update_same, compl_eq_univ_diff] theorem is_open_map.continuous_on_image_of_left_inv_on {f : α → β} {s : set α} (h : is_open_map (s.restrict f)) {finv : β → α} (hleft : left_inv_on finv f s) : continuous_on finv (f '' s) := begin refine continuous_on_iff'.2 (λ t ht, ⟨f '' (t ∩ s), _, _⟩), { rw ← image_restrict, exact h _ (ht.preimage continuous_subtype_coe) }, { rw [inter_eq_self_of_subset_left (image_subset f (inter_subset_right t s)), hleft.image_inter'] }, end theorem is_open_map.continuous_on_range_of_left_inverse {f : α → β} (hf : is_open_map f) {finv : β → α} (hleft : function.left_inverse finv f) : continuous_on finv (range f) := begin rw [← image_univ], exact (hf.restrict is_open_univ).continuous_on_image_of_left_inv_on (λ x _, hleft x) end lemma continuous_on.congr_mono {f g : α → β} {s s₁ : set α} (h : continuous_on f s) (h' : eq_on g f s₁) (h₁ : s₁ ⊆ s) : continuous_on g s₁ := begin assume x hx, unfold continuous_within_at, have A := (h x (h₁ hx)).mono h₁, unfold continuous_within_at at A, rw ← h' hx at A, exact A.congr' h'.eventually_eq_nhds_within.symm end lemma continuous_on.congr {f g : α → β} {s : set α} (h : continuous_on f s) (h' : eq_on g f s) : continuous_on g s := h.congr_mono h' (subset.refl _) lemma continuous_on_congr {f g : α → β} {s : set α} (h' : eq_on g f s) : continuous_on g s ↔ continuous_on f s := ⟨λ h, continuous_on.congr h h'.symm, λ h, h.congr h'⟩ lemma continuous_at.continuous_within_at {f : α → β} {s : set α} {x : α} (h : continuous_at f x) : continuous_within_at f s x := continuous_within_at.mono ((continuous_within_at_univ f x).2 h) (subset_univ _) lemma continuous_within_at_iff_continuous_at {f : α → β} {s : set α} {x : α} (h : s ∈ 𝓝 x) : continuous_within_at f s x ↔ continuous_at f x := by rw [← univ_inter s, continuous_within_at_inter h, continuous_within_at_univ] lemma continuous_within_at.continuous_at {f : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (hs : s ∈ 𝓝 x) : continuous_at f x := (continuous_within_at_iff_continuous_at hs).mp h lemma is_open.continuous_on_iff {f : α → β} {s : set α} (hs : is_open s) : continuous_on f s ↔ ∀ ⦃a⦄, a ∈ s → continuous_at f a := ball_congr $ λ _, continuous_within_at_iff_continuous_at ∘ hs.mem_nhds lemma continuous_on.continuous_at {f : α → β} {s : set α} {x : α} (h : continuous_on f s) (hx : s ∈ 𝓝 x) : continuous_at f x := (h x (mem_of_mem_nhds hx)).continuous_at hx lemma continuous_at.continuous_on {f : α → β} {s : set α} (hcont : ∀ x ∈ s, continuous_at f x) : continuous_on f s := λ x hx, (hcont x hx).continuous_within_at lemma continuous_within_at.comp {g : β → γ} {f : α → β} {s : set α} {t : set β} {x : α} (hg : continuous_within_at g t (f x)) (hf : continuous_within_at f s x) (h : maps_to f s t) : continuous_within_at (g ∘ f) s x := hg.tendsto.comp (hf.tendsto_nhds_within h) lemma continuous_within_at.comp' {g : β → γ} {f : α → β} {s : set α} {t : set β} {x : α} (hg : continuous_within_at g t (f x)) (hf : continuous_within_at f s x) : continuous_within_at (g ∘ f) (s ∩ f⁻¹' t) x := hg.comp (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) lemma continuous_at.comp_continuous_within_at {g : β → γ} {f : α → β} {s : set α} {x : α} (hg : continuous_at g (f x)) (hf : continuous_within_at f s x) : continuous_within_at (g ∘ f) s x := hg.continuous_within_at.comp hf (maps_to_univ _ _) lemma continuous_on.comp {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : continuous_on g t) (hf : continuous_on f s) (h : maps_to f s t) : continuous_on (g ∘ f) s := λx hx, continuous_within_at.comp (hg _ (h hx)) (hf x hx) h lemma continuous_on.mono {f : α → β} {s t : set α} (hf : continuous_on f s) (h : t ⊆ s) : continuous_on f t := λx hx, (hf x (h hx)).mono_left (nhds_within_mono _ h) lemma antitone_continuous_on {f : α → β} : antitone (continuous_on f) := λ s t hst hf, hf.mono hst lemma continuous_on.comp' {g : β → γ} {f : α → β} {s : set α} {t : set β} (hg : continuous_on g t) (hf : continuous_on f s) : continuous_on (g ∘ f) (s ∩ f⁻¹' t) := hg.comp (hf.mono (inter_subset_left _ _)) (inter_subset_right _ _) lemma continuous.continuous_on {f : α → β} {s : set α} (h : continuous f) : continuous_on f s := begin rw continuous_iff_continuous_on_univ at h, exact h.mono (subset_univ _) end lemma continuous.continuous_within_at {f : α → β} {s : set α} {x : α} (h : continuous f) : continuous_within_at f s x := h.continuous_at.continuous_within_at lemma continuous.comp_continuous_on {g : β → γ} {f : α → β} {s : set α} (hg : continuous g) (hf : continuous_on f s) : continuous_on (g ∘ f) s := hg.continuous_on.comp hf (maps_to_univ _ _) lemma continuous_on.comp_continuous {g : β → γ} {f : α → β} {s : set β} (hg : continuous_on g s) (hf : continuous f) (hs : ∀ x, f x ∈ s) : continuous (g ∘ f) := begin rw continuous_iff_continuous_on_univ at *, exact hg.comp hf (λ x _, hs x), end lemma continuous_within_at.preimage_mem_nhds_within {f : α → β} {x : α} {s : set α} {t : set β} (h : continuous_within_at f s x) (ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ 𝓝[s] x := h ht lemma set.left_inv_on.map_nhds_within_eq {f : α → β} {g : β → α} {x : β} {s : set β} (h : left_inv_on f g s) (hx : f (g x) = x) (hf : continuous_within_at f (g '' s) (g x)) (hg : continuous_within_at g s x) : map g (𝓝[s] x) = 𝓝[g '' s] (g x) := begin apply le_antisymm, { exact hg.tendsto_nhds_within (maps_to_image _ _) }, { have A : g ∘ f =ᶠ[𝓝[g '' s] (g x)] id, from h.right_inv_on_image.eq_on.eventually_eq_of_mem self_mem_nhds_within, refine le_map_of_right_inverse A _, simpa only [hx] using hf.tendsto_nhds_within (h.maps_to (surj_on_image _ _)) } end lemma function.left_inverse.map_nhds_eq {f : α → β} {g : β → α} {x : β} (h : function.left_inverse f g) (hf : continuous_within_at f (range g) (g x)) (hg : continuous_at g x) : map g (𝓝 x) = 𝓝[range g] (g x) := by simpa only [nhds_within_univ, image_univ] using (h.left_inv_on univ).map_nhds_within_eq (h x) (by rwa image_univ) hg.continuous_within_at lemma continuous_within_at.preimage_mem_nhds_within' {f : α → β} {x : α} {s : set α} {t : set β} (h : continuous_within_at f s x) (ht : t ∈ 𝓝[f '' s] (f x)) : f ⁻¹' t ∈ 𝓝[s] x := h.tendsto_nhds_within (maps_to_image _ _) ht lemma filter.eventually_eq.congr_continuous_within_at {f g : α → β} {s : set α} {x : α} (h : f =ᶠ[𝓝[s] x] g) (hx : f x = g x) : continuous_within_at f s x ↔ continuous_within_at g s x := by rw [continuous_within_at, hx, tendsto_congr' h, continuous_within_at] lemma continuous_within_at.congr_of_eventually_eq {f f₁ : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (h₁ : f₁ =ᶠ[𝓝[s] x] f) (hx : f₁ x = f x) : continuous_within_at f₁ s x := (h₁.congr_continuous_within_at hx).2 h lemma continuous_within_at.congr {f f₁ : α → β} {s : set α} {x : α} (h : continuous_within_at f s x) (h₁ : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : continuous_within_at f₁ s x := h.congr_of_eventually_eq (mem_of_superset self_mem_nhds_within h₁) hx lemma continuous_within_at.congr_mono {f g : α → β} {s s₁ : set α} {x : α} (h : continuous_within_at f s x) (h' : eq_on g f s₁) (h₁ : s₁ ⊆ s) (hx : g x = f x): continuous_within_at g s₁ x := (h.mono h₁).congr h' hx lemma continuous_on_const {s : set α} {c : β} : continuous_on (λx, c) s := continuous_const.continuous_on lemma continuous_within_at_const {b : β} {s : set α} {x : α} : continuous_within_at (λ _:α, b) s x := continuous_const.continuous_within_at lemma continuous_on_id {s : set α} : continuous_on id s := continuous_id.continuous_on lemma continuous_within_at_id {s : set α} {x : α} : continuous_within_at id s x := continuous_id.continuous_within_at lemma continuous_on_open_iff {f : α → β} {s : set α} (hs : is_open s) : continuous_on f s ↔ (∀t, is_open t → is_open (s ∩ f⁻¹' t)) := begin rw continuous_on_iff', split, { assume h t ht, rcases h t ht with ⟨u, u_open, hu⟩, rw [inter_comm, hu], apply is_open.inter u_open hs }, { assume h t ht, refine ⟨s ∩ f ⁻¹' t, h t ht, _⟩, rw [@inter_comm _ s (f ⁻¹' t), inter_assoc, inter_self] } end lemma continuous_on.preimage_open_of_open {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_open s) (ht : is_open t) : is_open (s ∩ f⁻¹' t) := (continuous_on_open_iff hs).1 hf t ht lemma continuous_on.is_open_preimage {f : α → β} {s : set α} {t : set β} (h : continuous_on f s) (hs : is_open s) (hp : f ⁻¹' t ⊆ s) (ht : is_open t) : is_open (f ⁻¹' t) := begin convert (continuous_on_open_iff hs).mp h t ht, rw [inter_comm, inter_eq_self_of_subset_left hp], end lemma continuous_on.preimage_closed_of_closed {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_closed s) (ht : is_closed t) : is_closed (s ∩ f⁻¹' t) := begin rcases continuous_on_iff_is_closed.1 hf t ht with ⟨u, hu⟩, rw [inter_comm, hu.2], apply is_closed.inter hu.1 hs end lemma continuous_on.preimage_interior_subset_interior_preimage {f : α → β} {s : set α} {t : set β} (hf : continuous_on f s) (hs : is_open s) : s ∩ f⁻¹' (interior t) ⊆ s ∩ interior (f⁻¹' t) := calc s ∩ f ⁻¹' (interior t) ⊆ interior (s ∩ f ⁻¹' t) : interior_maximal (inter_subset_inter (subset.refl _) (preimage_mono interior_subset)) (hf.preimage_open_of_open hs is_open_interior) ... = s ∩ interior (f ⁻¹' t) : by rw [interior_inter, hs.interior_eq] lemma continuous_on_of_locally_continuous_on {f : α → β} {s : set α} (h : ∀x∈s, ∃t, is_open t ∧ x ∈ t ∧ continuous_on f (s ∩ t)) : continuous_on f s := begin assume x xs, rcases h x xs with ⟨t, open_t, xt, ct⟩, have := ct x ⟨xs, xt⟩, rwa [continuous_within_at, ← nhds_within_restrict _ xt open_t] at this end lemma continuous_on_open_of_generate_from {β : Type*} {s : set α} {T : set (set β)} {f : α → β} (hs : is_open s) (h : ∀t ∈ T, is_open (s ∩ f⁻¹' t)) : @continuous_on α β _ (topological_space.generate_from T) f s := begin rw continuous_on_open_iff, assume t ht, induction ht with u hu u v Tu Tv hu hv U hU hU', { exact h u hu }, { simp only [preimage_univ, inter_univ], exact hs }, { have : s ∩ f ⁻¹' (u ∩ v) = (s ∩ f ⁻¹' u) ∩ (s ∩ f ⁻¹' v), by rw [preimage_inter, inter_assoc, inter_left_comm _ s, ← inter_assoc s s, inter_self], rw this, exact hu.inter hv }, { rw [preimage_sUnion, inter_Union₂], exact is_open_bUnion hU' }, { exact hs } end lemma continuous_within_at.prod {f : α → β} {g : α → γ} {s : set α} {x : α} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λx, (f x, g x)) s x := hf.prod_mk_nhds hg lemma continuous_on.prod {f : α → β} {g : α → γ} {s : set α} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λx, (f x, g x)) s := λx hx, continuous_within_at.prod (hf x hx) (hg x hx) lemma inducing.continuous_within_at_iff {f : α → β} {g : β → γ} (hg : inducing g) {s : set α} {x : α} : continuous_within_at f s x ↔ continuous_within_at (g ∘ f) s x := by simp_rw [continuous_within_at, inducing.tendsto_nhds_iff hg] lemma inducing.continuous_on_iff {f : α → β} {g : β → γ} (hg : inducing g) {s : set α} : continuous_on f s ↔ continuous_on (g ∘ f) s := by simp_rw [continuous_on, hg.continuous_within_at_iff] lemma embedding.continuous_on_iff {f : α → β} {g : β → γ} (hg : embedding g) {s : set α} : continuous_on f s ↔ continuous_on (g ∘ f) s := inducing.continuous_on_iff hg.1 lemma embedding.map_nhds_within_eq {f : α → β} (hf : embedding f) (s : set α) (x : α) : map f (𝓝[s] x) = 𝓝[f '' s] (f x) := by rw [nhds_within, map_inf hf.inj, hf.map_nhds_eq, map_principal, ← nhds_within_inter', inter_eq_self_of_subset_right (image_subset_range _ _)] lemma open_embedding.map_nhds_within_preimage_eq {f : α → β} (hf : open_embedding f) (s : set β) (x : α) : map f (𝓝[f ⁻¹' s] x) = 𝓝[s] (f x) := begin rw [hf.to_embedding.map_nhds_within_eq, image_preimage_eq_inter_range], apply nhds_within_eq_nhds_within (mem_range_self _) hf.open_range, rw [inter_assoc, inter_self] end lemma continuous_within_at_of_not_mem_closure {f : α → β} {s : set α} {x : α} : x ∉ closure s → continuous_within_at f s x := begin intros hx, rw [mem_closure_iff_nhds_within_ne_bot, ne_bot_iff, not_not] at hx, rw [continuous_within_at, hx], exact tendsto_bot, end lemma continuous_on.piecewise' {s t : set α} {f g : α → β} [∀ a, decidable (a ∈ t)] (hpf : ∀ a ∈ s ∩ frontier t, tendsto f (𝓝[s ∩ t] a) (𝓝 (piecewise t f g a))) (hpg : ∀ a ∈ s ∩ frontier t, tendsto g (𝓝[s ∩ tᶜ] a) (𝓝 (piecewise t f g a))) (hf : continuous_on f $ s ∩ t) (hg : continuous_on g $ s ∩ tᶜ) : continuous_on (piecewise t f g) s := begin intros x hx, by_cases hx' : x ∈ frontier t, { exact (hpf x ⟨hx, hx'⟩).piecewise_nhds_within (hpg x ⟨hx, hx'⟩) }, { rw [← inter_univ s, ← union_compl_self t, inter_union_distrib_left] at hx ⊢, cases hx, { apply continuous_within_at.union, { exact (hf x hx).congr (λ y hy, piecewise_eq_of_mem _ _ _ hy.2) (piecewise_eq_of_mem _ _ _ hx.2) }, { have : x ∉ closure tᶜ, from λ h, hx' ⟨subset_closure hx.2, by rwa closure_compl at h⟩, exact continuous_within_at_of_not_mem_closure (λ h, this (closure_inter_subset_inter_closure _ _ h).2) } }, { apply continuous_within_at.union, { have : x ∉ closure t, from (λ h, hx' ⟨h, (λ (h' : x ∈ interior t), hx.2 (interior_subset h'))⟩), exact continuous_within_at_of_not_mem_closure (λ h, this (closure_inter_subset_inter_closure _ _ h).2) }, { exact (hg x hx).congr (λ y hy, piecewise_eq_of_not_mem _ _ _ hy.2) (piecewise_eq_of_not_mem _ _ _ hx.2) } } } end lemma continuous_on.if' {s : set α} {p : α → Prop} {f g : α → β} [∀ a, decidable (p a)] (hpf : ∀ a ∈ s ∩ frontier {a | p a}, tendsto f (𝓝[s ∩ {a | p a}] a) (𝓝 $ if p a then f a else g a)) (hpg : ∀ a ∈ s ∩ frontier {a | p a}, tendsto g (𝓝[s ∩ {a | ¬p a}] a) (𝓝 $ if p a then f a else g a)) (hf : continuous_on f $ s ∩ {a | p a}) (hg : continuous_on g $ s ∩ {a | ¬p a}) : continuous_on (λ a, if p a then f a else g a) s := hf.piecewise' hpf hpg hg lemma continuous_on.if {α β : Type*} [topological_space α] [topological_space β] {p : α → Prop} [∀ a, decidable (p a)] {s : set α} {f g : α → β} (hp : ∀ a ∈ s ∩ frontier {a | p a}, f a = g a) (hf : continuous_on f $ s ∩ closure {a | p a}) (hg : continuous_on g $ s ∩ closure {a | ¬ p a}) : continuous_on (λa, if p a then f a else g a) s := begin apply continuous_on.if', { rintros a ha, simp only [← hp a ha, if_t_t], apply tendsto_nhds_within_mono_left (inter_subset_inter_right s subset_closure), exact hf a ⟨ha.1, ha.2.1⟩ }, { rintros a ha, simp only [hp a ha, if_t_t], apply tendsto_nhds_within_mono_left (inter_subset_inter_right s subset_closure), rcases ha with ⟨has, ⟨_, ha⟩⟩, rw [← mem_compl_iff, ← closure_compl] at ha, apply hg a ⟨has, ha⟩ }, { exact hf.mono (inter_subset_inter_right s subset_closure) }, { exact hg.mono (inter_subset_inter_right s subset_closure) } end lemma continuous_on.piecewise {s t : set α} {f g : α → β} [∀ a, decidable (a ∈ t)] (ht : ∀ a ∈ s ∩ frontier t, f a = g a) (hf : continuous_on f $ s ∩ closure t) (hg : continuous_on g $ s ∩ closure tᶜ) : continuous_on (piecewise t f g) s := hf.if ht hg lemma continuous_if' {p : α → Prop} {f g : α → β} [∀ a, decidable (p a)] (hpf : ∀ a ∈ frontier {x | p x}, tendsto f (𝓝[{x | p x}] a) (𝓝 $ ite (p a) (f a) (g a))) (hpg : ∀ a ∈ frontier {x | p x}, tendsto g (𝓝[{x | ¬p x}] a) (𝓝 $ ite (p a) (f a) (g a))) (hf : continuous_on f {x | p x}) (hg : continuous_on g {x | ¬p x}) : continuous (λ a, ite (p a) (f a) (g a)) := begin rw continuous_iff_continuous_on_univ, apply continuous_on.if'; simp *; assumption end lemma continuous_if {p : α → Prop} {f g : α → β} [∀ a, decidable (p a)] (hp : ∀ a ∈ frontier {x | p x}, f a = g a) (hf : continuous_on f (closure {x | p x})) (hg : continuous_on g (closure {x | ¬p x})) : continuous (λ a, if p a then f a else g a) := begin rw continuous_iff_continuous_on_univ, apply continuous_on.if; simp; assumption end lemma continuous.if {p : α → Prop} {f g : α → β} [∀ a, decidable (p a)] (hp : ∀ a ∈ frontier {x | p x}, f a = g a) (hf : continuous f) (hg : continuous g) : continuous (λ a, if p a then f a else g a) := continuous_if hp hf.continuous_on hg.continuous_on lemma continuous_if_const (p : Prop) {f g : α → β} [decidable p] (hf : p → continuous f) (hg : ¬ p → continuous g) : continuous (λ a, if p then f a else g a) := by { split_ifs, exact hf h, exact hg h } lemma continuous.if_const (p : Prop) {f g : α → β} [decidable p] (hf : continuous f) (hg : continuous g) : continuous (λ a, if p then f a else g a) := continuous_if_const p (λ _, hf) (λ _, hg) lemma continuous_piecewise {s : set α} {f g : α → β} [∀ a, decidable (a ∈ s)] (hs : ∀ a ∈ frontier s, f a = g a) (hf : continuous_on f (closure s)) (hg : continuous_on g (closure sᶜ)) : continuous (piecewise s f g) := continuous_if hs hf hg lemma continuous.piecewise {s : set α} {f g : α → β} [∀ a, decidable (a ∈ s)] (hs : ∀ a ∈ frontier s, f a = g a) (hf : continuous f) (hg : continuous g) : continuous (piecewise s f g) := hf.if hs hg lemma is_open.ite' {s s' t : set α} (hs : is_open s) (hs' : is_open s') (ht : ∀ x ∈ frontier t, x ∈ s ↔ x ∈ s') : is_open (t.ite s s') := begin classical, simp only [is_open_iff_continuous_mem, set.ite] at *, convert continuous_piecewise (λ x hx, propext (ht x hx)) hs.continuous_on hs'.continuous_on, ext x, by_cases hx : x ∈ t; simp [hx] end lemma is_open.ite {s s' t : set α} (hs : is_open s) (hs' : is_open s') (ht : s ∩ frontier t = s' ∩ frontier t) : is_open (t.ite s s') := hs.ite' hs' $ λ x hx, by simpa [hx] using ext_iff.1 ht x lemma ite_inter_closure_eq_of_inter_frontier_eq {s s' t : set α} (ht : s ∩ frontier t = s' ∩ frontier t) : t.ite s s' ∩ closure t = s ∩ closure t := by rw [closure_eq_self_union_frontier, inter_union_distrib_left, inter_union_distrib_left, ite_inter_self, ite_inter_of_inter_eq _ ht] lemma ite_inter_closure_compl_eq_of_inter_frontier_eq {s s' t : set α} (ht : s ∩ frontier t = s' ∩ frontier t) : t.ite s s' ∩ closure tᶜ = s' ∩ closure tᶜ := by { rw [← ite_compl, ite_inter_closure_eq_of_inter_frontier_eq], rwa [frontier_compl, eq_comm] } lemma continuous_on_piecewise_ite' {s s' t : set α} {f f' : α → β} [∀ x, decidable (x ∈ t)] (h : continuous_on f (s ∩ closure t)) (h' : continuous_on f' (s' ∩ closure tᶜ)) (H : s ∩ frontier t = s' ∩ frontier t) (Heq : eq_on f f' (s ∩ frontier t)) : continuous_on (t.piecewise f f') (t.ite s s') := begin apply continuous_on.piecewise, { rwa ite_inter_of_inter_eq _ H }, { rwa ite_inter_closure_eq_of_inter_frontier_eq H }, { rwa ite_inter_closure_compl_eq_of_inter_frontier_eq H } end lemma continuous_on_piecewise_ite {s s' t : set α} {f f' : α → β} [∀ x, decidable (x ∈ t)] (h : continuous_on f s) (h' : continuous_on f' s') (H : s ∩ frontier t = s' ∩ frontier t) (Heq : eq_on f f' (s ∩ frontier t)) : continuous_on (t.piecewise f f') (t.ite s s') := continuous_on_piecewise_ite' (h.mono (inter_subset_left _ _)) (h'.mono (inter_subset_left _ _)) H Heq lemma frontier_inter_open_inter {s t : set α} (ht : is_open t) : frontier (s ∩ t) ∩ t = frontier s ∩ t := by simp only [← subtype.preimage_coe_eq_preimage_coe_iff, ht.is_open_map_subtype_coe.preimage_frontier_eq_frontier_preimage continuous_subtype_coe, subtype.preimage_coe_inter_self] lemma continuous_on_fst {s : set (α × β)} : continuous_on prod.fst s := continuous_fst.continuous_on lemma continuous_within_at_fst {s : set (α × β)} {p : α × β} : continuous_within_at prod.fst s p := continuous_fst.continuous_within_at lemma continuous_on.fst {f : α → β × γ} {s : set α} (hf : continuous_on f s) : continuous_on (λ x, (f x).1) s := continuous_fst.comp_continuous_on hf lemma continuous_within_at.fst {f : α → β × γ} {s : set α} {a : α} (h : continuous_within_at f s a) : continuous_within_at (λ x, (f x).fst) s a := continuous_at_fst.comp_continuous_within_at h lemma continuous_on_snd {s : set (α × β)} : continuous_on prod.snd s := continuous_snd.continuous_on lemma continuous_within_at_snd {s : set (α × β)} {p : α × β} : continuous_within_at prod.snd s p := continuous_snd.continuous_within_at lemma continuous_on.snd {f : α → β × γ} {s : set α} (hf : continuous_on f s) : continuous_on (λ x, (f x).2) s := continuous_snd.comp_continuous_on hf lemma continuous_within_at.snd {f : α → β × γ} {s : set α} {a : α} (h : continuous_within_at f s a) : continuous_within_at (λ x, (f x).snd) s a := continuous_at_snd.comp_continuous_within_at h lemma continuous_within_at_prod_iff {f : α → β × γ} {s : set α} {x : α} : continuous_within_at f s x ↔ continuous_within_at (prod.fst ∘ f) s x ∧ continuous_within_at (prod.snd ∘ f) s x := ⟨λ h, ⟨h.fst, h.snd⟩, by { rintro ⟨h1, h2⟩, convert h1.prod h2, ext, refl, refl }⟩
5c85f569121979393d9d6a5471032a01174bd799
c5b07d17b3c9fb19e4b302465d237fd1d988c14f
/src/data/emb.lean
41ecfef852988bb509ba534923d137026988c4fa
[ "MIT" ]
permissive
skaslev/papers
acaec61602b28c33d6115e53913b2002136aa29b
f15b379f3c43bbd0a37ac7bb75f4278f7e901389
refs/heads/master
1,665,505,770,318
1,660,378,602,000
1,660,378,602,000
14,101,547
0
1
MIT
1,595,414,522,000
1,383,542,702,000
Lean
UTF-8
Lean
false
false
135
lean
structure {u v} emb (A : Sort u) (B : Sort v) := (f : A → B) (g : B → A) (gf : Π x, g (f x) = x) notation a ` ≲ ` b := emb a b
f5b35568862cb2322d80bf241f0007b005ca011b
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/subpp.lean
c584ea780bdcfbbc8bdad480695cc8629c167c80
[ "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
65
lean
-- import data.subtype open nat subtype check {x : nat| x > 0 }
b4de4b04a4a64f5b4f7a1a505220fdb8a3d83462
94e33a31faa76775069b071adea97e86e218a8ee
/src/order/filter/ultrafilter.lean
6faf3a83386fbb52261b44d8b5790f051d03b2e2
[ "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
16,730
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad, Yury Kudryashov -/ import order.filter.cofinite import order.zorn /-! # Ultrafilters An ultrafilter is a minimal (maximal in the set order) proper filter. In this file we define * `ultrafilter.of`: an ultrafilter that is less than or equal to a given filter; * `ultrafilter`: subtype of ultrafilters; * `ultrafilter.pure`: `pure x` as an `ultrafiler`; * `ultrafilter.map`, `ultrafilter.bind`, `ultrafilter.comap` : operations on ultrafilters; * `hyperfilter`: the ultrafilter extending the cofinite filter. -/ universes u v variables {α : Type u} {β : Type v} {γ : Type*} open set filter function open_locale classical filter /-- An ultrafilter is a minimal (maximal in the set order) proper filter. -/ @[protect_proj] structure ultrafilter (α : Type*) extends filter α := (ne_bot' : ne_bot to_filter) (le_of_le : ∀ g, filter.ne_bot g → g ≤ to_filter → to_filter ≤ g) namespace ultrafilter variables {f g : ultrafilter α} {s t : set α} {p q : α → Prop} instance : has_coe_t (ultrafilter α) (filter α) := ⟨ultrafilter.to_filter⟩ instance : has_mem (set α) (ultrafilter α) := ⟨λ s f, s ∈ (f : filter α)⟩ lemma unique (f : ultrafilter α) {g : filter α} (h : g ≤ f) (hne : ne_bot g . tactic.apply_instance) : g = f := le_antisymm h $ f.le_of_le g hne h instance ne_bot (f : ultrafilter α) : ne_bot (f : filter α) := f.ne_bot' @[simp, norm_cast] lemma mem_coe : s ∈ (f : filter α) ↔ s ∈ f := iff.rfl lemma coe_injective : injective (coe : ultrafilter α → filter α) | ⟨f, h₁, h₂⟩ ⟨g, h₃, h₄⟩ rfl := by congr lemma eq_of_le {f g : ultrafilter α} (h : (f : filter α) ≤ g) : f = g := coe_injective (g.unique h) @[simp, norm_cast] lemma coe_le_coe {f g : ultrafilter α} : (f : filter α) ≤ g ↔ f = g := ⟨λ h, eq_of_le h, λ h, h ▸ le_rfl⟩ @[simp, norm_cast] lemma coe_inj : (f : filter α) = g ↔ f = g := coe_injective.eq_iff @[ext] lemma ext ⦃f g : ultrafilter α⦄ (h : ∀ s, s ∈ f ↔ s ∈ g) : f = g := coe_injective $ filter.ext h lemma le_of_inf_ne_bot (f : ultrafilter α) {g : filter α} (hg : ne_bot (↑f ⊓ g)) : ↑f ≤ g := le_of_inf_eq (f.unique inf_le_left hg) lemma le_of_inf_ne_bot' (f : ultrafilter α) {g : filter α} (hg : ne_bot (g ⊓ f)) : ↑f ≤ g := f.le_of_inf_ne_bot $ by rwa inf_comm @[simp] lemma compl_not_mem_iff : sᶜ ∉ f ↔ s ∈ f := ⟨λ hsc, le_principal_iff.1 $ f.le_of_inf_ne_bot ⟨λ h, hsc $ mem_of_eq_bot$ by rwa compl_compl⟩, compl_not_mem⟩ @[simp] lemma frequently_iff_eventually : (∃ᶠ x in f, p x) ↔ ∀ᶠ x in f, p x := compl_not_mem_iff alias frequently_iff_eventually ↔ _root_.filter.frequently.eventually _ lemma compl_mem_iff_not_mem : sᶜ ∈ f ↔ s ∉ f := by rw [← compl_not_mem_iff, compl_compl] lemma diff_mem_iff (f : ultrafilter α) : s \ t ∈ f ↔ s ∈ f ∧ t ∉ f := inter_mem_iff.trans $ and_congr iff.rfl compl_mem_iff_not_mem /-- If `sᶜ ∉ f ↔ s ∈ f`, then `f` is an ultrafilter. The other implication is given by `ultrafilter.compl_not_mem_iff`. -/ def of_compl_not_mem_iff (f : filter α) (h : ∀ s, sᶜ ∉ f ↔ s ∈ f) : ultrafilter α := { to_filter := f, ne_bot' := ⟨λ hf, by simpa [hf] using h⟩, le_of_le := λ g hg hgf s hs, (h s).1 $ λ hsc, by exactI compl_not_mem hs (hgf hsc) } lemma nonempty_of_mem (hs : s ∈ f) : s.nonempty := nonempty_of_mem hs lemma ne_empty_of_mem (hs : s ∈ f) : s ≠ ∅ := (nonempty_of_mem hs).ne_empty @[simp] lemma empty_not_mem : ∅ ∉ f := empty_not_mem f lemma mem_or_compl_mem (f : ultrafilter α) (s : set α) : s ∈ f ∨ sᶜ ∈ f := or_iff_not_imp_left.2 compl_mem_iff_not_mem.2 protected lemma em (f : ultrafilter α) (p : α → Prop) : (∀ᶠ x in f, p x) ∨ ∀ᶠ x in f, ¬p x := f.mem_or_compl_mem {x | p x} lemma eventually_or : (∀ᶠ x in f, p x ∨ q x) ↔ (∀ᶠ x in f, p x) ∨ ∀ᶠ x in f, q x := ⟨λ H, (f.em p).imp_right $ λ hp, (H.and hp).mono $ λ x ⟨hx, hnx⟩, hx.resolve_left hnx, λ H, H.elim (λ hp, hp.mono $ λ x, or.inl) (λ hp, hp.mono $ λ x, or.inr)⟩ lemma union_mem_iff : s ∪ t ∈ f ↔ s ∈ f ∨ t ∈ f := eventually_or lemma eventually_not : (∀ᶠ x in f, ¬p x) ↔ ¬∀ᶠ x in f, p x := compl_mem_iff_not_mem lemma eventually_imp : (∀ᶠ x in f, p x → q x) ↔ (∀ᶠ x in f, p x) → ∀ᶠ x in f, q x := by simp only [imp_iff_not_or, eventually_or, eventually_not] lemma finite_sUnion_mem_iff {s : set (set α)} (hs : s.finite) : ⋃₀ s ∈ f ↔ ∃t∈s, t ∈ f := finite.induction_on hs (by simp) $ λ a s ha hs his, by simp [union_mem_iff, his, or_and_distrib_right, exists_or_distrib] lemma finite_bUnion_mem_iff {is : set β} {s : β → set α} (his : is.finite) : (⋃i∈is, s i) ∈ f ↔ ∃i∈is, s i ∈ f := by simp only [← sUnion_image, finite_sUnion_mem_iff (his.image s), bex_image_iff] /-- Pushforward for ultrafilters. -/ def map (m : α → β) (f : ultrafilter α) : ultrafilter β := of_compl_not_mem_iff (map m f) $ λ s, @compl_not_mem_iff _ f (m ⁻¹' s) @[simp, norm_cast] lemma coe_map (m : α → β) (f : ultrafilter α) : (map m f : filter β) = filter.map m ↑f := rfl @[simp] lemma mem_map {m : α → β} {f : ultrafilter α} {s : set β} : s ∈ map m f ↔ m ⁻¹' s ∈ f := iff.rfl @[simp] lemma map_id (f : ultrafilter α) : f.map id = f := coe_injective map_id @[simp] lemma map_id' (f : ultrafilter α) : f.map (λ x, x) = f := map_id _ @[simp] lemma map_map (f : ultrafilter α) (m : α → β) (n : β → γ) : (f.map m).map n = f.map (n ∘ m) := coe_injective map_map /-- The pullback of an ultrafilter along an injection whose range is large with respect to the given ultrafilter. -/ def comap {m : α → β} (u : ultrafilter β) (inj : injective m) (large : set.range m ∈ u) : ultrafilter α := { to_filter := comap m u, ne_bot' := u.ne_bot'.comap_of_range_mem large, le_of_le := λ g hg hgu, by { resetI, simp only [← u.unique (map_le_iff_le_comap.2 hgu), comap_map inj, le_rfl] } } @[simp] lemma mem_comap {m : α → β} (u : ultrafilter β) (inj : injective m) (large : set.range m ∈ u) {s : set α} : s ∈ u.comap inj large ↔ m '' s ∈ u := mem_comap_iff inj large @[simp, norm_cast] lemma coe_comap {m : α → β} (u : ultrafilter β) (inj : injective m) (large : set.range m ∈ u) : (u.comap inj large : filter α) = filter.comap m u := rfl @[simp] lemma comap_id (f : ultrafilter α) (h₀ : injective (id : α → α) := injective_id) (h₁ : range id ∈ f := by { rw range_id, exact univ_mem}) : f.comap h₀ h₁ = f := coe_injective comap_id @[simp] lemma comap_comap (f : ultrafilter γ) {m : α → β} {n : β → γ} (inj₀ : injective n) (large₀ : range n ∈ f) (inj₁ : injective m) (large₁ : range m ∈ f.comap inj₀ large₀) (inj₂ : injective (n ∘ m) := inj₀.comp inj₁) (large₂ : range (n ∘ m) ∈ f := by { rw range_comp, exact image_mem_of_mem_comap large₀ large₁ }) : (f.comap inj₀ large₀).comap inj₁ large₁ = f.comap inj₂ large₂ := coe_injective comap_comap /-- The principal ultrafilter associated to a point `x`. -/ instance : has_pure ultrafilter := ⟨λ α a, of_compl_not_mem_iff (pure a) $ λ s, by simp⟩ @[simp] lemma mem_pure {a : α} {s : set α} : s ∈ (pure a : ultrafilter α) ↔ a ∈ s := iff.rfl @[simp] lemma coe_pure (a : α) : ↑(pure a : ultrafilter α) = (pure a : filter α) := rfl @[simp] lemma map_pure (m : α → β) (a : α) : map m (pure a) = pure (m a) := rfl @[simp] lemma comap_pure {m : α → β} (a : α) (inj : injective m) (large) : comap (pure $ m a) inj large = pure a := coe_injective $ comap_pure.trans $ by rw [coe_pure, ←principal_singleton, ←image_singleton, preimage_image_eq _ inj] lemma pure_injective : injective (pure : α → ultrafilter α) := λ a b h, filter.pure_injective (congr_arg ultrafilter.to_filter h : _) instance [inhabited α] : inhabited (ultrafilter α) := ⟨pure default⟩ instance [nonempty α] : nonempty (ultrafilter α) := nonempty.map pure infer_instance lemma eq_pure_of_finite_mem (h : s.finite) (h' : s ∈ f) : ∃ x ∈ s, (f : filter α) = pure x := begin rw ← bUnion_of_singleton s at h', rcases (ultrafilter.finite_bUnion_mem_iff h).mp h' with ⟨a, has, haf⟩, use [a, has], change (f : filter α) = (pure a : ultrafilter α), rw [ultrafilter.coe_inj, ← ultrafilter.coe_le_coe], change (f : filter α) ≤ pure a, rwa [← principal_singleton, le_principal_iff] end lemma eq_pure_of_fintype [fintype α] (f : ultrafilter α) : ∃ a, (f : filter α) = pure a := (eq_pure_of_finite_mem finite_univ univ_mem).imp $ λ a ⟨_, ha⟩, ha /-- Monadic bind for ultrafilters, coming from the one on filters defined in terms of map and join.-/ def bind (f : ultrafilter α) (m : α → ultrafilter β) : ultrafilter β := of_compl_not_mem_iff (bind ↑f (λ x, ↑(m x))) $ λ s, by simp only [mem_bind', mem_coe, ← compl_mem_iff_not_mem, compl_set_of, compl_compl] instance has_bind : has_bind ultrafilter := ⟨@ultrafilter.bind⟩ instance functor : functor ultrafilter := { map := @ultrafilter.map } instance monad : monad ultrafilter := { map := @ultrafilter.map } section local attribute [instance] filter.monad filter.is_lawful_monad instance is_lawful_monad : is_lawful_monad ultrafilter := { id_map := assume α f, coe_injective (id_map f.1), pure_bind := assume α β a f, coe_injective (pure_bind a (coe ∘ f)), bind_assoc := assume α β γ f m₁ m₂, coe_injective (filter_eq rfl), bind_pure_comp_eq_map := assume α β f x, coe_injective (bind_pure_comp_eq_map f x.1) } end /-- The ultrafilter lemma: Any proper filter is contained in an ultrafilter. -/ lemma exists_le (f : filter α) [h : ne_bot f] : ∃u : ultrafilter α, ↑u ≤ f := begin let τ := {f' // ne_bot f' ∧ f' ≤ f}, let r : τ → τ → Prop := λt₁ t₂, t₂.val ≤ t₁.val, haveI := nonempty_of_ne_bot f, let top : τ := ⟨f, h, le_refl f⟩, let sup : Π(c:set τ), is_chain r c → τ := λc hc, ⟨⨅a:{a:τ // a ∈ insert top c}, a.1, infi_ne_bot_of_directed (is_chain.directed $ hc.insert $ λ ⟨b, _, hb⟩ _ _, or.inl hb) (assume ⟨⟨a, ha, _⟩, _⟩, ha), infi_le_of_le ⟨top, mem_insert _ _⟩ le_rfl⟩, have : ∀ c (hc : is_chain r c) a (ha : a ∈ c), r a (sup c hc), from assume c hc a ha, infi_le_of_le ⟨a, mem_insert_of_mem _ ha⟩ le_rfl, have : (∃ (u : τ), ∀ (a : τ), r u a → r a u), from exists_maximal_of_chains_bounded (assume c hc, ⟨sup c hc, this c hc⟩) (assume f₁ f₂ f₃ h₁ h₂, le_trans h₂ h₁), cases this with uτ hmin, exact ⟨⟨uτ.val, uτ.property.left, assume g hg₁ hg₂, hmin ⟨g, hg₁, le_trans hg₂ uτ.property.right⟩ hg₂⟩, uτ.property.right⟩ end alias exists_le ← _root_.filter.exists_ultrafilter_le /-- Construct an ultrafilter extending a given filter. The ultrafilter lemma is the assertion that such a filter exists; we use the axiom of choice to pick one. -/ noncomputable def of (f : filter α) [ne_bot f] : ultrafilter α := classical.some (exists_le f) lemma of_le (f : filter α) [ne_bot f] : ↑(of f) ≤ f := classical.some_spec (exists_le f) lemma of_coe (f : ultrafilter α) : of ↑f = f := coe_inj.1 $ f.unique (of_le f) lemma exists_ultrafilter_of_finite_inter_nonempty (S : set (set α)) (cond : ∀ T : finset (set α), (↑T : set (set α)) ⊆ S → (⋂₀ (↑T : set (set α))).nonempty) : ∃ F : ultrafilter α, S ⊆ F.sets := begin suffices : ∃ F : filter α, ne_bot F ∧ S ⊆ F.sets, { rcases this with ⟨F, cond, hF⟩, resetI, obtain ⟨G : ultrafilter α, h1 : ↑G ≤ F⟩ := exists_le F, exact ⟨G, λ T hT, h1 (hF hT)⟩ }, use filter.generate S, refine ⟨_, λ T hT, filter.generate_sets.basic hT⟩, rw ← forall_mem_nonempty_iff_ne_bot, intros T hT, rcases mem_generate_iff.mp hT with ⟨A, h1, h2, h3⟩, let B := set.finite.to_finset h2, rw (show A = ↑B, by simp) at *, rcases cond B h1 with ⟨x, hx⟩, exact ⟨x, h3 hx⟩, end end ultrafilter namespace filter variables {f : filter α} {s : set α} {a : α} open ultrafilter protected lemma ne_bot.le_pure_iff (hf : f.ne_bot) : f ≤ pure a ↔ f = pure a := ⟨ultrafilter.unique (pure a), le_of_eq⟩ lemma mem_iff_ultrafilter : s ∈ f ↔ ∀ g : ultrafilter α, ↑g ≤ f → s ∈ g := begin refine ⟨λ hf g hg, hg hf, λ H, by_contra $ λ hf, _⟩, set g : filter ↥sᶜ := comap coe f, haveI : ne_bot g := comap_ne_bot_iff_compl_range.2 (by simpa [compl_set_of]), simpa using H ((of g).map coe) (map_le_iff_le_comap.mpr (of_le g)) end lemma le_iff_ultrafilter {f₁ f₂ : filter α} : f₁ ≤ f₂ ↔ ∀ g : ultrafilter α, ↑g ≤ f₁ → ↑g ≤ f₂ := ⟨λ h g h₁, h₁.trans h, λ h s hs, mem_iff_ultrafilter.2 $ λ g hg, h g hg hs⟩ /-- A filter equals the intersection of all the ultrafilters which contain it. -/ lemma supr_ultrafilter_le_eq (f : filter α) : (⨆ (g : ultrafilter α) (hg : ↑g ≤ f), (g : filter α)) = f := eq_of_forall_ge_iff $ λ f', by simp only [supr_le_iff, ← le_iff_ultrafilter] /-- The `tendsto` relation can be checked on ultrafilters. -/ lemma tendsto_iff_ultrafilter (f : α → β) (l₁ : filter α) (l₂ : filter β) : tendsto f l₁ l₂ ↔ ∀ g : ultrafilter α, ↑g ≤ l₁ → tendsto f g l₂ := by simpa only [tendsto_iff_comap] using le_iff_ultrafilter lemma exists_ultrafilter_iff {f : filter α} : (∃ (u : ultrafilter α), ↑u ≤ f) ↔ ne_bot f := ⟨λ ⟨u, uf⟩, ne_bot_of_le uf, λ h, @exists_ultrafilter_le _ _ h⟩ lemma forall_ne_bot_le_iff {g : filter α} {p : filter α → Prop} (hp : monotone p) : (∀ f : filter α, ne_bot f → f ≤ g → p f) ↔ ∀ f : ultrafilter α, ↑f ≤ g → p f := begin refine ⟨λ H f hf, H f f.ne_bot hf, _⟩, introsI H f hf hfg, exact hp (of_le f) (H _ ((of_le f).trans hfg)) end section hyperfilter variables (α) [infinite α] /-- The ultrafilter extending the cofinite filter. -/ noncomputable def hyperfilter : ultrafilter α := ultrafilter.of cofinite variable {α} lemma hyperfilter_le_cofinite : ↑(hyperfilter α) ≤ @cofinite α := ultrafilter.of_le cofinite @[simp] lemma bot_ne_hyperfilter : (⊥ : filter α) ≠ hyperfilter α := (by apply_instance : ne_bot ↑(hyperfilter α)).1.symm theorem nmem_hyperfilter_of_finite {s : set α} (hf : s.finite) : s ∉ hyperfilter α := λ hy, compl_not_mem hy $ hyperfilter_le_cofinite hf.compl_mem_cofinite alias nmem_hyperfilter_of_finite ← _root_.set.finite.nmem_hyperfilter theorem compl_mem_hyperfilter_of_finite {s : set α} (hf : set.finite s) : sᶜ ∈ hyperfilter α := compl_mem_iff_not_mem.2 hf.nmem_hyperfilter alias compl_mem_hyperfilter_of_finite ← _root_.set.finite.compl_mem_hyperfilter theorem mem_hyperfilter_of_finite_compl {s : set α} (hf : set.finite sᶜ) : s ∈ hyperfilter α := compl_compl s ▸ hf.compl_mem_hyperfilter end hyperfilter end filter namespace ultrafilter open filter variables {m : α → β} {s : set α} {g : ultrafilter β} lemma comap_inf_principal_ne_bot_of_image_mem (h : m '' s ∈ g) : (filter.comap m g ⊓ 𝓟 s).ne_bot := filter.comap_inf_principal_ne_bot_of_image_mem g.ne_bot h /-- Ultrafilter extending the inf of a comapped ultrafilter and a principal ultrafilter. -/ noncomputable def of_comap_inf_principal (h : m '' s ∈ g) : ultrafilter α := @of _ (filter.comap m g ⊓ 𝓟 s) (comap_inf_principal_ne_bot_of_image_mem h) lemma of_comap_inf_principal_mem (h : m '' s ∈ g) : s ∈ of_comap_inf_principal h := begin let f := filter.comap m g ⊓ 𝓟 s, haveI : f.ne_bot := comap_inf_principal_ne_bot_of_image_mem h, have : s ∈ f := mem_inf_of_right (mem_principal_self s), exact le_def.mp (of_le _) s this end lemma of_comap_inf_principal_eq_of_map (h : m '' s ∈ g) : (of_comap_inf_principal h).map m = g := begin let f := filter.comap m g ⊓ 𝓟 s, haveI : f.ne_bot := comap_inf_principal_ne_bot_of_image_mem h, apply eq_of_le, calc filter.map m (of f) ≤ filter.map m f : map_mono (of_le _) ... ≤ (filter.map m $ filter.comap m g) ⊓ filter.map m (𝓟 s) : map_inf_le ... = (filter.map m $ filter.comap m g) ⊓ (𝓟 $ m '' s) : by rw map_principal ... ≤ g ⊓ (𝓟 $ m '' s) : inf_le_inf_right _ map_comap_le ... = g : inf_of_le_left (le_principal_iff.mpr h) end end ultrafilter
a3380fff23cdf814cb90066df42950bbe58cdea4
9cb9db9d79fad57d80ca53543dc07efb7c4f3838
/src/for_mathlib/topology.lean
67d62233d43a8fdfafc5ac042125b02ac0fd3fe5
[]
no_license
mr-infty/lean-liquid
3ff89d1f66244b434654c59bdbd6b77cb7de0109
a8db559073d2101173775ccbd85729d3a4f1ed4d
refs/heads/master
1,678,465,145,334
1,614,565,310,000
1,614,565,310,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,735
lean
import topology.separation import topology.subset_properties variables {X Y : Type*} [topological_space X] [topological_space Y] lemma is_totally_disconnected_of_totally_disconnected_space [totally_disconnected_space X] (s : set X) : is_totally_disconnected s := λ t hts ht, totally_disconnected_space.is_totally_disconnected_univ _ (set.subset_univ t) ht lemma is_preconnected.subsingleton [totally_disconnected_space X] {s : set X} (hs : is_preconnected s) : subsingleton s := is_totally_disconnected_of_totally_disconnected_space s s (set.subset.refl _) hs namespace embedding lemma t2_space [t2_space Y] {f : X → Y} (hf : embedding f) : t2_space X := { t2 := λ x y h, begin obtain ⟨U, V, hU, hV, hx, hy, hUV⟩ := t2_separation (hf.inj.ne h), refine ⟨f ⁻¹' U, f ⁻¹' V, hf.continuous.is_open_preimage _ hU, hf.continuous.is_open_preimage _ hV, set.mem_preimage.mpr hx, set.mem_preimage.mpr hy, _⟩, rw ← set.disjoint_iff_inter_eq_empty at hUV ⊢, exact hUV.preimage _ end } lemma is_totally_disconnected {f : X → Y} (hf : embedding f) (s : set X) (h : is_totally_disconnected (f '' s)) : is_totally_disconnected s := begin rintro t hts ht, have htc : is_preconnected (f '' t) := ht.image f hf.continuous.continuous_on, haveI := h _ (set.image_subset _ hts) htc, constructor, intros a b, ext, apply hf.inj, have := @subsingleton.elim (f '' t) _ ⟨f a, set.mem_image_of_mem f a.2⟩ ⟨f b, set.mem_image_of_mem f b.2⟩, simpa only [subtype.mk_eq_mk] end lemma totally_disconnected_space [totally_disconnected_space Y] {f : X → Y} (hf : embedding f) : totally_disconnected_space X := { is_totally_disconnected_univ := begin apply hf.is_totally_disconnected, apply is_totally_disconnected_of_totally_disconnected_space end } end embedding namespace inducing lemma exists_open {f : X → Y} (hf : inducing f) ⦃U : set X⦄ (hU : is_open U) : ∃ V, is_open V ∧ f ⁻¹' V = U := begin unfreezingI { cases hf.induced }, rwa ← @is_open_induced_iff X Y _ _ f end lemma is_compact {f : X → Y} (hf : inducing f) (s : set X) (hs : is_compact (f '' s)) : is_compact s := begin apply compact_of_finite_subcover, intros ι U hU hsU, have : ∀ i, ∃ V, is_open V ∧ f ⁻¹' V = (U i), { intro i, apply hf.exists_open (hU i) }, choose V hV₁ hV₂ using this, have : f '' s ⊆ ⋃ (i : ι), V i, { rw [set.image_subset_iff, set.preimage_Union], refine set.subset.trans hsU (set.Union_subset_Union _), intro i, rw hV₂ }, obtain ⟨t, ht⟩ := hs.elim_finite_subcover V hV₁ this, refine ⟨t, _⟩, simp only [set.image_subset_iff, set.preimage_Union] at ht, refine set.subset.trans ht (set.Union_subset_Union _), intro i, refine set.Union_subset_Union _, rintro -, rw hV₂ end -- -- is there a short proof using filters? jmc couldn't find it -- lemma is_compact {f : X → Y} (hf : inducing f) (s : set X) (hs : is_compact (f '' s)) : -- is_compact s := -- begin -- intros F hF hFs, -- have : (F.map f) ≤ filter.principal (f '' s), -- { rw filter.map_le_iff_le_comap, -- simp only [filter.le_principal_iff, filter.comap_principal] at hFs ⊢, -- apply filter.mem_sets_of_superset hFs, -- exact set.subset_preimage_image f s }, -- haveI : (F.map f).ne_bot := _, -- obtain ⟨-, ⟨x, hxs, rfl⟩, hx⟩ := hs this, -- refine ⟨x, hxs, _⟩, -- rw cluster_pt_iff at hx ⊢, -- intros U hU V hV, -- rw [hf.nhds_eq_comap, filter.mem_comap_sets] at hU, -- rcases hU with ⟨U', hU', hfU'⟩, -- specialize hx hU', -- have : f '' V ∈ F.map f, -- { rw filter.mem_map, }, -- admit, -- admit -- end end inducing
afd136b50d357b79ca04a1b9f495bd929e3ccb08
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/tactic/default.lean
5634b77de9754dd399c6de69d980e07f1723da2e
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
876
lean
/- This file imports many useful tactics ("the kitchen sink"). You can use `import tactic` at the beginning of your file to get everything. (Although you may want to strip things down when you're polishing.) Because this file imports some complicated tactics, it has many transitive dependencies (which of course may not use `import tactic`, and must import selectively). As (non-exhaustive) examples, these includes things like: * algebra.group_power * algebra.ordered_ring * data.rat * data.nat.prime * data.list.perm * data.set.lattice * data.equiv.encodable * order.complete_lattice -/ import tactic.abel import tactic.ring_exp import tactic.linarith import tactic.omega import tactic.tfae import tactic.apply_fun import tactic.interval_cases import tactic.reassoc_axiom -- most likely useful only for category_theory import tactic.slice import tactic.subtype_instance
a766536f64b9bc5da7341723e6c40f231ea3319d
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/tactic/monotonicity/basic.lean
3e23bd4e22f1fdb7b0ee6ed2bef8c17be9c54c7b
[ "Apache-2.0" ]
permissive
agjftucker/mathlib
d634cd0d5256b6325e3c55bb7fb2403548371707
87fe50de17b00af533f72a102d0adefe4a2285e8
refs/heads/master
1,625,378,131,941
1,599,166,526,000
1,599,166,526,000
160,748,509
0
0
Apache-2.0
1,544,141,789,000
1,544,141,789,000
null
UTF-8
Lean
false
false
5,469
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon -/ import algebra.order_functions namespace tactic.interactive open tactic list open lean lean.parser interactive open interactive.types @[derive inhabited] structure mono_cfg := (unify := ff) @[derive [decidable_eq, has_reflect, inhabited]] inductive mono_selection : Type | left : mono_selection | right : mono_selection | both : mono_selection section compare parameter opt : mono_cfg meta def compare (e₀ e₁ : expr) : tactic unit := do if opt.unify then do guard (¬ e₀.is_mvar ∧ ¬ e₁.is_mvar), unify e₀ e₁ else is_def_eq e₀ e₁ meta def find_one_difference : list expr → list expr → tactic (list expr × expr × expr × list expr) | (x :: xs) (y :: ys) := do c ← try_core (compare x y), if c.is_some then prod.map (cons x) id <$> find_one_difference xs ys else do guard (xs.length = ys.length), mzip_with' compare xs ys, return ([],x,y,xs) | xs ys := fail format!"find_one_difference: {xs}, {ys}" end compare def last_two {α : Type*} (l : list α) : option (α × α) := match l.reverse with | (x₁ :: x₀ :: _) := some (x₀, x₁) | _ := none end meta def match_imp : expr → tactic (expr × expr) | `(%%e₀ → %%e₁) := do guard (¬ e₁.has_var), return (e₀,e₁) | _ := failed open expr meta def same_operator : expr → expr → bool | (app e₀ _) (app e₁ _) := let fn₀ := e₀.get_app_fn, fn₁ := e₁.get_app_fn in fn₀.is_constant ∧ fn₀.const_name = fn₁.const_name | (pi _ _ _ _) (pi _ _ _ _) := tt | _ _ := ff meta def get_operator (e : expr) : option name := guard (¬ e.is_pi) >> pure e.get_app_fn.const_name meta def monotonicity.check_rel (l r : expr) : tactic (option name) := do guard (same_operator l r) <|> do { fail format!"{l} and {r} should be the f x and f y for some f" }, if l.is_pi then pure none else pure r.get_app_fn.const_name @[reducible] def mono_key := (with_bot name × with_bot name) open nat meta def mono_head_candidates : ℕ → list expr → expr → tactic mono_key | 0 _ h := fail!"Cannot find relation in {h}" | (succ n) xs h := do { (rel,l,r) ← if h.is_arrow then pure (none,h.binding_domain,h.binding_body) else guard h.get_app_fn.is_constant >> prod.mk (some h.get_app_fn.const_name) <$> last_two h.get_app_args, prod.mk <$> monotonicity.check_rel l r <*> pure rel } <|> match xs with | [] := fail format!"oh? {h}" | (x::xs) := mono_head_candidates n xs (h.pis [x]) end meta def monotonicity.check (lm_n : name) : tactic mono_key := do lm ← mk_const lm_n, lm_t ← infer_type lm, lm_t ← expr.dsimp lm_t { fail_if_unchanged := ff } tt [] [simp_arg_type.expr ``(monotone)], (xs,h) ← open_pis lm_t, mono_head_candidates 3 xs.reverse h meta instance : has_to_format mono_selection := ⟨ λ x, match x with | mono_selection.left := "left" | mono_selection.right := "right" | mono_selection.both := "both" end ⟩ meta def side : lean.parser mono_selection := with_desc "expecting 'left', 'right' or 'both' (default)" $ do some n ← optional ident | pure mono_selection.both, if n = `left then pure $ mono_selection.left else if n = `right then pure $ mono_selection.right else if n = `both then pure $ mono_selection.both else fail format!"invalid argument: {n}, expecting 'left', 'right' or 'both' (default)" open function @[user_attribute] meta def monotonicity.attr : user_attribute (native.rb_lmap mono_key (name)) (option mono_key × mono_selection) := { name := `mono , descr := "monotonicity of function `f` wrt relations `R₀` and `R₁`: R₀ x y → R₁ (f x) (f y)" , cache_cfg := { dependencies := [], mk_cache := λ ls, do ps ← ls.mmap monotonicity.attr.get_param, let ps := ps.filter_map prod.fst, pure $ (ps.zip ls).foldl (flip $ uncurry (λ k n m, m.insert k n)) (native.rb_lmap.mk mono_key _) } , after_set := some $ λ n prio p, do { (none,v) ← monotonicity.attr.get_param n | pure (), k ← monotonicity.check n, monotonicity.attr.set n (some k,v) p } , parser := prod.mk none <$> side } meta def filter_instances (e : mono_selection) (ns : list name) : tactic (list name) := ns.mfilter $ λ n, do d ← user_attribute.get_param_untyped monotonicity.attr n, (_,d) ← to_expr ``(id %%d) >>= eval_expr (option mono_key × mono_selection), return (e = d : bool) meta def get_monotonicity_lemmas (k : expr) (e : mono_selection) : tactic (list name) := do ns ← monotonicity.attr.get_cache, k' ← if k.is_pi then pure (get_operator k.binding_domain,none) else do { (x₀,x₁) ← last_two k.get_app_args, pure (get_operator x₀,some k.get_app_fn.const_name) }, let ns := ns.find_def [] k', ns' ← filter_instances e ns, if e ≠ mono_selection.both then (++) ns' <$> filter_instances mono_selection.both ns else pure ns' end tactic.interactive attribute [mono] add_le_add mul_le_mul neg_le_neg mul_lt_mul_of_pos_left mul_lt_mul_of_pos_right imp_imp_imp le_implies_le_of_le_of_le sub_le_sub abs_le_abs attribute [mono left] add_lt_add_of_le_of_lt mul_lt_mul' attribute [mono right] add_lt_add_of_lt_of_le mul_lt_mul
158a4ae4e7187870e925b82b4a006d95b790425b
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/ring_theory/euclidean_domain.lean
2a65a7e94117f5f85697524c7511b7cf0bcdfc9a
[ "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
2,126
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes -/ import ring_theory.coprime import ring_theory.ideals noncomputable theory open_locale classical open euclidean_domain set ideal theorem span_gcd {α} [euclidean_domain α] (x y : α) : span ({gcd x y} : set α) = span ({x, y} : set α) := begin apply le_antisymm, { refine span_le.2 (λ x, _), simp only [set.mem_singleton_iff, submodule.mem_coe, mem_span_pair], rintro rfl, exact ⟨gcd_a x y, gcd_b x y, by simp [gcd_eq_gcd_ab, mul_comm]⟩ }, { assume z , simp [mem_span_singleton, euclidean_domain.gcd_dvd_left, mem_span_pair, @eq_comm _ _ z] {contextual := tt}, assume a b h, exact dvd_add (dvd_mul_of_dvd_right (gcd_dvd_left _ _) _) (dvd_mul_of_dvd_right (gcd_dvd_right _ _) _) } end theorem gcd_is_unit_iff {α} [euclidean_domain α] {x y : α} : is_unit (gcd x y) ↔ is_coprime x y := ⟨λ h, let ⟨b, hb⟩ := is_unit_iff_exists_inv'.1 h in ⟨b * gcd_a x y, b * gcd_b x y, by rw [← hb, gcd_eq_gcd_ab, mul_comm x, mul_comm y, mul_add, mul_assoc, mul_assoc]⟩, λ ⟨a, b, h⟩, is_unit_iff_dvd_one.2 $ h ▸ dvd_add (dvd_mul_of_dvd_right (gcd_dvd_left x y) _) (dvd_mul_of_dvd_right (gcd_dvd_right x y) _)⟩ theorem is_coprime_of_dvd {α} [euclidean_domain α] {x y : α} (z : ¬ (x = 0 ∧ y = 0)) (H : ∀ z ∈ nonunits α, z ≠ 0 → z ∣ x → ¬ z ∣ y) : is_coprime x y := begin rw [← gcd_is_unit_iff], by_contra h, refine H _ h _ (gcd_dvd_left _ _) (gcd_dvd_right _ _), rwa [ne, euclidean_domain.gcd_eq_zero_iff] end theorem dvd_or_coprime {α} [euclidean_domain α] (x y : α) (h : irreducible x) : x ∣ y ∨ is_coprime x y := begin refine or_iff_not_imp_left.2 (λ h', _), apply is_coprime_of_dvd, { unfreezingI { rintro ⟨rfl, rfl⟩ }, simpa using h }, { unfreezingI { rintro z nu nz ⟨w, rfl⟩ dy }, refine h' (dvd.trans _ dy), simpa using mul_dvd_mul_left z (is_unit_iff_dvd_one.1 $ (of_irreducible_mul h).resolve_left nu) } end
59d3a3de0ef9770d03a3946ef2b35bbeb8a2142b
b00eb947a9c4141624aa8919e94ce6dcd249ed70
/stage0/src/Lean/Hygiene.lean
97c2d835a45a878fec0f620b96fadce49f3a1a46
[ "Apache-2.0" ]
permissive
gebner/lean4-old
a4129a041af2d4d12afb3a8d4deedabde727719b
ee51cdfaf63ee313c914d83264f91f414a0e3b6e
refs/heads/master
1,683,628,606,745
1,622,651,300,000
1,622,654,405,000
142,608,821
1
0
null
null
null
null
UTF-8
Lean
false
false
4,616
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import Lean.Data.Name import Lean.Data.Options import Lean.Data.Format namespace Lean /- Remark: `MonadQuotation` class is part of the `Init` package and loaded by default since it is used in the builtin command `macro`. -/ structure Unhygienic.Context where ref : Syntax scope : MacroScope /-- Simplistic MonadQuotation that does not guarantee globally fresh names, that is, between different runs of this or other MonadQuotation implementations. It is only safe if the syntax quotations do not introduce bindings around antiquotations, and if references to globals are prefixed with `_root_.` (which is not allowed to refer to a local variable). `Unhygienic` can also be seen as a model implementation of `MonadQuotation` (since it is completely hygienic as long as it is "run" only once and can assume that there are no other implentations in use, as is the case for the elaboration monads that carry their macro scope state through the entire processing of a file). It uses the state monad to query and allocate the next macro scope, and uses the reader monad to store the stack of scopes corresponding to `withFreshMacroScope` calls. -/ abbrev Unhygienic := ReaderT Lean.Unhygienic.Context $ StateM MacroScope namespace Unhygienic instance : MonadQuotation Unhygienic := { getRef := do (← read).ref, withRef := fun ref => withReader ({ · with ref := ref }), getCurrMacroScope := do (← read).scope, getMainModule := pure `UnhygienicMain, withFreshMacroScope := fun x => do let fresh ← modifyGet fun n => (n, n + 1) withReader ({ · with scope := fresh}) x } protected def run {α : Type} (x : Unhygienic α) : α := (x ⟨Syntax.missing, firstFrontendMacroScope⟩).run' (firstFrontendMacroScope+1) end Unhygienic private def mkInaccessibleUserNameAux (unicode : Bool) (name : Name) (idx : Nat) : Name := if unicode then if idx == 0 then name.appendAfter "✝" else name.appendAfter ("✝" ++ idx.toSuperscriptString) else name ++ Name.mkNum "_inaccessible" idx private def mkInaccessibleUserName (unicode : Bool) : Name → Name | Name.num p@(Name.str _ _ _) idx _ => mkInaccessibleUserNameAux unicode p idx | Name.num Name.anonymous idx _ => mkInaccessibleUserNameAux unicode Name.anonymous idx | Name.num p idx _ => if unicode then (mkInaccessibleUserName unicode p).appendAfter ("⁻" ++ idx.toSuperscriptString) else Name.mkNum (mkInaccessibleUserName unicode p) idx | n => n def sanitizeNamesDefault := true def getSanitizeNames (o : Options) : Bool:= o.get `pp.sanitizeNames sanitizeNamesDefault builtin_initialize registerOption `pp.sanitizeNames { defValue := sanitizeNamesDefault, group := "pp", descr := "add suffix '_{<idx>}' to shadowed/inaccessible variables when pretty printing" } structure NameSanitizerState where options : Options -- `x` ~> 2 if we're already using `x✝`, `x✝¹` nameStem2Idx : NameMap Nat := {} -- `x._hyg...` ~> `x✝` userName2Sanitized : NameMap Name := {} private partial def mkFreshInaccessibleUserName (userName : Name) (idx : Nat) : StateM NameSanitizerState Name := do let s ← get let userNameNew := mkInaccessibleUserName (Std.Format.getUnicode s.options) (Name.mkNum userName idx) if s.nameStem2Idx.contains userNameNew then mkFreshInaccessibleUserName userName (idx+1) else do modify fun s => { s with nameStem2Idx := s.nameStem2Idx.insert userName (idx+1) } pure userNameNew def sanitizeName (userName : Name) : StateM NameSanitizerState Name := do let stem := userName.eraseMacroScopes; let idx := (← get).nameStem2Idx.find? stem |>.getD 0 let san ← mkFreshInaccessibleUserName stem idx modify fun s => { s with userName2Sanitized := s.userName2Sanitized.insert userName san } pure san private partial def sanitizeSyntaxAux : Syntax → StateM NameSanitizerState Syntax | Syntax.ident _ _ n _ => do mkIdent <$> match (← get).userName2Sanitized.find? n with | some n' => pure n' | none => if n.hasMacroScopes then sanitizeName n else pure n | Syntax.node k args => Syntax.node k <$> args.mapM sanitizeSyntaxAux | stx => pure stx def sanitizeSyntax (stx : Syntax) : StateM NameSanitizerState Syntax := do if getSanitizeNames (← get).options then sanitizeSyntaxAux stx else pure stx end Lean
795ea8341cddbb8526fb65cdf29f070749fc3705
2385ce0e3b60d8dbea33dd439902a2070cca7a24
/tests/lean/run/with_cases1.lean
9a5a4da4171c696f955d70cee73af7b084dda38c
[ "Apache-2.0" ]
permissive
TehMillhouse/lean
68d6fdd2fb11a6c65bc28dec308d70f04dad38b4
6bbf2fbd8912617e5a973575bab8c383c9c268a1
refs/heads/master
1,620,830,893,339
1,515,592,479,000
1,515,592,997,000
116,964,828
0
0
null
1,515,592,734,000
1,515,592,734,000
null
UTF-8
Lean
false
false
1,402
lean
example (n : nat) (m : nat) : n > m → m < n := begin with_cases { revert m, induction n }, case nat.zero : m' { show 0 > m' → m' < 0, sorry }, case nat.succ : n' ih m' { show nat.succ n' > m' → m' < nat.succ n', sorry } end example (n : nat) (m : nat) : n > m → m < n := begin with_cases { revert m, induction n }, case nat.zero { show ∀ m, 0 > m → m < 0, sorry }, case nat.succ { show ∀ m, nat.succ n_n > m → m < nat.succ n_n, sorry } end example (n : nat) (m : nat) : n > m → m < n := begin with_cases { induction n generalizing m }, case nat.zero { show 0 > m → m < 0, sorry }, case nat.succ { show nat.succ n_n > m → m < nat.succ n_n, sorry } end example (n : nat) (m : nat) : n > m → m < n := begin with_cases { induction n generalizing m }, case nat.zero : m' { show 0 > m' → m' < 0, sorry }, case nat.succ : n' ih m' { show nat.succ n' > m' → m' < nat.succ n', sorry } end example (n : nat) (m : nat) : n > m → m < n := begin with_cases { induction n generalizing m }, case nat.zero : m' { show 0 > m' → m' < 0, sorry }, case nat.succ : n' ih { show nat.succ n' > m → m < nat.succ n', sorry } end example (n : nat) (m : nat) : n > m → m < n := begin with_cases { induction n generalizing m }, case nat.zero { show 0 > m → m < 0, sorry }, case nat.succ : n' ih { show nat.succ n' > m → m < nat.succ n', sorry } end
9912754255a9aa746e222d28e54a7934edcf5f36
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/system/io.lean
0775e0127476e772cdef8f131bac2ea686cb4d78
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
7,192
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Nelson, Jared Roesch and Leonardo de Moura -/ import data.buffer inductive io.error | other : string → io.error | sys : nat → io.error structure io.terminal (m : Type → Type → Type) := (put_str : string → m io.error unit) (get_line : m io.error string) (cmdline_args : list string) inductive io.mode | read | write | read_write | append structure io.file_system (handle : Type) (m : Type → Type → Type) := /- Remark: in Haskell, they also provide (Maybe TextEncoding) and NewlineMode -/ (mk_file_handle : string → io.mode → bool → m io.error handle) (is_eof : handle → m io.error bool) (flush : handle → m io.error unit) (close : handle → m io.error unit) (read : handle → nat → m io.error char_buffer) (write : handle → char_buffer → m io.error unit) (get_line : handle → m io.error char_buffer) (stdin : m io.error handle) (stdout : m io.error handle) (stderr : m io.error handle) structure io.environment (m : Type → Type → Type) := (get_env : string → m io.error (option string)) -- we don't provide set_env as it is (thread-)unsafe (at least with glibc) inductive io.process.stdio | piped | inherit | null structure io.process.spawn_args := /- Command name. -/ (cmd : string) /- Arguments for the process -/ (args : list string := []) /- Configuration for the process' stdin handle. -/ (stdin := stdio.inherit) /- Configuration for the process' stdout handle. -/ (stdout := stdio.inherit) /- Configuration for the process' stderr handle. -/ (stderr := stdio.inherit) /- Working directory for the process. -/ (cwd : option string := none) /- Environment variables for the process. -/ (env : list (string × option string) := []) structure io.process (handle : Type) (m : Type → Type → Type) := (child : Type) (stdin : child → handle) (stdout : child → handle) (stderr : child → handle) (spawn : io.process.spawn_args → m io.error child) (wait : child → m io.error nat) class io.interface := (m : Type → Type → Type) (monad : Π e, monad (m e)) (catch : Π e₁ e₂ α, m e₁ α → (e₁ → m e₂ α) → m e₂ α) (fail : Π e α, e → m e α) (iterate : Π e α, α → (α → m e (option α)) → m e α) -- Primitive Types (handle : Type) -- Interface Extensions (term : io.terminal m) (fs : io.file_system handle m) (process : io.process handle m) (env : io.environment m) variable [ioi : io.interface] include ioi def io_core (e : Type) (α : Type) := io.interface.m e α @[reducible] def io (α : Type) := io_core io.error α instance io_core_is_monad (e : Type) : monad (io_core e) := io.interface.monad e protected def io.fail {α : Type} (s : string) : io α := io.interface.fail io.error α (io.error.other s) instance : monad_fail io := { io_core_is_monad io.error with fail := @io.fail _ } namespace io def iterate {e α} (a : α) (f : α → io_core e (option α)) : io_core e α := interface.iterate e α a f def forever {e} (a : io_core e unit) : io_core e unit := iterate () $ λ _, a >> return (some ()) def catch {e₁ e₂ α} (a : io_core e₁ α) (b : e₁ → io_core e₂ α) : io_core e₂ α := interface.catch e₁ e₂ α a b def finally {α e} (a : io_core e α) (cleanup : io_core e unit) : io_core e α := do res ← catch (sum.inr <$> a) (return ∘ sum.inl), cleanup, match res with | sum.inr res := return res | sum.inl error := io.interface.fail _ _ error end instance : alternative io := { interface.monad _ with orelse := λ _ a b, catch a (λ _, b), failure := λ _, io.fail "failure" } def put_str : string → io unit := interface.term.put_str def put_str_ln (s : string) : io unit := put_str s >> put_str "\n" def get_line : io string := interface.term.get_line def cmdline_args : io (list string) := return interface.term.cmdline_args def print {α} [has_to_string α] (s : α) : io unit := put_str ∘ to_string $ s def print_ln {α} [has_to_string α] (s : α) : io unit := print s >> put_str "\n" def handle : Type := interface.handle def mk_file_handle (s : string) (m : mode) (bin : bool := ff) : io handle := interface.fs.mk_file_handle s m bin def stdin : io handle := interface.fs.stdin def stderr : io handle := interface.fs.stderr def stdout : io handle := interface.fs.stdout namespace env def get (env_var : string) : io (option string) := interface.env.get_env env_var end env namespace fs def is_eof : handle → io bool := interface.fs.is_eof def flush : handle → io unit := interface.fs.flush def close : handle → io unit := interface.fs.close def read : handle → nat → io char_buffer := interface.fs.read def write : handle → char_buffer → io unit := interface.fs.write def get_char (h : handle) : io char := do b ← read h 1, if h : b.size = 1 then return $ b.read ⟨0, h.symm ▸ zero_lt_one⟩ else io.fail "get_char failed" def get_line : handle → io char_buffer := interface.fs.get_line def put_char (h : handle) (c : char) : io unit := write h (mk_buffer.push_back c) def put_str (h : handle) (s : string) : io unit := write h (mk_buffer.append_string s) def put_str_ln (h : handle) (s : string) : io unit := put_str h s >> put_str h "\n" def read_to_end (h : handle) : io char_buffer := iterate mk_buffer $ λ r, do done ← is_eof h, if done then return none else do c ← read h 1024, return $ some (r ++ c) def read_file (s : string) (bin := ff) : io char_buffer := do h ← mk_file_handle s io.mode.read bin, read_to_end h end fs namespace proc def child : Type := interface.process.child def child.stdin : child → handle := interface.process.stdin def child.stdout : child → handle := interface.process.stdout def child.stderr : child → handle := interface.process.stderr def spawn (p : io.process.spawn_args) : io child := interface.process.spawn p def wait (c : child) : io nat := interface.process.wait c end proc end io meta constant format.print_using : format → options → io unit meta definition format.print (fmt : format) : io unit := format.print_using fmt options.mk meta definition pp_using {α : Type} [has_to_format α] (a : α) (o : options) : io unit := format.print_using (to_fmt a) o meta definition pp {α : Type} [has_to_format α] (a : α) : io unit := format.print (to_fmt a) /-- Run the external process specified by `args`. The process will run to completion with its output captured by a pipe, and read into `string` which is then returned. -/ def io.cmd (args : io.process.spawn_args) : io string := do child ← io.proc.spawn { args with stdout := io.process.stdio.piped }, buf ← io.fs.read_to_end child.stdout, exitv ← io.proc.wait child, when (exitv ≠ 0) $ io.fail $ "process exited with status " ++ exitv.to_string, return buf.to_string omit ioi /-- Lift a monadic `io` action into the `tactic` monad. -/ meta constant tactic.run_io {α : Type} : (Π ioi : io.interface, @io ioi α) → tactic α
c10d3caac431bd15b156ac9c8fe7091557ded131
a9fe717b93ccfa4b2e64faeb24f96dfefb390240
/int/preterm.lean
599d0a6156290473d18b5dd32aa3086c512dedec
[]
no_license
skbaek/omega
ab1f4a6daadfc8c855f14c39d9459ab841527141
715e384ed14e8eb177a326700066e7c98269e078
refs/heads/master
1,588,000,876,352
1,552,645,917,000
1,552,645,917,000
174,442,914
1
0
null
null
null
null
UTF-8
Lean
false
false
1,451
lean
import ..int ..simp_omega ..term ..logic namespace int @[derive has_reflect] inductive preterm : Type | cst : int → preterm | var : int → nat → preterm | add : preterm → preterm → preterm notation `&` k := preterm.cst k infix `**` : 300 := preterm.var notation t `+*` s := preterm.add t s -- | (& i) := sorry -- | (i ** n) := sorry -- | (t1 +* t2) := sorry namespace preterm @[omega] def val (v : nat → int) : preterm → int | (& i) := i | (i ** n) := if i = 1 then v n else if i = -1 then -(v n) else (v n) * i | (t1 +* t2) := t1.val + t2.val def fresh_idx : preterm → nat | (& _) := 0 | (i ** n) := n + 1 | (t1 +* t2) := max t1.fresh_idx t2.fresh_idx @[omega] def succ (t : preterm) : preterm := t +* (&1) def repr : preterm → string | (& i) := i.repr | (i ** n) := i.repr ++ "*x" ++ n.repr | (t1 +* t2) := "(" ++ t1.repr ++ " + " ++ t2.repr ++ ")" end preterm @[omega] def canonize : preterm → term | (& i) := ⟨i,[]⟩ | (i ** n) := ⟨0,[]{n ↦ i}⟩ | (t1 +* t2) := term.add (canonize t1) (canonize t2) @[omega] lemma val_canonize {v} : ∀ {t}, (canonize t).val v = t.val v | (& i) := by simp_omega | (i ** n) := begin simp_omega, apply ite.rec; intro h1, { simp only [one_mul, h1] }, { apply ite.rec; intro h2, { rw h2, simp }, { rw mul_comm } } end | (t1 +* t2) := by simp_omega [@val_canonize t1, @val_canonize t2] end int
6006d5803999dc96b8de961234a9a6c8082e2237
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/src/Lean/Data/KVMap.lean
70377c82308dee1b7a55636233ae28921ce9ace8
[ "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
6,014
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.Name namespace Lean inductive DataValue where | ofString (v : String) | ofBool (v : Bool) | ofName (v : Name) | ofNat (v : Nat) | ofInt (v : Int) deriving Inhabited, BEq @[export lean_mk_bool_data_value] def mkBoolDataValueEx (b : Bool) : DataValue := DataValue.ofBool b @[export lean_data_value_bool] def DataValue.getBoolEx : DataValue → Bool | DataValue.ofBool b => b | _ => false def DataValue.sameCtor : DataValue → DataValue → Bool | DataValue.ofString _, DataValue.ofString _ => true | DataValue.ofBool _, DataValue.ofBool _ => true | DataValue.ofName _, DataValue.ofName _ => true | DataValue.ofNat _, DataValue.ofNat _ => true | DataValue.ofInt _, DataValue.ofInt _ => true | _, _ => false @[export lean_data_value_to_string] def DataValue.str : DataValue → String | DataValue.ofString v => v | DataValue.ofBool v => toString v | DataValue.ofName v => toString v | DataValue.ofNat v => toString v | DataValue.ofInt v => toString v instance : ToString DataValue := ⟨DataValue.str⟩ instance : Coe String DataValue := ⟨DataValue.ofString⟩ instance : Coe Bool DataValue := ⟨DataValue.ofBool⟩ instance : Coe Name DataValue := ⟨DataValue.ofName⟩ instance : Coe Nat DataValue := ⟨DataValue.ofNat⟩ instance : Coe Int DataValue := ⟨DataValue.ofInt⟩ /- Remark: we do not use RBMap here because we need to manipulate KVMap objects in C++ and RBMap is implemented in Lean. So, we use just a List until we can generate C++ code from Lean code. -/ structure KVMap where entries : List (Name × DataValue) := [] deriving Inhabited namespace KVMap instance : ToString KVMap := ⟨fun m => toString m.entries⟩ def empty : KVMap := {} def isEmpty : KVMap → Bool | ⟨m⟩ => m.isEmpty def size (m : KVMap) : Nat := m.entries.length def findCore : List (Name × DataValue) → Name → Option DataValue | [], k' => none | (k,v)::m, k' => if k == k' then some v else findCore m k' def find : KVMap → Name → Option DataValue | ⟨m⟩, k => findCore m k def findD (m : KVMap) (k : Name) (d₀ : DataValue) : DataValue := (m.find k).getD d₀ def insertCore : List (Name × DataValue) → Name → DataValue → List (Name × DataValue) | [], k', v' => [(k',v')] | (k,v)::m, k', v' => if k == k' then (k, v') :: m else (k, v) :: insertCore m k' v' def insert : KVMap → Name → DataValue → KVMap | ⟨m⟩, k, v => ⟨insertCore m k v⟩ def contains (m : KVMap) (n : Name) : Bool := (m.find n).isSome def getString (m : KVMap) (k : Name) (defVal := "") : String := match m.find k with | some (DataValue.ofString v) => v | _ => defVal def getNat (m : KVMap) (k : Name) (defVal := 0) : Nat := match m.find k with | some (DataValue.ofNat v) => v | _ => defVal def getInt (m : KVMap) (k : Name) (defVal : Int := 0) : Int := match m.find k with | some (DataValue.ofInt v) => v | _ => defVal def getBool (m : KVMap) (k : Name) (defVal := false) : Bool := match m.find k with | some (DataValue.ofBool v) => v | _ => defVal def getName (m : KVMap) (k : Name) (defVal := Name.anonymous) : Name := match m.find k with | some (DataValue.ofName v) => v | _ => defVal def setString (m : KVMap) (k : Name) (v : String) : KVMap := m.insert k (DataValue.ofString v) def setNat (m : KVMap) (k : Name) (v : Nat) : KVMap := m.insert k (DataValue.ofNat v) def setInt (m : KVMap) (k : Name) (v : Int) : KVMap := m.insert k (DataValue.ofInt v) def setBool (m : KVMap) (k : Name) (v : Bool) : KVMap := m.insert k (DataValue.ofBool v) def setName (m : KVMap) (k : Name) (v : Name) : KVMap := m.insert k (DataValue.ofName v) @[inline] protected def forIn.{w, w'} {δ : Type w} {m : Type w → Type w'} [Monad m] (kv : KVMap) (init : δ) (f : Name × DataValue → δ → m (ForInStep δ)) : m δ := kv.entries.forIn init f instance : ForIn m KVMap (Name × DataValue) where forIn := KVMap.forIn def subsetAux : List (Name × DataValue) → KVMap → Bool | [], m₂ => true | (k, v₁)::m₁, m₂ => match m₂.find k with | some v₂ => v₁ == v₂ && subsetAux m₁ m₂ | none => false def subset : KVMap → KVMap → Bool | ⟨m₁⟩, m₂ => subsetAux m₁ m₂ def eqv (m₁ m₂ : KVMap) : Bool := subset m₁ m₂ && subset m₂ m₁ instance : BEq KVMap where beq := eqv class Value (α : Type) where toDataValue : α → DataValue ofDataValue? : DataValue → Option α @[inline] def get? {α : Type} [s : Value α] (m : KVMap) (k : Name) : Option α := m.find k |>.bind Value.ofDataValue? @[inline] def get {α : Type} [s : Value α] (m : KVMap) (k : Name) (defVal : α) : α := m.get? k |>.getD defVal @[inline] def set {α : Type} [s : Value α] (m : KVMap) (k : Name) (v : α) : KVMap := m.insert k (Value.toDataValue v) instance : Value Bool where toDataValue := DataValue.ofBool ofDataValue? | DataValue.ofBool b => some b | _ => none instance : Value Nat where toDataValue := DataValue.ofNat ofDataValue? | DataValue.ofNat n => some n | _ => none instance : Value Int where toDataValue := DataValue.ofInt ofDataValue? | DataValue.ofInt i => some i | _ => none instance : Value Name where toDataValue := DataValue.ofName ofDataValue? | DataValue.ofName n => some n | _ => none instance : Value String where toDataValue := DataValue.ofString ofDataValue? | DataValue.ofString n => some n | _ => none end Lean.KVMap
ee091364cb60e1310fa93b5b0cbc467d7e919bca
94e33a31faa76775069b071adea97e86e218a8ee
/src/data/multiset/basic.lean
7a67071d9e2d36275faf9089220937ffe55b717b
[ "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
94,494
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.bool.all_any import data.list.perm /-! # Multisets These are implemented as the quotient of a list by permutations. ## Notation We define the global infix notation `::ₘ` for `multiset.cons`. -/ open list subtype nat variables {α : Type*} {β : Type*} {γ : Type*} /-- `multiset α` is the quotient of `list α` by list permutation. The result is a type of finite sets with duplicates allowed. -/ def {u} multiset (α : Type u) : Type u := quotient (list.is_setoid α) namespace multiset instance : has_coe (list α) (multiset α) := ⟨quot.mk _⟩ @[simp] theorem quot_mk_to_coe (l : list α) : @eq (multiset α) ⟦l⟧ l := rfl @[simp] theorem quot_mk_to_coe' (l : list α) : @eq (multiset α) (quot.mk (≈) l) l := rfl @[simp] theorem quot_mk_to_coe'' (l : list α) : @eq (multiset α) (quot.mk setoid.r l) l := rfl @[simp] theorem coe_eq_coe {l₁ l₂ : list α} : (l₁ : multiset α) = l₂ ↔ l₁ ~ l₂ := quotient.eq instance has_decidable_eq [decidable_eq α] : decidable_eq (multiset α) | s₁ s₂ := quotient.rec_on_subsingleton₂ s₁ s₂ $ λ l₁ l₂, decidable_of_iff' _ quotient.eq /-- defines a size for a multiset by referring to the size of the underlying list -/ protected def sizeof [has_sizeof α] (s : multiset α) : ℕ := quot.lift_on s sizeof $ λ l₁ l₂, perm.sizeof_eq_sizeof instance has_sizeof [has_sizeof α] : has_sizeof (multiset α) := ⟨multiset.sizeof⟩ /-! ### Empty multiset -/ /-- `0 : multiset α` is the empty set -/ protected def zero : multiset α := @nil α instance : has_zero (multiset α) := ⟨multiset.zero⟩ instance : has_emptyc (multiset α) := ⟨0⟩ instance inhabited_multiset : inhabited (multiset α) := ⟨0⟩ @[simp] theorem coe_nil_eq_zero : (@nil α : multiset α) = 0 := rfl @[simp] theorem empty_eq_zero : (∅ : multiset α) = 0 := rfl @[simp] theorem coe_eq_zero (l : list α) : (l : multiset α) = 0 ↔ l = [] := iff.trans coe_eq_coe perm_nil /-! ### `multiset.cons` -/ /-- `cons a s` is the multiset which contains `s` plus one more instance of `a`. -/ def cons (a : α) (s : multiset α) : multiset α := quot.lift_on s (λ l, (a :: l : multiset α)) (λ l₁ l₂ p, quot.sound (p.cons a)) infixr ` ::ₘ `:67 := multiset.cons instance : has_insert α (multiset α) := ⟨cons⟩ @[simp] theorem insert_eq_cons (a : α) (s : multiset α) : insert a s = a ::ₘ s := rfl @[simp] theorem cons_coe (a : α) (l : list α) : (a ::ₘ l : multiset α) = (a::l : list α) := rfl theorem singleton_coe (a : α) : (a ::ₘ 0 : multiset α) = ([a] : list α) := rfl @[simp] theorem cons_inj_left {a b : α} (s : multiset α) : a ::ₘ s = b ::ₘ s ↔ a = b := ⟨quot.induction_on s $ λ l e, have [a] ++ l ~ [b] ++ l, from quotient.exact e, singleton_perm_singleton.1 $ (perm_append_right_iff _).1 this, congr_arg _⟩ @[simp] theorem cons_inj_right (a : α) : ∀{s t : multiset α}, a ::ₘ s = a ::ₘ t ↔ s = t := by rintros ⟨l₁⟩ ⟨l₂⟩; simp @[recursor 5] protected theorem induction {p : multiset α → Prop} (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a ::ₘ s)) : ∀s, p s := by rintros ⟨l⟩; induction l with _ _ ih; [exact h₁, exact h₂ ih] @[elab_as_eliminator] protected theorem induction_on {p : multiset α → Prop} (s : multiset α) (h₁ : p 0) (h₂ : ∀ ⦃a : α⦄ {s : multiset α}, p s → p (a ::ₘ s)) : p s := multiset.induction h₁ h₂ s theorem cons_swap (a b : α) (s : multiset α) : a ::ₘ b ::ₘ s = b ::ₘ a ::ₘ s := quot.induction_on s $ λ l, quotient.sound $ perm.swap _ _ _ section rec variables {C : multiset α → Sort*} /-- Dependent recursor on multisets. TODO: should be @[recursor 6], but then the definition of `multiset.pi` fails with a stack overflow in `whnf`. -/ protected def rec (C_0 : C 0) (C_cons : Πa m, C m → C (a ::ₘ m)) (C_cons_heq : ∀ a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)) (m : multiset α) : C m := quotient.hrec_on m (@list.rec α (λl, C ⟦l⟧) C_0 (λa l b, C_cons a ⟦l⟧ b)) $ assume l l' h, h.rec_heq (assume a l l' b b' hl, have ⟦l⟧ = ⟦l'⟧, from quot.sound hl, by cc) (assume a a' l, C_cons_heq a a' ⟦l⟧) /-- Companion to `multiset.rec` with more convenient argument order. -/ @[elab_as_eliminator] protected def rec_on (m : multiset α) (C_0 : C 0) (C_cons : Πa m, C m → C (a ::ₘ m)) (C_cons_heq : ∀a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)) : C m := multiset.rec C_0 C_cons C_cons_heq m variables {C_0 : C 0} {C_cons : Πa m, C m → C (a ::ₘ m)} {C_cons_heq : ∀a a' m b, C_cons a (a' ::ₘ m) (C_cons a' m b) == C_cons a' (a ::ₘ m) (C_cons a m b)} @[simp] lemma rec_on_0 : @multiset.rec_on α C (0:multiset α) C_0 C_cons C_cons_heq = C_0 := rfl @[simp] lemma rec_on_cons (a : α) (m : multiset α) : (a ::ₘ m).rec_on C_0 C_cons C_cons_heq = C_cons a m (m.rec_on C_0 C_cons C_cons_heq) := quotient.induction_on m $ assume l, rfl end rec section mem /-- `a ∈ s` means that `a` has nonzero multiplicity in `s`. -/ def mem (a : α) (s : multiset α) : Prop := quot.lift_on s (λ l, a ∈ l) (λ l₁ l₂ (e : l₁ ~ l₂), propext $ e.mem_iff) instance : has_mem α (multiset α) := ⟨mem⟩ @[simp] lemma mem_coe {a : α} {l : list α} : a ∈ (l : multiset α) ↔ a ∈ l := iff.rfl instance decidable_mem [decidable_eq α] (a : α) (s : multiset α) : decidable (a ∈ s) := quot.rec_on_subsingleton s $ list.decidable_mem a @[simp] theorem mem_cons {a b : α} {s : multiset α} : a ∈ b ::ₘ s ↔ a = b ∨ a ∈ s := quot.induction_on s $ λ l, iff.rfl lemma mem_cons_of_mem {a b : α} {s : multiset α} (h : a ∈ s) : a ∈ b ::ₘ s := mem_cons.2 $ or.inr h @[simp] theorem mem_cons_self (a : α) (s : multiset α) : a ∈ a ::ₘ s := mem_cons.2 (or.inl rfl) theorem forall_mem_cons {p : α → Prop} {a : α} {s : multiset α} : (∀ x ∈ (a ::ₘ s), p x) ↔ p a ∧ ∀ x ∈ s, p x := quotient.induction_on' s $ λ L, list.forall_mem_cons theorem exists_cons_of_mem {s : multiset α} {a : α} : a ∈ s → ∃ t, s = a ::ₘ t := quot.induction_on s $ λ l (h : a ∈ l), let ⟨l₁, l₂, e⟩ := mem_split h in e.symm ▸ ⟨(l₁++l₂ : list α), quot.sound perm_middle⟩ @[simp] theorem not_mem_zero (a : α) : a ∉ (0 : multiset α) := id theorem eq_zero_of_forall_not_mem {s : multiset α} : (∀x, x ∉ s) → s = 0 := quot.induction_on s $ λ l H, by rw eq_nil_iff_forall_not_mem.mpr H; refl theorem eq_zero_iff_forall_not_mem {s : multiset α} : s = 0 ↔ ∀ a, a ∉ s := ⟨λ h, h.symm ▸ λ _, not_false, eq_zero_of_forall_not_mem⟩ theorem exists_mem_of_ne_zero {s : multiset α} : s ≠ 0 → ∃ a : α, a ∈ s := quot.induction_on s $ assume l hl, match l, hl with | [] := assume h, false.elim $ h rfl | (a :: l) := assume _, ⟨a, by simp⟩ end lemma empty_or_exists_mem (s : multiset α) : s = 0 ∨ ∃ a, a ∈ s := or_iff_not_imp_left.mpr multiset.exists_mem_of_ne_zero @[simp] lemma zero_ne_cons {a : α} {m : multiset α} : 0 ≠ a ::ₘ m := assume h, have a ∈ (0:multiset α), from h.symm ▸ mem_cons_self _ _, not_mem_zero _ this @[simp] lemma cons_ne_zero {a : α} {m : multiset α} : a ::ₘ m ≠ 0 := zero_ne_cons.symm lemma cons_eq_cons {a b : α} {as bs : multiset α} : a ::ₘ as = b ::ₘ bs ↔ ((a = b ∧ as = bs) ∨ (a ≠ b ∧ ∃cs, as = b ::ₘ cs ∧ bs = a ::ₘ cs)) := begin haveI : decidable_eq α := classical.dec_eq α, split, { assume eq, by_cases a = b, { subst h, simp * at * }, { have : a ∈ b ::ₘ bs, from eq ▸ mem_cons_self _ _, have : a ∈ bs, by simpa [h], rcases exists_cons_of_mem this with ⟨cs, hcs⟩, simp [h, hcs], have : a ::ₘ as = b ::ₘ a ::ₘ cs, by simp [eq, hcs], have : a ::ₘ as = a ::ₘ b ::ₘ cs, by rwa [cons_swap], simpa using this } }, { assume h, rcases h with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { simp * }, { simp [*, cons_swap a b] } } end end mem /-! ### `multiset.subset` -/ section subset /-- `s ⊆ t` is the lift of the list subset relation. It means that any element with nonzero multiplicity in `s` has nonzero multiplicity in `t`, but it does not imply that the multiplicity of `a` in `s` is less or equal than in `t`; see `s ≤ t` for this relation. -/ protected def subset (s t : multiset α) : Prop := ∀ ⦃a : α⦄, a ∈ s → a ∈ t instance : has_subset (multiset α) := ⟨multiset.subset⟩ instance : has_ssubset (multiset α) := ⟨λ s t, s ⊆ t ∧ ¬ t ⊆ s⟩ @[simp] theorem coe_subset {l₁ l₂ : list α} : (l₁ : multiset α) ⊆ l₂ ↔ l₁ ⊆ l₂ := iff.rfl @[simp] theorem subset.refl (s : multiset α) : s ⊆ s := λ a h, h theorem subset.trans {s t u : multiset α} : s ⊆ t → t ⊆ u → s ⊆ u := λ h₁ h₂ a m, h₂ (h₁ m) theorem subset_iff {s t : multiset α} : s ⊆ t ↔ (∀⦃x⦄, x ∈ s → x ∈ t) := iff.rfl theorem mem_of_subset {s t : multiset α} {a : α} (h : s ⊆ t) : a ∈ s → a ∈ t := @h _ @[simp] theorem zero_subset (s : multiset α) : 0 ⊆ s := λ a, (not_mem_nil a).elim lemma subset_cons (s : multiset α) (a : α) : s ⊆ a ::ₘ s := λ _, mem_cons_of_mem lemma ssubset_cons {s : multiset α} {a : α} (ha : a ∉ s) : s ⊂ a ::ₘ s := ⟨subset_cons _ _, λ h, ha $ h $ mem_cons_self _ _⟩ @[simp] theorem cons_subset {a : α} {s t : multiset α} : (a ::ₘ s) ⊆ t ↔ a ∈ t ∧ s ⊆ t := by simp [subset_iff, or_imp_distrib, forall_and_distrib] lemma cons_subset_cons {a : α} {s t : multiset α} : s ⊆ t → a ::ₘ s ⊆ a ::ₘ t := quotient.induction_on₂ s t $ λ _ _, cons_subset_cons _ theorem eq_zero_of_subset_zero {s : multiset α} (h : s ⊆ 0) : s = 0 := eq_zero_of_forall_not_mem h theorem subset_zero {s : multiset α} : s ⊆ 0 ↔ s = 0 := ⟨eq_zero_of_subset_zero, λ xeq, xeq.symm ▸ subset.refl 0⟩ lemma induction_on' {p : multiset α → Prop} (S : multiset α) (h₁ : p 0) (h₂ : ∀ {a s}, a ∈ S → s ⊆ S → p s → p (insert a s)) : p S := @multiset.induction_on α (λ T, T ⊆ S → p T) S (λ _, h₁) (λ a s hps hs, let ⟨hS, sS⟩ := cons_subset.1 hs in h₂ hS sS (hps sS)) (subset.refl S) end subset section to_list /-- Produces a list of the elements in the multiset using choice. -/ @[reducible] noncomputable def to_list {α : Type*} (s : multiset α) := classical.some (quotient.exists_rep s) @[simp] lemma to_list_zero {α : Type*} : (multiset.to_list 0 : list α) = [] := (multiset.coe_eq_zero _).1 (classical.some_spec (quotient.exists_rep multiset.zero)) @[simp, norm_cast] lemma coe_to_list {α : Type*} (s : multiset α) : (s.to_list : multiset α) = s := classical.some_spec (quotient.exists_rep _) @[simp] lemma mem_to_list {α : Type*} (a : α) (s : multiset α) : a ∈ s.to_list ↔ a ∈ s := by rw [←multiset.mem_coe, multiset.coe_to_list] end to_list /-! ### Partial order on `multiset`s -/ /-- `s ≤ t` means that `s` is a sublist of `t` (up to permutation). Equivalently, `s ≤ t` means that `count a s ≤ count a t` for all `a`. -/ protected def le (s t : multiset α) : Prop := quotient.lift_on₂ s t (<+~) $ λ v₁ v₂ w₁ w₂ p₁ p₂, propext (p₂.subperm_left.trans p₁.subperm_right) instance : partial_order (multiset α) := { le := multiset.le, le_refl := by rintros ⟨l⟩; exact subperm.refl _, le_trans := by rintros ⟨l₁⟩ ⟨l₂⟩ ⟨l₃⟩; exact @subperm.trans _ _ _ _, le_antisymm := by rintros ⟨l₁⟩ ⟨l₂⟩ h₁ h₂; exact quot.sound (subperm.antisymm h₁ h₂) } section variables {s t : multiset α} {a : α} lemma subset_of_le : s ≤ t → s ⊆ t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm.subset alias subset_of_le ← le.subset lemma mem_of_le (h : s ≤ t) : a ∈ s → a ∈ t := mem_of_subset (subset_of_le h) lemma not_mem_mono (h : s ⊆ t) : a ∉ t → a ∉ s := mt $ @h _ @[simp] theorem coe_le {l₁ l₂ : list α} : (l₁ : multiset α) ≤ l₂ ↔ l₁ <+~ l₂ := iff.rfl @[elab_as_eliminator] theorem le_induction_on {C : multiset α → multiset α → Prop} {s t : multiset α} (h : s ≤ t) (H : ∀ {l₁ l₂ : list α}, l₁ <+ l₂ → C l₁ l₂) : C s t := quotient.induction_on₂ s t (λ l₁ l₂ ⟨l, p, s⟩, (show ⟦l⟧ = ⟦l₁⟧, from quot.sound p) ▸ H s) h theorem zero_le (s : multiset α) : 0 ≤ s := quot.induction_on s $ λ l, (nil_sublist l).subperm lemma le_zero : s ≤ 0 ↔ s = 0 := ⟨λ h, le_antisymm h (zero_le _), le_of_eq⟩ theorem lt_cons_self (s : multiset α) (a : α) : s < a ::ₘ s := quot.induction_on s $ λ l, suffices l <+~ a :: l ∧ (¬l ~ a :: l), by simpa [lt_iff_le_and_ne], ⟨(sublist_cons _ _).subperm, λ p, ne_of_lt (lt_succ_self (length l)) p.length_eq⟩ theorem le_cons_self (s : multiset α) (a : α) : s ≤ a ::ₘ s := le_of_lt $ lt_cons_self _ _ lemma cons_le_cons_iff (a : α) : a ::ₘ s ≤ a ::ₘ t ↔ s ≤ t := quotient.induction_on₂ s t $ λ l₁ l₂, subperm_cons a lemma cons_le_cons (a : α) : s ≤ t → a ::ₘ s ≤ a ::ₘ t := (cons_le_cons_iff a).2 lemma le_cons_of_not_mem (m : a ∉ s) : s ≤ a ::ₘ t ↔ s ≤ t := begin refine ⟨_, λ h, le_trans h $ le_cons_self _ _⟩, suffices : ∀ {t'} (_ : s ≤ t') (_ : a ∈ t'), a ::ₘ s ≤ t', { exact λ h, (cons_le_cons_iff a).1 (this h (mem_cons_self _ _)) }, introv h, revert m, refine le_induction_on h _, introv s m₁ m₂, rcases mem_split m₂ with ⟨r₁, r₂, rfl⟩, exact perm_middle.subperm_left.2 ((subperm_cons _).2 $ ((sublist_or_mem_of_sublist s).resolve_right m₁).subperm) end end /-! ### Singleton -/ instance : has_singleton α (multiset α) := ⟨λ a, a ::ₘ 0⟩ instance : is_lawful_singleton α (multiset α) := ⟨λ a, rfl⟩ theorem singleton_eq_cons (a : α) : singleton a = a ::ₘ 0 := rfl @[simp] theorem mem_singleton {a b : α} : b ∈ ({a} : multiset α) ↔ b = a := by simp only [singleton_eq_cons, mem_cons, iff_self, or_false, not_mem_zero] theorem mem_singleton_self (a : α) : a ∈ ({a} : multiset α) := by { rw singleton_eq_cons, exact mem_cons_self _ _ } theorem singleton_inj {a b : α} : ({a} : multiset α) = {b} ↔ a = b := by { simp_rw [singleton_eq_cons], exact cons_inj_left _ } @[simp] theorem singleton_ne_zero (a : α) : ({a} : multiset α) ≠ 0 := ne_of_gt (lt_cons_self _ _) @[simp] theorem singleton_le {a : α} {s : multiset α} : {a} ≤ s ↔ a ∈ s := ⟨λ h, mem_of_le h (mem_singleton_self _), λ h, let ⟨t, e⟩ := exists_cons_of_mem h in e.symm ▸ cons_le_cons _ (zero_le _)⟩ theorem pair_comm (x y : α) : ({x, y} : multiset α) = {y, x} := cons_swap x y 0 /-! ### Additive monoid -/ /-- The sum of two multisets is the lift of the list append operation. This adds the multiplicities of each element, i.e. `count a (s + t) = count a s + count a t`. -/ protected def add (s₁ s₂ : multiset α) : multiset α := quotient.lift_on₂ s₁ s₂ (λ l₁ l₂, ((l₁ ++ l₂ : list α) : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.append p₂ instance : has_add (multiset α) := ⟨multiset.add⟩ @[simp] theorem coe_add (s t : list α) : (s + t : multiset α) = (s ++ t : list α) := rfl theorem singleton_add (a : α) (s : multiset α) : {a} + s = a ::ₘ s := rfl private theorem add_le_add_iff_left' {s t u : multiset α} : s + t ≤ s + u ↔ t ≤ u := quotient.induction_on₃ s t u $ λ l₁ l₂ l₃, subperm_append_left _ instance : covariant_class (multiset α) (multiset α) (+) (≤) := ⟨λ s t u, add_le_add_iff_left'.2⟩ instance : contravariant_class (multiset α) (multiset α) (+) (≤) := ⟨λ s t u, add_le_add_iff_left'.1⟩ instance : ordered_cancel_add_comm_monoid (multiset α) := { zero := 0, add := (+), add_comm := λ s t, quotient.induction_on₂ s t $ λ l₁ l₂, quot.sound perm_append_comm, add_assoc := λ s₁ s₂ s₃, quotient.induction_on₃ s₁ s₂ s₃ $ λ l₁ l₂ l₃, congr_arg coe $ append_assoc l₁ l₂ l₃, zero_add := λ s, quot.induction_on s $ λ l, rfl, add_zero := λ s, quotient.induction_on s $ λ l, congr_arg coe $ append_nil l, add_left_cancel := λ a b c, add_left_cancel'', add_le_add_left := λ s₁ s₂, add_le_add_left, le_of_add_le_add_left := λ s₁ s₂ s₃, le_of_add_le_add_left, ..@multiset.partial_order α } theorem le_add_right (s t : multiset α) : s ≤ s + t := by simpa using add_le_add_left (zero_le t) s theorem le_add_left (s t : multiset α) : s ≤ t + s := by simpa using add_le_add_right (zero_le t) s theorem le_iff_exists_add {s t : multiset α} : s ≤ t ↔ ∃ u, t = s + u := ⟨λ h, le_induction_on h $ λ l₁ l₂ s, let ⟨l, p⟩ := s.exists_perm_append in ⟨l, quot.sound p⟩, λ ⟨u, e⟩, e.symm ▸ le_add_right _ _⟩ instance : order_bot (multiset α) := { bot := 0, bot_le := multiset.zero_le } instance : canonically_ordered_add_monoid (multiset α) := { le_self_add := le_add_right, exists_add_of_le := λ a b h, le_induction_on h $ λ l₁ l₂ s, let ⟨l, p⟩ := s.exists_perm_append in ⟨l, quot.sound p⟩, ..multiset.order_bot, ..multiset.ordered_cancel_add_comm_monoid } /-- This is a `rfl` and `simp` version of `bot_eq_zero`. -/ @[simp] theorem bot_eq_zero : (⊥ : multiset α) = 0 := rfl @[simp] theorem cons_add (a : α) (s t : multiset α) : a ::ₘ s + t = a ::ₘ (s + t) := by rw [← singleton_add, ← singleton_add, add_assoc] @[simp] theorem add_cons (a : α) (s t : multiset α) : s + a ::ₘ t = a ::ₘ (s + t) := by rw [add_comm, cons_add, add_comm] @[simp] theorem mem_add {a : α} {s t : multiset α} : a ∈ s + t ↔ a ∈ s ∨ a ∈ t := quotient.induction_on₂ s t $ λ l₁ l₂, mem_append lemma mem_of_mem_nsmul {a : α} {s : multiset α} {n : ℕ} (h : a ∈ n • s) : a ∈ s := begin induction n with n ih, { rw zero_nsmul at h, exact absurd h (not_mem_zero _) }, { rw [succ_nsmul, mem_add] at h, exact h.elim id ih }, end @[simp] lemma mem_nsmul {a : α} {s : multiset α} {n : ℕ} (h0 : n ≠ 0) : a ∈ n • s ↔ a ∈ s := begin refine ⟨mem_of_mem_nsmul, λ h, _⟩, obtain ⟨n, rfl⟩ := exists_eq_succ_of_ne_zero h0, rw [succ_nsmul, mem_add], exact or.inl h end lemma nsmul_cons {s : multiset α} (n : ℕ) (a : α) : n • (a ::ₘ s) = n • {a} + n • s := by rw [←singleton_add, nsmul_add] /-! ### Cardinality -/ /-- The cardinality of a multiset is the sum of the multiplicities of all its elements, or simply the length of the underlying list. -/ def card : multiset α →+ ℕ := { to_fun := λ s, quot.lift_on s length $ λ l₁ l₂, perm.length_eq, map_zero' := rfl, map_add' := λ s t, quotient.induction_on₂ s t length_append } @[simp] theorem coe_card (l : list α) : card (l : multiset α) = length l := rfl @[simp] theorem card_zero : @card α 0 = 0 := rfl theorem card_add (s t : multiset α) : card (s + t) = card s + card t := card.map_add s t lemma card_nsmul (s : multiset α) (n : ℕ) : (n • s).card = n * s.card := by rw [card.map_nsmul s n, nat.nsmul_eq_mul] @[simp] theorem card_cons (a : α) (s : multiset α) : card (a ::ₘ s) = card s + 1 := quot.induction_on s $ λ l, rfl @[simp] theorem card_singleton (a : α) : card ({a} : multiset α) = 1 := by simp only [singleton_eq_cons, card_zero, eq_self_iff_true, zero_add, card_cons] lemma card_pair (a b : α) : ({a, b} : multiset α).card = 2 := by rw [insert_eq_cons, card_cons, card_singleton] theorem card_eq_one {s : multiset α} : card s = 1 ↔ ∃ a, s = {a} := ⟨quot.induction_on s $ λ l h, (list.length_eq_one.1 h).imp $ λ a, congr_arg coe, λ ⟨a, e⟩, e.symm ▸ rfl⟩ theorem card_le_of_le {s t : multiset α} (h : s ≤ t) : card s ≤ card t := le_induction_on h $ λ l₁ l₂, length_le_of_sublist @[mono] theorem card_mono : monotone (@card α) := λ a b, card_le_of_le theorem eq_of_le_of_card_le {s t : multiset α} (h : s ≤ t) : card t ≤ card s → s = t := le_induction_on h $ λ l₁ l₂ s h₂, congr_arg coe $ eq_of_sublist_of_length_le s h₂ theorem card_lt_of_lt {s t : multiset α} (h : s < t) : card s < card t := lt_of_not_ge $ λ h₂, ne_of_lt h $ eq_of_le_of_card_le (le_of_lt h) h₂ theorem lt_iff_cons_le {s t : multiset α} : s < t ↔ ∃ a, a ::ₘ s ≤ t := ⟨quotient.induction_on₂ s t $ λ l₁ l₂ h, subperm.exists_of_length_lt (le_of_lt h) (card_lt_of_lt h), λ ⟨a, h⟩, lt_of_lt_of_le (lt_cons_self _ _) h⟩ @[simp] theorem card_eq_zero {s : multiset α} : card s = 0 ↔ s = 0 := ⟨λ h, (eq_of_le_of_card_le (zero_le _) (le_of_eq h)).symm, λ e, by simp [e]⟩ theorem card_pos {s : multiset α} : 0 < card s ↔ s ≠ 0 := pos_iff_ne_zero.trans $ not_congr card_eq_zero theorem card_pos_iff_exists_mem {s : multiset α} : 0 < card s ↔ ∃ a, a ∈ s := quot.induction_on s $ λ l, length_pos_iff_exists_mem lemma card_eq_two {s : multiset α} : s.card = 2 ↔ ∃ x y, s = {x, y} := ⟨quot.induction_on s (λ l h, (list.length_eq_two.mp h).imp (λ a, Exists.imp (λ b, congr_arg coe))), λ ⟨a, b, e⟩, e.symm ▸ rfl⟩ lemma card_eq_three {s : multiset α} : s.card = 3 ↔ ∃ x y z, s = {x, y, z} := ⟨quot.induction_on s (λ l h, (list.length_eq_three.mp h).imp (λ a, Exists.imp (λ b, Exists.imp (λ c, congr_arg coe)))), λ ⟨a, b, c, e⟩, e.symm ▸ rfl⟩ /-! ### Induction principles -/ /-- A strong induction principle for multisets: If you construct a value for a particular multiset given values for all strictly smaller multisets, you can construct a value for any multiset. -/ @[elab_as_eliminator] def strong_induction_on {p : multiset α → Sort*} : ∀ (s : multiset α), (∀ s, (∀t < s, p t) → p s) → p s | s := λ ih, ih s $ λ t h, have card t < card s, from card_lt_of_lt h, strong_induction_on t ih using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf card⟩]} theorem strong_induction_eq {p : multiset α → Sort*} (s : multiset α) (H) : @strong_induction_on _ p s H = H s (λ t h, @strong_induction_on _ p t H) := by rw [strong_induction_on] @[elab_as_eliminator] lemma case_strong_induction_on {p : multiset α → Prop} (s : multiset α) (h₀ : p 0) (h₁ : ∀ a s, (∀t ≤ s, p t) → p (a ::ₘ s)) : p s := multiset.strong_induction_on s $ assume s, multiset.induction_on s (λ _, h₀) $ λ a s _ ih, h₁ _ _ $ λ t h, ih _ $ lt_of_le_of_lt h $ lt_cons_self _ _ /-- 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 multisets `s` of cardinality less than `n`, starting from multisets of card `n` and iterating. This can be used either to define data, or to prove properties. -/ def strong_downward_induction {p : multiset α → Sort*} {n : ℕ} (H : ∀ t₁, (∀ {t₂ : multiset α}, t₂.card ≤ n → t₁ < t₂ → p t₂) → t₁.card ≤ n → p t₁) : ∀ (s : multiset α), s.card ≤ n → p s | s := H s (λ t ht h, have n - card t < n - card s, from (tsub_lt_tsub_iff_left_of_le ht).2 (card_lt_of_lt h), strong_downward_induction t ht) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, measure_wf (λ (t : multiset α), n - t.card)⟩]} lemma strong_downward_induction_eq {p : multiset α → Sort*} {n : ℕ} (H : ∀ t₁, (∀ {t₂ : multiset α}, t₂.card ≤ n → t₁ < t₂ → p t₂) → t₁.card ≤ n → p t₁) (s : multiset α) : 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 : multiset α → Sort*} {n : ℕ} : ∀ (s : multiset α), (∀ t₁, (∀ {t₂ : multiset α}, 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 : multiset α → Sort*} (s : multiset α) {n : ℕ} (H : ∀ t₁, (∀ {t₂ : multiset α}, 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 } /-- Another way of expressing `strong_induction_on`: the `(<)` relation is well-founded. -/ lemma well_founded_lt : well_founded ((<) : multiset α → multiset α → Prop) := subrelation.wf (λ _ _, multiset.card_lt_of_lt) (measure_wf multiset.card) /-! ### `multiset.repeat` -/ /-- `repeat a n` is the multiset containing only `a` with multiplicity `n`. -/ def repeat (a : α) (n : ℕ) : multiset α := repeat a n @[simp] lemma repeat_zero (a : α) : repeat a 0 = 0 := rfl @[simp] lemma repeat_succ (a : α) (n) : repeat a (n+1) = a ::ₘ repeat a n := by simp [repeat] @[simp] lemma repeat_one (a : α) : repeat a 1 = {a} := by simp only [repeat_succ, singleton_eq_cons, eq_self_iff_true, repeat_zero, cons_inj_right] @[simp] lemma card_repeat : ∀ (a : α) n, card (repeat a n) = n := length_repeat lemma mem_repeat {a b : α} {n : ℕ} : b ∈ repeat a n ↔ n ≠ 0 ∧ b = a := mem_repeat theorem eq_of_mem_repeat {a b : α} {n} : b ∈ repeat a n → b = a := eq_of_mem_repeat theorem eq_repeat' {a : α} {s : multiset α} : s = repeat a s.card ↔ ∀ b ∈ s, b = a := quot.induction_on s $ λ l, iff.trans ⟨λ h, (perm_repeat.1 $ (quotient.exact h)), congr_arg coe⟩ eq_repeat' theorem eq_repeat_of_mem {a : α} {s : multiset α} : (∀ b ∈ s, b = a) → s = repeat a s.card := eq_repeat'.2 theorem eq_repeat {a : α} {n} {s : multiset α} : s = repeat a n ↔ card s = n ∧ ∀ b ∈ s, b = a := ⟨λ h, h.symm ▸ ⟨card_repeat _ _, λ b, eq_of_mem_repeat⟩, λ ⟨e, al⟩, e ▸ eq_repeat_of_mem al⟩ lemma repeat_left_injective {n : ℕ} (hn : n ≠ 0) : function.injective (λ a : α, repeat a n) := λ a b h, (eq_repeat.1 h).2 _ $ mem_repeat.2 ⟨hn, rfl⟩ @[simp] lemma repeat_left_inj {a b : α} {n : ℕ} (h : n ≠ 0) : repeat a n = repeat b n ↔ a = b := (repeat_left_injective h).eq_iff theorem repeat_injective (a : α) : function.injective (repeat a) := λ m n h, by rw [← (eq_repeat.1 h).1, card_repeat] theorem repeat_subset_singleton : ∀ (a : α) n, repeat a n ⊆ {a} := repeat_subset_singleton theorem repeat_le_coe {a : α} {n} {l : list α} : repeat a n ≤ l ↔ list.repeat a n <+ l := ⟨λ ⟨l', p, s⟩, (perm_repeat.1 p) ▸ s, sublist.subperm⟩ theorem nsmul_singleton (a : α) (n) : n • ({a} : multiset α) = repeat a n := begin refine eq_repeat.mpr ⟨_, λ b hb, mem_singleton.mp (mem_of_mem_nsmul hb)⟩, rw [card_nsmul, card_singleton, mul_one] end lemma nsmul_repeat {a : α} (n m : ℕ) : n • (repeat a m) = repeat a (n * m) := begin rw eq_repeat, split, { rw [card_nsmul, card_repeat] }, { exact λ b hb, eq_of_mem_repeat (mem_of_mem_nsmul hb) }, end /-! ### Erasing one copy of an element -/ section erase variables [decidable_eq α] {s t : multiset α} {a b : α} /-- `erase s a` is the multiset that subtracts 1 from the multiplicity of `a`. -/ def erase (s : multiset α) (a : α) : multiset α := quot.lift_on s (λ l, (l.erase a : multiset α)) (λ l₁ l₂ p, quot.sound (p.erase a)) @[simp] theorem coe_erase (l : list α) (a : α) : erase (l : multiset α) a = l.erase a := rfl @[simp] theorem erase_zero (a : α) : (0 : multiset α).erase a = 0 := rfl @[simp] theorem erase_cons_head (a : α) (s : multiset α) : (a ::ₘ s).erase a = s := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_head a l @[simp, priority 990] theorem erase_cons_tail {a b : α} (s : multiset α) (h : b ≠ a) : (b ::ₘ s).erase a = b ::ₘ s.erase a := quot.induction_on s $ λ l, congr_arg coe $ erase_cons_tail l h @[simp] theorem erase_singleton (a : α) : ({a} : multiset α).erase a = 0 := erase_cons_head a 0 @[simp, priority 980] theorem erase_of_not_mem {a : α} {s : multiset α} : a ∉ s → s.erase a = s := quot.induction_on s $ λ l h, congr_arg coe $ erase_of_not_mem h @[simp, priority 980] theorem cons_erase {s : multiset α} {a : α} : a ∈ s → a ::ₘ s.erase a = s := quot.induction_on s $ λ l h, quot.sound (perm_cons_erase h).symm theorem le_cons_erase (s : multiset α) (a : α) : s ≤ a ::ₘ s.erase a := if h : a ∈ s then le_of_eq (cons_erase h).symm else by rw erase_of_not_mem h; apply le_cons_self lemma add_singleton_eq_iff {s t : multiset α} {a : α} : s + {a} = t ↔ a ∈ t ∧ s = t.erase a := begin rw [add_comm, singleton_add], split, { rintro rfl, exact ⟨s.mem_cons_self a, (s.erase_cons_head a).symm⟩ }, { rintro ⟨h, rfl⟩, exact cons_erase h }, end theorem erase_add_left_pos {a : α} {s : multiset α} (t) : a ∈ s → (s + t).erase a = s.erase a + t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_left l₂ h theorem erase_add_right_pos {a : α} (s) {t : multiset α} (h : a ∈ t) : (s + t).erase a = s + t.erase a := by rw [add_comm, erase_add_left_pos s h, add_comm] theorem erase_add_right_neg {a : α} {s : multiset α} (t) : a ∉ s → (s + t).erase a = s + t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ erase_append_right l₂ h theorem erase_add_left_neg {a : α} (s) {t : multiset α} (h : a ∉ t) : (s + t).erase a = s.erase a + t := by rw [add_comm, erase_add_right_neg s h, add_comm] theorem erase_le (a : α) (s : multiset α) : s.erase a ≤ s := quot.induction_on s $ λ l, (erase_sublist a l).subperm @[simp] theorem erase_lt {a : α} {s : multiset α} : s.erase a < s ↔ a ∈ s := ⟨λ h, not_imp_comm.1 erase_of_not_mem (ne_of_lt h), λ h, by simpa [h] using lt_cons_self (s.erase a) a⟩ theorem erase_subset (a : α) (s : multiset α) : s.erase a ⊆ s := subset_of_le (erase_le a s) theorem mem_erase_of_ne {a b : α} {s : multiset α} (ab : a ≠ b) : a ∈ s.erase b ↔ a ∈ s := quot.induction_on s $ λ l, list.mem_erase_of_ne ab theorem mem_of_mem_erase {a b : α} {s : multiset α} : a ∈ s.erase b → a ∈ s := mem_of_subset (erase_subset _ _) theorem erase_comm (s : multiset α) (a b : α) : (s.erase a).erase b = (s.erase b).erase a := quot.induction_on s $ λ l, congr_arg coe $ l.erase_comm a b theorem erase_le_erase {s t : multiset α} (a : α) (h : s ≤ t) : s.erase a ≤ t.erase a := le_induction_on h $ λ l₁ l₂ h, (h.erase _).subperm theorem erase_le_iff_le_cons {s t : multiset α} {a : α} : s.erase a ≤ t ↔ s ≤ a ::ₘ t := ⟨λ h, le_trans (le_cons_erase _ _) (cons_le_cons _ h), λ h, if m : a ∈ s then by rw ← cons_erase m at h; exact (cons_le_cons_iff _).1 h else le_trans (erase_le _ _) ((le_cons_of_not_mem m).1 h)⟩ @[simp] theorem card_erase_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) = pred (card s) := quot.induction_on s $ λ l, length_erase_of_mem @[simp] lemma card_erase_add_one {a : α} {s : multiset α} : a ∈ s → (s.erase a).card + 1 = s.card := quot.induction_on s $ λ l, length_erase_add_one theorem card_erase_lt_of_mem {a : α} {s : multiset α} : a ∈ s → card (s.erase a) < card s := λ h, card_lt_of_lt (erase_lt.mpr h) theorem card_erase_le {a : α} {s : multiset α} : card (s.erase a) ≤ card s := card_le_of_le (erase_le a s) theorem card_erase_eq_ite {a : α} {s : multiset α} : card (s.erase a) = if a ∈ s then pred (card s) else card s := begin by_cases h : a ∈ s, { rwa [card_erase_of_mem h, if_pos] }, { rwa [erase_of_not_mem h, if_neg] } end end erase @[simp] theorem coe_reverse (l : list α) : (reverse l : multiset α) = l := quot.sound $ reverse_perm _ /-! ### `multiset.map` -/ /-- `map f s` is the lift of the list `map` operation. The multiplicity of `b` in `map f s` is the number of `a ∈ s` (counting multiplicity) such that `f a = b`. -/ def map (f : α → β) (s : multiset α) : multiset β := quot.lift_on s (λ l : list α, (l.map f : multiset β)) (λ l₁ l₂ p, quot.sound (p.map f)) @[congr] theorem map_congr {f g : α → β} {s t : multiset α} : s = t → (∀ x ∈ t, f x = g x) → map f s = map g t := begin rintros rfl h, induction s using quot.induction_on, exact congr_arg coe (map_congr h) end lemma map_hcongr {β' : Type*} {m : multiset α} {f : α → β} {f' : α → β'} (h : β = β') (hf : ∀a∈m, f a == f' a) : map f m == map f' m := begin subst h, simp at hf, simp [map_congr rfl hf] end theorem forall_mem_map_iff {f : α → β} {p : β → Prop} {s : multiset α} : (∀ y ∈ s.map f, p y) ↔ (∀ x ∈ s, p (f x)) := quotient.induction_on' s $ λ L, list.forall_mem_map_iff @[simp] theorem coe_map (f : α → β) (l : list α) : map f ↑l = l.map f := rfl @[simp] theorem map_zero (f : α → β) : map f 0 = 0 := rfl @[simp] theorem map_cons (f : α → β) (a s) : map f (a ::ₘ s) = f a ::ₘ map f s := quot.induction_on s $ λ l, rfl theorem map_comp_cons (f : α → β) (t) : map f ∘ cons t = cons (f t) ∘ map f := by { ext, simp } @[simp] theorem map_singleton (f : α → β) (a : α) : ({a} : multiset α).map f = {f a} := rfl theorem map_repeat (f : α → β) (a : α) (k : ℕ) : (repeat a k).map f = repeat (f a) k := by { induction k, simp, simpa } @[simp] theorem map_add (f : α → β) (s t) : map f (s + t) = map f s + map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ map_append _ _ _ /-- If each element of `s : multiset α` can be lifted to `β`, then `s` can be lifted to `multiset β`. -/ instance [can_lift α β] : can_lift (multiset α) (multiset β) := { cond := λ s, ∀ x ∈ s, can_lift.cond β x, coe := map can_lift.coe, prf := by { rintro ⟨l⟩ hl, lift l to list β using hl, exact ⟨l, coe_map _ _⟩ } } /-- `multiset.map` as an `add_monoid_hom`. -/ def map_add_monoid_hom (f : α → β) : multiset α →+ multiset β := { to_fun := map f, map_zero' := map_zero _, map_add' := map_add _ } @[simp] lemma coe_map_add_monoid_hom (f : α → β) : (map_add_monoid_hom f : multiset α → multiset β) = map f := rfl theorem map_nsmul (f : α → β) (n : ℕ) (s) : map f (n • s) = n • (map f s) := (map_add_monoid_hom f).map_nsmul _ _ @[simp] theorem mem_map {f : α → β} {b : β} {s : multiset α} : b ∈ map f s ↔ ∃ a, a ∈ s ∧ f a = b := quot.induction_on s $ λ l, mem_map @[simp] theorem card_map (f : α → β) (s) : card (map f s) = card s := quot.induction_on s $ λ l, length_map _ _ @[simp] theorem map_eq_zero {s : multiset α} {f : α → β} : s.map f = 0 ↔ s = 0 := by rw [← multiset.card_eq_zero, multiset.card_map, multiset.card_eq_zero] theorem mem_map_of_mem (f : α → β) {a : α} {s : multiset α} (h : a ∈ s) : f a ∈ map f s := mem_map.2 ⟨_, h, rfl⟩ lemma map_eq_singleton {f : α → β} {s : multiset α} {b : β} : map f s = {b} ↔ ∃ a : α, s = {a} ∧ f a = b := begin split, { intro h, obtain ⟨a, ha⟩ : ∃ a, s = {a}, { rw [←card_eq_one, ←card_map, h, card_singleton] }, refine ⟨a, ha, _⟩, rw [←mem_singleton, ←h, ha, map_singleton, mem_singleton] }, { rintro ⟨a, rfl, rfl⟩, simp } end lemma map_eq_cons [decidable_eq α] (f : α → β) (s : multiset α) (t : multiset β) (b : β) : (∃ a ∈ s, f a = b ∧ (s.erase a).map f = t) ↔ s.map f = b ::ₘ t := begin split, { rintro ⟨a, ha, rfl, rfl⟩, rw [←map_cons, multiset.cons_erase ha] }, { intro h, have : b ∈ s.map f, { rw h, exact mem_cons_self _ _ }, obtain ⟨a, h1, rfl⟩ := mem_map.mp this, obtain ⟨u, rfl⟩ := exists_cons_of_mem h1, rw [map_cons, cons_inj_right] at h, refine ⟨a, mem_cons_self _ _, rfl, _⟩, rw [multiset.erase_cons_head, h] } end theorem mem_map_of_injective {f : α → β} (H : function.injective f) {a : α} {s : multiset α} : f a ∈ map f s ↔ a ∈ s := quot.induction_on s $ λ l, mem_map_of_injective H @[simp] theorem map_map (g : β → γ) (f : α → β) (s : multiset α) : map g (map f s) = map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ list.map_map _ _ _ theorem map_id (s : multiset α) : map id s = s := quot.induction_on s $ λ l, congr_arg coe $ map_id _ @[simp] lemma map_id' (s : multiset α) : map (λx, x) s = s := map_id s @[simp] theorem map_const (s : multiset α) (b : β) : map (function.const α b) s = repeat b s.card := quot.induction_on s $ λ l, congr_arg coe $ map_const _ _ theorem eq_of_mem_map_const {b₁ b₂ : β} {l : list α} (h : b₁ ∈ map (function.const α b₂) l) : b₁ = b₂ := eq_of_mem_repeat $ by rwa map_const at h @[simp] theorem map_le_map {f : α → β} {s t : multiset α} (h : s ≤ t) : map f s ≤ map f t := le_induction_on h $ λ l₁ l₂ h, (h.map f).subperm @[simp] lemma map_lt_map {f : α → β} {s t : multiset α} (h : s < t) : s.map f < t.map f := begin refine (map_le_map h.le).lt_of_not_le (λ H, h.ne $ eq_of_le_of_card_le h.le _), rw [←s.card_map f, ←t.card_map f], exact card_le_of_le H, end lemma map_mono (f : α → β) : monotone (map f) := λ _ _, map_le_map lemma map_strict_mono (f : α → β) : strict_mono (map f) := λ _ _, map_lt_map @[simp] theorem map_subset_map {f : α → β} {s t : multiset α} (H : s ⊆ t) : map f s ⊆ map f t := λ b m, let ⟨a, h, e⟩ := mem_map.1 m in mem_map.2 ⟨a, H h, e⟩ lemma map_erase [decidable_eq α] [decidable_eq β] (f : α → β) (hf : function.injective f) (x : α) (s : multiset α) : (s.erase x).map f = (s.map f).erase (f x) := begin induction s using multiset.induction_on with y s ih, { simp }, by_cases hxy : y = x, { cases hxy, simp }, { rw [s.erase_cons_tail hxy, map_cons, map_cons, (s.map f).erase_cons_tail (hf.ne hxy), ih] } end lemma map_surjective_of_surjective {f : α → β} (hf : function.surjective f) : function.surjective (map f) := begin intro s, induction s using multiset.induction_on with x s ih, { exact ⟨0, map_zero _⟩ }, { obtain ⟨y, rfl⟩ := hf x, obtain ⟨t, rfl⟩ := ih, exact ⟨y ::ₘ t, map_cons _ _ _⟩ } end /-! ### `multiset.fold` -/ /-- `foldl f H b s` is the lift of the list operation `foldl f b l`, which folds `f` over the multiset. It is well defined when `f` is right-commutative, that is, `f (f b a₁) a₂ = f (f b a₂) a₁`. -/ def foldl (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldl f b l) (λ l₁ l₂ p, p.foldl_eq H b) @[simp] theorem foldl_zero (f : β → α → β) (H b) : foldl f H b 0 = b := rfl @[simp] theorem foldl_cons (f : β → α → β) (H b a s) : foldl f H b (a ::ₘ s) = foldl f H (f b a) s := quot.induction_on s $ λ l, rfl @[simp] theorem foldl_add (f : β → α → β) (H b s t) : foldl f H b (s + t) = foldl f H (foldl f H b s) t := quotient.induction_on₂ s t $ λ l₁ l₂, foldl_append _ _ _ _ /-- `foldr f H b s` is the lift of the list operation `foldr f b l`, which folds `f` over the multiset. It is well defined when `f` is left-commutative, that is, `f a₁ (f a₂ b) = f a₂ (f a₁ b)`. -/ def foldr (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : β := quot.lift_on s (λ l, foldr f b l) (λ l₁ l₂ p, p.foldr_eq H b) @[simp] theorem foldr_zero (f : α → β → β) (H b) : foldr f H b 0 = b := rfl @[simp] theorem foldr_cons (f : α → β → β) (H b a s) : foldr f H b (a ::ₘ s) = f a (foldr f H b s) := quot.induction_on s $ λ l, rfl @[simp] theorem foldr_singleton (f : α → β → β) (H b a) : foldr f H b ({a} : multiset α) = f a b := rfl @[simp] theorem foldr_add (f : α → β → β) (H b s t) : foldr f H b (s + t) = foldr f H (foldr f H b t) s := quotient.induction_on₂ s t $ λ l₁ l₂, foldr_append _ _ _ _ @[simp] theorem coe_foldr (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldr f b := rfl @[simp] theorem coe_foldl (f : β → α → β) (H : right_commutative f) (b : β) (l : list α) : foldl f H b l = l.foldl f b := rfl theorem coe_foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (l : list α) : foldr f H b l = l.foldl (λ x y, f y x) b := (congr_arg (foldr f H b) (coe_reverse l)).symm.trans $ foldr_reverse _ _ _ theorem foldr_swap (f : α → β → β) (H : left_commutative f) (b : β) (s : multiset α) : foldr f H b s = foldl (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := quot.induction_on s $ λ l, coe_foldr_swap _ _ _ _ theorem foldl_swap (f : β → α → β) (H : right_commutative f) (b : β) (s : multiset α) : foldl f H b s = foldr (λ x y, f y x) (λ x y z, (H _ _ _).symm) b s := (foldr_swap _ _ _ _).symm lemma foldr_induction' (f : α → β → β) (H : left_commutative f) (x : β) (q : α → Prop) (p : β → Prop) (s : multiset α) (hpqf : ∀ a b, q a → p b → p (f a b)) (px : p x) (q_s : ∀ a ∈ s, q a) : p (foldr f H x s) := begin revert s, refine multiset.induction (by simp [px]) _, intros a s hs hsa, rw foldr_cons, have hps : ∀ (x : α), x ∈ s → q x, from λ x hxs, hsa x (mem_cons_of_mem hxs), exact hpqf a (foldr f H x s) (hsa a (mem_cons_self a s)) (hs hps), end lemma foldr_induction (f : α → α → α) (H : left_commutative f) (x : α) (p : α → Prop) (s : multiset α) (p_f : ∀ a b, p a → p b → p (f a b)) (px : p x) (p_s : ∀ a ∈ s, p a) : p (foldr f H x s) := foldr_induction' f H x p p s p_f px p_s lemma foldl_induction' (f : β → α → β) (H : right_commutative f) (x : β) (q : α → Prop) (p : β → Prop) (s : multiset α) (hpqf : ∀ a b, q a → p b → p (f b a)) (px : p x) (q_s : ∀ a ∈ s, q a) : p (foldl f H x s) := begin rw foldl_swap, exact foldr_induction' (λ x y, f y x) (λ x y z, (H _ _ _).symm) x q p s hpqf px q_s, end lemma foldl_induction (f : α → α → α) (H : right_commutative f) (x : α) (p : α → Prop) (s : multiset α) (p_f : ∀ a b, p a → p b → p (f b a)) (px : p x) (p_s : ∀ a ∈ s, p a) : p (foldl f H x s) := foldl_induction' f H x p p s p_f px p_s /-! ### Map for partial functions -/ /-- Lift of the list `pmap` operation. Map a partial function `f` over a multiset `s` whose elements are all in the domain of `f`. -/ def pmap {p : α → Prop} (f : Π a, p a → β) (s : multiset α) : (∀ a ∈ s, p a) → multiset β := quot.rec_on s (λ l H, ↑(pmap f l H)) $ λ l₁ l₂ (pp : l₁ ~ l₂), funext $ λ (H₂ : ∀ a ∈ l₂, p a), have H₁ : ∀ a ∈ l₁, p a, from λ a h, H₂ a (pp.subset h), have ∀ {s₂ e H}, @eq.rec (multiset α) l₁ (λ s, (∀ a ∈ s, p a) → multiset β) (λ _, ↑(pmap f l₁ H₁)) s₂ e H = ↑(pmap f l₁ H₁), by intros s₂ e _; subst e, this.trans $ quot.sound $ pp.pmap f @[simp] theorem coe_pmap {p : α → Prop} (f : Π a, p a → β) (l : list α) (H : ∀ a ∈ l, p a) : pmap f l H = l.pmap f H := rfl @[simp] lemma pmap_zero {p : α → Prop} (f : Π a, p a → β) (h : ∀a∈(0:multiset α), p a) : pmap f 0 h = 0 := rfl @[simp] lemma pmap_cons {p : α → Prop} (f : Π a, p a → β) (a : α) (m : multiset α) : ∀(h : ∀b∈a ::ₘ m, p b), pmap f (a ::ₘ m) h = f a (h a (mem_cons_self a m)) ::ₘ pmap f m (λa ha, h a $ mem_cons_of_mem ha) := quotient.induction_on m $ assume l h, rfl /-- "Attach" a proof that `a ∈ s` to each element `a` in `s` to produce a multiset on `{x // x ∈ s}`. -/ def attach (s : multiset α) : multiset {x // x ∈ s} := pmap subtype.mk s (λ a, id) @[simp] theorem coe_attach (l : list α) : @eq (multiset {x // x ∈ l}) (@attach α l) l.attach := rfl theorem sizeof_lt_sizeof_of_mem [has_sizeof α] {x : α} {s : multiset α} (hx : x ∈ s) : sizeof x < sizeof s := by { induction s with l a b, exact list.sizeof_lt_sizeof_of_mem hx, refl } theorem pmap_eq_map (p : α → Prop) (f : α → β) (s : multiset α) : ∀ H, @pmap _ _ p (λ a _, f a) s H = map f s := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map p f l H theorem pmap_congr {p q : α → Prop} {f : Π a, p a → β} {g : Π a, q a → β} (s : multiset α) {H₁ H₂} (h : ∀ a h₁ h₂, f a h₁ = g a h₂) : pmap f s H₁ = pmap g s H₂ := quot.induction_on s (λ l H₁ H₂, congr_arg coe $ pmap_congr l h) H₁ H₂ theorem map_pmap {p : α → Prop} (g : β → γ) (f : Π a, p a → β) (s) : ∀ H, map g (pmap f s H) = pmap (λ a h, g (f a h)) s H := quot.induction_on s $ λ l H, congr_arg coe $ map_pmap g f l H theorem pmap_eq_map_attach {p : α → Prop} (f : Π a, p a → β) (s) : ∀ H, pmap f s H = s.attach.map (λ x, f x.1 (H _ x.2)) := quot.induction_on s $ λ l H, congr_arg coe $ pmap_eq_map_attach f l H theorem attach_map_val (s : multiset α) : s.attach.map subtype.val = s := quot.induction_on s $ λ l, congr_arg coe $ attach_map_val l @[simp] theorem mem_attach (s : multiset α) : ∀ x, x ∈ s.attach := quot.induction_on s $ λ l, mem_attach _ @[simp] theorem mem_pmap {p : α → Prop} {f : Π a, p a → β} {s H b} : b ∈ pmap f s H ↔ ∃ a (h : a ∈ s), f a (H a h) = b := quot.induction_on s (λ l H, mem_pmap) H @[simp] theorem card_pmap {p : α → Prop} (f : Π a, p a → β) (s H) : card (pmap f s H) = card s := quot.induction_on s (λ l H, length_pmap) H @[simp] theorem card_attach {m : multiset α} : card (attach m) = card m := card_pmap _ _ _ @[simp] lemma attach_zero : (0 : multiset α).attach = 0 := rfl lemma attach_cons (a : α) (m : multiset α) : (a ::ₘ m).attach = ⟨a, mem_cons_self a m⟩ ::ₘ (m.attach.map $ λp, ⟨p.1, mem_cons_of_mem p.2⟩) := quotient.induction_on m $ assume l, congr_arg coe $ congr_arg (list.cons _) $ by rw [list.map_pmap]; exact list.pmap_congr _ (assume a' h₁ h₂, subtype.eq rfl) section decidable_pi_exists variables {m : multiset α} /-- If `p` is a decidable predicate, so is the predicate that all elements of a multiset satisfy `p`. -/ protected def decidable_forall_multiset {p : α → Prop} [hp : ∀ a, decidable (p a)] : decidable (∀ a ∈ m, p a) := quotient.rec_on_subsingleton m (λl, decidable_of_iff (∀a ∈ l, p a) $ by simp) instance decidable_dforall_multiset {p : Π a ∈ m, Prop} [hp : ∀ a (h : a ∈ m), decidable (p a h)] : decidable (∀ a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_forall_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (assume h a ha, h ⟨a, ha⟩ (mem_attach _ _)) (assume h ⟨a, ha⟩ _, h _ _)) /-- decidable equality for functions whose domain is bounded by multisets -/ instance decidable_eq_pi_multiset {β : α → Type*} [h : ∀ a, decidable_eq (β a)] : decidable_eq (Π a ∈ m, β a) := assume f g, decidable_of_iff (∀ a (h : a ∈ m), f a h = g a h) (by simp [function.funext_iff]) /-- If `p` is a decidable predicate, so is the existence of an element in a multiset satisfying `p`. -/ protected def decidable_exists_multiset {p : α → Prop} [decidable_pred p] : decidable (∃ x ∈ m, p x) := quotient.rec_on_subsingleton m (λl, decidable_of_iff (∃ a ∈ l, p a) $ by simp) instance decidable_dexists_multiset {p : Π a ∈ m, Prop} [hp : ∀ a (h : a ∈ m), decidable (p a h)] : decidable (∃ a (h : a ∈ m), p a h) := decidable_of_decidable_of_iff (@multiset.decidable_exists_multiset {a // a ∈ m} m.attach (λa, p a.1 a.2) _) (iff.intro (λ ⟨⟨a, ha₁⟩, _, ha₂⟩, ⟨a, ha₁, ha₂⟩) (λ ⟨a, ha₁, ha₂⟩, ⟨⟨a, ha₁⟩, mem_attach _ _, ha₂⟩)) end decidable_pi_exists /-! ### Subtraction -/ section variables [decidable_eq α] {s t u : multiset α} {a b : α} /-- `s - t` is the multiset such that `count a (s - t) = count a s - count a t` for all `a` (note that it is truncated subtraction, so it is `0` if `count a t ≥ count a s`). -/ protected def sub (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.diff l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.diff p₂ instance : has_sub (multiset α) := ⟨multiset.sub⟩ @[simp] theorem coe_sub (s t : list α) : (s - t : multiset α) = (s.diff t : list α) := rfl /-- This is a special case of `tsub_zero`, which should be used instead of this. This is needed to prove `has_ordered_sub (multiset α)`. -/ protected theorem sub_zero (s : multiset α) : s - 0 = s := quot.induction_on s $ λ l, rfl @[simp] theorem sub_cons (a : α) (s t : multiset α) : s - a ::ₘ t = s.erase a - t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ diff_cons _ _ _ /-- This is a special case of `tsub_le_iff_right`, which should be used instead of this. This is needed to prove `has_ordered_sub (multiset α)`. -/ protected theorem sub_le_iff_le_add : s - t ≤ u ↔ s ≤ u + t := by revert s; exact multiset.induction_on t (by simp [multiset.sub_zero]) (λ a t IH s, by simp [IH, erase_le_iff_le_cons]) instance : has_ordered_sub (multiset α) := ⟨λ n m k, multiset.sub_le_iff_le_add⟩ theorem sub_eq_fold_erase (s t : multiset α) : s - t = foldl erase erase_comm s t := quotient.induction_on₂ s t $ λ l₁ l₂, show ↑(l₁.diff l₂) = foldl erase erase_comm ↑l₁ ↑l₂, by { rw diff_eq_foldl l₁ l₂, symmetry, exact foldl_hom _ _ _ _ _ (λ x y, rfl) } @[simp] theorem card_sub {s t : multiset α} (h : t ≤ s) : card (s - t) = card s - card t := (tsub_eq_of_eq_add_rev $ by rw [add_comm, ← card_add, tsub_add_cancel_of_le h]).symm /-! ### Union -/ /-- `s ∪ t` is the lattice join operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∪ t` is the maximum of the multiplicities in `s` and `t`. -/ def union (s t : multiset α) : multiset α := s - t + t instance : has_union (multiset α) := ⟨union⟩ theorem union_def (s t : multiset α) : s ∪ t = s - t + t := rfl theorem le_union_left (s t : multiset α) : s ≤ s ∪ t := le_tsub_add theorem le_union_right (s t : multiset α) : t ≤ s ∪ t := le_add_left _ _ theorem eq_union_left : t ≤ s → s ∪ t = s := tsub_add_cancel_of_le theorem union_le_union_right (h : s ≤ t) (u) : s ∪ u ≤ t ∪ u := add_le_add_right (tsub_le_tsub_right h _) u theorem union_le (h₁ : s ≤ u) (h₂ : t ≤ u) : s ∪ t ≤ u := by rw ← eq_union_left h₂; exact union_le_union_right h₁ t @[simp] theorem mem_union : a ∈ s ∪ t ↔ a ∈ s ∨ a ∈ t := ⟨λ h, (mem_add.1 h).imp_left (mem_of_le tsub_le_self), or.rec (mem_of_le $ le_union_left _ _) (mem_of_le $ le_union_right _ _)⟩ @[simp] theorem map_union [decidable_eq β] {f : α → β} (finj : function.injective f) {s t : multiset α} : map f (s ∪ t) = map f s ∪ map f t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe (by rw [list.map_append f, list.map_diff finj]) /-! ### Intersection -/ /-- `s ∩ t` is the lattice meet operation with respect to the multiset `≤`. The multiplicity of `a` in `s ∩ t` is the minimum of the multiplicities in `s` and `t`. -/ def inter (s t : multiset α) : multiset α := quotient.lift_on₂ s t (λ l₁ l₂, (l₁.bag_inter l₂ : multiset α)) $ λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound $ p₁.bag_inter p₂ instance : has_inter (multiset α) := ⟨inter⟩ @[simp] theorem inter_zero (s : multiset α) : s ∩ 0 = 0 := quot.induction_on s $ λ l, congr_arg coe l.bag_inter_nil @[simp] theorem zero_inter (s : multiset α) : 0 ∩ s = 0 := quot.induction_on s $ λ l, congr_arg coe l.nil_bag_inter @[simp] theorem cons_inter_of_pos {a} (s : multiset α) {t} : a ∈ t → (a ::ₘ s) ∩ t = a ::ₘ s ∩ t.erase a := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_pos _ h @[simp] theorem cons_inter_of_neg {a} (s : multiset α) {t} : a ∉ t → (a ::ₘ s) ∩ t = s ∩ t := quotient.induction_on₂ s t $ λ l₁ l₂ h, congr_arg coe $ cons_bag_inter_of_neg _ h theorem inter_le_left (s t : multiset α) : s ∩ t ≤ s := quotient.induction_on₂ s t $ λ l₁ l₂, (bag_inter_sublist_left _ _).subperm theorem inter_le_right (s : multiset α) : ∀ t, s ∩ t ≤ t := multiset.induction_on s (λ t, (zero_inter t).symm ▸ zero_le _) $ λ a s IH t, if h : a ∈ t then by simpa [h] using cons_le_cons a (IH (t.erase a)) else by simp [h, IH] theorem le_inter (h₁ : s ≤ t) (h₂ : s ≤ u) : s ≤ t ∩ u := begin revert s u, refine multiset.induction_on t _ (λ a t IH, _); intros, { simp [h₁] }, by_cases a ∈ u, { rw [cons_inter_of_pos _ h, ← erase_le_iff_le_cons], exact IH (erase_le_iff_le_cons.2 h₁) (erase_le_erase _ h₂) }, { rw cons_inter_of_neg _ h, exact IH ((le_cons_of_not_mem $ mt (mem_of_le h₂) h).1 h₁) h₂ } end @[simp] theorem mem_inter : a ∈ s ∩ t ↔ a ∈ s ∧ a ∈ t := ⟨λ h, ⟨mem_of_le (inter_le_left _ _) h, mem_of_le (inter_le_right _ _) h⟩, λ ⟨h₁, h₂⟩, by rw [← cons_erase h₁, cons_inter_of_pos _ h₂]; apply mem_cons_self⟩ instance : lattice (multiset α) := { sup := (∪), sup_le := @union_le _ _, le_sup_left := le_union_left, le_sup_right := le_union_right, inf := (∩), le_inf := @le_inter _ _, inf_le_left := inter_le_left, inf_le_right := inter_le_right, ..@multiset.partial_order α } @[simp] theorem sup_eq_union (s t : multiset α) : s ⊔ t = s ∪ t := rfl @[simp] theorem inf_eq_inter (s t : multiset α) : s ⊓ t = s ∩ t := rfl @[simp] theorem le_inter_iff : s ≤ t ∩ u ↔ s ≤ t ∧ s ≤ u := le_inf_iff @[simp] theorem union_le_iff : s ∪ t ≤ u ↔ s ≤ u ∧ t ≤ u := sup_le_iff theorem union_comm (s t : multiset α) : s ∪ t = t ∪ s := sup_comm theorem inter_comm (s t : multiset α) : s ∩ t = t ∩ s := inf_comm theorem eq_union_right (h : s ≤ t) : s ∪ t = t := by rw [union_comm, eq_union_left h] theorem union_le_union_left (h : s ≤ t) (u) : u ∪ s ≤ u ∪ t := sup_le_sup_left h _ theorem union_le_add (s t : multiset α) : s ∪ t ≤ s + t := union_le (le_add_right _ _) (le_add_left _ _) theorem union_add_distrib (s t u : multiset α) : (s ∪ t) + u = (s + u) ∪ (t + u) := by simpa [(∪), union, eq_comm, add_assoc] using show s + u - (t + u) = s - t, by rw [add_comm t, tsub_add_eq_tsub_tsub, add_tsub_cancel_right] theorem add_union_distrib (s t u : multiset α) : s + (t ∪ u) = (s + t) ∪ (s + u) := by rw [add_comm, union_add_distrib, add_comm s, add_comm s] theorem cons_union_distrib (a : α) (s t : multiset α) : a ::ₘ (s ∪ t) = (a ::ₘ s) ∪ (a ::ₘ t) := by simpa using add_union_distrib (a ::ₘ 0) s t theorem inter_add_distrib (s t u : multiset α) : (s ∩ t) + u = (s + u) ∩ (t + u) := begin by_contra h, cases lt_iff_cons_le.1 (lt_of_le_of_ne (le_inter (add_le_add_right (inter_le_left s t) u) (add_le_add_right (inter_le_right s t) u)) h) with a hl, rw ← cons_add at hl, exact not_le_of_lt (lt_cons_self (s ∩ t) a) (le_inter (le_of_add_le_add_right (le_trans hl (inter_le_left _ _))) (le_of_add_le_add_right (le_trans hl (inter_le_right _ _)))) end theorem add_inter_distrib (s t u : multiset α) : s + (t ∩ u) = (s + t) ∩ (s + u) := by rw [add_comm, inter_add_distrib, add_comm s, add_comm s] theorem cons_inter_distrib (a : α) (s t : multiset α) : a ::ₘ (s ∩ t) = (a ::ₘ s) ∩ (a ::ₘ t) := by simp theorem union_add_inter (s t : multiset α) : s ∪ t + s ∩ t = s + t := begin apply le_antisymm, { rw union_add_distrib, refine union_le (add_le_add_left (inter_le_right _ _) _) _, rw add_comm, exact add_le_add_right (inter_le_left _ _) _ }, { rw [add_comm, add_inter_distrib], refine le_inter (add_le_add_right (le_union_right _ _) _) _, rw add_comm, exact add_le_add_right (le_union_left _ _) _ } end theorem sub_add_inter (s t : multiset α) : s - t + s ∩ t = s := begin rw [inter_comm], revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), by_cases a ∈ s, { rw [cons_inter_of_pos _ h, sub_cons, add_cons, IH, cons_erase h] }, { rw [cons_inter_of_neg _ h, sub_cons, erase_of_not_mem h, IH] } end theorem sub_inter (s t : multiset α) : s - (s ∩ t) = s - t := add_right_cancel $ by rw [sub_add_inter s t, tsub_add_cancel_of_le (inter_le_left s t)] end /-! ### `multiset.filter` -/ section variables (p : α → Prop) [decidable_pred p] /-- `filter p s` returns the elements in `s` (with the same multiplicities) which satisfy `p`, and removes the rest. -/ def filter (s : multiset α) : multiset α := quot.lift_on s (λ l, (filter p l : multiset α)) (λ l₁ l₂ h, quot.sound $ h.filter p) @[simp] theorem coe_filter (l : list α) : filter p (↑l) = l.filter p := rfl @[simp] theorem filter_zero : filter p 0 = 0 := rfl lemma filter_congr {p q : α → Prop} [decidable_pred p] [decidable_pred q] {s : multiset α} : (∀ x ∈ s, p x ↔ q x) → filter p s = filter q s := quot.induction_on s $ λ l h, congr_arg coe $ filter_congr' h @[simp] theorem filter_add (s t : multiset α) : filter p (s + t) = filter p s + filter p t := quotient.induction_on₂ s t $ λ l₁ l₂, congr_arg coe $ filter_append _ _ @[simp] theorem filter_le (s : multiset α) : filter p s ≤ s := quot.induction_on s $ λ l, (filter_sublist _).subperm @[simp] theorem filter_subset (s : multiset α) : filter p s ⊆ s := subset_of_le $ filter_le _ _ theorem filter_le_filter {s t} (h : s ≤ t) : filter p s ≤ filter p t := le_induction_on h $ λ l₁ l₂ h, (h.filter p).subperm lemma monotone_filter_left : monotone (filter p) := λ s t, filter_le_filter p lemma monotone_filter_right (s : multiset α) ⦃p q : α → Prop⦄ [decidable_pred p] [decidable_pred q] (h : p ≤ q) : s.filter p ≤ s.filter q := quotient.induction_on s (λ l, (l.monotone_filter_right h).subperm) variable {p} @[simp] theorem filter_cons_of_pos {a : α} (s) : p a → filter p (a ::ₘ s) = a ::ₘ filter p s := quot.induction_on s $ λ l h, congr_arg coe $ filter_cons_of_pos l h @[simp] theorem filter_cons_of_neg {a : α} (s) : ¬ p a → filter p (a ::ₘ s) = filter p s := quot.induction_on s $ λ l h, @congr_arg _ _ _ _ coe $ filter_cons_of_neg l h @[simp] theorem mem_filter {a : α} {s} : a ∈ filter p s ↔ a ∈ s ∧ p a := quot.induction_on s $ λ l, mem_filter theorem of_mem_filter {a : α} {s} (h : a ∈ filter p s) : p a := (mem_filter.1 h).2 theorem mem_of_mem_filter {a : α} {s} (h : a ∈ filter p s) : a ∈ s := (mem_filter.1 h).1 theorem mem_filter_of_mem {a : α} {l} (m : a ∈ l) (h : p a) : a ∈ filter p l := mem_filter.2 ⟨m, h⟩ theorem filter_eq_self {s} : filter p s = s ↔ ∀ a ∈ s, p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_of_sublist_of_length_eq (filter_sublist _) (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_self theorem filter_eq_nil {s} : filter p s = 0 ↔ ∀ a ∈ s, ¬p a := quot.induction_on s $ λ l, iff.trans ⟨λ h, eq_nil_of_length_eq_zero (@congr_arg _ _ _ _ card h), congr_arg coe⟩ filter_eq_nil theorem le_filter {s t} : s ≤ filter p t ↔ s ≤ t ∧ ∀ a ∈ s, p a := ⟨λ h, ⟨le_trans h (filter_le _ _), λ a m, of_mem_filter (mem_of_le h m)⟩, λ ⟨h, al⟩, filter_eq_self.2 al ▸ filter_le_filter p h⟩ theorem filter_cons {a : α} (s : multiset α) : filter p (a ::ₘ s) = (if p a then {a} else 0) + filter p s := begin split_ifs with h, { rw [filter_cons_of_pos _ h, singleton_add] }, { rw [filter_cons_of_neg _ h, zero_add] }, end lemma filter_singleton {a : α} (p : α → Prop) [decidable_pred p] : filter p {a} = if p a then {a} else ∅ := by simp only [singleton, filter_cons, filter_zero, add_zero, empty_eq_zero] lemma filter_nsmul (s : multiset α) (n : ℕ) : filter p (n • s) = n • filter p s := begin refine s.induction_on _ _, { simp only [filter_zero, nsmul_zero] }, { intros a ha ih, rw [nsmul_cons, filter_add, ih, filter_cons, nsmul_add], congr, split_ifs with hp; { simp only [filter_eq_self, nsmul_zero, filter_eq_nil], intros b hb, rwa (mem_singleton.mp (mem_of_mem_nsmul hb)) } } end variable (p) @[simp] theorem filter_sub [decidable_eq α] (s t : multiset α) : filter p (s - t) = filter p s - filter p t := begin revert s, refine multiset.induction_on t (by simp) (λ a t IH s, _), rw [sub_cons, IH], by_cases p a, { rw [filter_cons_of_pos _ h, sub_cons], congr, by_cases m : a ∈ s, { rw [← cons_inj_right a, ← filter_cons_of_pos _ h, cons_erase (mem_filter_of_mem m h), cons_erase m] }, { rw [erase_of_not_mem m, erase_of_not_mem (mt mem_of_mem_filter m)] } }, { rw [filter_cons_of_neg _ h], by_cases m : a ∈ s, { rw [(by rw filter_cons_of_neg _ h : filter p (erase s a) = filter p (a ::ₘ erase s a)), cons_erase m] }, { rw [erase_of_not_mem m] } } end @[simp] theorem filter_union [decidable_eq α] (s t : multiset α) : filter p (s ∪ t) = filter p s ∪ filter p t := by simp [(∪), union] @[simp] theorem filter_inter [decidable_eq α] (s t : multiset α) : filter p (s ∩ t) = filter p s ∩ filter p t := le_antisymm (le_inter (filter_le_filter _ $ inter_le_left _ _) (filter_le_filter _ $ inter_le_right _ _)) $ le_filter.2 ⟨inf_le_inf (filter_le _ _) (filter_le _ _), λ a h, of_mem_filter (mem_of_le (inter_le_left _ _) h)⟩ @[simp] theorem filter_filter (q) [decidable_pred q] (s : multiset α) : filter p (filter q s) = filter (λ a, p a ∧ q a) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter p q l theorem filter_add_filter (q) [decidable_pred q] (s : multiset α) : filter p s + filter q s = filter (λ a, p a ∨ q a) s + filter (λ a, p a ∧ q a) s := multiset.induction_on s rfl $ λ a s IH, by by_cases p a; by_cases q a; simp * theorem filter_add_not (s : multiset α) : filter p s + filter (λ a, ¬ p a) s = s := by rw [filter_add_filter, filter_eq_self.2, filter_eq_nil.2]; simp [decidable.em] theorem map_filter (f : β → α) (s : multiset β) : filter p (map f s) = map f (filter (p ∘ f) s) := quot.induction_on s (λ l, by simp [map_filter]) /-! ### Simultaneously filter and map elements of a multiset -/ /-- `filter_map f s` is a combination filter/map operation on `s`. The function `f : α → option β` is applied to each element of `s`; if `f a` is `some b` then `b` is added to the result, otherwise `a` is removed from the resulting multiset. -/ def filter_map (f : α → option β) (s : multiset α) : multiset β := quot.lift_on s (λ l, (filter_map f l : multiset β)) (λ l₁ l₂ h, quot.sound $ h.filter_map f) @[simp] theorem coe_filter_map (f : α → option β) (l : list α) : filter_map f l = l.filter_map f := rfl @[simp] theorem filter_map_zero (f : α → option β) : filter_map f 0 = 0 := rfl @[simp] theorem filter_map_cons_none {f : α → option β} (a : α) (s : multiset α) (h : f a = none) : filter_map f (a ::ₘ s) = filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_none a l h @[simp] theorem filter_map_cons_some (f : α → option β) (a : α) (s : multiset α) {b : β} (h : f a = some b) : filter_map f (a ::ₘ s) = b ::ₘ filter_map f s := quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ filter_map_cons_some f a l h theorem filter_map_eq_map (f : α → β) : filter_map (some ∘ f) = map f := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_map f) l theorem filter_map_eq_filter : filter_map (option.guard p) = filter p := funext $ λ s, quot.induction_on s $ λ l, @congr_arg _ _ _ _ coe $ congr_fun (filter_map_eq_filter p) l theorem filter_map_filter_map (f : α → option β) (g : β → option γ) (s : multiset α) : filter_map g (filter_map f s) = filter_map (λ x, (f x).bind g) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter_map f g l theorem map_filter_map (f : α → option β) (g : β → γ) (s : multiset α) : map g (filter_map f s) = filter_map (λ x, (f x).map g) s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map f g l theorem filter_map_map (f : α → β) (g : β → option γ) (s : multiset α) : filter_map g (map f s) = filter_map (g ∘ f) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_map f g l theorem filter_filter_map (f : α → option β) (p : β → Prop) [decidable_pred p] (s : multiset α) : filter p (filter_map f s) = filter_map (λ x, (f x).filter p) s := quot.induction_on s $ λ l, congr_arg coe $ filter_filter_map f p l theorem filter_map_filter (f : α → option β) (s : multiset α) : filter_map f (filter p s) = filter_map (λ x, if p x then f x else none) s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_filter p f l @[simp] theorem filter_map_some (s : multiset α) : filter_map some s = s := quot.induction_on s $ λ l, congr_arg coe $ filter_map_some l @[simp] theorem mem_filter_map (f : α → option β) (s : multiset α) {b : β} : b ∈ filter_map f s ↔ ∃ a, a ∈ s ∧ f a = some b := quot.induction_on s $ λ l, mem_filter_map f l theorem map_filter_map_of_inv (f : α → option β) (g : β → α) (H : ∀ x : α, (f x).map g = some x) (s : multiset α) : map g (filter_map f s) = s := quot.induction_on s $ λ l, congr_arg coe $ map_filter_map_of_inv f g H l theorem filter_map_le_filter_map (f : α → option β) {s t : multiset α} (h : s ≤ t) : filter_map f s ≤ filter_map f t := le_induction_on h $ λ l₁ l₂ h, (h.filter_map _).subperm /-! ### countp -/ /-- `countp p s` counts the number of elements of `s` (with multiplicity) that satisfy `p`. -/ def countp (s : multiset α) : ℕ := quot.lift_on s (countp p) (λ l₁ l₂, perm.countp_eq p) @[simp] theorem coe_countp (l : list α) : countp p l = l.countp p := rfl @[simp] theorem countp_zero : countp p 0 = 0 := rfl variable {p} @[simp] theorem countp_cons_of_pos {a : α} (s) : p a → countp p (a ::ₘ s) = countp p s + 1 := quot.induction_on s $ countp_cons_of_pos p @[simp] theorem countp_cons_of_neg {a : α} (s) : ¬ p a → countp p (a ::ₘ s) = countp p s := quot.induction_on s $ countp_cons_of_neg p variable (p) theorem countp_cons (b : α) (s) : countp p (b ::ₘ s) = countp p s + (if p b then 1 else 0) := quot.induction_on s $ by simp [list.countp_cons] theorem countp_eq_card_filter (s) : countp p s = card (filter p s) := quot.induction_on s $ λ l, l.countp_eq_length_filter p theorem countp_le_card (s) : countp p s ≤ card s := quot.induction_on s $ λ l, countp_le_length p @[simp] theorem countp_add (s t) : countp p (s + t) = countp p s + countp p t := by simp [countp_eq_card_filter] @[simp] theorem countp_nsmul (s) (n : ℕ) : countp p (n • s) = n * countp p s := by induction n; simp [*, succ_nsmul', succ_mul, zero_nsmul] theorem card_eq_countp_add_countp (s) : card s = countp p s + countp (λ x, ¬ p x) s := quot.induction_on s $ λ l, by simp [l.length_eq_countp_add_countp p] /-- `countp p`, the number of elements of a multiset satisfying `p`, promoted to an `add_monoid_hom`. -/ def countp_add_monoid_hom : multiset α →+ ℕ := { to_fun := countp p, map_zero' := countp_zero _, map_add' := countp_add _ } @[simp] lemma coe_countp_add_monoid_hom : (countp_add_monoid_hom p : multiset α → ℕ) = countp p := rfl @[simp] theorem countp_sub [decidable_eq α] {s t : multiset α} (h : t ≤ s) : countp p (s - t) = countp p s - countp p t := by simp [countp_eq_card_filter, h, filter_le_filter] theorem countp_le_of_le {s t} (h : s ≤ t) : countp p s ≤ countp p t := by simpa [countp_eq_card_filter] using card_le_of_le (filter_le_filter p h) @[simp] theorem countp_filter (q) [decidable_pred q] (s : multiset α) : countp p (filter q s) = countp (λ a, p a ∧ q a) s := by simp [countp_eq_card_filter] theorem countp_eq_countp_filter_add (s) (p q : α → Prop) [decidable_pred p] [decidable_pred q] : countp p s = (filter q s).countp p + (filter (λ a, ¬ q a) s).countp p := quot.induction_on s $ λ l, l.countp_eq_countp_filter_add _ _ @[simp] lemma countp_true {s : multiset α} : countp (λ _, true) s = card s := quot.induction_on s $ λ l, list.countp_true @[simp] lemma countp_false {s : multiset α} : countp (λ _, false) s = 0 := quot.induction_on s $ λ l, list.countp_false theorem countp_map (f : α → β) (s : multiset α) (p : β → Prop) [decidable_pred p] : countp p (map f s) = (s.filter (λ a, p (f a))).card := begin refine multiset.induction_on s _ (λ a t IH, _), { rw [map_zero, countp_zero, filter_zero, card_zero] }, { rw [map_cons, countp_cons, IH, filter_cons, card_add, apply_ite card, card_zero, card_singleton, add_comm] }, end variable {p} theorem countp_pos {s} : 0 < countp p s ↔ ∃ a ∈ s, p a := quot.induction_on s $ λ l, list.countp_pos p theorem countp_eq_zero {s} : countp p s = 0 ↔ ∀ a ∈ s, ¬ p a := quot.induction_on s $ λ l, list.countp_eq_zero p theorem countp_eq_card {s} : countp p s = card s ↔ ∀ a ∈ s, p a := quot.induction_on s $ λ l, list.countp_eq_length p theorem countp_pos_of_mem {s a} (h : a ∈ s) (pa : p a) : 0 < countp p s := countp_pos.2 ⟨_, h, pa⟩ theorem countp_congr {s s' : multiset α} (hs : s = s') {p p' : α → Prop} [decidable_pred p] [decidable_pred p'] (hp : ∀ x ∈ s, p x = p' x) : s.countp p = s'.countp p' := quot.induction_on₂ s s' (λ l l' hs hp, begin simp only [quot_mk_to_coe'', coe_eq_coe] at hs, exact hs.countp_congr hp, end) hs hp end /-! ### Multiplicity of an element -/ section variable [decidable_eq α] /-- `count a s` is the multiplicity of `a` in `s`. -/ def count (a : α) : multiset α → ℕ := countp (eq a) @[simp] theorem coe_count (a : α) (l : list α) : count a (↑l) = l.count a := coe_countp _ _ @[simp] theorem count_zero (a : α) : count a 0 = 0 := rfl @[simp] theorem count_cons_self (a : α) (s : multiset α) : count a (a ::ₘ s) = succ (count a s) := countp_cons_of_pos _ rfl @[simp, priority 990] theorem count_cons_of_ne {a b : α} (h : a ≠ b) (s : multiset α) : count a (b ::ₘ s) = count a s := countp_cons_of_neg _ h theorem count_le_card (a : α) (s) : count a s ≤ card s := countp_le_card _ _ theorem count_le_of_le (a : α) {s t} : s ≤ t → count a s ≤ count a t := countp_le_of_le _ theorem count_le_count_cons (a b : α) (s : multiset α) : count a s ≤ count a (b ::ₘ s) := count_le_of_le _ (le_cons_self _ _) theorem count_cons (a b : α) (s : multiset α) : count a (b ::ₘ s) = count a s + (if a = b then 1 else 0) := countp_cons _ _ _ @[simp] theorem count_singleton_self (a : α) : count a ({a} : multiset α) = 1 := by simp only [count_cons_self, singleton_eq_cons, eq_self_iff_true, count_zero] theorem count_singleton (a b : α) : count a ({b} : multiset α) = if a = b then 1 else 0 := by simp only [count_cons, singleton_eq_cons, count_zero, zero_add] @[simp] theorem count_add (a : α) : ∀ s t, count a (s + t) = count a s + count a t := countp_add _ /-- `count a`, the multiplicity of `a` in a multiset, promoted to an `add_monoid_hom`. -/ def count_add_monoid_hom (a : α) : multiset α →+ ℕ := countp_add_monoid_hom (eq a) @[simp] lemma coe_count_add_monoid_hom {a : α} : (count_add_monoid_hom a : multiset α → ℕ) = count a := rfl @[simp] theorem count_nsmul (a : α) (n s) : count a (n • s) = n * count a s := by induction n; simp [*, succ_nsmul', succ_mul, zero_nsmul] theorem count_pos {a : α} {s : multiset α} : 0 < count a s ↔ a ∈ s := by simp [count, countp_pos] theorem one_le_count_iff_mem {a : α} {s : multiset α} : 1 ≤ count a s ↔ a ∈ s := by rw [succ_le_iff, count_pos] @[simp, priority 980] theorem count_eq_zero_of_not_mem {a : α} {s : multiset α} (h : a ∉ s) : count a s = 0 := by_contradiction $ λ h', h $ count_pos.1 (nat.pos_of_ne_zero h') @[simp] theorem count_eq_zero {a : α} {s : multiset α} : count a s = 0 ↔ a ∉ s := iff_not_comm.1 $ count_pos.symm.trans pos_iff_ne_zero theorem count_ne_zero {a : α} {s : multiset α} : count a s ≠ 0 ↔ a ∈ s := by simp [ne.def, count_eq_zero] theorem count_eq_card {a : α} {s} : count a s = card s ↔ ∀ (x ∈ s), a = x := countp_eq_card @[simp] theorem count_repeat_self (a : α) (n : ℕ) : count a (repeat a n) = n := by simp [repeat] theorem count_repeat (a b : α) (n : ℕ) : count a (repeat b n) = if (a = b) then n else 0 := begin split_ifs with h₁, { rw [h₁, count_repeat_self] }, { rw [count_eq_zero], apply mt eq_of_mem_repeat h₁ }, end @[simp] theorem count_erase_self (a : α) (s : multiset α) : count a (erase s a) = pred (count a s) := begin by_cases a ∈ s, { rw [(by rw cons_erase h : count a s = count a (a ::ₘ erase s a)), count_cons_self]; refl }, { rw [erase_of_not_mem h, count_eq_zero.2 h]; refl } end @[simp, priority 980] theorem count_erase_of_ne {a b : α} (ab : a ≠ b) (s : multiset α) : count a (erase s b) = count a s := begin by_cases b ∈ s, { rw [← count_cons_of_ne ab, cons_erase h] }, { rw [erase_of_not_mem h] } end @[simp] theorem count_sub (a : α) (s t : multiset α) : count a (s - t) = count a s - count a t := begin revert s, refine multiset.induction_on t (by simp) (λ b t IH s, _), rw [sub_cons, IH], by_cases ab : a = b, { subst b, rw [count_erase_self, count_cons_self, sub_succ, pred_sub] }, { rw [count_erase_of_ne ab, count_cons_of_ne ab] } end @[simp] theorem count_union (a : α) (s t : multiset α) : count a (s ∪ t) = max (count a s) (count a t) := by simp [(∪), union, tsub_add_eq_max, -add_comm] @[simp] theorem count_inter (a : α) (s t : multiset α) : count a (s ∩ t) = min (count a s) (count a t) := begin apply @nat.add_left_cancel (count a (s - t)), rw [← count_add, sub_add_inter, count_sub, tsub_add_min], end theorem le_count_iff_repeat_le {a : α} {s : multiset α} {n : ℕ} : n ≤ count a s ↔ repeat a n ≤ s := quot.induction_on s $ λ l, le_count_iff_repeat_sublist.trans repeat_le_coe.symm @[simp] theorem count_filter_of_pos {p} [decidable_pred p] {a} {s : multiset α} (h : p a) : count a (filter p s) = count a s := quot.induction_on s $ λ l, count_filter h @[simp] theorem count_filter_of_neg {p} [decidable_pred p] {a} {s : multiset α} (h : ¬ p a) : count a (filter p s) = 0 := multiset.count_eq_zero_of_not_mem (λ t, h (of_mem_filter t)) theorem count_filter {p} [decidable_pred p] {a} {s : multiset α} : count a (filter p s) = if p a then count a s else 0 := begin split_ifs with h, { exact count_filter_of_pos h }, { exact count_filter_of_neg h }, end theorem ext {s t : multiset α} : s = t ↔ ∀ a, count a s = count a t := quotient.induction_on₂ s t $ λ l₁ l₂, quotient.eq.trans perm_iff_count @[ext] theorem ext' {s t : multiset α} : (∀ a, count a s = count a t) → s = t := ext.2 @[simp] theorem coe_inter (s t : list α) : (s ∩ t : multiset α) = (s.bag_inter t : list α) := by ext; simp theorem le_iff_count {s t : multiset α} : s ≤ t ↔ ∀ a, count a s ≤ count a t := ⟨λ h a, count_le_of_le a h, λ al, by rw ← (ext.2 (λ a, by simp [max_eq_right (al a)]) : s ∪ t = t); apply le_union_left⟩ instance : distrib_lattice (multiset α) := { le_sup_inf := λ s t u, le_of_eq $ eq.symm $ ext.2 $ λ a, by simp only [max_min_distrib_left, multiset.count_inter, multiset.sup_eq_union, multiset.count_union, multiset.inf_eq_inter], ..multiset.lattice } theorem repeat_inf (s : multiset α) (a : α) (n : ℕ) : (repeat a n) ⊓ s = repeat a (min (s.count a) n) := begin ext x, rw [inf_eq_inter, count_inter, count_repeat, count_repeat], by_cases x = a, simp only [min_comm, h, if_true, eq_self_iff_true], simp only [h, if_false, zero_min], end theorem count_map {α β : Type*} (f : α → β) (s : multiset α) [decidable_eq β] (b : β) : count b (map f s) = (s.filter (λ a, b = f a)).card := countp_map _ _ _ /-- `multiset.map f` preserves `count` if `f` is injective on the set of elements contained in the multiset -/ theorem count_map_eq_count [decidable_eq β] (f : α → β) (s : multiset α) (hf : set.inj_on f {x : α | x ∈ s}) (x ∈ s) : (s.map f).count (f x) = s.count x := begin suffices : (filter (λ (a : α), f x = f a) s).count x = card (filter (λ (a : α), f x = f a) s), { rw [count, countp_map, ← this], exact count_filter_of_pos rfl }, { rw eq_repeat.2 ⟨rfl, λ b hb, eq_comm.1 ((hf H (mem_filter.1 hb).left) (mem_filter.1 hb).right)⟩, simp only [count_repeat, eq_self_iff_true, if_true, card_repeat]}, end /-- `multiset.map f` preserves `count` if `f` is injective -/ theorem count_map_eq_count' [decidable_eq β] (f : α → β) (s : multiset α) (hf : function.injective f) (x : α) : (s.map f).count (f x) = s.count x := begin by_cases H : x ∈ s, { exact count_map_eq_count f _ (set.inj_on_of_injective hf _) _ H, }, { rw [count_eq_zero_of_not_mem H, count_eq_zero, mem_map], rintro ⟨k, hks, hkx⟩, rw hf hkx at *, contradiction } end lemma filter_eq' (s : multiset α) (b : α) : s.filter (= b) = repeat b (count b s) := begin ext a, rw [count_repeat, count_filter], exact if_ctx_congr iff.rfl (λ h, congr_arg _ h) (λ h, rfl), end lemma filter_eq (s : multiset α) (b : α) : s.filter (eq b) = repeat b (count b s) := by simp_rw [←filter_eq', eq_comm] @[simp] lemma repeat_inter (x : α) (n : ℕ) (s : multiset α) : repeat x n ∩ s = repeat x (min n (s.count x)) := begin refine le_antisymm _ _, { simp only [le_iff_count, count_inter, count_repeat], intro a, split_ifs with h, { rw h }, { rw [nat.zero_min] } }, simp only [le_inter_iff, ← le_count_iff_repeat_le, count_inter, count_repeat_self], end @[simp] lemma inter_repeat (s : multiset α) (x : α) (n : ℕ) : s ∩ repeat x n = repeat x (min (s.count x) n) := by rw [inter_comm, repeat_inter, min_comm] end section embedding @[simp] lemma map_le_map_iff {f : α → β} (hf : function.injective f) {s t : multiset α} : s.map f ≤ t.map f ↔ s ≤ t := begin classical, refine ⟨λ h, le_iff_count.mpr (λ a, _), map_le_map⟩, simpa [count_map_eq_count' f _ hf] using le_iff_count.mp h (f a), end /-- Associate to an embedding `f` from `α` to `β` the order embedding that maps a multiset to its image under `f`. -/ @[simps] def map_embedding (f : α ↪ β) : multiset α ↪o multiset β := order_embedding.of_map_le_iff (map f) (λ _ _, map_le_map_iff f.inj') end embedding lemma count_eq_card_filter_eq [decidable_eq α] (s : multiset α) (a : α) : s.count a = (s.filter (eq a)).card := by rw [count, countp_eq_card_filter] /-- Mapping a multiset through a predicate and counting the `true`s yields the cardinality of the set filtered by the predicate. Note that this uses the notion of a multiset of `Prop`s - due to the decidability requirements of `count`, the decidability instance on the LHS is different from the RHS. In particular, the decidability instance on the left leaks `classical.dec_eq`. See [here](https://github.com/leanprover-community/mathlib/pull/11306#discussion_r782286812) for more discussion. -/ @[simp] lemma map_count_true_eq_filter_card (s : multiset α) (p : α → Prop) [decidable_pred p] : (s.map p).count true = (s.filter p).card := by simp only [count_eq_card_filter_eq, map_filter, card_map, function.comp.left_id, eq_true_eq_id] /-! ### Lift a relation to `multiset`s -/ section rel /-- `rel r s t` -- lift the relation `r` between two elements to a relation between `s` and `t`, s.t. there is a one-to-one mapping betweem elements in `s` and `t` following `r`. -/ @[mk_iff] inductive rel (r : α → β → Prop) : multiset α → multiset β → Prop | zero : rel 0 0 | cons {a b as bs} : r a b → rel as bs → rel (a ::ₘ as) (b ::ₘ bs) variables {δ : Type*} {r : α → β → Prop} {p : γ → δ → Prop} private lemma rel_flip_aux {s t} (h : rel r s t) : rel (flip r) t s := rel.rec_on h rel.zero (assume _ _ _ _ h₀ h₁ ih, rel.cons h₀ ih) lemma rel_flip {s t} : rel (flip r) s t ↔ rel r t s := ⟨rel_flip_aux, rel_flip_aux⟩ lemma rel_refl_of_refl_on {m : multiset α} {r : α → α → Prop} : (∀ x ∈ m, r x x) → rel r m m := begin apply m.induction_on, { intros, apply rel.zero }, { intros a m ih h, exact rel.cons (h _ (mem_cons_self _ _)) (ih (λ _ ha, h _ (mem_cons_of_mem ha))) } end lemma rel_eq_refl {s : multiset α} : rel (=) s s := rel_refl_of_refl_on (λ x hx, rfl) lemma rel_eq {s t : multiset α} : rel (=) s t ↔ s = t := begin split, { assume h, induction h; simp * }, { assume h, subst h, exact rel_eq_refl } end lemma rel.mono {r p : α → β → Prop} {s t} (hst : rel r s t) (h : ∀(a ∈ s) (b ∈ t), r a b → p a b) : rel p s t := begin induction hst, case rel.zero { exact rel.zero }, case rel.cons : a b s t hab hst ih { apply rel.cons (h a (mem_cons_self _ _) b (mem_cons_self _ _) hab), exact ih (λ a' ha' b' hb' h', h a' (mem_cons_of_mem ha') b' (mem_cons_of_mem hb') h') } end lemma rel.add {s t u v} (hst : rel r s t) (huv : rel r u v) : rel r (s + u) (t + v) := begin induction hst, case rel.zero { simpa using huv }, case rel.cons : a b s t hab hst ih { simpa using ih.cons hab } end lemma rel_flip_eq {s t : multiset α} : rel (λa b, b = a) s t ↔ s = t := show rel (flip (=)) s t ↔ s = t, by rw [rel_flip, rel_eq, eq_comm] @[simp] lemma rel_zero_left {b : multiset β} : rel r 0 b ↔ b = 0 := by rw [rel_iff]; simp @[simp] lemma rel_zero_right {a : multiset α} : rel r a 0 ↔ a = 0 := by rw [rel_iff]; simp lemma rel_cons_left {a as bs} : rel r (a ::ₘ as) bs ↔ (∃b bs', r a b ∧ rel r as bs' ∧ bs = b ::ₘ bs') := begin split, { generalize hm : a ::ₘ as = m, assume h, induction h generalizing as, case rel.zero { simp at hm, contradiction }, case rel.cons : a' b as' bs ha'b h ih { rcases cons_eq_cons.1 hm with ⟨eq₁, eq₂⟩ | ⟨h, cs, eq₁, eq₂⟩, { subst eq₁, subst eq₂, exact ⟨b, bs, ha'b, h, rfl⟩ }, { rcases ih eq₂.symm with ⟨b', bs', h₁, h₂, eq⟩, exact ⟨b', b ::ₘ bs', h₁, eq₁.symm ▸ rel.cons ha'b h₂, eq.symm ▸ cons_swap _ _ _⟩ } } }, { exact assume ⟨b, bs', hab, h, eq⟩, eq.symm ▸ rel.cons hab h } end lemma rel_cons_right {as b bs} : rel r as (b ::ₘ bs) ↔ (∃a as', r a b ∧ rel r as' bs ∧ as = a ::ₘ as') := begin rw [← rel_flip, rel_cons_left], refine exists₂_congr (λ a as', _), rw [rel_flip, flip] end lemma rel_add_left {as₀ as₁} : ∀{bs}, rel r (as₀ + as₁) bs ↔ (∃bs₀ bs₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ bs = bs₀ + bs₁) := multiset.induction_on as₀ (by simp) begin assume a s ih bs, simp only [ih, cons_add, rel_cons_left], split, { assume h, rcases h with ⟨b, bs', hab, h, rfl⟩, rcases h with ⟨bs₀, bs₁, h₀, h₁, rfl⟩, exact ⟨b ::ₘ bs₀, bs₁, ⟨b, bs₀, hab, h₀, rfl⟩, h₁, by simp⟩ }, { assume h, rcases h with ⟨bs₀, bs₁, h, h₁, rfl⟩, rcases h with ⟨b, bs, hab, h₀, rfl⟩, exact ⟨b, bs + bs₁, hab, ⟨bs, bs₁, h₀, h₁, rfl⟩, by simp⟩ } end lemma rel_add_right {as bs₀ bs₁} : rel r as (bs₀ + bs₁) ↔ (∃as₀ as₁, rel r as₀ bs₀ ∧ rel r as₁ bs₁ ∧ as = as₀ + as₁) := by rw [← rel_flip, rel_add_left]; simp [rel_flip] lemma rel_map_left {s : multiset γ} {f : γ → α} : ∀{t}, rel r (s.map f) t ↔ rel (λa b, r (f a) b) s t := multiset.induction_on s (by simp) (by simp [rel_cons_left] {contextual := tt}) lemma rel_map_right {s : multiset α} {t : multiset γ} {f : γ → β} : rel r s (t.map f) ↔ rel (λa b, r a (f b)) s t := by rw [← rel_flip, rel_map_left, ← rel_flip]; refl lemma rel_map {s : multiset α} {t : multiset β} {f : α → γ} {g : β → δ} : rel p (s.map f) (t.map g) ↔ rel (λa b, p (f a) (g b)) s t := rel_map_left.trans rel_map_right lemma card_eq_card_of_rel {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : card s = card t := by induction h; simp [*] lemma exists_mem_of_rel_of_mem {r : α → β → Prop} {s : multiset α} {t : multiset β} (h : rel r s t) : ∀ {a : α} (ha : a ∈ s), ∃ b ∈ t, r a b := begin induction h with x y s t hxy hst ih, { simp }, { assume a ha, cases mem_cons.1 ha with ha ha, { exact ⟨y, mem_cons_self _ _, ha.symm ▸ hxy⟩ }, { rcases ih ha with ⟨b, hbt, hab⟩, exact ⟨b, mem_cons.2 (or.inr hbt), hab⟩ } } end lemma rel_of_forall {m1 m2 : multiset α} {r : α → α → Prop} (h : ∀ a b, a ∈ m1 → b ∈ m2 → r a b) (hc : card m1 = card m2) : m1.rel r m2 := begin revert m1, apply m2.induction_on, { intros m h hc, rw [rel_zero_right, ← card_eq_zero, hc, card_zero] }, { intros a t ih m h hc, rw card_cons at hc, obtain ⟨b, hb⟩ := card_pos_iff_exists_mem.1 (show 0 < card m, from hc.symm ▸ (nat.succ_pos _)), obtain ⟨m', rfl⟩ := exists_cons_of_mem hb, refine rel_cons_right.mpr ⟨b, m', h _ _ hb (mem_cons_self _ _), ih _ _, rfl⟩, { exact λ _ _ ha hb, h _ _ (mem_cons_of_mem ha) (mem_cons_of_mem hb) }, { simpa using hc } } end lemma rel_repeat_left {m : multiset α} {a : α} {r : α → α → Prop} {n : ℕ} : (repeat a n).rel r m ↔ m.card = n ∧ ∀ x, x ∈ m → r a x := ⟨λ h, ⟨(card_eq_card_of_rel h).symm.trans (card_repeat _ _), λ x hx, begin obtain ⟨b, hb1, hb2⟩ := exists_mem_of_rel_of_mem (rel_flip.2 h) hx, rwa eq_of_mem_repeat hb1 at hb2, end⟩, λ h, rel_of_forall (λ x y hx hy, (eq_of_mem_repeat hx).symm ▸ (h.2 _ hy)) (eq.trans (card_repeat _ _) h.1.symm)⟩ lemma rel_repeat_right {m : multiset α} {a : α} {r : α → α → Prop} {n : ℕ} : m.rel r (repeat a n) ↔ m.card = n ∧ ∀ x, x ∈ m → r x a := by { rw [← rel_flip], exact rel_repeat_left } lemma rel.trans (r : α → α → Prop) [is_trans α r] {s t u : multiset α} (r1 : rel r s t) (r2 : rel r t u) : rel r s u := begin induction t using multiset.induction_on with x t ih generalizing s u, { rw [rel_zero_right.mp r1, rel_zero_left.mp r2, rel_zero_left] }, { obtain ⟨a, as, ha1, ha2, rfl⟩ := rel_cons_right.mp r1, obtain ⟨b, bs, hb1, hb2, rfl⟩ := rel_cons_left.mp r2, exact multiset.rel.cons (trans ha1 hb1) (ih ha2 hb2) } end lemma rel.countp_eq (r : α → α → Prop) [is_trans α r] [is_symm α r] {s t : multiset α} (x : α) [decidable_pred (r x)] (h : rel r s t) : countp (r x) s = countp (r x) t := begin induction s using multiset.induction_on with y s ih generalizing t, { rw rel_zero_left.mp h, }, { obtain ⟨b, bs, hb1, hb2, rfl⟩ := rel_cons_left.mp h, rw [countp_cons, countp_cons, ih hb2], exact congr_arg _ (if_congr ⟨λ h, trans h hb1, λ h, trans h (symm hb1)⟩ rfl rfl) }, end end rel section map theorem map_eq_map {f : α → β} (hf : function.injective f) {s t : multiset α} : s.map f = t.map f ↔ s = t := by { rw [← rel_eq, ← rel_eq, rel_map], simp only [hf.eq_iff] } theorem map_injective {f : α → β} (hf : function.injective f) : function.injective (multiset.map f) := assume x y, (map_eq_map hf).1 end map section quot theorem map_mk_eq_map_mk_of_rel {r : α → α → Prop} {s t : multiset α} (hst : s.rel r t) : s.map (quot.mk r) = t.map (quot.mk r) := rel.rec_on hst rfl $ assume a b s t hab hst ih, by simp [ih, quot.sound hab] theorem exists_multiset_eq_map_quot_mk {r : α → α → Prop} (s : multiset (quot r)) : ∃t:multiset α, s = t.map (quot.mk r) := multiset.induction_on s ⟨0, rfl⟩ $ assume a s ⟨t, ht⟩, quot.induction_on a $ assume a, ht.symm ▸ ⟨a ::ₘ t, (map_cons _ _ _).symm⟩ theorem induction_on_multiset_quot {r : α → α → Prop} {p : multiset (quot r) → Prop} (s : multiset (quot r)) : (∀s:multiset α, p (s.map (quot.mk r))) → p s := match s, exists_multiset_eq_map_quot_mk s with _, ⟨t, rfl⟩ := assume h, h _ end end quot /-! ### Disjoint multisets -/ /-- `disjoint s t` means that `s` and `t` have no elements in common. -/ def disjoint (s t : multiset α) : Prop := ∀ ⦃a⦄, a ∈ s → a ∈ t → false @[simp] theorem coe_disjoint (l₁ l₂ : list α) : @disjoint α l₁ l₂ ↔ l₁.disjoint l₂ := iff.rfl theorem disjoint.symm {s t : multiset α} (d : disjoint s t) : disjoint t s | a i₂ i₁ := d i₁ i₂ theorem disjoint_comm {s t : multiset α} : disjoint s t ↔ disjoint t s := ⟨disjoint.symm, disjoint.symm⟩ theorem disjoint_left {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ s → a ∉ t := iff.rfl theorem disjoint_right {s t : multiset α} : disjoint s t ↔ ∀ {a}, a ∈ t → a ∉ s := disjoint_comm theorem disjoint_iff_ne {s t : multiset α} : disjoint s t ↔ ∀ a ∈ s, ∀ b ∈ t, a ≠ b := by simp [disjoint_left, imp_not_comm] theorem disjoint_of_subset_left {s t u : multiset α} (h : s ⊆ u) (d : disjoint u t) : disjoint s t | x m₁ := d (h m₁) theorem disjoint_of_subset_right {s t u : multiset α} (h : t ⊆ u) (d : disjoint s u) : disjoint s t | x m m₁ := d m (h m₁) theorem disjoint_of_le_left {s t u : multiset α} (h : s ≤ u) : disjoint u t → disjoint s t := disjoint_of_subset_left (subset_of_le h) theorem disjoint_of_le_right {s t u : multiset α} (h : t ≤ u) : disjoint s u → disjoint s t := disjoint_of_subset_right (subset_of_le h) @[simp] theorem zero_disjoint (l : multiset α) : disjoint 0 l | a := (not_mem_nil a).elim @[simp, priority 1100] theorem singleton_disjoint {l : multiset α} {a : α} : disjoint {a} l ↔ a ∉ l := by simp [disjoint]; refl @[simp, priority 1100] theorem disjoint_singleton {l : multiset α} {a : α} : disjoint l {a} ↔ a ∉ l := by rw [disjoint_comm, singleton_disjoint] @[simp] theorem disjoint_add_left {s t u : multiset α} : disjoint (s + t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_add_right {s t u : multiset α} : disjoint s (t + u) ↔ disjoint s t ∧ disjoint s u := by rw [disjoint_comm, disjoint_add_left]; tauto @[simp] theorem disjoint_cons_left {a : α} {s t : multiset α} : disjoint (a ::ₘ s) t ↔ a ∉ t ∧ disjoint s t := (@disjoint_add_left _ {a} s t).trans $ by rw singleton_disjoint @[simp] theorem disjoint_cons_right {a : α} {s t : multiset α} : disjoint s (a ::ₘ t) ↔ a ∉ s ∧ disjoint s t := by rw [disjoint_comm, disjoint_cons_left]; tauto theorem inter_eq_zero_iff_disjoint [decidable_eq α] {s t : multiset α} : s ∩ t = 0 ↔ disjoint s t := by rw ← subset_zero; simp [subset_iff, disjoint] @[simp] theorem disjoint_union_left [decidable_eq α] {s t u : multiset α} : disjoint (s ∪ t) u ↔ disjoint s u ∧ disjoint t u := by simp [disjoint, or_imp_distrib, forall_and_distrib] @[simp] theorem disjoint_union_right [decidable_eq α] {s t u : multiset α} : disjoint s (t ∪ u) ↔ disjoint s t ∧ disjoint s u := by simp [disjoint, or_imp_distrib, forall_and_distrib] lemma add_eq_union_iff_disjoint [decidable_eq α] {s t : multiset α} : s + t = s ∪ t ↔ disjoint s t := by simp_rw [←inter_eq_zero_iff_disjoint, ext, count_add, count_union, count_inter, count_zero, nat.min_eq_zero_iff, nat.add_eq_max_iff] lemma disjoint_map_map {f : α → γ} {g : β → γ} {s : multiset α} {t : multiset β} : disjoint (s.map f) (t.map g) ↔ (∀a∈s, ∀b∈t, f a ≠ g b) := by { simp [disjoint, @eq_comm _ (f _) (g _)], refl } /-- `pairwise r m` states that there exists a list of the elements s.t. `r` holds pairwise on this list. -/ def pairwise (r : α → α → Prop) (m : multiset α) : Prop := ∃l:list α, m = l ∧ l.pairwise r lemma pairwise_coe_iff_pairwise {r : α → α → Prop} (hr : symmetric r) {l : list α} : multiset.pairwise r l ↔ l.pairwise r := iff.intro (assume ⟨l', eq, h⟩, ((quotient.exact eq).pairwise_iff hr).2 h) (assume h, ⟨l, rfl, h⟩) end multiset namespace multiset section choose variables (p : α → Prop) [decidable_pred p] (l : multiset α) /-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `choose_x p l hp` returns that `a` together with proofs of `a ∈ l` and `p a`. -/ def choose_x : Π hp : (∃! a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } := quotient.rec_on l (λ l' ex_unique, list.choose_x p l' (exists_of_exists_unique ex_unique)) begin intros, funext hp, suffices all_equal : ∀ x y : { t // t ∈ b ∧ p t }, x = y, { apply all_equal }, { rintros ⟨x, px⟩ ⟨y, py⟩, rcases hp with ⟨z, ⟨z_mem_l, pz⟩, z_unique⟩, congr, calc x = z : z_unique x px ... = y : (z_unique y py).symm } end /-- Given a proof `hp` that there exists a unique `a ∈ l` such that `p a`, `choose p l hp` returns that `a`. -/ 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 variable (α) /-- The equivalence between lists and multisets of a subsingleton type. -/ def subsingleton_equiv [subsingleton α] : list α ≃ multiset α := { to_fun := coe, inv_fun := quot.lift id $ λ (a b : list α) (h : a ~ b), list.ext_le h.length_eq $ λ n h₁ h₂, subsingleton.elim _ _, left_inv := λ l, rfl, right_inv := λ m, quot.induction_on m $ λ l, rfl } variable {α} @[simp] lemma coe_subsingleton_equiv [subsingleton α] : (subsingleton_equiv α : list α → multiset α) = coe := rfl end multiset
7f19c6599aa17a02771240653f65e344c9e8f7ed
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/symplectic_group.lean
3e04c91cdebded7b4f45fa0e64139fd95fa771a7
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,330
lean
/- Copyright (c) 2022 Matej Penciak. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Matej Penciak, Moritz Doll, Fabien Clery -/ import linear_algebra.matrix.nonsingular_inverse /-! # The Symplectic Group This file defines the symplectic group and proves elementary properties. ## Main Definitions `matrix.J`: the canonical `2n × 2n` skew-symmetric matrix `symplectic_group`: the group of symplectic matrices ## TODO * Every symplectic matrix has determinant 1. * For `n = 1` the symplectic group coincides with the special linear group. -/ open_locale matrix variables {l R : Type*} namespace matrix variables (l) [decidable_eq l] (R) [comm_ring R] section J_matrix_lemmas /-- The matrix defining the canonical skew-symmetric bilinear form. -/ def J : matrix (l ⊕ l) (l ⊕ l) R := matrix.from_blocks 0 (-1) 1 0 @[simp] lemma J_transpose : (J l R)ᵀ = - (J l R) := begin rw [J, from_blocks_transpose, ←neg_one_smul R (from_blocks _ _ _ _), from_blocks_smul, matrix.transpose_zero, matrix.transpose_one, transpose_neg], simp [from_blocks], end variables [fintype l] lemma J_squared : (J l R) ⬝ (J l R) = -1 := begin rw [J, from_blocks_multiply], simp only [matrix.zero_mul, matrix.neg_mul, zero_add, neg_zero, matrix.one_mul, add_zero], rw [← neg_zero, ← matrix.from_blocks_neg, ← from_blocks_one], end lemma J_inv : (J l R)⁻¹ = -(J l R) := begin refine matrix.inv_eq_right_inv _, rw [matrix.mul_neg, J_squared], exact neg_neg 1, end lemma J_det_mul_J_det : (det (J l R)) * (det (J l R)) = 1 := begin rw [←det_mul, J_squared], rw [←one_smul R (-1 : matrix _ _ R)], rw [smul_neg, ←neg_smul, det_smul], simp only [fintype.card_sum, det_one, mul_one], apply even.neg_one_pow, exact even_add_self _ end lemma is_unit_det_J : is_unit (det (J l R)) := is_unit_iff_exists_inv.mpr ⟨det (J l R), J_det_mul_J_det _ _⟩ end J_matrix_lemmas variable [fintype l] /-- The group of symplectic matrices over a ring `R`. -/ def symplectic_group : submonoid (matrix (l ⊕ l) (l ⊕ l) R) := { carrier := { A | A ⬝ (J l R) ⬝ Aᵀ = J l R}, mul_mem' := begin intros a b ha hb, simp only [mul_eq_mul, set.mem_set_of_eq, transpose_mul] at *, rw [←matrix.mul_assoc, a.mul_assoc, a.mul_assoc, hb], exact ha, end, one_mem' := by simp } end matrix namespace symplectic_group variables {l} {R} [decidable_eq l] [fintype l] [comm_ring R] open matrix lemma mem_iff {A : matrix (l ⊕ l) (l ⊕ l) R} : A ∈ symplectic_group l R ↔ A ⬝ (J l R) ⬝ Aᵀ = J l R := by simp [symplectic_group] instance coe_matrix : has_coe (symplectic_group l R) (matrix (l ⊕ l) (l ⊕ l) R) := by apply_instance section symplectic_J variables (l) (R) lemma J_mem : (J l R) ∈ symplectic_group l R := begin rw [mem_iff, J, from_blocks_multiply, from_blocks_transpose, from_blocks_multiply], simp, end /-- The canonical skew-symmetric matrix as an element in the symplectic group. -/ def sym_J : symplectic_group l R := ⟨J l R, J_mem l R⟩ variables {l} {R} @[simp] lemma coe_J : ↑(sym_J l R) = J l R := rfl end symplectic_J variables {R} {A : matrix (l ⊕ l) (l ⊕ l) R} lemma neg_mem (h : A ∈ symplectic_group l R) : -A ∈ symplectic_group l R := begin rw mem_iff at h ⊢, simp [h], end lemma symplectic_det (hA : A ∈ symplectic_group l R) : is_unit $ det A := begin rw is_unit_iff_exists_inv, use A.det, refine (is_unit_det_J l R).mul_left_cancel _, rw [mul_one], rw mem_iff at hA, apply_fun det at hA, simp only [det_mul, det_transpose] at hA, rw [mul_comm A.det, mul_assoc] at hA, exact hA, end lemma transpose_mem (hA : A ∈ symplectic_group l R) : Aᵀ ∈ symplectic_group l R := begin rw mem_iff at ⊢ hA, rw transpose_transpose, have huA := symplectic_det hA, have huAT : is_unit (Aᵀ).det := begin rw matrix.det_transpose, exact huA, end, calc Aᵀ ⬝ J l R ⬝ A = - Aᵀ ⬝ (J l R)⁻¹ ⬝ A : by {rw J_inv, simp} ... = - Aᵀ ⬝ (A ⬝ J l R ⬝ Aᵀ)⁻¹ ⬝ A : by rw hA ... = - (Aᵀ ⬝ (Aᵀ⁻¹ ⬝ (J l R)⁻¹)) ⬝ A⁻¹ ⬝ A : by simp only [matrix.mul_inv_rev, matrix.mul_assoc, matrix.neg_mul] ... = - (J l R)⁻¹ : by rw [mul_nonsing_inv_cancel_left _ _ huAT, nonsing_inv_mul_cancel_right _ _ huA] ... = (J l R) : by simp [J_inv] end @[simp] lemma transpose_mem_iff : Aᵀ ∈ symplectic_group l R ↔ A ∈ symplectic_group l R := ⟨λ hA, by simpa using transpose_mem hA , transpose_mem⟩ lemma mem_iff' : A ∈ symplectic_group l R ↔ Aᵀ ⬝ (J l R) ⬝ A = J l R := by rw [←transpose_mem_iff, mem_iff, transpose_transpose] instance : has_inv (symplectic_group l R) := { inv := λ A, ⟨- (J l R) ⬝ (A : matrix (l ⊕ l) (l ⊕ l) R)ᵀ ⬝ (J l R), mul_mem (mul_mem (neg_mem $ J_mem _ _) $ transpose_mem A.2) $ J_mem _ _⟩ } lemma coe_inv (A : symplectic_group l R) : (↑(A⁻¹) : matrix _ _ _) = - J l R ⬝ (↑A)ᵀ ⬝ J l R := rfl lemma inv_left_mul_aux (hA : A ∈ symplectic_group l R) : -(J l R ⬝ Aᵀ ⬝ J l R ⬝ A) = 1 := calc -(J l R ⬝ Aᵀ ⬝ J l R ⬝ A) = - J l R ⬝ (Aᵀ ⬝ J l R ⬝ A) : by simp only [matrix.mul_assoc, matrix.neg_mul] ... = - J l R ⬝ J l R : by {rw mem_iff' at hA, rw hA} ... = (-1 : R) • (J l R ⬝ J l R) : by simp only [matrix.neg_mul, neg_smul, one_smul] ... = (-1 : R) • -1 : by rw J_squared ... = 1 : by simp only [neg_smul_neg, one_smul] lemma coe_inv' (A : symplectic_group l R) : (↑(A⁻¹) : matrix (l ⊕ l) (l ⊕ l) R) = A⁻¹ := begin refine (coe_inv A).trans (inv_eq_left_inv _).symm, simp [inv_left_mul_aux, coe_inv], end lemma inv_eq_symplectic_inv (A : matrix (l ⊕ l) (l ⊕ l) R) (hA : A ∈ symplectic_group l R) : A⁻¹ = - (J l R) ⬝ Aᵀ ⬝ (J l R) := inv_eq_left_inv (by simp only [matrix.neg_mul, inv_left_mul_aux hA]) instance : group (symplectic_group l R) := { mul_left_inv := λ A, begin apply subtype.ext, simp only [submonoid.coe_one, submonoid.coe_mul, matrix.neg_mul, coe_inv], rw [matrix.mul_eq_mul, matrix.neg_mul], exact inv_left_mul_aux A.2, end, .. symplectic_group.has_inv, .. submonoid.to_monoid _ } end symplectic_group
14330553edfe7f64ffb8fd368a547e080ca324eb
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/data/nat/enat.lean
210a865ca809bb35a1cb533ee32ca0a23083c42b
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
20,033
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.pfun import tactic.norm_num import data.equiv.mul_add /-! # Natural numbers with infinity The natural numbers and an extra `top` element `⊤`. ## Main definitions The following instances are defined: * `ordered_add_comm_monoid enat` * `canonically_ordered_add_monoid enat` There is no additive analogue of `monoid_with_zero`; if there were then `enat` could be an `add_monoid_with_top`. * `to_with_top` : the map from `enat` to `with_top ℕ`, with theorems that it plays well with `+` and `≤`. * `with_top_add_equiv : enat ≃+ with_top ℕ` * `with_top_order_iso : enat ≃o with_top ℕ` ## Implementation details `enat` is defined to be `part ℕ`. `+` and `≤` are defined on `enat`, but there is an issue with `*` because it's not clear what `0 * ⊤` should be. `mul` is hence left undefined. Similarly `⊤ - ⊤` is ambiguous so there is no `-` defined on `enat`. Before the `open_locale classical` line, various proofs are made with decidability assumptions. This can cause issues -- see for example the non-simp lemma `to_with_top_zero` proved by `rfl`, followed by `@[simp] lemma to_with_top_zero'` whose proof uses `convert`. ## Tags enat, with_top ℕ -/ open part (hiding some) /-- Type of natural numbers with infinity (`⊤`) -/ def enat : Type := part ℕ namespace enat /-- The computable embedding `ℕ → enat`. This coincides with the coercion `coe : ℕ → enat`, see `enat.some_eq_coe`. However, `coe` is noncomputable so `some` is preferable when computability is a concern. -/ def some : ℕ → enat := part.some instance : has_zero enat := ⟨some 0⟩ instance : inhabited enat := ⟨0⟩ instance : has_one enat := ⟨some 1⟩ instance : has_add enat := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, get x h.1 + get y h.2⟩⟩ instance (n : ℕ) : decidable (some n).dom := is_true trivial lemma some_eq_coe (n : ℕ) : some n = n := begin induction n with n ih, { refl }, apply part.ext', { show true ↔ ((n : enat).dom ∧ true), rw [← ih, and_true], exact iff.rfl }, { intros h H, show n.succ = (n : enat).get H.1 + 1, rw [nat.cast_succ] at H, revert H, simp only [← ih], intro, refl }, end @[simp] lemma coe_inj {x y : ℕ} : (x : enat) = y ↔ x = y := by simpa only [← some_eq_coe] using part.some_inj @[simp] lemma dom_some (x : ℕ) : (some x).dom := trivial @[simp] lemma dom_coe (x : ℕ) : (x : enat).dom := by rw [← some_eq_coe]; trivial instance : add_comm_monoid enat := { add := (+), zero := (0), add_comm := λ x y, part.ext' and.comm (λ _ _, add_comm _ _), zero_add := λ x, part.ext' (true_and _) (λ _ _, zero_add _), add_zero := λ x, part.ext' (and_true _) (λ _ _, add_zero _), add_assoc := λ x y z, part.ext' and.assoc (λ _ _, add_assoc _ _ _) } instance : has_le enat := ⟨λ x y, ∃ h : y.dom → x.dom, ∀ hy : y.dom, x.get (h hy) ≤ y.get hy⟩ instance : has_top enat := ⟨none⟩ instance : has_bot enat := ⟨0⟩ instance : has_sup enat := ⟨λ x y, ⟨x.dom ∧ y.dom, λ h, x.get h.1 ⊔ y.get h.2⟩⟩ lemma le_def (x y : enat) : x ≤ y ↔ ∃ h : y.dom → x.dom, ∀ hy : y.dom, x.get (h hy) ≤ y.get hy := iff.rfl @[elab_as_eliminator] protected lemma cases_on' {P : enat → Prop} : ∀ a : enat, P ⊤ → (∀ n : ℕ, P (some n)) → P a := part.induction_on @[elab_as_eliminator] protected lemma cases_on {P : enat → Prop} : ∀ a : enat, P ⊤ → (∀ n : ℕ, P n) → P a := by { simp only [← some_eq_coe], exact enat.cases_on' } @[simp] lemma top_add (x : enat) : ⊤ + x = ⊤ := part.ext' (false_and _) (λ h, h.left.elim) @[simp] lemma add_top (x : enat) : x + ⊤ = ⊤ := by rw [add_comm, top_add] @[simp] lemma coe_get {x : enat} (h : x.dom) : (x.get h : enat) = x := by { rw [← some_eq_coe], exact part.ext' (iff_of_true trivial h) (λ _ _, rfl) } @[simp, norm_cast] lemma get_coe' (x : ℕ) (h : (x : enat).dom) : get (x : enat) h = x := by rw [← coe_inj, coe_get] lemma get_coe {x : ℕ} : get (x : enat) (dom_coe x) = x := get_coe' _ _ lemma coe_add_get {x : ℕ} {y : enat} (h : ((x : enat) + y).dom) : get ((x : enat) + y) h = x + get y h.2 := by { simp only [← some_eq_coe] at h ⊢, refl } @[simp] lemma get_add {x y : enat} (h : (x + y).dom) : get (x + y) h = x.get h.1 + y.get h.2 := rfl @[simp] lemma get_zero (h : (0 : enat).dom) : (0 : enat).get h = 0 := rfl @[simp] lemma get_one (h : (1 : enat).dom) : (1 : enat).get h = 1 := rfl lemma get_eq_iff_eq_some {a : enat} {ha : a.dom} {b : ℕ} : a.get ha = b ↔ a = some b := get_eq_iff_eq_some lemma get_eq_iff_eq_coe {a : enat} {ha : a.dom} {b : ℕ} : a.get ha = b ↔ a = b := by rw [get_eq_iff_eq_some, some_eq_coe] lemma dom_of_le_of_dom {x y : enat} : x ≤ y → y.dom → x.dom := λ ⟨h, _⟩, h lemma dom_of_le_some {x : enat} {y : ℕ} (h : x ≤ some y) : x.dom := dom_of_le_of_dom h trivial lemma dom_of_le_coe {x : enat} {y : ℕ} (h : x ≤ y) : x.dom := by { rw [← some_eq_coe] at h, exact dom_of_le_some h } instance decidable_le (x y : enat) [decidable x.dom] [decidable y.dom] : decidable (x ≤ y) := if hx : x.dom then decidable_of_decidable_of_iff (show decidable (∀ (hy : (y : enat).dom), x.get hx ≤ (y : enat).get hy), from forall_prop_decidable _) $ by { dsimp [(≤)], simp only [hx, exists_prop_of_true, forall_true_iff] } else if hy : y.dom then is_false $ λ h, hx $ dom_of_le_of_dom h hy else is_true ⟨λ h, (hy h).elim, λ h, (hy h).elim⟩ /-- The coercion `ℕ → enat` preserves `0` and addition. -/ def coe_hom : ℕ →+ enat := ⟨coe, nat.cast_zero, nat.cast_add⟩ @[simp] lemma coe_coe_hom : ⇑coe_hom = coe := rfl instance : partial_order enat := { le := (≤), le_refl := λ x, ⟨id, λ _, le_refl _⟩, le_trans := λ x y z ⟨hxy₁, hxy₂⟩ ⟨hyz₁, hyz₂⟩, ⟨hxy₁ ∘ hyz₁, λ _, le_trans (hxy₂ _) (hyz₂ _)⟩, le_antisymm := λ x y ⟨hxy₁, hxy₂⟩ ⟨hyx₁, hyx₂⟩, part.ext' ⟨hyx₁, hxy₁⟩ (λ _ _, le_antisymm (hxy₂ _) (hyx₂ _)) } lemma lt_def (x y : enat) : x < y ↔ ∃ (hx : x.dom), ∀ (hy : y.dom), x.get hx < y.get hy := begin rw [lt_iff_le_not_le, le_def, le_def, not_exists], split, { rintro ⟨⟨hyx, H⟩, h⟩, by_cases hx : x.dom, { use hx, intro hy, specialize H hy, specialize h (λ _, hy), rw not_forall at h, cases h with hx' h, rw not_le at h, exact h }, { specialize h (λ hx', (hx hx').elim), rw not_forall at h, cases h with hx' h, exact (hx hx').elim } }, { rintro ⟨hx, H⟩, exact ⟨⟨λ _, hx, λ hy, (H hy).le⟩, λ hxy h, not_lt_of_le (h _) (H _)⟩ } end @[simp, norm_cast] lemma coe_le_coe {x y : ℕ} : (x : enat) ≤ y ↔ x ≤ y := by { rw [← some_eq_coe, ← some_eq_coe], exact ⟨λ ⟨_, h⟩, h trivial, λ h, ⟨λ _, trivial, λ _, h⟩⟩ } @[simp, norm_cast] lemma coe_lt_coe {x y : ℕ} : (x : enat) < y ↔ x < y := by rw [lt_iff_le_not_le, lt_iff_le_not_le, coe_le_coe, coe_le_coe] @[simp] lemma get_le_get {x y : enat} {hx : x.dom} {hy : y.dom} : x.get hx ≤ y.get hy ↔ x ≤ y := by conv { to_lhs, rw [← coe_le_coe, coe_get, coe_get]} lemma le_coe_iff (x : enat) (n : ℕ) : x ≤ n ↔ ∃ h : x.dom, x.get h ≤ n := begin rw [← some_eq_coe], show (∃ (h : true → x.dom), _) ↔ ∃ h : x.dom, x.get h ≤ n, simp only [forall_prop_of_true, some_eq_coe, dom_coe, get_coe'], split; rintro ⟨_, _⟩; refine ⟨_, _⟩; intros; try { assumption } end lemma lt_coe_iff (x : enat) (n : ℕ) : x < n ↔ ∃ h : x.dom, x.get h < n := by simp only [lt_def, forall_prop_of_true, get_coe', dom_coe] lemma coe_le_iff (n : ℕ) (x : enat) : (n : enat) ≤ x ↔ ∀ h : x.dom, n ≤ x.get h := begin rw [← some_eq_coe], simp only [le_def, exists_prop_of_true, dom_some, forall_true_iff], refl, end lemma coe_lt_iff (n : ℕ) (x : enat) : (n : enat) < x ↔ ∀ h : x.dom, n < x.get h := begin rw [← some_eq_coe], simp only [lt_def, exists_prop_of_true, dom_some, forall_true_iff], refl, end protected lemma zero_lt_one : (0 : enat) < 1 := by { norm_cast, norm_num } instance semilattice_sup_bot : semilattice_sup_bot enat := { sup := (⊔), bot := (⊥), bot_le := λ _, ⟨λ _, trivial, λ _, nat.zero_le _⟩, le_sup_left := λ _ _, ⟨and.left, λ _, le_sup_left⟩, le_sup_right := λ _ _, ⟨and.right, λ _, le_sup_right⟩, sup_le := λ x y z ⟨hx₁, hx₂⟩ ⟨hy₁, hy₂⟩, ⟨λ hz, ⟨hx₁ hz, hy₁ hz⟩, λ _, sup_le (hx₂ _) (hy₂ _)⟩, ..enat.partial_order } instance order_top : order_top enat := { top := (⊤), le_top := λ x, ⟨λ h, false.elim h, λ hy, false.elim hy⟩, ..enat.semilattice_sup_bot } lemma dom_of_lt {x y : enat} : x < y → x.dom := enat.cases_on x not_top_lt $ λ _ _, dom_coe _ lemma top_eq_none : (⊤ : enat) = none := rfl @[simp] lemma coe_lt_top (x : ℕ) : (x : enat) < ⊤ := ne.lt_top (λ h, absurd (congr_arg dom h) $ by simpa only [dom_coe] using true_ne_false) @[simp] lemma coe_ne_top (x : ℕ) : (x : enat) ≠ ⊤ := ne_of_lt (coe_lt_top x) lemma ne_top_iff {x : enat} : x ≠ ⊤ ↔ ∃ (n : ℕ), x = n := by simpa only [← some_eq_coe] using part.ne_none_iff lemma ne_top_iff_dom {x : enat} : x ≠ ⊤ ↔ x.dom := by classical; exact not_iff_comm.1 part.eq_none_iff'.symm lemma ne_top_of_lt {x y : enat} (h : x < y) : x ≠ ⊤ := ne_of_lt $ lt_of_lt_of_le h le_top lemma eq_top_iff_forall_lt (x : enat) : x = ⊤ ↔ ∀ n : ℕ, (n : enat) < x := begin split, { rintro rfl n, exact coe_lt_top _ }, { contrapose!, rw ne_top_iff, rintro ⟨n, rfl⟩, exact ⟨n, irrefl _⟩ } end lemma eq_top_iff_forall_le (x : enat) : x = ⊤ ↔ ∀ n : ℕ, (n : enat) ≤ x := (eq_top_iff_forall_lt x).trans ⟨λ h n, (h n).le, λ h n, lt_of_lt_of_le (coe_lt_coe.mpr n.lt_succ_self) (h (n + 1))⟩ lemma pos_iff_one_le {x : enat} : 0 < x ↔ 1 ≤ x := enat.cases_on x (by simp only [iff_true, le_top, coe_lt_top, ← @nat.cast_zero enat]) $ λ n, by { rw [← nat.cast_zero, ← nat.cast_one, enat.coe_lt_coe, enat.coe_le_coe], refl } noncomputable instance : linear_order enat := { le_total := λ x y, enat.cases_on x (or.inr le_top) (enat.cases_on y (λ _, or.inl le_top) (λ x y, (le_total x y).elim (or.inr ∘ coe_le_coe.2) (or.inl ∘ coe_le_coe.2))), decidable_le := classical.dec_rel _, ..enat.partial_order } noncomputable instance : bounded_lattice enat := { inf := min, inf_le_left := min_le_left, inf_le_right := min_le_right, le_inf := λ _ _ _, le_min, ..enat.order_top, ..enat.semilattice_sup_bot } lemma sup_eq_max {a b : enat} : a ⊔ b = max a b := le_antisymm (sup_le (le_max_left _ _) (le_max_right _ _)) (max_le le_sup_left le_sup_right) lemma inf_eq_min {a b : enat} : a ⊓ b = min a b := rfl instance : ordered_add_comm_monoid enat := { add_le_add_left := λ a b ⟨h₁, h₂⟩ c, enat.cases_on c (by simp) (λ c, ⟨λ h, and.intro (dom_coe _) (h₁ h.2), λ h, by simpa only [coe_add_get] using add_le_add_left (h₂ _) c⟩), ..enat.linear_order, ..enat.add_comm_monoid } instance : canonically_ordered_add_monoid enat := { le_iff_exists_add := λ a b, enat.cases_on b (iff_of_true le_top ⟨⊤, (add_top _).symm⟩) (λ b, enat.cases_on a (iff_of_false (not_le_of_gt (coe_lt_top _)) (not_exists.2 (λ x, ne_of_lt (by rw [top_add]; exact coe_lt_top _)))) (λ a, ⟨λ h, ⟨(b - a : ℕ), by rw [← nat.cast_add, coe_inj, add_comm, tsub_add_cancel_of_le (coe_le_coe.1 h)]⟩, (λ ⟨c, hc⟩, enat.cases_on c (λ hc, hc.symm ▸ show (a : enat) ≤ a + ⊤, by rw [add_top]; exact le_top) (λ c (hc : (b : enat) = a + c), coe_le_coe.2 (by rw [← nat.cast_add, coe_inj] at hc; rw hc; exact nat.le_add_right _ _)) hc)⟩)), ..enat.semilattice_sup_bot, ..enat.ordered_add_comm_monoid } protected lemma add_lt_add_right {x y z : enat} (h : x < y) (hz : z ≠ ⊤) : x + z < y + z := begin rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, rcases ne_top_iff.mp hz with ⟨k, rfl⟩, induction y using enat.cases_on with n, { rw [top_add], apply_mod_cast coe_lt_top }, norm_cast at h, apply_mod_cast add_lt_add_right h end protected lemma add_lt_add_iff_right {x y z : enat} (hz : z ≠ ⊤) : x + z < y + z ↔ x < y := ⟨lt_of_add_lt_add_right, λ h, enat.add_lt_add_right h hz⟩ protected lemma add_lt_add_iff_left {x y z : enat} (hz : z ≠ ⊤) : z + x < z + y ↔ x < y := by rw [add_comm z, add_comm z, enat.add_lt_add_iff_right hz] protected lemma lt_add_iff_pos_right {x y : enat} (hx : x ≠ ⊤) : x < x + y ↔ 0 < y := by { conv_rhs { rw [← enat.add_lt_add_iff_left hx] }, rw [add_zero] } lemma lt_add_one {x : enat} (hx : x ≠ ⊤) : x < x + 1 := by { rw [enat.lt_add_iff_pos_right hx], norm_cast, norm_num } lemma le_of_lt_add_one {x y : enat} (h : x < y + 1) : x ≤ y := begin induction y using enat.cases_on with n, apply le_top, rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, apply_mod_cast nat.le_of_lt_succ, apply_mod_cast h end lemma add_one_le_of_lt {x y : enat} (h : x < y) : x + 1 ≤ y := begin induction y using enat.cases_on with n, apply le_top, rcases ne_top_iff.mp (ne_top_of_lt h) with ⟨m, rfl⟩, apply_mod_cast nat.succ_le_of_lt, apply_mod_cast h end lemma add_one_le_iff_lt {x y : enat} (hx : x ≠ ⊤) : x + 1 ≤ y ↔ x < y := begin split, swap, exact add_one_le_of_lt, intro h, rcases ne_top_iff.mp hx with ⟨m, rfl⟩, induction y using enat.cases_on with n, apply coe_lt_top, apply_mod_cast nat.lt_of_succ_le, apply_mod_cast h end lemma lt_add_one_iff_lt {x y : enat} (hx : x ≠ ⊤) : x < y + 1 ↔ x ≤ y := begin split, exact le_of_lt_add_one, intro h, rcases ne_top_iff.mp hx with ⟨m, rfl⟩, induction y using enat.cases_on with n, { rw [top_add], apply coe_lt_top }, apply_mod_cast nat.lt_succ_of_le, apply_mod_cast h end lemma add_eq_top_iff {a b : enat} : a + b = ⊤ ↔ a = ⊤ ∨ b = ⊤ := by apply enat.cases_on a; apply enat.cases_on b; simp; simp only [(nat.cast_add _ _).symm, enat.coe_ne_top]; simp protected lemma add_right_cancel_iff {a b c : enat} (hc : c ≠ ⊤) : a + c = b + c ↔ a = b := begin rcases ne_top_iff.1 hc with ⟨c, rfl⟩, apply enat.cases_on a; apply enat.cases_on b; simp [add_eq_top_iff, coe_ne_top, @eq_comm _ (⊤ : enat)]; simp only [(nat.cast_add _ _).symm, add_left_cancel_iff, enat.coe_inj, add_comm]; tauto end protected lemma add_left_cancel_iff {a b c : enat} (ha : a ≠ ⊤) : a + b = a + c ↔ b = c := by rw [add_comm a, add_comm a, enat.add_right_cancel_iff ha] section with_top /-- Computably converts an `enat` to a `with_top ℕ`. -/ def to_with_top (x : enat) [decidable x.dom] : with_top ℕ := x.to_option lemma to_with_top_top : to_with_top ⊤ = ⊤ := rfl @[simp] lemma to_with_top_top' {h : decidable (⊤ : enat).dom} : to_with_top ⊤ = ⊤ := by convert to_with_top_top lemma to_with_top_zero : to_with_top 0 = 0 := rfl @[simp] lemma to_with_top_zero' {h : decidable (0 : enat).dom} : to_with_top 0 = 0 := by convert to_with_top_zero lemma to_with_top_some (n : ℕ) : to_with_top (some n) = n := rfl lemma to_with_top_coe (n : ℕ) {_ : decidable (n : enat).dom} : to_with_top n = n := by { simp only [← some_eq_coe, ← to_with_top_some], congr } @[simp] lemma to_with_top_coe' (n : ℕ) {h : decidable (n : enat).dom} : to_with_top (n : enat) = n := by convert to_with_top_coe n @[simp] lemma to_with_top_le {x y : enat} : Π [decidable x.dom] [decidable y.dom], by exactI to_with_top x ≤ to_with_top y ↔ x ≤ y := enat.cases_on y (by simp) (enat.cases_on x (by simp) (by intros; simp)) @[simp] lemma to_with_top_lt {x y : enat} [decidable x.dom] [decidable y.dom] : to_with_top x < to_with_top y ↔ x < y := lt_iff_lt_of_le_iff_le to_with_top_le end with_top section with_top_equiv open_locale classical @[simp] lemma to_with_top_add {x y : enat} : to_with_top (x + y) = to_with_top x + to_with_top y := begin apply enat.cases_on y; apply enat.cases_on x, { simp }, { simp }, { simp }, -- not sure why `simp` can't do this { intros, rw [to_with_top_coe', to_with_top_coe'], norm_cast, exact to_with_top_coe' _ } end /-- `equiv` between `enat` and `with_top ℕ` (for the order isomorphism see `with_top_order_iso`). -/ noncomputable def with_top_equiv : enat ≃ with_top ℕ := { to_fun := λ x, to_with_top x, inv_fun := λ x, match x with (option.some n) := coe n | none := ⊤ end, left_inv := λ x, by apply enat.cases_on x; intros; simp; refl, right_inv := λ x, by cases x; simp [with_top_equiv._match_1]; refl } @[simp] lemma with_top_equiv_top : with_top_equiv ⊤ = ⊤ := to_with_top_top' @[simp] lemma with_top_equiv_coe (n : nat) : with_top_equiv n = n := to_with_top_coe' _ @[simp] lemma with_top_equiv_zero : with_top_equiv 0 = 0 := by simpa only [nat.cast_zero] using with_top_equiv_coe 0 @[simp] lemma with_top_equiv_le {x y : enat} : with_top_equiv x ≤ with_top_equiv y ↔ x ≤ y := to_with_top_le @[simp] lemma with_top_equiv_lt {x y : enat} : with_top_equiv x < with_top_equiv y ↔ x < y := to_with_top_lt /-- `to_with_top` induces an order isomorphism between `enat` and `with_top ℕ`. -/ noncomputable def with_top_order_iso : enat ≃o with_top ℕ := { map_rel_iff' := λ _ _, with_top_equiv_le, .. with_top_equiv} @[simp] lemma with_top_equiv_symm_top : with_top_equiv.symm ⊤ = ⊤ := rfl @[simp] lemma with_top_equiv_symm_coe (n : nat) : with_top_equiv.symm n = n := rfl @[simp] lemma with_top_equiv_symm_zero : with_top_equiv.symm 0 = 0 := rfl @[simp] lemma with_top_equiv_symm_le {x y : with_top ℕ} : with_top_equiv.symm x ≤ with_top_equiv.symm y ↔ x ≤ y := by rw ← with_top_equiv_le; simp @[simp] lemma with_top_equiv_symm_lt {x y : with_top ℕ} : with_top_equiv.symm x < with_top_equiv.symm y ↔ x < y := by rw ← with_top_equiv_lt; simp /-- `to_with_top` induces an additive monoid isomorphism between `enat` and `with_top ℕ`. -/ noncomputable def with_top_add_equiv : enat ≃+ with_top ℕ := { map_add' := λ x y, by simp only [with_top_equiv]; convert to_with_top_add, ..with_top_equiv} end with_top_equiv lemma lt_wf : well_founded ((<) : enat → enat → Prop) := show well_founded (λ a b : enat, a < b), by haveI := classical.dec; simp only [to_with_top_lt.symm] {eta := ff}; exact inv_image.wf _ (with_top.well_founded_lt nat.lt_wf) instance : has_well_founded enat := ⟨(<), lt_wf⟩ section find variables (P : ℕ → Prop) [decidable_pred P] /-- The smallest `enat` satisfying a (decidable) predicate `P : ℕ → Prop` -/ def find : enat := ⟨∃ n, P n, nat.find⟩ @[simp] lemma find_get (h : (find P).dom) : (find P).get h = nat.find h := rfl lemma find_dom (h : ∃ n, P n) : (find P).dom := h lemma lt_find (n : ℕ) (h : ∀ m ≤ n, ¬P m) : (n : enat) < find P := begin rw coe_lt_iff, intro h', rw find_get, have := @nat.find_spec P _ h', contrapose! this, exact h _ this end lemma lt_find_iff (n : ℕ) : (n : enat) < find P ↔ (∀ m ≤ n, ¬P m) := begin refine ⟨_, lt_find P n⟩, intros h m hm, by_cases H : (find P).dom, { apply nat.find_min H, rw coe_lt_iff at h, specialize h H, exact lt_of_le_of_lt hm h }, { exact not_exists.mp H m } end lemma find_le (n : ℕ) (h : P n) : find P ≤ n := by { rw le_coe_iff, refine ⟨⟨_, h⟩, @nat.find_min' P _ _ _ h⟩ } lemma find_eq_top_iff : find P = ⊤ ↔ ∀ n, ¬P n := (eq_top_iff_forall_lt _).trans ⟨λ h n, (lt_find_iff P n).mp (h n) _ le_rfl, λ h n, lt_find P n $ λ _ _, h _⟩ end find noncomputable instance : linear_ordered_add_comm_monoid_with_top enat := { top_add' := top_add, .. enat.linear_order, .. enat.ordered_add_comm_monoid, .. enat.order_top } end enat
ac85c60078f77fb781651ae17dcfbc7bd8e7435c
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/padics/padic_numbers.lean
0601a7efe26a655bb82ec520322b7b9db35a16fa
[ "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
32,419
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import data.padics.padic_norm import analysis.normed_space.basic /-! # p-adic numbers This file defines the p-adic numbers (rationals) ℚ_p as the completion of ℚ with respect to the p-adic norm. We show that the p-adic norm on ℚ extends to ℚ_p, that ℚ is embedded in ℚ_p, and that ℚ_p is Cauchy complete. ## Important definitions * `padic` : the type of p-adic numbers * `padic_norm_e` : the rational valued p-adic norm on ℚ_p ## Notation We introduce the notation ℚ_[p] for the p-adic numbers. ## Implementation notes Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically by taking `[fact (prime p)]` as a type class argument. We use the same concrete Cauchy sequence construction that is used to construct ℝ. ℚ_p inherits a field structure from this construction. The extension of the norm on ℚ to ℚ_p is *not* analogous to extending the absolute value to ℝ, and hence the proof that ℚ_p is complete is different from the proof that ℝ is complete. A small special-purpose simplification tactic, `padic_index_simp`, is used to manipulate sequence indices in the proof that the norm extends. `padic_norm_e` is the rational-valued p-adic norm on ℚ_p. To instantiate ℚ_p as a normed field, we must cast this into a ℝ-valued norm. The ℝ-valued norm, using notation ∥ ∥ from normed spaces, is the canonical representation of this norm. Coercions from ℚ to ℚ_p are set up to work with the `norm_cast` tactic. ## References * [F. Q. Gouêva, *p-adic numbers*][gouvea1997] * [R. Y. Lewis, *A formal proof of Hensel's lemma over the p-adic integers*][lewis2019] * <https://en.wikipedia.org/wiki/P-adic_number> ## Tags p-adic, p adic, padic, norm, valuation, cauchy, completion, p-adic completion -/ noncomputable theory open_locale classical open nat multiplicity padic_norm cau_seq cau_seq.completion metric /-- The type of Cauchy sequences of rationals with respect to the p-adic norm. -/ @[reducible] def padic_seq (p : ℕ) [fact p.prime] := cau_seq _ (padic_norm p) namespace padic_seq section variables {p : ℕ} [fact p.prime] /-- The p-adic norm of the entries of a nonzero Cauchy sequence of rationals is eventually constant. -/ lemma stationary {f : cau_seq ℚ (padic_norm p)} (hf : ¬ f ≈ 0) : ∃ N, ∀ m n, N ≤ m → N ≤ n → padic_norm p (f n) = padic_norm p (f m) := have ∃ ε > 0, ∃ N1, ∀ j ≥ N1, ε ≤ padic_norm p (f j), from cau_seq.abv_pos_of_not_lim_zero $ not_lim_zero_of_not_congr_zero hf, let ⟨ε, hε, N1, hN1⟩ := this, ⟨N2, hN2⟩ := cau_seq.cauchy₂ f hε in ⟨ max N1 N2, λ n m hn hm, have padic_norm p (f n - f m) < ε, from hN2 _ _ (max_le_iff.1 hn).2 (max_le_iff.1 hm).2, have padic_norm p (f n - f m) < padic_norm p (f n), from lt_of_lt_of_le this $ hN1 _ (max_le_iff.1 hn).1, have padic_norm p (f n - f m) < max (padic_norm p (f n)) (padic_norm p (f m)), from lt_max_iff.2 (or.inl this), begin by_contradiction hne, rw ←padic_norm.neg p (f m) at hne, have hnam := add_eq_max_of_ne p hne, rw [padic_norm.neg, max_comm] at hnam, rw [←hnam, sub_eq_add_neg, add_comm] at this, apply _root_.lt_irrefl _ this end ⟩ /-- For all n ≥ stationary_point f hf, the p-adic norm of f n is the same. -/ def stationary_point {f : padic_seq p} (hf : ¬ f ≈ 0) : ℕ := classical.some $ stationary hf lemma stationary_point_spec {f : padic_seq p} (hf : ¬ f ≈ 0) : ∀ {m n}, m ≥ stationary_point hf → n ≥ stationary_point hf → padic_norm p (f n) = padic_norm p (f m) := classical.some_spec $ stationary hf /-- Since the norm of the entries of a Cauchy sequence is eventually stationary, we can lift the norm to sequences. -/ def norm (f : padic_seq p) : ℚ := if hf : f ≈ 0 then 0 else padic_norm p (f (stationary_point hf)) lemma norm_zero_iff (f : padic_seq p) : f.norm = 0 ↔ f ≈ 0 := begin constructor, { intro h, by_contradiction hf, unfold norm at h, split_ifs at h, apply hf, intros ε hε, existsi stationary_point hf, intros j hj, have heq := stationary_point_spec hf (le_refl _) hj, simpa [h, heq] }, { intro h, simp [norm, h] } end end section embedding open cau_seq variables {p : ℕ} [fact p.prime] lemma equiv_zero_of_val_eq_of_equiv_zero {f g : padic_seq p} (h : ∀ k, padic_norm p (f k) = padic_norm p (g k)) (hf : f ≈ 0) : g ≈ 0 := λ ε hε, let ⟨i, hi⟩ := hf _ hε in ⟨i, λ j hj, by simpa [h] using hi _ hj⟩ lemma norm_nonzero_of_not_equiv_zero {f : padic_seq p} (hf : ¬ f ≈ 0) : f.norm ≠ 0 := hf ∘ f.norm_zero_iff.1 lemma norm_eq_norm_app_of_nonzero {f : padic_seq p} (hf : ¬ f ≈ 0) : ∃ k, f.norm = padic_norm p k ∧ k ≠ 0 := have heq : f.norm = padic_norm p (f $ stationary_point hf), by simp [norm, hf], ⟨f $ stationary_point hf, heq, λ h, norm_nonzero_of_not_equiv_zero hf (by simpa [h] using heq)⟩ lemma not_lim_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ lim_zero (const (padic_norm p) q) := λ h', hq $ const_lim_zero.1 h' lemma not_equiv_zero_const_of_nonzero {q : ℚ} (hq : q ≠ 0) : ¬ (const (padic_norm p) q) ≈ 0 := λ h : lim_zero (const (padic_norm p) q - 0), not_lim_zero_const_of_nonzero hq $ by simpa using h lemma norm_nonneg (f : padic_seq p) : f.norm ≥ 0 := if hf : f ≈ 0 then by simp [hf, norm] else by simp [norm, hf, padic_norm.nonneg] /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_left_left {f : padic_seq p} (hf : ¬ f ≈ 0) (v2 v3 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max (stationary_point hf) (max v2 v3))) := let i := max (stationary_point hf) (max v2 v3) in begin apply stationary_point_spec hf, { apply le_max_left }, { apply le_refl } end /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_left {f : padic_seq p} (hf : ¬ f ≈ 0) (v1 v3 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max v1 (max (stationary_point hf) v3))) := let i := max v1 (max (stationary_point hf) v3) in begin apply stationary_point_spec hf, { apply le_trans, { apply le_max_left _ v3 }, { apply le_max_right } }, { apply le_refl } end /-- An auxiliary lemma for manipulating sequence indices. -/ lemma lift_index_right {f : padic_seq p} (hf : ¬ f ≈ 0) (v1 v2 : ℕ) : padic_norm p (f (stationary_point hf)) = padic_norm p (f (max v1 (max v2 (stationary_point hf)))) := let i := max v1 (max v2 (stationary_point hf)) in begin apply stationary_point_spec hf, { apply le_trans, { apply le_max_right v2 }, { apply le_max_right } }, { apply le_refl } end end embedding end padic_seq section open padic_seq private meta def index_simp_core (hh hf hg : expr) (at_ : interactive.loc := interactive.loc.ns [none]) : tactic unit := do [v1, v2, v3] ← [hh, hf, hg].mmap (λ n, tactic.mk_app ``stationary_point [n] <|> return n), e1 ← tactic.mk_app ``lift_index_left_left [hh, v2, v3] <|> return `(true), e2 ← tactic.mk_app ``lift_index_left [hf, v1, v3] <|> return `(true), e3 ← tactic.mk_app ``lift_index_right [hg, v1, v2] <|> return `(true), sl ← [e1, e2, e3].mfoldl (λ s e, simp_lemmas.add s e) simp_lemmas.mk, when at_.include_goal (tactic.simp_target sl), hs ← at_.get_locals, hs.mmap' (tactic.simp_hyp sl []) /-- This is a special-purpose tactic that lifts padic_norm (f (stationary_point f)) to padic_norm (f (max _ _ _)). -/ meta def tactic.interactive.padic_index_simp (l : interactive.parse interactive.types.pexpr_list) (at_ : interactive.parse interactive.types.location) : tactic unit := do [h, f, g] ← l.mmap tactic.i_to_expr, index_simp_core h f g at_ end namespace padic_seq section embedding open cau_seq variables {p : ℕ} [hp : fact p.prime] include hp lemma norm_mul (f g : padic_seq p) : (f * g).norm = f.norm * g.norm := if hf : f ≈ 0 then have hg : f * g ≈ 0, from mul_equiv_zero' _ hf, by simp [hf, hg, norm] else if hg : g ≈ 0 then have hf : f * g ≈ 0, from mul_equiv_zero _ hg, by simp [hf, hg, norm] else have hfg : ¬ f * g ≈ 0, by apply mul_not_equiv_zero; assumption, begin unfold norm, split_ifs, padic_index_simp [hfg, hf, hg], apply padic_norm.mul end lemma eq_zero_iff_equiv_zero (f : padic_seq p) : mk f = 0 ↔ f ≈ 0 := mk_eq lemma ne_zero_iff_nequiv_zero (f : padic_seq p) : mk f ≠ 0 ↔ ¬ f ≈ 0 := not_iff_not.2 (eq_zero_iff_equiv_zero _) lemma norm_const (q : ℚ) : norm (const (padic_norm p) q) = padic_norm p q := if hq : q = 0 then have (const (padic_norm p) q) ≈ 0, by simp [hq]; apply setoid.refl (const (padic_norm p) 0), by subst hq; simp [norm, this] else have ¬ (const (padic_norm p) q) ≈ 0, from not_equiv_zero_const_of_nonzero hq, by simp [norm, this] lemma norm_image (a : padic_seq p) (ha : ¬ a ≈ 0) : (∃ (n : ℤ), a.norm = ↑p ^ (-n)) := let ⟨k, hk, hk'⟩ := norm_eq_norm_app_of_nonzero ha in by simpa [hk] using padic_norm.image p hk' lemma norm_one : norm (1 : padic_seq p) = 1 := have h1 : ¬ (1 : padic_seq p) ≈ 0, from one_not_equiv_zero _, by simp [h1, norm, hp.one_lt] private lemma norm_eq_of_equiv_aux {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) (h : padic_norm p (f (stationary_point hf)) ≠ padic_norm p (g (stationary_point hg))) (hgt : padic_norm p (f (stationary_point hf)) > padic_norm p (g (stationary_point hg))) : false := begin have hpn : padic_norm p (f (stationary_point hf)) - padic_norm p (g (stationary_point hg)) > 0, from sub_pos_of_lt hgt, cases hfg _ hpn with N hN, let i := max N (max (stationary_point hf) (stationary_point hg)), have hi : i ≥ N, from le_max_left _ _, have hN' := hN _ hi, padic_index_simp [N, hf, hg] at hN' h hgt, have hpne : padic_norm p (f i) ≠ padic_norm p (-(g i)), by rwa [ ←padic_norm.neg p (g i)] at h, let hpnem := add_eq_max_of_ne p hpne, have hpeq : padic_norm p ((f - g) i) = max (padic_norm p (f i)) (padic_norm p (g i)), { rwa padic_norm.neg at hpnem }, rw [hpeq, max_eq_left_of_lt hgt] at hN', have : padic_norm p (f i) < padic_norm p (f i), { apply lt_of_lt_of_le hN', apply sub_le_self, apply padic_norm.nonneg }, exact lt_irrefl _ this end private lemma norm_eq_of_equiv {f g : padic_seq p} (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) (hfg : f ≈ g) : padic_norm p (f (stationary_point hf)) = padic_norm p (g (stationary_point hg)) := begin by_contradiction h, cases (decidable.em (padic_norm p (f (stationary_point hf)) > padic_norm p (g (stationary_point hg)))) with hgt hngt, { exact norm_eq_of_equiv_aux hf hg hfg h hgt }, { apply norm_eq_of_equiv_aux hg hf (setoid.symm hfg) (ne.symm h), apply lt_of_le_of_ne, apply le_of_not_gt hngt, apply h } end theorem norm_equiv {f g : padic_seq p} (hfg : f ≈ g) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from setoid.trans (setoid.symm hfg) hf, by simp [norm, hf, hg] else have hg : ¬ g ≈ 0, from hf ∘ setoid.trans hfg, by unfold norm; split_ifs; exact norm_eq_of_equiv hf hg hfg private lemma norm_nonarchimedean_aux {f g : padic_seq p} (hfg : ¬ f + g ≈ 0) (hf : ¬ f ≈ 0) (hg : ¬ g ≈ 0) : (f + g).norm ≤ max (f.norm) (g.norm) := begin unfold norm, split_ifs, padic_index_simp [hfg, hf, hg], apply padic_norm.nonarchimedean end theorem norm_nonarchimedean (f g : padic_seq p) : (f + g).norm ≤ max (f.norm) (g.norm) := if hfg : f + g ≈ 0 then have 0 ≤ max (f.norm) (g.norm), from le_max_left_of_le (norm_nonneg _), by simpa [hfg, norm] else if hf : f ≈ 0 then have hfg' : f + g ≈ g, { change lim_zero (f - 0) at hf, show lim_zero (f + g - g), by simpa using hf }, have hcfg : (f + g).norm = g.norm, from norm_equiv hfg', have hcl : f.norm = 0, from (norm_zero_iff f).2 hf, have max (f.norm) (g.norm) = g.norm, by rw hcl; exact max_eq_right (norm_nonneg _), by rw [this, hcfg] else if hg : g ≈ 0 then have hfg' : f + g ≈ f, { change lim_zero (g - 0) at hg, show lim_zero (f + g - f), by simpa [add_sub_cancel'] using hg }, have hcfg : (f + g).norm = f.norm, from norm_equiv hfg', have hcl : g.norm = 0, from (norm_zero_iff g).2 hg, have max (f.norm) (g.norm) = f.norm, by rw hcl; exact max_eq_left (norm_nonneg _), by rw [this, hcfg] else norm_nonarchimedean_aux hfg hf hg lemma norm_eq {f g : padic_seq p} (h : ∀ k, padic_norm p (f k) = padic_norm p (g k)) : f.norm = g.norm := if hf : f ≈ 0 then have hg : g ≈ 0, from equiv_zero_of_val_eq_of_equiv_zero h hf, by simp [hf, hg, norm] else have hg : ¬ g ≈ 0, from λ hg, hf $ equiv_zero_of_val_eq_of_equiv_zero (by simp [h]) hg, begin simp [hg, hf, norm], let i := max (stationary_point hf) (stationary_point hg), have hpf : padic_norm p (f (stationary_point hf)) = padic_norm p (f i), { apply stationary_point_spec, apply le_max_left, apply le_refl }, have hpg : padic_norm p (g (stationary_point hg)) = padic_norm p (g i), { apply stationary_point_spec, apply le_max_right, apply le_refl }, rw [hpf, hpg, h] end lemma norm_neg (a : padic_seq p) : (-a).norm = a.norm := norm_eq $ by simp lemma norm_eq_of_add_equiv_zero {f g : padic_seq p} (h : f + g ≈ 0) : f.norm = g.norm := have lim_zero (f + g - 0), from h, have f ≈ -g, from show lim_zero (f - (-g)), by simpa, have f.norm = (-g).norm, from norm_equiv this, by simpa [norm_neg] using this lemma add_eq_max_of_ne {f g : padic_seq p} (hfgne : f.norm ≠ g.norm) : (f + g).norm = max f.norm g.norm := have hfg : ¬f + g ≈ 0, from mt norm_eq_of_add_equiv_zero hfgne, if hf : f ≈ 0 then have lim_zero (f - 0), from hf, have f + g ≈ g, from show lim_zero ((f + g) - g), by simpa, have h1 : (f+g).norm = g.norm, from norm_equiv this, have h2 : f.norm = 0, from (norm_zero_iff _).2 hf, by rw [h1, h2]; rw max_eq_right (norm_nonneg _) else if hg : g ≈ 0 then have lim_zero (g - 0), from hg, have f + g ≈ f, from show lim_zero ((f + g) - f), by rw [add_sub_cancel']; simpa, have h1 : (f+g).norm = f.norm, from norm_equiv this, have h2 : g.norm = 0, from (norm_zero_iff _).2 hg, by rw [h1, h2]; rw max_eq_left (norm_nonneg _) else begin unfold norm at ⊢ hfgne, split_ifs at ⊢ hfgne, padic_index_simp [hfg, hf, hg] at ⊢ hfgne, apply padic_norm.add_eq_max_of_ne, simpa [hf, hg, norm] using hfgne end end embedding end padic_seq /-- The p-adic numbers `Q_[p]` are the Cauchy completion of `ℚ` with respect to the p-adic norm. -/ def padic (p : ℕ) [fact p.prime] := @cau_seq.completion.Cauchy _ _ _ _ (padic_norm p) _ notation `ℚ_[` p `]` := padic p namespace padic section completion variables {p : ℕ} [fact p.prime] /-- The discrete field structure on ℚ_p is inherited from the Cauchy completion construction. -/ instance field : field (ℚ_[p]) := cau_seq.completion.field instance : inhabited ℚ_[p] := ⟨0⟩ -- short circuits instance : has_zero ℚ_[p] := by apply_instance instance : has_one ℚ_[p] := by apply_instance instance : has_add ℚ_[p] := by apply_instance instance : has_mul ℚ_[p] := by apply_instance instance : has_sub ℚ_[p] := by apply_instance instance : has_neg ℚ_[p] := by apply_instance instance : has_div ℚ_[p] := by apply_instance instance : add_comm_group ℚ_[p] := by apply_instance instance : comm_ring ℚ_[p] := by apply_instance /-- Builds the equivalence class of a Cauchy sequence of rationals. -/ def mk : padic_seq p → ℚ_[p] := quotient.mk end completion section completion variables (p : ℕ) [fact p.prime] lemma mk_eq {f g : padic_seq p} : mk f = mk g ↔ f ≈ g := quotient.eq /-- Embeds the rational numbers in the p-adic numbers. -/ def of_rat : ℚ → ℚ_[p] := cau_seq.completion.of_rat @[simp] lemma of_rat_add : ∀ (x y : ℚ), of_rat p (x + y) = of_rat p x + of_rat p y := cau_seq.completion.of_rat_add @[simp] lemma of_rat_neg : ∀ (x : ℚ), of_rat p (-x) = -of_rat p x := cau_seq.completion.of_rat_neg @[simp] lemma of_rat_mul : ∀ (x y : ℚ), of_rat p (x * y) = of_rat p x * of_rat p y := cau_seq.completion.of_rat_mul @[simp] lemma of_rat_sub : ∀ (x y : ℚ), of_rat p (x - y) = of_rat p x - of_rat p y := cau_seq.completion.of_rat_sub @[simp] lemma of_rat_div : ∀ (x y : ℚ), of_rat p (x / y) = of_rat p x / of_rat p y := cau_seq.completion.of_rat_div @[simp] lemma of_rat_one : of_rat p 1 = 1 := rfl @[simp] lemma of_rat_zero : of_rat p 0 = 0 := rfl @[simp] lemma cast_eq_of_rat_of_nat (n : ℕ) : (↑n : ℚ_[p]) = of_rat p n := begin induction n with n ih, { refl }, { simpa using ih } end @[simp] lemma cast_eq_of_rat_of_int (n : ℤ) : ↑n = of_rat p n := by induction n; simp lemma cast_eq_of_rat : ∀ (q : ℚ), (↑q : ℚ_[p]) = of_rat p q | ⟨n, d, h1, h2⟩ := show ↑n / ↑d = _, from have (⟨n, d, h1, h2⟩ : ℚ) = rat.mk n d, from rat.num_denom', by simp [this, rat.mk_eq_div, of_rat_div] @[norm_cast] lemma coe_add : ∀ {x y : ℚ}, (↑(x + y) : ℚ_[p]) = ↑x + ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_neg : ∀ {x : ℚ}, (↑(-x) : ℚ_[p]) = -↑x := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_mul : ∀ {x y : ℚ}, (↑(x * y) : ℚ_[p]) = ↑x * ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_sub : ∀ {x y : ℚ}, (↑(x - y) : ℚ_[p]) = ↑x - ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_div : ∀ {x y : ℚ}, (↑(x / y) : ℚ_[p]) = ↑x / ↑y := by simp [cast_eq_of_rat] @[norm_cast] lemma coe_one : (↑1 : ℚ_[p]) = 1 := rfl @[norm_cast] lemma coe_zero : (↑0 : ℚ_[p]) = 0 := rfl lemma const_equiv {q r : ℚ} : const (padic_norm p) q ≈ const (padic_norm p) r ↔ q = r := ⟨ λ heq : lim_zero (const (padic_norm p) (q - r)), eq_of_sub_eq_zero $ const_lim_zero.1 heq, λ heq, by rw heq; apply setoid.refl _ ⟩ lemma of_rat_eq {q r : ℚ} : of_rat p q = of_rat p r ↔ q = r := ⟨(const_equiv p).1 ∘ quotient.eq.1, λ h, by rw h⟩ @[norm_cast] lemma coe_inj {q r : ℚ} : (↑q : ℚ_[p]) = ↑r ↔ q = r := by simp [cast_eq_of_rat, of_rat_eq] instance : char_zero ℚ_[p] := ⟨λ m n, by { rw ← rat.cast_coe_nat, norm_cast, exact id }⟩ end completion end padic /-- The rational-valued p-adic norm on ℚ_p is lifted from the norm on Cauchy sequences. The canonical form of this function is the normed space instance, with notation `∥ ∥`. -/ def padic_norm_e {p : ℕ} [hp : fact p.prime] : ℚ_[p] → ℚ := quotient.lift padic_seq.norm $ @padic_seq.norm_equiv _ _ namespace padic_norm_e section embedding open padic_seq variables {p : ℕ} [fact p.prime] lemma defn (f : padic_seq p) {ε : ℚ} (hε : ε > 0) : ∃ N, ∀ i ≥ N, padic_norm_e (⟦f⟧ - f i) < ε := begin simp only [padic.cast_eq_of_rat], change ∃ N, ∀ i ≥ N, (f - const _ (f i)).norm < ε, by_contradiction h, cases cauchy₂ f hε with N hN, have : ∀ N, ∃ i ≥ N, (f - const _ (f i)).norm ≥ ε, by simpa [not_forall] using h, rcases this N with ⟨i, hi, hge⟩, have hne : ¬ (f - const (padic_norm p) (f i)) ≈ 0, { intro h, unfold padic_seq.norm at hge; split_ifs at hge, exact not_lt_of_ge hge hε }, unfold padic_seq.norm at hge; split_ifs at hge, apply not_le_of_gt _ hge, cases decidable.em ((stationary_point hne) ≥ N) with hgen hngen, { apply hN; assumption }, { have := stationary_point_spec hne (le_refl _) (le_of_not_le hngen), rw ←this, apply hN, apply le_refl, assumption } end protected lemma nonneg (q : ℚ_[p]) : padic_norm_e q ≥ 0 := quotient.induction_on q $ norm_nonneg lemma zero_def : (0 : ℚ_[p]) = ⟦0⟧ := rfl lemma zero_iff (q : ℚ_[p]) : padic_norm_e q = 0 ↔ q = 0 := quotient.induction_on q $ by simpa only [zero_def, quotient.eq] using norm_zero_iff @[simp] protected lemma zero : padic_norm_e (0 : ℚ_[p]) = 0 := (zero_iff _).2 rfl /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ @[simp] protected lemma one' : padic_norm_e (1 : ℚ_[p]) = 1 := norm_one @[simp] protected lemma neg (q : ℚ_[p]) : padic_norm_e (-q) = padic_norm_e q := quotient.induction_on q $ norm_neg /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ theorem nonarchimedean' (q r : ℚ_[p]) : padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r $ norm_nonarchimedean /-- Theorems about `padic_norm_e` are named with a `'` so the names do not conflict with the equivalent theorems about `norm` (`∥ ∥`). -/ theorem add_eq_max_of_ne' {q r : ℚ_[p]} : padic_norm_e q ≠ padic_norm_e r → padic_norm_e (q + r) = max (padic_norm_e q) (padic_norm_e r) := quotient.induction_on₂ q r $ λ _ _, padic_seq.add_eq_max_of_ne lemma triangle_ineq (x y z : ℚ_[p]) : padic_norm_e (x - z) ≤ padic_norm_e (x - y) + padic_norm_e (y - z) := calc padic_norm_e (x - z) = padic_norm_e ((x - y) + (y - z)) : by rw sub_add_sub_cancel ... ≤ max (padic_norm_e (x - y)) (padic_norm_e (y - z)) : padic_norm_e.nonarchimedean' _ _ ... ≤ padic_norm_e (x - y) + padic_norm_e (y - z) : max_le_add_of_nonneg (padic_norm_e.nonneg _) (padic_norm_e.nonneg _) protected lemma add (q r : ℚ_[p]) : padic_norm_e (q + r) ≤ (padic_norm_e q) + (padic_norm_e r) := calc padic_norm_e (q + r) ≤ max (padic_norm_e q) (padic_norm_e r) : nonarchimedean' _ _ ... ≤ (padic_norm_e q) + (padic_norm_e r) : max_le_add_of_nonneg (padic_norm_e.nonneg _) (padic_norm_e.nonneg _) protected lemma mul' (q r : ℚ_[p]) : padic_norm_e (q * r) = (padic_norm_e q) * (padic_norm_e r) := quotient.induction_on₂ q r $ norm_mul instance : is_absolute_value (@padic_norm_e p _) := { abv_nonneg := padic_norm_e.nonneg, abv_eq_zero := zero_iff, abv_add := padic_norm_e.add, abv_mul := padic_norm_e.mul' } @[simp] lemma eq_padic_norm' (q : ℚ) : padic_norm_e (padic.of_rat p q) = padic_norm p q := norm_const _ protected theorem image' {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, padic_norm_e q = p ^ (-n) := quotient.induction_on q $ λ f hf, have ¬ f ≈ 0, from (ne_zero_iff_nequiv_zero f).1 hf, norm_image f this lemma sub_rev (q r : ℚ_[p]) : padic_norm_e (q - r) = padic_norm_e (r - q) := by rw ←(padic_norm_e.neg); simp end embedding end padic_norm_e namespace padic section complete open padic_seq padic theorem rat_dense' {p : ℕ} [fact p.prime] (q : ℚ_[p]) {ε : ℚ} (hε : ε > 0) : ∃ r : ℚ, padic_norm_e (q - r) < ε := quotient.induction_on q $ λ q', have ∃ N, ∀ m n ≥ N, padic_norm p (q' m - q' n) < ε, from cauchy₂ _ hε, let ⟨N, hN⟩ := this in ⟨q' N, begin simp only [padic.cast_eq_of_rat], change padic_seq.norm (q' - const _ (q' N)) < ε, cases decidable.em ((q' - const (padic_norm p) (q' N)) ≈ 0) with heq hne', { simpa only [heq, padic_seq.norm, dif_pos] }, { simp only [padic_seq.norm, dif_neg hne'], change padic_norm p (q' _ - q' _) < ε, have := stationary_point_spec hne', cases decidable.em (N ≥ stationary_point hne') with hle hle, { have := eq.symm (this (le_refl _) hle), simp at this, simpa [this] }, { apply hN, apply le_of_lt, apply lt_of_not_ge, apply hle, apply le_refl }} end⟩ variables {p : ℕ} [fact p.prime] (f : cau_seq _ (@padic_norm_e p _)) open classical private lemma div_nat_pos (n : ℕ) : (1 / ((n + 1): ℚ)) > 0 := div_pos zero_lt_one (by exact_mod_cast succ_pos _) def lim_seq : ℕ → ℚ := λ n, classical.some (rat_dense' (f n) (div_nat_pos n)) lemma exi_rat_seq_conv {ε : ℚ} (hε : 0 < ε) : ∃ N, ∀ i ≥ N, padic_norm_e (f i - ((lim_seq f) i : ℚ_[p])) < ε := begin refine (exists_nat_gt (1/ε)).imp (λ N hN i hi, _), have h := classical.some_spec (rat_dense' (f i) (div_nat_pos i)), refine lt_of_lt_of_le h (div_le_of_le_mul (by exact_mod_cast succ_pos _) _), rw right_distrib, apply le_add_of_le_of_nonneg, { exact le_mul_of_div_le hε (le_trans (le_of_lt hN) (by exact_mod_cast hi)) }, { apply le_of_lt, simpa } end lemma exi_rat_seq_conv_cauchy : is_cau_seq (padic_norm p) (lim_seq f) := assume ε hε, have hε3 : ε / 3 > 0, from div_pos hε (by norm_num), let ⟨N, hN⟩ := exi_rat_seq_conv f hε3, ⟨N2, hN2⟩ := f.cauchy₂ hε3 in begin existsi max N N2, intros j hj, suffices : padic_norm_e ((↑(lim_seq f j) - f (max N N2)) + (f (max N N2) - lim_seq f (max N N2))) < ε, { ring at this ⊢, rw [← padic_norm_e.eq_padic_norm', ← padic.cast_eq_of_rat], exact_mod_cast this }, { apply lt_of_le_of_lt, { apply padic_norm_e.add }, { have : (3 : ℚ) ≠ 0, by norm_num, have : ε = ε / 3 + ε / 3 + ε / 3, { field_simp [this], simp [bit0, bit1, mul_add] }, rw this, apply add_lt_add, { suffices : padic_norm_e ((↑(lim_seq f j) - f j) + (f j - f (max N N2))) < ε / 3 + ε / 3, by simpa [sub_add_sub_cancel], apply lt_of_le_of_lt, { apply padic_norm_e.add }, { apply add_lt_add, { rw [padic_norm_e.sub_rev], apply_mod_cast hN, exact le_of_max_le_left hj }, { apply hN2, exact le_of_max_le_right hj, apply le_max_right }}}, { apply_mod_cast hN, apply le_max_left }}} end private def lim' : padic_seq p := ⟨_, exi_rat_seq_conv_cauchy f⟩ private def lim : ℚ_[p] := ⟦lim' f⟧ theorem complete' : ∃ q : ℚ_[p], ∀ ε > 0, ∃ N, ∀ i ≥ N, padic_norm_e (q - f i) < ε := ⟨ lim f, λ ε hε, let ⟨N, hN⟩ := exi_rat_seq_conv f (show ε / 2 > 0, from div_pos hε (by norm_num)), ⟨N2, hN2⟩ := padic_norm_e.defn (lim' f) (show ε / 2 > 0, from div_pos hε (by norm_num)) in begin existsi max N N2, intros i hi, suffices : padic_norm_e ((lim f - lim' f i) + (lim' f i - f i)) < ε, { ring at this; exact this }, { apply lt_of_le_of_lt, { apply padic_norm_e.add }, { have : ε = ε / 2 + ε / 2, by rw ←(add_self_div_two ε); simp, rw this, apply add_lt_add, { apply hN2, exact le_of_max_le_right hi }, { rw_mod_cast [padic_norm_e.sub_rev], apply hN, exact le_of_max_le_left hi }}} end ⟩ end complete section normed_space variables (p : ℕ) [fact p.prime] instance : has_dist ℚ_[p] := ⟨λ x y, padic_norm_e (x - y)⟩ instance : metric_space ℚ_[p] := { dist_self := by simp [dist], dist_comm := λ x y, by unfold dist; rw ←padic_norm_e.neg (x - y); simp, dist_triangle := begin intros, unfold dist, exact_mod_cast padic_norm_e.triangle_ineq _ _ _, end, eq_of_dist_eq_zero := begin unfold dist, intros _ _ h, apply eq_of_sub_eq_zero, apply (padic_norm_e.zero_iff _).1, exact_mod_cast h end } instance : has_norm ℚ_[p] := ⟨λ x, padic_norm_e x⟩ instance : normed_field ℚ_[p] := { dist_eq := λ _ _, rfl, norm_mul' := by simp [has_norm.norm, padic_norm_e.mul'] } instance : is_absolute_value (λ a : ℚ_[p], ∥a∥) := { abv_nonneg := norm_nonneg, abv_eq_zero := λ _, norm_eq_zero, abv_add := norm_add_le, abv_mul := by simp [has_norm.norm, padic_norm_e.mul'] } theorem rat_dense {p : ℕ} {hp : fact p.prime} (q : ℚ_[p]) {ε : ℝ} (hε : ε > 0) : ∃ r : ℚ, ∥q - r∥ < ε := let ⟨ε', hε'l, hε'r⟩ := exists_rat_btwn hε, ⟨r, hr⟩ := rat_dense' q (by simpa using hε'l) in ⟨r, lt.trans (by simpa [has_norm.norm] using hr) hε'r⟩ end normed_space end padic namespace padic_norm_e section normed_space variables {p : ℕ} [hp : fact p.prime] include hp @[simp] protected lemma mul (q r : ℚ_[p]) : ∥q * r∥ = ∥q∥ * ∥r∥ := by simp [has_norm.norm, padic_norm_e.mul'] protected lemma is_norm (q : ℚ_[p]) : ↑(padic_norm_e q) = ∥q∥ := rfl theorem nonarchimedean (q r : ℚ_[p]) : ∥q + r∥ ≤ max (∥q∥) (∥r∥) := begin unfold has_norm.norm, exact_mod_cast nonarchimedean' _ _ end theorem add_eq_max_of_ne {q r : ℚ_[p]} (h : ∥q∥ ≠ ∥r∥) : ∥q+r∥ = max (∥q∥) (∥r∥) := begin unfold has_norm.norm, apply_mod_cast add_eq_max_of_ne', intro h', apply h, unfold has_norm.norm, exact_mod_cast h' end @[simp] lemma eq_padic_norm (q : ℚ) : ∥(↑q : ℚ_[p])∥ = padic_norm p q := begin unfold has_norm.norm, rw [← padic_norm_e.eq_padic_norm', ← padic.cast_eq_of_rat] end instance : nondiscrete_normed_field ℚ_[p] := { non_trivial := ⟨padic.of_rat p (p⁻¹), begin have h0 : p ≠ 0 := ne_of_gt (hp.pos), have h1 : 1 < p := hp.one_lt, rw [← padic.cast_eq_of_rat, eq_padic_norm], simp only [padic_norm, inv_eq_zero], simp only [if_neg] {discharger := `[exact_mod_cast h0]}, norm_cast, simp only [padic_val_rat.inv] {discharger := `[exact_mod_cast h0]}, rw [neg_neg, padic_val_rat.padic_val_rat_self h1], erw _root_.pow_one, exact_mod_cast h1, end⟩ } protected theorem image {q : ℚ_[p]} : q ≠ 0 → ∃ n : ℤ, ∥q∥ = ↑((↑p : ℚ) ^ (-n)) := quotient.induction_on q $ λ f hf, have ¬ f ≈ 0, from (padic_seq.ne_zero_iff_nequiv_zero f).1 hf, let ⟨n, hn⟩ := padic_seq.norm_image f this in ⟨n, congr_arg coe hn⟩ protected lemma is_rat (q : ℚ_[p]) : ∃ q' : ℚ, ∥q∥ = ↑q' := if h : q = 0 then ⟨0, by simp [h]⟩ else let ⟨n, hn⟩ := padic_norm_e.image h in ⟨_, hn⟩ def rat_norm (q : ℚ_[p]) : ℚ := classical.some (padic_norm_e.is_rat q) lemma eq_rat_norm (q : ℚ_[p]) : ∥q∥ = rat_norm q := classical.some_spec (padic_norm_e.is_rat q) theorem norm_rat_le_one : ∀ {q : ℚ} (hq : ¬ p ∣ q.denom), ∥(q : ℚ_[p])∥ ≤ 1 | ⟨n, d, hn, hd⟩ := λ hq : ¬ p ∣ d, if hnz : n = 0 then have (⟨n, d, hn, hd⟩ : ℚ) = 0, from rat.zero_iff_num_zero.mpr hnz, by norm_num [this] else begin have hnz' : {rat . num := n, denom := d, pos := hn, cop := hd} ≠ 0, from mt rat.zero_iff_num_zero.1 hnz, rw [padic_norm_e.eq_padic_norm], norm_cast, rw [padic_norm.eq_fpow_of_nonzero p hnz', padic_val_rat_def p hnz'], have h : (multiplicity p d).get _ = 0, by simp [multiplicity_eq_zero_of_not_dvd, hq], simp only, norm_cast, rw_mod_cast [h, sub_zero], apply fpow_le_one_of_nonpos, { exact_mod_cast le_of_lt hp.one_lt, }, { apply neg_nonpos_of_nonneg, norm_cast, simp, } end lemma eq_of_norm_add_lt_right {p : ℕ} {hp : fact p.prime} {z1 z2 : ℚ_[p]} (h : ∥z1 + z2∥ < ∥z2∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_e.add_eq_max_of_ne hne; apply le_max_right) h lemma eq_of_norm_add_lt_left {p : ℕ} {hp : fact p.prime} {z1 z2 : ℚ_[p]} (h : ∥z1 + z2∥ < ∥z1∥) : ∥z1∥ = ∥z2∥ := by_contradiction $ λ hne, not_lt_of_ge (by rw padic_norm_e.add_eq_max_of_ne hne; apply le_max_left) h end normed_space end padic_norm_e namespace padic variables {p : ℕ} [fact p.prime] set_option eqn_compiler.zeta true instance complete : cau_seq.is_complete ℚ_[p] norm := begin split, intro f, have cau_seq_norm_e : is_cau_seq padic_norm_e f, { intros ε hε, let h := is_cau f ε (by exact_mod_cast hε), unfold norm at h, apply_mod_cast h }, cases padic.complete' ⟨f, cau_seq_norm_e⟩ with q hq, existsi q, intros ε hε, cases exists_rat_btwn hε with ε' hε', norm_cast at hε', cases hq ε' hε'.1 with N hN, existsi N, intros i hi, let h := hN i hi, unfold norm, rw_mod_cast [cau_seq.sub_apply, padic_norm_e.sub_rev], refine lt.trans _ hε'.2, exact_mod_cast hN i hi end lemma padic_norm_e_lim_le {f : cau_seq ℚ_[p] norm} {a : ℝ} (ha : a > 0) (hf : ∀ i, ∥f i∥ ≤ a) : ∥f.lim∥ ≤ a := let ⟨N, hN⟩ := setoid.symm (cau_seq.equiv_lim f) _ ha in calc ∥f.lim∥ = ∥f.lim - f N + f N∥ : by simp ... ≤ max (∥f.lim - f N∥) (∥f N∥) : padic_norm_e.nonarchimedean _ _ ... ≤ a : max_le (le_of_lt (hN _ (le_refl _))) (hf _) end padic
bf1d1d0a6df4da896e07ea1731478d6a8debc7af
e1da55f4222dac91b940ca052928eaace09762da
/src/mathlib.lean
b7d8821740a3d8874dce53e756b2a45cfa98b2c6
[]
no_license
b-mehta/regularity-lemma
c5826e22c280d0b073a4e62dba731f4dd3d1b69f
cf26082b0c88fa54276e6fdc3338c15e607c52c6
refs/heads/master
1,658,209,524,267
1,644,406,456,000
1,644,406,456,000
457,327,371
1
0
null
null
null
null
UTF-8
Lean
false
false
25,761
lean
/- Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import analysis.special_functions.log import combinatorics.simple_graph.degree_sum import combinatorics.pigeonhole import data.set.equitable import .finpartition /-! # Things that belong to mathlib -/ open_locale big_operators nat open finset fintype function variables {α β ι ι' : Type*} namespace nat lemma weird_thing : ∀ {d : ℕ}, d ≤ 2 * d - 1 | 0 := by simp | (n+1) := by simp [mul_add, two_mul] lemma thing2 (i j : ℕ) (hj : 0 < j) : j * (j - 1) * (i / j + 1) ^ 2 < (i + j) ^ 2 := begin have : j * (j-1) < j^2, { rw sq, exact nat.mul_lt_mul_of_pos_left (nat.sub_lt hj zero_lt_one) hj }, apply (nat.mul_lt_mul_of_pos_right this $ pow_pos nat.succ_pos' _).trans_le, rw ←mul_pow, exact nat.pow_le_pow_of_le_left (add_le_add_right (nat.mul_div_le i j) _) _, end def from_digits {n : ℕ} (d : ℕ) (a : fin n → ℕ) : ℕ := ∑ i, a i * d^(i : ℕ) @[simp] lemma from_digits_zero (d : ℕ) (a : fin 0 → ℕ) : from_digits d a = 0 := by simp [from_digits] lemma from_digits_succ {n d : ℕ} (a : fin (n+1) → ℕ) : from_digits d a = a 0 + (∑ (x : fin n), a x.succ * d ^ (x : ℕ)) * d := by simp [from_digits, fin.sum_univ_succ, pow_succ', ←mul_assoc, ←sum_mul] lemma from_digits_succ' {n d : ℕ} (a : fin (n+1) → ℕ) : from_digits d a = a 0 + (from_digits d (a ∘ fin.succ)) * d := from_digits_succ _ lemma from_digits_monotone {n : ℕ} (d : ℕ) : monotone (from_digits d : (fin n → ℕ) → ℕ) := begin intros x₁ x₂ h, induction n with n ih, { simp }, rw [from_digits_succ', from_digits_succ'], exact add_le_add (h 0) (nat.mul_le_mul_right d (ih (λ i, h i.succ))), end lemma from_digits_two_add {n d : ℕ} {x y : fin n → ℕ} (hx : ∀ i, x i < d) (hy : ∀ i, y i < d) : from_digits (2 * d - 1) (x + y) = from_digits (2 * d - 1) x + from_digits (2 * d - 1) y := begin induction n with n ih, { simp [from_digits_zero] }, simp only [from_digits_succ', pi.add_apply, add_add_add_comm, add_right_inj, ←add_mul, ←@ih (x ∘ fin.succ) (y ∘ fin.succ) (λ _, hx _) (λ _, hy _)], refl, end lemma sum_bound {n d : ℕ} {x y : fin n → ℕ} (hx : ∀ i, x i < d) (hy : ∀ i, y i < d) (i : fin n) : (x + y) i < 2 * d - 1 := begin rw [←nat.pred_eq_sub_one, nat.lt_pred_iff, nat.lt_iff_add_one_le, nat.succ_eq_add_one, pi.add_apply, add_right_comm _ (y i), add_assoc, two_mul], apply add_le_add (nat.succ_le_of_lt (hx i)) (nat.succ_le_of_lt (hy i)) end lemma sum_fin {β : Type*} [add_comm_monoid β] (n : ℕ) (f : ℕ → β) : ∑ (i : fin n), f i = ∑ i in range n, f i := (sum_subtype (range n) (by simp) f).symm lemma digits_sum_eq {n d : ℕ} : ∑ (i : fin n), (d - 1) * (2 * d - 1)^(i : ℕ) = ((2 * d - 1)^n - 1) / 2 := begin apply (nat.div_eq_of_eq_mul_left zero_lt_two _).symm, rcases nat.eq_zero_or_pos d with rfl | hd, { simp only [mul_zero, nat.zero_sub, zero_mul, sum_const_zero, tsub_eq_zero_iff_le, zero_pow_eq], split_ifs; simp }, have : ((2 * d - 2) + 1) = 2 * d - 1, { rw ←tsub_tsub_assoc (nat.le_mul_of_pos_right hd) one_le_two }, rw [sum_fin n (λ i, (d - 1) * (2 * d - 1)^(i : ℕ)), ←mul_sum, mul_right_comm, nat.mul_sub_right_distrib, mul_comm d, one_mul, ←this, ←geom_sum_def, ←geom_sum_mul_add, nat.add_sub_cancel, mul_comm], end lemma digits_sum_le {n d : ℕ} (hd : 0 < d) : ∑ (i : fin n), (d - 1) * (2 * d - 1)^(i : ℕ) < (2 * d - 1)^n := begin rw digits_sum_eq, apply (nat.div_le_self _ _).trans_lt (nat.pred_lt (pow_pos (hd.trans_le weird_thing) _).ne'), end end nat section -- Should *replace* the existing lemma with a similar name. lemma exists_le_card_fiber_of_mul_le_card_of_maps_to' {α : Type*} {β : Type*} {M : Type*} [linear_ordered_comm_ring M] [decidable_eq β] {s : finset α} {t : finset β} {f : α → β} {b : M} (hf : ∀ a ∈ s, f a ∈ t) (ht : t.nonempty) (hn : t.card • b ≤ s.card) : ∃ y ∈ t, b ≤ (s.filter (λ x, f x = y)).card := begin simp only [finset.card_eq_sum_ones, nat.cast_sum], refine exists_le_sum_fiber_of_maps_to_of_nsmul_le_sum hf ht _, simpa using hn, end end namespace set variables {s : set ι} {t : set ι'} {f : ι → set α} {g : ι' → set β} lemma pairwise_disjoint.prod (hs : s.pairwise_disjoint f) (ht : t.pairwise_disjoint g) : (s ×ˢ t : set (ι × ι')).pairwise_disjoint (λ i, (f i.1) ×ˢ (g i.2)) := λ ⟨i, i'⟩ ⟨hi, hi'⟩ ⟨j, j'⟩ ⟨hj, hj'⟩ hij ⟨a, b⟩ ⟨⟨hai, hbi⟩, haj, hbj⟩, hij $ prod.ext (hs.elim_set hi hj _ hai haj) $ ht.elim_set hi' hj' _ hbi hbj lemma pairwise_disjoint.product [decidable_eq α] [decidable_eq β] {f : ι → finset α} {g : ι' → finset β} (hs : s.pairwise_disjoint f) (ht : t.pairwise_disjoint g) : (s ×ˢ t : set (ι × ι')).pairwise_disjoint (λ i, (f i.1).product (g i.2)) := begin rintro ⟨i, i'⟩ ⟨hi, hi'⟩ ⟨j, j'⟩ ⟨hj, hj'⟩ hij ⟨a, b⟩ hab, simp_rw [finset.inf_eq_inter, finset.mem_inter, finset.mem_product] at hab, exact hij (prod.ext (hs.elim_finset hi hj _ hab.1.1 hab.2.1) $ ht.elim_finset hi' hj' _ hab.1.2 hab.2.2), end -- lemma pairwise_disjoint.product' [decidable_eq α] [decidable_eq β] {s : finset ι} {t : finset ι'} -- {f : ι → finset α} {g : ι' → finset β} (hs : s.pairwise_disjoint f) -- (ht : t.pairwise_disjoint g) : -- (s.product t).pairwise_disjoint (λ i, (f i.1).product (g i.2)) := -- begin -- rintro ⟨i, i'⟩ ⟨hi, hi'⟩ ⟨j, j'⟩ ⟨hj, hj'⟩ hij ⟨a, b⟩ hab, -- simp_rw [finset.inf_eq_inter, finset.mem_inter, finset.mem_product] at hab, -- exact hij (prod.ext (hs.elim_finset hi hj _ hab.1.1 hab.2.1) $ -- ht.elim_finset hi' hj' _ hab.1.2 hab.2.2), -- end lemma pairwise_disjoint_pi {α : ι' → Type*} {ι : ι' → Type*} {s : Π i, set (ι i)} {f : Π i, ι i → set (α i)} (hs : ∀ i, (s i).pairwise_disjoint (f i)) : ((univ : set ι').pi s).pairwise_disjoint (λ I, (univ : set ι').pi (λ i, f _ (I i))) := λ I hI J hJ hIJ a ⟨haI, haJ⟩, hIJ $ funext $ λ i, (hs i).elim_set (hI i trivial) (hJ i trivial) (a i) (haI i trivial) (haJ i trivial) lemma pairwise_disjoint.attach [semilattice_inf α] [order_bot α] {s : finset ι} {f : ι → α} (hs : (s : set ι).pairwise_disjoint f) : (s.attach : set {x // x ∈ s}).pairwise_disjoint (f ∘ subtype.val) := λ i _ j _ hij, hs i.2 j.2 $ mt subtype.ext_val hij lemma subsingleton_of_subset_singleton {s : set α} {a : α} (h : s ⊆ {a}) : s.subsingleton := subsingleton_singleton.mono h end set namespace finset lemma sum_mod (s : finset α) {m : ℕ} (f : α → ℕ) : (∑ i in s, f i) % m = (∑ i in s, (f i % m)) % m := begin classical, induction s using finset.induction with i s hi ih, { simp }, rw [sum_insert hi, sum_insert hi, nat.add_mod, ih, nat.add_mod], simp, end -- lemma nonempty_diff [decidable_eq α] {s t : finset α} : (s \ t).nonempty ↔ ¬ s ⊆ t := -- sorry lemma dumb_thing {α : Type*} [decidable_eq α] {X Y Z : finset α} (hXY : disjoint X Y) (hXZ : disjoint X Z) (hYZ : disjoint Y Z) {x₁ x₂ y₁ y₂ z₁ z₂ : α} (h : ({x₁, y₁, z₁} : finset α) = {x₂, y₂, z₂}) (hx₁ : x₁ ∈ X) (hx₂ : x₂ ∈ X) (hy₁ : y₁ ∈ Y) (hy₂ : y₂ ∈ Y) (hz₁ : z₁ ∈ Z) (hz₂ : z₂ ∈ Z) : (x₁, y₁, z₁) = (x₂, y₂, z₂) := begin simp only [finset.subset.antisymm_iff, subset_iff, mem_insert, mem_singleton, forall_eq_or_imp, forall_eq] at h, rw disjoint_left at hXY hXZ hYZ, rw [prod.mk.inj_iff, prod.mk.inj_iff], simp only [and.assoc, @or.left_comm _ (y₁ = y₂), @or.comm _ (z₁ = z₂), @or.left_comm _ (z₁ = z₂)] at h, refine ⟨h.1.resolve_right (not_or _ _), h.2.1.resolve_right (not_or _ _), h.2.2.1.resolve_right (not_or _ _)⟩; { rintro rfl, solve_by_elim }, end end finset lemma exists_ne_ne_fin {n : ℕ} (hn : 3 ≤ n) (a b : fin n) : ∃ c, a ≠ c ∧ b ≠ c := begin obtain ⟨c, hc⟩ : ({a,b}ᶜ : finset (fin n)).nonempty, { rw [←finset.card_pos, card_compl, fintype.card_fin], apply nat.sub_pos_of_lt ((card_insert_le _ _).trans_lt _), rw card_singleton, linarith }, exact ⟨c, by simpa [not_or_distrib, @eq_comm _ c] using hc⟩, end lemma fin3_cases (i j : fin 3) : i = j ∨ i = j + 1 ∨ i = j + 2 := by { fin_cases i; fin_cases j; finish } lemma lt_of_not_le [linear_order α] {a b : α} (h : ¬ a ≤ b) : b < a := lt_of_not_ge' h section linear_ordered_field variables [linear_ordered_field α] lemma one_div_le_one_of_one_le {a : α} (ha : 1 ≤ a) : 1 / a ≤ 1 := (div_le_one $ zero_lt_one.trans_le ha).2 ha lemma le_div_self {x y : α} (hx : 0 ≤ x) (hy₀ : 0 < y) (hy₁ : y ≤ 1) : x ≤ x / y := by simpa using div_le_div_of_le_left hx hy₀ hy₁ lemma mul_le_of_nonneg_of_le_div {x y z : α} (hy : 0 ≤ y) (hz : 0 ≤ z) (h : x ≤ y / z) : x * z ≤ y := begin rcases hz.eq_or_lt with rfl | hz, { simpa using hy }, rwa le_div_iff hz at h, end end linear_ordered_field lemma disjoint.eq_bot_of_ge {α : Type*} [semilattice_inf α] [order_bot α] {a b : α} (hab : disjoint a b) (h : b ≤ a) : b = ⊥ := hab.symm.eq_bot_of_le h lemma sum_mul_sq_le_sq_mul_sq {α : Type*} (s : finset α) (f g : α → ℝ) : (∑ i in s, f i * g i)^2 ≤ (∑ i in s, (f i)^2) * (∑ i in s, (g i)^2) := begin have h : 0 ≤ ∑ i in s, (f i * ∑ j in s, (g j)^2 - g i * ∑ j in s, f j * g j)^2 := sum_nonneg (λ i hi, sq_nonneg _), simp_rw [sub_sq, sum_add_distrib, sum_sub_distrib, mul_pow, mul_assoc, ←mul_sum, ←sum_mul, mul_left_comm, ←mul_assoc, ←sum_mul, mul_right_comm, ←sq, mul_comm, sub_add, two_mul, add_sub_cancel, mul_comm (∑ j in s, (g j)^2), sq (∑ j in s, (g j)^2), ←mul_assoc, ←mul_sub_right_distrib] at h, obtain h' | h' := (sum_nonneg (λ i (hi : i ∈ s), sq_nonneg (g i))).eq_or_lt, { have h'' : ∀ i ∈ s, g i = 0 := λ i hi, by simpa using (sum_eq_zero_iff_of_nonneg (λ i _, sq_nonneg (g i))).1 h'.symm i hi, rw [←h', sum_congr rfl (show ∀ i ∈ s, f i * g i = 0, from λ i hi, by simp [h'' i hi])], simp }, rw ←sub_nonneg, apply nonneg_of_mul_nonneg_right h h', end lemma chebyshev' (s : finset α) (f : α → ℝ) : (∑ (i : α) in s, f i) ^ 2 ≤ (∑ (i : α) in s, f i ^ 2) * s.card := by simpa using sum_mul_sq_le_sq_mul_sq s f (λ _, 1) lemma chebyshev (s : finset α) (f : α → ℝ) : ((∑ i in s, f i) / s.card)^2 ≤ (∑ i in s, (f i)^2) / s.card := begin rcases s.eq_empty_or_nonempty with rfl | hs, { simp }, rw div_pow, have hs' : 0 < (s.card : ℝ) := nat.cast_pos.2 hs.card_pos, rw [div_le_div_iff (sq_pos_of_ne_zero _ hs'.ne') hs', sq (s.card : ℝ), ←mul_assoc], apply mul_le_mul_of_nonneg_right (chebyshev' _ _) hs'.le, end namespace simple_graph variables {G G' : simple_graph α} {s : finset α} instance {r : α → α → Prop} [h : decidable_rel r] : decidable_pred (uncurry r) := λ x, h x.1 x.2 @[mono] lemma edge_set_mono (h : G ≤ G') : G.edge_set ⊆ G'.edge_set := begin refine sym2.ind _, intros x y h', exact h h', end variables [decidable_eq α] [fintype α] [decidable_rel G.adj] [decidable_rel G'.adj] @[mono] lemma edge_finset_mono (h : G ≤ G') : G.edge_finset ⊆ G'.edge_finset := set.to_finset_mono.2 (edge_set_mono h) variables (G G') def edge_finset_on [decidable_eq α] [decidable_rel G.adj] (s : finset α) : finset (sym2 α) := ((s.product s).filter $ function.uncurry G.adj).image quotient.mk variables {G G'} lemma mem_edge_finset_on {x : sym2 α} : x ∈ G.edge_finset_on s ↔ ∃ a b, a ∈ s ∧ b ∈ s ∧ G.adj a b ∧ x = ⟦(a, b)⟧ := begin simp_rw [edge_finset_on, mem_image, exists_prop, mem_filter, mem_product], split, { rintro ⟨⟨a, b⟩, ⟨⟨hsa, hsb⟩, hGab⟩, h⟩, exact ⟨a, b, hsa, hsb, hGab, h.symm⟩ }, { rintro ⟨a, b, hsa, hsb, hGab, h⟩, exact ⟨⟨a, b⟩, ⟨⟨hsa, hsb⟩, hGab⟩, h.symm⟩ } end @[simp] lemma dart.adj (d : G.dart) : G.adj d.fst d.snd := d.3 variables [fintype α] lemma double_edge_finset_card_eq [decidable_eq α] [decidable_rel G.adj] : 2 * G.edge_finset.card = (univ.filter (λ (xy : α × α), G.adj xy.1 xy.2)).card := begin rw [←dart_card_eq_twice_card_edges, ←card_univ], refine card_congr (λ i _, (i.1, i.2)) (by simp) (by simp [dart.ext_iff, ←and_imp]) _, rintro ⟨x, y⟩ h, exact ⟨⟨x, y, (mem_filter.1 h).2⟩, mem_univ _, rfl⟩, end end simple_graph open finset /-! ## pairs_finset and pairs_density -/ namespace relation variables (r : α → α → Prop) [decidable_rel r] /-- Finset of edges between two finsets of vertices -/ def pairs_finset (U V : finset α) : finset (α × α) := (U.product V).filter (λ e, r e.1 e.2) lemma mem_pairs_finset (U V : finset α) (x : α × α) : x ∈ pairs_finset r U V ↔ x.1 ∈ U ∧ x.2 ∈ V ∧ r x.1 x.2 := by simp only [pairs_finset, and_assoc, mem_filter, finset.mem_product] lemma mem_pairs_finset' (U V : finset α) (x y : α) : (x, y) ∈ pairs_finset r U V ↔ x ∈ U ∧ y ∈ V ∧ r x y := mem_pairs_finset _ _ _ _ @[simp] lemma pairs_finset_empty_left (V : finset α) : pairs_finset r ∅ V = ∅ := by rw [pairs_finset, finset.empty_product, filter_empty] lemma pairs_finset_mono {A B A' B' : finset α} (hA : A' ⊆ A) (hB : B' ⊆ B) : pairs_finset r A' B' ⊆ pairs_finset r A B := begin intro x, rw [mem_pairs_finset, mem_pairs_finset], exact λ h, ⟨hA h.1, hB h.2.1, h.2.2⟩, end lemma card_pairs_finset_compl (U V : finset α) : (pairs_finset r U V).card + (pairs_finset (λ x y, ¬r x y) U V).card = U.card * V.card := begin classical, rw [←card_product, pairs_finset, pairs_finset, ←card_union_eq, filter_union_filter_neg_eq], rw disjoint_filter, exact λ x _, not_not.2, end section decidable_eq variable [decidable_eq α] lemma pairs_finset_disjoint_left {U U' : finset α} (hU : disjoint U U') (V : finset α) : disjoint (pairs_finset r U V) (pairs_finset r U' V) := begin rw [disjoint_iff_inter_eq_empty, ←subset_empty] at ⊢ hU, rintro x hx, rw [mem_inter, mem_pairs_finset, mem_pairs_finset] at hx, exact hU (mem_inter.2 ⟨hx.1.1, hx.2.1⟩), end lemma pairs_finset_disjoint_right (U : finset α) {V V' : finset α} (hV : disjoint V V') : disjoint (pairs_finset r U V) (pairs_finset r U V') := begin rw [disjoint_iff_inter_eq_empty, ←subset_empty] at ⊢ hV, rintro x hx, rw [mem_inter, mem_pairs_finset, mem_pairs_finset] at hx, exact hV (mem_inter.2 ⟨hx.1.2.1, hx.2.2.1⟩), end lemma pairs_finset_bUnion_left (A : finset β) (V : finset α) (f : β → finset α) : pairs_finset r (A.bUnion f) V = A.bUnion (λ a, pairs_finset r (f a) V) := by { ext x, simp only [mem_pairs_finset, mem_bUnion, exists_and_distrib_right] } lemma pairs_finset_bUnion_right (U : finset α) (B : finset β) (f : β → finset α) : pairs_finset r U (B.bUnion f) = B.bUnion (λ b, pairs_finset r U (f b)) := by { ext x, simp only [mem_pairs_finset, mem_bUnion], tauto } lemma pairs_finset_bUnion (A B : finset β) (f g : β → finset α) : pairs_finset r (A.bUnion f) (B.bUnion g) = (A.product B).bUnion (λ ab, pairs_finset r (f ab.1) (g ab.2)) := by simp_rw [product_bUnion, pairs_finset_bUnion_left, pairs_finset_bUnion_right] end decidable_eq /-- Number of edges between two finsets of vertices -/ def pairs_count (U V : finset α) : ℕ := (pairs_finset r U V).card lemma pairs_count_le_mul (U V : finset α) : pairs_count r U V ≤ U.card * V.card := begin rw [pairs_count, pairs_finset, ←finset.card_product], exact finset.card_filter_le _ _, end -- lemma pairs_count_bUnion_left [decidable_eq α] (A : finset β) (f : β → finset α) (B : finset α) : -- pairs_count r (A.bUnion f) B = ∑ a in A, pairs_count r (f a) B := -- begin -- rw [pairs_count, pairs_finset_bUnion_left, card_bUnion], -- { refl }, -- intros x hx y hy h, -- apply pairs_finset_disjoint_left, -- -- simp only [pairs_count, pairs_finset_bUnion], -- -- rw card_bUnion, -- end -- lemma pairs_count_bUnion [decidable_eq α] (A B : finset β) (f g : β → finset α) : -- pairs_count r (A.bUnion f) (B.bUnion g) = -- ∑ ab in A.product B, pairs_count r (f ab.1) (g ab.2) := -- begin -- simp only [pairs_count, pairs_finset_bUnion], -- rw card_bUnion, -- end /-- Edge density between two finsets of vertices -/ noncomputable def pairs_density (U V : finset α) : ℝ := pairs_count r U V / (U.card * V.card) lemma pairs_density_nonneg (U V : finset α) : 0 ≤ pairs_density r U V := by { apply div_nonneg; exact_mod_cast nat.zero_le _ } lemma pairs_density_le_one (U V : finset α) : pairs_density r U V ≤ 1 := div_le_one_of_le (by exact_mod_cast (pairs_count_le_mul _ _ _)) (by exact_mod_cast (nat.zero_le _)) lemma pairs_density_compl {U V : finset α} (hU : U.nonempty) (hV : V.nonempty) : pairs_density r U V + pairs_density (λ x y, ¬r x y) U V = 1 := begin rw [pairs_density, pairs_density, div_add_div_same, div_eq_one_iff_eq], { exact_mod_cast card_pairs_finset_compl r U V }, { exact_mod_cast (mul_pos hU.card_pos hV.card_pos).ne' }, end @[simp] lemma pairs_density_empty_left (V : finset α) : pairs_density r ∅ V = 0 := by rw [pairs_density, finset.card_empty, nat.cast_zero, zero_mul, div_zero] @[simp] lemma pairs_density_empty_right (U : finset α) : pairs_density r U ∅ = 0 := by rw [pairs_density, finset.card_empty, nat.cast_zero, mul_zero, div_zero] section symmetric variables {r} (hr : symmetric r) include hr lemma mem_pairs_finset_comm (U V : finset α) (x y : α) : (x, y) ∈ pairs_finset r U V ↔ (y, x) ∈ pairs_finset r V U := begin rw [mem_pairs_finset', mem_pairs_finset'], split; exact λ h, ⟨h.2.1, h.1, hr h.2.2⟩, end lemma pairs_count_comm (U V : finset α) : pairs_count r U V = pairs_count r V U := begin apply finset.card_congr (λ (i : α × α) hi, (i.2, i.1)) _ _ _, { rintro ⟨i, j⟩ h, rwa mem_pairs_finset_comm hr }, { rintro ⟨i₁, j₁⟩ ⟨i₂, j₂⟩ h₁ h₂ ⟨⟩, refl }, rintro ⟨i, j⟩ h, refine ⟨⟨j, i⟩, _, rfl⟩, rwa mem_pairs_finset_comm hr, end lemma pairs_density_comm (U V : finset α) : pairs_density r U V = pairs_density r V U := by rw [pairs_density, mul_comm, pairs_count_comm hr, pairs_density] end symmetric end relation /-! ## Specialization to `simple_graph` -/ namespace simple_graph variables (G : simple_graph α) [decidable_rel G.adj] open relation def edge_count (U V : finset α) : ℝ := (pairs_finset G.adj U V).card /- Remnants of what's now under `relation`. The only point for keeping it is to sometimes avoid writing `G.adj` and `G.sym` sometimes. -/ /-- Edge density between two finsets of vertices -/ noncomputable def edge_density : finset α → finset α → ℝ := pairs_density G.adj lemma edge_density_eq_edge_count_div_card (U V : finset α) : G.edge_density U V = G.edge_count U V/(U.card * V.card) := rfl lemma edge_density_comm (U V : finset α) : G.edge_density U V = G.edge_density V U := pairs_density_comm G.symm U V lemma edge_density_nonneg (U V : finset α) : 0 ≤ G.edge_density U V := pairs_density_nonneg _ U V lemma edge_density_le_one (U V : finset α) : G.edge_density U V ≤ 1 := pairs_density_le_one _ U V end simple_graph /-! ## is_uniform for simple_graph -/ namespace simple_graph variables (G : simple_graph α) (ε : ℝ) [decidable_rel G.adj] /-- A pair of finsets of vertices is ε-uniform iff their edge density is close to the density of any big enough pair of subsets. Intuitively, the edges between them are random-like. -/ def is_uniform (U V : finset α) : Prop := ∀ U', U' ⊆ U → ∀ V', V' ⊆ V → (U.card : ℝ) * ε ≤ U'.card → (V.card : ℝ) * ε ≤ V'.card → abs (edge_density G U' V' - edge_density G U V) < ε /-- If the pair `(U, V)` is `ε`-uniform and `ε ≤ ε'`, then it is `ε'`-uniform. -/ lemma is_uniform_mono {ε ε' : ℝ} {U V : finset α} (h : ε ≤ ε') (hε : is_uniform G ε U V) : is_uniform G ε' U V := λ U' hU' V' hV' hU hV, begin refine (hε _ hU' _ hV' (le_trans _ hU) (le_trans _ hV)).trans_le h; exact mul_le_mul_of_nonneg_left h (nat.cast_nonneg _), end lemma is_uniform.symm {G : simple_graph α} [decidable_rel G.adj] {ε : ℝ} : symmetric (is_uniform G ε) := begin intros U V h V' hV' U' hU' hV hU, rw [edge_density_comm _ V', edge_density_comm _ V], apply h _ hU' _ hV' hU hV, end lemma is_uniform_comm {U V : finset α} : is_uniform G ε U V ↔ is_uniform G ε V U := ⟨λ h, h.symm, λ h, h.symm⟩ lemma is_uniform_singleton {ε : ℝ} {x y : α} (hε : 0 < ε) : G.is_uniform ε {x} {y} := begin rintro U' hU' V' hV' hU hV, rw [card_singleton, nat.cast_one, one_mul] at hU hV, obtain rfl | rfl := finset.subset_singleton_iff.1 hU', { rw [finset.card_empty] at hU, exact (hε.not_le hU).elim }, obtain rfl | rfl := finset.subset_singleton_iff.1 hV', { rw [finset.card_empty] at hV, exact (hε.not_le hV).elim }, rwa [sub_self, abs_zero], end lemma not_is_uniform_zero {U V : finset α} : ¬ G.is_uniform 0 U V := λ h, not_le_of_lt (h ∅ (by simp) ∅ (by simp) (by simp) (by simp)) (abs_nonneg _) variables {ε} lemma is_uniform_of_one_le (hε : 1 ≤ ε) {U V : finset α} : G.is_uniform ε U V := begin intros U' hU' V' hV' hU hV, have hU'' := nat.cast_le.1 ((le_mul_of_one_le_right (nat.cast_nonneg _) hε).trans hU), have hV'' := nat.cast_le.1 ((le_mul_of_one_le_right (nat.cast_nonneg _) hε).trans hV), rw [eq_of_subset_of_card_le hU' hU'', eq_of_subset_of_card_le hV' hV'', sub_self, abs_zero], linarith end end simple_graph /-! ## pairs_count with finpartition -/ namespace relation variables [decidable_eq α] {r : α → α → Prop} [decidable_rel r] lemma pairs_count_finpartition_left {U : finset α} (P : finpartition U) (V : finset α) : pairs_count r U V = ∑ a in P.parts, pairs_count r a V := begin simp_rw [pairs_count, ←P.bUnion_parts, pairs_finset_bUnion_left, id.def], rw card_bUnion, exact λ x hx y hy h, pairs_finset_disjoint_left r (P.disjoint hx hy h) _, end lemma pairs_count_finpartition_right (U : finset α) {V : finset α} (P : finpartition V) : pairs_count r U V = ∑ b in P.parts, pairs_count r U b := begin simp_rw [pairs_count, ←P.bUnion_parts, pairs_finset_bUnion_right, id], rw card_bUnion, exact λ x hx y hy h, pairs_finset_disjoint_right r _ (P.disjoint hx hy h), end lemma pairs_count_finpartition {U V : finset α} (P : finpartition U) (Q : finpartition V) : pairs_count r U V = ∑ ab in P.parts.product Q.parts, pairs_count r ab.1 ab.2 := by simp_rw [pairs_count_finpartition_left P, pairs_count_finpartition_right _ Q, sum_product] end relation /-! ## is_equipartition -/ namespace finpartition variables [decidable_eq α] {s : finset α} (P : finpartition s) /-- An equipartition is a partition whose parts are all the same size, up to a difference of `1`. -/ def is_equipartition : Prop := (P.parts : set (finset α)).equitable_on card lemma is_equipartition_iff_card_parts_eq_average : P.is_equipartition ↔ ∀ a : finset α, a ∈ P.parts → a.card = s.card/P.parts.card ∨ a.card = s.card/P.parts.card + 1 := by simp_rw [is_equipartition, finset.equitable_on_iff, P.sum_card_parts] variables {P} lemma _root_.set.subsingleton.is_equipartition (h : (P.parts : set (finset α)).subsingleton) : P.is_equipartition := h.equitable_on _ end finpartition lemma finpartition.is_equipartition_iff_card_parts_eq_average' [decidable_eq α] [fintype α] {P : finpartition (univ : finset α)} : P.is_equipartition ↔ ∀ a : finset α, a ∈ P.parts → a.card = card α/P.parts.card ∨ a.card = card α/P.parts.card + 1 := by rw [P.is_equipartition_iff_card_parts_eq_average, card_univ] lemma finpartition.is_equipartition.average_le_card_part [decidable_eq α] [fintype α] {P : finpartition (univ : finset α)} (hP : P.is_equipartition) {a : finset α} (ha : a ∈ P.parts) : card α/P.parts.card ≤ a.card := (finpartition.is_equipartition_iff_card_parts_eq_average'.1 hP a ha).elim ge_of_eq (λ h, (nat.le_succ _).trans h.ge) lemma finpartition.is_equipartition.card_part_le_average_add_one [decidable_eq α] [fintype α] {P : finpartition (univ : finset α)} (hP : P.is_equipartition) {a : finset α} (ha : a ∈ P.parts) : a.card ≤ card α/P.parts.card + 1 := (finpartition.is_equipartition_iff_card_parts_eq_average'.1 hP a ha).elim (λ i, by simp [i]) le_of_eq /-! ### Discrete and indiscrete finpartition -/ namespace finpartition variables [decidable_eq α] (s : finset α) lemma bot_is_equipartition : (⊥ : finpartition s).is_equipartition := set.equitable_on_iff_exists_eq_eq_add_one.2 ⟨1, by simp⟩ lemma indiscrete_is_equipartition {hs : s ≠ ∅} : (indiscrete hs).is_equipartition := by { rw [is_equipartition, indiscrete_parts, coe_singleton], exact set.equitable_on_singleton s _ } lemma parts_top_subset [lattice α] [order_bot α] (a : α) : (⊤ : finpartition a).parts ⊆ {a} := begin rintro b hb, change b ∈ finpartition.parts (dite _ _ _) at hb, split_ifs at hb, { simp only [copy_parts, empty_parts, not_mem_empty] at hb, exact hb.elim }, { exact hb } end lemma parts_top_subsingleton [lattice α] [order_bot α] (a : α) : ((⊤ : finpartition a).parts : set α).subsingleton := set.subsingleton_of_subset_singleton $ λ b hb, mem_singleton.1 $ parts_top_subset _ hb lemma top_is_equipartition : (⊤ : finpartition s).is_equipartition := (parts_top_subsingleton _).is_equipartition end finpartition
634edec11291b5115f3e573004ebc4d254b3d458
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/category_theory/triangulated/basic.lean
055cd606fda222c9b5e1a3627444028f0ef5a41c
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,115
lean
/- Copyright (c) 2021 Luke Kershaw. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Kershaw -/ import category_theory.additive.basic import category_theory.shift import category_theory.preadditive.additive_functor /-! # Triangles This file contains the definition of triangles in an additive category with an additive shift. It also defines morphisms between these triangles. TODO: generalise this to n-angles in n-angulated categories as in https://arxiv.org/abs/1006.4592 -/ noncomputable theory open category_theory open category_theory.preadditive open category_theory.limits universes v v₀ v₁ v₂ u u₀ u₁ u₂ namespace category_theory.triangulated open category_theory.category /- We work in a category `C` equipped with a shift. -/ variables (C : Type u) [category.{v} C] [has_shift C] /-- A triangle in `C` is a sextuple `(X,Y,Z,f,g,h)` where `X,Y,Z` are objects of `C`, and `f : X ⟶ Y`, `g : Y ⟶ Z`, `h : Z ⟶ X⟦1⟧` are morphisms in `C`. See https://stacks.math.columbia.edu/tag/0144. -/ structure triangle := mk' :: (obj₁ : C) (obj₂ : C) (obj₃ : C) (mor₁ : obj₁ ⟶ obj₂) (mor₂ : obj₂ ⟶ obj₃) (mor₃ : obj₃ ⟶ obj₁⟦1⟧) /-- A triangle `(X,Y,Z,f,g,h)` in `C` is defined by the morphisms `f : X ⟶ Y`, `g : Y ⟶ Z` and `h : Z ⟶ X⟦1⟧`. -/ @[simps] def triangle.mk {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) (h : Z ⟶ X⟦1⟧) : triangle C := { obj₁ := X, obj₂ := Y, obj₃ := Z, mor₁ := f, mor₂ := g, mor₃ := h } section variables [has_zero_object C] [has_zero_morphisms C] local attribute [instance] has_zero_object.has_zero instance : inhabited (triangle C) := ⟨⟨0,0,0,0,0,0⟩⟩ /-- For each object in `C`, there is a triangle of the form `(X,X,0,𝟙 X,0,0)` -/ @[simps] def contractible_triangle (X : C) : triangle C := triangle.mk C (𝟙 X) (0 : X ⟶ 0) 0 end variable {C} /-- A morphism of triangles `(X,Y,Z,f,g,h) ⟶ (X',Y',Z',f',g',h')` in `C` is a triple of morphisms `a : X ⟶ X'`, `b : Y ⟶ Y'`, `c : Z ⟶ Z'` such that `a ≫ f' = f ≫ b`, `b ≫ g' = g ≫ c`, and `a⟦1⟧' ≫ h = h' ≫ c`. In other words, we have a commutative diagram: ``` f g h X ───> Y ───> Z ───> X⟦1⟧ │ │ │ │ │a │b │c │a⟦1⟧' V V V V X' ───> Y' ───> Z' ───> X'⟦1⟧ f' g' h' ``` See https://stacks.math.columbia.edu/tag/0144. -/ @[ext] structure triangle_morphism (T₁ : triangle C) (T₂ : triangle C) := (hom₁ : T₁.obj₁ ⟶ T₂.obj₁) (hom₂ : T₁.obj₂ ⟶ T₂.obj₂) (hom₃ : T₁.obj₃ ⟶ T₂.obj₃) (comm₁' : T₁.mor₁ ≫ hom₂ = hom₁ ≫ T₂.mor₁ . obviously) (comm₂' : T₁.mor₂ ≫ hom₃ = hom₂ ≫ T₂.mor₂ . obviously) (comm₃' : T₁.mor₃ ≫ hom₁⟦1⟧' = hom₃ ≫ T₂.mor₃ . obviously) restate_axiom triangle_morphism.comm₁' restate_axiom triangle_morphism.comm₂' restate_axiom triangle_morphism.comm₃' attribute [simp, reassoc] triangle_morphism.comm₁ triangle_morphism.comm₂ triangle_morphism.comm₃ /-- The identity triangle morphism. -/ @[simps] def triangle_morphism_id (T : triangle C) : triangle_morphism T T := { hom₁ := 𝟙 T.obj₁, hom₂ := 𝟙 T.obj₂, hom₃ := 𝟙 T.obj₃ } instance (T : triangle C) : inhabited (triangle_morphism T T) := ⟨triangle_morphism_id T⟩ variables {T₁ T₂ T₃ : triangle C} /-- Composition of triangle morphisms gives a triangle morphism. -/ @[simps] def triangle_morphism.comp (f : triangle_morphism T₁ T₂) (g : triangle_morphism T₂ T₃) : triangle_morphism T₁ T₃ := { hom₁ := f.hom₁ ≫ g.hom₁, hom₂ := f.hom₂ ≫ g.hom₂, hom₃ := f.hom₃ ≫ g.hom₃ } /-- Triangles with triangle morphisms form a category. -/ @[simps] instance triangle_category : category (triangle C) := { hom := λ A B, triangle_morphism A B, id := λ A, triangle_morphism_id A, comp := λ A B C f g, f.comp g } end category_theory.triangulated
e47d00bf40f324bd6455b50c7650fae5b683085f
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/slow_error.lean
a760e3e97e8bfcd7a8e19a2912599b097891b154
[ "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
69
lean
variable a : user_attribute string variable b : string #check a = b
5babe61104c5a1c4752de7bfaf360c007360b722
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/quotient.lean
ed577b27c5b0d303c7f47cbbe10a898101b20691
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,132
lean
/- Copyright (c) 2020 David Wärn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Wärn -/ import category_theory.natural_isomorphism import category_theory.eq_to_hom /-! # Quotient category Constructs the quotient of a category by an arbitrary family of relations on its hom-sets, by introducing a type synonym for the objects, and identifying homs as necessary. This is analogous to 'the quotient of a group by the normal closure of a subset', rather than 'the quotient of a group by a normal subgroup'. When taking the quotient by a congruence relation, `functor_map_eq_iff` says that no unnecessary identifications have been made. -/ /-- A `hom_rel` on `C` consists of a relation on every hom-set. -/ @[derive inhabited] def hom_rel (C) [quiver C] := Π ⦃X Y : C⦄, (X ⟶ Y) → (X ⟶ Y) → Prop namespace category_theory variables {C : Type*} [category C] (r : hom_rel C) include r /-- A `hom_rel` is a congruence when it's an equivalence on every hom-set, and it can be composed from left and right. -/ class congruence : Prop := (is_equiv : ∀ {X Y}, is_equiv _ (@r X Y)) (comp_left : ∀ {X Y Z} (f : X ⟶ Y) {g g' : Y ⟶ Z}, r g g' → r (f ≫ g) (f ≫ g')) (comp_right : ∀ {X Y Z} {f f' : X ⟶ Y} (g : Y ⟶ Z), r f f' → r (f ≫ g) (f' ≫ g)) attribute [instance] congruence.is_equiv /-- A type synonym for `C`, thought of as the objects of the quotient category. -/ @[ext] structure quotient := (as : C) instance [inhabited C] : inhabited (quotient r) := ⟨ { as := default } ⟩ namespace quotient /-- Generates the closure of a family of relations w.r.t. composition from left and right. -/ inductive comp_closure ⦃s t : C⦄ : (s ⟶ t) → (s ⟶ t) → Prop | intro {a b} (f : s ⟶ a) (m₁ m₂ : a ⟶ b) (g : b ⟶ t) (h : r m₁ m₂) : comp_closure (f ≫ m₁ ≫ g) (f ≫ m₂ ≫ g) lemma comp_closure.of {a b} (m₁ m₂ : a ⟶ b) (h : r m₁ m₂) : comp_closure r m₁ m₂ := by simpa using comp_closure.intro (𝟙 _) m₁ m₂ (𝟙 _) h lemma comp_left {a b c : C} (f : a ⟶ b) : Π (g₁ g₂ : b ⟶ c) (h : comp_closure r g₁ g₂), comp_closure r (f ≫ g₁) (f ≫ g₂) | _ _ ⟨x, m₁, m₂, y, h⟩ := by simpa using comp_closure.intro (f ≫ x) m₁ m₂ y h lemma comp_right {a b c : C} (g : b ⟶ c) : Π (f₁ f₂ : a ⟶ b) (h : comp_closure r f₁ f₂), comp_closure r (f₁ ≫ g) (f₂ ≫ g) | _ _ ⟨x, m₁, m₂, y, h⟩ := by simpa using comp_closure.intro x m₁ m₂ (y ≫ g) h /-- Hom-sets of the quotient category. -/ def hom (s t : quotient r) := quot $ @comp_closure C _ r s.as t.as instance (a : quotient r) : inhabited (hom r a a) := ⟨quot.mk _ (𝟙 a.as)⟩ /-- Composition in the quotient category. -/ def comp ⦃a b c : quotient r⦄ : hom r a b → hom r b c → hom r a c := λ hf hg, quot.lift_on hf ( λ f, quot.lift_on hg (λ g, quot.mk _ (f ≫ g)) (λ g₁ g₂ h, quot.sound $ comp_left r f g₁ g₂ h) ) (λ f₁ f₂ h, quot.induction_on hg $ λ g, quot.sound $ comp_right r g f₁ f₂ h) @[simp] lemma comp_mk {a b c : quotient r} (f : a.as ⟶ b.as) (g : b.as ⟶ c.as) : comp r (quot.mk _ f) (quot.mk _ g) = quot.mk _ (f ≫ g) := rfl instance category : category (quotient r) := { hom := hom r, id := λ a, quot.mk _ (𝟙 a.as), comp := comp r } /-- The functor from a category to its quotient. -/ @[simps] def functor : C ⥤ quotient r := { obj := λ a, { as := a }, map := λ _ _ f, quot.mk _ f } noncomputable instance : full (functor r) := { preimage := λ X Y f, quot.out f, } instance : ess_surj (functor r) := { mem_ess_image := λ Y, ⟨Y.as, ⟨eq_to_iso (by { ext, refl, })⟩⟩ } protected lemma induction {P : Π {a b : quotient r}, (a ⟶ b) → Prop} (h : ∀ {x y : C} (f : x ⟶ y), P ((functor r).map f)) : ∀ {a b : quotient r} (f : a ⟶ b), P f := by { rintros ⟨x⟩ ⟨y⟩ ⟨f⟩, exact h f, } protected lemma sound {a b : C} {f₁ f₂ : a ⟶ b} (h : r f₁ f₂) : (functor r).map f₁ = (functor r).map f₂ := by simpa using quot.sound (comp_closure.intro (𝟙 a) f₁ f₂ (𝟙 b) h) lemma functor_map_eq_iff [congruence r] {X Y : C} (f f' : X ⟶ Y) : (functor r).map f = (functor r).map f' ↔ r f f' := begin split, { erw quot.eq, intro h, induction h with m m' hm, { cases hm, apply congruence.comp_left, apply congruence.comp_right, assumption, }, { apply refl }, { apply symm, assumption }, { apply trans; assumption }, }, { apply quotient.sound }, end variables {D : Type*} [category D] (F : C ⥤ D) (H : ∀ (x y : C) (f₁ f₂ : x ⟶ y), r f₁ f₂ → F.map f₁ = F.map f₂) include H /-- The induced functor on the quotient category. -/ @[simps] def lift : quotient r ⥤ D := { obj := λ a, F.obj a.as, map := λ a b hf, quot.lift_on hf (λ f, F.map f) (by { rintro _ _ ⟨_, _, _, _, h⟩, simp [H _ _ _ _ h], }), map_id' := λ a, F.map_id a.as, map_comp' := by { rintros a b c ⟨f⟩ ⟨g⟩, exact F.map_comp f g, } } lemma lift_spec : (functor r) ⋙ lift r F H = F := begin apply functor.ext, rotate, { rintro X, refl, }, { rintro X Y f, simp, }, end lemma lift_unique (Φ : quotient r ⥤ D) (hΦ : (functor r) ⋙ Φ = F) : Φ = lift r F H := begin subst_vars, apply functor.hext, { rintro X, dsimp [lift, functor], congr, ext, refl, }, { rintro X Y f, dsimp [lift, functor], apply quot.induction_on f, rintro ff, simp only [quot.lift_on_mk, functor.comp_map], congr; ext; refl, }, end /-- The original functor factors through the induced functor. -/ def lift.is_lift : (functor r) ⋙ lift r F H ≅ F := nat_iso.of_components (λ X, iso.refl _) (by tidy) @[simp] lemma lift.is_lift_hom (X : C) : (lift.is_lift r F H).hom.app X = 𝟙 (F.obj X) := rfl @[simp] lemma lift.is_lift_inv (X : C) : (lift.is_lift r F H).inv.app X = 𝟙 (F.obj X) := rfl lemma lift_map_functor_map {X Y : C} (f : X ⟶ Y) : (lift r F H).map ((functor r).map f) = F.map f := by { rw ←(nat_iso.naturality_1 (lift.is_lift r F H)), dsimp, simp, } end quotient end category_theory
b32b06b60b48838b01a3ef89b451ab54120fc94d
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/tests/lean/run/def8.lean
5be2803e1ee30d0c2498b63474e97d943ed54ed3
[ "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
937
lean
def g : List Nat → List Nat → Nat | [], y::ys => y | [], ys => 0 | x1::x2::xs, ys => g xs ys | x::xs, y::ys => g xs ys + y | x::xs, [] => g xs [] universes u v inductive Imf {α : Type u} {β : Type v} (f : α → β) : β → Type (max u v) | mk : (a : α) → Imf f (f a) def h {α β} {f : α → β} : {b : β} → Imf f b → α | _, Imf.mk a => a theorem ex1 {α β} (f : α → β) (a : α) : h (Imf.mk (f := f) a) = a := rfl def v₁ : Imf Nat.succ 1 := Imf.mk 0 def v₂ : Imf (fun x => 1 + x) 1 := Imf.mk 0 theorem ex2 : h v₁ = 0 := rfl theorem ex3 : h v₂ = 0 := rfl theorem ex4 {α} : {a b : α} → a = b → b = a | _, _, rfl => rfl theorem ex5 {α} : {a b : α} → a = b → b = a | a, .(a), rfl => rfl theorem ex6 {α} : {a b : α} → a = b → b = a | a, .(a), Eq.refl .(a) => rfl theorem ex7 {α} : {a b : α} → a = b → b = a | .(a), a, Eq.refl .(a) => rfl
97ce49137d592db861c532d51ddf358bf811827a
0851884047bb567d19e188e8f1ad959c5ae9c5ce
/src/Topology/Material/first_attempts_homeomorphism.lean
71dd905beb1b02e3314bfd0dbb1ba3f64d1b2855
[ "Apache-2.0" ]
permissive
yz5216/xena-UROP-2018
00d3f71a831324966d40d302544ed2cbbec3fd0f
5e9da9dc64dc51897677f8b73ab9f94061a8d977
refs/heads/master
1,584,922,436,989
1,531,487,250,000
1,531,487,250,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,641
lean
import analysis.topology.continuity import analysis.topology.topological_space import analysis.topology.infinite_sum import analysis.topology.topological_structures import analysis.topology.uniform_space universes u v w open set filter lattice classical def empty_set_topology : topological_space empty := { is_open := λ (a : set empty), true, is_open_univ := begin trivial, end, is_open_inter := begin intros h1 h2 h3 h4, trivial end, is_open_sUnion := begin intros h1 h2, trivial end } #print univ #check empty_set_topology.is_open definition is_open_sets {α : Type u} (is_open : set α → Prop) := is_open univ ∧ (∀s t, is_open s → is_open t → is_open (s ∩ t)) ∧ (∀s, (∀t∈s, is_open t) → is_open (⋃₀ s)) definition is_to_top {α : Type u} (is_open : set α → Prop) (H : is_open_sets (is_open)) : topological_space α := { is_open := is_open, is_open_univ := H.left, is_open_inter := H.right.left, is_open_sUnion := H.right.right } definition top_to_is {α : Type u} (T : topological_space α) : is_open_sets (T.is_open) := ⟨T.is_open_univ,T.is_open_inter,T.is_open_sUnion⟩ --8.7 defn homeo, 8.12 continuity by bases, ex 8.4, 10.11 product topology definition I : set ℝ := λ x, x ≤ 1 ∧ x ≥ 0 --We could define these here, but they have been defined in the core definition is_injective {α : Type u} {β : Type v} (f : α → β) := ∀ x y : α, f x = f y → x = y definition is_surjective {α : Type u} {β : Type v} (f : α → β) := ∀ b : β, ∃ x : α, f(x) = b definition is_bijective {α : Type u} {β : Type v} (f : α → β) := is_injective f ∧ is_surjective f --Or we could define things using structures: structure injection (α : Type u) (β : Type v) := (f : α → β) (f_is_injective : ∀ x y : α, f x = f y → x = y) structure surjection (α : Type u) (β : Type v) := (f : α → β) (f_is_surjective : ∀ b : β, ∃ x : α, f(x) = b) structure bijection (α : Type u) (β : Type v) := (f : α → β) (f_is_injective : ∀ x y : α, f x = f y → x = y) (f_is_surjective : ∀ b : β, ∃ x : α, f(x) = b) --These can be swapped between definition bij_to_is {α : Type u} {β : Type v} (B : bijection α β) : is_bijective B.1 := ⟨B.2 , B.3⟩ definition is_to_bij {α : Type u} {β : Type v} (f : α → β) (H : is_bijective f) : bijection α β := { f := f, f_is_injective := H.1, f_is_surjective := H.2 } --First we must show that bijection is equivalent to having a two-sided inverse def two_sided_inverse {α : Type u} {β : Type v} (g : β → α) (f : α → β) : Prop := function.left_inverse g f ∧ function.right_inverse g f theorem two_sided_inverse_iff_bijection {α : Type u} {β : Type v} {f : α → β} : (∃ g : β → α, two_sided_inverse g f) ↔ function.bijective f := begin admit, end --Here we use the definition bijective from the core. definition open_mapping {α : Type u} {β : Type v} [topological_space α] [topological_space β] (f : α → β) := ∀s : set α, is_open s → is_open (set.image f s) definition is_homeomorphism {α : Type u} {β : Type v} [topological_space α] [topological_space β] (f : α → β) := continuous f ∧ function.bijective f ∧ open_mapping f -- Square brackets okay? definition is_homeomorphic_to {α : Type u} {β : Type v} (X :topological_space α) (Y : topological_space β) := ∃ f : α → β, is_homeomorphism f structure homeomorphism1 {α : Type u} {β : Type v} (X : topological_space α) (Y : topological_space β) := (f : α → β) (is_homeomorphism : is_homeomorphism f) definition id_is_homeomorphism {α : Type u} {X : topological_space α} : homeomorphism1 X X := {f := id, is_homeomorphism := begin unfold is_homeomorphism, split, unfold continuous, unfold set.preimage, intros s H1, unfold id, exact H1, split, apply function.bijective_id, unfold open_mapping, intros s H, unfold set.image, unfold id, simp, assumption, end } theorem homeomorphism_is_reflexive : reflexive (λ X Y : Σ α, topological_space α, is_homeomorphic_to X.2 Y.2) := begin unfold reflexive, intro top, unfold is_homeomorphic_to, existsi id, exact id_is_homeomorphism.2, end --FOR THIS IT WOULD BE NICE TO HAVE AN INVERSE FUNCTION EXPLICIT theorem homeomorphism_is_symmetric : symmetric (λ X Y : Σ α, topological_space α, is_homeomorphic_to X.2 Y.2) := begin unfold symmetric, intros X Y, unfold is_homeomorphic_to, admit, end theorem homeomorphism_is_equiv_rel : equivalence (λ X Y : Σ α, topological_space α, is_homeomorphic_to X.2 Y.2) := begin admit, end --We require β : Sort v and two topological spaces of type β --Sort?
3c932a0b71050ad98f53c99e7bb207465f258785
367134ba5a65885e863bdc4507601606690974c1
/src/category_theory/monoidal/internal/Module.lean
2f85876d65dcf95d10f89af2a6e324c6d6f4aa88
[ "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
5,002
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 algebra.category.Module.monoidal import algebra.category.Algebra.basic import category_theory.monoidal.Mon_ /-! # `Mon_ (Module R) ≌ Algebra R` The category of internal monoid objects in `Module R` is equivalent to the category of "native" bundled `R`-algebras. Moreover, this equivalence is compatible with the forgetful functors to `Module R`. -/ universes v u open category_theory open linear_map open_locale tensor_product namespace Module variables {R : Type u} [comm_ring R] namespace Mon_Module_equivalence_Algebra @[simps] instance (A : Mon_ (Module.{u} R)) : ring A.X := { one := A.one (1 : R), mul := λ x y, A.mul (x ⊗ₜ y), one_mul := λ x, by { convert linear_map.congr_fun A.one_mul ((1 : R) ⊗ₜ x), simp, }, mul_one := λ x, by { convert linear_map.congr_fun A.mul_one (x ⊗ₜ (1 : R)), simp, }, mul_assoc := λ x y z, by convert linear_map.congr_fun A.mul_assoc ((x ⊗ₜ y) ⊗ₜ z), left_distrib := λ x y z, begin convert A.mul.map_add (x ⊗ₜ y) (x ⊗ₜ z), rw ←tensor_product.tmul_add, refl, end, right_distrib := λ x y z, begin convert A.mul.map_add (x ⊗ₜ z) (y ⊗ₜ z), rw ←tensor_product.add_tmul, refl, end, ..(by apply_instance : add_comm_group A.X) } instance (A : Mon_ (Module.{u} R)) : algebra R A.X := { map_zero' := A.one.map_zero, map_one' := rfl, map_mul' := λ x y, begin have h := linear_map.congr_fun A.one_mul.symm (x ⊗ₜ (A.one y)), rwa [monoidal_category.left_unitor_hom_apply, ←A.one.map_smul] at h, end, commutes' := λ r a, begin dsimp, have h₁ := linear_map.congr_fun A.one_mul (r ⊗ₜ a), have h₂ := linear_map.congr_fun A.mul_one (a ⊗ₜ r), exact h₁.trans h₂.symm, end, smul_def' := λ r a, by { convert (linear_map.congr_fun A.one_mul (r ⊗ₜ a)).symm, simp, }, ..A.one } @[simp] lemma algebra_map (A : Mon_ (Module.{u} R)) (r : R) : algebra_map R A.X r = A.one r := rfl /-- Converting a monoid object in `Module R` to a bundled algebra. -/ @[simps] def functor : Mon_ (Module.{u} R) ⥤ Algebra R := { obj := λ A, Algebra.of R A.X, map := λ A B f, { to_fun := f.hom, map_one' := linear_map.congr_fun f.one_hom (1 : R), map_mul' := λ x y, linear_map.congr_fun f.mul_hom (x ⊗ₜ y), commutes' := λ r, linear_map.congr_fun f.one_hom r, ..(f.hom.to_add_monoid_hom) }, }. /-- Converting a bundled algebra to a monoid object in `Module R`. -/ @[simps] def inverse_obj (A : Algebra.{u} R) : Mon_ (Module.{u} R) := { X := Module.of R A, one := algebra.linear_map R A, mul := @algebra.lmul' R A _ _ _, one_mul' := begin ext x, dsimp, rw [algebra.lmul'_apply, monoidal_category.left_unitor_hom_apply, algebra.smul_def], refl, end, mul_one' := begin ext x, dsimp, rw [algebra.lmul'_apply, monoidal_category.right_unitor_hom_apply, ←algebra.commutes, algebra.smul_def], refl, end, mul_assoc' := begin ext x y z, dsimp, simp only [mul_assoc, algebra.lmul'_apply], end } /-- Converting a bundled algebra to a monoid object in `Module R`. -/ @[simps] def inverse : Algebra.{u} R ⥤ Mon_ (Module.{u} R) := { obj := inverse_obj, map := λ A B f, { hom := f.to_linear_map, }, }. end Mon_Module_equivalence_Algebra open Mon_Module_equivalence_Algebra /-- The category of internal monoid objects in `Module R` is equivalent to the category of "native" bundled `R`-algebras. -/ def Mon_Module_equivalence_Algebra : Mon_ (Module.{u} R) ≌ Algebra R := { functor := functor, inverse := inverse, unit_iso := nat_iso.of_components (λ A, { hom := { hom := { to_fun := id, map_add' := λ x y, rfl, map_smul' := λ r a, rfl, } }, inv := { hom := { to_fun := id, map_add' := λ x y, rfl, map_smul' := λ r a, rfl, } } }) (by tidy), counit_iso := nat_iso.of_components (λ A, { hom := { to_fun := id, map_zero' := rfl, map_add' := λ x y, rfl, map_one' := (algebra_map R A).map_one, map_mul' := λ x y, algebra.lmul'_apply, commutes' := λ r, rfl, }, inv := { to_fun := id, map_zero' := rfl, map_add' := λ x y, rfl, map_one' := (algebra_map R A).map_one.symm, map_mul' := λ x y, algebra.lmul'_apply.symm, commutes' := λ r, rfl } }) (by tidy), }. /-- The equivalence `Mon_ (Module R) ≌ Algebra R` is naturally compatible with the forgetful functors to `Module R`. -/ def Mon_Module_equivalence_Algebra_forget : Mon_Module_equivalence_Algebra.functor ⋙ forget₂ (Algebra.{u} R) (Module.{u} R) ≅ Mon_.forget (Module.{u} R):= nat_iso.of_components (λ A, { hom := { to_fun := id, map_add' := λ x y, rfl, map_smul' := λ c x, rfl }, inv := { to_fun := id, map_add' := λ x y, rfl, map_smul' := λ c x, rfl }, }) (by tidy) end Module
b33eef408e00745e38902f932443155c2f2816f4
5ca87fb2890eabae94422af0565520bfafd6c4ae
/lean/elf.lean
ae1941d36abe6d253acdfe80e2ba27d4294e7d78
[ "Apache-2.0" ]
permissive
dagit/reopt-vcg
5b7e1a0eceaac4736fd8ab8985d861c86ac5cff2
a80da1c1ff8dbf28d864b30999b166f76e66e231
refs/heads/master
1,585,418,433,534
1,541,806,437,000
1,541,806,437,000
148,844,174
0
0
null
1,536,960,966,000
1,536,960,966,000
null
UTF-8
Lean
false
false
14,468
lean
/- This file contains the start of an Elf parser for Lean. It currently has facilities for parsing Elf -/ import system.io import init.category.reader def repeat {α : Type} {m : Type → Type} [applicative m] : ℕ → m α → m (list α) | 0 m := pure [] | (nat.succ n) m := list.cons <$> m <*> repeat n m def forM' {m : Type → Type} [monad m] {α : Type} {β:Type} (l:list α) (f:α → m β) : m unit := list.mmap' f l def bracket {α β:Type} (c:io α) (d:α → io unit) (f:α → io β) := do x ← c, io.finally (f x) (d x) @[reducible] def uint8 := fin (nat.succ 0xff) @[reducible] def uint16 := fin (nat.succ 0xffff) @[reducible] def uint32 := fin (nat.succ 0xffffffff) @[reducible] def uint64 := fin (nat.succ 0xffffffffffffffff) namespace buffer @[reducible] def reader := except_t string (state char_buffer) namespace reader protected def read_chars (n:ℕ) : reader (list char) := do s ← get, when (s.size < n) (throw "read_chars eof"), put $ s.drop n, return ((s.take n).to_list) def skip (n:ℕ) : reader unit := do s ← get, when (s.size < n) (throw "skip eof"), put $ s.drop n def read_uint8 : reader uint8 := do l ← reader.read_chars 1, match l with | [h] := do return $ fin.of_nat h.val | _ := throw "internal: read_uint8" end def from_handle {α} (h:io.handle) (n:ℕ) (r:reader α) : io α := do b ← io.fs.read h n, match r.run.run b with | ⟨except.ok r,b'⟩ := do pure r | ⟨except.error e, b'⟩ := do io.fail e end end reader end buffer namespace elf def magic : list char := ['\x7f', 'E', 'L', 'F' ] inductive elf_class | ELF32 : elf_class | ELF64 : elf_class namespace elf_class protected def repr : elf_class → string | ELF32 := "ELF32" | ELF64 := "ELF64" protected def bytes : elf_class → ℕ | ELF32 := 4 | ELF64 := 8 protected def bits : elf_class → ℕ | ELF32 := 32 | ELF64 := 64 end elf_class inductive elf_data | ELFDATA2LSB : elf_data | ELFDATA2MSB : elf_data namespace elf_data protected def repr : elf_data → string | ELFDATA2LSB := "ELFDATA2LSB" | ELFDATA2MSB := "ELFDATA2MSB" end elf_data open elf_class open elf_data structure osabi := (val : uint8) namespace osabi protected def repr (o:osabi) : string := match o.val.val with | 0 := "UNIX - System V" | v := v.repr end end osabi -- Information from first 16-bytes of Elf file (allows reading rest of file). structure info := (elf_class : elf_class) (elf_data : elf_data) (osabi : osabi) (abi_version : uint8) namespace info protected def pp (e:info) : string := "Class: " ++ e.elf_class.repr ++ "\n" ++ "Data: " ++ e.elf_data.repr ++ "\n" ++ "OS/ABI: " ++ e.osabi.repr ++ "\n" ++ "ABI Version: " ++ e.abi_version.val.repr ++ "\n" open buffer def read : reader info := do b ← reader.read_chars 4, when (b ≠ magic) (throw "Not an elf file."), cl_val ← reader.read_uint8, cl ← match cl_val.val with | 1 := pure ELF32 | 2 := pure ELF64 | _ := throw "Invalid elf data." end, dt_val ← reader.read_uint8, dt ← match dt_val.val with | 1 := pure ELFDATA2LSB | 2 := pure ELFDATA2MSB | _ := throw "Invalid elf data." end, elf_version ← reader.read_uint8, when (elf_version ≠ 1) (throw "Mismatched elf version."), osabi ← reader.read_uint8, osabi_ver ← reader.read_uint8, pure { elf_class := cl , elf_data := dt , osabi := ⟨osabi⟩ , abi_version := osabi_ver } end info -- A reader for elf files @[reducible] def file_reader := reader_t info buffer.reader namespace file_reader protected def from_handle {α:Type} (i:info) (h:io.handle) (n:ℕ) (r:file_reader α) : io α := do b ← io.fs.read h n, match (r.run i).run.run b with | ⟨except.ok r, b'⟩ := do pure r | ⟨except.error e, b'⟩ := do io.fail e end def read_u8 : file_reader uint8 := reader_t.lift $ buffer.reader.read_uint8 protected def read_chars_lsb (w:ℕ) : file_reader (list char) := do i ← read, let f (l:list char) : list char := match i.elf_data with | ELFDATA2LSB := l | ELFDATA2MSB := l.reverse end in do reader_t.lift $ f <$> buffer.reader.read_chars w def read_u16 : file_reader uint16 := do l ← file_reader.read_chars_lsb 2, match l with | [x0,x1] := return $ fin.of_nat $ nat.shiftl x1.val 8 + x0.val | _ := throw "internal: read_uint16" end def read_u32 : file_reader uint32 := do l ← file_reader.read_chars_lsb 4, match l with | [x0,x1,x2,x3] := return $ fin.of_nat $ nat.shiftl x3.val 24 + nat.shiftl x2.val 16 + nat.shiftl x1.val 8 + x0.val | _ := throw "internal: read_uint32" end def read_u64 : file_reader uint64 := do l ← file_reader.read_chars_lsb 8, match l with | [x0,x1,x2,x3, x4, x5, x6, x7] := return $ fin.of_nat $ nat.shiftl x7.val 56 + nat.shiftl x6.val 48 + nat.shiftl x5.val 40 + nat.shiftl x4.val 32 + nat.shiftl x3.val 24 + nat.shiftl x2.val 16 + nat.shiftl x1.val 8 + x0.val | _ := throw "internal: read_uint64" end end file_reader class elf_file_data (α:Type) := (read {} : file_reader α) instance uint16_si_elf_file_data : elf_file_data uint16 := { read := file_reader.read_u16 } -- A 32 or 64-bit word dependent on the class. def word (c:elf_class) := fin (nat.succ (2^c.bits-1)) namespace word protected def to_hex_with_leading_zeros : list char → ℕ → ℕ → string | prev 0 _ := prev.as_string | prev (nat.succ w) x := let c := (nat.land x 0xf).digit_char in to_hex_with_leading_zeros (c::prev) w (nat.shiftr x 4) protected def to_hex' : list char → ℕ → ℕ → string | prev 0 _ := prev.as_string | prev w 0 := prev.as_string | prev (nat.succ w) x := let c := (nat.land x 0xf).digit_char in to_hex' (c::prev) w (nat.shiftr x 4) -- Print word as decinal protected def pp_dec : Π{c:elf_class}, word c → string | ELF32 v := v.val.repr | ELF64 v := v.val.repr --- Print word as hex protected def pp_hex : Π{c:elf_class}, word c → string | ELF32 v := "0x" ++ word.to_hex' [] 8 v.val | ELF64 v := "0x" ++ word.to_hex' [] 16 v.val protected def size : elf_class → ℕ := elf_class.bytes theorem dbl_is_bit0 (x y:ℕ) : bit0 x*y = bit0 (x*y) := begin simp [bit0, nat.right_distrib], end --- `bit1_dec d x` is a utility function that denotes `(d+1)*x-1` -- It is primarily used def bit1_dec : ℕ → ℕ → ℕ | d x := (d+1)*x-1 theorem bit0_sub_1_congr (x:ℕ) : bit0 x - 1 = bit1_dec 1 x := begin simp [bit1_dec, bit1, bit0, nat.add_succ, nat.succ_mul], end theorem bit1_dec_bit0 (d x:ℕ) : bit1_dec d (bit0 x) = bit1_dec (bit1 d) x := begin simp [bit1_dec, bit1, bit0, nat.add_succ, nat.succ_mul, nat.left_distrib, nat.right_distrib], end theorem bit1_dec_one (d:ℕ) : bit1_dec d 1 = d := begin simp [bit1_dec], end theorem word32_is_uint32 : uint32 = word ELF32 := begin simp [uint32, word, elf_class.bits, has_pow.pow, nat.pow, dbl_is_bit0, bit0_sub_1_congr , bit1_dec_bit0, bit1_dec_one], end theorem word64_is_uint64 : uint64 = word ELF64 := begin simp [uint32, word, elf_class.bits, has_pow.pow, nat.pow, dbl_is_bit0, bit0_sub_1_congr , bit1_dec_bit0, bit1_dec_one], end instance (c:elf_class) : elf_file_data (word c) := { read := do match c with | ELF32 := eq.mp word32_is_uint32 <$> file_reader.read_u32 | ELF64 := eq.mp word64_is_uint64 <$> file_reader.read_u64 end } end word ------------------------------------------------------------------------ -- phdr structure phdr_type := (val : uint32) namespace phdr_type instance : elf_file_data phdr_type := { read := mk <$> file_reader.read_u32 } end phdr_type /-- Flags for a program header. -/ structure phdr_flags := (val : uint32) namespace phdr_flags instance : elf_file_data phdr_flags := { read := mk <$> file_reader.read_u32 } end phdr_flags structure phdr (c:elf_class) := (phdr_type : phdr_type) (flags : phdr_flags) (offset : word c) (vaddr : word c) (paddr : word c) (filesz : word c) (memsz : word c) (align : word c) namespace phdr def size (c:elf_class) : ℕ := 8 + 6 * word.size c protected def pp {c:elf_class} (x:phdr c) := "Type: " ++ x.phdr_type.val.val.repr ++ "\n" ++ "Flags: " ++ x.flags.val.val.repr ++ "\n" ++ "File Offset: " ++ x.offset.pp_dec ++ "\n" ++ "Virtual Address: " ++ x.vaddr.pp_hex ++ "\n" ++ "Physical Address: " ++ x.paddr.pp_hex ++ "\n" ++ "File Size: " ++ x.filesz.pp_dec ++ "\n" ++ "Memory Size: " ++ x.memsz.pp_dec ++ "\n" ++ "Alignment: " ++ x.memsz.pp_hex ++ "\n" end phdr def read_phdr : Π(c:elf_class), file_reader (phdr c) | ELF32 := do tp ← elf_file_data.read, offset ← elf_file_data.read, vaddr ← elf_file_data.read, paddr ← elf_file_data.read, filesz ← elf_file_data.read, memsz ← elf_file_data.read, flags ← elf_file_data.read, align ← elf_file_data.read, pure { phdr_type := tp , flags := flags , offset := offset , vaddr := vaddr , paddr := paddr , filesz := filesz , memsz := memsz , align := align } | ELF64 := do tp ← elf_file_data.read, flags ← elf_file_data.read, offset ← elf_file_data.read, vaddr ← elf_file_data.read, paddr ← elf_file_data.read, filesz ← elf_file_data.read, memsz ← elf_file_data.read, align ← elf_file_data.read, pure { phdr_type := tp , flags := flags , offset := offset , vaddr := vaddr , paddr := paddr , filesz := filesz , memsz := memsz , align := align } ------------------------------------------------------------------------ -- ehdr /-- Elf file type -/ structure elf_type := (val : uint16) namespace elf_type instance : elf_file_data elf_type := { read := elf_type.mk <$> file_reader.read_u16 } end elf_type /-- Elf header machine type. -/ structure machine := (val : uint16) namespace machine instance : elf_file_data machine := { read := machine.mk <$> file_reader.read_u16 } end machine /-- Flags for a elf header. -/ structure ehdr_flags := (val : uint32) namespace ehdr_flags instance : elf_file_data ehdr_flags := { read := ehdr_flags.mk <$> file_reader.read_u32 } end ehdr_flags /-- The elf header information -/ structure ehdr := (info : info) (elf_type : elf_type) (machine : machine) (entry : word info.elf_class) (phoff : word info.elf_class) (shoff : word info.elf_class) (flags : ehdr_flags) (phnum : uint16) (shnum : uint16) (shstrndx : uint16) namespace ehdr -- Number of bytes in the ehdr after the 16 byte info. protected def size (c:elf_class) : ℕ := 16 + 24 + 3 * c.bytes protected def elf_class (e:ehdr) := e.info.elf_class protected def pp (e:ehdr) := e.info.pp ++ "Type: " ++ e.elf_type.val.val.repr ++ "\n" ++ "Machine: " ++ e.machine.val.val.repr ++ "\n" ++ "Entry point address: " ++ e.entry.pp_hex ++ "\n" ++ "Start of program headers: " ++ e.phoff.val.repr ++ " (bytes into file)\n" ++ "Start of section headers: " ++ e.shoff.val.repr ++ " (bytes into file)\n" ++ "Flags: " ++ e.flags.val.val.repr ++ "\n" ++ "Number of program headers: " ++ e.phnum.val.repr ++ "\n" ++ "Number of section headers: " ++ e.shnum.val.repr ++ "\n" ++ "Section header string table index: " ++ e.shstrndx.val.repr ++ "\n" end ehdr -- Read the remainder of the elf header after the first 16 bytes for the info. def read_ehdr_remainder : file_reader ehdr := do i ← read, tp ← elf_file_data.read, mach ← elf_file_data.read, ver ← file_reader.read_u32, when (ver ≠ 1) (throw $ "Unexpected version: " ++ ver.val.repr), entry ← elf_file_data.read, phoff ← elf_file_data.read, shoff ← elf_file_data.read, flags ← elf_file_data.read, _ehsize ← file_reader.read_u16, _phentsize ← file_reader.read_u16, phnum ← elf_file_data.read, _shentsize ← file_reader.read_u16, shnum ← elf_file_data.read, shstrndx ← elf_file_data.read, pure { info := i , elf_type := tp , machine := mach , entry := entry , phoff := phoff , shoff := shoff , flags := flags , phnum := phnum , shnum := shnum , shstrndx := shstrndx } -- The the elf header from the handle (which should be at the -- beginning of the file. def read_ehdr_from_handle (h:io.handle) : io ehdr := do i ← buffer.reader.from_handle h 16 info.read, let ehdr_size := ehdr.size i.elf_class in do file_reader.from_handle i h (ehdr_size - 16) read_ehdr_remainder -- Return size of phdr table def phdr_table_size (e:ehdr) : ℕ := phdr.size e.elf_class * e.phnum.val def read_phdrs_from_handle (e:ehdr) (h:io.handle) : io (list (phdr e.elf_class)) := file_reader.from_handle (e.info) h (phdr_table_size e) ( repeat (e.phnum.val) $ read_phdr e.elf_class) -- Move from current offset to target offset. def move_to_target (h:io.handle) (cur_off:ℕ) (target_off:ℕ) : io unit := if target_off < cur_off then do io.fail "Unexpected phdr offset" else do _ ← io.fs.read h (target_off - cur_off), pure () def pp_phdrs {c:elf_class} (phdrs:list (phdr c)) : io unit := do forM' (list.zip (list.range phdrs.length) phdrs) (λphdr, do let idx := phdr.fst in do io.put_str_ln $ "Index: " ++ idx.repr, io.put_str_ln phdr.snd.pp) /--- Read the elf file from the given path, and print out ehdr and program headers. -/ def read_info_from_file (path:string) : io unit := do bracket (io.mk_file_handle path io.mode.read tt) io.fs.close $ λh, do e ← read_ehdr_from_handle h, let i := e.info in do let ehdr_size := ehdr.size i.elf_class in do move_to_target h ehdr_size e.phoff.val, phdrs ← read_phdrs_from_handle e h, pp_phdrs phdrs end elf def get_filename_arg : io string := do args ← io.cmdline_args, match args with | [name] := do return name | _ := do io.fail "Please provide single argument containing path to elf file." end def main : io unit := do args ← get_filename_arg, io.print_ln args
53c8542263b573ee7830cbe21a198ef54e8ed3fa
9dc8cecdf3c4634764a18254e94d43da07142918
/src/field_theory/tower.lean
c1bfff5697175cda4dad488bbc43b2664a94617b
[ "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
5,538
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import ring_theory.algebra_tower import linear_algebra.matrix.finite_dimensional import linear_algebra.matrix.to_lin /-! # Tower of field extensions In this file we prove the tower law for arbitrary extensions and finite extensions. Suppose `L` is a field extension of `K` and `K` is a field extension of `F`. Then `[L:F] = [L:K] [K:F]` where `[E₁:E₂]` means the `E₂`-dimension of `E₁`. In fact we generalize it to vector spaces, where `L` is not necessarily a field, but just a vector space over `K`. ## Implementation notes We prove two versions, since there are two notions of dimensions: `module.rank` which gives the dimension of an arbitrary vector space as a cardinal, and `finite_dimensional.finrank` which gives the dimension of a finitely-dimensional vector space as a natural number. ## Tags tower law -/ universes u v w u₁ v₁ w₁ open_locale classical big_operators section field open cardinal variables (F : Type u) (K : Type v) (A : Type w) variables [field F] [field K] [add_comm_group A] variables [algebra F K] [module K A] [module F A] [is_scalar_tower F K A] /-- Tower law: if `A` is a `K`-vector space and `K` is a field extension of `F` then `dim_F(A) = dim_F(K) * dim_K(A)`. -/ theorem dim_mul_dim' : (cardinal.lift.{w} (module.rank F K) * cardinal.lift.{v} (module.rank K A)) = cardinal.lift.{v} (module.rank F A) := let b := basis.of_vector_space F K, c := basis.of_vector_space K A in by rw [← (module.rank F K).lift_id, ← b.mk_eq_dim, ← (module.rank K A).lift_id, ← c.mk_eq_dim, ← lift_umax.{w v}, ← (b.smul c).mk_eq_dim, mk_prod, lift_mul, lift_lift, lift_lift, lift_lift, lift_lift, lift_umax] /-- Tower law: if `A` is a `K`-vector space and `K` is a field extension of `F` then `dim_F(A) = dim_F(K) * dim_K(A)`. -/ theorem dim_mul_dim (F : Type u) (K A : Type v) [field F] [field K] [add_comm_group A] [algebra F K] [module K A] [module F A] [is_scalar_tower F K A] : module.rank F K * module.rank K A = module.rank F A := by convert dim_mul_dim' F K A; rw lift_id namespace finite_dimensional open is_noetherian theorem trans [finite_dimensional F K] [finite_dimensional K A] : finite_dimensional F A := let b := basis.of_vector_space F K, c := basis.of_vector_space K A in of_fintype_basis $ b.smul c /-- In a tower of field extensions `L / K / F`, if `L / F` is finite, so is `K / F`. (In fact, it suffices that `L` is a nontrivial ring.) Note this cannot be an instance as Lean cannot infer `L`. -/ theorem left (L : Type*) [ring L] [nontrivial L] [algebra F L] [algebra K L] [is_scalar_tower F K L] [finite_dimensional F L] : finite_dimensional F K := finite_dimensional.of_injective (is_scalar_tower.to_alg_hom F K L).to_linear_map (ring_hom.injective _) lemma right [hf : finite_dimensional F A] : finite_dimensional K A := let ⟨⟨b, hb⟩⟩ := hf in ⟨⟨b, submodule.restrict_scalars_injective F _ _ $ by { rw [submodule.restrict_scalars_top, eq_top_iff, ← hb, submodule.span_le], exact submodule.subset_span }⟩⟩ /-- Tower law: if `A` is a `K`-algebra and `K` is a field extension of `F` then `dim_F(A) = dim_F(K) * dim_K(A)`. -/ theorem finrank_mul_finrank [finite_dimensional F K] : finrank F K * finrank K A = finrank F A := begin by_cases hA : finite_dimensional K A, { resetI, let b := basis.of_vector_space F K, let c := basis.of_vector_space K A, rw [finrank_eq_card_basis b, finrank_eq_card_basis c, finrank_eq_card_basis (b.smul c), fintype.card_prod] }, { rw [finrank_of_infinite_dimensional hA, mul_zero, finrank_of_infinite_dimensional], exact mt (@right F K A _ _ _ _ _ _ _) hA } end instance linear_map (F : Type u) (V : Type v) (W : Type w) [field F] [add_comm_group V] [module F V] [add_comm_group W] [module F W] [finite_dimensional F V] [finite_dimensional F W] : finite_dimensional F (V →ₗ[F] W) := let b := basis.of_vector_space F V, c := basis.of_vector_space F W in (matrix.to_lin b c).finite_dimensional lemma finrank_linear_map (F : Type u) (V : Type v) (W : Type w) [field F] [add_comm_group V] [module F V] [add_comm_group W] [module F W] [finite_dimensional F V] [finite_dimensional F W] : finrank F (V →ₗ[F] W) = finrank F V * finrank F W := let b := basis.of_vector_space F V, c := basis.of_vector_space F W in by rw [linear_equiv.finrank_eq (linear_map.to_matrix b c), matrix.finrank_matrix, finrank_eq_card_basis b, finrank_eq_card_basis c, mul_comm] -- TODO: generalize by removing [finite_dimensional F K] -- V = ⊕F, -- (V →ₗ[F] K) = ((⊕F) →ₗ[F] K) = (⊕ (F →ₗ[F] K)) = ⊕K instance linear_map' (F : Type u) (K : Type v) (V : Type w) [field F] [field K] [algebra F K] [finite_dimensional F K] [add_comm_group V] [module F V] [finite_dimensional F V] : finite_dimensional K (V →ₗ[F] K) := right F _ _ lemma finrank_linear_map' (F : Type u) (K : Type v) (V : Type w) [field F] [field K] [algebra F K] [finite_dimensional F K] [add_comm_group V] [module F V] [finite_dimensional F V] : finrank K (V →ₗ[F] K) = finrank F V := (nat.mul_right_inj $ show 0 < finrank F K, from finrank_pos).1 $ calc finrank F K * finrank K (V →ₗ[F] K) = finrank F (V →ₗ[F] K) : finrank_mul_finrank _ _ _ ... = finrank F V * finrank F K : finrank_linear_map F V K ... = finrank F K * finrank F V : mul_comm _ _ end finite_dimensional end field
12d6d31935242892d08ae8d3be618f2562be5ad9
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/06_Inductive_Types.org.13.lean
f96a9bb812f14ec92333f4c3a15c25505967b0fb
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
250
lean
/- page 81 -/ import standard import data.prod open prod namespace hide -- BEGIN definition pr1 {A B : Type} (p : A × B) : A := prod.rec_on p (λ a b, a) definition pr2 {A B : Type} (p : A × B) : B := prod.rec_on p (λ a b, b) -- END end hide
1b0dae43de3340282512fd25336a905f0e957b63
5749d8999a76f3a8fddceca1f6941981e33aaa96
/src/data/mv_polynomial.lean
5b18abf81a9f87467e46df04f0db428a3c8a29f1
[ "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
46,905
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Johan Commelin, Mario Carneiro -/ import algebra.ring import data.finsupp data.polynomial data.equiv.algebra /-! # Multivariate polynomials This file defines polynomial rings over a base ring (or even semiring), with variables from a general type `σ` (which could be infinite). ## Important definitions Let `R` be a commutative ring (or a semiring) and let `σ` be an arbitrary type. This file creates the type `mv_polynomial σ R`, which mathematicians might denote `R[X_i : i ∈ σ]`. It is the type of multivariate (a.k.a. multivariable) polynomials, with variables corresponding to the terms in `σ`, and coefficients in `R`. ### Notation In the definitions below, we use the following notation: + `σ : Type*` (indexing the variables) + `R : Type*` `[comm_semiring R]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s` + `a : R` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ R` ### Definitions * `mv_polynomial σ R` : the type of polynomials with variables of type `σ` and coefficients in the commutative semiring `R` * `monomial s a` : the monomial which mathematically would be denoted `a * X^s` * `C a` : the constant polynomial with value `a` * `X i` : the degree one monomial corresponding to i; mathematically this might be denoted `Xᵢ`. * `coeff s p` : the coefficient of `s` in `p`. * `eval₂ (f : R → S) (g : σ → S) p` : given a semiring homomorphism from `R` to another semiring `S`, and a map `σ → S`, evaluates `p` at this valuation, returning a term of type `S`. Note that `eval₂` can be made using `eval` and `map` (see below), and it has been suggested that sticking to `eval` and `map` might make the code less brittle. * `eval (g : σ → R) p` : given a map `σ → R`, evaluates `p` at this valuation, returning a term of type `R` * `map (f : R → S) p` : returns the multivariate polynomial obtained from `p` by the change of coefficient semiring corresponding to `f` * `degrees p` : the multiset of variables representing the union of the multisets corresponding to each non-zero monomial in `p`. For example if `7 ≠ 0` in `R` and `p = x²y+7y³` then `degrees p = {x, x, y, y, y}` * `vars p` : the finset of variables occurring in `p`. For example if `p = x⁴y+yz` then `vars p = {x, y, z}` * `degree_of n p : ℕ` -- the total degree of `p` with respect to the variable `n`. For example if `p = x⁴y+yz` then `degree_of y p = 1`. * `total_degree p : ℕ` -- the max of the sizes of the multisets `s` whose monomials `X^s` occur in `p`. For example if `p = x⁴y+yz` then `total_degree p = 5`. ## Implementation notes Recall that if `Y` has a zero, then `X →₀ Y` is the type of functions from `X` to `Y` with finite support, i.e. such that only finitely many elements of `X` get sent to non-zero terms in `Y`. The definition of `mv_polynomial σ α` is `(σ →₀ ℕ) →₀ α` ; here `σ →₀ ℕ` denotes the space of all monomials in the variables, and the function to α sends a monomial to its coefficient in the polynomial being represented. ## Tags polynomial, multivariate polynomial, multivariable polynomial -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open set function finsupp lattice universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} /-- Multivariate polynomial, where `σ` is the index set of the variables and `α` is the coefficient ring -/ def mv_polynomial (σ : Type*) (α : Type*) [comm_semiring α] := (σ →₀ ℕ) →₀ α namespace mv_polynomial variables {σ : Type*} {a a' a₁ a₂ : α} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} section comm_semiring variables [comm_semiring α] {p q : mv_polynomial σ α} instance decidable_eq_mv_polynomial [decidable_eq σ] [decidable_eq α] : decidable_eq (mv_polynomial σ α) := finsupp.decidable_eq instance : has_zero (mv_polynomial σ α) := finsupp.has_zero instance : has_one (mv_polynomial σ α) := finsupp.has_one instance : has_add (mv_polynomial σ α) := finsupp.has_add instance : has_mul (mv_polynomial σ α) := finsupp.has_mul instance : comm_semiring (mv_polynomial σ α) := finsupp.comm_semiring /-- `monomial s a` is the monomial `a * X^s` -/ def monomial (s : σ →₀ ℕ) (a : α) : mv_polynomial σ α := single s a /-- `C a` is the constant polynomial with value `a` -/ def C (a : α) : mv_polynomial σ α := monomial 0 a /-- `X n` is the degree `1` monomial `1*n` -/ def X (n : σ) : mv_polynomial σ α := monomial (single n 1) 1 @[simp] lemma C_0 : C 0 = (0 : mv_polynomial σ α) := by simp [C, monomial]; refl @[simp] lemma C_1 : C 1 = (1 : mv_polynomial σ α) := rfl lemma C_mul_monomial : C a * monomial s a' = monomial s (a * a') := by simp [C, monomial, single_mul_single] @[simp] lemma C_add : (C (a + a') : mv_polynomial σ α) = C a + C a' := single_add @[simp] lemma C_mul : (C (a * a') : mv_polynomial σ α) = C a * C a' := C_mul_monomial.symm @[simp] lemma C_pow (a : α) (n : ℕ) : (C (a^n) : mv_polynomial σ α) = (C a)^n := by induction n; simp [pow_succ, *] instance : is_semiring_hom (C : α → mv_polynomial σ α) := { map_zero := C_0, map_one := C_1, map_add := λ a a', C_add, map_mul := λ a a', C_mul } lemma C_eq_coe_nat (n : ℕ) : (C ↑n : mv_polynomial σ α) = n := by induction n; simp [nat.succ_eq_add_one, *] lemma X_pow_eq_single : X n ^ e = monomial (single n e) (1 : α) := begin induction e, { simp [X], refl }, { simp [pow_succ, e_ih], simp [X, monomial, single_mul_single, nat.succ_eq_add_one] } end lemma monomial_add_single : monomial (s + single n e) a = (monomial s a * X n ^ e) := by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp lemma monomial_single_add : monomial (single n e + s) a = (X n ^ e * monomial s a) := by rw [X_pow_eq_single, monomial, monomial, monomial, single_mul_single]; simp lemma monomial_eq : monomial s a = C a * (s.prod $ λn e, X n ^ e : mv_polynomial σ α) := begin apply @finsupp.induction σ ℕ _ _ s, { simp [C, prod_zero_index]; exact (mul_one _).symm }, { assume n e s hns he ih, simp [prod_add_index, prod_single_index, pow_zero, pow_add, (mul_assoc _ _ _).symm, ih.symm, monomial_add_single] } end @[recursor 5] lemma induction_on {M : mv_polynomial σ α → Prop} (p : mv_polynomial σ α) (h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_X : ∀p n, M p → M (p * X n)) : M p := have ∀s a, M (monomial s a), begin assume s a, apply @finsupp.induction σ ℕ _ _ s, { show M (monomial 0 a), from h_C a, }, { assume n e p hpn he ih, have : ∀e:ℕ, M (monomial p a * X n ^ e), { intro e, induction e, { simp [ih] }, { simp [ih, pow_succ', (mul_assoc _ _ _).symm, h_X, e_ih] } }, simp [monomial_add_single, this] } end, finsupp.induction p (by have : M (C 0) := h_C 0; rwa [C_0] at this) (assume s a p hsp ha hp, h_add _ _ (this s a) hp) lemma hom_eq_hom [semiring γ] (f g : mv_polynomial σ α → γ) (hf : is_semiring_hom f) (hg : is_semiring_hom g) (hC : ∀a:α, f (C a) = g (C a)) (hX : ∀n:σ, f (X n) = g (X n)) (p : mv_polynomial σ α) : f p = g p := mv_polynomial.induction_on p hC begin assume p q hp hq, rw [is_semiring_hom.map_add f, is_semiring_hom.map_add g, hp, hq] end begin assume p n hp, rw [is_semiring_hom.map_mul f, is_semiring_hom.map_mul g, hp, hX] end lemma is_id (f : mv_polynomial σ α → mv_polynomial σ α) (hf : is_semiring_hom f) (hC : ∀a:α, f (C a) = (C a)) (hX : ∀n:σ, f (X n) = (X n)) (p : mv_polynomial σ α) : f p = p := hom_eq_hom f id hf is_semiring_hom.id hC hX p section coeff section -- While setting up `coeff`, we make `mv_polynomial` reducible so we can treat it as a function. local attribute [reducible] mv_polynomial /-- The coefficient of the monomial `m` in the multi-variable polynomial `p`. -/ def coeff (m : σ →₀ ℕ) (p : mv_polynomial σ α) : α := p m end lemma ext (p q : mv_polynomial σ α) : (∀ m, coeff m p = coeff m q) → p = q := ext lemma ext_iff (p q : mv_polynomial σ α) : (∀ m, coeff m p = coeff m q) ↔ p = q := ⟨ext p q, λ h m, by rw h⟩ @[simp] lemma coeff_add (m : σ →₀ ℕ) (p q : mv_polynomial σ α) : coeff m (p + q) = coeff m p + coeff m q := add_apply @[simp] lemma coeff_zero (m : σ →₀ ℕ) : coeff m (0 : mv_polynomial σ α) = 0 := rfl @[simp] lemma coeff_zero_X (i : σ) : coeff 0 (X i : mv_polynomial σ α) = 0 := single_eq_of_ne (λ h, by cases single_eq_zero.1 h) instance coeff.is_add_monoid_hom (m : σ →₀ ℕ) : is_add_monoid_hom (coeff m : mv_polynomial σ α → α) := { map_add := coeff_add m, map_zero := coeff_zero m } lemma coeff_sum {X : Type*} (s : finset X) (f : X → mv_polynomial σ α) (m : σ →₀ ℕ) : coeff m (s.sum f) = s.sum (λ x, coeff m (f x)) := (s.sum_hom _).symm lemma monic_monomial_eq (m) : monomial m (1:α) = (m.prod $ λn e, X n ^ e : mv_polynomial σ α) := by simp [monomial_eq] @[simp] lemma coeff_monomial (m n) (a) : coeff m (monomial n a : mv_polynomial σ α) = if n = m then a else 0 := by convert single_apply @[simp] lemma coeff_C (m) (a) : coeff m (C a : mv_polynomial σ α) = if 0 = m then a else 0 := by convert single_apply lemma coeff_X_pow (i : σ) (m) (k : ℕ) : coeff m (X i ^ k : mv_polynomial σ α) = if single i k = m then 1 else 0 := begin have := coeff_monomial m (finsupp.single i k) (1:α), rwa [@monomial_eq _ _ (1:α) (finsupp.single i k) _, C_1, one_mul, finsupp.prod_single_index] at this, exact pow_zero _ end lemma coeff_X' (i : σ) (m) : coeff m (X i : mv_polynomial σ α) = if single i 1 = m then 1 else 0 := by rw [← coeff_X_pow, pow_one] @[simp] lemma coeff_X (i : σ) : coeff (single i 1) (X i : mv_polynomial σ α) = 1 := by rw [coeff_X', if_pos rfl] @[simp] lemma coeff_C_mul (m) (a : α) (p : mv_polynomial σ α) : coeff m (C a * p) = a * coeff m p := begin rw [mul_def, C, monomial], simp only [sum_single_index, zero_mul, single_zero, zero_add, sum_zero], convert sum_apply, simp only [single_apply, finsupp.sum], rw finset.sum_eq_single m, { rw if_pos rfl, refl }, { intros m' hm' H, apply if_neg, exact H }, { intros hm, rw if_pos rfl, rw not_mem_support_iff at hm, simp [hm] } end lemma coeff_mul (p q : mv_polynomial σ α) (n : σ →₀ ℕ) : coeff n (p * q) = finset.sum (antidiagonal n).support (λ x, coeff x.1 p * coeff x.2 q) := begin rw mul_def, have := @finset.sum_sigma (σ →₀ ℕ) α _ _ p.support (λ _, q.support) (λ x, if (x.1 + x.2 = n) then coeff x.1 p * coeff x.2 q else 0), convert this.symm using 1; clear this, { rw [coeff], repeat {rw sum_apply, apply finset.sum_congr rfl, intros, dsimp only}, convert single_apply }, { have : (antidiagonal n).support.filter (λ x, x.1 ∈ p.support ∧ x.2 ∈ q.support) ⊆ (antidiagonal n).support := finset.filter_subset _, rw [← finset.sum_sdiff this, finset.sum_eq_zero, zero_add], swap, { intros x hx, rw [finset.mem_sdiff, not_iff_not_of_iff (finset.mem_filter), not_and, not_and, not_mem_support_iff] at hx, by_cases H : x.1 ∈ p.support, { rw [coeff, coeff, hx.2 hx.1 H, mul_zero] }, { rw not_mem_support_iff at H, rw [coeff, H, zero_mul] } }, symmetry, rw [← finset.sum_sdiff (finset.filter_subset _), finset.sum_eq_zero, zero_add], swap, { intros x hx, rw [finset.mem_sdiff, not_iff_not_of_iff (finset.mem_filter), not_and] at hx, rw if_neg, exact hx.2 hx.1 }, { apply finset.sum_bij, swap 5, { intros x hx, exact (x.1, x.2) }, { intros x hx, rw [finset.mem_filter, finset.mem_sigma] at hx, simpa [finset.mem_filter, mem_antidiagonal_support] using hx.symm }, { intros x hx, rw finset.mem_filter at hx, rw if_pos hx.2 }, { rintros ⟨i,j⟩ ⟨k,l⟩ hij hkl, simpa using and.intro }, { rintros ⟨i,j⟩ hij, refine ⟨⟨i,j⟩, _, _⟩, { apply_instance }, { rw [finset.mem_filter, mem_antidiagonal_support] at hij, simpa [finset.mem_filter, finset.mem_sigma] using hij.symm }, { refl } } }, all_goals { apply_instance } } end @[simp] lemma coeff_mul_X (m) (s : σ) (p : mv_polynomial σ α) : coeff (m + single s 1) (p * X s) = coeff m p := begin have : (m, single s 1) ∈ (m + single s 1).antidiagonal.support := mem_antidiagonal_support.2 rfl, rw [coeff_mul, ← finset.insert_erase this, finset.sum_insert (finset.not_mem_erase _ _), finset.sum_eq_zero, add_zero, coeff_X, mul_one], rintros ⟨i,j⟩ hij, rw [finset.mem_erase, mem_antidiagonal_support] at hij, by_cases H : single s 1 = j, { subst j, simpa using hij }, { rw [coeff_X', if_neg H, mul_zero] }, end lemma coeff_mul_X' (m) (s : σ) (p : mv_polynomial σ α) : coeff m (p * X s) = if s ∈ m.support then coeff (m - single s 1) p else 0 := begin split_ifs with h h, { conv_rhs {rw ← coeff_mul_X _ s}, congr' 1, ext t, by_cases hj : s = t, { subst t, simp only [nat_sub_apply, add_apply, single_eq_same], refine (nat.sub_add_cancel $ nat.pos_of_ne_zero _).symm, rwa mem_support_iff at h }, { simp [single_eq_of_ne hj] } }, { delta coeff, rw ← not_mem_support_iff, intro hm, apply h, have H := support_mul _ _ hm, simp only [finset.mem_bind] at H, rcases H with ⟨j, hj, i', hi', H⟩, delta X monomial at hi', rw mem_support_single at hi', cases hi', subst i', erw finset.mem_singleton at H, subst m, rw [mem_support_iff, add_apply, single_apply, if_pos rfl], intro H, rw [add_eq_zero_iff] at H, exact one_ne_zero H.2 } end end coeff section eval₂ variables [comm_semiring β] variables (f : α → β) (g : σ → β) /-- Evaluate a polynomial `p` given a valuation `g` of all the variables and a ring hom `f` from the scalar ring to the target -/ def eval₂ (p : mv_polynomial σ α) : β := p.sum (λs a, f a * s.prod (λn e, g n ^ e)) @[simp] lemma eval₂_zero : (0 : mv_polynomial σ α).eval₂ f g = 0 := finsupp.sum_zero_index section variables [is_semiring_hom f] @[simp] lemma eval₂_add : (p + q).eval₂ f g = p.eval₂ f g + q.eval₂ f g := finsupp.sum_add_index (by simp [is_semiring_hom.map_zero f]) (by simp [add_mul, is_semiring_hom.map_add f]) @[simp] lemma eval₂_monomial : (monomial s a).eval₂ f g = f a * s.prod (λn e, g n ^ e) := finsupp.sum_single_index (by simp [is_semiring_hom.map_zero f]) @[simp] lemma eval₂_C (a) : (C a).eval₂ f g = f a := by simp [eval₂_monomial, C, prod_zero_index] @[simp] lemma eval₂_one : (1 : mv_polynomial σ α).eval₂ f g = 1 := (eval₂_C _ _ _).trans (is_semiring_hom.map_one f) @[simp] lemma eval₂_X (n) : (X n).eval₂ f g = g n := by simp [eval₂_monomial, is_semiring_hom.map_one f, X, prod_single_index, pow_one] lemma eval₂_mul_monomial : ∀{s a}, (p * monomial s a).eval₂ f g = p.eval₂ f g * f a * s.prod (λn e, g n ^ e) := begin apply mv_polynomial.induction_on p, { assume a' s a, simp [C_mul_monomial, eval₂_monomial, is_semiring_hom.map_mul f] }, { assume p q ih_p ih_q, simp [add_mul, eval₂_add, ih_p, ih_q] }, { assume p n ih s a, from calc (p * X n * monomial s a).eval₂ f g = (p * monomial (single n 1 + s) a).eval₂ f g : by simp [monomial_single_add, -add_comm, pow_one, mul_assoc] ... = (p * monomial (single n 1) 1).eval₂ f g * f a * s.prod (λn e, g n ^ e) : by simp [ih, prod_single_index, prod_add_index, pow_one, pow_add, mul_assoc, mul_left_comm, is_semiring_hom.map_one f, -add_comm] } end @[simp] lemma eval₂_mul : ∀{p}, (p * q).eval₂ f g = p.eval₂ f g * q.eval₂ f g := begin apply mv_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 @[simp] lemma eval₂_pow {p:mv_polynomial σ α} : ∀{n:ℕ}, (p ^ n).eval₂ f g = (p.eval₂ f g)^n | 0 := eval₂_one _ _ | (n + 1) := by rw [pow_add, pow_one, pow_add, pow_one, eval₂_mul, eval₂_pow] instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f g) := { map_zero := eval₂_zero _ _, map_one := eval₂_one _ _, map_add := λ p q, eval₂_add _ _, map_mul := λ p q, eval₂_mul _ _ } end lemma eval₂_comp_left {γ} [comm_semiring γ] (k : β → γ) [is_semiring_hom k] (f : α → β) [is_semiring_hom f] (g : σ → β) (p) : k (eval₂ f g p) = eval₂ (k ∘ f) (k ∘ g) p := by apply mv_polynomial.induction_on p; simp [ eval₂_add, is_semiring_hom.map_add k, eval₂_mul, is_semiring_hom.map_mul k] {contextual := tt} @[simp] lemma eval₂_eta (p : mv_polynomial σ α) : eval₂ C X p = p := by apply mv_polynomial.induction_on p; simp [eval₂_add, eval₂_mul] {contextual := tt} lemma eval₂_congr (g₁ g₂ : σ → β) (h : ∀ {i : σ} {c : σ →₀ ℕ}, i ∈ c.support → coeff c p ≠ 0 → g₁ i = g₂ i) : p.eval₂ f g₁ = p.eval₂ f g₂ := begin apply finset.sum_congr rfl, intros c hc, dsimp, congr' 1, apply finset.prod_congr rfl, intros i hi, dsimp, congr' 1, apply h hi, rwa finsupp.mem_support_iff at hc end variables [is_semiring_hom f] @[simp] lemma eval₂_prod (s : finset γ) (p : γ → mv_polynomial σ α) : eval₂ f g (s.prod p) = s.prod (λ x, eval₂ f g $ p x) := (s.prod_hom _).symm @[simp] lemma eval₂_sum (s : finset γ) (p : γ → mv_polynomial σ α) : eval₂ f g (s.sum p) = s.sum (λ x, eval₂ f g $ p x) := (s.sum_hom _).symm attribute [to_additive] eval₂_prod lemma eval₂_assoc (q : γ → mv_polynomial σ α) (p : mv_polynomial γ α) : eval₂ f (λ t, eval₂ f g (q t)) p = eval₂ f g (eval₂ C q p) := by { rw eval₂_comp_left (eval₂ f g), congr, funext, simp } end eval₂ section eval variables {f : σ → α} /-- Evaluate a polynomial `p` given a valuation `f` of all the variables -/ def eval (f : σ → α) : mv_polynomial σ α → α := eval₂ id f @[simp] lemma eval_zero : (0 : mv_polynomial σ α).eval f = 0 := eval₂_zero _ _ @[simp] lemma eval_add : (p + q).eval f = p.eval f + q.eval f := eval₂_add _ _ lemma eval_monomial : (monomial s a).eval f = a * s.prod (λn e, f n ^ e) := eval₂_monomial _ _ @[simp] lemma eval_C : ∀ a, (C a).eval f = a := eval₂_C _ _ @[simp] lemma eval_X : ∀ n, (X n).eval f = f n := eval₂_X _ _ @[simp] lemma eval_mul : (p * q).eval f = p.eval f * q.eval f := eval₂_mul _ _ instance eval.is_semiring_hom : is_semiring_hom (eval f) := eval₂.is_semiring_hom _ _ theorem eval_assoc {τ} (f : σ → mv_polynomial τ α) (g : τ → α) (p : mv_polynomial σ α) : p.eval (eval g ∘ f) = (eval₂ C f p).eval g := begin rw eval₂_comp_left (eval g), unfold eval, congr; funext a; simp end end eval section map variables [comm_semiring β] variables (f : α → β) /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map : mv_polynomial σ α → mv_polynomial σ β := eval₂ (C ∘ f) X variables [is_semiring_hom f] @[simp] theorem map_monomial (s : σ →₀ ℕ) (a : α) : map f (monomial s a) = monomial s (f a) := (eval₂_monomial _ _).trans monomial_eq.symm @[simp] theorem map_C : ∀ (a : α), map f (C a : mv_polynomial σ α) = C (f a) := map_monomial _ _ @[simp] theorem map_X : ∀ (n : σ), map f (X n : mv_polynomial σ α) = X n := eval₂_X _ _ @[simp] theorem map_one : map f (1 : mv_polynomial σ α) = 1 := eval₂_one _ _ @[simp] theorem map_add (p q : mv_polynomial σ α) : map f (p + q) = map f p + map f q := eval₂_add _ _ @[simp] theorem map_mul (p q : mv_polynomial σ α) : map f (p * q) = map f p * map f q := eval₂_mul _ _ @[simp] lemma map_pow (p : mv_polynomial σ α) (n : ℕ) : map f (p^n) = (map f p)^n := eval₂_pow _ _ instance map.is_semiring_hom : is_semiring_hom (map f : mv_polynomial σ α → mv_polynomial σ β) := eval₂.is_semiring_hom _ _ theorem map_id : ∀ (p : mv_polynomial σ α), map id p = p := eval₂_eta theorem map_map [comm_semiring γ] (g : β → γ) [is_semiring_hom g] (p : mv_polynomial σ α) : map g (map f p) = map (g ∘ f) p := (eval₂_comp_left (map g) (C ∘ f) X p).trans $ by congr; funext a; simp theorem eval₂_eq_eval_map (g : σ → β) (p : mv_polynomial σ α) : p.eval₂ f g = (map f p).eval g := begin unfold map eval, rw eval₂_comp_left (eval₂ id g), congr; funext a; simp end lemma eval₂_comp_right {γ} [comm_semiring γ] (k : β → γ) [is_semiring_hom k] (f : α → β) [is_semiring_hom f] (g : σ → β) (p) : k (eval₂ f g p) = eval₂ k (k ∘ g) (map f p) := begin apply mv_polynomial.induction_on p, { intro r, rw [eval₂_C, map_C, eval₂_C] }, { intros p q hp hq, rw [eval₂_add, is_semiring_hom.map_add k, map_add, eval₂_add, hp, hq] }, { intros p s hp, rw [eval₂_mul, is_semiring_hom.map_mul k, map_mul, eval₂_mul, map_X, hp, eval₂_X, eval₂_X] } end lemma map_eval₂ (f : α → β) [is_semiring_hom f] (g : γ → mv_polynomial δ α) (p : mv_polynomial γ α) : map f (eval₂ C g p) = eval₂ C (map f ∘ g) (map f p) := begin apply mv_polynomial.induction_on p, { intro r, rw [eval₂_C, map_C, map_C, eval₂_C] }, { intros p q hp hq, rw [eval₂_add, map_add, hp, hq, map_add, eval₂_add] }, { intros p s hp, rw [eval₂_mul, map_mul, hp, map_mul, map_X, eval₂_mul, eval₂_X, eval₂_X] } end lemma coeff_map (p : mv_polynomial σ α) : ∀ (m : σ →₀ ℕ), coeff m (p.map f) = f (coeff m p) := begin apply mv_polynomial.induction_on p; clear p, { intros r m, rw [map_C], simp only [coeff_C], split_ifs, {refl}, rw is_semiring_hom.map_zero f }, { intros p q hp hq m, simp only [hp, hq, map_add, coeff_add], rw is_semiring_hom.map_add f }, { intros p i hp m, simp only [hp, map_mul, map_X], simp only [hp, mem_support_iff, coeff_mul_X'], split_ifs, {refl}, rw is_semiring_hom.map_zero f } end lemma map_injective (hf : function.injective f) : function.injective (map f : mv_polynomial σ α → mv_polynomial σ β) := λ p q h, ext _ _ $ λ m, hf $ begin rw ← ext_iff at h, specialize h m, rw [coeff_map, coeff_map] at h, exact h end end map section degrees section comm_semiring /-- The maximal degrees of each variable in a multi-variable polynomial, expressed as a multiset. (For example, `degrees (x^2 * y + y^3)` would be `{x, x, y, y, y}`.) -/ def degrees (p : mv_polynomial σ α) : multiset σ := p.support.sup (λs:σ →₀ ℕ, s.to_multiset) lemma degrees_monomial (s : σ →₀ ℕ) (a : α) : degrees (monomial s a) ≤ s.to_multiset := finset.sup_le $ assume t h, begin have := finsupp.support_single_subset h, rw [finset.singleton_eq_singleton, finset.mem_singleton] at this, rw this end lemma degrees_monomial_eq (s : σ →₀ ℕ) (a : α) (ha : a ≠ 0) : degrees (monomial s a) = s.to_multiset := le_antisymm (degrees_monomial s a) $ finset.le_sup $ by rw [monomial, finsupp.support_single_ne_zero ha, finset.singleton_eq_singleton, finset.mem_singleton] lemma degrees_C (a : α) : degrees (C a : mv_polynomial σ α) = 0 := multiset.le_zero.1 $ degrees_monomial _ _ lemma degrees_X (n : σ) : degrees (X n : mv_polynomial σ α) ≤ {n} := le_trans (degrees_monomial _ _) $ le_of_eq $ to_multiset_single _ _ lemma degrees_zero : degrees (0 : mv_polynomial σ α) = 0 := by { rw ← C_0, exact degrees_C 0 } lemma degrees_one : degrees (1 : mv_polynomial σ α) = 0 := degrees_C 1 lemma degrees_add (p q : mv_polynomial σ α) : (p + q).degrees ≤ p.degrees ⊔ q.degrees := begin refine finset.sup_le (assume b hb, _), have := finsupp.support_add hb, rw finset.mem_union at this, cases this, { exact le_sup_left_of_le (finset.le_sup this) }, { exact le_sup_right_of_le (finset.le_sup this) }, end lemma degrees_sum {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ α) : (s.sum f).degrees ≤ s.sup (λi, (f i).degrees) := begin refine s.induction _ _, { simp only [finset.sum_empty, finset.sup_empty, degrees_zero], exact le_refl _ }, { assume i s his ih, rw [finset.sup_insert, finset.sum_insert his], exact le_trans (degrees_add _ _) (sup_le_sup_left ih _) } end lemma degrees_mul (p q : mv_polynomial σ α) : (p * q).degrees ≤ p.degrees + q.degrees := begin refine finset.sup_le (assume b hb, _), have := support_mul p q hb, simp only [finset.mem_bind, finset.singleton_eq_singleton, finset.mem_singleton] at this, rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩, rw [finsupp.to_multiset_add], exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂) end lemma degrees_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ α) : (s.prod f).degrees ≤ s.sum (λi, (f i).degrees) := begin refine s.induction _ _, { simp only [finset.prod_empty, finset.sum_empty, degrees_one] }, { assume i s his ih, rw [finset.prod_insert his, finset.sum_insert his], exact le_trans (degrees_mul _ _) (add_le_add_left ih _) } end lemma degrees_pow (p : mv_polynomial σ α) : ∀(n : ℕ), (p^n).degrees ≤ add_monoid.smul n p.degrees | 0 := begin rw [pow_zero, degrees_one], exact multiset.zero_le _ end | (n + 1) := le_trans (degrees_mul _ _) (add_le_add_left (degrees_pow n) _) end comm_semiring end degrees section vars /-- `vars p` is the set of variables appearing in the polynomial `p` -/ def vars (p : mv_polynomial σ α) : finset σ := p.degrees.to_finset @[simp] lemma vars_0 : (0 : mv_polynomial σ α).vars = ∅ := by rw [vars, degrees_zero, multiset.to_finset_zero] @[simp] lemma vars_monomial (h : a ≠ 0) : (monomial s a).vars = s.support := by rw [vars, degrees_monomial_eq _ _ h, finsupp.to_finset_to_multiset] @[simp] lemma vars_C : (C a : mv_polynomial σ α).vars = ∅ := by rw [vars, degrees_C, multiset.to_finset_zero] @[simp] lemma vars_X (h : 0 ≠ (1 : α)) : (X n : mv_polynomial σ α).vars = {n} := by rw [X, vars_monomial h.symm, finsupp.support_single_ne_zero zero_ne_one.symm] end vars section degree_of /-- `degree_of n p` gives the highest power of X_n that appears in `p` -/ def degree_of (n : σ) (p : mv_polynomial σ α) : ℕ := p.degrees.count n end degree_of section total_degree /-- `total_degree p` gives the maximum |s| over the monomials X^s in `p` -/ def total_degree (p : mv_polynomial σ α) : ℕ := p.support.sup (λs, s.sum $ λn e, e) lemma total_degree_eq (p : mv_polynomial σ α) : p.total_degree = p.support.sup (λm, m.to_multiset.card) := begin rw [total_degree], congr, funext m, exact (finsupp.card_to_multiset _).symm end lemma total_degree_le_degrees_card (p : mv_polynomial σ α) : p.total_degree ≤ p.degrees.card := begin rw [total_degree_eq], exact finset.sup_le (assume s hs, multiset.card_le_of_le $ finset.le_sup hs) end lemma total_degree_C (a : α) : (C a : mv_polynomial σ α).total_degree = 0 := nat.eq_zero_of_le_zero $ finset.sup_le $ assume n hn, have _ := finsupp.support_single_subset hn, begin rw [finset.singleton_eq_singleton, finset.mem_singleton] at this, subst this, exact le_refl _ end lemma total_degree_zero : (0 : mv_polynomial σ α).total_degree = 0 := by rw [← C_0]; exact total_degree_C (0 : α) lemma total_degree_one : (1 : mv_polynomial σ α).total_degree = 0 := total_degree_C (1 : α) lemma total_degree_add (a b : mv_polynomial σ α) : (a + b).total_degree ≤ max a.total_degree b.total_degree := finset.sup_le $ assume n hn, have _ := finsupp.support_add hn, begin rw finset.mem_union at this, cases this, { exact le_max_left_of_le (finset.le_sup this) }, { exact le_max_right_of_le (finset.le_sup this) } end lemma total_degree_mul (a b : mv_polynomial σ α) : (a * b).total_degree ≤ a.total_degree + b.total_degree := finset.sup_le $ assume n hn, have _ := finsupp.support_mul a b hn, begin simp only [finset.mem_bind, finset.mem_singleton, finset.singleton_eq_singleton] at this, rcases this with ⟨a₁, h₁, a₂, h₂, rfl⟩, rw [finsupp.sum_add_index], { exact add_le_add (finset.le_sup h₁) (finset.le_sup h₂) }, { assume a, refl }, { assume a b₁ b₂, refl } end lemma total_degree_list_prod : ∀(s : list (mv_polynomial σ α)), s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum | [] := by rw [@list.prod_nil (mv_polynomial σ α) _, total_degree_one]; refl | (p :: ps) := begin rw [@list.prod_cons (mv_polynomial σ α) _, list.map, list.sum_cons], exact le_trans (total_degree_mul _ _) (add_le_add_left (total_degree_list_prod ps) _) end lemma total_degree_multiset_prod (s : multiset (mv_polynomial σ α)) : s.prod.total_degree ≤ (s.map mv_polynomial.total_degree).sum := begin refine quotient.induction_on s (assume l, _), rw [multiset.quot_mk_to_coe, multiset.coe_prod, multiset.coe_map, multiset.coe_sum], exact total_degree_list_prod l end lemma total_degree_finset_prod {ι : Type*} (s : finset ι) (f : ι → mv_polynomial σ α) : (s.prod f).total_degree ≤ s.sum (λi, (f i).total_degree) := begin refine le_trans (total_degree_multiset_prod _) _, rw [multiset.map_map], refl end end total_degree end comm_semiring section comm_ring variable [comm_ring α] variables {p q : mv_polynomial σ α} instance : ring (mv_polynomial σ α) := finsupp.ring instance : comm_ring (mv_polynomial σ α) := finsupp.comm_ring instance : has_scalar α (mv_polynomial σ α) := finsupp.has_scalar instance : module α (mv_polynomial σ α) := finsupp.module _ α instance C.is_ring_hom : is_ring_hom (C : α → mv_polynomial σ α) := by apply is_ring_hom.of_semiring variables (σ a a') lemma C_sub : (C (a - a') : mv_polynomial σ α) = C a - C a' := is_ring_hom.map_sub _ @[simp] lemma C_neg : (C (-a) : mv_polynomial σ α) = -C a := is_ring_hom.map_neg _ @[simp] lemma coeff_sub (m : σ →₀ ℕ) (p q : mv_polynomial σ α) : coeff m (p - q) = coeff m p - coeff m q := finsupp.sub_apply instance coeff.is_add_group_hom (m : σ →₀ ℕ) : is_add_group_hom (coeff m : mv_polynomial σ α → α) := { map_add := coeff_add m } variables {σ} (p) theorem C_mul' : mv_polynomial.C a * p = a • p := begin apply finsupp.induction p, { exact (mul_zero $ mv_polynomial.C a).trans (@smul_zero α (mv_polynomial σ α) _ _ _ a).symm }, intros p b f haf hb0 ih, rw [mul_add, ih, @smul_add α (mv_polynomial σ α) _ _ _ a], congr' 1, rw [finsupp.mul_def, finsupp.smul_single, mv_polynomial.C, mv_polynomial.monomial], rw [finsupp.sum_single_index, finsupp.sum_single_index, zero_add, smul_eq_mul], { rw [mul_zero, finsupp.single_zero] }, { rw finsupp.sum_single_index, all_goals { rw [zero_mul, finsupp.single_zero] } } end lemma smul_eq_C_mul (p : mv_polynomial σ α) (a : α) : a • p = C a * p := begin rw [← finsupp.sum_single p, @finsupp.smul_sum (σ →₀ ℕ) α α, finsupp.mul_sum], refine finset.sum_congr rfl (assume n _, _), simp only [finsupp.smul_single], exact C_mul_monomial.symm end @[simp] lemma smul_eval (x) (p : mv_polynomial σ α) (s) : (s • p).eval x = s * p.eval x := by rw [smul_eq_C_mul, eval_mul, eval_C] section degrees lemma degrees_neg (p : mv_polynomial σ α) : (- p).degrees = p.degrees := by rw [degrees, finsupp.support_neg]; refl lemma degrees_sub (p q : mv_polynomial σ α) : (p - q).degrees ≤ p.degrees ⊔ q.degrees := le_trans (degrees_add p (-q)) $ by rw [degrees_neg] end degrees section eval₂ variables [comm_ring β] variables (f : α → β) [is_ring_hom f] (g : σ → β) instance eval₂.is_ring_hom : is_ring_hom (eval₂ f g) := by apply is_ring_hom.of_semiring lemma eval₂_sub : (p - q).eval₂ f g = p.eval₂ f g - q.eval₂ f g := is_ring_hom.map_sub _ @[simp] lemma eval₂_neg : (-p).eval₂ f g = -(p.eval₂ f g) := is_ring_hom.map_neg _ lemma hom_C (f : mv_polynomial σ ℤ → β) [is_ring_hom f] (n : ℤ) : f (C n) = (n : β) := congr_fun (int.eq_cast' (f ∘ C)) n /-- A ring homomorphism f : Z[X_1, X_2, ...] → R is determined by the evaluations f(X_1), f(X_2), ... -/ @[simp] lemma eval₂_hom_X {α : Type u} (c : ℤ → β) [is_ring_hom c] (f : mv_polynomial α ℤ → β) [is_ring_hom f] (x : mv_polynomial α ℤ) : eval₂ c (f ∘ X) x = f x := mv_polynomial.induction_on x (λ n, by { rw [hom_C f, eval₂_C, int.eq_cast' c], refl }) (λ p q hp hq, by { rw [eval₂_add, hp, hq], exact (is_ring_hom.map_add f).symm }) (λ p n hp, by { rw [eval₂_mul, eval₂_X, hp], exact (is_ring_hom.map_mul f).symm }) /-- Ring homomorphisms out of integer polynomials on a type `σ` are the same as functions out of the type `σ`, -/ def hom_equiv : (mv_polynomial σ ℤ →+* β) ≃ (σ → β) := { to_fun := λ f, ⇑f ∘ X, inv_fun := λ f, ring_hom.of (eval₂ (λ n : ℤ, (n : β)) f), left_inv := λ f, ring_hom.ext $ eval₂_hom_X _ _, right_inv := λ f, funext $ λ x, by simp only [ring_hom.coe_of, function.comp_app, eval₂_X] } end eval₂ section eval variables (f : σ → α) instance eval.is_ring_hom : is_ring_hom (eval f) := eval₂.is_ring_hom _ _ lemma eval_sub : (p - q).eval f = p.eval f - q.eval f := is_ring_hom.map_sub _ @[simp] lemma eval_neg : (-p).eval f = -(p.eval f) := is_ring_hom.map_neg _ end eval section map variables [comm_ring β] variables (f : α → β) [is_ring_hom f] instance map.is_ring_hom : is_ring_hom (map f : mv_polynomial σ α → mv_polynomial σ β) := eval₂.is_ring_hom _ _ lemma map_sub : (p - q).map f = p.map f - q.map f := is_ring_hom.map_sub _ @[simp] lemma map_neg : (-p).map f = -(p.map f) := is_ring_hom.map_neg _ end map end comm_ring section rename variables {α} [comm_semiring α] /-- Rename all the variables in a multivariable polynomial. -/ def rename (f : β → γ) : mv_polynomial β α → mv_polynomial γ α := eval₂ C (X ∘ f) instance rename.is_semiring_hom (f : β → γ) : is_semiring_hom (rename f : mv_polynomial β α → mv_polynomial γ α) := by unfold rename; apply_instance @[simp] lemma rename_C (f : β → γ) (a : α) : rename f (C a) = C a := eval₂_C _ _ _ @[simp] lemma rename_X (f : β → γ) (b : β) : rename f (X b : mv_polynomial β α) = X (f b) := eval₂_X _ _ _ @[simp] lemma rename_zero (f : β → γ) : rename f (0 : mv_polynomial β α) = 0 := eval₂_zero _ _ @[simp] lemma rename_one (f : β → γ) : rename f (1 : mv_polynomial β α) = 1 := eval₂_one _ _ @[simp] lemma rename_add (f : β → γ) (p q : mv_polynomial β α) : rename f (p + q) = rename f p + rename f q := eval₂_add _ _ @[simp] lemma rename_sub {α} [comm_ring α] (f : β → γ) (p q : mv_polynomial β α) : rename f (p - q) = rename f p - rename f q := eval₂_sub _ _ _ @[simp] lemma rename_mul (f : β → γ) (p q : mv_polynomial β α) : rename f (p * q) = rename f p * rename f q := eval₂_mul _ _ @[simp] lemma rename_pow (f : β → γ) (p : mv_polynomial β α) (n : ℕ) : rename f (p^n) = (rename f p)^n := eval₂_pow _ _ lemma map_rename [comm_semiring β] (f : α → β) [is_semiring_hom f] (g : γ → δ) (p : mv_polynomial γ α) : map f (rename g p) = rename g (map f p) := mv_polynomial.induction_on p (λ a, by simp) (λ p q hp hq, by simp [hp, hq]) (λ p n hp, by simp [hp]) @[simp] lemma rename_rename (f : β → γ) (g : γ → δ) (p : mv_polynomial β α) : rename g (rename f p) = rename (g ∘ f) p := show rename g (eval₂ C (X ∘ f) p) = _, by simp only [eval₂_comp_left (rename g) C (X ∘ f) p, (∘), rename_C, rename_X]; refl @[simp] lemma rename_id (p : mv_polynomial β α) : rename id p = p := eval₂_eta p lemma rename_monomial (f : β → γ) (p : β →₀ ℕ) (a : α) : rename f (monomial p a) = monomial (p.map_domain f) a := begin rw [rename, eval₂_monomial, monomial_eq, finsupp.prod_map_domain_index], { exact assume n, pow_zero _ }, { exact assume n i₁ i₂, pow_add _ _ _ } end lemma rename_eq (f : β → γ) (p : mv_polynomial β α) : rename f p = finsupp.map_domain (finsupp.map_domain f) p := begin simp only [rename, eval₂, finsupp.map_domain], congr, ext s a : 2, rw [← monomial, monomial_eq, finsupp.prod_sum_index], congr, ext n i : 2, rw [finsupp.prod_single_index], exact pow_zero _, exact assume a, pow_zero _, exact assume a b c, pow_add _ _ _ end lemma injective_rename (f : β → γ) (hf : function.injective f) : function.injective (rename f : mv_polynomial β α → mv_polynomial γ α) := have (rename f : mv_polynomial β α → mv_polynomial γ α) = finsupp.map_domain (finsupp.map_domain f) := funext (rename_eq f), begin rw this, exact finsupp.injective_map_domain (finsupp.injective_map_domain hf) end lemma total_degree_rename_le (f : β → γ) (p : mv_polynomial β α) : (p.rename f).total_degree ≤ p.total_degree := finset.sup_le $ assume b, begin assume h, rw rename_eq at h, have h' := finsupp.map_domain_support h, rw finset.mem_image at h', rcases h' with ⟨s, hs, rfl⟩, rw finsupp.sum_map_domain_index, exact le_trans (le_refl _) (finset.le_sup hs), exact assume _, rfl, exact assume _ _ _, rfl end section variables [comm_semiring β] (f : α → β) [is_semiring_hom f] variables (k : γ → δ) (g : δ → β) (p : mv_polynomial γ α) lemma eval₂_rename : (p.rename k).eval₂ f g = p.eval₂ f (g ∘ k) := by apply mv_polynomial.induction_on p; { intros, simp [*] } lemma rename_eval₂ (g : δ → mv_polynomial γ α) : (p.eval₂ C (g ∘ k)).rename k = (p.rename k).eval₂ C (rename k ∘ g) := by apply mv_polynomial.induction_on p; { intros, simp [*] } lemma rename_prodmk_eval₂ (d : δ) (g : γ → mv_polynomial γ α) : (p.eval₂ C g).rename (prod.mk d) = p.eval₂ C (λ x, (g x).rename (prod.mk d)) := by apply mv_polynomial.induction_on p; { intros, simp [*] } lemma eval₂_rename_prodmk (g : δ × γ → β) (d : δ) : (rename (prod.mk d) p).eval₂ f g = eval₂ f (λ i, g (d, i)) p := by apply mv_polynomial.induction_on p; { intros, simp [*] } lemma eval_rename_prodmk (g : δ × γ → α) (d : δ) : (rename (prod.mk d) p).eval g = eval (λ i, g (d, i)) p := eval₂_rename_prodmk id _ _ _ end end rename lemma eval₂_cast_comp {β : Type u} {γ : Type v} (f : γ → β) {α : Type w} [comm_ring α] (c : ℤ → α) [is_ring_hom c] (g : β → α) (x : mv_polynomial γ ℤ) : eval₂ c (g ∘ f) x = eval₂ c g (rename f x) := mv_polynomial.induction_on x (λ n, by simp only [eval₂_C, rename_C]) (λ p q hp hq, by simp only [hp, hq, rename, eval₂_add]) (λ p n hp, by simp only [hp, rename, eval₂_X, eval₂_mul]) instance rename.is_ring_hom {α} [comm_ring α] (f : β → γ) : is_ring_hom (rename f : mv_polynomial β α → mv_polynomial γ α) := @is_ring_hom.of_semiring (mv_polynomial β α) (mv_polynomial γ α) _ _ (rename f) (rename.is_semiring_hom f) section equiv variables (α) [comm_semiring α] /-- The ring isomorphism between multivariable polynomials in no variables and the ground ring. -/ def pempty_ring_equiv : mv_polynomial pempty α ≃+* α := { to_fun := mv_polynomial.eval₂ id $ pempty.elim, inv_fun := C, left_inv := is_id _ (by apply_instance) (assume a, by rw [eval₂_C]; refl) (assume a, a.elim), right_inv := λ r, eval₂_C _ _ _, map_mul' := λ _ _, eval₂_mul _ _, map_add' := λ _ _, eval₂_add _ _ } /-- The ring isomorphism between multivariable polynomials in a single variable and polynomials over the ground ring. -/ def punit_ring_equiv : mv_polynomial punit α ≃+* polynomial α := { to_fun := eval₂ polynomial.C (λu:punit, polynomial.X), inv_fun := polynomial.eval₂ mv_polynomial.C (X punit.star), left_inv := begin refine is_id _ _ _ _, apply is_semiring_hom.comp (eval₂ polynomial.C (λu:punit, polynomial.X)) _; apply_instance, { assume a, rw [eval₂_C, polynomial.eval₂_C] }, { rintros ⟨⟩, rw [eval₂_X, polynomial.eval₂_X] } end, right_inv := assume p, polynomial.induction_on p (assume a, by rw [polynomial.eval₂_C, mv_polynomial.eval₂_C]) (assume p q hp hq, by rw [polynomial.eval₂_add, mv_polynomial.eval₂_add, hp, hq]) (assume p n hp, by rw [polynomial.eval₂_mul, polynomial.eval₂_pow, polynomial.eval₂_X, polynomial.eval₂_C, eval₂_mul, eval₂_C, eval₂_pow, eval₂_X]), map_mul' := λ _ _, eval₂_mul _ _, map_add' := λ _ _, eval₂_add _ _ } /-- The ring isomorphism between multivariable polynomials induced by an equivalence of the variables. -/ def ring_equiv_of_equiv (e : β ≃ γ) : mv_polynomial β α ≃+* mv_polynomial γ α := { to_fun := rename e, inv_fun := rename e.symm, left_inv := λ p, by simp only [rename_rename, (∘), e.symm_apply_apply]; exact rename_id p, right_inv := λ p, by simp only [rename_rename, (∘), e.apply_symm_apply]; exact rename_id p, map_mul' := rename_mul e, map_add' := rename_add e } /-- The ring isomorphism between multivariable polynomials induced by a ring isomorphism of the ground ring. -/ def ring_equiv_congr [comm_semiring γ] (e : α ≃+* γ) : mv_polynomial β α ≃+* mv_polynomial β γ := { to_fun := map e, inv_fun := map e.symm, left_inv := assume p, have (e.symm ∘ e) = id, { ext a, exact e.symm_apply_apply a }, by simp only [map_map, this, map_id], right_inv := assume p, have (e ∘ e.symm) = id, { ext a, exact e.apply_symm_apply a }, by simp only [map_map, this, map_id], map_mul' := map_mul _, map_add' := map_add _ } section variables (β γ δ) /-- The function from multivariable polynomials in a sum of two types, to multivariable polynomials in one of the types, with coefficents in multivariable polynomials in the other type. See `sum_ring_equiv` for the ring isomorphism. -/ def sum_to_iter : mv_polynomial (β ⊕ γ) α → mv_polynomial β (mv_polynomial γ α) := eval₂ (C ∘ C) (λbc, sum.rec_on bc X (C ∘ X)) instance is_semiring_hom_C_C : is_semiring_hom (C ∘ C : α → mv_polynomial β (mv_polynomial γ α)) := @is_semiring_hom.comp _ _ _ _ C mv_polynomial.is_semiring_hom _ _ C mv_polynomial.is_semiring_hom instance is_semiring_hom_sum_to_iter : is_semiring_hom (sum_to_iter α β γ) := eval₂.is_semiring_hom _ _ lemma sum_to_iter_C (a : α) : sum_to_iter α β γ (C a) = C (C a) := eval₂_C _ _ a lemma sum_to_iter_Xl (b : β) : sum_to_iter α β γ (X (sum.inl b)) = X b := eval₂_X _ _ (sum.inl b) lemma sum_to_iter_Xr (c : γ) : sum_to_iter α β γ (X (sum.inr c)) = C (X c) := eval₂_X _ _ (sum.inr c) /-- The function from multivariable polynomials in one type, with coefficents in multivariable polynomials in another type, to multivariable polynomials in the sum of the two types. See `sum_ring_equiv` for the ring isomorphism. -/ def iter_to_sum : mv_polynomial β (mv_polynomial γ α) → mv_polynomial (β ⊕ γ) α := eval₂ (eval₂ C (X ∘ sum.inr)) (X ∘ sum.inl) instance is_semiring_hom_iter_to_sum : is_semiring_hom (iter_to_sum α β γ) := eval₂.is_semiring_hom _ _ lemma iter_to_sum_C_C (a : α) : iter_to_sum α β γ (C (C a)) = C a := eq.trans (eval₂_C _ _ (C a)) (eval₂_C _ _ _) lemma iter_to_sum_X (b : β) : iter_to_sum α β γ (X b) = X (sum.inl b) := eval₂_X _ _ _ lemma iter_to_sum_C_X (c : γ) : iter_to_sum α β γ (C (X c)) = X (sum.inr c) := eq.trans (eval₂_C _ _ (X c)) (eval₂_X _ _ _) /-- A helper function for `sum_ring_equiv`. -/ def mv_polynomial_equiv_mv_polynomial [comm_semiring δ] (f : mv_polynomial β α → mv_polynomial γ δ) (hf : is_semiring_hom f) (g : mv_polynomial γ δ → mv_polynomial β α) (hg : is_semiring_hom g) (hfgC : ∀a, f (g (C a)) = C a) (hfgX : ∀n, f (g (X n)) = X n) (hgfC : ∀a, g (f (C a)) = C a) (hgfX : ∀n, g (f (X n)) = X n) : mv_polynomial β α ≃+* mv_polynomial γ δ := { to_fun := f, inv_fun := g, left_inv := is_id _ (is_semiring_hom.comp _ _) hgfC hgfX, right_inv := is_id _ (is_semiring_hom.comp _ _) hfgC hfgX, map_mul' := hf.map_mul, map_add' := hf.map_add } /-- The ring isomorphism between multivariable polynomials in a sum of two types, and multivariable polynomials in one of the types, with coefficents in multivariable polynomials in the other type. -/ def sum_ring_equiv : mv_polynomial (β ⊕ γ) α ≃+* mv_polynomial β (mv_polynomial γ α) := begin apply @mv_polynomial_equiv_mv_polynomial α (β ⊕ γ) _ _ _ _ (sum_to_iter α β γ) _ (iter_to_sum α β γ) _, { assume p, apply hom_eq_hom _ _ _ _ _ _ p, apply_instance, { apply @is_semiring_hom.comp _ _ _ _ _ _ _ _ _ _, apply_instance, apply @is_semiring_hom.comp _ _ _ _ _ _ _ _ _ _, apply_instance, { apply @mv_polynomial.is_semiring_hom }, { apply mv_polynomial.is_semiring_hom_iter_to_sum α β γ }, { apply mv_polynomial.is_semiring_hom_sum_to_iter α β γ } }, { apply mv_polynomial.is_semiring_hom }, { assume a, rw [iter_to_sum_C_C α β γ, sum_to_iter_C α β γ] }, { assume c, rw [iter_to_sum_C_X α β γ, sum_to_iter_Xr α β γ] } }, { assume b, rw [iter_to_sum_X α β γ, sum_to_iter_Xl α β γ] }, { assume a, rw [sum_to_iter_C α β γ, iter_to_sum_C_C α β γ] }, { assume n, cases n with b c, { rw [sum_to_iter_Xl, iter_to_sum_X] }, { rw [sum_to_iter_Xr, iter_to_sum_C_X] } }, { apply mv_polynomial.is_semiring_hom_sum_to_iter α β γ }, { apply mv_polynomial.is_semiring_hom_iter_to_sum α β γ } end /-- The ring isomorphism between multivariable polynomials in `option β` and polynomials with coefficients in `mv_polynomial β α`. -/ def option_equiv_left : mv_polynomial (option β) α ≃+* polynomial (mv_polynomial β α) := (ring_equiv_of_equiv α $ (equiv.option_equiv_sum_punit β).trans (equiv.sum_comm _ _)).trans $ (sum_ring_equiv α _ _).trans $ punit_ring_equiv _ /-- The ring isomorphism between multivariable polynomials in `option β` and multivariable polynomials with coefficients in polynomials. -/ def option_equiv_right : mv_polynomial (option β) α ≃+* mv_polynomial β (polynomial α) := (ring_equiv_of_equiv α $ equiv.option_equiv_sum_punit.{0} β).trans $ (sum_ring_equiv α β unit).trans $ ring_equiv_congr (mv_polynomial unit α) (punit_ring_equiv α) end end equiv end mv_polynomial
02143a67bc97eb92fbe4bb254626acb126d13ed2
f5f7e6fae601a5fe3cac7cc3ed353ed781d62419
/src/data/num/basic.lean
a36b360ee37f1f1981409b65e8cf1751514633cd
[ "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
17,315
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Mario Carneiro Binary representation of integers using inductive types. Note: Unlike in Coq, where this representation is preferred because of the reliance on kernel reduction, in Lean this representation is discouraged in favor of the "Peano" natural numbers `nat`, and the purpose of this collection of theorems is to show the equivalence of the different approaches. -/ import data.pnat data.bool data.vector data.bitvec /-- The type of positive binary numbers. 13 = 1101(base 2) = bit1 (bit0 (bit1 one)) -/ @[derive has_reflect, derive decidable_eq] inductive pos_num : Type | one : pos_num | bit1 : pos_num → pos_num | bit0 : pos_num → pos_num instance : has_one pos_num := ⟨pos_num.one⟩ /-- The type of nonnegative binary numbers, using `pos_num`. 13 = 1101(base 2) = pos (bit1 (bit0 (bit1 one))) -/ @[derive has_reflect, derive decidable_eq] inductive num : Type | zero : num | pos : pos_num → num instance : has_zero num := ⟨num.zero⟩ instance : has_one num := ⟨num.pos 1⟩ /-- Representation of integers using trichotomy around zero. 13 = 1101(base 2) = pos (bit1 (bit0 (bit1 one))) -13 = -1101(base 2) = neg (bit1 (bit0 (bit1 one))) -/ @[derive has_reflect, derive decidable_eq] inductive znum : Type | zero : znum | pos : pos_num → znum | neg : pos_num → znum instance : has_zero znum := ⟨znum.zero⟩ instance : has_one znum := ⟨znum.pos 1⟩ /-- See `snum`. -/ @[derive has_reflect, derive decidable_eq] inductive nzsnum : Type | msb : bool → nzsnum | bit : bool → nzsnum → nzsnum /-- Alternative representation of integers using a sign bit at the end. The convention on sign here is to have the argument to `msb` denote the sign of the MSB itself, with all higher bits set to the negation of this sign. The result is interpreted in two's complement. 13 = ..0001101(base 2) = nz (bit1 (bit0 (bit1 (msb tt)))) -13 = ..1110011(base 2) = nz (bit1 (bit1 (bit0 (msb ff)))) As with `num`, a special case must be added for zero, which has no msb, but by two's complement symmetry there is a second special case for -1. Here the `bool` field indicates the sign of the number. 0 = ..0000000(base 2) = zero ff -1 = ..1111111(base 2) = zero tt -/ @[derive has_reflect, derive decidable_eq] inductive snum : Type | zero : bool → snum | nz : nzsnum → snum instance : has_coe nzsnum snum := ⟨snum.nz⟩ instance : has_zero snum := ⟨snum.zero ff⟩ instance : has_one nzsnum := ⟨nzsnum.msb tt⟩ instance : has_one snum := ⟨snum.nz 1⟩ namespace pos_num def bit (b : bool) : pos_num → pos_num := cond b bit1 bit0 def succ : pos_num → pos_num | 1 := bit0 one | (bit1 n) := bit0 (succ n) | (bit0 n) := bit1 n def is_one : pos_num → bool | 1 := tt | _ := ff protected def add : pos_num → pos_num → pos_num | 1 b := succ b | a 1 := succ a | (bit0 a) (bit0 b) := bit0 (add a b) | (bit1 a) (bit1 b) := bit0 (succ (add a b)) | (bit0 a) (bit1 b) := bit1 (add a b) | (bit1 a) (bit0 b) := bit1 (add a b) instance : has_add pos_num := ⟨pos_num.add⟩ def pred' : pos_num → num | 1 := 0 | (bit0 n) := num.pos (num.cases_on (pred' n) 1 bit1) | (bit1 n) := num.pos (bit0 n) def pred (a : pos_num) : pos_num := num.cases_on (pred' a) 1 id def size : pos_num → pos_num | 1 := 1 | (bit0 n) := succ (size n) | (bit1 n) := succ (size n) def nat_size : pos_num → nat | 1 := 1 | (bit0 n) := nat.succ (nat_size n) | (bit1 n) := nat.succ (nat_size n) protected def mul (a : pos_num) : pos_num → pos_num | 1 := a | (bit0 b) := bit0 (mul b) | (bit1 b) := bit0 (mul b) + a instance : has_mul pos_num := ⟨pos_num.mul⟩ def of_nat_succ : ℕ → pos_num | 0 := 1 | (nat.succ n) := succ (of_nat_succ n) def of_nat (n : ℕ) : pos_num := of_nat_succ (nat.pred n) open ordering def cmp : pos_num → pos_num → ordering | 1 1 := eq | _ 1 := gt | 1 _ := lt | (bit0 a) (bit0 b) := cmp a b | (bit0 a) (bit1 b) := ordering.cases_on (cmp a b) lt lt gt | (bit1 a) (bit0 b) := ordering.cases_on (cmp a b) lt gt gt | (bit1 a) (bit1 b) := cmp a b instance : has_lt pos_num := ⟨λa b, cmp a b = ordering.lt⟩ instance : has_le pos_num := ⟨λa b, ¬ b < a⟩ instance decidable_lt : @decidable_rel pos_num (<) | a b := by dsimp [(<)]; apply_instance instance decidable_le : @decidable_rel pos_num (≤) | a b := by dsimp [(≤)]; apply_instance end pos_num section variables {α : Type*} [has_zero α] [has_one α] [has_add α] def cast_pos_num : pos_num → α | 1 := 1 | (pos_num.bit0 a) := bit0 (cast_pos_num a) | (pos_num.bit1 a) := bit1 (cast_pos_num a) def cast_num : num → α | 0 := 0 | (num.pos p) := cast_pos_num p @[priority 0] instance pos_num_coe : has_coe pos_num α := ⟨cast_pos_num⟩ @[priority 0] instance num_nat_coe : has_coe num α := ⟨cast_num⟩ instance : has_repr pos_num := ⟨λ n, repr (n : ℕ)⟩ instance : has_repr num := ⟨λ n, repr (n : ℕ)⟩ end namespace num open pos_num def succ' : num → pos_num | 0 := 1 | (pos p) := succ p def succ (n : num) : num := pos (succ' n) protected def add : num → num → num | 0 a := a | b 0 := b | (pos a) (pos b) := pos (a + b) instance : has_add num := ⟨num.add⟩ protected def bit0 : num → num | 0 := 0 | (pos n) := pos (pos_num.bit0 n) protected def bit1 : num → num | 0 := 1 | (pos n) := pos (pos_num.bit1 n) def bit (b : bool) : num → num := cond b num.bit1 num.bit0 def size : num → num | 0 := 0 | (pos n) := pos (pos_num.size n) def nat_size : num → nat | 0 := 0 | (pos n) := pos_num.nat_size n protected def mul : num → num → num | 0 _ := 0 | _ 0 := 0 | (pos a) (pos b) := pos (a * b) instance : has_mul num := ⟨num.mul⟩ open ordering def cmp : num → num → ordering | 0 0 := eq | _ 0 := gt | 0 _ := lt | (pos a) (pos b) := pos_num.cmp a b instance : has_lt num := ⟨λa b, cmp a b = ordering.lt⟩ instance : has_le num := ⟨λa b, ¬ b < a⟩ instance decidable_lt : @decidable_rel num (<) | a b := by dsimp [(<)]; apply_instance instance decidable_le : @decidable_rel num (≤) | a b := by dsimp [(≤)]; apply_instance def to_znum : num → znum | 0 := 0 | (pos a) := znum.pos a def to_znum_neg : num → znum | 0 := 0 | (pos a) := znum.neg a def of_nat' : ℕ → num := nat.binary_rec 0 (λ b n, cond b num.bit1 num.bit0) end num namespace znum open pos_num def zneg : znum → znum | 0 := 0 | (pos a) := neg a | (neg a) := pos a instance : has_neg znum := ⟨zneg⟩ def abs : znum → num | 0 := 0 | (pos a) := num.pos a | (neg a) := num.pos a def succ : znum → znum | 0 := 1 | (pos a) := pos (pos_num.succ a) | (neg a) := (pos_num.pred' a).to_znum_neg def pred : znum → znum | 0 := neg 1 | (pos a) := (pos_num.pred' a).to_znum | (neg a) := neg (pos_num.succ a) protected def bit0 : znum → znum | 0 := 0 | (pos n) := pos (pos_num.bit0 n) | (neg n) := neg (pos_num.bit0 n) protected def bit1 : znum → znum | 0 := 1 | (pos n) := pos (pos_num.bit1 n) | (neg n) := neg (num.cases_on (pred' n) 1 pos_num.bit1) protected def bitm1 : znum → znum | 0 := neg 1 | (pos n) := pos (num.cases_on (pred' n) 1 pos_num.bit1) | (neg n) := neg (pos_num.bit1 n) def of_int' : ℤ → znum | (n : ℕ) := num.to_znum (num.of_nat' n) | -[1+ n] := num.to_znum_neg (num.of_nat' (n+1)) end znum namespace pos_num open znum def sub' : pos_num → pos_num → znum | a 1 := (pred' a).to_znum | 1 b := (pred' b).to_znum_neg | (bit0 a) (bit0 b) := (sub' a b).bit0 | (bit0 a) (bit1 b) := (sub' a b).bitm1 | (bit1 a) (bit0 b) := (sub' a b).bit1 | (bit1 a) (bit1 b) := (sub' a b).bit0 def of_znum' : znum → option pos_num | (znum.pos p) := some p | _ := none def of_znum : znum → pos_num | (znum.pos p) := p | _ := 1 protected def sub (a b : pos_num) : pos_num := match sub' a b with | (znum.pos p) := p | _ := 1 end instance : has_sub pos_num := ⟨pos_num.sub⟩ end pos_num namespace num def ppred : num → option num | 0 := none | (pos p) := some p.pred' def pred : num → num | 0 := 0 | (pos p) := p.pred' def div2 : num → num | 0 := 0 | 1 := 0 | (pos (pos_num.bit0 p)) := pos p | (pos (pos_num.bit1 p)) := pos p def of_znum' : znum → option num | 0 := some 0 | (znum.pos p) := some (pos p) | (znum.neg p) := none def of_znum : znum → num | (znum.pos p) := pos p | _ := 0 def sub' : num → num → znum | 0 0 := 0 | (pos a) 0 := znum.pos a | 0 (pos b) := znum.neg b | (pos a) (pos b) := a.sub' b def psub (a b : num) : option num := of_znum' (sub' a b) protected def sub (a b : num) : num := of_znum (sub' a b) instance : has_sub num := ⟨num.sub⟩ end num namespace znum open pos_num protected def add : znum → znum → znum | 0 a := a | b 0 := b | (pos a) (pos b) := pos (a + b) | (pos a) (neg b) := sub' a b | (neg a) (pos b) := sub' b a | (neg a) (neg b) := neg (a + b) instance : has_add znum := ⟨znum.add⟩ protected def mul : znum → znum → znum | 0 a := 0 | b 0 := 0 | (pos a) (pos b) := pos (a * b) | (pos a) (neg b) := neg (a * b) | (neg a) (pos b) := neg (a * b) | (neg a) (neg b) := pos (a * b) instance : has_mul znum := ⟨znum.mul⟩ open ordering def cmp : znum → znum → ordering | 0 0 := eq | (pos a) (pos b) := pos_num.cmp a b | (neg a) (neg b) := pos_num.cmp b a | (pos _) _ := gt | (neg _) _ := lt | _ (pos _) := lt | _ (neg _) := gt instance : has_lt znum := ⟨λa b, cmp a b = ordering.lt⟩ instance : has_le znum := ⟨λa b, ¬ b < a⟩ instance decidable_lt : @decidable_rel znum (<) | a b := by dsimp [(<)]; apply_instance instance decidable_le : @decidable_rel znum (≤) | a b := by dsimp [(≤)]; apply_instance end znum namespace pos_num def divmod_aux (d : pos_num) (q r : num) : num × num := match num.of_znum' (num.sub' r (num.pos d)) with | some r' := (num.bit1 q, r') | none := (num.bit0 q, r) end def divmod (d : pos_num) : pos_num → num × num | (bit0 n) := let (q, r₁) := divmod n in divmod_aux d q (num.bit0 r₁) | (bit1 n) := let (q, r₁) := divmod n in divmod_aux d q (num.bit1 r₁) | 1 := divmod_aux d 0 1 def div' (n d : pos_num) : num := (divmod d n).1 def mod' (n d : pos_num) : num := (divmod d n).2 def sqrt_aux1 (b : pos_num) (r n : num) : num × num := match num.of_znum' (n.sub' (r + num.pos b)) with | some n' := (r.div2 + num.pos b, n') | none := (r.div2, n) end def sqrt_aux : pos_num → num → num → num | b@(bit0 b') r n := let (r', n') := sqrt_aux1 b r n in sqrt_aux b' r' n' | b@(bit1 b') r n := let (r', n') := sqrt_aux1 b r n in sqrt_aux b' r' n' | 1 r n := (sqrt_aux1 1 r n).1 /- def sqrt_aux : ℕ → ℕ → ℕ → ℕ | b r n := if b0 : b = 0 then r else let b' := shiftr b 2 in have b' < b, from sqrt_aux_dec b0, match (n - (r + b : ℕ) : ℤ) with | (n' : ℕ) := sqrt_aux b' (div2 r + b) n' | _ := sqrt_aux b' (div2 r) n end /-- `sqrt n` is the square root of a natural number `n`. If `n` is not a perfect square, it returns the largest `k:ℕ` such that `k*k ≤ n`. -/ def sqrt (n : ℕ) : ℕ := match size n with | 0 := 0 | succ s := sqrt_aux (shiftl 1 (bit0 (div2 s))) 0 n end -/ end pos_num namespace num def div : num → num → num | 0 _ := 0 | _ 0 := 0 | (pos n) (pos d) := pos_num.div' n d def mod : num → num → num | 0 _ := 0 | n 0 := n | (pos n) (pos d) := pos_num.mod' n d instance : has_div num := ⟨num.div⟩ instance : has_mod num := ⟨num.mod⟩ def gcd_aux : nat → num → num → num | 0 a b := b | (nat.succ n) 0 b := b | (nat.succ n) a b := gcd_aux n (b % a) a def gcd (a b : num) : num := if a ≤ b then gcd_aux (a.nat_size + b.nat_size) a b else gcd_aux (b.nat_size + a.nat_size) b a end num namespace znum def div : znum → znum → znum | 0 _ := 0 | _ 0 := 0 | (pos n) (pos d) := num.to_znum (pos_num.div' n d) | (pos n) (neg d) := num.to_znum_neg (pos_num.div' n d) | (neg n) (pos d) := neg (pos_num.pred' n / num.pos d).succ' | (neg n) (neg d) := pos (pos_num.pred' n / num.pos d).succ' def mod : znum → znum → znum | 0 d := 0 | (pos n) d := num.to_znum (num.pos n % d.abs) | (neg n) d := d.abs.sub' (pos_num.pred' n % d.abs).succ instance : has_div znum := ⟨znum.div⟩ instance : has_mod znum := ⟨znum.mod⟩ def gcd (a b : znum) : num := a.abs.gcd b.abs end znum section variables {α : Type*} [has_zero α] [has_one α] [has_add α] [has_neg α] def cast_znum : znum → α | 0 := 0 | (znum.pos p) := p | (znum.neg p) := -p @[priority 0] instance znum_coe : has_coe znum α := ⟨cast_znum⟩ instance : has_repr znum := ⟨λ n, repr (n : ℤ)⟩ end /- The snum representation uses a bit string, essentially a list of 0 (ff) and 1 (tt) bits, and the negation of the MSB is sign-extended to all higher bits. -/ namespace nzsnum notation a :: b := bit a b def sign : nzsnum → bool | (msb b) := bnot b | (b :: p) := sign p @[pattern] def not : nzsnum → nzsnum | (msb b) := msb (bnot b) | (b :: p) := bnot b :: not p prefix ~ := not def bit0 : nzsnum → nzsnum := bit ff def bit1 : nzsnum → nzsnum := bit tt def head : nzsnum → bool | (msb b) := b | (b :: p) := b def tail : nzsnum → snum | (msb b) := snum.zero (bnot b) | (b :: p) := p end nzsnum namespace snum open nzsnum def sign : snum → bool | (zero z) := z | (nz p) := p.sign @[pattern] def not : snum → snum | (zero z) := zero (bnot z) | (nz p) := ~p prefix ~ := not @[pattern] def bit : bool → snum → snum | b (zero z) := if b = z then zero b else msb b | b (nz p) := p.bit b notation a :: b := bit a b def bit0 : snum → snum := bit ff def bit1 : snum → snum := bit tt theorem bit_zero (b) : b :: zero b = zero b := by cases b; refl theorem bit_one (b) : b :: zero (bnot b) = msb b := by cases b; refl end snum namespace nzsnum open snum def drec' {C : snum → Sort*} (z : Π b, C (snum.zero b)) (s : Π b p, C p → C (b :: p)) : Π p : nzsnum, C p | (msb b) := by rw ←bit_one; exact s b (snum.zero (bnot b)) (z (bnot b)) | (bit b p) := s b p (drec' p) end nzsnum namespace snum open nzsnum def head : snum → bool | (zero z) := z | (nz p) := p.head def tail : snum → snum | (zero z) := zero z | (nz p) := p.tail def drec' {C : snum → Sort*} (z : Π b, C (snum.zero b)) (s : Π b p, C p → C (b :: p)) : Π p, C p | (zero b) := z b | (nz p) := p.drec' z s def rec' {α} (z : bool → α) (s : bool → snum → α → α) : snum → α := drec' z s def bits : snum → Π n, vector bool n | p 0 := vector.nil | p (n+1) := head p :: bits (tail p) n def test_bit : nat → snum → bool | 0 p := head p | (n+1) p := test_bit n (tail p) def succ : snum → snum := rec' (λ b, cond b 0 1) (λb p succp, cond b (ff :: succp) (tt :: p)) def pred : snum → snum := rec' (λ b, cond b (~1) ~0) (λb p predp, cond b (ff :: p) (tt :: predp)) protected def neg (n : snum) : snum := succ ~n instance : has_neg snum := ⟨snum.neg⟩ -- First bit is 0 or 1 (tt), second bit is 0 or -1 (tt) def czadd : bool → bool → snum → snum | ff ff p := p | ff tt p := pred p | tt ff p := succ p | tt tt p := p def cadd : snum → snum → bool → snum := rec' (λ a p c, czadd c a p) $ λa p IH, rec' (λb c, czadd c b (a :: p)) $ λb q _ c, bitvec.xor3 a b c :: IH q (bitvec.carry a b c) protected def add (a b : snum) : snum := cadd a b ff instance : has_add snum := ⟨snum.add⟩ protected def sub (a b : snum) : snum := a + -b instance : has_sub snum := ⟨snum.sub⟩ protected def mul (a : snum) : snum → snum := rec' (λ b, cond b (-a) 0) $ λb q IH, cond b (bit0 IH + a) (bit0 IH) instance : has_mul snum := ⟨snum.mul⟩ end snum namespace int def of_snum : snum → ℤ := snum.rec' (λ a, cond a (-1) 0) (λa p IH, cond a (bit1 IH) (bit0 IH)) instance snum_coe : has_coe snum ℤ := ⟨of_snum⟩ end int instance : has_lt snum := ⟨λa b, (a : ℤ) < b⟩ instance : has_le snum := ⟨λa b, (a : ℤ) ≤ b⟩
263b93809b4fda1fabf1f15f208661ae19f79919
9dc8cecdf3c4634764a18254e94d43da07142918
/src/group_theory/group_action/sum.lean
12e63af2154b719e0c5dec6052931a04d98b1421
[ "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
2,568
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import group_theory.group_action.defs /-! # Sum instances for additive and multiplicative actions This file defines instances for additive and multiplicative actions on the binary `sum` type. ## See also * `group_theory.group_action.option` * `group_theory.group_action.pi` * `group_theory.group_action.prod` * `group_theory.group_action.sigma` -/ variables {M N P α β γ : Type*} namespace sum section has_smul variables [has_smul M α] [has_smul M β] [has_smul N α] [has_smul N β] (a : M) (b : α) (c : β) (x : α ⊕ β) @[to_additive sum.has_vadd] instance : has_smul M (α ⊕ β) := ⟨λ a, sum.map ((•) a) ((•) a)⟩ @[to_additive] lemma smul_def : a • x = x.map ((•) a) ((•) a) := rfl @[simp, to_additive] lemma smul_inl : a • (inl b : α ⊕ β) = inl (a • b) := rfl @[simp, to_additive] lemma smul_inr : a • (inr c : α ⊕ β) = inr (a • c) := rfl @[simp, to_additive] lemma smul_swap : (a • x).swap = a • x.swap := by cases x; refl instance [has_smul M N] [is_scalar_tower M N α] [is_scalar_tower M N β] : is_scalar_tower M N (α ⊕ β) := ⟨λ a b x, by { cases x, exacts [congr_arg inl (smul_assoc _ _ _), congr_arg inr (smul_assoc _ _ _)] }⟩ @[to_additive] instance [smul_comm_class M N α] [smul_comm_class M N β] : smul_comm_class M N (α ⊕ β) := ⟨λ a b x, by { cases x, exacts [congr_arg inl (smul_comm _ _ _), congr_arg inr (smul_comm _ _ _)] }⟩ instance [has_smul Mᵐᵒᵖ α] [has_smul Mᵐᵒᵖ β] [is_central_scalar M α] [is_central_scalar M β] : is_central_scalar M (α ⊕ β) := ⟨λ a x, by { cases x, exacts [congr_arg inl (op_smul_eq_smul _ _), congr_arg inr (op_smul_eq_smul _ _)] }⟩ @[to_additive] instance has_faithful_smul_left [has_faithful_smul M α] : has_faithful_smul M (α ⊕ β) := ⟨λ x y h, eq_of_smul_eq_smul $ λ a : α, by injection h (inl a)⟩ @[to_additive] instance has_faithful_smul_right [has_faithful_smul M β] : has_faithful_smul M (α ⊕ β) := ⟨λ x y h, eq_of_smul_eq_smul $ λ b : β, by injection h (inr b)⟩ end has_smul @[to_additive] instance {m : monoid M} [mul_action M α] [mul_action M β] : mul_action M (α ⊕ β) := { mul_smul := λ a b x, by { cases x, exacts [congr_arg inl (mul_smul _ _ _), congr_arg inr (mul_smul _ _ _)] }, one_smul := λ x, by { cases x, exacts [congr_arg inl (one_smul _ _), congr_arg inr (one_smul _ _)] } } end sum
945f7109535a7700889f5ea229346ba2fba88a2b
57fdc8de88f5ea3bfde4325e6ecd13f93a274ab5
/ring_theory/localization.lean
73ebc610eae50faa4c6777bb8780c2c4fb86b982
[ "Apache-2.0" ]
permissive
louisanu/mathlib
11f56f2d40dc792bc05ee2f78ea37d73e98ecbfe
2bd5e2159d20a8f20d04fc4d382e65eea775ed39
refs/heads/master
1,617,706,993,439
1,523,163,654,000
1,523,163,654,000
124,519,997
0
0
Apache-2.0
1,520,588,283,000
1,520,588,283,000
null
UTF-8
Lean
false
false
10,412
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import tactic.ring data.quot ring_theory.ideals universe u namespace localization variables (α : Type u) [comm_ring α] (S : set α) [is_submonoid α S] def r : α × S → α × S → Prop := λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩, ∃ t ∈ S, (s₁ * r₂ - s₂ * r₁) * t = 0 local infix ≈ := r α S section variables {α S} theorem r_of_eq : ∀{a₀ a₁ : α × S} (h : a₀.2.1 * a₁.1 = a₁.2.1 * a₀.1), a₀ ≈ a₁ | ⟨r₀, s₀, hs₀⟩ ⟨r₁, s₁, hs₁⟩ h := ⟨1, is_submonoid.one_mem S, by simp [h] at h ⊢⟩ end theorem refl (x : α × S) : x ≈ x := r_of_eq rfl theorem symm : ∀ (x y : α × S), x ≈ y → y ≈ x := λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨t, hts, ht⟩, ⟨t, hts, calc (s₂ * r₁ - s₁ * r₂) * t = -((s₁ * r₂ - s₂ * r₁) * t) : by simp [add_mul] ... = 0 : by rw ht; simp⟩ theorem trans : ∀ (x y z : α × S), x ≈ y → y ≈ z → x ≈ z := λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨r₃, s₃, hs₃⟩ ⟨t, hts, ht⟩ ⟨t', hts', ht'⟩, ⟨s₂ * t' * t, is_submonoid.mul_mem (is_submonoid.mul_mem hs₂ hts') hts, calc (s₁ * r₃ - s₃ * r₁) * (s₂ * t' * t) = t' * s₃ * ((s₁ * r₂ - s₂ * r₁) * t) + t * s₁ * ((s₂ * r₃ - s₃ * r₂) * t') : by simp [mul_left_comm, mul_add, mul_comm] ... = 0 : by rw [ht, ht']; simp⟩ instance : setoid (α × S) := ⟨r α S, refl α S, symm α S, trans α S⟩ def loc := quotient $ localization.setoid α S private def add_aux : α × S → α × S → loc α S := λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩, ⟦⟨s₁ * r₂ + s₂ * r₁, s₁ * s₂, is_submonoid.mul_mem hs₁ hs₂⟩⟧ instance : has_add (loc α S) := ⟨quotient.lift₂ (add_aux α S) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨r₃, s₃, hs₃⟩ ⟨r₄, s₄, hs₄⟩ ⟨t₅, hts₅, ht₅⟩ ⟨t₆, hts₆, ht₆⟩, quotient.sound ⟨t₆ * t₅, is_submonoid.mul_mem hts₆ hts₅, calc (s₁ * s₂ * (s₃ * r₄ + s₄ * r₃) - s₃ * s₄ * (s₁ * r₂ + s₂ * r₁)) * (t₆ * t₅) = s₁ * s₃ * ((s₂ * r₄ - s₄ * r₂) * t₆) * t₅ + s₂ * s₄ * ((s₁ * r₃ - s₃ * r₁) * t₅) * t₆ : by ring ... = 0 : by rw [ht₆, ht₅]; simp⟩⟩ private def neg_aux : α × S → loc α S := λ ⟨r, s, hs⟩, ⟦⟨-r, s, hs⟩⟧ instance : has_neg (loc α S) := ⟨quotient.lift (neg_aux α S) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨t, hts, ht⟩, quotient.sound ⟨t, hts, calc (s₁ * -r₂ - s₂ * -r₁) * t = -((s₁ * r₂ - s₂ * r₁) * t) : by ring ... = 0 : by rw ht; simp⟩⟩ private def mul_aux : α × S → α × S → loc α S := λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩, ⟦⟨r₁ * r₂, s₁ * s₂, is_submonoid.mul_mem hs₁ hs₂⟩⟧ instance : has_mul (loc α S) := ⟨quotient.lift₂ (mul_aux α S) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨r₃, s₃, hs₃⟩ ⟨r₄, s₄, hs₄⟩ ⟨t₅, hts₅, ht₅⟩ ⟨t₆, hts₆, ht₆⟩, quotient.sound ⟨t₆ * t₅, is_submonoid.mul_mem hts₆ hts₅, calc ((s₁ * s₂) * (r₃ * r₄) - (s₃ * s₄) * (r₁ * r₂)) * (t₆ * t₅) = t₆ * ((s₁ * r₃ - s₃ * r₁) * t₅) * r₂ * s₄ + t₅ * ((s₂ * r₄ - s₄ * r₂) * t₆) * r₃ * s₁ : by simp [mul_left_comm, mul_add, mul_comm] ... = 0 : by rw [ht₅, ht₆]; simp⟩⟩ def of_comm_ring : α → loc α S := λ r, ⟦⟨r, 1, is_submonoid.one_mem S⟩⟧ instance : comm_ring (loc α S) := by refine { add := has_add.add, add_assoc := λ m n k, quotient.induction_on₃ m n k _, zero := of_comm_ring α S 0, zero_add := quotient.ind _, add_zero := quotient.ind _, neg := has_neg.neg, add_left_neg := quotient.ind _, add_comm := quotient.ind₂ _, mul := has_mul.mul, mul_assoc := λ m n k, quotient.induction_on₃ m n k _, one := of_comm_ring α S 1, one_mul := quotient.ind _, mul_one := quotient.ind _, left_distrib := λ m n k, quotient.induction_on₃ m n k _, right_distrib := λ m n k, quotient.induction_on₃ m n k _, mul_comm := quotient.ind₂ _ }; { intros, try {cases a with r₁ s₁, cases s₁ with s₁ hs₁}, try {cases b with r₂ s₂, cases s₂ with s₂ hs₂}, try {cases c with r₃ s₃, cases s₃ with s₃ hs₃}, refine (quotient.sound $ r_of_eq _), simp [mul_left_comm, mul_add, mul_comm] } instance : is_ring_hom (of_comm_ring α S) := { map_add := λ x y, quotient.sound $ by simp, map_mul := λ x y, quotient.sound $ by simp, map_one := rfl } variable {α} def away (x : α) := loc α (powers x) instance away.comm_ring (x : α) : comm_ring (away x) := localization.comm_ring α (powers x) section at_prime variables (P : set α) [is_prime_ideal P] instance prime.is_submonoid : is_submonoid α (set.compl P) := { one_mem := λ h, is_proper_ideal.ne_univ P $ is_submodule.univ_of_one_mem P h, mul_mem := λ x y hnx hny hxy, or.cases_on (is_prime_ideal.mem_or_mem_of_mul_mem hxy) hnx hny } def at_prime := loc α (set.compl P) instance at_prime.comm_ring : comm_ring (at_prime P) := localization.comm_ring α (set.compl P) instance at_prime.local_ring : local_ring (at_prime P) := local_of_nonunits_ideal (λ hze, let ⟨t, hts, ht⟩ := quotient.exact hze in hts $ have htz : t = 0, by simpa using ht, suffices (0:α) ∈ P, by rwa htz, @is_submodule.zero _ _ _ _ P _) (λ x y hx hy ⟨z, hz⟩, let ⟨⟨r₁, s₁, hs₁⟩, hrs₁⟩ := quotient.exists_rep x, ⟨⟨r₂, s₂, hs₂⟩, hrs₂⟩ := quotient.exists_rep y, ⟨⟨r₃, s₃, hs₃⟩, hrs₃⟩ := quotient.exists_rep z in have _, by rw [← hrs₁, ← hrs₂, ← hrs₃] at hz; from quotient.exact hz, let ⟨t, hts, ht⟩ := this in have hr₁ : r₁ ∈ P, from classical.by_contradiction $ λ hnr₁, hx ⟨⟦⟨s₁, r₁, hnr₁⟩⟧, by rw ←hrs₁; from (quotient.sound $ r_of_eq $ by simp [mul_comm])⟩, have hr₂ : r₂ ∈ P, from classical.by_contradiction $ λ hnr₂, hy ⟨⟦⟨s₂, r₂, hnr₂⟩⟧, by rw ←hrs₂; from (quotient.sound $ r_of_eq $ by simp [mul_comm])⟩, have hr₃ : _ , from or.resolve_right (mem_or_mem_of_mul_eq_zero P ht) hts, have h : s₃ * (s₁ * s₂) - r₃ * (s₁ * r₂ + s₂ * r₁) ∈ P, by simpa using hr₃, have h1 : r₃ * (s₁ * r₂ + s₂ * r₁) ∈ P, from is_submodule.smul r₃ $ is_submodule.add (is_submodule.smul s₁ hr₂) (is_submodule.smul s₂ hr₁), have h2 : s₃ * (s₁ * s₂) ∈ P, from calc s₃ * (s₁ * s₂) = s₃ * (s₁ * s₂) - r₃ * (s₁ * r₂ + s₂ * r₁) + r₃ * (s₁ * r₂ + s₂ * r₁) : eq.symm $ sub_add_cancel _ _ ... ∈ P : is_submodule.add h h1, have h3 : s₁ * s₂ ∈ P, from or.resolve_left (is_prime_ideal.mem_or_mem_of_mul_mem h2) hs₃, or.cases_on (is_prime_ideal.mem_or_mem_of_mul_mem h3) hs₁ hs₂) end at_prime inductive in_closure (S : set α) : α → Prop | basic : ∀a∈S, in_closure a | one : in_closure 1 | mul : ∀x y, in_closure x → in_closure y → in_closure (x * y) def closure (S : set α) : set α := {x | in_closure S x} instance closure.is_submonoid (S : set α) : is_submonoid α (closure S) := { one_mem := in_closure.one S, mul_mem := in_closure.mul } theorem subset_closure {S : set α} : S ⊆ closure S := in_closure.basic variable (α) def non_zero_divisors : set α := {x | ∀ z, z * x = 0 → z = 0} instance non_zero_divisors.is_submonoid : is_submonoid α (non_zero_divisors α) := { one_mem := λ z hz, by simpa using hz, mul_mem := λ x₁ x₂ hx₁ hx₂ z hz, have z * x₁ * x₂ = 0, by rwa mul_assoc, hx₁ z $ hx₂ (z * x₁) this } def quotient_ring := loc α (non_zero_divisors α) instance quotient_ring.comm_ring : comm_ring (quotient_ring α) := localization.comm_ring α (non_zero_divisors α) section quotient_ring variables {β : Type u} [integral_domain β] [decidable_eq β] lemma ne_zero_of_mem_non_zero_divisors {x : β} : x ∈ localization.non_zero_divisors β → x ≠ 0 := λ hm hz, have 1 * x = 0, by simp [hz], zero_ne_one (hm 1 this).symm lemma eq_zero_of_ne_zero_of_mul_eq_zero {x y : β} : x ≠ 0 → y * x = 0 → y = 0 := λ hnx hxy, or.resolve_right (eq_zero_or_eq_zero_of_mul_eq_zero hxy) hnx lemma mem_non_zero_divisors_of_ne_zero {x : β} : x ≠ 0 → x ∈ localization.non_zero_divisors β := λ hnx z, eq_zero_of_ne_zero_of_mul_eq_zero hnx variable (β) private def inv_aux : β × (non_zero_divisors β) → quotient_ring β := λ ⟨r, s, hs⟩, if h : r = 0 then 0 else ⟦⟨s, r, mem_non_zero_divisors_of_ne_zero h⟩⟧ instance : has_inv (quotient_ring β) := ⟨quotient.lift (inv_aux β) $ λ ⟨r₁, s₁, hs₁⟩ ⟨r₂, s₂, hs₂⟩ ⟨t, hts, ht⟩, begin have hrs : s₁ * r₂ = 0 + s₂ * r₁, from sub_eq_iff_eq_add.1 (hts _ ht), by_cases hr₁ : r₁ = 0; by_cases hr₂ : r₂ = 0; simp [hr₁, hr₂] at hrs; simp [inv_aux, hr₁, hr₂], { exfalso, exact ne_zero_of_mem_non_zero_divisors hs₁ (eq_zero_of_ne_zero_of_mul_eq_zero hr₂ hrs) }, { exfalso, exact ne_zero_of_mem_non_zero_divisors hs₂ (eq_zero_of_ne_zero_of_mul_eq_zero hr₁ hrs.symm) }, { apply r_of_eq, simpa [mul_comm] using hrs.symm } end⟩ def quotient_ring.field.of_integral_domain : field (quotient_ring β) := by refine { inv := has_inv.inv, zero_ne_one := λ hzo, let ⟨t, hts, ht⟩ := quotient.exact hzo in zero_ne_one (by simpa using hts _ ht : 0 = 1), mul_inv_cancel := quotient.ind _, inv_mul_cancel := quotient.ind _, ..localization.comm_ring β _ }; { intros x hnx, rcases x with ⟨x, z, hz⟩, have : x ≠ 0, from assume hx, hnx (quotient.sound $ r_of_eq $ by simp [hx]), simp [has_inv.inv, inv_aux, inv_aux._match_1, this], exact (quotient.sound $ r_of_eq $ by simp; ring) } end quotient_ring end localization
7466e13a3ddf272da5c388ae8608382cfd75d734
556aeb81a103e9e0ac4e1fe0ce1bc6e6161c3c5e
/src/starkware/cairo/lean/semantics/air_encoding/final_correctness.lean
bfee87532255c5dc876f0cf3a34c35ac98c45922
[ "Apache-2.0" ]
permissive
starkware-libs/formal-proofs
d6b731604461bf99e6ba820e68acca62a21709e8
f5fa4ba6a471357fd171175183203d0b437f6527
refs/heads/master
1,691,085,444,753
1,690,507,386,000
1,690,507,386,000
410,476,629
32
9
Apache-2.0
1,690,506,773,000
1,632,639,790,000
Lean
UTF-8
Lean
false
false
3,858
lean
/- This is the final correctenss theorem, stated in terms of the autogenerated constraints. The statements of theorems only depend on the data and constraints specified in `constraints_autogenerated.lean` and the machine semantics in `cpu.lean`. -/ import starkware.cairo.lean.semantics.air_encoding.correctness import starkware.cairo.lean.semantics.air_encoding.glue noncomputable theory open_locale classical open_locale big_operators variables {F : Type} [field F] [fintype F] /- These are the constraints that the verifier has to check against the public data. -/ structure public_constraints (inp : input_data F) (pd : public_data F) : Prop := (h_mem_star : let z := pd.memory__multi_column_perm__perm__interaction_elm, alpha := pd.memory__multi_column_perm__hash_interaction_elm0, p := pd.memory__multi_column_perm__perm__public_memory_prod, dom_m_star := { x // option.is_some (inp.m_star x) } in p * ∏ a : dom_m_star, (z - (a.val + alpha * mem_val a)) = z^(fintype.card dom_m_star)) (h_card_dom : 8 * fintype.card { x // option.is_some (inp.m_star x) } + 2 ≤ inp.trace_length) (public_memory_prod_eq_one : pd.rc16__perm__public_memory_prod = 1) (rc_max_lt : pd.rc_max < 2^16) (rc_min_le : pd.rc_min ≤ pd.rc_max) (trace_length_le_char : inp.trace_length ≤ ring_char F) /- The main correctness theorem. -/ theorem final_correctness (char_ge : ring_char F ≥ 2^63) /- public data -/ (inp : input_data F) (pd : public_data F) (pc : public_constraints inp pd) (c : columns F) : /- sets to avoid -/ ∃ bad1 bad2 bad3 : finset F, bad1.card ≤ (inp.trace_length / 2)^2 ∧ bad2.card ≤ inp.trace_length / 2 ∧ bad3.card ≤ inp.trace_length ∧ ∀ ci : columns_inter F, /- autogenerated constraints-/ cpu__decode c ∧ cpu__operands c ∧ cpu__update_registers inp c ∧ cpu__opcodes c ∧ memory inp pd c ci ∧ rc16 inp pd c ci ∧ public_memory c ∧ rc_builtin inp pd c ∧ toplevel_constraints inp c ∧ /- probabilistic constraints -/ pd.memory__multi_column_perm__hash_interaction_elm0 ∉ bad1 ∧ pd.memory__multi_column_perm__perm__interaction_elm ∉ bad2 ∧ pd.memory__multi_column_perm__perm__interaction_elm ≠ 0 ∧ pd.rc16__perm__interaction_elm ∉ bad3 → let -- number of execution steps T := inp.trace_length / 16 - 1, -- memory elements checked by range check builtin rc_len := inp.trace_length / 128 in /- the conclusion -/ ∃ mem : F → F, option.fn_extends mem inp.m_star ∧ (∀ i < rc_len, ∃ n < 2^128, mem (pd.initial_rc_addr + i) = ↑n) ∧ ∃ exec : fin (T + 1) → register_state F, (exec 0).pc = inp.initial_pc ∧ (exec 0).ap = inp.initial_ap ∧ (exec 0).fp = inp.initial_ap ∧ (exec (fin.last T)).pc = inp.final_pc ∧ (exec (fin.last T)).ap = inp.final_ap ∧ ∀ i : fin T, next_state mem (exec i.cast_succ) (exec i.succ) := begin use bad1 pc.h_card_dom c.column19 c.column20, use bad2 pd pc.h_card_dom c.column19 c.column20, use bad3 inp c.column0 c.column2, use bad1_bound pc.h_card_dom _ _, use bad2_bound pd pc.h_card_dom _ _, use bad3_bound pc.h_card_dom _ _, intro ci, rintros ⟨cd, ops, upd, opcodes, m, rc, pm, rcb, iandf, prob1, prob2, prob3, prob4⟩, dsimp, exact execution_exists char_ge (inp.to_input_data_aux pd pc.rc_max_lt pc.rc_min_le) (to_constraints cd ops upd opcodes m rc pm rcb iandf pc.h_mem_star pc.h_card_dom pc.public_memory_prod_eq_one pc.rc_max_lt pc.rc_min_le pc.trace_length_le_char) { hprob₁ := prob1, hprob₂ := prob2, hprob₃ := prob3, hprob₄ := prob4 } end
31c7d904b49b3814a40d47b40d343f6c70a5ccad
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/data/set/function.lean
c517aaaaa3fe723bfd3a257bfb13ab877662d56c
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
18,238
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 import logic.function.basic /-! # 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
52f4cf51eeebb15726891925b57906ea1686ba19
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/choice_ctx.lean
1b19094ae5a73a3d9b98319c6317dc6f0321c953
[ "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
314
lean
open nat open eq set_option pp.coercions true namespace foo theorem trans {a b c : nat} (H1 : a = b) (H2 : b = c) : a = c := trans H1 H2 end foo open foo theorem tst (a b : nat) (H0 : b = a) (H : b = 0) : a = 0 := have H1 : a = b, from symm H0, foo.trans H1 H definition f (a b : nat) := let x := 3 in a + x
416aabfbf494bb213a907b2ce93e2da010179744
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/converter/apply_congr.lean
4c1ff3f74ea780ba546a8592ea269652f65e637c
[ "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,348
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Lucas Allen, Scott Morrison -/ import tactic.interactive import tactic.converter.interactive /-! ## Introduce the `apply_congr` conv mode tactic. `apply_congr` will apply congruence lemmas inside `conv` mode. It is particularly useful when the automatically generated congruence lemmas are not of the optimal shape. An example, described in the doc-string is rewriting inside the operand of a `finset.sum`. -/ open tactic namespace conv.interactive open interactive interactive.types lean.parser local postfix `?`:9001 := optional /-- Apply a congruence lemma inside `conv` mode. When called without an argument `apply_congr` will try applying all lemmas marked with `@[congr]`. Otherwise `apply_congr e` will apply the lemma `e`. Recall that a goal that appears as `∣ X` in `conv` mode represents a goal of `⊢ X = ?m`, i.e. an equation with a metavariable for the right hand side. To successfully use `apply_congr e`, `e` will need to be an equation (possibly after function arguments), which can be unified with a goal of the form `X = ?m`. The right hand side of `e` will then determine the metavariable, and `conv` will subsequently replace `X` with that right hand side. As usual, `apply_congr` can create new goals; any of these which are _not_ equations with a metavariable on the right hand side will be hard to deal with in `conv` mode. Thus `apply_congr` automatically calls `intros` on any new goals, and fails if they are not then equations. In particular it is useful for rewriting inside the operand of a `finset.sum`, as it provides an extra hypothesis asserting we are inside the domain. For example: ```lean example (f g : ℤ → ℤ) (S : finset ℤ) (h : ∀ m ∈ S, f m = g m) : finset.sum S f = finset.sum S g := begin conv_lhs { -- If we just call `congr` here, in the second goal we're helpless, -- because we are only given the opportunity to rewrite `f`. -- However `apply_congr` uses the appropriate `@[congr]` lemma, -- so we get to rewrite `f x`, in the presence of the crucial `H : x ∈ S` hypothesis. apply_congr, skip, simp [h, H], } end ``` In the above example, when the `apply_congr` tactic is called it gives the hypothesis `H : x ∈ S` which is then used to rewrite the `f x` to `g x`. -/ meta def apply_congr (q : parse texpr?) : conv unit := do congr_lemmas ← match q with -- If the user specified a lemma, use that one, | some e := do gs ← get_goals, e ← to_expr e, -- to_expr messes with the goals? (see tests) set_goals gs, return [e] -- otherwise, look up everything tagged `@[congr]` | none := do congr_lemma_names ← attribute.get_instances `congr, congr_lemma_names.mmap mk_const end, -- For every lemma: congr_lemmas.any_of (λ n, -- Call tactic.eapply seq' (tactic.eapply n >> tactic.skip) -- and then call `intros` on each resulting goal, and require that afterwards it's an equation. (tactic.intros >> (do `(_ = _) ← target, tactic.skip))) add_tactic_doc { name := "apply_congr", category := doc_category.tactic, decl_names := [`conv.interactive.apply_congr], tags := ["conv", "congruence", "rewriting"] } end conv.interactive
c886528d5f67937f3839a79bca77559ad7125bae
ea5678cc400c34ff95b661fa26d15024e27ea8cd
/prob.lean
1cb003902773ae74de4e01fcd71184028491c661
[]
no_license
ChrisHughes24/leanstuff
dca0b5349c3ed893e8792ffbd98cbcadaff20411
9efa85f72efaccd1d540385952a6acc18fce8687
refs/heads/master
1,654,883,241,759
1,652,873,885,000
1,652,873,885,000
134,599,537
1
0
null
null
null
null
UTF-8
Lean
false
false
2,242
lean
import data.real.basic tactic.find variables {Ω : Type*} {α : Type*} open set local attribute [instance] classical.prop_decidable noncomputable theory lemma union_diff_eq_union (s t : set α) : s ∪ (t \ s) = s ∪ t := set.ext $ λ x, or.by_cases (classical.em (x ∈ s)) (λ h, by simp [h]) (λ h, by simp [h]) @[simp] lemma diff_disjoint (s t : set α) : disjoint (s \ t) t := show (s ∩ -t) ∩ t = ∅, from (inter_assoc s (-t) t).symm ▸ (compl_inter_self t).symm ▸ inter_empty s @[simp] lemma disjoint_diff (s t : set α) : disjoint s (t \ s) := disjoint_symm (diff_disjoint _ _) variables [iα : discrete_linear_ordered_field α] (P : set Ω → α) include iα class prob : Prop := (prob_nonneg : ∀ E : set Ω, 0 ≤ P E) (prob_univ : P univ = 1) (prob_add : ∀ {E₁ E₂ : set Ω}, disjoint E₁ E₂ → P (E₁ ∪ E₂) = P E₁ + P E₂) attribute [simp] prob.prob_univ namespace prob variables [hP : prob P] include hP @[simp] lemma union_compl_self (E : set Ω) : P (E ∪ -E) = 1 := eq.symm (set.union_compl_self E) ▸ prob_univ _ @[simp] lemma compl_union_self (E : set Ω) : P (-E ∪ E) = 1 := (set.compl_union_self E).symm ▸ prob_univ _ lemma subset_le {E₁ E₂ : set Ω} (h : E₁ ⊆ E₂) : P E₁ ≤ P E₂ := union_diff_cancel h ▸ (prob_add P (disjoint_diff E₁ E₂)).symm ▸ le_add_of_nonneg_right (prob_nonneg _ _) lemma le_union_left (E₁ E₂ : set Ω) : P E₁ ≤ P (E₁ ∪ E₂) := subset_le P (subset_union_left _ _) lemma le_union_right (E₁ E₂ : set Ω) : P E₂ ≤ P (E₁ ∪ E₂) := subset_le P (subset_union_right _ _) lemma le_one (E : set Ω) : P E ≤ 1 := prob_univ P ▸ subset_le P (subset_univ _) lemma inter_le_left (E₁ E₂ : set Ω) : P (E₁ ∩ E₂) ≤ P E₁ := subset_le P (inter_subset_left _ _) lemma inter_le_right (E₁ E₂ : set Ω) : P (E₁ ∩ E₂) ≤ P E₂ := subset_le P (inter_subset_right _ _) @[simp] lemma empty : P ∅ = 0 := have h : P (univ ∪ ∅) = P univ + P ∅ := prob_add P (inter_empty univ), by rwa [union_empty, prob_univ P, ← add_zero (1 : α), add_assoc, add_left_cancel_iff, zero_add, eq_comm] at h def given (E₁ E₂ : set Ω) := P (E₁ ∩ E₂) / P E₂ #print mul_comm end
b34795c0cb17e41a9cca6e7d4dad88ea448da9c9
6dc0c8ce7a76229dd81e73ed4474f15f88a9e294
/stage0/src/Lean/Elab/Declaration.lean
d0aeabf782a343046c232ab89a43f58da002b277
[ "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
11,804
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.Util.CollectLevelParams import Lean.Elab.DeclUtil import Lean.Elab.DefView import Lean.Elab.Inductive import Lean.Elab.Structure import Lean.Elab.MutualDef import Lean.Elab.DeclarationRange namespace Lean.Elab.Command open Meta /- Auxiliary function for `expandDeclNamespace?` -/ def expandDeclIdNamespace? (declId : Syntax) : Option (Name × Syntax) := let (id, optUnivDeclStx) := expandDeclIdCore declId let scpView := extractMacroScopes id match scpView.name with | Name.str Name.anonymous s _ => none | Name.str pre s _ => let nameNew := { scpView with name := Name.mkSimple s }.review if declId.isIdent then some (pre, mkIdentFrom declId nameNew) else some (pre, declId.setArg 0 (mkIdentFrom declId nameNew)) | _ => none /- given declarations such as `@[...] def Foo.Bla.f ...` return `some (Foo.Bla, @[...] def f ...)` -/ def expandDeclNamespace? (stx : Syntax) : Option (Name × Syntax) := if !stx.isOfKind `Lean.Parser.Command.declaration then none else let decl := stx[1] let k := decl.getKind if k == `Lean.Parser.Command.abbrev || k == `Lean.Parser.Command.def || k == `Lean.Parser.Command.theorem || k == `Lean.Parser.Command.constant || k == `Lean.Parser.Command.axiom || k == `Lean.Parser.Command.inductive || k == `Lean.Parser.Command.classInductive || k == `Lean.Parser.Command.structure then match expandDeclIdNamespace? decl[1] with | some (ns, declId) => some (ns, stx.setArg 1 (decl.setArg 1 declId)) | none => none else if k == `Lean.Parser.Command.instance then let optDeclId := decl[3] if optDeclId.isNone then none else match expandDeclIdNamespace? optDeclId[0] with | some (ns, declId) => some (ns, stx.setArg 1 (decl.setArg 3 (optDeclId.setArg 0 declId))) | none => none else none def elabAxiom (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do -- parser! "axiom " >> declId >> declSig let declId := stx[1] let (binders, typeStx) := expandDeclSig stx[2] let scopeLevelNames ← getLevelNames let ⟨name, declName, allUserLevelNames⟩ ← expandDeclId declId modifiers addDeclarationRanges declName stx runTermElabM declName fun vars => Term.withLevelNames allUserLevelNames $ Term.elabBinders binders.getArgs fun xs => do Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.beforeElaboration let type ← Term.elabType typeStx Term.synthesizeSyntheticMVarsNoPostponing let type ← instantiateMVars type let type ← mkForallFVars xs type let type ← mkForallFVars vars type (usedOnly := true) let (type, _) ← Term.levelMVarToParam type let usedParams := collectLevelParams {} type |>.params match sortDeclLevelParams scopeLevelNames allUserLevelNames usedParams with | Except.error msg => throwErrorAt stx msg | Except.ok levelParams => let decl := Declaration.axiomDecl { name := declName, levelParams := levelParams, type := type, isUnsafe := modifiers.isUnsafe } Term.ensureNoUnassignedMVars decl addDecl decl Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterTypeChecking if isExtern (← getEnv) declName then compileDecl decl Term.applyAttributesAt declName modifiers.attrs AttributeApplicationTime.afterCompilation /- parser! "inductive " >> declId >> optDeclSig >> optional ":=" >> many ctor parser! atomic (group ("class " >> "inductive ")) >> declId >> optDeclSig >> optional ":=" >> many ctor >> optDeriving -/ private def inductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) : CommandElabM InductiveView := do checkValidInductiveModifier modifiers let (binders, type?) := expandOptDeclSig decl[2] let declId := decl[1] let ⟨name, declName, levelNames⟩ ← expandDeclId declId modifiers addDeclarationRanges declName decl let ctors ← decl[4].getArgs.mapM fun ctor => withRef ctor do -- def ctor := parser! " | " >> declModifiers >> ident >> optional inferMod >> optDeclSig let ctorModifiers ← elabModifiers ctor[1] if ctorModifiers.isPrivate && modifiers.isPrivate then throwError "invalid 'private' constructor in a 'private' inductive datatype" if ctorModifiers.isProtected && modifiers.isPrivate then throwError "invalid 'protected' constructor in a 'private' inductive datatype" checkValidCtorModifier ctorModifiers let ctorName := ctor.getIdAt 2 let ctorName := declName ++ ctorName let ctorName ← withRef ctor[2] $ applyVisibility ctorModifiers.visibility ctorName let inferMod := !ctor[3].isNone let (binders, type?) := expandOptDeclSig ctor[4] addDocString' ctorName ctorModifiers.docString? addAuxDeclarationRanges ctorName ctor ctor[2] pure { ref := ctor, modifiers := ctorModifiers, declName := ctorName, inferMod := inferMod, binders := binders, type? := type? : CtorView } let classes ← getOptDerivingClasses decl[5] pure { ref := decl modifiers := modifiers shortDeclName := name declName := declName levelNames := levelNames binders := binders type? := type? ctors := ctors derivingClasses := classes } private def classInductiveSyntaxToView (modifiers : Modifiers) (decl : Syntax) : CommandElabM InductiveView := inductiveSyntaxToView modifiers decl def elabInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do let v ← inductiveSyntaxToView modifiers stx elabInductiveViews #[v] def elabClassInductive (modifiers : Modifiers) (stx : Syntax) : CommandElabM Unit := do let modifiers := modifiers.addAttribute { name := `class } let v ← classInductiveSyntaxToView modifiers stx elabInductiveViews #[v] @[builtinCommandElab declaration] def elabDeclaration : CommandElab := fun stx => match expandDeclNamespace? stx with | some (ns, newStx) => do let ns := mkIdentFrom stx ns let newStx ← `(namespace $ns:ident $newStx end $ns:ident) withMacroExpansion stx newStx $ elabCommand newStx | none => do let modifiers ← elabModifiers stx[0] let decl := stx[1] let declKind := decl.getKind if declKind == `Lean.Parser.Command.«axiom» then elabAxiom modifiers decl else if declKind == `Lean.Parser.Command.«inductive» then elabInductive modifiers decl else if declKind == `Lean.Parser.Command.classInductive then elabClassInductive modifiers decl else if declKind == `Lean.Parser.Command.«structure» then elabStructure modifiers decl else if isDefLike decl then elabMutualDef #[stx] else throwError "unexpected declaration" /- Return true if all elements of the mutual-block are inductive declarations. -/ private def isMutualInductive (stx : Syntax) : Bool := stx[1].getArgs.all fun elem => let decl := elem[1] let declKind := decl.getKind declKind == `Lean.Parser.Command.inductive private def elabMutualInductive (elems : Array Syntax) : CommandElabM Unit := do let views ← elems.mapM fun stx => do let modifiers ← elabModifiers stx[0] inductiveSyntaxToView modifiers stx[1] elabInductiveViews views /- Return true if all elements of the mutual-block are definitions/theorems/abbrevs. -/ private def isMutualDef (stx : Syntax) : Bool := stx[1].getArgs.all fun elem => let decl := elem[1] isDefLike decl private def isMutualPreambleCommand (stx : Syntax) : Bool := let k := stx.getKind k == `Lean.Parser.Command.variable || k == `Lean.Parser.Command.variables || k == `Lean.Parser.Command.universe || k == `Lean.Parser.Command.universes || k == `Lean.Parser.Command.check || k == `Lean.Parser.Command.set_option || k == `Lean.Parser.Command.open private partial def splitMutualPreamble (elems : Array Syntax) : Option (Array Syntax × Array Syntax) := let rec loop (i : Nat) : Option (Array Syntax × Array Syntax) := if h : i < elems.size then let elem := elems.get ⟨i, h⟩ if isMutualPreambleCommand elem then loop (i+1) else if i == 0 then none -- `mutual` block does not contain any preamble commands else some (elems[0:i], elems[i:elems.size]) else none -- a `mutual` block containing only preamble commands is not a valid `mutual` block loop 0 @[builtinMacro Lean.Parser.Command.mutual] def expandMutualNamespace : Macro := fun stx => do let mut ns? := none let mut elemsNew := #[] for elem in stx[1].getArgs do match ns?, expandDeclNamespace? elem with | _, none => elemsNew := elemsNew.push elem | none, some (ns, elem) => ns? := some ns; elemsNew := elemsNew.push elem | some nsCurr, some (nsNew, elem) => if nsCurr == nsNew then elemsNew := elemsNew.push elem else Macro.throwErrorAt elem s!"conflicting namespaces in mutual declaration, using namespace '{nsNew}', but used '{nsCurr}' in previous declaration" match ns? with | some ns => let ns := mkIdentFrom stx ns let stxNew := stx.setArg 1 (mkNullNode elemsNew) `(namespace $ns:ident $stxNew end $ns:ident) | none => Macro.throwUnsupported @[builtinMacro Lean.Parser.Command.mutual] def expandMutualElement : Macro := fun stx => do let mut elemsNew := #[] let mut modified := false for elem in stx[1].getArgs do match (← expandMacro? elem) with | some elemNew => elemsNew := elemsNew.push elemNew; modified := true | none => elemsNew := elemsNew.push elem if modified then pure $ stx.setArg 1 (mkNullNode elemsNew) else Macro.throwUnsupported @[builtinMacro Lean.Parser.Command.mutual] def expandMutualPreamble : Macro := fun stx => match splitMutualPreamble stx[1].getArgs with | none => Macro.throwUnsupported | some (preamble, rest) => do let secCmd ← `(section) let newMutual := stx.setArg 1 (mkNullNode rest) let endCmd ← `(end) pure $ mkNullNode (#[secCmd] ++ preamble ++ #[newMutual] ++ #[endCmd]) @[builtinCommandElab «mutual»] def elabMutual : CommandElab := fun stx => do if isMutualInductive stx then elabMutualInductive stx[1].getArgs else if isMutualDef stx then elabMutualDef stx[1].getArgs else throwError "invalid mutual block" /- parser! "attribute " >> "[" >> sepBy1 Term.attrInstance ", " >> "]" >> many1 ident -/ @[builtinCommandElab «attribute»] def elabAttr : CommandElab := fun stx => do let attrs ← elabAttrs stx[2] let idents := stx[4].getArgs for ident in idents do withRef ident $ liftTermElabM none do let declName ← resolveGlobalConstNoOverload ident.getId Term.applyAttributes declName attrs def expandInitCmd (builtin : Bool) : Macro := fun stx => let optHeader := stx[1] let doSeq := stx[2] let attrId := mkIdentFrom stx $ if builtin then `builtinInit else `init if optHeader.isNone then `(@[$attrId:ident]def initFn : IO Unit := do $doSeq) else let id := optHeader[0] let type := optHeader[1][1] `(def initFn : IO $type := do $doSeq @[$attrId:ident initFn]constant $id : $type) @[builtinMacro Lean.Parser.Command.«initialize»] def expandInitialize : Macro := expandInitCmd (builtin := false) @[builtinMacro Lean.Parser.Command.«builtin_initialize»] def expandBuiltinInitialize : Macro := expandInitCmd (builtin := true) end Lean.Elab.Command
1e302262dc72e0957966d5fdab556b1b9ac2b821
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/field_theory/normal.lean
096d58cb1702f794ccb162e24207fde654e0fa51
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
15,329
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Thomas Browning, Patrick Lutz -/ import field_theory.adjoin import field_theory.tower import group_theory.solvable import ring_theory.power_basis /-! # Normal field extensions In this file we define normal field extensions and prove that for a finite extension, being normal is the same as being a splitting field (`normal.of_is_splitting_field` and `normal.exists_is_splitting_field`). ## Main Definitions - `normal F K` where `K` is a field extension of `F`. -/ noncomputable theory open_locale big_operators open_locale classical open polynomial is_scalar_tower variables (F K : Type*) [field F] [field K] [algebra F K] --TODO(Commelin): refactor normal to extend `is_algebraic`?? /-- Typeclass for normal field extension: `K` is a normal extension of `F` iff the minimal polynomial of every element `x` in `K` splits in `K`, i.e. every conjugate of `x` is in `K`. -/ class normal : Prop := (is_integral' (x : K) : is_integral F x) (splits' (x : K) : splits (algebra_map F K) (minpoly F x)) variables {F K} theorem normal.is_integral (h : normal F K) (x : K) : is_integral F x := normal.is_integral' x theorem normal.splits (h : normal F K) (x : K) : splits (algebra_map F K) (minpoly F x) := normal.splits' x theorem normal_iff : normal F K ↔ ∀ x : K, is_integral F x ∧ splits (algebra_map F K) (minpoly F x) := ⟨λ h x, ⟨h.is_integral x, h.splits x⟩, λ h, ⟨λ x, (h x).1, λ x, (h x).2⟩⟩ theorem normal.out : normal F K → ∀ x : K, is_integral F x ∧ splits (algebra_map F K) (minpoly F x) := normal_iff.1 variables (F K) instance normal_self : normal F F := ⟨λ x, is_integral_algebra_map, λ x, by { rw minpoly.eq_X_sub_C', exact splits_X_sub_C _ }⟩ variables {K} variables (K) theorem normal.exists_is_splitting_field [h : normal F K] [finite_dimensional F K] : ∃ p : polynomial F, is_splitting_field F K p := begin let s := basis.of_vector_space F K, refine ⟨∏ x, minpoly F (s x), splits_prod _ $ λ x hx, h.splits (s x), subalgebra.to_submodule_injective _⟩, rw [algebra.top_to_submodule, eq_top_iff, ← s.span_eq, submodule.span_le, set.range_subset_iff], refine λ x, algebra.subset_adjoin (multiset.mem_to_finset.mpr $ (mem_roots $ mt (map_eq_zero $ algebra_map F K).1 $ finset.prod_ne_zero_iff.2 $ λ x hx, _).2 _), { exact minpoly.ne_zero (h.is_integral (s x)) }, rw [is_root.def, eval_map, ← aeval_def, alg_hom.map_prod], exact finset.prod_eq_zero (finset.mem_univ _) (minpoly.aeval _ _) end section normal_tower variables (E : Type*) [field E] [algebra F E] [algebra K E] [is_scalar_tower F K E] lemma normal.tower_top_of_normal [h : normal F E] : normal K E := normal_iff.2 $ λ x, begin cases h.out x with hx hhx, rw algebra_map_eq F K E at hhx, exact ⟨is_integral_of_is_scalar_tower x hx, polynomial.splits_of_splits_of_dvd (algebra_map K E) (polynomial.map_ne_zero (minpoly.ne_zero hx)) ((polynomial.splits_map_iff (algebra_map F K) (algebra_map K E)).mpr hhx) (minpoly.dvd_map_of_is_scalar_tower F K x)⟩, end lemma alg_hom.normal_bijective [h : normal F E] (ϕ : E →ₐ[F] K) : function.bijective ϕ := ⟨ϕ.to_ring_hom.injective, λ x, by { letI : algebra E K := ϕ.to_ring_hom.to_algebra, obtain ⟨h1, h2⟩ := h.out (algebra_map K E x), cases minpoly.mem_range_of_degree_eq_one E x (or.resolve_left h2 (minpoly.ne_zero h1) (minpoly.irreducible (is_integral_of_is_scalar_tower x ((is_integral_algebra_map_iff (algebra_map K E).injective).mp h1))) (minpoly.dvd E x ((algebra_map K E).injective (by { rw [ring_hom.map_zero, aeval_map, ←is_scalar_tower.to_alg_hom_apply F K E, ←alg_hom.comp_apply, ←aeval_alg_hom], exact minpoly.aeval F (algebra_map K E x) })))) with y hy, exact ⟨y, hy⟩ }⟩ variables {F} {E} {E' : Type*} [field E'] [algebra F E'] lemma normal.of_alg_equiv [h : normal F E] (f : E ≃ₐ[F] E') : normal F E' := normal_iff.2 $ λ x, begin cases h.out (f.symm x) with hx hhx, have H := is_integral_alg_hom f.to_alg_hom hx, rw [alg_equiv.to_alg_hom_eq_coe, alg_equiv.coe_alg_hom, alg_equiv.apply_symm_apply] at H, use H, apply polynomial.splits_of_splits_of_dvd (algebra_map F E') (minpoly.ne_zero hx), { rw ← alg_hom.comp_algebra_map f.to_alg_hom, exact polynomial.splits_comp_of_splits (algebra_map F E) f.to_alg_hom.to_ring_hom hhx }, { apply minpoly.dvd _ _, rw ← add_equiv.map_eq_zero_iff f.symm.to_add_equiv, exact eq.trans (polynomial.aeval_alg_hom_apply f.symm.to_alg_hom x (minpoly F (f.symm x))).symm (minpoly.aeval _ _) }, end lemma alg_equiv.transfer_normal (f : E ≃ₐ[F] E') : normal F E ↔ normal F E' := ⟨λ h, by exactI normal.of_alg_equiv f, λ h, by exactI normal.of_alg_equiv f.symm⟩ lemma normal.of_is_splitting_field (p : polynomial F) [hFEp : is_splitting_field F E p] : normal F E := begin by_cases hp : p = 0, { haveI : is_splitting_field F F p, { rw hp, exact ⟨splits_zero _, subsingleton.elim _ _⟩ }, exactI (alg_equiv.transfer_normal ((is_splitting_field.alg_equiv F p).trans (is_splitting_field.alg_equiv E p).symm)).mp (normal_self F) }, refine normal_iff.2 (λ x, _), haveI hFE : finite_dimensional F E := is_splitting_field.finite_dimensional E p, have Hx : is_integral F x := is_integral_of_noetherian hFE x, refine ⟨Hx, or.inr _⟩, rintros q q_irred ⟨r, hr⟩, let D := adjoin_root q, let pbED := adjoin_root.power_basis q_irred.ne_zero, haveI : finite_dimensional E D := power_basis.finite_dimensional pbED, have finrankED : finite_dimensional.finrank E D = q.nat_degree := power_basis.finrank pbED, letI : algebra F D := ring_hom.to_algebra ((algebra_map E D).comp (algebra_map F E)), haveI : is_scalar_tower F E D := of_algebra_map_eq (λ _, rfl), haveI : finite_dimensional F D := finite_dimensional.trans F E D, suffices : nonempty (D →ₐ[F] E), { cases this with ϕ, rw [←with_bot.coe_one, degree_eq_iff_nat_degree_eq q_irred.ne_zero, ←finrankED], have nat_lemma : ∀ a b c : ℕ, a * b = c → c ≤ a → 0 < c → b = 1, { intros a b c h1 h2 h3, nlinarith }, exact nat_lemma _ _ _ (finite_dimensional.finrank_mul_finrank F E D) (linear_map.finrank_le_finrank_of_injective (show function.injective ϕ.to_linear_map, from ϕ.to_ring_hom.injective)) finite_dimensional.finrank_pos, }, let C := adjoin_root (minpoly F x), have Hx_irred := minpoly.irreducible Hx, letI : algebra C D := ring_hom.to_algebra (adjoin_root.lift (algebra_map F D) (adjoin_root.root q) (by rw [algebra_map_eq F E D, ←eval₂_map, hr, adjoin_root.algebra_map_eq, eval₂_mul, adjoin_root.eval₂_root, zero_mul])), letI : algebra C E := ring_hom.to_algebra (adjoin_root.lift (algebra_map F E) x (minpoly.aeval F x)), haveI : is_scalar_tower F C D := of_algebra_map_eq (λ x, adjoin_root.lift_of.symm), haveI : is_scalar_tower F C E := of_algebra_map_eq (λ x, adjoin_root.lift_of.symm), suffices : nonempty (D →ₐ[C] E), { exact nonempty.map (alg_hom.restrict_scalars F) this }, let S : set D := ((p.map (algebra_map F E)).roots.map (algebra_map E D)).to_finset, suffices : ⊤ ≤ intermediate_field.adjoin C S, { refine intermediate_field.alg_hom_mk_adjoin_splits' (top_le_iff.mp this) (λ y hy, _), rcases multiset.mem_map.mp (multiset.mem_to_finset.mp hy) with ⟨z, hz1, hz2⟩, have Hz : is_integral F z := is_integral_of_noetherian hFE z, use (show is_integral C y, from is_integral_of_noetherian (finite_dimensional.right F C D) y), apply splits_of_splits_of_dvd (algebra_map C E) (map_ne_zero (minpoly.ne_zero Hz)), { rw [splits_map_iff, ←algebra_map_eq F C E], exact splits_of_splits_of_dvd _ hp hFEp.splits (minpoly.dvd F z (eq.trans (eval₂_eq_eval_map _) ((mem_roots (map_ne_zero hp)).mp hz1))) }, { apply minpoly.dvd, rw [←hz2, aeval_def, eval₂_map, ←algebra_map_eq F C D, algebra_map_eq F E D, ←hom_eval₂, ←aeval_def, minpoly.aeval F z, ring_hom.map_zero] } }, rw [←intermediate_field.to_subalgebra_le_to_subalgebra, intermediate_field.top_to_subalgebra], apply ge_trans (intermediate_field.algebra_adjoin_le_adjoin C S), suffices : (algebra.adjoin C S).restrict_scalars F = (algebra.adjoin E {adjoin_root.root q}).restrict_scalars F, { rw [adjoin_root.adjoin_root_eq_top, subalgebra.restrict_scalars_top, ←@subalgebra.restrict_scalars_top F C] at this, exact top_le_iff.mpr (subalgebra.restrict_scalars_injective F this) }, dsimp only [S], rw [←finset.image_to_finset, finset.coe_image], apply eq.trans (algebra.adjoin_res_eq_adjoin_res F E C D hFEp.adjoin_roots adjoin_root.adjoin_root_eq_top), rw [set.image_singleton, ring_hom.algebra_map_to_algebra, adjoin_root.lift_root] end instance (p : polynomial F) : normal F p.splitting_field := normal.of_is_splitting_field p end normal_tower variables {F} {K} (ϕ ψ : K →ₐ[F] K) (χ ω : K ≃ₐ[F] K) section restrict variables (E : Type*) [field E] [algebra F E] [algebra E K] [is_scalar_tower F E K] /-- Restrict algebra homomorphism to image of normal subfield -/ def alg_hom.restrict_normal_aux [h : normal F E] : (to_alg_hom F E K).range →ₐ[F] (to_alg_hom F E K).range := { to_fun := λ x, ⟨ϕ x, by { suffices : (to_alg_hom F E K).range.map ϕ ≤ _, { exact this ⟨x, subtype.mem x, rfl⟩ }, rintros x ⟨y, ⟨z, hy⟩, hx⟩, rw [←hx, ←hy], apply minpoly.mem_range_of_degree_eq_one E, exact or.resolve_left (h.splits z) (minpoly.ne_zero (h.is_integral z)) (minpoly.irreducible $ is_integral_of_is_scalar_tower _ $ is_integral_alg_hom ϕ $ is_integral_alg_hom _ $ h.is_integral z) (minpoly.dvd E _ $ by rw [aeval_map, aeval_alg_hom, aeval_alg_hom, alg_hom.comp_apply, alg_hom.comp_apply, minpoly.aeval, alg_hom.map_zero, alg_hom.map_zero]) }⟩, map_zero' := subtype.ext ϕ.map_zero, map_one' := subtype.ext ϕ.map_one, map_add' := λ x y, subtype.ext (ϕ.map_add x y), map_mul' := λ x y, subtype.ext (ϕ.map_mul x y), commutes' := λ x, subtype.ext (ϕ.commutes x) } /-- Restrict algebra homomorphism to normal subfield -/ def alg_hom.restrict_normal [normal F E] : E →ₐ[F] E := ((alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F E K)).symm.to_alg_hom.comp (ϕ.restrict_normal_aux E)).comp (alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F E K)).to_alg_hom @[simp] lemma alg_hom.restrict_normal_commutes [normal F E] (x : E) : algebra_map E K (ϕ.restrict_normal E x) = ϕ (algebra_map E K x) := subtype.ext_iff.mp (alg_equiv.apply_symm_apply (alg_equiv.of_injective_field (is_scalar_tower.to_alg_hom F E K)) (ϕ.restrict_normal_aux E ⟨is_scalar_tower.to_alg_hom F E K x, x, rfl⟩)) lemma alg_hom.restrict_normal_comp [normal F E] : (ϕ.restrict_normal E).comp (ψ.restrict_normal E) = (ϕ.comp ψ).restrict_normal E := alg_hom.ext (λ _, (algebra_map E K).injective (by simp only [alg_hom.comp_apply, alg_hom.restrict_normal_commutes])) /-- Restrict algebra isomorphism to a normal subfield -/ def alg_equiv.restrict_normal [h : normal F E] : E ≃ₐ[F] E := alg_equiv.of_bijective (χ.to_alg_hom.restrict_normal E) (alg_hom.normal_bijective F E E _) @[simp] lemma alg_equiv.restrict_normal_commutes [normal F E] (x : E) : algebra_map E K (χ.restrict_normal E x) = χ (algebra_map E K x) := χ.to_alg_hom.restrict_normal_commutes E x lemma alg_equiv.restrict_normal_trans [normal F E] : (χ.trans ω).restrict_normal E = (χ.restrict_normal E).trans (ω.restrict_normal E) := alg_equiv.ext (λ _, (algebra_map E K).injective (by simp only [alg_equiv.trans_apply, alg_equiv.restrict_normal_commutes])) /-- Restriction to an normal subfield as a group homomorphism -/ def alg_equiv.restrict_normal_hom [normal F E] : (K ≃ₐ[F] K) →* (E ≃ₐ[F] E) := monoid_hom.mk' (λ χ, χ.restrict_normal E) (λ ω χ, (χ.restrict_normal_trans ω E)) end restrict section lift variables {F} {K} (E : Type*) [field E] [algebra F E] [algebra K E] [is_scalar_tower F K E] /-- If `E/K/F` is a tower of fields with `E/F` normal then we can lift an algebra homomorphism `ϕ : K →ₐ[F] K` to `ϕ.lift_normal E : E →ₐ[F] E`. -/ noncomputable def alg_hom.lift_normal [h : normal F E] : E →ₐ[F] E := @alg_hom.restrict_scalars F K E E _ _ _ _ _ _ ((is_scalar_tower.to_alg_hom F K E).comp ϕ).to_ring_hom.to_algebra _ _ _ _ (nonempty.some (@intermediate_field.alg_hom_mk_adjoin_splits' K E E _ _ _ _ ((is_scalar_tower.to_alg_hom F K E).comp ϕ).to_ring_hom.to_algebra ⊤ rfl (λ x hx, ⟨is_integral_of_is_scalar_tower x (h.out x).1, splits_of_splits_of_dvd _ (map_ne_zero (minpoly.ne_zero (h.out x).1)) (by { rw [splits_map_iff, ←is_scalar_tower.algebra_map_eq], exact (h.out x).2 }) (minpoly.dvd_map_of_is_scalar_tower F K x)⟩))) @[simp] lemma alg_hom.lift_normal_commutes [normal F E] (x : K) : ϕ.lift_normal E (algebra_map K E x) = algebra_map K E (ϕ x) := @alg_hom.commutes K E E _ _ _ _ ((is_scalar_tower.to_alg_hom F K E).comp ϕ).to_ring_hom.to_algebra _ x @[simp] lemma alg_hom.restrict_lift_normal [normal F K] [normal F E] : (ϕ.lift_normal E).restrict_normal K = ϕ := alg_hom.ext (λ x, (algebra_map K E).injective (eq.trans (alg_hom.restrict_normal_commutes _ K x) (ϕ.lift_normal_commutes E x))) /-- If `E/K/F` is a tower of fields with `E/F` normal then we can lift an algebra isomorphism `ϕ : K ≃ₐ[F] K` to `ϕ.lift_normal E : E ≃ₐ[F] E`. -/ noncomputable def alg_equiv.lift_normal [normal F E] : E ≃ₐ[F] E := alg_equiv.of_bijective (χ.to_alg_hom.lift_normal E) (alg_hom.normal_bijective F E E _) @[simp] lemma alg_equiv.lift_normal_commutes [normal F E] (x : K) : χ.lift_normal E (algebra_map K E x) = algebra_map K E (χ x) := χ.to_alg_hom.lift_normal_commutes E x @[simp] lemma alg_equiv.restrict_lift_normal [normal F K] [normal F E] : (χ.lift_normal E).restrict_normal K = χ := alg_equiv.ext (λ x, (algebra_map K E).injective (eq.trans (alg_equiv.restrict_normal_commutes _ K x) (χ.lift_normal_commutes E x))) lemma alg_equiv.restrict_normal_hom_surjective [normal F K] [normal F E] : function.surjective (alg_equiv.restrict_normal_hom K : (E ≃ₐ[F] E) → (K ≃ₐ[F] K)) := λ χ, ⟨χ.lift_normal E, χ.restrict_lift_normal E⟩ variables (F) (K) (E) lemma is_solvable_of_is_scalar_tower [normal F K] [h1 : is_solvable (K ≃ₐ[F] K)] [h2 : is_solvable (E ≃ₐ[K] E)] : is_solvable (E ≃ₐ[F] E) := begin let f : (E ≃ₐ[K] E) →* (E ≃ₐ[F] E) := { to_fun := λ ϕ, alg_equiv.of_alg_hom (ϕ.to_alg_hom.restrict_scalars F) (ϕ.symm.to_alg_hom.restrict_scalars F) (alg_hom.ext (λ x, ϕ.apply_symm_apply x)) (alg_hom.ext (λ x, ϕ.symm_apply_apply x)), map_one' := alg_equiv.ext (λ _, rfl), map_mul' := λ _ _, alg_equiv.ext (λ _, rfl) }, refine solvable_of_ker_le_range f (alg_equiv.restrict_normal_hom K) (λ ϕ hϕ, ⟨{commutes' := λ x, _, .. ϕ}, alg_equiv.ext (λ _, rfl)⟩), exact (eq.trans (ϕ.restrict_normal_commutes K x).symm (congr_arg _ (alg_equiv.ext_iff.mp hϕ x))), end end lift
cedb8db9bb27eeb376dd80eff807c1e2336694c6
b3fced0f3ff82d577384fe81653e47df68bb2fa1
/src/category_theory/isomorphism.lean
d160959c50bb37124f26234e795e6468406595ce
[ "Apache-2.0" ]
permissive
ratmice/mathlib
93b251ef5df08b6fd55074650ff47fdcc41a4c75
3a948a6a4cd5968d60e15ed914b1ad2f4423af8d
refs/heads/master
1,599,240,104,318
1,572,981,183,000
1,572,981,183,000
219,830,178
0
0
Apache-2.0
1,572,980,897,000
1,572,980,896,000
null
UTF-8
Lean
false
false
10,405
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Tim Baumann, Stephen Morgan, Scott Morrison, Floris van Doorn -/ import category_theory.functor import tactic.reassoc_axiom /-! # Isomorphisms This file defines isomorphisms between objects of a category. ## Main definitions - `structure iso` : a bundled isomorphism between two objects of a category; - `class is_iso` : an unbundled version of `iso`; note that `is_iso f` is usually *not* a `Prop`, because it holds the inverse morphism; - `as_iso` : convert from `is_iso` to `iso`; - `of_iso` : convert from `iso` to `is_iso`; - standard operations on isomorphisms (composition, inverse etc) ## Notations - `X ≅ Y` : same as `iso X Y`; - `α ≪≫ β` : composition of two isomorphisms; it is called `iso.trans` ## Tags category, category theory, isomorphism -/ universes v u -- declare the `v`'s first; see `category_theory.category` for an explanation namespace category_theory open category structure iso {C : Type u} [category.{v} C] (X Y : C) := (hom : X ⟶ Y) (inv : Y ⟶ X) (hom_inv_id' : hom ≫ inv = 𝟙 X . obviously) (inv_hom_id' : inv ≫ hom = 𝟙 Y . obviously) restate_axiom iso.hom_inv_id' restate_axiom iso.inv_hom_id' attribute [simp, reassoc] iso.hom_inv_id iso.inv_hom_id infixr ` ≅ `:10 := iso -- type as \cong or \iso variables {C : Type u} [𝒞 : category.{v} C] include 𝒞 variables {X Y Z : C} namespace iso @[extensionality] lemma ext ⦃α β : X ≅ Y⦄ (w : α.hom = β.hom) : α = β := suffices α.inv = β.inv, by cases α; cases β; cc, calc α.inv = α.inv ≫ (β.hom ≫ β.inv) : by rw [iso.hom_inv_id, category.comp_id] ... = (α.inv ≫ α.hom) ≫ β.inv : by rw [category.assoc, ←w] ... = β.inv : by rw [iso.inv_hom_id, category.id_comp] @[symm] def symm (I : X ≅ Y) : Y ≅ X := { hom := I.inv, inv := I.hom, hom_inv_id' := I.inv_hom_id', inv_hom_id' := I.hom_inv_id' } @[simp] lemma symm_hom (α : X ≅ Y) : α.symm.hom = α.inv := rfl @[simp] lemma symm_inv (α : X ≅ Y) : α.symm.inv = α.hom := rfl @[simp] lemma symm_mk {X Y : C} (hom : X ⟶ Y) (inv : Y ⟶ X) (hom_inv_id) (inv_hom_id) : iso.symm {hom := hom, inv := inv, hom_inv_id' := hom_inv_id, inv_hom_id' := inv_hom_id} = {hom := inv, inv := hom, hom_inv_id' := inv_hom_id, inv_hom_id' := hom_inv_id} := rfl @[simp] lemma symm_symm_eq {X Y : C} (α : X ≅ Y) : α.symm.symm = α := by cases α; refl @[simp] lemma symm_eq_iff {X Y : C} {α β : X ≅ Y} : α.symm = β.symm ↔ α = β := ⟨λ h, symm_symm_eq α ▸ symm_symm_eq β ▸ congr_arg symm h, congr_arg symm⟩ @[refl] def refl (X : C) : X ≅ X := { hom := 𝟙 X, inv := 𝟙 X } @[simp] lemma refl_hom (X : C) : (iso.refl X).hom = 𝟙 X := rfl @[simp] lemma refl_inv (X : C) : (iso.refl X).inv = 𝟙 X := rfl @[simp] lemma refl_symm (X : C) : (iso.refl X).symm = iso.refl X := rfl @[trans] def trans (α : X ≅ Y) (β : Y ≅ Z) : X ≅ Z := { hom := α.hom ≫ β.hom, inv := β.inv ≫ α.inv } infixr ` ≪≫ `:80 := iso.trans -- type as `\ll \gg`. @[simp] lemma trans_hom (α : X ≅ Y) (β : Y ≅ Z) : (α ≪≫ β).hom = α.hom ≫ β.hom := rfl @[simp] lemma trans_inv (α : X ≅ Y) (β : Y ≅ Z) : (α ≪≫ β).inv = β.inv ≫ α.inv := rfl @[simp] lemma trans_mk {X Y Z : C} (hom : X ⟶ Y) (inv : Y ⟶ X) (hom_inv_id) (inv_hom_id) (hom' : Y ⟶ Z) (inv' : Z ⟶ Y) (hom_inv_id') (inv_hom_id') (hom_inv_id'') (inv_hom_id'') : iso.trans {hom := hom, inv := inv, hom_inv_id' := hom_inv_id, inv_hom_id' := inv_hom_id} {hom := hom', inv := inv', hom_inv_id' := hom_inv_id', inv_hom_id' := inv_hom_id'} = {hom := hom ≫ hom', inv := inv' ≫ inv, hom_inv_id' := hom_inv_id'', inv_hom_id' := inv_hom_id''} := rfl @[simp] lemma trans_symm (α : X ≅ Y) (β : Y ≅ Z) : (α ≪≫ β).symm = β.symm ≪≫ α.symm := rfl @[simp] lemma trans_assoc {Z' : C} (α : X ≅ Y) (β : Y ≅ Z) (γ : Z ≅ Z') : (α ≪≫ β) ≪≫ γ = α ≪≫ β ≪≫ γ := by ext; simp only [trans_hom, category.assoc] @[simp] lemma refl_trans (α : X ≅ Y) : (iso.refl X) ≪≫ α = α := by ext; apply category.id_comp @[simp] lemma trans_refl (α : X ≅ Y) : α ≪≫ (iso.refl Y) = α := by ext; apply category.comp_id @[simp] lemma symm_self_id (α : X ≅ Y) : α.symm ≪≫ α = iso.refl Y := ext α.inv_hom_id @[simp] lemma self_symm_id (α : X ≅ Y) : α ≪≫ α.symm = iso.refl X := ext α.hom_inv_id @[simp] lemma symm_self_id_assoc (α : X ≅ Y) (β : Y ≅ Z) : α.symm ≪≫ α ≪≫ β = β := by rw [← trans_assoc, symm_self_id, refl_trans] @[simp] lemma self_symm_id_assoc (α : X ≅ Y) (β : X ≅ Z) : α ≪≫ α.symm ≪≫ β = β := by rw [← trans_assoc, self_symm_id, refl_trans] lemma inv_comp_eq (α : X ≅ Y) {f : X ⟶ Z} {g : Y ⟶ Z} : α.inv ≫ f = g ↔ f = α.hom ≫ g := ⟨λ H, by simp [H.symm], λ H, by simp [H]⟩ lemma eq_inv_comp (α : X ≅ Y) {f : X ⟶ Z} {g : Y ⟶ Z} : g = α.inv ≫ f ↔ α.hom ≫ g = f := (inv_comp_eq α.symm).symm lemma comp_inv_eq (α : X ≅ Y) {f : Z ⟶ Y} {g : Z ⟶ X} : f ≫ α.inv = g ↔ f = g ≫ α.hom := ⟨λ H, by simp [H.symm], λ H, by simp [H]⟩ lemma eq_comp_inv (α : X ≅ Y) {f : Z ⟶ Y} {g : Z ⟶ X} : g = f ≫ α.inv ↔ g ≫ α.hom = f := (comp_inv_eq α.symm).symm lemma inv_eq_inv (f g : X ≅ Y) : f.inv = g.inv ↔ f.hom = g.hom := have ∀{X Y : C} (f g : X ≅ Y), f.hom = g.hom → f.inv = g.inv, from λ X Y f g h, by rw [ext h], ⟨this f.symm g.symm, this f g⟩ lemma hom_comp_eq_id (α : X ≅ Y) {f : Y ⟶ X} : α.hom ≫ f = 𝟙 X ↔ f = α.inv := by rw [←eq_inv_comp, comp_id] lemma comp_hom_eq_id (α : X ≅ Y) {f : Y ⟶ X} : f ≫ α.hom = 𝟙 Y ↔ f = α.inv := by rw [←eq_comp_inv, id_comp] lemma hom_eq_inv (α : X ≅ Y) (β : Y ≅ X) : α.hom = β.inv ↔ β.hom = α.inv := by { erw [inv_eq_inv α.symm β, eq_comm], refl } end iso /-- `is_iso` typeclass expressing that a morphism is invertible. This contains the data of the inverse, but is a subsingleton type. -/ class is_iso (f : X ⟶ Y) := (inv : Y ⟶ X) (hom_inv_id' : f ≫ inv = 𝟙 X . obviously) (inv_hom_id' : inv ≫ f = 𝟙 Y . obviously) export is_iso (inv) def as_iso (f : X ⟶ Y) [h : is_iso f] : X ≅ Y := { hom := f, ..h } @[simp] lemma as_iso_hom (f : X ⟶ Y) [is_iso f] : (as_iso f).hom = f := rfl @[simp] lemma as_iso_inv (f : X ⟶ Y) [is_iso f] : (as_iso f).inv = inv f := rfl namespace is_iso @[simp] lemma hom_inv_id (f : X ⟶ Y) [is_iso f] : f ≫ inv f = 𝟙 X := is_iso.hom_inv_id' f @[simp] lemma inv_hom_id (f : X ⟶ Y) [is_iso f] : inv f ≫ f = 𝟙 Y := is_iso.inv_hom_id' f @[simp] lemma hom_inv_id_assoc {Z} (f : X ⟶ Y) [is_iso f] (g : X ⟶ Z) : f ≫ inv f ≫ g = g := (as_iso f).hom_inv_id_assoc g @[simp] lemma inv_hom_id_assoc {Z} (f : X ⟶ Y) [is_iso f] (g : Y ⟶ Z) : inv f ≫ f ≫ g = g := (as_iso f).inv_hom_id_assoc g instance (X : C) : is_iso (𝟙 X) := { inv := 𝟙 X } instance of_iso (f : X ≅ Y) : is_iso f.hom := { .. f } instance of_iso_inverse (f : X ≅ Y) : is_iso f.inv := is_iso.of_iso f.symm variables {f g : X ⟶ Y} {h : Y ⟶ Z} instance inv_is_iso [is_iso f] : is_iso (inv f) := is_iso.of_iso_inverse (as_iso f) instance comp_is_iso [is_iso f] [is_iso h] : is_iso (f ≫ h) := is_iso.of_iso $ (as_iso f) ≪≫ (as_iso h) @[simp] lemma inv_id : inv (𝟙 X) = 𝟙 X := rfl @[simp] lemma inv_comp [is_iso f] [is_iso h] : inv (f ≫ h) = inv h ≫ inv f := rfl @[simp] lemma inv_inv [is_iso f] : inv (inv f) = f := rfl @[simp] lemma iso.inv_inv (f : X ≅ Y) : inv (f.inv) = f.hom := rfl @[simp] lemma iso.inv_hom (f : X ≅ Y) : inv (f.hom) = f.inv := rfl instance epi_of_iso (f : X ⟶ Y) [is_iso f] : epi f := { left_cancellation := λ Z g h w, -- This is an interesting test case for better rewrite automation. by rw [← is_iso.inv_hom_id_assoc f g, w, is_iso.inv_hom_id_assoc f h] } instance mono_of_iso (f : X ⟶ Y) [is_iso f] : mono f := { right_cancellation := λ Z g h w, by rw [←category.comp_id C g, ←category.comp_id C h, ←is_iso.hom_inv_id f, ←category.assoc, w, ←category.assoc] } end is_iso open is_iso lemma eq_of_inv_eq_inv {f g : X ⟶ Y} [is_iso f] [is_iso g] (p : inv f = inv g) : f = g := begin apply (cancel_epi (inv f)).1, erw [inv_hom_id, p, inv_hom_id], end instance (f : X ⟶ Y) : subsingleton (is_iso f) := ⟨λ a b, suffices a.inv = b.inv, by cases a; cases b; congr; exact this, show (@as_iso C _ _ _ f a).inv = (@as_iso C _ _ _ f b).inv, by congr' 1; ext; refl⟩ lemma is_iso.inv_eq_inv {f g : X ⟶ Y} [is_iso f] [is_iso g] : inv f = inv g ↔ f = g := iso.inv_eq_inv (as_iso f) (as_iso g) namespace functor universes u₁ v₁ u₂ v₂ variables {D : Type u₂} variables [𝒟 : category.{v₂} D] include 𝒟 def map_iso (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : F.obj X ≅ F.obj Y := { hom := F.map i.hom, inv := F.map i.inv, hom_inv_id' := by rw [←map_comp, iso.hom_inv_id, ←map_id], inv_hom_id' := by rw [←map_comp, iso.inv_hom_id, ←map_id] } @[simp] lemma map_iso_hom (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : (F.map_iso i).hom = F.map i.hom := rfl @[simp] lemma map_iso_inv (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : (F.map_iso i).inv = F.map i.inv := rfl @[simp] lemma map_iso_symm (F : C ⥤ D) {X Y : C} (i : X ≅ Y) : F.map_iso i.symm = (F.map_iso i).symm := rfl @[simp] lemma map_iso_trans (F : C ⥤ D) {X Y Z : C} (i : X ≅ Y) (j : Y ≅ Z) : F.map_iso (i ≪≫ j) = (F.map_iso i) ≪≫ (F.map_iso j) := by ext; apply functor.map_comp @[simp] lemma map_iso_refl (F : C ⥤ D) (X : C) : F.map_iso (iso.refl X) = iso.refl (F.obj X) := iso.ext $ F.map_id X instance map_is_iso (F : C ⥤ D) (f : X ⟶ Y) [is_iso f] : is_iso (F.map f) := is_iso.of_iso $ F.map_iso (as_iso f) @[simp] lemma map_inv (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) [is_iso f] : F.map (inv f) = inv (F.map f) := rfl @[simp] lemma map_hom_inv (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) [is_iso f] : F.map f ≫ F.map (inv f) = 𝟙 (F.obj X) := by rw [map_inv, is_iso.hom_inv_id] @[simp] lemma map_inv_hom (F : C ⥤ D) {X Y : C} (f : X ⟶ Y) [is_iso f] : F.map (inv f) ≫ F.map f = 𝟙 (F.obj Y) := by rw [map_inv, is_iso.inv_hom_id] end functor end category_theory
5f69749d5b5b97520c25c07a19a3b85b51454c96
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/SyntheticMVars.lean
d0bb07faef3a1aec1a60ab84148160a2d2c0e9b4
[ "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
24,591
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.Meta.Tactic.Util import Lean.Util.ForEachExpr import Lean.Util.OccursCheck import Lean.Elab.Tactic.Basic namespace Lean.Elab.Term open Tactic (TacticM evalTactic getUnsolvedGoals withTacticInfoContext) open Meta /-- Auxiliary function used to implement `synthesizeSyntheticMVars`. -/ private def resumeElabTerm (stx : Syntax) (expectedType? : Option Expr) (errToSorry := true) : TermElabM Expr := -- Remark: if `ctx.errToSorry` is already false, then we don't enable it. Recall tactics disable `errToSorry` withReader (fun ctx => { ctx with errToSorry := ctx.errToSorry && errToSorry }) do elabTerm stx expectedType? false /-- Try to elaborate `stx` that was postponed by an elaboration method using `Expection.postpone`. It returns `true` if it succeeded, and `false` otherwise. It is used to implement `synthesizeSyntheticMVars`. -/ private def resumePostponed (savedContext : SavedContext) (stx : Syntax) (mvarId : MVarId) (postponeOnError : Bool) : TermElabM Bool := withRef stx <| mvarId.withContext do let s ← saveState try withSavedContext savedContext do let mvarDecl ← getMVarDecl mvarId let expectedType ← instantiateMVars mvarDecl.type withInfoHole mvarId do let result ← resumeElabTerm stx expectedType (!postponeOnError) /- We must ensure `result` has the expected type because it is the one expected by the method that postponed stx. That is, the method does not have an opportunity to check whether `result` has the expected type or not. -/ let result ← withRef stx <| ensureHasType expectedType result /- We must perform `occursCheck` here since `result` may contain `mvarId` when it has synthetic `sorry`s. -/ if (← occursCheck mvarId result) then mvarId.assign result return true else return false catch | ex@(.internal id _) => if id == postponeExceptionId then s.restore (restoreInfo := true) return false else throw ex | ex@(.error ..) => if postponeOnError then s.restore (restoreInfo := true) return false else logException ex return true /-- Similar to `synthesizeInstMVarCore`, but makes sure that `instMVar` local context and instances are used. It also logs any error message produced. -/ private def synthesizePendingInstMVar (instMVar : MVarId) : TermElabM Bool := instMVar.withContext do try synthesizeInstMVarCore instMVar catch | ex@(.error ..) => logException ex; return true | _ => unreachable! /-- Try to synthesize `mvarId` by starting using a default instance with the give privority. This method succeeds only if the metavariable of fully synthesized. Remark: In the past, we would return a list of pending TC problems, but this was problematic since a default instance may create subproblems that cannot be solved. Remark: The new approach also has limitations because other pending metavariables are not taken into account while backtraking. That is, we fail to synthesize `mvarId` because we reach subproblems that are stuck, but we could "unstuck" them if we tried to solve other pending metavariables. Considering all pending metavariables into a single backtracking search seems to be too expensive, and potentially generate incomprehensible error messages. This is particularly true if we consider pending metavariables for "postponed" elaboration steps. Here is an example that demonstrate this issue. The example considers we are using the old `binrel%` elaborator which was disconnected from `binop%`. ``` example (a : Int) (b c : Nat) : a = ↑b - ↑c := sorry ``` We have two pending coercions for the `↑` and `HSub ?m.220 ?m.221 ?m.222`. When we did not use a backtracking search here, then the homogenous default instance for `HSub`. ``` instance [Sub α] : HSub α α α where ``` would be applied first, and would propagate the expected type `Int` to the pending coercions which would now be unblocked. Instead of performing a backtracking search that considers all pending metavariables, we improved the `binrel%` elaborator. -/ private partial def synthesizeUsingDefaultPrio (mvarId : MVarId) (prio : Nat) : TermElabM Bool := mvarId.withContext do let mvarType ← mvarId.getType match (← isClass? mvarType) with | none => return false | some className => match (← getDefaultInstances className) with | [] => return false | defaultInstances => for (defaultInstance, instPrio) in defaultInstances do if instPrio == prio then if (← synthesizeUsingDefaultInstance mvarId defaultInstance) then return true return false where synthesizeUsingDefault (mvarId : MVarId) : TermElabM Bool := do for prio in (← getDefaultInstancesPriorities) do if (← synthesizeUsingDefaultPrio mvarId prio) then return true return false synthesizePendingInstMVar' (mvarId : MVarId) : TermElabM Bool := commitWhen <| mvarId.withContext do try synthesizeInstMVarCore mvarId catch _ => return false synthesizeUsingInstancesStep (mvarIds : List MVarId) : TermElabM (List MVarId) := mvarIds.filterM fun mvarId => do if (← synthesizePendingInstMVar' mvarId) then return false else return true synthesizeUsingInstances (mvarIds : List MVarId) : TermElabM (List MVarId) := do let mvarIds' ← synthesizeUsingInstancesStep mvarIds if mvarIds'.length < mvarIds.length then synthesizeUsingInstances mvarIds' else return mvarIds' synthesizeUsingDefaultInstance (mvarId : MVarId) (defaultInstance : Name) : TermElabM Bool := commitWhen do let candidate ← mkConstWithFreshMVarLevels defaultInstance let (mvars, bis, _) ← forallMetaTelescopeReducing (← inferType candidate) let candidate := mkAppN candidate mvars trace[Elab.defaultInstance] "{toString (mkMVar mvarId)}, {mkMVar mvarId} : {← inferType (mkMVar mvarId)} =?= {candidate} : {← inferType candidate}" /- The `coeAtOutParam` feature may mark output parameters of local instances as `syntheticOpaque`. This kind of parameter is not assignable by default. We use `withAssignableSyntheticOpaque` to workaround this behavior when processing default instances. TODO: try to avoid `withAssignableSyntheticOpaque`. -/ if (← withAssignableSyntheticOpaque <| isDefEqGuarded (mkMVar mvarId) candidate) then -- Succeeded. Collect new TC problems trace[Elab.defaultInstance] "isDefEq worked {mkMVar mvarId} : {← inferType (mkMVar mvarId)} =?= {candidate} : {← inferType candidate}" let mut pending := [] for i in [:bis.size] do if bis[i]! == BinderInfo.instImplicit then pending := mvars[i]!.mvarId! :: pending synthesizePending pending else return false synthesizeSomeUsingDefault? (mvarIds : List MVarId) : TermElabM (Option (List MVarId)) := do match mvarIds with | [] => return none | mvarId :: mvarIds => if (← synthesizeUsingDefault mvarId) then return mvarIds else if let some mvarIds' ← synthesizeSomeUsingDefault? mvarIds then return mvarId :: mvarIds' else return none synthesizePending (mvarIds : List MVarId) : TermElabM Bool := do let mvarIds ← synthesizeUsingInstances mvarIds if mvarIds.isEmpty then return true let some mvarIds ← synthesizeSomeUsingDefault? mvarIds | return false synthesizePending mvarIds /-- Used to implement `synthesizeUsingDefault`. This method only consider default instances with the given priority. -/ private def synthesizeSomeUsingDefaultPrio (prio : Nat) : TermElabM Bool := do let rec visit (pendingMVars : List MVarId) (pendingMVarsNew : List MVarId) : TermElabM Bool := do match pendingMVars with | [] => return false | mvarId :: pendingMVars => let some mvarDecl ← getSyntheticMVarDecl? mvarId | visit pendingMVars (mvarId :: pendingMVarsNew) match mvarDecl.kind with | .typeClass => if (← withRef mvarDecl.stx <| synthesizeUsingDefaultPrio mvarId prio) then modify fun s => { s with pendingMVars := pendingMVars.reverse ++ pendingMVarsNew } return true else visit pendingMVars (mvarId :: pendingMVarsNew) | _ => visit pendingMVars (mvarId :: pendingMVarsNew) /- Recall that s.pendingMVars is essentially a stack. The first metavariable was the last one created. We want to apply the default instance in reverse creation order. Otherwise, `toString 0` will produce a `OfNat String _` cannot be synthesized error. -/ visit (← get).pendingMVars.reverse [] /-- Apply default value to any pending synthetic metavariable of kind `SyntheticMVarKind.withDefault` Return true if something was synthesized. -/ private def synthesizeUsingDefault : TermElabM Bool := do let prioSet ← getDefaultInstancesPriorities /- Recall that `prioSet` is stored in descending order -/ for prio in prioSet do if (← synthesizeSomeUsingDefaultPrio prio) then return true return false /-- We use this method to report typeclass (and coercion) resolution problems that are "stuck". That is, there is nothing else to do, and we don't have enough information to synthesize them using TC resolution. -/ def reportStuckSyntheticMVar (mvarId : MVarId) (ignoreStuckTC := false) : TermElabM Unit := do let some mvarSyntheticDecl ← getSyntheticMVarDecl? mvarId | return () withRef mvarSyntheticDecl.stx do match mvarSyntheticDecl.kind with | .typeClass => unless ignoreStuckTC do mvarId.withContext do let mvarDecl ← getMVarDecl mvarId unless (← MonadLog.hasErrors) do throwError "typeclass instance problem is stuck, it is often due to metavariables{indentExpr mvarDecl.type}" | .coe header expectedType e f? => mvarId.withContext do throwTypeMismatchError header expectedType (← inferType e) e f? m!"failed to create type class instance for{indentExpr (← getMVarDecl mvarId).type}" | _ => unreachable! -- TODO handle other cases. /-- Report an error for each synthetic metavariable that could not be resolved. Remark: we set `ignoreStuckTC := true` when elaborating `simp` arguments. -/ private def reportStuckSyntheticMVars (ignoreStuckTC := false) : TermElabM Unit := do let pendingMVars ← modifyGet fun s => (s.pendingMVars, { s with pendingMVars := [] }) for mvarId in pendingMVars do reportStuckSyntheticMVar mvarId ignoreStuckTC private def getSomeSynthethicMVarsRef : TermElabM Syntax := do for mvarId in (← get).pendingMVars do if let some decl ← getSyntheticMVarDecl? mvarId then if decl.stx.getPos?.isSome then return decl.stx return .missing /-- Generate an nicer error message for stuck universe constraints. -/ private def throwStuckAtUniverseCnstr : TermElabM Unit := do -- This code assumes `entries` is not empty. Note that `processPostponed` uses `exceptionOnFailure` to guarantee this property let entries ← getPostponed let mut found : HashSet (Level × Level) := {} let mut uniqueEntries := #[] for entry in entries do let mut lhs := entry.lhs let mut rhs := entry.rhs if Level.normLt rhs lhs then (lhs, rhs) := (rhs, lhs) unless found.contains (lhs, rhs) do found := found.insert (lhs, rhs) uniqueEntries := uniqueEntries.push entry for i in [1:uniqueEntries.size] do logErrorAt uniqueEntries[i]!.ref (← mkLevelStuckErrorMessage uniqueEntries[i]!) throwErrorAt uniqueEntries[0]!.ref (← mkLevelStuckErrorMessage uniqueEntries[0]!) /-- Try to solve postponed universe constraints, and throws an exception if there are stuck constraints. Remark: in previous versions, each `isDefEq u v` invocation would fail if there were pending universe level constraints. With this old approach, we were not able to process ``` Functor.map Prod.fst (x s) ``` because after elaborating `Prod.fst` and trying to ensure its type match the expected one, we would be stuck at the universe constraint: ``` u =?= max u ?v ``` Another benefit of using `withoutPostponingUniverseConstraints` is better error messages. Instead of getting a mysterious type mismatch constraint, we get a list of universe contraints the system is stuck at. -/ private def processPostponedUniverseContraints : TermElabM Unit := do unless (← processPostponed (mayPostpone := false) (exceptionOnFailure := true)) do throwStuckAtUniverseCnstr /-- Remove `mvarId` from the `syntheticMVars` table. We use this method after the metavariable has been synthesized. -/ private def markAsResolved (mvarId : MVarId) : TermElabM Unit := modify fun s => { s with syntheticMVars := s.syntheticMVars.erase mvarId } mutual /-- Try to synthesize a term `val` using the tactic code `tacticCode`, and then assign `mvarId := val`. -/ partial def runTactic (mvarId : MVarId) (tacticCode : Syntax) : TermElabM Unit := withoutAutoBoundImplicit do /- Recall, `tacticCode` is the whole `by ...` expression. -/ let code := tacticCode[1] instantiateMVarDeclMVars mvarId /- TODO: consider using `runPendingTacticsAt` at `mvarId` local context and target type. Issue #1380 demonstrates that the goal may still contain pending metavariables. It happens in the following scenario we have a term `foo A (by tac)` where `A` has been postponed and contains nested `by ...` terms. The pending metavar list contains two metavariables: ?m1 (for `A`) and `?m2` (for `by tac`). When `A` is resumed, it creates a new metavariable `?m3` for the nested `by ...` term in `A`. `?m3` is after `?m2` in the to-do list. Then, we execute `by tac` for synthesizing `?m2`, but its type depends on `?m3`. We have considered putting `?m3` at `?m2` place in the to-do list, but this is not super robust. The ideal solution is to make sure a tactic "resolves" all pending metavariables nested in their local contex and target type before starting tactic execution. The procedure would be a generalization of `runPendingTacticsAt`. We can try to combine it with `instantiateMVarDeclMVars` to make sure we do not perform two traversals. Regarding issue #1380, we addressed the issue by avoiding the elaboration postponement step. However, the same issue can happen in more complicated scenarios. -/ try let remainingGoals ← withInfoHole mvarId <| Tactic.run mvarId do withTacticInfoContext tacticCode do -- also put an info node on the `by` keyword specifically -- the token may be `canonical` and thus shown in the info -- view even though it is synthetic while a node like `tacticCode` never is (#1990) withTacticInfoContext tacticCode[0] do evalTactic code synthesizeSyntheticMVars (mayPostpone := false) unless remainingGoals.isEmpty do reportUnsolvedGoals remainingGoals catch ex => if (← read).errToSorry then for mvarId in (← getMVars (mkMVar mvarId)) do mvarId.admit logException ex else throw ex /-- Try to synthesize the given pending synthetic metavariable. -/ private partial def synthesizeSyntheticMVar (mvarId : MVarId) (postponeOnError : Bool) (runTactics : Bool) : TermElabM Bool := do let some mvarSyntheticDecl ← getSyntheticMVarDecl? mvarId | return true -- The metavariable has already been synthesized withRef mvarSyntheticDecl.stx do match mvarSyntheticDecl.kind with | .typeClass => synthesizePendingInstMVar mvarId | .coe _header? expectedType e _f? => mvarId.withContext do if (← withDefault do isDefEq (← inferType e) expectedType) then -- Types may be defeq now due to mvar assignments, type class -- defaulting, etc. if (← occursCheck mvarId e) then mvarId.assign e return true if let .some coerced ← coerce? e expectedType then if (← occursCheck mvarId coerced) then mvarId.assign coerced return true return false -- NOTE: actual processing at `synthesizeSyntheticMVarsAux` | .postponed savedContext => resumePostponed savedContext mvarSyntheticDecl.stx mvarId postponeOnError | .tactic tacticCode savedContext => withSavedContext savedContext do if runTactics then runTactic mvarId tacticCode return true else return false /-- Try to synthesize the current list of pending synthetic metavariables. Return `true` if at least one of them was synthesized. -/ private partial def synthesizeSyntheticMVarsStep (postponeOnError : Bool) (runTactics : Bool) : TermElabM Bool := do let ctx ← read traceAtCmdPos `Elab.resuming fun _ => m!"resuming synthetic metavariables, mayPostpone: {ctx.mayPostpone}, postponeOnError: {postponeOnError}" let pendingMVars := (← get).pendingMVars let numSyntheticMVars := pendingMVars.length -- We reset `pendingMVars` because new synthetic metavariables may be created by `synthesizeSyntheticMVar`. modify fun s => { s with pendingMVars := [] } -- Recall that `pendingMVars` is a list where head is the most recent pending synthetic metavariable. -- We use `filterRevM` instead of `filterM` to make sure we process the synthetic metavariables using the order they were created. -- It would not be incorrect to use `filterM`. let remainingPendingMVars ← pendingMVars.filterRevM fun mvarId => do -- We use `traceM` because we want to make sure the metavar local context is used to trace the message traceM `Elab.postpone (mvarId.withContext do addMessageContext m!"resuming {mkMVar mvarId}") let succeeded ← synthesizeSyntheticMVar mvarId postponeOnError runTactics if succeeded then markAsResolved mvarId trace[Elab.postpone] if succeeded then format "succeeded" else format "not ready yet" pure !succeeded -- Merge new synthetic metavariables with `remainingPendingMVars`, i.e., metavariables that still couldn't be synthesized modify fun s => { s with pendingMVars := s.pendingMVars ++ remainingPendingMVars } return numSyntheticMVars != remainingPendingMVars.length /-- Try to process pending synthetic metavariables. If `mayPostpone == false`, then `pendingMVars` is `[]` after executing this method. It keeps executing `synthesizeSyntheticMVarsStep` while progress is being made. If `mayPostpone == false`, then it applies default instances to `SyntheticMVarKind.typeClass` (if available) metavariables that are still unresolved, and then tries to resolve metavariables with `mayPostpone == false`. That is, we force them to produce error messages and/or commit to a "best option". If, after that, we still haven't made progress, we report "stuck" errors. Remark: we set `ignoreStuckTC := true` when elaborating `simp` arguments. Then, pending TC problems become implicit parameters for the simp theorem. -/ partial def synthesizeSyntheticMVars (mayPostpone := true) (ignoreStuckTC := false) : TermElabM Unit := do let rec loop (_ : Unit) : TermElabM Unit := do withRef (← getSomeSynthethicMVarsRef) <| withIncRecDepth do unless (← get).pendingMVars.isEmpty do if ← synthesizeSyntheticMVarsStep (postponeOnError := false) (runTactics := false) then loop () else if !mayPostpone then /- Resume pending metavariables with "elaboration postponement" disabled. We postpone elaboration errors in this step by setting `postponeOnError := true`. Example: ``` #check let x := ⟨1, 2⟩; Prod.fst x ``` The term `⟨1, 2⟩` can't be elaborated because the expected type is not know. The `x` at `Prod.fst x` is not elaborated because the type of `x` is not known. When we execute the following step with "elaboration postponement" disabled, the elaborator fails at `⟨1, 2⟩` and postpones it, and succeeds at `x` and learns that its type must be of the form `Prod ?α ?β`. Recall that we postponed `x` at `Prod.fst x` because its type it is not known. We the type of `x` may learn later its type and it may contain implicit and/or auto arguments. By disabling postponement, we are essentially giving up the opportunity of learning `x`s type and assume it does not have implict and/or auto arguments. -/ if ← withoutPostponing <| synthesizeSyntheticMVarsStep (postponeOnError := true) (runTactics := false) then loop () else if ← synthesizeUsingDefault then loop () else if ← withoutPostponing <| synthesizeSyntheticMVarsStep (postponeOnError := false) (runTactics := false) then loop () else if ← synthesizeSyntheticMVarsStep (postponeOnError := false) (runTactics := true) then loop () else reportStuckSyntheticMVars ignoreStuckTC loop () unless mayPostpone do processPostponedUniverseContraints end def synthesizeSyntheticMVarsNoPostponing (ignoreStuckTC := false) : TermElabM Unit := synthesizeSyntheticMVars (mayPostpone := false) (ignoreStuckTC := ignoreStuckTC) /-- Keep invoking `synthesizeUsingDefault` until it returns false. -/ private partial def synthesizeUsingDefaultLoop : TermElabM Unit := do if (← synthesizeUsingDefault) then synthesizeSyntheticMVars (mayPostpone := true) synthesizeUsingDefaultLoop def synthesizeSyntheticMVarsUsingDefault : TermElabM Unit := do synthesizeSyntheticMVars (mayPostpone := true) synthesizeUsingDefaultLoop private partial def withSynthesizeImp {α} (k : TermElabM α) (mayPostpone : Bool) (synthesizeDefault : Bool) : TermElabM α := do let pendingMVarsSaved := (← get).pendingMVars modify fun s => { s with pendingMVars := [] } try let a ← k synthesizeSyntheticMVars mayPostpone if mayPostpone && synthesizeDefault then synthesizeUsingDefaultLoop return a finally modify fun s => { s with pendingMVars := s.pendingMVars ++ pendingMVarsSaved } /-- Execute `k`, and synthesize pending synthetic metavariables created while executing `k` are solved. If `mayPostpone == false`, then all of them must be synthesized. Remark: even if `mayPostpone == true`, the method still uses `synthesizeUsingDefault` -/ @[inline] def withSynthesize [MonadFunctorT TermElabM m] [Monad m] (k : m α) (mayPostpone := false) : m α := monadMap (m := TermElabM) (withSynthesizeImp · mayPostpone (synthesizeDefault := true)) k /-- Similar to `withSynthesize`, but sets `mayPostpone` to `true`, and do not use `synthesizeUsingDefault` -/ @[inline] def withSynthesizeLight [MonadFunctorT TermElabM m] [Monad m] (k : m α) : m α := monadMap (m := TermElabM) (withSynthesizeImp · (mayPostpone := true) (synthesizeDefault := false)) k /-- Elaborate `stx`, and make sure all pending synthetic metavariables created while elaborating `stx` are solved. -/ def elabTermAndSynthesize (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := withRef stx do instantiateMVars (← withSynthesize <| elabTerm stx expectedType?) /-- Collect unassigned metavariables at `e` that have associated tactic blocks, and then execute them using `runTactic`. We use this method at the `match .. with` elaborator when it cannot be postponed anymore, but it is still waiting the result of a tactic block. -/ def runPendingTacticsAt (e : Expr) : TermElabM Unit := do for mvarId in (← getMVars e) do let mvarId ← getDelayedMVarRoot mvarId if let some { kind := .tactic tacticCode savedContext, .. } ← getSyntheticMVarDecl? mvarId then withSavedContext savedContext do runTactic mvarId tacticCode markAsResolved mvarId builtin_initialize registerTraceClass `Elab.resume end Lean.Elab.Term
0ed4b70ac6e4e05890364cdd024b38dab76ea92e
b7f22e51856f4989b970961f794f1c435f9b8f78
/library/init/quot.lean
27ac8b4595a93edfbfdf3de241c5acfc09efe302
[ "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
8,018
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura Quotient types. -/ prelude import init.sigma init.setoid init.logic open sigma.ops setoid constant quot.{l} : Π {A : Type.{l}}, setoid A → Type.{l} -- Remark: if we do not use propext here, then we would need a quot.lift for propositions. constant propext {a b : Prop} : (a ↔ b) → a = b -- iff can now be used to do substitutions in a calculation theorem iff_subst [subst] {a b : Prop} {P : Prop → Prop} (H₁ : a ↔ b) (H₂ : P a) : P b := eq.subst (propext H₁) H₂ namespace quot protected constant mk : Π {A : Type} [s : setoid A], A → quot s notation `⟦`:max a `⟧`:0 := quot.mk a constant sound : Π {A : Type} [s : setoid A] {a b : A}, a ≈ b → ⟦a⟧ = ⟦b⟧ constant lift : Π {A B : Type} [s : setoid A] (f : A → B), (∀ a b, a ≈ b → f a = f b) → quot s → B constant ind : ∀ {A : Type} [s : setoid A] {B : quot s → Prop}, (∀ a, B ⟦a⟧) → ∀ q, B q init_quotient protected theorem lift_beta {A B : Type} [setoid A] (f : A → B) (c : ∀ a b, a ≈ b → f a = f b) (a : A) : lift f c ⟦a⟧ = f a := rfl protected theorem ind_beta {A : Type} [s : setoid A] {B : quot s → Prop} (p : ∀ a, B ⟦a⟧) (a : A) : ind p ⟦a⟧ = p a := rfl protected definition lift_on [reducible] {A B : Type} [s : setoid A] (q : quot s) (f : A → B) (c : ∀ a b, a ≈ b → f a = f b) : B := lift f c q protected theorem induction_on {A : Type} [s : setoid A] {B : quot s → Prop} (q : quot s) (H : ∀ a, B ⟦a⟧) : B q := ind H q theorem exists_rep {A : Type} [s : setoid A] (q : quot s) : ∃ a : A, ⟦a⟧ = q := quot.induction_on q (λ a, exists.intro a rfl) section variable {A : Type} variable [s : setoid A] variable {B : quot s → Type} include s protected definition indep [reducible] (f : Π a, B ⟦a⟧) (a : A) : Σ q, B q := ⟨⟦a⟧, f a⟩ protected lemma indep_coherent (f : Π a, B ⟦a⟧) (H : ∀ (a b : A) (p : a ≈ b), eq.rec (f a) (sound p) = f b) : ∀ a b, a ≈ b → quot.indep f a = quot.indep f b := λa b e, sigma.eq (sound e) (H a b e) protected lemma lift_indep_pr1 (f : Π a, B ⟦a⟧) (H : ∀ (a b : A) (p : a ≈ b), eq.rec (f a) (sound p) = f b) (q : quot s) : (lift (quot.indep f) (quot.indep_coherent f H) q).1 = q := quot.ind (λ a, by esimp) q protected definition rec [reducible] (f : Π a, B ⟦a⟧) (H : ∀ (a b : A) (p : a ≈ b), eq.rec (f a) (sound p) = f b) (q : quot s) : B q := let p := lift (quot.indep f) (quot.indep_coherent f H) q in eq.rec_on (quot.lift_indep_pr1 f H q) (p.2) protected definition rec_on [reducible] (q : quot s) (f : Π a, B ⟦a⟧) (H : ∀ (a b : A) (p : a ≈ b), eq.rec (f a) (sound p) = f b) : B q := quot.rec f H q protected definition rec_on_subsingleton [reducible] [H : ∀ a, subsingleton (B ⟦a⟧)] (q : quot s) (f : Π a, B ⟦a⟧) : B q := quot.rec f (λ a b h, !subsingleton.elim) q protected definition hrec_on [reducible] (q : quot s) (f : Π a, B ⟦a⟧) (c : ∀ (a b : A) (p : a ≈ b), f a == f b) : B q := quot.rec_on q f (λ a b p, eq_of_heq (calc eq.rec (f a) (sound p) == f a : eq_rec_heq ... == f b : c a b p)) end section variables {A B C : Type} variables [s₁ : setoid A] [s₂ : setoid B] include s₁ s₂ protected definition lift₂ [reducible] (f : A → B → C)(c : ∀ a₁ a₂ b₁ b₂, a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) (q₁ : quot s₁) (q₂ : quot s₂) : C := quot.lift (λ a₁, lift (λ a₂, f a₁ a₂) (λ a b H, c a₁ a a₁ b (setoid.refl a₁) H) q₂) (λ a b H, ind (λ a', proof c a a' b a' H (setoid.refl a') qed) q₂) q₁ protected definition lift_on₂ [reducible] (q₁ : quot s₁) (q₂ : quot s₂) (f : A → B → C) (c : ∀ a₁ a₂ b₁ b₂, a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ = f b₁ b₂) : C := quot.lift₂ f c q₁ q₂ protected theorem ind₂ {C : quot s₁ → quot s₂ → Prop} (H : ∀ a b, C ⟦a⟧ ⟦b⟧) (q₁ : quot s₁) (q₂ : quot s₂) : C q₁ q₂ := quot.ind (λ a₁, quot.ind (λ a₂, H a₁ a₂) q₂) q₁ protected theorem induction_on₂ {C : quot s₁ → quot s₂ → Prop} (q₁ : quot s₁) (q₂ : quot s₂) (H : ∀ a b, C ⟦a⟧ ⟦b⟧) : C q₁ q₂ := quot.ind (λ a₁, quot.ind (λ a₂, H a₁ a₂) q₂) q₁ protected theorem induction_on₃ [s₃ : setoid C] {D : quot s₁ → quot s₂ → quot s₃ → Prop} (q₁ : quot s₁) (q₂ : quot s₂) (q₃ : quot s₃) (H : ∀ a b c, D ⟦a⟧ ⟦b⟧ ⟦c⟧) : D q₁ q₂ q₃ := quot.ind (λ a₁, quot.ind (λ a₂, quot.ind (λ a₃, H a₁ a₂ a₃) q₃) q₂) q₁ end section exact variable {A : Type} variable [s : setoid A] include s private definition rel (q₁ q₂ : quot s) : Prop := quot.lift_on₂ q₁ q₂ (λ a₁ a₂, a₁ ≈ a₂) (λ a₁ a₂ b₁ b₂ a₁b₁ a₂b₂, propext (iff.intro (λ a₁a₂, setoid.trans (setoid.symm a₁b₁) (setoid.trans a₁a₂ a₂b₂)) (λ b₁b₂, setoid.trans a₁b₁ (setoid.trans b₁b₂ (setoid.symm a₂b₂))))) local infix `~` := rel private lemma rel.refl : ∀ q : quot s, q ~ q := λ q, quot.induction_on q (λ a, setoid.refl a) private lemma eq_imp_rel {q₁ q₂ : quot s} : q₁ = q₂ → q₁ ~ q₂ := assume h, eq.rec_on h (rel.refl q₁) theorem exact {a b : A} : ⟦a⟧ = ⟦b⟧ → a ≈ b := assume h, eq_imp_rel h end exact section variables {A B : Type} variables [s₁ : setoid A] [s₂ : setoid B] include s₁ s₂ variable {C : quot s₁ → quot s₂ → Type} protected definition rec_on_subsingleton₂ [reducible] {C : quot s₁ → quot s₂ → Type₁} [H : ∀ a b, subsingleton (C ⟦a⟧ ⟦b⟧)] (q₁ : quot s₁) (q₂ : quot s₂) (f : Π a b, C ⟦a⟧ ⟦b⟧) : C q₁ q₂:= @quot.rec_on_subsingleton _ _ _ (λ a, quot.ind _ _) q₁ (λ a, quot.rec_on_subsingleton q₂ (λ b, f a b)) protected definition hrec_on₂ [reducible] {C : quot s₁ → quot s₂ → Type₁} (q₁ : quot s₁) (q₂ : quot s₂) (f : Π a b, C ⟦a⟧ ⟦b⟧) (c : ∀ a₁ a₂ b₁ b₂, a₁ ≈ b₁ → a₂ ≈ b₂ → f a₁ a₂ == f b₁ b₂) : C q₁ q₂:= quot.hrec_on q₁ (λ a, quot.hrec_on q₂ (λ b, f a b) (λ b₁ b₂ p, c _ _ _ _ !setoid.refl p)) (λ a₁ a₂ p, quot.induction_on q₂ (λ b, have aux : f a₁ b == f a₂ b, from c _ _ _ _ p !setoid.refl, calc quot.hrec_on ⟦b⟧ (λ (b : B), f a₁ b) _ == f a₁ b : eq_rec_heq ... == f a₂ b : aux ... == quot.hrec_on ⟦b⟧ (λ (b : B), f a₂ b) _ : eq_rec_heq)) end end quot attribute quot.mk [constructor] attribute quot.lift_on [unfold 4] attribute quot.rec [unfold 6] attribute quot.rec_on [unfold 4] attribute quot.hrec_on [unfold 4] attribute quot.rec_on_subsingleton [unfold 5] attribute quot.lift₂ [unfold 8] attribute quot.lift_on₂ [unfold 6] attribute quot.hrec_on₂ [unfold 6] attribute quot.rec_on_subsingleton₂ [unfold 7] open decidable definition quot.has_decidable_eq [instance] {A : Type} {s : setoid A} [decR : ∀ a b : A, decidable (a ≈ b)] : decidable_eq (quot s) := λ q₁ q₂ : quot s, quot.rec_on_subsingleton₂ q₁ q₂ (λ a₁ a₂, match decR a₁ a₂ with | inl h₁ := inl (quot.sound h₁) | inr h₂ := inr (λ h, absurd (quot.exact h) h₂) end)
440164981cab8eced8e7dfeed411d404917647fb
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/category/CommRing/limits.lean
41450923623b6007c1b27b4bacd36905da5049e3
[]
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
19,717
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.algebra.ring.pi import Mathlib.algebra.category.CommRing.basic import Mathlib.algebra.category.Group.limits import Mathlib.ring_theory.subring import Mathlib.PostPort universes u u_1 namespace Mathlib /-! # The category of (commutative) rings has all limits Further, these limits are preserved by the forgetful functor --- that is, the underlying types are just the limits in the category of types. -/ namespace SemiRing protected instance semiring_obj {J : Type u} [category_theory.small_category J] (F : J ⥤ SemiRing) (j : J) : semiring (category_theory.functor.obj (F ⋙ category_theory.forget SemiRing) j) := id (SemiRing.semiring (category_theory.functor.obj F j)) /-- The flat sections of a functor into `SemiRing` form a subsemiring of all sections. -/ def sections_subsemiring {J : Type u} [category_theory.small_category J] (F : J ⥤ SemiRing) : subsemiring ((j : J) → ↥(category_theory.functor.obj F j)) := subsemiring.mk (category_theory.functor.sections (F ⋙ category_theory.forget SemiRing)) sorry sorry sorry sorry protected instance limit_semiring {J : Type u} [category_theory.small_category J] (F : J ⥤ SemiRing) : semiring (category_theory.limits.cone.X (category_theory.limits.types.limit_cone (F ⋙ category_theory.forget SemiRing))) := subsemiring.to_semiring (sections_subsemiring F) /-- `limit.π (F ⋙ forget SemiRing) j` as a `ring_hom`. -/ def limit_π_ring_hom {J : Type u} [category_theory.small_category J] (F : J ⥤ SemiRing) (j : J) : category_theory.limits.cone.X (category_theory.limits.types.limit_cone (F ⋙ category_theory.forget SemiRing)) →+* category_theory.functor.obj (F ⋙ category_theory.forget SemiRing) j := ring_hom.mk (category_theory.nat_trans.app (category_theory.limits.cone.π (category_theory.limits.types.limit_cone (F ⋙ category_theory.forget SemiRing))) j) sorry sorry sorry sorry namespace has_limits -- The next two definitions are used in the construction of `has_limits SemiRing`. -- After that, the limits should be constructed using the generic limits API, -- e.g. `limit F`, `limit.cone F`, and `limit.is_limit F`. /-- Construction of a limit cone in `SemiRing`. (Internal use only; use the limits API.) -/ def limit_cone {J : Type u} [category_theory.small_category J] (F : J ⥤ SemiRing) : category_theory.limits.cone F := category_theory.limits.cone.mk (of (category_theory.limits.cone.X (category_theory.limits.types.limit_cone (F ⋙ category_theory.forget SemiRing)))) (category_theory.nat_trans.mk (limit_π_ring_hom F)) /-- Witness that the limit cone in `SemiRing` is a limit cone. (Internal use only; use the limits API.) -/ def limit_cone_is_limit {J : Type u} [category_theory.small_category J] (F : J ⥤ SemiRing) : category_theory.limits.is_limit (limit_cone F) := category_theory.limits.is_limit.of_faithful (category_theory.forget SemiRing) (category_theory.limits.types.limit_cone_is_limit (F ⋙ category_theory.forget SemiRing)) (fun (s : category_theory.limits.cone F) => ring_hom.mk (fun (v : category_theory.limits.cone.X (category_theory.functor.map_cone (category_theory.forget SemiRing) s)) => { val := fun (j : J) => category_theory.nat_trans.app (category_theory.limits.cone.π (category_theory.functor.map_cone (category_theory.forget SemiRing) s)) j v, property := sorry }) sorry sorry sorry sorry) sorry end has_limits /-- The category of rings has all limits. -/ protected instance has_limits : category_theory.limits.has_limits SemiRing := category_theory.limits.has_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.has_limits_of_shape.mk fun (F : J ⥤ SemiRing) => category_theory.limits.has_limit.mk (category_theory.limits.limit_cone.mk sorry sorry) /-- An auxiliary declaration to speed up typechecking. -/ def forget₂_AddCommMon_preserves_limits_aux {J : Type u} [category_theory.small_category J] (F : J ⥤ SemiRing) : category_theory.limits.is_limit (category_theory.functor.map_cone (category_theory.forget₂ SemiRing AddCommMon) (has_limits.limit_cone F)) := AddCommMon.limit_cone_is_limit (F ⋙ category_theory.forget₂ SemiRing AddCommMon) /-- The forgetful functor from semirings to additive commutative monoids preserves all limits. -/ protected instance forget₂_AddCommMon_preserves_limits : category_theory.limits.preserves_limits (category_theory.forget₂ SemiRing AddCommMon) := category_theory.limits.preserves_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.preserves_limits_of_shape.mk fun (F : J ⥤ SemiRing) => category_theory.limits.preserves_limit_of_preserves_limit_cone (has_limits.limit_cone_is_limit F) (forget₂_AddCommMon_preserves_limits_aux F) /-- An auxiliary declaration to speed up typechecking. -/ def forget₂_Mon_preserves_limits_aux {J : Type u} [category_theory.small_category J] (F : J ⥤ SemiRing) : category_theory.limits.is_limit (category_theory.functor.map_cone (category_theory.forget₂ SemiRing Mon) (has_limits.limit_cone F)) := Mon.has_limits.limit_cone_is_limit (F ⋙ category_theory.forget₂ SemiRing Mon) /-- The forgetful functor from semirings to monoids preserves all limits. -/ protected instance forget₂_Mon_preserves_limits : category_theory.limits.preserves_limits (category_theory.forget₂ SemiRing Mon) := category_theory.limits.preserves_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.preserves_limits_of_shape.mk fun (F : J ⥤ SemiRing) => category_theory.limits.preserves_limit_of_preserves_limit_cone (has_limits.limit_cone_is_limit F) (forget₂_Mon_preserves_limits_aux F) /-- The forgetful functor from semirings to types preserves all limits. -/ protected instance forget_preserves_limits : category_theory.limits.preserves_limits (category_theory.forget SemiRing) := category_theory.limits.preserves_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.preserves_limits_of_shape.mk fun (F : J ⥤ SemiRing) => category_theory.limits.preserves_limit_of_preserves_limit_cone (has_limits.limit_cone_is_limit F) (category_theory.limits.types.limit_cone_is_limit (F ⋙ category_theory.forget SemiRing)) end SemiRing namespace CommSemiRing protected instance comm_semiring_obj {J : Type u} [category_theory.small_category J] (F : J ⥤ CommSemiRing) (j : J) : comm_semiring (category_theory.functor.obj (F ⋙ category_theory.forget CommSemiRing) j) := id (CommSemiRing.comm_semiring (category_theory.functor.obj F j)) protected instance limit_comm_semiring {J : Type u} [category_theory.small_category J] (F : J ⥤ CommSemiRing) : comm_semiring (category_theory.limits.cone.X (category_theory.limits.types.limit_cone (F ⋙ category_theory.forget CommSemiRing))) := subsemiring.to_comm_semiring (SemiRing.sections_subsemiring (F ⋙ category_theory.forget₂ CommSemiRing SemiRing)) /-- We show that the forgetful functor `CommSemiRing ⥤ SemiRing` creates limits. All we need to do is notice that the limit point has a `comm_semiring` instance available, and then reuse the existing limit. -/ protected instance category_theory.forget₂.category_theory.creates_limit {J : Type u} [category_theory.small_category J] (F : J ⥤ CommSemiRing) : category_theory.creates_limit F (category_theory.forget₂ CommSemiRing SemiRing) := sorry /-- A choice of limit cone for a functor into `CommSemiRing`. (Generally, you'll just want to use `limit F`.) -/ def limit_cone {J : Type u} [category_theory.small_category J] (F : J ⥤ CommSemiRing) : category_theory.limits.cone F := category_theory.lift_limit (category_theory.limits.limit.is_limit (F ⋙ category_theory.forget₂ CommSemiRing SemiRing)) /-- The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.) -/ def limit_cone_is_limit {J : Type u} [category_theory.small_category J] (F : J ⥤ CommSemiRing) : category_theory.limits.is_limit (limit_cone F) := category_theory.lifted_limit_is_limit (category_theory.limits.limit.is_limit (F ⋙ category_theory.forget₂ CommSemiRing SemiRing)) /-- The category of rings has all limits. -/ protected instance has_limits : category_theory.limits.has_limits CommSemiRing := category_theory.limits.has_limits.mk fun (J : Type u) (𝒥 : category_theory.small_category J) => category_theory.limits.has_limits_of_shape.mk fun (F : J ⥤ CommSemiRing) => category_theory.has_limit_of_created F (category_theory.forget₂ CommSemiRing SemiRing) /-- The forgetful functor from rings to semirings preserves all limits. -/ protected instance forget₂_SemiRing_preserves_limits : category_theory.limits.preserves_limits (category_theory.forget₂ CommSemiRing SemiRing) := category_theory.limits.preserves_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.preserves_limits_of_shape.mk fun (F : J ⥤ CommSemiRing) => category_theory.preserves_limit_of_creates_limit_and_has_limit F (category_theory.forget₂ CommSemiRing SemiRing) /-- The forgetful functor from rings to types preserves all limits. (That is, the underlying types could have been computed instead as limits in the category of types.) -/ protected instance forget_preserves_limits : category_theory.limits.preserves_limits (category_theory.forget CommSemiRing) := category_theory.limits.preserves_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.preserves_limits_of_shape.mk fun (F : J ⥤ CommSemiRing) => category_theory.limits.comp_preserves_limit (category_theory.forget₂ CommSemiRing SemiRing) (category_theory.forget SemiRing) end CommSemiRing namespace Ring protected instance ring_obj {J : Type u} [category_theory.small_category J] (F : J ⥤ Ring) (j : J) : ring (category_theory.functor.obj (F ⋙ category_theory.forget Ring) j) := id (Ring.ring (category_theory.functor.obj F j)) /-- The flat sections of a functor into `Ring` form a subring of all sections. -/ def sections_subring {J : Type u} [category_theory.small_category J] (F : J ⥤ Ring) : subring ((j : J) → ↥(category_theory.functor.obj F j)) := subring.mk (category_theory.functor.sections (F ⋙ category_theory.forget Ring)) sorry sorry sorry sorry sorry protected instance limit_ring {J : Type u} [category_theory.small_category J] (F : J ⥤ Ring) : ring (category_theory.limits.cone.X (category_theory.limits.types.limit_cone (F ⋙ category_theory.forget Ring))) := subring.to_ring (sections_subring F) /-- We show that the forgetful functor `CommRing ⥤ Ring` creates limits. All we need to do is notice that the limit point has a `ring` instance available, and then reuse the existing limit. -/ protected instance category_theory.forget₂.category_theory.creates_limit {J : Type u} [category_theory.small_category J] (F : J ⥤ Ring) : category_theory.creates_limit F (category_theory.forget₂ Ring SemiRing) := sorry /-- A choice of limit cone for a functor into `Ring`. (Generally, you'll just want to use `limit F`.) -/ def limit_cone {J : Type u} [category_theory.small_category J] (F : J ⥤ Ring) : category_theory.limits.cone F := category_theory.lift_limit (category_theory.limits.limit.is_limit (F ⋙ category_theory.forget₂ Ring SemiRing)) /-- The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.) -/ def limit_cone_is_limit {J : Type u} [category_theory.small_category J] (F : J ⥤ Ring) : category_theory.limits.is_limit (limit_cone F) := category_theory.lifted_limit_is_limit (category_theory.limits.limit.is_limit (F ⋙ category_theory.forget₂ Ring SemiRing)) /-- The category of rings has all limits. -/ protected instance has_limits : category_theory.limits.has_limits Ring := category_theory.limits.has_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.has_limits_of_shape.mk fun (F : J ⥤ Ring) => category_theory.has_limit_of_created F (category_theory.forget₂ Ring SemiRing) /-- The forgetful functor from rings to semirings preserves all limits. -/ protected instance forget₂_SemiRing_preserves_limits : category_theory.limits.preserves_limits (category_theory.forget₂ Ring SemiRing) := category_theory.limits.preserves_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.preserves_limits_of_shape.mk fun (F : J ⥤ Ring) => category_theory.preserves_limit_of_creates_limit_and_has_limit F (category_theory.forget₂ Ring SemiRing) /-- An auxiliary declaration to speed up typechecking. -/ def forget₂_AddCommGroup_preserves_limits_aux {J : Type u} [category_theory.small_category J] (F : J ⥤ Ring) : category_theory.limits.is_limit (category_theory.functor.map_cone (category_theory.forget₂ Ring AddCommGroup) (limit_cone F)) := AddCommGroup.limit_cone_is_limit (F ⋙ category_theory.forget₂ Ring AddCommGroup) /-- The forgetful functor from rings to additive commutative groups preserves all limits. -/ protected instance forget₂_AddCommGroup_preserves_limits : category_theory.limits.preserves_limits (category_theory.forget₂ Ring AddCommGroup) := category_theory.limits.preserves_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.preserves_limits_of_shape.mk fun (F : J ⥤ Ring) => category_theory.limits.preserves_limit_of_preserves_limit_cone (limit_cone_is_limit F) (forget₂_AddCommGroup_preserves_limits_aux F) /-- The forgetful functor from rings to types preserves all limits. (That is, the underlying types could have been computed instead as limits in the category of types.) -/ protected instance forget_preserves_limits : category_theory.limits.preserves_limits (category_theory.forget Ring) := category_theory.limits.preserves_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.preserves_limits_of_shape.mk fun (F : J ⥤ Ring) => category_theory.limits.comp_preserves_limit (category_theory.forget₂ Ring SemiRing) (category_theory.forget SemiRing) end Ring namespace CommRing protected instance comm_ring_obj {J : Type u} [category_theory.small_category J] (F : J ⥤ CommRing) (j : J) : comm_ring (category_theory.functor.obj (F ⋙ category_theory.forget CommRing) j) := id (CommRing.comm_ring (category_theory.functor.obj F j)) protected instance limit_comm_ring {J : Type u} [category_theory.small_category J] (F : J ⥤ CommRing) : comm_ring (category_theory.limits.cone.X (category_theory.limits.types.limit_cone (F ⋙ category_theory.forget CommRing))) := subring.to_comm_ring (Ring.sections_subring (F ⋙ category_theory.forget₂ CommRing Ring)) /-- We show that the forgetful functor `CommRing ⥤ Ring` creates limits. All we need to do is notice that the limit point has a `comm_ring` instance available, and then reuse the existing limit. -/ /- protected instance category_theory.forget₂.category_theory.creates_limit {J : Type u} [category_theory.small_category J] (F : J ⥤ CommRing) : category_theory.creates_limit F (category_theory.forget₂ CommRing Ring) := sorry A terse solution here would be ``` creates_limit_of_fully_faithful_of_iso (CommRing.of (limit (F ⋙ forget _))) (iso.refl _) ``` but it seems this would introduce additional identity morphisms in `limit.π`. -/ /-- A choice of limit cone for a functor into `CommRing`. (Generally, you'll just want to use `limit F`.) -/ def limit_cone {J : Type u} [category_theory.small_category J] (F : J ⥤ CommRing) : category_theory.limits.cone F := category_theory.lift_limit (category_theory.limits.limit.is_limit (F ⋙ category_theory.forget₂ CommRing Ring)) /-- The chosen cone is a limit cone. (Generally, you'll just want to use `limit.cone F`.) -/ def limit_cone_is_limit {J : Type u} [category_theory.small_category J] (F : J ⥤ CommRing) : category_theory.limits.is_limit (limit_cone F) := category_theory.lifted_limit_is_limit (category_theory.limits.limit.is_limit (F ⋙ category_theory.forget₂ CommRing Ring)) /-- The category of commutative rings has all limits. -/ protected instance has_limits : category_theory.limits.has_limits CommRing := category_theory.limits.has_limits.mk fun (J : Type u) (𝒥 : category_theory.small_category J) => category_theory.limits.has_limits_of_shape.mk fun (F : J ⥤ CommRing) => category_theory.has_limit_of_created F (category_theory.forget₂ CommRing Ring) /-- The forgetful functor from commutative rings to rings preserves all limits. (That is, the underlying rings could have been computed instead as limits in the category of rings.) -/ protected instance forget₂_Ring_preserves_limits : category_theory.limits.preserves_limits (category_theory.forget₂ CommRing Ring) := category_theory.limits.preserves_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.preserves_limits_of_shape.mk fun (F : J ⥤ CommRing) => category_theory.preserves_limit_of_creates_limit_and_has_limit F (category_theory.forget₂ CommRing Ring) /-- An auxiliary declaration to speed up typechecking. -/ def forget₂_CommSemiRing_preserves_limits_aux {J : Type u} [category_theory.small_category J] (F : J ⥤ CommRing) : category_theory.limits.is_limit (category_theory.functor.map_cone (category_theory.forget₂ CommRing CommSemiRing) (limit_cone F)) := CommSemiRing.limit_cone_is_limit (F ⋙ category_theory.forget₂ CommRing CommSemiRing) /-- The forgetful functor from commutative rings to commutative semirings preserves all limits. (That is, the underlying commutative semirings could have been computed instead as limits in the category of commutative semirings.) -/ protected instance forget₂_CommSemiRing_preserves_limits : category_theory.limits.preserves_limits (category_theory.forget₂ CommRing CommSemiRing) := category_theory.limits.preserves_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.preserves_limits_of_shape.mk fun (F : J ⥤ CommRing) => category_theory.limits.preserves_limit_of_preserves_limit_cone (limit_cone_is_limit F) (forget₂_CommSemiRing_preserves_limits_aux F) /-- The forgetful functor from commutative rings to types preserves all limits. (That is, the underlying types could have been computed instead as limits in the category of types.) -/ protected instance forget_preserves_limits : category_theory.limits.preserves_limits (category_theory.forget CommRing) := category_theory.limits.preserves_limits.mk fun (J : Type u_1) (𝒥 : category_theory.small_category J) => category_theory.limits.preserves_limits_of_shape.mk fun (F : J ⥤ CommRing) => category_theory.limits.comp_preserves_limit (category_theory.forget₂ CommRing Ring) (category_theory.forget Ring)
c215755611ede35bde260b5ede5740626c7d6f3c
b7f22e51856f4989b970961f794f1c435f9b8f78
/hott/hit/refl_quotient.hlean
010a307054db99006d53975fcbb409cd8cf820a7
[ "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
3,101
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 Quotient of a reflexive relation -/ import homotopy.circle cubical.squareover .two_quotient open eq simple_two_quotient e_closure namespace refl_quotient section parameters {A : Type} (R : A → A → Type) (ρ : Πa, R a a) inductive refl_quotient_Q : Π⦃a : A⦄, e_closure R a a → Type := | Qmk {} : Π(a : A), refl_quotient_Q [ρ a] open refl_quotient_Q local abbreviation Q := refl_quotient_Q definition refl_quotient : Type := simple_two_quotient R Q definition rclass_of (a : A) : refl_quotient := incl0 R Q a definition req_of_rel ⦃a a' : A⦄ (r : R a a') : rclass_of a = rclass_of a' := incl1 R Q r definition pρ (a : A) : req_of_rel (ρ a) = idp := incl2 R Q (Qmk a) protected definition rec {P : refl_quotient → Type} (Pc : Π(a : A), P (rclass_of a)) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a =[req_of_rel H] Pc a') (Pr : Π(a : A), change_path (pρ a) (Pp (ρ a)) = idpo) (x : refl_quotient) : P x := begin induction x, exact Pc a, exact Pp s, induction q, apply Pr end protected definition rec_on [reducible] {P : refl_quotient → Type} (x : refl_quotient) (Pc : Π(a : A), P (rclass_of a)) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a =[req_of_rel H] Pc a') (Pr : Π(a : A), change_path (pρ a) (Pp (ρ a)) = idpo) : P x := rec Pc Pp Pr x definition rec_req_of_rel {P : Type} {P : refl_quotient → Type} (Pc : Π(a : A), P (rclass_of a)) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a =[req_of_rel H] Pc a') (Pr : Π(a : A), change_path (pρ a) (Pp (ρ a)) = idpo) ⦃a a' : A⦄ (r : R a a') : apd (rec Pc Pp Pr) (req_of_rel r) = Pp r := !rec_incl1 protected definition elim {P : Type} (Pc : Π(a : A), P) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a = Pc a') (Pr : Π(a : A), Pp (ρ a) = idp) (x : refl_quotient) : P := begin induction x, exact Pc a, exact Pp s, induction q, apply Pr end protected definition elim_on [reducible] {P : Type} (x : refl_quotient) (Pc : Π(a : A), P) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a = Pc a') (Pr : Π(a : A), Pp (ρ a) = idp) : P := elim Pc Pp Pr x definition elim_req_of_rel {P : Type} {Pc : Π(a : A), P} {Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a = Pc a'} (Pr : Π(a : A), Pp (ρ a) = idp) ⦃a a' : A⦄ (r : R a a') : ap (elim Pc Pp Pr) (req_of_rel r) = Pp r := !elim_incl1 theorem elim_pρ {P : Type} (Pc : Π(a : A), P) (Pp : Π⦃a a' : A⦄ (H : R a a'), Pc a = Pc a') (Pr : Π(a : A), Pp (ρ a) = idp) (a : A) : square (ap02 (elim Pc Pp Pr) (pρ a)) (Pr a) (elim_req_of_rel Pr (ρ a)) idp := !elim_incl2 end end refl_quotient attribute refl_quotient.rclass_of [constructor] attribute refl_quotient.rec refl_quotient.elim [unfold 8] [recursor 8] --attribute refl_quotient.elim_type [unfold 9] attribute refl_quotient.rec_on refl_quotient.elim_on [unfold 5] --attribute refl_quotient.elim_type_on [unfold 6]
bbbc7b654fb114d3b4b4bef91d8b003e5b52c097
9dc8cecdf3c4634764a18254e94d43da07142918
/counterexamples/phillips.lean
548429ff4b7f5acf8b8602373f648334efbc4ec9
[ "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
28,989
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 analysis.normed_space.hahn_banach.extension import measure_theory.measure.lebesgue /-! # A counterexample on Pettis integrability There are several theories of integration for functions taking values in Banach spaces. Bochner integration, requiring approximation by simple functions, is the analogue of the one-dimensional theory. It is very well behaved, but only works for functions with second-countable range. For functions `f` taking values in a larger Banach space `B`, one can define the Dunford integral as follows. Assume that, for all continuous linear functional `φ`, the function `φ ∘ f` is measurable (we say that `f` is weakly measurable, or scalarly measurable) and integrable. Then `φ ↦ ∫ φ ∘ f` is continuous (by the closed graph theorem), and therefore defines an element of the bidual `B**`. This is the Dunford integral of `f`. This Dunford integral is not usable in practice as it does not belong to the right space. Let us say that a function is Pettis integrable if its Dunford integral belongs to the canonical image of `B` in `B**`. In this case, we define the Pettis integral as the Dunford integral inside `B`. This integral is very general, but not really usable to do analysis. This file illustrates this, by giving an example of a function with nice properties but which is *not* Pettis-integrable. This function: - is defined from `[0, 1]` to a complete Banach space; - is weakly measurable; - has norm everywhere bounded by `1` (in particular, its norm is integrable); - and yet it is not Pettis-integrable with respect to Lebesgue measure. This construction is due to [Ralph S. Phillips, *Integration in a convex linear topological space*][phillips1940], in Example 10.8. It requires the continuum hypothesis. The example is the following. Under the continuum hypothesis, one can find a subset of `ℝ²` which, along each vertical line, only misses a countable set of points, while it is countable along each horizontal line. This is due to Sierpinski, and formalized in `sierpinski_pathological_family`. (In fact, Sierpinski proves that the existence of such a set is equivalent to the continuum hypothesis). Let `B` be the set of all bounded functions on `ℝ` (we are really talking about everywhere defined functions here). Define `f : ℝ → B` by taking `f x` to be the characteristic function of the vertical slice at position `x` of Sierpinski's set. It is our counterexample. To show that it is weakly measurable, we should consider `φ ∘ f` where `φ` is an arbitrary continuous linear form on `B`. There is no reasonable classification of such linear forms (they can be very wild). But if one restricts such a linear form to characteristic functions, one gets a finitely additive signed "measure". Such a "measure" can be decomposed into a discrete part (supported on a countable set) and a continuous part (giving zero mass to countable sets). For all but countably many points, `f x` will not intersect the discrete support of `φ` thanks to the definition of the Sierpinski set. This implies that `φ ∘ f` is constant outside of a countable set, and equal to the total mass of the continuous part of `φ` there. In particular, it is measurable (and its integral is the total mass of the continuous part of `φ`). Assume that `f` has a Pettis integral `g`. For all continuous linear form `φ`, then `φ g` should be the total mass of the continuous part of `φ`. Taking for `φ` the evaluation at the point `x` (which has no continuous part), one gets `g x = 0`. Take then for `φ` the Lebesgue integral on `[0, 1]` (or rather an arbitrary extension of Lebesgue integration to all bounded functions, thanks to Hahn-Banach). Then `φ g` should be the total mass of the continuous part of `φ`, which is `1`. This contradicts the fact that `g = 0`, and concludes the proof that `f` has no Pettis integral. ## Implementation notes The space of all bounded functions is defined as the space of all bounded continuous functions on a discrete copy of the original type, as mathlib only contains the space of all bounded continuous functions (which is the useful one). -/ universe u variables {α : Type u} open set bounded_continuous_function measure_theory open cardinal (aleph) open_locale cardinal bounded_continuous_function noncomputable theory /-- A copy of a type, endowed with the discrete topology -/ def discrete_copy (α : Type u) : Type u := α instance : topological_space (discrete_copy α) := ⊥ instance : discrete_topology (discrete_copy α) := ⟨rfl⟩ instance [inhabited α] : inhabited (discrete_copy α) := ⟨show α, from default⟩ namespace phillips_1940 /-! ### Extending the integral Thanks to Hahn-Banach, one can define a (non-canonical) continuous linear functional on the space of all bounded functions, coinciding with the integral on the integrable ones. -/ /-- The subspace of integrable functions in the space of all bounded functions on a type. This is a technical device, used to apply Hahn-Banach theorem to construct an extension of the integral to all bounded functions. -/ def bounded_integrable_functions [measurable_space α] (μ : measure α) : subspace ℝ (discrete_copy α →ᵇ ℝ) := { carrier := {f | integrable f μ}, zero_mem' := integrable_zero _ _ _, add_mem' := λ f g hf hg, integrable.add hf hg, smul_mem' := λ c f hf, integrable.smul c hf } /-- The integral, as a continuous linear map on the subspace of integrable functions in the space of all bounded functions on a type. This is a technical device, that we will extend through Hahn-Banach. -/ def bounded_integrable_functions_integral_clm [measurable_space α] (μ : measure α) [is_finite_measure μ] : bounded_integrable_functions μ →L[ℝ] ℝ := linear_map.mk_continuous { to_fun := λ f, ∫ x, f x ∂μ, map_add' := λ f g, integral_add f.2 g.2, map_smul' := λ c f, integral_smul _ _ } (μ univ).to_real begin assume f, rw mul_comm, apply norm_integral_le_of_norm_le_const, apply filter.eventually_of_forall, assume x, exact bounded_continuous_function.norm_coe_le_norm f x, end /-- Given a measure, there exists a continuous linear form on the space of all bounded functions (not necessarily measurable) that coincides with the integral on bounded measurable functions. -/ lemma exists_linear_extension_to_bounded_functions [measurable_space α] (μ : measure α) [is_finite_measure μ] : ∃ φ : (discrete_copy α →ᵇ ℝ) →L[ℝ] ℝ, ∀ (f : discrete_copy α →ᵇ ℝ), integrable f μ → φ f = ∫ x, f x ∂μ := begin rcases exists_extension_norm_eq _ (bounded_integrable_functions_integral_clm μ) with ⟨φ, hφ⟩, exact ⟨φ, λ f hf, hφ.1 ⟨f, hf⟩⟩, end /-- An arbitrary extension of the integral to all bounded functions, as a continuous linear map. It is not at all canonical, and constructed using Hahn-Banach. -/ def _root_.measure_theory.measure.extension_to_bounded_functions [measurable_space α] (μ : measure α) [is_finite_measure μ] : (discrete_copy α →ᵇ ℝ) →L[ℝ] ℝ := (exists_linear_extension_to_bounded_functions μ).some lemma extension_to_bounded_functions_apply [measurable_space α] (μ : measure α) [is_finite_measure μ] (f : discrete_copy α →ᵇ ℝ) (hf : integrable f μ) : μ.extension_to_bounded_functions f = ∫ x, f x ∂μ := (exists_linear_extension_to_bounded_functions μ).some_spec f hf /-! ### Additive measures on the space of all sets We define bounded finitely additive signed measures on the space of all subsets of a type `α`, and show that such an object can be split into a discrete part and a continuous part. -/ /-- A bounded signed finitely additive measure defined on *all* subsets of a type. -/ structure bounded_additive_measure (α : Type u) := (to_fun : set α → ℝ) (additive' : ∀ s t, disjoint s t → to_fun (s ∪ t) = to_fun s + to_fun t) (exists_bound : ∃ (C : ℝ), ∀ s, |to_fun s| ≤ C) instance : inhabited (bounded_additive_measure α) := ⟨{ to_fun := λ s, 0, additive' := λ s t hst, by simp, exists_bound := ⟨0, λ s, by simp⟩ }⟩ instance : has_coe_to_fun (bounded_additive_measure α) (λ _, set α → ℝ) := ⟨λ f, f.to_fun⟩ namespace bounded_additive_measure /-- A constant bounding the mass of any set for `f`. -/ def C (f : bounded_additive_measure α) := f.exists_bound.some lemma additive (f : bounded_additive_measure α) (s t : set α) (h : disjoint s t) : f (s ∪ t) = f s + f t := f.additive' s t h lemma abs_le_bound (f : bounded_additive_measure α) (s : set α) : |f s| ≤ f.C := f.exists_bound.some_spec s lemma le_bound (f : bounded_additive_measure α) (s : set α) : f s ≤ f.C := le_trans (le_abs_self _) (f.abs_le_bound s) @[simp] lemma empty (f : bounded_additive_measure α) : f ∅ = 0 := begin have : (∅ : set α) = ∅ ∪ ∅, by simp only [empty_union], apply_fun f at this, rwa [f.additive _ _ (empty_disjoint _), self_eq_add_left] at this, end instance : has_neg (bounded_additive_measure α) := ⟨λ f, { to_fun := λ s, - f s, additive' := λ s t hst, by simp only [f.additive s t hst, add_comm, neg_add_rev], exists_bound := ⟨f.C, λ s, by simp [f.abs_le_bound]⟩ }⟩ @[simp] lemma neg_apply (f : bounded_additive_measure α) (s : set α) : (-f) s = - (f s) := rfl /-- Restricting a bounded additive measure to a subset still gives a bounded additive measure. -/ def restrict (f : bounded_additive_measure α) (t : set α) : bounded_additive_measure α := { to_fun := λ s, f (t ∩ s), additive' := λ s s' h, begin rw [← f.additive (t ∩ s) (t ∩ s'), inter_union_distrib_left], exact h.mono (inter_subset_right _ _) (inter_subset_right _ _), end, exists_bound := ⟨f.C, λ s, f.abs_le_bound _⟩ } @[simp] lemma restrict_apply (f : bounded_additive_measure α) (s t : set α) : f.restrict s t = f (s ∩ t) := rfl /-- There is a maximal countable set of positive measure, in the sense that any countable set not intersecting it has nonpositive measure. Auxiliary lemma to prove `exists_discrete_support`. -/ lemma exists_discrete_support_nonpos (f : bounded_additive_measure α) : ∃ (s : set α), s.countable ∧ (∀ t : set α, t.countable → f (t \ s) ≤ 0) := begin /- The idea of the proof is to construct the desired set inductively, adding at each step a countable set with close to maximal measure among those points that have not already been chosen. Doing this countably many steps will be enough. Indeed, otherwise, a remaining set would have positive measure `ε`. This means that at each step the set we have added also had a large measure, say at least `ε / 2`. After `n` steps, the set we have constructed has therefore measure at least `n * ε / 2`. This is a contradiction since the measures have to remain uniformly bounded. We argue from the start by contradiction, as this means that our inductive construction will never be stuck, so we won't have to consider this case separately. In this proof, we use explicit coercions `↑s` for `s : A` as otherwise the system tries to find a `has_coe_to_fun` instance on `↥A`, which is too costly. -/ by_contra' h, -- We will formulate things in terms of the type of countable subsets of `α`, as this is more -- convenient to formalize the inductive construction. let A : set (set α) := {t | t.countable}, let empty : A := ⟨∅, countable_empty⟩, haveI : nonempty A := ⟨empty⟩, -- given a countable set `s`, one can find a set `t` in its complement with measure close to -- maximal. have : ∀ (s : A), ∃ (t : A), (∀ (u : A), f (↑u \ ↑s) ≤ 2 * f (↑t \ ↑s)), { assume s, have B : bdd_above (range (λ (u : A), f (↑u \ ↑s))), { refine ⟨f.C, λ x hx, _⟩, rcases hx with ⟨u, hu⟩, rw ← hu, exact f.le_bound _ }, let S := supr (λ (t : A), f (↑t \ ↑s)), have S_pos : 0 < S, { rcases h s.1 s.2 with ⟨t, t_count, ht⟩, apply ht.trans_le, let t' : A := ⟨t, t_count⟩, change f (↑t' \ ↑s) ≤ S, exact le_csupr B t' }, rcases exists_lt_of_lt_csupr (half_lt_self S_pos) with ⟨t, ht⟩, refine ⟨t, λ u, _⟩, calc f (↑u \ ↑s) ≤ S : le_csupr B _ ... = 2 * (S / 2) : by ring ... ≤ 2 * f (↑t \ ↑s) : mul_le_mul_of_nonneg_left ht.le (by norm_num) }, choose! F hF using this, -- iterate the above construction, by adding at each step a set with measure close to maximal in -- the complement of already chosen points. This is the set `s n` at step `n`. let G : A → A := λ u, ⟨(↑u : set α) ∪ ↑(F u), u.2.union (F u).2⟩, let s : ℕ → A := λ n, G^[n] empty, -- We will get a contradiction from the fact that there is a countable set `u` with positive -- measure in the complement of `⋃ n, s n`. rcases h (⋃ n, ↑(s n)) (countable_Union (λ n, (s n).2)) with ⟨t, t_count, ht⟩, let u : A := ⟨t \ ⋃ n, ↑(s n), t_count.mono (diff_subset _ _)⟩, set ε := f (↑u) with hε, have ε_pos : 0 < ε := ht, have I1 : ∀ n, ε / 2 ≤ f (↑(s (n+1)) \ ↑(s n)), { assume n, rw [div_le_iff' (show (0 : ℝ) < 2, by norm_num), hε], convert hF (s n) u using 3, { dsimp [u], ext x, simp only [not_exists, mem_Union, mem_diff], tauto }, { simp only [s, function.iterate_succ', subtype.coe_mk, union_diff_left] } }, have I2 : ∀ (n : ℕ), (n : ℝ) * (ε / 2) ≤ f (↑(s n)), { assume n, induction n with n IH, { simp only [s, bounded_additive_measure.empty, id.def, nat.cast_zero, zero_mul, function.iterate_zero, subtype.coe_mk], }, { have : (↑(s (n+1)) : set α) = (↑(s (n+1)) \ ↑(s n)) ∪ ↑(s n), by simp only [s, function.iterate_succ', union_comm, union_diff_self, subtype.coe_mk, union_diff_left], rw [nat.succ_eq_add_one, this, f.additive], swap, { rw disjoint.comm, apply disjoint_diff }, calc ((n + 1 : ℕ) : ℝ) * (ε / 2) = ε / 2 + n * (ε / 2) : by simp only [nat.cast_succ]; ring ... ≤ f (↑(s (n + 1 : ℕ)) \ ↑(s n)) + f (↑(s n)) : add_le_add (I1 n) IH } }, rcases exists_nat_gt (f.C / (ε / 2)) with ⟨n, hn⟩, have : (n : ℝ) ≤ f.C / (ε / 2), by { rw le_div_iff (half_pos ε_pos), exact (I2 n).trans (f.le_bound _) }, exact lt_irrefl _ (this.trans_lt hn) end lemma exists_discrete_support (f : bounded_additive_measure α) : ∃ s : set α, s.countable ∧ (∀ t : set α, t.countable → f (t \ s) = 0) := begin rcases f.exists_discrete_support_nonpos with ⟨s₁, s₁_count, h₁⟩, rcases (-f).exists_discrete_support_nonpos with ⟨s₂, s₂_count, h₂⟩, refine ⟨s₁ ∪ s₂, s₁_count.union s₂_count, λ t ht, le_antisymm _ _⟩, { have : t \ (s₁ ∪ s₂) = (t \ (s₁ ∪ s₂)) \ s₁, by rw [diff_diff, union_comm, union_assoc, union_self], rw this, exact h₁ _ (ht.mono (diff_subset _ _)) }, { have : t \ (s₁ ∪ s₂) = (t \ (s₁ ∪ s₂)) \ s₂, by rw [diff_diff, union_assoc, union_self], rw this, simp only [neg_nonpos, neg_apply] at h₂, exact h₂ _ (ht.mono (diff_subset _ _)) }, end /-- A countable set outside of which the measure gives zero mass to countable sets. We are not claiming this set is unique, but we make an arbitrary choice of such a set. -/ def discrete_support (f : bounded_additive_measure α) : set α := (exists_discrete_support f).some lemma countable_discrete_support (f : bounded_additive_measure α) : f.discrete_support.countable := (exists_discrete_support f).some_spec.1 lemma apply_countable (f : bounded_additive_measure α) (t : set α) (ht : t.countable) : f (t \ f.discrete_support) = 0 := (exists_discrete_support f).some_spec.2 t ht /-- The discrete part of a bounded additive measure, obtained by restricting the measure to its countable support. -/ def discrete_part (f : bounded_additive_measure α) : bounded_additive_measure α := f.restrict f.discrete_support /-- The continuous part of a bounded additive measure, giving zero measure to every countable set. -/ def continuous_part (f : bounded_additive_measure α) : bounded_additive_measure α := f.restrict (univ \ f.discrete_support) lemma eq_add_parts (f : bounded_additive_measure α) (s : set α) : f s = f.discrete_part s + f.continuous_part s := begin simp only [discrete_part, continuous_part, restrict_apply], rw [← f.additive, ← inter_distrib_right], { simp only [union_univ, union_diff_self, univ_inter] }, { have : disjoint f.discrete_support (univ \ f.discrete_support) := disjoint_diff, exact this.mono (inter_subset_left _ _) (inter_subset_left _ _) } end lemma discrete_part_apply (f : bounded_additive_measure α) (s : set α) : f.discrete_part s = f (f.discrete_support ∩ s) := rfl lemma continuous_part_apply_eq_zero_of_countable (f : bounded_additive_measure α) (s : set α) (hs : s.countable) : f.continuous_part s = 0 := begin simp [continuous_part], convert f.apply_countable s hs using 2, ext x, simp [and_comm] end lemma continuous_part_apply_diff (f : bounded_additive_measure α) (s t : set α) (hs : s.countable) : f.continuous_part (t \ s) = f.continuous_part t := begin conv_rhs { rw ← diff_union_inter t s }, rw [additive, self_eq_add_right], { exact continuous_part_apply_eq_zero_of_countable _ _ (hs.mono (inter_subset_right _ _)) }, { exact disjoint.mono_right (inter_subset_right _ _) (disjoint.comm.1 disjoint_diff) }, end end bounded_additive_measure open bounded_additive_measure section /-! ### Relationship between continuous functionals and finitely additive measures. -/ lemma norm_indicator_le_one (s : set α) (x : α) : ∥(indicator s (1 : α → ℝ)) x∥ ≤ 1 := by { simp only [indicator, pi.one_apply], split_ifs; norm_num } /-- A functional in the dual space of bounded functions gives rise to a bounded additive measure, by applying the functional to the indicator functions. -/ def _root_.continuous_linear_map.to_bounded_additive_measure [topological_space α] [discrete_topology α] (f : (α →ᵇ ℝ) →L[ℝ] ℝ) : bounded_additive_measure α := { to_fun := λ s, f (of_normed_add_comm_group_discrete (indicator s 1) 1 (norm_indicator_le_one s)), additive' := λ s t hst, begin have : of_normed_add_comm_group_discrete (indicator (s ∪ t) 1) 1 (norm_indicator_le_one _) = of_normed_add_comm_group_discrete (indicator s 1) 1 (norm_indicator_le_one s) + of_normed_add_comm_group_discrete (indicator t 1) 1 (norm_indicator_le_one t), by { ext x, simp [indicator_union_of_disjoint hst], }, rw [this, f.map_add], end, exists_bound := ⟨∥f∥, λ s, begin have I : ∥of_normed_add_comm_group_discrete (indicator s 1) 1 (norm_indicator_le_one s)∥ ≤ 1, by apply norm_of_normed_add_comm_group_le _ zero_le_one, apply le_trans (f.le_op_norm _), simpa using mul_le_mul_of_nonneg_left I (norm_nonneg f), end⟩ } @[simp] lemma continuous_part_eval_clm_eq_zero [topological_space α] [discrete_topology α] (s : set α) (x : α) : (eval_clm ℝ x).to_bounded_additive_measure.continuous_part s = 0 := let f := (eval_clm ℝ x).to_bounded_additive_measure in calc f.continuous_part s = f.continuous_part (s \ {x}) : (continuous_part_apply_diff _ _ _ (countable_singleton x)).symm ... = f ((univ \ f.discrete_support) ∩ (s \ {x})) : rfl ... = indicator ((univ \ f.discrete_support) ∩ (s \ {x})) 1 x : rfl ... = 0 : by simp lemma to_functions_to_measure [measurable_space α] (μ : measure α) [is_finite_measure μ] (s : set α) (hs : measurable_set s) : μ.extension_to_bounded_functions.to_bounded_additive_measure s = (μ s).to_real := begin change μ.extension_to_bounded_functions (of_normed_add_comm_group_discrete (indicator s 1) 1 (norm_indicator_le_one s)) = (μ s).to_real, rw extension_to_bounded_functions_apply, { change ∫ x, s.indicator (λ y, (1 : ℝ)) x ∂μ = _, simp [integral_indicator hs] }, { change integrable (indicator s 1) μ, have : integrable (λ x, (1 : ℝ)) μ := integrable_const (1 : ℝ), apply this.mono' (measurable.indicator (@measurable_const _ _ _ _ (1 : ℝ)) hs).ae_strongly_measurable, apply filter.eventually_of_forall, exact norm_indicator_le_one _ } end lemma to_functions_to_measure_continuous_part [measurable_space α] [measurable_singleton_class α] (μ : measure α) [is_finite_measure μ] [has_no_atoms μ] (s : set α) (hs : measurable_set s) : μ.extension_to_bounded_functions.to_bounded_additive_measure.continuous_part s = (μ s).to_real := begin let f := μ.extension_to_bounded_functions.to_bounded_additive_measure, change f ((univ \ f.discrete_support) ∩ s) = (μ s).to_real, rw to_functions_to_measure, swap, { exact measurable_set.inter (measurable_set.univ.diff (countable.measurable_set f.countable_discrete_support)) hs }, congr' 1, rw [inter_comm, ← inter_diff_assoc, inter_univ], exact measure_diff_null (f.countable_discrete_support.measure_zero _) end end /-! ### A set in `ℝ²` large along verticals, small along horizontals We construct a subset of `ℝ²`, given as a family of sets, which is large along verticals (i.e., it only misses a countable set along each vertical) but small along horizontals (it is countable along horizontals). Such a set can not be measurable as it would contradict Fubini theorem. We need the continuum hypothesis to construct it. -/ theorem sierpinski_pathological_family (Hcont : #ℝ = aleph 1) : ∃ (f : ℝ → set ℝ), (∀ x, (univ \ f x).countable) ∧ (∀ y, {x : ℝ | y ∈ f x}.countable) := begin rcases cardinal.ord_eq ℝ with ⟨r, hr, H⟩, resetI, refine ⟨λ x, {y | r x y}, λ x, _, λ y, _⟩, { have : univ \ {y | r x y} = {y | r y x} ∪ {x}, { ext y, simp only [true_and, mem_univ, mem_set_of_eq, mem_insert_iff, union_singleton, mem_diff], rcases trichotomous_of r x y with h|rfl|h, { simp only [h, not_or_distrib, false_iff, not_true], split, { rintros rfl, exact irrefl_of r y h }, { exact asymm h } }, { simp only [true_or, eq_self_iff_true, iff_true], exact irrefl x }, { simp only [h, iff_true, or_true], exact asymm h } }, rw this, apply countable.union _ (countable_singleton _), rw [cardinal.countable_iff_lt_aleph_one, ← Hcont], exact cardinal.card_typein_lt r x H }, { rw [cardinal.countable_iff_lt_aleph_one, ← Hcont], exact cardinal.card_typein_lt r y H } end /-- A family of sets in `ℝ` which only miss countably many points, but such that any point is contained in only countably many of them. -/ def spf (Hcont : #ℝ = aleph 1) (x : ℝ) : set ℝ := (sierpinski_pathological_family Hcont).some x lemma countable_compl_spf (Hcont : #ℝ = aleph 1) (x : ℝ) : (univ \ spf Hcont x).countable := (sierpinski_pathological_family Hcont).some_spec.1 x lemma countable_spf_mem (Hcont : #ℝ = aleph 1) (y : ℝ) : {x | y ∈ spf Hcont x}.countable := (sierpinski_pathological_family Hcont).some_spec.2 y /-! ### A counterexample for the Pettis integral We construct a function `f` from `[0,1]` to a complete Banach space `B`, which is weakly measurable (i.e., for any continuous linear form `φ` on `B` the function `φ ∘ f` is measurable), bounded in norm (i.e., for all `x`, one has `∥f x∥ ≤ 1`), and still `f` has no Pettis integral. This construction, due to Phillips, requires the continuum hypothesis. We will take for `B` the space of all bounded functions on `ℝ`, with the supremum norm (no measure here, we are really talking of everywhere defined functions). And `f x` will be the characteristic function of a set which is large (it has countable complement), as in the Sierpinski pathological family. -/ /-- A family of bounded functions `f_x` from `ℝ` (seen with the discrete topology) to `ℝ` (in fact taking values in `{0, 1}`), indexed by a real parameter `x`, corresponding to the characteristic functions of the different fibers of the Sierpinski pathological family -/ def f (Hcont : #ℝ = aleph 1) (x : ℝ) : (discrete_copy ℝ →ᵇ ℝ) := of_normed_add_comm_group_discrete (indicator (spf Hcont x) 1) 1 (norm_indicator_le_one _) lemma apply_f_eq_continuous_part (Hcont : #ℝ = aleph 1) (φ : (discrete_copy ℝ →ᵇ ℝ) →L[ℝ] ℝ) (x : ℝ) (hx : φ.to_bounded_additive_measure.discrete_support ∩ spf Hcont x = ∅) : φ (f Hcont x) = φ.to_bounded_additive_measure.continuous_part univ := begin set ψ := φ.to_bounded_additive_measure with hψ, have : φ (f Hcont x) = ψ (spf Hcont x) := rfl, have U : univ = spf Hcont x ∪ (univ \ spf Hcont x), by simp only [union_univ, union_diff_self], rw [this, eq_add_parts, discrete_part_apply, hx, ψ.empty, zero_add, U, ψ.continuous_part.additive _ _ (disjoint_diff), ψ.continuous_part_apply_eq_zero_of_countable _ (countable_compl_spf Hcont x), add_zero], end lemma countable_ne (Hcont : #ℝ = aleph 1) (φ : (discrete_copy ℝ →ᵇ ℝ) →L[ℝ] ℝ) : {x | φ.to_bounded_additive_measure.continuous_part univ ≠ φ (f Hcont x)}.countable := begin have A : {x | φ.to_bounded_additive_measure.continuous_part univ ≠ φ (f Hcont x)} ⊆ {x | φ.to_bounded_additive_measure.discrete_support ∩ spf Hcont x ≠ ∅}, { assume x hx, contrapose! hx, simp only [not_not, mem_set_of_eq] at hx, simp [apply_f_eq_continuous_part Hcont φ x hx], }, have B : {x | φ.to_bounded_additive_measure.discrete_support ∩ spf Hcont x ≠ ∅} ⊆ ⋃ y ∈ φ.to_bounded_additive_measure.discrete_support, {x | y ∈ spf Hcont x}, { assume x hx, dsimp at hx, rw [← ne.def, ne_empty_iff_nonempty] at hx, simp only [exists_prop, mem_Union, mem_set_of_eq], exact hx }, apply countable.mono (subset.trans A B), exact countable.bUnion (countable_discrete_support _) (λ a ha, countable_spf_mem Hcont a), end lemma comp_ae_eq_const (Hcont : #ℝ = aleph 1) (φ : (discrete_copy ℝ →ᵇ ℝ) →L[ℝ] ℝ) : ∀ᵐ x ∂(volume.restrict (Icc (0 : ℝ) 1)), φ.to_bounded_additive_measure.continuous_part univ = φ (f Hcont x) := begin apply ae_restrict_of_ae, refine measure_mono_null _ ((countable_ne Hcont φ).measure_zero _), assume x, simp only [imp_self, mem_set_of_eq, mem_compl_eq], end lemma integrable_comp (Hcont : #ℝ = aleph 1) (φ : (discrete_copy ℝ →ᵇ ℝ) →L[ℝ] ℝ) : integrable_on (λ x, φ (f Hcont x)) (Icc 0 1) := begin have : integrable_on (λ x, φ.to_bounded_additive_measure.continuous_part univ) (Icc (0 : ℝ) 1) volume, by simp [integrable_on_const], apply integrable.congr this (comp_ae_eq_const Hcont φ), end lemma integral_comp (Hcont : #ℝ = aleph 1) (φ : (discrete_copy ℝ →ᵇ ℝ) →L[ℝ] ℝ) : ∫ x in Icc 0 1, φ (f Hcont x) = φ.to_bounded_additive_measure.continuous_part univ := begin rw ← integral_congr_ae (comp_ae_eq_const Hcont φ), simp, end /-! The next few statements show that the function `f Hcont : ℝ → (discrete_copy ℝ →ᵇ ℝ)` takes its values in a complete space, is scalarly measurable, is everywhere bounded by `1`, and still has no Pettis integral. -/ example : complete_space (discrete_copy ℝ →ᵇ ℝ) := by apply_instance /-- The function `f Hcont : ℝ → (discrete_copy ℝ →ᵇ ℝ)` is scalarly measurable. -/ lemma measurable_comp (Hcont : #ℝ = aleph 1) (φ : (discrete_copy ℝ →ᵇ ℝ) →L[ℝ] ℝ) : measurable (λ x, φ (f Hcont x)) := begin have : measurable (λ x, φ.to_bounded_additive_measure.continuous_part univ) := measurable_const, refine this.measurable_of_countable_ne _, exact countable_ne Hcont φ, end /-- The function `f Hcont : ℝ → (discrete_copy ℝ →ᵇ ℝ)` is uniformly bounded by `1` in norm. -/ lemma norm_bound (Hcont : #ℝ = aleph 1) (x : ℝ) : ∥f Hcont x∥ ≤ 1 := norm_of_normed_add_comm_group_le _ zero_le_one _ /-- The function `f Hcont : ℝ → (discrete_copy ℝ →ᵇ ℝ)` has no Pettis integral. -/ theorem no_pettis_integral (Hcont : #ℝ = aleph 1) : ¬ ∃ (g : discrete_copy ℝ →ᵇ ℝ), ∀ (φ : (discrete_copy ℝ →ᵇ ℝ) →L[ℝ] ℝ), ∫ x in Icc 0 1, φ (f Hcont x) = φ g := begin rintros ⟨g, h⟩, simp only [integral_comp] at h, have : g = 0, { ext x, have : g x = eval_clm ℝ x g := rfl, rw [this, ← h], simp }, simp only [this, continuous_linear_map.map_zero] at h, specialize h (volume.restrict (Icc (0 : ℝ) 1)).extension_to_bounded_functions, simp_rw [to_functions_to_measure_continuous_part _ _ measurable_set.univ] at h, simpa using h, end end phillips_1940
60b45f78dcefde605e7bd22425451bebf7819215
bb31430994044506fa42fd667e2d556327e18dfe
/src/topology/algebra/order/monotone_convergence.lean
f2c2e1bfbb0753248b13ae1bdf55f310fe6558f1
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
13,761
lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth, Yury Kudryashov -/ import topology.order.basic /-! # Bounded monotone sequences converge In this file we prove a few theorems of the form “if the range of a monotone function `f : ι → α` admits a least upper bound `a`, then `f x` tends to `a` as `x → ∞`”, as well as version of this statement for (conditionally) complete lattices that use `⨆ x, f x` instead of `is_lub`. These theorems work for linear orders with order topologies as well as their products (both in terms of `prod` and in terms of function types). In order to reduce code duplication, we introduce two typeclasses (one for the property formulated above and one for the dual property), prove theorems assuming one of these typeclasses, and provide instances for linear orders and their products. We also prove some "inverse" results: if `f n` is a monotone sequence and `a` is its limit, then `f n ≤ a` for all `n`. ## Tags monotone convergence -/ open filter set function open_locale filter topological_space classical variables {α β : Type*} /-- We say that `α` is a `Sup_convergence_class` if the following holds. Let `f : ι → α` be a monotone function, let `a : α` be a least upper bound of `set.range f`. Then `f x` tends to `𝓝 a` as `x → ∞` (formally, at the filter `filter.at_top`). We require this for `ι = (s : set α)`, `f = coe` in the definition, then prove it for any `f` in `tendsto_at_top_is_lub`. This property holds for linear orders with order topology as well as their products. -/ class Sup_convergence_class (α : Type*) [preorder α] [topological_space α] : Prop := (tendsto_coe_at_top_is_lub : ∀ (a : α) (s : set α), is_lub s a → tendsto (coe : s → α) at_top (𝓝 a)) /-- We say that `α` is an `Inf_convergence_class` if the following holds. Let `f : ι → α` be a monotone function, let `a : α` be a greatest lower bound of `set.range f`. Then `f x` tends to `𝓝 a` as `x → -∞` (formally, at the filter `filter.at_bot`). We require this for `ι = (s : set α)`, `f = coe` in the definition, then prove it for any `f` in `tendsto_at_bot_is_glb`. This property holds for linear orders with order topology as well as their products. -/ class Inf_convergence_class (α : Type*) [preorder α] [topological_space α] : Prop := (tendsto_coe_at_bot_is_glb : ∀ (a : α) (s : set α), is_glb s a → tendsto (coe : s → α) at_bot (𝓝 a)) instance order_dual.Sup_convergence_class [preorder α] [topological_space α] [Inf_convergence_class α] : Sup_convergence_class αᵒᵈ := ⟨‹Inf_convergence_class α›.1⟩ instance order_dual.Inf_convergence_class [preorder α] [topological_space α] [Sup_convergence_class α] : Inf_convergence_class αᵒᵈ := ⟨‹Sup_convergence_class α›.1⟩ @[priority 100] -- see Note [lower instance priority] instance linear_order.Sup_convergence_class [topological_space α] [linear_order α] [order_topology α] : Sup_convergence_class α := begin refine ⟨λ a s ha, tendsto_order.2 ⟨λ b hb, _, λ b hb, _⟩⟩, { rcases ha.exists_between hb with ⟨c, hcs, bc, bca⟩, lift c to s using hcs, refine (eventually_ge_at_top c).mono (λ x hx, bc.trans_le hx) }, { exact eventually_of_forall (λ x, (ha.1 x.2).trans_lt hb) } end @[priority 100] -- see Note [lower instance priority] instance linear_order.Inf_convergence_class [topological_space α] [linear_order α] [order_topology α] : Inf_convergence_class α := show Inf_convergence_class αᵒᵈᵒᵈ, from order_dual.Inf_convergence_class section variables {ι : Type*} [preorder ι] [topological_space α] section is_lub variables [preorder α] [Sup_convergence_class α] {f : ι → α} {a : α} lemma tendsto_at_top_is_lub (h_mono : monotone f) (ha : is_lub (set.range f) a) : tendsto f at_top (𝓝 a) := begin suffices : tendsto (range_factorization f) at_top at_top, from (Sup_convergence_class.tendsto_coe_at_top_is_lub _ _ ha).comp this, exact h_mono.range_factorization.tendsto_at_top_at_top (λ b, b.2.imp $ λ a ha, ha.ge) end lemma tendsto_at_bot_is_lub (h_anti : antitone f) (ha : is_lub (set.range f) a) : tendsto f at_bot (𝓝 a) := by convert tendsto_at_top_is_lub h_anti.dual_left ha end is_lub section is_glb variables [preorder α] [Inf_convergence_class α] {f : ι → α} {a : α} lemma tendsto_at_bot_is_glb (h_mono : monotone f) (ha : is_glb (set.range f) a) : tendsto f at_bot (𝓝 a) := by convert tendsto_at_top_is_lub h_mono.dual ha.dual lemma tendsto_at_top_is_glb (h_anti : antitone f) (ha : is_glb (set.range f) a) : tendsto f at_top (𝓝 a) := by convert tendsto_at_bot_is_lub h_anti.dual ha.dual end is_glb section csupr variables [conditionally_complete_lattice α] [Sup_convergence_class α] {f : ι → α} {a : α} lemma tendsto_at_top_csupr (h_mono : monotone f) (hbdd : bdd_above $ range f) : tendsto f at_top (𝓝 (⨆i, f i)) := begin casesI is_empty_or_nonempty ι, exacts [tendsto_of_is_empty, tendsto_at_top_is_lub h_mono (is_lub_csupr hbdd)] end lemma tendsto_at_bot_csupr (h_anti : antitone f) (hbdd : bdd_above $ range f) : tendsto f at_bot (𝓝 (⨆ i, f i)) := by convert tendsto_at_top_csupr h_anti.dual hbdd.dual end csupr section cinfi variables [conditionally_complete_lattice α] [Inf_convergence_class α] {f : ι → α} {a : α} lemma tendsto_at_bot_cinfi (h_mono : monotone f) (hbdd : bdd_below $ range f) : tendsto f at_bot (𝓝 (⨅ i, f i)) := by convert tendsto_at_top_csupr h_mono.dual hbdd.dual lemma tendsto_at_top_cinfi (h_anti : antitone f) (hbdd : bdd_below $ range f) : tendsto f at_top (𝓝 (⨅ i, f i)) := by convert tendsto_at_bot_csupr h_anti.dual hbdd.dual end cinfi section supr variables [complete_lattice α] [Sup_convergence_class α] {f : ι → α} {a : α} lemma tendsto_at_top_supr (h_mono : monotone f) : tendsto f at_top (𝓝 (⨆i, f i)) := tendsto_at_top_csupr h_mono (order_top.bdd_above _) lemma tendsto_at_bot_supr (h_anti : antitone f) : tendsto f at_bot (𝓝 (⨆i, f i)) := tendsto_at_bot_csupr h_anti (order_top.bdd_above _) end supr section infi variables [complete_lattice α] [Inf_convergence_class α] {f : ι → α} {a : α} lemma tendsto_at_bot_infi (h_mono : monotone f) : tendsto f at_bot (𝓝 (⨅i, f i)) := tendsto_at_bot_cinfi h_mono (order_bot.bdd_below _) lemma tendsto_at_top_infi (h_anti : antitone f) : tendsto f at_top (𝓝 (⨅i, f i)) := tendsto_at_top_cinfi h_anti (order_bot.bdd_below _) end infi end instance [preorder α] [preorder β] [topological_space α] [topological_space β] [Sup_convergence_class α] [Sup_convergence_class β] : Sup_convergence_class (α × β) := begin constructor, rintro ⟨a, b⟩ s h, rw [is_lub_prod, ← range_restrict, ← range_restrict] at h, have A : tendsto (λ x : s, (x : α × β).1) at_top (𝓝 a), from tendsto_at_top_is_lub (monotone_fst.restrict s) h.1, have B : tendsto (λ x : s, (x : α × β).2) at_top (𝓝 b), from tendsto_at_top_is_lub (monotone_snd.restrict s) h.2, convert A.prod_mk_nhds B, ext1 ⟨⟨x, y⟩, h⟩, refl end instance [preorder α] [preorder β] [topological_space α] [topological_space β] [Inf_convergence_class α] [Inf_convergence_class β] : Inf_convergence_class (α × β) := show Inf_convergence_class (αᵒᵈ × βᵒᵈ)ᵒᵈ, from order_dual.Inf_convergence_class instance {ι : Type*} {α : ι → Type*} [Π i, preorder (α i)] [Π i, topological_space (α i)] [Π i, Sup_convergence_class (α i)] : Sup_convergence_class (Π i, α i) := begin refine ⟨λ f s h, _⟩, simp only [is_lub_pi, ← range_restrict] at h, exact tendsto_pi_nhds.2 (λ i, tendsto_at_top_is_lub ((monotone_eval _).restrict _) (h i)) end instance {ι : Type*} {α : ι → Type*} [Π i, preorder (α i)] [Π i, topological_space (α i)] [Π i, Inf_convergence_class (α i)] : Inf_convergence_class (Π i, α i) := show Inf_convergence_class (Π i, (α i)ᵒᵈ)ᵒᵈ, from order_dual.Inf_convergence_class instance pi.Sup_convergence_class' {ι : Type*} [preorder α] [topological_space α] [Sup_convergence_class α] : Sup_convergence_class (ι → α) := pi.Sup_convergence_class instance pi.Inf_convergence_class' {ι : Type*} [preorder α] [topological_space α] [Inf_convergence_class α] : Inf_convergence_class (ι → α) := pi.Inf_convergence_class lemma tendsto_of_monotone {ι α : Type*} [preorder ι] [topological_space α] [conditionally_complete_linear_order α] [order_topology α] {f : ι → α} (h_mono : monotone f) : tendsto f at_top at_top ∨ (∃ l, tendsto f at_top (𝓝 l)) := if H : bdd_above (range f) then or.inr ⟨_, tendsto_at_top_csupr h_mono H⟩ else or.inl $ tendsto_at_top_at_top_of_monotone' h_mono H lemma tendsto_iff_tendsto_subseq_of_monotone {ι₁ ι₂ α : Type*} [semilattice_sup ι₁] [preorder ι₂] [nonempty ι₁] [topological_space α] [conditionally_complete_linear_order α] [order_topology α] [no_max_order α] {f : ι₂ → α} {φ : ι₁ → ι₂} {l : α} (hf : monotone f) (hg : tendsto φ at_top at_top) : tendsto f at_top (𝓝 l) ↔ tendsto (f ∘ φ) at_top (𝓝 l) := begin split; intro h, { exact h.comp hg }, { rcases tendsto_of_monotone hf with h' | ⟨l', hl'⟩, { exact (not_tendsto_at_top_of_tendsto_nhds h (h'.comp hg)).elim }, { rwa tendsto_nhds_unique h (hl'.comp hg) } } end /-! The next family of results, such as `is_lub_of_tendsto_at_top` and `supr_eq_of_tendsto`, are converses to the standard fact that bounded monotone functions converge. They state, that if a monotone function `f` tends to `a` along `filter.at_top`, then that value `a` is a least upper bound for the range of `f`. Related theorems above (`is_lub.is_lub_of_tendsto`, `is_glb.is_glb_of_tendsto` etc) cover the case when `f x` tends to `a` as `x` tends to some point `b` in the domain. -/ lemma monotone.ge_of_tendsto [topological_space α] [preorder α] [order_closed_topology α] [semilattice_sup β] {f : β → α} {a : α} (hf : monotone f) (ha : tendsto f at_top (𝓝 a)) (b : β) : f b ≤ a := begin haveI : nonempty β := nonempty.intro b, exact ge_of_tendsto ha ((eventually_ge_at_top b).mono (λ _ hxy, hf hxy)) end lemma monotone.le_of_tendsto [topological_space α] [preorder α] [order_closed_topology α] [semilattice_inf β] {f : β → α} {a : α} (hf : monotone f) (ha : tendsto f at_bot (𝓝 a)) (b : β) : a ≤ f b := hf.dual.ge_of_tendsto ha b lemma antitone.le_of_tendsto [topological_space α] [preorder α] [order_closed_topology α] [semilattice_sup β] {f : β → α} {a : α} (hf : antitone f) (ha : tendsto f at_top (𝓝 a)) (b : β) : a ≤ f b := hf.dual_right.ge_of_tendsto ha b lemma antitone.ge_of_tendsto [topological_space α] [preorder α] [order_closed_topology α] [semilattice_inf β] {f : β → α} {a : α} (hf : antitone f) (ha : tendsto f at_bot (𝓝 a)) (b : β) : f b ≤ a := hf.dual_right.le_of_tendsto ha b lemma is_lub_of_tendsto_at_top [topological_space α] [preorder α] [order_closed_topology α] [nonempty β] [semilattice_sup β] {f : β → α} {a : α} (hf : monotone f) (ha : tendsto f at_top (𝓝 a)) : is_lub (set.range f) a := begin split, { rintros _ ⟨b, rfl⟩, exact hf.ge_of_tendsto ha b }, { exact λ _ hb, le_of_tendsto' ha (λ x, hb (set.mem_range_self x)) } end lemma is_glb_of_tendsto_at_bot [topological_space α] [preorder α] [order_closed_topology α] [nonempty β] [semilattice_inf β] {f : β → α} {a : α} (hf : monotone f) (ha : tendsto f at_bot (𝓝 a)) : is_glb (set.range f) a := @is_lub_of_tendsto_at_top αᵒᵈ βᵒᵈ _ _ _ _ _ _ _ hf.dual ha lemma is_lub_of_tendsto_at_bot [topological_space α] [preorder α] [order_closed_topology α] [nonempty β] [semilattice_inf β] {f : β → α} {a : α} (hf : antitone f) (ha : tendsto f at_bot (𝓝 a)) : is_lub (set.range f) a := @is_lub_of_tendsto_at_top α βᵒᵈ _ _ _ _ _ _ _ hf.dual_left ha lemma is_glb_of_tendsto_at_top [topological_space α] [preorder α] [order_closed_topology α] [nonempty β] [semilattice_sup β] {f : β → α} {a : α} (hf : antitone f) (ha : tendsto f at_top (𝓝 a)) : is_glb (set.range f) a := @is_glb_of_tendsto_at_bot α βᵒᵈ _ _ _ _ _ _ _ hf.dual_left ha lemma supr_eq_of_tendsto {α β} [topological_space α] [complete_linear_order α] [order_topology α] [nonempty β] [semilattice_sup β] {f : β → α} {a : α} (hf : monotone f) : tendsto f at_top (𝓝 a) → supr f = a := tendsto_nhds_unique (tendsto_at_top_supr hf) lemma infi_eq_of_tendsto {α} [topological_space α] [complete_linear_order α] [order_topology α] [nonempty β] [semilattice_sup β] {f : β → α} {a : α} (hf : antitone f) : tendsto f at_top (𝓝 a) → infi f = a := tendsto_nhds_unique (tendsto_at_top_infi hf) lemma supr_eq_supr_subseq_of_monotone {ι₁ ι₂ α : Type*} [preorder ι₂] [complete_lattice α] {l : filter ι₁} [l.ne_bot] {f : ι₂ → α} {φ : ι₁ → ι₂} (hf : monotone f) (hφ : tendsto φ l at_top) : (⨆ i, f i) = (⨆ i, f (φ i)) := le_antisymm (supr_mono' $ λ i, exists_imp_exists (λ j (hj : i ≤ φ j), hf hj) (hφ.eventually $ eventually_ge_at_top i).exists) (supr_mono' $ λ i, ⟨φ i, le_rfl⟩) lemma infi_eq_infi_subseq_of_monotone {ι₁ ι₂ α : Type*} [preorder ι₂] [complete_lattice α] {l : filter ι₁} [l.ne_bot] {f : ι₂ → α} {φ : ι₁ → ι₂} (hf : monotone f) (hφ : tendsto φ l at_bot) : (⨅ i, f i) = (⨅ i, f (φ i)) := supr_eq_supr_subseq_of_monotone hf.dual hφ
3c352487ada7ad3035ca28865a5f61af52cda405
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/basics/unnamed_2007.lean
777165bfc46b76a2b197285ae4d6f2455af893e2
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
256
lean
import algebra.ordered_ring variables {R : Type*} [ordered_ring R] variables a b c : R -- BEGIN example : a ≤ b → 0 ≤ b - a := sorry example : 0 ≤ b - a → a ≤ b := sorry example (h : a ≤ b) (h' : 0 ≤ c) : a * c ≤ b * c := sorry -- END
7c9141695b87fe039dc029989aec032a70cd91d3
8b9f17008684d796c8022dab552e42f0cb6fb347
/library/data/list/as_type.lean
83ec2cc58cd44b510c97dc8ff99eec9e689a2019
[ "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
481
lean
/- Copyright (c) 2015 Leonardo de Moura. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: data.list.as_type Authors: Leonardo de Moura -/ import data.list.basic namespace list structure as_type {A : Type} (l : list A) : Type := (value : A) (is_member : value ∈ l) namespace as_type notation `⟪`:max l `⟫`:0 := as_type l definition lval {A : Type} (a : A) {l : list A} (m : a ∈ l) : ⟪l⟫ := mk a m end as_type end list
f8c6ef94a99fcc07dc80d2dd45eed175bd0841e5
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/normed_space/lp_equiv.lean
ce69795dbb0442c07bbad41d6ee13ea7593afa56
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
7,243
lean
/- Copyright (c) 2022 Jireh Loreaux. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jireh Loreaux -/ import analysis.normed_space.lp_space import analysis.normed_space.pi_Lp import topology.continuous_function.bounded /-! # Equivalences among $$L^p$$ spaces In this file we collect a variety of equivalences among various $$L^p$$ spaces. In particular, when `α` is a `fintype`, given `E : α → Type u` and `p : ℝ≥0∞`, there is a natural linear isometric equivalence `lp_pi_Lpₗᵢ : lp E p ≃ₗᵢ pi_Lp p E`. In addition, when `α` is a discrete topological space, the bounded continuous functions `α →ᵇ β` correspond exactly to `lp (λ _, β) ∞`. Here there can be more structure, including ring and algebra structures, and we implement these equivalences accordingly as well. We keep this as a separate file so that the various $$L^p$$ space files don't import the others. Recall that `pi_Lp` is just a type synonym for `Π i, E i` but given a different metric and norm structure, although the topological, uniform and bornological structures coincide definitionally. These structures are only defined on `pi_Lp` for `fintype α`, so there are no issues of convergence to consider. While `pre_lp` is also a type synonym for `Π i, E i`, it allows for infinite index types. On this type there is a predicate `mem_ℓp` which says that the relevant `p`-norm is finite and `lp E p` is the subtype of `pre_lp` satisfying `mem_ℓp`. ## TODO * Equivalence between `lp` and `measure_theory.Lp`, for `f : α → E` (i.e., functions rather than pi-types) and the counting measure on `α` -/ open_locale ennreal section lp_pi_Lp variables {α : Type*} {E : α → Type*} [Π i, normed_add_comm_group (E i)] {p : ℝ≥0∞} /-- When `α` is `finite`, every `f : pre_lp E p` satisfies `mem_ℓp f p`. -/ lemma mem_ℓp.all [finite α] (f : Π i, E i) : mem_ℓp f p := begin rcases p.trichotomy with (rfl | rfl | h), { exact mem_ℓp_zero_iff.mpr {i : α | f i ≠ 0}.to_finite, }, { exact mem_ℓp_infty_iff.mpr (set.finite.bdd_above (set.range (λ (i : α), ‖f i‖)).to_finite) }, { casesI nonempty_fintype α, exact mem_ℓp_gen ⟨finset.univ.sum _, has_sum_fintype _⟩ } end variables [fintype α] /-- The canonical `equiv` between `lp E p ≃ pi_Lp p E` when `E : α → Type u` with `[fintype α]`. -/ def equiv.lp_pi_Lp : lp E p ≃ pi_Lp p E := { to_fun := λ f, f, inv_fun := λ f, ⟨f, mem_ℓp.all f⟩, left_inv := λ f, lp.ext $ funext $ λ x, rfl, right_inv := λ f, funext $ λ x, rfl } lemma coe_equiv_lp_pi_Lp (f : lp E p) : equiv.lp_pi_Lp f = f := rfl lemma coe_equiv_lp_pi_Lp_symm (f : pi_Lp p E) : (equiv.lp_pi_Lp.symm f : Π i, E i) = f := rfl lemma equiv_lp_pi_Lp_norm (f : lp E p) : ‖equiv.lp_pi_Lp f‖ = ‖f‖ := begin unfreezingI { rcases p.trichotomy with (rfl | rfl | h) }, { rw [pi_Lp.norm_eq_card, lp.norm_eq_card_dsupport], refl }, { rw [pi_Lp.norm_eq_csupr, lp.norm_eq_csupr], refl }, { rw [pi_Lp.norm_eq_sum h, lp.norm_eq_tsum_rpow h, tsum_fintype], refl }, end /-- The canonical `add_equiv` between `lp E p` and `pi_Lp p E` when `E : α → Type u` with `[fintype α]` and `[fact (1 ≤ p)]`. -/ def add_equiv.lp_pi_Lp [fact (1 ≤ p)] : lp E p ≃+ pi_Lp p E := { map_add' := λ f g, rfl, .. equiv.lp_pi_Lp } lemma coe_add_equiv_lp_pi_Lp [fact (1 ≤ p)] (f : lp E p) : add_equiv.lp_pi_Lp f = f := rfl lemma coe_add_equiv_lp_pi_Lp_symm [fact (1 ≤ p)] (f : pi_Lp p E) : (add_equiv.lp_pi_Lp.symm f : Π i, E i) = f := rfl section equivₗᵢ variables (𝕜 : Type*) [nontrivially_normed_field 𝕜] [Π i, normed_space 𝕜 (E i)] /-- The canonical `linear_isometry_equiv` between `lp E p` and `pi_Lp p E` when `E : α → Type u` with `[fintype α]` and `[fact (1 ≤ p)]`. -/ noncomputable def lp_pi_Lpₗᵢ [fact (1 ≤ p)] : lp E p ≃ₗᵢ[𝕜] pi_Lp p E := { map_smul' := λ k f, rfl, norm_map' := equiv_lp_pi_Lp_norm, .. add_equiv.lp_pi_Lp } variables {𝕜} lemma coe_lp_pi_Lpₗᵢ [fact (1 ≤ p)] (f : lp E p) : lp_pi_Lpₗᵢ 𝕜 f = f := rfl lemma coe_lp_pi_Lpₗᵢ_symm [fact (1 ≤ p)] (f : pi_Lp p E) : ((lp_pi_Lpₗᵢ 𝕜).symm f : Π i, E i) = f := rfl end equivₗᵢ end lp_pi_Lp section lp_bcf open_locale bounded_continuous_function open bounded_continuous_function -- note: `R` and `A` are explicit because otherwise Lean has elaboration problems variables {α E : Type*} (R A 𝕜 : Type*) [topological_space α] [discrete_topology α] variables [normed_ring A] [norm_one_class A] [nontrivially_normed_field 𝕜] [normed_algebra 𝕜 A] variables [normed_add_comm_group E] [normed_space 𝕜 E] [non_unital_normed_ring R] section normed_add_comm_group /-- The canonical map between `lp (λ (_ : α), E) ∞` and `α →ᵇ E` as an `add_equiv`. -/ noncomputable def add_equiv.lp_bcf : lp (λ (_ : α), E) ∞ ≃+ (α →ᵇ E) := { to_fun := λ f, of_normed_add_comm_group_discrete f (‖f‖) $ le_csupr (mem_ℓp_infty_iff.mp f.prop), inv_fun := λ f, ⟨f, f.bdd_above_range_norm_comp⟩, left_inv := λ f, lp.ext rfl, right_inv := λ f, ext $ λ x, rfl, map_add' := λ f g, ext $ λ x, rfl } lemma coe_add_equiv_lp_bcf (f : lp (λ (_ : α), E) ∞) : (add_equiv.lp_bcf f : α → E) = f := rfl lemma coe_add_equiv_lp_bcf_symm (f : α →ᵇ E) : (add_equiv.lp_bcf.symm f : α → E) = f := rfl /-- The canonical map between `lp (λ (_ : α), E) ∞` and `α →ᵇ E` as a `linear_isometry_equiv`. -/ noncomputable def lp_bcfₗᵢ : lp (λ (_ : α), E) ∞ ≃ₗᵢ[𝕜] (α →ᵇ E) := { map_smul' := λ k f, rfl, norm_map' := λ f, by { simp only [norm_eq_supr_norm, lp.norm_eq_csupr], refl }, .. add_equiv.lp_bcf } variables {𝕜} lemma coe_lp_bcfₗᵢ (f : lp (λ (_ : α), E) ∞) : (lp_bcfₗᵢ 𝕜 f : α → E) = f := rfl lemma coe_lp_bcfₗᵢ_symm (f : α →ᵇ E) : ((lp_bcfₗᵢ 𝕜).symm f : α → E) = f := rfl end normed_add_comm_group section ring_algebra /-- The canonical map between `lp (λ (_ : α), R) ∞` and `α →ᵇ R` as a `ring_equiv`. -/ noncomputable def ring_equiv.lp_bcf : lp (λ (_ : α), R) ∞ ≃+* (α →ᵇ R) := { map_mul' := λ f g, ext $ λ x, rfl, .. @add_equiv.lp_bcf _ R _ _ _ } variables {R} lemma coe_ring_equiv_lp_bcf (f : lp (λ (_ : α), R) ∞) : (ring_equiv.lp_bcf R f : α → R) = f := rfl lemma coe_ring_equiv_lp_bcf_symm (f : α →ᵇ R) : ((ring_equiv.lp_bcf R).symm f : α → R) = f := rfl variables (α) -- even `α` needs to be explicit here for elaboration -- the `norm_one_class A` shouldn't really be necessary, but currently it is for -- `one_mem_ℓp_infty` to get the `ring` instance on `lp`. /-- The canonical map between `lp (λ (_ : α), A) ∞` and `α →ᵇ A` as an `alg_equiv`. -/ noncomputable def alg_equiv.lp_bcf : lp (λ (_ : α), A) ∞ ≃ₐ[𝕜] (α →ᵇ A) := { commutes' := λ k, rfl, .. ring_equiv.lp_bcf A } variables {α A 𝕜} lemma coe_alg_equiv_lp_bcf (f : lp (λ (_ : α), A) ∞) : (alg_equiv.lp_bcf α A 𝕜 f : α → A) = f := rfl lemma coe_alg_equiv_lp_bcf_symm (f : α →ᵇ A) : ((alg_equiv.lp_bcf α A 𝕜).symm f : α → A) = f := rfl end ring_algebra end lp_bcf
da0850cc1e4fe37b789399c54cae31f2ec3a3a99
968e2f50b755d3048175f176376eff7139e9df70
/examples/pred_logic/unnamed_744.lean
01c232103e795c6400ec8aa15a94fe4f17bbb4f0
[]
no_license
gihanmarasingha/mth1001_sphinx
190a003269ba5e54717b448302a27ca26e31d491
05126586cbf5786e521be1ea2ef5b4ba3c44e74a
refs/heads/master
1,672,913,933,677
1,604,516,583,000
1,604,516,583,000
309,245,750
1
0
null
null
null
null
UTF-8
Lean
false
false
112
lean
def even (a : ℕ) := ∃ b, a = 2 * b example (h : 10 = 2 * 5) : even 10 := begin exact exists.intro 5 h end
a468526c6c5da7140ed15b1bb93f7944b251d964
1abd1ed12aa68b375cdef28959f39531c6e95b84
/src/analysis/special_functions/log.lean
9f6414056def940b9a6bc3d1165591c1262bae2e
[ "Apache-2.0" ]
permissive
jumpy4/mathlib
d3829e75173012833e9f15ac16e481e17596de0f
af36f1a35f279f0e5b3c2a77647c6bf2cfd51a13
refs/heads/master
1,693,508,842,818
1,636,203,271,000
1,636,203,271,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,305
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 -/ import analysis.special_functions.exp /-! # Real logarithm In this file we define `real.log` to be the logarithm of a real number. As usual, we extend it from its domain `(0, +∞)` to a globally defined function. We choose to do it so that `log 0 = 0` and `log (-x) = log x`. We prove some basic properties of this function and show that it is continuous. ## Tags logarithm, continuity -/ open set filter function open_locale topological_space noncomputable theory namespace real variables {x y : ℝ} /-- The real logarithm function, equal to the inverse of the exponential for `x > 0`, to `log |x|` for `x < 0`, and to `0` for `0`. We use this unconventional extension to `(-∞, 0]` as it gives the formula `log (x * y) = log x + log y` for all nonzero `x` and `y`, and the derivative of `log` is `1/x` away from `0`. -/ @[pp_nodot] noncomputable def log (x : ℝ) : ℝ := if hx : x = 0 then 0 else exp_order_iso.symm ⟨|x|, abs_pos.2 hx⟩ lemma log_of_ne_zero (hx : x ≠ 0) : log x = exp_order_iso.symm ⟨|x|, abs_pos.2 hx⟩ := dif_neg hx lemma log_of_pos (hx : 0 < x) : log x = exp_order_iso.symm ⟨x, hx⟩ := by { rw [log_of_ne_zero hx.ne'], congr, exact abs_of_pos hx } lemma exp_log_eq_abs (hx : x ≠ 0) : exp (log x) = |x| := by rw [log_of_ne_zero hx, ← coe_exp_order_iso_apply, order_iso.apply_symm_apply, subtype.coe_mk] lemma exp_log (hx : 0 < x) : exp (log x) = x := by { rw exp_log_eq_abs hx.ne', exact abs_of_pos hx } lemma exp_log_of_neg (hx : x < 0) : exp (log x) = -x := by { rw exp_log_eq_abs (ne_of_lt hx), exact abs_of_neg hx } @[simp] lemma log_exp (x : ℝ) : log (exp x) = x := exp_injective $ exp_log (exp_pos x) lemma surj_on_log : surj_on log (Ioi 0) univ := λ x _, ⟨exp x, exp_pos x, log_exp x⟩ lemma log_surjective : surjective log := λ x, ⟨exp x, log_exp x⟩ @[simp] lemma range_log : range log = univ := log_surjective.range_eq @[simp] lemma log_zero : log 0 = 0 := dif_pos rfl @[simp] lemma log_one : log 1 = 0 := exp_injective $ by rw [exp_log zero_lt_one, exp_zero] @[simp] lemma log_abs (x : ℝ) : log (|x|) = log x := begin by_cases h : x = 0, { simp [h] }, { rw [← exp_eq_exp, exp_log_eq_abs h, exp_log_eq_abs (abs_pos.2 h).ne', abs_abs] } end @[simp] lemma log_neg_eq_log (x : ℝ) : log (-x) = log x := by rw [← log_abs x, ← log_abs (-x), abs_neg] lemma surj_on_log' : surj_on log (Iio 0) univ := λ x _, ⟨-exp x, neg_lt_zero.2 $ exp_pos x, by rw [log_neg_eq_log, log_exp]⟩ lemma log_mul (hx : x ≠ 0) (hy : y ≠ 0) : log (x * y) = log x + log y := exp_injective $ by rw [exp_log_eq_abs (mul_ne_zero hx hy), exp_add, exp_log_eq_abs hx, exp_log_eq_abs hy, abs_mul] lemma log_div (hx : x ≠ 0) (hy : y ≠ 0) : log (x / y) = log x - log y := exp_injective $ by rw [exp_log_eq_abs (div_ne_zero hx hy), exp_sub, exp_log_eq_abs hx, exp_log_eq_abs hy, abs_div] @[simp] lemma log_inv (x : ℝ) : log (x⁻¹) = -log x := begin by_cases hx : x = 0, { simp [hx] }, rw [← exp_eq_exp, exp_log_eq_abs (inv_ne_zero hx), exp_neg, exp_log_eq_abs hx, abs_inv] end lemma log_le_log (h : 0 < x) (h₁ : 0 < y) : real.log x ≤ real.log y ↔ x ≤ y := by rw [← exp_le_exp, exp_log h, exp_log h₁] lemma log_lt_log (hx : 0 < x) : x < y → log x < log y := by { intro h, rwa [← exp_lt_exp, exp_log hx, exp_log (lt_trans hx h)] } lemma log_lt_log_iff (hx : 0 < x) (hy : 0 < y) : log x < log y ↔ x < y := by { rw [← exp_lt_exp, exp_log hx, exp_log hy] } lemma log_pos_iff (hx : 0 < x) : 0 < log x ↔ 1 < x := by { rw ← log_one, exact log_lt_log_iff zero_lt_one hx } lemma log_pos (hx : 1 < x) : 0 < log x := (log_pos_iff (lt_trans zero_lt_one hx)).2 hx lemma log_neg_iff (h : 0 < x) : log x < 0 ↔ x < 1 := by { rw ← log_one, exact log_lt_log_iff h zero_lt_one } lemma log_neg (h0 : 0 < x) (h1 : x < 1) : log x < 0 := (log_neg_iff h0).2 h1 lemma log_nonneg_iff (hx : 0 < x) : 0 ≤ log x ↔ 1 ≤ x := by rw [← not_lt, log_neg_iff hx, not_lt] lemma log_nonneg (hx : 1 ≤ x) : 0 ≤ log x := (log_nonneg_iff (zero_lt_one.trans_le hx)).2 hx lemma log_nonpos_iff (hx : 0 < x) : log x ≤ 0 ↔ x ≤ 1 := by rw [← not_lt, log_pos_iff hx, not_lt] lemma log_nonpos_iff' (hx : 0 ≤ x) : log x ≤ 0 ↔ x ≤ 1 := begin rcases hx.eq_or_lt with (rfl|hx), { simp [le_refl, zero_le_one] }, exact log_nonpos_iff hx end lemma log_nonpos (hx : 0 ≤ x) (h'x : x ≤ 1) : log x ≤ 0 := (log_nonpos_iff' hx).2 h'x lemma strict_mono_on_log : strict_mono_on log (set.Ioi 0) := λ x hx y hy hxy, log_lt_log hx hxy lemma strict_anti_on_log : strict_anti_on log (set.Iio 0) := begin rintros x (hx : x < 0) y (hy : y < 0) hxy, rw [← log_abs y, ← log_abs x], refine log_lt_log (abs_pos.2 hy.ne) _, rwa [abs_of_neg hy, abs_of_neg hx, neg_lt_neg_iff] end lemma log_inj_on_pos : set.inj_on log (set.Ioi 0) := strict_mono_on_log.inj_on lemma eq_one_of_pos_of_log_eq_zero {x : ℝ} (h₁ : 0 < x) (h₂ : log x = 0) : x = 1 := log_inj_on_pos (set.mem_Ioi.2 h₁) (set.mem_Ioi.2 zero_lt_one) (h₂.trans real.log_one.symm) lemma log_ne_zero_of_pos_of_ne_one {x : ℝ} (hx_pos : 0 < x) (hx : x ≠ 1) : log x ≠ 0 := mt (eq_one_of_pos_of_log_eq_zero hx_pos) hx @[simp] lemma log_eq_zero {x : ℝ} : log x = 0 ↔ x = 0 ∨ x = 1 ∨ x = -1 := begin split, { intros h, rcases lt_trichotomy x 0 with x_lt_zero | rfl | x_gt_zero, { refine or.inr (or.inr (eq_neg_iff_eq_neg.mp _)), rw [←log_neg_eq_log x] at h, exact (eq_one_of_pos_of_log_eq_zero (neg_pos.mpr x_lt_zero) h).symm, }, { exact or.inl rfl }, { exact or.inr (or.inl (eq_one_of_pos_of_log_eq_zero x_gt_zero h)), }, }, { rintro (rfl|rfl|rfl); simp only [log_one, log_zero, log_neg_eq_log], } end /-- The real logarithm function tends to `+∞` at `+∞`. -/ lemma tendsto_log_at_top : tendsto log at_top at_top := tendsto_comp_exp_at_top.1 $ by simpa only [log_exp] using tendsto_id lemma tendsto_log_nhds_within_zero : tendsto log (𝓝[{0}ᶜ] 0) at_bot := begin rw [← (show _ = log, from funext log_abs)], refine tendsto.comp _ tendsto_abs_nhds_within_zero, simpa [← tendsto_comp_exp_at_bot] using tendsto_id end lemma continuous_on_log : continuous_on log {0}ᶜ := begin rw [continuous_on_iff_continuous_restrict, restrict], conv in (log _) { rw [log_of_ne_zero (show (x : ℝ) ≠ 0, from x.2)] }, exact exp_order_iso.symm.continuous.comp (continuous_subtype_mk _ continuous_subtype_coe.norm) end @[continuity] lemma continuous_log : continuous (λ x : {x : ℝ // x ≠ 0}, log x) := continuous_on_iff_continuous_restrict.1 $ continuous_on_log.mono $ λ x hx, hx @[continuity] lemma continuous_log' : continuous (λ x : {x : ℝ // 0 < x}, log x) := continuous_on_iff_continuous_restrict.1 $ continuous_on_log.mono $ λ x hx, ne_of_gt hx lemma continuous_at_log (hx : x ≠ 0) : continuous_at log x := (continuous_on_log x hx).continuous_at $ is_open.mem_nhds is_open_compl_singleton hx @[simp] lemma continuous_at_log_iff : continuous_at log x ↔ x ≠ 0 := begin refine ⟨_, continuous_at_log⟩, rintros h rfl, exact not_tendsto_nhds_of_tendsto_at_bot tendsto_log_nhds_within_zero _ (h.tendsto.mono_left inf_le_left) end end real section continuity open real variables {α : Type*} lemma filter.tendsto.log {f : α → ℝ} {l : filter α} {x : ℝ} (h : tendsto f l (𝓝 x)) (hx : x ≠ 0) : tendsto (λ x, log (f x)) l (𝓝 (log x)) := (continuous_at_log hx).tendsto.comp h variables [topological_space α] {f : α → ℝ} {s : set α} {a : α} lemma continuous.log (hf : continuous f) (h₀ : ∀ x, f x ≠ 0) : continuous (λ x, log (f x)) := continuous_on_log.comp_continuous hf h₀ lemma continuous_at.log (hf : continuous_at f a) (h₀ : f a ≠ 0) : continuous_at (λ x, log (f x)) a := hf.log h₀ lemma continuous_within_at.log (hf : continuous_within_at f s a) (h₀ : f a ≠ 0) : continuous_within_at (λ x, log (f x)) s a := hf.log h₀ lemma continuous_on.log (hf : continuous_on f s) (h₀ : ∀ x ∈ s, f x ≠ 0) : continuous_on (λ x, log (f x)) s := λ x hx, (hf x hx).log (h₀ x hx) end continuity
33693f2c58060e703a73ab0db93136e5a5301bad
5d166a16ae129621cb54ca9dde86c275d7d2b483
/tests/lean/run/mk_dec_eq_instance_indices.lean
d7eaf2a492ab0990548f8ae7afa479d4f6f9e72d
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
666
lean
open tactic namespace X1 inductive Foo : unit -> Type | mk : Foo () -> Foo () instance (u : unit) : decidable_eq (Foo u) := by mk_dec_eq_instance end X1 namespace X2 inductive Foo : bool -> bool -> Type | mk₁ : Foo tt tt | mk₂ : Foo ff ff -> Foo tt ff instance (idx₁ idx₂ : bool) : decidable_eq (Foo idx₁ idx₂) := by mk_dec_eq_instance end X2 namespace X3 constants (C : nat -> Type) constants (c : Pi (n : nat), C n) inductive Foo : Pi (n : nat), C n -> Type | mk₁ : Pi (n : nat), Foo n (c n) -> Foo (n+1) (c (n+1)) | mk₂ : Foo 0 (c 0) noncomputable instance (n : nat) (c : C n) : decidable_eq (Foo n c) := by mk_dec_eq_instance end X3
e2cd151c57d7e763c82a2006464f50a14dc62cab
4727251e0cd73359b15b664c3170e5d754078599
/src/category_theory/linear/default.lean
ea1e87f9ee9dd1f14aab46bf01cc4ad48d6552fa
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
4,416
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 category_theory.preadditive import algebra.module.linear_map import algebra.invertible import linear_algebra.basic import algebra.algebra.basic /-! # Linear categories An `R`-linear category is a category in which `X ⟶ Y` is an `R`-module in such a way that composition of morphisms is `R`-linear in both variables. Note that sometimes in the literature a "linear category" is further required to be abelian. ## Implementation Corresponding to the fact that we need to have an `add_comm_group X` structure in place to talk about a `module R X` structure, we need `preadditive C` as a prerequisite typeclass for `linear R C`. This makes for longer signatures than would be ideal. ## Future work It would be nice to have a usable framework of enriched categories in which this just became a category enriched in `Module R`. -/ universes w v u open category_theory.limits open linear_map namespace category_theory /-- A category is called `R`-linear if `P ⟶ Q` is an `R`-module such that composition is `R`-linear in both variables. -/ class linear (R : Type w) [semiring R] (C : Type u) [category.{v} C] [preadditive C] := (hom_module : Π X Y : C, module R (X ⟶ Y) . tactic.apply_instance) (smul_comp' : ∀ (X Y Z : C) (r : R) (f : X ⟶ Y) (g : Y ⟶ Z), (r • f) ≫ g = r • (f ≫ g) . obviously) (comp_smul' : ∀ (X Y Z : C) (f : X ⟶ Y) (r : R) (g : Y ⟶ Z), f ≫ (r • g) = r • (f ≫ g) . obviously) attribute [instance] linear.hom_module restate_axiom linear.smul_comp' restate_axiom linear.comp_smul' attribute [simp,reassoc] linear.smul_comp attribute [reassoc, simp] linear.comp_smul -- (the linter doesn't like `simp` on the `_assoc` lemma) end category_theory open category_theory namespace category_theory.linear variables {C : Type u} [category.{v} C] [preadditive C] instance preadditive_nat_linear : linear ℕ C := { smul_comp' := λ X Y Z r f g, (preadditive.right_comp X g).map_nsmul f r, comp_smul' := λ X Y Z f r g, (preadditive.left_comp Z f).map_nsmul g r, } instance preadditive_int_linear : linear ℤ C := { smul_comp' := λ X Y Z r f g, (preadditive.right_comp X g).map_zsmul f r, comp_smul' := λ X Y Z f r g, (preadditive.left_comp Z f).map_zsmul g r, } section End variables {R : Type w} [comm_ring R] [linear R C] instance (X : C) : module R (End X) := by { dsimp [End], apply_instance, } instance (X : C) : algebra R (End X) := algebra.of_module (λ r f g, comp_smul _ _ _ _ _ _) (λ r f g, smul_comp _ _ _ _ _ _) end End section variables {R : Type w} [semiring R] [linear R C] section induced_category universes u' variables {C} {D : Type u'} (F : D → C) instance induced_category.category : linear.{w v} R (induced_category C F) := { hom_module := λ X Y, @linear.hom_module R _ C _ _ _ (F X) (F Y), smul_comp' := λ P Q R f f' g, smul_comp' _ _ _ _ _ _, comp_smul' := λ P Q R f g g', comp_smul' _ _ _ _ _ _, } end induced_category variables (R) /-- Composition by a fixed left argument as an `R`-linear map. -/ @[simps] def left_comp {X Y : C} (Z : C) (f : X ⟶ Y) : (Y ⟶ Z) →ₗ[R] (X ⟶ Z) := { to_fun := λ g, f ≫ g, map_add' := by simp, map_smul' := by simp, } /-- Composition by a fixed right argument as an `R`-linear map. -/ @[simps] def right_comp (X : C) {Y Z : C} (g : Y ⟶ Z) : (X ⟶ Y) →ₗ[R] (X ⟶ Z) := { to_fun := λ f, f ≫ g, map_add' := by simp, map_smul' := by simp, } instance {X Y : C} (f : X ⟶ Y) [epi f] (r : R) [invertible r] : epi (r • f) := ⟨λ R g g' H, begin rw [smul_comp, smul_comp, ←comp_smul, ←comp_smul, cancel_epi] at H, simpa [smul_smul] using congr_arg (λ f, ⅟r • f) H, end⟩ instance {X Y : C} (f : X ⟶ Y) [mono f] (r : R) [invertible r] : mono (r • f) := ⟨λ R g g' H, begin rw [comp_smul, comp_smul, ←smul_comp, ←smul_comp, cancel_mono] at H, simpa [smul_smul] using congr_arg (λ f, ⅟r • f) H, end⟩ end section variables {S : Type w} [comm_semiring S] [linear S C] /-- Composition as a bilinear map. -/ @[simps] def comp (X Y Z : C) : (X ⟶ Y) →ₗ[S] ((Y ⟶ Z) →ₗ[S] (X ⟶ Z)) := { to_fun := λ f, left_comp S Z f, map_add' := by { intros, ext, simp, }, map_smul' := by { intros, ext, simp, }, } end end category_theory.linear
e1258d29f805b8eeb210ef57bb6b2b57465048f7
94e33a31faa76775069b071adea97e86e218a8ee
/src/topology/continuous_function/basic.lean
20ccb6ea930bad75c9b1eaf81f387208c6f96e5f
[ "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
10,628
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri -/ import data.set.Union_lift import topology.homeomorph /-! # Continuous bundled maps In this file we define the type `continuous_map` of continuous bundled maps. We use the `fun_like` design, so each type of morphisms has a companion typeclass which is meant to be satisfied by itself and all stricter types. -/ open function /-- The type of continuous maps from `α` to `β`. When possible, instead of parametrizing results over `(f : C(α, β))`, you should parametrize over `{F : Type*} [continuous_map_class F α β] (f : F)`. When you extend this structure, make sure to extend `continuous_map_class`. -/ @[protect_proj] structure continuous_map (α β : Type*) [topological_space α] [topological_space β] := (to_fun : α → β) (continuous_to_fun : continuous to_fun . tactic.interactive.continuity') notation `C(` α `, ` β `)` := continuous_map α β /-- `continuous_map_class F α β` states that `F` is a type of continuous maps. You should extend this class when you extend `continuous_map`. -/ class continuous_map_class (F : Type*) (α β : out_param $ Type*) [topological_space α] [topological_space β] extends fun_like F α (λ _, β) := (map_continuous (f : F) : continuous f) export continuous_map_class (map_continuous) attribute [continuity] map_continuous section continuous_map_class variables {F α β : Type*} [topological_space α] [topological_space β] [continuous_map_class F α β] include β lemma map_continuous_at (f : F) (a : α) : continuous_at f a := (map_continuous f).continuous_at lemma map_continuous_within_at (f : F) (s : set α) (a : α) : continuous_within_at f s a := (map_continuous f).continuous_within_at instance : has_coe_t F C(α, β) := ⟨λ f, { to_fun := f, continuous_to_fun := map_continuous f }⟩ end continuous_map_class /-! ### Continuous maps-/ namespace continuous_map variables {α β γ δ : Type*} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] instance : continuous_map_class C(α, β) α β := { coe := continuous_map.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_continuous := continuous_map.continuous_to_fun } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (C(α, β)) (λ _, α → β) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : C(α, β)} : f.to_fun = (f : α → β) := rfl -- this must come after the coe_to_fun definition initialize_simps_projections continuous_map (to_fun → apply) @[ext] lemma ext {f g : C(α, β)} (h : ∀ a, f a = g a) : f = g := fun_like.ext _ _ h /-- Copy of a `continuous_map` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : C(α, β)) (f' : α → β) (h : f' = f) : C(α, β) := { to_fun := f', continuous_to_fun := h.symm ▸ f.continuous_to_fun } variables {α β} {f g : C(α, β)} /-- Deprecated. Use `map_continuous` instead. -/ protected lemma continuous (f : C(α, β)) : continuous f := f.continuous_to_fun @[continuity] lemma continuous_set_coe (s : set C(α, β)) (f : s) : continuous f := f.1.continuous /-- Deprecated. Use `map_continuous_at` instead. -/ protected lemma continuous_at (f : C(α, β)) (x : α) : continuous_at f x := f.continuous.continuous_at /-- Deprecated. Use `fun_like.congr_fun` instead. -/ protected lemma congr_fun {f g : C(α, β)} (H : f = g) (x : α) : f x = g x := H ▸ rfl /-- Deprecated. Use `fun_like.congr_arg` instead. -/ protected lemma congr_arg (f : C(α, β)) {x y : α} (h : x = y) : f x = f y := h ▸ rfl lemma coe_injective : @function.injective (C(α, β)) (α → β) coe_fn := λ f g h, by cases f; cases g; congr' @[simp] lemma coe_mk (f : α → β) (h : continuous f) : ⇑(⟨f, h⟩ : C(α, β)) = f := rfl lemma map_specializes (f : C(α, β)) {x y : α} (h : x ⤳ y) : f x ⤳ f y := h.map f.2 section variables (α β) /-- The continuous functions from `α` to `β` are the same as the plain functions when `α` is discrete. -/ @[simps] def equiv_fn_of_discrete [discrete_topology α] : C(α, β) ≃ (α → β) := ⟨(λ f, f), (λ f, ⟨f, continuous_of_discrete_topology⟩), λ f, by { ext, refl, }, λ f, by { ext, refl, }⟩ end variables (α) /-- The identity as a continuous map. -/ protected def id : C(α, α) := ⟨id⟩ @[simp] lemma coe_id : ⇑(continuous_map.id α) = id := rfl /-- The constant map as a continuous map. -/ def const (b : β) : C(α, β) := ⟨const α b⟩ @[simp] lemma coe_const (b : β) : ⇑(const α b) = function.const α b := rfl instance [inhabited β] : inhabited C(α, β) := ⟨const α default⟩ variables {α} @[simp] lemma id_apply (a : α) : continuous_map.id α a = a := rfl @[simp] lemma const_apply (b : β) (a : α) : const α b a = b := rfl /-- The composition of continuous maps, as a continuous map. -/ def comp (f : C(β, γ)) (g : C(α, β)) : C(α, γ) := ⟨f ∘ g⟩ @[simp] lemma coe_comp (f : C(β, γ)) (g : C(α, β)) : ⇑(comp f g) = f ∘ g := rfl @[simp] lemma comp_apply (f : C(β, γ)) (g : C(α, β)) (a : α) : comp f g a = f (g a) := rfl @[simp] lemma comp_assoc (f : C(γ, δ)) (g : C(β, γ)) (h : C(α, β)) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma id_comp (f : C(α, β)) : (continuous_map.id _).comp f = f := ext $ λ _, rfl @[simp] lemma comp_id (f : C(α, β)) : f.comp (continuous_map.id _) = f := ext $ λ _, rfl @[simp] lemma const_comp (c : γ) (f : C(α, β)) : (const β c).comp f = const α c := ext $ λ _, rfl @[simp] lemma comp_const (f : C(β, γ)) (b : β) : f.comp (const α b) = const α (f b) := ext $ λ _, rfl lemma cancel_right {f₁ f₂ : C(β, γ)} {g : C(α, β)} (hg : surjective g) : f₁.comp g = f₂.comp g ↔ f₁ = f₂ := ⟨λ h, ext $ hg.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {f : C(β, γ)} {g₁ g₂ : C(α, β)} (hf : injective f) : f.comp g₁ = f.comp g₂ ↔ g₁ = g₂ := ⟨λ h, ext $ λ a, hf $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ instance [nonempty α] [nontrivial β] : nontrivial C(α, β) := ⟨let ⟨b₁, b₂, hb⟩ := exists_pair_ne β in ⟨const _ b₁, const _ b₂, λ h, hb $ fun_like.congr_fun h $ classical.arbitrary α⟩⟩ section prod variables {α₁ α₂ β₁ β₂ : Type*} [topological_space α₁] [topological_space α₂] [topological_space β₁] [topological_space β₂] /-- Given two continuous maps `f` and `g`, this is the continuous map `x ↦ (f x, g x)`. -/ def prod_mk (f : C(α, β₁)) (g : C(α, β₂)) : C(α, β₁ × β₂) := { to_fun := (λ x, (f x, g x)), continuous_to_fun := continuous.prod_mk f.continuous g.continuous } /-- Given two continuous maps `f` and `g`, this is the continuous map `(x, y) ↦ (f x, g y)`. -/ def prod_map (f : C(α₁, α₂)) (g : C(β₁, β₂)) : C(α₁ × β₁, α₂ × β₂) := { to_fun := prod.map f g, continuous_to_fun := continuous.prod_map f.continuous g.continuous } @[simp] lemma prod_eval (f : C(α, β₁)) (g : C(α, β₂)) (a : α) : (prod_mk f g) a = (f a, g a) := rfl end prod section pi variables {I A : Type*} {X : I → Type*} [topological_space A] [∀ i, topological_space (X i)] /-- Abbreviation for product of continuous maps, which is continuous -/ def pi (f : Π i, C(A, X i)) : C(A, Π i, X i) := { to_fun := λ (a : A) (i : I), f i a, } @[simp] lemma pi_eval (f : Π i, C(A, X i)) (a : A) : (pi f) a = λ i : I, (f i) a := rfl end pi section restrict variables (s : set α) /-- The restriction of a continuous function `α → β` to a subset `s` of `α`. -/ def restrict (f : C(α, β)) : C(s, β) := ⟨f ∘ coe⟩ @[simp] lemma coe_restrict (f : C(α, β)) : ⇑(f.restrict s) = f ∘ coe := rfl end restrict section gluing variables {ι : Type*} (S : ι → set α) (φ : Π i : ι, C(S i, β)) (hφ : ∀ i j (x : α) (hxi : x ∈ S i) (hxj : x ∈ S j), φ i ⟨x, hxi⟩ = φ j ⟨x, hxj⟩) (hS : ∀ x : α, ∃ i, S i ∈ nhds x) include hφ hS /-- A family `φ i` of continuous maps `C(S i, β)`, where the domains `S i` contain a neighbourhood of each point in `α` and the functions `φ i` agree pairwise on intersections, can be glued to construct a continuous map in `C(α, β)`. -/ noncomputable def lift_cover : C(α, β) := begin have H : (⋃ i, S i) = set.univ, { rw set.eq_univ_iff_forall, intros x, rw set.mem_Union, obtain ⟨i, hi⟩ := hS x, exact ⟨i, mem_of_mem_nhds hi⟩ }, refine ⟨set.lift_cover S (λ i, φ i) hφ H, continuous_subtype_nhds_cover hS _⟩, intros i, convert (φ i).continuous, ext x, exact set.lift_cover_coe x, end variables {S φ hφ hS} @[simp] lemma lift_cover_coe {i : ι} (x : S i) : lift_cover S φ hφ hS x = φ i x := set.lift_cover_coe _ @[simp] lemma lift_cover_restrict {i : ι} : (lift_cover S φ hφ hS).restrict (S i) = φ i := ext $ lift_cover_coe omit hφ hS variables (A : set (set α)) (F : Π (s : set α) (hi : s ∈ A), C(s, β)) (hF : ∀ s (hs : s ∈ A) t (ht : t ∈ A) (x : α) (hxi : x ∈ s) (hxj : x ∈ t), F s hs ⟨x, hxi⟩ = F t ht ⟨x, hxj⟩) (hA : ∀ x : α, ∃ i ∈ A, i ∈ nhds x) include hF hA /-- A family `F s` of continuous maps `C(s, β)`, where (1) the domains `s` are taken from a set `A` of sets in `α` which contain a neighbourhood of each point in `α` and (2) the functions `F s` agree pairwise on intersections, can be glued to construct a continuous map in `C(α, β)`. -/ noncomputable def lift_cover' : C(α, β) := begin let S : A → set α := coe, let F : Π i : A, C(i, β) := λ i, F i i.prop, refine lift_cover S F (λ i j, hF i i.prop j j.prop) _, intros x, obtain ⟨s, hs, hsx⟩ := hA x, exact ⟨⟨s, hs⟩, hsx⟩ end variables {A F hF hA} @[simp] lemma lift_cover_coe' {s : set α} {hs : s ∈ A} (x : s) : lift_cover' A F hF hA x = F s hs x := let x' : (coe : A → set α) ⟨s, hs⟩ := x in lift_cover_coe x' @[simp] lemma lift_cover_restrict' {s : set α} {hs : s ∈ A} : (lift_cover' A F hF hA).restrict s = F s hs := ext $ lift_cover_coe' end gluing end continuous_map /-- The forward direction of a homeomorphism, as a bundled continuous map. -/ @[simps] def homeomorph.to_continuous_map {α β : Type*} [topological_space α] [topological_space β] (e : α ≃ₜ β) : C(α, β) := ⟨e⟩
61753d9376d3fe6c809a2191ecba6451256f639d
df561f413cfe0a88b1056655515399c546ff32a5
/1-tutorial-world/l1.lean
8d482426ebda60a91459bed3a9651c9f25dd61c6
[]
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
73
lean
lemma example1 (x y z : mynat) : x * y + z = x * y + z := begin refl, end
c431e594afa35c200b2ea66f1b12c5a7f7eddc77
c777c32c8e484e195053731103c5e52af26a25d1
/src/analysis/locally_convex/continuous_of_bounded.lean
7245d211bd25b0393859d833ab6c5d7499a43c66
[ "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
7,760
lean
/- Copyright (c) 2022 Anatole Dedecker. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Moritz Doll -/ import analysis.locally_convex.bounded import data.is_R_or_C.basic /-! # Continuity and Von Neumann boundedness This files proves that for `E` and `F` two topological vector spaces over `ℝ` or `ℂ`, if `E` is first countable, then every locally bounded linear map `E →ₛₗ[σ] F` is continuous (this is `linear_map.continuous_of_locally_bounded`). We keep this file separate from `analysis/locally_convex/bounded` in order not to import `analysis/normed_space/is_R_or_C` there, because defining the strong topology on the space of continuous linear maps will require importing `analysis/locally_convex/bounded` in `analysis/normed_space/operator_norm`. ## References * [Bourbaki, *Topological Vector Spaces*][bourbaki1987] -/ open topological_space bornology filter open_locale topology pointwise variables {𝕜 𝕜' E F : Type*} variables [add_comm_group E] [uniform_space E] [uniform_add_group E] variables [add_comm_group F] [uniform_space F] section nontrivially_normed_field variables [uniform_add_group F] variables [nontrivially_normed_field 𝕜] [module 𝕜 E] [module 𝕜 F] [has_continuous_smul 𝕜 E] /-- Construct a continuous linear map from a linear map `f : E →ₗ[𝕜] F` and the existence of a neighborhood of zero that gets mapped into a bounded set in `F`. -/ def linear_map.clm_of_exists_bounded_image (f : E →ₗ[𝕜] F) (h : ∃ (V : set E) (hV : V ∈ 𝓝 (0 : E)), bornology.is_vonN_bounded 𝕜 (f '' V)) : E →L[𝕜] F := ⟨f, begin -- It suffices to show that `f` is continuous at `0`. refine continuous_of_continuous_at_zero f _, rw [continuous_at_def, f.map_zero], intros U hU, -- Continuity means that `U ∈ 𝓝 0` implies that `f ⁻¹' U ∈ 𝓝 0`. rcases h with ⟨V, hV, h⟩, rcases h hU with ⟨r, hr, h⟩, rcases normed_field.exists_lt_norm 𝕜 r with ⟨x, hx⟩, specialize h x hx.le, -- After unfolding all the definitions, we know that `f '' V ⊆ x • U`. We use this to show the -- inclusion `x⁻¹ • V ⊆ f⁻¹' U`. have x_ne := norm_pos_iff.mp (hr.trans hx), have : x⁻¹ • V ⊆ f⁻¹' U := calc x⁻¹ • V ⊆ x⁻¹ • (f⁻¹' (f '' V)) : set.smul_set_mono (set.subset_preimage_image ⇑f V) ... ⊆ x⁻¹ • (f⁻¹' (x • U)) : set.smul_set_mono (set.preimage_mono h) ... = f⁻¹' (x⁻¹ • (x • U)) : by ext; simp only [set.mem_inv_smul_set_iff₀ x_ne, set.mem_preimage, linear_map.map_smul] ... ⊆ f⁻¹' U : by rw inv_smul_smul₀ x_ne _, -- Using this inclusion, it suffices to show that `x⁻¹ • V` is in `𝓝 0`, which is trivial. refine mem_of_superset _ this, convert set_smul_mem_nhds_smul hV (inv_ne_zero x_ne), exact (smul_zero _).symm, end⟩ lemma linear_map.clm_of_exists_bounded_image_coe {f : E →ₗ[𝕜] F} {h : ∃ (V : set E) (hV : V ∈ 𝓝 (0 : E)), bornology.is_vonN_bounded 𝕜 (f '' V)} : (f.clm_of_exists_bounded_image h : E →ₗ[𝕜] F) = f := rfl @[simp] lemma linear_map.clm_of_exists_bounded_image_apply {f : E →ₗ[𝕜] F} {h : ∃ (V : set E) (hV : V ∈ 𝓝 (0 : E)), bornology.is_vonN_bounded 𝕜 (f '' V)} {x : E} : f.clm_of_exists_bounded_image h x = f x := rfl end nontrivially_normed_field section is_R_or_C open topological_space bornology variables [first_countable_topology E] variables [is_R_or_C 𝕜] [module 𝕜 E] [has_continuous_smul 𝕜 E] variables [is_R_or_C 𝕜'] [module 𝕜' F] [has_continuous_smul 𝕜' F] variables {σ : 𝕜 →+* 𝕜'} lemma linear_map.continuous_at_zero_of_locally_bounded (f : E →ₛₗ[σ] F) (hf : ∀ (s : set E) (hs : is_vonN_bounded 𝕜 s), is_vonN_bounded 𝕜' (f '' s)) : continuous_at f 0 := begin -- Assume that f is not continuous at 0 by_contradiction, -- We use a decreasing balanced basis for 0 : E and a balanced basis for 0 : F -- and reformulate non-continuity in terms of these bases rcases (nhds_basis_balanced 𝕜 E).exists_antitone_subbasis with ⟨b, bE1, bE⟩, simp only [id.def] at bE, have bE' : (𝓝 (0 : E)).has_basis (λ (x : ℕ), x ≠ 0) (λ n : ℕ, (n : 𝕜)⁻¹ • b n) := begin refine bE.1.to_has_basis _ _, { intros n _, use n+1, simp only [ne.def, nat.succ_ne_zero, not_false_iff, nat.cast_add, nat.cast_one, true_and], -- `b (n + 1) ⊆ b n` follows from `antitone`. have h : b (n + 1) ⊆ b n := bE.2 (by simp), refine subset_trans _ h, rintros y ⟨x, hx, hy⟩, -- Since `b (n + 1)` is balanced `(n+1)⁻¹ b (n + 1) ⊆ b (n + 1)` rw ←hy, refine (bE1 (n+1)).2.smul_mem _ hx, have h' : 0 < (n : ℝ) + 1 := n.cast_add_one_pos, rw [norm_inv, ←nat.cast_one, ←nat.cast_add, is_R_or_C.norm_nat_cast, nat.cast_add, nat.cast_one, inv_le h' zero_lt_one], simp }, intros n hn, -- The converse direction follows from continuity of the scalar multiplication have hcont : continuous_at (λ (x : E), (n : 𝕜) • x) 0 := (continuous_const_smul (n : 𝕜)).continuous_at, simp only [continuous_at, map_zero, smul_zero] at hcont, rw bE.1.tendsto_left_iff at hcont, rcases hcont (b n) (bE1 n).1 with ⟨i, _, hi⟩, refine ⟨i, trivial, λ x hx, ⟨(n : 𝕜) • x, hi hx, _⟩⟩, simp [←mul_smul, hn], end, rw [continuous_at, map_zero, bE'.tendsto_iff (nhds_basis_balanced 𝕜' F)] at h, push_neg at h, rcases h with ⟨V, ⟨hV, hV'⟩, h⟩, simp only [id.def, forall_true_left] at h, -- There exists `u : ℕ → E` such that for all `n : ℕ` we have `u n ∈ n⁻¹ • b n` and `f (u n) ∉ V` choose! u hu hu' using h, -- The sequence `(λ n, n • u n)` converges to `0` have h_tendsto : tendsto (λ n : ℕ, (n : 𝕜) • u n) at_top (𝓝 (0 : E)) := begin apply bE.tendsto, intros n, by_cases h : n = 0, { rw [h, nat.cast_zero, zero_smul], refine mem_of_mem_nhds (bE.1.mem_of_mem $ by triv) }, rcases hu n h with ⟨y, hy, hu1⟩, convert hy, rw [←hu1, ←mul_smul], simp only [h, mul_inv_cancel, ne.def, nat.cast_eq_zero, not_false_iff, one_smul], end, -- The image `(λ n, n • u n)` is von Neumann bounded: have h_bounded : is_vonN_bounded 𝕜 (set.range (λ n : ℕ, (n : 𝕜) • u n)) := h_tendsto.cauchy_seq.totally_bounded_range.is_vonN_bounded 𝕜, -- Since `range u` is bounded it absorbs `V` rcases hf _ h_bounded hV with ⟨r, hr, h'⟩, cases exists_nat_gt r with n hn, -- We now find a contradiction between `f (u n) ∉ V` and the absorbing property have h1 : r ≤ ‖(n : 𝕜')‖ := by { rw [is_R_or_C.norm_nat_cast], exact hn.le }, have hn' : 0 < ‖(n : 𝕜')‖ := lt_of_lt_of_le hr h1, rw [norm_pos_iff, ne.def, nat.cast_eq_zero] at hn', have h'' : f (u n) ∈ V := begin simp only [set.image_subset_iff] at h', specialize h' (n : 𝕜') h1 (set.mem_range_self n), simp only [set.mem_preimage, linear_map.map_smulₛₗ, map_nat_cast] at h', rcases h' with ⟨y, hy, h'⟩, apply_fun (λ y : F, (n : 𝕜')⁻¹ • y) at h', simp only [hn', inv_smul_smul₀, ne.def, nat.cast_eq_zero, not_false_iff] at h', rwa ←h', end, exact hu' n hn' h'', end /-- If `E` is first countable, then every locally bounded linear map `E →ₛₗ[σ] F` is continuous. -/ lemma linear_map.continuous_of_locally_bounded [uniform_add_group F] (f : E →ₛₗ[σ] F) (hf : ∀ (s : set E) (hs : is_vonN_bounded 𝕜 s), is_vonN_bounded 𝕜' (f '' s)) : continuous f := (uniform_continuous_of_continuous_at_zero f $ f.continuous_at_zero_of_locally_bounded hf).continuous end is_R_or_C
1785841531bf8eb1fa30e3501bddd12985ed0d0c
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/char_p/exp_char.lean
4aeb0a2af172eaaf17e248b13d70bc7fc89c8e2a
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
4,065
lean
/- Copyright (c) 2021 Jakob Scholbach. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob Scholbach -/ import algebra.char_p.basic import data.nat.prime /-! # Exponential characteristic This file defines the exponential characteristic and establishes a few basic results relating it to the (ordinary characteristic). The definition is stated for a semiring, but the actual results are for nontrivial rings (as far as exponential characteristic one is concerned), respectively a ring without zero-divisors (for prime characteristic). ## Main results - `exp_char`: the definition of exponential characteristic - `exp_char_is_prime_or_one`: the exponential characteristic is a prime or one - `char_eq_exp_char_iff`: the characteristic equals the exponential characteristic iff the characteristic is prime ## Tags exponential characteristic, characteristic -/ universe u variables (R : Type u) section semiring variables [semiring R] /-- The definition of the exponential characteristic of a semiring. -/ class inductive exp_char (R : Type u) [semiring R] : ℕ → Prop | zero [char_zero R] : exp_char 1 | prime {q : ℕ} (hprime : q.prime) [hchar : char_p R q] : exp_char q /-- The exponential characteristic is one if the characteristic is zero. -/ lemma exp_char_one_of_char_zero (q : ℕ) [hp : char_p R 0] [hq : exp_char R q] : q = 1 := begin casesI hq with q hq_one hq_prime, { refl }, { exact false.elim (lt_irrefl _ ((hp.eq R hq_hchar).symm ▸ hq_prime : (0 : ℕ).prime).pos) } end /-- The characteristic equals the exponential characteristic iff the former is prime. -/ theorem char_eq_exp_char_iff (p q : ℕ) [hp : char_p R p] [hq : exp_char R q] : p = q ↔ p.prime := begin casesI hq with q hq_one hq_prime, { apply iff_of_false, { unfreezingI {rintro rfl}, exact one_ne_zero (hp.eq R (char_p.of_char_zero R)) }, { intro pprime, rw (char_p.eq R hp infer_instance : p = 0) at pprime, exact nat.not_prime_zero pprime } }, { exact ⟨λ hpq, hpq.symm ▸ hq_prime, λ _, char_p.eq R hp hq_hchar⟩ }, end section nontrivial variables [nontrivial R] /-- The exponential characteristic is one if the characteristic is zero. -/ lemma char_zero_of_exp_char_one (p : ℕ) [hp : char_p R p] [hq : exp_char R 1] : p = 0 := begin casesI hq, { exact char_p.eq R hp infer_instance, }, { exact false.elim (char_p.char_ne_one R 1 rfl), } end /-- The characteristic is zero if the exponential characteristic is one. -/ @[priority 100] -- see Note [lower instance priority] instance char_zero_of_exp_char_one' [hq : exp_char R 1] : char_zero R := begin casesI hq, { assumption, }, { exact false.elim (char_p.char_ne_one R 1 rfl), } end /-- The exponential characteristic is one iff the characteristic is zero. -/ theorem exp_char_one_iff_char_zero (p q : ℕ) [char_p R p] [exp_char R q] : q = 1 ↔ p = 0 := begin split, { unfreezingI {rintro rfl}, exact char_zero_of_exp_char_one R p, }, { unfreezingI {rintro rfl}, exact exp_char_one_of_char_zero R q, } end section no_zero_divisors variable [no_zero_divisors R] /-- A helper lemma: the characteristic is prime if it is non-zero. -/ lemma char_prime_of_ne_zero {p : ℕ} [hp : char_p R p] (p_ne_zero : p ≠ 0) : nat.prime p := begin cases char_p.char_is_prime_or_zero R p with h h, { exact h, }, { contradiction, } end /-- The exponential characteristic is a prime number or one. -/ theorem exp_char_is_prime_or_one (q : ℕ) [hq : exp_char R q] : nat.prime q ∨ q = 1 := or_iff_not_imp_right.mpr $ λ h, begin casesI char_p.exists R with p hp, have p_ne_zero : p ≠ 0, { intro p_zero, haveI : char_p R 0, { rwa ←p_zero }, have : q = 1 := exp_char_one_of_char_zero R q, contradiction, }, have p_eq_q : p = q := (char_eq_exp_char_iff R p q).mpr (char_prime_of_ne_zero R p_ne_zero), cases char_p.char_is_prime_or_zero R p with pprime, { rwa p_eq_q at pprime }, { contradiction }, end end no_zero_divisors end nontrivial end semiring