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
8ccbadaafe63c379519f9b38cd257218c2a759b2
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/mean_inequalities_pow.lean
0865f42f60bc18dee84d3192c37719d6bc4ddbb7
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
12,993
lean
/- Copyright (c) 2019 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov, Sébastien Gouëzel, Rémy Degenne -/ import analysis.convex.specific_functions import tactic.positivity /-! # Mean value inequalities In this file we prove several mean inequalities for finite sums. Versions for integrals of some of these inequalities are available in `measure_theory.mean_inequalities`. ## Main theorems: generalized mean inequality The inequality says that for two non-negative vectors $w$ and $z$ with $\sum_{i\in s} w_i=1$ and $p ≤ q$ we have $$ \sqrt[p]{\sum_{i\in s} w_i z_i^p} ≤ \sqrt[q]{\sum_{i\in s} w_i z_i^q}. $$ Currently we only prove this inequality for $p=1$. As in the rest of `mathlib`, we provide different theorems for natural exponents (`pow_arith_mean_le_arith_mean_pow`), integer exponents (`zpow_arith_mean_le_arith_mean_zpow`), and real exponents (`rpow_arith_mean_le_arith_mean_rpow` and `arith_mean_le_rpow_mean`). In the first two cases we prove $$ \left(\sum_{i\in s} w_i z_i\right)^n ≤ \sum_{i\in s} w_i z_i^n $$ in order to avoid using real exponents. For real exponents we prove both this and standard versions. ## TODO - each inequality `A ≤ B` should come with a theorem `A = B ↔ _`; one of the ways to prove them is to define `strict_convex_on` functions. - generalized mean inequality with any `p ≤ q`, including negative numbers; - prove that the power mean tends to the geometric mean as the exponent tends to zero. -/ universes u v open finset open_locale classical big_operators nnreal ennreal noncomputable theory variables {ι : Type u} (s : finset ι) namespace real theorem pow_arith_mean_le_arith_mean_pow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) (n : ℕ) : (∑ i in s, w i * z i) ^ n ≤ ∑ i in s, (w i * z i ^ n) := (convex_on_pow n).map_sum_le hw hw' hz theorem pow_arith_mean_le_arith_mean_pow_of_even (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) {n : ℕ} (hn : even n) : (∑ i in s, w i * z i) ^ n ≤ ∑ i in s, (w i * z i ^ n) := hn.convex_on_pow.map_sum_le hw hw' (λ _ _, trivial) theorem zpow_arith_mean_le_arith_mean_zpow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 < z i) (m : ℤ) : (∑ i in s, w i * z i) ^ m ≤ ∑ i in s, (w i * z i ^ m) := (convex_on_zpow m).map_sum_le hw hw' hz theorem rpow_arith_mean_le_arith_mean_rpow (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) {p : ℝ} (hp : 1 ≤ p) : (∑ i in s, w i * z i) ^ p ≤ ∑ i in s, (w i * z i ^ p) := (convex_on_rpow hp).map_sum_le hw hw' hz theorem arith_mean_le_rpow_mean (w z : ι → ℝ) (hw : ∀ i ∈ s, 0 ≤ w i) (hw' : ∑ i in s, w i = 1) (hz : ∀ i ∈ s, 0 ≤ z i) {p : ℝ} (hp : 1 ≤ p) : ∑ i in s, w i * z i ≤ (∑ i in s, (w i * z i ^ p)) ^ (1 / p) := begin have : 0 < p := by positivity, rw [← rpow_le_rpow_iff _ _ this, ← rpow_mul, one_div_mul_cancel (ne_of_gt this), rpow_one], exact rpow_arith_mean_le_arith_mean_rpow s w z hw hw' hz hp, all_goals { apply_rules [sum_nonneg, rpow_nonneg_of_nonneg], intros i hi, apply_rules [mul_nonneg, rpow_nonneg_of_nonneg, hw i hi, hz i hi] }, end end real namespace nnreal /-- Weighted generalized mean inequality, version sums over finite sets, with `ℝ≥0`-valued functions and natural exponent. -/ theorem pow_arith_mean_le_arith_mean_pow (w z : ι → ℝ≥0) (hw' : ∑ i in s, w i = 1) (n : ℕ) : (∑ i in s, w i * z i) ^ n ≤ ∑ i in s, (w i * z i ^ n) := by exact_mod_cast real.pow_arith_mean_le_arith_mean_pow s _ _ (λ i _, (w i).coe_nonneg) (by exact_mod_cast hw') (λ i _, (z i).coe_nonneg) n /-- Weighted generalized mean inequality, version for sums over finite sets, with `ℝ≥0`-valued functions and real exponents. -/ theorem rpow_arith_mean_le_arith_mean_rpow (w z : ι → ℝ≥0) (hw' : ∑ i in s, w i = 1) {p : ℝ} (hp : 1 ≤ p) : (∑ i in s, w i * z i) ^ p ≤ ∑ i in s, (w i * z i ^ p) := by exact_mod_cast real.rpow_arith_mean_le_arith_mean_rpow s _ _ (λ i _, (w i).coe_nonneg) (by exact_mod_cast hw') (λ i _, (z i).coe_nonneg) hp /-- Weighted generalized mean inequality, version for two elements of `ℝ≥0` and real exponents. -/ theorem rpow_arith_mean_le_arith_mean2_rpow (w₁ w₂ z₁ z₂ : ℝ≥0) (hw' : w₁ + w₂ = 1) {p : ℝ} (hp : 1 ≤ p) : (w₁ * z₁ + w₂ * z₂) ^ p ≤ w₁ * z₁ ^ p + w₂ * z₂ ^ p := begin have h := rpow_arith_mean_le_arith_mean_rpow univ ![w₁, w₂] ![z₁, z₂] _ hp, { simpa [fin.sum_univ_succ] using h, }, { simp [hw', fin.sum_univ_succ], }, end /-- Weighted generalized mean inequality, version for sums over finite sets, with `ℝ≥0`-valued functions and real exponents. -/ theorem arith_mean_le_rpow_mean (w z : ι → ℝ≥0) (hw' : ∑ i in s, w i = 1) {p : ℝ} (hp : 1 ≤ p) : ∑ i in s, w i * z i ≤ (∑ i in s, (w i * z i ^ p)) ^ (1 / p) := by exact_mod_cast real.arith_mean_le_rpow_mean s _ _ (λ i _, (w i).coe_nonneg) (by exact_mod_cast hw') (λ i _, (z i).coe_nonneg) hp end nnreal namespace nnreal private lemma add_rpow_le_one_of_add_le_one {p : ℝ} (a b : ℝ≥0) (hab : a + b ≤ 1) (hp1 : 1 ≤ p) : a ^ p + b ^ p ≤ 1 := begin have h_le_one : ∀ x : ℝ≥0, x ≤ 1 → x ^ p ≤ x, from λ x hx, rpow_le_self_of_le_one hx hp1, have ha : a ≤ 1, from (self_le_add_right a b).trans hab, have hb : b ≤ 1, from (self_le_add_left b a).trans hab, exact (add_le_add (h_le_one a ha) (h_le_one b hb)).trans hab, end lemma add_rpow_le_rpow_add {p : ℝ} (a b : ℝ≥0) (hp1 : 1 ≤ p) : a ^ p + b ^ p ≤ (a + b) ^ p := begin have hp_pos : 0 < p := by positivity, by_cases h_zero : a + b = 0, { simp [add_eq_zero_iff.mp h_zero, hp_pos.ne'] }, have h_nonzero : ¬(a = 0 ∧ b = 0), by rwa add_eq_zero_iff at h_zero, have h_add : a/(a+b) + b/(a+b) = 1, by rw [div_add_div_same, div_self h_zero], have h := add_rpow_le_one_of_add_le_one (a/(a+b)) (b/(a+b)) h_add.le hp1, rw [div_rpow a (a+b), div_rpow b (a+b)] at h, have hab_0 : (a + b)^p ≠ 0, by simp [hp_pos, h_nonzero], have hab_0' : 0 < (a + b) ^ p := zero_lt_iff.mpr hab_0, have h_mul : (a + b)^p * (a ^ p / (a + b) ^ p + b ^ p / (a + b) ^ p) ≤ (a + b)^p, { nth_rewrite 3 ←mul_one ((a + b)^p), exact (mul_le_mul_left hab_0').mpr h, }, rwa [div_eq_mul_inv, div_eq_mul_inv, mul_add, mul_comm (a^p), mul_comm (b^p), ←mul_assoc, ←mul_assoc, mul_inv_cancel hab_0, one_mul, one_mul] at h_mul, end lemma rpow_add_rpow_le_add {p : ℝ} (a b : ℝ≥0) (hp1 : 1 ≤ p) : (a ^ p + b ^ p) ^ (1/p) ≤ a + b := begin rw ←@nnreal.le_rpow_one_div_iff _ _ (1/p) (by simp [lt_of_lt_of_le zero_lt_one hp1]), rw one_div_one_div, exact add_rpow_le_rpow_add _ _ hp1, end theorem rpow_add_rpow_le {p q : ℝ} (a b : ℝ≥0) (hp_pos : 0 < p) (hpq : p ≤ q) : (a ^ q + b ^ q) ^ (1/q) ≤ (a ^ p + b ^ p) ^ (1/p) := begin have h_rpow : ∀ a : ℝ≥0, a^q = (a^p)^(q/p), from λ a, by rw [←nnreal.rpow_mul, div_eq_inv_mul, ←mul_assoc, _root_.mul_inv_cancel hp_pos.ne.symm, one_mul], have h_rpow_add_rpow_le_add : ((a^p)^(q/p) + (b^p)^(q/p)) ^ (1/(q/p)) ≤ a^p + b^p, { refine rpow_add_rpow_le_add (a^p) (b^p) _, rwa one_le_div hp_pos, }, rw [h_rpow a, h_rpow b, nnreal.le_rpow_one_div_iff hp_pos, ←nnreal.rpow_mul, mul_comm, mul_one_div], rwa one_div_div at h_rpow_add_rpow_le_add, end lemma rpow_add_le_add_rpow {p : ℝ} (a b : ℝ≥0) (hp : 0 ≤ p) (hp1 : p ≤ 1) : (a + b) ^ p ≤ a ^ p + b ^ p := begin rcases hp.eq_or_lt with rfl|hp_pos, { simp }, have h := rpow_add_rpow_le a b hp_pos hp1, rw one_div_one at h, repeat { rw nnreal.rpow_one at h }, exact (nnreal.le_rpow_one_div_iff hp_pos).mp h end end nnreal namespace ennreal /-- Weighted generalized mean inequality, version for sums over finite sets, with `ℝ≥0∞`-valued functions and real exponents. -/ theorem rpow_arith_mean_le_arith_mean_rpow (w z : ι → ℝ≥0∞) (hw' : ∑ i in s, w i = 1) {p : ℝ} (hp : 1 ≤ p) : (∑ i in s, w i * z i) ^ p ≤ ∑ i in s, (w i * z i ^ p) := begin have hp_pos : 0 < p, positivity, have hp_nonneg : 0 ≤ p, positivity, have hp_not_nonpos : ¬ p ≤ 0, by simp [hp_pos], have hp_not_neg : ¬ p < 0, by simp [hp_nonneg], have h_top_iff_rpow_top : ∀ (i : ι) (hi : i ∈ s), w i * z i = ⊤ ↔ w i * (z i) ^ p = ⊤, by simp [hp_pos, hp_nonneg, hp_not_nonpos, hp_not_neg], refine le_of_top_imp_top_of_to_nnreal_le _ _, { -- first, prove `(∑ i in s, w i * z i) ^ p = ⊤ → ∑ i in s, (w i * z i ^ p) = ⊤` rw [rpow_eq_top_iff, sum_eq_top_iff, sum_eq_top_iff], intro h, simp only [and_false, hp_not_neg, false_or] at h, rcases h.left with ⟨a, H, ha⟩, use [a, H], rwa ←h_top_iff_rpow_top a H, }, { -- second, suppose both `(∑ i in s, w i * z i) ^ p ≠ ⊤` and `∑ i in s, (w i * z i ^ p) ≠ ⊤`, -- and prove `((∑ i in s, w i * z i) ^ p).to_nnreal ≤ (∑ i in s, (w i * z i ^ p)).to_nnreal`, -- by using `nnreal.rpow_arith_mean_le_arith_mean_rpow`. intros h_top_rpow_sum _, -- show hypotheses needed to put the `.to_nnreal` inside the sums. have h_top : ∀ (a : ι), a ∈ s → w a * z a ≠ ⊤, { have h_top_sum : ∑ (i : ι) in s, w i * z i ≠ ⊤, { intro h, rw [h, top_rpow_of_pos hp_pos] at h_top_rpow_sum, exact h_top_rpow_sum rfl, }, exact λ a ha, (lt_top_of_sum_ne_top h_top_sum ha).ne }, have h_top_rpow : ∀ (a : ι), a ∈ s → w a * z a ^ p ≠ ⊤, { intros i hi, specialize h_top i hi, rwa [ne.def, ←h_top_iff_rpow_top i hi], }, -- put the `.to_nnreal` inside the sums. simp_rw [to_nnreal_sum h_top_rpow, ←to_nnreal_rpow, to_nnreal_sum h_top, to_nnreal_mul, ←to_nnreal_rpow], -- use corresponding nnreal result refine nnreal.rpow_arith_mean_le_arith_mean_rpow s (λ i, (w i).to_nnreal) (λ i, (z i).to_nnreal) _ hp, -- verify the hypothesis `∑ i in s, (w i).to_nnreal = 1`, using `∑ i in s, w i = 1` . have h_sum_nnreal : (∑ i in s, w i) = ↑(∑ i in s, (w i).to_nnreal), { rw coe_finset_sum, refine sum_congr rfl (λ i hi, (coe_to_nnreal _).symm), refine (lt_top_of_sum_ne_top _ hi).ne, exact hw'.symm ▸ ennreal.one_ne_top }, rwa [←coe_eq_coe, ←h_sum_nnreal], }, end /-- Weighted generalized mean inequality, version for two elements of `ℝ≥0∞` and real exponents. -/ theorem rpow_arith_mean_le_arith_mean2_rpow (w₁ w₂ z₁ z₂ : ℝ≥0∞) (hw' : w₁ + w₂ = 1) {p : ℝ} (hp : 1 ≤ p) : (w₁ * z₁ + w₂ * z₂) ^ p ≤ w₁ * z₁ ^ p + w₂ * z₂ ^ p := begin have h := rpow_arith_mean_le_arith_mean_rpow univ ![w₁, w₂] ![z₁, z₂] _ hp, { simpa [fin.sum_univ_succ] using h, }, { simp [hw', fin.sum_univ_succ], }, end end ennreal namespace ennreal lemma add_rpow_le_rpow_add {p : ℝ} (a b : ℝ≥0∞) (hp1 : 1 ≤ p) : a ^ p + b ^ p ≤ (a + b) ^ p := begin have hp_pos : 0 < p := by positivity, by_cases h_top : a + b = ⊤, { rw ←@ennreal.rpow_eq_top_iff_of_pos (a + b) p hp_pos at h_top, rw h_top, exact le_top, }, obtain ⟨ha_top, hb_top⟩ := add_ne_top.mp h_top, lift a to ℝ≥0 using ha_top, lift b to ℝ≥0 using hb_top, simpa [← ennreal.coe_rpow_of_nonneg _ hp_pos.le] using ennreal.coe_le_coe.2 (nnreal.add_rpow_le_rpow_add a b hp1), end lemma rpow_add_rpow_le_add {p : ℝ} (a b : ℝ≥0∞) (hp1 : 1 ≤ p) : (a ^ p + b ^ p) ^ (1/p) ≤ a + b := begin rw ←@ennreal.le_rpow_one_div_iff _ _ (1/p) (by simp [lt_of_lt_of_le zero_lt_one hp1]), rw one_div_one_div, exact add_rpow_le_rpow_add _ _ hp1, end theorem rpow_add_rpow_le {p q : ℝ} (a b : ℝ≥0∞) (hp_pos : 0 < p) (hpq : p ≤ q) : (a ^ q + b ^ q) ^ (1/q) ≤ (a ^ p + b ^ p) ^ (1/p) := begin have h_rpow : ∀ a : ℝ≥0∞, a^q = (a^p)^(q/p), from λ a, by rw [← ennreal.rpow_mul, _root_.mul_div_cancel' _ hp_pos.ne'], have h_rpow_add_rpow_le_add : ((a^p)^(q/p) + (b^p)^(q/p)) ^ (1/(q/p)) ≤ a^p + b^p, { refine rpow_add_rpow_le_add (a^p) (b^p) _, rwa one_le_div hp_pos, }, rw [h_rpow a, h_rpow b, ennreal.le_rpow_one_div_iff hp_pos, ←ennreal.rpow_mul, mul_comm, mul_one_div], rwa one_div_div at h_rpow_add_rpow_le_add, end lemma rpow_add_le_add_rpow {p : ℝ} (a b : ℝ≥0∞) (hp : 0 ≤ p) (hp1 : p ≤ 1) : (a + b) ^ p ≤ a ^ p + b ^ p := begin rcases hp.eq_or_lt with rfl|hp_pos, { suffices : (1 : ℝ≥0∞) ≤ 1 + 1, { simpa using this }, norm_cast, norm_num }, have h := rpow_add_rpow_le a b hp_pos hp1, rw one_div_one at h, repeat { rw ennreal.rpow_one at h }, exact (ennreal.le_rpow_one_div_iff hp_pos).mp h, end end ennreal
8153695d0293f5b4da3b45ab18061319e5de547c
9f7051a7c2110f6027b18c72aaea0de2e35cf548
/1.lean
c717df5d9b4eee788a02f72744bd92c80a3b122d
[]
no_license
zac-garby/learning-lean
87d680dee914c44fcfb0b1148e7d4c9783452e29
b96ba2be10afd445ed2207532af3eceda23c421b
refs/heads/main
1,671,754,244,291
1,601,638,632,000
1,601,638,632,000
300,594,697
1
0
null
1,601,638,633,000
1,601,638,428,000
Lean
UTF-8
Lean
false
false
459
lean
-- The code from the first lecture variables P Q R : Prop #check P ∧ Q #check P → Q #check P ∨ Q #check ¬ P #check P ↔ Q theorem I : P → P := begin assume h, exact h end theorem C : (P → Q) → (Q → R) → (P → R) := begin assume f, assume g, assume p, apply g, apply f, exact p, end theorem swap : (P → Q → R) → (Q → P → R) := begin assume f, assume q, assume p, apply f, exact p, exact q, end
520f5fe31836867d3330a2f97a2f2bde5c0a3e00
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/field_theory/mv_polynomial.lean
e913154f720506057af1a24ca6685e44df052f60
[ "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
1,522
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import ring_theory.mv_polynomial.basic /-! # Multivariate polynomials over fields This file contains basic facts about multivariate polynomials over fields, for example that the dimension of the space of multivariate polynomials over a field is equal to the cardinality of finitely supported functions from the indexing set to `ℕ`. -/ noncomputable theory open_locale classical open set linear_map submodule open_locale big_operators namespace mv_polynomial universes u v variables {σ : Type u} {K : Type v} variables (σ K) [field K] lemma quotient_mk_comp_C_injective (I : ideal (mv_polynomial σ K)) (hI : I ≠ ⊤) : function.injective ((ideal.quotient.mk I).comp mv_polynomial.C) := begin refine (ring_hom.injective_iff _).2 (λ x hx, _), rw [ring_hom.comp_apply, ideal.quotient.eq_zero_iff_mem] at hx, refine classical.by_contradiction (λ hx0, absurd (I.eq_top_iff_one.2 _) hI), have := I.mul_mem_left (mv_polynomial.C x⁻¹) hx, rwa [← mv_polynomial.C.map_mul, inv_mul_cancel hx0, mv_polynomial.C_1] at this, end end mv_polynomial namespace mv_polynomial universe u variables {σ : Type u} {K : Type u} [field K] open_locale classical lemma dim_mv_polynomial : vector_space.dim K (mv_polynomial σ K) = cardinal.mk (σ →₀ ℕ) := by rw [← cardinal.lift_inj, ← (is_basis_monomials σ K).mk_eq_dim] end mv_polynomial
2daef6752afcc1bc08bbfd25460b296d99fada39
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/linear_algebra/affine_space/finite_dimensional.lean
aba5a523f7c06edb36d0432631a8e22f071b9ebe
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
16,306
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import linear_algebra.affine_space.independent import linear_algebra.finite_dimensional /-! # Finite-dimensional subspaces of affine spaces. This file provides a few results relating to finite-dimensional subspaces of affine spaces. ## Main definitions * `collinear` defines collinear sets of points as those that span a subspace of dimension at most 1. -/ noncomputable theory open_locale big_operators classical affine section affine_space' variables (k : Type*) {V : Type*} {P : Type*} [field k] [add_comm_group V] [module k V] [affine_space V P] variables {ι : Type*} include V open affine_subspace finite_dimensional module /-- The `vector_span` of a finite set is finite-dimensional. -/ lemma finite_dimensional_vector_span_of_finite {s : set P} (h : set.finite s) : finite_dimensional k (vector_span k s) := span_of_finite k $ h.vsub h /-- The `vector_span` of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_vector_span_of_fintype [fintype ι] (p : ι → P) : finite_dimensional k (vector_span k (set.range p)) := finite_dimensional_vector_span_of_finite k (set.finite_range _) /-- The `vector_span` of a subset of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_vector_span_image_of_fintype [fintype ι] (p : ι → P) (s : set ι) : finite_dimensional k (vector_span k (p '' s)) := finite_dimensional_vector_span_of_finite k ((set.finite.of_fintype _).image _) /-- The direction of the affine span of a finite set is finite-dimensional. -/ lemma finite_dimensional_direction_affine_span_of_finite {s : set P} (h : set.finite s) : finite_dimensional k (affine_span k s).direction := (direction_affine_span k s).symm ▸ finite_dimensional_vector_span_of_finite k h /-- The direction of the affine span of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_direction_affine_span_of_fintype [fintype ι] (p : ι → P) : finite_dimensional k (affine_span k (set.range p)).direction := finite_dimensional_direction_affine_span_of_finite k (set.finite_range _) /-- The direction of the affine span of a subset of a family indexed by a `fintype` is finite-dimensional. -/ instance finite_dimensional_direction_affine_span_image_of_fintype [fintype ι] (p : ι → P) (s : set ι) : finite_dimensional k (affine_span k (p '' s)).direction := finite_dimensional_direction_affine_span_of_finite k ((set.finite.of_fintype _).image _) /-- An affine-independent family of points in a finite-dimensional affine space is finite. -/ noncomputable def fintype_of_fin_dim_affine_independent [finite_dimensional k V] {p : ι → P} (hi : affine_independent k p) : fintype ι := if hι : is_empty ι then (@fintype.of_is_empty _ hι) else begin let q := (not_is_empty_iff.mp hι).some, rw affine_independent_iff_linear_independent_vsub k p q at hi, exact fintype_of_fintype_ne _ (fintype_of_is_noetherian_linear_independent hi) end /-- An affine-independent subset of a finite-dimensional affine space is finite. -/ lemma finite_of_fin_dim_affine_independent [finite_dimensional k V] {s : set P} (hi : affine_independent k (coe : s → P)) : s.finite := ⟨fintype_of_fin_dim_affine_independent k hi⟩ variables {k} /-- The `vector_span` of a finite subset of an affinely independent family has dimension one less than its cardinality. -/ lemma affine_independent.finrank_vector_span_image_finset {p : ι → P} (hi : affine_independent k p) {s : finset ι} {n : ℕ} (hc : finset.card s = n + 1) : finrank k (vector_span k (s.image p : set P)) = n := begin have hi' := hi.range.mono (set.image_subset_range p ↑s), have hc' : (s.image p).card = n + 1, { rwa s.card_image_of_injective hi.injective }, have hn : (s.image p).nonempty, { simp [hc', ←finset.card_pos] }, rcases hn with ⟨p₁, hp₁⟩, have hp₁' : p₁ ∈ p '' s := by simpa using hp₁, rw [affine_independent_set_iff_linear_independent_vsub k hp₁', ← finset.coe_singleton, ← finset.coe_image, ← finset.coe_sdiff, finset.sdiff_singleton_eq_erase, ← finset.coe_image] at hi', have hc : (finset.image (λ (p : P), p -ᵥ p₁) ((finset.image p s).erase p₁)).card = n, { rw [finset.card_image_of_injective _ (vsub_left_injective _), finset.card_erase_of_mem hp₁], exact nat.pred_eq_of_eq_succ hc' }, rwa [vector_span_eq_span_vsub_finset_right_ne k hp₁, finrank_span_finset_eq_card, hc] end /-- The `vector_span` of a finite affinely independent family has dimension one less than its cardinality. -/ lemma affine_independent.finrank_vector_span [fintype ι] {p : ι → P} (hi : affine_independent k p) {n : ℕ} (hc : fintype.card ι = n + 1) : finrank k (vector_span k (set.range p)) = n := begin rw ← finset.card_univ at hc, rw [← set.image_univ, ← finset.coe_univ, ← finset.coe_image], exact hi.finrank_vector_span_image_finset hc end /-- If the `vector_span` of a finite subset of an affinely independent family lies in a submodule with dimension one less than its cardinality, it equals that submodule. -/ lemma affine_independent.vector_span_image_finset_eq_of_le_of_card_eq_finrank_add_one {p : ι → P} (hi : affine_independent k p) {s : finset ι} {sm : submodule k V} [finite_dimensional k sm] (hle : vector_span k (s.image p : set P) ≤ sm) (hc : finset.card s = finrank k sm + 1) : vector_span k (s.image p : set P) = sm := eq_of_le_of_finrank_eq hle $ hi.finrank_vector_span_image_finset hc /-- If the `vector_span` of a finite affinely independent family lies in a submodule with dimension one less than its cardinality, it equals that submodule. -/ lemma affine_independent.vector_span_eq_of_le_of_card_eq_finrank_add_one [fintype ι] {p : ι → P} (hi : affine_independent k p) {sm : submodule k V} [finite_dimensional k sm] (hle : vector_span k (set.range p) ≤ sm) (hc : fintype.card ι = finrank k sm + 1) : vector_span k (set.range p) = sm := eq_of_le_of_finrank_eq hle $ hi.finrank_vector_span hc /-- If the `affine_span` of a finite subset of an affinely independent family lies in an affine subspace whose direction has dimension one less than its cardinality, it equals that subspace. -/ lemma affine_independent.affine_span_image_finset_eq_of_le_of_card_eq_finrank_add_one {p : ι → P} (hi : affine_independent k p) {s : finset ι} {sp : affine_subspace k P} [finite_dimensional k sp.direction] (hle : affine_span k (s.image p : set P) ≤ sp) (hc : finset.card s = finrank k sp.direction + 1) : affine_span k (s.image p : set P) = sp := begin have hn : (s.image p).nonempty, { rw [finset.nonempty.image_iff, ← finset.card_pos, hc], apply nat.succ_pos }, refine eq_of_direction_eq_of_nonempty_of_le _ ((affine_span_nonempty k _).2 hn) hle, have hd := direction_le hle, rw direction_affine_span at ⊢ hd, exact hi.vector_span_image_finset_eq_of_le_of_card_eq_finrank_add_one hd hc end /-- If the `affine_span` of a finite affinely independent family lies in an affine subspace whose direction has dimension one less than its cardinality, it equals that subspace. -/ lemma affine_independent.affine_span_eq_of_le_of_card_eq_finrank_add_one [fintype ι] {p : ι → P} (hi : affine_independent k p) {sp : affine_subspace k P} [finite_dimensional k sp.direction] (hle : affine_span k (set.range p) ≤ sp) (hc : fintype.card ι = finrank k sp.direction + 1) : affine_span k (set.range p) = sp := begin rw ←finset.card_univ at hc, rw [←set.image_univ, ←finset.coe_univ, ← finset.coe_image] at ⊢ hle, exact hi.affine_span_image_finset_eq_of_le_of_card_eq_finrank_add_one hle hc end /-- The `vector_span` of a finite affinely independent family whose cardinality is one more than that of the finite-dimensional space is `⊤`. -/ lemma affine_independent.vector_span_eq_top_of_card_eq_finrank_add_one [finite_dimensional k V] [fintype ι] {p : ι → P} (hi : affine_independent k p) (hc : fintype.card ι = finrank k V + 1) : vector_span k (set.range p) = ⊤ := eq_top_of_finrank_eq $ hi.finrank_vector_span hc /-- The `affine_span` of a finite affinely independent family is `⊤` iff the family's cardinality is one more than that of the finite-dimensional space. -/ lemma affine_independent.affine_span_eq_top_iff_card_eq_finrank_add_one [finite_dimensional k V] [fintype ι] {p : ι → P} (hi : affine_independent k p) : affine_span k (set.range p) = ⊤ ↔ fintype.card ι = finrank k V + 1 := begin split, { intros h_tot, let n := fintype.card ι - 1, have hn : fintype.card ι = n + 1, { exact (nat.succ_pred_eq_of_pos (card_pos_of_affine_span_eq_top k V P h_tot)).symm, }, rw [hn, ← finrank_top, ← (vector_span_eq_top_of_affine_span_eq_top k V P) h_tot, ← hi.finrank_vector_span hn], }, { intros hc, rw [← finrank_top, ← direction_top k V P] at hc, exact hi.affine_span_eq_of_le_of_card_eq_finrank_add_one le_top hc, }, end variables (k) /-- The `vector_span` of `n + 1` points in an indexed family has dimension at most `n`. -/ lemma finrank_vector_span_image_finset_le (p : ι → P) (s : finset ι) {n : ℕ} (hc : finset.card s = n + 1) : finrank k (vector_span k (s.image p : set P)) ≤ n := begin have hn : (s.image p).nonempty, { rw [finset.nonempty.image_iff, ← finset.card_pos, hc], apply nat.succ_pos }, rcases hn with ⟨p₁, hp₁⟩, rw [vector_span_eq_span_vsub_finset_right_ne k hp₁], refine le_trans (finrank_span_finset_le_card (((s.image p).erase p₁).image (λ p, p -ᵥ p₁))) _, rw [finset.card_image_of_injective _ (vsub_left_injective p₁), finset.card_erase_of_mem hp₁, nat.pred_le_iff, nat.succ_eq_add_one, ← hc], apply finset.card_image_le end /-- The `vector_span` of an indexed family of `n + 1` points has dimension at most `n`. -/ lemma finrank_vector_span_range_le [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 1) : finrank k (vector_span k (set.range p)) ≤ n := begin rw [←set.image_univ, ←finset.coe_univ, ← finset.coe_image], rw ←finset.card_univ at hc, exact finrank_vector_span_image_finset_le _ _ _ hc end /-- `n + 1` points are affinely independent if and only if their `vector_span` has dimension `n`. -/ lemma affine_independent_iff_finrank_vector_span_eq [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 1) : affine_independent k p ↔ finrank k (vector_span k (set.range p)) = n := begin have hn : nonempty ι, by simp [←fintype.card_pos_iff, hc], cases hn with i₁, rw [affine_independent_iff_linear_independent_vsub _ _ i₁, linear_independent_iff_card_eq_finrank_span, eq_comm, vector_span_range_eq_span_range_vsub_right_ne k p i₁], congr', rw ←finset.card_univ at hc, rw fintype.subtype_card, simp [finset.filter_ne', finset.card_erase_of_mem, hc] end /-- `n + 1` points are affinely independent if and only if their `vector_span` has dimension at least `n`. -/ lemma affine_independent_iff_le_finrank_vector_span [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 1) : affine_independent k p ↔ n ≤ finrank k (vector_span k (set.range p)) := begin rw affine_independent_iff_finrank_vector_span_eq k p hc, split, { rintro rfl, refl }, { exact λ hle, le_antisymm (finrank_vector_span_range_le k p hc) hle } end /-- `n + 2` points are affinely independent if and only if their `vector_span` does not have dimension at most `n`. -/ lemma affine_independent_iff_not_finrank_vector_span_le [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 2) : affine_independent k p ↔ ¬ finrank k (vector_span k (set.range p)) ≤ n := by rw [affine_independent_iff_le_finrank_vector_span k p hc, ←nat.lt_iff_add_one_le, lt_iff_not_ge] /-- `n + 2` points have a `vector_span` with dimension at most `n` if and only if they are not affinely independent. -/ lemma finrank_vector_span_le_iff_not_affine_independent [fintype ι] (p : ι → P) {n : ℕ} (hc : fintype.card ι = n + 2) : finrank k (vector_span k (set.range p)) ≤ n ↔ ¬ affine_independent k p := (not_iff_comm.1 (affine_independent_iff_not_finrank_vector_span_le k p hc).symm).symm /-- A set of points is collinear if their `vector_span` has dimension at most `1`. -/ def collinear (s : set P) : Prop := module.rank k (vector_span k s) ≤ 1 /-- The definition of `collinear`. -/ lemma collinear_iff_dim_le_one (s : set P) : collinear k s ↔ module.rank k (vector_span k s) ≤ 1 := iff.rfl /-- A set of points, whose `vector_span` is finite-dimensional, is collinear if and only if their `vector_span` has dimension at most `1`. -/ lemma collinear_iff_finrank_le_one (s : set P) [finite_dimensional k (vector_span k s)] : collinear k s ↔ finrank k (vector_span k s) ≤ 1 := begin have h := collinear_iff_dim_le_one k s, rw ←finrank_eq_dim at h, exact_mod_cast h end variables (P) /-- The empty set is collinear. -/ lemma collinear_empty : collinear k (∅ : set P) := begin rw [collinear_iff_dim_le_one, vector_span_empty], simp end variables {P} /-- A single point is collinear. -/ lemma collinear_singleton (p : P) : collinear k ({p} : set P) := begin rw [collinear_iff_dim_le_one, vector_span_singleton], simp end /-- Given a point `p₀` in a set of points, that set is collinear if and only if the points can all be expressed as multiples of the same vector, added to `p₀`. -/ lemma collinear_iff_of_mem {s : set P} {p₀ : P} (h : p₀ ∈ s) : collinear k s ↔ ∃ v : V, ∀ p ∈ s, ∃ r : k, p = r • v +ᵥ p₀ := begin simp_rw [collinear_iff_dim_le_one, dim_submodule_le_one_iff', submodule.le_span_singleton_iff], split, { rintro ⟨v₀, hv⟩, use v₀, intros p hp, obtain ⟨r, hr⟩ := hv (p -ᵥ p₀) (vsub_mem_vector_span k hp h), use r, rw eq_vadd_iff_vsub_eq, exact hr.symm }, { rintro ⟨v, hp₀v⟩, use v, intros w hw, have hs : vector_span k s ≤ k ∙ v, { rw [vector_span_eq_span_vsub_set_right k h, submodule.span_le, set.subset_def], intros x hx, rw [set_like.mem_coe, submodule.mem_span_singleton], rw set.mem_image at hx, rcases hx with ⟨p, hp, rfl⟩, rcases hp₀v p hp with ⟨r, rfl⟩, use r, simp }, have hw' := set_like.le_def.1 hs hw, rwa submodule.mem_span_singleton at hw' } end /-- A set of points is collinear if and only if they can all be expressed as multiples of the same vector, added to the same base point. -/ lemma collinear_iff_exists_forall_eq_smul_vadd (s : set P) : collinear k s ↔ ∃ (p₀ : P) (v : V), ∀ p ∈ s, ∃ r : k, p = r • v +ᵥ p₀ := begin rcases set.eq_empty_or_nonempty s with rfl | ⟨⟨p₁, hp₁⟩⟩, { simp [collinear_empty] }, { rw collinear_iff_of_mem k hp₁, split, { exact λ h, ⟨p₁, h⟩ }, { rintros ⟨p, v, hv⟩, use v, intros p₂ hp₂, rcases hv p₂ hp₂ with ⟨r, rfl⟩, rcases hv p₁ hp₁ with ⟨r₁, rfl⟩, use r - r₁, simp [vadd_vadd, ←add_smul] } } end /-- Two points are collinear. -/ lemma collinear_insert_singleton (p₁ p₂ : P) : collinear k ({p₁, p₂} : set P) := begin rw collinear_iff_exists_forall_eq_smul_vadd, use [p₁, p₂ -ᵥ p₁], intros p hp, rw [set.mem_insert_iff, set.mem_singleton_iff] at hp, cases hp, { use 0, simp [hp] }, { use 1, simp [hp] } end /-- Three points are affinely independent if and only if they are not collinear. -/ lemma affine_independent_iff_not_collinear (p : fin 3 → P) : affine_independent k p ↔ ¬ collinear k (set.range p) := by rw [collinear_iff_finrank_le_one, affine_independent_iff_not_finrank_vector_span_le k p (fintype.card_fin 3)] /-- Three points are collinear if and only if they are not affinely independent. -/ lemma collinear_iff_not_affine_independent (p : fin 3 → P) : collinear k (set.range p) ↔ ¬ affine_independent k p := by rw [collinear_iff_finrank_le_one, finrank_vector_span_le_iff_not_affine_independent k p (fintype.card_fin 3)] end affine_space'
89a233a27e0808b3df35134acf402ce5be03509e
1d919b78d6a734e5de3de473660e94e055348e0d
/library/init/data/list/basic.lean
c3ae8bb093dbdb41dc31debdfa9d1eb91fd173e3
[ "Apache-2.0" ]
permissive
soraismus/lean
70db3ea85e830809cc380e99f65eebe8ee9964e6
a4aae537fe771ee92d746d4a2be1e73c543e48b9
refs/heads/master
1,584,606,830,523
1,526,634,341,000
1,526,634,341,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
9,926
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.logic init.data.nat.basic init.data.bool.basic init.propext open decidable list universes u v w instance (α : Type u) : inhabited (list α) := ⟨list.nil⟩ variables {α : Type u} {β : Type v} {γ : Type w} namespace list protected def has_dec_eq [s : decidable_eq α] : decidable_eq (list α) | [] [] := is_true rfl | (a::as) [] := is_false (λ h, list.no_confusion h) | [] (b::bs) := is_false (λ h, list.no_confusion h) | (a::as) (b::bs) := match s a b with | is_true hab := match has_dec_eq as bs with | is_true habs := is_true (eq.subst hab (eq.subst habs rfl)) | is_false nabs := is_false (λ h, list.no_confusion h (λ _ habs, absurd habs nabs)) end | is_false nab := is_false (λ h, list.no_confusion h (λ hab _, absurd hab nab)) end instance [decidable_eq α] : decidable_eq (list α) := list.has_dec_eq @[simp] protected def append : list α → list α → list α | [] l := l | (h :: s) t := h :: (append s t) instance : has_append (list α) := ⟨list.append⟩ protected def mem : α → list α → Prop | a [] := false | a (b :: l) := a = b ∨ mem a l instance : has_mem α (list α) := ⟨list.mem⟩ instance decidable_mem [decidable_eq α] (a : α) : ∀ (l : list α), decidable (a ∈ l) | [] := is_false not_false | (b::l) := if h₁ : a = b then is_true (or.inl h₁) else match decidable_mem l with | is_true h₂ := is_true (or.inr h₂) | is_false h₂ := is_false (not_or h₁ h₂) end instance : has_emptyc (list α) := ⟨list.nil⟩ protected def erase {α} [decidable_eq α] : list α → α → list α | [] b := [] | (a::l) b := if a = b then l else a :: erase l b protected def bag_inter {α} [decidable_eq α] : list α → list α → list α | [] _ := [] | _ [] := [] | (a::l₁) l₂ := if a ∈ l₂ then a :: bag_inter l₁ (l₂.erase a) else bag_inter l₁ l₂ protected def diff {α} [decidable_eq α] : list α → list α → list α | l [] := l | l₁ (a::l₂) := if a ∈ l₁ then diff (l₁.erase a) l₂ else diff l₁ l₂ @[simp] def length : list α → nat | [] := 0 | (a :: l) := length l + 1 def empty : list α → bool | [] := tt | (_ :: _) := ff open option nat @[simp] def nth : list α → nat → option α | [] n := none | (a :: l) 0 := some a | (a :: l) (n+1) := nth l n @[simp] def nth_le : Π (l : list α) (n), n < l.length → α | [] n h := absurd h (not_lt_zero n) | (a :: l) 0 h := a | (a :: l) (n+1) h := nth_le l n (le_of_succ_le_succ h) @[simp] def head [inhabited α] : list α → α | [] := default α | (a :: l) := a @[simp] def tail : list α → list α | [] := [] | (a :: l) := l def reverse_core : list α → list α → list α | [] r := r | (a::l) r := reverse_core l (a::r) def reverse : list α → list α := λ l, reverse_core l [] @[simp] def map (f : α → β) : list α → list β | [] := [] | (a :: l) := f a :: map l @[simp] def map₂ (f : α → β → γ) : list α → list β → list γ | [] _ := [] | _ [] := [] | (x::xs) (y::ys) := f x y :: map₂ xs ys def join : list (list α) → list α | [] := [] | (l :: ls) := l ++ join ls def filter_map (f : α → option β) : list α → list β | [] := [] | (a::l) := match f a with | none := filter_map l | some b := b :: filter_map l end def filter (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then a :: filter l else filter l def partition (p : α → Prop) [decidable_pred p] : list α → list α × list α | [] := ([], []) | (a::l) := let (l₁, l₂) := partition l in if p a then (a :: l₁, l₂) else (l₁, a :: l₂) def drop_while (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then drop_while l else a::l def span (p : α → Prop) [decidable_pred p] : list α → list α × list α | [] := ([], []) | (a::xs) := if p a then let (l, r) := span xs in (a :: l, r) else ([], a::xs) def find_index (p : α → Prop) [decidable_pred p] : list α → nat | [] := 0 | (a::l) := if p a then 0 else succ (find_index l) def index_of [decidable_eq α] (a : α) : list α → nat := find_index (eq a) def remove_all [decidable_eq α] (xs ys : list α) : list α := filter (∉ ys) xs def update_nth : list α → ℕ → α → list α | (x::xs) 0 a := a :: xs | (x::xs) (i+1) a := x :: update_nth xs i a | [] _ _ := [] def remove_nth : list α → ℕ → list α | [] _ := [] | (x::xs) 0 := xs | (x::xs) (i+1) := x :: remove_nth xs i @[simp] def drop : ℕ → list α → list α | 0 a := a | (succ n) [] := [] | (succ n) (x::r) := drop n r @[simp] def take : ℕ → list α → list α | 0 a := [] | (succ n) [] := [] | (succ n) (x :: r) := x :: take n r @[simp] def foldl (f : α → β → α) : α → list β → α | a [] := a | a (b :: l) := foldl (f a b) l @[simp] def foldr (f : α → β → β) (b : β) : list α → β | [] := b | (a :: l) := f a (foldr l) def any (l : list α) (p : α → bool) : bool := foldr (λ a r, p a || r) ff l def all (l : list α) (p : α → bool) : bool := foldr (λ a r, p a && r) tt l def bor (l : list bool) : bool := any l id def band (l : list bool) : bool := all l id def zip_with (f : α → β → γ) : list α → list β → list γ | (x::xs) (y::ys) := f x y :: zip_with xs ys | _ _ := [] def zip : list α → list β → list (prod α β) := zip_with prod.mk def unzip : list (α × β) → list α × list β | [] := ([], []) | ((a, b) :: t) := match unzip t with (al, bl) := (a::al, b::bl) end protected def insert [decidable_eq α] (a : α) (l : list α) : list α := if a ∈ l then l else a :: l instance [decidable_eq α] : has_insert α (list α) := ⟨list.insert⟩ protected def union [decidable_eq α] (l₁ l₂ : list α) : list α := foldr insert l₂ l₁ instance [decidable_eq α] : has_union (list α) := ⟨list.union⟩ protected def inter [decidable_eq α] (l₁ l₂ : list α) : list α := filter (∈ l₂) l₁ instance [decidable_eq α] : has_inter (list α) := ⟨list.inter⟩ @[simp] def repeat (a : α) : ℕ → list α | 0 := [] | (succ n) := a :: repeat n def range_core : ℕ → list ℕ → list ℕ | 0 l := l | (succ n) l := range_core n (n :: l) def range (n : ℕ) : list ℕ := range_core n [] def iota : ℕ → list ℕ | 0 := [] | (succ n) := succ n :: iota n def enum_from : ℕ → list α → list (ℕ × α) | n [] := nil | n (x :: xs) := (n, x) :: enum_from (n + 1) xs def enum : list α → list (ℕ × α) := enum_from 0 @[simp] def last : Π l : list α, l ≠ [] → α | [] h := absurd rfl h | [a] h := a | (a::b::l) h := last (b::l) (λ h, list.no_confusion h) def ilast [inhabited α] : list α → α | [] := arbitrary α | [a] := a | [a, b] := b | (a::b::l) := ilast l def init : list α → list α | [] := [] | [a] := [] | (a::l) := a::init l def intersperse (sep : α) : list α → list α | [] := [] | [x] := [x] | (x::xs) := x::sep::intersperse xs def intercalate (sep : list α) (xs : list (list α)) : list α := join (intersperse sep xs) @[inline] protected def bind {α : Type u} {β : Type v} (a : list α) (b : α → list β) : list β := join (map b a) @[inline] protected def ret {α : Type u} (a : α) : list α := [a] protected def lt [has_lt α] : list α → list α → Prop | [] [] := false | [] (b::bs) := true | (a::as) [] := false | (a::as) (b::bs) := a < b ∨ lt as bs instance [has_lt α] : has_lt (list α) := ⟨list.lt⟩ instance has_decidable_lt [has_lt α] [h : decidable_rel ((<) : α → α → Prop)] : Π l₁ l₂ : list α, decidable (l₁ < l₂) | [] [] := is_false not_false | [] (b::bs) := is_true trivial | (a::as) [] := is_false not_false | (a::as) (b::bs) := match h a b with | is_true h₁ := is_true (or.inl h₁) | is_false h₁ := match has_decidable_lt as bs with | is_true h₂ := is_true (or.inr h₂) | is_false h₂ := is_false (λ hd, or.elim hd (λ n₁, absurd n₁ h₁) (λ n₂, absurd n₂ h₂)) end end @[reducible] protected def le [has_lt α] (a b : list α) : Prop := ¬ b < a instance [has_lt α] : has_le (list α) := ⟨list.le⟩ instance has_decidable_le [has_lt α] [h : decidable_rel ((<) : α → α → Prop)] : Π l₁ l₂ : list α, decidable (l₁ ≤ l₂) := λ a b, not.decidable lemma le_eq_not_gt [has_lt α] : ∀ l₁ l₂ : list α, (l₁ ≤ l₂) = ¬ (l₂ < l₁) := λ l₁ l₂, rfl lemma lt_eq_not_ge [has_lt α] [decidable_rel ((<) : α → α → Prop)] : ∀ l₁ l₂ : list α, (l₁ < l₂) = ¬ (l₂ ≤ l₁) := λ l₁ l₂, show (l₁ < l₂) = ¬ ¬ (l₁ < l₂), from eq.subst (propext (not_not_iff (l₁ < l₂))).symm rfl /-- `is_prefix_of l₁ l₂` returns `tt` iff `l₁` is a prefix of `l₂`. -/ def is_prefix_of [decidable_eq α] : list α → list α → bool | [] _ := tt | _ [] := ff | (a::as) (b::bs) := to_bool (a = b) && is_prefix_of as bs /-- `is_suffix_of l₁ l₂` returns `tt` iff `l₁` is a suffix of `l₂`. -/ def is_suffix_of [decidable_eq α] (l₁ l₂ : list α) : bool := is_prefix_of l₁.reverse l₂.reverse end list namespace bin_tree private def to_list_aux : bin_tree α → list α → list α | empty as := as | (leaf a) as := a::as | (node l r) as := to_list_aux l (to_list_aux r as) def to_list (t : bin_tree α) : list α := to_list_aux t [] end bin_tree
9c4ba468bf47fa6c1e54a58d947f3452056dba6e
bb31430994044506fa42fd667e2d556327e18dfe
/src/number_theory/padics/padic_val.lean
67493b8b5f2bf4fb2cde4c7116fed48b68802c44
[ "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
19,956
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 number_theory.divisors import ring_theory.int.basic import tactic.ring_exp /-! # p-adic Valuation This file defines the `p`-adic valuation on `ℕ`, `ℤ`, and `ℚ`. The `p`-adic valuation on `ℚ` is the difference of the multiplicities of `p` in the numerator and denominator of `q`. This function obeys the standard properties of a valuation, with the appropriate assumptions on `p`. The `p`-adic valuations on `ℕ` and `ℤ` agree with that on `ℚ`. The valuation induces a norm on `ℚ`. This norm is defined in padic_norm.lean. ## Notations This file uses the local notation `/.` for `rat.mk`. ## Implementation notes Much, but not all, of this file assumes that `p` is prime. This assumption is inferred automatically by taking `[fact p.prime]` as a type class argument. ## References * [F. Q. Gouvêa, *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 -/ universe u open nat open_locale rat open multiplicity /-- For `p ≠ 1`, the `p`-adic valuation of a natural `n ≠ 0` is the largest natural number `k` such that `p^k` divides `z`. If `n = 0` or `p = 1`, then `padic_val_nat p q` defaults to `0`. -/ def padic_val_nat (p : ℕ) (n : ℕ) : ℕ := if h : p ≠ 1 ∧ 0 < n then (multiplicity p n).get (multiplicity.finite_nat_iff.2 h) else 0 namespace padic_val_nat open multiplicity variables {p : ℕ} /-- `padic_val_nat p 0` is `0` for any `p`. -/ @[simp] protected lemma zero : padic_val_nat p 0 = 0 := by simp [padic_val_nat] /-- `padic_val_nat p 1` is `0` for any `p`. -/ @[simp] protected lemma one : padic_val_nat p 1 = 0 := by { unfold padic_val_nat, split_ifs, simp } /-- If `p ≠ 0` and `p ≠ 1`, then `padic_val_rat p p` is `1`. -/ @[simp] lemma self (hp : 1 < p) : padic_val_nat p p = 1 := begin have neq_one : (¬ p = 1) ↔ true, { exact iff_of_true ((ne_of_lt hp).symm) trivial }, have eq_zero_false : p = 0 ↔ false, { exact iff_false_intro ((ne_of_lt (trans zero_lt_one hp)).symm) }, simp [padic_val_nat, neq_one, eq_zero_false] end @[simp] lemma eq_zero_iff {n : ℕ} : padic_val_nat p n = 0 ↔ p = 1 ∨ n = 0 ∨ ¬ p ∣ n := by simp only [padic_val_nat, dite_eq_right_iff, part_enat.get_eq_iff_eq_coe, nat.cast_zero, multiplicity_eq_zero, and_imp, pos_iff_ne_zero, ne.def, ← or_iff_not_imp_left] lemma eq_zero_of_not_dvd {n : ℕ} (h : ¬ p ∣ n) : padic_val_nat p n = 0 := eq_zero_iff.2 $ or.inr $ or.inr h end padic_val_nat /-- For `p ≠ 1`, the `p`-adic valuation of an integer `z ≠ 0` is the largest natural number `k` such that `p^k` divides `z`. If `x = 0` or `p = 1`, then `padic_val_int p q` defaults to `0`. -/ def padic_val_int (p : ℕ) (z : ℤ) : ℕ := padic_val_nat p z.nat_abs namespace padic_val_int open multiplicity variables {p : ℕ} lemma of_ne_one_ne_zero {z : ℤ} (hp : p ≠ 1) (hz : z ≠ 0) : padic_val_int p z = (multiplicity (p : ℤ) z).get (by {apply multiplicity.finite_int_iff.2, simp [hp, hz]}) := begin rw [padic_val_int, padic_val_nat, dif_pos (and.intro hp (int.nat_abs_pos_of_ne_zero hz))], simp only [multiplicity.int.nat_abs p z], refl end /-- `padic_val_int p 0` is `0` for any `p`. -/ @[simp] protected lemma zero : padic_val_int p 0 = 0 := by simp [padic_val_int] /-- `padic_val_int p 1` is `0` for any `p`. -/ @[simp] protected lemma one : padic_val_int p 1 = 0 := by simp [padic_val_int] /-- The `p`-adic value of a natural is its `p`-adic value as an integer. -/ @[simp] lemma of_nat {n : ℕ} : padic_val_int p n = padic_val_nat p n := by simp [padic_val_int] /-- If `p ≠ 0` and `p ≠ 1`, then `padic_val_int p p` is `1`. -/ lemma self (hp : 1 < p) : padic_val_int p p = 1 := by simp [padic_val_nat.self hp] lemma eq_zero_of_not_dvd {z : ℤ} (h : ¬ (p : ℤ) ∣ z) : padic_val_int p z = 0 := begin rw [padic_val_int, padic_val_nat], split_ifs; simp [multiplicity.int.nat_abs, multiplicity_eq_zero.2 h], end end padic_val_int /-- `padic_val_rat` defines the valuation of a rational `q` to be the valuation of `q.num` minus the valuation of `q.denom`. If `q = 0` or `p = 1`, then `padic_val_rat p q` defaults to `0`. -/ def padic_val_rat (p : ℕ) (q : ℚ) : ℤ := padic_val_int p q.num - padic_val_nat p q.denom namespace padic_val_rat open multiplicity variables {p : ℕ} /-- `padic_val_rat p q` is symmetric in `q`. -/ @[simp] protected lemma neg (q : ℚ) : padic_val_rat p (-q) = padic_val_rat p q := by simp [padic_val_rat, padic_val_int] /-- `padic_val_rat p 0` is `0` for any `p`. -/ @[simp] protected lemma zero : padic_val_rat p 0 = 0 := by simp [padic_val_rat] /-- `padic_val_rat p 1` is `0` for any `p`. -/ @[simp] protected lemma one : padic_val_rat p 1 = 0 := by simp [padic_val_rat] /-- The `p`-adic value of an integer `z ≠ 0` is its `p`-adic_value as a rational. -/ @[simp] lemma of_int {z : ℤ} : padic_val_rat p z = padic_val_int p z := by simp [padic_val_rat] /-- The `p`-adic value of an integer `z ≠ 0` is the multiplicity of `p` in `z`. -/ lemma of_int_multiplicity {z : ℤ} (hp : p ≠ 1) (hz : z ≠ 0) : padic_val_rat p (z : ℚ) = (multiplicity (p : ℤ) z).get (finite_int_iff.2 ⟨hp, hz⟩) := by rw [of_int, padic_val_int.of_ne_one_ne_zero hp hz] lemma multiplicity_sub_multiplicity {q : ℚ} (hp : p ≠ 1) (hq : q ≠ 0) : padic_val_rat p q = (multiplicity (p : ℤ) q.num).get (finite_int_iff.2 ⟨hp, rat.num_ne_zero_of_ne_zero hq⟩) - (multiplicity p q.denom).get (by { rw [← finite_iff_dom, finite_nat_iff], exact ⟨hp, q.pos⟩ }) := begin rw [padic_val_rat, padic_val_int.of_ne_one_ne_zero hp, padic_val_nat, dif_pos], { refl }, { exact ⟨hp, q.pos⟩ }, { exact rat.num_ne_zero_of_ne_zero hq } end /-- The `p`-adic value of an integer `z ≠ 0` is its `p`-adic value as a rational. -/ @[simp] lemma of_nat {n : ℕ} : padic_val_rat p n = padic_val_nat p n := by simp [padic_val_rat] /-- If `p ≠ 0` and `p ≠ 1`, then `padic_val_rat p p` is `1`. -/ lemma self (hp : 1 < p) : padic_val_rat p p = 1 := by simp [hp] end padic_val_rat section padic_val_nat variables {p : ℕ} lemma zero_le_padic_val_rat_of_nat (n : ℕ) : 0 ≤ padic_val_rat p n := by simp /-- `padic_val_rat` coincides with `padic_val_nat`. -/ @[norm_cast] lemma padic_val_rat_of_nat (n : ℕ) : ↑(padic_val_nat p n) = padic_val_rat p n := by simp /-- A simplification of `padic_val_nat` when one input is prime, by analogy with `padic_val_rat_def`. -/ lemma padic_val_nat_def [hp : fact p.prime] {n : ℕ} (hn : 0 < n) : padic_val_nat p n = (multiplicity p n).get (multiplicity.finite_nat_iff.2 ⟨hp.out.ne_one, hn⟩) := dif_pos ⟨hp.out.ne_one, hn⟩ lemma padic_val_nat_def' {n : ℕ} (hp : p ≠ 1) (hn : 0 < n) : ↑(padic_val_nat p n) = multiplicity p n := by simp [padic_val_nat, hp, hn] @[simp] lemma padic_val_nat_self [fact p.prime] : padic_val_nat p p = 1 := by simp [padic_val_nat_def (fact.out p.prime).pos] lemma one_le_padic_val_nat_of_dvd {n : ℕ} [hp : fact p.prime] (hn : 0 < n) (div : p ∣ n) : 1 ≤ padic_val_nat p n := by rwa [← part_enat.coe_le_coe, padic_val_nat_def' hp.out.ne_one hn, ← pow_dvd_iff_le_multiplicity, pow_one] lemma dvd_iff_padic_val_nat_ne_zero {p n : ℕ} [fact p.prime] (hn0 : n ≠ 0) : (p ∣ n) ↔ padic_val_nat p n ≠ 0 := ⟨λ h, one_le_iff_ne_zero.mp (one_le_padic_val_nat_of_dvd hn0.bot_lt h), λ h, not_not.1 (mt padic_val_nat.eq_zero_of_not_dvd h)⟩ end padic_val_nat namespace padic_val_rat open multiplicity variables {p : ℕ} [hp : fact p.prime] include hp /-- The multiplicity of `p : ℕ` in `a : ℤ` is finite exactly when `a ≠ 0`. -/ lemma finite_int_prime_iff {a : ℤ} : finite (p : ℤ) a ↔ a ≠ 0 := by simp [finite_int_iff, ne.symm (ne_of_lt hp.1.one_lt)] /-- A rewrite lemma for `padic_val_rat p q` when `q` is expressed in terms of `rat.mk`. -/ protected lemma defn (p : ℕ) [hp : fact p.prime] {q : ℚ} {n d : ℤ} (hqz : q ≠ 0) (qdf : q = n /. d) : padic_val_rat p q = (multiplicity (p : ℤ) n).get (finite_int_iff.2 ⟨ne.symm $ ne_of_lt hp.1.one_lt, λ hn, by simp * at *⟩) - (multiplicity (p : ℤ) d).get (finite_int_iff.2 ⟨ne.symm $ ne_of_lt hp.1.one_lt, λ hd, by simp * at *⟩) := have hd : d ≠ 0, from rat.mk_denom_ne_zero_of_ne_zero hqz qdf, let ⟨c, hc1, hc2⟩ := rat.num_denom_mk hd qdf in begin rw [padic_val_rat.multiplicity_sub_multiplicity]; simp [hc1, hc2, multiplicity.mul' (nat.prime_iff_prime_int.1 hp.1), ne.symm (ne_of_lt hp.1.one_lt), hqz, pos_iff_ne_zero, int.coe_nat_multiplicity p q.denom] end /-- A rewrite lemma for `padic_val_rat p (q * r)` with conditions `q ≠ 0`, `r ≠ 0`. -/ protected lemma mul {q r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) : padic_val_rat p (q * r) = padic_val_rat p q + padic_val_rat p r := have q * r = (q.num * r.num) /. (q.denom * r.denom), by rw_mod_cast rat.mul_num_denom, have hq' : q.num /. q.denom ≠ 0, by rw rat.num_denom; exact hq, have hr' : r.num /. r.denom ≠ 0, by rw rat.num_denom; exact hr, have hp' : _root_.prime (p : ℤ), from nat.prime_iff_prime_int.1 hp.1, begin rw [padic_val_rat.defn p (mul_ne_zero hq hr) this], conv_rhs { rw [← @rat.num_denom q, padic_val_rat.defn p hq', ← @rat.num_denom r, padic_val_rat.defn p hr'] }, rw [multiplicity.mul' hp', multiplicity.mul' hp']; simp [add_comm, add_left_comm, sub_eq_add_neg] end /-- A rewrite lemma for `padic_val_rat p (q^k)` with condition `q ≠ 0`. -/ protected lemma pow {q : ℚ} (hq : q ≠ 0) {k : ℕ} : padic_val_rat p (q ^ k) = k * padic_val_rat p q := by induction k; simp [*, padic_val_rat.mul hq (pow_ne_zero _ hq), pow_succ, add_mul, add_comm] /-- A rewrite lemma for `padic_val_rat p (q⁻¹)` with condition `q ≠ 0`. -/ protected lemma inv (q : ℚ) : padic_val_rat p q⁻¹ = -padic_val_rat p q := begin by_cases hq : q = 0, { simp [hq] }, { rw [eq_neg_iff_add_eq_zero, ← padic_val_rat.mul (inv_ne_zero hq) hq, inv_mul_cancel hq, padic_val_rat.one], exact hp }, end /-- A rewrite lemma for `padic_val_rat p (q / r)` with conditions `q ≠ 0`, `r ≠ 0`. -/ protected lemma div {q r : ℚ} (hq : q ≠ 0) (hr : r ≠ 0) : padic_val_rat p (q / r) = padic_val_rat p q - padic_val_rat p r := begin rw [div_eq_mul_inv, padic_val_rat.mul hq (inv_ne_zero hr), padic_val_rat.inv r, sub_eq_add_neg], all_goals { exact hp } end /-- A condition for `padic_val_rat p (n₁ / d₁) ≤ padic_val_rat p (n₂ / d₂)`, in terms of divisibility by `p^n`. -/ lemma padic_val_rat_le_padic_val_rat_iff {n₁ n₂ d₁ d₂ : ℤ} (hn₁ : n₁ ≠ 0) (hn₂ : n₂ ≠ 0) (hd₁ : d₁ ≠ 0) (hd₂ : d₂ ≠ 0) : padic_val_rat p (n₁ /. d₁) ≤ padic_val_rat p (n₂ /. d₂) ↔ ∀ n : ℕ, ↑p ^ n ∣ n₁ * d₂ → ↑p ^ n ∣ n₂ * d₁ := have hf1 : finite (p : ℤ) (n₁ * d₂), from finite_int_prime_iff.2 (mul_ne_zero hn₁ hd₂), have hf2 : finite (p : ℤ) (n₂ * d₁), from finite_int_prime_iff.2 (mul_ne_zero hn₂ hd₁), by conv { to_lhs, rw [padic_val_rat.defn p (rat.mk_ne_zero_of_ne_zero hn₁ hd₁) rfl, padic_val_rat.defn p (rat.mk_ne_zero_of_ne_zero hn₂ hd₂) rfl, sub_le_iff_le_add', ← add_sub_assoc, le_sub_iff_add_le], norm_cast, rw [← multiplicity.mul' (nat.prime_iff_prime_int.1 hp.1) hf1, add_comm, ← multiplicity.mul' (nat.prime_iff_prime_int.1 hp.1) hf2, part_enat.get_le_get, multiplicity_le_multiplicity_iff] } /-- Sufficient conditions to show that the `p`-adic valuation of `q` is less than or equal to the `p`-adic valuation of `q + r`. -/ theorem le_padic_val_rat_add_of_le {q r : ℚ} (hqr : q + r ≠ 0) (h : padic_val_rat p q ≤ padic_val_rat p r) : padic_val_rat p q ≤ padic_val_rat p (q + r) := if hq : q = 0 then by simpa [hq] using h else if hr : r = 0 then by simp [hr] else have hqn : q.num ≠ 0, from rat.num_ne_zero_of_ne_zero hq, have hqd : (q.denom : ℤ) ≠ 0, by exact_mod_cast rat.denom_ne_zero _, have hrn : r.num ≠ 0, from rat.num_ne_zero_of_ne_zero hr, have hrd : (r.denom : ℤ) ≠ 0, by exact_mod_cast rat.denom_ne_zero _, have hqreq : q + r = (q.num * r.denom + q.denom * r.num) /. (q.denom * r.denom), from rat.add_num_denom _ _, have hqrd : q.num * r.denom + q.denom * r.num ≠ 0, from rat.mk_num_ne_zero_of_ne_zero hqr hqreq, begin conv_lhs { rw ← @rat.num_denom q }, rw [hqreq, padic_val_rat_le_padic_val_rat_iff hqn hqrd hqd (mul_ne_zero hqd hrd), ← multiplicity_le_multiplicity_iff, mul_left_comm, multiplicity.mul (nat.prime_iff_prime_int.1 hp.1), add_mul], rw [← @rat.num_denom q, ← @rat.num_denom r, padic_val_rat_le_padic_val_rat_iff hqn hrn hqd hrd, ← multiplicity_le_multiplicity_iff] at h, calc _ ≤ min (multiplicity ↑p (q.num * ↑r.denom * ↑q.denom)) (multiplicity ↑p (↑q.denom * r.num * ↑q.denom)) : (le_min (by rw [@multiplicity.mul _ _ _ _ (_ * _) _ (nat.prime_iff_prime_int.1 hp.1), add_comm]) (by rw [mul_assoc, @multiplicity.mul _ _ _ _ (q.denom : ℤ) (_ * _) (nat.prime_iff_prime_int.1 hp.1)]; exact add_le_add_left h _)) ... ≤ _ : min_le_multiplicity_add, all_goals { exact hp } end /-- The minimum of the valuations of `q` and `r` is at most the valuation of `q + r`. -/ theorem min_le_padic_val_rat_add {q r : ℚ} (hqr : q + r ≠ 0) : min (padic_val_rat p q) (padic_val_rat p r) ≤ padic_val_rat p (q + r) := (le_total (padic_val_rat p q) (padic_val_rat p r)).elim (λ h, by rw [min_eq_left h]; exact le_padic_val_rat_add_of_le hqr h) (λ h, by rw [min_eq_right h, add_comm]; exact le_padic_val_rat_add_of_le (by rwa add_comm) h) open_locale big_operators /-- A finite sum of rationals with positive `p`-adic valuation has positive `p`-adic valuation (if the sum is non-zero). -/ theorem sum_pos_of_pos {n : ℕ} {F : ℕ → ℚ} (hF : ∀ i, i < n → 0 < padic_val_rat p (F i)) (hn0 : ∑ i in finset.range n, F i ≠ 0) : 0 < padic_val_rat p (∑ i in finset.range n, F i) := begin induction n with d hd, { exact false.elim (hn0 rfl) }, { rw finset.sum_range_succ at hn0 ⊢, by_cases h : ∑ (x : ℕ) in finset.range d, F x = 0, { rw [h, zero_add], exact hF d (lt_add_one _) }, { refine lt_of_lt_of_le _ (min_le_padic_val_rat_add hn0), { refine lt_min (hd (λ i hi, _) h) (hF d (lt_add_one _)), exact hF _ (lt_trans hi (lt_add_one _)) } } } end end padic_val_rat namespace padic_val_nat variables {p a b : ℕ} [hp : fact p.prime] include hp /-- A rewrite lemma for `padic_val_nat p (a * b)` with conditions `a ≠ 0`, `b ≠ 0`. -/ protected lemma mul : a ≠ 0 → b ≠ 0 → padic_val_nat p (a * b) = padic_val_nat p a + padic_val_nat p b := by exact_mod_cast @padic_val_rat.mul p _ a b protected lemma div_of_dvd (h : b ∣ a) : padic_val_nat p (a / b) = padic_val_nat p a - padic_val_nat p b := begin rcases eq_or_ne a 0 with rfl | ha, { simp }, obtain ⟨k, rfl⟩ := h, obtain ⟨hb, hk⟩ := mul_ne_zero_iff.mp ha, rw [mul_comm, k.mul_div_cancel hb.bot_lt, padic_val_nat.mul hk hb, nat.add_sub_cancel], exact hp end /-- Dividing out by a prime factor reduces the `padic_val_nat` by `1`. -/ protected lemma div (dvd : p ∣ b) : padic_val_nat p (b / p) = (padic_val_nat p b) - 1 := begin convert padic_val_nat.div_of_dvd dvd, rw padic_val_nat_self, exact hp end /-- A version of `padic_val_rat.pow` for `padic_val_nat`. -/ protected lemma pow (n : ℕ) (ha : a ≠ 0) : padic_val_nat p (a ^ n) = n * padic_val_nat p a := by simpa only [← @nat.cast_inj ℤ] with push_cast using padic_val_rat.pow (cast_ne_zero.mpr ha) @[simp] protected lemma prime_pow (n : ℕ) : padic_val_nat p (p ^ n) = n := by rwa [padic_val_nat.pow _ (fact.out p.prime).ne_zero, padic_val_nat_self, mul_one] protected lemma div_pow (dvd : p ^ a ∣ b) : padic_val_nat p (b / p ^ a) = (padic_val_nat p b) - a := begin rw [padic_val_nat.div_of_dvd dvd, padic_val_nat.prime_pow], exact hp end protected lemma div' {m : ℕ} (cpm : coprime p m) {b : ℕ} (dvd : m ∣ b) : padic_val_nat p (b / m) = padic_val_nat p b := by rw [padic_val_nat.div_of_dvd dvd, eq_zero_of_not_dvd (hp.out.coprime_iff_not_dvd.mp cpm), nat.sub_zero]; assumption end padic_val_nat section padic_val_nat variables {p : ℕ} lemma dvd_of_one_le_padic_val_nat {n : ℕ} (hp : 1 ≤ padic_val_nat p n) : p ∣ n := begin by_contra h, rw padic_val_nat.eq_zero_of_not_dvd h at hp, exact lt_irrefl 0 (lt_of_lt_of_le zero_lt_one hp) end lemma pow_padic_val_nat_dvd {n : ℕ} : p ^ padic_val_nat p n ∣ n := begin rcases n.eq_zero_or_pos with rfl | hn, { simp }, rcases eq_or_ne p 1 with rfl | hp, { simp }, rw [multiplicity.pow_dvd_iff_le_multiplicity, padic_val_nat_def']; assumption end lemma padic_val_nat_dvd_iff_le [hp : fact p.prime] {a n : ℕ} (ha : a ≠ 0) : p ^ n ∣ a ↔ n ≤ padic_val_nat p a := by rw [pow_dvd_iff_le_multiplicity, ← padic_val_nat_def' hp.out.ne_one ha.bot_lt, part_enat.coe_le_coe] lemma padic_val_nat_dvd_iff (n : ℕ) [hp : fact p.prime] (a : ℕ) : p ^ n ∣ a ↔ a = 0 ∨ n ≤ padic_val_nat p a := begin rcases eq_or_ne a 0 with rfl | ha, { exact iff_of_true (dvd_zero _) (or.inl rfl) }, { simp only [ha, false_or, padic_val_nat_dvd_iff_le ha] } end lemma pow_succ_padic_val_nat_not_dvd {n : ℕ} [hp : fact p.prime] (hn : n ≠ 0) : ¬ p ^ (padic_val_nat p n + 1) ∣ n := begin rw [padic_val_nat_dvd_iff_le hn, not_le], exacts [nat.lt_succ_self _, hp] end lemma padic_val_nat_primes {q : ℕ} [hp : fact p.prime] [hq : fact q.prime] (neq : p ≠ q) : padic_val_nat p q = 0 := @padic_val_nat.eq_zero_of_not_dvd p q $ (not_congr (iff.symm (prime_dvd_prime_iff_eq hp.1 hq.1))).mp neq open_locale big_operators lemma range_pow_padic_val_nat_subset_divisors {n : ℕ} (hn : n ≠ 0) : (finset.range (padic_val_nat p n + 1)).image (pow p) ⊆ n.divisors := begin intros t ht, simp only [exists_prop, finset.mem_image, finset.mem_range] at ht, obtain ⟨k, hk, rfl⟩ := ht, rw nat.mem_divisors, exact ⟨(pow_dvd_pow p $ by linarith).trans pow_padic_val_nat_dvd, hn⟩ end lemma range_pow_padic_val_nat_subset_divisors' {n : ℕ} [hp : fact p.prime] : (finset.range (padic_val_nat p n)).image (λ t, p ^ (t + 1)) ⊆ n.divisors.erase 1 := begin rcases eq_or_ne n 0 with rfl | hn, { simp }, intros t ht, simp only [exists_prop, finset.mem_image, finset.mem_range] at ht, obtain ⟨k, hk, rfl⟩ := ht, rw [finset.mem_erase, nat.mem_divisors], refine ⟨_, (pow_dvd_pow p $ succ_le_iff.2 hk).trans pow_padic_val_nat_dvd, hn⟩, exact (nat.one_lt_pow _ _ k.succ_pos hp.out.one_lt).ne' end end padic_val_nat section padic_val_int variables {p : ℕ} [hp : fact p.prime] include hp lemma padic_val_int_dvd_iff (n : ℕ) (a : ℤ) : (p : ℤ) ^ n ∣ a ↔ a = 0 ∨ n ≤ padic_val_int p a := by rw [padic_val_int, ← int.nat_abs_eq_zero, ← padic_val_nat_dvd_iff, ← int.coe_nat_dvd_left, int.coe_nat_pow] lemma padic_val_int_dvd (a : ℤ) : (p : ℤ) ^ padic_val_int p a ∣ a := begin rw padic_val_int_dvd_iff, exact or.inr le_rfl end lemma padic_val_int_self : padic_val_int p p = 1 := padic_val_int.self hp.out.one_lt lemma padic_val_int.mul {a b : ℤ} (ha : a ≠ 0) (hb : b ≠ 0) : padic_val_int p (a * b) = padic_val_int p a + padic_val_int p b := begin simp_rw padic_val_int, rw [int.nat_abs_mul, padic_val_nat.mul]; rwa int.nat_abs_ne_zero end lemma padic_val_int_mul_eq_succ (a : ℤ) (ha : a ≠ 0) : padic_val_int p (a * p) = (padic_val_int p a) + 1 := begin rw padic_val_int.mul ha (int.coe_nat_ne_zero.mpr hp.out.ne_zero), simp only [eq_self_iff_true, padic_val_int.of_nat, padic_val_nat_self], exact hp end end padic_val_int
1ab1da6ab25bfe2189cfba48dbfc5cf197878b0e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/sets/closeds.lean
dbe085444079e428d6dfefcdb3f27e09a836cc1c
[ "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
9,285
lean
/- Copyright (c) 2020 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Yaël Dillies -/ import topology.sets.opens /-! # Closed sets > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define a few types of closed sets in a topological space. ## Main Definitions For a topological space `α`, * `closeds α`: The type of closed sets. * `clopens α`: The type of clopen sets. -/ open order order_dual set variables {ι α β : Type*} [topological_space α] [topological_space β] namespace topological_space /-! ### Closed sets -/ /-- The type of closed subsets of a topological space. -/ structure closeds (α : Type*) [topological_space α] := (carrier : set α) (closed' : is_closed carrier) namespace closeds variables {α} instance : set_like (closeds α) α := { coe := closeds.carrier, coe_injective' := λ s t h, by { cases s, cases t, congr' } } lemma closed (s : closeds α) : is_closed (s : set α) := s.closed' @[ext] protected lemma ext {s t : closeds α} (h : (s : set α) = t) : s = t := set_like.ext' h @[simp] lemma coe_mk (s : set α) (h) : (mk s h : set α) = s := rfl /-- The closure of a set, as an element of `closeds`. -/ protected def closure (s : set α) : closeds α := ⟨closure s, is_closed_closure⟩ lemma gc : galois_connection closeds.closure (coe : closeds α → set α) := λ s U, ⟨subset_closure.trans, λ h, closure_minimal h U.closed⟩ /-- The galois coinsertion between sets and opens. -/ def gi : galois_insertion (@closeds.closure α _) coe := { choice := λ s hs, ⟨s, closure_eq_iff_is_closed.1 $ hs.antisymm subset_closure⟩, gc := gc, le_l_u := λ _, subset_closure, choice_eq := λ s hs, set_like.coe_injective $ subset_closure.antisymm hs } instance : complete_lattice (closeds α) := complete_lattice.copy (galois_insertion.lift_complete_lattice gi) /- le -/ _ rfl /- top -/ ⟨univ, is_closed_univ⟩ rfl /- bot -/ ⟨∅, is_closed_empty⟩ (set_like.coe_injective closure_empty.symm) /- sup -/ (λ s t, ⟨s ∪ t, s.2.union t.2⟩) (funext $ λ s, funext $ λ t, set_like.coe_injective (s.2.union t.2).closure_eq.symm) /- inf -/ (λ s t, ⟨s ∩ t, s.2.inter t.2⟩) rfl /- Sup -/ _ rfl /- Inf -/ (λ S, ⟨⋂ s ∈ S, ↑s, is_closed_bInter $ λ s _, s.2⟩) (funext $ λ S, set_like.coe_injective Inf_image.symm) /-- The type of closed sets is inhabited, with default element the empty set. -/ instance : inhabited (closeds α) := ⟨⊥⟩ @[simp, norm_cast] lemma coe_sup (s t : closeds α) : (↑(s ⊔ t) : set α) = s ∪ t := rfl @[simp, norm_cast] lemma coe_inf (s t : closeds α) : (↑(s ⊓ t) : set α) = s ∩ t := rfl @[simp, norm_cast] lemma coe_top : (↑(⊤ : closeds α) : set α) = univ := rfl @[simp, norm_cast] lemma coe_bot : (↑(⊥ : closeds α) : set α) = ∅ := rfl @[simp, norm_cast] lemma coe_Inf {S : set (closeds α)} : (↑(Inf S) : set α) = ⋂ i ∈ S, ↑i := rfl @[simp, norm_cast] lemma coe_finset_sup (f : ι → closeds α) (s : finset ι) : (↑(s.sup f) : set α) = s.sup (coe ∘ f) := map_finset_sup (⟨⟨coe, coe_sup⟩, coe_bot⟩ : sup_bot_hom (closeds α) (set α)) _ _ @[simp, norm_cast] lemma coe_finset_inf (f : ι → closeds α) (s : finset ι) : (↑(s.inf f) : set α) = s.inf (coe ∘ f) := map_finset_inf (⟨⟨coe, coe_inf⟩, coe_top⟩ : inf_top_hom (closeds α) (set α)) _ _ lemma infi_def {ι} (s : ι → closeds α) : (⨅ i, s i) = ⟨⋂ i, s i, is_closed_Inter $ λ i, (s i).2⟩ := by { ext, simp only [infi, coe_Inf, bInter_range], refl } @[simp] lemma infi_mk {ι} (s : ι → set α) (h : ∀ i, is_closed (s i)) : (⨅ i, ⟨s i, h i⟩ : closeds α) = ⟨⋂ i, s i, is_closed_Inter h⟩ := by simp [infi_def] @[simp, norm_cast] lemma coe_infi {ι} (s : ι → closeds α) : ((⨅ i, s i : closeds α) : set α) = ⋂ i, s i := by simp [infi_def] @[simp] lemma mem_infi {ι} {x : α} {s : ι → closeds α} : x ∈ infi s ↔ ∀ i, x ∈ s i := by simp [←set_like.mem_coe] @[simp] lemma mem_Inf {S : set (closeds α)} {x : α} : x ∈ Inf S ↔ ∀ s ∈ S, x ∈ s := by simp_rw [Inf_eq_infi, mem_infi] instance : coframe (closeds α) := { Inf := Inf, infi_sup_le_sup_Inf := λ a s, (set_like.coe_injective $ by simp only [coe_sup, coe_infi, coe_Inf, set.union_Inter₂]).le, ..closeds.complete_lattice } /-- The term of `closeds α` corresponding to a singleton. -/ @[simps] def singleton [t1_space α] (x : α) : closeds α := ⟨{x}, is_closed_singleton⟩ end closeds /-- The complement of a closed set as an open set. -/ @[simps] def closeds.compl (s : closeds α) : opens α := ⟨sᶜ, s.2.is_open_compl⟩ /-- The complement of an open set as a closed set. -/ @[simps] def opens.compl (s : opens α) : closeds α := ⟨sᶜ, s.2.is_closed_compl⟩ lemma closeds.compl_compl (s : closeds α) : s.compl.compl = s := closeds.ext (compl_compl s) lemma opens.compl_compl (s : opens α) : s.compl.compl = s := opens.ext (compl_compl s) lemma closeds.compl_bijective : function.bijective (@closeds.compl α _) := function.bijective_iff_has_inverse.mpr ⟨opens.compl, closeds.compl_compl, opens.compl_compl⟩ lemma opens.compl_bijective : function.bijective (@opens.compl α _) := function.bijective_iff_has_inverse.mpr ⟨closeds.compl, opens.compl_compl, closeds.compl_compl⟩ variables (α) /-- `closeds.compl` as an `order_iso` to the order dual of `opens α`. -/ @[simps] def closeds.compl_order_iso : closeds α ≃o (opens α)ᵒᵈ := { to_fun := order_dual.to_dual ∘ closeds.compl, inv_fun := opens.compl ∘ order_dual.of_dual, left_inv := λ s, by simp [closeds.compl_compl], right_inv := λ s, by simp [opens.compl_compl], map_rel_iff' := λ s t, by simpa only [equiv.coe_fn_mk, function.comp_app, order_dual.to_dual_le_to_dual] using compl_subset_compl } /-- `opens.compl` as an `order_iso` to the order dual of `closeds α`. -/ @[simps] def opens.compl_order_iso : opens α ≃o (closeds α)ᵒᵈ := { to_fun := order_dual.to_dual ∘ opens.compl, inv_fun := closeds.compl ∘ order_dual.of_dual, left_inv := λ s, by simp [opens.compl_compl], right_inv := λ s, by simp [closeds.compl_compl], map_rel_iff' := λ s t, by simpa only [equiv.coe_fn_mk, function.comp_app, order_dual.to_dual_le_to_dual] using compl_subset_compl } variables {α} /-- in a `t1_space`, atoms of `closeds α` are precisely the `closeds.singleton`s. -/ lemma closeds.is_atom_iff [t1_space α] {s : closeds α} : is_atom s ↔ ∃ x, s = closeds.singleton x := begin have : is_atom (s : set α) ↔ is_atom s, { refine closeds.gi.is_atom_iff' rfl (λ t ht, _) s, obtain ⟨x, rfl⟩ := t.is_atom_iff.mp ht, exact closure_singleton }, simpa only [← this, (s : set α).is_atom_iff, set_like.ext_iff, set.ext_iff] end /-- in a `t1_space`, coatoms of `opens α` are precisely complements of singletons: `(closeds.singleton x).compl`. -/ lemma opens.is_coatom_iff [t1_space α] {s : opens α} : is_coatom s ↔ ∃ x, s = (closeds.singleton x).compl := begin rw [←s.compl_compl, ←is_atom_dual_iff_is_coatom], change is_atom (closeds.compl_order_iso α s.compl) ↔ _, rw [(closeds.compl_order_iso α).is_atom_iff, closeds.is_atom_iff], congrm ∃ x, _, exact closeds.compl_bijective.injective.eq_iff.symm, end /-! ### Clopen sets -/ /-- The type of clopen sets of a topological space. -/ structure clopens (α : Type*) [topological_space α] := (carrier : set α) (clopen' : is_clopen carrier) namespace clopens instance : set_like (clopens α) α := { coe := λ s, s.carrier, coe_injective' := λ s t h, by { cases s, cases t, congr' } } lemma clopen (s : clopens α) : is_clopen (s : set α) := s.clopen' /-- Reinterpret a compact open as an open. -/ @[simps] def to_opens (s : clopens α) : opens α := ⟨s, s.clopen.is_open⟩ @[ext] protected lemma ext {s t : clopens α} (h : (s : set α) = t) : s = t := set_like.ext' h @[simp] lemma coe_mk (s : set α) (h) : (mk s h : set α) = s := rfl instance : has_sup (clopens α) := ⟨λ s t, ⟨s ∪ t, s.clopen.union t.clopen⟩⟩ instance : has_inf (clopens α) := ⟨λ s t, ⟨s ∩ t, s.clopen.inter t.clopen⟩⟩ instance : has_top (clopens α) := ⟨⟨⊤, is_clopen_univ⟩⟩ instance : has_bot (clopens α) := ⟨⟨⊥, is_clopen_empty⟩⟩ instance : has_sdiff (clopens α) := ⟨λ s t, ⟨s \ t, s.clopen.diff t.clopen⟩⟩ instance : has_compl (clopens α) := ⟨λ s, ⟨sᶜ, s.clopen.compl⟩⟩ instance : boolean_algebra (clopens α) := set_like.coe_injective.boolean_algebra _ (λ _ _, rfl) (λ _ _, rfl) rfl rfl (λ _, rfl) (λ _ _, rfl) @[simp] lemma coe_sup (s t : clopens α) : (↑(s ⊔ t) : set α) = s ∪ t := rfl @[simp] lemma coe_inf (s t : clopens α) : (↑(s ⊓ t) : set α) = s ∩ t := rfl @[simp] lemma coe_top : (↑(⊤ : clopens α) : set α) = univ := rfl @[simp] lemma coe_bot : (↑(⊥ : clopens α) : set α) = ∅ := rfl @[simp] lemma coe_sdiff (s t : clopens α) : (↑(s \ t) : set α) = s \ t := rfl @[simp] lemma coe_compl (s : clopens α) : (↑sᶜ : set α) = sᶜ := rfl instance : inhabited (clopens α) := ⟨⊥⟩ end clopens end topological_space
960d6fbd8e2f2fcaad1cfa38218c4edcc2f1a8d2
19cc34575500ee2e3d4586c15544632aa07a8e66
/src/number_theory/divisors.lean
fb3305695bc5edfe350fe72eb7b2a7d64771413c
[ "Apache-2.0" ]
permissive
LibertasSpZ/mathlib
b9fcd46625eb940611adb5e719a4b554138dade6
33f7870a49d7cc06d2f3036e22543e6ec5046e68
refs/heads/master
1,672,066,539,347
1,602,429,158,000
1,602,429,158,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,321
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import algebra.big_operators.basic import tactic /-! # Divisor finsets This file defines sets of divisors of a natural number. This is particularly useful as background for defining Dirichlet convolution. ## Main Definitions Let `n : ℕ`. All of the following definitions are in the `nat` namespace: * `divisors n` is the `finset` of natural numbers that divide `n`. * `proper_divisors n` is the `finset` of natural numbers that divide `n`, other than `n`. * `divisors_antidiagonal n` is the `finset` of pairs `(x,y)` such that `x * y = n`. * `perfect n` is true when the sum of `proper_divisors n` is `n`. ## Implementation details * `divisors 0` is defined to be `{0}`, while `proper_divisors 0`, and `divisors_antidiagonal 0` are defined to be `∅`. ## Tags divisors, perfect numbers -/ open_locale classical open_locale big_operators namespace nat variable (n : ℕ) /-- `divisors n` is the `finset` of divisors of `n`. As a special case, `divisors 0 = {0}`. -/ def divisors : finset ℕ := finset.filter (λ x : ℕ, x ∣ n) (finset.Ico 1 (n + 1)) /-- `proper_divisors n` is the `finset` of divisors of `n`, other than `n`. As a special case, `proper_divisors 0 = ∅`. -/ def proper_divisors : finset ℕ := finset.filter (λ x : ℕ, x ∣ n) (finset.Ico 1 n) /-- `divisors_antidiagonal n` is the `finset` of pairs `(x,y)` such that `x * y = n`. As a special case, `divisors_antidiagonal 0 = ∅`. -/ def divisors_antidiagonal : finset (ℕ × ℕ) := ((finset.Ico 1 (n + 1)).product (finset.Ico 1 (n + 1))).filter (λ x, x.fst * x.snd = n) variable {n} lemma proper_divisors.not_self_mem : ¬ n ∈ proper_divisors n := begin rw proper_divisors, simp, end @[simp] lemma mem_proper_divisors {m : ℕ} : n ∈ proper_divisors m ↔ n ∣ m ∧ n < m := begin rw [proper_divisors, finset.mem_filter, finset.Ico.mem, and_comm], apply and_congr_right, rw and_iff_right_iff_imp, intros hdvd hlt, apply nat.pos_of_ne_zero _, rintro rfl, rw zero_dvd_iff.1 hdvd at hlt, apply lt_irrefl 0 hlt, end lemma divisors_eq_proper_divisors_insert_self_of_pos (h : 0 < n): divisors n = has_insert.insert n (proper_divisors n) := by rw [divisors, proper_divisors, finset.Ico.succ_top h, finset.filter_insert, if_pos (dvd_refl n)] @[simp] lemma mem_divisors {m : ℕ} : n ∈ divisors m ↔ (n ∣ m ∧ m ≠ 0) := begin cases m, { simp [divisors] }, simp only [divisors, finset.Ico.mem, ne.def, finset.mem_filter, succ_ne_zero, and_true, and_iff_right_iff_imp, not_false_iff], intro hdvd, split, { apply nat.pos_of_ne_zero, rintro rfl, apply nat.succ_ne_zero, rwa zero_dvd_iff at hdvd }, { rw nat.lt_succ_iff, apply nat.le_of_dvd (nat.succ_pos m) hdvd } end lemma dvd_of_mem_divisors {m : ℕ} (h : n ∈ divisors m) : n ∣ m := begin cases m, { apply dvd_zero }, { simp [mem_divisors.1 h], } end @[simp] lemma mem_divisors_antidiagonal {x : ℕ × ℕ} : x ∈ divisors_antidiagonal n ↔ x.fst * x.snd = n ∧ n ≠ 0 := begin simp only [divisors_antidiagonal, finset.Ico.mem, ne.def, finset.mem_filter, finset.mem_product], rw and_comm, apply and_congr_right, rintro rfl, split; intro h, { contrapose! h, simp [h], }, { rw [nat.lt_add_one_iff, nat.lt_add_one_iff], rw [mul_eq_zero, decidable.not_or_iff_and_not] at h, simp only [succ_le_of_lt (nat.pos_of_ne_zero h.1), succ_le_of_lt (nat.pos_of_ne_zero h.2), true_and], exact ⟨le_mul_of_pos_right (nat.pos_of_ne_zero h.2), le_mul_of_pos_left (nat.pos_of_ne_zero h.1)⟩ } end variable {n} lemma divisor_le {m : ℕ}: n ∈ divisors m → n ≤ m := begin cases m, { simp }, simp only [mem_divisors, m.succ_ne_zero, and_true, ne.def, not_false_iff], exact nat.le_of_dvd (nat.succ_pos m), end variable (n) @[simp] lemma divisors_zero : divisors 0 = ∅ := by { ext, simp } @[simp] lemma proper_divisors_zero : proper_divisors 0 = ∅ := by { ext, simp } @[simp] lemma divisors_antidiagonal_zero : divisors_antidiagonal 0 = ∅ := by { ext, simp } @[simp] lemma divisors_antidiagonal_one : divisors_antidiagonal 1 = {(1,1)} := by { ext, simp [nat.mul_eq_one_iff, prod.ext_iff], } lemma swap_mem_divisors_antidiagonal {n : ℕ} {x : ℕ × ℕ} (h : x ∈ divisors_antidiagonal n) : x.swap ∈ divisors_antidiagonal n := begin rw [mem_divisors_antidiagonal, mul_comm] at h, simp [h.1, h.2], end lemma fst_mem_divisors_of_mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} (h : x ∈ divisors_antidiagonal n) : x.fst ∈ divisors n := begin rw mem_divisors_antidiagonal at h, simp [dvd.intro _ h.1, h.2], end lemma snd_mem_divisors_of_mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} (h : x ∈ divisors_antidiagonal n) : x.snd ∈ divisors n := begin rw mem_divisors_antidiagonal at h, simp [dvd.intro_left _ h.1, h.2], end @[simp] lemma map_swap_divisors_antidiagonal {n : ℕ} : (divisors_antidiagonal n).map ⟨prod.swap, prod.swap_right_inverse.injective⟩ = divisors_antidiagonal n := begin ext, simp only [exists_prop, mem_divisors_antidiagonal, finset.mem_map, function.embedding.coe_fn_mk, ne.def, prod.swap_prod_mk, prod.exists], split, { rintros ⟨x, y, ⟨⟨rfl, h⟩, rfl⟩⟩, simp [mul_comm, h], }, { rintros ⟨rfl, h⟩, use [a.snd, a.fst], rw mul_comm, simp [h] } end lemma sum_divisors_eq_sum_proper_divisors_add_self : ∑ i in divisors n, i = ∑ i in proper_divisors n, i + n := begin cases n, { simp }, { rw [divisors_eq_proper_divisors_insert_self_of_pos (nat.succ_pos _), finset.sum_insert (proper_divisors.not_self_mem), add_comm] } end /-- `n : ℕ` is perfect if and only the sum of the proper divisors of `n` is `n`. -/ def perfect (n : ℕ) : Prop := ∑ i in proper_divisors n, i = n theorem perfect_iff_sum_proper_divisors {n : ℕ} : perfect n ↔ ∑ i in proper_divisors n, i = n := iff.rfl theorem perfect_iff_sum_divisors_eq_two_mul {n : ℕ} : perfect n ↔ ∑ i in divisors n, i = 2 * n := begin rw [perfect, sum_divisors_eq_sum_proper_divisors_add_self, two_mul], split; intro h, { rw h }, { apply add_right_cancel h } end end nat
7e31688e088a2256fbe9d2183e08efaaf401e9ed
e514e8b939af519a1d5e9b30a850769d058df4e9
/src/tactic/rewrite_search/discovery/collector/bundle.lean
840b58f4961cf869b8fdaa78f5511eb461e32da6
[]
no_license
semorrison/lean-rewrite-search
dca317c5a52e170fb6ffc87c5ab767afb5e3e51a
e804b8f2753366b8957be839908230ee73f9e89f
refs/heads/master
1,624,051,754,485
1,614,160,817,000
1,614,160,817,000
162,660,605
0
1
null
null
null
null
UTF-8
Lean
false
false
2,263
lean
import data.rat.basic import data.list.defs import tactic.rewrite_search.core.common import ..types import .common open tactic namespace tactic.rewrite_search.discovery open tactic.rewrite_search def BUNDLE_CHUNK_SIZE := 1 -- TODO Be smarter about calculating this. meta def score_bundle (b : bundle_ref) (sample : list expr) : tactic ℕ := do mems ← b.get_members, mems.mfoldl (λ sum n, do e ← mk_const n, ret ← are_promising_rewrites (rewrite_list_from_lemma e) sample, return $ if ret then sum + 1 else sum ) 0 -- TODO report the lemma(s) which caused a selected bundle to be chosen, -- so that that lemma could just be tagged individually. -- TODO at the end of the search report which "desperations" things happened -- (bundles added, random lemmas found and used) so that they can be addressed -- more easily/conveniently. def min_rel {α : Type} (l : list α) (r : α → α → Prop) [decidable_rel r] : option α := l.foldl (λ o a, match o with | none := some a | some b := if r b a then b else a end) none meta def try_bundles (conf : config) (rs : list (expr × bool)) (p : progress) (sample : list expr) : tactic (progress × list (expr × bool)) := if p.persistence < persistence.try_bundles then return (p, []) else do bs ← list.filter (λ b, b ∉ p.seen_bundles) <$> get_bundles, bs ← bs.mmap $ λ b, (do s ← score_bundle b sample, return (b, s)), (awful_bs, interesting_bs) ← pure $ bs.partition $ λ b, b.2 = 0, let p := {p with seen_bundles := p.seen_bundles.append (awful_bs.map prod.fst)}, match min_rel interesting_bs (λ a b, a.2 > b.2) with | none := do if conf.trace_discovery then discovery_trace format!"Could not find any promising bundles of the {bs.length} non-suggested bundles considered: {bs.map $ λ b, b.1.bundle.name}" else skip, return (p, []) | some (b, score) := do if conf.trace_discovery then discovery_trace format!"Found a promising bundle (of {bs.length} considered) \"{b.bundle.name}\"! If we succeed, please suggest this bundle for consideration." else skip, ms ← b.get_members >>= load_names, return (p, rewrite_list_from_lemmas ms) end end tactic.rewrite_search.discovery
8704fb90e6c6433783d27cd0b08a8615bf1d5a7d
7565ffb53cc64430691ce89265da0f944ee43051
/hott/homotopy/complex_hopf.hlean
4d91ba633f52a42e45035a7c3c78bf52b84eea24
[ "Apache-2.0" ]
permissive
EgbertRijke/lean2
cacddba3d150f8b38688e044960a208bf851f90e
519dcee739fbca5a4ab77d66db7652097b4604cd
refs/heads/master
1,606,936,954,854
1,498,836,083,000
1,498,910,882,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,647
hlean
/- Copyright (c) 2016 Ulrik Buchholtz and Egbert Rijke. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Ulrik Buchholtz, Egbert Rijke, Floris van Doorn The H-space structure on S¹ and the complex Hopf fibration (the standard one). -/ import .hopf .circle types.fin open eq equiv is_equiv circle is_conn trunc is_trunc sphere susp pointed fiber sphere.ops function namespace hopf definition circle_h_space [instance] : h_space S¹ := ⦃ h_space, one := base, mul := circle_mul, one_mul := circle_base_mul, mul_one := circle_mul_base ⦄ definition circle_assoc (x y z : S¹) : (x * y) * z = x * (y * z) := begin induction x, { reflexivity }, { apply eq_pathover, induction y, { exact natural_square (λa : S¹, ap (λb : S¹, b * z) (circle_mul_base a)) loop }, { apply is_prop.elimo, apply is_trunc_square } } end open sphere_index definition complex_hopf : S 3 → S 2 := begin intro x, apply @sigma.pr1 (susp S¹) (hopf S¹), apply inv (hopf.total S¹), apply inv (join.spheres 1 1), exact x end definition complex_phopf [constructor] : S* 3 →* S* 2 := proof pmap.mk complex_hopf idp qed definition pfiber_complex_phopf : pfiber complex_phopf ≃* S* 1 := begin fapply pequiv_of_equiv, { esimp, unfold [complex_hopf], refine fiber.equiv_precompose (sigma.pr1 ∘ (hopf.total S¹)⁻¹ᵉ) (join.spheres (of_nat 1) (of_nat 1))⁻¹ᵉ _ ⬝e _, refine fiber.equiv_precompose _ (hopf.total S¹)⁻¹ᵉ _ ⬝e _, apply fiber_pr1}, { reflexivity} end end hopf
17f22e305e48e59f80b0fa32b8d9c6e5a2d504a2
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/data/complex/exponential_bounds.lean
674a605153f4116c2dca79a31a59f162c109f2aa
[ "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
2,582
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Joseph Myers -/ import data.complex.exponential import analysis.special_functions.log_deriv /-! # Bounds on specific values of the exponential -/ namespace real open is_absolute_value finset cau_seq complex lemma exp_one_near_10 : |exp 1 - 2244083/825552| ≤ 1/10^10 := begin apply exp_approx_start, iterate 13 { refine exp_1_approx_succ_eq (by norm_num1; refl) (by norm_cast; refl) _ }, norm_num1, refine exp_approx_end' _ (by norm_num1; refl) _ (by norm_cast; refl) (by simp) _, rw [_root_.abs_one, abs_of_pos]; norm_num1, end lemma exp_one_near_20 : |exp 1 - 363916618873/133877442384| ≤ 1/10^20 := begin apply exp_approx_start, iterate 21 { refine exp_1_approx_succ_eq (by norm_num1; refl) (by norm_cast; refl) _ }, norm_num1, refine exp_approx_end' _ (by norm_num1; refl) _ (by norm_cast; refl) (by simp) _, rw [_root_.abs_one, abs_of_pos]; norm_num1, end lemma exp_one_gt_d9 : 2.7182818283 < exp 1 := lt_of_lt_of_le (by norm_num) (sub_le.1 (abs_sub_le_iff.1 exp_one_near_10).2) lemma exp_one_lt_d9 : exp 1 < 2.7182818286 := lt_of_le_of_lt (sub_le_iff_le_add.1 (abs_sub_le_iff.1 exp_one_near_10).1) (by norm_num) lemma exp_neg_one_gt_d9 : 0.36787944116 < exp (-1) := begin rw [exp_neg, lt_inv _ (exp_pos _)], refine lt_of_le_of_lt (sub_le_iff_le_add.1 (abs_sub_le_iff.1 exp_one_near_10).1) _, all_goals {norm_num}, end lemma exp_neg_one_lt_d9 : exp (-1) < 0.36787944120 := begin rw [exp_neg, inv_lt (exp_pos _)], refine lt_of_lt_of_le _ (sub_le.1 (abs_sub_le_iff.1 exp_one_near_10).2), all_goals {norm_num}, end lemma log_two_near_10 : |log 2 - 287209 / 414355| ≤ 1/10^10 := begin suffices : |log 2 - 287209 / 414355| ≤ 1/17179869184 + (1/10^10 - 1/2^34), { norm_num1 at *, assumption }, have t : |(2⁻¹ : ℝ)| = 2⁻¹, { rw abs_of_pos, norm_num }, have z := real.abs_log_sub_add_sum_range_le (show |(2⁻¹ : ℝ)| < 1, by { rw t, norm_num }) 34, rw t at z, norm_num1 at z, rw [one_div (2:ℝ), log_inv, ←sub_eq_add_neg, _root_.abs_sub_comm] at z, apply le_trans (_root_.abs_sub_le _ _ _) (add_le_add z _), simp_rw [sum_range_succ], norm_num, rw abs_of_pos; norm_num end lemma log_two_gt_d9 : 0.6931471803 < log 2 := lt_of_lt_of_le (by norm_num1) (sub_le.1 (abs_sub_le_iff.1 log_two_near_10).2) lemma log_two_lt_d9 : log 2 < 0.6931471808 := lt_of_le_of_lt (sub_le_iff_le_add.1 (abs_sub_le_iff.1 log_two_near_10).1) (by norm_num) end real
ad4e537ef3f0fe1f128a2ed0c732edd32e7a53d6
ac1c2a2f522b0fdf854095ba00f882ca849669e7
/library/init/data/string/basic.lean
655f3cb4244091d4fc06c8fdae646087c31cb7f1
[ "Apache-2.0" ]
permissive
abliss/lean
b8b336abc8d50dbb0726dcff9dd16793c23bfbe1
fb24cc99573c153f97a1951ee94bbbdda300b6be
refs/heads/master
1,611,536,584,520
1,497,811,981,000
1,497,811,981,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,507
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import init.data.list.basic import init.data.char.basic private structure string_imp := (data : list char) def string := string_imp def list.as_string (s : list char) : string := ⟨s.reverse⟩ namespace string def empty : string := ⟨list.nil⟩ instance : inhabited string := ⟨empty⟩ def length : string → nat | ⟨s⟩ := s.length instance : has_sizeof string := ⟨string.length⟩ def str : string → char → string | ⟨s⟩ c := ⟨c::s⟩ def append : string → string → string | ⟨a⟩ ⟨b⟩ := ⟨b ++ a⟩ def is_empty : string → bool | ⟨[]⟩ := tt | _ := ff instance : has_append string := ⟨string.append⟩ def to_list : string → list char | ⟨s⟩ := s.reverse def pop_back : string → string | ⟨s⟩ := ⟨s.tail⟩ def popn_back : string → nat → string | ⟨s⟩ n := ⟨s.dropn n⟩ def intercalate (s : string) (ss : list string) : string := (list.intercalate s.to_list (ss.map to_list)).as_string def fold {α} (a : α) (f : α → char → α) (s : string) : α := s.to_list.foldl f a def front (s : string) : char := s.to_list.head def back : string → char | ⟨[]⟩ := default char | ⟨c::cs⟩ := c def backn : string → nat → string | ⟨s⟩ n := ⟨s.taken n⟩ def join (l : list string) : string := l.foldl (λ r s, r ++ s) "" def singleton (c : char) : string := str empty c end string open list string private def utf8_length_aux : nat → nat → list char → nat | 0 r (c::s) := let n := char.to_nat c in if n < 0x80 then utf8_length_aux 0 (r+1) s else if 0xC0 ≤ n ∧ n < 0xE0 then utf8_length_aux 1 (r+1) s else if 0xE0 ≤ n ∧ n < 0xF0 then utf8_length_aux 2 (r+1) s else if 0xF0 ≤ n ∧ n < 0xF8 then utf8_length_aux 3 (r+1) s else if 0xF8 ≤ n ∧ n < 0xFC then utf8_length_aux 4 (r+1) s else if 0xFC ≤ n ∧ n < 0xFE then utf8_length_aux 5 (r+1) s else utf8_length_aux 0 (r+1) s | (n+1) r (c::s) := utf8_length_aux n r s | n r [] := r def string.utf8_length : string → nat | s := utf8_length_aux 0 0 s.to_list export string (utf8_length) private def to_nat_core : list char → nat → nat | [] r := r | (c::cs) r := to_nat_core cs (char.to_nat c - char.to_nat '0' + r*10) def string.to_nat (s : string) : nat := to_nat_core s.to_list 0
6a2166c8c257d28130585a1470aa0eb3ec132735
f4bff2062c030df03d65e8b69c88f79b63a359d8
/src/game/limits/seq_cauchyBdd.lean
a5adbda00515bced5f9244073e871ec697864164
[ "Apache-2.0" ]
permissive
adastra7470/real-number-game
776606961f52db0eb824555ed2f8e16f92216ea3
f9dcb7d9255a79b57e62038228a23346c2dc301b
refs/heads/master
1,669,221,575,893
1,594,669,800,000
1,594,669,800,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,526
lean
import game.limits.L01defs import game.limits.seq_proveLimit import algebra.pi_instances import game.order.level05 --open function open finset namespace xena -- hide notation `|` x `|` := abs x -- hide def is_convergent (a : ℕ → ℝ) := ∃ α : ℝ, is_limit a α def is_Cauchy (a : ℕ → ℝ) := ∀ ε : ℝ, 0 < ε → ∃ N : ℕ, ∀ m n : ℕ, N ≤ m ∧ N ≤ n → |a m - a n| < ε def is_bdd (a : ℕ → ℝ) := ∃ B > 0, ∀ n, |a n| ≤ B -- begin hide -- We may want to skip this in RNG unless we can make it look (or be) easy --? -- end hide /- Cauchy sequences are bounded. -/ /- Lemma A Cauchy sequence is bounded. -/ lemma cauchy_is_bdd (a : ℕ → ℝ) : is_Cauchy a → is_bdd a:= begin --classical proof for boundedness of Cauchy sequences intro HC, set e := (1:ℝ), have h1e : (0:ℝ) < 1, linarith, have H := HC 1 h1e, cases H with N hN, have G := hN N, -- construct X = {|a0|, |a1|, ...,|am|} let X := finset.image (abs ∘ a) (finset.range (N + 1)), -- at least a0 is in X have ha0 : |a 0| ∈ X := finset.mem_image_of_mem _ (mem_range.2 (nat.zero_lt_succ _)), -- hence the set X is not empty have ha1 : X ≠ ∅ := ne_empty_of_mem ha0, have ha2 := nonempty_iff_ne_empty.mpr ha1, -- and therefore has a maximum let B1 := X.max' ha2, -- If n ≤ m then get a proof that |a n| ≤ B1. have HB1 : ∀ n ≤ N, |a n| ≤ B1 := λ n Hn, le_max' X ha2 _ (mem_image_of_mem _ (mem_range.2 (nat.lt_succ_of_le Hn))), -- term that bounds all members of the sequence set B := max B1 ( |a N| + 1 ) with hB, -- so this will be our bound use B, split, swap, intro n, cases le_or_gt n N with hn1 hn2, { -- n ≤ N have g1 : | a n | ≤ B1 := HB1 n hn1, have g2 : B1 ≤ B := le_max_left _ _, linarith, }, { -- n > N have g1 := G n, have g2 : N ≤ N ∧ N ≤ n, split; linarith, have g3 := g1 g2, rw abs_lt at g3, have fact1 := g3.left, have fact2 := g3.right, simp, right, rw abs_le, -- our abs_le is conditional on 0 ≤ c - proven in the last section simp, split, { have simplefact1: - a N ≤ | a N | := neg_le_abs_self (a N), linarith, }, {have simplefact2: a N ≤ | a N | := le_abs_self(a N), linarith}, have simplefact3: 0 ≤ |a N|, from abs_nonneg (a N), linarith, }, have g1 : |a N| + 1 ≤ B := le_max_right _ _, have g2: 0 ≤ |a N|, from abs_nonneg (a N), linarith, end end xena -- hide
286af2e83b6fad877c4ce224a8e712362c7c4c2f
5df84495ec6c281df6d26411cc20aac5c941e745
/src/formal_ml/topological_space.lean
1821076093e4e6fdd3fc7ed0729c6f9754a1aa33
[ "Apache-2.0" ]
permissive
eric-wieser/formal-ml
e278df5a8df78aa3947bc8376650419e1b2b0a14
630011d19fdd9539c8d6493a69fe70af5d193590
refs/heads/master
1,681,491,589,256
1,612,642,743,000
1,612,642,743,000
360,114,136
0
0
Apache-2.0
1,618,998,189,000
1,618,998,188,000
null
UTF-8
Lean
false
false
17,274
lean
/- Copyright 2020 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -/ import topology.basic import topology.order import topology.constructions import topology.bases import data.set.countable import formal_ml.set import topology.instances.nnreal import topology.instances.ennreal /- The nnreal and ennreal are only needed for two methods. Could move those to a separate file. -/ lemma topological_space_le_def {α:Type*} (S T:topological_space α): S ≤ T ↔ (T.is_open ≤ S.is_open) := begin refl, end lemma topological_space_generate_from_refl {α:Type*} (T:topological_space α): (topological_space.generate_from (T.is_open)) = T := begin apply complete_lattice.le_antisymm, { rw topological_space_le_def, intros U A1, unfold topological_space.generate_from, simp, apply topological_space.generate_open.basic, exact A1, }, { apply (@le_generate_from_iff_subset_is_open α (T.is_open) T).mpr, apply set.subset.refl, } end lemma topological_space_induced_is_open {α β:Type*} (f:α → β) (T:topological_space β): (topological_space.induced f T).is_open = (λs, ∃s', T.is_open s' ∧ f ⁻¹' s' = s) := begin refl, end lemma topological_space_induced_is_open2 {α β:Type*} (f:α → β) (T:topological_space β): (topological_space.induced f T).is_open = (set.image (set.preimage f) T.is_open) := begin refl, end lemma topological_space_generate_from_is_open {α:Type*} {B:set (set α)}: (topological_space.generate_from B).is_open = topological_space.generate_open B := begin refl, end lemma topological_space_induced_def {α β:Type*} {Bβ:set (set β)} (f:α → β): topological_space.induced f (@topological_space.generate_from β Bβ) = @topological_space.generate_from α (set.image (set.preimage f) Bβ) := begin rw @induced_generate_from_eq, end lemma topological_space_induced_fst_def {α β:Type*} {Bα:set (set α)}: topological_space.induced (@prod.fst α β) (@topological_space.generate_from α Bα) = @topological_space.generate_from (α × β) {U:set (α × β)|∃ A∈ Bα, U = set.prod A set.univ} := begin rw topological_space_induced_def, rw set.preimage_fst_def, end lemma topological_space_induced_snd_def {α β:Type*} {Bβ:set (set β)}: topological_space.induced (@prod.snd α β) (@topological_space.generate_from β Bβ) = @topological_space.generate_from (α × β) {U:set (α × β)|∃ B∈ Bβ, U = set.prod set.univ B} := begin rw topological_space_induced_def, rw set.preimage_snd_def, end lemma semilattice_inf_inf_intro {α:Type*} [SL:semilattice_inf α] (x y z:α): (z ≤ x) → (z ≤ y) → (∀ w, (w≤ x)→ (w≤ y)→ (w≤ z))→ (x ⊓ y = z) := begin intros A1 A2 A3, apply semilattice_inf.le_antisymm, { -- x ⊓ y ≤ z apply A3, { apply semilattice_inf.inf_le_left, }, { apply semilattice_inf.inf_le_right, } }, { -- ⊢ z ≤ x ⊓ y apply semilattice_inf.le_inf, { apply A1, }, { apply A2, } } end lemma topological_space_inf_def {α:Type*} {S:set (set α)} {T:set (set α)}: (@topological_space.generate_from α S) ⊓ (@topological_space.generate_from α T)= (@topological_space.generate_from α (S∪ T)) := begin apply semilattice_inf_inf_intro, { apply generate_from_mono, apply set.subset_union_left }, { apply generate_from_mono, apply set.subset_union_right }, { intros w a a_1, have A1:S ⊆ w.is_open, { apply (@le_generate_from_iff_subset_is_open α S w).mp a, }, have A2:T ⊆ w.is_open, { apply (@le_generate_from_iff_subset_is_open α T w).mp a_1, }, have A2:S ∪ T ⊆ w.is_open, { apply set.union_subset;assumption, }, apply (@le_generate_from_iff_subset_is_open α (S∪T) w).mpr A2, } end lemma prod_topological_space_def {α β:Type*} {Bα:set (set α)} {Bβ:set (set β)}:@prod.topological_space α β (topological_space.generate_from Bα) (topological_space.generate_from Bβ) = topological_space.generate_from ({U:set (α × β)|∃ A∈ Bα, U = set.prod A set.univ} ∪ {U:set (α × β)|∃ B∈ Bβ, U = set.prod set.univ B}) := begin have A1:(@prod.topological_space α β (@topological_space.generate_from α Bα) (@topological_space.generate_from β Bβ)) = topological_space.induced prod.fst (@topological_space.generate_from α Bα) ⊓ topological_space.induced prod.snd (@topological_space.generate_from β Bβ), { refl, }, rw (@topological_space_induced_fst_def α β Bα) at A1, rw (@topological_space_induced_snd_def α β Bβ) at A1, rw topological_space_inf_def at A1, apply A1, end /- We have to be careful about continuous and measurable functions when it comes to functions with two variables. Specifically, if we say a function like f:α → β → γ is continuous, this implies it is a continuous function from α to β → γ, which is usually not what we want. This would ignore the topological space of β. Instead, we want to consider a related function f:(α × β) → γ, and ask if the preimage of an open set in γ is an open set in (α × β). This is a stronger statement (I think). This little definition takes care of this. Note that if you look at the topological_semiring definition below, it matches this definition of continuity. -/ def continuous2 {α β γ:Type*} [topological_space α] [topological_space β] [topological_space γ] (f:α → β → γ):Prop := continuous (λ p:α × β, f (p.fst) (p.snd)) lemma continuous2_def {α β γ:Type*} [topological_space α] [topological_space β] [topological_space γ] (f:α → β → γ):continuous2 f ↔ continuous (λ p:α × β, f (p.fst) (p.snd)) := begin refl end lemma continuous2_of_has_continuous_mul {α:Type*} [T:topological_space α] [HM:has_mul α]:@has_continuous_mul α T HM ↔ (@continuous2 α α α T T T (@has_mul.mul α _)) := begin split;intros A1, { rw continuous2_def, apply @continuous_mul α T HM A1, }, { rw continuous2_def at A1, have A2:@has_continuous_mul α T HM := { continuous_mul := A1, }, apply A2, }, end lemma has_continuous_add_iff_continuous2 {α:Type*} [T:topological_space α] [HM:has_add α]:@has_continuous_add α T HM ↔ (@continuous2 α α α T T T (@has_add.add α _)) := begin split;intros A1, { rw continuous2_def, apply @continuous_add α T HM A1, }, { rw continuous2_def at A1, have A2:@has_continuous_add α T HM := { continuous_add := A1, }, apply A2, }, end lemma continuous2_nnreal_add: continuous2 nnreal.has_add.add := begin rw ← has_continuous_add_iff_continuous2, apply nnreal.topological_semiring.to_has_continuous_add, end lemma continuous2_real_add: continuous2 real.linear_ordered_comm_ring.add := begin have A1:real.linear_ordered_comm_ring.add = (@has_add.add ℝ _) := rfl, rw A1, rw ← has_continuous_add_iff_continuous2, apply real.topological_semiring.to_has_continuous_add, end lemma continuous2_ennreal_add: continuous2 ennreal.canonically_ordered_comm_semiring.add := begin have A1:ennreal.canonically_ordered_comm_semiring.add = (@has_add.add ennreal _) := rfl, rw A1, rw ← has_continuous_add_iff_continuous2, apply ennreal.has_continuous_add, end -- Topological basis is the true topological basis, as would be found in Munkres. -- The important distinction is that any open set can be formed via a union of elements of the -- basis. --Trivial: do not use lemma contains_nbhd_of_basis {α:Type*} [Tα:topological_space α] {Gα:set (set α)} {x:α} {V:set α}: (@topological_space.is_topological_basis α Tα Gα) → (is_open V) → (x∈ V) → (∃ S∈ Gα, x∈ S∧ S⊆V) := begin intros A1 A2 A3, apply @topological_space.mem_basis_subset_of_mem_open α Tα Gα A1 x V A3 A2, end --Trivial: do not use lemma union_basis_of_is_open {α:Type*} [Tα:topological_space α] {Gα:set (set α)} {V:set α}: (@topological_space.is_topological_basis α Tα Gα) → (is_open V) → (∃ S⊆ Gα, V = set.sUnion S) := begin intros A1 A2, apply topological_space.sUnion_basis_of_is_open, apply A1, apply A2, end --set_option pp.implicit true lemma continuous_intro {α β:Type*} {Tα:topological_space α} {Tβ:topological_space β} {Gβ:set (set β)} (f:α → β): (@topological_space.is_topological_basis β Tβ Gβ) → (∀ U∈ Gβ, is_open (f⁻¹' U)) → (@continuous α β Tα Tβ f) := begin rw continuous_def, intros A1 A2 S A3, --unfold topological_space.is_topological_basis at A1, have A4:(∃ X⊆ Gβ, S = set.sUnion X), { apply topological_space.sUnion_basis_of_is_open, apply A1, apply A3, }, cases A4 with X A5, cases A5 with A6 A7, rw A7, rw set.preimage_sUnion', apply is_open_sUnion, intro T, intro A8, cases A8 with T2 A9, cases A9 with A10 A11, subst T, apply A2, rw set.subset_def at A6, apply A6, exact A10, end lemma sUnion_eq_univ_intro {β:Type*} {Gβ:set (set β)}: (∀ x:β, ∃ B∈ Gβ, x∈ B) → (⋃₀ Gβ = set.univ) := begin intro A1, ext,split;intros A2, { simp, }, { have A3: ∃ (B : set β) (H : B ∈ Gβ), x ∈ B, { apply A1, }, cases A3 with B A4, cases A4 with A5 A6, simp, apply exists.intro B, split, exact A5, exact A6, } end /- This theorem uses a middle definition of basis. Specifically, every point must be in some set in the basis. Note that this is equivalent to the union of the sets in the basis being the universe. -/ lemma continuous_intro2 {α β:Type*} {Tα:topological_space α} {Gβ:set (set β)} (f:α → β): (∀ x:β, ∃ B∈ Gβ, x∈ B) → (∀ U∈ Gβ, is_open (f⁻¹' U)) → (@continuous α β Tα (topological_space.generate_from Gβ) f) := begin intros A0 A1, rw continuous_def, intros U A2, have A3:@topological_space.generate_open β Gβ U, { rw ← topological_space_generate_from_is_open, apply A2, }, clear A2, induction A3, { apply A1, exact A3_H, }, { have A4:(⋃₀ Gβ = set.univ), { apply sUnion_eq_univ_intro, apply A0, }, { rw ← A4, rw set.preimage_sUnion', apply is_open_sUnion, intros t A5, cases A5 with B A6, cases A6 with A7 A8, subst t, apply A1, exact A7, }, }, { rw set.preimage_inter, apply is_open_inter;assumption, }, { rw set.preimage_sUnion', apply is_open_sUnion, intros t A5, cases A5 with B A6, cases A6 with A7 A8, subst t, apply A3_ih, exact A7, } end lemma generate_from_le_generate_from {α:Type*} {A B:set (set α)}: (∀ b∈ B, topological_space.generate_open A b) → (topological_space.generate_from A ≤ topological_space.generate_from B) := begin intro A1, apply le_generate_from_iff_subset_is_open.mpr, rw set.subset_def, unfold topological_space.generate_from, intros x A3, apply A1, exact A3, end lemma generate_from_eq_generate_from {α:Type*} {A B:set (set α)}: (∀ a∈ A, topological_space.generate_open B a) → (∀ b∈ B, topological_space.generate_open A b) → (topological_space.generate_from A = topological_space.generate_from B) := begin intros A1 A2, apply le_antisymm, { apply generate_from_le_generate_from, exact A2, }, { apply generate_from_le_generate_from, exact A1, }, end lemma prod_topological_space_def2 {α β:Type*} {Tα:topological_space α} {Tβ:topological_space β} {Bα:set (set α)} {Bβ:set (set β)}: (@topological_space.is_topological_basis α Tα Bα) → (@topological_space.is_topological_basis β Tβ Bβ) → (@topological_space.is_topological_basis (α × β) (@prod.topological_space α β Tα Tβ) ({U:set (α × β)|∃ A∈ Bα, ∃ B∈ Bβ, U = set.prod A B})) := begin intros A1 A2, unfold topological_space.is_topological_basis at A1, cases A1 with A3 A4, cases A4 with A5 A6, rw A6, unfold topological_space.is_topological_basis at A2, cases A2 with A7 A8, cases A8 with A9 A10, rw A10, rw prod_topological_space_def, unfold topological_space.is_topological_basis, split, { intros t₁ B1 t₂ B2 x B3, cases B1 with tA₁ B4, cases B4 with B5 B6, cases B6 with tB₁ B7, cases B7 with B7 B8, subst t₁, --unfold set.prod at B3, cases B2 with tA₂ B9, cases B9 with B10 B11, cases B11 with tB₂ B12, cases B12 with B13 B14, subst t₂, rw set.prod_inter_prod at B3, cases B3 with B15 B16, have B17:(∃ (tA₃ : set α) (H : tA₃ ∈ Bα), x.fst ∈ tA₃ ∧ tA₃ ⊆ tA₁ ∩ tA₂), { apply A3, exact B5, exact B10, exact B15, }, have B18:(∃ (tB₃ : set β) (H : tB₃ ∈ Bβ), x.snd ∈ tB₃ ∧ tB₃ ⊆ tB₁ ∩ tB₂), { apply A7, exact B7, exact B13, exact B16, }, cases B17 with tA₃ B19, cases B19 with B20 B21, cases B21 with B22 B23, cases B18 with tB₃ B24, cases B24 with B25 B26, cases B26 with B27 B28, apply exists.intro (set.prod tA₃ tB₃), split, { simp, apply exists.intro tA₃, split, exact B20, apply exists.intro tB₃, split, exact B25, refl, }, { split, { split, apply B22, apply B27, }, { rw set.prod_inter_prod, rw set.prod_subset_prod_iff, left,split;assumption, } } }, { split, { ext;split;intro C1, { simp, }, { simp, have C2:x.fst ∈ ⋃₀ Bα, { rw A5, simp, }, cases C2 with S C3, cases C3 with C4 C5, have C6:x.snd ∈ ⋃₀ Bβ, { rw A9, simp, }, cases C6 with T C7, cases C7 with C8 C9, apply exists.intro (@set.prod α β S T), simp, split, { apply (exists.intro S), split, exact C4, apply (exists.intro T), split, { exact C8, }, { refl, } }, { split, { exact C5, }, { exact C9, } } } }, { apply generate_from_eq_generate_from, { intros X D1, cases D1, { cases D1 with S D2, cases D2 with D3 D4, rw ← A9 at D4, rw set.prod_sUnion_right at D4, subst X, apply topological_space.generate_open.sUnion, intros ST D5, cases D5 with T D6, cases D6 with D7 D8, subst ST, apply topological_space.generate_open.basic, simp, apply exists.intro S, split, exact D3, apply exists.intro T, split, exact D7, refl, }, { cases D1 with T D2, cases D2 with D3 D4, rw ← A5 at D4, rw set.prod_sUnion_left at D4, subst X, apply topological_space.generate_open.sUnion, intros ST D5, cases D5 with S D6, cases D6 with D7 D8, subst ST, apply topological_space.generate_open.basic, simp, apply exists.intro S, split, exact D7, apply exists.intro T, split, exact D3, refl, } }, { intros X E1, cases E1 with S E2, cases E2 with E2 E3, cases E3 with T E4, cases E4 with E5 E6, have E7:X = (set.prod S set.univ) ∩ (set.prod set.univ T), { rw E6, rw set.prod_inter_prod, simp, }, subst X, apply topological_space.generate_open.inter;apply topological_space.generate_open.basic, { left, apply exists.intro S, split, { exact E2, }, { unfold set.prod, simp,refl, } }, { right, apply exists.intro T, split, { exact E5, }, { unfold set.prod, simp,refl, } } } } }, end
a686345aae18ed2082202519a665314c5e3fdade
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/pi/algebra.lean
dd41405df5a0efcfe9bc8be79ff8c19ecfefe9fd
[ "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
11,883
lean
/- Copyright (c) 2020 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Patrick Massot, Eric Wieser -/ import tactic.to_additive import algebra.group.defs import logic.unique import tactic.congr import tactic.simpa import tactic.split_ifs import data.sum.basic import data.prod.basic /-! # Instances and theorems on pi types > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > https://github.com/leanprover-community/mathlib4/pull/564 > Any changes to this file require a corresponding PR to mathlib4. This file provides basic definitions and notation instances for Pi types. Instances of more sophisticated classes are defined in `pi.lean` files elsewhere. -/ open function universes u v₁ v₂ v₃ variable {I : Type u} -- The indexing type variables {α β γ : Type*} -- The families of types already equipped with instances variables {f : I → Type v₁} {g : I → Type v₂} {h : I → Type v₃} variables (x y : Π i, f i) (i : I) namespace pi /-! `1`, `0`, `+`, `*`, `+ᵥ`, `•`, `^`, `-`, `⁻¹`, and `/` are defined pointwise. -/ @[to_additive] instance has_one [∀ i, has_one $ f i] : has_one (Π i : I, f i) := ⟨λ _, 1⟩ @[simp, to_additive] lemma one_apply [∀ i, has_one $ f i] : (1 : Π i, f i) i = 1 := rfl @[to_additive] lemma one_def [Π i, has_one $ f i] : (1 : Π i, f i) = λ i, 1 := rfl @[simp, to_additive] lemma const_one [has_one β] : const α (1 : β) = 1 := rfl @[simp, to_additive] lemma one_comp [has_one γ] (x : α → β) : (1 : β → γ) ∘ x = 1 := rfl @[simp, to_additive] lemma comp_one [has_one β] (x : β → γ) : x ∘ 1 = const α (x 1) := rfl @[to_additive] instance has_mul [∀ i, has_mul $ f i] : has_mul (Π i : I, f i) := ⟨λ f g i, f i * g i⟩ @[simp, to_additive] lemma mul_apply [∀ i, has_mul $ f i] : (x * y) i = x i * y i := rfl @[to_additive] lemma mul_def [Π i, has_mul $ f i] : x * y = λ i, x i * y i := rfl @[simp, to_additive] lemma const_mul [has_mul β] (a b : β) : const α a * const α b = const α (a * b) := rfl @[to_additive] lemma mul_comp [has_mul γ] (x y : β → γ) (z : α → β) : (x * y) ∘ z = x ∘ z * y ∘ z := rfl @[to_additive pi.has_vadd] instance has_smul [Π i, has_smul α $ f i] : has_smul α (Π i : I, f i) := ⟨λ s x, λ i, s • (x i)⟩ @[simp, to_additive] lemma smul_apply [Π i, has_smul α $ f i] (s : α) (x : Π i, f i) (i : I) : (s • x) i = s • x i := rfl @[to_additive] lemma smul_def [Π i, has_smul α $ f i] (s : α) (x : Π i, f i) : s • x = λ i, s • x i := rfl @[simp, to_additive] lemma smul_const [has_smul α β] (a : α) (b : β) : a • const I b = const I (a • b) := rfl @[to_additive] lemma smul_comp [has_smul α γ] (a : α) (x : β → γ) (y : I → β) : (a • x) ∘ y = a • (x ∘ y) := rfl @[to_additive pi.has_smul] instance has_pow [Π i, has_pow (f i) β] : has_pow (Π i, f i) β := ⟨λ x b i, (x i) ^ b⟩ @[simp, to_additive pi.smul_apply, to_additive_reorder 5] lemma pow_apply [Π i, has_pow (f i) β] (x : Π i, f i) (b : β) (i : I) : (x ^ b) i = (x i) ^ b := rfl @[to_additive pi.smul_def, to_additive_reorder 5] lemma pow_def [Π i, has_pow (f i) β] (x : Π i, f i) (b : β) : x ^ b = λ i, (x i) ^ b := rfl -- `to_additive` generates bad output if we take `has_pow α β`. @[simp, to_additive smul_const, to_additive_reorder 5] lemma const_pow [has_pow β α] (b : β) (a : α) : const I b ^ a = const I (b ^ a) := rfl @[to_additive smul_comp, to_additive_reorder 6] lemma pow_comp [has_pow γ α] (x : β → γ) (a : α) (y : I → β) : (x ^ a) ∘ y = (x ∘ y) ^ a := rfl @[simp] lemma bit0_apply [Π i, has_add $ f i] : (bit0 x) i = bit0 (x i) := rfl @[simp] lemma bit1_apply [Π i, has_add $ f i] [Π i, has_one $ f i] : (bit1 x) i = bit1 (x i) := rfl @[to_additive] instance has_inv [∀ i, has_inv $ f i] : has_inv (Π i : I, f i) := ⟨λ f i, (f i)⁻¹⟩ @[simp, to_additive] lemma inv_apply [∀ i, has_inv $ f i] : x⁻¹ i = (x i)⁻¹ := rfl @[to_additive] lemma inv_def [Π i, has_inv $ f i] : x⁻¹ = λ i, (x i)⁻¹ := rfl @[to_additive] lemma const_inv [has_inv β] (a : β) : (const α a)⁻¹ = const α a⁻¹ := rfl @[to_additive] lemma inv_comp [has_inv γ] (x : β → γ) (y : α → β) : x⁻¹ ∘ y = (x ∘ y)⁻¹ := rfl @[to_additive] instance has_div [Π i, has_div $ f i] : has_div (Π i : I, f i) := ⟨λ f g i, f i / g i⟩ @[simp, to_additive] lemma div_apply [Π i, has_div $ f i] : (x / y) i = x i / y i := rfl @[to_additive] lemma div_def [Π i, has_div $ f i] : x / y = λ i, x i / y i := rfl @[to_additive] lemma div_comp [has_div γ] (x y : β → γ) (z : α → β) : (x / y) ∘ z = x ∘ z / y ∘ z := rfl @[simp, to_additive] lemma const_div [has_div β] (a b : β) : const α a / const α b = const α (a / b) := rfl section variables [decidable_eq I] variables [Π i, has_one (f i)] [Π i, has_one (g i)] [Π i, has_one (h i)] /-- The function supported at `i`, with value `x` there, and `1` elsewhere. -/ @[to_additive pi.single "The function supported at `i`, with value `x` there, and `0` elsewhere." ] def mul_single (i : I) (x : f i) : Π i, f i := function.update 1 i x @[simp, to_additive] lemma mul_single_eq_same (i : I) (x : f i) : mul_single i x i = x := function.update_same i x _ @[simp, to_additive] lemma mul_single_eq_of_ne {i i' : I} (h : i' ≠ i) (x : f i) : mul_single i x i' = 1 := function.update_noteq h x _ /-- Abbreviation for `mul_single_eq_of_ne h.symm`, for ease of use by `simp`. -/ @[simp, to_additive "Abbreviation for `single_eq_of_ne h.symm`, for ease of use by `simp`."] lemma mul_single_eq_of_ne' {i i' : I} (h : i ≠ i') (x : f i) : mul_single i x i' = 1 := mul_single_eq_of_ne h.symm x @[simp, to_additive] lemma mul_single_one (i : I) : mul_single i (1 : f i) = 1 := function.update_eq_self _ _ /-- On non-dependent functions, `pi.mul_single` can be expressed as an `ite` -/ @[to_additive "On non-dependent functions, `pi.single` can be expressed as an `ite`"] lemma mul_single_apply {β : Sort*} [has_one β] (i : I) (x : β) (i' : I) : mul_single i x i' = if i' = i then x else 1 := function.update_apply 1 i x i' /-- On non-dependent functions, `pi.mul_single` is symmetric in the two indices. -/ @[to_additive "On non-dependent functions, `pi.single` is symmetric in the two indices."] lemma mul_single_comm {β : Sort*} [has_one β] (i : I) (x : β) (i' : I) : mul_single i x i' = mul_single i' x i := by simp [mul_single_apply, eq_comm] @[to_additive] lemma apply_mul_single (f' : Π i, f i → g i) (hf' : ∀ i, f' i 1 = 1) (i : I) (x : f i) (j : I): f' j (mul_single i x j) = mul_single i (f' i x) j := by simpa only [pi.one_apply, hf', mul_single] using function.apply_update f' 1 i x j @[to_additive apply_single₂] lemma apply_mul_single₂ (f' : Π i, f i → g i → h i) (hf' : ∀ i, f' i 1 1 = 1) (i : I) (x : f i) (y : g i) (j : I): f' j (mul_single i x j) (mul_single i y j) = mul_single i (f' i x y) j := begin by_cases h : j = i, { subst h, simp only [mul_single_eq_same] }, { simp only [mul_single_eq_of_ne h, hf'] }, end @[to_additive] lemma mul_single_op {g : I → Type*} [Π i, has_one (g i)] (op : Π i, f i → g i) (h : ∀ i, op i 1 = 1) (i : I) (x : f i) : mul_single i (op i x) = λ j, op j (mul_single i x j) := eq.symm $ funext $ apply_mul_single op h i x @[to_additive] lemma mul_single_op₂ {g₁ g₂ : I → Type*} [Π i, has_one (g₁ i)] [Π i, has_one (g₂ i)] (op : Π i, g₁ i → g₂ i → f i) (h : ∀ i, op i 1 1 = 1) (i : I) (x₁ : g₁ i) (x₂ : g₂ i) : mul_single i (op i x₁ x₂) = λ j, op j (mul_single i x₁ j) (mul_single i x₂ j) := eq.symm $ funext $ apply_mul_single₂ op h i x₁ x₂ variables (f) @[to_additive] lemma mul_single_injective (i : I) : function.injective (mul_single i : f i → Π i, f i) := function.update_injective _ i @[simp, to_additive] lemma mul_single_inj (i : I) {x y : f i} : mul_single i x = mul_single i y ↔ x = y := (pi.mul_single_injective _ _).eq_iff end /-- The mapping into a product type built from maps into each component. -/ @[simp] protected def prod (f' : Π i, f i) (g' : Π i, g i) (i : I) : f i × g i := (f' i, g' i) @[simp] lemma prod_fst_snd : pi.prod (prod.fst : α × β → α) (prod.snd : α × β → β) = id := funext $ λ _, prod.mk.eta @[simp] lemma prod_snd_fst : pi.prod (prod.snd : α × β → β) (prod.fst : α × β → α) = prod.swap := rfl end pi namespace function section extend @[to_additive] lemma extend_one [has_one γ] (f : α → β) : function.extend f (1 : α → γ) (1 : β → γ) = 1 := funext $ λ _, by apply if_t_t _ _ @[to_additive] lemma extend_mul [has_mul γ] (f : α → β) (g₁ g₂ : α → γ) (e₁ e₂ : β → γ) : function.extend f (g₁ * g₂) (e₁ * e₂) = function.extend f g₁ e₁ * function.extend f g₂ e₂ := funext $ λ _, by convert (apply_dite2 (*) _ _ _ _ _).symm @[to_additive] lemma extend_inv [has_inv γ] (f : α → β) (g : α → γ) (e : β → γ) : function.extend f (g⁻¹) (e⁻¹) = (function.extend f g e)⁻¹ := funext $ λ _, by convert (apply_dite has_inv.inv _ _ _).symm @[to_additive] lemma extend_div [has_div γ] (f : α → β) (g₁ g₂ : α → γ) (e₁ e₂ : β → γ) : function.extend f (g₁ / g₂) (e₁ / e₂) = function.extend f g₁ e₁ / function.extend f g₂ e₂ := funext $ λ _, by convert (apply_dite2 (/) _ _ _ _ _).symm end extend lemma surjective_pi_map {F : Π i, f i → g i} (hF : ∀ i, surjective (F i)) : surjective (λ x : Π i, f i, λ i, F i (x i)) := λ y, ⟨λ i, (hF i (y i)).some, funext $ λ i, (hF i (y i)).some_spec⟩ lemma injective_pi_map {F : Π i, f i → g i} (hF : ∀ i, injective (F i)) : injective (λ x : Π i, f i, λ i, F i (x i)) := λ x y h, funext $ λ i, hF i $ (congr_fun h i : _) lemma bijective_pi_map {F : Π i, f i → g i} (hF : ∀ i, bijective (F i)) : bijective (λ x : Π i, f i, λ i, F i (x i)) := ⟨injective_pi_map (λ i, (hF i).injective), surjective_pi_map (λ i, (hF i).surjective)⟩ end function /-- If the one function is surjective, the codomain is trivial. -/ @[to_additive "If the zero function is surjective, the codomain is trivial."] def unique_of_surjective_one (α : Type*) {β : Type*} [has_one β] (h : function.surjective (1 : α → β)) : unique β := h.unique_of_surjective_const α (1 : β) @[to_additive subsingleton.pi_single_eq] lemma subsingleton.pi_mul_single_eq {α : Type*} [decidable_eq I] [subsingleton I] [has_one α] (i : I) (x : α) : pi.mul_single i x = λ _, x := funext $ λ j, by rw [subsingleton.elim j i, pi.mul_single_eq_same] namespace sum variables (a a' : α → γ) (b b' : β → γ) @[simp, to_additive] lemma elim_one_one [has_one γ] : sum.elim (1 : α → γ) (1 : β → γ) = 1 := sum.elim_const_const 1 @[simp, to_additive] lemma elim_mul_single_one [decidable_eq α] [decidable_eq β] [has_one γ] (i : α) (c : γ) : sum.elim (pi.mul_single i c) (1 : β → γ) = pi.mul_single (sum.inl i) c := by simp only [pi.mul_single, sum.elim_update_left, elim_one_one] @[simp, to_additive] lemma elim_one_mul_single [decidable_eq α] [decidable_eq β] [has_one γ] (i : β) (c : γ) : sum.elim (1 : α → γ) (pi.mul_single i c) = pi.mul_single (sum.inr i) c := by simp only [pi.mul_single, sum.elim_update_right, elim_one_one] @[to_additive] lemma elim_inv_inv [has_inv γ] : sum.elim a⁻¹ b⁻¹ = (sum.elim a b)⁻¹ := (sum.comp_elim has_inv.inv a b).symm @[to_additive] lemma elim_mul_mul [has_mul γ] : sum.elim (a * a') (b * b') = sum.elim a b * sum.elim a' b' := by { ext x, cases x; refl } @[to_additive] lemma elim_div_div [has_div γ] : sum.elim (a / a') (b / b') = sum.elim a b / sum.elim a' b' := by { ext x, cases x; refl } end sum
34ae80052363d28a41df3d4e43f3867616b42843
4727251e0cd73359b15b664c3170e5d754078599
/src/probability/cond_count.lean
ade487c565820c447df258240f90e1628f19ac59
[ "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,273
lean
/- Copyright (c) 2022 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying, Bhavik Mehta -/ import probability.conditional /-! # Classical probability The classical formulation of probability states that the probability of an event occurring is the ratio of that event to all possible events. This notion can be expressed with measure theory using the counting measure. In particular, given the sets `s` and `t`, we define the probability of `t` occuring in `s` to be `|s|⁻¹ * |s ∩ t|`. With this definition, we recover the the probability over the entire sample space when `s = set.univ`. Classical probability is often used in combinatorics and we prove some useful lemmas in this file for that purpose. ## main definition * `probability_theory.cond_count`: given a set `s`, `cond_count s` is the counting measure conditioned on `s`. This is a probability measure when `s` is finite and nonempty. ## notes The original aim of this file is to provide a measure theoretic method of describing the probability an element of a set `s` satisfies some predicate `P`. Our current formulation still allow us to describe this by abusing the definitional equality of sets and predicates by simply writing `cond_count s P`. We should avoid this however as none of the lemmas are written for predicates. -/ noncomputable theory open_locale probability_theory open measure_theory measurable_space namespace probability_theory variables {α : Type*} [measurable_space α] /-- Given a set `s`, `cond_count s` is the counting measure conditioned on `s`. In particular, `cond_count s t` is the proportion of `s` that is contained in `t`. This is a probability measure when `s` is finite and nonempty and is given by `probability_theory.cond_count_is_probability_measure`. -/ def cond_count (s : set α) : measure α := measure.count[|s] @[simp] lemma cond_count_empty_meas : (cond_count ∅ : measure α) = 0 := by simp [cond_count] lemma cond_count_empty {s : set α} : cond_count s ∅ = 0 := by simp lemma finite_of_cond_count_ne_zero {s t : set α} (h : cond_count s t ≠ 0) : s.finite := begin by_contra hs', simpa [cond_count, cond, measure.count_apply_infinite hs'] using h, end variables [measurable_singleton_class α] lemma cond_count_is_probability_measure {s : set α} (hs : s.finite) (hs' : s.nonempty) : is_probability_measure (cond_count s) := { measure_univ := begin rw [cond_count, cond_apply _ hs.measurable_set, set.inter_univ, ennreal.inv_mul_cancel], { exact λ h, hs'.ne_empty $ measure.empty_of_count_eq_zero h }, { exact (measure.count_apply_lt_top.2 hs).ne } end } lemma cond_count_singleton (a : α) (t : set α) [decidable (a ∈ t)] : cond_count {a} t = if a ∈ t then 1 else 0 := begin rw [cond_count, cond_apply _ (measurable_set_singleton a), measure.count_singleton, ennreal.inv_one, one_mul], split_ifs, { rw [(by simpa : ({a} : set α) ∩ t = {a}), measure.count_singleton] }, { rw [(by simpa : ({a} : set α) ∩ t = ∅), measure.count_empty] }, end variables {s t u : set α} lemma cond_count_inter_self (hs : s.finite): cond_count s (s ∩ t) = cond_count s t := by rw [cond_count, cond_inter_self _ hs.measurable_set] lemma cond_count_self (hs : s.finite) (hs' : s.nonempty) : cond_count s s = 1 := begin rw [cond_count, cond_apply _ hs.measurable_set, set.inter_self, ennreal.inv_mul_cancel], { exact λ h, hs'.ne_empty $ measure.empty_of_count_eq_zero h }, { exact (measure.count_apply_lt_top.2 hs).ne } end lemma cond_count_eq_one_of (hs : s.finite) (hs' : s.nonempty) (ht : s ⊆ t) : cond_count s t = 1 := begin haveI := cond_count_is_probability_measure hs hs', refine eq_of_le_of_not_lt prob_le_one _, rw [not_lt, ← cond_count_self hs hs'], exact measure_mono ht, end lemma pred_true_of_cond_count_eq_one (h : cond_count s t = 1) : s ⊆ t := begin have hsf := finite_of_cond_count_ne_zero (by { rw h, exact one_ne_zero }), rw [cond_count, cond_apply _ hsf.measurable_set, mul_comm] at h, replace h := ennreal.eq_inv_of_mul_eq_one_left h, rw [inv_inv, measure.count_apply_finite _ hsf, measure.count_apply_finite _ (hsf.inter_of_left _), nat.cast_inj] at h, suffices : s ∩ t = s, { exact this ▸ λ x hx, hx.2 }, rw ← @set.finite.to_finset_inj _ _ _ (hsf.inter_of_left _) hsf, exact finset.eq_of_subset_of_card_le (set.finite.to_finset_mono.2 (s.inter_subset_left t)) h.symm.le end lemma cond_count_eq_zero_iff (hs : s.finite) : cond_count s t = 0 ↔ s ∩ t = ∅ := by simp [cond_count, cond_apply _ hs.measurable_set, measure.count_apply_eq_top, set.not_infinite.2 hs, measure.count_apply_finite _ (hs.inter_of_left _)] lemma cond_count_univ (hs : s.finite) (hs' : s.nonempty) : cond_count s set.univ = 1 := cond_count_eq_one_of hs hs' s.subset_univ lemma cond_count_inter (hs : s.finite) : cond_count s (t ∩ u) = cond_count (s ∩ t) u * cond_count s t := begin by_cases hst : s ∩ t = ∅, { rw [hst, cond_count_empty_meas, measure.coe_zero, pi.zero_apply, zero_mul, cond_count_eq_zero_iff hs, ← set.inter_assoc, hst, set.empty_inter] }, rw [cond_count, cond_count, cond_apply _ hs.measurable_set, cond_apply _ hs.measurable_set, cond_apply _ (hs.inter_of_left _).measurable_set, mul_comm _ (measure.count (s ∩ t)), ← mul_assoc, mul_comm _ (measure.count (s ∩ t)), ← mul_assoc, ennreal.mul_inv_cancel, one_mul, mul_comm, set.inter_assoc], { rwa ← measure.count_eq_zero_iff at hst }, { exact (measure.count_apply_lt_top.2 $ hs.inter_of_left _).ne } end lemma cond_count_inter' (hs : s.finite) : cond_count s (t ∩ u) = cond_count (s ∩ u) t * cond_count s u := begin rw ← set.inter_comm, exact cond_count_inter hs, end lemma cond_count_union (hs : s.finite) (htu : disjoint t u) : cond_count s (t ∪ u) = cond_count s t + cond_count s u := begin rw [cond_count, cond_apply _ hs.measurable_set, cond_apply _ hs.measurable_set, cond_apply _ hs.measurable_set, set.inter_union_distrib_left, measure_union, mul_add], exacts [htu.mono inf_le_right inf_le_right, (hs.inter_of_left _).measurable_set], end lemma cond_count_compl (hs : s.finite) (hs' : s.nonempty) : cond_count s t + cond_count s tᶜ = 1 := begin rw [← cond_count_union hs disjoint_compl_right, set.union_compl_self, (cond_count_is_probability_measure hs hs').measure_univ], end lemma cond_count_disjoint_union (hs : s.finite) (ht : t.finite) (hst : disjoint s t) : cond_count s u * cond_count (s ∪ t) s + cond_count t u * cond_count (s ∪ t) t = cond_count (s ∪ t) u := begin rcases s.eq_empty_or_nonempty with (rfl | hs'); rcases t.eq_empty_or_nonempty with (rfl | ht'), { simp }, { simp [cond_count_self ht ht'] }, { simp [cond_count_self hs hs'] }, rw [cond_count, cond_count, cond_count, cond_apply _ hs.measurable_set, cond_apply _ ht.measurable_set, cond_apply _ (hs.union ht).measurable_set, cond_apply _ (hs.union ht).measurable_set, cond_apply _ (hs.union ht).measurable_set], conv_lhs { rw [set.union_inter_cancel_left, set.union_inter_cancel_right, mul_comm (measure.count (s ∪ t))⁻¹, mul_comm (measure.count (s ∪ t))⁻¹, ← mul_assoc, ← mul_assoc, mul_comm _ (measure.count s), mul_comm _ (measure.count t), ← mul_assoc, ← mul_assoc] }, rw [ennreal.mul_inv_cancel, ennreal.mul_inv_cancel, one_mul, one_mul, ← add_mul, ← measure_union, set.union_inter_distrib_right, mul_comm], exacts [hst.mono inf_le_left inf_le_left, (ht.inter_of_left _).measurable_set, measure.count_ne_zero ht', (measure.count_apply_lt_top.2 ht).ne, measure.count_ne_zero hs', (measure.count_apply_lt_top.2 hs).ne], end /-- A version of the law of total probability for counting probabilites. -/ lemma cond_count_add_compl_eq (hs : s.finite) : cond_count (s ∩ u) t * cond_count s u + cond_count (s ∩ uᶜ) t * cond_count s uᶜ = cond_count s t := begin conv_rhs { rw [(by simp : s = s ∩ u ∪ s ∩ uᶜ), ← cond_count_disjoint_union (hs.inter_of_left _) (hs.inter_of_left _) (disjoint_compl_right.mono inf_le_right inf_le_right)] }, simp [cond_count_inter_self hs], end end probability_theory
7d71d40b11271bcac389d01997f467e01ff3a534
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/differentiable.lean
567543cfa0078d8ecd4941bcfe7ce1ca7b52d18b
[ "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,450
lean
import analysis.special_functions.trigonometric.deriv import analysis.special_functions.log.deriv namespace real example : differentiable ℝ (λ (x : ℝ), exp x) := by simp example : differentiable ℝ (λ (x : ℝ), exp ((sin x)^2) - exp (exp (cos (x - 3)))) := by simp example (x : ℝ) : deriv (λ (x : ℝ), (cos x)^2 + 1 + (sin x)^2) x = 0 := by { simp, ring } example (x : ℝ) : deriv (λ (x : ℝ), (1+x)^3 - x^3 - 3 * x^2 - 3 * x - 4) x = 0 := by { simp, ring } example (x : ℝ) : deriv (λ x, cos (sin x) * exp x) x = (cos(sin(x))-sin(sin(x))*cos(x))*exp(x) := by { simp, ring } example (x : ℝ) : differentiable_at ℝ (λ x, (cos x, x)) x := by simp example (x : ℝ) (h : 1 + sin x ≠ 0) : deriv (λ x, exp (cos x) / (1 + sin x)) x = (-(exp (cos x) * sin x * (1 + sin x)) - exp (cos x) * cos x) / (1 + sin x) ^ 2 := by simp [h] example (x : ℝ) : differentiable_at ℝ (λ x, (sin x) / (exp x)) x := by simp [exp_ne_zero] example : differentiable ℝ (λ x, (sin x) / (exp x)) := by simp [exp_ne_zero] example (x : ℝ) (h : x ≠ 0) : deriv (λ x, x * (log x - 1)) x = log x := by simp [h] end real namespace complex example : differentiable ℂ (λ (x : ℂ), exp x) := by simp example : differentiable ℂ (λ (x : ℂ), exp ((sin x)^2) - exp (exp (cos (x - 3)))) := by simp example (x : ℂ) : deriv (λ (x : ℂ), (cos x)^2 + I + (sin x)^2) x = 0 := by { simp, ring } example (x : ℂ) : deriv (λ x, cos (sin x) * exp x) x = (cos(sin(x))-sin(sin(x))*cos(x))*exp(x) := by { simp, ring } example (x : ℂ) : differentiable_at ℂ (λ x, (cos x, x)) x := by simp example (x : ℂ) (h : 1 + sin x ≠ 0) : deriv (λ x, exp (cos x) / (1 + sin x)) x = (-(exp (cos x) * sin x * (1 + sin x)) - exp (cos x) * cos x) / (1 + sin x) ^ 2 := by simp [h] example (x : ℂ) : differentiable_at ℂ (λ x, (sin x) / (exp x)) x := by simp [exp_ne_zero] example : differentiable ℂ (λ x, (sin x) / (exp x)) := by simp [exp_ne_zero] end complex namespace polynomial open_locale polynomial variables {R : Type*} [comm_semiring R] example : (2 : R[X]).derivative = 0 := by conv_lhs { simp } example : (3 + X : R[X]).derivative = 1 := by conv_lhs { simp } example : (2 * X ^ 2 : R[X]).derivative = 4 * X := by conv_lhs { simp, ring_nf, } example : (X ^ 2 : R[X]).derivative = 2 * X := by conv_lhs { simp } example : ((C 2 * X ^ 3).derivative : R[X]) = 6 * X ^ 2 := by conv_lhs { simp, ring_nf, } end polynomial
8b5bdd5b861ba07d3564112a56c4d1107756b988
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/sym/card.lean
09bba6bf1c06b7521aed6521a4718e2dca7efee3
[ "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
8,808
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, Huỳnh Trần Khanh, Stuart Presnell -/ import algebra.big_operators.basic import data.finset.sym /-! # Stars and bars In this file, we prove (in `sym.card_sym_eq_multichoose`) that the function `multichoose n k` defined in `data/nat/choose/basic` counts the number of multisets of cardinality `k` over an alphabet of cardinality `n`. In conjunction with `nat.multichoose_eq` proved in `data/nat/choose/basic`, which shows that `multichoose n k = choose (n + k - 1) k`, this is central to the "stars and bars" technique in combinatorics, where we switch between counting multisets of size `k` over an alphabet of size `n` to counting strings of `k` elements ("stars") separated by `n-1` dividers ("bars"). ## Informal statement Many problems in mathematics are of the form of (or can be reduced to) putting `k` indistinguishable objects into `n` distinguishable boxes; for example, the problem of finding natural numbers `x1, ..., xn` whose sum is `k`. This is equivalent to forming a multiset of cardinality `k` from an alphabet of cardinality `n` -- for each box `i ∈ [1, n]` the multiset contains as many copies of `i` as there are items in the `i`th box. The "stars and bars" technique arises from another way of presenting the same problem. Instead of putting `k` items into `n` boxes, we take a row of `k` items (the "stars") and separate them by inserting `n-1` dividers (the "bars"). For example, the pattern `*|||**|*|` exhibits 4 items distributed into 6 boxes -- note that any box, including the first and last, may be empty. Such arrangements of `k` stars and `n-1` bars are in 1-1 correspondence with multisets of size `k` over an alphabet of size `n`, and are counted by `choose (n + k - 1) k`. Note that this problem is one component of Gian-Carlo Rota's "Twelvefold Way" https://en.wikipedia.org/wiki/Twelvefold_way ## Formal statement Here we generalise the alphabet to an arbitrary fintype `α`, and we use `sym α k` as the type of multisets of size `k` over `α`. Thus the statement that these are counted by `multichoose` is: `sym.card_sym_eq_multichoose : card (sym α k) = multichoose (card α) k` while the "stars and bars" technique gives `sym.card_sym_eq_choose : card (sym α k) = choose (card α + k - 1) k` ## Tags stars and bars, multichoose -/ open finset fintype function sum nat variables {α β : Type*} namespace sym section sym variables (α) (n : ℕ) /-- Over `fin n+1`, the multisets of size `k+1` containing `0` are equivalent to those of size `k`, as demonstrated by respectively erasing or appending `0`. -/ protected def E1 {n k : ℕ} : {s : sym (fin n.succ) k.succ // ↑0 ∈ s} ≃ sym (fin n.succ) k := { to_fun := λ s, s.1.erase 0 s.2, inv_fun := λ s, ⟨cons 0 s, mem_cons_self 0 s⟩, left_inv := λ s, by simp, right_inv := λ s, by simp } /-- The multisets of size `k` over `fin n+2` not containing `0` are equivalent to those of size `k` over `fin n+1`, as demonstrated by respectively decrementing or incrementing every element of the multiset. -/ protected def E2 {n k : ℕ} : {s : sym (fin n.succ.succ) k // ↑0 ∉ s} ≃ sym (fin n.succ) k := { to_fun := λ s, map (fin.pred_above 0) s.1, inv_fun := λ s, ⟨map (fin.succ_above 0) s, (mt mem_map.1) (not_exists.2 (λ t, (not_and.2 (λ _, (fin.succ_above_ne _ t)))))⟩, left_inv := λ s, by { obtain ⟨s, hs⟩ := s, simp only [fin.zero_succ_above, map_map, comp_app], nth_rewrite_rhs 0 ←(map_id' s), refine sym.map_congr (λ v hv, _), simp [fin.pred_above_zero (ne_of_mem_of_not_mem hv hs)] }, right_inv := λ s, by { simp only [fin.zero_succ_above, map_map, comp_app], nth_rewrite_rhs 0 ←(map_id' s), refine sym.map_congr (λ v hv, _), rw [←fin.zero_succ_above v, ←fin.cast_succ_zero, fin.pred_above_succ_above 0 v] } } lemma card_sym_fin_eq_multichoose (n k : ℕ) : card (sym (fin n) k) = multichoose n k := begin apply @pincer_recursion (λ n k, card (sym (fin n) k) = multichoose n k), { simp }, { intros b, induction b with b IHb, { simp }, rw [multichoose_zero_succ, card_eq_zero_iff], apply_instance }, { intros x y h1 h2, rw [multichoose_succ_succ, ←h1, ←h2, add_comm], cases x, { simp only [card_eq_zero_iff, nat.nat_zero_eq_zero, card_unique, self_eq_add_right], apply_instance }, rw ←card_sum, refine fintype.card_congr (equiv.symm _), apply (equiv.sum_congr sym.E1.symm sym.E2.symm).trans, apply equiv.sum_compl }, end /-- For any fintype `α` of cardinality `n`, `card (sym α k) = multichoose (card α) k` -/ lemma card_sym_eq_multichoose (α : Type*) (k : ℕ) [fintype α] [fintype (sym α k)] : card (sym α k) = multichoose (card α) k := by { rw ←card_sym_fin_eq_multichoose, exact card_congr (equiv_congr (equiv_fin α)) } /-- The *stars and bars* lemma: the cardinality of `sym α k` is equal to `nat.choose (card α + k - 1) k`. -/ lemma card_sym_eq_choose {α : Type*} [fintype α] (k : ℕ) [fintype (sym α k)] : card (sym α k) = (card α + k - 1).choose k := by rw [card_sym_eq_multichoose, nat.multichoose_eq] end sym end sym namespace sym2 variables [decidable_eq α] /-- The `diag` of `s : finset α` is sent on a finset of `sym2 α` of card `s.card`. -/ lemma card_image_diag (s : finset α) : (s.diag.image quotient.mk).card = s.card := begin rw [card_image_of_inj_on, diag_card], rintro ⟨x₀, x₁⟩ hx _ _ h, cases quotient.eq.1 h, { refl }, { simp only [mem_coe, mem_diag] at hx, rw hx.2 } end lemma two_mul_card_image_off_diag (s : finset α) : 2 * (s.off_diag.image quotient.mk).card = s.off_diag.card := begin rw [card_eq_sum_card_fiberwise (λ x, mem_image_of_mem _ : ∀ x ∈ s.off_diag, quotient.mk x ∈ s.off_diag.image quotient.mk), sum_const_nat (quotient.ind _), mul_comm], rintro ⟨x, y⟩ hxy, simp_rw [mem_image, exists_prop, mem_off_diag, quotient.eq] at hxy, obtain ⟨a, ⟨ha₁, ha₂, ha⟩, h⟩ := hxy, obtain ⟨hx, hy, hxy⟩ : x ∈ s ∧ y ∈ s ∧ x ≠ y, { cases h; have := ha.symm; exact ⟨‹_›, ‹_›, ‹_›⟩ }, have hxy' : y ≠ x := hxy.symm, have : s.off_diag.filter (λ z, ⟦z⟧ = ⟦(x, y)⟧) = ({(x, y), (y, x)} : finset _), { ext ⟨x₁, y₁⟩, rw [mem_filter, mem_insert, mem_singleton, sym2.eq_iff, prod.mk.inj_iff, prod.mk.inj_iff, and_iff_right_iff_imp], rintro (⟨rfl, rfl⟩ | ⟨rfl, rfl⟩); rw mem_off_diag; exact ⟨‹_›, ‹_›, ‹_›⟩ }, -- hxy' is used here rw [this, card_insert_of_not_mem, card_singleton], simp only [not_and, prod.mk.inj_iff, mem_singleton], exact λ _, hxy', end /-- The `off_diag` of `s : finset α` is sent on a finset of `sym2 α` of card `s.off_diag.card / 2`. This is because every element `⟦(x, y)⟧` of `sym2 α` not on the diagonal comes from exactly two pairs: `(x, y)` and `(y, x)`. -/ lemma card_image_off_diag (s : finset α) : (s.off_diag.image quotient.mk).card = s.card.choose 2 := by rw [nat.choose_two_right, mul_tsub, mul_one, ←off_diag_card, nat.div_eq_of_eq_mul_right zero_lt_two (two_mul_card_image_off_diag s).symm] lemma card_subtype_diag [fintype α] : card {a : sym2 α // a.is_diag} = card α := begin convert card_image_diag (univ : finset α), rw [fintype.card_of_subtype, ←filter_image_quotient_mk_is_diag], rintro x, rw [mem_filter, univ_product_univ, mem_image], obtain ⟨a, ha⟩ := quotient.exists_rep x, exact and_iff_right ⟨a, mem_univ _, ha⟩, end lemma card_subtype_not_diag [fintype α] : card {a : sym2 α // ¬a.is_diag} = (card α).choose 2 := begin convert card_image_off_diag (univ : finset α), rw [fintype.card_of_subtype, ←filter_image_quotient_mk_not_is_diag], rintro x, rw [mem_filter, univ_product_univ, mem_image], obtain ⟨a, ha⟩ := quotient.exists_rep x, exact and_iff_right ⟨a, mem_univ _, ha⟩, end /-- Finset **stars and bars** for the case `n = 2`. -/ lemma _root_.finset.card_sym2 (s : finset α) : s.sym2.card = s.card * (s.card + 1) / 2 := begin rw [←image_diag_union_image_off_diag, card_union_eq, sym2.card_image_diag, sym2.card_image_off_diag, nat.choose_two_right, add_comm, ←nat.triangle_succ, nat.succ_sub_one, mul_comm], rintro m he, rw [inf_eq_inter, mem_inter, mem_image, mem_image] at he, obtain ⟨⟨a, ha, rfl⟩, b, hb, hab⟩ := he, refine not_is_diag_mk_of_mem_off_diag hb _, rw hab, exact is_diag_mk_of_mem_diag ha, end /-- Type **stars and bars** for the case `n = 2`. -/ protected lemma card [fintype α] : card (sym2 α) = card α * (card α + 1) / 2 := finset.card_sym2 _ end sym2
5d64b19ab43395d3bf1a229b306994523708fa12
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Meta/Offset.lean
21ade50c12ecdfdbccab0cdb9a131c2763a3c475
[ "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
5,208
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.LBool import Lean.Meta.InferType import Lean.Meta.AppBuilder namespace Lean.Meta private abbrev withInstantiatedMVars (e : Expr) (k : Expr → OptionT MetaM α) : OptionT MetaM α := do let eNew ← instantiateMVars e if eNew.getAppFn.isMVar then failure else k eNew def isNatProjInst (declName : Name) (numArgs : Nat) : Bool := (numArgs == 4 && (declName == ``Add.add || declName == ``Sub.sub || declName == ``Mul.mul)) || (numArgs == 6 && (declName == ``HAdd.hAdd || declName == ``HSub.hSub || declName == ``HMul.hMul)) || (numArgs == 3 && declName == ``OfNat.ofNat) /-- Evaluate simple `Nat` expressions. Remark: this method assumes the given expression has type `Nat`. -/ partial def evalNat (e : Expr) : OptionT MetaM Nat := do match e with | .lit (.natVal n) => return n | .mdata _ e => evalNat e | .const ``Nat.zero .. => return 0 | .app .. => visit e | .mvar .. => visit e | _ => failure where visit e := do let f := e.getAppFn match f with | .mvar .. => withInstantiatedMVars e evalNat | .const c _ => let nargs := e.getAppNumArgs if c == ``Nat.succ && nargs == 1 then let v ← evalNat (e.getArg! 0) return v+1 else if c == ``Nat.add && nargs == 2 then let v₁ ← evalNat (e.getArg! 0) let v₂ ← evalNat (e.getArg! 1) return v₁ + v₂ else if c == ``Nat.sub && nargs == 2 then let v₁ ← evalNat (e.getArg! 0) let v₂ ← evalNat (e.getArg! 1) return v₁ - v₂ else if c == ``Nat.mul && nargs == 2 then let v₁ ← evalNat (e.getArg! 0) let v₂ ← evalNat (e.getArg! 1) return v₁ * v₂ else if isNatProjInst c nargs then evalNat (← unfoldProjInst? e) else failure | _ => failure mutual /-- Quick function for converting `e` into `s + k` s.t. `e` is definitionally equal to `Nat.add s k`. This function always succeeds in finding such `s` and `k` (as a last resort it returns `e` and `0`). -/ private partial def getOffset (e : Expr) : MetaM (Expr × Nat) := return (← isOffset? e).getD (e, 0) /-- Similar to `getOffset` but returns `none` if the expression is not syntactically an offset. -/ private partial def isOffset? (e : Expr) : OptionT MetaM (Expr × Nat) := do match e with | .app _ a => do let f := e.getAppFn match f with | .mvar .. => withInstantiatedMVars e isOffset? | .const c _ => let nargs := e.getAppNumArgs if c == ``Nat.succ && nargs == 1 then let (s, k) ← getOffset a pure (s, k+1) else if c == ``Nat.add && nargs == 2 then let v ← evalNat (e.getArg! 1) let (s, k) ← getOffset (e.getArg! 0) pure (s, k+v) else if (c == ``Add.add && nargs == 4) || (c == ``HAdd.hAdd && nargs == 6) then isOffset? (← unfoldProjInst? e) else failure | _ => failure | _ => failure end private def isNatZero (e : Expr) : MetaM Bool := do match (← evalNat e) with | some v => return v == 0 | _ => return false private def mkOffset (e : Expr) (offset : Nat) : MetaM Expr := do if offset == 0 then return e else if (← isNatZero e) then return mkNatLit offset else mkAdd e (mkNatLit offset) def isDefEqOffset (s t : Expr) : MetaM LBool := do let ifNatExpr (x : MetaM LBool) : MetaM LBool := do let type ← inferType s -- Remark: we use `withNewMCtxDepth` to make sure we don't assing metavariables when performing the `isDefEq` test if (← withNewMCtxDepth <| Meta.isExprDefEqAux type (mkConst ``Nat)) then x else return LBool.undef let isDefEq (s t) : MetaM LBool := ifNatExpr <| toLBoolM <| Meta.isExprDefEqAux s t if !(← getConfig).offsetCnstrs then return LBool.undef else match (← isOffset? s) with | some (s, k₁) => match (← isOffset? t) with | some (t, k₂) => -- s+k₁ =?= t+k₂ if k₁ == k₂ then isDefEq s t else if k₁ < k₂ then isDefEq s (← mkOffset t (k₂ - k₁)) else isDefEq (← mkOffset s (k₁ - k₂)) t | none => match (← evalNat t) with | some v₂ => -- s+k₁ =?= v₂ if v₂ ≥ k₁ then isDefEq s (mkNatLit <| v₂ - k₁) else ifNatExpr <| return LBool.false | none => return LBool.undef | none => match (← evalNat s) with | some v₁ => match (← isOffset? t) with | some (t, k₂) => -- v₁ =?= t+k₂ if v₁ ≥ k₂ then isDefEq (mkNatLit <| v₁ - k₂) t else ifNatExpr <| return LBool.false | none => match (← evalNat t) with | some v₂ => ifNatExpr <| return (v₁ == v₂).toLBool -- v₁ =?= v₂ | none => return LBool.undef | none => return LBool.undef end Lean.Meta
0faef4746f56796a7b14409e7614ae8806859ecb
3fed20a6f59e2663e48ee3bfc33dbc79256b4a50
/src/more.lean
97709f63426af9cde36c33cbcea5c28a530f8a2d
[]
no_license
arademaker/alc-lean
575203dae75f466cc686831d8b0d230fc3c00ced
46d5b582d4272493a26d6d47c0bfa0622c52aae4
refs/heads/master
1,622,696,540,378
1,618,442,995,000
1,618,442,995,000
37,130,780
4
3
null
1,618,365,416,000
1,433,853,111,000
Lean
UTF-8
Lean
false
false
12,114
lean
definition TBOX_subsumption (D : @Set Prop) (α : Prop) : Prop := (forall p: Prop, (p∈D → p)) → α infix `⊧` : 1 := TBOX_subsumption --\models definition models_proof (Ω: @Set Prop) (α: Prop) (h: (∀p: Prop, (p∈ Ω → p)) → α) : Ω⊧α := h example (C D : Concept) : C ⊓ D ⊑ C := take (I : Interp), take x : Interp.δ I, assume h : x ∈ interp (C⊓D), have l: x ∈ (interp C)∩(interp D), from h, have l2: x∈(interp C)∧x∈(interp D), from (iff.elim_left (IntersMember x)) l, show x∈(interp C), from and.elim_left l2 example (A B : Concept) : A ⊓ B ⊑ A ⊔ B := sorry example (C D E : Concept) : (Set.spec (λp: Prop, p = C ⊑ D ∨ p = D ⊑ E)) ⊧ C ⊑ E := assume h: forall (p: Prop), (p∈(Set.spec (λp: Prop, p = C⊑D ∨ p = D⊑E)) → p), have l1: C⊑D = C⊑D, from rfl, have l2: C⊑D = C⊑D ∨ C⊑D = D⊑E, from or.intro_left (C⊑D = D⊑E) l1, have l3: C⊑D ∈ (Set.spec (λp: Prop, p = C⊑D ∨ p = D⊑E)), from l2, have l4: D⊑E = D⊑E, from rfl, have l5: D⊑E = C⊑D ∨ D⊑E = D⊑E, from or.intro_right (D⊑E = C⊑D) l4, have l6: D⊑E ∈ (Set.spec (λp: Prop, p = C⊑D ∨ p = D⊑E)), from l5, have l7: C⊑D, from h (C⊑D) l3, have l8: D⊑E, from h (D⊑E) l6, assume I : Interp, take x : Interp.δ I, assume h2: x∈ interp C, have l9: x∈ interp D, from l7 I x h2, show x ∈ interp E, from l8 I x l9 inductive Label : Type := | all : Role → Label | ex : Role → Label notation `∀;` R := Label.all R inductive LabelConc : Type := -- labeled concept | mk : list Label → Concept → LabelConc notation L `[` C `]` := LabelConc.mk L C -- label to prefix definition LabelToPrefix [reducible] : list Label → (Concept → Concept) | LabelToPrefix nil C := C | LabelToPrefix ((Label.all R)::L) C := ∀;R . (LabelToPrefix L C) | LabelToPrefix ((Label.ex R)::L) C := ∃;R .(LabelToPrefix L C) definition getLabelList : LabelConc → list Label | getLabelList (LabelConc.mk L C) := L definition σ [reducible] : LabelConc → Concept | σ (LabelConc.mk L C) := (LabelToPrefix L) C -- negation of a list of labels definition negLabel: list Label → list Label | negLabel nil := nil | negLabel ((Label.all R)::L) := (Label.ex R)::(negLabel L) | negLabel ((Label.ex R)::L) := (Label.all R)::(negLabel L) definition AppendLabelList (L: list Label) (α: LabelConc) : LabelConc := LabelConc.rec_on α (λ(R: list Label) (C: Concept), (L++R)[C]) definition isNullLabelList : list Label → bool | isNullLabelList nil := tt | isNullLabelList (L::R) := ff definition isAllLabel : Label → bool | isAllLabel (Label.all R) := tt | isAllLabel (Label.ex R) := ff definition isExLabel : Label → bool | isExLabel (Label.all R) := ff | isExLabel (Label.ex R) := tt definition internalLabel : list Label → list Label | internalLabel nil := nil | internalLabel (R::L) := cond (isNullLabelList L) (R::nil) (internalLabel L) definition remainderLabel : list Label → list Label | remainderLabel nil := nil | remainderLabel (R::L) := cond (isNullLabelList L) nil (R::(remainderLabel L)) definition downLabelConc : LabelConc → Concept | downLabelConc (LabelConc.mk L C) := LabelToPrefix L C definition downInternalLabel : LabelConc → LabelConc | downInternalLabel (LabelConc.mk L C) := LabelConc.mk (remainderLabel L) ((LabelToPrefix (internalLabel L)) C) definition isOnlyAllLabel : list Label → bool | isOnlyAllLabel nil := tt | isOnlyAllLabel ((Label.all R)::L) := isOnlyAllLabel L | isOnlyAllLabel ((Label.ex R)::L) := ff definition isOnlyExLabel : list Label → bool | isOnlyExLabel nil := tt | isOnlyExLabel ((Label.all R)::L) := ff | isOnlyExLabel ((Label.ex R)::L) := (isOnlyExLabel L) definition is_true [reducible] (b : bool) := b = tt /- namespace tests -- tests constant C: Concept constants R1 R2 R3 : Role eval internalLabel (Label.ex R3 (Label.ex R1 (Label.all R2 (Label.null)))) eval remainderLabel (Label.ex R3 (Label.ex R1 (Label.all R2 (Label.null)))) definition test := LabelConc.mk (Label.ex R3 (Label.ex R1 (Label.all R2 (Label.null)))) C eval downInternalLabel test end tests-/ -- Structural Rules definition isNil {A: Type} : list A → bool | isNil nil := tt | isNil (a :: l) := ff definition AntecedentWrap : list LabelConc → Concept -- Não está sendo utilizado | AntecedentWrap nil := ⊤ | AntecedentWrap (α :: L) := list.rec_on L (σ α) (λα2 L2 C2, (σ α)⊓(AntecedentWrap L)) definition ConsequentWrap : list LabelConc → Concept | ConsequentWrap nil := ⊥ | ConsequentWrap (α :: L) := list.rec_on L (σ α) (λα2 L2 C2, (σ α)⊔(ConsequentWrap L)) definition AInterp [reducible] {I: Interp} : list LabelConc → @Set (Interp.δ I) -- Antecedent Interpretation | AInterp nil := U | AInterp (α :: L) := (interp (σ α))∩(AInterp L) definition CInterp [reducible] {I: Interp} : list LabelConc → @Set (Interp.δ I) -- Consequent Interpretation | CInterp nil := ∅ | CInterp (α::L) := (interp (σ α))∪(CInterp L) set_option pp.universes true set_option unifier.max_steps 1000000 definition AInterp_append {I: Interp} (Δ1 Δ2: list LabelConc) : @AInterp I ((Δ1)++Δ2) = (AInterp Δ1)∩(AInterp Δ2) := begin apply (list.induction_on Δ1), apply eq.trans, rewrite (eq.refl (nil++Δ2)), apply (eq.refl (AInterp Δ2)), rewrite (Inters_commu (AInterp nil) (AInterp Δ2)), apply (eq.symm IntersUniv), intro a, intro Δ, intro IndHyp, rewrite (append_cons a Δ Δ2), rewrite {AInterp (a::Δ)}(eq.refl ((interp (σ a))∩(AInterp Δ))), rewrite -(!Inters_assoc), rewrite -IndHyp, end definition CInterp_append {I: Interp} (Δ1 Δ2: list LabelConc) : @CInterp I ((Δ1)++Δ2) = (CInterp Δ1)∪(CInterp Δ2) := begin apply (list.induction_on Δ1), apply eq.trans, rewrite (eq.refl (nil++Δ2)), apply (eq.refl (CInterp Δ2)), rewrite (Union_commu (CInterp nil) (CInterp Δ2)), rewrite {CInterp nil}(eq.refl ∅), rewrite -(eq.symm UnionEmpty), intro a, intro Δ, intro IndHyp, rewrite (append_cons a Δ Δ2), rewrite {CInterp (a::Δ)}(eq.refl ((interp (σ a))∪(CInterp Δ))), rewrite -(!Union_assoc), rewrite -IndHyp, end inductive sequent (Δ : list LabelConc) (Γ: list LabelConc) : Prop := infix `⇒`:51 := sequent | intro : (∀I: Interp, (@AInterp I Δ) ⊂ CInterp Γ) → Δ⇒Γ infix `⇒`:51 := sequent -- Duas definições apenas para conseguir usar a notação {a,b} para as listas de LabelConc e somente para elas definition label_conc_append (a: list LabelConc) (b: list LabelConc): list LabelConc := append a b local notation `{` a `,` b`}` := label_conc_append a b definition label_conc_cons (a: list LabelConc) (b: LabelConc): list LabelConc := b::a local notation `{` b `,` a`}` := label_conc_cons a b -- notation overload definition label.to_labellist [coercion] (l: Label) : list Label := l::nil definition Concept.to_LabelConc [coercion] (C: Concept) : LabelConc := nil[C] definition LabelConc.to_ListLabelConc [coercion] (a: LabelConc) : list LabelConc := a::nil namespace test constants X R : Role constant C: Concept constant L: Label constant M: list Label check ∃;R check (L::L)[C] check ((∀;R) ++ (∀;R))[C] check ∀; R . C check { M[C] , M[C] } eval { ((∀;R)::L)[C] , C} check M[C] check L[C] check (∀;R : list Label)[C] end test namnespace test2 constant a: list LabelConc constant b: list LabelConc constant c: LabelConc constant d: Label constant e: Concept constant d2: Label check a++b check {a,b} check {c,a} check {(d::nil)[e],a} check {d[e],a} check {(d2::d2::d)[e],a} -- Seria interessante conseguir utilizar a notação {a, b, b}... end test2 namespace sequent definition meaning {Δ : list LabelConc} {Γ: list LabelConc} (h: Δ⇒Γ) : ∀I: Interp, (@AInterp I Δ) ⊂ CInterp Γ := -- elimination rule for sequents sequent.rec_on h (assume h2: ∀I: Interp, (@AInterp I Δ) ⊂ CInterp Γ, take I: Interp, h2 I) end sequent open Label inductive SCALCproof (Ω: @Set Prop) : Prop → Prop := infix `⊢` : 25 := SCALCproof -- \vdash | hypo : Π{α: Concept}, Ω⊢(nil[α]::nil)⇒(nil[α]::nil) -- fazer uma coercion concept -> labeled concept | ex_falsum : Π(α: Concept), Ω⊢(nil[⊥]::nil) ⇒ (nil[α]::nil) | weak_l : Π(Δ Γ: list LabelConc) (δ: LabelConc), Ω⊢(Δ⇒Γ) → Ω⊢(δ::Δ)⇒Γ | weak_r : Π(Δ Γ: list LabelConc) (γ: LabelConc), Ω⊢Δ⇒Γ → Ω⊢Δ⇒(γ::Γ) | contraction_l : Π(Δ Γ: list LabelConc) (δ: LabelConc), Ω⊢(δ::δ::Δ)⇒Γ → Ω⊢(δ::Δ)⇒Γ | contraction_r : Π(Δ Γ: list LabelConc) (γ: LabelConc), Ω⊢Δ⇒(γ::γ::Γ) → Ω⊢Δ⇒(γ::Γ) | perm_l : Π(Δ1 Δ2 Γ: list LabelConc) (δ1 δ2: LabelConc), Ω⊢Δ1++(δ1::δ2::Δ2)⇒Γ → Ω⊢(Δ1++(δ2::δ1::Δ2))⇒Γ | perm_r : Π(Δ Γ1 Γ2: list LabelConc) (γ1 γ2: LabelConc), Ω⊢Δ⇒Γ1++(γ1::γ2::Γ2) → Ω⊢Δ⇒Γ1++(γ2::γ1::Γ2) | cut : Π(Δ1 Δ2 Γ1 Γ2: list LabelConc) (α: LabelConc), Ω⊢Δ1⇒α::Γ1 → Ω⊢α::Δ2⇒Γ2 → Ω⊢Δ1++Δ2⇒Γ1++Γ2 | and_l : Π(Δ Γ : list LabelConc) (L: list Label) (α β : Concept) (p: is_true (isOnlyAllLabel L)), Ω⊢(L[α]::L[β]::Δ)⇒Γ → Ω⊢(L[α⊓β]::Δ)⇒Γ | all_r : Π(Δ Γ: list LabelConc) (L: list Label) (α: Concept) (R: Role), Ω⊢ Δ⇒{ (L++(∀;R))[α], Γ} → Ω⊢ Δ⇒{ (L[∀;R .α]), Γ} infix `⊢` : 25 := SCALCproof definition cut_soundness (Ω: @Set Prop) (Δ1 Δ2 Γ1 Γ2: list LabelConc) (α: LabelConc) : (Ω⊧ Δ1⇒α::Γ1) → (Ω⊧ α::Δ2⇒Γ2) → (Ω⊧ Δ1++Δ2⇒Γ1++Γ2) := assume h: Ω⊧Δ1⇒α::Γ1, assume h2: Ω⊧α::Δ2⇒Γ2, assume h3: ∀p: Prop, (p∈ Ω → p), have l1: Δ1⇒α::Γ1, from h h3, have l2: α::Δ2⇒Γ2, from h2 h3, have l3: ∀I: Interp, AInterp Δ1 ⊂ CInterp (α::Γ1), from sequent.meaning l1, have l4: ∀I: Interp, AInterp (α::Δ2) ⊂ CInterp Γ2, from sequent.meaning l2, assert l5: (∀I: Interp, AInterp Δ1 ⊂ (interp (σ α)∪(CInterp Γ1))), from take I: Interp, eq.subst rfl (l3 I), assert l6: (∀I: Interp, (@interp I (σ α)) ∩ (AInterp Δ2) ⊂ (CInterp Γ2)), from take I: Interp, eq.subst rfl (l4 I), show Δ1++Δ2⇒(Γ1++Γ2), from begin apply sequent.intro, intro I, rewrite [(AInterp_append Δ1 Δ2), (CInterp_append Γ1 Γ2)], exact (SetCut (l5 I) (l6 I)), end definition drop_last_all_label {L: list Label} {α: Concept} {R: Role} : σ ((L++(∀;R))[α]) = σ(L[∀;R . α]) := sorry definition all_r_soundness (Ω: @Set Prop) (Δ Γ: list LabelConc) (L: list Label) (α: Concept) (R: Role): (Ω⊧ (Δ⇒{ (L++(∀;R))[α], Γ})) → (Ω⊧ Δ⇒{ L[∀;R .α], Γ}) := assume h: Ω⊧( Δ⇒{ (L++(∀;R))[α], Γ}), assume h2: ∀p: Prop, (p∈Ω → p), have l1: Δ⇒{ (L++(∀;R))[α], Γ}, from h h2, assert l2: ∀I: Interp, AInterp Δ ⊂ CInterp { (L++(∀;R))[α], Γ}, from sequent.meaning l1, assert l3: (σ ((L++(∀;R))[α])) = (σ (L[∀;R . α])), from drop_last_all_label, have l4: (CInterp {(L++(∀;R))[α], Γ}) = (CInterp {L[∀;R. α], Γ}), from begin esimp, rewrite l3, end, --have l3: (CInterp {(L++(∀;R))[α], Γ}) = (CInterp {L[∀;R. α], Γ}), from sorry, show Δ ⇒ {(L[∀;R .α]), Γ}, from begin apply sequent.intro, intro I, end section hide constants (Δ Γ: list LabelConc) (L: list Label) (α: Concept) (R: Role) check (eq.refl (CInterp { (L++(∀;R))[α], Γ})) end hide axiom Axiom2_1 (R: Role) (α β: Concept) : ValueRestr R α⊓β ≡ (ValueRestr R α) ⊓ (ValueRestr R β) /- definition and_l_soundness (Ω: @Set Prop) (Δ Γ: list LabelConc) (L: list Label) (α β: Concept) (p: is_true (isOnlyAllLabel L)) : (Ω⊧ (L[α]::L[β]::Δ)⇒Γ) → (Ω⊧ (L[α⊓β]::Δ)⇒Γ) := assume h: Ω⊧ (L[α]::L[β]::Δ)⇒Γ, assume h2: ∀q: Prop, (q∈ Ω → q), assert l1: (L[α]::L[β]::Δ)⇒Γ, from h h2, begin apply sequent.meaning, end -/ end ALC
06d6e4181e23aeff7f407852ab88dd567fcd789c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/itauto.lean
f0a2609e65d960221016165859be9d5e70523f1b
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
3,411
lean
/- Copyright (c) 2021 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import tactic.itauto section itauto₀ variables p q r : Prop variables h : p ∧ q ∨ p ∧ r include h example : p ∧ p := by itauto end itauto₀ section itauto₃ example (p : Prop) : ¬ (p ↔ ¬ p) := by itauto example (p : Prop) : ¬ (p = ¬ p) := by itauto example (p : Prop) : p ≠ ¬ p := by itauto example (p : Prop) : p ∧ true ↔ p := by itauto example (p : Prop) : p ∨ false ↔ p := by itauto example (p q : Prop) (h0 : q) : p → q := by itauto example (p q r : Prop) : p ∨ (q ∧ r) → (p ∨ q) ∧ (r ∨ p ∨ r) := by itauto example (p q r : Prop) : p ∨ (q ∧ r) → (p ∨ q) ∧ (r ∨ p ∨ r) := by itauto example (p q r : Prop) (h : p) : (p → q ∨ r) → q ∨ r := by itauto example (p q : Prop) (h : ¬ (p ↔ q)) (h' : p) : ¬ q := by itauto example (p q : Prop) (h : ¬ (p ↔ q)) (h' : q) : ¬ p := by itauto example (p q : Prop) (h : ¬ (p ↔ q)) (h' : ¬ q) (h'' : ¬ p) : false := by itauto example (p q r : Prop) (h : p ↔ q) (h' : r ↔ q) (h'' : ¬ r) : ¬ p := by itauto example (p q r : Prop) (h : p ↔ q) (h' : r ↔ q) : p ↔ r := by itauto example (p q : Prop) : xor p q → (p ↔ ¬ q) := by itauto example (p q : Prop) : xor p q → xor q p := by itauto example (p q r : Prop) (h : ¬ (p ↔ q)) (h' : r ↔ q) : ¬ (p ↔ r) := by itauto example (p : Prop) : p → ¬ (p → ¬ p) := by itauto example (p : Prop) (em : p ∨ ¬ p) : ¬ (p ↔ ¬ p) := by itauto example (p : Prop) [decidable p] : p ∨ ¬ p := by itauto* example (p : Prop) [decidable p] : ¬ (p ↔ ¬ p) := by itauto example (p q r : Prop) [decidable p] : (p → (q ∨ r)) → ((p → q) ∨ (p → r)) := by itauto* example (p q r : Prop) [decidable q] : (p → (q ∨ r)) → ((p → q) ∨ (p → r)) := by itauto [q] example (xl yl zl xr yr zr : Prop) : (xl ∧ yl ∨ xr ∧ yr) ∧ zl ∨ (xl ∧ yr ∨ xr ∧ yl) ∧ zr ↔ xl ∧ (yl ∧ zl ∨ yr ∧ zr) ∨ xr ∧ (yl ∧ zr ∨ yr ∧ zl) := by itauto example : 0 < 1 ∨ ¬ 0 < 1 := by itauto* example (p : Prop) (h : 0 < 1 → p) (h2 : ¬ 0 < 1 → p) : p := by itauto* example (b : bool) : ¬ b ∨ b := by itauto* example (p : Prop) : ¬ p ∨ p := by itauto! [p] example (p : Prop) : ¬ p ∨ p := by itauto!* -- failure tests example (p q r : Prop) : true := begin have : p ∨ ¬ p, {success_if_fail {itauto}, sorry}, clear this, have : ¬ (p ↔ q) → ¬ p → q, {success_if_fail {itauto}, sorry}, clear this, have : ¬ (p ↔ q) → (r ↔ q) → (p ↔ ¬ r), {success_if_fail {itauto}, sorry}, clear this, trivial end example (P : ℕ → Prop) (n : ℕ) (h : ¬ (n = 7 ∨ n = 0) ∧ P n) : ¬ (P n → n = 7 ∨ n = 0) := by itauto section modulo_symmetry variables {p q r : Prop} {α : Type} {x y : α} variables (h : x = y) variables (h'' : (p ∧ q ↔ q ∨ r) ↔ (r ∧ p ↔ r ∨ q)) include h include h'' example (h' : ¬ x = y) : p ∧ q := by itauto example : x = y := by itauto end modulo_symmetry end itauto₃ example (p1 p2 p3 p4 p5 p6 f : Prop) (h : ( (p1 ∧ p2 ∧ p3 ∧ p4 ∧ p5 ∧ p6 ∧ true) ∨ (((p1 → f) → f) → f) ∨ (p2 → f) ∨ (p3 → f) ∨ (p4 → f) ∨ (p5 → f) ∨ (p6 → f) ∨ false ) → f) : f := by itauto
cb0ba33372cd36739724ac7a4ca450d3e4524e20
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/algebra/ring/basic.lean
19f987fd1d55c714d39198f9cb96c4823cca4ace
[ "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
35,193
lean
/- Copyright (c) 2014 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Amelia Livingston, Yury Kudryashov, Neil Strickland -/ import algebra.divisibility import data.set.basic /-! # Properties and homomorphisms of semirings and rings This file proves simple properties of semirings, rings and domains and their unit groups. It also defines bundled homomorphisms of semirings and rings. As with monoid and groups, we use the same structure `ring_hom a β`, a.k.a. `α →+* β`, for both homomorphism types. The unbundled homomorphisms are defined in `deprecated/ring`. They are deprecated and the plan is to slowly remove them from mathlib. ## Main definitions ring_hom, nonzero, domain, integral_domain ## Notations →+* for bundled ring homs (also use for semiring homs) ## Implementation notes There's a coercion from bundled homs to fun, and the canonical notation is to use the bundled hom as a function via this coercion. There is no `semiring_hom` -- the idea is that `ring_hom` is used. The constructor for a `ring_hom` between semirings needs a proof of `map_zero`, `map_one` and `map_add` as well as `map_mul`; a separate constructor `ring_hom.mk'` will construct ring homs between rings from monoid homs given only a proof that addition is preserved. Throughout the section on `ring_hom` implicit `{}` brackets are often used instead of type class `[]` brackets. This is done when the instances can be inferred because they are implicit arguments to the type `ring_hom`. When they can be inferred from the type it is faster to use this method than to use type class inference. ## Tags `ring_hom`, `semiring_hom`, `semiring`, `comm_semiring`, `ring`, `comm_ring`, `domain`, `integral_domain`, `nonzero`, `units` -/ universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {R : Type x} set_option default_priority 100 -- see Note [default priority] set_option old_structure_cmd true open function /-! ### `distrib` class -/ /-- A typeclass stating that multiplication is left and right distributive over addition. -/ @[protect_proj, ancestor has_mul has_add] class distrib (R : Type*) extends has_mul R, has_add R := (left_distrib : ∀ a b c : R, a * (b + c) = (a * b) + (a * c)) (right_distrib : ∀ a b c : R, (a + b) * c = (a * c) + (b * c)) lemma left_distrib [distrib R] (a b c : R) : a * (b + c) = a * b + a * c := distrib.left_distrib a b c alias left_distrib ← mul_add lemma right_distrib [distrib R] (a b c : R) : (a + b) * c = a * c + b * c := distrib.right_distrib a b c alias right_distrib ← add_mul /-- Pullback a `distrib` instance along an injective function. -/ protected def function.injective.distrib {S} [has_mul R] [has_add R] [distrib S] (f : R → S) (hf : injective f) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : distrib R := { mul := (*), add := (+), left_distrib := λ x y z, hf $ by simp only [*, left_distrib], right_distrib := λ x y z, hf $ by simp only [*, right_distrib] } /-- Pushforward a `distrib` instance along a surjective function. -/ protected def function.surjective.distrib {S} [distrib R] [has_add S] [has_mul S] (f : R → S) (hf : surjective f) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : distrib S := { mul := (*), add := (+), left_distrib := hf.forall₃.2 $ λ x y z, by simp only [← add, ← mul, left_distrib], right_distrib := hf.forall₃.2 $ λ x y z, by simp only [← add, ← mul, right_distrib] } /-! ### Semirings -/ @[protect_proj, ancestor add_comm_monoid monoid_with_zero distrib] class semiring (α : Type u) extends add_comm_monoid α, monoid_with_zero α, distrib α section semiring variables [semiring α] /-- Pullback a `semiring` instance along an injective function. -/ protected def function.injective.semiring [has_zero β] [has_one β] [has_add β] [has_mul β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : semiring β := { .. hf.monoid_with_zero f zero one mul, .. hf.add_comm_monoid f zero add, .. hf.distrib f add mul } /-- Pullback a `semiring` instance along an injective function. -/ protected def function.surjective.semiring [has_zero β] [has_one β] [has_add β] [has_mul β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : semiring β := { .. hf.monoid_with_zero f zero one mul, .. hf.add_comm_monoid f zero add, .. hf.distrib f add mul } lemma one_add_one_eq_two : 1 + 1 = (2 : α) := by unfold bit0 theorem two_mul (n : α) : 2 * n = n + n := eq.trans (right_distrib 1 1 n) (by simp) lemma distrib_three_right (a b c d : α) : (a + b + c) * d = a * d + b * d + c * d := by simp [right_distrib] theorem mul_two (n : α) : n * 2 = n + n := (left_distrib n 1 1).trans (by simp) theorem bit0_eq_two_mul (n : α) : bit0 n = 2 * n := (two_mul _).symm @[to_additive] lemma mul_ite {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) : a * (if P then b else c) = if P then a * b else a * c := by split_ifs; refl @[to_additive] lemma ite_mul {α} [has_mul α] (P : Prop) [decidable P] (a b c : α) : (if P then a else b) * c = if P then a * c else b * c := by split_ifs; refl -- We make `mul_ite` and `ite_mul` simp lemmas, -- but not `add_ite` or `ite_add`. -- The problem we're trying to avoid is dealing with -- summations of the form `∑ x in s, (f x + ite P 1 0)`, -- in which `add_ite` followed by `sum_ite` would needlessly slice up -- the `f x` terms according to whether `P` holds at `x`. -- There doesn't appear to be a corresponding difficulty so far with -- `mul_ite` and `ite_mul`. attribute [simp] mul_ite ite_mul @[simp] lemma mul_boole {α} [semiring α] (P : Prop) [decidable P] (a : α) : a * (if P then 1 else 0) = if P then a else 0 := by simp @[simp] lemma boole_mul {α} [semiring α] (P : Prop) [decidable P] (a : α) : (if P then 1 else 0) * a = if P then a else 0 := by simp lemma ite_mul_zero_left {α : Type*} [mul_zero_class α] (P : Prop) [decidable P] (a b : α) : ite P (a * b) 0 = ite P a 0 * b := by { by_cases h : P; simp [h], } lemma ite_mul_zero_right {α : Type*} [mul_zero_class α] (P : Prop) [decidable P] (a b : α) : ite P (a * b) 0 = a * ite P b 0 := by { by_cases h : P; simp [h], } end semiring namespace add_monoid_hom /-- Left multiplication by an element of a (semi)ring is an `add_monoid_hom` -/ def mul_left {R : Type*} [semiring R] (r : R) : R →+ R := { to_fun := (*) r, map_zero' := mul_zero r, map_add' := mul_add r } @[simp] lemma coe_mul_left {R : Type*} [semiring R] (r : R) : ⇑(mul_left r) = (*) r := rfl /-- Right multiplication by an element of a (semi)ring is an `add_monoid_hom` -/ def mul_right {R : Type*} [semiring R] (r : R) : R →+ R := { to_fun := λ a, a * r, map_zero' := zero_mul r, map_add' := λ _ _, add_mul _ _ r } @[simp] lemma mul_right_apply {R : Type*} [semiring R] (a r : R) : (mul_right r : R → R) a = a * r := rfl end add_monoid_hom /-- Bundled semiring homomorphisms; use this for bundled ring homomorphisms too. -/ structure ring_hom (α : Type*) (β : Type*) [semiring α] [semiring β] extends monoid_hom α β, add_monoid_hom α β infixr ` →+* `:25 := ring_hom @[priority 1000] instance {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} : has_coe_to_fun (α →+* β) := ⟨_, ring_hom.to_fun⟩ @[priority 1000] instance {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} : has_coe (α →+* β) (α →* β) := ⟨ring_hom.to_monoid_hom⟩ @[priority 1000] instance {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} : has_coe (α →+* β) (α →+ β) := ⟨ring_hom.to_add_monoid_hom⟩ @[simp, norm_cast] lemma coe_monoid_hom {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} (f : α →+* β) : ⇑(f : α →* β) = f := rfl @[simp, norm_cast] lemma coe_add_monoid_hom {α : Type*} {β : Type*} {rα : semiring α} {rβ : semiring β} (f : α →+* β) : ⇑(f : α →+ β) = f := rfl namespace ring_hom variables [rα : semiring α] [rβ : semiring β] section include rα rβ @[simp] lemma to_fun_eq_coe (f : α →+* β) : f.to_fun = f := rfl @[simp] lemma coe_mk (f : α → β) (h₁ h₂ h₃ h₄) : ⇑(⟨f, h₁, h₂, h₃, h₄⟩ : α →+* β) = f := rfl variables (f : α →+* β) {x y : α} {rα rβ} theorem coe_inj ⦃f g : α →+* β⦄ (h : (f : α → β) = g) : f = g := by cases f; cases g; cases h; refl @[ext] theorem ext ⦃f g : α →+* β⦄ (h : ∀ x, f x = g x) : f = g := coe_inj (funext h) theorem ext_iff {f g : α →+* β} : f = g ↔ ∀ x, f x = g x := ⟨λ h x, h ▸ rfl, λ h, ext h⟩ theorem coe_add_monoid_hom_injective : function.injective (coe : (α →+* β) → (α →+ β)) := λ f g h, coe_inj $ show ((f : α →+ β) : α → β) = (g : α →+ β), from congr_arg coe_fn h theorem coe_monoid_hom_injective : function.injective (coe : (α →+* β) → (α →* β)) := λ f g h, coe_inj $ show ((f : α →* β) : α → β) = (g : α →* β), from congr_arg coe_fn h /-- Ring homomorphisms map zero to zero. -/ @[simp] lemma map_zero (f : α →+* β) : f 0 = 0 := f.map_zero' /-- Ring homomorphisms map one to one. -/ @[simp] lemma map_one (f : α →+* β) : f 1 = 1 := f.map_one' /-- Ring homomorphisms preserve addition. -/ @[simp] lemma map_add (f : α →+* β) (a b : α) : f (a + b) = f a + f b := f.map_add' a b /-- Ring homomorphisms preserve multiplication. -/ @[simp] lemma map_mul (f : α →+* β) (a b : α) : f (a * b) = f a * f b := f.map_mul' a b /-- `f : R →+* S` has a trivial codomain iff `f 1 = 0`. -/ lemma codomain_trivial_iff_map_one_eq_zero : (0 : β) = 1 ↔ f 1 = 0 := by rw [map_one, eq_comm] /-- `f : R →+* S` has a trivial codomain iff it has a trivial range. -/ lemma codomain_trivial_iff_range_trivial : (0 : β) = 1 ↔ (∀ x, f x = 0) := f.codomain_trivial_iff_map_one_eq_zero.trans ⟨λ h x, by rw [←mul_one x, map_mul, h, mul_zero], λ h, h 1⟩ /-- `f : R →+* S` has a trivial codomain iff its range is `{0}`. -/ lemma codomain_trivial_iff_range_eq_singleton_zero : (0 : β) = 1 ↔ set.range f = {0} := f.codomain_trivial_iff_range_trivial.trans ⟨ λ h, set.ext (λ y, ⟨λ ⟨x, hx⟩, by simp [←hx, h x], λ hy, ⟨0, by simpa using hy.symm⟩⟩), λ h x, set.mem_singleton_iff.mp (h ▸ set.mem_range_self x)⟩ /-- `f : R →+* S` doesn't map `1` to `0` if `S` is nontrivial -/ lemma map_one_ne_zero [nontrivial β] : f 1 ≠ 0 := mt f.codomain_trivial_iff_map_one_eq_zero.mpr zero_ne_one /-- If there is a homomorphism `f : R →+* S` and `S` is nontrivial, then `R` is nontrivial. -/ lemma domain_nontrivial [nontrivial β] : nontrivial α := ⟨⟨1, 0, mt (λ h, show f 1 = 0, by rw [h, map_zero]) f.map_one_ne_zero⟩⟩ lemma is_unit_map (f : α →+* β) {a : α} (h : is_unit a) : is_unit (f a) := h.map (f.to_monoid_hom) end /-- The identity ring homomorphism from a semiring to itself. -/ def id (α : Type*) [semiring α] : α →+* α := by refine {to_fun := id, ..}; intros; refl include rα @[simp] lemma id_apply (x : α) : ring_hom.id α x = x := rfl variable {rγ : semiring γ} include rβ rγ /-- Composition of ring homomorphisms is a ring homomorphism. -/ def comp (hnp : β →+* γ) (hmn : α →+* β) : α →+* γ := { to_fun := hnp ∘ hmn, map_zero' := by simp, map_one' := by simp, map_add' := λ x y, by simp, map_mul' := λ x y, by simp} /-- Composition of semiring homomorphisms is associative. -/ lemma comp_assoc {δ} {rδ: semiring δ} (f : α →+* β) (g : β →+* γ) (h : γ →+* δ) : (h.comp g).comp f = h.comp (g.comp f) := rfl @[simp] lemma coe_comp (hnp : β →+* γ) (hmn : α →+* β) : (hnp.comp hmn : α → γ) = hnp ∘ hmn := rfl lemma comp_apply (hnp : β →+* γ) (hmn : α →+* β) (x : α) : (hnp.comp hmn : α → γ) x = (hnp (hmn x)) := rfl omit rγ @[simp] lemma comp_id (f : α →+* β) : f.comp (id α) = f := ext $ λ x, rfl @[simp] lemma id_comp (f : α →+* β) : (id β).comp f = f := ext $ λ x, rfl omit rβ instance : monoid (α →+* α) := { one := id α, mul := comp, mul_one := comp_id, one_mul := id_comp, mul_assoc := λ f g h, comp_assoc _ _ _ } lemma one_def : (1 : α →+* α) = id α := rfl @[simp] lemma coe_one : ⇑(1 : α →+* α) = _root_.id := rfl lemma mul_def (f g : α →+* α) : f * g = f.comp g := rfl @[simp] lemma coe_mul (f g : α →+* α) : ⇑(f * g) = f ∘ g := rfl include rβ rγ lemma cancel_right {g₁ g₂ : β →+* γ} {f : α →+* β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ring_hom.ext $ (forall_iff_forall_surj hf).1 (ext_iff.1 h), λ h, h ▸ rfl⟩ lemma cancel_left {g : β →+* γ} {f₁ f₂ : α →+* β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ring_hom.ext $ λ x, hg $ by rw [← comp_apply, h, comp_apply], λ h, h ▸ rfl⟩ omit rα rβ rγ end ring_hom @[protect_proj, ancestor semiring comm_monoid] class comm_semiring (α : Type u) extends semiring α, comm_monoid α instance comm_semiring.to_comm_monoid_with_zero [comm_semiring α] : comm_monoid_with_zero α := { .. comm_semiring.to_comm_monoid α, .. comm_semiring.to_semiring α } section comm_semiring variables [comm_semiring α] [comm_semiring β] {a b c : α} instance comm_semiring.comm_monoid_with_zero : comm_monoid_with_zero α := { .. (‹_› : comm_semiring α) } /-- Pullback a `semiring` instance along an injective function. -/ protected def function.injective.comm_semiring [has_zero γ] [has_one γ] [has_add γ] [has_mul γ] (f : γ → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : comm_semiring γ := { .. hf.semiring f zero one add mul, .. hf.comm_semigroup f mul } /-- Pullback a `semiring` instance along an injective function. -/ protected def function.surjective.comm_semiring [has_zero γ] [has_one γ] [has_add γ] [has_mul γ] (f : α → γ) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) : comm_semiring γ := { .. hf.semiring f zero one add mul, .. hf.comm_semigroup f mul } lemma add_mul_self_eq (a b : α) : (a + b) * (a + b) = a*a + 2*a*b + b*b := calc (a + b)*(a + b) = a*a + (1+1)*a*b + b*b : by simp [add_mul, mul_add, mul_comm, add_assoc] ... = a*a + 2*a*b + b*b : by rw one_add_one_eq_two theorem dvd_add (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b + c := dvd.elim h₁ (λ d hd, dvd.elim h₂ (λ e he, dvd.intro (d + e) (by simp [left_distrib, hd, he]))) @[simp] theorem two_dvd_bit0 : 2 ∣ bit0 a := ⟨a, bit0_eq_two_mul _⟩ lemma ring_hom.map_dvd (f : α →+* β) {a b : α} : a ∣ b → f a ∣ f b := λ ⟨z, hz⟩, ⟨f z, by rw [hz, f.map_mul]⟩ end comm_semiring /-! ### Rings -/ @[protect_proj, ancestor add_comm_group monoid distrib] class ring (α : Type u) extends add_comm_group α, monoid α, distrib α section ring variables [ring α] {a b c d e : α} instance ring.to_semiring : semiring α := { zero_mul := λ a, add_left_cancel $ show 0 * a + 0 * a = 0 * a + 0, by rw [← add_mul, zero_add, add_zero], mul_zero := λ a, add_left_cancel $ show a * 0 + a * 0 = a * 0 + 0, by rw [← mul_add, add_zero, add_zero], ..‹ring α› } /- The instance from `ring` to `semiring` happens often in linear algebra, for which all the basic definitions are given in terms of semirings, but many applications use rings or fields. We increase a little bit its priority above 100 to try it quickly, but remaining below the default 1000 so that more specific instances are tried first. -/ attribute [instance, priority 200] ring.to_semiring /-- Pullback a `ring` instance along an injective function. -/ protected def function.injective.ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : ring β := { .. hf.add_comm_group f zero add neg, .. hf.monoid f one mul, .. hf.distrib f add mul } /-- Pullback a `ring` instance along an injective function. -/ protected def function.surjective.ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : ring β := { .. hf.add_comm_group f zero add neg, .. hf.monoid f one mul, .. hf.distrib f add mul } lemma neg_mul_eq_neg_mul (a b : α) : -(a * b) = -a * b := neg_eq_of_add_eq_zero begin rw [← right_distrib, add_right_neg, zero_mul] end lemma neg_mul_eq_mul_neg (a b : α) : -(a * b) = a * -b := neg_eq_of_add_eq_zero begin rw [← left_distrib, add_right_neg, mul_zero] end @[simp] lemma neg_mul_eq_neg_mul_symm (a b : α) : - a * b = - (a * b) := eq.symm (neg_mul_eq_neg_mul a b) @[simp] lemma mul_neg_eq_neg_mul_symm (a b : α) : a * - b = - (a * b) := eq.symm (neg_mul_eq_mul_neg a b) lemma neg_mul_neg (a b : α) : -a * -b = a * b := by simp lemma neg_mul_comm (a b : α) : -a * b = a * -b := by simp theorem neg_eq_neg_one_mul (a : α) : -a = -1 * a := by simp lemma mul_sub_left_distrib (a b c : α) : a * (b - c) = a * b - a * c := calc a * (b - c) = a * b + a * -c : left_distrib a b (-c) ... = a * b - a * c : by simp [sub_eq_add_neg] alias mul_sub_left_distrib ← mul_sub lemma mul_sub_right_distrib (a b c : α) : (a - b) * c = a * c - b * c := calc (a - b) * c = a * c + -b * c : right_distrib a (-b) c ... = a * c - b * c : by simp [sub_eq_add_neg] alias mul_sub_right_distrib ← sub_mul /-- An element of a ring multiplied by the additive inverse of one is the element's additive inverse. -/ lemma mul_neg_one (a : α) : a * -1 = -a := by simp /-- The additive inverse of one multiplied by an element of a ring is the element's additive inverse. -/ lemma neg_one_mul (a : α) : -1 * a = -a := by simp /-- An iff statement following from right distributivity in rings and the definition of subtraction. -/ theorem mul_add_eq_mul_add_iff_sub_mul_add_eq : a * e + c = b * e + d ↔ (a - b) * e + c = d := calc a * e + c = b * e + d ↔ a * e + c = d + b * e : by simp [add_comm] ... ↔ a * e + c - b * e = d : iff.intro (λ h, begin rw h, simp end) (λ h, begin rw ← h, simp end) ... ↔ (a - b) * e + c = d : begin simp [sub_mul, sub_add_eq_add_sub] end /-- A simplification of one side of an equation exploiting right distributivity in rings and the definition of subtraction. -/ theorem sub_mul_add_eq_of_mul_add_eq_mul_add : a * e + c = b * e + d → (a - b) * e + c = d := assume h, calc (a - b) * e + c = (a * e + c) - b * e : begin simp [sub_mul, sub_add_eq_add_sub] end ... = d : begin rw h, simp [@add_sub_cancel α] end end ring namespace units variables [ring α] {a b : α} /-- Each element of the group of units of a ring has an additive inverse. -/ instance : has_neg (units α) := ⟨λu, ⟨-↑u, -↑u⁻¹, by simp, by simp⟩ ⟩ /-- Representing an element of a ring's unit group as an element of the ring commutes with mapping this element to its additive inverse. -/ @[simp, norm_cast] protected theorem coe_neg (u : units α) : (↑-u : α) = -u := rfl @[simp, norm_cast] protected theorem coe_neg_one : ((-1 : units α) : α) = -1 := rfl /-- Mapping an element of a ring's unit group to its inverse commutes with mapping this element to its additive inverse. -/ @[simp] protected theorem neg_inv (u : units α) : (-u)⁻¹ = -u⁻¹ := rfl /-- An element of a ring's unit group equals the additive inverse of its additive inverse. -/ @[simp] protected theorem neg_neg (u : units α) : - -u = u := units.ext $ neg_neg _ /-- Multiplication of elements of a ring's unit group commutes with mapping the first argument to its additive inverse. -/ @[simp] protected theorem neg_mul (u₁ u₂ : units α) : -u₁ * u₂ = -(u₁ * u₂) := units.ext $ neg_mul_eq_neg_mul_symm _ _ /-- Multiplication of elements of a ring's unit group commutes with mapping the second argument to its additive inverse. -/ @[simp] protected theorem mul_neg (u₁ u₂ : units α) : u₁ * -u₂ = -(u₁ * u₂) := units.ext $ (neg_mul_eq_mul_neg _ _).symm /-- Multiplication of the additive inverses of two elements of a ring's unit group equals multiplication of the two original elements. -/ @[simp] protected theorem neg_mul_neg (u₁ u₂ : units α) : -u₁ * -u₂ = u₁ * u₂ := by simp /-- The additive inverse of an element of a ring's unit group equals the additive inverse of one times the original element. -/ protected theorem neg_eq_neg_one_mul (u : units α) : -u = -1 * u := by simp end units namespace ring_hom /-- Ring homomorphisms preserve additive inverse. -/ @[simp] theorem map_neg {α β} [ring α] [ring β] (f : α →+* β) (x : α) : f (-x) = -(f x) := (f : α →+ β).map_neg x /-- Ring homomorphisms preserve subtraction. -/ @[simp] theorem map_sub {α β} [ring α] [ring β] (f : α →+* β) (x y : α) : f (x - y) = (f x) - (f y) := (f : α →+ β).map_sub x y /-- A ring homomorphism is injective iff its kernel is trivial. -/ theorem injective_iff {α β} [ring α] [semiring β] (f : α →+* β) : function.injective f ↔ (∀ a, f a = 0 → a = 0) := (f : α →+ β).injective_iff /-- Makes a ring homomorphism from a monoid homomorphism of rings which preserves addition. -/ def mk' {γ} [semiring α] [ring γ] (f : α →* γ) (map_add : ∀ a b : α, f (a + b) = f a + f b) : α →+* γ := { to_fun := f, .. add_monoid_hom.mk' f map_add, .. f } end ring_hom @[protect_proj, ancestor ring comm_semigroup] class comm_ring (α : Type u) extends ring α, comm_semigroup α instance comm_ring.to_comm_semiring [s : comm_ring α] : comm_semiring α := { mul_zero := mul_zero, zero_mul := zero_mul, ..s } section comm_ring variables [comm_ring α] {a b c : α} /-- Pullback a `ring` instance along an injective function. -/ protected def function.injective.comm_ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : comm_ring β := { .. hf.ring f zero one add mul neg, .. hf.comm_semigroup f mul } /-- Pullback a `ring` instance along an injective function. -/ protected def function.surjective.comm_ring [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : α → β) (hf : surjective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : comm_ring β := { .. hf.ring f zero one add mul neg, .. hf.comm_semigroup f mul } local attribute [simp] add_assoc add_comm add_left_comm mul_comm lemma mul_self_sub_mul_self_eq (a b : α) : a * a - b * b = (a + b) * (a - b) := by simp [right_distrib, left_distrib, sub_eq_add_neg] lemma mul_self_sub_one_eq (a : α) : a * a - 1 = (a + 1) * (a - 1) := by rw [← mul_self_sub_mul_self_eq, mul_one] theorem dvd_neg_of_dvd (h : a ∣ b) : (a ∣ -b) := dvd.elim h (assume c, assume : b = a * c, dvd.intro (-c) (by simp [this])) theorem dvd_of_dvd_neg (h : a ∣ -b) : (a ∣ b) := let t := dvd_neg_of_dvd h in by rwa neg_neg at t theorem dvd_neg_iff_dvd (a b : α) : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ theorem neg_dvd_of_dvd (h : a ∣ b) : -a ∣ b := dvd.elim h (assume c, assume : b = a * c, dvd.intro (-c) (by simp [this])) theorem dvd_of_neg_dvd (h : -a ∣ b) : a ∣ b := let t := neg_dvd_of_dvd h in by rwa neg_neg at t theorem neg_dvd_iff_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ theorem dvd_sub (h₁ : a ∣ b) (h₂ : a ∣ c) : a ∣ b - c := dvd_add h₁ (dvd_neg_of_dvd h₂) theorem dvd_add_iff_left (h : a ∣ c) : a ∣ b ↔ a ∣ b + c := ⟨λh₂, dvd_add h₂ h, λH, by have t := dvd_sub H h; rwa add_sub_cancel at t⟩ theorem dvd_add_iff_right (h : a ∣ b) : a ∣ c ↔ a ∣ b + c := by rw add_comm; exact dvd_add_iff_left h theorem two_dvd_bit1 : 2 ∣ bit1 a ↔ (2 : α) ∣ 1 := (dvd_add_iff_right (@two_dvd_bit0 _ _ a)).symm /-- Representation of a difference of two squares in a commutative ring as a product. -/ theorem mul_self_sub_mul_self (a b : α) : a * a - b * b = (a + b) * (a - b) := by rw [add_mul, mul_sub, mul_sub, mul_comm a b, sub_add_sub_cancel] /-- An element a of a commutative ring divides the additive inverse of an element b iff a divides b. -/ @[simp] lemma dvd_neg (a b : α) : (a ∣ -b) ↔ (a ∣ b) := ⟨dvd_of_dvd_neg, dvd_neg_of_dvd⟩ /-- The additive inverse of an element a of a commutative ring divides another element b iff a divides b. -/ @[simp] lemma neg_dvd (a b : α) : (-a ∣ b) ↔ (a ∣ b) := ⟨dvd_of_neg_dvd, neg_dvd_of_dvd⟩ /-- If an element a divides another element c in a commutative ring, a divides the sum of another element b with c iff a divides b. -/ theorem dvd_add_left (h : a ∣ c) : a ∣ b + c ↔ a ∣ b := (dvd_add_iff_left h).symm /-- If an element a divides another element b in a commutative ring, a divides the sum of b and another element c iff a divides c. -/ theorem dvd_add_right (h : a ∣ b) : a ∣ b + c ↔ a ∣ c := (dvd_add_iff_right h).symm /-- An element a divides the sum a + b if and only if a divides b.-/ @[simp] lemma dvd_add_self_left {a b : α} : a ∣ a + b ↔ a ∣ b := dvd_add_right (dvd_refl a) /-- An element a divides the sum b + a if and only if a divides b.-/ @[simp] lemma dvd_add_self_right {a b : α} : a ∣ b + a ↔ a ∣ b := dvd_add_left (dvd_refl a) /-- Vieta's formula for a quadratic equation, relating the coefficients of the polynomial with its roots. This particular version states that if we have a root `x` of a monic quadratic polynomial, then there is another root `y` such that `x + y` is negative the `a_1` coefficient and `x * y` is the `a_0` coefficient. -/ lemma Vieta_formula_quadratic {b c x : α} (h : x * x - b * x + c = 0) : ∃ y : α, y * y - b * y + c = 0 ∧ x + y = b ∧ x * y = c := begin have : c = -(x * x - b * x) := (neg_eq_of_add_eq_zero h).symm, have : c = x * (b - x), by subst this; simp [mul_sub, mul_comm], refine ⟨b - x, _, by simp, by rw this⟩, rw [this, sub_add, ← sub_mul, sub_self] end lemma dvd_mul_sub_mul {k a b x y : α} (hab : k ∣ a - b) (hxy : k ∣ x - y) : k ∣ a * x - b * y := begin convert dvd_add (dvd_mul_of_dvd_right hxy a) (dvd_mul_of_dvd_left hab y), rw [mul_sub_left_distrib, mul_sub_right_distrib], simp only [sub_eq_add_neg, add_assoc, neg_add_cancel_left], end lemma dvd_iff_dvd_of_dvd_sub {a b c : α} (h : a ∣ (b - c)) : (a ∣ b ↔ a ∣ c) := begin split, { intro h', convert dvd_sub h' h, exact eq.symm (sub_sub_self b c) }, { intro h', convert dvd_add h h', exact eq_add_of_sub_eq rfl } end end comm_ring lemma succ_ne_self [ring α] [nontrivial α] (a : α) : a + 1 ≠ a := λ h, one_ne_zero ((add_right_inj a).mp (by simp [h])) lemma pred_ne_self [ring α] [nontrivial α] (a : α) : a - 1 ≠ a := λ h, one_ne_zero (neg_injective ((add_right_inj a).mp (by { convert h, simp }))) /-- A domain is a ring with no zero divisors, i.e. satisfying the condition `a * b = 0 ↔ a = 0 ∨ b = 0`. Alternatively, a domain is an integral domain without assuming commutativity of multiplication. -/ @[protect_proj] class domain (α : Type u) extends ring α, nontrivial α := (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ a b : α, a * b = 0 → a = 0 ∨ b = 0) section domain variable [domain α] instance domain.to_no_zero_divisors : no_zero_divisors α := ⟨domain.eq_zero_or_eq_zero_of_mul_eq_zero⟩ instance domain.to_cancel_monoid_with_zero : cancel_monoid_with_zero α := { mul_left_cancel_of_ne_zero := λ a b c ha, by { rw [← sub_eq_zero, ← mul_sub], simp [ha, sub_eq_zero] }, mul_right_cancel_of_ne_zero := λ a b c hb, by { rw [← sub_eq_zero, ← sub_mul], simp [hb, sub_eq_zero] }, .. (infer_instance : semiring α) } /-- Pullback a `domain` instance along an injective function. -/ protected def function.injective.domain [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : domain β := { .. hf.ring f zero one add mul neg, .. pullback_nonzero f zero one, .. hf.no_zero_divisors f zero mul } end domain /-! ### Integral domains -/ @[protect_proj, ancestor comm_ring domain] class integral_domain (α : Type u) extends comm_ring α, domain α section integral_domain variables [integral_domain α] {a b c d e : α} instance integral_domain.to_comm_cancel_monoid_with_zero : comm_cancel_monoid_with_zero α := { ..comm_semiring.to_comm_monoid_with_zero, ..domain.to_cancel_monoid_with_zero } /-- Pullback an `integral_domain` instance along an injective function. -/ protected def function.injective.integral_domain [has_zero β] [has_one β] [has_add β] [has_mul β] [has_neg β] (f : β → α) (hf : injective f) (zero : f 0 = 0) (one : f 1 = 1) (add : ∀ x y, f (x + y) = f x + f y) (mul : ∀ x y, f (x * y) = f x * f y) (neg : ∀ x, f (-x) = -f x) : integral_domain β := { .. hf.comm_ring f zero one add mul neg, .. hf.domain f zero one add mul neg } lemma mul_self_eq_mul_self_iff {a b : α} : a * a = b * b ↔ a = b ∨ a = -b := by rw [← sub_eq_zero, mul_self_sub_mul_self, mul_eq_zero, or_comm, sub_eq_zero, add_eq_zero_iff_eq_neg] lemma mul_self_eq_one_iff {a : α} : a * a = 1 ↔ a = 1 ∨ a = -1 := by rw [← mul_self_eq_mul_self_iff, one_mul] /-- In the unit group of an integral domain, a unit is its own inverse iff the unit is one or one's additive inverse. -/ lemma units.inv_eq_self_iff (u : units α) : u⁻¹ = u ↔ u = 1 ∨ u = -1 := by { rw inv_eq_iff_mul_eq_one, simp only [units.ext_iff], push_cast, exact mul_self_eq_one_iff } end integral_domain namespace ring variables [ring R] open_locale classical /-- Introduce a function `inverse` on a ring `R`, which sends `x` to `x⁻¹` if `x` is invertible and to `0` otherwise. This definition is somewhat ad hoc, but one needs a fully (rather than partially) defined inverse function for some purposes, including for calculus. -/ noncomputable def inverse : R → R := λ x, if h : is_unit x then (((classical.some h)⁻¹ : units R) : R) else 0 /-- By definition, if `x` is invertible then `inverse x = x⁻¹`. -/ lemma inverse_unit (a : units R) : inverse (a : R) = (a⁻¹ : units R) := begin simp [is_unit_unit, inverse], exact units.inv_unique (classical.some_spec (is_unit_unit a)), end end ring /-- A predicate to express that a ring is an integral domain. This is mainly useful because such a predicate does not contain data, and can therefore be easily transported along ring isomorphisms. -/ structure is_integral_domain (R : Type u) [ring R] extends nontrivial R : Prop := (mul_comm : ∀ (x y : R), x * y = y * x) (eq_zero_or_eq_zero_of_mul_eq_zero : ∀ x y : R, x * y = 0 → x = 0 ∨ y = 0) -- The linter does not recognize that is_integral_domain.to_nontrivial is a structure -- projection, disable it attribute [nolint def_lemma doc_blame] is_integral_domain.to_nontrivial /-- Every integral domain satisfies the predicate for integral domains. -/ lemma integral_domain.to_is_integral_domain (R : Type u) [integral_domain R] : is_integral_domain R := { .. (‹_› : integral_domain R) } /-- If a ring satisfies the predicate for integral domains, then it can be endowed with an `integral_domain` instance whose data is definitionally equal to the existing data. -/ def is_integral_domain.to_integral_domain (R : Type u) [ring R] (h : is_integral_domain R) : integral_domain R := { .. (‹_› : ring R), .. (‹_› : is_integral_domain R) } namespace semiconj_by @[simp] lemma add_right [distrib R] {a x y x' y' : R} (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x + x') (y + y') := by simp only [semiconj_by, left_distrib, right_distrib, h.eq, h'.eq] @[simp] lemma add_left [distrib R] {a b x y : R} (ha : semiconj_by a x y) (hb : semiconj_by b x y) : semiconj_by (a + b) x y := by simp only [semiconj_by, left_distrib, right_distrib, ha.eq, hb.eq] variables [ring R] {a b x y x' y' : R} lemma neg_right (h : semiconj_by a x y) : semiconj_by a (-x) (-y) := by simp only [semiconj_by, h.eq, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm] @[simp] lemma neg_right_iff : semiconj_by a (-x) (-y) ↔ semiconj_by a x y := ⟨λ h, neg_neg x ▸ neg_neg y ▸ h.neg_right, semiconj_by.neg_right⟩ lemma neg_left (h : semiconj_by a x y) : semiconj_by (-a) x y := by simp only [semiconj_by, h.eq, neg_mul_eq_neg_mul_symm, mul_neg_eq_neg_mul_symm] @[simp] lemma neg_left_iff : semiconj_by (-a) x y ↔ semiconj_by a x y := ⟨λ h, neg_neg a ▸ h.neg_left, semiconj_by.neg_left⟩ @[simp] lemma neg_one_right (a : R) : semiconj_by a (-1) (-1) := (one_right a).neg_right @[simp] lemma neg_one_left (x : R) : semiconj_by (-1) x x := (semiconj_by.one_left x).neg_left @[simp] lemma sub_right (h : semiconj_by a x y) (h' : semiconj_by a x' y') : semiconj_by a (x - x') (y - y') := h.add_right h'.neg_right @[simp] lemma sub_left (ha : semiconj_by a x y) (hb : semiconj_by b x y) : semiconj_by (a - b) x y := ha.add_left hb.neg_left end semiconj_by namespace commute @[simp] theorem add_right [distrib R] {a b c : R} : commute a b → commute a c → commute a (b + c) := semiconj_by.add_right @[simp] theorem add_left [distrib R] {a b c : R} : commute a c → commute b c → commute (a + b) c := semiconj_by.add_left variables [ring R] {a b c : R} theorem neg_right : commute a b → commute a (- b) := semiconj_by.neg_right @[simp] theorem neg_right_iff : commute a (-b) ↔ commute a b := semiconj_by.neg_right_iff theorem neg_left : commute a b → commute (- a) b := semiconj_by.neg_left @[simp] theorem neg_left_iff : commute (-a) b ↔ commute a b := semiconj_by.neg_left_iff @[simp] theorem neg_one_right (a : R) : commute a (-1) := semiconj_by.neg_one_right a @[simp] theorem neg_one_left (a : R): commute (-1) a := semiconj_by.neg_one_left a @[simp] theorem sub_right : commute a b → commute a c → commute a (b - c) := semiconj_by.sub_right @[simp] theorem sub_left : commute a c → commute b c → commute (a - b) c := semiconj_by.sub_left end commute
35f2172a59e77f739f1cebdf2f25c09db32de018
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/analysis/calculus/tangent_cone.lean
114f612eb32d151cb4d36d9f63b02cee1e578bd3
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
18,707
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import analysis.convex.basic import analysis.specific_limits /-! # Tangent cone In this file, we define two predicates `unique_diff_within_at 𝕜 s x` and `unique_diff_on 𝕜 s` ensuring that, if a function has two derivatives, then they have to coincide. As a direct definition of this fact (quantifying on all target types and all functions) would depend on universes, we use a more intrinsic definition: if all the possible tangent directions to the set `s` at the point `x` span a dense subset of the whole subset, it is easy to check that the derivative has to be unique. Therefore, we introduce the set of all tangent directions, named `tangent_cone_at`, and express `unique_diff_within_at` and `unique_diff_on` in terms of it. One should however think of this definition as an implementation detail: the only reason to introduce the predicates `unique_diff_within_at` and `unique_diff_on` is to ensure the uniqueness of the derivative. This is why their names reflect their uses, and not how they are defined. ## Implementation details Note that this file is imported by `fderiv.lean`. Hence, derivatives are not defined yet. The property of uniqueness of the derivative is therefore proved in `fderiv.lean`, but based on the properties of the tangent cone we prove here. -/ variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜] open filter set open_locale topological_space section tangent_cone variables {E : Type*} [add_comm_monoid E] [module 𝕜 E] [topological_space E] /-- The set of all tangent directions to the set `s` at the point `x`. -/ def tangent_cone_at (s : set E) (x : E) : set E := {y : E | ∃(c : ℕ → 𝕜) (d : ℕ → E), (∀ᶠ n in at_top, x + d n ∈ s) ∧ (tendsto (λn, ∥c n∥) at_top at_top) ∧ (tendsto (λn, c n • d n) at_top (𝓝 y))} /-- A property ensuring that the tangent cone to `s` at `x` spans a dense subset of the whole space. The main role of this property is to ensure that the differential within `s` at `x` is unique, hence this name. The uniqueness it asserts is proved in `unique_diff_within_at.eq` in `fderiv.lean`. To avoid pathologies in dimension 0, we also require that `x` belongs to the closure of `s` (which is automatic when `E` is not `0`-dimensional). -/ @[mk_iff] structure unique_diff_within_at (s : set E) (x : E) : Prop := (dense_tangent_cone : dense ((submodule.span 𝕜 (tangent_cone_at 𝕜 s x)) : set E)) (mem_closure : x ∈ closure s) /-- A property ensuring that the tangent cone to `s` at any of its points spans a dense subset of the whole space. The main role of this property is to ensure that the differential along `s` is unique, hence this name. The uniqueness it asserts is proved in `unique_diff_on.eq` in `fderiv.lean`. -/ def unique_diff_on (s : set E) : Prop := ∀x ∈ s, unique_diff_within_at 𝕜 s x end tangent_cone variables {E : Type*} [normed_group E] [normed_space 𝕜 E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] variables {G : Type*} [normed_group G] [normed_space ℝ G] variables {𝕜} {x y : E} {s t : set E} section tangent_cone /- This section is devoted to the properties of the tangent cone. -/ open normed_field lemma tangent_cone_univ : tangent_cone_at 𝕜 univ x = univ := begin refine univ_subset_iff.1 (λy hy, _), rcases exists_one_lt_norm 𝕜 with ⟨w, hw⟩, refine ⟨λn, w^n, λn, (w^n)⁻¹ • y, univ_mem' (λn, mem_univ _), _, _⟩, { simp only [norm_pow], exact tendsto_pow_at_top_at_top_of_one_lt hw }, { convert tendsto_const_nhds, ext n, have : w ^ n * (w ^ n)⁻¹ = 1, { apply mul_inv_cancel, apply pow_ne_zero, simpa [norm_eq_zero] using (ne_of_lt (lt_trans zero_lt_one hw)).symm }, rw [smul_smul, this, one_smul] } end lemma tangent_cone_mono (h : s ⊆ t) : tangent_cone_at 𝕜 s x ⊆ tangent_cone_at 𝕜 t x := begin rintros y ⟨c, d, ds, ctop, clim⟩, exact ⟨c, d, mem_of_superset ds (λn hn, h hn), ctop, clim⟩ end /-- Auxiliary lemma ensuring that, under the assumptions defining the tangent cone, the sequence `d` tends to 0 at infinity. -/ lemma tangent_cone_at.lim_zero {α : Type*} (l : filter α) {c : α → 𝕜} {d : α → E} (hc : tendsto (λn, ∥c n∥) l at_top) (hd : tendsto (λn, c n • d n) l (𝓝 y)) : tendsto d l (𝓝 0) := begin have A : tendsto (λn, ∥c n∥⁻¹) l (𝓝 0) := tendsto_inv_at_top_zero.comp hc, have B : tendsto (λn, ∥c n • d n∥) l (𝓝 ∥y∥) := (continuous_norm.tendsto _).comp hd, have C : tendsto (λn, ∥c n∥⁻¹ * ∥c n • d n∥) l (𝓝 (0 * ∥y∥)) := A.mul B, rw zero_mul at C, have : ∀ᶠ n in l, ∥c n∥⁻¹ * ∥c n • d n∥ = ∥d n∥, { apply (eventually_ne_of_tendsto_norm_at_top hc 0).mono (λn hn, _), rw [norm_smul, ← mul_assoc, inv_mul_cancel, one_mul], rwa [ne.def, norm_eq_zero] }, have D : tendsto (λ n, ∥d n∥) l (𝓝 0) := tendsto.congr' this C, rw tendsto_zero_iff_norm_tendsto_zero, exact D end lemma tangent_cone_mono_nhds (h : 𝓝[s] x ≤ 𝓝[t] x) : tangent_cone_at 𝕜 s x ⊆ tangent_cone_at 𝕜 t x := begin rintros y ⟨c, d, ds, ctop, clim⟩, refine ⟨c, d, _, ctop, clim⟩, suffices : tendsto (λ n, x + d n) at_top (𝓝[t] x), from tendsto_principal.1 (tendsto_inf.1 this).2, refine (tendsto_inf.2 ⟨_, tendsto_principal.2 ds⟩).mono_right h, simpa only [add_zero] using tendsto_const_nhds.add (tangent_cone_at.lim_zero at_top ctop clim) end /-- Tangent cone of `s` at `x` depends only on `𝓝[s] x`. -/ lemma tangent_cone_congr (h : 𝓝[s] x = 𝓝[t] x) : tangent_cone_at 𝕜 s x = tangent_cone_at 𝕜 t x := subset.antisymm (tangent_cone_mono_nhds $ le_of_eq h) (tangent_cone_mono_nhds $ le_of_eq h.symm) /-- Intersecting with a neighborhood of the point does not change the tangent cone. -/ lemma tangent_cone_inter_nhds (ht : t ∈ 𝓝 x) : tangent_cone_at 𝕜 (s ∩ t) x = tangent_cone_at 𝕜 s x := tangent_cone_congr (nhds_within_restrict' _ ht).symm /-- The tangent cone of a product contains the tangent cone of its left factor. -/ lemma subset_tangent_cone_prod_left {t : set F} {y : F} (ht : y ∈ closure t) : linear_map.inl 𝕜 E F '' (tangent_cone_at 𝕜 s x) ⊆ tangent_cone_at 𝕜 (set.prod s t) (x, y) := begin rintros _ ⟨v, ⟨c, d, hd, hc, hy⟩, rfl⟩, have : ∀n, ∃d', y + d' ∈ t ∧ ∥c n • d'∥ < ((1:ℝ)/2)^n, { assume n, rcases mem_closure_iff_nhds.1 ht _ (eventually_nhds_norm_smul_sub_lt (c n) y (pow_pos one_half_pos n)) with ⟨z, hz, hzt⟩, exact ⟨z - y, by simpa using hzt, by simpa using hz⟩ }, choose d' hd' using this, refine ⟨c, λn, (d n, d' n), _, hc, _⟩, show ∀ᶠ n in at_top, (x, y) + (d n, d' n) ∈ set.prod s t, { filter_upwards [hd], assume n hn, simp [hn, (hd' n).1] }, { apply tendsto.prod_mk_nhds hy _, refine squeeze_zero_norm (λn, (hd' n).2.le) _, exact tendsto_pow_at_top_nhds_0_of_lt_1 one_half_pos.le one_half_lt_one } end /-- The tangent cone of a product contains the tangent cone of its right factor. -/ lemma subset_tangent_cone_prod_right {t : set F} {y : F} (hs : x ∈ closure s) : linear_map.inr 𝕜 E F '' (tangent_cone_at 𝕜 t y) ⊆ tangent_cone_at 𝕜 (set.prod s t) (x, y) := begin rintros _ ⟨w, ⟨c, d, hd, hc, hy⟩, rfl⟩, have : ∀n, ∃d', x + d' ∈ s ∧ ∥c n • d'∥ < ((1:ℝ)/2)^n, { assume n, rcases mem_closure_iff_nhds.1 hs _ (eventually_nhds_norm_smul_sub_lt (c n) x (pow_pos one_half_pos n)) with ⟨z, hz, hzs⟩, exact ⟨z - x, by simpa using hzs, by simpa using hz⟩ }, choose d' hd' using this, refine ⟨c, λn, (d' n, d n), _, hc, _⟩, show ∀ᶠ n in at_top, (x, y) + (d' n, d n) ∈ set.prod s t, { filter_upwards [hd], assume n hn, simp [hn, (hd' n).1] }, { apply tendsto.prod_mk_nhds _ hy, refine squeeze_zero_norm (λn, (hd' n).2.le) _, exact tendsto_pow_at_top_nhds_0_of_lt_1 one_half_pos.le one_half_lt_one } end /-- The tangent cone of a product contains the tangent cone of each factor. -/ lemma maps_to_tangent_cone_pi {ι : Type*} [decidable_eq ι] {E : ι → Type*} [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] {s : Π i, set (E i)} {x : Π i, E i} {i : ι} (hi : ∀ j ≠ i, x j ∈ closure (s j)) : maps_to (linear_map.single i : E i →ₗ[𝕜] Π j, E j) (tangent_cone_at 𝕜 (s i) (x i)) (tangent_cone_at 𝕜 (set.pi univ s) x) := begin rintros w ⟨c, d, hd, hc, hy⟩, have : ∀ n (j ≠ i), ∃ d', x j + d' ∈ s j ∧ ∥c n • d'∥ < (1 / 2 : ℝ) ^ n, { assume n j hj, rcases mem_closure_iff_nhds.1 (hi j hj) _ (eventually_nhds_norm_smul_sub_lt (c n) (x j) (pow_pos one_half_pos n)) with ⟨z, hz, hzs⟩, exact ⟨z - x j, by simpa using hzs, by simpa using hz⟩ }, choose! d' hd's hcd', refine ⟨c, λ n, function.update (d' n) i (d n), hd.mono (λ n hn j hj', _), hc, tendsto_pi.2 $ λ j, _⟩, { rcases em (j = i) with rfl|hj; simp * }, { rcases em (j = i) with rfl|hj, { simp [hy] }, { suffices : tendsto (λ n, c n • d' n j) at_top (𝓝 0), by simpa [hj], refine squeeze_zero_norm (λ n, (hcd' n j hj).le) _, exact tendsto_pow_at_top_nhds_0_of_lt_1 one_half_pos.le one_half_lt_one } } end /-- If a subset of a real vector space contains a segment, then the direction of this segment belongs to the tangent cone at its endpoints. -/ lemma mem_tangent_cone_of_segment_subset {s : set G} {x y : G} (h : segment ℝ x y ⊆ s) : y - x ∈ tangent_cone_at ℝ s x := begin let c := λn:ℕ, (2:ℝ)^n, let d := λn:ℕ, (c n)⁻¹ • (y-x), refine ⟨c, d, filter.univ_mem' (λn, h _), _, _⟩, show x + d n ∈ segment ℝ x y, { rw segment_eq_image, refine ⟨(c n)⁻¹, ⟨_, _⟩, _⟩, { rw inv_nonneg, apply pow_nonneg, norm_num }, { apply inv_le_one, apply one_le_pow_of_one_le, norm_num }, { simp only [d, sub_smul, smul_sub, one_smul], abel } }, show filter.tendsto (λ (n : ℕ), ∥c n∥) filter.at_top filter.at_top, { have : (λ (n : ℕ), ∥c n∥) = c, by { ext n, exact abs_of_nonneg (pow_nonneg (by norm_num) _) }, rw this, exact tendsto_pow_at_top_at_top_of_one_lt (by norm_num) }, show filter.tendsto (λ (n : ℕ), c n • d n) filter.at_top (𝓝 (y - x)), { have : (λ (n : ℕ), c n • d n) = (λn, y - x), { ext n, simp only [d, smul_smul], rw [mul_inv_cancel, one_smul], exact pow_ne_zero _ (by norm_num) }, rw this, apply tendsto_const_nhds } end end tangent_cone section unique_diff /-! ### Properties of `unique_diff_within_at` and `unique_diff_on` This section is devoted to properties of the predicates `unique_diff_within_at` and `unique_diff_on`. -/ lemma unique_diff_on.unique_diff_within_at {s : set E} {x} (hs : unique_diff_on 𝕜 s) (h : x ∈ s) : unique_diff_within_at 𝕜 s x := hs x h lemma unique_diff_within_at_univ : unique_diff_within_at 𝕜 univ x := by { rw [unique_diff_within_at_iff, tangent_cone_univ], simp } lemma unique_diff_on_univ : unique_diff_on 𝕜 (univ : set E) := λx hx, unique_diff_within_at_univ lemma unique_diff_on_empty : unique_diff_on 𝕜 (∅ : set E) := λ x hx, hx.elim lemma unique_diff_within_at.mono_nhds (h : unique_diff_within_at 𝕜 s x) (st : 𝓝[s] x ≤ 𝓝[t] x) : unique_diff_within_at 𝕜 t x := begin simp only [unique_diff_within_at_iff] at *, rw [mem_closure_iff_nhds_within_ne_bot] at h ⊢, exact ⟨h.1.mono $ submodule.span_mono $ tangent_cone_mono_nhds st, h.2.mono st⟩ end lemma unique_diff_within_at.mono (h : unique_diff_within_at 𝕜 s x) (st : s ⊆ t) : unique_diff_within_at 𝕜 t x := h.mono_nhds $ nhds_within_mono _ st lemma unique_diff_within_at_congr (st : 𝓝[s] x = 𝓝[t] x) : unique_diff_within_at 𝕜 s x ↔ unique_diff_within_at 𝕜 t x := ⟨λ h, h.mono_nhds $ le_of_eq st, λ h, h.mono_nhds $ le_of_eq st.symm⟩ lemma unique_diff_within_at_inter (ht : t ∈ 𝓝 x) : unique_diff_within_at 𝕜 (s ∩ t) x ↔ unique_diff_within_at 𝕜 s x := unique_diff_within_at_congr $ (nhds_within_restrict' _ ht).symm lemma unique_diff_within_at.inter (hs : unique_diff_within_at 𝕜 s x) (ht : t ∈ 𝓝 x) : unique_diff_within_at 𝕜 (s ∩ t) x := (unique_diff_within_at_inter ht).2 hs lemma unique_diff_within_at_inter' (ht : t ∈ 𝓝[s] x) : unique_diff_within_at 𝕜 (s ∩ t) x ↔ unique_diff_within_at 𝕜 s x := unique_diff_within_at_congr $ (nhds_within_restrict'' _ ht).symm lemma unique_diff_within_at.inter' (hs : unique_diff_within_at 𝕜 s x) (ht : t ∈ 𝓝[s] x) : unique_diff_within_at 𝕜 (s ∩ t) x := (unique_diff_within_at_inter' ht).2 hs lemma unique_diff_within_at_of_mem_nhds (h : s ∈ 𝓝 x) : unique_diff_within_at 𝕜 s x := by simpa only [univ_inter] using unique_diff_within_at_univ.inter h lemma is_open.unique_diff_within_at (hs : is_open s) (xs : x ∈ s) : unique_diff_within_at 𝕜 s x := unique_diff_within_at_of_mem_nhds (is_open.mem_nhds hs xs) lemma unique_diff_on.inter (hs : unique_diff_on 𝕜 s) (ht : is_open t) : unique_diff_on 𝕜 (s ∩ t) := λx hx, (hs x hx.1).inter (is_open.mem_nhds ht hx.2) lemma is_open.unique_diff_on (hs : is_open s) : unique_diff_on 𝕜 s := λx hx, is_open.unique_diff_within_at hs hx /-- The product of two sets of unique differentiability at points `x` and `y` has unique differentiability at `(x, y)`. -/ lemma unique_diff_within_at.prod {t : set F} {y : F} (hs : unique_diff_within_at 𝕜 s x) (ht : unique_diff_within_at 𝕜 t y) : unique_diff_within_at 𝕜 (set.prod s t) (x, y) := begin rw [unique_diff_within_at_iff] at ⊢ hs ht, rw [closure_prod_eq], refine ⟨_, hs.2, ht.2⟩, have : _ ≤ submodule.span 𝕜 (tangent_cone_at 𝕜 (s.prod t) (x, y)) := submodule.span_mono (union_subset (subset_tangent_cone_prod_left ht.2) (subset_tangent_cone_prod_right hs.2)), rw [linear_map.span_inl_union_inr, set_like.le_def] at this, exact (hs.1.prod ht.1).mono this end lemma unique_diff_within_at.univ_pi (ι : Type*) [fintype ι] (E : ι → Type*) [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] (s : Π i, set (E i)) (x : Π i, E i) (h : ∀ i, unique_diff_within_at 𝕜 (s i) (x i)) : unique_diff_within_at 𝕜 (set.pi univ s) x := begin classical, simp only [unique_diff_within_at_iff, closure_pi_set] at h ⊢, refine ⟨(dense_pi univ (λ i _, (h i).1)).mono _, λ i _, (h i).2⟩, norm_cast, simp only [← submodule.supr_map_single, supr_le_iff, linear_map.map_span, submodule.span_le, ← maps_to'], exact λ i, (maps_to_tangent_cone_pi $ λ j hj, (h j).2).mono subset.rfl submodule.subset_span end lemma unique_diff_within_at.pi (ι : Type*) [fintype ι] (E : ι → Type*) [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] (s : Π i, set (E i)) (x : Π i, E i) (I : set ι) (h : ∀ i ∈ I, unique_diff_within_at 𝕜 (s i) (x i)) : unique_diff_within_at 𝕜 (set.pi I s) x := begin classical, rw [← set.univ_pi_piecewise], refine unique_diff_within_at.univ_pi _ _ _ _ (λ i, _), by_cases hi : i ∈ I; simp [*, unique_diff_within_at_univ], end /-- The product of two sets of unique differentiability is a set of unique differentiability. -/ lemma unique_diff_on.prod {t : set F} (hs : unique_diff_on 𝕜 s) (ht : unique_diff_on 𝕜 t) : unique_diff_on 𝕜 (set.prod s t) := λ ⟨x, y⟩ h, unique_diff_within_at.prod (hs x h.1) (ht y h.2) /-- The finite product of a family of sets of unique differentiability is a set of unique differentiability. -/ lemma unique_diff_on.pi (ι : Type*) [fintype ι] (E : ι → Type*) [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] (s : Π i, set (E i)) (I : set ι) (h : ∀ i ∈ I, unique_diff_on 𝕜 (s i)) : unique_diff_on 𝕜 (set.pi I s) := λ x hx, unique_diff_within_at.pi _ _ _ _ _ $ λ i hi, h i hi (x i) (hx i hi) /-- The finite product of a family of sets of unique differentiability is a set of unique differentiability. -/ lemma unique_diff_on.univ_pi (ι : Type*) [fintype ι] (E : ι → Type*) [Π i, normed_group (E i)] [Π i, normed_space 𝕜 (E i)] (s : Π i, set (E i)) (h : ∀ i, unique_diff_on 𝕜 (s i)) : unique_diff_on 𝕜 (set.pi univ s) := unique_diff_on.pi _ _ _ _ $ λ i _, h i /-- In a real vector space, a convex set with nonempty interior is a set of unique differentiability. -/ theorem unique_diff_on_convex {s : set G} (conv : convex s) (hs : (interior s).nonempty) : unique_diff_on ℝ s := begin assume x xs, rcases hs with ⟨y, hy⟩, suffices : y - x ∈ interior (tangent_cone_at ℝ s x), { refine ⟨dense.of_closure _, subset_closure xs⟩, simp [(submodule.span ℝ (tangent_cone_at ℝ s x)).eq_top_of_nonempty_interior' ⟨y - x, interior_mono submodule.subset_span this⟩] }, rw [mem_interior_iff_mem_nhds] at hy ⊢, apply mem_of_superset ((is_open_map_sub_right x).image_mem_nhds hy), rintros _ ⟨z, zs, rfl⟩, exact mem_tangent_cone_of_segment_subset (conv.segment_subset xs zs) end lemma unique_diff_on_Ici (a : ℝ) : unique_diff_on ℝ (Ici a) := unique_diff_on_convex (convex_Ici a) $ by simp only [interior_Ici, nonempty_Ioi] lemma unique_diff_on_Iic (a : ℝ) : unique_diff_on ℝ (Iic a) := unique_diff_on_convex (convex_Iic a) $ by simp only [interior_Iic, nonempty_Iio] lemma unique_diff_on_Ioi (a : ℝ) : unique_diff_on ℝ (Ioi a) := is_open_Ioi.unique_diff_on lemma unique_diff_on_Iio (a : ℝ) : unique_diff_on ℝ (Iio a) := is_open_Iio.unique_diff_on lemma unique_diff_on_Icc {a b : ℝ} (hab : a < b) : unique_diff_on ℝ (Icc a b) := unique_diff_on_convex (convex_Icc a b) $ by simp only [interior_Icc, nonempty_Ioo, hab] lemma unique_diff_on_Ico (a b : ℝ) : unique_diff_on ℝ (Ico a b) := if hab : a < b then unique_diff_on_convex (convex_Ico a b) $ by simp only [interior_Ico, nonempty_Ioo, hab] else by simp only [Ico_eq_empty hab, unique_diff_on_empty] lemma unique_diff_on_Ioc (a b : ℝ) : unique_diff_on ℝ (Ioc a b) := if hab : a < b then unique_diff_on_convex (convex_Ioc a b) $ by simp only [interior_Ioc, nonempty_Ioo, hab] else by simp only [Ioc_eq_empty hab, unique_diff_on_empty] lemma unique_diff_on_Ioo (a b : ℝ) : unique_diff_on ℝ (Ioo a b) := is_open_Ioo.unique_diff_on /-- The real interval `[0, 1]` is a set of unique differentiability. -/ lemma unique_diff_on_Icc_zero_one : unique_diff_on ℝ (Icc (0:ℝ) 1) := unique_diff_on_Icc zero_lt_one end unique_diff
1df4f7372fa95e4d8fd59e41862d984568e7c9fd
9e90bb7eb4d1bde1805f9eb6187c333fdf09588a
/src/stump/sample_complexity.lean
552b3367274f429c994f0b53cfa3e036597ebb7c
[ "Apache-2.0" ]
permissive
alexjbest/stump-learnable
6311d0c3a1a1a0e65ce83edcbb3b4b7cecabb851
f8fd812fc646d2ece312ff6ffc2a19848ac76032
refs/heads/master
1,659,486,805,691
1,590,454,024,000
1,590,454,024,000
266,173,720
0
0
Apache-2.0
1,590,169,884,000
1,590,169,883,000
null
UTF-8
Lean
false
false
2,170
lean
/- Copyright © 2019, Oracle and/or its affiliates. All rights reserved. -/ import analysis.special_functions.exp_log import ..lib.util open real noncomputable def complexity (ε: ℝ) (δ: ℝ) : ℝ := (log(δ) / log(1 - ε)) - (1: nat) lemma complexity_enough: ∀ ε: nnreal, ∀ δ: nnreal, ∀ n: ℕ, ε > (0: nnreal) → ε < (1: nnreal) → δ > (0: nnreal) → δ < (1: nnreal) → (n: ℝ) > (complexity ε δ) → ((1 - ε)^(n+1)) ≤ δ := begin unfold complexity, intros, have h0: ((1: nnreal) - ε) > 0, by change (0 < 1 - ε);rwa[← nnreal.coe_pos, nnreal.coe_sub (le_of_lt (a_1)), sub_pos, nnreal.coe_lt_coe], rw log_le_log_nnreal, { have h2:= log_pow_nnreal (1 - ε) h0 (n+1), unfold_coes at *, rw ← pow_coe, rw h2, apply mul_le_of_div_le_of_neg, { rw ←exp_lt_exp, simp, rw exp_log _, { rw nnreal.coe_sub, cases ε, exact sub_lt_self 1 a, apply le_of_lt, assumption, }, { rw nnreal.coe_sub, cases ε, exact sub_pos.mpr a_1, apply le_of_lt, assumption, }, }, { apply le_of_lt, clear h2, have nat_cast_1: ∀ x: ℕ, (nat.cast x) + (1:ℝ) = nat.cast(x + 1), exact nat.cast_succ, rw ← nat_cast_1, have minus_nnreal: ∀ x: nnreal, x < 1 → (1 - x).val = 1 - x.val, assume x h, exact nnreal.coe_sub (le_of_lt h), rw minus_nnreal, swap, assumption, have plus_1:= add_lt_add_right a_4 1, simp at plus_1, simp, conv { to_rhs, rw add_comm, skip, }, have silly: (1: ℝ) = nat.cast 1, { unfold nat.cast, simp, }, conv { to_rhs, rw silly, skip, }, exact sub_lt_iff_lt_add'.mp a_4, }, }, { refine pow_pos h0 (n + 1), }, { assumption, }, end
b05e7c75072dba94c4b8c9b85263610d0cf95c71
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/ind5.lean
80bd169e8231673c14a3e978415c70a42629af86
[ "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
182
lean
prelude definition Prop : Type.{1} := Type.{0} inductive or (A B : Prop) : Prop := intro_left : A → or A B, intro_right : B → or A B check or check or.intro_left check or.rec
0f533c1eea7894a7d535ceaf06178baddd61a881
11273cd7abe620b674d36c28ff284c6832b763e8
/src/export_json.lean
4c6112d202e7ddb724e705cb70486aa96d7fcad6
[]
no_license
robertylewis/doc_gen
a97b3086f91951e24e4efa0dc2ced5727e72ddf6
bd4e6a3a29182de7a7c476927f9507b3a1dfd988
refs/heads/master
1,624,306,176,487
1,585,046,989,000
1,585,046,989,000
221,195,720
1
1
null
1,576,511,575,000
1,573,556,076,000
Python
UTF-8
Lean
false
false
13,098
lean
/- Copyright (c) 2019 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Robert Y. Lewis -/ import tactic.core system.io data.string.defs tactic.interactive data.list.sort import all /-! Used to generate a json file for html docs. The json file is a list of maps, where each map has the structure { name: string, args : list string, type: string, doc_string: string, filename: string, line: int, attributes: list string, equations: list string, kind: string, structure_fields: list (list string), constructors: list (list string) } The lists in structure_fields and constructors are assumed to contain two strings each. Include this file somewhere in mathlib, e.g. in the `scripts` directory. Make sure mathlib is precompiled, with `all.lean` generated by `mk_all.sh`. Usage: `lean --run export_json.lean` creates `json_export.txt` in the current directory. -/ open tactic io io.fs native set_option pp.generalized_field_notation true /-- The information collected from each declaration -/ structure decl_info := (name : name) (is_meta : bool) (args : list (bool × string)) -- tt means implicit (type : string) (doc_string : option string) (filename : string) (line : ℕ) (attributes : list string) -- not all attributes, we have a hardcoded list to check (equations : list string) (kind : string) -- def, thm, cnst, ax (structure_fields : list (string × string)) -- name and type of fields of a constructor (constructors : list (string × string)) -- name and type of constructors of an inductive type structure module_doc_info := (filename : string) (line : ℕ) (content : string) section set_option old_structure_cmd true structure ext_tactic_doc_entry extends tactic_doc_entry := (imported : string) meta def ext_tactic_doc_entry.to_string : ext_tactic_doc_entry → string | ⟨name, category, decl_names, tags, description, _, imported⟩ := let decl_names := decl_names.map (repr ∘ to_string), tags := tags.map repr in "{" ++ to_string (format!"\"name\": {repr name}, \"category\": \"{category}\", \"decl_names\":{decl_names}, \"tags\": {tags}, \"description\": {repr description}, \"import\": {repr imported}") ++ "}" end meta def escape_quotes (s : string) : string := s.fold "" (λ s x, s ++ if x = '"' then '\\'.to_string ++ '"'.to_string else x.to_string) meta def print_arg : bool × string → string | (b, s) := let bstr := if b then "true" else "false" in "{" ++ (to_string $ format!"\"arg\":{repr s}, \"implicit\":{bstr}") ++ "}" meta def decl_info.to_format : decl_info → format | ⟨name, is_meta, args, type, doc_string, filename, line, attributes, equations, kind, structure_fields, constructors⟩ := let doc_string := doc_string.get_or_else "", is_meta := if is_meta then "true" else "false", args := args.map print_arg, attributes := attributes.map repr, equations := equations.map repr, structure_fields := structure_fields.map (λ ⟨n, t⟩, format!"[\"{to_string n}\", {repr t}]"), constructors := constructors.map (λ ⟨n, t⟩, format!"[\"{to_string n}\", {repr t}]") in "{" ++ format!"\"name\":\"{to_string name}\", \"is_meta\":{is_meta}, \"args\":{args}, \"type\":{repr type}, \"doc_string\":{repr doc_string}, " ++ format!"\"filename\":\"{filename}\",\"line\":{line}, \"attributes\":{attributes}, \"equations\":{equations}, " ++ format!" \"kind\":{repr kind}, \"structure_fields\":{structure_fields}, \"constructors\":{constructors}" ++ "}" section open tactic.interactive -- tt means implicit private meta def format_binders : list name × binder_info × expr → tactic (bool × format) | (ns, binder_info.default, t) := prod.mk ff <$> pformat!"({format_names ns} : {t})" | (ns, binder_info.implicit, t) := prod.mk tt <$> pformat!"{{{format_names ns} : {t}}" | (ns, binder_info.strict_implicit, t) := prod.mk tt <$> pformat!"⦃{format_names ns} : {t}⦄" | ([n], binder_info.inst_implicit, t) := prod.mk tt <$> if "_".is_prefix_of n.to_string then pformat!"[{t}]" else pformat!"[{format_names [n]} : {t}]" | (ns, binder_info.inst_implicit, t) := prod.mk tt <$> pformat!"[{format_names ns} : {t}]" | (ns, binder_info.aux_decl, t) := prod.mk tt <$> pformat!"({format_names ns} : {t})" meta def binder_info.is_inst_implicit : binder_info → bool | binder_info.inst_implicit := tt | _ := ff meta def count_named_intros : expr → tactic ℕ | e@(expr.pi _ bi _ _) := do ([_], b) ← mk_local_pisn e 1, v ← count_named_intros b, return $ if v = 0 ∧ e.is_arrow ∧ ¬ bi.is_inst_implicit then v else v + 1 | _ := return 0 /- meta def count_named_intros : expr → ℕ | e@(expr.pi _ _ _ b) := let v := count_named_intros b in if v = 0 ∧ e.is_arrow then v else v + 1 | _ := 0 -/ -- tt means implicit meta def get_args_and_type (e : expr) : tactic (list (bool × string) × string) := prod.fst <$> solve_aux e ( do count_named_intros e >>= intron, cxt ← local_context >>= tactic.interactive.compact_decl, cxt' ← cxt.mmap (λ t, do ft ← format_binders t, return (ft.1, to_string ft.2)), tgt ← target >>= pp, return (cxt', to_string tgt)) end /-- The attributes we check for -/ meta def attribute_list := [`simp, `squash_cast, `move_cast, `elim_cast, `nolint, `ext, `instance, `class] meta def attributes_of (n : name) : tactic (list string) := list.map to_string <$> attribute_list.mfilter (λ attr, succeeds $ has_attribute attr n) meta def declaration.kind : declaration → string | (declaration.defn a a_1 a_2 a_3 a_4 a_5) := "def" | (declaration.thm a a_1 a_2 a_3) := "thm" | (declaration.cnst a a_1 a_2 a_3) := "cnst" | (declaration.ax a a_1 a_2) := "ax" -- does this not exist already? I'm confused. meta def expr.instantiate_pis : list expr → expr → expr | (e'::es) (expr.pi n bi t e) := expr.instantiate_pis es (e.instantiate_var e') | _ e := e meta def enable_links : tactic unit := do o ← get_options, set_options $ o.set_bool `pp.links tt -- assumes proj_name exists meta def get_proj_type (struct_name proj_name : name) : tactic string := do (locs, _) ← mk_const struct_name >>= infer_type >>= mk_local_pis, proj_tp ← mk_const proj_name >>= infer_type, (_, t) ← mk_local_pisn (proj_tp.instantiate_pis locs) 1, to_string <$> pp t meta def mk_structure_fields (decl : name) (e : environment) : tactic (list (string × string)) := match e.is_structure decl, e.structure_fields_full decl with | tt, some proj_names := proj_names.mmap $ λ n, do tp ← get_proj_type decl n, return (to_string n, to_string tp) | _, _ := return [] end -- this is used as a hack in get_constructor_type to avoid printing `Type ?`. meta def mk_const_with_params (d : declaration) : expr := let lvls := d.univ_params.map level.param in expr.const d.to_name lvls meta def get_constructor_type (type_name constructor_name : name) : tactic string := do d ← get_decl type_name, (locs, _) ← infer_type (mk_const_with_params d) >>= mk_local_pis, proj_tp ← mk_const constructor_name >>= infer_type, do t ← pis locs (proj_tp.instantiate_pis locs), --.abstract_locals (locs.map expr.local_uniq_name), to_string <$> pp t meta def mk_constructors (decl : name) (e : environment): tactic (list (string × string)) := if (¬ e.is_inductive decl) ∨ (e.is_structure decl) then return [] else do d ← get_decl decl, ns ← get_constructors_for (mk_const_with_params d), ns.mmap $ λ n, do tp ← get_constructor_type decl n, return (to_string n, to_string tp) meta def get_equations (decl : name) : tactic (list string) := do ns ← get_eqn_lemmas_for tt decl, ns.mmap $ λ n, do d ← get_decl n, (_, ty) ← mk_local_pis d.type, to_string <$> pp ty /-- extracts `decl_info` from `d`. Should return `none` instead of failing. -/ meta def process_decl (d : declaration) : tactic (option decl_info) := do ff ← d.in_current_file | return none, e ← get_env, let decl_name := d.to_name, if decl_name.is_internal ∨ d.is_auto_generated e then return none else do some filename ← return (e.decl_olean decl_name) | return none, some ⟨line, _⟩ ← return (e.decl_pos decl_name) | return none, doc_string ← (some <$> doc_string decl_name) <|> return none, (args, type) ← get_args_and_type d.type, -- type ← escape_quotes <$> to_string <$> pp d.type, attributes ← attributes_of decl_name, equations ← get_equations decl_name, structure_fields ← mk_structure_fields decl_name e, constructors ← mk_constructors decl_name e, return $ some ⟨decl_name, !d.is_trusted, args, type, doc_string, filename, line, attributes, equations, d.kind, structure_fields, constructors⟩ meta def run_on_dcl_list (e : environment) (ens : list name) (handle : handle) (is_first : bool) : io unit := ens.mfoldl (λ is_first d_name, do d ← run_tactic (e.get d_name), odi ← run_tactic (enable_links >> process_decl d), match odi with | some di := do when (bnot is_first) (put_str_ln handle ","), put_str_ln handle $ to_string di.to_format, return ff | none := return is_first end) is_first >> return () meta def itersplit {α} : list α → ℕ → list (list α) | l 0 := [l] | l 1 := let (l1, l2) := l.split in [l1, l2] | l (k+2) := let (l1, l2) := l.split in itersplit l1 (k+1) ++ itersplit l2 (k+1) meta def write_module_doc_pair : pos × string → string | (⟨line, _⟩, doc) := "{\"line\":" ++ to_string line ++ ", \"doc\" :" ++ repr doc ++ "}" meta def write_olean_docs : tactic (list string) := do docs ← olean_doc_strings, return (docs.foldl (λ rest p, match p with | (none, _) := rest | (_, []) := rest | (some filename, l) := let new := "\"" ++ filename ++ "\":" ++ to_string (l.map write_module_doc_pair) in new::rest end) []) meta def get_instances : tactic (rb_lmap string string) := attribute.get_instances `instance >>= list.mfoldl (λ map inst_nm, do (_, e) ← mk_const inst_nm >>= infer_type >>= mk_local_pis, (expr.const class_nm _) ← return e.get_app_fn, return $ map.insert class_nm.to_string inst_nm.to_string) mk_rb_map meta def format_instance_list : tactic string := do map ← get_instances, let lst := map.to_list.map (λ ⟨n, l⟩, to_string format!"\"{n}\" : {repr l}"), return $ "{" ++ (string.join (lst.intersperse ",")) ++ "}" meta def format_notes : tactic string := do l ← get_library_notes, let l := l.map $ λ ⟨l, r⟩, to_string $ format!"[{repr l}, {repr r}]", let l := string.join $ l.intersperse ", ", return $ to_string $ format!"[{l}]" meta def name.imported_by_tactic_basic (decl_name : name) : bool := let env := environment.from_imported_module_name `tactic.basic in env.contains decl_name meta def name.imported_by_tactic_default (decl_name : name) : bool := let env := environment.from_imported_module_name `tactic.default in env.contains decl_name meta def name.imported_always (decl_name : name) : bool := let env := environment.from_imported_module_name `system.random in env.contains decl_name meta def tactic_doc_entry.add_import : tactic_doc_entry → ext_tactic_doc_entry | ⟨name, category, [], tags, description, idf⟩ := ⟨name, category, [], tags, description, idf, ""⟩ | ⟨name, category, rel_decls@(decl_name::_), tags, description, idf⟩ := let imported := if decl_name.imported_always then "always imported" else if decl_name.imported_by_tactic_basic then "tactic.basic" else if decl_name.imported_by_tactic_default then "tactic" else "" in ⟨name, category, rel_decls, tags, description, idf, imported⟩ meta def format_tactic_docs : tactic string := do l ← list.map tactic_doc_entry.add_import <$> get_tactic_doc_entries, return $ to_string $ l.map ext_tactic_doc_entry.to_string /-- Using `environment.mfold` is much cleaner. Unfortunately this led to a segfault, I think because of a stack overflow. Converting the environment to a list of declarations and folding over that led to "deep recursion detected". Instead, we split that list into 8 smaller lists and process them one by one. More investigation is needed. -/ meta def export_json (filename : string) : io unit := do handle ← mk_file_handle filename mode.write, put_str_ln handle "{ \"decls\":[", e ← run_tactic get_env, let ens := environment.get_decl_names e, let enss := itersplit ens 3, enss.mfoldl (λ is_first l, do run_on_dcl_list e l handle is_first, return ff) tt, put_str_ln handle "],", ods ← run_tactic write_olean_docs, put_str_ln handle $ "\"mod_docs\": {" ++ string.join (ods.intersperse ",\n") ++ "},", notes ← run_tactic format_notes, put_str_ln handle $ "\"notes\": " ++ notes ++ ",", tactic_docs ← run_tactic format_tactic_docs, put_str_ln handle $ "\"tactic_docs\": " ++ tactic_docs ++ ",", instl ← run_tactic format_instance_list, put_str_ln handle $ "\"instances\": " ++ instl ++ "}", close handle meta def main : io unit := export_json "json_export.txt"
3445d2dc9760b5a4ef3bcb6844e7d91b73ee0965
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/Match.lean
22e5dd297c92d4940185dc918df5d452ea041f0d
[ "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
57,295
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Util.ForEachExprWhere import Lean.Meta.Match.Match import Lean.Meta.GeneralizeVars import Lean.Meta.ForEachExpr import Lean.Elab.BindersUtil import Lean.Elab.PatternVar import Lean.Elab.Quotation.Precheck import Lean.Elab.SyntheticMVars namespace Lean.Elab.Term open Meta open Lean.Parser.Term private def expandSimpleMatch (stx : Syntax) (discr : Term) (lhsVar : Ident) (rhs : Term) (expectedType? : Option Expr) : TermElabM Expr := do let newStx ← `(let $lhsVar := $discr; $rhs) withMacroExpansion stx newStx <| elabTerm newStx expectedType? private def mkUserNameFor (e : Expr) : TermElabM Name := do match e with /- Remark: we use `mkFreshUserName` to make sure we don't add a variable to the local context that can be resolved to `e`. -/ | .fvar fvarId => mkFreshUserName (← fvarId.getUserName) | _ => mkFreshBinderName /-- Remark: if the discriminat is `Systax.missing`, we abort the elaboration of the `match`-expression. This can happen due to error recovery. Example ``` example : (p ∨ p) → p := fun h => match ``` If we don't abort, the elaborator loops because we will keep trying to expand ``` match ``` into ``` let d := <Syntax.missing>; match ``` Recall that `Syntax.setArg stx i arg` is a no-op when `i` is out-of-bounds. -/ def isAtomicDiscr (discr : Syntax) : TermElabM Bool := do match discr with | `($_:ident) => pure true | `(@$_:ident) => pure true | `(?$_:ident) => pure true | _ => if discr.isMissing then throwAbortTerm else pure false -- See expandNonAtomicDiscrs? private def elabAtomicDiscr (discr : Syntax) : TermElabM Expr := do let term := discr[1] elabTerm term none structure Discr where expr : Expr /-- `some h` if discriminant is annotated with the `h : ` notation. -/ h? : Option Syntax := none deriving Inhabited structure ElabMatchTypeAndDiscrsResult where discrs : Array Discr matchType : Expr /-- `true` when performing dependent elimination. We use this to decide whether we optimize the "match unit" case. See `isMatchUnit?`. -/ isDep : Bool alts : Array MatchAltView private partial def elabMatchTypeAndDiscrs (discrStxs : Array Syntax) (matchOptMotive : Syntax) (matchAltViews : Array MatchAltView) (expectedType : Expr) : TermElabM ElabMatchTypeAndDiscrsResult := do if matchOptMotive.isNone then elabDiscrs 0 #[] else -- motive := leading_parser atomic ("(" >> nonReservedSymbol "motive" >> " := ") >> termParser >> ")" let matchTypeStx := matchOptMotive[0][3] let matchType ← elabType matchTypeStx let (discrs, isDep) ← elabDiscrsWitMatchType matchType return { discrs := discrs, matchType := matchType, isDep := isDep, alts := matchAltViews } where /-- Easy case: elaborate discriminant when the match-type has been explicitly provided by the user. -/ elabDiscrsWitMatchType (matchType : Expr) : TermElabM (Array Discr × Bool) := do let mut discrs := #[] let mut i := 0 let mut matchType := matchType let mut isDep := false for discrStx in discrStxs do i := i + 1 matchType ← whnf matchType match matchType with | Expr.forallE _ d b _ => let discr ← fullApproxDefEq <| elabTermEnsuringType discrStx[1] d trace[Elab.match] "discr #{i} {discr} : {d}" if b.hasLooseBVars then isDep := true matchType := b.instantiate1 discr discrs := discrs.push { expr := discr } | _ => throwError "invalid motive provided to match-expression, function type with arity #{discrStxs.size} expected" return (discrs, isDep) markIsDep (r : ElabMatchTypeAndDiscrsResult) := { r with isDep := true } /-- Elaborate discriminants inferring the match-type -/ elabDiscrs (i : Nat) (discrs : Array Discr) : TermElabM ElabMatchTypeAndDiscrsResult := do if h : i < discrStxs.size then let discrStx := discrStxs.get ⟨i, h⟩ let discr ← elabAtomicDiscr discrStx let discr ← instantiateMVars discr let userName ← mkUserNameFor discr let h? := if discrStx[0].isNone then none else some discrStx[0][0] let discrs := discrs.push { expr := discr, h? } let mut result ← elabDiscrs (i + 1) discrs let matchTypeBody ← kabstract result.matchType discr if matchTypeBody.hasLooseBVars then result := markIsDep result /- We use `transform (usedLetOnly := true)` to eliminate unnecessary let-expressions. This transformation was added to address issue #1155, and avoid an unnecessary dependency. In issue #1155, `discrType` was of the form `let _discr := OfNat.ofNat ... 0 ?m; ...`, and not removing the unnecessary `let-expr` was introducing an artificial dependency to `?m`. TODO: make sure that even when this kind of artificial dependecy occurs we catch it before sending the term to the kernel. -/ let discrType ← transform (usedLetOnly := true) (← instantiateMVars (← inferType discr)) let matchType := Lean.mkForall userName BinderInfo.default discrType matchTypeBody return { result with matchType } else return { discrs, alts := matchAltViews, isDep := false, matchType := expectedType } def expandMacrosInPatterns (matchAlts : Array MatchAltView) : MacroM (Array MatchAltView) := do matchAlts.mapM fun matchAlt => do let patterns ← matchAlt.patterns.mapM expandMacros pure { matchAlt with patterns := patterns } private def getMatchGeneralizing? : Syntax → Option Bool | `(match (generalizing := true) $[$motive]? $_discrs,* with $_alts:matchAlt*) => some true | `(match (generalizing := false) $[$motive]? $_discrs,* with $_alts:matchAlt*) => some false | _ => none /-- Given `stx` a match-expression, return its alternatives. -/ private def getMatchAlts : Syntax → Array MatchAltView | `(match $[$gen]? $[$motive]? $_discrs,* with $alts:matchAlt*) => alts.filterMap fun alt => match alt with | `(matchAltExpr| | $patterns,* => $rhs) => some { ref := alt, patterns := patterns, rhs := rhs } | _ => none | _ => #[] @[builtin_term_elab inaccessible] def elabInaccessible : TermElab := fun stx expectedType? => do let e ← elabTerm stx[1] expectedType? return mkInaccessible e open Lean.Elab.Term.Quotation in @[builtin_quot_precheck Lean.Parser.Term.match] def precheckMatch : Precheck | `(match $[$discrs:term],* with $[| $[$patss],* => $rhss]*) => do discrs.forM precheck for (pats, rhs) in patss.zip rhss do let vars ← try getPatternsVars pats catch | _ => return -- can happen in case of pattern antiquotations Quotation.withNewLocals (getPatternVarNames vars) <| precheck rhs | _ => throwUnsupportedSyntax /-- We convert the collected `PatternVar`s intro `PatternVarDecl` -/ structure PatternVarDecl where fvarId : FVarId private partial def withPatternVars {α} (pVars : Array PatternVar) (k : Array PatternVarDecl → TermElabM α) : TermElabM α := let rec loop (i : Nat) (decls : Array PatternVarDecl) (userNames : Array Name) := do if h : i < pVars.size then let var := pVars.get ⟨i, h⟩ let type ← mkFreshTypeMVar withLocalDecl var.getId BinderInfo.default type fun x => loop (i+1) (decls.push { fvarId := x.fvarId! }) (userNames.push Name.anonymous) else k decls loop 0 #[] #[] /-! Remark: when performing dependent pattern matching, we often had to write code such as ```lean def Vec.map' (f : α → β) (xs : Vec α n) : Vec β n := match n, xs with | _, nil => nil | _, cons a as => cons (f a) (map' f as) ``` We had to include `n` and the `_`s because the type of `xs` depends on `n`. Moreover, `nil` and `cons a as` have different types. This was quite tedious. So, we have implemented an automatic "discriminant refinement procedure". The procedure is based on the observation that we get a type error whenenver we forget to include `_`s and the indices a discriminant depends on. So, we catch the exception, check whether the type of the discriminant is an indexed family, and add their indices as new discriminants. The current implementation, adds indices as they are found, and does not try to "sort" the new discriminants. If the refinement process fails, we report the original error message. -/ /-- Auxiliary structure for storing an type mismatch exception when processing the pattern #`idx` of some alternative. -/ structure PatternElabException where ex : Exception patternIdx : Nat -- Discriminant that sh pathToIndex : List Nat -- Path to the problematic inductive type index that produced the type mismatch /-- This method is part of the "discriminant refinement" procedure. It in invoked when the type of the `pattern` does not match the expected type. The expected type is based on the motive computed using the `match` discriminants. It tries to compute a path to an index of the discriminant type. For example, suppose the user has written ``` inductive Mem (a : α) : List α → Prop where | head {as} : Mem a (a::as) | tail {as} : Mem a as → Mem a (a'::as) infix:50 " ∈ " => Mem example (a b : Nat) (h : a ∈ [b]) : b = a := match h with | Mem.head => rfl ``` The motive for the match is `a ∈ [b] → b = a`, and get a type mismatch between the type of `Mem.head` and `a ∈ [b]`. This procedure return the path `[2, 1]` to the index `b`. We use it to produce the following refinement ``` example (a b : Nat) (h : a ∈ [b]) : b = a := match b, h with | _, Mem.head => rfl ``` which produces the new motive `(x : Nat) → a ∈ [x] → x = a` After this refinement step, the `match` is elaborated successfully. This method relies on the fact that the dependent pattern matcher compiler solves equations between indices of indexed inductive families. The following kinds of equations are supported by this compiler: - `x = t` - `t = x` - `ctor ... = ctor ...` where `x` is a free variable, `t` is an arbitrary term, and `ctor` is constructor. Our procedure ensures that "information" is not lost, and will *not* succeed in an example such as ``` example (a b : Nat) (f : Nat → Nat) (h : f a ∈ [f b]) : f b = f a := match h with | Mem.head => rfl ``` and will not add `f b` as a new discriminant. We may add an option in the future to enable this more liberal form of refinement. -/ private partial def findDiscrRefinementPath (pattern : Expr) (expected : Expr) : OptionT MetaM (List Nat) := do goType (← instantiateMVars (← inferType pattern)) expected where checkCompatibleApps (t d : Expr) : OptionT MetaM Unit := do guard d.isApp guard <| t.getAppNumArgs == d.getAppNumArgs let tFn := t.getAppFn let dFn := d.getAppFn guard <| tFn.isConst && dFn.isConst guard (← isDefEq tFn dFn) -- Visitor for inductive types goType (t d : Expr) : OptionT MetaM (List Nat) := do let t ← whnf t let d ← whnf d checkCompatibleApps t d matchConstInduct t.getAppFn (fun _ => failure) fun info _ => do let tArgs := t.getAppArgs let dArgs := d.getAppArgs for i in [:info.numParams] do let tArg := tArgs[i]! let dArg := dArgs[i]! unless (← isDefEq tArg dArg) do return i :: (← goType tArg dArg) for i in [info.numParams : tArgs.size] do let tArg := tArgs[i]! let dArg := dArgs[i]! unless (← isDefEq tArg dArg) do return i :: (← goIndex tArg dArg) failure -- Visitor for indexed families goIndex (t d : Expr) : OptionT MetaM (List Nat) := do let t ← whnfD t let d ← whnfD d if t.isFVar || d.isFVar then return [] -- Found refinement path else checkCompatibleApps t d matchConstCtor t.getAppFn (fun _ => failure) fun info _ => do let tArgs := t.getAppArgs let dArgs := d.getAppArgs for i in [:info.numParams] do let tArg := tArgs[i]! let dArg := dArgs[i]! unless (← isDefEq tArg dArg) do failure for i in [info.numParams : tArgs.size] do let tArg := tArgs[i]! let dArg := dArgs[i]! unless (← isDefEq tArg dArg) do return i :: (← goIndex tArg dArg) failure private partial def eraseIndices (type : Expr) : MetaM Expr := do let type' ← whnfD type matchConstInduct type'.getAppFn (fun _ => return type) fun info _ => do let args := type'.getAppArgs let params ← args[:info.numParams].toArray.mapM eraseIndices let result := mkAppN type'.getAppFn params let resultType ← inferType result let (newIndices, _, _) ← forallMetaTelescopeReducing resultType (some (args.size - info.numParams)) return mkAppN result newIndices private def withPatternElabConfig (x : TermElabM α) : TermElabM α := withoutErrToSorry <| withReader (fun ctx => { ctx with inPattern := true }) <| x private def elabPatterns (patternStxs : Array Syntax) (matchType : Expr) : ExceptT PatternElabException TermElabM (Array Expr × Expr) := withReader (fun ctx => { ctx with implicitLambda := false }) do let mut patterns := #[] let mut matchType := matchType for idx in [:patternStxs.size] do let patternStx := patternStxs[idx]! matchType ← whnf matchType match matchType with | Expr.forallE _ d b _ => let pattern ← do let s ← saveState try liftM <| withSynthesize <| withPatternElabConfig <| elabTermEnsuringType patternStx d catch ex : Exception => restoreState s match (← liftM <| commitIfNoErrors? <| withPatternElabConfig do elabTermAndSynthesize patternStx (← eraseIndices d)) with | some pattern => match (← findDiscrRefinementPath pattern d |>.run) with | some path => restoreState s -- Wrap the type mismatch exception for the "discriminant refinement" feature. throwThe PatternElabException { ex := ex, patternIdx := idx, pathToIndex := path } | none => restoreState s; throw ex | none => throw ex matchType := b.instantiate1 pattern patterns := patterns.push pattern | _ => throwError "unexpected match type" return (patterns, matchType) open Meta.Match (Pattern Pattern.var Pattern.inaccessible Pattern.ctor Pattern.as Pattern.val Pattern.arrayLit AltLHS MatcherResult) namespace ToDepElimPattern private def throwInvalidPattern (e : Expr) : MetaM α := throwError "invalid pattern {indentExpr e}" structure State where patternVars : Array Expr := #[] structure Context where /-- When visiting an assigned metavariable, if it has an user-name. We save it here. We want to preserve these user-names when generating new pattern variables. -/ userName : Name := Name.anonymous /-- Pattern variables that were explicitly provided by the user. Recall that implicit parameters and `_` are elaborated as metavariables, and then converted into pattern variables by the `normalize` procedure. -/ explicitPatternVars : Array FVarId := #[] abbrev M := ReaderT Context $ StateRefT State TermElabM /-- Return true iff `e` is an explicit pattern variable provided by the user. -/ def isExplicitPatternVar (e : Expr) : M Bool := do if e.isFVar then return (← read).explicitPatternVars.any (· == e.fvarId!) else return false /-- Helper function for "saving" the user name associated with `mvarId` (if it is not "anonymous") before visiting `x` The auto generalization feature will uses synthetic holes to preserve the name of the free variable included during generalization. For example, if we are generalizing a free variable `bla`, we add the synthetic hole `?bla` for the pattern. We use synthetic hole because we don't know whether `?bla` will become an inaccessible pattern or not. The `withMVar` method makes sure we don't "lose" this name when `isDefEq` perform assignments of the form `?bla := ?m` where `?m` has no user name. This can happen, for example, when the user provides a `_` pattern, or for implicit fields. -/ private def withMVar (mvarId : MVarId) (x : M α) : M α := do let localDecl ← getMVarDecl mvarId if !localDecl.userName.isAnonymous && (← read).userName.isAnonymous then withReader (fun ctx => { ctx with userName := localDecl.userName }) x else x /-- Creating a mapping containing `b ↦ e'` where `patternWithRef e' = some (stx, b)`, and `e'` is a subterm of `e`. This is a helper function for `whnfPreservingPatternRef`. -/ private def mkPatternRefMap (e : Expr) : ExprMap Expr := runST go where go (σ) : ST σ (ExprMap Expr) := do let map : ST.Ref σ (ExprMap Expr) ← ST.mkRef {} e.forEachWhere isPatternWithRef fun e => do let some (_, b) := patternWithRef? e | unreachable! map.modify (·.insert b e) map.get /-- Try to restore `Syntax` ref information stored in `map` after applying `whnf` at `whnfPreservingPatternRef`. It assumes `map` has been constructed using `mkPatternRefMap`. -/ private def applyRefMap (e : Expr) (map : ExprMap Expr) : Expr := e.replace fun e => match patternWithRef? e with | some _ => some e -- stop `e` already has annotation | none => match map.find? e with | some eWithRef => some eWithRef -- stop `e` found annotation | none => none -- continue /-- Applies `whnf` but tries to preserve `PatternWithRef` information. This is a bit hackish, but it is necessary for providing proper jump-to-definition information in examples such as ``` def f (x : Nat) : Nat := match x with | 0 => 1 | y + 1 => y ``` Without this trick, the `PatternWithRef` is lost for the `y` at the pattern `y+1`. -/ private def whnfPreservingPatternRef (e : Expr) : MetaM Expr := do let eNew ← whnf e if eNew.isConstructorApp (← getEnv) then return eNew else return applyRefMap eNew (mkPatternRefMap e) /-- Normalize the pattern and collect all patterns variables (explicit and implicit). This method is the one that decides where the inaccessible annotations must be inserted. The pattern variables are both free variables (for explicit pattern variables) and metavariables (for implicit ones). Recall that `mkLambdaFVars` now allows us to abstract both free variables and metavariables. -/ partial def normalize (e : Expr) : M Expr := do match inaccessible? e with | some e => processInaccessible e | none => match patternWithRef? e with | some (ref, e) => return mkPatternWithRef (← normalize e) ref | none => match e.arrayLit? with | some (α, lits) => mkArrayLit α (← lits.mapM normalize) | none => if let some e := Match.isNamedPattern? e then let x := e.getArg! 1 let p := e.getArg! 2 let h := e.getArg! 3 unless x.consumeMData.isFVar && h.consumeMData.isFVar do throwError "unexpected occurrence of auxiliary declaration 'namedPattern'" addVar x let p ← normalize p addVar h return mkApp4 e.getAppFn (e.getArg! 0) x p h else if isMatchValue e then return e else if e.isFVar then if (← isExplicitPatternVar e) then processVar e else return mkInaccessible e else if e.getAppFn.isMVar then let eNew ← instantiateMVars e if eNew != e then withMVar e.getAppFn.mvarId! <| normalize eNew else if e.isMVar then withMVar e.mvarId! <| processVar e else throwInvalidPattern e else let eNew ← whnfPreservingPatternRef e if eNew != e then normalize eNew else matchConstCtor e.getAppFn (fun _ => return mkInaccessible (← eraseInaccessibleAnnotations (← instantiateMVars e))) (fun v _ => do let args := e.getAppArgs unless args.size == v.numParams + v.numFields do throwInvalidPattern e let params := args.extract 0 v.numParams let params ← params.mapM fun p => instantiateMVars p let fields := args.extract v.numParams args.size let fields ← fields.mapM normalize return mkAppN e.getAppFn (params ++ fields)) where addVar (e : Expr) : M Unit := do let e ← erasePatternRefAnnotations e unless (← get).patternVars.contains e do modify fun s => { s with patternVars := s.patternVars.push e } processVar (e : Expr) : M Expr := do let e' ← erasePatternRefAnnotations e if (← get).patternVars.contains e' then return mkInaccessible (← eraseInaccessibleAnnotations e) else if e'.isMVar then e'.mvarId!.setTag (← read).userName modify fun s => { s with patternVars := s.patternVars.push e' } return e processInaccessible (e : Expr) : M Expr := do let e' ← erasePatternRefAnnotations e match e' with | Expr.fvar _ => if (← isExplicitPatternVar e') then processVar e else return mkInaccessible e | _ => if e'.getAppFn.isMVar then let eNew ← instantiateMVars e' if eNew != e' then withMVar e'.getAppFn.mvarId! <| processInaccessible eNew else if e'.isMVar then withMVar e'.mvarId! <| processVar e' else throwInvalidPattern e else return mkInaccessible (← eraseInaccessibleAnnotations (← instantiateMVars e)) /-- Auxiliary function for combining the `matchType` and all patterns into a single expression. We use it before we abstract all patterns variables. -/ private partial def packMatchTypePatterns (matchType : Expr) (ps : Array Expr) : MetaM Expr := ps.foldlM (init := matchType) fun result p => mkAppM ``PProd.mk #[result, p] /-- The inverse of `packMatchTypePatterns`. -/ private partial def unpackMatchTypePatterns (p : Expr) : Expr × Array Expr := if p.isAppOf ``PProd.mk then let (matchType, ps) := unpackMatchTypePatterns (p.getArg! 2) (matchType, ps.push (p.getArg! 3)) else (p, #[]) /-- Convert a (normalized) pattern encoded as an `Expr` into a `Pattern`. This method assumes that `e` has been normalized and the explicit and implicit (i.e., metavariables) pattern variables have already been abstracted and converted back into new free variables. -/ private partial def toPattern (e : Expr) : MetaM Pattern := do match inaccessible? e with | some e => return Pattern.inaccessible e | none => match e.arrayLit? with | some (α, lits) => return Pattern.arrayLit α (← lits.mapM toPattern) | none => if let some e := Match.isNamedPattern? e then let p ← toPattern <| e.getArg! 2 match e.getArg! 1, e.getArg! 3 with | Expr.fvar x, Expr.fvar h => return Pattern.as x p h | _, _ => throwError "unexpected occurrence of auxiliary declaration 'namedPattern'" else if isMatchValue e then return Pattern.val e else if e.isFVar then return Pattern.var e.fvarId! else matchConstCtor e.getAppFn (fun _ => unreachable!) fun v us => do let args := e.getAppArgs let params := args.extract 0 v.numParams let params ← params.mapM fun p => instantiateMVars p let fields := args.extract v.numParams args.size let fields ← fields.mapM toPattern return Pattern.ctor v.name us params.toList fields.toList structure TopSort.State where visitedFVars : FVarIdSet := {} visitedMVars : MVarIdSet := {} result : Array Expr := #[] abbrev TopSortM := StateRefT TopSort.State TermElabM /-- Topological sort. We need it because inaccessible patterns may contain pattern variables that are declared later. That is, processing patterns from left to right to do not guarantee that the pattern variables are collected in the "right" order. "Right" here means pattern `x` must occur befor pattern `y` if `y`s type depends on `x`. -/ private partial def topSort (patternVars : Array Expr) : TermElabM (Array Expr) := do let (_, s) ← patternVars.mapM visit |>.run {} return s.result where visit (e : Expr) : TopSortM Unit := do match e with | Expr.proj _ _ e => visit e | Expr.forallE _ d b _ => visit d; visit b | Expr.lam _ d b _ => visit d; visit b | Expr.letE _ t v b _ => visit t; visit v; visit b | Expr.app f a => visit f; visit a | Expr.mdata _ b => visit b | Expr.mvar mvarId => let v ← instantiateMVars e if !v.isMVar then visit v else if patternVars.contains e then unless (← get).visitedMVars.contains mvarId do modify fun s => { s with visitedMVars := s.visitedMVars.insert mvarId } let mvarDecl ← getMVarDecl mvarId visit mvarDecl.type modify fun s => { s with result := s.result.push e } | Expr.fvar fvarId => if patternVars.contains e then unless (← get).visitedFVars.contains fvarId do modify fun s => { s with visitedFVars := s.visitedFVars.insert fvarId } visit (← fvarId.getType) modify fun s => { s with result := s.result.push e } | _ => return () /-- Save pattern information in the info tree, and remove `patternWithRef?` annotations. -/ partial def savePatternInfo (p : Expr) : TermElabM Expr := go p |>.run false where /-- The `Bool` context is true iff we are inside of an "inaccessible" pattern. -/ go (p : Expr) : ReaderT Bool TermElabM Expr := do match p with | .forallE n d b bi => withLocalDecl n bi (← go d) fun x => do mkForallFVars #[x] (← go (b.instantiate1 x)) | .lam n d b bi => withLocalDecl n bi (← go d) fun x => do mkLambdaFVars #[x] (← go (b.instantiate1 x)) | .letE n t v b .. => withLetDecl n (← go t) (← go v) fun x => do mkLetFVars #[x] (← go (b.instantiate1 x)) | .app f a => return mkApp (← go f) (← go a) | .proj _ _ b => return p.updateProj! (← go b) | .mdata k b => if inaccessible? p |>.isSome then return mkMData k (← withReader (fun _ => false) (go b)) else if let some (stx, p) := patternWithRef? p then Elab.withInfoContext' (go p) fun p => do /- If `p` is a free variable and we are not inside of an "inaccessible" pattern, this `p` is a binder. -/ mkTermInfo Name.anonymous stx p (isBinder := p.isFVar && !(← read)) else return mkMData k (← go b) | _ => return p /-- Main method for `withDepElimPatterns`. - `PatternVarDecls`: are the explicit pattern variables provided by the user. - `ps`: are the patterns provided by the user. - `matchType`: the expected typ for this branch. It depends on the explicit pattern variables and the implicit ones that are still represented as metavariables, and are found by this function. - `k` is the continuation that is executed in an updated local context with the all pattern variables (explicit and implicit). Note that, `patternVarDecls` are all replaced since they may depend on implicit pattern variables (i.e., metavariables) that are converted into new free variables by this method. -/ partial def main (patternVarDecls : Array PatternVarDecl) (ps : Array Expr) (matchType : Expr) (k : Array LocalDecl → Array Pattern → Expr → TermElabM α) : TermElabM α := do let explicitPatternVars := patternVarDecls.map fun decl => decl.fvarId let (ps, s) ← ps.mapM normalize |>.run { explicitPatternVars } |>.run {} let patternVars ← topSort s.patternVars trace[Elab.match] "patternVars after topSort: {patternVars}" for explicit in explicitPatternVars do unless patternVars.any (· == mkFVar explicit) do withInPattern do throwError "invalid patterns, `{mkFVar explicit}` is an explicit pattern variable, but it only occurs in positions that are inaccessible to pattern matching{indentD (MessageData.joinSep (ps.toList.map (MessageData.ofExpr .)) m!"\n\n")}" let packed ← pack patternVars ps matchType trace[Elab.match] "packed: {packed}" let lctx := explicitPatternVars.foldl (init := (← getLCtx)) fun lctx d => lctx.erase d withTheReader Meta.Context (fun ctx => { ctx with lctx := lctx }) do check packed unpack packed fun patternVars patterns matchType => do let localDecls ← patternVars.mapM fun x => x.fvarId!.getDecl trace[Elab.match] "patternVars: {patternVars}, matchType: {matchType}" k localDecls (← patterns.mapM fun p => toPattern p) matchType where pack (patternVars : Array Expr) (ps : Array Expr) (matchType : Expr) : MetaM Expr := do /- Recall that some of the `patternVars` are metavariables without a user facing name. Thus, this method tries to infer names for them using `ps` before performing the `mkLambdaFVars` abstraction. Let `?m` be a metavariable in `patternVars` without a user facing name. The heuristic uses the patterns `ps`. We traverse the patterns from right to left searching for applications `f ... ?m`. The name for the corresponding `f`-parameter is used to name `?m`. We search from right to left to make sure we visit a pattern before visiting its indices. Example: ``` #[@List.cons α i ?m, @HList.cons α β i ?m a as, @Member.head α i ?m] ``` -/ let setMVarsAt (e : Expr) : StateRefT (Array MVarId) MetaM Unit := do let mvarIds ← setMVarUserNamesAt (← erasePatternRefAnnotations e) patternVars modify (· ++ mvarIds) let go : StateRefT (Array MVarId) MetaM Expr := do try for p in ps.reverse do setMVarsAt p mkLambdaFVars patternVars (← packMatchTypePatterns matchType ps) (binderInfoForMVars := BinderInfo.default) finally resetMVarUserNames (← get) go |>.run' #[] unpack (packed : Expr) (k : (patternVars : Array Expr) → (patterns : Array Expr) → (matchType : Expr) → TermElabM α) : TermElabM α := let rec go (packed : Expr) (patternVars : Array Expr) : TermElabM α := do match packed with | .lam n d b _ => withLocalDeclD n (← erasePatternRefAnnotations (← eraseInaccessibleAnnotations d)) fun patternVar => go (b.instantiate1 patternVar) (patternVars.push patternVar) | _ => let (matchType, patterns) := unpackMatchTypePatterns packed let matchType ← erasePatternRefAnnotations (← eraseInaccessibleAnnotations matchType) let patterns ← patterns.mapM (savePatternInfo ·) k patternVars patterns matchType go packed #[] end ToDepElimPattern def withDepElimPatterns (patternVarDecls : Array PatternVarDecl) (ps : Array Expr) (matchType : Expr) (k : Array LocalDecl → Array Pattern → Expr → TermElabM α) : TermElabM α := do ToDepElimPattern.main patternVarDecls ps matchType k private def withElaboratedLHS {α} (ref : Syntax) (patternVarDecls : Array PatternVarDecl) (patternStxs : Array Syntax) (matchType : Expr) (k : AltLHS → Expr → TermElabM α) : ExceptT PatternElabException TermElabM α := do let (patterns, matchType) ← withSynthesize <| elabPatterns patternStxs matchType id (α := TermElabM α) do trace[Elab.match] "patterns: {patterns}" withDepElimPatterns patternVarDecls patterns matchType fun localDecls patterns matchType => do k { ref := ref, fvarDecls := localDecls.toList, patterns := patterns.toList } matchType /-- Try to clear the free variables in `toClear` and auxiliary discriminants, and then execute `k` in the updated local context. If `type` or another local variables depends on a free variable in `toClear`, then it is not cleared. -/ private def withToClear (toClear : Array FVarId) (type : Expr) (k : TermElabM α) : TermElabM α := do if toClear.isEmpty then k else let toClear ← sortFVarIds toClear trace[Elab.match] ">> toClear {toClear.map mkFVar}" let mut lctx ← getLCtx let mut localInsts ← getLocalInstances for fvarId in toClear.reverse do if !(← dependsOn type fvarId) then if !(← lctx.anyM fun localDecl => pure (localDecl.fvarId != fvarId) <&&> localDeclDependsOn localDecl fvarId) then lctx := lctx.erase fvarId localInsts := localInsts.filter fun localInst => localInst.fvar.fvarId! != fvarId withLCtx lctx localInsts k /-- Generate equalities `h : discr = pattern` for discriminants annotated with `h :`. We use these equalities to elaborate the right-hand-side of a `match` alternative. -/ private def withEqs (discrs : Array Discr) (patterns : List Pattern) (k : Array Expr → TermElabM α) : TermElabM α := do go 0 patterns #[] where go (i : Nat) (ps : List Pattern) (eqs : Array Expr) : TermElabM α := do match ps with | [] => k eqs | p::ps => if h : i < discrs.size then let discr := discrs.get ⟨i, h⟩ if let some h := discr.h? then withLocalDeclD h.getId (← mkEqHEq discr.expr (← p.toExpr)) fun eq => do addTermInfo' h eq (isBinder := true) go (i+1) ps (eqs.push eq) else go (i+1) ps eqs else k eqs /-- Elaborate the `match` alternative `alt` using the given `matchType`. The array `toClear` contains variables that must be cleared before elaborating the `rhs` because they have been generalized/refined. -/ private def elabMatchAltView (discrs : Array Discr) (alt : MatchAltView) (matchType : Expr) (toClear : Array FVarId) : ExceptT PatternElabException TermElabM (AltLHS × Expr) := withRef alt.ref do let (patternVars, alt) ← collectPatternVars alt trace[Elab.match] "patternVars: {patternVars}" withPatternVars patternVars fun patternVarDecls => do withElaboratedLHS alt.ref patternVarDecls alt.patterns matchType fun altLHS matchType => withEqs discrs altLHS.patterns fun eqs => withLocalInstances altLHS.fvarDecls do trace[Elab.match] "elabMatchAltView: {matchType}" -- connect match-generalized pattern fvars, which are a suffix of `latLHS.fvarDecls`, -- to their original fvars (independently of whether they were cleared successfully) in the info tree for (fvar, baseId) in altLHS.fvarDecls.toArray.reverse.zip toClear.reverse do pushInfoLeaf <| .ofFVarAliasInfo { id := fvar.fvarId, baseId, userName := fvar.userName } let matchType ← instantiateMVars matchType -- If `matchType` is of the form `@m ...`, we create a new metavariable with the current scope. -- This improves the effectiveness of the `isDefEq` default approximations let matchType' ← if matchType.getAppFn.isMVar then mkFreshTypeMVar else pure matchType withToClear toClear matchType' do let rhs ← elabTermEnsuringType alt.rhs matchType' -- We use all approximations to ensure the auxiliary type is defeq to the original one. unless (← fullApproxDefEq <| isDefEq matchType' matchType) do throwError "type mistmatch, alternative {← mkHasTypeButIsExpectedMsg matchType' matchType}" let xs := altLHS.fvarDecls.toArray.map LocalDecl.toExpr ++ eqs let rhs ← if xs.isEmpty then pure <| mkSimpleThunk rhs else mkLambdaFVars xs rhs trace[Elab.match] "rhs: {rhs}" return (altLHS, rhs) /-- Collect problematic index for the "discriminant refinement feature". This method is invoked when we detect a type mismatch at a pattern #`idx` of some alternative. -/ private partial def getIndexToInclude? (discr : Expr) (pathToIndex : List Nat) : TermElabM (Option Expr) := do go (← inferType discr) pathToIndex |>.run where go (e : Expr) (path : List Nat) : OptionT MetaM Expr := do match path with | [] => return e | i::path => let e ← whnfD e guard <| e.isApp && i < e.getAppNumArgs go (e.getArg! i) path structure GeneralizeResult where discrs : Array Discr /-- `FVarId`s of the variables that have been generalized. We store them to clear after in each branch. -/ toClear : Array FVarId := #[] matchType : Expr altViews : Array MatchAltView refined : Bool := false /-- "Generalize" variables that depend on the discriminants. Remarks and limitations: - We currently do not generalize let-decls. - We abort generalization if the new `matchType` is type incorrect. - Only discriminants that are free variables are considered during specialization. - We "generalize" by adding new discriminants and pattern variables. We do not "clear" the generalized variables, but they become inaccessible since they are shadowed by the patterns variables. We assume this is ok since this is the exact behavior users would get if they had written it by hand. Recall there is no `clear` in term mode. -/ private def generalize (discrs : Array Discr) (matchType : Expr) (altViews : Array MatchAltView) (generalizing? : Option Bool) : TermElabM GeneralizeResult := do let gen := if let some g := generalizing? then g else true if !gen then return { discrs, matchType, altViews } else let discrExprs := discrs.map (·.expr) /- let-decls are currently being ignored by the generalizer. -/ let ysFVarIds ← getFVarsToGeneralize discrExprs (ignoreLetDecls := true) if ysFVarIds.isEmpty then return { discrs, matchType, altViews } else let ys := ysFVarIds.map mkFVar let matchType' ← forallBoundedTelescope matchType discrs.size fun ds type => do let type ← mkForallFVars ys type let (discrs', ds') := Array.unzip <| Array.zip discrExprs ds |>.filter fun (di, _) => di.isFVar let type := type.replaceFVars discrs' ds' mkForallFVars ds type if (← isTypeCorrect matchType') then let discrs := discrs ++ ys.map fun y => { expr := y : Discr } let altViews ← altViews.mapM fun altView => do let patternVars ← getPatternsVars altView.patterns -- We traverse backwards because we want to keep the most recent names. -- For example, if `ys` contains `#[h, h]`, we want to make sure `mkFreshUsername is applied to the first `h`, -- since it is already shadowed by the second. let ysUserNames ← ys.foldrM (init := #[]) fun ys ysUserNames => do let yDecl ← ys.fvarId!.getDecl let mut yUserName := yDecl.userName if ysUserNames.contains yUserName then yUserName ← mkFreshUserName yUserName -- Explicitly provided pattern variables shadow `y` else if patternVars.any fun x => x.getId == yUserName then yUserName ← mkFreshUserName yUserName return ysUserNames.push yUserName let ysIds ← ysUserNames.reverse.mapM fun n => return mkIdentFrom (← getRef) n return { altView with patterns := altView.patterns ++ ysIds } return { discrs, toClear := ysFVarIds, matchType := matchType', altViews, refined := true } else return { discrs, matchType, altViews } private partial def elabMatchAltViews (generalizing? : Option Bool) (discrs : Array Discr) (matchType : Expr) (altViews : Array MatchAltView) : TermElabM (Array Discr × Expr × Array (AltLHS × Expr) × Bool) := do loop discrs #[] matchType altViews none where /-- "Discriminant refinement" main loop. `first?` contains the first error message we found before updated the `discrs`. -/ loop (discrs : Array Discr) (toClear : Array FVarId) (matchType : Expr) (altViews : Array MatchAltView) (first? : Option (SavedState × Exception)) : TermElabM (Array Discr × Expr × Array (AltLHS × Expr) × Bool) := do let s ← saveState let { discrs := discrs', toClear := toClear', matchType := matchType', altViews := altViews', refined } ← generalize discrs matchType altViews generalizing? match (← altViews'.mapM (fun altView => elabMatchAltView discrs' altView matchType' (toClear ++ toClear')) |>.run) with | Except.ok alts => return (discrs', matchType', alts, first?.isSome || refined) | Except.error { patternIdx := patternIdx, pathToIndex := pathToIndex, ex := ex } => let discr := discrs[patternIdx]! let some index ← getIndexToInclude? discr.expr pathToIndex | throwEx (← updateFirst first? ex) trace[Elab.match] "index to include: {index}" if (← discrs.anyM fun discr => isDefEq discr.expr index) then throwEx (← updateFirst first? ex) let first ← updateFirst first? ex s.restore (restoreInfo := true) let indices ← collectDeps #[index] (discrs.map (·.expr)) let matchType ← try updateMatchType indices matchType catch _ => throwEx first let ref ← getRef trace[Elab.match] "new indices to add as discriminants: {indices}" let wildcards ← indices.mapM fun index => do if index.isFVar then let localDecl ← index.fvarId!.getDecl if localDecl.userName.hasMacroScopes then return mkHole ref else let id := mkIdentFrom ref localDecl.userName `(?$id) else return mkHole ref let altViews := altViews.map fun altView => { altView with patterns := wildcards ++ altView.patterns } let indDiscrs ← indices.mapM fun i => do match discr.h? with | none => return { expr := i : Discr } | some h => -- If the discriminant that introduced this index is annotated with `h : discr`, then we should annotate the new discriminant too. let h := mkIdentFrom h (← mkFreshUserName `h) return { expr := i, h? := h : Discr } let discrs := indDiscrs ++ discrs let indexFVarIds := indices.filterMap fun | .fvar fvarId .. => some fvarId | _ => none loop discrs (toClear ++ indexFVarIds) matchType altViews first throwEx {α} (p : SavedState × Exception) : TermElabM α := do p.1.restore (restoreInfo := true); throw p.2 updateFirst (first? : Option (SavedState × Exception)) (ex : Exception) : TermElabM (SavedState × Exception) := do match first? with | none => return (← saveState, ex) | some first => return first containsFVar (es : Array Expr) (fvarId : FVarId) : Bool := es.any fun e => e.isFVar && e.fvarId! == fvarId /-- Update `indices` by including any free variable `x` s.t. - Type of some `discr` depends on `x`. - Type of `x` depends on some free variable in `indices`. If we don't include these extra variables in indices, then `updateMatchType` will generate a type incorrect term. For example, suppose `discr` contains `h : @HEq α a α b`, and `indices` is `#[α, b]`, and `matchType` is `@HEq α a α b → B`. `updateMatchType indices matchType` produces the type `(α' : Type) → (b : α') → @HEq α' a α' b → B` which is type incorrect because we have `a : α`. The method `collectDeps` will include `a` into `indices`. This method does not handle dependencies among non-free variables. We rely on the type checking method `check` at `updateMatchType`. Remark: `indices : Array Expr` does not need to be an array anymore. We should cleanup this code, and use `index : Expr` instead. -/ collectDeps (indices : Array Expr) (discrs : Array Expr) : TermElabM (Array Expr) := do let mut s : CollectFVars.State := {} for discr in discrs do s := collectFVars s (← instantiateMVars (← inferType discr)) let (indicesFVar, indicesNonFVar) := indices.split Expr.isFVar let indicesFVar := indicesFVar.map Expr.fvarId! let mut toAdd := #[] for fvarId in s.fvarSet.toList do unless containsFVar discrs fvarId || containsFVar indices fvarId do let localDecl ← fvarId.getDecl for indexFVarId in indicesFVar do if (← localDeclDependsOn localDecl indexFVarId) then toAdd := toAdd.push fvarId let indicesFVar ← sortFVarIds (indicesFVar ++ toAdd) return indicesFVar.map mkFVar ++ indicesNonFVar updateMatchType (indices : Array Expr) (matchType : Expr) : TermElabM Expr := do let matchType ← indices.foldrM (init := matchType) fun index matchType => do let indexType ← inferType index let matchTypeBody ← kabstract matchType index let userName ← mkUserNameFor index return Lean.mkForall userName BinderInfo.default indexType matchTypeBody check matchType return matchType def mkMatcher (input : Meta.Match.MkMatcherInput) : TermElabM MatcherResult := Meta.Match.mkMatcher input register_builtin_option match.ignoreUnusedAlts : Bool := { defValue := false descr := "if true, do not generate error if an alternative is not used" } def reportMatcherResultErrors (altLHSS : List AltLHS) (result : MatcherResult) : TermElabM Unit := do unless result.counterExamples.isEmpty do withHeadRefOnly <| logError m!"missing cases:\n{Meta.Match.counterExamplesToMessageData result.counterExamples}" return () unless match.ignoreUnusedAlts.get (← getOptions) || result.unusedAltIdxs.isEmpty do let mut i := 0 for alt in altLHSS do if result.unusedAltIdxs.contains i then withRef alt.ref do logError "redundant alternative" i := i + 1 /-- If `altLHSS + rhss` is encoding `| PUnit.unit => rhs[0]`, return `rhs[0]` Otherwise, return none. -/ private def isMatchUnit? (altLHSS : List Match.AltLHS) (rhss : Array Expr) : MetaM (Option Expr) := do assert! altLHSS.length == rhss.size match altLHSS with | [ { fvarDecls := [], patterns := [ Pattern.ctor `PUnit.unit .. ], .. } ] => /- Recall that for alternatives of the form `| PUnit.unit => rhs`, `rhss[0]` is of the form `fun _ : Unit => b`. -/ match rhss[0]! with | Expr.lam _ _ b _ => return if b.hasLooseBVars then none else b | _ => return none | _ => return none private def elabMatchAux (generalizing? : Option Bool) (discrStxs : Array Syntax) (altViews : Array MatchAltView) (matchOptMotive : Syntax) (expectedType : Expr) : TermElabM Expr := do let mut generalizing? := generalizing? if !matchOptMotive.isNone then if generalizing? == some true then throwError "the '(generalizing := true)' parameter is not supported when the 'match' motive is explicitly provided" generalizing? := some false let (discrs, matchType, altLHSS, isDep, rhss) ← commitIfDidNotPostpone do let ⟨discrs, matchType, isDep, altViews⟩ ← elabMatchTypeAndDiscrs discrStxs matchOptMotive altViews expectedType let matchAlts ← liftMacroM <| expandMacrosInPatterns altViews trace[Elab.match] "matchType: {matchType}" let (discrs, matchType, alts, refined) ← elabMatchAltViews generalizing? discrs matchType matchAlts let isDep := isDep || refined /- We should not use `synthesizeSyntheticMVarsNoPostponing` here. Otherwise, we will not be able to elaborate examples such as: ``` def f (x : Nat) : Option Nat := none def g (xs : List (Nat × Nat)) : IO Unit := xs.forM fun x => match f x.fst with | _ => pure () ``` If `synthesizeSyntheticMVarsNoPostponing`, the example above fails at `x.fst` because the type of `x` is only available after we proces the last argument of `List.forM`. We apply pending default types to make sure we can process examples such as ``` let (a, b) := (0, 0) ``` -/ synthesizeSyntheticMVarsUsingDefault let rhss := alts.map Prod.snd let matchType ← instantiateMVars matchType let altLHSS ← alts.toList.mapM fun alt => do let altLHS ← Match.instantiateAltLHSMVars alt.1 /- Remark: we try to postpone before throwing an error. The combinator `commitIfDidNotPostpone` ensures we backtrack any updates that have been performed. The quick-check `waitExpectedTypeAndDiscrs` minimizes the number of scenarios where we have to postpone here. Here is an example that passes the `waitExpectedTypeAndDiscrs` test, but postpones here. ``` def bad (ps : Array (Nat × Nat)) : Array (Nat × Nat) := (ps.filter fun (p : Prod _ _) => match p with | (x, y) => x == 0) ++ ps ``` When we try to elaborate `fun (p : Prod _ _) => ...` for the first time, we haven't propagated the type of `ps` yet because `Array.filter` has type `{α : Type u_1} → (α → Bool) → (as : Array α) → optParam Nat 0 → optParam Nat (Array.size as) → Array α` However, the partial type annotation `(p : Prod _ _)` makes sure we succeed at the quick-check `waitExpectedTypeAndDiscrs`. -/ withRef altLHS.ref do for d in altLHS.fvarDecls do if d.hasExprMVar then tryPostpone withExistingLocalDecls altLHS.fvarDecls do runPendingTacticsAt d.type if (← instantiateMVars d.type).hasExprMVar then throwMVarError m!"invalid match-expression, type of pattern variable '{d.toExpr}' contains metavariables{indentExpr d.type}" for p in altLHS.patterns do if (← Match.instantiatePatternMVars p).hasExprMVar then tryPostpone withExistingLocalDecls altLHS.fvarDecls do throwMVarError m!"invalid match-expression, pattern contains metavariables{indentExpr (← p.toExpr)}" pure altLHS return (discrs, matchType, altLHSS, isDep, rhss) if let some r ← if isDep then pure none else isMatchUnit? altLHSS rhss then return r else let numDiscrs := discrs.size let matcherName ← mkAuxName `match let matcherResult ← mkMatcher { matcherName, matchType, discrInfos := discrs.map fun discr => { hName? := discr.h?.map (·.getId) }, lhss := altLHSS } reportMatcherResultErrors altLHSS matcherResult matcherResult.addMatcher let motive ← forallBoundedTelescope matchType numDiscrs fun xs matchType => mkLambdaFVars xs matchType let r := mkApp matcherResult.matcher motive let r := mkAppN r (discrs.map (·.expr)) let r := mkAppN r rhss trace[Elab.match] "result: {r}" return r -- leading_parser "match " >> optional generalizingParam >> optional motive >> sepBy1 matchDiscr ", " >> " with " >> ppDedent matchAlts private def getDiscrs (matchStx : Syntax) : Array Syntax := matchStx[3].getSepArgs private def getMatchOptMotive (matchStx : Syntax) : Syntax := matchStx[2] open TSyntax.Compat in private def expandNonAtomicDiscrs? (matchStx : Syntax) : TermElabM (Option Syntax) := let matchOptMotive := getMatchOptMotive matchStx if matchOptMotive.isNone then do let discrs := getDiscrs matchStx let allLocal ← discrs.allM fun discr => isAtomicDiscr discr[1] if allLocal then return none else let rec loop (discrs : List Syntax) (discrsNew : Array Syntax) := do match discrs with | [] => let discrs := Syntax.mkSep discrsNew (mkAtomFrom matchStx ", ") pure (matchStx.setArg 3 discrs) | discr :: discrs => -- Recall that -- matchDiscr := leading_parser optional (ident >> ":") >> termParser let term := discr[1] if (← isAtomicDiscr term) then loop discrs (discrsNew.push discr) else withFreshMacroScope do let discrNew := discr.setArg 1 (← `(?x)) let r ← loop discrs (discrsNew.push discrNew) `(let_mvar% ?x := $term; $r) return some (← loop discrs.toList #[]) else -- We do not pull non atomic discriminants when match type is provided explicitly by the user return none private def waitExpectedType (expectedType? : Option Expr) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? match expectedType? with | some expectedType => pure expectedType | none => mkFreshTypeMVar private def tryPostponeIfDiscrTypeIsMVar (matchStx : Syntax) : TermElabM Unit := do -- We don't wait for the discriminants types when match type is provided by user if getMatchOptMotive matchStx |>.isNone then let discrs := getDiscrs matchStx for discr in discrs do let term := discr[1] let d ← elabTerm term none let dType ← inferType d trace[Elab.match] "discr {d} : {← instantiateMVars dType}" tryPostponeIfMVar dType /-- We (try to) elaborate a `match` only when the expected type is available. If the `matchType` has not been provided by the user, we also try to postpone elaboration if the type of a discriminant is not available. That is, it is of the form `(?m ...)`. We use `expandNonAtomicDiscrs?` to make sure all discriminants are metavariables, so that they are not elaborated twice. This is a standard trick we use in the elaborator, and it is also used to elaborate structure instances. Suppose, we are trying to elaborate ``` match g x with | ... => ... ``` `expandNonAtomicDiscrs?` converts it intro ``` let_mvar% ?discr := g x match ?discr with | ... => ... ``` This elaboration technique is needed to elaborate terms such as: ```lean xs.filter fun (a, b) => a > b ``` which are syntax sugar for ```lean List.filter (fun p => match p with | (a, b) => a > b) xs ``` When we visit `match p with | (a, b) => a > b`, we don't know the type of `p` yet. -/ private def waitExpectedTypeAndDiscrs (matchStx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? tryPostponeIfDiscrTypeIsMVar matchStx match expectedType? with | some expectedType => return expectedType | none => mkFreshTypeMVar /-- ``` leading_parser "match " >> optional generalizingParam >> optional motive >> sepBy1 matchDiscr ", " >> " with " >> ppDedent matchAlts ``` Remark the `optIdent` must be `none` at `matchDiscr`. They are expanded by `expandMatchDiscr?`. -/ private def elabMatchCore (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do let expectedType ← waitExpectedTypeAndDiscrs stx expectedType? let discrStxs := (getDiscrs stx).map fun d => d let gen? := getMatchGeneralizing? stx let altViews := getMatchAlts stx let matchOptMotive := getMatchOptMotive stx elabMatchAux gen? discrStxs altViews matchOptMotive expectedType private def isPatternVar (stx : Syntax) : TermElabM Bool := do match (← resolveId? stx "pattern") with | none => return isAtomicIdent stx | some f => match f with | Expr.const fName _ => match (← getEnv).find? fName with | some (ConstantInfo.ctorInfo _) => return false | some _ => return !hasMatchPatternAttribute (← getEnv) fName | _ => return isAtomicIdent stx | _ => return isAtomicIdent stx where isAtomicIdent (stx : Syntax) : Bool := stx.isIdent && stx.getId.eraseMacroScopes.isAtomic @[builtin_term_elab «match»] def elabMatch : TermElab := fun stx expectedType? => do match stx with | `(match $discr:term with | $y:ident => $rhs) => if (← isPatternVar y) then expandSimpleMatch stx discr y rhs expectedType? else elabMatchDefault stx expectedType? | _ => elabMatchDefault stx expectedType? where elabMatchDefault (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do match (← liftMacroM <| expandMatchAlts? stx) with | some stxNew => withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? | none => match (← expandNonAtomicDiscrs? stx) with | some stxNew => withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? | none => let discrs := getDiscrs stx let matchOptMotive := getMatchOptMotive stx if !matchOptMotive.isNone && discrs.any fun d => !d[0].isNone then throwErrorAt matchOptMotive "match motive should not be provided when discriminants with equality proofs are used" elabMatchCore stx expectedType? builtin_initialize registerTraceClass `Elab.match -- leading_parser:leadPrec "nomatch " >> termParser @[builtin_term_elab «nomatch»] def elabNoMatch : TermElab := fun stx expectedType? => do match stx with | `(nomatch $discrExpr) => if (← isAtomicDiscr discrExpr) then let expectedType ← waitExpectedType expectedType? let discr := mkNode ``Lean.Parser.Term.matchDiscr #[mkNullNode, discrExpr] elabMatchAux none #[discr] #[] mkNullNode expectedType else let stxNew ← `(let_mvar% ?x := $discrExpr; nomatch ?x) withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? | _ => throwUnsupportedSyntax end Lean.Elab.Term
9071a1e707ee5ece314fef8b4a2f8771dba499f1
4727251e0cd73359b15b664c3170e5d754078599
/src/logic/equiv/embedding.lean
e73af659e8869dc6c711e4b7738999cdaadc2aa8
[ "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,748
lean
/- Copyright (c) 2021 Eric Rodriguez. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Rodriguez -/ import logic.embedding /-! # Equivalences on embeddings This file shows some advanced equivalences on embeddings, useful for constructing larger embeddings from smaller ones. -/ open function.embedding namespace equiv /-- Embeddings from a sum type are equivalent to two separate embeddings with disjoint ranges. -/ def sum_embedding_equiv_prod_embedding_disjoint {α β γ : Type*} : ((α ⊕ β) ↪ γ) ≃ {f : (α ↪ γ) × (β ↪ γ) // disjoint (set.range f.1) (set.range f.2)} := { to_fun := λ f, ⟨(inl.trans f, inr.trans f), begin rintros _ ⟨⟨a, h⟩, ⟨b, rfl⟩⟩, simp only [trans_apply, inl_apply, inr_apply] at h, have : sum.inl a = sum.inr b := f.injective h, simp only at this, assumption end⟩, inv_fun := λ ⟨⟨f, g⟩, disj⟩, ⟨λ x, match x with | (sum.inl a) := f a | (sum.inr b) := g b end, begin rintros (a₁|b₁) (a₂|b₂) f_eq; simp only [equiv.coe_fn_symm_mk, sum.elim_inl, sum.elim_inr] at f_eq, { rw f.injective f_eq }, { simp! only at f_eq, exfalso, exact disj ⟨⟨a₁, by simp⟩, ⟨b₂, by simp [f_eq]⟩⟩ }, { simp! only at f_eq, exfalso, exact disj ⟨⟨a₂, by simp⟩, ⟨b₁, by simp [f_eq]⟩⟩ }, { rw g.injective f_eq } end⟩, left_inv := λ f, by { dsimp only, ext, cases x; simp! }, right_inv := λ ⟨⟨f, g⟩, _⟩, by { simp only [prod.mk.inj_iff], split; ext; simp! } } /-- Embeddings whose range lies within a set are equivalent to embeddings to that set. This is `function.embedding.cod_restrict` as an equiv. -/ def cod_restrict (α : Type*) {β : Type*} (bs : set β) : {f : α ↪ β // ∀ a, f a ∈ bs} ≃ (α ↪ bs) := { to_fun := λ f, (f : α ↪ β).cod_restrict bs f.prop, inv_fun := λ f, ⟨f.trans (function.embedding.subtype _), λ a, (f a).prop⟩, left_inv := λ x, by ext; refl, right_inv := λ x, by ext; refl } /-- Pairs of embeddings with disjoint ranges are equivalent to a dependent sum of embeddings, in which the second embedding cannot take values in the range of the first. -/ def prod_embedding_disjoint_equiv_sigma_embedding_restricted {α β γ : Type*} : {f : (α ↪ γ) × (β ↪ γ) // disjoint (set.range f.1) (set.range f.2)} ≃ (Σ f : α ↪ γ, β ↪ ↥((set.range f)ᶜ)) := (subtype_prod_equiv_sigma_subtype $ λ (a : α ↪ γ) (b : β ↪ _), disjoint (set.range a) (set.range b)).trans $ equiv.sigma_congr_right $ λ a, (subtype_equiv_prop begin ext f, rw [←set.range_subset_iff, set.subset_compl_iff_disjoint], exact disjoint.comm.trans disjoint_iff, end).trans (cod_restrict _ _) /-- A combination of the above results, allowing us to turn one embedding over a sum type into two dependent embeddings, the second of which avoids any members of the range of the first. This is helpful for constructing larger embeddings out of smaller ones. -/ def sum_embedding_equiv_sigma_embedding_restricted {α β γ : Type*} : ((α ⊕ β) ↪ γ) ≃ (Σ f : α ↪ γ, β ↪ ↥((set.range f)ᶜ)) := equiv.trans sum_embedding_equiv_prod_embedding_disjoint prod_embedding_disjoint_equiv_sigma_embedding_restricted /-- Embeddings from a single-member type are equivalent to members of the target type. -/ def unique_embedding_equiv_result {α β : Type*} [unique α] : (α ↪ β) ≃ β := { to_fun := λ f, f default, inv_fun := λ x, ⟨λ _, x, λ _ _ _, subsingleton.elim _ _⟩, left_inv := λ _, by { ext, simp_rw [function.embedding.coe_fn_mk], congr }, right_inv := λ _, by simp } end equiv
b19ca88f8a1f78a5bfd6b64543848fa128df32c6
4727251e0cd73359b15b664c3170e5d754078599
/src/algebra/add_torsor.lean
8e7e9a2fe99824e5295ffe6f446d079015568dfa
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
14,551
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Yury Kudryashov -/ import data.set.pointwise /-! # Torsors of additive group actions This file defines torsors of additive group actions. ## Notations The group elements are referred to as acting on points. This file defines the notation `+ᵥ` for adding a group element to a point and `-ᵥ` for subtracting two points to produce a group element. ## Implementation notes Affine spaces are the motivating example of torsors of additive group actions. It may be appropriate to refactor in terms of the general definition of group actions, via `to_additive`, when there is a use for multiplicative torsors (currently mathlib only develops the theory of group actions for multiplicative group actions). ## Notations * `v +ᵥ p` is a notation for `has_vadd.vadd`, the left action of an additive monoid; * `p₁ -ᵥ p₂` is a notation for `has_vsub.vsub`, difference between two points in an additive torsor as an element of the corresponding additive group; ## References * https://en.wikipedia.org/wiki/Principal_homogeneous_space * https://en.wikipedia.org/wiki/Affine_space -/ /-- An `add_torsor G P` gives a structure to the nonempty type `P`, acted on by an `add_group G` with a transitive and free action given by the `+ᵥ` operation and a corresponding subtraction given by the `-ᵥ` operation. In the case of a vector space, it is an affine space. -/ class add_torsor (G : out_param Type*) (P : Type*) [out_param $ add_group G] extends add_action G P, has_vsub G P := [nonempty : nonempty P] (vsub_vadd' : ∀ (p1 p2 : P), (p1 -ᵥ p2 : G) +ᵥ p2 = p1) (vadd_vsub' : ∀ (g : G) (p : P), g +ᵥ p -ᵥ p = g) attribute [instance, priority 100, nolint dangerous_instance] add_torsor.nonempty attribute [nolint dangerous_instance] add_torsor.to_has_vsub /-- An `add_group G` is a torsor for itself. -/ @[nolint instance_priority] instance add_group_is_add_torsor (G : Type*) [add_group G] : add_torsor G G := { vsub := has_sub.sub, vsub_vadd' := sub_add_cancel, vadd_vsub' := add_sub_cancel } /-- Simplify subtraction for a torsor for an `add_group G` over itself. -/ @[simp] lemma vsub_eq_sub {G : Type*} [add_group G] (g1 g2 : G) : g1 -ᵥ g2 = g1 - g2 := rfl section general variables {G : Type*} {P : Type*} [add_group G] [T : add_torsor G P] include T /-- Adding the result of subtracting from another point produces that point. -/ @[simp] lemma vsub_vadd (p1 p2 : P) : p1 -ᵥ p2 +ᵥ p2 = p1 := add_torsor.vsub_vadd' p1 p2 /-- Adding a group element then subtracting the original point produces that group element. -/ @[simp] lemma vadd_vsub (g : G) (p : P) : g +ᵥ p -ᵥ p = g := add_torsor.vadd_vsub' g p /-- If the same point added to two group elements produces equal results, those group elements are equal. -/ lemma vadd_right_cancel {g1 g2 : G} (p : P) (h : g1 +ᵥ p = g2 +ᵥ p) : g1 = g2 := by rw [←vadd_vsub g1, h, vadd_vsub] @[simp] lemma vadd_right_cancel_iff {g1 g2 : G} (p : P) : g1 +ᵥ p = g2 +ᵥ p ↔ g1 = g2 := ⟨vadd_right_cancel p, λ h, h ▸ rfl⟩ /-- Adding a group element to the point `p` is an injective function. -/ lemma vadd_right_injective (p : P) : function.injective ((+ᵥ p) : G → P) := λ g1 g2, vadd_right_cancel p /-- Adding a group element to a point, then subtracting another point, produces the same result as subtracting the points then adding the group element. -/ lemma vadd_vsub_assoc (g : G) (p1 p2 : P) : g +ᵥ p1 -ᵥ p2 = g + (p1 -ᵥ p2) := begin apply vadd_right_cancel p2, rw [vsub_vadd, add_vadd, vsub_vadd] end /-- Subtracting a point from itself produces 0. -/ @[simp] lemma vsub_self (p : P) : p -ᵥ p = (0 : G) := by rw [←zero_add (p -ᵥ p), ←vadd_vsub_assoc, vadd_vsub] /-- If subtracting two points produces 0, they are equal. -/ lemma eq_of_vsub_eq_zero {p1 p2 : P} (h : p1 -ᵥ p2 = (0 : G)) : p1 = p2 := by rw [←vsub_vadd p1 p2, h, zero_vadd] /-- Subtracting two points produces 0 if and only if they are equal. -/ @[simp] lemma vsub_eq_zero_iff_eq {p1 p2 : P} : p1 -ᵥ p2 = (0 : G) ↔ p1 = p2 := iff.intro eq_of_vsub_eq_zero (λ h, h ▸ vsub_self _) lemma vsub_ne_zero {p q : P} : p -ᵥ q ≠ (0 : G) ↔ p ≠ q := not_congr vsub_eq_zero_iff_eq /-- Cancellation adding the results of two subtractions. -/ @[simp] lemma vsub_add_vsub_cancel (p1 p2 p3 : P) : p1 -ᵥ p2 + (p2 -ᵥ p3) = (p1 -ᵥ p3) := begin apply vadd_right_cancel p3, rw [add_vadd, vsub_vadd, vsub_vadd, vsub_vadd] end /-- Subtracting two points in the reverse order produces the negation of subtracting them. -/ @[simp] lemma neg_vsub_eq_vsub_rev (p1 p2 : P) : -(p1 -ᵥ p2) = (p2 -ᵥ p1) := begin refine neg_eq_of_add_eq_zero_right (vadd_right_cancel p1 _), rw [vsub_add_vsub_cancel, vsub_self], end lemma vadd_vsub_eq_sub_vsub (g : G) (p q : P) : g +ᵥ p -ᵥ q = g - (q -ᵥ p) := by rw [vadd_vsub_assoc, sub_eq_add_neg, neg_vsub_eq_vsub_rev] /-- Subtracting the result of adding a group element produces the same result as subtracting the points and subtracting that group element. -/ lemma vsub_vadd_eq_vsub_sub (p1 p2 : P) (g : G) : p1 -ᵥ (g +ᵥ p2) = (p1 -ᵥ p2) - g := by rw [←add_right_inj (p2 -ᵥ p1 : G), vsub_add_vsub_cancel, ←neg_vsub_eq_vsub_rev, vadd_vsub, ←add_sub_assoc, ←neg_vsub_eq_vsub_rev, neg_add_self, zero_sub] /-- Cancellation subtracting the results of two subtractions. -/ @[simp] lemma vsub_sub_vsub_cancel_right (p1 p2 p3 : P) : (p1 -ᵥ p3) - (p2 -ᵥ p3) = (p1 -ᵥ p2) := by rw [←vsub_vadd_eq_vsub_sub, vsub_vadd] /-- Convert between an equality with adding a group element to a point and an equality of a subtraction of two points with a group element. -/ lemma eq_vadd_iff_vsub_eq (p1 : P) (g : G) (p2 : P) : p1 = g +ᵥ p2 ↔ p1 -ᵥ p2 = g := ⟨λ h, h.symm ▸ vadd_vsub _ _, λ h, h ▸ (vsub_vadd _ _).symm⟩ lemma vadd_eq_vadd_iff_neg_add_eq_vsub {v₁ v₂ : G} {p₁ p₂ : P} : v₁ +ᵥ p₁ = v₂ +ᵥ p₂ ↔ - v₁ + v₂ = p₁ -ᵥ p₂ := by rw [eq_vadd_iff_vsub_eq, vadd_vsub_assoc, ← add_right_inj (-v₁), neg_add_cancel_left, eq_comm] namespace set open_locale pointwise @[simp] lemma singleton_vsub_self (p : P) : ({p} : set P) -ᵥ {p} = {(0:G)} := by rw [set.singleton_vsub_singleton, vsub_self] end set @[simp] lemma vadd_vsub_vadd_cancel_right (v₁ v₂ : G) (p : P) : (v₁ +ᵥ p) -ᵥ (v₂ +ᵥ p) = v₁ - v₂ := by rw [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, vsub_self, add_zero] /-- If the same point subtracted from two points produces equal results, those points are equal. -/ lemma vsub_left_cancel {p1 p2 p : P} (h : p1 -ᵥ p = p2 -ᵥ p) : p1 = p2 := by rwa [←sub_eq_zero, vsub_sub_vsub_cancel_right, vsub_eq_zero_iff_eq] at h /-- The same point subtracted from two points produces equal results if and only if those points are equal. -/ @[simp] lemma vsub_left_cancel_iff {p1 p2 p : P} : (p1 -ᵥ p) = p2 -ᵥ p ↔ p1 = p2 := ⟨vsub_left_cancel, λ h, h ▸ rfl⟩ /-- Subtracting the point `p` is an injective function. -/ lemma vsub_left_injective (p : P) : function.injective ((-ᵥ p) : P → G) := λ p2 p3, vsub_left_cancel /-- If subtracting two points from the same point produces equal results, those points are equal. -/ lemma vsub_right_cancel {p1 p2 p : P} (h : p -ᵥ p1 = p -ᵥ p2) : p1 = p2 := begin refine vadd_left_cancel (p -ᵥ p2) _, rw [vsub_vadd, ← h, vsub_vadd] end /-- Subtracting two points from the same point produces equal results if and only if those points are equal. -/ @[simp] lemma vsub_right_cancel_iff {p1 p2 p : P} : p -ᵥ p1 = p -ᵥ p2 ↔ p1 = p2 := ⟨vsub_right_cancel, λ h, h ▸ rfl⟩ /-- Subtracting a point from the point `p` is an injective function. -/ lemma vsub_right_injective (p : P) : function.injective ((-ᵥ) p : P → G) := λ p2 p3, vsub_right_cancel end general section comm variables {G : Type*} {P : Type*} [add_comm_group G] [add_torsor G P] include G /-- Cancellation subtracting the results of two subtractions. -/ @[simp] lemma vsub_sub_vsub_cancel_left (p1 p2 p3 : P) : (p3 -ᵥ p2) - (p3 -ᵥ p1) = (p1 -ᵥ p2) := by rw [sub_eq_add_neg, neg_vsub_eq_vsub_rev, add_comm, vsub_add_vsub_cancel] @[simp] lemma vadd_vsub_vadd_cancel_left (v : G) (p1 p2 : P) : (v +ᵥ p1) -ᵥ (v +ᵥ p2) = p1 -ᵥ p2 := by rw [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub_cancel'] lemma vsub_vadd_comm (p1 p2 p3 : P) : (p1 -ᵥ p2 : G) +ᵥ p3 = p3 -ᵥ p2 +ᵥ p1 := begin rw [←@vsub_eq_zero_iff_eq G, vadd_vsub_assoc, vsub_vadd_eq_vsub_sub], simp end lemma vadd_eq_vadd_iff_sub_eq_vsub {v₁ v₂ : G} {p₁ p₂ : P} : v₁ +ᵥ p₁ = v₂ +ᵥ p₂ ↔ v₂ - v₁ = p₁ -ᵥ p₂ := by rw [vadd_eq_vadd_iff_neg_add_eq_vsub, neg_add_eq_sub] lemma vsub_sub_vsub_comm (p₁ p₂ p₃ p₄ : P) : (p₁ -ᵥ p₂) - (p₃ -ᵥ p₄) = (p₁ -ᵥ p₃) - (p₂ -ᵥ p₄) := by rw [← vsub_vadd_eq_vsub_sub, vsub_vadd_comm, vsub_vadd_eq_vsub_sub] end comm namespace prod variables {G : Type*} {P : Type*} {G' : Type*} {P' : Type*} [add_group G] [add_group G'] [add_torsor G P] [add_torsor G' P'] instance : add_torsor (G × G') (P × P') := { vadd := λ v p, (v.1 +ᵥ p.1, v.2 +ᵥ p.2), zero_vadd := λ p, by simp, add_vadd := by simp [add_vadd], vsub := λ p₁ p₂, (p₁.1 -ᵥ p₂.1, p₁.2 -ᵥ p₂.2), nonempty := prod.nonempty, vsub_vadd' := λ p₁ p₂, show (p₁.1 -ᵥ p₂.1 +ᵥ p₂.1, _) = p₁, by simp, vadd_vsub' := λ v p, show (v.1 +ᵥ p.1 -ᵥ p.1, v.2 +ᵥ p.2 -ᵥ p.2) =v, by simp } @[simp] lemma fst_vadd (v : G × G') (p : P × P') : (v +ᵥ p).1 = v.1 +ᵥ p.1 := rfl @[simp] lemma snd_vadd (v : G × G') (p : P × P') : (v +ᵥ p).2 = v.2 +ᵥ p.2 := rfl @[simp] lemma mk_vadd_mk (v : G) (v' : G') (p : P) (p' : P') : (v, v') +ᵥ (p, p') = (v +ᵥ p, v' +ᵥ p') := rfl @[simp] lemma fst_vsub (p₁ p₂ : P × P') : (p₁ -ᵥ p₂ : G × G').1 = p₁.1 -ᵥ p₂.1 := rfl @[simp] lemma snd_vsub (p₁ p₂ : P × P') : (p₁ -ᵥ p₂ : G × G').2 = p₁.2 -ᵥ p₂.2 := rfl @[simp] lemma mk_vsub_mk (p₁ p₂ : P) (p₁' p₂' : P') : ((p₁, p₁') -ᵥ (p₂, p₂') : G × G') = (p₁ -ᵥ p₂, p₁' -ᵥ p₂') := rfl end prod namespace pi universes u v w variables {I : Type u} {fg : I → Type v} [∀ i, add_group (fg i)] {fp : I → Type w} open add_action add_torsor /-- A product of `add_torsor`s is an `add_torsor`. -/ instance [T : ∀ i, add_torsor (fg i) (fp i)] : add_torsor (Π i, fg i) (Π i, fp i) := { vadd := λ g p, λ i, g i +ᵥ p i, zero_vadd := λ p, funext $ λ i, zero_vadd (fg i) (p i), add_vadd := λ g₁ g₂ p, funext $ λ i, add_vadd (g₁ i) (g₂ i) (p i), vsub := λ p₁ p₂, λ i, p₁ i -ᵥ p₂ i, nonempty := ⟨λ i, classical.choice (T i).nonempty⟩, vsub_vadd' := λ p₁ p₂, funext $ λ i, vsub_vadd (p₁ i) (p₂ i), vadd_vsub' := λ g p, funext $ λ i, vadd_vsub (g i) (p i) } end pi namespace equiv variables {G : Type*} {P : Type*} [add_group G] [add_torsor G P] include G /-- `v ↦ v +ᵥ p` as an equivalence. -/ def vadd_const (p : P) : G ≃ P := { to_fun := λ v, v +ᵥ p, inv_fun := λ p', p' -ᵥ p, left_inv := λ v, vadd_vsub _ _, right_inv := λ p', vsub_vadd _ _ } @[simp] lemma coe_vadd_const (p : P) : ⇑(vadd_const p) = λ v, v+ᵥ p := rfl @[simp] lemma coe_vadd_const_symm (p : P) : ⇑(vadd_const p).symm = λ p', p' -ᵥ p := rfl /-- `p' ↦ p -ᵥ p'` as an equivalence. -/ def const_vsub (p : P) : P ≃ G := { to_fun := (-ᵥ) p, inv_fun := λ v, -v +ᵥ p, left_inv := λ p', by simp, right_inv := λ v, by simp [vsub_vadd_eq_vsub_sub] } @[simp] lemma coe_const_vsub (p : P) : ⇑(const_vsub p) = (-ᵥ) p := rfl @[simp] lemma coe_const_vsub_symm (p : P) : ⇑(const_vsub p).symm = λ v, -v +ᵥ p := rfl variables (P) /-- The permutation given by `p ↦ v +ᵥ p`. -/ def const_vadd (v : G) : equiv.perm P := { to_fun := (+ᵥ) v, inv_fun := (+ᵥ) (-v), left_inv := λ p, by simp [vadd_vadd], right_inv := λ p, by simp [vadd_vadd] } @[simp] lemma coe_const_vadd (v : G) : ⇑(const_vadd P v) = (+ᵥ) v := rfl variable (G) @[simp] lemma const_vadd_zero : const_vadd P (0:G) = 1 := ext $ zero_vadd G variable {G} @[simp] lemma const_vadd_add (v₁ v₂ : G) : const_vadd P (v₁ + v₂) = const_vadd P v₁ * const_vadd P v₂ := ext $ add_vadd v₁ v₂ /-- `equiv.const_vadd` as a homomorphism from `multiplicative G` to `equiv.perm P` -/ def const_vadd_hom : multiplicative G →* equiv.perm P := { to_fun := λ v, const_vadd P v.to_add, map_one' := const_vadd_zero G P, map_mul' := const_vadd_add P } variable {P} open function /-- Point reflection in `x` as a permutation. -/ def point_reflection (x : P) : perm P := (const_vsub x).trans (vadd_const x) lemma point_reflection_apply (x y : P) : point_reflection x y = x -ᵥ y +ᵥ x := rfl @[simp] lemma point_reflection_symm (x : P) : (point_reflection x).symm = point_reflection x := ext $ by simp [point_reflection] @[simp] lemma point_reflection_self (x : P) : point_reflection x x = x := vsub_vadd _ _ lemma point_reflection_involutive (x : P) : involutive (point_reflection x : P → P) := λ y, (equiv.apply_eq_iff_eq_symm_apply _).2 $ by rw point_reflection_symm /-- `x` is the only fixed point of `point_reflection x`. This lemma requires `x + x = y + y ↔ x = y`. There is no typeclass to use here, so we add it as an explicit argument. -/ lemma point_reflection_fixed_iff_of_injective_bit0 {x y : P} (h : injective (bit0 : G → G)) : point_reflection x y = y ↔ y = x := by rw [point_reflection_apply, eq_comm, eq_vadd_iff_vsub_eq, ← neg_vsub_eq_vsub_rev, neg_eq_iff_add_eq_zero, ← bit0, ← bit0_zero, h.eq_iff, vsub_eq_zero_iff_eq, eq_comm] omit G lemma injective_point_reflection_left_of_injective_bit0 {G P : Type*} [add_comm_group G] [add_torsor G P] (h : injective (bit0 : G → G)) (y : P) : injective (λ x : P, point_reflection x y) := λ x₁ x₂ (hy : point_reflection x₁ y = point_reflection x₂ y), by rwa [point_reflection_apply, point_reflection_apply, vadd_eq_vadd_iff_sub_eq_vsub, vsub_sub_vsub_cancel_right, ← neg_vsub_eq_vsub_rev, neg_eq_iff_add_eq_zero, ← bit0, ← bit0_zero, h.eq_iff, vsub_eq_zero_iff_eq] at hy end equiv lemma add_torsor.subsingleton_iff (G P : Type*) [add_group G] [add_torsor G P] : subsingleton G ↔ subsingleton P := begin inhabit P, exact (equiv.vadd_const default).subsingleton_congr, end
d53f482cbdae85e29660c596604e5b1a9078ca15
63abd62053d479eae5abf4951554e1064a4c45b4
/src/topology/metric_space/completion.lean
09dae4769b31cdadea4b7b2331a4c041cbe9d568
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
8,559
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sébastien Gouëzel -/ import topology.uniform_space.completion import topology.metric_space.isometry /-! # The completion of a metric space Completion of uniform spaces are already defined in `topology.uniform_space.completion`. We show here that the uniform space completion of a metric space inherits a metric space structure, by extending the distance to the completion and checking that it is indeed a distance, and that it defines the same uniformity as the already defined uniform structure on the completion -/ open set filter uniform_space uniform_space.completion open_locale filter noncomputable theory universes u variables {α : Type u} [metric_space α] namespace metric /-- The distance on the completion is obtained by extending the distance on the original space, by uniform continuity. -/ instance : has_dist (completion α) := ⟨completion.extension₂ dist⟩ /-- The new distance is uniformly continuous. -/ protected lemma completion.uniform_continuous_dist : uniform_continuous (λp:completion α × completion α, dist p.1 p.2) := uniform_continuous_extension₂ dist /-- The new distance is an extension of the original distance. -/ protected lemma completion.dist_eq (x y : α) : dist (x : completion α) y = dist x y := completion.extension₂_coe_coe uniform_continuous_dist _ _ /- Let us check that the new distance satisfies the axioms of a distance, by starting from the properties on α and extending them to `completion α` by continuity. -/ protected lemma completion.dist_self (x : completion α) : dist x x = 0 := begin apply induction_on x, { refine is_closed_eq _ continuous_const, exact (completion.uniform_continuous_dist.continuous.comp (continuous.prod_mk continuous_id continuous_id) : _) }, { assume a, rw [completion.dist_eq, dist_self] } end protected lemma completion.dist_comm (x y : completion α) : dist x y = dist y x := begin apply induction_on₂ x y, { refine is_closed_eq completion.uniform_continuous_dist.continuous _, exact (completion.uniform_continuous_dist.continuous.comp continuous_swap : _) }, { assume a b, rw [completion.dist_eq, completion.dist_eq, dist_comm] } end protected lemma completion.dist_triangle (x y z : completion α) : dist x z ≤ dist x y + dist y z := begin apply induction_on₃ x y z, { refine is_closed_le _ (continuous.add _ _), { have : continuous (λp : completion α × completion α × completion α, (p.1, p.2.2)) := continuous.prod_mk continuous_fst (continuous.comp continuous_snd continuous_snd), exact (completion.uniform_continuous_dist.continuous.comp this : _) }, { have : continuous (λp : completion α × completion α × completion α, (p.1, p.2.1)) := continuous.prod_mk continuous_fst (continuous_fst.comp continuous_snd), exact (completion.uniform_continuous_dist.continuous.comp this : _) }, { have : continuous (λp : completion α × completion α × completion α, (p.2.1, p.2.2)) := continuous.prod_mk (continuous_fst.comp continuous_snd) (continuous.comp continuous_snd continuous_snd), exact (continuous.comp completion.uniform_continuous_dist.continuous this : _) } }, { assume a b c, rw [completion.dist_eq, completion.dist_eq, completion.dist_eq], exact dist_triangle a b c } end /-- Elements of the uniformity (defined generally for completions) can be characterized in terms of the distance. -/ protected lemma completion.mem_uniformity_dist (s : set (completion α × completion α)) : s ∈ uniformity (completion α) ↔ (∃ε>0, ∀{a b}, dist a b < ε → (a, b) ∈ s) := begin split, { /- Start from an entourage `s`. It contains a closed entourage `t`. Its pullback in α is an entourage, so it contains an ε-neighborhood of the diagonal by definition of the entourages in metric spaces. Then `t` contains an ε-neighborhood of the diagonal in `completion α`, as closed properties pass to the completion. -/ assume hs, rcases mem_uniformity_is_closed hs with ⟨t, ht, ⟨tclosed, ts⟩⟩, have A : {x : α × α | (coe (x.1), coe (x.2)) ∈ t} ∈ uniformity α := uniform_continuous_def.1 (uniform_continuous_coe α) t ht, rcases mem_uniformity_dist.1 A with ⟨ε, εpos, hε⟩, refine ⟨ε, εpos, λx y hxy, _⟩, have : ε ≤ dist x y ∨ (x, y) ∈ t, { apply induction_on₂ x y, { have : {x : completion α × completion α | ε ≤ dist (x.fst) (x.snd) ∨ (x.fst, x.snd) ∈ t} = {p : completion α × completion α | ε ≤ dist p.1 p.2} ∪ t, by ext; simp, rw this, apply is_closed_union _ tclosed, exact is_closed_le continuous_const completion.uniform_continuous_dist.continuous }, { assume x y, rw completion.dist_eq, by_cases h : ε ≤ dist x y, { exact or.inl h }, { have Z := hε (not_le.1 h), simp only [set.mem_set_of_eq] at Z, exact or.inr Z }}}, simp only [not_le.mpr hxy, false_or, not_le] at this, exact ts this }, { /- Start from a set `s` containing an ε-neighborhood of the diagonal in `completion α`. To show that it is an entourage, we use the fact that `dist` is uniformly continuous on `completion α × completion α` (this is a general property of the extension of uniformly continuous functions). Therefore, the preimage of the ε-neighborhood of the diagonal in ℝ is an entourage in `completion α × completion α`. Massaging this property, it follows that the ε-neighborhood of the diagonal is an entourage in `completion α`, and therefore this is also the case of `s`. -/ rintros ⟨ε, εpos, hε⟩, let r : set (ℝ × ℝ) := {p | dist p.1 p.2 < ε}, have : r ∈ uniformity ℝ := metric.dist_mem_uniformity εpos, have T := uniform_continuous_def.1 (@completion.uniform_continuous_dist α _) r this, simp only [uniformity_prod_eq_prod, mem_prod_iff, exists_prop, filter.mem_map, set.mem_set_of_eq] at T, rcases T with ⟨t1, ht1, t2, ht2, ht⟩, refine mem_sets_of_superset ht1 _, have A : ∀a b : completion α, (a, b) ∈ t1 → dist a b < ε, { assume a b hab, have : ((a, b), (a, a)) ∈ set.prod t1 t2 := ⟨hab, refl_mem_uniformity ht2⟩, have I := ht this, simp [completion.dist_self, real.dist_eq, completion.dist_comm] at I, exact lt_of_le_of_lt (le_abs_self _) I }, show t1 ⊆ s, { rintros ⟨a, b⟩ hp, have : dist a b < ε := A a b hp, exact hε this }} end /-- If two points are at distance 0, then they coincide. -/ protected lemma completion.eq_of_dist_eq_zero (x y : completion α) (h : dist x y = 0) : x = y := begin /- This follows from the separation of `completion α` and from the description of entourages in terms of the distance. -/ have : separated_space (completion α) := by apply_instance, refine separated_def.1 this x y (λs hs, _), rcases (completion.mem_uniformity_dist s).1 hs with ⟨ε, εpos, hε⟩, rw ← h at εpos, exact hε εpos end /-- Reformulate `completion.mem_uniformity_dist` in terms that are suitable for the definition of the metric space structure. -/ protected lemma completion.uniformity_dist' : uniformity (completion α) = (⨅ε:{ε : ℝ // 0 < ε}, 𝓟 {p | dist p.1 p.2 < ε.val}) := begin ext s, rw mem_infi, { simp [completion.mem_uniformity_dist, subset_def] }, { rintro ⟨r, hr⟩ ⟨p, hp⟩, use ⟨min r p, lt_min hr hp⟩, simp [lt_min_iff, (≥)] {contextual := tt} } end protected lemma completion.uniformity_dist : uniformity (completion α) = (⨅ ε>0, 𝓟 {p | dist p.1 p.2 < ε}) := by simpa [infi_subtype] using @completion.uniformity_dist' α _ /-- Metric space structure on the completion of a metric space. -/ instance completion.metric_space : metric_space (completion α) := { dist_self := completion.dist_self, eq_of_dist_eq_zero := completion.eq_of_dist_eq_zero, dist_comm := completion.dist_comm, dist_triangle := completion.dist_triangle, to_uniform_space := by apply_instance, uniformity_dist := completion.uniformity_dist } /-- The embedding of a metric space in its completion is an isometry. -/ lemma completion.coe_isometry : isometry (coe : α → completion α) := isometry_emetric_iff_metric.2 completion.dist_eq end metric
283c0391456b2b4bcfbc0ff8c7a17fd94ba572f9
6e8de6b43162bef473b4a0bd93b71db886df98ce
/src/projective_space/classical.lean
3eee1be72f07dc0447cd20ec0b42df01205244a0
[ "Unlicense" ]
permissive
adamtopaz/comb_geom
38ec6fde8d2543f56227ec50cdfb86cac6ac33c1
e16b629d6de3fbdea54a528755e7305dfb51e902
refs/heads/master
1,668,613,552,530
1,593,199,940,000
1,593,199,940,000
269,824,442
6
0
Unlicense
1,593,119,545,000
1,591,404,975,000
Lean
UTF-8
Lean
false
false
4,799
lean
import tactic import linear_algebra import linear_algebra.dimension import ..linear_algebra.lincomb import ..pregeom.basic import ..pregeom.geometrize import ..helpers /--! # What is going on here? In this file, we define the pregeometry instance on a vector space V. Since the vectorspace structure on V depends on the field (a priori V is just an abelian group), this was made a definition and not an instance. See `vector_space.pregeom_instance`. We then define the projective geometry associated to the k-vectorspace V as the geometry associated to this pregeomety. Explicitly, `projectivization k V` is the projectivization of V as a k-vectorspace. It is a geometry in the sense of the definition in `pregeom.basic`. -/ variables (k : Type*) [field k] variables (V : Type*) [add_comm_group V] [module k V] set_option default_priority 100 open_locale classical namespace vector_space open submodule include k /-- A has_cl instance for a k-vectorspace V. Used to define the associated projective geometry. -/ def has_cl_instance : has_cl V := ⟨ λ S, span k S ⟩ local attribute [instance] has_cl_instance /-- A pregeom instance for a k-vectorspace V. Used to define the associated projective geometry. -/ def pregeom_instance : pregeom V := begin split; intros, { exact subset_span }, { exact span_mono a }, { unfold has_cl.cl, rwa span_span, }, { replace a : x ∈ span k (insert y S), by exact a, rw mem_span_insert at a, rcases a with ⟨a,v,w,h⟩, have : a ≠ 0, { intro contra, rw contra at h, replace h : x = v, by rwa [zero_smul,zero_add] at h, rw h at *, contradiction, }, have : a⁻¹ • x + a⁻¹ • -v = y, by calc a⁻¹ • x + a⁻¹ • -v = a⁻¹ • a • y + a⁻¹ • v + a⁻¹ • -v : by rw [h, smul_add] ... = (1 : k) • y + a⁻¹ • v + a⁻¹ • -v : by rw [←mul_smul, inv_mul_cancel this] ... = y : by rw [add_assoc, ←smul_add, one_smul]; simp, rw ←this, set H := span k (insert x S), apply add_mem' H, { apply smul_mem' H, apply subset_span, simp, }, { apply smul_mem' H, apply neg_mem H, have : S ⊆ insert x S, by simp, apply span_mono this, assumption, } }, { unfold has_cl.cl at *, rw ←lcspan.lcspan_eq_span at a, rcases a with ⟨L,hL1,hL2⟩, refine ⟨(lincomb.vects L).to_finset, _ , _⟩, { intros x hx, replace hx : x ∈ (lincomb.vects L).to_finset, by exact hx, rw list.mem_to_finset at hx, exact hL2 hx, }, { rw ←hL1, apply lincomb.mem_span, } } end local attribute [instance] pregeom_instance @[simp] lemma cl_empty : cl (∅ : set V) = {0} := by simp [has_cl.cl] end vector_space open vector_space include k /-- `projectivization k V` is the projectivization of the k-vectorspace V. -/ abbreviation projectivization := @pregeom.geom V (has_cl_instance k V) namespace projectivization instance : geometry (projectivization k V) := @pregeom.geom.geom_instance V (pregeom_instance k V) variable {V} def homogenize {v : V} : v ≠ 0 → projectivization k V := λ hv, @pregeom.geom.to_geom V (vector_space.has_cl_instance k V) ⟨v, by simpa [pregeom.reg_set]⟩ theorem homogenize_eq_iff {v w : V} {hv : v ≠ 0} {hw : w ≠ 0} : homogenize k hv = homogenize k hw ↔ submodule.span k ({v} : set V) = submodule.span k {w} := begin set regs := @pregeom.reg V (vector_space.has_cl_instance k V), change pregeom.geom.to_geom _ = pregeom.geom.to_geom _ ↔ _, rw pregeom.geom.eq_iff, change pregeom.pullback.pcl _ _ = pregeom.pullback.pcl _ _ ↔ _, split; intro h, { replace h := congr_arg (λ A, subtype.val '' A) h, change _ '' _ = _ '' _ at h, conv at h { congr, rw [pregeom.pullback.image_pcl, set.image_singleton], dsimp, skip, rw [pregeom.pullback.image_pcl, set.image_singleton], dsimp, }, change _ ∩ ↑(submodule.span _ _) = _ ∩ ↑(submodule.span _ _) at h, have : v ∈ set.range (subtype.val : regs → V) ∩ ↑(submodule.span k ({v} : set V)), { split, { use v, change v ∉ cl _, rw cl_empty, assumption, }, { apply submodule.subset_span, tauto, } }, rw h at this, cases this with h1 h2, replace h2 : v ∈ submodule.span k ({w} : set V), by exact h2, rw submodule.mem_span_singleton at h2, symmetry, rw submodule.span_singleton_eq_iff, assumption' }, { change _ ⁻¹' ↑(submodule.span _ _) = _ ⁻¹' ↑(submodule.span _ _), repeat {rw set.image_singleton}, rw h } end theorem homogenize_eq_iff' {v w : V} {hv : v ≠ 0} {hw : w ≠ 0} : homogenize k hv = homogenize k hw ↔ ∃ x : k, x • v = w := begin rw homogenize_eq_iff, apply submodule.span_singleton_eq_iff, assumption' end end projectivization
725f6db46c81013476ecc3e19d93f85f0fa04299
80746c6dba6a866de5431094bf9f8f841b043d77
/src/data/quot.lean
e0debdc4db0fc9b00bd52a07889d367e43d42dc7
[ "Apache-2.0" ]
permissive
leanprover-fork/mathlib-backup
8b5c95c535b148fca858f7e8db75a76252e32987
0eb9db6a1a8a605f0cf9e33873d0450f9f0ae9b0
refs/heads/master
1,585,156,056,139
1,548,864,430,000
1,548,864,438,000
143,964,213
0
0
Apache-2.0
1,550,795,966,000
1,533,705,322,000
Lean
UTF-8
Lean
false
false
9,655
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 Quotients -- extends the core library -/ variables {α : Sort*} {β : Sort*} namespace setoid lemma ext {α : Sort*} : ∀{s t : setoid α}, (∀a b, @setoid.r α s a b ↔ @setoid.r α t a b) → s = t | ⟨r, _⟩ ⟨p, _⟩ eq := have r = p, from funext $ assume a, funext $ assume b, propext $ eq a b, by subst this end setoid namespace quot variables {ra : α → α → Prop} {rb : β → β → Prop} {φ : quot ra → quot rb → Sort*} local notation `⟦`:max a `⟧` := quot.mk _ a protected def hrec_on₂ (qa : quot ra) (qb : quot rb) (f : ∀ a b, φ ⟦a⟧ ⟦b⟧) (ca : ∀ {b a₁ a₂}, ra a₁ a₂ → f a₁ b == f a₂ b) (cb : ∀ {a b₁ b₂}, rb b₁ b₂ → f a b₁ == f a b₂) : φ qa qb := quot.hrec_on qa (λ a, quot.hrec_on qb (f a) (λ b₁ b₂ pb, cb pb)) $ λ a₁ a₂ pa, quot.induction_on qb $ λ b, calc @quot.hrec_on _ _ (φ _) ⟦b⟧ (f a₁) (@cb _) == f a₁ b : by simp ... == f a₂ b : ca pa ... == @quot.hrec_on _ _ (φ _) ⟦b⟧ (f a₂) (@cb _) : by simp end quot namespace quotient variables [sa : setoid α] [sb : setoid β] variables {φ : quotient sa → quotient sb → Sort*} protected def hrec_on₂ (qa : quotient sa) (qb : quotient sb) (f : ∀ a b, φ ⟦a⟧ ⟦b⟧) (c : ∀ a₁ b₁ a₂ b₂, a₁ ≈ a₂ → b₁ ≈ b₂ → f a₁ b₁ == f a₂ b₂) : φ qa qb := quot.hrec_on₂ qa qb f (λ _ _ _ p, c _ _ _ _ p (setoid.refl _)) (λ _ _ _ p, c _ _ _ _ (setoid.refl _) p) end quotient @[simp] theorem quotient.eq [r : setoid α] {x y : α} : ⟦x⟧ = ⟦y⟧ ↔ x ≈ y := ⟨quotient.exact, quotient.sound⟩ theorem forall_quotient_iff {α : Type*} [r : setoid α] {p : quotient r → Prop} : (∀a:quotient r, p a) ↔ (∀a:α, p ⟦a⟧) := ⟨assume h x, h _, assume h a, a.induction_on h⟩ @[simp] lemma quotient.lift_beta [s : setoid α] (f : α → β) (h : ∀ (a b : α), a ≈ b → f a = f b) (x : α): quotient.lift f h (quotient.mk x) = f x := rfl @[simp] lemma quotient.lift_on_beta [s : setoid α] (f : α → β) (h : ∀ (a b : α), a ≈ b → f a = f b) (x : α): quotient.lift_on (quotient.mk x) f h = f x := rfl /-- Choose an element of the equivalence class using the axiom of choice. Sound but noncomputable. -/ noncomputable def quot.out {r : α → α → Prop} (q : quot r) : α := classical.some (quot.exists_rep q) /-- Unwrap the VM representation of a quotient to obtain an element of the equivalence class. Computable but unsound. -/ meta def quot.unquot {r : α → α → Prop} : quot r → α := unchecked_cast @[simp] theorem quot.out_eq {r : α → α → Prop} (q : quot r) : quot.mk r q.out = q := classical.some_spec (quot.exists_rep q) /-- Choose an element of the equivalence class using the axiom of choice. Sound but noncomputable. -/ noncomputable def quotient.out [s : setoid α] : quotient s → α := quot.out @[simp] theorem quotient.out_eq [s : setoid α] (q : quotient s) : ⟦q.out⟧ = q := q.out_eq theorem quotient.mk_out [s : setoid α] (a : α) : ⟦a⟧.out ≈ a := quotient.exact (quotient.out_eq _) instance pi_setoid {ι : Sort*} {α : ι → Sort*} [∀ i, setoid (α i)] : setoid (Π i, α i) := { r := λ a b, ∀ i, a i ≈ b i, iseqv := ⟨ λ a i, setoid.refl _, λ a b h i, setoid.symm (h _), λ a b c h₁ h₂ i, setoid.trans (h₁ _) (h₂ _)⟩ } noncomputable def quotient.choice {ι : Type*} {α : ι → Type*} [S : ∀ i, setoid (α i)] (f : ∀ i, quotient (S i)) : @quotient (Π i, α i) (by apply_instance) := ⟦λ i, (f i).out⟧ theorem quotient.choice_eq {ι : Type*} {α : ι → Type*} [∀ i, setoid (α i)] (f : ∀ i, α i) : quotient.choice (λ i, ⟦f i⟧) = ⟦f⟧ := quotient.sound $ λ i, quotient.mk_out _ lemma nonempty_quotient_iff (s : setoid α): nonempty (quotient s) ↔ nonempty α := ⟨assume ⟨a⟩, quotient.induction_on a nonempty.intro, assume ⟨a⟩, ⟨⟦a⟧⟩⟩ /-- `trunc α` is the quotient of `α` by the always-true relation. This is related to the propositional truncation in HoTT, and is similar in effect to `nonempty α`, but unlike `nonempty α`, `trunc α` is data, so the VM representation is the same as `α`, and so this can be used to maintain computability. -/ def {u} trunc (α : Sort u) : Sort u := @quot α (λ _ _, true) theorem true_equivalence : @equivalence α (λ _ _, true) := ⟨λ _, trivial, λ _ _ _, trivial, λ _ _ _ _ _, trivial⟩ namespace trunc /-- Constructor for `trunc α` -/ def mk (a : α) : trunc α := quot.mk _ a /-- Any constant function lifts to a function out of the truncation -/ def lift (f : α → β) (c : ∀ a b : α, f a = f b) : trunc α → β := quot.lift f (λ a b _, c a b) theorem ind {β : trunc α → Prop} : (∀ a : α, β (mk a)) → ∀ q : trunc α, β q := quot.ind protected theorem lift_beta (f : α → β) (c) (a : α) : lift f c (mk a) = f a := rfl @[reducible, elab_as_eliminator] protected def lift_on (q : trunc α) (f : α → β) (c : ∀ a b : α, f a = f b) : β := lift f c q @[elab_as_eliminator] protected theorem induction_on {β : trunc α → Prop} (q : trunc α) (h : ∀ a, β (mk a)) : β q := ind h q theorem exists_rep (q : trunc α) : ∃ a : α, mk a = q := quot.exists_rep q attribute [elab_as_eliminator] protected theorem induction_on₂ {C : trunc α → trunc β → Prop} (q₁ : trunc α) (q₂ : trunc β) (h : ∀ a b, C (mk a) (mk b)) : C q₁ q₂ := trunc.induction_on q₁ $ λ a₁, trunc.induction_on q₂ (h a₁) protected theorem eq (a b : trunc α) : a = b := trunc.induction_on₂ a b (λ x y, quot.sound trivial) instance : subsingleton (trunc α) := ⟨trunc.eq⟩ def bind (q : trunc α) (f : α → trunc β) : trunc β := trunc.lift_on q f (λ a b, trunc.eq _ _) def map (f : α → β) (q : trunc α) : trunc β := bind q (trunc.mk ∘ f) instance : monad trunc := { pure := @trunc.mk, bind := @trunc.bind } instance : is_lawful_monad trunc := { id_map := λ α q, trunc.eq _ _, pure_bind := λ α β q f, rfl, bind_assoc := λ α β γ x f g, trunc.eq _ _ } variable {C : trunc α → Sort*} @[reducible, elab_as_eliminator] protected def rec (f : Π a, C (mk a)) (h : ∀ (a b : α), (eq.rec (f a) (trunc.eq (mk a) (mk b)) : C (mk b)) = f b) (q : trunc α) : C q := quot.rec f (λ a b _, h a b) q @[reducible, elab_as_eliminator] protected def rec_on (q : trunc α) (f : Π a, C (mk a)) (h : ∀ (a b : α), (eq.rec (f a) (trunc.eq (mk a) (mk b)) : C (mk b)) = f b) : C q := trunc.rec f h q @[reducible, elab_as_eliminator] protected def rec_on_subsingleton [∀ a, subsingleton (C (mk a))] (q : trunc α) (f : Π a, C (mk a)) : C q := trunc.rec f (λ a b, subsingleton.elim _ (f b)) q /-- Noncomputably extract a representative of `trunc α` (using the axiom of choice). -/ noncomputable def out : trunc α → α := quot.out @[simp] theorem out_eq (q : trunc α) : mk q.out = q := trunc.eq _ _ end trunc theorem nonempty_of_trunc (q : trunc α) : nonempty α := let ⟨a, _⟩ := q.exists_rep in ⟨a⟩ namespace quotient variables {γ : Sort*} {φ : Sort*} {s₁ : setoid α} {s₂ : setoid β} {s₃ : setoid γ} /- Versions of quotient definitions and lemmas ending in `'` use unification instead of typeclass inference for inferring the `setoid` argument. This is useful when there are several different quotient relations on a type, for example quotient groups, rings and modules -/ protected def mk' (a : α) : quotient s₁ := quot.mk s₁.1 a @[elab_as_eliminator, reducible] protected def lift_on' (q : quotient s₁) (f : α → φ) (h : ∀ a b, @setoid.r α s₁ a b → f a = f b) : φ := quotient.lift_on q f h @[elab_as_eliminator, reducible] protected def lift_on₂' (q₁ : quotient s₁) (q₂ : quotient s₂) (f : α → β → γ) (h : ∀ a₁ a₂ b₁ b₂, @setoid.r α s₁ a₁ b₁ → @setoid.r β s₂ a₂ b₂ → f a₁ a₂ = f b₁ b₂) : γ := quotient.lift_on₂ q₁ q₂ f h @[elab_as_eliminator] protected lemma induction_on' {p : quotient s₁ → Prop} (q : quotient s₁) (h : ∀ a, p (quotient.mk' a)) : p q := quotient.induction_on q h @[elab_as_eliminator] protected lemma induction_on₂' {p : quotient s₁ → quotient s₂ → Prop} (q₁ : quotient s₁) (q₂ : quotient s₂) (h : ∀ a₁ a₂, p (quotient.mk' a₁) (quotient.mk' a₂)) : p q₁ q₂ := quotient.induction_on₂ q₁ q₂ h @[elab_as_eliminator] protected lemma induction_on₃' {p : quotient s₁ → quotient s₂ → quotient s₃ → Prop} (q₁ : quotient s₁) (q₂ : quotient s₂) (q₃ : quotient s₃) (h : ∀ a₁ a₂ a₃, p (quotient.mk' a₁) (quotient.mk' a₂) (quotient.mk' a₃)) : p q₁ q₂ q₃ := quotient.induction_on₃ q₁ q₂ q₃ h lemma exact' {a b : α} : (quotient.mk' a : quotient s₁) = quotient.mk' b → @setoid.r _ s₁ a b := quotient.exact lemma sound' {a b : α} : @setoid.r _ s₁ a b → @quotient.mk' α s₁ a = quotient.mk' b := quotient.sound @[simp] protected lemma eq' {a b : α} : @quotient.mk' α s₁ a = quotient.mk' b ↔ @setoid.r _ s₁ a b := quotient.eq noncomputable def out' (a : quotient s₁) : α := quotient.out a @[simp] theorem out_eq' (q : quotient s₁) : quotient.mk' q.out' = q := q.out_eq theorem mk_out' (a : α) : @setoid.r α s₁ (quotient.mk' a : quotient s₁).out' a := quotient.exact (quotient.out_eq _) end quotient
bba17234fc10b59f469425338bb486caa3558d88
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/tests/lean/interactive/plainGoal.lean
dfa8945e00bbda5b44b1b6461b4510d0a37c021b
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
2,445
lean
example : α → α := by --^ $/lean/plainGoal --^ $/lean/plainGoal intro a --^ $/lean/plainGoal --^ $/lean/plainGoal --v $/lean/plainGoal focus apply a example : α → α := by --^ $/lean/plainGoal example : 0 + n = n := by induction n with | zero => simp; simp --^ $/lean/plainGoal | succ --^ $/lean/plainGoal example : α → α := by intro a; apply a --^ $/lean/plainGoal --^ $/lean/plainGoal --^ $/lean/plainGoal example (h1 : n = m) (h2 : m = 0) : 0 = n := by rw [h1, h2] --^ $/lean/plainGoal --^ $/lean/plainGoal --^ $/lean/plainGoal example : 0 + n = n := by induction n focus --^ $/lean/plainGoal rfl -- TODO: goal state after dedent example : 0 + n = n := by induction n --^ $/lean/plainGoal example : 0 + n = n := by cases n --^ $/lean/plainGoal example : ∀ a b : Nat, a = b := by intro a b --^ $/lean/plainGoal example : α → α := (by --^ $/lean/plainGoal example (p : α → Prop) (a b : α) [DecidablePred p] (h : ∀ {p} [DecidablePred p], p a → p b) : p b := by apply h _ --^ $/lean/plainGoal -- should not display solved goal `⊢ DecidablePred p` example : True ∧ False := by constructor { constructor } --^ $/lean/plainGoal { } --^ $/lean/plainGoal example : True ∧ False := by constructor · constructor --^ $/lean/plainGoal · --^ $/lean/plainGoal theorem left_distrib (t a b : Nat) : t * (a + b) = t * a + t * b := by induction b next => simp next => rw [Nat.add_succ] repeat (rw [Nat.mul_succ]) --^ $/lean/plainGoal example (as bs cs : List α) : (as ++ bs) ++ cs = as ++ (bs ++ cs) := by induction as <;> skip <;> (try rename_i h; simp[h]) <;> rfl --^ $/lean/plainGoal --^ $/lean/plainGoal example : True := (by exact True.intro) --^ $/lean/plainGoal example : True := (by exact True.intro ) --^ $/lean/plainGoal example : True ∧ False := by · constructor; constructor --^ $/lean/plainGoal example : True = True := by conv => --^ $/lean/plainGoal whnf --^ $/lean/plainGoal -- --^ $/lean/plainGoal example : False := by -- EOF test --^ $/lean/plainGoal
02b3fadd051cfa34c1881034f0ba9e61f34a8879
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/Lake/DSL/Require.lean
c4a692156641cfe34eef192399364ce15a301bf6
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
1,790
lean
/- Copyright (c) 2021 Mac Malone. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mac Malone -/ import Lean.Parser.Command import Lake.DSL.Extensions namespace Lake.DSL open Lean Parser Command syntax fromPath := term syntax fromGit := &" git " term:max ("@" term:max)? ("/" term)? syntax depSpec := ident " from " (fromGit <|> fromPath) (" with " term)? def expandDepSpec : TSyntax ``depSpec → MacroM Command | `(depSpec| $name:ident from git $url $[@ $rev?]? $[/ $path?]? $[with $opts?]?) => do let rev ← match rev? with | some rev => `(some $rev) | none => `(none) let path ← match path? with | some path => `(some $path) | none => `(none) let opts := opts?.getD <| ← `({}) `(@[package_dep] def $name : Dependency := { name := $(quote name.getId), src := Source.git $url $rev $path, opts := $opts }) | `(depSpec| $name:ident from $path:term $[with $opts?]?) => do let opts := opts?.getD <| ← `({}) `(@[package_dep] def $name : Dependency := { name := $(quote name.getId), src := Source.path $path, opts := $opts }) | _ => Macro.throwUnsupported /-- Adds a new package dependency to the workspace. Has two forms: ```lean require foo from "path"/"to"/"local"/"package" with NameMap.empty require bar from git "url.git"@"rev"/"optional"/"path-to"/"dir-with-pkg" ``` Either form supports the optional `with` clause. The `@"rev"` and `/"path"/"dir"` parts of the git form of `require` are optional. The elements of both the `from` and `with` clauses are proper terms so normal computation is supported within them (though parentheses made be required to disambiguate the syntax). -/ scoped macro (name := requireDecl) "require " spec:depSpec : command => expandDepSpec spec
163d1a50b72718ab41b1e7fa537cae40b39c0c7c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/testing/slim_check/sampleable.lean
68a46235cb5fdbf94a972495b8223fec267ecf78
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
27,026
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author(s): Simon Hudon -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.lazy_list.basic import Mathlib.data.tree import Mathlib.data.int.basic import Mathlib.control.bifunctor import Mathlib.tactic.linarith.default import Mathlib.testing.slim_check.gen import Mathlib.PostPort universes u_1 u l v w u_2 u_3 namespace Mathlib /-! # `sampleable` Class This class permits the creation samples of a given type controlling the size of those values using the `gen` monad`. It also helps minimize examples by creating smaller versions of given values. When testing a proposition like `∀ n : ℕ, prime n → n ≤ 100`, `slim_check` requires that `ℕ` have an instance of `sampleable` and for `prime n` to be decidable. `slim_check` will then use the instance of `sampleable` to generate small examples of ℕ and progressively increase in size. For each example `n`, `prime n` is tested. If it is false, the example will be rejected (not a test success nor a failure) and `slim_check` will move on to other examples. If `prime n` is true, `n ≤ 100` will be tested. If it is false, `n` is a counter-example of `∀ n : ℕ, prime n → n ≤ 100` and the test fails. If `n ≤ 100` is true, the test passes and `slim_check` moves on to trying more examples. This is a port of the Haskell QuickCheck library. ## Main definitions * `sampleable` class * `sampleable_functor` and `sampleable_bifunctor` class * `sampleable_ext` class ### `sampleable` `sampleable α` provides ways of creating examples of type `α`, and given such an example `x : α`, gives us a way to shrink it and find simpler examples. ### `sampleable_ext` `sampleable_ext` generalizes the behavior of `sampleable` and makes it possible to express instances for types that do not lend themselves to introspection, such as `ℕ → ℕ`. If we test a quantification over functions the counter-examples cannot be shrunken or printed meaningfully. For that purpose, `sampleable_ext` provides a proxy representation `proxy_repr` that can be printed and shrunken as well as interpreted (using `interp`) as an object of the right type. ### `sampleable_functor` and `sampleable_bifunctor` `sampleable_functor F` and `sampleable_bifunctor F` makes it possible to create samples of and shrink `F α` given a sampling function and a shrinking function for arbitrary `α`. This allows us to separate the logic for generating the shape of a collection from the logic for generating its contents. Specifically, the contents could be generated using either `sampleable` or `sampleable_ext` instance and the `sampleable_(bi)functor` does not need to use that information ## Shrinking Shrinking happens when `slim_check` find a counter-example to a property. It is likely that the example will be more complicated than necessary so `slim_check` proceeds to shrink it as much as possible. Although equally valid, a smaller counter-example is easier for a user to understand and use. The `sampleable` class, beside having the `sample` function, has a `shrink` function so that we can use specialized knowledge while shrinking a value. It is not responsible for the whole shrinking process however. It only has to take one step in the shrinking process. `slim_check` will repeatedly call `shrink` until no more steps can be taken. Because `shrink` guarantees that the size of the candidates it produces is strictly smaller than the argument, we know that `slim_check` is guaranteed to terminate. ## Tags random testing ## References * https://hackage.haskell.org/package/QuickCheck -/ namespace slim_check /-- `sizeof_lt x y` compares the sizes of `x` and `y`. -/ def sizeof_lt {α : Sort u_1} [SizeOf α] (x : α) (y : α) := sizeof x < sizeof y /-- `shrink_fn α` is the type of functions that shrink an argument of type `α` -/ def shrink_fn (α : Type u_1) [SizeOf α] := (x : α) → lazy_list (Subtype fun (y : α) => sizeof_lt y x) /-- `sampleable α` provides ways of creating examples of type `α`, and given such an example `x : α`, gives us a way to shrink it and find simpler examples. -/ class sampleable (α : Type u) where wf : SizeOf α sample : gen α shrink : (x : α) → lazy_list (Subtype fun (y : α) => sizeof y < sizeof x) /-- `sampleable_functor F` makes it possible to create samples of and shrink `F α` given a sampling function and a shrinking function for arbitrary `α` -/ class sampleable_functor (F : Type u → Type v) [Functor F] where wf : (α : Type u) → [_inst_1 : SizeOf α] → SizeOf (F α) sample : {α : Type u} → gen α → gen (F α) shrink : (α : Type u) → [_inst_1 : SizeOf α] → shrink_fn α → shrink_fn (F α) p_repr : (α : Type u) → has_repr α → has_repr (F α) /-- `sampleable_bifunctor F` makes it possible to create samples of and shrink `F α β` given a sampling function and a shrinking function for arbitrary `α` and `β` -/ class sampleable_bifunctor (F : Type u → Type v → Type w) [bifunctor F] where wf : (α : Type u) → (β : Type v) → [_inst_1 : SizeOf α] → [_inst_2 : SizeOf β] → SizeOf (F α β) sample : {α : Type u} → {β : Type v} → gen α → gen β → gen (F α β) shrink : (α : Type u) → (β : Type v) → [_inst_1 : SizeOf α] → [_inst_2 : SizeOf β] → shrink_fn α → shrink_fn β → shrink_fn (F α β) p_repr : (α : Type u) → (β : Type v) → has_repr α → has_repr β → has_repr (F α β) /-- This function helps infer the proxy representation and interpretation in `sampleable_ext` instances. -/ /-- `sampleable_ext` generalizes the behavior of `sampleable` and makes it possible to express instances for types that do not lend themselves to introspection, such as `ℕ → ℕ`. If we test a quantification over functions the counter-examples cannot be shrunken or printed meaningfully. For that purpose, `sampleable_ext` provides a proxy representation `proxy_repr` that can be printed and shrunken as well as interpreted (using `interp`) as an object of the right type. -/ class sampleable_ext (α : Sort u) where proxy_repr : Type v wf : SizeOf proxy_repr interp : autoParam (proxy_repr → α) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.slim_check.sampleable.mk_trivial_interp") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "slim_check") "sampleable") "mk_trivial_interp") []) p_repr : has_repr proxy_repr sample : gen proxy_repr shrink : shrink_fn proxy_repr protected instance sampleable_ext.of_sampleable {α : Type u_1} [sampleable α] [has_repr α] : sampleable_ext α := sampleable_ext.mk α (sample α) shrink protected instance sampleable.functor {α : Type u_1} {F : Type u_1 → Type u_2} [Functor F] [sampleable_functor F] [sampleable α] : sampleable (F α) := sampleable.mk (sampleable_functor.sample F (sample α)) (sampleable_functor.shrink α shrink) protected instance sampleable.bifunctor {α : Type u_1} {β : Type u_2} {F : Type u_1 → Type u_2 → Type u_3} [bifunctor F] [sampleable_bifunctor F] [sampleable α] [sampleable β] : sampleable (F α β) := sampleable.mk (sampleable_bifunctor.sample F (sample α) (sample β)) (sampleable_bifunctor.shrink α β shrink shrink) protected instance sampleable_ext.functor {α : Type u_1} {F : Type u_1 → Type u_2} [Functor F] [sampleable_functor F] [sampleable_ext α] : sampleable_ext (F α) := sampleable_ext.mk (F (sampleable_ext.proxy_repr α)) (sampleable_functor.sample F (sampleable_ext.sample α)) (sampleable_functor.shrink (sampleable_ext.proxy_repr α) sampleable_ext.shrink) protected instance sampleable_ext.bifunctor {α : Type u_1} {β : Type u_2} {F : Type u_1 → Type u_2 → Type u_3} [bifunctor F] [sampleable_bifunctor F] [sampleable_ext α] [sampleable_ext β] : sampleable_ext (F α β) := sampleable_ext.mk (F (sampleable_ext.proxy_repr α) (sampleable_ext.proxy_repr β)) (sampleable_bifunctor.sample F (sampleable_ext.sample α) (sampleable_ext.sample β)) (sampleable_bifunctor.shrink (sampleable_ext.proxy_repr α) (sampleable_ext.proxy_repr β) sampleable_ext.shrink sampleable_ext.shrink) /-- `nat.shrink' k n` creates a list of smaller natural numbers by successively dividing `n` by 2 and subtracting the difference from `k`. For example, `nat.shrink 100 = [50, 75, 88, 94, 97, 99]`. -/ def nat.shrink' (k : ℕ) (n : ℕ) : n ≤ k → List (Subtype fun (m : ℕ) => has_well_founded.r m k) → List (Subtype fun (m : ℕ) => has_well_founded.r m k) := sorry /-- `nat.shrink n` creates a list of smaller natural numbers by successively dividing by 2 and subtracting the difference from `n`. For example, `nat.shrink 100 = [50, 75, 88, 94, 97, 99]`. -/ def nat.shrink (n : ℕ) : List (Subtype fun (m : ℕ) => has_well_founded.r m n) := dite (n > 0) (fun (h : n > 0) => (fun (this : ∀ (k : ℕ), 1 < k → n / k < n) => { val := n / bit1 (bit1 (bit0 1)), property := sorry } :: { val := n / bit1 1, property := sorry } :: nat.shrink' n n sorry []) sorry) fun (h : ¬n > 0) => [] /-- Transport a `sampleable` instance from a type `α` to a type `β` using functions between the two, going in both directions. Function `g` is used to define the well-founded order that `shrink` is expected to follow. -/ def sampleable.lift (α : Type u) {β : Type u} [sampleable α] (f : α → β) (g : β → α) (h : ∀ (a : α), sizeof (g (f a)) ≤ sizeof a) : sampleable β := sampleable.mk (f <$> sample α) fun (x : β) => (fun (this : ∀ (a : α), sizeof a < sizeof (g x) → sizeof (g (f a)) < sizeof (g x)) => subtype.map f this <$> shrink (g x)) sorry protected instance nat.sampleable : sampleable ℕ := sampleable.mk (gen.sized fun (sz : ℕ) => gen.freq [(1, coe <$> gen.choose_any (fin (Nat.succ (sz ^ bit1 1)))), (bit1 1, coe <$> gen.choose_any (fin (Nat.succ sz)))] sorry) fun (x : ℕ) => lazy_list.of_list (nat.shrink x) /-- `iterate_shrink p x` takes a decidable predicate `p` and a value `x` of some sampleable type and recursively shrinks `x`. It first calls `shrink x` to get a list of candidate sample, finds the first that satisfies `p` and recursively tries to shrink that one. -/ def iterate_shrink {α : Type} [has_to_string α] [sampleable α] (p : α → Prop) [decidable_pred p] : α → Option α := well_founded.fix sorry fun (x : α) (f_rec : (y : α) → has_well_founded.r y x → Option α) => do trace (string.empty ++ to_string x ++ (string.str (string.str (string.str string.empty (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1))))))) (char.of_nat (bit0 (bit1 (bit0 (bit1 (bit1 1))))))) (char.of_nat (bit0 (bit0 (bit0 (bit0 (bit0 1)))))) ++ to_string (lazy_list.to_list (shrink x)) ++ string.empty)) fun (_ : Unit) => pure Unit.unit let y ← lazy_list.find (fun (a : Subtype fun (y : α) => sizeof y < sizeof x) => p ↑a) (shrink x) f_rec ↑y sorry <|> some (subtype.val y) protected instance fin.sampleable {n : ℕ} [fact (0 < n)] : sampleable (fin n) := sampleable.lift ℕ fin.of_nat' subtype.val sorry protected instance fin.sampleable' {n : ℕ} : sampleable (fin (Nat.succ n)) := sampleable.lift ℕ fin.of_nat subtype.val sorry protected instance pnat.sampleable : sampleable ℕ+ := sampleable.lift ℕ nat.succ_pnat pnat.nat_pred sorry /-- Redefine `sizeof` for `int` to make it easier to use with `nat` -/ def int.has_sizeof : SizeOf ℤ := { sizeOf := int.nat_abs } protected instance int.sampleable : sampleable ℤ := sampleable.mk (gen.sized fun (sz : ℕ) => gen.freq [(1, subtype.val <$> gen.choose (-(↑sz ^ bit1 1 + 1)) (↑sz ^ bit1 1 + 1) sorry), (bit1 1, subtype.val <$> gen.choose (-(↑sz + 1)) (↑sz + 1) sorry)] sorry) fun (x : ℤ) => lazy_list.of_list (list.bind (nat.shrink (int.nat_abs x)) fun (_x : Subtype fun (m : ℕ) => has_well_founded.r m (int.nat_abs x)) => sorry) protected instance bool.sampleable : sampleable Bool := sampleable.mk (do let x ← gen.choose_any Bool return x) fun (b : Bool) => dite (↥b) (fun (h : ↥b) => lazy_list.singleton { val := false, property := sorry }) fun (h : ¬↥b) => lazy_list.nil /-- Provided two shrinking functions `prod.shrink` shrinks a pair `(x, y)` by first shrinking `x` and pairing the results with `y` and then shrinking `y` and pairing the results with `x`. All pairs either contain `x` untouched or `y` untouched. We rely on shrinking being repeated for `x` to get maximally shrunken and then for `y` to get shrunken too. -/ def prod.shrink {α : Type u_1} {β : Type u_2} [SizeOf α] [SizeOf β] (shr_a : shrink_fn α) (shr_b : shrink_fn β) : shrink_fn (α × β) := sorry protected instance prod.sampleable : sampleable_bifunctor Prod := sampleable_bifunctor.mk (fun (α : Type u) (β : Type v) (sama : gen α) (samb : gen β) => do uliftable.up sama sorry) prod.shrink prod.has_repr protected instance sigma.sampleable {α : Type u_1} {β : Type u_2} [sampleable α] [sampleable β] : sampleable (sigma fun (_x : α) => β) := sampleable.lift (α × β) (fun (_x : α × β) => sorry) (fun (_x : sigma fun (_x : α) => β) => sorry) sorry /-- shrinking function for sum types -/ def sum.shrink {α : Type u_1} {β : Type u_2} [SizeOf α] [SizeOf β] (shrink_α : shrink_fn α) (shrink_β : shrink_fn β) : shrink_fn (α ⊕ β) := sorry protected instance sum.sampleable : sampleable_bifunctor sum := sampleable_bifunctor.mk (fun (α : Type u) (β : Type v) (sam_α : gen α) (sam_β : gen β) => uliftable.up_map sum.inl sam_α <|> uliftable.up_map sum.inr sam_β) (fun (α : Type u) (β : Type v) (Iα : SizeOf α) (Iβ : SizeOf β) (shr_α : shrink_fn α) (shr_β : shrink_fn β) => sum.shrink shr_α shr_β) sum.has_repr protected instance rat.sampleable : sampleable ℚ := sampleable.lift (ℤ × ℕ+) (fun (x : ℤ × ℕ+) => prod.cases_on x rat.mk_pnat) (fun (r : ℚ) => (rat.num r, { val := rat.denom r, property := rat.pos r })) sorry /-- `sampleable_char` can be specialized into customized `sampleable char` instances. The resulting instance has `1 / length` chances of making an unrestricted choice of characters and it otherwise chooses a character from `characters` with uniform probabilities. -/ def sampleable_char (length : ℕ) (characters : string) : sampleable char := sampleable.mk (do let x ← gen.choose_nat 0 length sorry ite (subtype.val x = 0) (do let n ← sample ℕ pure (char.of_nat n)) (do let i ← gen.choose_nat 0 (string.length characters - 1) sorry pure (string.iterator.curr (string.iterator.nextn (string.mk_iterator characters) ↑i)))) fun (_x : char) => lazy_list.nil protected instance char.sampleable : sampleable char := sorry theorem list.sizeof_drop_lt_sizeof_of_lt_length {α : Type u} [SizeOf α] {xs : List α} {k : ℕ} (hk : 0 < k) (hk' : k < list.length xs) : sizeof (list.drop k xs) < sizeof xs := sorry theorem list.sizeof_cons_lt_right {α : Type u} [SizeOf α] (a : α) (b : α) {xs : List α} (h : sizeof a < sizeof b) : sizeof (a :: xs) < sizeof (b :: xs) := sorry theorem list.sizeof_cons_lt_left {α : Type u} [SizeOf α] (x : α) {xs : List α} {xs' : List α} (h : sizeof xs < sizeof xs') : sizeof (x :: xs) < sizeof (x :: xs') := sorry theorem list.sizeof_append_lt_left {α : Type u} [SizeOf α] {xs : List α} {ys : List α} {ys' : List α} (h : sizeof ys < sizeof ys') : sizeof (xs ++ ys) < sizeof (xs ++ ys') := sorry theorem list.one_le_sizeof {α : Type u} [SizeOf α] (xs : List α) : 1 ≤ sizeof xs := sorry /-- `list.shrink_removes` shrinks a list by removing chunks of size `k` in the middle of the list. -/ def list.shrink_removes {α : Type u} [SizeOf α] (k : ℕ) (hk : 0 < k) (xs : List α) (n : ℕ) : n = list.length xs → lazy_list (Subtype fun (ys : List α) => sizeof_lt ys xs) := sorry /-- `list.shrink_one xs` shrinks list `xs` by shrinking only one item in the list. -/ def list.shrink_one {α : Type u} [SizeOf α] (shr : (x : α) → lazy_list (Subtype fun (y : α) => sizeof_lt y x)) : shrink_fn (List α) := sorry /-- `list.shrink_with shrink_f xs` shrinks `xs` by first considering `xs` with chunks removed in the middle (starting with chunks of size `xs.length` and halving down to `1`) and then shrinks only one element of the list. This strategy is taken directly from Haskell's QuickCheck -/ def list.shrink_with {α : Type u} [SizeOf α] (shr : (x : α) → lazy_list (Subtype fun (y : α) => sizeof_lt y x)) (xs : List α) : lazy_list (Subtype fun (ys : List α) => sizeof_lt ys xs) := let n : ℕ := list.length xs; lazy_list.append (lazy_list.bind (lazy_list.cons n fun (_ : Unit) => lazy_list.map subtype.val (lazy_list.reverse (shrink n))) fun (k : ℕ) => dite (0 < k) (fun (hk : 0 < k) => list.shrink_removes k hk xs n rfl) fun (hk : ¬0 < k) => lazy_list.nil) fun (_ : Unit) => list.shrink_one shr xs protected instance list.sampleable : sampleable_functor List := sampleable_functor.mk (fun (α : Type u) (sam_α : gen α) => gen.list_of sam_α) (fun (α : Type u) (Iα : SizeOf α) (shr_α : shrink_fn α) => list.shrink_with shr_α) list.has_repr protected instance prop.sampleable_ext : sampleable_ext Prop := sampleable_ext.mk Bool (gen.choose_any Bool) fun (_x : Bool) => lazy_list.nil /-- `no_shrink` is a type annotation to signal that a certain type is not to be shrunk. It can be useful in combination with other types: e.g. `xs : list (no_shrink ℤ)` will result in the list being cut down but individual integers being kept as is. -/ def no_shrink (α : Type u_1) := α protected instance no_shrink.inhabited {α : Type u_1} [Inhabited α] : Inhabited (no_shrink α) := { default := Inhabited.default } /-- Introduction of the `no_shrink` type. -/ def no_shrink.mk {α : Type u_1} (x : α) : no_shrink α := x /-- Selector of the `no_shrink` type. -/ def no_shrink.get {α : Type u_1} (x : no_shrink α) : α := x protected instance no_shrink.sampleable {α : Type u_1} [sampleable α] : sampleable (no_shrink α) := sampleable.mk (no_shrink.mk <$> sample α) fun (_x : no_shrink α) => lazy_list.nil protected instance string.sampleable : sampleable string := sampleable.mk (do let x ← gen.list_of (sample char) pure (list.as_string x)) shrink /-- implementation of `sampleable (tree α)` -/ def tree.sample {α : Type u} (sample : gen α) : ℕ → gen (tree α) := sorry /-- `rec_shrink x f_rec` takes the recursive call `f_rec` introduced by `well_founded.fix` and turns it into a shrinking function whose result is adequate to use in a recursive call. -/ def rec_shrink {α : Type u_1} [SizeOf α] (t : α) (sh : (x : α) → sizeof_lt x t → lazy_list (Subtype fun (y : α) => sizeof_lt y x)) : shrink_fn (Subtype fun (t' : α) => sizeof_lt t' t) := sorry theorem tree.one_le_sizeof {α : Type u_1} [SizeOf α] (t : tree α) : 1 ≤ sizeof t := sorry protected instance tree.functor : Functor tree := { map := tree.map, mapConst := fun (α β : Type u_1) => tree.map ∘ function.const β } /-- Recursion principle for shrinking tree-like structures. -/ def rec_shrink_with {α : Type u} [SizeOf α] (shrink_a : (x : α) → shrink_fn (Subtype fun (y : α) => sizeof_lt y x) → List (lazy_list (Subtype fun (y : α) => sizeof_lt y x))) : shrink_fn α := well_founded.fix (sizeof_measure_wf α) fun (t : α) (f_rec : (y : α) → sizeof_measure α y t → lazy_list (Subtype fun (y_1 : α) => sizeof_lt y_1 y)) => lazy_list.join (lazy_list.of_list (shrink_a t fun (_x : Subtype fun (y : α) => sizeof_lt y t) => sorry)) theorem rec_shrink_with_eq {α : Type u} [SizeOf α] (shrink_a : (x : α) → shrink_fn (Subtype fun (y : α) => sizeof_lt y x) → List (lazy_list (Subtype fun (y : α) => sizeof_lt y x))) (x : α) : rec_shrink_with shrink_a x = lazy_list.join (lazy_list.of_list (shrink_a x fun (t' : Subtype fun (y : α) => sizeof_lt y x) => rec_shrink x (fun (x_1 : α) (h' : sizeof_lt x_1 x) => rec_shrink_with shrink_a x_1) t')) := sorry /-- `tree.shrink_with shrink_f t` shrinks `xs` by using the empty tree, each subtrees, and by shrinking the subtree to recombine them. This strategy is taken directly from Haskell's QuickCheck -/ def tree.shrink_with {α : Type u} [SizeOf α] (shrink_a : shrink_fn α) : shrink_fn (tree α) := rec_shrink_with fun (t : tree α) => sorry protected instance sampleable_tree : sampleable_functor tree := sampleable_functor.mk (fun (α : Type u_1) (sam_α : gen α) => gen.sized (tree.sample sam_α)) (fun (α : Type u_1) (Iα : SizeOf α) (shr_α : shrink_fn α) => tree.shrink_with shr_α) tree.has_repr /-- Type tag that signals to `slim_check` to use small values for a given type. -/ def small (α : Type u_1) := α /-- Add the `small` type tag -/ def small.mk {α : Type u_1} (x : α) : small α := x /-- Type tag that signals to `slim_check` to use large values for a given type. -/ def large (α : Type u_1) := α /-- Add the `large` type tag -/ def large.mk {α : Type u_1} (x : α) : large α := x protected instance small.functor : Functor small := applicative.to_functor protected instance large.functor : Functor large := applicative.to_functor protected instance small.inhabited {α : Type u} [Inhabited α] : Inhabited (small α) := { default := Inhabited.default } protected instance large.inhabited {α : Type u} [Inhabited α] : Inhabited (large α) := { default := Inhabited.default } protected instance small.sampleable_functor : sampleable_functor small := sampleable_functor.mk (fun (α : Type u_1) (samp : gen α) => gen.resize (fun (n : ℕ) => n / bit1 (bit0 1) + bit1 (bit0 1)) samp) (fun (α : Type u_1) (_x : SizeOf α) => id) fun (α : Type u_1) => id protected instance large.sampleable_functor : sampleable_functor large := sampleable_functor.mk (fun (α : Type u_1) (samp : gen α) => gen.resize (fun (n : ℕ) => n * bit1 (bit0 1)) samp) (fun (α : Type u_1) (_x : SizeOf α) => id) fun (α : Type u_1) => id protected instance ulift.sampleable_functor : sampleable_functor ulift := sampleable_functor.mk (fun (α : Type v) (samp : gen α) => uliftable.up_map ulift.up samp) (fun (α : Type v) (_x : SizeOf α) (shr : shrink_fn α) (_x : ulift α) => sorry) fun (α : Type v) (h : has_repr α) => has_repr.mk (repr ∘ ulift.down) /-! ## Subtype instances The following instances are meant to improve the testing of properties of the form `∀ i j, i ≤ j, ...` The naive way to test them is to choose two numbers `i` and `j` and check that the proper ordering is satisfied. Instead, the following instances make it so that `j` will be chosen with considerations to the required ordering constraints. The benefit is that we will not have to discard any choice of `j`. -/ /-! ### Subtypes of `ℕ` -/ protected instance nat_le.sampleable {y : ℕ} : sampleable (Subtype fun (x : ℕ) => x ≤ y) := sampleable.mk (do gen.choose_nat 0 y sorry sorry) fun (_x : Subtype fun (x : ℕ) => x ≤ y) => sorry protected instance nat_ge.sampleable {x : ℕ} : sampleable (Subtype fun (y : ℕ) => x ≤ y) := sampleable.mk (do sample ℕ sorry) fun (_x : Subtype fun (y : ℕ) => x ≤ y) => sorry /- there is no `nat_lt.sampleable` instance because if `y = 0`, there is no valid choice to satisfy `x < y` -/ protected instance nat_gt.sampleable {x : ℕ} : sampleable (Subtype fun (y : ℕ) => x < y) := sampleable.mk (do sample ℕ sorry) fun (x_1 : Subtype fun (y : ℕ) => x < y) => shrink x_1 /-! ### Subtypes of any `linear_ordered_add_comm_group` -/ protected instance le.sampleable {α : Type u} {y : α} [sampleable α] [linear_ordered_add_comm_group α] : sampleable (Subtype fun (x : α) => x ≤ y) := sampleable.mk (do let x ← sample α pure { val := y - abs x, property := sorry }) fun (_x : Subtype fun (x : α) => x ≤ y) => lazy_list.nil protected instance ge.sampleable {α : Type u} {x : α} [sampleable α] [linear_ordered_add_comm_group α] : sampleable (Subtype fun (y : α) => x ≤ y) := sampleable.mk (do let y ← sample α pure { val := x + abs y, property := sorry }) fun (_x : Subtype fun (y : α) => x ≤ y) => lazy_list.nil /-! ### Subtypes of `ℤ` Specializations of `le.sampleable` and `ge.sampleable` for `ℤ` to help instance search. -/ protected instance int_le.sampleable {y : ℤ} : sampleable (Subtype fun (x : ℤ) => x ≤ y) := sampleable.lift ℕ (fun (n : ℕ) => { val := y - ↑n, property := sorry }) (fun (_x : Subtype fun (x : ℤ) => x ≤ y) => sorry) sorry protected instance int_ge.sampleable {x : ℤ} : sampleable (Subtype fun (y : ℤ) => x ≤ y) := sampleable.lift ℕ (fun (n : ℕ) => { val := x + ↑n, property := sorry }) (fun (_x : Subtype fun (y : ℤ) => x ≤ y) => sorry) sorry protected instance int_lt.sampleable {y : ℤ} : sampleable (Subtype fun (x : ℤ) => x < y) := sampleable.lift ℕ (fun (n : ℕ) => { val := y - (↑n + 1), property := sorry }) (fun (_x : Subtype fun (x : ℤ) => x < y) => sorry) sorry protected instance int_gt.sampleable {x : ℤ} : sampleable (Subtype fun (y : ℤ) => x < y) := sampleable.lift ℕ (fun (n : ℕ) => { val := x + (↑n + 1), property := sorry }) (fun (_x : Subtype fun (y : ℤ) => x < y) => sorry) sorry /-! ### Subtypes of any `list` -/ protected instance perm.slim_check {α : Type u} {xs : List α} : sampleable (Subtype fun (ys : List α) => xs ~ ys) := sampleable.mk (gen.permutation_of xs) fun (_x : Subtype fun (ys : List α) => xs ~ ys) => lazy_list.nil protected instance perm'.slim_check {α : Type u} {xs : List α} : sampleable (Subtype fun (ys : List α) => ys ~ xs) := sampleable.mk (subtype.map id list.perm.symm <$> gen.permutation_of xs) fun (_x : Subtype fun (ys : List α) => ys ~ xs) => lazy_list.nil /-- Print (at most) 10 samples of a given type to stdout for debugging. -/ def print_samples {t : Type u} [has_repr t] (g : gen t) : io Unit := do let xs ← io.run_rand (uliftable.down (do let xs ← mmap (reader_t.run g ∘ ulift.up) (list.range (bit0 (bit1 (bit0 1)))) pure (ulift.up (list.map repr xs)))) mmap' io.put_str_ln xs
8f3da8c88edb2b49afee33040068a3fb22328388
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/dotNotationRecDecl.lean
b8be9327247123fe84d1961aabde3183ee07d496
[ "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
56
lean
def foo.aux := 1 def foo : Nat → Nat | n => foo.aux
13b7b92ce4681657062be20ea489fea8b2655a34
200d3d1df35af2ce65dc9bd0f6c7a2819fe40f1c
/main.lean
c9315f5a7bb5af8ab6e4e0d87718724c93df9a4e
[ "Apache-2.0" ]
permissive
stop-cran/calkin_wilf_trees
ef4ed5afeaff3006d2fe25ae95541e329c9ad064
59fc72262c4053b70a18f1ff6f37d1a2241b5443
refs/heads/master
1,593,224,293,613
1,564,563,664,000
1,564,563,664,000
199,818,636
0
0
null
null
null
null
UTF-8
Lean
false
false
4,156
lean
inductive compare : Type | eq | lt | gt def compare_dec : ℕ → ℕ → compare | 0 0 := compare.eq | 0 (nat.succ n) := compare.lt | (nat.succ m) 0 := compare.gt | (nat.succ m) (nat.succ n) := compare_dec m n def compare_dec_eq_iff : Π (m n : ℕ), compare_dec m n = compare.eq ↔ m = n := begin intros m, induction m; intro n; split; intro H; cases n; try { trivial }, congr, exact (m_ih n).mp H, apply (m_ih n).mpr, injection H end def compare_dec_lt_iff : Π (m n : ℕ), compare_dec m n = compare.lt ↔ m < n := begin intros m, induction m; intro n; split; intro H; cases n; try { trivial }; try { exfalso; exact (nat.not_succ_le_zero _ H)}, apply nat.zero_lt_succ, apply nat.succ_lt_succ, exact (m_ih _).mp H, apply (m_ih _).mpr, exact nat.lt_of_succ_lt_succ H end def compare_dec_gt_iff : Π (m n : ℕ), compare_dec m n = compare.gt ↔ m > n := begin intros m, induction m; intro n; split; intro H; cases n; try { trivial }; try { exfalso; exact (nat.not_succ_le_zero _ H)}, apply nat.zero_lt_succ, apply nat.succ_lt_succ, exact (m_ih _).mp H, apply (m_ih _).mpr, exact nat.lt_of_succ_lt_succ H end inductive calkin_wilf : Type | cw_one : calkin_wilf | cw_left : calkin_wilf → calkin_wilf | cw_right : calkin_wilf → calkin_wilf open calkin_wilf inductive cw_rational : Type | cw_zero : cw_rational | cw_pos : calkin_wilf → cw_rational | cw_neg : calkin_wilf → cw_rational lemma sub_lt2 {m n : ℕ} : m > 0 → n > m → n - m < n := begin intros Hm Hn, cases m, exfalso; exact (nat.not_succ_le_zero _ Hm), cases n, exfalso; exact (nat.not_succ_le_zero _ Hn), rewrite nat.succ_sub_succ_eq_sub, apply nat.sub_lt_succ end lemma succ_n_sub_n_1 (n : ℕ) : nat.succ n - n = 1 := begin induction n, refl, rewrite nat.succ_sub_succ_eq_sub, assumption end lemma succ_succ_n_sub_n_2 (n : ℕ) : nat.succ (nat.succ n) - n = 2 := begin induction n, refl, rewrite nat.succ_sub_succ_eq_sub, assumption end lemma sub_succ_eq {m n : ℕ} : n > m → nat.succ n - m = nat.succ (n - m) := begin revert n, induction m; intros n H, refl, cases n, exfalso, exact (nat.not_succ_le_zero _ H), simp [nat.succ_sub_succ_eq_sub], apply m_ih, apply nat.lt_of_succ_lt_succ, assumption end lemma sub_gt_0 {m n : ℕ} : m > n → m - n > 0 := begin intro H, induction H, rewrite succ_n_sub_n_1, constructor, apply (nat.lt_trans H_ih), rewrite sub_succ_eq, constructor, assumption end def cw_to_nat_prod : calkin_wilf → ℕ × ℕ | cw_one := (1, 1) | (cw_left cw) := let ⟨m, n⟩ := (cw_to_nat_prod cw) in (m, m + n) | (cw_right cw) := let ⟨m, n⟩ := (cw_to_nat_prod cw) in (m + n, n) def nat_prod_to_cw_rec (m : ℕ) (f : Π (x : ℕ) (H : x < m) (n' : ℕ) (g' : Π (x : ℕ) (H : x < n') (m' : ℕ), 0 < x → 0 < m' → calkin_wilf), 0 < x → 0 < n' → calkin_wilf) (n : ℕ) (g : Π (x : ℕ) (H : x < n) (m' : ℕ), 0 < x → 0 < m' → calkin_wilf) (Hm : 0 < m) (Hn : 0 < n) : calkin_wilf := begin cases eq : (compare_dec m n), exact cw_one, apply cw_left, refine (g m _ (n - m) Hm _), exact (compare_dec_lt_iff m n).mp eq, apply sub_gt_0, exact (compare_dec_lt_iff m n).mp eq, apply cw_right, refine (f (m - n) _ n g _ Hn), apply sub_lt2, assumption, exact (compare_dec_gt_iff m n).mp eq, apply sub_gt_0, exact (compare_dec_gt_iff m n).mp eq end def cw_symmetry : calkin_wilf → calkin_wilf | cw_one := cw_one | (cw_left cw) := cw_right (cw_symmetry cw) | (cw_right cw) := cw_left (cw_symmetry cw) def nat_prod_to_cw_rec2 (m : ℕ) (f : Π (x : ℕ) (H : x < m) (n' : ℕ), 0 < x → 0 < n' → calkin_wilf) (n : ℕ) (Hm : 0 < m) (Hn : 0 < n) : calkin_wilf := cw_symmetry ((well_founded.fix nat.lt_wf nat_prod_to_cw_rec) n m f Hn Hm) def nat_prod_to_cw (m n : nat) (Hm : 0 < m) (Hn : 0 < n) : calkin_wilf := cw_symmetry (well_founded.fix nat.lt_wf nat_prod_to_cw_rec2 n m Hn Hm) #check nat_prod_to_cw #reduce cw_to_nat_prod (nat_prod_to_cw 7 28 _ _)
3a8092c3a8fa92137a060f3358892f2f3c232e3a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/1690.lean
1910ff82cf38d1414fd191508093f33d1a4b29d9
[ "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
WINDOWS-1252
Lean
false
false
13
lean
def foo :=ó
d4ebf909d8c9afa879fad4b2cdc240beba2702eb
6fca17f8d5025f89be1b2d9d15c9e0c4b4900cbf
/src/game/world4/level3.lean
f108c5733a18ed20c36c206f40b418012426a884
[ "Apache-2.0" ]
permissive
arolihas/natural_number_game
4f0c93feefec93b8824b2b96adff8b702b8b43ce
8e4f7b4b42888a3b77429f90cce16292bd288138
refs/heads/master
1,621,872,426,808
1,586,270,467,000
1,586,270,467,000
253,648,466
0
0
null
1,586,219,694,000
1,586,219,694,000
null
UTF-8
Lean
false
false
249
lean
import game.world4.level2 -- hide namespace mynat -- hide /- # Power World ## Level 3: `pow_one` -/ /- Lemma For all naturals $a$, $a ^ 1 = a$. -/ lemma pow_one (a : mynat) : a ^ (1 : mynat) = a := begin [nat_num_game] end end mynat -- hide
1d29dbd5edb303189c53000718a013a66d06b884
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/no_field_access.lean
a0a2a7dd33759a391f2aa639ca68f433dc9b55de
[ "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
146
lean
namespace foo constant bar : ℕ → ℕ end foo noncomputable def foo : ℕ → ℕ | x := @foo.bar x -- should not use field notation with '@'
7200117340e21e1657e7bcf13b7f0000d468cb08
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/finset/powerset.lean
d39d7b808622965c44ee2e8f41d930726b37d999
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
3,279
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import data.finset.basic /-! # The powerset of a finset -/ namespace finset open multiset variables {α : Type*} /-! ### powerset -/ section powerset /-- When `s` is a finset, `s.powerset` is the finset of all subsets of `s` (seen as finsets). -/ def powerset (s : finset α) : finset (finset α) := ⟨s.1.powerset.pmap finset.mk (λ t h, nodup_of_le (mem_powerset.1 h) s.2), nodup_pmap (λ a ha b hb, congr_arg finset.val) (nodup_powerset.2 s.2)⟩ @[simp] theorem mem_powerset {s t : finset α} : s ∈ powerset t ↔ s ⊆ t := by cases s; simp only [powerset, mem_mk, mem_pmap, mem_powerset, exists_prop, exists_eq_right]; rw ← val_le_iff @[simp] theorem empty_mem_powerset (s : finset α) : ∅ ∈ powerset s := mem_powerset.2 (empty_subset _) @[simp] theorem mem_powerset_self (s : finset α) : s ∈ powerset s := mem_powerset.2 (subset.refl _) @[simp] lemma powerset_empty : finset.powerset (∅ : finset α) = {∅} := rfl @[simp] theorem powerset_mono {s t : finset α} : powerset s ⊆ powerset t ↔ s ⊆ t := ⟨λ h, (mem_powerset.1 $ h $ mem_powerset_self _), λ st u h, mem_powerset.2 $ subset.trans (mem_powerset.1 h) st⟩ @[simp] theorem card_powerset (s : finset α) : card (powerset s) = 2 ^ card s := (card_pmap _ _ _).trans (card_powerset s.1) lemma not_mem_of_mem_powerset_of_not_mem {s t : finset α} {a : α} (ht : t ∈ s.powerset) (h : a ∉ s) : a ∉ t := by { apply mt _ h, apply mem_powerset.1 ht } lemma powerset_insert [decidable_eq α] (s : finset α) (a : α) : powerset (insert a s) = s.powerset ∪ s.powerset.image (insert a) := begin ext t, simp only [exists_prop, mem_powerset, mem_image, mem_union, subset_insert_iff], by_cases h : a ∈ t, { split, { exact λH, or.inr ⟨_, H, insert_erase h⟩ }, { intros H, cases H, { exact subset.trans (erase_subset a t) H }, { rcases H with ⟨u, hu⟩, rw ← hu.2, exact subset.trans (erase_insert_subset a u) hu.1 } } }, { have : ¬ ∃ (u : finset α), u ⊆ s ∧ insert a u = t, by simp [ne.symm (ne_insert_of_not_mem _ _ h)], simp [finset.erase_eq_of_not_mem h, this] } end end powerset section powerset_len /-- Given an integer `n` and a finset `s`, then `powerset_len n s` is the finset of subsets of `s` of cardinality `n`.-/ def powerset_len (n : ℕ) (s : finset α) : finset (finset α) := ⟨(s.1.powerset_len n).pmap finset.mk (λ t h, nodup_of_le (mem_powerset_len.1 h).1 s.2), nodup_pmap (λ a ha b hb, congr_arg finset.val) (nodup_powerset_len s.2)⟩ theorem mem_powerset_len {n} {s t : finset α} : s ∈ powerset_len n t ↔ s ⊆ t ∧ card s = n := by cases s; simp [powerset_len, val_le_iff.symm]; refl @[simp] theorem powerset_len_mono {n} {s t : finset α} (h : s ⊆ t) : powerset_len n s ⊆ powerset_len n t := λ u h', mem_powerset_len.2 $ and.imp (λ h₂, subset.trans h₂ h) id (mem_powerset_len.1 h') @[simp] theorem card_powerset_len (n : ℕ) (s : finset α) : card (powerset_len n s) = nat.choose (card s) n := (card_pmap _ _ _).trans (card_powerset_len n s.1) end powerset_len end finset
0fbe20d5ecc6abe8268b87d819f58661b88e863b
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Meta/Tactic/Split.lean
1910a4458ac0e4716445c2acd69c052181176269
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
7,053
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Match.MatchEqs import Lean.Meta.Tactic.Generalize namespace Lean.Meta namespace Split private def getSimpMatchContext : MetaM Simp.Context := return { simpLemmas := {} congrLemmas := (← getCongrLemmas) config.zeta := false config.beta := false config.eta := false config.iota := false config.proj := false config.decide := false } def simpMatch (e : Expr) : MetaM Simp.Result := do Simp.main e (← getSimpMatchContext) (methods := { pre }) where pre (e : Expr) : SimpM Simp.Step := do let some app ← matchMatcherApp? e | return Simp.Step.visit { expr := e } -- First try to reduce matcher match (← reduceRecMatcher? e) with | some e' => return Simp.Step.done { expr := e' } | none => for matchEq in (← Match.getEquationsFor app.matcherName).eqnNames do -- Try lemma match (← withReducible <| Simp.tryLemma? e { proof := mkConst matchEq, name? := some matchEq } SplitIf.discharge?) with | none => pure () | some r => return Simp.Step.done r return Simp.Step.visit { expr := e } def simpMatchTarget (mvarId : MVarId) : MetaM MVarId := withMVarContext mvarId do let target ← instantiateMVars (← getMVarType mvarId) let r ← simpMatch target applySimpResultToTarget mvarId target r private def simpMatchCore (matchDeclName : Name) (matchEqDeclName : Name) (e : Expr) : MetaM Simp.Result := do Simp.main e (← getSimpMatchContext) (methods := { pre }) where pre (e : Expr) : SimpM Simp.Step := do if e.isAppOf matchDeclName then -- First try to reduce matcher match (← reduceRecMatcher? e) with | some e' => return Simp.Step.done { expr := e' } | none => -- Try lemma match (← withReducible <| Simp.tryLemma? e { proof := mkConst matchEqDeclName, name? := matchEqDeclName } SplitIf.discharge?) with | none => return Simp.Step.visit { expr := e } | some r => return Simp.Step.done r else return Simp.Step.visit { expr := e } private def simpMatchTargetCore (mvarId : MVarId) (matchDeclName : Name) (matchEqDeclName : Name) : MetaM MVarId := do withMVarContext mvarId do let target ← instantiateMVars (← getMVarType mvarId) let r ← simpMatchCore matchDeclName matchEqDeclName target match r.proof? with | some proof => replaceTargetEq mvarId r.expr proof | none => replaceTargetDefEq mvarId r.expr private def generalizeMatchDiscrs (mvarId : MVarId) (discrs : Array Expr) : MetaM (Array FVarId × MVarId) := do if discrs.all (·.isFVar) then return (discrs.map (·.fvarId!), mvarId) else let args ← discrs.mapM fun d => return { expr := d, hName? := (← mkFreshUserName `h) : GeneralizeArg } let (fvarIds, mvarId) ← generalize mvarId args return (fvarIds[:discrs.size], mvarId) def applyMatchSplitter (mvarId : MVarId) (matcherDeclName : Name) (us : Array Level) (params : Array Expr) (discrs : Array Expr) : MetaM (List MVarId) := do let (discrFVarIds, mvarId) ← generalizeMatchDiscrs mvarId discrs let (reverted, mvarId) ← revert mvarId discrFVarIds (preserveOrder := true) let (discrFVarIds, mvarId) ← introNP mvarId discrFVarIds.size let numExtra := reverted.size - discrFVarIds.size let discrs := discrFVarIds.map mkFVar let some info ← getMatcherInfo? matcherDeclName | throwError "'applyMatchSplitter' failed, '{matcherDeclName}' is not a 'match' auxiliary declaration." let matchEqns ← Match.getEquationsFor matcherDeclName withMVarContext mvarId do let motive ← mkLambdaFVars discrs (← getMVarType mvarId) -- Fix universe let mut us := us if let some uElimPos := info.uElimPos? then -- Set universe elimination level to zero (Prop). us := us.set! uElimPos levelZero let splitter := mkAppN (mkConst matchEqns.splitterName us.toList) params let splitter := mkAppN (mkApp splitter motive) discrs check splitter -- TODO let mvarIds ← apply mvarId splitter let (_, mvarIds) ← mvarIds.foldlM (init := (0, [])) fun (i, mvarIds) mvarId => do let numParams := matchEqns.splitterAltNumParams[i] let (_, mvarId) ← introN mvarId numParams let (_, mvarId) ← introNP mvarId numExtra return (i+1, mvarId::mvarIds) return mvarIds.reverse def splitMatch (mvarId : MVarId) (e : Expr) : MetaM (List MVarId) := do let some app ← matchMatcherApp? e | throwError "match application expected" let matchEqns ← Match.getEquationsFor app.matcherName let mvarIds ← applyMatchSplitter mvarId app.matcherName app.matcherLevels app.params app.discrs let (_, mvarIds) ← mvarIds.foldlM (init := (0, [])) fun (i, mvarIds) mvarId => do let mvarId ← simpMatchTargetCore mvarId app.matcherName matchEqns.eqnNames[i] return (i+1, mvarId::mvarIds) return mvarIds.reverse /-- Return an `if-then-else` or `match-expr` to split. -/ partial def findSplit? (env : Environment) (e : Expr) : Option Expr := if let some target := e.find? isCandidate then if e.isIte || e.isDIte then let cond := target.getArg! 1 5 -- Try to find a nested `if` in `cond` findSplit? env cond |>.getD target else some target else none where isCandidate (e : Expr) : Bool := Id.run <| do if e.isIte || e.isDIte then !(e.getArg! 1 5).hasLooseBVars else if let some info := isMatcherAppCore? env e then let args := e.getAppArgs for i in [info.getFirstDiscrPos : info.getFirstDiscrPos + info.numDiscrs] do if args[i].hasLooseBVars then return false return true else false end Split open Split def splitTarget? (mvarId : MVarId) : MetaM (Option (List MVarId)) := commitWhenSome? do if let some e := findSplit? (← getEnv) (← instantiateMVars (← getMVarType mvarId)) then if e.isIte || e.isDIte then return (← splitIfTarget? mvarId).map fun (s₁, s₂) => [s₁.mvarId, s₂.mvarId] else splitMatch mvarId e else trace[Meta.Tactic.split] "did not find term to split\n{MessageData.ofGoal mvarId}" return none def splitLocalDecl? (mvarId : MVarId) (fvarId : FVarId) : MetaM (Option (List MVarId)) := commitWhenSome? do withMVarContext mvarId do if let some e := findSplit? (← getEnv) (← instantiateMVars (← inferType (mkFVar fvarId))) then if e.isIte || e.isDIte then return (← splitIfLocalDecl? mvarId fvarId).map fun (mvarId₁, mvarId₂) => [mvarId₁, mvarId₂] else let (fvarIds, mvarId) ← revert mvarId #[fvarId] let num := fvarIds.size let mvarIds ← splitMatch mvarId e let mvarIds ← mvarIds.mapM fun mvarId => return (← introNP mvarId num).2 return some mvarIds else return none builtin_initialize registerTraceClass `Meta.Tactic.split end Lean.Meta
486d653cda08bed4235d6c2e3a2789b3820bdf36
c31182a012eec69da0a1f6c05f42b0f0717d212d
/src/thm95/polyhedral_iso.lean
dffa382ce5648296d9879db900230540b7002fc2
[]
no_license
Ja1941/lean-liquid
fbec3ffc7fc67df1b5ca95b7ee225685ab9ffbdc
8e80ed0cbdf5145d6814e833a674eaf05a1495c1
refs/heads/master
1,689,437,983,362
1,628,362,719,000
1,628,362,719,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,882
lean
import thm95.double_complex import rescale.Tinv import pseudo_normed_group.sum_hom universe variables u noncomputable theory open_locale nnreal local attribute [instance] type_pow open category_theory namespace PolyhedralLattice open simplex_category polyhedral_lattice (conerve.L conerve.obj) variables (Λ : PolyhedralLattice.{u}) (N : ℕ) [fact (0 < N)] variables (r' : ℝ≥0) (M : ProFiltPseuNormGrpWithTinv.{u} r') -- TODO: we probably want some efficient constructor for these isomorphisms, -- because the default has a lot of redundancy in the proof obligations lemma augmentation_eq_diagonal : cosimplicial_augmentation_map Λ N ≫ (Cech_conerve.obj_zero_iso _).hom = diagonal_embedding Λ N := by { rw ← iso.eq_comp_inv, refl } def Hom_rescale_hom [fact (0 < r')] : polyhedral_lattice.Hom (rescale N Λ) M ≃+ (ProFiltPseuNormGrpWithTinv.of r' $ (rescale N (polyhedral_lattice.Hom Λ M))) := add_equiv.refl _ lemma Hom_rescale_hom_symm_apply [fact (0 < r')] (x) : (Hom_rescale_hom Λ N r' M).symm x = x := rfl lemma Hom_rescale_hom_strict [fact (0 < r')] (c : ℝ≥0) (f : polyhedral_lattice.Hom (rescale ↑N Λ) M) : f ∈ pseudo_normed_group.filtration (polyhedral_lattice.Hom (rescale ↑N Λ) M) c ↔ f ∈ pseudo_normed_group.filtration (ProFiltPseuNormGrpWithTinv.of r' (rescale ↑N (polyhedral_lattice.Hom Λ M))) c := begin split, { intros hf c' l hl, rw mul_assoc, refine hf _, simp only [semi_normed_group.mem_filtration_iff], erw [rescale.nnnorm_def, mul_comm, div_eq_mul_inv], refine mul_le_mul' _ le_rfl, exact hl }, { intros hf c' l hl, apply pseudo_normed_group.filtration_mono (le_of_eq _), convert hf _, { exact ↑N * c' }, { simp only [semi_normed_group.mem_filtration_iff] at hl ⊢, erw [rescale.nnnorm_def, div_eq_mul_inv] at hl, rwa [← inv_inv' (N : ℝ≥0), ← nnreal.mul_le_iff_le_inv, mul_comm], apply ne_of_gt, rw [nnreal.inv_pos], have hN : 0 < N := fact.out _, exact_mod_cast hN }, { rw [mul_assoc, inv_mul_cancel_left'], have hN : 0 < N := fact.out _, exact_mod_cast hN.ne' } } end section open profinitely_filtered_pseudo_normed_group polyhedral_lattice lemma Hom_rescale_hom_ctu [fact (0 < r')] (c : ℝ≥0) : continuous (pseudo_normed_group.level (Hom_rescale_hom Λ N r' M) (λ c f, (Hom_rescale_hom_strict Λ N r' M c f).1) c) := begin refine (add_monoid_hom.continuous_iff _ _ _ _ _).mpr _, intro l, haveI : fact (c * (nnnorm l * N⁻¹) ≤ c * N⁻¹ * nnnorm l) := ⟨by { rw [mul_comm (nnnorm _), mul_assoc] }⟩, have aux1 := add_monoid_hom.incl_continuous (rescale N Λ) r' M c, have aux2 := (continuous_apply (rescale.of l)).comp aux1, exact (embedding_cast_le (c * (nnnorm l * N⁻¹)) (c * N⁻¹ * nnnorm l)).continuous_iff.mp aux2 end end def Hom_rescale_iso [fact (0 < r')] : polyhedral_lattice.Hom (rescale N Λ) M ≅ (ProFiltPseuNormGrpWithTinv.of r' $ (rescale N (polyhedral_lattice.Hom Λ M))) := @ProFiltPseuNormGrpWithTinv.iso_of_equiv_of_strict' _ (polyhedral_lattice.Hom (rescale N Λ) M) (ProFiltPseuNormGrpWithTinv.of r' (rescale N (polyhedral_lattice.Hom Λ M))) (Hom_rescale_hom Λ N r' M) (λ c f, Hom_rescale_hom_strict Λ N r' M c f) (Hom_rescale_hom_ctu Λ N r' M) (λ x, rfl) @[simps apply symm_apply {fully_applied := ff}] def Hom_finsupp_equiv [fact (0 < r')] : polyhedral_lattice.Hom (fin N →₀ Λ) M ≃+ (ProFiltPseuNormGrpWithTinv.of r' $ ((polyhedral_lattice.Hom Λ M) ^ N)) := { to_fun := λ (f : (fin N →₀ Λ) →+ M) i, { to_fun := λ l, f (finsupp.single i l), map_zero' := by rw [finsupp.single_zero, f.map_zero], map_add' := λ l₁ l₂, by rw [finsupp.single_add, f.map_add] }, map_add' := λ f g, by { ext i l, simp only [add_monoid_hom.add_apply, add_monoid_hom.coe_mk, pi.add_apply] }, inv_fun := λ (f : (Λ →+ M) ^ N), { to_fun := λ x, x.sum $ λ i l, f i l, map_zero' := by rw [finsupp.sum_zero_index], map_add' := λ x y, by simp only [finsupp.sum_add_index'] }, left_inv := λ f, begin ext i l, dsimp only, simp only [add_monoid_hom.coe_comp, add_monoid_hom.coe_mk, add_monoid_hom.to_fun_eq_coe, finsupp.single_add_hom_apply, function.comp_app, add_monoid_hom.map_zero, finsupp.sum_single_index], erw [finsupp.sum_single_index], rw [finsupp.single_zero, add_monoid_hom.map_zero], end, right_inv := λ f, begin ext i l, dsimp only, simp only [add_monoid_hom.to_fun_eq_coe, add_monoid_hom.coe_mk, finsupp.sum_single_index, add_monoid_hom.map_zero], end } . section open profinitely_filtered_pseudo_normed_group polyhedral_lattice pseudo_normed_group lemma Hom_finsupp_equiv_strict [fact (0 < r')] (c : ℝ≥0) (f : (polyhedral_lattice.Hom (fin N →₀ Λ) M)) : f ∈ filtration (polyhedral_lattice.Hom (fin N →₀ Λ) M) c ↔ (Λ.Hom_finsupp_equiv N r' M) f ∈ filtration (ProFiltPseuNormGrpWithTinv.of r' ((polyhedral_lattice.Hom Λ M) ^ N)) c := begin split, { intros hf i c' l hl, refine hf _, rw [semi_normed_group.mem_filtration_iff, finsupp.nnnorm_def, finsupp.sum_single_index], { exact hl }, { exact nnnorm_zero } }, { intros hf c' l hl, let g := (Λ.Hom_finsupp_equiv N r' M) f, have hg : (Λ.Hom_finsupp_equiv N r' M).symm g = f := add_equiv.symm_apply_apply _ _, rw [semi_normed_group.mem_filtration_iff, finsupp.nnnorm_def, finsupp.sum_fintype] at hl, swap, { intro, exact nnnorm_zero }, rw [← hg, Hom_finsupp_equiv_symm_apply, add_monoid_hom.coe_mk, finsupp.sum_fintype], swap, { intro, exact add_monoid_hom.map_zero _ }, apply filtration_mono (mul_le_mul' le_rfl hl), rw [finset.mul_sum], apply sum_mem_filtration, rintro i hi, apply hf _, exact (semi_normed_group.mem_filtration_iff _ _).mpr rfl.le } end lemma Hom_finsupp_equiv_ctu [fact (0 < r')] (c : ℝ≥0) : continuous (level (Λ.Hom_finsupp_equiv N r' M) (λ c x, (Hom_finsupp_equiv_strict Λ N r' M c x).1) c) := begin apply continuous_induced_rng, rw continuous_pi_iff, intro i, dsimp only [function.comp], rw add_monoid_hom.continuous_iff, intro l, haveI : fact (c * ∥finsupp.single i l∥₊ ≤ c * ∥l∥₊) := ⟨mul_le_mul' le_rfl $ le_of_eq _⟩, { have aux1 := add_monoid_hom.incl_continuous (fin N →₀ Λ) r' M c, have aux2 := (continuous_apply (finsupp.single i l)).comp aux1, rwa (embedding_cast_le (c * ∥finsupp.single i l∥₊) (c * ∥l∥₊)).continuous_iff at aux2 }, { rw [finsupp.nnnorm_def, finsupp.sum_single_index], exact nnnorm_zero } end end @[simps] def Hom_finsupp_iso [fact (0 < r')] : polyhedral_lattice.Hom (fin N →₀ Λ) M ≅ (ProFiltPseuNormGrpWithTinv.of r' $ ((polyhedral_lattice.Hom Λ M) ^ N)) := ProFiltPseuNormGrpWithTinv.iso_of_equiv_of_strict' (Hom_finsupp_equiv _ _ _ _) (Hom_finsupp_equiv_strict Λ N r' M) (Hom_finsupp_equiv_ctu Λ N r' M) (by { intro, ext1, refl }) . open opposite section variables [fact (0 < r')] (N' : ℝ≥0) def Hom_cosimplicial_zero_iso' : (Hom M).obj (op $ of $ rescale N (of (fin N →₀ Λ))) ≅ (Hom M).obj (op $ (Λ.cosimplicial N).obj (mk 0)) := (Hom M).map_iso $ (Cech_conerve.obj_zero_iso _).op def Hom_cosimplicial_zero_iso_aux (h : N' = N) : ProFiltPseuNormGrpWithTinv.of r' (rescale N (polyhedral_lattice.Hom Λ M)) ≅ (ProFiltPseuNormGrpWithTinv.rescale r' N').obj (polyhedral_lattice.Hom Λ M) := begin rw h, exact iso.refl _ end @[simp] lemma Hom_cosimplicial_zero_iso_aux_rfl : Hom_cosimplicial_zero_iso_aux Λ N r' M N rfl = iso.refl _ := rfl def Hom_cosimplicial_zero_iso (h : N' = N) : polyhedral_lattice.Hom ((Λ.cosimplicial N).obj (simplex_category.mk 0)) M ≅ (ProFiltPseuNormGrpWithTinv.of r' (rescale N' ((polyhedral_lattice.Hom Λ M) ^ N))) := (Hom_cosimplicial_zero_iso' Λ N r' M).symm ≪≫ /- jmc is not very proud of this -/ (by exact iso.refl _ : _) ≪≫ (Hom_rescale_iso (of (fin N →₀ Λ)) N r' M) ≪≫ Hom_cosimplicial_zero_iso_aux _ _ _ _ _ h ≪≫ (ProFiltPseuNormGrpWithTinv.rescale r' N').map_iso (Hom_finsupp_iso Λ N r' M) end variables [fact (0 < r')] [fact (r' ≤ 1)] open_locale big_operators def unrescale (N : ℝ≥0) (M : Type*) [profinitely_filtered_pseudo_normed_group M] : profinitely_filtered_pseudo_normed_group_hom (rescale N M) M := profinitely_filtered_pseudo_normed_group_hom.mk_of_bound (add_monoid_hom.id _) N⁻¹ begin intro c, refine ⟨λ x hx, _, _⟩, { rwa mul_comm }, { haveI : fact (c * N⁻¹ ≤ N⁻¹ * c) := ⟨(mul_comm _ _).le⟩, exact profinitely_filtered_pseudo_normed_group.continuous_cast_le (c * N⁻¹) (N⁻¹ * c) }, end def rescale_proj (N : ℕ) (M : Type*) [profinitely_filtered_pseudo_normed_group M] (i : fin N) : profinitely_filtered_pseudo_normed_group_hom (rescale N (M ^ N)) M := (profinitely_filtered_pseudo_normed_group.pi_proj i).comp (unrescale N _) lemma rescale_proj_bound_by (N : ℕ) (M : Type*) [profinitely_filtered_pseudo_normed_group M] (i : fin N) : (rescale_proj N M i).bound_by N⁻¹ := by { intros c x hx, rw [rescale.mem_filtration, mul_comm] at hx, exact hx i } def Hom_sum : ProFiltPseuNormGrpWithTinv.of r' (rescale N ((Λ →+ M) ^ N)) ⟶ ProFiltPseuNormGrpWithTinv.of r' (Λ →+ M) := profinitely_filtered_pseudo_normed_group_with_Tinv.sum_hom (Λ →+ M) N lemma Hom_sum_apply (x) : Hom_sum Λ N r' M x = ∑ i, x i := profinitely_filtered_pseudo_normed_group_with_Tinv.sum_hom_apply _ _ _ lemma finsupp_sum_diagonal_embedding (f : (Λ →+ M) ^ N) (l : Λ) : finsupp.sum ((Λ.diagonal_embedding N) l) (λ i, (f i)) = (show Λ → M, from show Λ →+ M, from Λ.Hom_sum N r' M f) l := begin simp only [add_monoid_hom.coe_mk, Hom_sum_apply], rw [finsupp.sum_fintype, add_monoid_hom.finset_sum_apply, fintype.sum_congr], { intro i, dsimp only [diagonal_embedding, polyhedral_lattice_hom.coe_mk, finsupp.single_add_hom_apply, rescale.of, equiv.coe_refl, id], simp only [finset.sum_apply', finsupp.single_apply, finset.sum_ite_eq', finset.mem_univ, if_true], }, { intro i, exact (f i).map_zero } end lemma Cech_augmentation_map_eq_Hom_sum : (Λ.Hom_cosimplicial_zero_iso N r' M ↑N rfl).inv ≫ (thm95.Cech_augmentation_map r' Λ M N) = (Hom_sum Λ N r' M) := begin dsimp only [thm95.Cech_augmentation_map, Hom_cosimplicial_zero_iso, Hom_cosimplicial_zero_iso_aux_rfl, Hom_cosimplicial_zero_iso'], rw [iso.refl_trans, iso.refl_trans], dsimp only [iso.trans_inv, functor.map_iso_hom, functor.map_iso_inv, iso.symm_inv, op_comp], simp only [category.assoc, ← (Hom M).map_comp, augmentation_eq_diagonal, iso.op_hom, ← op_comp], dsimp only [Hom_rescale_iso, Hom_finsupp_iso], ext f l : 2, exact finsupp_sum_diagonal_embedding Λ N r' M f l, end end PolyhedralLattice
1dcd064077a7367bbfcb222993917beb3aebbcf0
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/list/nodup_equiv_fin.lean
52e91d4c08c2fe83f81cc5caf11d645d2e2ac224
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,255
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import data.fin.basic import data.list.sort import data.list.duplicate /-! # Isomorphism between `fin (length l)` and `{x // x ∈ l}` Given a list `l, * if `l` has no duplicates, then `list.nodup.nth_le_equiv` is the bijection between `fin (length l)` and `{x // x ∈ l}` sending `⟨i, hi⟩` to `⟨nth_le l i hi, _⟩` with the inverse sending `⟨x, hx⟩` to `⟨index_of x l, _⟩`; * if `l` is sorted w.r.t. `(<)`, then `list.sorted.nth_le_iso` is the same bijection reinterpreted as an `order_iso`. -/ namespace list variable {α : Type*} namespace nodup variable [decidable_eq α] /-- If `l` has no duplicates, then `list.nth_le` defines a bijection between `fin (length l)` and the set of elements of `l`. -/ def nth_le_equiv (l : list α) (H : nodup l) : fin (length l) ≃ {x // x ∈ l} := { to_fun := λ i, ⟨nth_le l i i.2, nth_le_mem l i i.2⟩, inv_fun := λ x, ⟨index_of ↑x l, index_of_lt_length.2 x.2⟩, left_inv := λ i, by simp [H], right_inv := λ x, by simp } variables {l : list α} (H : nodup l) (x : {x // x ∈ l}) (i : fin (length l)) @[simp] lemma coe_nth_le_equiv_apply : (H.nth_le_equiv l i : α) = nth_le l i i.2 := rfl @[simp] lemma coe_nth_le_equiv_symm_apply : ((H.nth_le_equiv l).symm x : ℕ) = index_of ↑x l := rfl end nodup namespace sorted variables [preorder α] {l : list α} lemma nth_le_mono (h : l.sorted (≤)) : monotone (λ i : fin l.length, l.nth_le i i.2) := λ i j, h.rel_nth_le_of_le _ _ lemma nth_le_strict_mono (h : l.sorted (<)) : strict_mono (λ i : fin l.length, l.nth_le i i.2) := λ i j, h.rel_nth_le_of_lt _ _ variable [decidable_eq α] /-- If `l` is a list sorted w.r.t. `(<)`, then `list.nth_le` defines an order isomorphism between `fin (length l)` and the set of elements of `l`. -/ def nth_le_iso (l : list α) (H : sorted (<) l) : fin (length l) ≃o {x // x ∈ l} := { to_equiv := H.nodup.nth_le_equiv l, map_rel_iff' := λ i j, H.nth_le_strict_mono.le_iff_le } variables (H : sorted (<) l) {x : {x // x ∈ l}} {i : fin l.length} @[simp] lemma coe_nth_le_iso_apply : (H.nth_le_iso l i : α) = nth_le l i i.2 := rfl @[simp] lemma coe_nth_le_iso_symm_apply : ((H.nth_le_iso l).symm x : ℕ) = index_of ↑x l := rfl end sorted section sublist /-- If there is `f`, an order-preserving embedding of `ℕ` into `ℕ` such that any element of `l` found at index `ix` can be found at index `f ix` in `l'`, then `sublist l l'`. -/ lemma sublist_of_order_embedding_nth_eq {l l' : list α} (f : ℕ ↪o ℕ) (hf : ∀ (ix : ℕ), l.nth ix = l'.nth (f ix)) : l <+ l' := begin induction l with hd tl IH generalizing l' f, { simp }, have : some hd = _ := hf 0, rw [eq_comm, list.nth_eq_some] at this, obtain ⟨w, h⟩ := this, let f' : ℕ ↪o ℕ := order_embedding.of_map_le_iff (λ i, f (i + 1) - (f 0 + 1)) (λ a b, by simp [nat.sub_le_sub_right_iff, nat.succ_le_iff, nat.lt_succ_iff]), have : ∀ ix, tl.nth ix = (l'.drop (f 0 + 1)).nth (f' ix), { intro ix, simp [list.nth_drop, nat.add_sub_of_le, nat.succ_le_iff, ←hf] }, rw [←list.take_append_drop (f 0 + 1) l', ←list.singleton_append], apply list.sublist.append _ (IH _ this), rw [list.singleton_sublist, ←h, l'.nth_le_take _ (nat.lt_succ_self _)], apply list.nth_le_mem end /-- A `l : list α` is `sublist l l'` for `l' : list α` iff there is `f`, an order-preserving embedding of `ℕ` into `ℕ` such that any element of `l` found at index `ix` can be found at index `f ix` in `l'`. -/ lemma sublist_iff_exists_order_embedding_nth_eq {l l' : list α} : l <+ l' ↔ ∃ (f : ℕ ↪o ℕ), ∀ (ix : ℕ), l.nth ix = l'.nth (f ix) := begin split, { intro H, induction H with xs ys y H IH xs ys x H IH, { simp }, { obtain ⟨f, hf⟩ := IH, refine ⟨f.trans (order_embedding.of_strict_mono (+ 1) (λ _, by simp)), _⟩, simpa using hf }, { obtain ⟨f, hf⟩ := IH, refine ⟨order_embedding.of_map_le_iff (λ (ix : ℕ), if ix = 0 then 0 else (f ix.pred).succ) _, _⟩, { rintro ⟨_|a⟩ ⟨_|b⟩; simp [nat.succ_le_succ_iff] }, { rintro ⟨_|i⟩, { simp }, { simpa using hf _ } } } }, { rintro ⟨f, hf⟩, exact sublist_of_order_embedding_nth_eq f hf } end /-- A `l : list α` is `sublist l l'` for `l' : list α` iff there is `f`, an order-preserving embedding of `fin l.length` into `fin l'.length` such that any element of `l` found at index `ix` can be found at index `f ix` in `l'`. -/ lemma sublist_iff_exists_fin_order_embedding_nth_le_eq {l l' : list α} : l <+ l' ↔ ∃ (f : fin l.length ↪o fin l'.length), ∀ (ix : fin l.length), l.nth_le ix ix.is_lt = l'.nth_le (f ix) (f ix).is_lt := begin rw sublist_iff_exists_order_embedding_nth_eq, split, { rintro ⟨f, hf⟩, have h : ∀ {i : ℕ} (h : i < l.length), f i < l'.length, { intros i hi, specialize hf i, rw [nth_le_nth hi, eq_comm, nth_eq_some] at hf, obtain ⟨h, -⟩ := hf, exact h }, refine ⟨order_embedding.of_map_le_iff (λ ix, ⟨f ix, h ix.is_lt⟩) _, _⟩, { simp }, { intro i, apply option.some_injective, simpa [←nth_le_nth] using hf _ } }, { rintro ⟨f, hf⟩, refine ⟨order_embedding.of_strict_mono (λ i, if hi : i < l.length then f ⟨i, hi⟩ else i + l'.length) _, _⟩, { intros i j h, dsimp only, split_ifs with hi hj hj hi, { simpa using h }, { rw add_comm, exact lt_add_of_lt_of_pos (fin.is_lt _) (i.zero_le.trans_lt h) }, { exact absurd (h.trans hj) hi }, { simpa using h } }, { intro i, simp only [order_embedding.coe_of_strict_mono], split_ifs with hi, { rw [nth_le_nth hi, nth_le_nth, ←hf], simp }, { rw [nth_len_le, nth_len_le], { simp }, { simpa using hi } } } } end /-- An element `x : α` of `l : list α` is a duplicate iff it can be found at two distinct indices `n m : ℕ` inside the list `l`. -/ lemma duplicate_iff_exists_distinct_nth_le {l : list α} {x : α} : l.duplicate x ↔ ∃ (n : ℕ) (hn : n < l.length) (m : ℕ) (hm : m < l.length) (h : n < m), x = l.nth_le n hn ∧ x = l.nth_le m hm := begin classical, rw [duplicate_iff_two_le_count, le_count_iff_repeat_sublist, sublist_iff_exists_fin_order_embedding_nth_le_eq], split, { rintro ⟨f, hf⟩, refine ⟨f ⟨0, by simp⟩, fin.is_lt _, f ⟨1, by simp⟩, fin.is_lt _, by simp, _, _⟩, { simpa using hf ⟨0, by simp⟩ }, { simpa using hf ⟨1, by simp⟩ } }, { rintro ⟨n, hn, m, hm, hnm, h, h'⟩, refine ⟨order_embedding.of_strict_mono (λ i, if (i : ℕ) = 0 then ⟨n, hn⟩ else ⟨m, hm⟩) _, _⟩, { rintros ⟨⟨_|i⟩, hi⟩ ⟨⟨_|j⟩, hj⟩, { simp }, { simp [hnm] }, { simp }, { simp only [nat.lt_succ_iff, nat.succ_le_succ_iff, repeat, length, nonpos_iff_eq_zero] at hi hj, simp [hi, hj] } }, { rintros ⟨⟨_|i⟩, hi⟩, { simpa using h }, { simpa using h' } } } end end sublist end list
8c4780ba3d11073d460298477dd1e964755ab21a
acc85b4be2c618b11fc7cb3005521ae6858a8d07
/algebra/group_power.lean
2e63e8e35054375da7e93f533fb336a8f3ddc557
[ "Apache-2.0" ]
permissive
linpingchuan/mathlib
d49990b236574df2a45d9919ba43c923f693d341
5ad8020f67eb13896a41cc7691d072c9331b1f76
refs/heads/master
1,626,019,377,808
1,508,048,784,000
1,508,048,784,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
6,728
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis The power operation on monoids and groups. We separate this from group, because it depends on nat, which in turn depends on other parts of algebra. We have "pow a n" for natural number powers, and "gpow a i" for integer powers. The notation a^n is used for the first, but users can locally redefine it to gpow when needed. Note: power adopts the convention that 0^0=1. -/ import data.nat.basic data.int.basic tactic.finish universe u variable {α : Type u} @[simp] theorem inv_one [division_ring α] : (1⁻¹ : α) = 1 := by rw [inv_eq_one_div, one_div_one] @[simp] theorem inv_inv' [discrete_field α] {a:α} : a⁻¹⁻¹ = a := by rw [inv_eq_one_div, inv_eq_one_div, div_div_eq_mul_div]; simp [div_one] class has_pow_nat (α : Type u) := (pow_nat : α → nat → α) def pow_nat {α : Type u} [has_pow_nat α] : α → nat → α := has_pow_nat.pow_nat infix ` ^ ` := pow_nat class has_pow_int (α : Type u) := (pow_int : α → int → α) def pow_int {α : Type u} [has_pow_int α] : α → int → α := has_pow_int.pow_int /- monoid -/ section monoid variable [monoid α] def monoid.pow (a : α) : ℕ → α | 0 := 1 | (n+1) := a * monoid.pow n instance monoid.has_pow_nat : has_pow_nat α := has_pow_nat.mk monoid.pow @[simp] theorem pow_zero (a : α) : a^0 = 1 := rfl theorem pow_succ (a : α) (n : ℕ) : a^(n+1) = a * a^n := rfl @[simp] theorem pow_one (a : α) : a^1 = a := mul_one _ theorem pow_mul_comm' (a : α) (n : ℕ) : a^n * a = a * a^n := by induction n with n ih; simp [*, pow_succ] theorem pow_succ' (a : α) (n : ℕ) : a^(n+1) = a^n * a := by simp [pow_succ, pow_mul_comm'] theorem pow_add (a : α) (m n : ℕ) : a^(m + n) = a^m * a^n := by induction n; simp [*, pow_succ', nat.add_succ] @[simp] theorem one_pow (n : ℕ) : (1 : α)^n = (1:α) := by induction n; simp [*, pow_succ] theorem pow_mul (a : α) (m : ℕ) : ∀ n, a^(m * n) = (a^m)^n | 0 := by simp | (n+1) := by rw [nat.mul_succ, pow_add, pow_succ', pow_mul] theorem pow_mul_comm (a : α) (m n : ℕ) : a^m * a^n = a^n * a^m := by rw [←pow_add, ←pow_add, add_comm] end monoid /- commutative monoid -/ section comm_monoid variable [comm_monoid α] theorem mul_pow (a b : α) : ∀ n, (a * b)^n = a^n * b^n | 0 := by simp | (n+1) := by simp [pow_succ]; rw mul_pow end comm_monoid section group variable [group α] section nat theorem inv_pow (a : α) : ∀n, (a⁻¹)^n = (a^n)⁻¹ | 0 := by simp | (n+1) := by rw [pow_succ', _root_.pow_succ, mul_inv_rev, inv_pow] theorem pow_sub (a : α) {m n : ℕ} (h : m ≥ n) : a^(m - n) = a^m * (a^n)⁻¹ := have h1 : m - n + n = m, from nat.sub_add_cancel h, have h2 : a^(m - n) * a^n = a^m, by rw [←pow_add, h1], eq_mul_inv_of_mul_eq h2 theorem pow_inv_comm (a : α) : ∀m n, (a⁻¹)^m * a^n = a^n * (a⁻¹)^m | 0 n := by simp | m 0 := by simp | (m+1) (n+1) := calc a⁻¹ ^ (m+1) * a ^ (n+1) = (a⁻¹ ^ m * a⁻¹) * (a * a^n) : by rw [pow_succ', _root_.pow_succ] ... = a⁻¹ ^ m * (a⁻¹ * a) * a^n : by simp [pow_succ, pow_succ'] ... = a⁻¹ ^ m * a^n : by simp ... = a ^ n * (a⁻¹)^m : by rw pow_inv_comm ... = a ^ n * (a * a⁻¹) * (a⁻¹)^m : by simp ... = (a^n * a) * (a⁻¹ * (a⁻¹)^m) : by simp only [mul_assoc] ... = a ^ (n+1) * a⁻¹ ^ (m+1) : by rw [pow_succ', _root_.pow_succ]; simp end nat open int def gpow (a : α) : ℤ → α | (of_nat n) := a^n | -[1+n] := (a^(nat.succ n))⁻¹ local attribute [ematch] le_of_lt open nat private lemma gpow_add_aux (a : α) (m n : nat) : gpow a ((of_nat m) + -[1+n]) = gpow a (of_nat m) * gpow a (-[1+n]) := or.elim (nat.lt_or_ge m (nat.succ n)) (assume : m < succ n, have m ≤ n, from le_of_lt_succ this, suffices gpow a -[1+ n-m] = (gpow a (of_nat m)) * (gpow a -[1+n]), by simp [*, of_nat_add_neg_succ_of_nat_of_lt], suffices (a^(nat.succ (n - m)))⁻¹ = (gpow a (of_nat m)) * (gpow a -[1+n]), from this, suffices (a^(nat.succ n - m))⁻¹ = (gpow a (of_nat m)) * (gpow a -[1+n]), by rw ←succ_sub; assumption, by rw pow_sub; finish [gpow]) (assume : m ≥ succ n, suffices gpow a (of_nat (m - succ n)) = (gpow a (of_nat m)) * (gpow a -[1+ n]), by rw [of_nat_add_neg_succ_of_nat_of_ge]; assumption, suffices a ^ (m - succ n) = a^m * (a^succ n)⁻¹, from this, by rw pow_sub; assumption) theorem gpow_add (a : α) : ∀i j : int, gpow a (i + j) = gpow a i * gpow a j | (of_nat m) (of_nat n) := pow_add _ _ _ | (of_nat m) -[1+n] := gpow_add_aux _ _ _ | -[1+m] (of_nat n) := begin rw [add_comm, gpow_add_aux], unfold gpow, rw [←inv_pow, pow_inv_comm] end | -[1+m] -[1+n] := suffices (a ^ (m + succ (succ n)))⁻¹ = (a ^ succ m)⁻¹ * (a ^ succ n)⁻¹, from this, by rw [←succ_add_eq_succ_add, add_comm, _root_.pow_add, mul_inv_rev] theorem gpow_mul_comm (a : α) (i j : ℤ) : gpow a i * gpow a j = gpow a j * gpow a i := by rw [←gpow_add, ←gpow_add, add_comm] end group theorem pow_ne_zero [integral_domain α] {a : α} {n : ℕ} (h : a ≠ 0) : a ^ n ≠ 0 := by induction n with n ih; simp [pow_succ, mul_eq_zero_iff_eq_zero_or_eq_zero, *] section discrete_field variables [discrete_field α] {a b c : α} {n : ℕ} theorem pow_inv (ha : a ≠ 0) : a⁻¹ ^ n = (a ^ n)⁻¹ := by induction n with n ih; simp [pow_succ, mul_inv', pow_ne_zero, *] end discrete_field section ordered_ring variable [linear_ordered_ring α] theorem pow_pos {a : α} (H : a > 0) : ∀ (n : ℕ), a ^ n > 0 | 0 := by simp; apply zero_lt_one | (n+1) := begin simp [_root_.pow_succ], apply mul_pos, assumption, apply pow_pos end theorem pow_nonneg {a : α} (H : a ≥ 0) : ∀ (n : ℕ), a ^ n ≥ 0 | 0 := by simp; apply zero_le_one | (n+1) := begin simp [_root_.pow_succ], apply mul_nonneg, assumption, apply pow_nonneg end theorem pow_ge_one_of_ge_one {a : α} (H : a ≥ 1) : ∀ (n : ℕ), a ^ n ≥ 1 | 0 := by simp; apply le_refl | (n+1) := begin simp [_root_.pow_succ], rw ←(one_mul (1 : α)), apply mul_le_mul, assumption, apply pow_ge_one_of_ge_one, apply zero_le_one, transitivity, apply zero_le_one, assumption end theorem pow_le_pow {a : α} {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := let ⟨k, hk⟩ := nat.le.dest h in calc a ^ n = a ^ n * 1 : by simp ... ≤ a ^ n * a ^ k : mul_le_mul_of_nonneg_left (pow_ge_one_of_ge_one ha _) (pow_nonneg (le_trans zero_le_one ha) _) ... = a ^ m : by rw [←hk, pow_add] end ordered_ring
d2df7a0923132db97c9b3d1db380fcd4b66770b6
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/filter/zero_and_bounded_at_filter.lean
3f51234f2975d7e25ccc0c362de972a6a84f55c9
[ "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,396
lean
/- Copyright (c) 2022 Chris Birkbeck. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Birkbeck, David Loeffler -/ import algebra.module.submodule.basic import topology.algebra.monoid import analysis.asymptotics.asymptotics /-! # Zero and Bounded at filter Given a filter `l` we define the notion of a function being `zero_at_filter` as well as being `bounded_at_filter`. Alongside this we construct the `submodule`, `add_submonoid` of functions that are `zero_at_filter`. Similarly, we construct the `submodule` and `subalgebra` of functions that are `bounded_at_filter`. -/ namespace filter variables {α β : Type*} open_locale topological_space /-- If `l` is a filter on `α`, then a function `f : α → β` is `zero_at_filter l` if it tends to zero along `l`. -/ def zero_at_filter [has_zero β] [topological_space β] (l : filter α) (f : α → β) : Prop := filter.tendsto f l (𝓝 0) lemma zero_is_zero_at_filter [has_zero β] [topological_space β] (l : filter α) : zero_at_filter l (0 : α → β) := tendsto_const_nhds /-- `zero_at_filter_submodule l` is the submodule of `f : α → β` which tend to zero along `l`. -/ def zero_at_filter_submodule [topological_space β] [semiring β] [has_continuous_add β] [has_continuous_mul β] (l : filter α) : submodule β (α → β) := { carrier := zero_at_filter l, zero_mem' := zero_is_zero_at_filter l, add_mem' := by { intros a b ha hb, simpa using ha.add hb, }, smul_mem' := by { intros c f hf, simpa using hf.const_mul c }, } /-- `zero_at_filter_add_submonoid l` is the additive submonoid of `f : α → β` which tend to zero along `l`. -/ def zero_at_filter_add_submonoid [topological_space β] [add_zero_class β] [has_continuous_add β] (l : filter α) : add_submonoid (α → β) := { carrier := zero_at_filter l, add_mem' := by { intros a b ha hb, simpa using ha.add hb }, zero_mem' := zero_is_zero_at_filter l, } /-- If `l` is a filter on `α`, then a function `f: α → β` is `bounded_at_filter l` if `f =O[l] 1`. -/ def bounded_at_filter [has_norm β] [has_one (α → β)] (l : filter α) (f : α → β) : Prop := asymptotics.is_O l f (1 : α → β) lemma zero_at_filter.bounded_at_filter [normed_field β] {l : filter α} {f : α → β} (hf : zero_at_filter l f) : bounded_at_filter l f := asymptotics.is_O_of_div_tendsto_nhds (by simp) _ (by { convert hf, ext1, simp, }) lemma zero_is_bounded_at_filter [normed_field β] (l : filter α) : bounded_at_filter l (0 : α → β) := (zero_is_zero_at_filter l).bounded_at_filter /-- The submodule of functions that are bounded along a filter `l`. -/ def bounded_filter_submodule [normed_field β] (l : filter α) : submodule β (α → β) := { carrier := bounded_at_filter l, zero_mem' := zero_is_bounded_at_filter l, add_mem' := by { intros f g hf hg, simpa using hf.add hg, }, smul_mem' := by { intros c f hf, simpa using hf.const_mul_left c }, } /-- The subalgebra of functions that are bounded along a filter `l`. -/ def bounded_filter_subalgebra [normed_field β] (l : filter α) : subalgebra β (α → β) := begin refine submodule.to_subalgebra (bounded_filter_submodule l) _ (λ f g hf hg, _), { simpa using asymptotics.is_O_const_mul_self (1 : β) (1 : α → β) l }, { simpa only [pi.one_apply, mul_one, norm_mul] using hf.mul hg, }, end end filter
a33b81d0bd5429986fa70ea6cc200aa7569b50ae
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/elab5.lean
dbc930e837fa547e1c0f032676e46eb1eb1d585d
[ "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
562
lean
set_option pp.implicit true #check (λ a b : nat, (nat.rec_on a (λ b, b) (λ a' ih b, ih b + 1) b : nat)) #check (λ a b : nat, (nat.rec_on a (λ b, b) (λ a' ih b, ih b + 1) b : nat)) constants a b c : nat constant p : nat → nat → Prop constant f : nat → nat axiom H1 : p (f a) (f a) axiom H2 : a = b axiom H3 : a = c #check (eq.subst H2 H1 : p (f a) (f b)) #check (eq.subst H2 (eq.subst H3 H1) : p (f c) (f b)) axiom H4 : a + 1 = b axiom H5 : p (a + nat.succ nat.zero) a #check (eq.subst H4 H5 : p b a)
75887a83c4123177e071a060f615337bfd155f9a
569919c7071b4209bdf17284c1b44d9b93c3b136
/src/solutions/tuto_lib.lean
f29cb02345fd8c18468241061cd23098e693b67c
[ "Apache-2.0" ]
permissive
dimpase/tutorials
74f149c4d5b945cd7cd677e4423d644265a7e3bf
cc7d1b2bff39b36907b3a56b446e123d0762a63b
refs/heads/master
1,668,521,216,072
1,593,390,403,000
1,593,390,403,000
276,760,422
0
0
Apache-2.0
1,593,730,650,000
1,593,730,649,000
null
UTF-8
Lean
false
false
9,733
lean
import analysis.specific_limits import data.int.parity attribute [instance] classical.prop_decidable /- Lemmas from that file were hidden in my course, or restating things which were proved without name in previous files. -/ notation `|`x`|` := abs x -- The mathlib version is unusable because it is stated in terms of ≤ lemma ge_max_iff {α : Type*} [decidable_linear_order α] {p q r : α} : r ≥ max p q ↔ r ≥ p ∧ r ≥ q := max_le_iff /- No idea why this is not in mathlib-/ lemma eq_of_abs_sub_le_all (x y : ℝ) : (∀ ε > 0, |x - y| ≤ ε) → x = y := begin intro h, apply decidable_linear_ordered_add_comm_group.eq_of_abs_sub_nonpos, by_contradiction H, push_neg at H, specialize h ( |x-y|/2) (by linarith), linarith, end def seq_limit (u : ℕ → ℝ) (l : ℝ) : Prop := ∀ ε > 0, ∃ N, ∀ n ≥ N, |u n - l| ≤ ε lemma unique_limit {u l l'} : seq_limit u l → seq_limit u l' → l = l' := begin intros hl hl', apply eq_of_abs_sub_le_all, intros ε ε_pos, specialize hl (ε/2) (by linarith), cases hl with N hN, specialize hl' (ε/2) (by linarith), cases hl' with N' hN', specialize hN (max N N') (le_max_left _ _), specialize hN' (max N N') (le_max_right _ _), calc |l - l'| = |(l-u (max N N')) + (u (max N N') -l')| : by ring ... ≤ |l - u (max N N')| + |u (max N N') - l'| : by apply abs_add ... = |u (max N N') - l| + |u (max N N') - l'| : by rw abs_sub ... ≤ ε/2 + ε/2 : by linarith ... = ε : by ring, end def pair (n : ℤ) := ∃ k, n = 2*k def int.odd (n : ℤ) := ∃ k, n = 2*k + 1 lemma int.not_even_iff_odd {n : ℤ} : ¬ int.even n ↔ int.odd n := begin rw int.not_even_iff, split ; intro h, use n/2, conv_rhs { rw add_comm, congr, rw ← h }, exact (int.mod_add_div n 2).symm, rcases h with ⟨k, rfl⟩, simp [add_comm], refl, end lemma le_of_le_add_all {x y : ℝ} : (∀ ε > 0, y ≤ x + ε) → y ≤ x := begin contrapose!, intro h, use (y-x)/2, split ; linarith, end def upper_bound (A : set ℝ) (x : ℝ) := ∀ a ∈ A, a ≤ x def is_sup (A : set ℝ) (x : ℝ) := upper_bound A x ∧ ∀ y, upper_bound A y → x ≤ y lemma lt_sup {A : set ℝ} {x : ℝ} (hx : is_sup A x) : ∀ y, y < x → ∃ a ∈ A, y < a := begin intro y, contrapose!, exact hx.right y, end lemma squeeze {u v w : ℕ → ℝ} {l} (hu : seq_limit u l) (hw : seq_limit w l) (h : ∀ n, u n ≤ v n) (h' : ∀ n, v n ≤ w n) : seq_limit v l := begin intros ε ε_pos, cases hu ε ε_pos with N hN, cases hw ε ε_pos with N' hN', use max N N', intros n hn, rw ge_max_iff at hn, specialize hN n (by linarith), specialize hN' n (by linarith), specialize h n, specialize h' n, rw abs_le at *, split ; linarith end def extraction (φ : ℕ → ℕ) := ∀ n m, n < m → φ n < φ m def tendsto_infinity (u : ℕ → ℝ) := ∀ A, ∃ N, ∀ n ≥ N, u n ≥ A lemma lim_le {x y : ℝ} {u : ℕ → ℝ} (hu : seq_limit u x) (ineg : ∀ n, u n ≤ y) : x ≤ y := begin apply le_of_le_add_all, intros ε ε_pos, cases hu ε ε_pos with N hN, specialize hN N (by linarith), specialize ineg N, rw abs_le at hN, linarith, end /- lemma limite_infinie_pas_finie {u : ℕ → ℝ} : limite_infinie_suite u → ∀ x, ¬ seq_limit u x := begin -- sorry intros lim_infinie x lim_x, cases lim_x 1 (by linarith) with N hN, cases lim_infinie (x+2) with N' hN', let N₀ := max N N', specialize hN N₀ (inferieur_max_gauche _ _), specialize hN' N₀ (inferieur_max_droite _ _), rw abs_inferieur_ssi at hN, linarith', -- sorry end -/ lemma inv_succ_le_all : ∀ ε > 0, ∃ N : ℕ, ∀ n ≥ N, 1/(n + 1 : ℝ) ≤ ε := begin convert metric.tendsto_at_top.mp (tendsto_one_div_add_at_top_nhds_0_nat), apply propext, simp only [real.dist_eq, sub_zero], split, intros h ε ε_pos, cases h (ε/2) (by linarith) with N hN, use N, intros n hn, rw abs_of_pos (nat.one_div_pos_of_nat : 1/(n+1 : ℝ) > 0), specialize hN n hn, linarith, intros h ε ε_pos, cases h ε (by linarith) with N hN, use N, intros n hn, specialize hN n hn, rw abs_of_pos (@nat.one_div_pos_of_nat ℝ _ n) at hN, linarith, end lemma limit_const (x : ℝ) : seq_limit (λ n, x) x := λ ε ε_pos, ⟨0, λ _ _, by simp [le_of_lt ε_pos]⟩ lemma limit_of_sub_le_inv_succ {u : ℕ → ℝ} {x : ℝ} (h : ∀ n, |u n - x| ≤ 1/(n+1)) : seq_limit u x := begin intros ε ε_pos, rcases inv_succ_le_all ε ε_pos with ⟨N, hN⟩, use N, intros n hn, specialize h n, specialize hN n hn, linarith, end lemma limit_const_add_inv_succ (x : ℝ) : seq_limit (λ n, x + 1/(n+1)) x := limit_of_sub_le_inv_succ (λ n, by rw abs_of_pos ; linarith [@nat.one_div_pos_of_nat ℝ _ n]) lemma limit_const_sub_inv_succ (x : ℝ) : seq_limit (λ n, x - 1/(n+1)) x := begin refine limit_of_sub_le_inv_succ (λ n, _), rw [show x - 1 / (n + 1) - x = -(1/(n+1)), by ring, abs_neg, abs_of_pos], linarith [@nat.one_div_pos_of_nat ℝ _ n] end lemma id_le_extraction {φ}: extraction φ → ∀ n, n ≤ φ n := begin intros hyp n, induction n with n hn, { exact nat.zero_le _ }, { exact nat.succ_le_of_lt (by linarith [hyp n (n+1) (by linarith)]) }, end lemma seq_limit_id : tendsto_infinity (λ n, n) := begin intros A, cases exists_nat_gt A with N hN, use N, intros n hn, have : (n : ℝ) ≥ N, exact_mod_cast hn, linarith, end lemma extraction_machine (ψ : ℕ → ℕ) (hψ : ∀ n, ψ n ≥ n) : ∃ f : ℕ → ℕ, extraction (ψ ∘ f) ∧ ∀ n, f n ≥ n := begin refine ⟨λ n, nat.rec_on n 0 (λ n ih, ψ ih + 1), λ m n h, _, λ n, _⟩, { induction h; dsimp [(∘)], { exact hψ _ }, { exact lt_trans h_ih (hψ _) } }, { induction n, {apply le_refl}, exact nat.succ_le_succ (le_trans n_ih (hψ _)) } end variables {u : ℕ → ℝ} {l : ℝ} {φ : ℕ → ℕ} lemma limite_extraction_si_limite (h : seq_limit u l) (hφ : extraction φ) : seq_limit (u ∘ φ) l := begin -- sorry intros ε ε_pos, cases h ε ε_pos with N hN, use N, intros n hn, apply hN, calc N ≤ n : hn ... ≤ φ n : id_le_extraction hφ n, -- sorry end def segment (a b : ℝ) := {x | a ≤ x ∧ x ≤ b} open set filter def cluster_point (u : ℕ → ℝ) (a : ℝ) := ∃ φ, extraction φ ∧ seq_limit (u ∘ φ) a lemma bolzano_weierstrass {a b : ℝ} {u : ℕ → ℝ} (h : ∀ n, u n ∈ Icc a b) : ∃ c ∈ Icc a b, cluster_point u c := begin have cpct : compact (Icc a b), exact compact_Icc, have : map u at_top ≤ principal (Icc a b), { change tendsto u _ _, rw tendsto_principal, filter_upwards [univ_mem_sets], intros n hn, exact h n }, rcases cpct (map u at_top) (map_ne_bot at_top_ne_bot) this with ⟨c, h, h'⟩, clear this, use [c, h], unfold cluster_point, have : ∀ N, ∃ n ≥ N, |u n -c| ≤ 1/(N+1), intro N, rw ← forall_sets_nonempty_iff_ne_bot at h', specialize h' (u '' {n | n ≥ N} ∩ {x | |x-c| ≤ 1/(N+1)}) _, { simp only [set.nonempty, set.mem_image, set.mem_inter_eq, ne.def, set.mem_set_of_eq] at h', rcases h' with ⟨_, ⟨n, ⟨hn, rfl⟩⟩, ineg⟩, use [n, hn, ineg] }, { apply inter_mem_inf_sets, { apply image_mem_map, apply mem_at_top }, { have fact: (0 : ℝ) < 1/(N+2), exact_mod_cast (nat.one_div_pos_of_nat : 1/((N+1 : ℕ) + 1 : ℝ) > 0), apply mem_sets_of_superset (metric.ball_mem_nhds c fact), intros x x_in, rw [metric.mem_ball, real.dist_eq] at x_in, exact le_of_lt ( calc |x - c| < 1 / (N + 2) : x_in ... = 1/((N+1)+1) : by { congr' 1, norm_cast } ... ≤ 1 / (N + 1) : nat.one_div_le_one_div (nat.le_succ N)), } }, choose ψ hψ using this, cases forall_and_distrib.mp hψ with hψ_id hψ', clear hψ, rcases extraction_machine ψ hψ_id with ⟨f, hf, hf'⟩, use [ψ ∘ f, hf], apply limit_of_sub_le_inv_succ, intros n, transitivity 1/(f n + 1 : ℝ), apply hψ', exact nat.one_div_le_one_div (hf' n), end lemma not_seq_limit_of_tendstoinfinity {u : ℕ → ℝ} : tendsto_infinity u → ∀ x, ¬ seq_limit u x := begin intros lim_infinie x lim_x, cases lim_x 1 (by linarith) with N hN, cases lim_infinie (x+2) with N' hN', let N₀ := max N N', specialize hN N₀ (le_max_left _ _), specialize hN' N₀ (le_max_right _ _), rw abs_le at hN, linarith, end open real lemma sup_segment {a b : ℝ} {A : set ℝ} (hnonvide : ∃ x, x ∈ A) (h : A ⊆ Icc a b) : ∃ x ∈ Icc a b, is_sup A x := begin have b_maj : ∀ (y : ℝ), y ∈ A → y ≤ b, from λ y y_in, (h y_in).2, have Sup_maj : upper_bound A (Sup A), { intro x, apply real.le_Sup, use [b, b_maj] } , refine ⟨Sup A, _, _⟩, { split, { cases hnonvide with x x_in, exact le_trans (h x_in).1 (Sup_maj _ x_in) }, { apply Sup_le_ub A hnonvide b_maj } }, { use Sup_maj, intros y y_in, rwa real.Sup_le _ hnonvide ⟨b, b_maj⟩ }, end lemma subseq_tendsto_of_tendsto (h : seq_limit u l) (hφ : extraction φ) : seq_limit (u ∘ φ) l := begin intros ε ε_pos, cases h ε ε_pos with N hN, use N, intros n hn, apply hN, calc N ≤ n : hn ... ≤ φ n : id_le_extraction hφ n, end namespace tactic.interactive open tactic meta def check_me : tactic unit := `[ { repeat { unfold seq_limit}, repeat { unfold continue_en }, push_neg, try { simp only [exists_prop] }, try { exact iff.rfl }, done } <|> fail "Ce n'est pas cela. Essayez encore." ] end tactic.interactive
fc7d9905323e18d91432e27429e43341f32e0c68
63abd62053d479eae5abf4951554e1064a4c45b4
/src/category_theory/limits/limits.lean
6ba975b111154f18bc74aa97b8edf0955fd93307
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
71,683
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Mario Carneiro, Scott Morrison, Floris van Doorn -/ import category_theory.adjunction.basic import category_theory.limits.cones import category_theory.reflects_isomorphisms /-! # Limits and colimits We set up the general theory of limits and colimits in a category. In this introduction we only describe the setup for limits; it is repeated, with slightly different names, for colimits. The three main structures involved are * `is_limit c`, for `c : cone F`, `F : J ⥤ C`, expressing that `c` is a limit cone, * `limit_cone F`, which consists of a choice of cone for `F` and the fact it is a limit cone, and * `has_limit F`, asserting the mere existence of some limit cone for `F`. `has_limit` is a propositional typeclass (it's important that it is a proposition merely asserting the existence of a limit, as otherwise we would have non-defeq problems from incompatible instances). Typically there are two different ways one can use the limits library: 1. working with particular cones, and terms of type `is_limit` 2. working solely with `has_limit`. While `has_limit` only asserts the existence of a limit cone, we happily use the axiom of choice in mathlib, so there are convenience functions all depending on `has_limit F`: * `limit F : C`, producing some limit object (of course all such are isomorphic) * `limit.π F j : limit F ⟶ F.obj j`, the morphisms out of the limit, * `limit.lift F c : c.X ⟶ limit F`, the universal morphism from any other `c : cone F`, etc. Key to using the `has_limit` interface is that there is an `@[ext]` lemma stating that to check `f = g`, for `f g : Z ⟶ limit F`, it suffices to check `f ≫ limit.π F j = g ≫ limit.π F j` for every `j`. This, combined with `@[simp]` lemmas, makes it possible to prove many easy facts about limits using automation (e.g. `tidy`). There are abbreviations `has_limits_of_shape J C` and `has_limits C` asserting the existence of classes of limits. Later more are introduced, for finite limits, special shapes of limits, etc. Ideally, many results about limits should be stated first in terms of `is_limit`, and then a result in terms of `has_limit` derived from this. At this point, however, this is far from uniformly achieved in mathlib --- often statements are only written in terms of `has_limit`. ## Implementation At present we simply say everything twice, in order to handle both limits and colimits. It would be highly desirable to have some automation support, e.g. a `@[dualize]` attribute that behaves similarly to `@[to_additive]`. ## References * [Stacks: Limits and colimits](https://stacks.math.columbia.edu/tag/002D) -/ noncomputable theory open category_theory category_theory.category category_theory.functor opposite namespace category_theory.limits universes v u u' u'' w -- declare the `v`'s first; see `category_theory.category` for an explanation variables {J K : Type v} [small_category J] [small_category K] variables {C : Type u} [category.{v} C] variables {F : J ⥤ C} /-- A cone `t` on `F` is a limit cone if each cone on `F` admits a unique cone morphism to `t`. See https://stacks.math.columbia.edu/tag/002E. -/ @[nolint has_inhabited_instance] structure is_limit (t : cone F) := (lift : Π (s : cone F), s.X ⟶ t.X) (fac' : ∀ (s : cone F) (j : J), lift s ≫ t.π.app j = s.π.app j . obviously) (uniq' : ∀ (s : cone F) (m : s.X ⟶ t.X) (w : ∀ j : J, m ≫ t.π.app j = s.π.app j), m = lift s . obviously) restate_axiom is_limit.fac' attribute [simp, reassoc] is_limit.fac restate_axiom is_limit.uniq' namespace is_limit instance subsingleton {t : cone F} : subsingleton (is_limit t) := ⟨by intros P Q; cases P; cases Q; congr; ext; solve_by_elim⟩ /-- Given a natural transformation `α : F ⟶ G`, we give a morphism from the cone point of any cone over `F` to the cone point of a limit cone over `G`. -/ def map {F G : J ⥤ C} (s : cone F) {t : cone G} (P : is_limit t) (α : F ⟶ G) : s.X ⟶ t.X := P.lift ((cones.postcompose α).obj s) @[simp, reassoc] lemma map_π {F G : J ⥤ C} (c : cone F) {d : cone G} (hd : is_limit d) (α : F ⟶ G) (j : J) : hd.map c α ≫ d.π.app j = c.π.app j ≫ α.app j := fac _ _ _ lemma lift_self {c : cone F} (t : is_limit c) : t.lift c = 𝟙 c.X := (t.uniq _ _ (λ j, id_comp _)).symm /- Repackaging the definition in terms of cone morphisms. -/ /-- The universal morphism from any other cone to a limit cone. -/ @[simps] def lift_cone_morphism {t : cone F} (h : is_limit t) (s : cone F) : s ⟶ t := { hom := h.lift s } lemma uniq_cone_morphism {s t : cone F} (h : is_limit t) {f f' : s ⟶ t} : f = f' := have ∀ {g : s ⟶ t}, g = h.lift_cone_morphism s, by intro g; ext; exact h.uniq _ _ g.w, this.trans this.symm /-- Alternative constructor for `is_limit`, providing a morphism of cones rather than a morphism between the cone points and separately the factorisation condition. -/ @[simps] def mk_cone_morphism {t : cone F} (lift : Π (s : cone F), s ⟶ t) (uniq' : ∀ (s : cone F) (m : s ⟶ t), m = lift s) : is_limit t := { lift := λ s, (lift s).hom, uniq' := λ s m w, have cone_morphism.mk m w = lift s, by apply uniq', congr_arg cone_morphism.hom this } /-- Limit cones on `F` are unique up to isomorphism. -/ @[simps] def unique_up_to_iso {s t : cone F} (P : is_limit s) (Q : is_limit t) : s ≅ t := { hom := Q.lift_cone_morphism s, inv := P.lift_cone_morphism t, hom_inv_id' := P.uniq_cone_morphism, inv_hom_id' := Q.uniq_cone_morphism } /-- Any cone morphism between limit cones is an isomorphism. -/ def hom_is_iso {s t : cone F} (P : is_limit s) (Q : is_limit t) (f : s ⟶ t) : is_iso f := { inv := P.lift_cone_morphism t, hom_inv_id' := P.uniq_cone_morphism, inv_hom_id' := Q.uniq_cone_morphism, } /-- Limits of `F` are unique up to isomorphism. -/ def cone_point_unique_up_to_iso {s t : cone F} (P : is_limit s) (Q : is_limit t) : s.X ≅ t.X := (cones.forget F).map_iso (unique_up_to_iso P Q) @[simp, reassoc] lemma cone_point_unique_up_to_iso_hom_comp {s t : cone F} (P : is_limit s) (Q : is_limit t) (j : J) : (cone_point_unique_up_to_iso P Q).hom ≫ t.π.app j = s.π.app j := (unique_up_to_iso P Q).hom.w _ @[simp, reassoc] lemma cone_point_unique_up_to_iso_inv_comp {s t : cone F} (P : is_limit s) (Q : is_limit t) (j : J) : (cone_point_unique_up_to_iso P Q).inv ≫ s.π.app j = t.π.app j := (unique_up_to_iso P Q).inv.w _ @[simp, reassoc] lemma lift_comp_cone_point_unique_up_to_iso_hom {r s t : cone F} (P : is_limit s) (Q : is_limit t) : P.lift r ≫ (cone_point_unique_up_to_iso P Q).hom = Q.lift r := Q.uniq _ _ (by simp) @[simp, reassoc] lemma lift_comp_cone_point_unique_up_to_iso_inv {r s t : cone F} (P : is_limit s) (Q : is_limit t) : Q.lift r ≫ (cone_point_unique_up_to_iso P Q).inv = P.lift r := P.uniq _ _ (by simp) /-- Transport evidence that a cone is a limit cone across an isomorphism of cones. -/ def of_iso_limit {r t : cone F} (P : is_limit r) (i : r ≅ t) : is_limit t := is_limit.mk_cone_morphism (λ s, P.lift_cone_morphism s ≫ i.hom) (λ s m, by rw ←i.comp_inv_eq; apply P.uniq_cone_morphism) @[simp] lemma of_iso_limit_lift {r t : cone F} (P : is_limit r) (i : r ≅ t) (s) : (P.of_iso_limit i).lift s = P.lift s ≫ i.hom.hom := rfl /-- Isomorphism of cones preserves whether or not they are limiting cones. -/ def equiv_iso_limit {r t : cone F} (i : r ≅ t) : is_limit r ≃ is_limit t := { to_fun := λ h, h.of_iso_limit i, inv_fun := λ h, h.of_iso_limit i.symm, left_inv := by tidy, right_inv := by tidy } @[simp] lemma equiv_iso_limit_apply {r t : cone F} (i : r ≅ t) (P : is_limit r) : equiv_iso_limit i P = P.of_iso_limit i := rfl @[simp] lemma equiv_iso_limit_symm_apply {r t : cone F} (i : r ≅ t) (P : is_limit t) : (equiv_iso_limit i).symm P = P.of_iso_limit i.symm := rfl /-- If the canonical morphism from a cone point to a limiting cone point is an iso, then the first cone was limiting also. -/ def of_point_iso {r t : cone F} (P : is_limit r) [i : is_iso (P.lift t)] : is_limit t := of_iso_limit P begin haveI : is_iso (P.lift_cone_morphism t).hom := i, haveI : is_iso (P.lift_cone_morphism t) := cones.cone_iso_of_hom_iso _, symmetry, apply as_iso (P.lift_cone_morphism t), end variables {t : cone F} lemma hom_lift (h : is_limit t) {W : C} (m : W ⟶ t.X) : m = h.lift { X := W, π := { app := λ b, m ≫ t.π.app b } } := h.uniq { X := W, π := { app := λ b, m ≫ t.π.app b } } m (λ b, rfl) /-- Two morphisms into a limit are equal if their compositions with each cone morphism are equal. -/ lemma hom_ext (h : is_limit t) {W : C} {f f' : W ⟶ t.X} (w : ∀ j, f ≫ t.π.app j = f' ≫ t.π.app j) : f = f' := by rw [h.hom_lift f, h.hom_lift f']; congr; exact funext w /-- Given a right adjoint functor between categories of cones, the image of a limit cone is a limit cone. -/ def of_right_adjoint {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cone G ⥤ cone F) [is_right_adjoint h] {c : cone G} (t : is_limit c) : is_limit (h.obj c) := mk_cone_morphism (λ s, (adjunction.of_right_adjoint h).hom_equiv s c (t.lift_cone_morphism _)) (λ s m, (adjunction.eq_hom_equiv_apply _ _ _).2 t.uniq_cone_morphism) /-- Given two functors which have equivalent categories of cones, we can transport a limiting cone across the equivalence. -/ def of_cone_equiv {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cone G ≌ cone F) {c : cone G} : is_limit (h.functor.obj c) ≃ is_limit c := { to_fun := λ P, of_iso_limit (of_right_adjoint h.inverse P) (h.unit_iso.symm.app c), inv_fun := of_right_adjoint h.functor, left_inv := by tidy, right_inv := by tidy, } @[simp] lemma of_cone_equiv_apply_desc {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cone G ≌ cone F) {c : cone G} (P : is_limit (h.functor.obj c)) (s) : (of_cone_equiv h P).lift s = ((h.unit_iso.hom.app s).hom ≫ (h.functor.inv.map (P.lift_cone_morphism (h.functor.obj s))).hom) ≫ (h.unit_iso.inv.app c).hom := rfl @[simp] lemma of_cone_equiv_symm_apply_desc {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cone G ≌ cone F) {c : cone G} (P : is_limit c) (s) : ((of_cone_equiv h).symm P).lift s = (h.counit_iso.inv.app s).hom ≫ (h.functor.map (P.lift_cone_morphism (h.inverse.obj s))).hom := rfl /-- A cone postcomposed with a natural isomorphism is a limit cone if and only if the original cone is. -/ def postcompose_hom_equiv {F G : J ⥤ C} (α : F ≅ G) (c : cone F) : is_limit ((cones.postcompose α.hom).obj c) ≃ is_limit c := of_cone_equiv (cones.postcompose_equivalence α) /-- A cone postcomposed with the inverse of a natural isomorphism is a limit cone if and only if the original cone is. -/ def postcompose_inv_equiv {F G : J ⥤ C} (α : F ≅ G) (c : cone G) : is_limit ((cones.postcompose α.inv).obj c) ≃ is_limit c := postcompose_hom_equiv α.symm c /-- The cone points of two limit cones for naturally isomorphic functors are themselves isomorphic. -/ @[simps] def cone_points_iso_of_nat_iso {F G : J ⥤ C} {s : cone F} {t : cone G} (P : is_limit s) (Q : is_limit t) (w : F ≅ G) : s.X ≅ t.X := { hom := Q.map s w.hom, inv := P.map t w.inv, hom_inv_id' := P.hom_ext (by tidy), inv_hom_id' := Q.hom_ext (by tidy), } @[reassoc] lemma cone_points_iso_of_nat_iso_hom_comp {F G : J ⥤ C} {s : cone F} {t : cone G} (P : is_limit s) (Q : is_limit t) (w : F ≅ G) (j : J) : (cone_points_iso_of_nat_iso P Q w).hom ≫ t.π.app j = s.π.app j ≫ w.hom.app j := by simp @[reassoc] lemma cone_points_iso_of_nat_iso_inv_comp {F G : J ⥤ C} {s : cone F} {t : cone G} (P : is_limit s) (Q : is_limit t) (w : F ≅ G) (j : J) : (cone_points_iso_of_nat_iso P Q w).inv ≫ s.π.app j = t.π.app j ≫ w.inv.app j := by simp @[reassoc] lemma lift_comp_cone_points_iso_of_nat_iso_hom {F G : J ⥤ C} {r s : cone F} {t : cone G} (P : is_limit s) (Q : is_limit t) (w : F ≅ G) : P.lift r ≫ (cone_points_iso_of_nat_iso P Q w).hom = Q.map r w.hom := Q.hom_ext (by simp) section equivalence open category_theory.equivalence /-- If `s : cone F` is a limit cone, so is `s` whiskered by an equivalence `e`. -/ def whisker_equivalence {s : cone F} (P : is_limit s) (e : K ≌ J) : is_limit (s.whisker e.functor) := of_right_adjoint (cones.whiskering_equivalence e).functor P /-- We can prove two cone points `(s : cone F).X` and `(t.cone F).X` are isomorphic if * both cones are limit cones * their indexing categories are equivalent via some `e : J ≌ K`, * the triangle of functors commutes up to a natural isomorphism: `e.functor ⋙ G ≅ F`. This is the most general form of uniqueness of cone points, allowing relabelling of both the indexing category (up to equivalence) and the functor (up to natural isomorphism). -/ @[simps] def cone_points_iso_of_equivalence {F : J ⥤ C} {s : cone F} {G : K ⥤ C} {t : cone G} (P : is_limit s) (Q : is_limit t) (e : J ≌ K) (w : e.functor ⋙ G ≅ F) : s.X ≅ t.X := let w' : e.inverse ⋙ F ≅ G := (iso_whisker_left e.inverse w).symm ≪≫ inv_fun_id_assoc e G in { hom := Q.lift ((cones.equivalence_of_reindexing e.symm w').functor.obj s), inv := P.lift ((cones.equivalence_of_reindexing e w).functor.obj t), hom_inv_id' := begin apply hom_ext P, intros j, dsimp, simp only [limits.cone.whisker_π, limits.cones.postcompose_obj_π, fac, whisker_left_app, assoc, id_comp, inv_fun_id_assoc_hom_app, fac_assoc, nat_trans.comp_app], rw [counit_app_functor, ←functor.comp_map, w.hom.naturality], simp, end, inv_hom_id' := by { apply hom_ext Q, tidy, }, } end equivalence /-- The universal property of a limit cone: a map `W ⟶ X` is the same as a cone on `F` with vertex `W`. -/ def hom_iso (h : is_limit t) (W : C) : (W ⟶ t.X) ≅ ((const J).obj W ⟶ F) := { hom := λ f, (t.extend f).π, inv := λ π, h.lift { X := W, π := π }, hom_inv_id' := by ext f; apply h.hom_ext; intro j; simp; dsimp; refl } @[simp] lemma hom_iso_hom (h : is_limit t) {W : C} (f : W ⟶ t.X) : (is_limit.hom_iso h W).hom f = (t.extend f).π := rfl /-- The limit of `F` represents the functor taking `W` to the set of cones on `F` with vertex `W`. -/ def nat_iso (h : is_limit t) : yoneda.obj t.X ≅ F.cones := nat_iso.of_components (λ W, is_limit.hom_iso h (unop W)) (by tidy). /-- Another, more explicit, formulation of the universal property of a limit cone. See also `hom_iso`. -/ def hom_iso' (h : is_limit t) (W : C) : ((W ⟶ t.X) : Type v) ≅ { p : Π j, W ⟶ F.obj j // ∀ {j j'} (f : j ⟶ j'), p j ≫ F.map f = p j' } := h.hom_iso W ≪≫ { hom := λ π, ⟨λ j, π.app j, λ j j' f, by convert ←(π.naturality f).symm; apply id_comp⟩, inv := λ p, { app := λ j, p.1 j, naturality' := λ j j' f, begin dsimp, rw [id_comp], exact (p.2 f).symm end } } /-- If G : C → D is a faithful functor which sends t to a limit cone, then it suffices to check that the induced maps for the image of t can be lifted to maps of C. -/ def of_faithful {t : cone F} {D : Type u'} [category.{v} D] (G : C ⥤ D) [faithful G] (ht : is_limit (G.map_cone t)) (lift : Π (s : cone F), s.X ⟶ t.X) (h : ∀ s, G.map (lift s) = ht.lift (G.map_cone s)) : is_limit t := { lift := lift, fac' := λ s j, by apply G.map_injective; rw [G.map_comp, h]; apply ht.fac, uniq' := λ s m w, begin apply G.map_injective, rw h, refine ht.uniq (G.map_cone s) _ (λ j, _), convert ←congr_arg (λ f, G.map f) (w j), apply G.map_comp end } /-- If `F` and `G` are naturally isomorphic, then `F.map_cone c` being a limit implies `G.map_cone c` is also a limit. -/ def map_cone_equiv {D : Type u'} [category.{v} D] {K : J ⥤ C} {F G : C ⥤ D} (h : F ≅ G) {c : cone K} (t : is_limit (F.map_cone c)) : is_limit (G.map_cone c) := { lift := λ s, t.map s (iso_whisker_left K h).inv ≫ h.hom.app c.X, fac' := λ s j, begin erw [assoc, ← h.hom.naturality (c.π.app j), t.map_π_assoc s (iso_whisker_left K h).inv j], dsimp, simp, end, uniq' := λ s m J, begin rw ← cancel_mono (h.inv.app c.X), apply t.hom_ext, intro j, rw [assoc, assoc, assoc, h.hom_inv_id_app_assoc], erw [← h.inv.naturality (c.π.app j), reassoc_of (J j)], apply (t.map_π s (iso_whisker_left K h).inv j).symm, end } /-- A cone is a limit cone exactly if there is a unique cone morphism from any other cone. -/ def iso_unique_cone_morphism {t : cone F} : is_limit t ≅ Π s, unique (s ⟶ t) := { hom := λ h s, { default := h.lift_cone_morphism s, uniq := λ _, h.uniq_cone_morphism }, inv := λ h, { lift := λ s, (h s).default.hom, uniq' := λ s f w, congr_arg cone_morphism.hom ((h s).uniq ⟨f, w⟩) } } namespace of_nat_iso variables {X : C} (h : yoneda.obj X ≅ F.cones) /-- If `F.cones` is represented by `X`, each morphism `f : Y ⟶ X` gives a cone with cone point `Y`. -/ def cone_of_hom {Y : C} (f : Y ⟶ X) : cone F := { X := Y, π := h.hom.app (op Y) f } /-- If `F.cones` is represented by `X`, each cone `s` gives a morphism `s.X ⟶ X`. -/ def hom_of_cone (s : cone F) : s.X ⟶ X := h.inv.app (op s.X) s.π @[simp] lemma cone_of_hom_of_cone (s : cone F) : cone_of_hom h (hom_of_cone h s) = s := begin dsimp [cone_of_hom, hom_of_cone], cases s, congr, dsimp, exact congr_fun (congr_fun (congr_arg nat_trans.app h.inv_hom_id) (op s_X)) s_π, end @[simp] lemma hom_of_cone_of_hom {Y : C} (f : Y ⟶ X) : hom_of_cone h (cone_of_hom h f) = f := congr_fun (congr_fun (congr_arg nat_trans.app h.hom_inv_id) (op Y)) f /-- If `F.cones` is represented by `X`, the cone corresponding to the identity morphism on `X` will be a limit cone. -/ def limit_cone : cone F := cone_of_hom h (𝟙 X) /-- If `F.cones` is represented by `X`, the cone corresponding to a morphism `f : Y ⟶ X` is the limit cone extended by `f`. -/ lemma cone_of_hom_fac {Y : C} (f : Y ⟶ X) : cone_of_hom h f = (limit_cone h).extend f := begin dsimp [cone_of_hom, limit_cone, cone.extend], congr' with j, have t := congr_fun (h.hom.naturality f.op) (𝟙 X), dsimp at t, simp only [comp_id] at t, rw congr_fun (congr_arg nat_trans.app t) j, refl, end /-- If `F.cones` is represented by `X`, any cone is the extension of the limit cone by the corresponding morphism. -/ lemma cone_fac (s : cone F) : (limit_cone h).extend (hom_of_cone h s) = s := begin rw ←cone_of_hom_of_cone h s, conv_lhs { simp only [hom_of_cone_of_hom] }, apply (cone_of_hom_fac _ _).symm, end end of_nat_iso section open of_nat_iso /-- If `F.cones` is representable, then the cone corresponding to the identity morphism on the representing object is a limit cone. -/ def of_nat_iso {X : C} (h : yoneda.obj X ≅ F.cones) : is_limit (limit_cone h) := { lift := λ s, hom_of_cone h s, fac' := λ s j, begin have h := cone_fac h s, cases s, injection h with h₁ h₂, simp only [heq_iff_eq] at h₂, conv_rhs { rw ← h₂ }, refl, end, uniq' := λ s m w, begin rw ←hom_of_cone_of_hom h m, congr, rw cone_of_hom_fac, dsimp, cases s, congr' with j, exact w j, end } end end is_limit /-- A cocone `t` on `F` is a colimit cocone if each cocone on `F` admits a unique cocone morphism from `t`. See https://stacks.math.columbia.edu/tag/002F. -/ @[nolint has_inhabited_instance] structure is_colimit (t : cocone F) := (desc : Π (s : cocone F), t.X ⟶ s.X) (fac' : ∀ (s : cocone F) (j : J), t.ι.app j ≫ desc s = s.ι.app j . obviously) (uniq' : ∀ (s : cocone F) (m : t.X ⟶ s.X) (w : ∀ j : J, t.ι.app j ≫ m = s.ι.app j), m = desc s . obviously) restate_axiom is_colimit.fac' attribute [simp,reassoc] is_colimit.fac restate_axiom is_colimit.uniq' namespace is_colimit instance subsingleton {t : cocone F} : subsingleton (is_colimit t) := ⟨by intros P Q; cases P; cases Q; congr; ext; solve_by_elim⟩ /-- Given a natural transformation `α : F ⟶ G`, we give a morphism from the cocone point of a colimit cocone over `F` to the cocone point of any cocone over `G`. -/ def map {F G : J ⥤ C} {s : cocone F} (P : is_colimit s) (t : cocone G) (α : F ⟶ G) : s.X ⟶ t.X := P.desc ((cocones.precompose α).obj t) @[simp, reassoc] lemma ι_map {F G : J ⥤ C} {c : cocone F} (hc : is_colimit c) (d : cocone G) (α : F ⟶ G) (j : J) : c.ι.app j ≫ is_colimit.map hc d α = α.app j ≫ d.ι.app j := fac _ _ _ @[simp] lemma desc_self {t : cocone F} (h : is_colimit t) : h.desc t = 𝟙 t.X := (h.uniq _ _ (λ j, comp_id _)).symm /- Repackaging the definition in terms of cocone morphisms. -/ /-- The universal morphism from a colimit cocone to any other cocone. -/ @[simps] def desc_cocone_morphism {t : cocone F} (h : is_colimit t) (s : cocone F) : t ⟶ s := { hom := h.desc s } lemma uniq_cocone_morphism {s t : cocone F} (h : is_colimit t) {f f' : t ⟶ s} : f = f' := have ∀ {g : t ⟶ s}, g = h.desc_cocone_morphism s, by intro g; ext; exact h.uniq _ _ g.w, this.trans this.symm /-- Alternative constructor for `is_colimit`, providing a morphism of cocones rather than a morphism between the cocone points and separately the factorisation condition. -/ @[simps] def mk_cocone_morphism {t : cocone F} (desc : Π (s : cocone F), t ⟶ s) (uniq' : ∀ (s : cocone F) (m : t ⟶ s), m = desc s) : is_colimit t := { desc := λ s, (desc s).hom, uniq' := λ s m w, have cocone_morphism.mk m w = desc s, by apply uniq', congr_arg cocone_morphism.hom this } /-- Colimit cocones on `F` are unique up to isomorphism. -/ @[simps] def unique_up_to_iso {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) : s ≅ t := { hom := P.desc_cocone_morphism t, inv := Q.desc_cocone_morphism s, hom_inv_id' := P.uniq_cocone_morphism, inv_hom_id' := Q.uniq_cocone_morphism } /-- Any cocone morphism between colimit cocones is an isomorphism. -/ def hom_is_iso {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) (f : s ⟶ t) : is_iso f := { inv := Q.desc_cocone_morphism s, hom_inv_id' := P.uniq_cocone_morphism, inv_hom_id' := Q.uniq_cocone_morphism, } /-- Colimits of `F` are unique up to isomorphism. -/ def cocone_point_unique_up_to_iso {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) : s.X ≅ t.X := (cocones.forget F).map_iso (unique_up_to_iso P Q) @[simp, reassoc] lemma comp_cocone_point_unique_up_to_iso_hom {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) (j : J) : s.ι.app j ≫ (cocone_point_unique_up_to_iso P Q).hom = t.ι.app j := (unique_up_to_iso P Q).hom.w _ @[simp, reassoc] lemma comp_cocone_point_unique_up_to_iso_inv {s t : cocone F} (P : is_colimit s) (Q : is_colimit t) (j : J) : t.ι.app j ≫ (cocone_point_unique_up_to_iso P Q).inv = s.ι.app j := (unique_up_to_iso P Q).inv.w _ @[simp, reassoc] lemma cocone_point_unique_up_to_iso_hom_desc {r s t : cocone F} (P : is_colimit s) (Q : is_colimit t) : (cocone_point_unique_up_to_iso P Q).hom ≫ Q.desc r = P.desc r := P.uniq _ _ (by simp) @[simp, reassoc] lemma cocone_point_unique_up_to_iso_inv_desc {r s t : cocone F} (P : is_colimit s) (Q : is_colimit t) : (cocone_point_unique_up_to_iso P Q).inv ≫ P.desc r = Q.desc r := Q.uniq _ _ (by simp) /-- Transport evidence that a cocone is a colimit cocone across an isomorphism of cocones. -/ def of_iso_colimit {r t : cocone F} (P : is_colimit r) (i : r ≅ t) : is_colimit t := is_colimit.mk_cocone_morphism (λ s, i.inv ≫ P.desc_cocone_morphism s) (λ s m, by rw i.eq_inv_comp; apply P.uniq_cocone_morphism) @[simp] lemma of_iso_colimit_desc {r t : cocone F} (P : is_colimit r) (i : r ≅ t) (s) : (P.of_iso_colimit i).desc s = i.inv.hom ≫ P.desc s := rfl /-- Isomorphism of cocones preserves whether or not they are colimiting cocones. -/ def equiv_iso_colimit {r t : cocone F} (i : r ≅ t) : is_colimit r ≃ is_colimit t := { to_fun := λ h, h.of_iso_colimit i, inv_fun := λ h, h.of_iso_colimit i.symm, left_inv := by tidy, right_inv := by tidy } @[simp] lemma equiv_iso_colimit_apply {r t : cocone F} (i : r ≅ t) (P : is_colimit r) : equiv_iso_colimit i P = P.of_iso_colimit i := rfl @[simp] lemma equiv_iso_colimit_symm_apply {r t : cocone F} (i : r ≅ t) (P : is_colimit t) : (equiv_iso_colimit i).symm P = P.of_iso_colimit i.symm := rfl /-- If the canonical morphism to a cocone point from a colimiting cocone point is an iso, then the first cocone was colimiting also. -/ def of_point_iso {r t : cocone F} (P : is_colimit r) [i : is_iso (P.desc t)] : is_colimit t := of_iso_colimit P begin haveI : is_iso (P.desc_cocone_morphism t).hom := i, haveI : is_iso (P.desc_cocone_morphism t) := cocones.cocone_iso_of_hom_iso _, apply as_iso (P.desc_cocone_morphism t), end variables {t : cocone F} lemma hom_desc (h : is_colimit t) {W : C} (m : t.X ⟶ W) : m = h.desc { X := W, ι := { app := λ b, t.ι.app b ≫ m, naturality' := by intros; erw [←assoc, t.ι.naturality, comp_id, comp_id] } } := h.uniq { X := W, ι := { app := λ b, t.ι.app b ≫ m, naturality' := _ } } m (λ b, rfl) /-- Two morphisms out of a colimit are equal if their compositions with each cocone morphism are equal. -/ lemma hom_ext (h : is_colimit t) {W : C} {f f' : t.X ⟶ W} (w : ∀ j, t.ι.app j ≫ f = t.ι.app j ≫ f') : f = f' := by rw [h.hom_desc f, h.hom_desc f']; congr; exact funext w /-- Given a left adjoint functor between categories of cocones, the image of a colimit cocone is a colimit cocone. -/ def of_left_adjoint {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cocone G ⥤ cocone F) [is_left_adjoint h] {c : cocone G} (t : is_colimit c) : is_colimit (h.obj c) := mk_cocone_morphism (λ s, ((adjunction.of_left_adjoint h).hom_equiv c s).symm (t.desc_cocone_morphism _)) (λ s m, (adjunction.hom_equiv_apply_eq _ _ _).1 t.uniq_cocone_morphism) /-- Given two functors which have equivalent categories of cocones, we can transport a colimiting cocone across the equivalence. -/ def of_cocone_equiv {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cocone G ≌ cocone F) {c : cocone G} : is_colimit (h.functor.obj c) ≃ is_colimit c := { to_fun := λ P, of_iso_colimit (of_left_adjoint h.inverse P) (h.unit_iso.symm.app c), inv_fun := of_left_adjoint h.functor, left_inv := by tidy, right_inv := by tidy, } @[simp] lemma of_cocone_equiv_apply_desc {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cocone G ≌ cocone F) {c : cocone G} (P : is_colimit (h.functor.obj c)) (s) : (of_cocone_equiv h P).desc s = (h.unit.app c).hom ≫ (h.inverse.map (P.desc_cocone_morphism (h.functor.obj s))).hom ≫ (h.unit_inv.app s).hom := rfl @[simp] lemma of_cocone_equiv_symm_apply_desc {D : Type u'} [category.{v} D] {G : K ⥤ D} (h : cocone G ≌ cocone F) {c : cocone G} (P : is_colimit c) (s) : ((of_cocone_equiv h).symm P).desc s = (h.functor.map (P.desc_cocone_morphism (h.inverse.obj s))).hom ≫ (h.counit.app s).hom := rfl /-- A cocone precomposed with a natural isomorphism is a colimit cocone if and only if the original cocone is. -/ def precompose_hom_equiv {F G : J ⥤ C} (α : F ≅ G) (c : cocone G) : is_colimit ((cocones.precompose α.hom).obj c) ≃ is_colimit c := of_cocone_equiv (cocones.precompose_equivalence α) /-- A cocone precomposed with the inverse of a natural isomorphism is a colimit cocone if and only if the original cocone is. -/ def precompose_inv_equiv {F G : J ⥤ C} (α : F ≅ G) (c : cocone F) : is_colimit ((cocones.precompose α.inv).obj c) ≃ is_colimit c := precompose_hom_equiv α.symm c /-- The cocone points of two colimit cocones for naturally isomorphic functors are themselves isomorphic. -/ @[simps] def cocone_points_iso_of_nat_iso {F G : J ⥤ C} {s : cocone F} {t : cocone G} (P : is_colimit s) (Q : is_colimit t) (w : F ≅ G) : s.X ≅ t.X := { hom := P.map t w.hom, inv := Q.map s w.inv, hom_inv_id' := P.hom_ext (by tidy), inv_hom_id' := Q.hom_ext (by tidy) } @[reassoc] lemma comp_cocone_points_iso_of_nat_iso_hom {F G : J ⥤ C} {s : cocone F} {t : cocone G} (P : is_colimit s) (Q : is_colimit t) (w : F ≅ G) (j : J) : s.ι.app j ≫ (cocone_points_iso_of_nat_iso P Q w).hom = w.hom.app j ≫ t.ι.app j := by simp @[reassoc] lemma comp_cocone_points_iso_of_nat_iso_inv {F G : J ⥤ C} {s : cocone F} {t : cocone G} (P : is_colimit s) (Q : is_colimit t) (w : F ≅ G) (j : J) : t.ι.app j ≫ (cocone_points_iso_of_nat_iso P Q w).inv = w.inv.app j ≫ s.ι.app j := by simp @[reassoc] lemma cocone_points_iso_of_nat_iso_hom_desc {F G : J ⥤ C} {s : cocone F} {r t : cocone G} (P : is_colimit s) (Q : is_colimit t) (w : F ≅ G) : (cocone_points_iso_of_nat_iso P Q w).hom ≫ Q.desc r = P.map _ w.hom := P.hom_ext (by simp) section equivalence open category_theory.equivalence /-- If `s : cone F` is a limit cone, so is `s` whiskered by an equivalence `e`. -/ def whisker_equivalence {s : cocone F} (P : is_colimit s) (e : K ≌ J) : is_colimit (s.whisker e.functor) := of_left_adjoint (cocones.whiskering_equivalence e).functor P /-- We can prove two cocone points `(s : cocone F).X` and `(t.cocone F).X` are isomorphic if * both cocones are colimit ccoones * their indexing categories are equivalent via some `e : J ≌ K`, * the triangle of functors commutes up to a natural isomorphism: `e.functor ⋙ G ≅ F`. This is the most general form of uniqueness of cocone points, allowing relabelling of both the indexing category (up to equivalence) and the functor (up to natural isomorphism). -/ @[simps] def cocone_points_iso_of_equivalence {F : J ⥤ C} {s : cocone F} {G : K ⥤ C} {t : cocone G} (P : is_colimit s) (Q : is_colimit t) (e : J ≌ K) (w : e.functor ⋙ G ≅ F) : s.X ≅ t.X := let w' : e.inverse ⋙ F ≅ G := (iso_whisker_left e.inverse w).symm ≪≫ inv_fun_id_assoc e G in { hom := P.desc ((cocones.equivalence_of_reindexing e w).functor.obj t), inv := Q.desc ((cocones.equivalence_of_reindexing e.symm w').functor.obj s), hom_inv_id' := begin apply hom_ext P, intros j, dsimp, simp only [limits.cocone.whisker_ι, fac, inv_fun_id_assoc_inv_app, whisker_left_app, assoc, comp_id, limits.cocones.precompose_obj_ι, fac_assoc, nat_trans.comp_app], rw [counit_inv_app_functor, ←functor.comp_map, ←w.inv.naturality_assoc], dsimp, simp, end, inv_hom_id' := by { apply hom_ext Q, tidy, }, } end equivalence /-- The universal property of a colimit cocone: a map `X ⟶ W` is the same as a cocone on `F` with vertex `W`. -/ def hom_iso (h : is_colimit t) (W : C) : (t.X ⟶ W) ≅ (F ⟶ (const J).obj W) := { hom := λ f, (t.extend f).ι, inv := λ ι, h.desc { X := W, ι := ι }, hom_inv_id' := by ext f; apply h.hom_ext; intro j; simp; dsimp; refl } @[simp] lemma hom_iso_hom (h : is_colimit t) {W : C} (f : t.X ⟶ W) : (is_colimit.hom_iso h W).hom f = (t.extend f).ι := rfl /-- The colimit of `F` represents the functor taking `W` to the set of cocones on `F` with vertex `W`. -/ def nat_iso (h : is_colimit t) : coyoneda.obj (op t.X) ≅ F.cocones := nat_iso.of_components (is_colimit.hom_iso h) (by intros; ext; dsimp; rw ←assoc; refl) /-- Another, more explicit, formulation of the universal property of a colimit cocone. See also `hom_iso`. -/ def hom_iso' (h : is_colimit t) (W : C) : ((t.X ⟶ W) : Type v) ≅ { p : Π j, F.obj j ⟶ W // ∀ {j j' : J} (f : j ⟶ j'), F.map f ≫ p j' = p j } := h.hom_iso W ≪≫ { hom := λ ι, ⟨λ j, ι.app j, λ j j' f, by convert ←(ι.naturality f); apply comp_id⟩, inv := λ p, { app := λ j, p.1 j, naturality' := λ j j' f, begin dsimp, rw [comp_id], exact (p.2 f) end } } /-- If G : C → D is a faithful functor which sends t to a colimit cocone, then it suffices to check that the induced maps for the image of t can be lifted to maps of C. -/ def of_faithful {t : cocone F} {D : Type u'} [category.{v} D] (G : C ⥤ D) [faithful G] (ht : is_colimit (G.map_cocone t)) (desc : Π (s : cocone F), t.X ⟶ s.X) (h : ∀ s, G.map (desc s) = ht.desc (G.map_cocone s)) : is_colimit t := { desc := desc, fac' := λ s j, by apply G.map_injective; rw [G.map_comp, h]; apply ht.fac, uniq' := λ s m w, begin apply G.map_injective, rw h, refine ht.uniq (G.map_cocone s) _ (λ j, _), convert ←congr_arg (λ f, G.map f) (w j), apply G.map_comp end } /-- A cocone is a colimit cocone exactly if there is a unique cocone morphism from any other cocone. -/ def iso_unique_cocone_morphism {t : cocone F} : is_colimit t ≅ Π s, unique (t ⟶ s) := { hom := λ h s, { default := h.desc_cocone_morphism s, uniq := λ _, h.uniq_cocone_morphism }, inv := λ h, { desc := λ s, (h s).default.hom, uniq' := λ s f w, congr_arg cocone_morphism.hom ((h s).uniq ⟨f, w⟩) } } namespace of_nat_iso variables {X : C} (h : coyoneda.obj (op X) ≅ F.cocones) /-- If `F.cocones` is corepresented by `X`, each morphism `f : X ⟶ Y` gives a cocone with cone point `Y`. -/ def cocone_of_hom {Y : C} (f : X ⟶ Y) : cocone F := { X := Y, ι := h.hom.app Y f } /-- If `F.cocones` is corepresented by `X`, each cocone `s` gives a morphism `X ⟶ s.X`. -/ def hom_of_cocone (s : cocone F) : X ⟶ s.X := h.inv.app s.X s.ι @[simp] lemma cocone_of_hom_of_cocone (s : cocone F) : cocone_of_hom h (hom_of_cocone h s) = s := begin dsimp [cocone_of_hom, hom_of_cocone], cases s, congr, dsimp, exact congr_fun (congr_fun (congr_arg nat_trans.app h.inv_hom_id) s_X) s_ι, end @[simp] lemma hom_of_cocone_of_hom {Y : C} (f : X ⟶ Y) : hom_of_cocone h (cocone_of_hom h f) = f := congr_fun (congr_fun (congr_arg nat_trans.app h.hom_inv_id) Y) f /-- If `F.cocones` is corepresented by `X`, the cocone corresponding to the identity morphism on `X` will be a colimit cocone. -/ def colimit_cocone : cocone F := cocone_of_hom h (𝟙 X) /-- If `F.cocones` is corepresented by `X`, the cocone corresponding to a morphism `f : Y ⟶ X` is the colimit cocone extended by `f`. -/ lemma cocone_of_hom_fac {Y : C} (f : X ⟶ Y) : cocone_of_hom h f = (colimit_cocone h).extend f := begin dsimp [cocone_of_hom, colimit_cocone, cocone.extend], congr' with j, have t := congr_fun (h.hom.naturality f) (𝟙 X), dsimp at t, simp only [id_comp] at t, rw congr_fun (congr_arg nat_trans.app t) j, refl, end /-- If `F.cocones` is corepresented by `X`, any cocone is the extension of the colimit cocone by the corresponding morphism. -/ lemma cocone_fac (s : cocone F) : (colimit_cocone h).extend (hom_of_cocone h s) = s := begin rw ←cocone_of_hom_of_cocone h s, conv_lhs { simp only [hom_of_cocone_of_hom] }, apply (cocone_of_hom_fac _ _).symm, end end of_nat_iso section open of_nat_iso /-- If `F.cocones` is corepresentable, then the cocone corresponding to the identity morphism on the representing object is a colimit cocone. -/ def of_nat_iso {X : C} (h : coyoneda.obj (op X) ≅ F.cocones) : is_colimit (colimit_cocone h) := { desc := λ s, hom_of_cocone h s, fac' := λ s j, begin have h := cocone_fac h s, cases s, injection h with h₁ h₂, simp only [heq_iff_eq] at h₂, conv_rhs { rw ← h₂ }, refl, end, uniq' := λ s m w, begin rw ←hom_of_cocone_of_hom h m, congr, rw cocone_of_hom_fac, dsimp, cases s, congr' with j, exact w j, end } end end is_colimit section limit /-- `limit_cone F` contains a cone over `F` together with the information that it is a limit. -/ @[nolint has_inhabited_instance] structure limit_cone (F : J ⥤ C) := (cone : cone F) (is_limit : is_limit cone) /-- `has_limit F` represents the mere existence of a limit for `F`. -/ class has_limit (F : J ⥤ C) : Prop := mk' :: (exists_limit : nonempty (limit_cone F)) lemma has_limit.mk {F : J ⥤ C} (d : limit_cone F) : has_limit F := ⟨nonempty.intro d⟩ /-- Use the axiom of choice to extract explicit `limit_cone F` from `has_limit F`. -/ def get_limit_cone (F : J ⥤ C) [has_limit F] : limit_cone F := classical.choice $ has_limit.exists_limit variables (J C) /-- `C` has limits of shape `J` if there exists a limit for every functor `F : J ⥤ C`. -/ class has_limits_of_shape : Prop := (has_limit : Π F : J ⥤ C, has_limit F) /-- `C` has all (small) limits if it has limits of every shape. -/ class has_limits : Prop := (has_limits_of_shape : Π (J : Type v) [𝒥 : small_category J], has_limits_of_shape J C) variables {J C} @[priority 100] -- see Note [lower instance priority] instance has_limit_of_has_limits_of_shape {J : Type v} [small_category J] [H : has_limits_of_shape J C] (F : J ⥤ C) : has_limit F := has_limits_of_shape.has_limit F @[priority 100] -- see Note [lower instance priority] instance has_limits_of_shape_of_has_limits {J : Type v} [small_category J] [H : has_limits C] : has_limits_of_shape J C := has_limits.has_limits_of_shape J /- Interface to the `has_limit` class. -/ /-- An arbitrary choice of limit cone for a functor. -/ def limit.cone (F : J ⥤ C) [has_limit F] : cone F := (get_limit_cone F).cone /-- An arbitrary choice of limit object of a functor. -/ def limit (F : J ⥤ C) [has_limit F] := (limit.cone F).X /-- The projection from the limit object to a value of the functor. -/ def limit.π (F : J ⥤ C) [has_limit F] (j : J) : limit F ⟶ F.obj j := (limit.cone F).π.app j @[simp] lemma limit.cone_X {F : J ⥤ C} [has_limit F] : (limit.cone F).X = limit F := rfl @[simp] lemma limit.cone_π {F : J ⥤ C} [has_limit F] (j : J) : (limit.cone F).π.app j = limit.π _ j := rfl @[simp, reassoc] lemma limit.w (F : J ⥤ C) [has_limit F] {j j' : J} (f : j ⟶ j') : limit.π F j ≫ F.map f = limit.π F j' := (limit.cone F).w f /-- Evidence that the arbitrary choice of cone provied by `limit.cone F` is a limit cone. -/ def limit.is_limit (F : J ⥤ C) [has_limit F] : is_limit (limit.cone F) := (get_limit_cone F).is_limit /-- The morphism from the cone point of any other cone to the limit object. -/ def limit.lift (F : J ⥤ C) [has_limit F] (c : cone F) : c.X ⟶ limit F := (limit.is_limit F).lift c @[simp] lemma limit.is_limit_lift {F : J ⥤ C} [has_limit F] (c : cone F) : (limit.is_limit F).lift c = limit.lift F c := rfl @[simp, reassoc] lemma limit.lift_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) : limit.lift F c ≫ limit.π F j = c.π.app j := is_limit.fac _ c j /-- Functoriality of limits. Usually this morphism should be accessed through `lim.map`, but may be needed separately when you have specified limits for the source and target functors, but not necessarily for all functors of shape `J`. -/ def lim_map {F G : J ⥤ C} [has_limit F] [has_limit G] (α : F ⟶ G) : limit F ⟶ limit G := is_limit.map _ (limit.is_limit G) α @[simp, reassoc] lemma lim_map_π {F G : J ⥤ C} [has_limit F] [has_limit G] (α : F ⟶ G) (j : J) : lim_map α ≫ limit.π G j = limit.π F j ≫ α.app j := limit.lift_π _ j /-- The cone morphism from any cone to the arbitrary choice of limit cone. -/ def limit.cone_morphism {F : J ⥤ C} [has_limit F] (c : cone F) : c ⟶ limit.cone F := (limit.is_limit F).lift_cone_morphism c @[simp] lemma limit.cone_morphism_hom {F : J ⥤ C} [has_limit F] (c : cone F) : (limit.cone_morphism c).hom = limit.lift F c := rfl lemma limit.cone_morphism_π {F : J ⥤ C} [has_limit F] (c : cone F) (j : J) : (limit.cone_morphism c).hom ≫ limit.π F j = c.π.app j := by simp @[simp, reassoc] lemma limit.cone_point_unique_up_to_iso_hom_comp {F : J ⥤ C} [has_limit F] {c : cone F} (hc : is_limit c) (j : J) : (is_limit.cone_point_unique_up_to_iso hc (limit.is_limit _)).hom ≫ limit.π F j = c.π.app j := is_limit.cone_point_unique_up_to_iso_hom_comp _ _ _ @[simp, reassoc] lemma limit.cone_point_unique_up_to_iso_inv_comp {F : J ⥤ C} [has_limit F] {c : cone F} (hc : is_limit c) (j : J) : (is_limit.cone_point_unique_up_to_iso (limit.is_limit _) hc).inv ≫ limit.π F j = c.π.app j := is_limit.cone_point_unique_up_to_iso_inv_comp _ _ _ /-- Given any other limit cone for `F`, the chosen `limit F` is isomorphic to the cone point. -/ def limit.iso_limit_cone {F : J ⥤ C} [has_limit F] (t : limit_cone F) : limit F ≅ t.cone.X := is_limit.cone_point_unique_up_to_iso (limit.is_limit F) t.is_limit @[simp, reassoc] lemma limit.iso_limit_cone_hom_π {F : J ⥤ C} [has_limit F] (t : limit_cone F) (j : J) : (limit.iso_limit_cone t).hom ≫ t.cone.π.app j = limit.π F j := by { dsimp [limit.iso_limit_cone, is_limit.cone_point_unique_up_to_iso], tidy, } @[simp, reassoc] lemma limit.iso_limit_cone_inv_π {F : J ⥤ C} [has_limit F] (t : limit_cone F) (j : J) : (limit.iso_limit_cone t).inv ≫ limit.π F j = t.cone.π.app j := by { dsimp [limit.iso_limit_cone, is_limit.cone_point_unique_up_to_iso], tidy, } @[ext] lemma limit.hom_ext {F : J ⥤ C} [has_limit F] {X : C} {f f' : X ⟶ limit F} (w : ∀ j, f ≫ limit.π F j = f' ≫ limit.π F j) : f = f' := (limit.is_limit F).hom_ext w @[simp] lemma limit.lift_cone {F : J ⥤ C} [has_limit F] : limit.lift F (limit.cone F) = 𝟙 (limit F) := (limit.is_limit _).lift_self /-- The isomorphism (in `Type`) between morphisms from a specified object `W` to the limit object, and cones with cone point `W`. -/ def limit.hom_iso (F : J ⥤ C) [has_limit F] (W : C) : (W ⟶ limit F) ≅ (F.cones.obj (op W)) := (limit.is_limit F).hom_iso W @[simp] lemma limit.hom_iso_hom (F : J ⥤ C) [has_limit F] {W : C} (f : W ⟶ limit F) : (limit.hom_iso F W).hom f = (const J).map f ≫ (limit.cone F).π := (limit.is_limit F).hom_iso_hom f /-- The isomorphism (in `Type`) between morphisms from a specified object `W` to the limit object, and an explicit componentwise description of cones with cone point `W`. -/ def limit.hom_iso' (F : J ⥤ C) [has_limit F] (W : C) : ((W ⟶ limit F) : Type v) ≅ { p : Π j, W ⟶ F.obj j // ∀ {j j' : J} (f : j ⟶ j'), p j ≫ F.map f = p j' } := (limit.is_limit F).hom_iso' W lemma limit.lift_extend {F : J ⥤ C} [has_limit F] (c : cone F) {X : C} (f : X ⟶ c.X) : limit.lift F (c.extend f) = f ≫ limit.lift F c := by obviously /-- If a functor `F` has a limit, so does any naturally isomorphic functor. -/ lemma has_limit_of_iso {F G : J ⥤ C} [has_limit F] (α : F ≅ G) : has_limit G := has_limit.mk { cone := (cones.postcompose α.hom).obj (limit.cone F), is_limit := { lift := λ s, limit.lift F ((cones.postcompose α.inv).obj s), fac' := λ s j, begin rw [cones.postcompose_obj_π, nat_trans.comp_app, limit.cone_π, ←category.assoc, limit.lift_π], simp end, uniq' := λ s m w, begin apply limit.hom_ext, intro j, rw [limit.lift_π, cones.postcompose_obj_π, nat_trans.comp_app, ←nat_iso.app_inv, iso.eq_comp_inv], simpa using w j end } } /-- If a functor `G` has the same collection of cones as a functor `F` which has a limit, then `G` also has a limit. -/ -- See the construction of limits from products and equalizers -- for an example usage. lemma has_limit.of_cones_iso {J K : Type v} [small_category J] [small_category K] (F : J ⥤ C) (G : K ⥤ C) (h : F.cones ≅ G.cones) [has_limit F] : has_limit G := has_limit.mk ⟨_, is_limit.of_nat_iso ((is_limit.nat_iso (limit.is_limit F)) ≪≫ h)⟩ /-- The limits of `F : J ⥤ C` and `G : J ⥤ C` are isomorphic, if the functors are naturally isomorphic. -/ def has_limit.iso_of_nat_iso {F G : J ⥤ C} [has_limit F] [has_limit G] (w : F ≅ G) : limit F ≅ limit G := is_limit.cone_points_iso_of_nat_iso (limit.is_limit F) (limit.is_limit G) w @[simp, reassoc] lemma has_limit.iso_of_nat_iso_hom_π {F G : J ⥤ C} [has_limit F] [has_limit G] (w : F ≅ G) (j : J) : (has_limit.iso_of_nat_iso w).hom ≫ limit.π G j = limit.π F j ≫ w.hom.app j := is_limit.cone_points_iso_of_nat_iso_hom_comp _ _ _ _ @[simp, reassoc] lemma has_limit.lift_iso_of_nat_iso_hom {F G : J ⥤ C} [has_limit F] [has_limit G] (t : cone F) (w : F ≅ G) : limit.lift F t ≫ (has_limit.iso_of_nat_iso w).hom = limit.lift G ((cones.postcompose w.hom).obj _) := is_limit.lift_comp_cone_points_iso_of_nat_iso_hom _ _ _ /-- The limits of `F : J ⥤ C` and `G : K ⥤ C` are isomorphic, if there is an equivalence `e : J ≌ K` making the triangle commute up to natural isomorphism. -/ def has_limit.iso_of_equivalence {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) : limit F ≅ limit G := is_limit.cone_points_iso_of_equivalence (limit.is_limit F) (limit.is_limit G) e w @[simp] lemma has_limit.iso_of_equivalence_hom_π {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (k : K) : (has_limit.iso_of_equivalence e w).hom ≫ limit.π G k = limit.π F (e.inverse.obj k) ≫ w.inv.app (e.inverse.obj k) ≫ G.map (e.counit.app k) := begin simp only [has_limit.iso_of_equivalence, is_limit.cone_points_iso_of_equivalence_hom], dsimp, simp, end @[simp] lemma has_limit.iso_of_equivalence_inv_π {F : J ⥤ C} [has_limit F] {G : K ⥤ C} [has_limit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (j : J) : (has_limit.iso_of_equivalence e w).inv ≫ limit.π F j = limit.π G (e.functor.obj j) ≫ w.hom.app j := begin simp only [has_limit.iso_of_equivalence, is_limit.cone_points_iso_of_equivalence_hom], dsimp, simp, end section pre variables (F) [has_limit F] (E : K ⥤ J) [has_limit (E ⋙ F)] /-- The canonical morphism from the limit of `F` to the limit of `E ⋙ F`. -/ def limit.pre : limit F ⟶ limit (E ⋙ F) := limit.lift (E ⋙ F) ((limit.cone F).whisker E) @[simp] lemma limit.pre_π (k : K) : limit.pre F E ≫ limit.π (E ⋙ F) k = limit.π F (E.obj k) := by { erw is_limit.fac, refl } @[simp] lemma limit.lift_pre (c : cone F) : limit.lift F c ≫ limit.pre F E = limit.lift (E ⋙ F) (c.whisker E) := by ext; simp variables {L : Type v} [small_category L] variables (D : L ⥤ K) [has_limit (D ⋙ E ⋙ F)] @[simp] lemma limit.pre_pre : limit.pre F E ≫ limit.pre (E ⋙ F) D = limit.pre F (D ⋙ E) := by ext j; erw [assoc, limit.pre_π, limit.pre_π, limit.pre_π]; refl variables {E F} /--- If we have particular limit cones available for `E ⋙ F` and for `F`, we obtain a formula for `limit.pre F E`. -/ lemma limit.pre_eq (s : limit_cone (E ⋙ F)) (t : limit_cone F) : limit.pre F E = (limit.iso_limit_cone t).hom ≫ s.is_limit.lift ((t.cone).whisker E) ≫ (limit.iso_limit_cone s).inv := by tidy end pre section post variables {D : Type u'} [category.{v} D] variables (F) [has_limit F] (G : C ⥤ D) [has_limit (F ⋙ G)] /-- The canonical morphism from `G` applied to the limit of `F` to the limit of `F ⋙ G`. -/ def limit.post : G.obj (limit F) ⟶ limit (F ⋙ G) := limit.lift (F ⋙ G) (G.map_cone (limit.cone F)) @[simp] lemma limit.post_π (j : J) : limit.post F G ≫ limit.π (F ⋙ G) j = G.map (limit.π F j) := by { erw is_limit.fac, refl } @[simp] lemma limit.lift_post (c : cone F) : G.map (limit.lift F c) ≫ limit.post F G = limit.lift (F ⋙ G) (G.map_cone c) := by { ext, rw [assoc, limit.post_π, ←G.map_comp, limit.lift_π, limit.lift_π], refl } @[simp] lemma limit.post_post {E : Type u''} [category.{v} E] (H : D ⥤ E) [has_limit ((F ⋙ G) ⋙ H)] : /- H G (limit F) ⟶ H (limit (F ⋙ G)) ⟶ limit ((F ⋙ G) ⋙ H) equals -/ /- H G (limit F) ⟶ limit (F ⋙ (G ⋙ H)) -/ H.map (limit.post F G) ≫ limit.post (F ⋙ G) H = limit.post F (G ⋙ H) := by ext; erw [assoc, limit.post_π, ←H.map_comp, limit.post_π, limit.post_π]; refl end post lemma limit.pre_post {D : Type u'} [category.{v} D] (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D) [has_limit F] [has_limit (E ⋙ F)] [has_limit (F ⋙ G)] [has_limit ((E ⋙ F) ⋙ G)] : /- G (limit F) ⟶ G (limit (E ⋙ F)) ⟶ limit ((E ⋙ F) ⋙ G) vs -/ /- G (limit F) ⟶ limit F ⋙ G ⟶ limit (E ⋙ (F ⋙ G)) or -/ G.map (limit.pre F E) ≫ limit.post (E ⋙ F) G = limit.post F G ≫ limit.pre (F ⋙ G) E := by ext; erw [assoc, limit.post_π, ←G.map_comp, limit.pre_π, assoc, limit.pre_π, limit.post_π]; refl open category_theory.equivalence instance has_limit_equivalence_comp (e : K ≌ J) [has_limit F] : has_limit (e.functor ⋙ F) := has_limit.mk { cone := cone.whisker e.functor (limit.cone F), is_limit := is_limit.whisker_equivalence (limit.is_limit F) e, } local attribute [elab_simple] inv_fun_id_assoc -- not entirely sure why this is needed /-- If a `E ⋙ F` has a limit, and `E` is an equivalence, we can construct a limit of `F`. -/ lemma has_limit_of_equivalence_comp (e : K ≌ J) [has_limit (e.functor ⋙ F)] : has_limit F := begin haveI : has_limit (e.inverse ⋙ e.functor ⋙ F) := limits.has_limit_equivalence_comp e.symm, apply has_limit_of_iso (e.inv_fun_id_assoc F), end -- `has_limit_comp_equivalence` and `has_limit_of_comp_equivalence` -- are proved in `category_theory/adjunction/limits.lean`. section lim_functor variables [has_limits_of_shape J C] section local attribute [simp] lim_map /-- `limit F` is functorial in `F`, when `C` has all limits of shape `J`. -/ @[simps obj] def lim : (J ⥤ C) ⥤ C := { obj := λ F, limit F, map := λ F G α, lim_map α, map_id' := λ F, by { ext, erw [lim_map_π, category.id_comp, category.comp_id] }, map_comp' := λ F G H α β, by ext; erw [assoc, is_limit.fac, is_limit.fac, ←assoc, is_limit.fac, assoc]; refl } end variables {F} {G : J ⥤ C} (α : F ⟶ G) @[simp, reassoc] lemma limit.map_π (j : J) : lim.map α ≫ limit.π G j = limit.π F j ≫ α.app j := by apply is_limit.fac @[simp] lemma limit.lift_map (c : cone F) : limit.lift F c ≫ lim.map α = limit.lift G ((cones.postcompose α).obj c) := by ext; rw [assoc, limit.map_π, ←assoc, limit.lift_π, limit.lift_π]; refl lemma limit.map_pre [has_limits_of_shape K C] (E : K ⥤ J) : lim.map α ≫ limit.pre G E = limit.pre F E ≫ lim.map (whisker_left E α) := by ext; rw [assoc, limit.pre_π, limit.map_π, assoc, limit.map_π, ←assoc, limit.pre_π]; refl lemma limit.map_pre' [has_limits_of_shape K C] (F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟶ E₂) : limit.pre F E₂ = limit.pre F E₁ ≫ lim.map (whisker_right α F) := by ext1; simp [← category.assoc] lemma limit.id_pre (F : J ⥤ C) : limit.pre F (𝟭 _) = lim.map (functor.left_unitor F).inv := by tidy lemma limit.map_post {D : Type u'} [category.{v} D] [has_limits_of_shape J D] (H : C ⥤ D) : /- H (limit F) ⟶ H (limit G) ⟶ limit (G ⋙ H) vs H (limit F) ⟶ limit (F ⋙ H) ⟶ limit (G ⋙ H) -/ H.map (lim.map α) ≫ limit.post G H = limit.post F H ≫ lim.map (whisker_right α H) := begin ext, rw [assoc, limit.post_π, ←H.map_comp, limit.map_π, H.map_comp], rw [assoc, limit.map_π, ←assoc, limit.post_π], refl end /-- The isomorphism between morphisms from `W` to the cone point of the limit cone for `F` and cones over `F` with cone point `W` is natural in `F`. -/ def lim_yoneda : lim ⋙ yoneda ≅ category_theory.cones J C := nat_iso.of_components (λ F, nat_iso.of_components (λ W, limit.hom_iso F (unop W)) (by tidy)) (by tidy) end lim_functor /-- We can transport limits of shape `J` along an equivalence `J ≌ J'`. -/ lemma has_limits_of_shape_of_equivalence {J' : Type v} [small_category J'] (e : J ≌ J') [has_limits_of_shape J C] : has_limits_of_shape J' C := by { constructor, intro F, apply has_limit_of_equivalence_comp e, apply_instance } end limit section colimit /-- `colimit_cocone F` contains a cocone over `F` together with the information that it is a colimit. -/ @[nolint has_inhabited_instance] structure colimit_cocone (F : J ⥤ C) := (cocone : cocone F) (is_colimit : is_colimit cocone) /-- `has_colimit F` represents the mere existence of a colimit for `F`. -/ class has_colimit (F : J ⥤ C) : Prop := mk' :: (exists_colimit : nonempty (colimit_cocone F)) lemma has_colimit.mk {F : J ⥤ C} (d : colimit_cocone F) : has_colimit F := ⟨nonempty.intro d⟩ /-- Use the axiom of choice to extract explicit `colimit_cocone F` from `has_colimit F`. -/ def get_colimit_cocone (F : J ⥤ C) [has_colimit F] : colimit_cocone F := classical.choice $ has_colimit.exists_colimit variables (J C) /-- `C` has colimits of shape `J` if there exists a colimit for every functor `F : J ⥤ C`. -/ class has_colimits_of_shape : Prop := (has_colimit : Π F : J ⥤ C, has_colimit F) /-- `C` has all (small) colimits if it has colimits of every shape. -/ class has_colimits : Prop := (has_colimits_of_shape : Π (J : Type v) [𝒥 : small_category J], has_colimits_of_shape J C) variables {J C} @[priority 100] -- see Note [lower instance priority] instance has_colimit_of_has_colimits_of_shape {J : Type v} [small_category J] [H : has_colimits_of_shape J C] (F : J ⥤ C) : has_colimit F := has_colimits_of_shape.has_colimit F @[priority 100] -- see Note [lower instance priority] instance has_colimits_of_shape_of_has_colimits {J : Type v} [small_category J] [H : has_colimits C] : has_colimits_of_shape J C := has_colimits.has_colimits_of_shape J /- Interface to the `has_colimit` class. -/ /-- An arbitrary choice of colimit cocone of a functor. -/ def colimit.cocone (F : J ⥤ C) [has_colimit F] : cocone F := (get_colimit_cocone F).cocone /-- An arbitrary choice of colimit object of a functor. -/ def colimit (F : J ⥤ C) [has_colimit F] := (colimit.cocone F).X /-- The coprojection from a value of the functor to the colimit object. -/ def colimit.ι (F : J ⥤ C) [has_colimit F] (j : J) : F.obj j ⟶ colimit F := (colimit.cocone F).ι.app j @[simp] lemma colimit.cocone_ι {F : J ⥤ C} [has_colimit F] (j : J) : (colimit.cocone F).ι.app j = colimit.ι _ j := rfl @[simp] lemma colimit.cocone_X {F : J ⥤ C} [has_colimit F] : (colimit.cocone F).X = colimit F := rfl @[simp, reassoc] lemma colimit.w (F : J ⥤ C) [has_colimit F] {j j' : J} (f : j ⟶ j') : F.map f ≫ colimit.ι F j' = colimit.ι F j := (colimit.cocone F).w f /-- Evidence that the arbitrary choice of cocone is a colimit cocone. -/ def colimit.is_colimit (F : J ⥤ C) [has_colimit F] : is_colimit (colimit.cocone F) := (get_colimit_cocone F).is_colimit /-- The morphism from the colimit object to the cone point of any other cocone. -/ def colimit.desc (F : J ⥤ C) [has_colimit F] (c : cocone F) : colimit F ⟶ c.X := (colimit.is_colimit F).desc c @[simp] lemma colimit.is_colimit_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.is_colimit F).desc c = colimit.desc F c := rfl /-- We have lots of lemmas describing how to simplify `colimit.ι F j ≫ _`, and combined with `colimit.ext` we rely on these lemmas for many calculations. However, since `category.assoc` is a `@[simp]` lemma, often expressions are right associated, and it's hard to apply these lemmas about `colimit.ι`. We thus use `reassoc` to define additional `@[simp]` lemmas, with an arbitrary extra morphism. (see `tactic/reassoc_axiom.lean`) -/ @[simp, reassoc] lemma colimit.ι_desc {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) : colimit.ι F j ≫ colimit.desc F c = c.ι.app j := is_colimit.fac _ c j /-- Functoriality of colimits. Usually this morphism should be accessed through `colim.map`, but may be needed separately when you have specified colimits for the source and target functors, but not necessarily for all functors of shape `J`. -/ def colim_map {F G : J ⥤ C} [has_colimit F] [has_colimit G] (α : F ⟶ G) : colimit F ⟶ colimit G := is_colimit.map (colimit.is_colimit F) _ α @[simp, reassoc] lemma ι_colim_map {F G : J ⥤ C} [has_colimit F] [has_colimit G] (α : F ⟶ G) (j : J) : colimit.ι F j ≫ colim_map α = α.app j ≫ colimit.ι G j := colimit.ι_desc _ j /-- The cocone morphism from the arbitrary choice of colimit cocone to any cocone. -/ def colimit.cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.cocone F) ⟶ c := (colimit.is_colimit F).desc_cocone_morphism c @[simp] lemma colimit.cocone_morphism_hom {F : J ⥤ C} [has_colimit F] (c : cocone F) : (colimit.cocone_morphism c).hom = colimit.desc F c := rfl lemma colimit.ι_cocone_morphism {F : J ⥤ C} [has_colimit F] (c : cocone F) (j : J) : colimit.ι F j ≫ (colimit.cocone_morphism c).hom = c.ι.app j := by simp @[simp, reassoc] lemma colimit.comp_cocone_point_unique_up_to_iso_hom {F : J ⥤ C} [has_colimit F] {c : cocone F} (hc : is_colimit c) (j : J) : colimit.ι F j ≫ (is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) hc).hom = c.ι.app j := is_colimit.comp_cocone_point_unique_up_to_iso_hom _ _ _ @[simp, reassoc] lemma colimit.comp_cocone_point_unique_up_to_iso_inv {F : J ⥤ C} [has_colimit F] {c : cocone F} (hc : is_colimit c) (j : J) : colimit.ι F j ≫ (is_colimit.cocone_point_unique_up_to_iso hc (colimit.is_colimit _)).inv = c.ι.app j := is_colimit.comp_cocone_point_unique_up_to_iso_inv _ _ _ /-- Given any other colimit cocone for `F`, the chosen `colimit F` is isomorphic to the cocone point. -/ def colimit.iso_colimit_cocone {F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) : colimit F ≅ t.cocone.X := is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit F) t.is_colimit @[simp, reassoc] lemma colimit.iso_colimit_cocone_ι_hom {F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) (j : J) : colimit.ι F j ≫ (colimit.iso_colimit_cocone t).hom = t.cocone.ι.app j := by { dsimp [colimit.iso_colimit_cocone, is_colimit.cocone_point_unique_up_to_iso], tidy, } @[simp, reassoc] lemma colimit.iso_colimit_cocone_ι_inv {F : J ⥤ C} [has_colimit F] (t : colimit_cocone F) (j : J) : t.cocone.ι.app j ≫ (colimit.iso_colimit_cocone t).inv = colimit.ι F j := by { dsimp [colimit.iso_colimit_cocone, is_colimit.cocone_point_unique_up_to_iso], tidy, } @[ext] lemma colimit.hom_ext {F : J ⥤ C} [has_colimit F] {X : C} {f f' : colimit F ⟶ X} (w : ∀ j, colimit.ι F j ≫ f = colimit.ι F j ≫ f') : f = f' := (colimit.is_colimit F).hom_ext w @[simp] lemma colimit.desc_cocone {F : J ⥤ C} [has_colimit F] : colimit.desc F (colimit.cocone F) = 𝟙 (colimit F) := (colimit.is_colimit _).desc_self /-- The isomorphism (in `Type`) between morphisms from the colimit object to a specified object `W`, and cocones with cone point `W`. -/ def colimit.hom_iso (F : J ⥤ C) [has_colimit F] (W : C) : (colimit F ⟶ W) ≅ (F.cocones.obj W) := (colimit.is_colimit F).hom_iso W @[simp] lemma colimit.hom_iso_hom (F : J ⥤ C) [has_colimit F] {W : C} (f : colimit F ⟶ W) : (colimit.hom_iso F W).hom f = (colimit.cocone F).ι ≫ (const J).map f := (colimit.is_colimit F).hom_iso_hom f /-- The isomorphism (in `Type`) between morphisms from the colimit object to a specified object `W`, and an explicit componentwise description of cocones with cone point `W`. -/ def colimit.hom_iso' (F : J ⥤ C) [has_colimit F] (W : C) : ((colimit F ⟶ W) : Type v) ≅ { p : Π j, F.obj j ⟶ W // ∀ {j j'} (f : j ⟶ j'), F.map f ≫ p j' = p j } := (colimit.is_colimit F).hom_iso' W lemma colimit.desc_extend (F : J ⥤ C) [has_colimit F] (c : cocone F) {X : C} (f : c.X ⟶ X) : colimit.desc F (c.extend f) = colimit.desc F c ≫ f := begin ext1, rw [←category.assoc], simp end /-- If `F` has a colimit, so does any naturally isomorphic functor. -/ -- This has the isomorphism pointing in the opposite direction than in `has_limit_of_iso`. -- This is intentional; it seems to help with elaboration. lemma has_colimit_of_iso {F G : J ⥤ C} [has_colimit F] (α : G ≅ F) : has_colimit G := has_colimit.mk { cocone := (cocones.precompose α.hom).obj (colimit.cocone F), is_colimit := { desc := λ s, colimit.desc F ((cocones.precompose α.inv).obj s), fac' := λ s j, begin rw [cocones.precompose_obj_ι, nat_trans.comp_app, colimit.cocone_ι], rw [category.assoc, colimit.ι_desc, ←nat_iso.app_hom, ←iso.eq_inv_comp], refl end, uniq' := λ s m w, begin apply colimit.hom_ext, intro j, rw [colimit.ι_desc, cocones.precompose_obj_ι, nat_trans.comp_app, ←nat_iso.app_inv, iso.eq_inv_comp], simpa using w j end } } /-- If a functor `G` has the same collection of cocones as a functor `F` which has a colimit, then `G` also has a colimit. -/ lemma has_colimit.of_cocones_iso {J K : Type v} [small_category J] [small_category K] (F : J ⥤ C) (G : K ⥤ C) (h : F.cocones ≅ G.cocones) [has_colimit F] : has_colimit G := has_colimit.mk ⟨_, is_colimit.of_nat_iso ((is_colimit.nat_iso (colimit.is_colimit F)) ≪≫ h)⟩ /-- The colimits of `F : J ⥤ C` and `G : J ⥤ C` are isomorphic, if the functors are naturally isomorphic. -/ def has_colimit.iso_of_nat_iso {F G : J ⥤ C} [has_colimit F] [has_colimit G] (w : F ≅ G) : colimit F ≅ colimit G := is_colimit.cocone_points_iso_of_nat_iso (colimit.is_colimit F) (colimit.is_colimit G) w @[simp, reassoc] lemma has_colimit.iso_of_nat_iso_ι_hom {F G : J ⥤ C} [has_colimit F] [has_colimit G] (w : F ≅ G) (j : J) : colimit.ι F j ≫ (has_colimit.iso_of_nat_iso w).hom = w.hom.app j ≫ colimit.ι G j := is_colimit.comp_cocone_points_iso_of_nat_iso_hom _ _ _ _ @[simp, reassoc] lemma has_colimit.iso_of_nat_iso_hom_desc {F G : J ⥤ C} [has_colimit F] [has_colimit G] (t : cocone G) (w : F ≅ G) : (has_colimit.iso_of_nat_iso w).hom ≫ colimit.desc G t = colimit.desc F ((cocones.precompose w.hom).obj _) := is_colimit.cocone_points_iso_of_nat_iso_hom_desc _ _ _ /-- The colimits of `F : J ⥤ C` and `G : K ⥤ C` are isomorphic, if there is an equivalence `e : J ≌ K` making the triangle commute up to natural isomorphism. -/ def has_colimit.iso_of_equivalence {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) : colimit F ≅ colimit G := is_colimit.cocone_points_iso_of_equivalence (colimit.is_colimit F) (colimit.is_colimit G) e w @[simp] lemma has_colimit.iso_of_equivalence_hom_π {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (j : J) : colimit.ι F j ≫ (has_colimit.iso_of_equivalence e w).hom = F.map (e.unit.app j) ≫ w.inv.app _ ≫ colimit.ι G _ := begin simp [has_colimit.iso_of_equivalence, is_colimit.cocone_points_iso_of_equivalence_inv], dsimp, simp, end @[simp] lemma has_colimit.iso_of_equivalence_inv_π {F : J ⥤ C} [has_colimit F] {G : K ⥤ C} [has_colimit G] (e : J ≌ K) (w : e.functor ⋙ G ≅ F) (k : K) : colimit.ι G k ≫ (has_colimit.iso_of_equivalence e w).inv = G.map (e.counit_inv.app k) ≫ w.hom.app (e.inverse.obj k) ≫ colimit.ι F (e.inverse.obj k) := begin simp [has_colimit.iso_of_equivalence, is_colimit.cocone_points_iso_of_equivalence_inv], dsimp, simp, end section pre variables (F) [has_colimit F] (E : K ⥤ J) [has_colimit (E ⋙ F)] /-- The canonical morphism from the colimit of `E ⋙ F` to the colimit of `F`. -/ def colimit.pre : colimit (E ⋙ F) ⟶ colimit F := colimit.desc (E ⋙ F) ((colimit.cocone F).whisker E) @[simp, reassoc] lemma colimit.ι_pre (k : K) : colimit.ι (E ⋙ F) k ≫ colimit.pre F E = colimit.ι F (E.obj k) := by { erw is_colimit.fac, refl, } @[simp] lemma colimit.pre_desc (c : cocone F) : colimit.pre F E ≫ colimit.desc F c = colimit.desc (E ⋙ F) (c.whisker E) := by ext; rw [←assoc, colimit.ι_pre]; simp variables {L : Type v} [small_category L] variables (D : L ⥤ K) [has_colimit (D ⋙ E ⋙ F)] @[simp] lemma colimit.pre_pre : colimit.pre (E ⋙ F) D ≫ colimit.pre F E = colimit.pre F (D ⋙ E) := begin ext j, rw [←assoc, colimit.ι_pre, colimit.ι_pre], letI : has_colimit ((D ⋙ E) ⋙ F) := show has_colimit (D ⋙ E ⋙ F), by apply_instance, exact (colimit.ι_pre F (D ⋙ E) j).symm end variables {E F} /--- If we have particular colimit cocones available for `E ⋙ F` and for `F`, we obtain a formula for `colimit.pre F E`. -/ lemma colimit.pre_eq (s : colimit_cocone (E ⋙ F)) (t : colimit_cocone F) : colimit.pre F E = (colimit.iso_colimit_cocone s).hom ≫ s.is_colimit.desc ((t.cocone).whisker E) ≫ (colimit.iso_colimit_cocone t).inv := by tidy end pre section post variables {D : Type u'} [category.{v} D] variables (F) [has_colimit F] (G : C ⥤ D) [has_colimit (F ⋙ G)] /-- The canonical morphism from `G` applied to the colimit of `F ⋙ G` to `G` applied to the colimit of `F`. -/ def colimit.post : colimit (F ⋙ G) ⟶ G.obj (colimit F) := colimit.desc (F ⋙ G) (G.map_cocone (colimit.cocone F)) @[simp, reassoc] lemma colimit.ι_post (j : J) : colimit.ι (F ⋙ G) j ≫ colimit.post F G = G.map (colimit.ι F j) := by { erw is_colimit.fac, refl, } @[simp] lemma colimit.post_desc (c : cocone F) : colimit.post F G ≫ G.map (colimit.desc F c) = colimit.desc (F ⋙ G) (G.map_cocone c) := by { ext, rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_desc, colimit.ι_desc], refl } @[simp] lemma colimit.post_post {E : Type u''} [category.{v} E] (H : D ⥤ E) [has_colimit ((F ⋙ G) ⋙ H)] : /- H G (colimit F) ⟶ H (colimit (F ⋙ G)) ⟶ colimit ((F ⋙ G) ⋙ H) equals -/ /- H G (colimit F) ⟶ colimit (F ⋙ (G ⋙ H)) -/ colimit.post (F ⋙ G) H ≫ H.map (colimit.post F G) = colimit.post F (G ⋙ H) := begin ext, rw [←assoc, colimit.ι_post, ←H.map_comp, colimit.ι_post], exact (colimit.ι_post F (G ⋙ H) j).symm end end post lemma colimit.pre_post {D : Type u'} [category.{v} D] (E : K ⥤ J) (F : J ⥤ C) (G : C ⥤ D) [has_colimit F] [has_colimit (E ⋙ F)] [has_colimit (F ⋙ G)] [has_colimit ((E ⋙ F) ⋙ G)] : /- G (colimit F) ⟶ G (colimit (E ⋙ F)) ⟶ colimit ((E ⋙ F) ⋙ G) vs -/ /- G (colimit F) ⟶ colimit F ⋙ G ⟶ colimit (E ⋙ (F ⋙ G)) or -/ colimit.post (E ⋙ F) G ≫ G.map (colimit.pre F E) = colimit.pre (F ⋙ G) E ≫ colimit.post F G := begin ext, rw [←assoc, colimit.ι_post, ←G.map_comp, colimit.ι_pre, ←assoc], letI : has_colimit (E ⋙ F ⋙ G) := show has_colimit ((E ⋙ F) ⋙ G), by apply_instance, erw [colimit.ι_pre (F ⋙ G) E j, colimit.ι_post] end open category_theory.equivalence instance has_colimit_equivalence_comp (e : K ≌ J) [has_colimit F] : has_colimit (e.functor ⋙ F) := has_colimit.mk { cocone := cocone.whisker e.functor (colimit.cocone F), is_colimit := is_colimit.whisker_equivalence (colimit.is_colimit F) e, } /-- If a `E ⋙ F` has a colimit, and `E` is an equivalence, we can construct a colimit of `F`. -/ lemma has_colimit_of_equivalence_comp (e : K ≌ J) [has_colimit (e.functor ⋙ F)] : has_colimit F := begin haveI : has_colimit (e.inverse ⋙ e.functor ⋙ F) := limits.has_colimit_equivalence_comp e.symm, apply has_colimit_of_iso (e.inv_fun_id_assoc F).symm, end section colim_functor variables [has_colimits_of_shape J C] section local attribute [simp] colim_map /-- `colimit F` is functorial in `F`, when `C` has all colimits of shape `J`. -/ @[simps obj] def colim : (J ⥤ C) ⥤ C := { obj := λ F, colimit F, map := λ F G α, colim_map α, map_id' := λ F, by { ext, erw [ι_colim_map, id_comp, comp_id] }, map_comp' := λ F G H α β, by { ext, erw [←assoc, is_colimit.fac, is_colimit.fac, assoc, is_colimit.fac, ←assoc], refl } } end variables {F} {G : J ⥤ C} (α : F ⟶ G) @[simp, reassoc] lemma colimit.ι_map (j : J) : colimit.ι F j ≫ colim.map α = α.app j ≫ colimit.ι G j := by apply is_colimit.fac @[simp] lemma colimit.map_desc (c : cocone G) : colim.map α ≫ colimit.desc G c = colimit.desc F ((cocones.precompose α).obj c) := by ext; rw [←assoc, colimit.ι_map, assoc, colimit.ι_desc, colimit.ι_desc]; refl lemma colimit.pre_map [has_colimits_of_shape K C] (E : K ⥤ J) : colimit.pre F E ≫ colim.map α = colim.map (whisker_left E α) ≫ colimit.pre G E := by ext; rw [←assoc, colimit.ι_pre, colimit.ι_map, ←assoc, colimit.ι_map, assoc, colimit.ι_pre]; refl lemma colimit.pre_map' [has_colimits_of_shape K C] (F : J ⥤ C) {E₁ E₂ : K ⥤ J} (α : E₁ ⟶ E₂) : colimit.pre F E₁ = colim.map (whisker_right α F) ≫ colimit.pre F E₂ := by ext1; simp [← category.assoc] lemma colimit.pre_id (F : J ⥤ C) : colimit.pre F (𝟭 _) = colim.map (functor.left_unitor F).hom := by tidy lemma colimit.map_post {D : Type u'} [category.{v} D] [has_colimits_of_shape J D] (H : C ⥤ D) : /- H (colimit F) ⟶ H (colimit G) ⟶ colimit (G ⋙ H) vs H (colimit F) ⟶ colimit (F ⋙ H) ⟶ colimit (G ⋙ H) -/ colimit.post F H ≫ H.map (colim.map α) = colim.map (whisker_right α H) ≫ colimit.post G H:= begin ext, rw [←assoc, colimit.ι_post, ←H.map_comp, colimit.ι_map, H.map_comp], rw [←assoc, colimit.ι_map, assoc, colimit.ι_post], refl end /-- The isomorphism between morphisms from the cone point of the colimit cocone for `F` to `W` and cocones over `F` with cone point `W` is natural in `F`. -/ def colim_coyoneda : colim.op ⋙ coyoneda ≅ category_theory.cocones J C := nat_iso.of_components (λ F, nat_iso.of_components (colimit.hom_iso (unop F)) (by tidy)) (by tidy) end colim_functor /-- We can transport colimits of shape `J` along an equivalence `J ≌ J'`. -/ lemma has_colimits_of_shape_of_equivalence {J' : Type v} [small_category J'] (e : J ≌ J') [has_colimits_of_shape J C] : has_colimits_of_shape J' C := by { constructor, intro F, apply has_colimit_of_equivalence_comp e, apply_instance } end colimit section opposite /-- If `t : cone F` is a limit cone, then `t.op : cocone F.op` is a colimit cocone. -/ def is_limit.op {t : cone F} (P : is_limit t) : is_colimit t.op := { desc := λ s, (P.lift s.unop).op, fac' := λ s j, congr_arg has_hom.hom.op (P.fac s.unop (unop j)), uniq' := λ s m w, begin rw ← P.uniq s.unop m.unop, { refl, }, { dsimp, intro j, rw ← w, refl, } end } /-- If `t : cocone F` is a colimit cocone, then `t.op : cone F.op` is a limit cone. -/ def is_colimit.op {t : cocone F} (P : is_colimit t) : is_limit t.op := { lift := λ s, (P.desc s.unop).op, fac' := λ s j, congr_arg has_hom.hom.op (P.fac s.unop (unop j)), uniq' := λ s m w, begin rw ← P.uniq s.unop m.unop, { refl, }, { dsimp, intro j, rw ← w, refl, } end } /-- If `t : cone F.op` is a limit cone, then `t.unop : cocone F` is a colimit cocone. -/ def is_limit.unop {t : cone F.op} (P : is_limit t) : is_colimit t.unop := { desc := λ s, (P.lift s.op).unop, fac' := λ s j, congr_arg has_hom.hom.unop (P.fac s.op (op j)), uniq' := λ s m w, begin rw ← P.uniq s.op m.op, { refl, }, { dsimp, intro j, rw ← w, refl, } end } /-- If `t : cocone F.op` is a colimit cocone, then `t.unop : cone F.` is a limit cone. -/ def is_colimit.unop {t : cocone F.op} (P : is_colimit t) : is_limit t.unop := { lift := λ s, (P.desc s.op).unop, fac' := λ s j, congr_arg has_hom.hom.unop (P.fac s.op (op j)), uniq' := λ s m w, begin rw ← P.uniq s.op m.op, { refl, }, { dsimp, intro j, rw ← w, refl, } end } /-- `t : cone F` is a limit cone if and only is `t.op : cocone F.op` is a colimit cocone. -/ def is_limit_equiv_is_colimit_op {t : cone F} : is_limit t ≃ is_colimit t.op := equiv_of_subsingleton_of_subsingleton is_limit.op (λ P, P.unop.of_iso_limit (cones.ext (iso.refl _) (by tidy))) /-- `t : cocone F` is a colimit cocone if and only is `t.op : cone F.op` is a limit cone. -/ def is_colimit_equiv_is_limit_op {t : cocone F} : is_colimit t ≃ is_limit t.op := equiv_of_subsingleton_of_subsingleton is_colimit.op (λ P, P.unop.of_iso_colimit (cocones.ext (iso.refl _) (by tidy))) end opposite end category_theory.limits
3ee1c5c0464b7379f0284fd1ea9e0e928774b920
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/algebra/direct_sum.lean
942aefe61fb2dd131170ae045e3f6f7d555b0a03
[]
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,785
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.dfinsupp import Mathlib.PostPort universes v w u₁ u_1 namespace Mathlib /-! # Direct sum This file defines the direct sum of abelian groups, indexed by a discrete type. ## Notation `⨁ i, β i` is the n-ary direct sum `direct_sum`. This notation is in the `direct_sum` locale, accessible after `open_locale direct_sum`. ## References * https://en.wikipedia.org/wiki/Direct_sum -/ /-- `direct_sum β` is the direct sum of a family of additive commutative monoids `β i`. Note: `open_locale direct_sum` will enable the notation `⨁ i, β i` for `direct_sum β`. -/ def direct_sum (ι : Type v) (β : ι → Type w) [(i : ι) → add_comm_monoid (β i)] := dfinsupp fun (i : ι) => β i namespace direct_sum protected instance add_comm_group {ι : Type v} (β : ι → Type w) [(i : ι) → add_comm_group (β i)] : add_comm_group (direct_sum ι β) := dfinsupp.add_comm_group @[simp] theorem sub_apply {ι : Type v} {β : ι → Type w} [(i : ι) → add_comm_group (β i)] (g₁ : direct_sum ι fun (i : ι) => β i) (g₂ : direct_sum ι fun (i : ι) => β i) (i : ι) : coe_fn (g₁ - g₂) i = coe_fn g₁ i - coe_fn g₂ i := dfinsupp.sub_apply g₁ g₂ i @[simp] theorem zero_apply {ι : Type v} (β : ι → Type w) [(i : ι) → add_comm_monoid (β i)] (i : ι) : coe_fn 0 i = 0 := rfl @[simp] theorem add_apply {ι : Type v} {β : ι → Type w} [(i : ι) → add_comm_monoid (β i)] (g₁ : direct_sum ι fun (i : ι) => β i) (g₂ : direct_sum ι fun (i : ι) => β i) (i : ι) : coe_fn (g₁ + g₂) i = coe_fn g₁ i + coe_fn g₂ i := dfinsupp.add_apply g₁ g₂ i /-- `mk β s x` is the element of `⨁ i, β i` that is zero outside `s` and has coefficient `x i` for `i` in `s`. -/ def mk {ι : Type v} [dec_ι : DecidableEq ι] (β : ι → Type w) [(i : ι) → add_comm_monoid (β i)] (s : finset ι) : ((i : ↥↑s) → β (subtype.val i)) →+ direct_sum ι fun (i : ι) => β i := add_monoid_hom.mk (dfinsupp.mk s) sorry sorry /-- `of i` is the natural inclusion map from `β i` to `⨁ i, β i`. -/ def of {ι : Type v} [dec_ι : DecidableEq ι] (β : ι → Type w) [(i : ι) → add_comm_monoid (β i)] (i : ι) : β i →+ direct_sum ι fun (i : ι) => β i := dfinsupp.single_add_hom β i theorem mk_injective {ι : Type v} [dec_ι : DecidableEq ι] {β : ι → Type w} [(i : ι) → add_comm_monoid (β i)] (s : finset ι) : function.injective ⇑(mk β s) := dfinsupp.mk_injective s theorem of_injective {ι : Type v} [dec_ι : DecidableEq ι] {β : ι → Type w} [(i : ι) → add_comm_monoid (β i)] (i : ι) : function.injective ⇑(of β i) := dfinsupp.single_injective protected theorem induction_on {ι : Type v} [dec_ι : DecidableEq ι] {β : ι → Type w} [(i : ι) → add_comm_monoid (β i)] {C : (direct_sum ι fun (i : ι) => β i) → Prop} (x : direct_sum ι fun (i : ι) => β i) (H_zero : C 0) (H_basic : ∀ (i : ι) (x : β i), C (coe_fn (of β i) x)) (H_plus : ∀ (x y : direct_sum ι fun (i : ι) => β i), C x → C y → C (x + y)) : C x := dfinsupp.induction x H_zero fun (i : ι) (b : β i) (f : dfinsupp fun (i : ι) => (fun (i : ι) => (fun (i : ι) => β i) i) i) (h1 : coe_fn f i = 0) (h2 : b ≠ 0) (ih : C f) => H_plus (dfinsupp.single i b) f (H_basic i b) ih /-- `to_add_monoid φ` is the natural homomorphism from `⨁ i, β i` to `γ` induced by a family `φ` of homomorphisms `β i → γ`. -/ def to_add_monoid {ι : Type v} [dec_ι : DecidableEq ι] {β : ι → Type w} [(i : ι) → add_comm_monoid (β i)] {γ : Type u₁} [add_comm_monoid γ] (φ : (i : ι) → β i →+ γ) : (direct_sum ι fun (i : ι) => β i) →+ γ := coe_fn dfinsupp.lift_add_hom φ @[simp] theorem to_add_monoid_of {ι : Type v} [dec_ι : DecidableEq ι] {β : ι → Type w} [(i : ι) → add_comm_monoid (β i)] {γ : Type u₁} [add_comm_monoid γ] (φ : (i : ι) → β i →+ γ) (i : ι) (x : β i) : coe_fn (to_add_monoid φ) (coe_fn (of β i) x) = coe_fn (φ i) x := dfinsupp.lift_add_hom_apply_single φ i x theorem to_add_monoid.unique {ι : Type v} [dec_ι : DecidableEq ι] {β : ι → Type w} [(i : ι) → add_comm_monoid (β i)] {γ : Type u₁} [add_comm_monoid γ] (ψ : (direct_sum ι fun (i : ι) => β i) →+ γ) (f : direct_sum ι fun (i : ι) => β i) : coe_fn ψ f = coe_fn (to_add_monoid fun (i : ι) => add_monoid_hom.comp ψ (of β i)) f := sorry /-- `from_add_monoid φ` is the natural homomorphism from `γ` to `⨁ i, β i` induced by a family `φ` of homomorphisms `γ → β i`. Note that this is not an isomorphism. Not every homomorphism `γ →+ ⨁ i, β i` arises in this way. -/ def from_add_monoid {ι : Type v} [dec_ι : DecidableEq ι] {β : ι → Type w} [(i : ι) → add_comm_monoid (β i)] {γ : Type u₁} [add_comm_monoid γ] : (direct_sum ι fun (i : ι) => γ →+ β i) →+ γ →+ direct_sum ι fun (i : ι) => β i := to_add_monoid fun (i : ι) => coe_fn add_monoid_hom.comp_hom (of β i) @[simp] theorem from_add_monoid_of {ι : Type v} [dec_ι : DecidableEq ι] {β : ι → Type w} [(i : ι) → add_comm_monoid (β i)] {γ : Type u₁} [add_comm_monoid γ] (i : ι) (f : γ →+ β i) : coe_fn from_add_monoid (coe_fn (of (fun (i : ι) => γ →+ β i) i) f) = add_monoid_hom.comp (of (fun (i : ι) => β i) i) f := sorry theorem from_add_monoid_of_apply {ι : Type v} [dec_ι : DecidableEq ι] {β : ι → Type w} [(i : ι) → add_comm_monoid (β i)] {γ : Type u₁} [add_comm_monoid γ] (i : ι) (f : γ →+ β i) (x : γ) : coe_fn (coe_fn from_add_monoid (coe_fn (of (fun (i : ι) => γ →+ β i) i) f)) x = coe_fn (of (fun (i : ι) => β i) i) (coe_fn f x) := sorry /-- `set_to_set β S T h` is the natural homomorphism `⨁ (i : S), β i → ⨁ (i : T), β i`, where `h : S ⊆ T`. -/ -- TODO: generalize this to remove the assumption `S ⊆ T`. def set_to_set {ι : Type v} [dec_ι : DecidableEq ι] (β : ι → Type w) [(i : ι) → add_comm_monoid (β i)] (S : set ι) (T : set ι) (H : S ⊆ T) : (direct_sum ↥S fun (i : ↥S) => β ↑i) →+ direct_sum ↥T fun (i : ↥T) => β ↑i := to_add_monoid fun (i : ↥S) => of (fun (i : Subtype T) => β ↑i) { val := ↑i, property := sorry } /-- The natural equivalence between `⨁ _ : ι, M` and `M` when `unique ι`. -/ protected def id (M : Type v) (ι : optParam (Type u_1) PUnit) [add_comm_monoid M] [unique ι] : (direct_sum ι fun (_x : ι) => M) ≃+ M := add_equiv.mk ⇑(to_add_monoid fun (_x : ι) => add_monoid_hom.id M) ⇑(of (fun (_x : ι) => M) Inhabited.default) sorry sorry sorry
886a1b8296a8aadce580ff1e871b1f96be3d28ca
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/data/sum/basic.lean
09807595a5c923cfd132ebca12ec892186c342bd
[ "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
515
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, Jeremy Avigad The sum type, aka disjoint union. -/ prelude import init.logic infixr ` ⊕ `:30 := sum universes u v variables {α : Type u} {β : Type v} instance sum.inhabited_left [h : inhabited α] : inhabited (α ⊕ β) := ⟨sum.inl default⟩ instance sum.inhabited_right [h : inhabited β] : inhabited (α ⊕ β) := ⟨sum.inr default⟩
c67eda10e9898287c33d55eee367d08d2a332743
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/match_convoy3.lean
f7397f0923ffe564ce058a38be0bb5bef5ebe075
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
1,587
lean
constant bag_setoid : ∀ A, setoid (list A) attribute [instance] bag_setoid noncomputable definition bag (A : Type) : Type := quotient (bag_setoid A) constant subcount : ∀ {A}, list A → list A → bool constant list.count : ∀ {A}, A → list A → nat constant all_of_subcount_eq_tt : ∀ {A} {l₁ l₂ : list A}, subcount l₁ l₂ = tt → ∀ a, list.count a l₁ ≤ list.count a l₂ constant ex_of_subcount_eq_ff : ∀ {A} {l₁ l₂ : list A}, subcount l₁ l₂ = ff → ∃ a, ¬ list.count a l₁ ≤ list.count a l₂ noncomputable definition count {A} (a : A) (b : bag A) : nat := quotient.lift_on b (λ l, list.count a l) (λ l₁ l₂ h, sorry) noncomputable definition subbag {A} (b₁ b₂ : bag A) := ∀ a, count a b₁ ≤ count a b₂ infix (name := subbag) ⊆ := subbag attribute [instance] noncomputable definition decidable_subbag {A} (b₁ b₂ : bag A) : decidable (b₁ ⊆ b₂) := quotient.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂, match subcount l₁ l₂, rfl : ∀ (b : _), subcount l₁ l₂ = b → _ with | tt, H := is_true (all_of_subcount_eq_tt H) | ff, H := is_false (λ h, exists.elim (ex_of_subcount_eq_ff H) (λ w hw, hw (h w))) end) noncomputable definition decidable_subbag2 {A} (b₁ b₂ : bag A) : decidable (b₁ ⊆ b₂) := quotient.rec_on_subsingleton₂ b₁ b₂ (λ l₁ l₂, match subcount l₁ l₂, rfl : ∀ (b : _), subcount l₁ l₂ = b → _ with | tt, H := is_true (all_of_subcount_eq_tt H) | ff, H := is_false (λ h, exists.elim (ex_of_subcount_eq_ff H) (λ w hw, absurd (h w) hw)) end)
d4d74f0003dd74634f0106ac39fc82ab400e74c2
c780ac8c1c0dd4de0fb63981226f2b53b62fe298
/src/integer.lean
83b5d6707b025f85027b45bb8b392722c3567c96
[]
no_license
jmvlangen/finite_fields
0672670245ccf62b2967d9c5edc2f60c53fc141f
757bd91636e0b3508ee21c92be775eb9d908391e
refs/heads/master
1,586,987,952,433
1,549,629,122,000
1,549,629,122,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
5,467
lean
import ring_theory.principal_ideal_domain import data.zmod.basic import ring_theory namespace int open euclidean_domain ideal is_ring_hom ideal.quotient def nℤ (n : ℕ) : ideal ℤ := span {(n : ℤ)} lemma nℤ_maximal (p : ℕ) : nat.prime p → is_maximal (nℤ p) := assume h₀ : nat.prime p, have prime (p : ℤ), from iff.mp nat.prime_iff_prime_int h₀, have irreducible (p : ℤ), from irreducible_of_prime this, show is_maximal (nℤ p), from principal_ideal_domain.is_maximal_of_irreducible this lemma bot_not_maximal : ¬(is_maximal (⊥ : ideal ℤ)) := assume h : is_maximal ⊥, let J := nℤ 2 in have J ≠ (⊥ : ideal ℤ), from assume h₁ : J = ⊥, have h2 : (2 : ℤ) = 0, from iff.mp span_singleton_eq_bot h₁, have h2n : (2 : ℤ) ≠ 0, from iff.mpr int.coe_nat_ne_zero (nat.succ_ne_zero 1), absurd h2 h2n, have ⊥ < J, from (iff.mpr lattice.bot_lt_iff_ne_bot ‹J ≠ (⊥ : ideal ℤ)›), have J = ⊤, from and.right ‹is_maximal ⊥› J this, have J ≠ ⊤, from and.left (nℤ_maximal 2 nat.prime_two), absurd ‹J = ⊤› ‹J ≠ ⊤› lemma ideal_eq_nℤ (I : ideal ℤ) : ∃ n : ℕ, I = nℤ n := have ∃ m : ℤ, I = span {m}, from (principal_ideal_domain.principal I).principal, let ⟨m, _⟩ := this in have I = nℤ (nat_abs m), from calc I = span {m} : by assumption ... = (span {m}) * ⊤ : by rw mul_top ... = (span {m}) * (span {(norm_unit m : ℤ)}) : by rw [iff.mpr (@span_singleton_eq_top _ _ ↑(norm_unit m)) ⟨(norm_unit m), refl (norm_unit m)⟩] ... = span {m * (norm_unit m : ℤ)} : by simp [span_mul_span] ... = span {(nat_abs m : ℤ)} : by rw coe_nat_abs_eq_mul_norm_unit, show ∃ n : ℕ, I = nℤ n, from ⟨nat_abs m, this⟩ lemma prime_ideal_eq_nℤ (I : ideal ℤ) [is_prime I] : ∃ p : ℕ, I = nℤ p ∧ (p = 0 ∨ nat.prime p) := have ∃ n : ℕ, I = nℤ n, from ideal_eq_nℤ I, let ⟨n, h⟩ := this in or.elim (nat.eq_zero_or_eq_succ_pred n) (assume h₀ : n = 0, show ∃ p : ℕ, I = nℤ p ∧ (p = 0 ∨ nat.prime p), from ⟨n, h, or.inl h₀⟩) (assume h₁ : n = nat.succ (nat.pred n), have n ≠ 0, from eq.symm h₁ ▸ nat.succ_ne_zero (nat.pred n), have (n : ℤ) ≠ 0, from λ h, this (int.of_nat.inj h), have is_prime (nℤ n), from h ▸ ‹is_prime I›, have prime (n : ℤ), from iff.mp (span_singleton_prime ‹(n : ℤ) ≠ 0›) this, have nat.prime n, from iff.mpr nat.prime_iff_prime_int this, show ∃ p : ℕ, I = nℤ p ∧ (p = 0 ∨ nat.prime p), from ⟨n, h, or.inr this⟩) lemma maximal_ideal_eq_nℤ (I : ideal ℤ) [is_maximal I] : ∃ p : ℕ, I = nℤ p ∧ nat.prime p := have ∃ p : ℕ, I = nℤ p ∧ (p = 0 ∨ nat.prime p), from prime_ideal_eq_nℤ I, let ⟨p, hI, hp⟩ := this in or.elim hp (assume h₀ : p = 0, have (p : ℤ) = 0, from int.of_nat.inj_eq.mpr h₀, have I = ⊥, from eq.symm hI ▸ iff.mpr span_singleton_eq_bot this, absurd ‹is_maximal I› (eq.symm this ▸ bot_not_maximal)) (assume h₁ : nat.prime p, show ∃ p : ℕ, I = nℤ p ∧ nat.prime p, from ⟨p, hI, h₁⟩) def ℤmodnℤ (n : ℕ) : Type* := ideal.quotient (nℤ n) instance ℤmodnℤ_comm_ring (n : ℕ) : comm_ring (ℤmodnℤ n) := ideal.quotient.comm_ring (nℤ n) def ℤmodnℤ_equiv_zmod (n : ℕ+) : ℤmodnℤ n ≃r zmod n := let n' : ℤ := n in let ι : ℤ → zmod n := int.cast in have hI : (nℤ n) ≤ ker ι, from span_le.mpr $ set.singleton_subset_iff.mpr $ mem_ker.mpr $ zmod.eq_zero_iff_dvd_int.mpr $ dvd_refl n, show quotient (nℤ n) ≃r zmod n, from { to_fun := factor ι (nℤ n) hI, inv_fun := λ m, ideal.quotient.mk (nℤ n) (m.val), left_inv := assume x : quotient (nℤ n), suffices ∀ y : ℤ, (λ m : zmod n, ideal.quotient.mk (nℤ n) (m.val)) ((factor ι (nℤ n) hI) (ideal.quotient.mk (nℤ n) y)) = ideal.quotient.mk (nℤ n) y, from quotient.induction_on' x this, assume y : ℤ, have y - y % n' = n' * (y / n'), from calc y - y % n' = y % n' + n' * (y / n') - y % n' : by rw (int.mod_add_div y n') ... = n' * (y / n') : by rw (add_sub_cancel'), have n' ∣ y - y % n', from dvd_of_mul_right_eq (y / n') (eq.symm this), have n' ∣ y - ((ι y).val : ℤ), from eq.symm (@zmod.coe_val_cast_int n y) ▸ this, begin unfold, rw (factor_commutes hI), apply eq.symm, apply ideal.quotient.eq.mpr, apply mem_span_singleton.mpr, assumption, end, right_inv := assume x : zmod n, eq.symm (@factor_commutes _ _ _ _ _ _ _ hI x.val) ▸ zmod.cast_val x, hom := factor_to_ring_hom' } def zmod_equiv_ℤmodnℤ (n : ℕ+) : zmod n ≃r ℤmodnℤ n := ring_equiv.symm (ℤmodnℤ_equiv_zmod n) instance ℤmodnℤ_fintype (n : ℕ+) : fintype (ℤmodnℤ n) := (fintype.of_equiv (zmod n) $ ring_equiv.to_equiv $ zmod_equiv_ℤmodnℤ n) lemma quotient_nℤ_card (n : ℕ+) : fintype.card (ℤmodnℤ n) = n := have h₁ : fintype.card (ℤmodnℤ n) = fintype.card (zmod n), from (fintype.of_equiv_card $ ring_equiv.to_equiv $ zmod_equiv_ℤmodnℤ n), have h₂ : fintype.card (zmod n) = n, from zmod.card_zmod n, show fintype.card (ℤmodnℤ n) = n, from eq.trans h₁ h₂ --def ℤmodnℤ_equiv_zmodp (p : ℕ) (hp : nat.prime p) : (ℤmodnℤ p) ≃r zmodp p hp := --ℤmodnℤ_equiv_zmod ⟨p, hp.pos⟩ end int
436257cc2bd3e687d07a694ebf18b7bb6610bc33
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/src/builtin/Nat.lean
94c540df30f2c7dcaf5dd238beda1f7dca810ba0
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
17,705
lean
import kernel import macros variable Nat : Type alias ℕ : Nat namespace Nat builtin numeral builtin add : Nat → Nat → Nat infixl 65 + : add builtin mul : Nat → Nat → Nat infixl 70 * : mul builtin le : Nat → Nat → Bool infix 50 <= : le infix 50 ≤ : le definition ge (a b : Nat) := b ≤ a infix 50 >= : ge infix 50 ≥ : ge definition lt (a b : Nat) := a + 1 ≤ b infix 50 < : lt definition gt (a b : Nat) := b < a infix 50 > : gt definition id (a : Nat) := a notation 55 | _ | : id axiom succ_nz (a : Nat) : a + 1 ≠ 0 axiom succ_inj {a b : Nat} (H : a + 1 = b + 1) : a = b axiom add_zeror (a : Nat) : a + 0 = a axiom add_succr (a b : Nat) : a + (b + 1) = (a + b) + 1 axiom mul_zeror (a : Nat) : a * 0 = 0 axiom mul_succr (a b : Nat) : a * (b + 1) = a * b + a axiom le_def (a b : Nat) : a ≤ b ↔ ∃ c, a + c = b axiom induction {P : Nat → Bool} (H1 : P 0) (H2 : ∀ (n : Nat) (iH : P n), P (n + 1)) : ∀ a, P a theorem induction_on {P : Nat → Bool} (a : Nat) (H1 : P 0) (H2 : ∀ (n : Nat) (iH : P n), P (n + 1)) : P a := induction H1 H2 a theorem pred_nz {a : Nat} : a ≠ 0 → ∃ b, b + 1 = a := induction_on a (λ H : 0 ≠ 0, false_elim (∃ b, b + 1 = 0) (a_neq_a_elim H)) (λ (n : Nat) (iH : n ≠ 0 → ∃ b, b + 1 = n) (H : n + 1 ≠ 0), or_elim (em (n = 0)) (λ Heq0 : n = 0, exists_intro 0 (calc 0 + 1 = n + 1 : { symm Heq0 })) (λ Hne0 : n ≠ 0, obtain (w : Nat) (Hw : w + 1 = n), from (iH Hne0), exists_intro (w + 1) (calc w + 1 + 1 = n + 1 : { Hw }))) theorem discriminate {B : Bool} {a : Nat} (H1: a = 0 → B) (H2 : ∀ n, a = n + 1 → B) : B := or_elim (em (a = 0)) (λ Heq0 : a = 0, H1 Heq0) (λ Hne0 : a ≠ 0, obtain (w : Nat) (Hw : w + 1 = a), from (pred_nz Hne0), H2 w (symm Hw)) theorem add_zerol (a : Nat) : 0 + a = a := induction_on a (show 0 + 0 = 0, from add_zeror 0) (λ (n : Nat) (iH : 0 + n = n), calc 0 + (n + 1) = (0 + n) + 1 : add_succr 0 n ... = n + 1 : { iH }) theorem add_succl (a b : Nat) : (a + 1) + b = (a + b) + 1 := induction_on b (calc (a + 1) + 0 = a + 1 : add_zeror (a + 1) ... = (a + 0) + 1 : { symm (add_zeror a) }) (λ (n : Nat) (iH : (a + 1) + n = (a + n) + 1), calc (a + 1) + (n + 1) = ((a + 1) + n) + 1 : add_succr (a + 1) n ... = ((a + n) + 1) + 1 : { iH } ... = (a + (n + 1)) + 1 : { show (a + n) + 1 = a + (n + 1), from symm (add_succr a n) }) theorem add_comm (a b : Nat) : a + b = b + a := induction_on b (calc a + 0 = a : add_zeror a ... = 0 + a : symm (add_zerol a)) (λ (n : Nat) (iH : a + n = n + a), calc a + (n + 1) = (a + n) + 1 : add_succr a n ... = (n + a) + 1 : { iH } ... = (n + 1) + a : symm (add_succl n a)) theorem add_assoc (a b c : Nat) : (a + b) + c = a + (b + c) := symm (induction_on a (calc 0 + (b + c) = b + c : add_zerol (b + c) ... = (0 + b) + c : { symm (add_zerol b) }) (λ (n : Nat) (iH : n + (b + c) = (n + b) + c), calc (n + 1) + (b + c) = (n + (b + c)) + 1 : add_succl n (b + c) ... = ((n + b) + c) + 1 : { iH } ... = ((n + b) + 1) + c : symm (add_succl (n + b) c) ... = ((n + 1) + b) + c : { show (n + b) + 1 = (n + 1) + b, from symm (add_succl n b) })) theorem mul_zerol (a : Nat) : 0 * a = 0 := induction_on a (show 0 * 0 = 0, from mul_zeror 0) (λ (n : Nat) (iH : 0 * n = 0), calc 0 * (n + 1) = (0 * n) + 0 : mul_succr 0 n ... = 0 + 0 : { iH } ... = 0 : add_zerol 0) theorem mul_succl (a b : Nat) : (a + 1) * b = a * b + b := induction_on b (calc (a + 1) * 0 = 0 : mul_zeror (a + 1) ... = a * 0 : symm (mul_zeror a) ... = a * 0 + 0 : symm (add_zeror (a * 0))) (λ (n : Nat) (iH : (a + 1) * n = a * n + n), calc (a + 1) * (n + 1) = (a + 1) * n + (a + 1) : mul_succr (a + 1) n ... = a * n + n + (a + 1) : { iH } ... = a * n + n + a + 1 : symm (add_assoc (a * n + n) a 1) ... = a * n + (n + a) + 1 : { show a * n + n + a = a * n + (n + a), from add_assoc (a * n) n a } ... = a * n + (a + n) + 1 : { add_comm n a } ... = a * n + a + n + 1 : { symm (add_assoc (a * n) a n) } ... = a * (n + 1) + n + 1 : { symm (mul_succr a n) } ... = a * (n + 1) + (n + 1) : add_assoc (a * (n + 1)) n 1) theorem mul_onel (a : Nat) : 1 * a = a := induction_on a (show 1 * 0 = 0, from mul_zeror 1) (λ (n : Nat) (iH : 1 * n = n), calc 1 * (n + 1) = 1 * n + 1 : mul_succr 1 n ... = n + 1 : { iH }) theorem mul_oner (a : Nat) : a * 1 = a := induction_on a (show 0 * 1 = 0, from mul_zeror 1) (λ (n : Nat) (iH : n * 1 = n), calc (n + 1) * 1 = n * 1 + 1 : mul_succl n 1 ... = n + 1 : { iH }) theorem mul_comm (a b : Nat) : a * b = b * a := induction_on b (calc a * 0 = 0 : mul_zeror a ... = 0 * a : symm (mul_zerol a)) (λ (n : Nat) (iH : a * n = n * a), calc a * (n + 1) = a * n + a : mul_succr a n ... = n * a + a : { iH } ... = (n + 1) * a : symm (mul_succl n a)) theorem distributer (a b c : Nat) : a * (b + c) = a * b + a * c := induction_on a (calc 0 * (b + c) = 0 : mul_zerol (b + c) ... = 0 + 0 : add_zeror 0 ... = 0 * b + 0 : { symm (mul_zerol b) } ... = 0 * b + 0 * c : { symm (mul_zerol c) }) (λ (n : Nat) (iH : n * (b + c) = n * b + n * c), calc (n + 1) * (b + c) = n * (b + c) + (b + c) : mul_succl n (b + c) ... = n * b + n * c + (b + c) : { iH } ... = n * b + n * c + b + c : symm (add_assoc (n * b + n * c) b c) ... = n * b + (n * c + b) + c : { add_assoc (n * b) (n * c) b } ... = n * b + (b + n * c) + c : { add_comm (n * c) b } ... = n * b + b + n * c + c : { symm (add_assoc (n * b) b (n * c)) } ... = (n + 1) * b + n * c + c : { symm (mul_succl n b) } ... = (n + 1) * b + (n * c + c) : add_assoc ((n + 1) * b) (n * c) c ... = (n + 1) * b + (n + 1) * c : { symm (mul_succl n c) }) theorem distributel (a b c : Nat) : (a + b) * c = a * c + b * c := calc (a + b) * c = c * (a + b) : mul_comm (a + b) c ... = c * a + c * b : distributer c a b ... = a * c + c * b : { mul_comm c a } ... = a * c + b * c : { mul_comm c b } theorem mul_assoc (a b c : Nat) : (a * b) * c = a * (b * c) := symm (induction_on a (calc 0 * (b * c) = 0 : mul_zerol (b * c) ... = 0 * c : symm (mul_zerol c) ... = (0 * b) * c : { symm (mul_zerol b) }) (λ (n : Nat) (iH : n * (b * c) = n * b * c), calc (n + 1) * (b * c) = n * (b * c) + (b * c) : mul_succl n (b * c) ... = n * b * c + (b * c) : { iH } ... = (n * b + b) * c : symm (distributel (n * b) b c) ... = (n + 1) * b * c : { symm (mul_succl n b) })) theorem add_left_comm (a b c : Nat) : a + (b + c) = b + (a + c) := left_comm add_comm add_assoc a b c theorem mul_left_comm (a b c : Nat) : a * (b * c) = b * (a * c) := left_comm mul_comm mul_assoc a b c theorem add_injr {a b c : Nat} : a + b = a + c → b = c := induction_on a (λ H : 0 + b = 0 + c, calc b = 0 + b : symm (add_zerol b) ... = 0 + c : H ... = c : add_zerol c) (λ (n : Nat) (iH : n + b = n + c → b = c) (H : n + 1 + b = n + 1 + c), let L1 : n + b + 1 = n + c + 1 := (calc n + b + 1 = n + (b + 1) : add_assoc n b 1 ... = n + (1 + b) : { add_comm b 1 } ... = n + 1 + b : symm (add_assoc n 1 b) ... = n + 1 + c : H ... = n + (1 + c) : add_assoc n 1 c ... = n + (c + 1) : { add_comm 1 c } ... = n + c + 1 : symm (add_assoc n c 1)), L2 : n + b = n + c := succ_inj L1 in iH L2) theorem add_injl {a b c : Nat} (H : a + b = c + b) : a = c := add_injr (calc b + a = a + b : add_comm _ _ ... = c + b : H ... = b + c : add_comm _ _) theorem add_eqz {a b : Nat} (H : a + b = 0) : a = 0 := discriminate (λ H1 : a = 0, H1) (λ (n : Nat) (H1 : a = n + 1), absurd_elim (a = 0) H (calc a + b = n + 1 + b : { H1 } ... = n + (1 + b) : add_assoc n 1 b ... = n + (b + 1) : { add_comm 1 b } ... = n + b + 1 : symm (add_assoc n b 1) ... ≠ 0 : succ_nz (n + b))) theorem le_intro {a b c : Nat} (H : a + c = b) : a ≤ b := (symm (le_def a b)) ◂ (show (∃ x, a + x = b), from exists_intro c H) theorem le_elim {a b : Nat} (H : a ≤ b) : ∃ x, a + x = b := (le_def a b) ◂ H theorem le_refl (a : Nat) : a ≤ a := le_intro (add_zeror a) theorem le_zero (a : Nat) : 0 ≤ a := le_intro (add_zerol a) theorem le_trans {a b c : Nat} (H1 : a ≤ b) (H2 : b ≤ c) : a ≤ c := obtain (w1 : Nat) (Hw1 : a + w1 = b), from (le_elim H1), obtain (w2 : Nat) (Hw2 : b + w2 = c), from (le_elim H2), le_intro (calc a + (w1 + w2) = a + w1 + w2 : symm (add_assoc a w1 w2) ... = b + w2 : { Hw1 } ... = c : Hw2) theorem le_add {a b : Nat} (H : a ≤ b) (c : Nat) : a + c ≤ b + c := obtain (w : Nat) (Hw : a + w = b), from (le_elim H), le_intro (calc a + c + w = a + (c + w) : add_assoc a c w ... = a + (w + c) : { add_comm c w } ... = a + w + c : symm (add_assoc a w c) ... = b + c : { Hw }) theorem le_antisym {a b : Nat} (H1 : a ≤ b) (H2 : b ≤ a) : a = b := obtain (w1 : Nat) (Hw1 : a + w1 = b), from (le_elim H1), obtain (w2 : Nat) (Hw2 : b + w2 = a), from (le_elim H2), let L1 : w1 + w2 = 0 := add_injr (calc a + (w1 + w2) = a + w1 + w2 : { symm (add_assoc a w1 w2) } ... = b + w2 : { Hw1 } ... = a : Hw2 ... = a + 0 : symm (add_zeror a)), L2 : w1 = 0 := add_eqz L1 in calc a = a + 0 : symm (add_zeror a) ... = a + w1 : { symm L2 } ... = b : Hw1 theorem not_lt_0 (a : Nat) : ¬ a < 0 := not_intro (λ H : a + 1 ≤ 0, obtain (w : Nat) (Hw1 : a + 1 + w = 0), from (le_elim H), absurd (calc a + w + 1 = a + (w + 1) : add_assoc _ _ _ ... = a + (1 + w) : { add_comm _ _ } ... = a + 1 + w : symm (add_assoc _ _ _) ... = 0 : Hw1) (succ_nz (a + w))) theorem lt_intro {a b c : Nat} (H : a + 1 + c = b) : a < b := le_intro H theorem lt_elim {a b : Nat} (H : a < b) : ∃ x, a + 1 + x = b := le_elim H theorem lt_le {a b : Nat} (H : a < b) : a ≤ b := obtain (w : Nat) (Hw : a + 1 + w = b), from (le_elim H), le_intro (calc a + (1 + w) = a + 1 + w : symm (add_assoc _ _ _) ... = b : Hw) theorem lt_ne {a b : Nat} (H : a < b) : a ≠ b := not_intro (λ H1 : a = b, obtain (w : Nat) (Hw : a + 1 + w = b), from (lt_elim H), absurd (calc w + 1 = 1 + w : add_comm _ _ ... = 0 : add_injr (calc b + (1 + w) = b + 1 + w : symm (add_assoc b 1 w) ... = a + 1 + w : { symm H1 } ... = b : Hw ... = b + 0 : symm (add_zeror b))) (succ_nz w)) theorem lt_nrefl (a : Nat) : ¬ a < a := not_intro (λ H : a < a, absurd (refl a) (lt_ne H)) theorem lt_trans {a b c : Nat} (H1 : a < b) (H2 : b < c) : a < c := obtain (w1 : Nat) (Hw1 : a + 1 + w1 = b), from (lt_elim H1), obtain (w2 : Nat) (Hw2 : b + 1 + w2 = c), from (lt_elim H2), lt_intro (calc a + 1 + (w1 + 1 + w2) = a + 1 + (w1 + (1 + w2)) : { add_assoc w1 1 w2 } ... = (a + 1 + w1) + (1 + w2) : symm (add_assoc _ _ _) ... = b + (1 + w2) : { Hw1 } ... = b + 1 + w2 : symm (add_assoc _ _ _) ... = c : Hw2) theorem lt_le_trans {a b c : Nat} (H1 : a < b) (H2 : b ≤ c) : a < c := obtain (w1 : Nat) (Hw1 : a + 1 + w1 = b), from (lt_elim H1), obtain (w2 : Nat) (Hw2 : b + w2 = c), from (le_elim H2), lt_intro (calc a + 1 + (w1 + w2) = a + 1 + w1 + w2 : symm (add_assoc _ _ _) ... = b + w2 : { Hw1 } ... = c : Hw2) theorem le_lt_trans {a b c : Nat} (H1 : a ≤ b) (H2 : b < c) : a < c := obtain (w1 : Nat) (Hw1 : a + w1 = b), from (le_elim H1), obtain (w2 : Nat) (Hw2 : b + 1 + w2 = c), from (lt_elim H2), lt_intro (calc a + 1 + (w1 + w2) = a + 1 + w1 + w2 : symm (add_assoc _ _ _) ... = a + (1 + w1) + w2 : { add_assoc a 1 w1 } ... = a + (w1 + 1) + w2 : { add_comm 1 w1 } ... = a + w1 + 1 + w2 : { symm (add_assoc a w1 1) } ... = b + 1 + w2 : { Hw1 } ... = c : Hw2) theorem ne_lt_succ {a b : Nat} (H1 : a ≠ b) (H2 : a < b + 1) : a < b := obtain (w : Nat) (Hw : a + 1 + w = b + 1), from (lt_elim H2), let L : a + w = b := add_injl (calc a + w + 1 = a + (w + 1) : add_assoc _ _ _ ... = a + (1 + w) : { add_comm _ _ } ... = a + 1 + w : symm (add_assoc _ _ _) ... = b + 1 : Hw) in discriminate (λ Hz : w = 0, absurd_elim (a < b) (calc a = a + 0 : symm (add_zeror _) ... = a + w : { symm Hz } ... = b : L) H1) (λ (p : Nat) (Hp : w = p + 1), lt_intro (calc a + 1 + p = a + (1 + p) : add_assoc _ _ _ ... = a + (p + 1) : { add_comm _ _ } ... = a + w : { symm Hp } ... = b : L)) theorem strong_induction {P : Nat → Bool} (H : ∀ n, (∀ m, m < n → P m) → P n) : ∀ a, P a := take a, let stronger : P a ∧ ∀ m, m < a → P m := -- we prove a stronger result by regular induction on a induction_on a (show P 0 ∧ ∀ m, m < 0 → P m, from let c2 : ∀ m, m < 0 → P m := λ (m : Nat) (Hlt : m < 0), absurd_elim (P m) Hlt (not_lt_0 m), c1 : P 0 := H 0 c2 in and_intro c1 c2) (λ (n : Nat) (iH : P n ∧ ∀ m, m < n → P m), show P (n + 1) ∧ ∀ m, m < n + 1 → P m, from let iH1 : P n := and_eliml iH, iH2 : ∀ m, m < n → P m := and_elimr iH, c2 : ∀ m, m < n + 1 → P m := λ (m : Nat) (Hlt : m < n + 1), or_elim (em (m = n)) (λ Heq : m = n, subst iH1 (symm Heq)) (λ Hne : m ≠ n, iH2 m (ne_lt_succ Hne Hlt)), c1 : P (n + 1) := H (n + 1) c2 in and_intro c1 c2) in and_eliml stronger set_opaque add true set_opaque mul true set_opaque le true set_opaque id true -- We should only mark constants as opaque after we proved the theorems/properties we need. -- set_opaque ge true -- set_opaque lt true -- set_opaque gt true -- set_opaque id true end
b65fd118d2bb98a16bb025a19accd97775a55599
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/tests/lean/run/blast5.lean
5886a3d9ee12c4dbf4fe6c3550705aafa9d224f0
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
233
lean
set_option blast.init_depth 10 example (a b : nat) : a = b → b = a := by blast example (a b c : nat) : a = b → a = c → b = c := by blast example (p : nat → Prop) (a b c : nat) : a = b → a = c → p b → p c := by blast
19966ba7b79629a5acd72e064c1ca64ec9089a6b
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/ty1.lean
8d086a9d42c4e57893c110d9306a83c14072af2c
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
209
lean
import Int. variable i : Int. check fun x, x + i check fun x, x + 1 check fun x, x check fun x y, y + i + 1 + x check (fun x, x) i check (fun x, x i) (fun x y, x + 1 + y) check (fun x, x) (fun x y, x + 1 + y)
1157259acd0cc297550f77fc5032761330e02065
be5348f86d661459153802318209304b793c0e2a
/src/forall_keys.lean
abfbd694e261a795f6aec8ec0406e841c2f606e4
[]
no_license
reglayass/lean-avl
6b758c7708bdb3316b1b97ada3e3f259b49da58a
c7bffa75d7548e5ff8cdd7d69f5a58499f883df1
refs/heads/master
1,692,297,536,477
1,633,946,864,000
1,633,946,864,000
340,881,572
4
0
null
null
null
null
UTF-8
Lean
false
false
1,393
lean
import definitions tactic.linarith set_option pp.generalized_field_notation false universe u namespace forall_keys_lemmas open btree variables {α : Type u} /- Transivitity property for keys in a binary search tree -/ lemma forall_keys_trans (t : btree α) (p : nat → nat → Prop) (z x : nat) (h₁ : p x z) (h₂ : ∀ a b c, p a b → p b c → p a c) : forall_keys p z t → forall_keys p x t := begin unfold forall_keys, intros h₃ k' h₄, apply h₂ _ _ _ h₁, apply h₃, exact h₄, end /- Characterization lemma to unfold forall_keys into two different children -/ lemma forall_keys_char {l r : btree α} {k x : nat} {v : α} {p : nat → nat → Prop} : (forall_keys p k l ∧ p k x ∧ forall_keys p k r) ↔ forall_keys p k (node l x v r) := begin split, { intro h₁, cases_matching* (_ ∧ _), unfold forall_keys at *, intros k' h₂, simp [bound] at h₂, cases_matching* (_ ∨ _), { subst h₂, exact h₁_right_left, }, { apply h₁_left, exact h₂, }, { apply h₁_right_right, exact h₂, }, }, { intro h₁, unfold forall_keys at h₁ ⊢, repeat { split }, { intros k' h₂, apply h₁, simp [bound], tauto, }, { apply h₁, simp [bound], }, { intros k' h₂, apply h₁, simp [bound], tauto, }, }, end end forall_keys_lemmas
19e612133a08fcdd56a62dd1872d0f119af3485a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/playground/deriving.lean
d5076ea9990c184960d69c8d74191c7bf5fe9d93
[ "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
11,296
lean
import Lean mutual inductive Vect (α : Type u) (β : Type v) : Nat → Nat → Type max u v where | nil : Vect α β 0 0 | lst : List (Array (Vect α β 0 0)) → Vect α β 0 0 | cons1 : {n m : Nat} → TreeV α β n → Vect α β n m → Vect α β (n+1) m | cons2 : {n m : Nat} → TreeV α β m → Vect α β n m → Vect α β n (m+1) inductive TreeV (α : Type u) (β : Type v) : Nat → Type max u v where | diag : {n : Nat} → Vect α β n n → TreeV α β n | lower : {n m : Nat} → n < m → Vect α β n m → TreeV α β m end mutual partial def aux1 {α β m n} [ToString α] [ToString β] (s : Vect α β m n) : String := let inst1 {m' n' : Nat} : ToString (Vect α β m' n') := ⟨aux1⟩ let inst1 {n' : Nat} : ToString (TreeV α β n') := ⟨aux2⟩ match m, n, s with | _, _, Vect.nil => "nil" | _, _, Vect.lst xs => "lst " ++ toString xs | _, _, Vect.cons1 t v => "cons1 " ++ toString t ++ " " ++ toString v | _, _, Vect.cons2 t v => "cons2 " ++ toString t ++ " " ++ toString v partial def aux2 {α β n} [ToString α] [ToString β] (s : TreeV α β n) : String := let inst1 {m' n' : Nat} : ToString (Vect α β m' n') := ⟨aux1⟩ let inst1 {n' : Nat} : ToString (TreeV α β n') := ⟨aux2⟩ match n, s with | _, TreeV.diag v => "diag " ++ toString v | _, TreeV.lower _ v => "lower " ++ "<proof>" ++ " " ++ toString v end instance {α β m n} [ToString α] [ToString β] : ToString (Vect α β m n) where toString := aux1 instance {α β n} [ToString α] [ToString β] : ToString (TreeV α β n) where toString := aux2 namespace Test mutual inductive Foo (α : Type) where | mk : List (Bla α) → Foo α | leaf : α → Foo α inductive Bla (α : Type) where | nil : Bla α | cons : Foo α → Bla α → Bla α end open Lean open Lean.Meta def tst : MetaM Unit := do let info ← getConstInfoInduct `Test.Bla trace[Meta.debug] "nested: {info.isNested}" pure () #eval tst mutual partial def fooToString {α : Type} [ToString α] (s : Foo α) : String := let inst1 : ToString (Bla α) := ⟨blaToString⟩ match s with | Foo.mk bs => "Foo.mk " ++ toString bs | Foo.leaf a => "Foo.leaf " ++ toString a partial def blaToString {α : Type} [ToString α] (s : Bla α) : String := let inst1 : ToString (Bla α) := ⟨blaToString⟩ let inst2 : ToString (Foo α) := ⟨fooToString⟩ match s with | Bla.nil => "Bla.nil" | Bla.cons h t => "Bla.cons (" ++ toString h ++ ") " ++ toString t end instance [ToString α] : ToString (Foo α) where toString := fooToString instance [ToString α] : ToString (Bla α) where toString := blaToString #eval Foo.mk [Bla.cons (Foo.leaf 10) Bla.nil] end Test namespace Lean.Elab open Meta namespace Deriving /- For type classes such as BEq, ToString, Format -/ namespace Default structure ContextCore where classInfo : ConstantInfo typeInfos : Array InductiveVal auxFunNames : Array Name usePartial : Bool resultType : Syntax structure Header where binders : Array Syntax argNames : Array Name targetName : Name abbrev MkAltRhs := ContextCore → (ctorName : Name) → (ctorArgs : Array (Syntax × Expr)) → TermElabM Syntax structure Context extends ContextCore where mkAltRhs : MkAltRhs def mkContext (className : Name) (typeName : Name) (resultType : Syntax) (mkAltRhs : MkAltRhs) : TermElabM Context := do let indVal ← getConstInfoInduct typeName let mut typeInfos := #[] for typeName in indVal.all do typeInfos ← typeInfos.push (← getConstInfoInduct typeName) let classInfo ← getConstInfo className let mut auxFunNames := #[] for typeName in indVal.all do match className.eraseMacroScopes, typeName.eraseMacroScopes with | Name.str _ c _, Name.str _ t _ => auxFunNames := auxFunNames.push (← mkFreshUserName <| Name.mkSimple <| c.decapitalize ++ t) | _, _ => auxFunNames := auxFunNames.push (← mkFreshUserName `instFn) trace[Meta.debug] "{auxFunNames}" let usePartial := indVal.isNested || typeInfos.size > 1 return { classInfo := classInfo typeInfos := typeInfos auxFunNames := auxFunNames usePartial := usePartial resultType := resultType mkAltRhs := mkAltRhs } def mkInductArgNames (indVal : InductiveVal) : TermElabM (Array Name) := do forallTelescopeReducing indVal.type fun xs _ => do let mut argNames := #[] for x in xs do let localDecl ← getLocalDecl x.fvarId! let paramName ← mkFreshUserName localDecl.userName.eraseMacroScopes argNames := argNames.push paramName pure argNames def mkInductiveApp (indVal : InductiveVal) (argNames : Array Name) : TermElabM Syntax := let f := mkIdent indVal.name let args := argNames.map mkIdent `(@$f $args*) def implicitBinderF := Parser.Term.implicitBinder def instBinderF := Parser.Term.instBinder def explicitBinderF := Parser.Term.explicitBinder def mkImplicitBinders (argNames : Array Name) : TermElabM (Array Syntax) := argNames.mapM fun argName => `(implicitBinderF| { $(mkIdent argName) }) def mkInstImplicitBinders (ctx : Context) (indVal : InductiveVal) (argNames : Array Name) : TermElabM (Array Syntax) := forallBoundedTelescope indVal.type indVal.nparams fun xs _ => do let mut binders := #[] for i in [:xs.size] do try let x := xs[i] let clsName := ctx.classInfo.name let c ← mkAppM clsName #[x] if (← isTypeCorrect c) then let argName := argNames[i] let binder ← `(instBinderF| [ $(mkIdent clsName):ident $(mkIdent argName):ident ]) binders := binders.push binder catch _ => pure () return binders def mkHeader (ctx : Context) (indVal : InductiveVal) : TermElabM Header := do let argNames ← mkInductArgNames indVal let binders ← mkImplicitBinders argNames let targetType ← mkInductiveApp indVal argNames let targetName ← mkFreshUserName `x let targetBinder ← `(explicitBinderF| ($(mkIdent targetName) : $targetType)) let binders := binders ++ (← mkInstImplicitBinders ctx indVal argNames) let binders := binders.push targetBinder return { binders := binders argNames := argNames targetName := targetName } def mkLocalInstanceLetDecls (ctx : Context) (argNames : Array Name) : TermElabM (Array Syntax) := do let mut letDecls := #[] for i in [:ctx.typeInfos.size] do let indVal := ctx.typeInfos[i] let auxFunName := ctx.auxFunNames[i] let currArgNames ← mkInductArgNames indVal let numParams := indVal.nparams let currIndices := currArgNames[numParams:] let binders ← mkImplicitBinders currIndices let argNamesNew := argNames[:numParams] ++ currIndices let indType ← mkInductiveApp indVal argNamesNew let type ← `($(mkIdent ctx.classInfo.name) $indType) let val ← `(⟨$(mkIdent auxFunName)⟩) let instName ← mkFreshUserName `localinst let letDecl ← `(Parser.Term.letDecl| $(mkIdent instName):ident $binders:implicitBinder* : $type := $val) letDecls := letDecls.push letDecl return letDecls def mkLet (letDecls : Array Syntax) (body : Syntax) : TermElabM Syntax := letDecls.foldrM (init := body) fun letDecl body => `(let $letDecl:letDecl; $body) def matchAltExpr := Parser.Term.matchAlt def mkMatch (ctx : Context) (header : Header) (indVal : InductiveVal) (argNames : Array Name) : TermElabM Syntax := do let discrs ← mkDiscrs let alts ← mkAlts `(match $[$discrs],* with | $[$alts:matchAlt]|*) where mkDiscr (varName : Name) : TermElabM Syntax := `(Parser.Term.matchDiscr| $(mkIdent varName):term) mkDiscrs : TermElabM (Array Syntax) := do let mut discrs := #[] -- add indices for argName in argNames[indVal.nparams:] do discrs := discrs.push (← mkDiscr argName) return discrs.push (← mkDiscr header.targetName) mkAlts : TermElabM (Array Syntax) := do let mut alts := #[] for ctorName in indVal.ctors do let mut patterns := #[] -- add `_` pattern for indices for i in [:indVal.nindices] do patterns := patterns.push (← `(_)) let ctorInfo ← getConstInfoCtor ctorName let mut ctorArgs := #[] -- add `_` for inductive parameters, they are inaccessible for i in [:indVal.nparams] do ctorArgs := ctorArgs.push (← `(_)) for i in [:ctorInfo.nfields] do ctorArgs := ctorArgs.push (mkIdent (← mkFreshUserName `y)) patterns := patterns.push (← `(@$(mkIdent ctorName):ident $ctorArgs:term*)) let altRhs ← forallTelescopeReducing ctorInfo.type fun xs _ => ctx.mkAltRhs ctx.toContextCore ctorName (Array.zip ctorArgs xs) let alt ← `(matchAltExpr| $[$patterns:term],* => $altRhs:term) alts := alts.push alt return alts def mkAuxFunction (ctx : Context) (i : Nat) : TermElabM Syntax := do let auxFunName ← ctx.auxFunNames[i] let indVal ← ctx.typeInfos[i] let header ← mkHeader ctx indVal let mut body ← mkMatch ctx header indVal header.argNames if ctx.usePartial then let letDecls ← mkLocalInstanceLetDecls ctx header.argNames body ← mkLet letDecls body let binders := header.binders if ctx.usePartial then `(private partial def $(mkIdent auxFunName):ident $binders:explicitBinder* : $ctx.resultType:term := $body:term) else `(private def $(mkIdent auxFunName):ident $binders:explicitBinder* : $ctx.resultType:term := $body:term) def mkMutualBlock (ctx : Context) : TermElabM Syntax := do let mut auxDefs := #[] for i in [:ctx.typeInfos.size] do auxDefs := auxDefs.push (← mkAuxFunction ctx i) `(mutual $auxDefs:command* end) def mkInstanceCmds (ctx : Context) : TermElabM (Array Syntax) := do let mut instances := #[] for i in [:ctx.typeInfos.size] do let indVal := ctx.typeInfos[i] let auxFunName := ctx.auxFunNames[i] let argNames ← mkInductArgNames indVal let binders ← mkImplicitBinders argNames let binders := binders ++ (← mkInstImplicitBinders ctx indVal argNames) let indType ← mkInductiveApp indVal argNames let type ← `($(mkIdent ctx.classInfo.name) $indType) let val ← `(⟨$(mkIdent auxFunName)⟩) let instCmd ← `(instance $binders:implicitBinder* : $type := $val) trace[Meta.debug] "\n{instCmd}" instances := instances.push instCmd return instances open Command def mkDeriving (className : Name) (typeName : Name) (resultType : Syntax) (mkAltRhs : MkAltRhs) : CommandElabM Unit := do let cmds ← liftTermElabM none do let ctx ← mkContext className typeName resultType mkAltRhs let block ← mkMutualBlock ctx trace[Meta.debug] "\n{block}" return #[block] ++ (← mkInstanceCmds ctx) cmds.forM elabCommand def mkDerivingToString (typeName : Name) : CommandElabM Unit := do mkDeriving `ToString typeName (← `(String)) fun ctx ctorName ctorArgs => quote (toString ctorName) -- TODO syntax[runTstKind] "runTst" : command @[command_elab runTstKind] def elabTst : CommandElab := fun stx => mkDerivingToString `Test.Foo set_option trace.Meta.debug true runTst
957643fec6f6894889e57361b674ea7ec85bf1e7
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/computability/DFA_auto.lean
2050544f984a31080481009eae5acf874a75af2d
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,813
lean
/- Copyright (c) 2020 Fox Thomson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Fox Thomson -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.fintype.basic import Mathlib.computability.language import Mathlib.PostPort universes u v l namespace Mathlib /-! # Deterministic Finite Automata This file contains the definition of a Deterministic Finite Automaton (DFA), a state machine which determines whether a string (implemented as a list over an arbitrary alphabet) is in a regular set in linear time. Note that this definition allows for Automaton with infinite states, a `fintype` instance must be supplied for true DFA's. -/ /-- A DFA is a set of states (`σ`), a transition function from state to state labelled by the alphabet (`step`), a starting state (`start`) and a set of acceptance states (`accept`). -/ structure DFA (α : Type u) (σ : Type v) where step : σ → α → σ start : σ accept : set σ namespace DFA protected instance inhabited {α : Type u} {σ : Type v} [Inhabited σ] : Inhabited (DFA α σ) := { default := mk (fun (_x : σ) (_x : α) => Inhabited.default) Inhabited.default ∅ } /-- `M.eval_from s x` evaluates `M` with input `x` starting from the state `s`. -/ def eval_from {α : Type u} {σ : Type v} (M : DFA α σ) (start : σ) : List α → σ := list.foldl (step M) start /-- `M.eval x` evaluates `M` with input `x` starting from the state `M.start`. -/ def eval {α : Type u} {σ : Type v} (M : DFA α σ) : List α → σ := eval_from M (start M) /-- `M.accepts` is the language of `x` such that `M.eval x` is an accept state. -/ def accepts {α : Type u} {σ : Type v} (M : DFA α σ) : language α := fun (x : List α) => eval M x ∈ accept M end Mathlib
e1646b9a4301667a5bf26d78d3e2b54f4bd22ddd
947b78d97130d56365ae2ec264df196ce769371a
/tests/lean/protected.lean
4765e3d3894ee111fb6a5f81c57049808d43fb7c
[ "Apache-2.0" ]
permissive
shyamalschandra/lean4
27044812be8698f0c79147615b1d5090b9f4b037
6e7a883b21eaf62831e8111b251dc9b18f40e604
refs/heads/master
1,671,417,126,371
1,601,859,995,000
1,601,860,020,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,035
lean
new_frontend namespace Foo protected def x := 10 end Foo open Foo #check x -- error unknown identifier `x` #check Foo.x namespace Bla.Foo protected def y := 20 def z := 30 end Bla.Foo open Bla #check Foo.y open Bla.Foo #check y -- error unknown identifier `y` #check z protected def x := 0 -- Error protected partial def Foo.f (x : Nat) := if x > 0 then f (x-1) * 2 else 1 -- Error protected partial def Bla.f (x : Nat) := if x > 0 then Bla.f (x-1) * 2 else 1 #eval Bla.f 3 namespace Foo protected partial def g (x : Nat) := if x > 0 then g (x-1) * 2 else 1 -- error end Foo namespace Bla protected partial def g (x : Nat) := if x > 0 then Bla.g (x-1) * 2 else 1 #eval g 3 -- error #eval Bla.g 3 end Bla def S (σ : Type) (m : Type → Type) (α : Type) := σ → m (α × σ) namespace S variables {σ : Type} {m : Type → Type} [Monad m] {α : Type} protected def pure (a : α) : S σ m α := fun s => pure (a, s) -- This `pure` is the top-level one. The `pure` being defined here is called `S.pure`. end S
50a18d50ccd046b3fb9f7e054714727951276dfa
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/mvar_backtrack.lean
5b90cceedd0ad83216e74c683090ba63a60a4efd
[ "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
376
lean
namespace foo open nat class lt (n : out_param ℕ) (m : ℕ) instance succ_lt_succ_of_lt (n m) [lt n m] : lt (succ n) (succ m) := by constructor instance zero_lt_succ (m) : lt 0 (succ m) := by constructor class foo (n : out_param ℕ) (m : ℕ) instance I (n m) [lt n 10] [lt m n] : foo n m := by constructor def bar {n} (m) [foo n m] := n #eval bar 0 #eval bar 1 end foo
309a0c9c344918f03aed118afc68585947789a38
367134ba5a65885e863bdc4507601606690974c1
/archive/imo/imo2013_q1.lean
2a74ec917b888d499a050677abe7faec35128a28
[ "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
4,270
lean
/- Copyright (c) 2021 David Renshaw. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Renshaw -/ import data.pnat.basic import data.nat.parity import algebra.big_operators.pi import tactic.ring import tactic.field_simp /-! # IMO 2013 Q1 Prove that for any pair of positive integers k and n, there exist k positive integers m₁, m₂, ..., mₖ (not necessarily different) such that 1 + (2ᵏ - 1)/ n = (1 + 1/m₁) * (1 + 1/m₂) * ... * (1 + 1/mₖ). # Solution Adaptation of the solution found in https://www.imo-official.org/problems/IMO2013SL.pdf We prove a slightly more general version where k does not need to be strictly positive. -/ open_locale big_operators lemma arith_lemma (k n : ℕ) : 0 < 2 * n + 2^k.succ := calc 0 < 2 : zero_lt_two ... = 2^1 : (pow_one 2).symm ... ≤ 2^k.succ : nat.pow_le_pow_of_le_right zero_lt_two (nat.le_add_left 1 k) ... ≤ 2 * n + 2^k.succ : nat.le_add_left _ _ lemma prod_lemma (m : ℕ → ℕ+) (k : ℕ) (nm : ℕ+): ∏ (i : ℕ) in finset.range k, ((1 : ℚ) + 1 / ↑(if i < k then m i else nm)) = ∏ (i : ℕ) in finset.range k, (1 + 1 / m i) := begin suffices : ∀ i, i ∈ finset.range k → (1 : ℚ) + 1 / ↑(if i < k then m i else nm) = 1 + 1 / m i, from finset.prod_congr rfl this, intros i hi, simp [finset.mem_range.mp hi] end theorem imo2013_q1 (n : ℕ+) (k : ℕ) : (∃ m : ℕ → ℕ+, (1 : ℚ) + (2^k - 1) / n = (∏ i in finset.range k, (1 + 1 / m i))) := begin revert n, induction k with pk hpk, { intro n, use (λ_, 1), simp }, -- For the base case, any m works. intro n, obtain ⟨t, ht : ↑n = 2 * t⟩ | ⟨t, ht : ↑n = 2 * t + 1⟩ := (n : ℕ).even_or_odd, { -- even case cases t, -- Eliminate the zero case to simplify later calculations. { exfalso, rw mul_zero at ht, exact pnat.ne_zero n ht }, -- Now we have ht : ↑n = 2 * (t + 1). let t_succ : ℕ+ := ⟨t + 1, t.succ_pos⟩, obtain ⟨pm, hpm⟩ := hpk t_succ, let m := λi, if i < pk then pm i else ⟨2 * t + 2^pk.succ, arith_lemma pk t⟩, use m, have hmpk : (m pk : ℚ) = 2 * t + 2^pk.succ, { have : m pk = ⟨2 * t + 2^pk.succ, _⟩ := if_neg (irrefl pk), simp [this] }, have denom_ne_zero : (2 * (t:ℚ) + 2^pk.succ) ≠ 0, { norm_cast, exact (ne_of_gt $ arith_lemma pk t) }, calc (1 : ℚ) + (2 ^ pk.succ - 1) / ↑n = 1 + (2 * 2 ^ pk - 1) / (2 * (t + 1) : ℕ) : by rw [coe_coe n, ht, pow_succ] ... = (1 + 1 / (2 * t + 2 * 2^pk)) * (1 + (2 ^ pk - 1) / (↑t + 1)) : by { field_simp [t.cast_add_one_ne_zero], ring } ... = (1 + 1 / (2 * t + 2^pk.succ)) * (1 + (2 ^ pk - 1) / t_succ) : by norm_cast ... = (1 + 1 / ↑(m pk)) * ∏ (i : ℕ) in finset.range pk, (1 + 1 / m i) : by rw [hpm, prod_lemma, ←hmpk] ... = ∏ (i : ℕ) in finset.range pk.succ, (1 + 1 / m i) : (finset.prod_range_succ _ pk).symm }, { -- odd case let t_succ : ℕ+ := ⟨t + 1, t.succ_pos⟩, obtain ⟨pm, hpm⟩ := hpk t_succ, let m := λi, if i < pk then pm i else ⟨2 * t + 1, nat.succ_pos _⟩, use m, have hmpk : (m pk : ℚ) = 2 * t + 1, { have : m pk = ⟨2 * t + 1, _⟩ := if_neg (irrefl pk), simp [this] }, have denom_ne_zero : (2 * (t : ℚ) + 1) ≠ 0 := by { norm_cast, apply (2 * t).succ_ne_zero }, calc (1 : ℚ) + (2 ^ pk.succ - 1) / ↑n = 1 + (2 * 2^pk - 1) / (2 * t + 1 : ℕ) : by rw [coe_coe n, ht, pow_succ] ... = (1 + 1 / (2 * t + 1)) * (1 + (2^pk - 1) / (t + 1)) : by { field_simp [t.cast_add_one_ne_zero], ring } ... = (1 + 1 / (2 * t + 1)) * (1 + (2^pk - 1) / t_succ) : by norm_cast ... = (1 + 1 / ↑(m pk)) * ∏ (i : ℕ) in finset.range pk, (1 + 1 / m i) : by rw [hpm, prod_lemma, ←hmpk] ... = ∏ (i : ℕ) in finset.range pk.succ, (1 + 1 / m i) : (finset.prod_range_succ _ pk).symm } end
be5544497790cc910994cb21ca601e0ce166fca0
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/data/real/basic.lean
fe3e26eb596500a246fedddc9294d6bbb3a62df0
[ "Apache-2.0" ]
permissive
ChrisHughes24/mathlib
98322577c460bc6b1fe5c21f42ce33ad1c3e5558
a2a867e827c2a6702beb9efc2b9282bd801d5f9a
refs/heads/master
1,583,848,251,477
1,565,164,247,000
1,565,164,247,000
129,409,993
0
1
Apache-2.0
1,565,164,817,000
1,523,628,059,000
Lean
UTF-8
Lean
false
false
25,879
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn The (classical) real numbers ℝ. This is a direct construction from Cauchy sequences. -/ import order.conditionally_complete_lattice data.real.cau_seq_completion algebra.archimedean order.bounds def real := @cau_seq.completion.Cauchy ℚ _ _ _ abs _ notation `ℝ` := real namespace real open cau_seq cau_seq.completion variables {x y : ℝ} def of_rat (x : ℚ) : ℝ := of_rat x def mk (x : cau_seq ℚ abs) : ℝ := cau_seq.completion.mk x def comm_ring_aux : comm_ring ℝ := cau_seq.completion.comm_ring instance : comm_ring ℝ := { ..comm_ring_aux } /- Extra instances to short-circuit type class resolution -/ instance : ring ℝ := by apply_instance instance : comm_semiring ℝ := by apply_instance instance : semiring ℝ := by apply_instance instance : add_comm_group ℝ := by apply_instance instance : add_group ℝ := by apply_instance instance : add_comm_monoid ℝ := by apply_instance instance : add_monoid ℝ := by apply_instance instance : add_left_cancel_semigroup ℝ := by apply_instance instance : add_right_cancel_semigroup ℝ := by apply_instance instance : add_comm_semigroup ℝ := by apply_instance instance : add_semigroup ℝ := by apply_instance instance : comm_monoid ℝ := by apply_instance instance : monoid ℝ := by apply_instance instance : comm_semigroup ℝ := by apply_instance instance : semigroup ℝ := by apply_instance instance : inhabited ℝ := ⟨0⟩ theorem of_rat_sub (x y : ℚ) : of_rat (x - y) = of_rat x - of_rat y := congr_arg mk (const_sub _ _) instance : has_lt ℝ := ⟨λ x y, quotient.lift_on₂ x y (<) $ λ f₁ g₁ f₂ g₂ hf hg, propext $ ⟨λ h, lt_of_eq_of_lt (setoid.symm hf) (lt_of_lt_of_eq h hg), λ h, lt_of_eq_of_lt hf (lt_of_lt_of_eq h (setoid.symm hg))⟩⟩ @[simp] theorem mk_lt {f g : cau_seq ℚ abs} : mk f < mk g ↔ f < g := iff.rfl theorem mk_eq {f g : cau_seq ℚ abs} : mk f = mk g ↔ f ≈ g := mk_eq theorem quotient_mk_eq_mk (f : cau_seq ℚ abs) : ⟦f⟧ = mk f := rfl theorem mk_eq_mk {f : cau_seq ℚ abs} : cau_seq.completion.mk f = mk f := rfl @[simp] theorem mk_pos {f : cau_seq ℚ abs} : 0 < mk f ↔ pos f := iff_of_eq (congr_arg pos (sub_zero f)) protected def le (x y : ℝ) : Prop := x < y ∨ x = y instance : has_le ℝ := ⟨real.le⟩ @[simp] theorem mk_le {f g : cau_seq ℚ abs} : mk f ≤ mk g ↔ f ≤ g := or_congr iff.rfl quotient.eq theorem add_lt_add_iff_left {a b : ℝ} (c : ℝ) : c + a < c + b ↔ a < b := quotient.induction_on₃ a b c (λ f g h, iff_of_eq (congr_arg pos $ by rw add_sub_add_left_eq_sub)) instance : linear_order ℝ := { le := (≤), lt := (<), le_refl := λ a, or.inr rfl, le_trans := λ a b c, quotient.induction_on₃ a b c $ λ f g h, by simpa [quotient_mk_eq_mk] using le_trans, lt_iff_le_not_le := λ a b, quotient.induction_on₂ a b $ λ f g, by simpa [quotient_mk_eq_mk] using lt_iff_le_not_le, le_antisymm := λ a b, quotient.induction_on₂ a b $ λ f g, by simpa [mk_eq, quotient_mk_eq_mk] using @cau_seq.le_antisymm _ _ f g, le_total := λ a b, quotient.induction_on₂ a b $ λ f g, by simpa [quotient_mk_eq_mk] using le_total f g } instance : partial_order ℝ := by apply_instance instance : preorder ℝ := by apply_instance theorem of_rat_lt {x y : ℚ} : of_rat x < of_rat y ↔ x < y := const_lt protected theorem zero_lt_one : (0 : ℝ) < 1 := of_rat_lt.2 zero_lt_one protected theorem mul_pos {a b : ℝ} : 0 < a → 0 < b → 0 < a * b := quotient.induction_on₂ a b $ λ f g, show pos (f - 0) → pos (g - 0) → pos (f * g - 0), by simpa using cau_seq.mul_pos instance : linear_ordered_comm_ring ℝ := { add_le_add_left := λ a b h c, (le_iff_le_iff_lt_iff_lt.2 $ real.add_lt_add_iff_left c).2 h, zero_ne_one := ne_of_lt real.zero_lt_one, mul_nonneg := λ a b a0 b0, match a0, b0 with | or.inl a0, or.inl b0 := le_of_lt (real.mul_pos a0 b0) | or.inr a0, _ := by simp [a0.symm] | _, or.inr b0 := by simp [b0.symm] end, mul_pos := @real.mul_pos, zero_lt_one := real.zero_lt_one, add_lt_add_left := λ a b h c, (real.add_lt_add_iff_left c).2 h, ..real.comm_ring, ..real.linear_order } /- Extra instances to short-circuit type class resolution -/ instance : linear_ordered_ring ℝ := by apply_instance instance : ordered_ring ℝ := by apply_instance instance : linear_ordered_semiring ℝ := by apply_instance instance : ordered_semiring ℝ := by apply_instance instance : ordered_comm_group ℝ := by apply_instance instance : ordered_cancel_comm_monoid ℝ := by apply_instance instance : ordered_comm_monoid ℝ := by apply_instance instance : domain ℝ := by apply_instance local attribute [instance] classical.prop_decidable noncomputable instance : discrete_linear_ordered_field ℝ := { decidable_le := by apply_instance, ..real.linear_ordered_comm_ring, ..real.domain, ..cau_seq.completion.discrete_field } /- Extra instances to short-circuit type class resolution -/ noncomputable instance : linear_ordered_field ℝ := by apply_instance noncomputable instance : decidable_linear_ordered_comm_ring ℝ := by apply_instance noncomputable instance : decidable_linear_ordered_semiring ℝ := by apply_instance noncomputable instance : decidable_linear_ordered_comm_group ℝ := by apply_instance noncomputable instance discrete_field : discrete_field ℝ := by apply_instance noncomputable instance : field ℝ := by apply_instance noncomputable instance : division_ring ℝ := by apply_instance noncomputable instance : integral_domain ℝ := by apply_instance noncomputable instance : nonzero_comm_ring ℝ := by apply_instance noncomputable instance : decidable_linear_order ℝ := by apply_instance noncomputable instance : lattice.distrib_lattice ℝ := by apply_instance noncomputable instance : lattice.lattice ℝ := by apply_instance noncomputable instance : lattice.semilattice_inf ℝ := by apply_instance noncomputable instance : lattice.semilattice_sup ℝ := by apply_instance noncomputable instance : lattice.has_inf ℝ := by apply_instance noncomputable instance : lattice.has_sup ℝ := by apply_instance lemma le_of_forall_epsilon_le {a b : real} (h : ∀ε, ε > 0 → a ≤ b + ε) : a ≤ b := le_of_forall_le_of_dense $ assume x hxb, calc a ≤ b + (x - b) : h (x-b) $ sub_pos.2 hxb ... = x : by rw [add_comm]; simp open rat @[simp] theorem of_rat_eq_cast : ∀ x : ℚ, of_rat x = x := eq_cast of_rat rfl of_rat_add of_rat_mul theorem le_mk_of_forall_le {f : cau_seq ℚ abs} : (∃ i, ∀ j ≥ i, x ≤ f j) → x ≤ mk f := quotient.induction_on x $ λ g h, le_of_not_lt $ λ ⟨K, K0, hK⟩, let ⟨i, H⟩ := exists_forall_ge_and h $ exists_forall_ge_and hK (f.cauchy₃ $ half_pos K0) in begin apply not_lt_of_le (H _ (le_refl _)).1, rw ← of_rat_eq_cast, refine ⟨_, half_pos K0, i, λ j ij, _⟩, have := add_le_add (H _ ij).2.1 (le_of_lt (abs_lt.1 $ (H _ (le_refl _)).2.2 _ ij).1), rwa [← sub_eq_add_neg, sub_self_div_two, sub_apply, sub_add_sub_cancel] at this end theorem mk_le_of_forall_le {f : cau_seq ℚ abs} {x : ℝ} : (∃ i, ∀ j ≥ i, (f j : ℝ) ≤ x) → mk f ≤ x | ⟨i, H⟩ := by rw [← neg_le_neg_iff, ← mk_eq_mk, mk_neg]; exact le_mk_of_forall_le ⟨i, λ j ij, by simp [H _ ij]⟩ theorem mk_near_of_forall_near {f : cau_seq ℚ abs} {x : ℝ} {ε : ℝ} (H : ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) ≤ ε) : abs (mk f - x) ≤ ε := abs_sub_le_iff.2 ⟨sub_le_iff_le_add'.2 $ mk_le_of_forall_le $ H.imp $ λ i h j ij, sub_le_iff_le_add'.1 (abs_sub_le_iff.1 $ h j ij).1, sub_le.1 $ le_mk_of_forall_le $ H.imp $ λ i h j ij, sub_le.1 (abs_sub_le_iff.1 $ h j ij).2⟩ instance : archimedean ℝ := archimedean_iff_rat_le.2 $ λ x, quotient.induction_on x $ λ f, let ⟨M, M0, H⟩ := f.bounded' 0 in ⟨M, mk_le_of_forall_le ⟨0, λ i _, rat.cast_le.2 $ le_of_lt (abs_lt.1 (H i)).2⟩⟩ /- mark `real` irreducible in order to prevent `auto_cases` unfolding reals, since users rarely want to consider real numbers as Cauchy sequences. Marking `comm_ring_aux` `irreducible` is done to ensure that there are no problems with non definitionally equal instances, caused by making `real` irreducible-/ attribute [irreducible] real comm_ring_aux noncomputable instance : floor_ring ℝ := archimedean.floor_ring _ theorem is_cau_seq_iff_lift {f : ℕ → ℚ} : is_cau_seq abs f ↔ is_cau_seq abs (λ i, (f i : ℝ)) := ⟨λ H ε ε0, let ⟨δ, δ0, δε⟩ := exists_pos_rat_lt ε0 in (H _ δ0).imp $ λ i hi j ij, lt_trans (by simpa using (@rat.cast_lt ℝ _ _ _).2 (hi _ ij)) δε, λ H ε ε0, (H _ (rat.cast_pos.2 ε0)).imp $ λ i hi j ij, (@rat.cast_lt ℝ _ _ _).1 $ by simpa using hi _ ij⟩ theorem of_near (f : ℕ → ℚ) (x : ℝ) (h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) < ε) : ∃ h', real.mk ⟨f, h'⟩ = x := ⟨is_cau_seq_iff_lift.2 (of_near _ (const abs x) h), sub_eq_zero.1 $ abs_eq_zero.1 $ eq_of_le_of_forall_le_of_dense (abs_nonneg _) $ λ ε ε0, mk_near_of_forall_near $ (h _ ε0).imp (λ i h j ij, le_of_lt (h j ij))⟩ theorem exists_floor (x : ℝ) : ∃ (ub : ℤ), (ub:ℝ) ≤ x ∧ ∀ (z : ℤ), (z:ℝ) ≤ x → z ≤ ub := int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h', int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩) theorem exists_sup (S : set ℝ) : (∃ x, x ∈ S) → (∃ x, ∀ y ∈ S, y ≤ x) → ∃ x, ∀ y, x ≤ y ↔ ∀ z ∈ S, z ≤ y | ⟨L, hL⟩ ⟨U, hU⟩ := begin choose f hf using begin refine λ d : ℕ, @int.exists_greatest_of_bdd (λ n, ∃ y ∈ S, (n:ℝ) ≤ y * d) _ _ _, { cases exists_int_gt U with k hk, refine ⟨k * d, λ z h, _⟩, rcases h with ⟨y, yS, hy⟩, refine int.cast_le.1 (le_trans hy _), simp, exact mul_le_mul_of_nonneg_right (le_trans (hU _ yS) (le_of_lt hk)) (nat.cast_nonneg _) }, { exact ⟨⌊L * d⌋, L, hL, floor_le _⟩ } end, have hf₁ : ∀ n > 0, ∃ y ∈ S, ((f n / n:ℚ):ℝ) ≤ y := λ n n0, let ⟨y, yS, hy⟩ := (hf n).1 in ⟨y, yS, by simpa using (div_le_iff ((nat.cast_pos.2 n0):((_:ℝ) < _))).2 hy⟩, have hf₂ : ∀ (n > 0) (y ∈ S), (y - (n:ℕ)⁻¹ : ℝ) < (f n / n:ℚ), { intros n n0 y yS, have := lt_of_lt_of_le (sub_one_lt_floor _) (int.cast_le.2 $ (hf n).2 _ ⟨y, yS, floor_le _⟩), simp [-sub_eq_add_neg], rwa [lt_div_iff ((nat.cast_pos.2 n0):((_:ℝ) < _)), sub_mul, _root_.inv_mul_cancel], exact ne_of_gt (nat.cast_pos.2 n0) }, suffices hg, let g : cau_seq ℚ abs := ⟨λ n, f n / n, hg⟩, refine ⟨mk g, λ y, ⟨λ h x xS, le_trans _ h, λ h, _⟩⟩, { refine le_of_forall_ge_of_dense (λ z xz, _), cases exists_nat_gt (x - z)⁻¹ with K hK, refine le_mk_of_forall_le ⟨K, λ n nK, _⟩, replace xz := sub_pos.2 xz, replace hK := le_trans (le_of_lt hK) (nat.cast_le.2 nK), have n0 : 0 < n := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos xz) hK), refine le_trans _ (le_of_lt $ hf₂ _ n0 _ xS), rwa [le_sub, inv_le ((nat.cast_pos.2 n0):((_:ℝ) < _)) xz] }, { exact mk_le_of_forall_le ⟨1, λ n n1, let ⟨x, xS, hx⟩ := hf₁ _ n1 in le_trans hx (h _ xS)⟩ }, intros ε ε0, suffices : ∀ j k ≥ nat_ceil ε⁻¹, (f j / j - f k / k : ℚ) < ε, { refine ⟨_, λ j ij, abs_lt.2 ⟨_, this _ _ ij (le_refl _)⟩⟩, rw [neg_lt, neg_sub], exact this _ _ (le_refl _) ij }, intros j k ij ik, replace ij := le_trans (le_nat_ceil _) (nat.cast_le.2 ij), replace ik := le_trans (le_nat_ceil _) (nat.cast_le.2 ik), have j0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos ε0) ij), have k0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos ε0) ik), rcases hf₁ _ j0 with ⟨y, yS, hy⟩, refine lt_of_lt_of_le ((@rat.cast_lt ℝ _ _ _).1 _) ((inv_le ε0 (nat.cast_pos.2 k0)).1 ik), simpa using sub_lt_iff_lt_add'.2 (lt_of_le_of_lt hy $ sub_lt_iff_lt_add.1 $ hf₂ _ k0 _ yS) end noncomputable def Sup (S : set ℝ) : ℝ := if h : (∃ x, x ∈ S) ∧ (∃ x, ∀ y ∈ S, y ≤ x) then classical.some (exists_sup S h.1 h.2) else 0 theorem Sup_le (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {y} : Sup S ≤ y ↔ ∀ z ∈ S, z ≤ y := by simp [Sup, h₁, h₂]; exact classical.some_spec (exists_sup S h₁ h₂) y theorem lt_Sup (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {y} : y < Sup S ↔ ∃ z ∈ S, y < z := by simpa [not_forall] using not_congr (@Sup_le S h₁ h₂ y) theorem le_Sup (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {x} (xS : x ∈ S) : x ≤ Sup S := (Sup_le S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS theorem Sup_le_ub (S : set ℝ) (h₁ : ∃ x, x ∈ S) {ub} (h₂ : ∀ y ∈ S, y ≤ ub) : Sup S ≤ ub := (Sup_le S h₁ ⟨_, h₂⟩).2 h₂ protected lemma is_lub_Sup {s : set ℝ} {a b : ℝ} (ha : a ∈ s) (hb : b ∈ upper_bounds s) : is_lub s (Sup s) := ⟨λ x xs, real.le_Sup s ⟨_, hb⟩ xs, λ u h, real.Sup_le_ub _ ⟨_, ha⟩ h⟩ noncomputable def Inf (S : set ℝ) : ℝ := -Sup {x | -x ∈ S} theorem le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {y} : y ≤ Inf S ↔ ∀ z ∈ S, y ≤ z := begin refine le_neg.trans ((Sup_le _ _ _).trans _), { cases h₁ with x xS, exact ⟨-x, by simp [xS]⟩ }, { cases h₂ with ub h, exact ⟨-ub, λ y hy, le_neg.1 $ h _ hy⟩ }, split; intros H z hz, { exact neg_le_neg_iff.1 (H _ $ by simp [hz]) }, { exact le_neg.2 (H _ hz) } end theorem Inf_lt (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {y} : Inf S < y ↔ ∃ z ∈ S, z < y := by simpa [not_forall] using not_congr (@le_Inf S h₁ h₂ y) theorem Inf_le (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {x} (xS : x ∈ S) : Inf S ≤ x := (le_Inf S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS theorem lb_le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) {lb} (h₂ : ∀ y ∈ S, lb ≤ y) : lb ≤ Inf S := (le_Inf S h₁ ⟨_, h₂⟩).2 h₂ open lattice noncomputable instance lattice : lattice ℝ := by apply_instance noncomputable instance : conditionally_complete_linear_order ℝ := { Sup := real.Sup, Inf := real.Inf, le_cSup := assume (s : set ℝ) (a : ℝ) (_ : bdd_above s) (_ : a ∈ s), show a ≤ Sup s, from le_Sup s ‹bdd_above s› ‹a ∈ s›, cSup_le := assume (s : set ℝ) (a : ℝ) (_ : s ≠ ∅) (H : ∀b∈s, b ≤ a), show Sup s ≤ a, from Sup_le_ub s (set.exists_mem_of_ne_empty ‹s ≠ ∅›) H, cInf_le := assume (s : set ℝ) (a : ℝ) (_ : bdd_below s) (_ : a ∈ s), show Inf s ≤ a, from Inf_le s ‹bdd_below s› ‹a ∈ s›, le_cInf := assume (s : set ℝ) (a : ℝ) (_ : s ≠ ∅) (H : ∀b∈s, a ≤ b), show a ≤ Inf s, from lb_le_Inf s (set.exists_mem_of_ne_empty ‹s ≠ ∅›) H, decidable_le := classical.dec_rel _, ..real.linear_order, ..real.lattice} theorem Sup_empty : lattice.Sup (∅ : set ℝ) = 0 := dif_neg $ by simp theorem Sup_of_not_bdd_above {s : set ℝ} (hs : ¬ bdd_above s) : lattice.Sup s = 0 := dif_neg $ assume h, hs h.2 theorem Sup_univ : real.Sup set.univ = 0 := real.Sup_of_not_bdd_above $ λ h, Exists.dcases_on h $ λ x h', not_le_of_lt (lt_add_one _) $ h' (x + 1) $ set.mem_univ _ theorem Inf_empty : lattice.Inf (∅ : set ℝ) = 0 := show Inf ∅ = 0, by simp [Inf]; exact Sup_empty theorem Inf_of_not_bdd_below {s : set ℝ} (hs : ¬ bdd_below s) : lattice.Inf s = 0 := have bdd_above {x | -x ∈ s} → bdd_below s, from assume ⟨b, hb⟩, ⟨-b, assume x hxs, neg_le.2 $ hb _ $ by simp [hxs]⟩, have ¬ bdd_above {x | -x ∈ s}, from mt this hs, neg_eq_zero.2 $ Sup_of_not_bdd_above $ this theorem cau_seq_converges (f : cau_seq ℝ abs) : ∃ x, f ≈ const abs x := begin let S := {x : ℝ | const abs x < f}, have lb : ∃ x, x ∈ S := exists_lt f, have ub' : ∀ x, f < const abs x → ∀ y ∈ S, y ≤ x := λ x h y yS, le_of_lt $ const_lt.1 $ cau_seq.lt_trans yS h, have ub : ∃ x, ∀ y ∈ S, y ≤ x := (exists_gt f).imp ub', refine ⟨Sup S, ((lt_total _ _).resolve_left (λ h, _)).resolve_right (λ h, _)⟩, { rcases h with ⟨ε, ε0, i, ih⟩, refine not_lt_of_le (Sup_le_ub S lb (ub' _ _)) ((sub_lt_self_iff _).2 (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, sub_right_comm, le_sub_iff_add_le, add_halves], exact ih _ ij }, { rcases h with ⟨ε, ε0, i, ih⟩, refine not_lt_of_le (le_Sup S ub _) ((lt_add_iff_pos_left _).2 (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, add_comm, ← sub_sub, le_sub_iff_add_le, add_halves], exact ih _ ij } end noncomputable instance : cau_seq.is_complete ℝ abs := ⟨cau_seq_converges⟩ theorem sqrt_exists : ∀ {x : ℝ}, 0 ≤ x → ∃ y, 0 ≤ y ∧ y * y = x := suffices H : ∀ {x : ℝ}, 0 < x → x ≤ 1 → ∃ y, 0 < y ∧ y * y = x, begin intros x x0, cases x0, cases le_total x 1 with x1 x1, { rcases H x0 x1 with ⟨y, y0, hy⟩, exact ⟨y, le_of_lt y0, hy⟩ }, { have := (inv_le_inv x0 zero_lt_one).2 x1, rw inv_one at this, rcases H (inv_pos x0) this with ⟨y, y0, hy⟩, refine ⟨y⁻¹, le_of_lt (inv_pos y0), _⟩, rw [← mul_inv', hy, inv_inv'] }, { exact ⟨0, by simp [x0.symm]⟩ } end, λ x x0 x1, begin let S := {y | 0 < y ∧ y * y ≤ x}, have lb : x ∈ S := ⟨x0, by simpa using (mul_le_mul_right x0).2 x1⟩, have ub : ∀ y ∈ S, (y:ℝ) ≤ 1, { intros y yS, cases yS with y0 yx, refine (mul_self_le_mul_self_iff (le_of_lt y0) zero_le_one).2 _, simpa using le_trans yx x1 }, have S0 : 0 < Sup S := lt_of_lt_of_le x0 (le_Sup _ ⟨_, ub⟩ lb), refine ⟨Sup S, S0, le_antisymm (not_lt.1 $ λ h, _) (not_lt.1 $ λ h, _)⟩, { rw [← div_lt_iff S0, lt_Sup S ⟨_, lb⟩ ⟨_, ub⟩] at h, rcases h with ⟨y, ⟨y0, yx⟩, hy⟩, rw [div_lt_iff S0, ← div_lt_iff' y0, lt_Sup S ⟨_, lb⟩ ⟨_, ub⟩] at hy, rcases hy with ⟨z, ⟨z0, zx⟩, hz⟩, rw [div_lt_iff y0] at hz, exact not_lt_of_lt ((mul_lt_mul_right y0).1 (lt_of_le_of_lt yx hz)) ((mul_lt_mul_left z0).1 (lt_of_le_of_lt zx hz)) }, { let s := Sup S, let y := s + (x - s * s) / 3, replace h : 0 < x - s * s := sub_pos.2 h, have _30 := bit1_pos zero_le_one, have : s < y := (lt_add_iff_pos_right _).2 (div_pos h _30), refine not_le_of_lt this (le_Sup S ⟨_, ub⟩ ⟨lt_trans S0 this, _⟩), rw [add_mul_self_eq, add_assoc, ← le_sub_iff_add_le', ← add_mul, ← le_div_iff (div_pos h _30), div_div_cancel (ne_of_gt h)], apply add_le_add, { simpa using (mul_le_mul_left (@two_pos ℝ _)).2 (Sup_le_ub _ ⟨_, lb⟩ ub) }, { rw [div_le_one_iff_le _30], refine le_trans (sub_le_self _ (mul_self_nonneg _)) (le_trans x1 _), exact (le_add_iff_nonneg_left _).2 (le_of_lt two_pos) } } end def sqrt_aux (f : cau_seq ℚ abs) : ℕ → ℚ | 0 := rat.mk_nat (f 0).num.to_nat.sqrt (f 0).denom.sqrt | (n + 1) := let s := sqrt_aux n in max 0 $ (s + f (n+1) / s) / 2 theorem sqrt_aux_nonneg (f : cau_seq ℚ abs) : ∀ i : ℕ, 0 ≤ sqrt_aux f i | 0 := by rw [sqrt_aux, mk_nat_eq, mk_eq_div]; apply div_nonneg'; exact int.cast_nonneg.2 (int.of_nat_nonneg _) | (n + 1) := le_max_left _ _ /- TODO(Mario): finish the proof theorem sqrt_aux_converges (f : cau_seq ℚ abs) : ∃ h x, 0 ≤ x ∧ x * x = max 0 (mk f) ∧ mk ⟨sqrt_aux f, h⟩ = x := begin rcases sqrt_exists (le_max_left 0 (mk f)) with ⟨x, x0, hx⟩, suffices : ∃ h, mk ⟨sqrt_aux f, h⟩ = x, { exact this.imp (λ h e, ⟨x, x0, hx, e⟩) }, apply of_near, suffices : ∃ δ > 0, ∀ i, abs (↑(sqrt_aux f i) - x) < δ / 2 ^ i, { rcases this with ⟨δ, δ0, hδ⟩, intros, } end -/ noncomputable def sqrt (x : ℝ) : ℝ := classical.some (sqrt_exists (le_max_left 0 x)) /-quotient.lift_on x (λ f, mk ⟨sqrt_aux f, (sqrt_aux_converges f).fst⟩) (λ f g e, begin rcases sqrt_aux_converges f with ⟨hf, x, x0, xf, xs⟩, rcases sqrt_aux_converges g with ⟨hg, y, y0, yg, ys⟩, refine xs.trans (eq.trans _ ys.symm), rw [← @mul_self_inj_of_nonneg ℝ _ x y x0 y0, xf, yg], congr' 1, exact quotient.sound e end)-/ theorem sqrt_prop (x : ℝ) : 0 ≤ sqrt x ∧ sqrt x * sqrt x = max 0 x := classical.some_spec (sqrt_exists (le_max_left 0 x)) /-quotient.induction_on x $ λ f, by rcases sqrt_aux_converges f with ⟨hf, _, x0, xf, rfl⟩; exact ⟨x0, xf⟩-/ theorem sqrt_eq_zero_of_nonpos (h : x ≤ 0) : sqrt x = 0 := eq_zero_of_mul_self_eq_zero $ (sqrt_prop x).2.trans $ max_eq_left h theorem sqrt_nonneg (x : ℝ) : 0 ≤ sqrt x := (sqrt_prop x).1 @[simp] theorem mul_self_sqrt (h : 0 ≤ x) : sqrt x * sqrt x = x := (sqrt_prop x).2.trans (max_eq_right h) @[simp] theorem sqrt_mul_self (h : 0 ≤ x) : sqrt (x * x) = x := (mul_self_inj_of_nonneg (sqrt_nonneg _) h).1 (mul_self_sqrt (mul_self_nonneg _)) theorem sqrt_eq_iff_mul_self_eq (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x = y ↔ y * y = x := ⟨λ h, by rw [← h, mul_self_sqrt hx], λ h, by rw [← h, sqrt_mul_self hy]⟩ @[simp] theorem sqr_sqrt (h : 0 ≤ x) : sqrt x ^ 2 = x := by rw [pow_two, mul_self_sqrt h] @[simp] theorem sqrt_sqr (h : 0 ≤ x) : sqrt (x ^ 2) = x := by rw [pow_two, sqrt_mul_self h] theorem sqrt_eq_iff_sqr_eq (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x = y ↔ y ^ 2 = x := by rw [pow_two, sqrt_eq_iff_mul_self_eq hx hy] theorem sqrt_mul_self_eq_abs (x : ℝ) : sqrt (x * x) = abs x := (le_total 0 x).elim (λ h, (sqrt_mul_self h).trans (abs_of_nonneg h).symm) (λ h, by rw [← neg_mul_neg, sqrt_mul_self (neg_nonneg.2 h), abs_of_nonpos h]) theorem sqrt_sqr_eq_abs (x : ℝ) : sqrt (x ^ 2) = abs x := by rw [pow_two, sqrt_mul_self_eq_abs] @[simp] theorem sqrt_zero : sqrt 0 = 0 := by simpa using sqrt_mul_self (le_refl _) @[simp] theorem sqrt_one : sqrt 1 = 1 := by simpa using sqrt_mul_self zero_le_one @[simp] theorem sqrt_le (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x ≤ sqrt y ↔ x ≤ y := by rw [mul_self_le_mul_self_iff (sqrt_nonneg _) (sqrt_nonneg _), mul_self_sqrt hx, mul_self_sqrt hy] @[simp] theorem sqrt_lt (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x < sqrt y ↔ x < y := lt_iff_lt_of_le_iff_le (sqrt_le hy hx) lemma sqrt_le_sqrt (h : x ≤ y) : sqrt x ≤ sqrt y := begin rw [mul_self_le_mul_self_iff (sqrt_nonneg _) (sqrt_nonneg _), (sqrt_prop _).2, (sqrt_prop _).2], exact max_le_max (le_refl _) h end lemma sqrt_le_left (hy : 0 ≤ y) : sqrt x ≤ y ↔ x ≤ y ^ 2 := begin rw [mul_self_le_mul_self_iff (sqrt_nonneg _) hy, pow_two], cases le_total 0 x with hx hx, { rw [mul_self_sqrt hx] }, { have h1 : 0 ≤ y * y := mul_nonneg hy hy, have h2 : x ≤ y * y := le_trans hx h1, simp [sqrt_eq_zero_of_nonpos, hx, h1, h2] } end /- note: if you want to conclude `x ≤ sqrt y`, then use `le_sqrt_of_sqr_le`. if you have `x > 0`, consider using `le_sqrt'` -/ lemma le_sqrt (hx : 0 ≤ x) (hy : 0 ≤ y) : x ≤ sqrt y ↔ x ^ 2 ≤ y := by rw [mul_self_le_mul_self_iff hx (sqrt_nonneg _), pow_two, mul_self_sqrt hy] lemma le_sqrt' (hx : 0 < x) : x ≤ sqrt y ↔ x ^ 2 ≤ y := begin rw [mul_self_le_mul_self_iff (le_of_lt hx) (sqrt_nonneg _), pow_two], cases le_total 0 y with hy hy, { rw [mul_self_sqrt hy] }, { have h1 : 0 < x * x := mul_pos hx hx, have h2 : ¬x * x ≤ y := not_le_of_lt (lt_of_le_of_lt hy h1), simp [sqrt_eq_zero_of_nonpos, hy, h1, h2] } end lemma le_sqrt_of_sqr_le (h : x ^ 2 ≤ y) : x ≤ sqrt y := begin cases lt_or_ge 0 x with hx hx, { rwa [le_sqrt' hx] }, { exact le_trans hx (sqrt_nonneg y) } end @[simp] theorem sqrt_inj (hx : 0 ≤ x) (hy : 0 ≤ y) : sqrt x = sqrt y ↔ x = y := by simp [le_antisymm_iff, hx, hy] @[simp] theorem sqrt_eq_zero (h : 0 ≤ x) : sqrt x = 0 ↔ x = 0 := by simpa using sqrt_inj h (le_refl _) theorem sqrt_eq_zero' : sqrt x = 0 ↔ x ≤ 0 := (le_total x 0).elim (λ h, by simp [h, sqrt_eq_zero_of_nonpos]) (λ h, by simp [h]; simp [le_antisymm_iff, h]) @[simp] theorem sqrt_pos : 0 < sqrt x ↔ 0 < x := lt_iff_lt_of_le_iff_le (iff.trans (by simp [le_antisymm_iff, sqrt_nonneg]) sqrt_eq_zero') @[simp] theorem sqrt_mul' (x) {y : ℝ} (hy : 0 ≤ y) : sqrt (x * y) = sqrt x * sqrt y := begin cases le_total 0 x with hx hx, { refine (mul_self_inj_of_nonneg _ (mul_nonneg _ _)).1 _; try {apply sqrt_nonneg}, rw [mul_self_sqrt (mul_nonneg hx hy), mul_assoc, mul_left_comm (sqrt y), mul_self_sqrt hy, ← mul_assoc, mul_self_sqrt hx] }, { rw [sqrt_eq_zero'.2 (mul_nonpos_of_nonpos_of_nonneg hx hy), sqrt_eq_zero'.2 hx, zero_mul] } end @[simp] theorem sqrt_mul (hx : 0 ≤ x) (y : ℝ) : sqrt (x * y) = sqrt x * sqrt y := by rw [mul_comm, sqrt_mul' _ hx, mul_comm] @[simp] theorem sqrt_inv (x : ℝ) : sqrt x⁻¹ = (sqrt x)⁻¹ := (le_or_lt x 0).elim (λ h, by simp [sqrt_eq_zero'.2, inv_nonpos, h]) (λ h, by rw [ ← mul_self_inj_of_nonneg (sqrt_nonneg _) (le_of_lt $ inv_pos $ sqrt_pos.2 h), mul_self_sqrt (le_of_lt $ inv_pos h), ← mul_inv', mul_self_sqrt (le_of_lt h)]) @[simp] theorem sqrt_div (hx : 0 ≤ x) (y : ℝ) : sqrt (x / y) = sqrt x / sqrt y := by rw [division_def, sqrt_mul hx, sqrt_inv]; refl attribute [irreducible] real.le end real
c27fb07de9841332a099d1579f5cccf0b1f92ea3
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/ring_theory/adjoin_root.lean
1f0d08d915b60bb2029064eb052fcee526db8cc4
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,337
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 Adjoining roots of polynomials -/ import data.polynomial.field_division import linear_algebra.finite_dimensional import ring_theory.adjoin.basic import ring_theory.power_basis import ring_theory.principal_ideal_domain /-! # Adjoining roots of polynomials This file defines the commutative ring `adjoin_root f`, the ring R[X]/(f) obtained from a commutative ring `R` and a polynomial `f : R[X]`. If furthermore `R` is a field and `f` is irreducible, the field structure on `adjoin_root f` is constructed. ## Main definitions and results The main definitions are in the `adjoin_root` namespace. * `mk f : polynomial R →+* adjoin_root f`, the natural ring homomorphism. * `of f : R →+* adjoin_root f`, the natural ring homomorphism. * `root f : adjoin_root f`, the image of X in R[X]/(f). * `lift (i : R →+* S) (x : S) (h : f.eval₂ i x = 0) : (adjoin_root f) →+* S`, the ring homomorphism from R[X]/(f) to S extending `i : R →+* S` and sending `X` to `x`. * `lift_hom (x : S) (hfx : aeval x f = 0) : adjoin_root f →ₐ[R] S`, the algebra homomorphism from R[X]/(f) to S extending `algebra_map R S` and sending `X` to `x` * `equiv : (adjoin_root f →ₐ[F] E) ≃ {x // x ∈ (f.map (algebra_map F E)).roots}` a bijection between algebra homomorphisms from `adjoin_root` and roots of `f` in `S` -/ noncomputable theory open_locale classical open_locale big_operators universes u v w variables {R : Type u} {S : Type v} {K : Type w} open polynomial ideal /-- Adjoin a root of a polynomial `f` to a commutative ring `R`. We define the new ring as the quotient of `R` by the principal ideal of `f`. -/ def adjoin_root [comm_ring R] (f : polynomial R) : Type u := ideal.quotient (span {f} : ideal (polynomial R)) namespace adjoin_root section comm_ring variables [comm_ring R] (f : polynomial R) instance : comm_ring (adjoin_root f) := ideal.quotient.comm_ring _ instance : inhabited (adjoin_root f) := ⟨0⟩ instance : decidable_eq (adjoin_root f) := classical.dec_eq _ /-- Ring homomorphism from `R[x]` to `adjoin_root f` sending `X` to the `root`. -/ def mk : polynomial R →+* adjoin_root f := ideal.quotient.mk _ @[elab_as_eliminator] theorem induction_on {C : adjoin_root f → Prop} (x : adjoin_root f) (ih : ∀ p : polynomial R, C (mk f p)) : C x := quotient.induction_on' x ih /-- Embedding of the original ring `R` into `adjoin_root f`. -/ def of : R →+* adjoin_root f := (mk f).comp C instance : algebra R (adjoin_root f) := (of f).to_algebra @[simp] lemma algebra_map_eq : algebra_map R (adjoin_root f) = of f := rfl /-- The adjoined root. -/ def root : adjoin_root f := mk f X variables {f} instance adjoin_root.has_coe_t : has_coe_t R (adjoin_root f) := ⟨of f⟩ @[simp] lemma mk_self : mk f f = 0 := quotient.sound' (mem_span_singleton.2 $ by simp) @[simp] lemma mk_C (x : R) : mk f (C x) = x := rfl @[simp] lemma mk_X : mk f X = root f := rfl @[simp] lemma aeval_eq (p : polynomial R) : aeval (root f) p = mk f p := polynomial.induction_on p (λ x, by { rw aeval_C, refl }) (λ p q ihp ihq, by rw [alg_hom.map_add, ring_hom.map_add, ihp, ihq]) (λ n x ih, by { rw [alg_hom.map_mul, aeval_C, alg_hom.map_pow, aeval_X, ring_hom.map_mul, mk_C, ring_hom.map_pow, mk_X], refl }) theorem adjoin_root_eq_top : algebra.adjoin R ({root f} : set (adjoin_root f)) = ⊤ := algebra.eq_top_iff.2 $ λ x, induction_on f x $ λ p, (algebra.adjoin_singleton_eq_range R (root f)).symm ▸ ⟨p, aeval_eq p⟩ @[simp] lemma eval₂_root (f : polynomial R) : f.eval₂ (of f) (root f) = 0 := by rw [← algebra_map_eq, ← aeval_def, aeval_eq, mk_self] lemma is_root_root (f : polynomial R) : is_root (f.map (of f)) (root f) := by rw [is_root, eval_map, eval₂_root] lemma is_algebraic_root (hf : f ≠ 0) : is_algebraic R (root f) := ⟨f, hf, eval₂_root f⟩ variables [comm_ring S] /-- Lift a ring homomorphism `i : R →+* S` to `adjoin_root f →+* S`. -/ def lift (i : R →+* S) (x : S) (h : f.eval₂ i x = 0) : (adjoin_root f) →+* S := begin apply ideal.quotient.lift _ (eval₂_ring_hom i x), intros g H, rcases mem_span_singleton.1 H with ⟨y, hy⟩, rw [hy, ring_hom.map_mul, coe_eval₂_ring_hom, h, zero_mul] end variables {i : R →+* S} {a : S} {h : f.eval₂ i a = 0} @[simp] lemma lift_mk {g : polynomial R} : lift i a h (mk f g) = g.eval₂ i a := ideal.quotient.lift_mk _ _ _ @[simp] lemma lift_root : lift i a h (root f) = a := by rw [root, lift_mk, eval₂_X] @[simp] lemma lift_of {x : R} : lift i a h x = i x := by rw [← mk_C x, lift_mk, eval₂_C] @[simp] lemma lift_comp_of : (lift i a h).comp (of f) = i := ring_hom.ext $ λ _, @lift_of _ _ _ _ _ _ _ h _ variables (f) [algebra R S] /-- Produce an algebra homomorphism `adjoin_root f →ₐ[R] S` sending `root f` to a root of `f` in `S`. -/ def lift_hom (x : S) (hfx : aeval x f = 0) : adjoin_root f →ₐ[R] S := { commutes' := λ r, show lift _ _ hfx r = _, from lift_of, .. lift (algebra_map R S) x hfx } @[simp] lemma coe_lift_hom (x : S) (hfx : aeval x f = 0) : (lift_hom f x hfx : adjoin_root f →+* S) = lift (algebra_map R S) x hfx := rfl @[simp] lemma aeval_alg_hom_eq_zero (ϕ : adjoin_root f →ₐ[R] S) : aeval (ϕ (root f)) f = 0 := begin have h : ϕ.to_ring_hom.comp (of f) = algebra_map R S := ring_hom.ext_iff.mpr (ϕ.commutes), rw [aeval_def, ←h, ←ring_hom.map_zero ϕ.to_ring_hom, ←eval₂_root f, hom_eval₂], refl, end @[simp] lemma lift_hom_eq_alg_hom (f : polynomial R) (ϕ : adjoin_root f →ₐ[R] S) : lift_hom f (ϕ (root f)) (aeval_alg_hom_eq_zero f ϕ) = ϕ := begin suffices : ϕ.equalizer (lift_hom f (ϕ (root f)) (aeval_alg_hom_eq_zero f ϕ)) = ⊤, { exact (alg_hom.ext (λ x, (set_like.ext_iff.mp (this) x).mpr algebra.mem_top)).symm }, rw [eq_top_iff, ←adjoin_root_eq_top, algebra.adjoin_le_iff, set.singleton_subset_iff], exact (@lift_root _ _ _ _ _ _ _ (aeval_alg_hom_eq_zero f ϕ)).symm, end end comm_ring section irreducible variables [field K] {f : polynomial K} [irreducible f] instance is_maximal_span : is_maximal (span {f} : ideal (polynomial K)) := principal_ideal_ring.is_maximal_of_irreducible ‹irreducible f› noncomputable instance field : field (adjoin_root f) := { ..adjoin_root.comm_ring f, ..ideal.quotient.field (span {f} : ideal (polynomial K)) } lemma coe_injective : function.injective (coe : K → adjoin_root f) := (of f).injective variable (f) lemma mul_div_root_cancel : ((X - C (root f)) * (f.map (of f) / (X - C (root f))) : polynomial (adjoin_root f)) = f.map (of f) := mul_div_eq_iff_is_root.2 $ is_root_root _ end irreducible section power_basis variables [field K] {f : polynomial K} lemma is_integral_root (hf : f ≠ 0) : is_integral K (root f) := (is_algebraic_iff_is_integral _).mp (is_algebraic_root hf) lemma minpoly_root (hf : f ≠ 0) : minpoly K (root f) = f * C (f.leading_coeff⁻¹) := begin have f'_monic : monic _ := monic_mul_leading_coeff_inv hf, refine (minpoly.unique K _ f'_monic _ _).symm, { rw [alg_hom.map_mul, aeval_eq, mk_self, zero_mul] }, intros q q_monic q_aeval, have commutes : (lift (algebra_map K (adjoin_root f)) (root f) q_aeval).comp (mk q) = mk f, { ext, { simp only [ring_hom.comp_apply, mk_C, lift_of], refl }, { simp only [ring_hom.comp_apply, mk_X, lift_root] } }, rw [degree_eq_nat_degree f'_monic.ne_zero, degree_eq_nat_degree q_monic.ne_zero, with_bot.coe_le_coe, nat_degree_mul hf, nat_degree_C, add_zero], apply nat_degree_le_of_dvd, { have : mk f q = 0, by rw [←commutes, ring_hom.comp_apply, mk_self, ring_hom.map_zero], rwa [←ideal.mem_span_singleton, ←ideal.quotient.eq_zero_iff_mem] }, { exact q_monic.ne_zero }, { rwa [ne.def, C_eq_zero, inv_eq_zero, leading_coeff_eq_zero] }, end /-- The elements `1, root f, ..., root f ^ (d - 1)` form a basis for `adjoin_root f`, where `f` is an irreducible polynomial over a field of degree `d`. -/ def power_basis_aux (hf : f ≠ 0) : basis (fin f.nat_degree) K (adjoin_root f) := begin set f' := f * C (f.leading_coeff⁻¹) with f'_def, have deg_f' : f'.nat_degree = f.nat_degree, { rw [nat_degree_mul hf, nat_degree_C, add_zero], { rwa [ne.def, C_eq_zero, inv_eq_zero, leading_coeff_eq_zero] } }, have minpoly_eq : minpoly K (root f) = f' := minpoly_root hf, apply @basis.mk _ _ _ (λ (i : fin f.nat_degree), (root f ^ i.val)), { rw [← deg_f', ← minpoly_eq], exact (is_integral_root hf).linear_independent_pow }, { rw _root_.eq_top_iff, rintros y -, rw [← deg_f', ← minpoly_eq], apply (is_integral_root hf).mem_span_pow, obtain ⟨g⟩ := y, use g, rw aeval_eq, refl } end /-- The power basis `1, root f, ..., root f ^ (d - 1)` for `adjoin_root f`, where `f` is an irreducible polynomial over a field of degree `d`. -/ @[simps] def power_basis (hf : f ≠ 0) : power_basis K (adjoin_root f) := { gen := root f, dim := f.nat_degree, basis := power_basis_aux hf, basis_eq_pow := basis.mk_apply _ _ } lemma minpoly_power_basis_gen (hf : f ≠ 0) : minpoly K (power_basis hf).gen = f * C (f.leading_coeff⁻¹) := by rw [power_basis_gen, minpoly_root hf] lemma minpoly_power_basis_gen_of_monic (hf : f.monic) (hf' : f ≠ 0 := hf.ne_zero) : minpoly K (power_basis hf').gen = f := by rw [minpoly_power_basis_gen hf', hf.leading_coeff, inv_one, C.map_one, mul_one] end power_basis section equiv variables (K) (L F : Type*) [field F] [field K] [field L] [algebra F K] [algebra F L] variables (pb : _root_.power_basis F K) /-- If `L` is a field extension of `F` and `f` is a polynomial over `F` then the set of maps from `F[x]/(f)` into `L` is in bijection with the set of roots of `f` in `L`. -/ def equiv (f : polynomial F) (hf : f ≠ 0) : (adjoin_root f →ₐ[F] L) ≃ {x // x ∈ (f.map (algebra_map F L)).roots} := (power_basis hf).lift_equiv'.trans ((equiv.refl _).subtype_equiv (λ x, begin rw [power_basis_gen, minpoly_root hf, polynomial.map_mul, roots_mul, polynomial.map_C, roots_C, add_zero, equiv.refl_apply], { rw ← polynomial.map_mul, exact map_monic_ne_zero (monic_mul_leading_coeff_inv hf) } end)) end equiv end adjoin_root
eaeabbfe62f30b4e4e56b98e135676da6d505ce8
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/structuralIssue.lean
5f37f1360e8b57a8cafcd64497c5fa533f2ac838
[ "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
354
lean
def f (xs : List Nat) : Nat := match xs with | [] => 0 | x::xs => match xs with | [] => 0 -- This examples fails if we write the following alternative as -- | _ => f xs + 1 | xs => f xs + 1 def g (xs : List Nat) : Nat := match xs with | [] => 0 | y::ys => match ys with | [] => 0 | _::_::zs => g zs + 1 | zs => g zs + 3
0a89ed68bb5a243f0e3c5de7228c38d5eb8e19e8
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/tactic/rename.lean
026a42dbc6fef4fa5317098788b441bf8ee1ce7c
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
4,285
lean
/- Copyright (c) 2020 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jannis Limperg -/ import tactic.core /-! # Better `rename` tactic This module defines a variant of the standard `rename` tactic, with the following improvements: * You can rename multiple hypotheses at the same time. * Renaming a hypothesis does not change its location in the context. -/ open lean lean.parser interactive native namespace tactic /-- Get the revertible part of the local context. These are the hypotheses that appear after the last frozen local instance in the local context. We call them revertible because `revert` can revert them, unlike those hypotheses which occur before a frozen instance. -/ meta def revertible_local_context : tactic (list expr) := do ctx ← local_context, frozen ← frozen_local_instances, pure $ match frozen with | none := ctx | some [] := ctx | some (h :: _) := ctx.after (eq h) end /-- Rename local hypotheses according to the given `name_map`. The `name_map` contains as keys those hypotheses that should be renamed; the associated values are the new names. This tactic can only rename hypotheses which occur after the last frozen local instance. If you need to rename earlier hypotheses, try `unfreeze_local_instances`. If `strict` is true, we fail if `name_map` refers to hypotheses that do not appear in the local context or that appear before a frozen local instance. Conversely, if `strict` is false, some entries of `name_map` may be silently ignored. Note that we allow shadowing, so renamed hypotheses may have the same name as other hypotheses in the context. -/ meta def rename' (renames : name_map name) (strict := tt) : tactic unit := do ctx ← revertible_local_context, when strict (do let ctx_names := rb_map.set_of_list (ctx.map expr.local_pp_name), let invalid_renames := (renames.to_list.map prod.fst).filter (λ h, ¬ ctx_names.contains h), when ¬ invalid_renames.empty $ fail $ format.join [ "Cannot rename these hypotheses:\n" , format.intercalate ", " (invalid_renames.map to_fmt) , format.line , "This is because these hypotheses either do not occur in the\n" , "context or they occur before a frozen local instance.\n" , "In the latter case, try `tactic.unfreeze_local_instances`." ]), let new_name := λ current_name, (renames.find current_name).get_or_else current_name, let intro_names := list.map (new_name ∘ expr.local_pp_name) ctx, revert_lst ctx, intro_lst intro_names, pure () end tactic namespace tactic.interactive /-- Parse a current name and new name for `rename'`. -/ meta def rename'_arg_parser : parser (name × name) := prod.mk <$> ident <*> (optional (tk "->") *> ident) /-- Parse the arguments of `rename'`. -/ meta def rename'_args_parser : parser (list (name × name)) := (functor.map (λ x, [x]) rename'_arg_parser) <|> (tk "[" *> sep_by (tk ",") rename'_arg_parser <* tk "]") /-- Rename one or more local hypotheses. The renamings are given as follows: ``` rename' x y -- rename x to y rename' x → y -- ditto rename' [x y, a b] -- rename x to y and a to b rename' [x → y, a → b] -- ditto ``` Brackets are necessary if multiple hypotheses should be renamed in parallel. -/ meta def rename' (renames : parse rename'_args_parser) : tactic unit := tactic.rename' (rb_map.of_list renames) /-- Renames one or more hypotheses in the context. ```lean example {α β} (a : α) (b : β) : unit := begin rename' a a', -- result: a' : α, b : β rename' a' → a, -- a : α, b : β rename' [a a', b b'], -- a' : α, b' : β rename' [a' → a, b' → b], -- a : α, b : β exact () end ``` Compared to the standard `rename` tactic, this tactic makes the following improvements: - You can rename multiple hypotheses at once. - Renaming a hypothesis always preserves its location in the context (whereas `rename` may reorder hypotheses). -/ add_tactic_doc { name := "rename'", category := doc_category.tactic, decl_names := [`tactic.interactive.rename'], tags := ["renaming"] } end tactic.interactive
3e009905cc165db62917202f35245d893aa5d026
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/path_connected.lean
33be284ce494cd9f58d13e72e64ee07007384fca
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
42,669
lean
/- Copyright (c) 2020 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.algebra.order.proj_Icc import topology.compact_open import topology.continuous_function.basic import topology.unit_interval /-! # Path connectedness ## Main definitions In the file the unit interval `[0, 1]` in `ℝ` is denoted by `I`, and `X` is a topological space. * `path (x y : X)` is the type of paths from `x` to `y`, i.e., continuous maps from `I` to `X` mapping `0` to `x` and `1` to `y`. * `path.map` is the image of a path under a continuous map. * `joined (x y : X)` means there is a path between `x` and `y`. * `joined.some_path (h : joined x y)` selects some path between two points `x` and `y`. * `path_component (x : X)` is the set of points joined to `x`. * `path_connected_space X` is a predicate class asserting that `X` is non-empty and every two points of `X` are joined. Then there are corresponding relative notions for `F : set X`. * `joined_in F (x y : X)` means there is a path `γ` joining `x` to `y` with values in `F`. * `joined_in.some_path (h : joined_in F x y)` selects a path from `x` to `y` inside `F`. * `path_component_in F (x : X)` is the set of points joined to `x` in `F`. * `is_path_connected F` asserts that `F` is non-empty and every two points of `F` are joined in `F`. * `loc_path_connected_space X` is a predicate class asserting that `X` is locally path-connected: each point has a basis of path-connected neighborhoods (we do *not* ask these to be open). ## Main theorems * `joined` and `joined_in F` are transitive relations. One can link the absolute and relative version in two directions, using `(univ : set X)` or the subtype `↥F`. * `path_connected_space_iff_univ : path_connected_space X ↔ is_path_connected (univ : set X)` * `is_path_connected_iff_path_connected_space : is_path_connected F ↔ path_connected_space ↥F` For locally path connected spaces, we have * `path_connected_space_iff_connected_space : path_connected_space X ↔ connected_space X` * `is_connected_iff_is_path_connected (U_op : is_open U) : is_path_connected U ↔ is_connected U` ## Implementation notes By default, all paths have `I` as their source and `X` as their target, but there is an operation `set.Icc_extend` that will extend any continuous map `γ : I → X` into a continuous map `Icc_extend zero_le_one γ : ℝ → X` that is constant before `0` and after `1`. This is used to define `path.extend` that turns `γ : path x y` into a continuous map `γ.extend : ℝ → X` whose restriction to `I` is the original `γ`, and is equal to `x` on `(-∞, 0]` and to `y` on `[1, +∞)`. -/ noncomputable theory open_locale classical topological_space filter unit_interval open filter set function unit_interval variables {X Y : Type*} [topological_space X] [topological_space Y] {x y z : X} {ι : Type*} /-! ### Paths -/ /-- Continuous path connecting two points `x` and `y` in a topological space -/ @[nolint has_nonempty_instance] structure path (x y : X) extends C(I, X) := (source' : to_fun 0 = x) (target' : to_fun 1 = y) instance : has_coe_to_fun (path x y) (λ _, I → X) := ⟨λ p, p.to_fun⟩ @[ext] protected lemma path.ext : ∀ {γ₁ γ₂ : path x y}, (γ₁ : I → X) = γ₂ → γ₁ = γ₂ | ⟨⟨x, h11⟩, h12, h13⟩ ⟨⟨.(x), h21⟩, h22, h23⟩ rfl := rfl namespace path @[simp] lemma coe_mk (f : I → X) (h₁ h₂ h₃) : ⇑(mk ⟨f, h₁⟩ h₂ h₃ : path x y) = f := rfl variable (γ : path x y) @[continuity] protected lemma continuous : continuous γ := γ.continuous_to_fun @[simp] protected lemma source : γ 0 = x := γ.source' @[simp] protected lemma target : γ 1 = y := γ.target' /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply : I → X := γ initialize_simps_projections path (to_continuous_map_to_fun → simps.apply, -to_continuous_map) @[simp] lemma coe_to_continuous_map : ⇑γ.to_continuous_map = γ := rfl /-- Any function `φ : Π (a : α), path (x a) (y a)` can be seen as a function `α × I → X`. -/ instance has_uncurry_path {X α : Type*} [topological_space X] {x y : α → X} : has_uncurry (Π (a : α), path (x a) (y a)) (α × I) X := ⟨λ φ p, φ p.1 p.2⟩ /-- The constant path from a point to itself -/ @[refl, simps] def refl (x : X) : path x x := { to_fun := λ t, x, continuous_to_fun := continuous_const, source' := rfl, target' := rfl } @[simp] lemma refl_range {a : X} : range (path.refl a) = {a} := by simp [path.refl, has_coe_to_fun.coe, coe_fn] /-- The reverse of a path from `x` to `y`, as a path from `y` to `x` -/ @[symm, simps] def symm (γ : path x y) : path y x := { to_fun := γ ∘ σ, continuous_to_fun := by continuity, source' := by simpa [-path.target] using γ.target, target' := by simpa [-path.source] using γ.source } @[simp] lemma symm_symm {γ : path x y} : γ.symm.symm = γ := by { ext, simp } @[simp] lemma refl_symm {a : X} : (path.refl a).symm = path.refl a := by { ext, refl } @[simp] lemma symm_range {a b : X} (γ : path a b) : range γ.symm = range γ := begin ext x, simp only [mem_range, path.symm, has_coe_to_fun.coe, coe_fn, unit_interval.symm, set_coe.exists, comp_app, subtype.coe_mk, subtype.val_eq_coe], split; rintros ⟨y, hy, hxy⟩; refine ⟨1-y, mem_iff_one_sub_mem.mp hy, _⟩; convert hxy, simp end /-! #### Space of paths -/ open continuous_map instance : has_coe (path x y) C(I, X) := ⟨λ γ, γ.1⟩ /-- The following instance defines the topology on the path space to be induced from the compact-open topology on the space `C(I,X)` of continuous maps from `I` to `X`. -/ instance : topological_space (path x y) := topological_space.induced (coe : _ → C(I, X)) continuous_map.compact_open lemma continuous_eval : continuous (λ p : path x y × I, p.1 p.2) := continuous_eval'.comp $ continuous_induced_dom.prod_map continuous_id @[continuity] lemma _root_.continuous.path_eval {Y} [topological_space Y] {f : Y → path x y} {g : Y → I} (hf : continuous f) (hg : continuous g) : continuous (λ y, f y (g y)) := continuous.comp continuous_eval (hf.prod_mk hg) lemma continuous_uncurry_iff {Y} [topological_space Y] {g : Y → path x y} : continuous ↿g ↔ continuous g := iff.symm $ continuous_induced_rng.trans ⟨λ h, continuous_uncurry_of_continuous ⟨_, h⟩, continuous_of_continuous_uncurry ↑g⟩ /-- A continuous map extending a path to `ℝ`, constant before `0` and after `1`. -/ def extend : ℝ → X := Icc_extend zero_le_one γ /-- See Note [continuity lemma statement]. -/ lemma _root_.continuous.path_extend {γ : Y → path x y} {f : Y → ℝ} (hγ : continuous ↿γ) (hf : continuous f) : continuous (λ t, (γ t).extend (f t)) := continuous.Icc_extend hγ hf /-- A useful special case of `continuous.path_extend`. -/ @[continuity] lemma continuous_extend : continuous γ.extend := γ.continuous.Icc_extend' lemma _root_.filter.tendsto.path_extend {X Y : Type*} [topological_space X] [topological_space Y] {l r : Y → X} {y : Y} {l₁ : filter ℝ} {l₂ : filter X} {γ : ∀ y, path (l y) (r y)} (hγ : tendsto ↿γ (𝓝 y ×ᶠ l₁.map (proj_Icc 0 1 zero_le_one)) l₂) : tendsto ↿(λ x, (γ x).extend) (𝓝 y ×ᶠ l₁) l₂ := filter.tendsto.Icc_extend _ hγ lemma _root_.continuous_at.path_extend {g : Y → ℝ} {l r : Y → X} (γ : ∀ y, path (l y) (r y)) {y : Y} (hγ : continuous_at ↿γ (y, proj_Icc 0 1 zero_le_one (g y))) (hg : continuous_at g y) : continuous_at (λ i, (γ i).extend (g i)) y := hγ.Icc_extend (λ x, γ x) hg @[simp] lemma extend_extends {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t : ℝ} (ht : t ∈ (Icc 0 1 : set ℝ)) : γ.extend t = γ ⟨t, ht⟩ := Icc_extend_of_mem _ γ ht lemma extend_zero : γ.extend 0 = x := by simp lemma extend_one : γ.extend 1 = y := by simp @[simp] lemma extend_extends' {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t : (Icc 0 1 : set ℝ)) : γ.extend t = γ t := Icc_extend_coe _ γ t @[simp] lemma extend_range {X : Type*} [topological_space X] {a b : X} (γ : path a b) : range γ.extend = range γ := Icc_extend_range _ γ lemma extend_of_le_zero {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t : ℝ} (ht : t ≤ 0) : γ.extend t = a := (Icc_extend_of_le_left _ _ ht).trans γ.source lemma extend_of_one_le {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t : ℝ} (ht : 1 ≤ t) : γ.extend t = b := (Icc_extend_of_right_le _ _ ht).trans γ.target @[simp] lemma refl_extend {X : Type*} [topological_space X] {a : X} : (path.refl a).extend = λ _, a := rfl /-- The path obtained from a map defined on `ℝ` by restriction to the unit interval. -/ def of_line {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y) : path x y := { to_fun := f ∘ coe, continuous_to_fun := hf.comp_continuous continuous_subtype_coe subtype.prop, source' := h₀, target' := h₁ } lemma of_line_mem {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y) : ∀ t, of_line hf h₀ h₁ t ∈ f '' I := λ ⟨t, t_in⟩, ⟨t, t_in, rfl⟩ local attribute [simp] Iic_def /-- Concatenation of two paths from `x` to `y` and from `y` to `z`, putting the first path on `[0, 1/2]` and the second one on `[1/2, 1]`. -/ @[trans] def trans (γ : path x y) (γ' : path y z) : path x z := { to_fun := (λ t : ℝ, if t ≤ 1/2 then γ.extend (2*t) else γ'.extend (2*t-1)) ∘ coe, continuous_to_fun := begin refine (continuous.if_le _ _ continuous_id continuous_const (by norm_num)).comp continuous_subtype_coe, -- TODO: the following are provable by `continuity` but it is too slow exacts [γ.continuous_extend.comp (continuous_const.mul continuous_id), γ'.continuous_extend.comp ((continuous_const.mul continuous_id).sub continuous_const)] end, source' := by norm_num, target' := by norm_num } lemma trans_apply (γ : path x y) (γ' : path y z) (t : I) : (γ.trans γ') t = if h : (t : ℝ) ≤ 1/2 then γ ⟨2 * t, (mul_pos_mem_iff zero_lt_two).2 ⟨t.2.1, h⟩⟩ else γ' ⟨2 * t - 1, two_mul_sub_one_mem_iff.2 ⟨(not_le.1 h).le, t.2.2⟩⟩ := show ite _ _ _ = _, by split_ifs; rw extend_extends @[simp] lemma trans_symm (γ : path x y) (γ' : path y z) : (γ.trans γ').symm = γ'.symm.trans γ.symm := begin ext t, simp only [trans_apply, ← one_div, symm_apply, not_le, comp_app], split_ifs with h h₁ h₂ h₃ h₄; rw [coe_symm_eq] at h, { have ht : (t : ℝ) = 1/2, { linarith [unit_interval.nonneg t, unit_interval.le_one t] }, norm_num [ht] }, { refine congr_arg _ (subtype.ext _), norm_num [sub_sub_eq_add_sub, mul_sub] }, { refine congr_arg _ (subtype.ext _), have h : 2 - 2 * (t : ℝ) - 1 = 1 - 2 * t, by linarith, norm_num [mul_sub, h] }, { exfalso, linarith [unit_interval.nonneg t, unit_interval.le_one t] } end @[simp] lemma refl_trans_refl {X : Type*} [topological_space X] {a : X} : (path.refl a).trans (path.refl a) = path.refl a := begin ext, simp only [path.trans, if_t_t, one_div, path.refl_extend], refl end lemma trans_range {X : Type*} [topological_space X] {a b c : X} (γ₁ : path a b) (γ₂ : path b c) : range (γ₁.trans γ₂) = range γ₁ ∪ range γ₂ := begin rw path.trans, apply eq_of_subset_of_subset, { rintros x ⟨⟨t, ht0, ht1⟩, hxt⟩, by_cases h : t ≤ 1/2, { left, use [2*t, ⟨by linarith, by linarith⟩], rw ← γ₁.extend_extends, unfold_coes at hxt, simp only [h, comp_app, if_true] at hxt, exact hxt }, { right, use [2*t-1, ⟨by linarith, by linarith⟩], rw ← γ₂.extend_extends, unfold_coes at hxt, simp only [h, comp_app, if_false] at hxt, exact hxt } }, { rintros x (⟨⟨t, ht0, ht1⟩, hxt⟩ | ⟨⟨t, ht0, ht1⟩, hxt⟩), { use ⟨t/2, ⟨by linarith, by linarith⟩⟩, unfold_coes, have : t/2 ≤ 1/2 := by linarith, simp only [this, comp_app, if_true], ring_nf, rwa γ₁.extend_extends }, { by_cases h : t = 0, { use ⟨1/2, ⟨by linarith, by linarith⟩⟩, unfold_coes, simp only [h, comp_app, if_true, le_refl, mul_one_div_cancel (two_ne_zero' ℝ)], rw γ₁.extend_one, rwa [← γ₂.extend_extends, h, γ₂.extend_zero] at hxt }, { use ⟨(t+1)/2, ⟨by linarith, by linarith⟩⟩, unfold_coes, change t ≠ 0 at h, have ht0 := lt_of_le_of_ne ht0 h.symm, have : ¬ (t+1)/2 ≤ 1/2 := by {rw not_le, linarith}, simp only [comp_app, if_false, this], ring_nf, rwa γ₂.extend_extends } } } end /-- Image of a path from `x` to `y` by a continuous map -/ def map (γ : path x y) {Y : Type*} [topological_space Y] {f : X → Y} (h : continuous f) : path (f x) (f y) := { to_fun := f ∘ γ, continuous_to_fun := by continuity, source' := by simp, target' := by simp } @[simp] lemma map_coe (γ : path x y) {Y : Type*} [topological_space Y] {f : X → Y} (h : continuous f) : (γ.map h : I → Y) = f ∘ γ := by { ext t, refl } @[simp] lemma map_symm (γ : path x y) {Y : Type*} [topological_space Y] {f : X → Y} (h : continuous f) : (γ.map h).symm = γ.symm.map h := rfl @[simp] lemma map_trans (γ : path x y) (γ' : path y z) {Y : Type*} [topological_space Y] {f : X → Y} (h : continuous f) : (γ.trans γ').map h = (γ.map h).trans (γ'.map h) := by { ext t, rw [trans_apply, map_coe, comp_app, trans_apply], split_ifs; refl } @[simp] lemma map_id (γ : path x y) : γ.map continuous_id = γ := by { ext, refl } @[simp] lemma map_map (γ : path x y) {Y : Type*} [topological_space Y] {Z : Type*} [topological_space Z] {f : X → Y} (hf : continuous f) {g : Y → Z} (hg : continuous g) : (γ.map hf).map hg = γ.map (hg.comp hf) := by { ext, refl } /-- Casting a path from `x` to `y` to a path from `x'` to `y'` when `x' = x` and `y' = y` -/ def cast (γ : path x y) {x' y'} (hx : x' = x) (hy : y' = y) : path x' y' := { to_fun := γ, continuous_to_fun := γ.continuous, source' := by simp [hx], target' := by simp [hy] } @[simp] lemma symm_cast {X : Type*} [topological_space X] {a₁ a₂ b₁ b₂ : X} (γ : path a₂ b₂) (ha : a₁ = a₂) (hb : b₁ = b₂) : (γ.cast ha hb).symm = (γ.symm).cast hb ha := rfl @[simp] lemma trans_cast {X : Type*} [topological_space X] {a₁ a₂ b₁ b₂ c₁ c₂ : X} (γ : path a₂ b₂) (γ' : path b₂ c₂) (ha : a₁ = a₂) (hb : b₁ = b₂) (hc : c₁ = c₂) : (γ.cast ha hb).trans (γ'.cast hb hc) = (γ.trans γ').cast ha hc := rfl @[simp] lemma cast_coe (γ : path x y) {x' y'} (hx : x' = x) (hy : y' = y) : (γ.cast hx hy : I → X) = γ := rfl @[continuity] lemma symm_continuous_family {X ι : Type*} [topological_space X] [topological_space ι] {a b : ι → X} (γ : Π (t : ι), path (a t) (b t)) (h : continuous ↿γ) : continuous ↿(λ t, (γ t).symm) := h.comp (continuous_id.prod_map continuous_symm) @[continuity] lemma continuous_symm : continuous (symm : path x y → path y x) := continuous_uncurry_iff.mp $ symm_continuous_family _ (continuous_fst.path_eval continuous_snd) @[continuity] lemma continuous_uncurry_extend_of_continuous_family {X ι : Type*} [topological_space X] [topological_space ι] {a b : ι → X} (γ : Π (t : ι), path (a t) (b t)) (h : continuous ↿γ) : continuous ↿(λ t, (γ t).extend) := h.comp (continuous_id.prod_map continuous_proj_Icc) @[continuity] lemma trans_continuous_family {X ι : Type*} [topological_space X] [topological_space ι] {a b c : ι → X} (γ₁ : Π (t : ι), path (a t) (b t)) (h₁ : continuous ↿γ₁) (γ₂ : Π (t : ι), path (b t) (c t)) (h₂ : continuous ↿γ₂) : continuous ↿(λ t, (γ₁ t).trans (γ₂ t)) := begin have h₁' := path.continuous_uncurry_extend_of_continuous_family γ₁ h₁, have h₂' := path.continuous_uncurry_extend_of_continuous_family γ₂ h₂, simp only [has_uncurry.uncurry, has_coe_to_fun.coe, coe_fn, path.trans, (∘)], refine continuous.if_le _ _ (continuous_subtype_coe.comp continuous_snd) continuous_const _, { change continuous ((λ p : ι × ℝ, (γ₁ p.1).extend p.2) ∘ (prod.map id (λ x, 2*x : I → ℝ))), exact h₁'.comp (continuous_id.prod_map $ continuous_const.mul continuous_subtype_coe) }, { change continuous ((λ p : ι × ℝ, (γ₂ p.1).extend p.2) ∘ (prod.map id (λ x, 2*x - 1 : I → ℝ))), exact h₂'.comp (continuous_id.prod_map $ (continuous_const.mul continuous_subtype_coe).sub continuous_const) }, { rintros st hst, simp [hst, mul_inv_cancel (two_ne_zero' ℝ)] } end @[continuity] lemma _root_.continuous.path_trans {f : Y → path x y} {g : Y → path y z} : continuous f → continuous g → continuous (λ t, (f t).trans (g t)) := begin intros hf hg, apply continuous_uncurry_iff.mp, exact trans_continuous_family _ (continuous_uncurry_iff.mpr hf) _ (continuous_uncurry_iff.mpr hg), end @[continuity] lemma continuous_trans {x y z : X} : continuous (λ ρ : path x y × path y z, ρ.1.trans ρ.2) := continuous_fst.path_trans continuous_snd /-! #### Product of paths -/ section prod variables {a₁ a₂ a₃ : X} {b₁ b₂ b₃ : Y} /-- Given a path in `X` and a path in `Y`, we can take their pointwise product to get a path in `X × Y`. -/ protected def prod (γ₁ : path a₁ a₂) (γ₂ : path b₁ b₂) : path (a₁, b₁) (a₂, b₂) := { to_continuous_map := continuous_map.prod_mk γ₁.to_continuous_map γ₂.to_continuous_map, source' := by simp, target' := by simp, } @[simp] lemma prod_coe_fn (γ₁ : path a₁ a₂) (γ₂ : path b₁ b₂) : (coe_fn (γ₁.prod γ₂)) = λ t, (γ₁ t, γ₂ t) := rfl /-- Path composition commutes with products -/ lemma trans_prod_eq_prod_trans (γ₁ : path a₁ a₂) (δ₁ : path a₂ a₃) (γ₂ : path b₁ b₂) (δ₂ : path b₂ b₃) : (γ₁.prod γ₂).trans (δ₁.prod δ₂) = (γ₁.trans δ₁).prod (γ₂.trans δ₂) := begin ext t; unfold path.trans; simp only [path.coe_mk, path.prod_coe_fn, function.comp_app]; split_ifs; refl, end end prod section pi variables {χ : ι → Type*} [∀ i, topological_space (χ i)] {as bs cs : Π i, χ i} /-- Given a family of paths, one in each Xᵢ, we take their pointwise product to get a path in Π i, Xᵢ. -/ protected def pi (γ : Π i, path (as i) (bs i)) : path as bs := { to_continuous_map := continuous_map.pi (λ i, (γ i).to_continuous_map), source' := by simp, target' := by simp, } @[simp] lemma pi_coe_fn (γ : Π i, path (as i) (bs i)) : (coe_fn (path.pi γ)) = λ t i, γ i t := rfl /-- Path composition commutes with products -/ lemma trans_pi_eq_pi_trans (γ₀ : Π i, path (as i) (bs i)) (γ₁ : Π i, path (bs i) (cs i)) : (path.pi γ₀).trans (path.pi γ₁) = path.pi (λ i, (γ₀ i).trans (γ₁ i)) := begin ext t i, unfold path.trans, simp only [path.coe_mk, function.comp_app, pi_coe_fn], split_ifs; refl, end end pi /-! #### Pointwise multiplication/addition of two paths in a topological (additive) group -/ /-- Pointwise multiplication of paths in a topological group. The additive version is probably more useful. -/ @[to_additive "Pointwise addition of paths in a topological additive group."] protected def mul [has_mul X] [has_continuous_mul X] {a₁ b₁ a₂ b₂ : X} (γ₁ : path a₁ b₁) (γ₂ : path a₂ b₂) : path (a₁ * a₂) (b₁ * b₂) := (γ₁.prod γ₂).map continuous_mul @[to_additive] protected lemma mul_apply [has_mul X] [has_continuous_mul X] {a₁ b₁ a₂ b₂ : X} (γ₁ : path a₁ b₁) (γ₂ : path a₂ b₂) (t : unit_interval) : (γ₁.mul γ₂) t = γ₁ t * γ₂ t := rfl /-! #### Truncating a path -/ /-- `γ.truncate t₀ t₁` is the path which follows the path `γ` on the time interval `[t₀, t₁]` and stays still otherwise. -/ def truncate {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t₀ t₁ : ℝ) : path (γ.extend $ min t₀ t₁) (γ.extend t₁) := { to_fun := λ s, γ.extend (min (max s t₀) t₁), continuous_to_fun := γ.continuous_extend.comp ((continuous_subtype_coe.max continuous_const).min continuous_const), source' := begin simp only [min_def, max_def'], norm_cast, split_ifs with h₁ h₂ h₃ h₄, { simp [γ.extend_of_le_zero h₁] }, { congr, linarith }, { have h₄ : t₁ ≤ 0 := le_of_lt (by simpa using h₂), simp [γ.extend_of_le_zero h₄, γ.extend_of_le_zero h₁] }, all_goals { refl } end, target' := begin simp only [min_def, max_def'], norm_cast, split_ifs with h₁ h₂ h₃, { simp [γ.extend_of_one_le h₂] }, { refl }, { have h₄ : 1 ≤ t₀ := le_of_lt (by simpa using h₁), simp [γ.extend_of_one_le h₄, γ.extend_of_one_le (h₄.trans h₃)] }, { refl } end } /-- `γ.truncate_of_le t₀ t₁ h`, where `h : t₀ ≤ t₁` is `γ.truncate t₀ t₁` casted as a path from `γ.extend t₀` to `γ.extend t₁`. -/ def truncate_of_le {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t₀ t₁ : ℝ} (h : t₀ ≤ t₁) : path (γ.extend t₀) (γ.extend t₁) := (γ.truncate t₀ t₁).cast (by rw min_eq_left h) rfl lemma truncate_range {X : Type*} [topological_space X] {a b : X} (γ : path a b) {t₀ t₁ : ℝ} : range (γ.truncate t₀ t₁) ⊆ range γ := begin rw ← γ.extend_range, simp only [range_subset_iff, set_coe.exists, set_coe.forall], intros x hx, simp only [has_coe_to_fun.coe, coe_fn, path.truncate, mem_range_self] end /-- For a path `γ`, `γ.truncate` gives a "continuous family of paths", by which we mean the uncurried function which maps `(t₀, t₁, s)` to `γ.truncate t₀ t₁ s` is continuous. -/ @[continuity] lemma truncate_continuous_family {X : Type*} [topological_space X] {a b : X} (γ : path a b) : continuous (λ x, γ.truncate x.1 x.2.1 x.2.2 : ℝ × ℝ × I → X) := γ.continuous_extend.comp (((continuous_subtype_coe.comp (continuous_snd.comp continuous_snd)).max continuous_fst).min (continuous_fst.comp continuous_snd)) /- TODO : When `continuity` gets quicker, change the proof back to : `begin` `simp only [has_coe_to_fun.coe, coe_fn, path.truncate],` `continuity,` `exact continuous_subtype_coe` `end` -/ @[continuity] lemma truncate_const_continuous_family {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t : ℝ) : continuous ↿(γ.truncate t) := have key : continuous (λ x, (t, x) : ℝ × I → ℝ × ℝ × I) := continuous_const.prod_mk continuous_id, by convert γ.truncate_continuous_family.comp key @[simp] lemma truncate_self {X : Type*} [topological_space X] {a b : X} (γ : path a b) (t : ℝ) : γ.truncate t t = (path.refl $ γ.extend t).cast (by rw min_self) rfl := begin ext x, rw cast_coe, simp only [truncate, has_coe_to_fun.coe, coe_fn, refl, min_def, max_def], split_ifs with h₁ h₂; congr, end @[simp] lemma truncate_zero_zero {X : Type*} [topological_space X] {a b : X} (γ : path a b) : γ.truncate 0 0 = (path.refl a).cast (by rw [min_self, γ.extend_zero]) γ.extend_zero := by convert γ.truncate_self 0; exact γ.extend_zero.symm @[simp] lemma truncate_one_one {X : Type*} [topological_space X] {a b : X} (γ : path a b) : γ.truncate 1 1 = (path.refl b).cast (by rw [min_self, γ.extend_one]) γ.extend_one := by convert γ.truncate_self 1; exact γ.extend_one.symm @[simp] lemma truncate_zero_one {X : Type*} [topological_space X] {a b : X} (γ : path a b) : γ.truncate 0 1 = γ.cast (by simp [zero_le_one, extend_zero]) (by simp) := begin ext x, rw cast_coe, have : ↑x ∈ (Icc 0 1 : set ℝ) := x.2, rw [truncate, coe_mk, max_eq_left this.1, min_eq_left this.2, extend_extends'] end /-! #### Reparametrising a path -/ /-- Given a path `γ` and a function `f : I → I` where `f 0 = 0` and `f 1 = 1`, `γ.reparam f` is the path defined by `γ ∘ f`. -/ def reparam (γ : path x y) (f : I → I) (hfcont : continuous f) (hf₀ : f 0 = 0) (hf₁ : f 1 = 1) : path x y := { to_fun := γ ∘ f, continuous_to_fun := by continuity, source' := by simp [hf₀], target' := by simp [hf₁] } @[simp] lemma coe_to_fun (γ : path x y) {f : I → I} (hfcont : continuous f) (hf₀ : f 0 = 0) (hf₁ : f 1 = 1) : ⇑(γ.reparam f hfcont hf₀ hf₁) = γ ∘ f := rfl @[simp] lemma reparam_id (γ : path x y) : γ.reparam id continuous_id rfl rfl = γ := by { ext, refl } lemma range_reparam (γ : path x y) {f : I → I} (hfcont : continuous f) (hf₀ : f 0 = 0) (hf₁ : f 1 = 1) : range ⇑(γ.reparam f hfcont hf₀ hf₁) = range γ := begin change range (γ ∘ f) = range γ, have : range f = univ, { rw range_iff_surjective, intro t, have h₁ : continuous (Icc_extend (zero_le_one' ℝ) f), { continuity }, have := intermediate_value_Icc (zero_le_one' ℝ) h₁.continuous_on, { rw [Icc_extend_left, Icc_extend_right] at this, change Icc (f 0) (f 1) ⊆ _ at this, rw [hf₀, hf₁] at this, rcases this t.2 with ⟨w, hw₁, hw₂⟩, rw Icc_extend_of_mem _ _ hw₁ at hw₂, use [⟨w, hw₁⟩, hw₂] } }, rw [range_comp, this, image_univ], end lemma refl_reparam {f : I → I} (hfcont : continuous f) (hf₀ : f 0 = 0) (hf₁ : f 1 = 1) : (refl x).reparam f hfcont hf₀ hf₁ = refl x := begin ext, simp, end end path /-! ### Being joined by a path -/ /-- The relation "being joined by a path". This is an equivalence relation. -/ def joined (x y : X) : Prop := nonempty (path x y) @[refl] lemma joined.refl (x : X) : joined x x := ⟨path.refl x⟩ /-- When two points are joined, choose some path from `x` to `y`. -/ def joined.some_path (h : joined x y) : path x y := nonempty.some h @[symm] lemma joined.symm {x y : X} (h : joined x y) : joined y x := ⟨h.some_path.symm⟩ @[trans] lemma joined.trans {x y z : X} (hxy : joined x y) (hyz : joined y z) : joined x z := ⟨hxy.some_path.trans hyz.some_path⟩ variables (X) /-- The setoid corresponding the equivalence relation of being joined by a continuous path. -/ def path_setoid : setoid X := { r := joined, iseqv := mk_equivalence _ joined.refl (λ x y, joined.symm) (λ x y z, joined.trans) } /-- The quotient type of points of a topological space modulo being joined by a continuous path. -/ def zeroth_homotopy := quotient (path_setoid X) instance : inhabited (zeroth_homotopy ℝ) := ⟨@quotient.mk ℝ (path_setoid ℝ) 0⟩ variables {X} /-! ### Being joined by a path inside a set -/ /-- The relation "being joined by a path in `F`". Not quite an equivalence relation since it's not reflexive for points that do not belong to `F`. -/ def joined_in (F : set X) (x y : X) : Prop := ∃ γ : path x y, ∀ t, γ t ∈ F variables {F : set X} lemma joined_in.mem (h : joined_in F x y) : x ∈ F ∧ y ∈ F := begin rcases h with ⟨γ, γ_in⟩, have : γ 0 ∈ F ∧ γ 1 ∈ F, by { split; apply γ_in }, simpa using this end lemma joined_in.source_mem (h : joined_in F x y) : x ∈ F := h.mem.1 lemma joined_in.target_mem (h : joined_in F x y) : y ∈ F := h.mem.2 /-- When `x` and `y` are joined in `F`, choose a path from `x` to `y` inside `F` -/ def joined_in.some_path (h : joined_in F x y) : path x y := classical.some h lemma joined_in.some_path_mem (h : joined_in F x y) (t : I) : h.some_path t ∈ F := classical.some_spec h t /-- If `x` and `y` are joined in the set `F`, then they are joined in the subtype `F`. -/ lemma joined_in.joined_subtype (h : joined_in F x y) : joined (⟨x, h.source_mem⟩ : F) (⟨y, h.target_mem⟩ : F) := ⟨{ to_fun := λ t, ⟨h.some_path t, h.some_path_mem t⟩, continuous_to_fun := by continuity, source' := by simp, target' := by simp }⟩ lemma joined_in.of_line {f : ℝ → X} (hf : continuous_on f I) (h₀ : f 0 = x) (h₁ : f 1 = y) (hF : f '' I ⊆ F) : joined_in F x y := ⟨path.of_line hf h₀ h₁, λ t, hF $ path.of_line_mem hf h₀ h₁ t⟩ lemma joined_in.joined (h : joined_in F x y) : joined x y := ⟨h.some_path⟩ lemma joined_in_iff_joined (x_in : x ∈ F) (y_in : y ∈ F) : joined_in F x y ↔ joined (⟨x, x_in⟩ : F) (⟨y, y_in⟩ : F) := ⟨λ h, h.joined_subtype, λ h, ⟨h.some_path.map continuous_subtype_coe, by simp⟩⟩ @[simp] lemma joined_in_univ : joined_in univ x y ↔ joined x y := by simp [joined_in, joined, exists_true_iff_nonempty] lemma joined_in.mono {U V : set X} (h : joined_in U x y) (hUV : U ⊆ V) : joined_in V x y := ⟨h.some_path, λ t, hUV (h.some_path_mem t)⟩ lemma joined_in.refl (h : x ∈ F) : joined_in F x x := ⟨path.refl x, λ t, h⟩ @[symm] lemma joined_in.symm (h : joined_in F x y) : joined_in F y x := begin cases h.mem with hx hy, simp [joined_in_iff_joined, *] at *, exact h.symm end lemma joined_in.trans (hxy : joined_in F x y) (hyz : joined_in F y z) : joined_in F x z := begin cases hxy.mem with hx hy, cases hyz.mem with hx hy, simp [joined_in_iff_joined, *] at *, exact hxy.trans hyz end /-! ### Path component -/ /-- The path component of `x` is the set of points that can be joined to `x`. -/ def path_component (x : X) := {y | joined x y} @[simp] lemma mem_path_component_self (x : X) : x ∈ path_component x := joined.refl x @[simp] lemma path_component.nonempty (x : X) : (path_component x).nonempty := ⟨x, mem_path_component_self x⟩ lemma mem_path_component_of_mem (h : x ∈ path_component y) : y ∈ path_component x := joined.symm h lemma path_component_symm : x ∈ path_component y ↔ y ∈ path_component x := ⟨λ h, mem_path_component_of_mem h, λ h, mem_path_component_of_mem h⟩ lemma path_component_congr (h : x ∈ path_component y) : path_component x = path_component y := begin ext z, split, { intro h', rw path_component_symm, exact (h.trans h').symm }, { intro h', rw path_component_symm at h' ⊢, exact h'.trans h }, end lemma path_component_subset_component (x : X) : path_component x ⊆ connected_component x := λ y h, (is_connected_range h.some_path.continuous).subset_connected_component ⟨0, by simp⟩ ⟨1, by simp⟩ /-- The path component of `x` in `F` is the set of points that can be joined to `x` in `F`. -/ def path_component_in (x : X) (F : set X) := {y | joined_in F x y} @[simp] lemma path_component_in_univ (x : X) : path_component_in x univ = path_component x := by simp [path_component_in, path_component, joined_in, joined, exists_true_iff_nonempty] lemma joined.mem_path_component (hyz : joined y z) (hxy : y ∈ path_component x) : z ∈ path_component x := hxy.trans hyz /-! ### Path connected sets -/ /-- A set `F` is path connected if it contains a point that can be joined to all other in `F`. -/ def is_path_connected (F : set X) : Prop := ∃ x ∈ F, ∀ {y}, y ∈ F → joined_in F x y lemma is_path_connected_iff_eq : is_path_connected F ↔ ∃ x ∈ F, path_component_in x F = F := begin split ; rintros ⟨x, x_in, h⟩ ; use [x, x_in], { ext y, exact ⟨λ hy, hy.mem.2, h⟩ }, { intros y y_in, rwa ← h at y_in }, end lemma is_path_connected.joined_in (h : is_path_connected F) : ∀ x y ∈ F, joined_in F x y := λ x x_in x y_in, let ⟨b, b_in, hb⟩ := h in (hb x_in).symm.trans (hb y_in) lemma is_path_connected_iff : is_path_connected F ↔ F.nonempty ∧ ∀ x y ∈ F, joined_in F x y := ⟨λ h, ⟨let ⟨b, b_in, hb⟩ := h in ⟨b, b_in⟩, h.joined_in⟩, λ ⟨⟨b, b_in⟩, h⟩, ⟨b, b_in, λ x x_in, h b b_in x x_in⟩⟩ lemma is_path_connected.image {Y : Type*} [topological_space Y] (hF : is_path_connected F) {f : X → Y} (hf : continuous f) : is_path_connected (f '' F) := begin rcases hF with ⟨x, x_in, hx⟩, use [f x, mem_image_of_mem f x_in], rintros _ ⟨y, y_in, rfl⟩, exact ⟨(hx y_in).some_path.map hf, λ t, ⟨_, (hx y_in).some_path_mem t, rfl⟩⟩, end lemma is_path_connected.mem_path_component (h : is_path_connected F) (x_in : x ∈ F) (y_in : y ∈ F) : y ∈ path_component x := (h.joined_in x x_in y y_in).joined lemma is_path_connected.subset_path_component (h : is_path_connected F) (x_in : x ∈ F) : F ⊆ path_component x := λ y y_in, h.mem_path_component x_in y_in lemma is_path_connected.union {U V : set X} (hU : is_path_connected U) (hV : is_path_connected V) (hUV : (U ∩ V).nonempty) : is_path_connected (U ∪ V) := begin rcases hUV with ⟨x, xU, xV⟩, use [x, or.inl xU], rintros y (yU | yV), { exact (hU.joined_in x xU y yU).mono (subset_union_left U V) }, { exact (hV.joined_in x xV y yV).mono (subset_union_right U V) }, end /-- If a set `W` is path-connected, then it is also path-connected when seen as a set in a smaller ambient type `U` (when `U` contains `W`). -/ lemma is_path_connected.preimage_coe {U W : set X} (hW : is_path_connected W) (hWU : W ⊆ U) : is_path_connected ((coe : U → X) ⁻¹' W) := begin rcases hW with ⟨x, x_in, hx⟩, use [⟨x, hWU x_in⟩, by simp [x_in]], rintros ⟨y, hyU⟩ hyW, exact ⟨(hx hyW).joined_subtype.some_path.map (continuous_inclusion hWU), by simp⟩ end lemma is_path_connected.exists_path_through_family {X : Type*} [topological_space X] {n : ℕ} {s : set X} (h : is_path_connected s) (p : fin (n+1) → X) (hp : ∀ i, p i ∈ s) : ∃ γ : path (p 0) (p n), (range γ ⊆ s) ∧ (∀ i, p i ∈ range γ) := begin let p' : ℕ → X := λ k, if h : k < n+1 then p ⟨k, h⟩ else p ⟨0, n.zero_lt_succ⟩, obtain ⟨γ, hγ⟩ : ∃ (γ : path (p' 0) (p' n)), (∀ i ≤ n, p' i ∈ range γ) ∧ range γ ⊆ s, { have hp' : ∀ i ≤ n, p' i ∈ s, { intros i hi, simp [p', nat.lt_succ_of_le hi, hp] }, clear_value p', clear hp p, induction n with n hn, { use path.refl (p' 0), { split, { rintros i hi, rw le_zero_iff.mp hi, exact ⟨0, rfl⟩ }, { rw range_subset_iff, rintros x, exact hp' 0 le_rfl } } }, { rcases hn (λ i hi, hp' i $ nat.le_succ_of_le hi) with ⟨γ₀, hγ₀⟩, rcases h.joined_in (p' n) (hp' n n.le_succ) (p' $ n+1) (hp' (n+1) $ le_rfl) with ⟨γ₁, hγ₁⟩, let γ : path (p' 0) (p' $ n+1) := γ₀.trans γ₁, use γ, have range_eq : range γ = range γ₀ ∪ range γ₁ := γ₀.trans_range γ₁, split, { rintros i hi, by_cases hi' : i ≤ n, { rw range_eq, left, exact hγ₀.1 i hi' }, { rw [not_le, ← nat.succ_le_iff] at hi', have : i = n.succ := by linarith, rw this, use 1, exact γ.target } }, { rw range_eq, apply union_subset hγ₀.2, rw range_subset_iff, exact hγ₁ } } }, have hpp' : ∀ k < n+1, p k = p' k, { intros k hk, simp only [p', hk, dif_pos], congr, ext, rw fin.coe_coe_of_lt hk, norm_cast }, use γ.cast (hpp' 0 n.zero_lt_succ) (hpp' n n.lt_succ_self), simp only [γ.cast_coe], refine and.intro hγ.2 _, rintros ⟨i, hi⟩, suffices : p ⟨i, hi⟩ = p' i, by convert hγ.1 i (nat.le_of_lt_succ hi), rw ← hpp' i hi, suffices : i = i % n.succ, { congr, assumption }, rw nat.mod_eq_of_lt hi, end lemma is_path_connected.exists_path_through_family' {X : Type*} [topological_space X] {n : ℕ} {s : set X} (h : is_path_connected s) (p : fin (n+1) → X) (hp : ∀ i, p i ∈ s) : ∃ (γ : path (p 0) (p n)) (t : fin (n + 1) → I), (∀ t, γ t ∈ s) ∧ ∀ i, γ (t i) = p i := begin rcases h.exists_path_through_family p hp with ⟨γ, hγ⟩, rcases hγ with ⟨h₁, h₂⟩, simp only [range, mem_set_of_eq] at h₂, rw range_subset_iff at h₁, choose! t ht using h₂, exact ⟨γ, t, h₁, ht⟩ end /-! ### Path connected spaces -/ /-- A topological space is path-connected if it is non-empty and every two points can be joined by a continuous path. -/ class path_connected_space (X : Type*) [topological_space X] : Prop := (nonempty : nonempty X) (joined : ∀ x y : X, joined x y) lemma path_connected_space_iff_zeroth_homotopy : path_connected_space X ↔ nonempty (zeroth_homotopy X) ∧ subsingleton (zeroth_homotopy X) := begin letI := path_setoid X, split, { introI h, refine ⟨(nonempty_quotient_iff _).mpr h.1, ⟨_⟩⟩, rintros ⟨x⟩ ⟨y⟩, exact quotient.sound (path_connected_space.joined x y) }, { unfold zeroth_homotopy, rintros ⟨h, h'⟩, resetI, exact ⟨(nonempty_quotient_iff _).mp h, λ x y, quotient.exact $ subsingleton.elim ⟦x⟧ ⟦y⟧⟩ }, end namespace path_connected_space variables [path_connected_space X] /-- Use path-connectedness to build a path between two points. -/ def some_path (x y : X) : path x y := nonempty.some (joined x y) end path_connected_space lemma is_path_connected_iff_path_connected_space : is_path_connected F ↔ path_connected_space F := begin rw is_path_connected_iff, split, { rintro ⟨⟨x, x_in⟩, h⟩, refine ⟨⟨⟨x, x_in⟩⟩, _⟩, rintros ⟨y, y_in⟩ ⟨z, z_in⟩, have H := h y y_in z z_in, rwa joined_in_iff_joined y_in z_in at H }, { rintros ⟨⟨x, x_in⟩, H⟩, refine ⟨⟨x, x_in⟩, λ y y_in z z_in, _⟩, rw joined_in_iff_joined y_in z_in, apply H } end lemma path_connected_space_iff_univ : path_connected_space X ↔ is_path_connected (univ : set X) := begin split, { introI h, haveI := @path_connected_space.nonempty X _ _, inhabit X, refine ⟨default, mem_univ _, _⟩, simpa using path_connected_space.joined default }, { intro h, have h' := h.joined_in, cases h with x h, exact ⟨⟨x⟩, by simpa using h'⟩ }, end lemma path_connected_space_iff_eq : path_connected_space X ↔ ∃ x : X, path_component x = univ := by simp [path_connected_space_iff_univ, is_path_connected_iff_eq] @[priority 100] -- see Note [lower instance priority] instance path_connected_space.connected_space [path_connected_space X] : connected_space X := begin rw connected_space_iff_connected_component, rcases is_path_connected_iff_eq.mp (path_connected_space_iff_univ.mp ‹_›) with ⟨x, x_in, hx⟩, use x, rw ← univ_subset_iff, exact (by simpa using hx : path_component x = univ) ▸ path_component_subset_component x end lemma is_path_connected.is_connected (hF : is_path_connected F) : is_connected F := begin rw is_connected_iff_connected_space, rw is_path_connected_iff_path_connected_space at hF, exact @path_connected_space.connected_space _ _ hF end namespace path_connected_space variables [path_connected_space X] lemma exists_path_through_family {n : ℕ} (p : fin (n+1) → X) : ∃ γ : path (p 0) (p n), (∀ i, p i ∈ range γ) := begin have : is_path_connected (univ : set X) := path_connected_space_iff_univ.mp (by apply_instance), rcases this.exists_path_through_family p (λ i, true.intro) with ⟨γ, -, h⟩, exact ⟨γ, h⟩ end lemma exists_path_through_family' {n : ℕ} (p : fin (n+1) → X) : ∃ (γ : path (p 0) (p n)) (t : fin (n + 1) → I), ∀ i, γ (t i) = p i := begin have : is_path_connected (univ : set X) := path_connected_space_iff_univ.mp (by apply_instance), rcases this.exists_path_through_family' p (λ i, true.intro) with ⟨γ, t, -, h⟩, exact ⟨γ, t, h⟩ end end path_connected_space /-! ### Locally path connected spaces -/ /-- A topological space is locally path connected, at every point, path connected neighborhoods form a neighborhood basis. -/ class loc_path_connected_space (X : Type*) [topological_space X] : Prop := (path_connected_basis : ∀ x : X, (𝓝 x).has_basis (λ s : set X, s ∈ 𝓝 x ∧ is_path_connected s) id) export loc_path_connected_space (path_connected_basis) lemma loc_path_connected_of_bases {p : ι → Prop} {s : X → ι → set X} (h : ∀ x, (𝓝 x).has_basis p (s x)) (h' : ∀ x i, p i → is_path_connected (s x i)) : loc_path_connected_space X := begin constructor, intro x, apply (h x).to_has_basis, { intros i pi, exact ⟨s x i, ⟨(h x).mem_of_mem pi, h' x i pi⟩, by refl⟩ }, { rintros U ⟨U_in, hU⟩, rcases (h x).mem_iff.mp U_in with ⟨i, pi, hi⟩, tauto } end lemma path_connected_space_iff_connected_space [loc_path_connected_space X] : path_connected_space X ↔ connected_space X := begin split, { introI h, apply_instance }, { introI hX, rw path_connected_space_iff_eq, use (classical.arbitrary X), refine is_clopen.eq_univ ⟨_, _⟩ (by simp), { rw is_open_iff_mem_nhds, intros y y_in, rcases (path_connected_basis y).ex_mem with ⟨U, ⟨U_in, hU⟩⟩, apply mem_of_superset U_in, rw ← path_component_congr y_in, exact hU.subset_path_component (mem_of_mem_nhds U_in) }, { rw is_closed_iff_nhds, intros y H, rcases (path_connected_basis y).ex_mem with ⟨U, ⟨U_in, hU⟩⟩, rcases H U U_in with ⟨z, hz, hz'⟩, exact ((hU.joined_in z hz y $ mem_of_mem_nhds U_in).joined.mem_path_component hz') } }, end lemma path_connected_subset_basis [loc_path_connected_space X] {U : set X} (h : is_open U) (hx : x ∈ U) : (𝓝 x).has_basis (λ s : set X, s ∈ 𝓝 x ∧ is_path_connected s ∧ s ⊆ U) id := (path_connected_basis x).has_basis_self_subset (is_open.mem_nhds h hx) lemma loc_path_connected_of_is_open [loc_path_connected_space X] {U : set X} (h : is_open U) : loc_path_connected_space U := ⟨begin rintros ⟨x, x_in⟩, rw nhds_subtype_eq_comap, constructor, intros V, rw (has_basis.comap (coe : U → X) (path_connected_subset_basis h x_in)).mem_iff, split, { rintros ⟨W, ⟨W_in, hW, hWU⟩, hWV⟩, exact ⟨coe ⁻¹' W, ⟨⟨preimage_mem_comap W_in, hW.preimage_coe hWU⟩, hWV⟩⟩ }, { rintros ⟨W, ⟨W_in, hW⟩, hWV⟩, refine ⟨coe '' W, ⟨filter.image_coe_mem_of_mem_comap (is_open.mem_nhds h x_in) W_in, hW.image continuous_subtype_coe, subtype.coe_image_subset U W⟩, _⟩, rintros x ⟨y, ⟨y_in, hy⟩⟩, rw ← subtype.coe_injective hy, tauto }, end⟩ lemma is_open.is_connected_iff_is_path_connected [loc_path_connected_space X] {U : set X} (U_op : is_open U) : is_path_connected U ↔ is_connected U := begin rw [is_connected_iff_connected_space, is_path_connected_iff_path_connected_space], haveI := loc_path_connected_of_is_open U_op, exact path_connected_space_iff_connected_space end
54a7a3ee68fb930a1277245a6ac928b01f357169
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/set_theory/lists.lean
bf71507308f262e8facd65fe8c0c1c03e2d45ed2
[ "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
14,881
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.list.basic /-! # A computable model of ZFA without infinity In this file we define finite hereditary lists. This is useful for calculations in naive set theory. We distinguish two kinds of ZFA lists: * Atoms. Directly correspond to an element of the original type. * Proper ZFA lists. Can be thought of (but aren't implemented) as a list of ZFA lists (not necessarily proper). For example, `lists ℕ` contains stuff like `23`, `[]`, `[37]`, `[1, [[2], 3], 4]`. ## Implementation note As we want to be able to append both atoms and proper ZFA lists to proper ZFA lists, it's handy that atoms and proper ZFA lists belong to the same type, even though atoms of `α` could be modelled as `α` directly. But we don't want to be able to append anything to atoms. This calls for a two-steps definition of ZFA lists: * First, define ZFA prelists as atoms and proper ZFA prelists. Those proper ZFA prelists are defined by inductive appending of (not necessarily proper) ZFA lists. * Second, define ZFA lists by rubbing out the distinction between atoms and proper lists. ## Main declarations * `lists' α ff`: Atoms as ZFA prelists. Basically a copy of `α`. * `lists' α tt`: Proper ZFA prelists. Defined inductively from the empty ZFA prelist (`lists'.nil`) and from appending a ZFA prelist to a proper ZFA prelist (`lists'.cons a l`). * `lists α`: ZFA lists. Sum of the atoms and proper ZFA prelists. ## TODO The next step is to define ZFA sets as lists quotiented by `lists.equiv`. (-/ variables {α : Type*} /-- Prelists, helper type to define `lists`. `lists' α ff` are the "atoms", a copy of `α`. `lists' α tt` are the "proper" ZFA prelists, inductively defined from the empty ZFA prelist and from appending a ZFA prelist to a proper ZFA prelist. It is made so that you can't append anything to an atom while having only one appending function for appending both atoms and proper ZFC prelists to a proper ZFA prelist. -/ @[derive decidable_eq] inductive {u} lists' (α : Type u) : bool → Type u | atom : α → lists' ff | nil : lists' tt | cons' {b} : lists' b → lists' tt → lists' tt /-- Hereditarily finite list, aka ZFA list. A ZFA list is either an "atom" (`b = ff`), corresponding to an element of `α`, or a "proper" ZFA list, inductively defined from the empty ZFA list and from appending a ZFA list to a proper ZFA list. -/ def lists (α : Type*) := Σ b, lists' α b namespace lists' instance [inhabited α] : ∀ b, inhabited (lists' α b) | tt := ⟨nil⟩ | ff := ⟨atom default⟩ /-- Appending a ZFA list to a proper ZFA prelist. -/ def cons : lists α → lists' α tt → lists' α tt | ⟨b, a⟩ l := cons' a l /-- Converts a ZFA prelist to a `list` of ZFA lists. Atoms are sent to `[]`. -/ @[simp] def to_list : ∀ {b}, lists' α b → list (lists α) | _ (atom a) := [] | _ nil := [] | _ (cons' a l) := ⟨_, a⟩ :: l.to_list @[simp] theorem to_list_cons (a : lists α) (l) : to_list (cons a l) = a :: l.to_list := by cases a; simp [cons] /-- Converts a `list` of ZFA lists to a proper ZFA prelist. -/ @[simp] def of_list : list (lists α) → lists' α tt | [] := nil | (a :: l) := cons a (of_list l) @[simp] theorem to_of_list (l : list (lists α)) : to_list (of_list l) = l := by induction l; simp * @[simp] theorem of_to_list : ∀ (l : lists' α tt), of_list (to_list l) = l := suffices ∀ b (h : tt = b) (l : lists' α b), let l' : lists' α tt := by rw h; exact l in of_list (to_list l') = l', from this _ rfl, λ b h l, begin induction l, {cases h}, {exact rfl}, case lists'.cons' : b a l IH₁ IH₂ { intro, change l' with cons' a l, simpa [cons] using IH₂ rfl } end end lists' mutual inductive lists.equiv, lists'.subset with lists.equiv : lists α → lists α → Prop | refl (l) : lists.equiv l l | antisymm {l₁ l₂ : lists' α tt} : lists'.subset l₁ l₂ → lists'.subset l₂ l₁ → lists.equiv ⟨_, l₁⟩ ⟨_, l₂⟩ with lists'.subset : lists' α tt → lists' α tt → Prop | nil {l} : lists'.subset lists'.nil l | cons {a a' l l'} : lists.equiv a a' → a' ∈ lists'.to_list l' → lists'.subset l l' → lists'.subset (lists'.cons a l) l' local infix ` ~ `:50 := lists.equiv /-- Equivalence of ZFA lists. Defined inductively. -/ add_decl_doc lists.equiv /-- Subset relation for ZFA lists. Defined inductively. -/ add_decl_doc lists'.subset namespace lists' instance : has_subset (lists' α tt) := ⟨lists'.subset⟩ /-- ZFA prelist membership. A ZFA list is in a ZFA prelist if some element of this ZFA prelist is equivalent as a ZFA list to this ZFA list. -/ instance {b} : has_mem (lists α) (lists' α b) := ⟨λ a l, ∃ a' ∈ l.to_list, a ~ a'⟩ theorem mem_def {b a} {l : lists' α b} : a ∈ l ↔ ∃ a' ∈ l.to_list, a ~ a' := iff.rfl @[simp] theorem mem_cons {a y l} : a ∈ @cons α y l ↔ a ~ y ∨ a ∈ l := by simp [mem_def, or_and_distrib_right, exists_or_distrib] theorem cons_subset {a} {l₁ l₂ : lists' α tt} : lists'.cons a l₁ ⊆ l₂ ↔ a ∈ l₂ ∧ l₁ ⊆ l₂ := begin refine ⟨λ h, _, λ ⟨⟨a', m, e⟩, s⟩, subset.cons e m s⟩, generalize_hyp h' : lists'.cons a l₁ = l₁' at h, cases h with l a' a'' l l' e m s, {cases a, cases h'}, cases a, cases a', cases h', exact ⟨⟨_, m, e⟩, s⟩ end theorem of_list_subset {l₁ l₂ : list (lists α)} (h : l₁ ⊆ l₂) : lists'.of_list l₁ ⊆ lists'.of_list l₂ := begin induction l₁, {exact subset.nil}, refine subset.cons (lists.equiv.refl _) _ (l₁_ih (list.subset_of_cons_subset h)), simp at h, simp [h] end @[refl] theorem subset.refl {l : lists' α tt} : l ⊆ l := by rw ← lists'.of_to_list l; exact of_list_subset (list.subset.refl _) theorem subset_nil {l : lists' α tt} : l ⊆ lists'.nil → l = lists'.nil := begin rw ← of_to_list l, induction to_list l; intro h, {refl}, rcases cons_subset.1 h with ⟨⟨_, ⟨⟩, _⟩, _⟩ end theorem mem_of_subset' {a} {l₁ l₂ : lists' α tt} (s : l₁ ⊆ l₂) (h : a ∈ l₁.to_list) : a ∈ l₂ := begin induction s with _ a a' l l' e m s IH, {cases h}, simp at h, rcases h with rfl|h, exacts [⟨_, m, e⟩, IH h] end theorem subset_def {l₁ l₂ : lists' α tt} : l₁ ⊆ l₂ ↔ ∀ a ∈ l₁.to_list, a ∈ l₂ := ⟨λ H a, mem_of_subset' H, λ H, begin rw ← of_to_list l₁, revert H, induction to_list l₁; intro, { exact subset.nil }, { simp at H, exact cons_subset.2 ⟨H.1, ih H.2⟩ } end⟩ end lists' namespace lists /-- Sends `a : α` to the corresponding atom in `lists α`. -/ @[pattern] def atom (a : α) : lists α := ⟨_, lists'.atom a⟩ /-- Converts a proper ZFA prelist to a ZFA list. -/ @[pattern] def of' (l : lists' α tt) : lists α := ⟨_, l⟩ /-- Converts a ZFA list to a `list` of ZFA lists. Atoms are sent to `[]`. -/ @[simp] def to_list : lists α → list (lists α) | ⟨b, l⟩ := l.to_list /-- Predicate stating that a ZFA list is proper. -/ def is_list (l : lists α) : Prop := l.1 /-- Converts a `list` of ZFA lists to a ZFA list. -/ def of_list (l : list (lists α)) : lists α := of' (lists'.of_list l) theorem is_list_to_list (l : list (lists α)) : is_list (of_list l) := eq.refl _ theorem to_of_list (l : list (lists α)) : to_list (of_list l) = l := by simp [of_list, of'] theorem of_to_list : ∀ {l : lists α}, is_list l → of_list (to_list l) = l | ⟨tt, l⟩ _ := by simp [of_list, of'] instance : inhabited (lists α) := ⟨of' lists'.nil⟩ instance [decidable_eq α] : decidable_eq (lists α) := by unfold lists; apply_instance instance [has_sizeof α] : has_sizeof (lists α) := by unfold lists; apply_instance /-- A recursion principle for pairs of ZFA lists and proper ZFA prelists. -/ def induction_mut (C : lists α → Sort*) (D : lists' α tt → Sort*) (C0 : ∀ a, C (atom a)) (C1 : ∀ l, D l → C (of' l)) (D0 : D lists'.nil) (D1 : ∀ a l, C a → D l → D (lists'.cons a l)) : pprod (∀ l, C l) (∀ l, D l) := begin suffices : ∀ {b} (l : lists' α b), pprod (C ⟨_, l⟩) (match b, l with | tt, l := D l | ff, l := punit end), { exact ⟨λ ⟨b, l⟩, (this _).1, λ l, (this l).2⟩ }, intros, induction l with a b a l IH₁ IH₂, { exact ⟨C0 _, ⟨⟩⟩ }, { exact ⟨C1 _ D0, D0⟩ }, { suffices, {exact ⟨C1 _ this, this⟩}, exact D1 ⟨_, _⟩ _ IH₁.1 IH₂.2 } end /-- Membership of ZFA list. A ZFA list belongs to a proper ZFA list if it belongs to the latter as a proper ZFA prelist. An atom has no members. -/ def mem (a : lists α) : lists α → Prop | ⟨ff, l⟩ := false | ⟨tt, l⟩ := a ∈ l instance : has_mem (lists α) (lists α) := ⟨mem⟩ theorem is_list_of_mem {a : lists α} : ∀ {l : lists α}, a ∈ l → is_list l | ⟨_, lists'.nil⟩ _ := rfl | ⟨_, lists'.cons' _ _⟩ _ := rfl theorem equiv.antisymm_iff {l₁ l₂ : lists' α tt} : of' l₁ ~ of' l₂ ↔ l₁ ⊆ l₂ ∧ l₂ ⊆ l₁ := begin refine ⟨λ h, _, λ ⟨h₁, h₂⟩, equiv.antisymm h₁ h₂⟩, cases h with _ _ _ h₁ h₂, { simp [lists'.subset.refl] }, { exact ⟨h₁, h₂⟩ } end attribute [refl] equiv.refl theorem equiv_atom {a} {l : lists α} : atom a ~ l ↔ atom a = l := ⟨λ h, by cases h; refl, λ h, h ▸ equiv.refl _⟩ theorem equiv.symm {l₁ l₂ : lists α} (h : l₁ ~ l₂) : l₂ ~ l₁ := by cases h with _ _ _ h₁ h₂; [refl, exact equiv.antisymm h₂ h₁] theorem equiv.trans : ∀ {l₁ l₂ l₃ : lists α}, l₁ ~ l₂ → l₂ ~ l₃ → l₁ ~ l₃ := begin let trans := λ (l₁ : lists α), ∀ ⦃l₂ l₃⦄, l₁ ~ l₂ → l₂ ~ l₃ → l₁ ~ l₃, suffices : pprod (∀ l₁, trans l₁) (∀ (l : lists' α tt) (l' ∈ l.to_list), trans l'), {exact this.1}, apply induction_mut, { intros a l₂ l₃ h₁ h₂, rwa ← equiv_atom.1 h₁ at h₂ }, { intros l₁ IH l₂ l₃ h₁ h₂, cases h₁ with _ _ l₂, {exact h₂}, cases h₂ with _ _ l₃, {exact h₁}, cases equiv.antisymm_iff.1 h₁ with hl₁ hr₁, cases equiv.antisymm_iff.1 h₂ with hl₂ hr₂, apply equiv.antisymm_iff.2; split; apply lists'.subset_def.2, { intros a₁ m₁, rcases lists'.mem_of_subset' hl₁ m₁ with ⟨a₂, m₂, e₁₂⟩, rcases lists'.mem_of_subset' hl₂ m₂ with ⟨a₃, m₃, e₂₃⟩, exact ⟨a₃, m₃, IH _ m₁ e₁₂ e₂₃⟩ }, { intros a₃ m₃, rcases lists'.mem_of_subset' hr₂ m₃ with ⟨a₂, m₂, e₃₂⟩, rcases lists'.mem_of_subset' hr₁ m₂ with ⟨a₁, m₁, e₂₁⟩, exact ⟨a₁, m₁, (IH _ m₁ e₂₁.symm e₃₂.symm).symm⟩ } }, { rintro _ ⟨⟩ }, { intros a l IH₁ IH₂, simpa [IH₁] using IH₂ } end instance : setoid (lists α) := ⟨(~), equiv.refl, @equiv.symm _, @equiv.trans _⟩ section decidable @[simp] def equiv.decidable_meas : (psum (Σ' (l₁ : lists α), lists α) $ psum (Σ' (l₁ : lists' α tt), lists' α tt) Σ' (a : lists α), lists' α tt) → ℕ | (psum.inl ⟨l₁, l₂⟩) := sizeof l₁ + sizeof l₂ | (psum.inr $ psum.inl ⟨l₁, l₂⟩) := sizeof l₁ + sizeof l₂ | (psum.inr $ psum.inr ⟨l₁, l₂⟩) := sizeof l₁ + sizeof l₂ open well_founded_tactics theorem sizeof_pos {b} (l : lists' α b) : 0 < sizeof l := by cases l; unfold_sizeof; trivial_nat_lt theorem lt_sizeof_cons' {b} (a : lists' α b) (l) : sizeof (⟨b, a⟩ : lists α) < sizeof (lists'.cons' a l) := by {unfold_sizeof, apply sizeof_pos} @[instance] mutual def equiv.decidable, subset.decidable, mem.decidable [decidable_eq α] with equiv.decidable : ∀ l₁ l₂ : lists α, decidable (l₁ ~ l₂) | ⟨ff, l₁⟩ ⟨ff, l₂⟩ := decidable_of_iff' (l₁ = l₂) $ by cases l₁; refine equiv_atom.trans (by simp [atom]) | ⟨ff, l₁⟩ ⟨tt, l₂⟩ := is_false $ by rintro ⟨⟩ | ⟨tt, l₁⟩ ⟨ff, l₂⟩ := is_false $ by rintro ⟨⟩ | ⟨tt, l₁⟩ ⟨tt, l₂⟩ := begin haveI := have sizeof l₁ + sizeof l₂ < sizeof (⟨tt, l₁⟩ : lists α) + sizeof (⟨tt, l₂⟩ : lists α), by default_dec_tac, subset.decidable l₁ l₂, haveI := have sizeof l₂ + sizeof l₁ < sizeof (⟨tt, l₁⟩ : lists α) + sizeof (⟨tt, l₂⟩ : lists α), by default_dec_tac, subset.decidable l₂ l₁, exact decidable_of_iff' _ equiv.antisymm_iff, end with subset.decidable : ∀ l₁ l₂ : lists' α tt, decidable (l₁ ⊆ l₂) | lists'.nil l₂ := is_true subset.nil | (@lists'.cons' _ b a l₁) l₂ := begin haveI := have sizeof (⟨b, a⟩ : lists α) + sizeof l₂ < sizeof (lists'.cons' a l₁) + sizeof l₂, from add_lt_add_right (lt_sizeof_cons' _ _) _, mem.decidable ⟨b, a⟩ l₂, haveI := have sizeof l₁ + sizeof l₂ < sizeof (lists'.cons' a l₁) + sizeof l₂, by default_dec_tac, subset.decidable l₁ l₂, exact decidable_of_iff' _ (@lists'.cons_subset _ ⟨_, _⟩ _ _) end with mem.decidable : ∀ (a : lists α) (l : lists' α tt), decidable (a ∈ l) | a lists'.nil := is_false $ by rintro ⟨_, ⟨⟩, _⟩ | a (lists'.cons' b l₂) := begin haveI := have sizeof a + sizeof (⟨_, b⟩ : lists α) < sizeof a + sizeof (lists'.cons' b l₂), from add_lt_add_left (lt_sizeof_cons' _ _) _, equiv.decidable a ⟨_, b⟩, haveI := have sizeof a + sizeof l₂ < sizeof a + sizeof (lists'.cons' b l₂), by default_dec_tac, mem.decidable a l₂, refine decidable_of_iff' (a ~ ⟨_, b⟩ ∨ a ∈ l₂) _, rw ← lists'.mem_cons, refl end using_well_founded { rel_tac := λ _ _, `[exact ⟨_, measure_wf equiv.decidable_meas⟩], dec_tac := `[assumption] } end decidable end lists namespace lists' theorem mem_equiv_left {l : lists' α tt} : ∀ {a a'}, a ~ a' → (a ∈ l ↔ a' ∈ l) := suffices ∀ {a a'}, a ~ a' → a ∈ l → a' ∈ l, from λ a a' e, ⟨this e, this e.symm⟩, λ a₁ a₂ e₁ ⟨a₃, m₃, e₂⟩, ⟨_, m₃, e₁.symm.trans e₂⟩ theorem mem_of_subset {a} {l₁ l₂ : lists' α tt} (s : l₁ ⊆ l₂) : a ∈ l₁ → a ∈ l₂ | ⟨a', m, e⟩ := (mem_equiv_left e).2 (mem_of_subset' s m) theorem subset.trans {l₁ l₂ l₃ : lists' α tt} (h₁ : l₁ ⊆ l₂) (h₂ : l₂ ⊆ l₃) : l₁ ⊆ l₃ := subset_def.2 $ λ a₁ m₁, mem_of_subset h₂ $ mem_of_subset' h₁ m₁ end lists' def finsets (α : Type*) := quotient (@lists.setoid α) namespace finsets instance : has_emptyc (finsets α) := ⟨⟦lists.of' lists'.nil⟧⟩ instance : inhabited (finsets α) := ⟨∅⟩ instance [decidable_eq α] : decidable_eq (finsets α) := by unfold finsets; apply_instance end finsets
712f5cc737380edb6acb82fb0cc7dc433314dedb
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/adjunction/opposites_auto.lean
0a3292717529ec3438f2a3535a130a6007042671
[]
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,257
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta, Thomas Read -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.adjunction.basic import Mathlib.category_theory.yoneda import Mathlib.category_theory.opposites import Mathlib.PostPort universes u₁ u₂ v₁ v₂ namespace Mathlib /-! # Opposite adjunctions This file contains constructions to relate adjunctions of functors to adjunctions of their opposites. These constructions are used to show uniqueness of adjoints (up to natural isomorphism). ## Tags adjunction, opposite, uniqueness -/ namespace adjunction /-- If `G.op` is adjoint to `F.op` then `F` is adjoint to `G`. -/ def adjoint_of_op_adjoint_op {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] (F : C ⥤ D) (G : D ⥤ C) (h : category_theory.functor.op G ⊣ category_theory.functor.op F) : F ⊣ G := category_theory.adjunction.mk_of_hom_equiv (category_theory.adjunction.core_hom_equiv.mk fun (X : C) (Y : D) => equiv.trans (equiv.symm (equiv.trans (category_theory.adjunction.hom_equiv h (opposite.op Y) (opposite.op X)) (category_theory.op_equiv (opposite.op Y) (category_theory.functor.obj (category_theory.functor.op F) (opposite.op X))))) (category_theory.op_equiv (category_theory.functor.obj (category_theory.functor.op G) (opposite.op Y)) (opposite.op X))) /-- If `G` is adjoint to `F.op` then `F` is adjoint to `G.unop`. -/ def adjoint_unop_of_adjoint_op {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] (F : C ⥤ D) (G : Dᵒᵖ ⥤ (Cᵒᵖ)) (h : G ⊣ category_theory.functor.op F) : F ⊣ category_theory.functor.unop G := adjoint_of_op_adjoint_op F (category_theory.functor.unop G) (category_theory.adjunction.of_nat_iso_left h (category_theory.iso.symm (category_theory.functor.op_unop_iso G))) /-- If `G.op` is adjoint to `F` then `F.unop` is adjoint to `G`. -/ def unop_adjoint_of_op_adjoint {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] (F : Cᵒᵖ ⥤ (Dᵒᵖ)) (G : D ⥤ C) (h : category_theory.functor.op G ⊣ F) : category_theory.functor.unop F ⊣ G := adjoint_of_op_adjoint_op (category_theory.functor.unop F) G (category_theory.adjunction.of_nat_iso_right h (category_theory.iso.symm (category_theory.functor.op_unop_iso F))) /-- If `G` is adjoint to `F` then `F.unop` is adjoint to `G.unop`. -/ def unop_adjoint_unop_of_adjoint {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] (F : Cᵒᵖ ⥤ (Dᵒᵖ)) (G : Dᵒᵖ ⥤ (Cᵒᵖ)) (h : G ⊣ F) : category_theory.functor.unop F ⊣ category_theory.functor.unop G := adjoint_unop_of_adjoint_op (category_theory.functor.unop F) G (category_theory.adjunction.of_nat_iso_right h (category_theory.iso.symm (category_theory.functor.op_unop_iso F))) /-- If `G` is adjoint to `F` then `F.op` is adjoint to `G.op`. -/ def op_adjoint_op_of_adjoint {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] (F : C ⥤ D) (G : D ⥤ C) (h : G ⊣ F) : category_theory.functor.op F ⊣ category_theory.functor.op G := category_theory.adjunction.mk_of_hom_equiv (category_theory.adjunction.core_hom_equiv.mk fun (X : Cᵒᵖ) (Y : Dᵒᵖ) => equiv.trans (category_theory.op_equiv (category_theory.functor.obj (category_theory.functor.op F) X) Y) (equiv.trans (equiv.symm (category_theory.adjunction.hom_equiv h (opposite.unop Y) (opposite.unop X))) (equiv.symm (category_theory.op_equiv X (opposite.op (category_theory.functor.obj G (opposite.unop Y))))))) /-- If `G` is adjoint to `F.unop` then `F` is adjoint to `G.op`. -/ def adjoint_op_of_adjoint_unop {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] (F : Cᵒᵖ ⥤ (Dᵒᵖ)) (G : D ⥤ C) (h : G ⊣ category_theory.functor.unop F) : F ⊣ category_theory.functor.op G := category_theory.adjunction.of_nat_iso_left (op_adjoint_op_of_adjoint (category_theory.functor.unop F) G h) (category_theory.functor.op_unop_iso F) /-- If `G.unop` is adjoint to `F` then `F.op` is adjoint to `G`. -/ def op_adjoint_of_unop_adjoint {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] (F : C ⥤ D) (G : Dᵒᵖ ⥤ (Cᵒᵖ)) (h : category_theory.functor.unop G ⊣ F) : category_theory.functor.op F ⊣ G := category_theory.adjunction.of_nat_iso_right (op_adjoint_op_of_adjoint F (category_theory.functor.unop G) h) (category_theory.functor.op_unop_iso G) /-- If `G.unop` is adjoint to `F.unop` then `F` is adjoint to `G`. -/ def adjoint_of_unop_adjoint_unop {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] (F : Cᵒᵖ ⥤ (Dᵒᵖ)) (G : Dᵒᵖ ⥤ (Cᵒᵖ)) (h : category_theory.functor.unop G ⊣ category_theory.functor.unop F) : F ⊣ G := category_theory.adjunction.of_nat_iso_right (adjoint_op_of_adjoint_unop F (category_theory.functor.unop G) h) (category_theory.functor.op_unop_iso G) /-- If `F` and `F'` are both adjoint to `G`, there is a natural isomorphism `F.op ⋙ coyoneda ≅ F'.op ⋙ coyoneda`. We use this in combination with `fully_faithful_cancel_right` to show left adjoints are unique. -/ def left_adjoints_coyoneda_equiv {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] {F : C ⥤ D} {F' : C ⥤ D} {G : D ⥤ C} (adj1 : F ⊣ G) (adj2 : F' ⊣ G) : category_theory.functor.op F ⋙ category_theory.coyoneda ≅ category_theory.functor.op F' ⋙ category_theory.coyoneda := category_theory.nat_iso.of_components (fun (X : Cᵒᵖ) => category_theory.nat_iso.of_components (fun (Y : D) => equiv.to_iso (equiv.trans (category_theory.adjunction.hom_equiv adj1 (opposite.unop X) Y) (equiv.symm (category_theory.adjunction.hom_equiv adj2 (opposite.unop X) Y)))) sorry) sorry /-- If `F` and `F'` are both left adjoint to `G`, then they are naturally isomorphic. -/ def left_adjoint_uniq {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] {F : C ⥤ D} {F' : C ⥤ D} {G : D ⥤ C} (adj1 : F ⊣ G) (adj2 : F' ⊣ G) : F ≅ F' := category_theory.nat_iso.remove_op (category_theory.fully_faithful_cancel_right category_theory.coyoneda (left_adjoints_coyoneda_equiv adj2 adj1)) /-- If `G` and `G'` are both right adjoint to `F`, then they are naturally isomorphic. -/ def right_adjoint_uniq {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] {F : C ⥤ D} {G : D ⥤ C} {G' : D ⥤ C} (adj1 : F ⊣ G) (adj2 : F ⊣ G') : G ≅ G' := category_theory.nat_iso.remove_op (left_adjoint_uniq (op_adjoint_op_of_adjoint G' F adj2) (op_adjoint_op_of_adjoint G F adj1)) /-- Given two adjunctions, if the left adjoints are naturally isomorphic, then so are the right adjoints. -/ def nat_iso_of_left_adjoint_nat_iso {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] {F : C ⥤ D} {F' : C ⥤ D} {G : D ⥤ C} {G' : D ⥤ C} (adj1 : F ⊣ G) (adj2 : F' ⊣ G') (l : F ≅ F') : G ≅ G' := right_adjoint_uniq adj1 (category_theory.adjunction.of_nat_iso_left adj2 (category_theory.iso.symm l)) /-- Given two adjunctions, if the right adjoints are naturally isomorphic, then so are the left adjoints. -/ def nat_iso_of_right_adjoint_nat_iso {C : Type u₁} [category_theory.category C] {D : Type u₂} [category_theory.category D] {F : C ⥤ D} {F' : C ⥤ D} {G : D ⥤ C} {G' : D ⥤ C} (adj1 : F ⊣ G) (adj2 : F' ⊣ G') (r : G ≅ G') : F ≅ F' := left_adjoint_uniq adj1 (category_theory.adjunction.of_nat_iso_right adj2 (category_theory.iso.symm r)) end Mathlib
fb012b52b82d72d703b9563a492ba72b76637f2c
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/test/simp_rw.lean
3246067adb0f1b7c96a65204327bb6357c6c18ad
[ "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
1,451
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen A set of test cases for the `simp_rw` tactic. -/ import tactic.simp_rw import data.set.basic -- `simp_rw` can perform rewrites under binders: example : (λ (x y : ℕ), x + y) = (λ x y, y + x) := by simp_rw [add_comm] -- `simp_rw` performs rewrites in the given order (`simp` fails on this example): example {α β : Type} {f : α → β} {t : set β} : (∀ s, f '' s ⊆ t) = ∀ s : set α, ∀ x ∈ s, x ∈ f ⁻¹' t := by simp_rw [set.image_subset_iff, set.subset_def] -- `simp_rw` applies rewrite rules multiple times: example (a b c d : ℕ) : a + (b + (c + d)) = ((d + c) + b) + a := by simp_rw [add_comm] -- `simp_rw` can also rewrite in assumptions: example (p : ℕ → Prop) (a b : ℕ) (h : p (a + b)) : p (b + a) := by {simp_rw [add_comm a b] at h, exact h} -- or explicitly rewrite at the goal: example (p : ℕ → Prop) (a b : ℕ) (h : p (a + b)) : p (b + a) := by {simp_rw [add_comm b a] at ⊢, exact h} -- or at multiple assumptions: example (p : ℕ → Prop) (a b : ℕ) (h₁ : p (b + a) → p (a + b)) (h₂ : p (a + b)) : p (b + a) := by {simp_rw [add_comm a b] at h₁ h₂, exact h₁ h₂} -- or everywhere: example (p : ℕ → Prop) (a b : ℕ) (h₁ : p (b + a) → p (a + b)) (h₂ : p (a + b)) : p (a + b) := by {simp_rw [add_comm a b] at *, exact h₁ h₂}
8decbf1f84879024a76f4249dcc2c5a333bdbfb2
e898bfefd5cb60a60220830c5eba68cab8d02c79
/uexp/src/uexp/cosette_tactics.lean
6c18516177b2753b7560deb7349c23c739f6ea4d
[ "BSD-2-Clause" ]
permissive
kkpapa/Cosette
9ed09e2dc4c1ecdef815c30b5501f64a7383a2ce
fda8fdbbf0de6c1be9b4104b87bbb06cede46329
refs/heads/master
1,584,573,128,049
1,526,370,422,000
1,526,370,422,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,198
lean
import system.io import .u_semiring import .cosette_lemmas open nat io open list io section cosette_tactics def list.remove_first_of_each {α : Type} [decidable_eq α] : list α → list α → list α | xs [] := xs | [] ys := [] | (x::xs) (y::ys) := if x = y then list.remove_first_of_each xs ys else x :: list.remove_first_of_each xs (y::ys) def list.swap_ith_forward {α : Type} {f : Type → Type} [alternative f] : nat → list α → f (list α) | 0 (x::y::zs) := pure $ y :: x :: zs | (nat.succ n) (x::xs) := list.cons x <$> list.swap_ith_forward n xs | _ _ := failure lemma swap_gives_result_if_index_in_range {α : Type} : ∀ (ls : list α) i, i + 2 < list.length ls → { ls' : list α // list.swap_ith_forward i ls = some ls' } := begin intros ls i h, revert ls, induction i with j ih; intros; cases ls with x ys, { exfalso, cases h }, { cases ys with y zs, { exfalso, cases h, cases h_a }, { existsi (y :: x :: zs), refl } }, { exfalso, cases h }, { cases ih ys _ with ys' h', existsi x :: ys', unfold list.swap_ith_forward, rw h', refl, apply nat.lt_of_succ_lt_succ, assumption } end meta def expr.swap_free_vars (i : nat) (j : nat) : expr → expr | (expr.var n) := if n = i then expr.var j else if n = j then expr.var i else expr.var n | (expr.app f x) := expr.app (expr.swap_free_vars f) (expr.swap_free_vars x) | (expr.lam n bi ty body) := let ty' := expr.swap_free_vars ty, body' := expr.swap_free_vars body in expr.lam n bi ty' body' | (expr.pi n bi ty body) := let ty' := expr.swap_free_vars ty, body' := expr.swap_free_vars body in expr.pi n bi ty' body' | (expr.elet n ty val body) := let ty' := expr.swap_free_vars ty, val' := expr.swap_free_vars val, body' := expr.swap_free_vars body in expr.elet n ty' val' body' | ex := ex -- substitute variable and also lift de bruijn index meta def expr.subst_var (target: expr) : expr → expr := λ e, if e = target then (expr.var 0) else match e with | (expr.var n) := expr.var (n+1) | (expr.app f x) := expr.app (expr.subst_var f) (expr.subst_var x) | (expr.lam n bi ty body) := expr.lam n bi (expr.subst_var ty) (expr.subst_var body) | (expr.pi n bi ty body) := expr.pi n bi (expr.subst_var ty) (expr.subst_var body) | (expr.elet n ty val body) := let ty' := expr.subst_var ty, val' := expr.subst_var val, body' := expr.subst_var body in expr.elet n ty' val' body' | ex := ex end -- substitute variable without lift de bruijn index meta def expr.subst_var' (target: expr) (replacement: expr) : expr → expr := λ e, if e = target then replacement else match e with | (expr.var n) := expr.var n | (expr.app f x) := expr.app (expr.subst_var' f) (expr.subst_var' x) | (expr.lam n bi ty body) := expr.lam n bi (expr.subst_var' ty) (expr.subst_var' body) | (expr.pi n bi ty body) := expr.pi n bi (expr.subst_var' ty) (expr.subst_var' body) | (expr.elet n ty val body) := let ty' := expr.subst_var' ty, val' := expr.subst_var' val, body' := expr.subst_var' body in expr.elet n ty' val' body' | ex := ex end def move_nth_to_kth {α : Type} {m : Type → Type} [alternative m] [monad m] (final initial : ℕ) (ls : list α) : m (list α) := list.append (ls.take initial) <$> nat.repeat (λ n (ls' : m (list α)), ls' >>= list.swap_ith_forward (final - n - 1)) (final - initial) (return $ ls.drop initial) universes u v w def congr_arg₂ {α : Sort u} {β : Sort v} {γ : Sort w} {a₁ a₂ : α} {b₁ b₂ : β} (f : α → β → γ) : a₁ = a₂ → b₁ = b₂ → f a₁ b₁ = f a₂ b₂ := begin intros, apply congr, { apply congr_arg, assumption }, { assumption } end -- repeat tacitic t exactly n times meta def repeat_n (n: nat) (t: tactic unit) : tactic unit := nat.repeat (λ n next, t >> next) n $ return () -- check if an expr is in the list meta def expr_in : expr → list expr → bool := (λ e l, match l with | [] := ff | (h :: t) := if h=e then tt else (expr_in e t) end) meta def get_eq_sides : tactic (expr × expr) := tactic.target >>= λ e, match e with | `(%%a = %%b) := return (a, b) | _ := tactic.failed end meta def get_lhs : tactic expr := prod.fst <$> get_eq_sides meta def get_rhs : tactic expr := prod.snd <$> get_eq_sides meta def solved_or_continue (next: tactic unit) : tactic unit := do tactic.try tactic.reflexivity, ok ← list.empty <$> tactic.get_goals, if ok then return () else next meta def print_goals : tactic unit := do goals ← tactic.get_goals, tactic.trace goals meta def repeat_or_sol (f: ℕ → tactic unit) : ℕ → tactic unit | 0 := (f 0) | (nat.succ n) := do repeat_or_sol n, ok ← list.empty <$> tactic.get_goals, if ok then return () else (f n) meta def beta_reduction (e: expr): tactic unit := do reduced ← tactic.head_beta e, n ← tactic.mk_fresh_name, tactic.to_expr ``(%%e=%%reduced) >>= tactic.assert n, tactic.reflexivity, eq_lemma ← tactic.resolve_name n >>= tactic.to_expr, tactic.rewrite_target eq_lemma, tactic.clear eq_lemma -- this assume that expr is a right associative product private meta def ra_product_to_repr' : expr → list expr | `(%%a * %%b) := a :: ra_product_to_repr' b | e := [e] -- this assume that expr is a right associative product meta def ra_product_to_repr (e: expr) : tactic (list expr) := return $ ra_product_to_repr' e meta def repr_to_product : list expr → tactic expr | [x] := return x | (h::t) := do te ← repr_to_product t, tactic.to_expr ``(%%h * %%te) | [] := tactic.to_expr ``(usr.one) -- this doesn't assume any form of the product expr private meta def product_to_repr' : expr → list expr | `(%%a * %%b) := (product_to_repr' a) ++ (product_to_repr' b) | x := [x] meta def product_to_repr (e: expr) : tactic (list expr) := return $ product_to_repr' e meta def is_ueq : expr → bool | `(_ ≃ _) := tt | _ := ff meta def get_ueqs (l: list expr) : list expr := list.filter (λ e, is_ueq e = tt) l meta def get_non_ueqs (l: list expr) : list expr := list.filter (λ e, is_ueq e = ff) l meta def get_lhs_expr1 : tactic expr := tactic.target >>= λ e, match e with | `(%%a * _ * _ = _) := return a | _ := tactic.failed end -- assuming lhs is in the form of a*b*c meta def get_lhs_repr1 : tactic (list expr) := tactic.target >>= λ e, match e with | `(%%a * _ * _ = %%_) := ra_product_to_repr a | _ := tactic.failed end meta def get_lhs_expr2 : tactic expr := tactic.target >>= λ e, match e with | `(_ * %%a * _ = _) := return a | _ := tactic.failed end -- assuming lhs is in the form of a*b*c meta def get_lhs_repr2 : tactic (list expr) := tactic.target >>= λ e, match e with | `(_ * %%a * _ = _) := ra_product_to_repr a | _ := tactic.failed end -- assuming lhs is in the form of a*b*c meta def get_lhs_repr3 : tactic (list expr) := tactic.target >>= λ e, match e with | `(_ * _ * %%a = _) := ra_product_to_repr a | _ := tactic.failed end meta def get_lhs_expr3 : tactic expr := tactic.target >>= λ e, match e with | `(_ * _ * %%a = _) := return a | _ := tactic.failed end -- swap i-th element in a product forward meta def swap_element_forward (i: nat) (l: list expr) : tactic unit := do swapped_list ← list.swap_ith_forward i l, origin_expr ← repr_to_product l, swapped_expr ← repr_to_product swapped_list, eq_lemma ← tactic.to_expr ``(%%origin_expr = %%swapped_expr), eq_lemma_name ← tactic.mk_fresh_name, tactic.assert eq_lemma_name eq_lemma, repeat_n i $ (tactic.to_expr ``(congr_arg (has_mul.mul _)) >>= tactic.apply >> return ()), tactic.applyc `prod_symm_assoc <|> tactic.applyc `mul_comm, eq_lemma ← tactic.resolve_name eq_lemma_name >>= tactic.to_expr, tactic.rewrite_target eq_lemma, tactic.clear eq_lemma /- suppose i > j -/ meta def forward_i_to_j (target: tactic expr) (i j: nat): tactic unit := let loop : nat → tactic unit → tactic unit := λ iter_num next_iter, do next_iter, ex ← target, repr ← product_to_repr ex, swap_element_forward (i - iter_num -1) repr in nat.repeat loop (i - j) $ return () meta def forward_i_to_j_lhs (i : nat) (j: nat) : tactic unit := forward_i_to_j get_lhs_expr1 i j /- the first nat is the size of body, the second nat is iteration -/ meta def repeat_if_progress (f: ℕ → ℕ → (tactic ℕ)) : ℕ → ℕ → (tactic ℕ) | (s) 0 := return 0 | (s) (nat.succ n) := do s' ← f s (s - n - 1), repeat_if_progress s' n meta structure usr_sigma_repr := (var_schemas : list expr) (body : expr) meta instance sigma_repr_format : has_to_format usr_sigma_repr := ⟨λ sig, format.cbrace $ "var_schemas := " ++ to_fmt sig.var_schemas ++ "," ++ " body := " ++ to_fmt sig.body⟩ meta def sigma_expr_to_sigma_repr : expr → usr_sigma_repr | `(usr.sig (λ t : Tuple %%s, %%a)) := match sigma_expr_to_sigma_repr a with | ⟨var_schemas, inner⟩ := ⟨s :: var_schemas, inner⟩ end | e := ⟨[], e⟩ -- This needs to be a tactic so we can resolve `Tuple and `usr.sig meta def sigma_repr_to_sigma_expr : usr_sigma_repr → tactic expr | ⟨[], body⟩ := return body | ⟨t::ts, body⟩ := do body' ← sigma_repr_to_sigma_expr ⟨ts, body⟩, n ← tactic.get_unused_name `x, ty ← tactic.to_expr ``(Tuple %%t), let lam : expr := expr.lam n binder_info.default ty body', tactic.to_expr ``(usr.sig %%lam) meta def get_lhs_sigma_repr : tactic usr_sigma_repr := tactic.target >>= λ e, match e with | `(%%a = %%b) := return $ sigma_expr_to_sigma_repr a | _ := tactic.failed end meta def sigma_repr_to_closed_body_expr : usr_sigma_repr → tactic (expr × list name) | ⟨schemas, body⟩ := do lconsts ← list.mfoldr (λ (t : expr) (lconsts : list (expr × name)), do n ← tactic.mk_fresh_name, ty ← tactic.to_expr ``(Tuple %%t), let local_const := expr.local_const n n binder_info.default ty, return $ (local_const, n) :: lconsts) [] $ list.reverse schemas, let ⟨lconsts', names⟩ := lconsts.unzip, return (expr.instantiate_vars body lconsts', names) meta def sigma_repr_to_closed_body_expr' : usr_sigma_repr → tactic (expr × list (expr × name)) | ⟨schemas, body⟩ := do lconsts ← list.mfoldr (λ (t : expr) (lconsts : list (expr × name)), do n ← tactic.mk_fresh_name, ty ← tactic.to_expr ``(Tuple %%t), let local_const := expr.local_const n n binder_info.default ty, return $ (local_const, n) :: lconsts) [] $ list.reverse schemas, let ⟨lconsts', names⟩ := lconsts.unzip, return (expr.instantiate_vars body lconsts', lconsts) private meta def get_types_of_local_consts (ns : list name) : expr → list (nat × expr) | (expr.app f x) := list.union (get_types_of_local_consts f) $ get_types_of_local_consts x | (expr.lam n bi ty body) := list.union (get_types_of_local_consts ty) $ get_types_of_local_consts body | (expr.pi n bi ty body) := list.union (get_types_of_local_consts ty) $ get_types_of_local_consts body | (expr.elet n ty val body) := list.union (get_types_of_local_consts ty) $ list.union (get_types_of_local_consts val) $ get_types_of_local_consts body | (expr.local_const n _ _ ty) := let idx : option nat := list.rec none (λ n' ns res, if n = n' then some 0 else nat.succ <$> res) ns in match idx with | some i := [(i, ty)] | none := [] end | _ := [] meta def closed_sigma_repr_to_sigma_repr (body : expr) (names : list name) : tactic usr_sigma_repr := do schemas ← monad.sequence $ list.map (λ p : nat × expr, match p with | (_, `(Tuple %%s)) := return s | _ := tactic.failed end) $ list.qsort (λ x y : nat × expr, x.fst ≥ y.fst) $ get_types_of_local_consts names body, return $ usr_sigma_repr.mk schemas $ expr.abstract_locals body $ list.reverse names meta def forward_i_to_j_in_sig (target: tactic expr) (i: nat) (j: nat) : tactic unit := do ex ← target, lr ← return $ sigma_expr_to_sigma_repr ex, match lr with |⟨xs, body⟩ := do le ← product_to_repr body, le' ← move_nth_to_kth i j le, body' ← repr_to_product le', origin ← target, new ← sigma_repr_to_sigma_expr ⟨xs, body'⟩, eq_lemma ← tactic.to_expr ``(%%origin = %%new), lemma_name ← tactic.mk_fresh_name, tactic.assert lemma_name eq_lemma, repeat_n (list.length xs) $ tactic.applyc `congr_arg >> tactic.funext, tactic.ac_refl, eq_lemma_name ← tactic.resolve_name lemma_name >>= tactic.to_expr, tactic.rewrite_target eq_lemma_name, tactic.clear eq_lemma_name end meta def forward_i_to_j_in_sig_lhs (i: nat) (j: nat) : tactic unit := forward_i_to_j_in_sig get_lhs i j meta def sig_body_size (target: tactic expr) : tactic ℕ := do ex ← target, lr ← return $ sigma_expr_to_sigma_repr ex, match lr with |⟨xs, body⟩ := do le ← product_to_repr body, return $ list.length le end meta def split_pairs : tactic unit := do `[repeat {rw eq_pair <|> rw eq_pair'}, try {dsimp}] meta def get_table_and_column (e : expr) : option (expr × expr) := let fn := expr.get_app_fn e in do match fn with | (expr.const n _) := if n = `isKey then match list.reverse $ expr.get_app_args e with | (rel::col::_) := some (rel, col) | _ := none end else none | _ := none end meta structure key_constraint := (name : expr) (table : expr) (column : expr) meta instance key_constraint_to_format : has_to_format key_constraint := ⟨λ kc, format.cbrace $ "name := " ++ to_fmt kc.name ++ "," ++ " table := " ++ to_fmt kc.table ++ "," ++ " column := " ++ to_fmt kc.column⟩ meta def find_keys : tactic (list key_constraint) := do hyps ← tactic.local_context, hyp_types ← monad.mapm tactic.infer_type hyps, return $ list.filter_map (λ (name_and_type : expr × expr), match name_and_type with | (key_name, key_type) := match get_table_and_column key_type with | some (rel, col) := some $ key_constraint.mk key_name rel col | none := none end end) $ list.zip hyps hyp_types meta def unfold_all_denotations := `[ repeat { unfold denoteSQL <|> unfold denotePred <|> unfold denoteProj <|> unfold denoteExpr <|> unfold groupBy <|> unfold combineGroupByProj <|> unfold pair <|> unfold plainGroupByProj <|> unfold aggregatorGroupByProj <|> unfold semiJoin <|> unfold semiJoin1}] meta def remove_all_unit : tactic unit := `[repeat {rw time_one <|> rw time_one'}, try {refl}] meta def swap_ith_sigma_forward (i : nat) : usr_sigma_repr → tactic unit | ⟨xs, body⟩ := do swapped_schemas ← list.swap_ith_forward i xs, -- We have to subtract because the de Bruijn indices are inside-out let num_free_vars := list.length xs, let swapped_body := expr.swap_free_vars (num_free_vars - 1 - i) (num_free_vars - 1 - nat.succ i) body, let swapped_repr := usr_sigma_repr.mk swapped_schemas swapped_body, normal_expr ← sigma_repr_to_sigma_expr ⟨xs, body⟩, swapped_expr ← sigma_repr_to_sigma_expr swapped_repr, equality_lemma ← tactic.to_expr ``(%%normal_expr = %%swapped_expr), eq_lemma_name ← tactic.mk_fresh_name, tactic.assert eq_lemma_name equality_lemma, repeat_n i $ tactic.applyc `congr_arg >> tactic.funext, tactic.applyc `sig_commute, eq_lemma ← tactic.resolve_name eq_lemma_name >>= tactic.to_expr, tactic.rewrite_target eq_lemma, tactic.clear eq_lemma meta def move_sig_once (target: tactic expr) (i: nat) : tactic unit := do ex ← target, lr ← return $ sigma_expr_to_sigma_repr ex, swap_ith_sigma_forward i lr meta def move_sig_to_front (target: tactic expr) (i : nat) : tactic unit := let loop : ℕ → tactic unit → tactic unit := λ iter_num next_iter, do ex ← target, lr ← return $ sigma_expr_to_sigma_repr ex, swap_ith_sigma_forward iter_num lr, next_iter in nat.repeat loop i $ return () --move back i to j meta def move_sig_back (target: tactic expr) (i: nat) (j: nat) := let loop: nat → tactic unit → tactic unit := λ num next, do next, move_sig_once target (i+num) in nat.repeat loop (j-i) $ return () -- a single step removal meta def remove_sig_step (target: tactic expr): tactic unit := do ex ← target, lr ← return $ sigma_expr_to_sigma_repr ex, match lr with | ⟨xs, body⟩ := do le ← ra_product_to_repr body, match list.head le with | `(%%a ≃ %%b) := match a, b with | (expr.var n), e := do let l := (list.length xs), move_sig_back target (l - 1 - n) (l - 1), ex' ← target, lr' ← return $ sigma_expr_to_sigma_repr ex', match lr' with | ⟨xs', body'⟩ := do match body' with | `((%%c ≃ %%d) * %%f) := do let sub_expr := expr.subst_var' c d f, let new_body := expr.lower_vars sub_expr 1 1, old_expr ← sigma_repr_to_sigma_expr lr', new_expr ← sigma_repr_to_sigma_expr ⟨list.take (l-1) xs', new_body⟩, eq_lemma ← tactic.to_expr ``(%%old_expr = %%new_expr), lemma_name ← tactic.mk_fresh_name, tactic.assert lemma_name eq_lemma, repeat_n (l-1) $ tactic.applyc `congr_arg >> tactic.funext, tactic.applyc `sig_eq_subst_r, eq_lemma_name ← tactic.resolve_name lemma_name >>= tactic.to_expr, tactic.rewrite_target eq_lemma_name, tactic.clear eq_lemma_name | _ := tactic.fail "fail in removal step" end end | e, (expr.var n) := do let l := (list.length xs), move_sig_back target (l - 1 - n) (l - 1), ex' ← target, lr' ← return $ sigma_expr_to_sigma_repr ex', match lr' with | ⟨xs', body'⟩ := do match body' with | `((%%c ≃ %%d) * %%f) := do let sub_expr := expr.subst_var' d c f, let new_body := expr.lower_vars sub_expr 1 1, old_expr ← sigma_repr_to_sigma_expr lr', new_expr ← sigma_repr_to_sigma_expr ⟨list.take (l-1) xs', new_body⟩, eq_lemma ← tactic.to_expr ``(%%old_expr = %%new_expr), lemma_name ← tactic.mk_fresh_name, tactic.assert lemma_name eq_lemma, repeat_n (l-1) $ tactic.applyc `congr_arg >> tactic.funext, tactic.applyc `sig_eq_subst_l, eq_lemma_name ← tactic.resolve_name lemma_name >>= tactic.to_expr, tactic.rewrite_target eq_lemma_name, tactic.clear eq_lemma_name | _ := tactic.fail "fail in removal step" end end | _, _ := return () end | _ := return () end end meta def split_p (ex : expr) : tactic (list expr) := match ex with | `(%%a ≃ %%b) := match a, b with | `((%%a1, %%a2)) , `((%%b1, %%b2)) := do x1 ← tactic.to_expr ``((%%a).1 ≃ (%%b).1), x2 ← tactic.to_expr ``((%%a).2 ≃ (%%b).2), return [x1, x2] | _, _ := return [ex] end | x := return [x] end meta def split_l (ex : expr) : tactic (list expr) := match ex with | `(%%a ≃ %%b) := match a, b with | _ , `((%%c, %%d)) := do /- ty ← infer_type a, let args := expr.get_app_args ty, (r1, r2) ← match args.nth 0 with | some `(%%r1 ++ %%r2) := return (r1, r2) | _ := failure end, trace (r1, r2), ty2 ← to_expr ``((@cast %%ty (Tuple %%r1 × Tuple %%r2) (by tactic.reflexivity) (%%a)).1), -/ x1 ← tactic.to_expr ``((%%a).1 ≃ %%c), x2 ← tactic.to_expr ``((%%a).2 ≃ %%d), return [x1, x2] | _, _ := return [ex] end | x := return [x] end meta def split_r (ex : expr) : tactic (list expr) := match ex with | `(%%a ≃ %%b) := match a, b with | `((%%c, %%d)), _ := do ty ← tactic.infer_type b, let args := expr.get_app_args ty, r ← match args.nth 0 with | some `(%%r ++ _) := return r | _ := failure end, ty2 ← tactic.to_expr ``((@cast %%ty (Tuple %%r × Tuple %%r) (by tactic.reflexivity) (%%b)).1), x1 ← tactic.to_expr ``(%%c ≃ (%%b).1), x2 ← tactic.to_expr ``(%%d ≃ (%%b).2), return [x1, x2] | _, _ := return [ex] end | x := return [x] end meta def flatmap_in_repr (f: expr → tactic (list expr)): list expr → tactic (list expr) | [x] := f x | (h::t) := do h' ← f h, t' ← flatmap_in_repr t, return (h' ++ t') | [] := return [] meta def split_pair_in_repr (r: list expr) : tactic (list expr) := do r1 ← flatmap_in_repr split_p r, s' ← flatmap_in_repr split_l r1, r ← flatmap_in_repr split_r s', return r meta def normalize_step (n: nat) : tactic unit := do repeat_n n $ tactic.applyc `congr_arg >> tactic.funext, split_pairs -- normalize body of a sigma meta def normalize_sig_body (target: tactic expr) : tactic unit := do ex ← target, lr ← return $ sigma_expr_to_sigma_repr ex, lr_body_closed ← sigma_repr_to_closed_body_expr lr, match lr_body_closed with | ⟨body, names⟩ := do le ← product_to_repr body, s1 ← split_pair_in_repr le, body' ← repr_to_product s1, origin ← target, let abstracted := expr.abstract_locals body' (list.reverse names), new ← sigma_repr_to_sigma_expr ⟨lr.var_schemas, abstracted⟩, eq_lemma ← tactic.to_expr ``(%%origin = %%new), lemma_name ← tactic.mk_fresh_name, tactic.assert lemma_name eq_lemma, tactic.focus1 $ normalize_step lr.var_schemas.length, tactic.try tactic.ac_refl, eq_lemma_name ← tactic.resolve_name lemma_name >>= tactic.to_expr, tactic.rewrite_target eq_lemma_name, tactic.clear eq_lemma_name end meta def remove_dup_sigs (target: tactic expr) : tactic unit := do -- this is a workround, this unnest 3 levels of pair -- repeat_n 3 $ normalize_sig_body_lhs >> try dsimp_target, repeat_n 3 $ normalize_sig_body target, s ← sig_body_size target, final ← let loop : ℕ → ℕ → (tactic ℕ) := λ s n, do forward_i_to_j_in_sig target n 0, remove_sig_step target, sig_body_size target in repeat_if_progress loop s s, return () meta def expr.size : expr → ℕ | (expr.var n) := 1 | (expr.app f x) := (expr.size f) + (expr.size x) | (expr.lam n bi ty body) := (expr.size body) | (expr.pi n bi ty body) := (expr.size body) | (expr.elet n ty val body) := (expr.size body) | ex := 1 meta def print_size : tactic unit := do l ← get_lhs, r ← get_rhs, tactic.trace (expr.size l + expr.size r) end cosette_tactics
9f809acc3d3cdf25083c6badf8a4dcee09a01690
ff5230333a701471f46c57e8c115a073ebaaa448
/library/init/meta/name.lean
6cce797df84efcad982481dab58044a1bdc01404
[ "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
3,819
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.ordering.basic init.coe init.data.to_string /-- Reflect a C++ name object. The VM replaces it with the C++ implementation. -/ inductive name | anonymous : name | mk_string : string → name → name | mk_numeral : unsigned → name → name /-- Gadget for automatic parameter support. This is similar to the opt_param gadget, but it uses the tactic declaration names tac_name to synthesize the argument. Like opt_param, this gadget only affects elaboration. For example, the tactic will *not* be invoked during type class resolution. -/ @[reducible] def {u} auto_param (α : Sort u) (tac_name : name) : Sort u := α @[simp] lemma {u} auto_param_eq (α : Sort u) (n : name) : auto_param α n = α := rfl instance : inhabited name := ⟨name.anonymous⟩ def mk_str_name (n : name) (s : string) : name := name.mk_string s n def mk_num_name (n : name) (v : nat) : name := name.mk_numeral (unsigned.of_nat' v) n def mk_simple_name (s : string) : name := mk_str_name name.anonymous s instance string_to_name : has_coe string name := ⟨mk_simple_name⟩ infix ` <.> `:65 := mk_str_name open name def name.get_prefix : name → name | anonymous := anonymous | (mk_string s p) := p | (mk_numeral s p) := p def name.update_prefix : name → name → name | anonymous new_p := anonymous | (mk_string s p) new_p := mk_string s new_p | (mk_numeral s p) new_p := mk_numeral s new_p /- The (decidable_eq string) has not been defined yet. So, we disable the use of if-then-else when compiling the following definitions. -/ set_option eqn_compiler.ite false def name.to_string_with_sep (sep : string) : name → string | anonymous := "[anonymous]" | (mk_string s anonymous) := s | (mk_numeral v anonymous) := repr v | (mk_string s n) := name.to_string_with_sep n ++ sep ++ s | (mk_numeral v n) := name.to_string_with_sep n ++ sep ++ repr v private def name.components' : name -> list name | anonymous := [] | (mk_string s n) := mk_string s anonymous :: name.components' n | (mk_numeral v n) := mk_numeral v anonymous :: name.components' n def name.components (n : name) : list name := (name.components' n).reverse protected def name.to_string : name → string := name.to_string_with_sep "." instance : has_to_string name := ⟨name.to_string⟩ /- TODO(Leo): provide a definition in Lean. -/ meta constant name.has_decidable_eq : decidable_eq name /- Both cmp and lex_cmp are total orders, but lex_cmp implements a lexicographical order. -/ meta constant name.cmp : name → name → ordering meta constant name.lex_cmp : name → name → ordering meta constant name.append : name → name → name meta constant name.is_internal : name → bool protected meta def name.lt (a b : name) : Prop := name.cmp a b = ordering.lt meta instance : decidable_rel name.lt := λ a b, ordering.decidable_eq _ _ meta instance : has_lt name := ⟨name.lt⟩ attribute [instance] name.has_decidable_eq meta instance : has_append name := ⟨name.append⟩ /-- `name.append_after n i` return a name of the form n_i -/ meta constant name.append_after : name → nat → name meta def name.is_prefix_of : name → name → bool | p name.anonymous := ff | p n := if p = n then tt else name.is_prefix_of p n.get_prefix meta def name.replace_prefix : name → name → name → name | anonymous p p' := anonymous | (mk_string s c) p p' := if c = p then mk_string s p' else mk_string s (name.replace_prefix c p p') | (mk_numeral v c) p p' := if c = p then mk_numeral v p' else mk_numeral v (name.replace_prefix c p p')
e3b7d53b5f250185f69b32dfbb593c8c2b4fee1c
bb31430994044506fa42fd667e2d556327e18dfe
/src/algebraic_geometry/projective_spectrum/scheme.lean
3d28c47c871a3a41f52d27700cf58a8b1a5d778d
[ "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
22,466
lean
/- Copyright (c) 2022 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang -/ import algebraic_geometry.projective_spectrum.structure_sheaf import algebraic_geometry.Spec import ring_theory.graded_algebra.radical /-! # Proj as a scheme This file is to prove that `Proj` is a scheme. ## Notation * `Proj` : `Proj` as a locally ringed space * `Proj.T` : the underlying topological space of `Proj` * `Proj| U` : `Proj` restricted to some open set `U` * `Proj.T| U` : the underlying topological space of `Proj` restricted to open set `U` * `pbo f` : basic open set at `f` in `Proj` * `Spec` : `Spec` as a locally ringed space * `Spec.T` : the underlying topological space of `Spec` * `sbo g` : basic open set at `g` in `Spec` * `A⁰_x` : the degree zero part of localized ring `Aₓ` ## Implementation In `src/algebraic_geometry/projective_spectrum/structure_sheaf.lean`, we have given `Proj` a structure sheaf so that `Proj` is a locally ringed space. In this file we will prove that `Proj` equipped with this structure sheaf is a scheme. We achieve this by using an affine cover by basic open sets in `Proj`, more specifically: 1. We prove that `Proj` can be covered by basic open sets at homogeneous element of positive degree. 2. We prove that for any homogeneous element `f : A` of positive degree `m`, `Proj.T | (pbo f)` is homeomorphic to `Spec.T A⁰_f`: - forward direction `to_Spec`: for any `x : pbo f`, i.e. a relevant homogeneous prime ideal `x`, send it to `A⁰_f ∩ span {g / 1 | g ∈ x}` (see `Proj_iso_Spec_Top_component.to_Spec.carrier`). This ideal is prime, the proof is in `Proj_iso_Spec_Top_component.to_Spec.to_fun`. The fact that this function is continuous is found in `Proj_iso_Spec_Top_component.to_Spec` - backward direction `from_Spec`: for any `q : Spec A⁰_f`, we send it to `{a | ∀ i, aᵢᵐ/fⁱ ∈ q}`; we need this to be a homogeneous prime ideal that is relevant. * This is in fact an ideal, the proof can be found in `Proj_iso_Spec_Top_component.from_Spec.carrier.as_ideal`; * This ideal is also homogeneous, the proof can be found in `Proj_iso_Spec_Top_component.from_Spec.carrier.as_ideal.homogeneous`; * This ideal is relevant, the proof can be found in `Proj_iso_Spec_Top_component.from_Spec.carrier.relevant`; * This ideal is prime, the proof can be found in `Proj_iso_Spec_Top_component.from_Spec.carrier.prime`. Hence we have a well defined function `Spec.T A⁰_f → Proj.T | (pbo f)`, this function is called `Proj_iso_Spec_Top_component.from_Spec.to_fun`. But to prove the continuity of this function, we need to prove `from_Spec ∘ to_Spec` and `to_Spec ∘ from_Spec` are both identities (TBC). ## Main Definitions and Statements * `degree_zero_part`: the degree zero part of the localized ring `Aₓ` where `x` is a homogeneous element of degree `n` is the subring of elements of the form `a/f^m` where `a` has degree `mn`. For a homogeneous element `f` of degree `n` * `Proj_iso_Spec_Top_component.to_Spec`: `forward f` is the continuous map between `Proj.T| pbo f` and `Spec.T A⁰_f` * `Proj_iso_Spec_Top_component.to_Spec.preimage_eq`: for any `a: A`, if `a/f^m` has degree zero, then the preimage of `sbo a/f^m` under `to_Spec f` is `pbo f ∩ pbo a`. * [Robin Hartshorne, *Algebraic Geometry*][Har77]: Chapter II.2 Proposition 2.5 -/ noncomputable theory namespace algebraic_geometry open_locale direct_sum big_operators pointwise big_operators open direct_sum set_like.graded_monoid localization finset (hiding mk_zero) variables {R A : Type*} variables [comm_ring R] [comm_ring A] [algebra R A] variables (𝒜 : ℕ → submodule R A) variables [graded_algebra 𝒜] open Top topological_space open category_theory opposite open projective_spectrum.structure_sheaf local notation `Proj` := Proj.to_LocallyRingedSpace 𝒜 -- `Proj` as a locally ringed space local notation `Proj.T` := Proj .1.1.1 -- the underlying topological space of `Proj` local notation `Proj| ` U := Proj .restrict (opens.open_embedding (U : opens Proj.T)) -- `Proj` restrict to some open set local notation `Proj.T| ` U := (Proj .restrict (opens.open_embedding (U : opens Proj.T))).to_SheafedSpace.to_PresheafedSpace.1 -- the underlying topological space of `Proj` restricted to some open set local notation `pbo ` x := projective_spectrum.basic_open 𝒜 x -- basic open sets in `Proj` local notation `sbo ` f := prime_spectrum.basic_open f -- basic open sets in `Spec` local notation `Spec ` ring := Spec.LocallyRingedSpace_obj (CommRing.of ring) -- `Spec` as a locally ringed space local notation `Spec.T ` ring := (Spec.LocallyRingedSpace_obj (CommRing.of ring)).to_SheafedSpace.to_PresheafedSpace.1 -- the underlying topological space of `Spec` local notation `A⁰_ ` f := homogeneous_localization.away 𝒜 f namespace Proj_iso_Spec_Top_component /- This section is to construct the homeomorphism between `Proj` restricted at basic open set at a homogeneous element `x` and `Spec A⁰ₓ` where `A⁰ₓ` is the degree zero part of the localized ring `Aₓ`. -/ namespace to_Spec open ideal -- This section is to construct the forward direction : -- So for any `x` in `Proj| (pbo f)`, we need some point in `Spec A⁰_f`, i.e. a prime ideal, -- and we need this correspondence to be continuous in their Zariski topology. variables {𝒜} {f : A} {m : ℕ} (f_deg : f ∈ 𝒜 m) (x : Proj| (pbo f)) /--For any `x` in `Proj| (pbo f)`, the corresponding ideal in `Spec A⁰_f`. This fact that this ideal is prime is proven in `Top_component.forward.to_fun`-/ def carrier : ideal (A⁰_ f) := ideal.comap (algebra_map (A⁰_ f) (away f)) (ideal.span $ algebra_map A (away f) '' x.val.as_homogeneous_ideal) lemma mem_carrier_iff (z : A⁰_ f) : z ∈ carrier 𝒜 x ↔ z.val ∈ ideal.span (algebra_map A (away f) '' x.1.as_homogeneous_ideal) := iff.rfl lemma mem_carrier.clear_denominator' [decidable_eq (away f)] {z : localization.away f} (hz : z ∈ span ((algebra_map A (away f)) '' x.val.as_homogeneous_ideal)) : ∃ (c : algebra_map A (away f) '' x.1.as_homogeneous_ideal →₀ away f) (N : ℕ) (acd : Π y ∈ c.support.image c, A), f ^ N • z = algebra_map A (away f) (∑ i in c.support.attach, acd (c i) (finset.mem_image.mpr ⟨i, ⟨i.2, rfl⟩⟩) * i.1.2.some) := begin rw [←submodule_span_eq, finsupp.span_eq_range_total, linear_map.mem_range] at hz, rcases hz with ⟨c, eq1⟩, rw [finsupp.total_apply, finsupp.sum] at eq1, obtain ⟨⟨_, N, rfl⟩, hN⟩ := is_localization.exist_integer_multiples_of_finset (submonoid.powers f) (c.support.image c), choose acd hacd using hN, refine ⟨c, N, acd, _⟩, rw [← eq1, smul_sum, map_sum, ← sum_attach], congr' 1, ext i, rw [_root_.map_mul, hacd, (classical.some_spec i.1.2).2, smul_eq_mul, smul_mul_assoc], refl end lemma mem_carrier.clear_denominator [decidable_eq (away f)] {z : A⁰_ f} (hz : z ∈ carrier 𝒜 x) : ∃ (c : algebra_map A (away f) '' x.1.as_homogeneous_ideal →₀ away f) (N : ℕ) (acd : Π y ∈ c.support.image c, A), f ^ N • z.val = algebra_map A (away f) (∑ i in c.support.attach, acd (c i) (finset.mem_image.mpr ⟨i, ⟨i.2, rfl⟩⟩) * i.1.2.some) := mem_carrier.clear_denominator' x $ (mem_carrier_iff 𝒜 x z).mpr hz lemma disjoint : (disjoint (x.1.as_homogeneous_ideal.to_ideal : set A) (submonoid.powers f : set A)) := begin by_contra rid, rw [set.not_disjoint_iff] at rid, choose g hg using rid, obtain ⟨hg1, ⟨k, rfl⟩⟩ := hg, by_cases k_ineq : 0 < k, { erw x.1.is_prime.pow_mem_iff_mem _ k_ineq at hg1, exact x.2 hg1 }, { erw [show k = 0, by linarith, pow_zero, ←ideal.eq_top_iff_one] at hg1, apply x.1.is_prime.1, exact hg1 }, end lemma carrier_ne_top : carrier 𝒜 x ≠ ⊤ := begin have eq_top := disjoint x, classical, contrapose! eq_top, obtain ⟨c, N, acd, eq1⟩ := mem_carrier.clear_denominator _ x ((ideal.eq_top_iff_one _).mp eq_top), rw [algebra.smul_def, homogeneous_localization.one_val, mul_one] at eq1, change localization.mk (f ^ N) 1 = mk (∑ _, _) 1 at eq1, simp only [mk_eq_mk', is_localization.eq] at eq1, rcases eq1 with ⟨⟨_, ⟨M, rfl⟩⟩, eq1⟩, erw [mul_one, mul_one] at eq1, change f^_ * f^_ = _ * f^_ at eq1, rw set.not_disjoint_iff_nonempty_inter, refine ⟨f^N * f^M, eq1.symm ▸ mul_mem_right _ _ (sum_mem _ (λ i hi, mul_mem_left _ _ _)), ⟨N+M, by rw pow_add⟩⟩, generalize_proofs h₁ h₂, exact (classical.some_spec h₂).1, end variable (f) /--The function between the basic open set `D(f)` in `Proj` to the corresponding basic open set in `Spec A⁰_f`. This is bundled into a continuous map in `Top_component.forward`. -/ def to_fun (x : Proj.T| (pbo f)) : (Spec.T (A⁰_ f)) := ⟨carrier 𝒜 x, carrier_ne_top x, λ x1 x2 hx12, begin classical, simp only [mem_carrier_iff] at hx12 ⊢, let J := span (⇑(algebra_map A (away f)) '' x.val.as_homogeneous_ideal), suffices h : ∀ (x y : localization.away f), x * y ∈ J → x ∈ J ∨ y ∈ J, { rw [homogeneous_localization.mul_val] at hx12, exact h x1.val x2.val hx12, }, clear' x1 x2 hx12, intros x1 x2 hx12, induction x1 using localization.induction_on with data_x1, induction x2 using localization.induction_on with data_x2, rcases ⟨data_x1, data_x2⟩ with ⟨⟨a1, _, ⟨n1, rfl⟩⟩, ⟨a2, _, ⟨n2, rfl⟩⟩⟩, rcases mem_carrier.clear_denominator' x hx12 with ⟨c, N, acd, eq1⟩, simp only [algebra.smul_def] at eq1, change localization.mk (f ^ N) 1 * (mk _ _ * mk _ _) = mk (∑ _, _) _ at eq1, simp only [localization.mk_mul, one_mul] at eq1, simp only [mk_eq_mk', is_localization.eq] at eq1, rcases eq1 with ⟨⟨_, ⟨M, rfl⟩⟩, eq1⟩, rw [submonoid.coe_one, mul_one] at eq1, change _ * _ * f^_ = _ * (f^_ * f^_) * f^_ at eq1, rcases x.1.is_prime.mem_or_mem (show a1 * a2 * f ^ N * f ^ M ∈ _, from _) with h1|rid2, rcases x.1.is_prime.mem_or_mem h1 with h1|rid1, rcases x.1.is_prime.mem_or_mem h1 with h1|h2, { left, simp only [show (mk a1 ⟨f ^ n1, _⟩ : away f) = mk a1 1 * mk 1 ⟨f^n1, ⟨n1, rfl⟩⟩, by rw [localization.mk_mul, mul_one, one_mul]], exact ideal.mul_mem_right _ _ (ideal.subset_span ⟨_, h1, rfl⟩), }, { right, simp only [show (mk a2 ⟨f ^ n2, _⟩ : away f) = mk a2 1 * mk 1 ⟨f^n2, ⟨n2, rfl⟩⟩, by rw [localization.mk_mul, mul_one, one_mul]], exact ideal.mul_mem_right _ _ (ideal.subset_span ⟨_, h2, rfl⟩), }, { exact false.elim (x.2 (x.1.is_prime.mem_of_pow_mem N rid1)), }, { exact false.elim (x.2 (x.1.is_prime.mem_of_pow_mem M rid2)), }, { rw [mul_comm _ (f^N), eq1], refine mul_mem_right _ _ (mul_mem_right _ _ (sum_mem _ (λ i hi, mul_mem_left _ _ _))), generalize_proofs h₁ h₂, exact (classical.some_spec h₂).1 }, end⟩ /- The preimage of basic open set `D(a/f^n)` in `Spec A⁰_f` under the forward map from `Proj A` to `Spec A⁰_f` is the basic open set `D(a) ∩ D(f)` in `Proj A`. This lemma is used to prove that the forward map is continuous. -/ lemma preimage_eq (a b : A) (k : ℕ) (a_mem : a ∈ 𝒜 k) (b_mem1 : b ∈ 𝒜 k) (b_mem2 : b ∈ submonoid.powers f) : to_fun 𝒜 f ⁻¹' ((@prime_spectrum.basic_open (A⁰_ f) _ (quotient.mk' ⟨k, ⟨a, a_mem⟩, ⟨b, b_mem1⟩, b_mem2⟩)) : set (prime_spectrum (homogeneous_localization.away 𝒜 f))) = {x | x.1 ∈ (pbo f) ⊓ (pbo a)} := begin classical, ext1 y, split; intros hy, { refine ⟨y.2, _⟩, rw [set.mem_preimage, opens.mem_coe, prime_spectrum.mem_basic_open] at hy, rw projective_spectrum.mem_coe_basic_open, intro a_mem_y, apply hy, rw [to_fun, mem_carrier_iff, homogeneous_localization.val_mk', subtype.coe_mk], dsimp, rcases b_mem2 with ⟨k, hk⟩, simp only [show (mk a ⟨b, ⟨k, hk⟩⟩ : away f) = mk 1 ⟨f^k, ⟨_, rfl⟩⟩ * mk a 1, by { rw [mk_mul, one_mul, mul_one], congr, rw hk }], exact ideal.mul_mem_left _ _ (ideal.subset_span ⟨_, a_mem_y, rfl⟩), }, { change y.1 ∈ _ at hy, rcases hy with ⟨hy1, hy2⟩, rw projective_spectrum.mem_coe_basic_open at hy1 hy2, rw [set.mem_preimage, to_fun, opens.mem_coe, prime_spectrum.mem_basic_open], intro rid, dsimp at rid, rcases mem_carrier.clear_denominator 𝒜 _ rid with ⟨c, N, acd, eq1⟩, rw [algebra.smul_def] at eq1, change localization.mk (f^N) 1 * mk _ _ = mk (∑ _, _) _ at eq1, rw [mk_mul, one_mul, mk_eq_mk', is_localization.eq] at eq1, rcases eq1 with ⟨⟨_, ⟨M, rfl⟩⟩, eq1⟩, rw [submonoid.coe_one, mul_one] at eq1, simp only [subtype.coe_mk] at eq1, rcases y.1.is_prime.mem_or_mem (show a * f ^ N * f ^ M ∈ _, from _) with H1 | H3, rcases y.1.is_prime.mem_or_mem H1 with H1 | H2, { exact hy2 H1, }, { exact y.2 (y.1.is_prime.mem_of_pow_mem N H2), }, { exact y.2 (y.1.is_prime.mem_of_pow_mem M H3), }, { rw [mul_comm _ (f^N), eq1], refine mul_mem_right _ _ (mul_mem_right _ _ (sum_mem _ (λ i hi, mul_mem_left _ _ _))), generalize_proofs h₁ h₂, exact (classical.some_spec h₂).1, }, }, end end to_Spec section variable {𝒜} /--The continuous function between the basic open set `D(f)` in `Proj` to the corresponding basic open set in `Spec A⁰_f`. -/ def to_Spec {f : A} : (Proj.T| (pbo f)) ⟶ (Spec.T (A⁰_ f)) := { to_fun := to_Spec.to_fun 𝒜 f, continuous_to_fun := begin apply is_topological_basis.continuous (prime_spectrum.is_topological_basis_basic_opens), rintros _ ⟨⟨k, ⟨a, ha⟩, ⟨b, hb1⟩, ⟨k', hb2⟩⟩, rfl⟩, dsimp, erw to_Spec.preimage_eq f a b k ha hb1 ⟨k', hb2⟩, refine is_open_induced_iff.mpr ⟨(pbo f).1 ⊓ (pbo a).1, is_open.inter (pbo f).2 (pbo a).2, _⟩, ext z, split; intros hz; simpa [set.mem_preimage], end } end namespace from_Spec open graded_algebra set_like finset (hiding mk_zero) open _root_.homogeneous_localization variables {𝒜} {f : A} {m : ℕ} (f_deg : f ∈ 𝒜 m) private meta def mem_tac : tactic unit := let b : tactic unit := `[exact pow_mem_graded _ (submodule.coe_mem _) <|> exact nat_cast_mem_graded _ _ <|> exact pow_mem_graded _ f_deg] in b <|> `[by repeat { all_goals { apply graded_monoid.mul_mem } }; b] include f_deg /--The function from `Spec A⁰_f` to `Proj|D(f)` is defined by `q ↦ {a | aᵢᵐ/fⁱ ∈ q}`, i.e. sending `q` a prime ideal in `A⁰_f` to the homogeneous prime relevant ideal containing only and all the elements `a : A` such that for every `i`, the degree 0 element formed by dividing the `m`-th power of the `i`-th projection of `a` by the `i`-th power of the degree-`m` homogeneous element `f`, lies in `q`. The set `{a | aᵢᵐ/fⁱ ∈ q}` * is an ideal, as proved in `carrier.as_ideal`; * is homogeneous, as proved in `carrier.as_homogeneous_ideal`; * is prime, as proved in `carrier.as_ideal.prime`; * is relevant, as proved in `carrier.relevant`. -/ def carrier (q : Spec.T (A⁰_ f)) : set A := {a | ∀ i, (quotient.mk' ⟨m * i, ⟨proj 𝒜 i a ^ m, by mem_tac⟩, ⟨f^i, by rw mul_comm; mem_tac⟩, ⟨_, rfl⟩⟩ : A⁰_ f) ∈ q.1} lemma mem_carrier_iff (q : Spec.T (A⁰_ f)) (a : A) : a ∈ carrier f_deg q ↔ ∀ i, (quotient.mk' ⟨m * i, ⟨proj 𝒜 i a ^ m, by mem_tac⟩, ⟨f^i, by rw mul_comm; mem_tac⟩, ⟨_, rfl⟩⟩ : A⁰_ f) ∈ q.1 := iff.rfl lemma mem_carrier_iff' (q : Spec.T (A⁰_ f)) (a : A) : a ∈ carrier f_deg q ↔ ∀ i, (localization.mk (proj 𝒜 i a ^ m) ⟨f^i, ⟨i, rfl⟩⟩ : localization.away f) ∈ (algebra_map (homogeneous_localization.away 𝒜 f) (localization.away f)) '' q.1.1 := (mem_carrier_iff f_deg q a).trans begin split; intros h i; specialize h i, { rw set.mem_image, refine ⟨_, h, rfl⟩, }, { rw set.mem_image at h, rcases h with ⟨x, h, hx⟩, convert h, rw [ext_iff_val, val_mk'], dsimp only [subtype.coe_mk], rw ←hx, refl, }, end lemma carrier.add_mem (q : Spec.T (A⁰_ f)) {a b : A} (ha : a ∈ carrier f_deg q) (hb : b ∈ carrier f_deg q) : a + b ∈ carrier f_deg q := begin refine λ i, (q.2.mem_or_mem _).elim id id, change (quotient.mk' ⟨_, _, _, _⟩ : A⁰_ f) ∈ q.1, dsimp only [subtype.coe_mk], simp_rw [←pow_add, map_add, add_pow, mul_comm, ← nsmul_eq_mul], let g : ℕ → A⁰_ f := λ j, (m + m).choose j • if h2 : m + m < j then 0 else if h1 : j ≤ m then quotient.mk' ⟨m * i, ⟨proj 𝒜 i a^j * proj 𝒜 i b ^ (m - j), _⟩, ⟨_, by rw mul_comm; mem_tac⟩, ⟨i, rfl⟩⟩ * quotient.mk' ⟨m * i, ⟨proj 𝒜 i b ^ m, by mem_tac⟩, ⟨_, by rw mul_comm; mem_tac⟩, ⟨i, rfl⟩⟩ else quotient.mk' ⟨m * i, ⟨proj 𝒜 i a ^ m, by mem_tac⟩, ⟨_, by rw mul_comm; mem_tac⟩, ⟨i, rfl⟩⟩ * quotient.mk' ⟨m * i, ⟨proj 𝒜 i a ^ (j - m) * proj 𝒜 i b ^ (m + m - j), _⟩, ⟨_, by rw mul_comm; mem_tac⟩, ⟨i, rfl⟩⟩, rotate, { rw (_ : m*i = _), mem_tac, rw [← add_smul, nat.add_sub_of_le h1], refl }, { rw (_ : m*i = _), mem_tac, rw ←add_smul, congr, zify [le_of_not_lt h2, le_of_not_le h1], abel }, convert_to ∑ i in range (m + m + 1), g i ∈ q.1, swap, { refine q.1.sum_mem (λ j hj, nsmul_mem _ _), split_ifs, exacts [q.1.zero_mem, q.1.mul_mem_left _ (hb i), q.1.mul_mem_right _ (ha i)] }, rw [ext_iff_val, val_mk'], change _ = (algebra_map (homogeneous_localization.away 𝒜 f) (localization.away f)) _, dsimp only [subtype.coe_mk], rw [map_sum, mk_sum], apply finset.sum_congr rfl (λ j hj, _), change _ = homogeneous_localization.val _, rw [homogeneous_localization.smul_val], split_ifs with h2 h1, { exact ((finset.mem_range.1 hj).not_le h2).elim }, all_goals { simp only [mul_val, zero_val, val_mk', subtype.coe_mk, mk_mul, ←smul_mk], congr' 2 }, { rw [mul_assoc, ←pow_add, add_comm (m-j), nat.add_sub_assoc h1] }, { simp_rw [pow_add], refl }, { rw [← mul_assoc, ←pow_add, nat.add_sub_of_le (le_of_not_le h1)] }, { simp_rw [pow_add], refl }, end variables (hm : 0 < m) (q : Spec.T (A⁰_ f)) include hm lemma carrier.zero_mem : (0 : A) ∈ carrier f_deg q := λ i, begin convert submodule.zero_mem q.1 using 1, rw [ext_iff_val, val_mk', zero_val], simp_rw [map_zero, zero_pow hm], convert localization.mk_zero _ using 1, end lemma carrier.smul_mem (c x : A) (hx : x ∈ carrier f_deg q) : c • x ∈ carrier f_deg q := begin revert c, refine direct_sum.decomposition.induction_on 𝒜 _ _ _, { rw zero_smul, exact carrier.zero_mem f_deg hm _ }, { rintros n ⟨a, ha⟩ i, simp_rw [subtype.coe_mk, proj_apply, smul_eq_mul, coe_decompose_mul_of_left_mem 𝒜 i ha], split_ifs, { convert_to (quotient.mk' ⟨_, ⟨a^m, pow_mem_graded m ha⟩, ⟨_, _⟩, ⟨n, rfl⟩⟩ * quotient.mk' ⟨_, ⟨proj 𝒜 (i - n) x ^ m, by mem_tac⟩, ⟨_, _⟩, ⟨i - n, rfl⟩⟩ : A⁰_ f) ∈ q.1, { erw [ext_iff_val, val_mk', mul_val, val_mk', val_mk', subtype.coe_mk], simp_rw [mul_pow, subtype.coe_mk], rw [localization.mk_mul], congr, erw [← pow_add, nat.add_sub_of_le h] }, { exact ideal.mul_mem_left _ _ (hx _), rw [smul_eq_mul, mul_comm], mem_tac, } }, { simp_rw [zero_pow hm], convert carrier.zero_mem f_deg hm q i, rw [map_zero, zero_pow hm] } }, { simp_rw add_smul, exact λ _ _, carrier.add_mem f_deg q }, end /-- For a prime ideal `q` in `A⁰_f`, the set `{a | aᵢᵐ/fⁱ ∈ q}` as an ideal. -/ def carrier.as_ideal : ideal A := { carrier := carrier f_deg q, zero_mem' := carrier.zero_mem f_deg hm q, add_mem' := λ a b, carrier.add_mem f_deg q, smul_mem' := carrier.smul_mem f_deg hm q } lemma carrier.as_ideal.homogeneous : (carrier.as_ideal f_deg hm q).is_homogeneous 𝒜 := λ i a ha j, (em (i = j)).elim (λ h, h ▸ by simpa only [proj_apply, decompose_coe, of_eq_same] using ha _) (λ h, begin simp only [proj_apply, decompose_of_mem_ne 𝒜 (submodule.coe_mem (decompose 𝒜 a i)) h, zero_pow hm], convert carrier.zero_mem f_deg hm q j, rw [map_zero, zero_pow hm], end) /-- For a prime ideal `q` in `A⁰_f`, the set `{a | aᵢᵐ/fⁱ ∈ q}` as a homogeneous ideal. -/ def carrier.as_homogeneous_ideal : homogeneous_ideal 𝒜 := ⟨carrier.as_ideal f_deg hm q, carrier.as_ideal.homogeneous f_deg hm q⟩ lemma carrier.denom_not_mem : f ∉ carrier.as_ideal f_deg hm q := λ rid, q.is_prime.ne_top $ (ideal.eq_top_iff_one _).mpr begin convert rid m, simpa only [ext_iff_val, one_val, proj_apply, decompose_of_mem_same _ f_deg, val_mk'] using (mk_self (⟨_, m, rfl⟩ : submonoid.powers f)).symm, end lemma carrier.relevant : ¬homogeneous_ideal.irrelevant 𝒜 ≤ carrier.as_homogeneous_ideal f_deg hm q := λ rid, carrier.denom_not_mem f_deg hm q $ rid $ direct_sum.decompose_of_mem_ne 𝒜 f_deg hm.ne' lemma carrier.as_ideal.ne_top : (carrier.as_ideal f_deg hm q) ≠ ⊤ := λ rid, carrier.denom_not_mem f_deg hm q (rid.symm ▸ submodule.mem_top) lemma carrier.as_ideal.prime : (carrier.as_ideal f_deg hm q).is_prime := (carrier.as_ideal.homogeneous f_deg hm q).is_prime_of_homogeneous_mem_or_mem (carrier.as_ideal.ne_top f_deg hm q) $ λ x y ⟨nx, hnx⟩ ⟨ny, hny⟩ hxy, show (∀ i, _ ∈ _) ∨ ∀ i, _ ∈ _, begin rw [← and_forall_ne nx, and_iff_left, ← and_forall_ne ny, and_iff_left], { apply q.2.mem_or_mem, convert hxy (nx + ny) using 1, simp_rw [proj_apply, decompose_of_mem_same 𝒜 hnx, decompose_of_mem_same 𝒜 hny, decompose_of_mem_same 𝒜 (mul_mem hnx hny), mul_pow, pow_add], simpa only [ext_iff_val, val_mk', mul_val, mk_mul], }, all_goals { intros n hn, convert q.1.zero_mem using 1, rw [ext_iff_val, val_mk', zero_val], simp_rw [proj_apply, subtype.coe_mk], convert mk_zero _, rw [decompose_of_mem_ne 𝒜 _ hn.symm, zero_pow hm], { exact hnx <|> exact hny } }, end variable (f_deg) /-- The function `Spec A⁰_f → Proj|D(f)` by sending `q` to `{a | aᵢᵐ/fⁱ ∈ q}`. -/ def to_fun : (Spec.T (A⁰_ f)) → (Proj.T| (pbo f)) := λ q, ⟨⟨carrier.as_homogeneous_ideal f_deg hm q, carrier.as_ideal.prime f_deg hm q, carrier.relevant f_deg hm q⟩, (projective_spectrum.mem_basic_open _ f _).mp $ carrier.denom_not_mem f_deg hm q⟩ end from_Spec end Proj_iso_Spec_Top_component end algebraic_geometry
198493625dafd8db1dea94d2b435dd4b964261b3
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/algebra/ring.lean
889c8398c11a8ee11b4741240df68ef0051b8b32
[ "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
19,287
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import algebra.ring.prod import ring_theory.ideal.quotient import ring_theory.subring.basic import topology.algebra.group /-! # Topological (semi)rings A topological (semi)ring is a (semi)ring equipped with a topology such that all operations are continuous. Besides this definition, this file proves that the topological closure of a subring (resp. an ideal) is a subring (resp. an ideal) and defines products and quotients of topological (semi)rings. ## Main Results - `subring.topological_closure`/`subsemiring.topological_closure`: the topological closure of a `subring`/`subsemiring` is itself a `sub(semi)ring`. - `prod.topological_semiring`/`prod.topological_ring`: The product of two topological (semi)rings. - `pi.topological_semiring`/`pi.topological_ring`: The arbitrary product of topological (semi)rings. - `ideal.closure`: The closure of an ideal is an ideal. - `topological_ring_quotient`: The quotient of a topological semiring by an ideal is a topological ring. -/ open classical set filter topological_space function open_locale classical topological_space filter section topological_semiring variables (α : Type*) /-- a topological semiring is a semiring `R` where addition and multiplication are continuous. We allow for non-unital and non-associative semirings as well. The `topological_semiring` class should *only* be instantiated in the presence of a `non_unital_non_assoc_semiring` instance; if there is an instance of `non_unital_non_assoc_ring`, then `topological_ring` should be used. Note: in the presence of `non_assoc_ring`, these classes are mathematically equivalent (see `topological_semiring.has_continuous_neg_of_mul` or `topological_semiring.to_topological_ring`). -/ class topological_semiring [topological_space α] [non_unital_non_assoc_semiring α] extends has_continuous_add α, has_continuous_mul α : Prop /-- A topological ring is a ring `R` where addition, multiplication and negation are continuous. If `R` is a (unital) ring, then continuity of negation can be derived from continuity of multiplication as it is multiplication with `-1`. (See `topological_semiring.has_continuous_neg_of_mul` and `topological_semiring.to_topological_add_group`) -/ class topological_ring [topological_space α] [non_unital_non_assoc_ring α] extends topological_semiring α, has_continuous_neg α : Prop variables {α} /-- If `R` is a ring with a continuous multiplication, then negation is continuous as well since it is just multiplication with `-1`. -/ lemma topological_semiring.has_continuous_neg_of_mul [topological_space α] [non_assoc_ring α] [has_continuous_mul α] : has_continuous_neg α := { continuous_neg := by simpa using (continuous_const.mul continuous_id : continuous (λ x : α, (-1) * x)) } /-- If `R` is a ring which is a topological semiring, then it is automatically a topological ring. This exists so that one can place a topological ring structure on `R` without explicitly proving `continuous_neg`. -/ lemma topological_semiring.to_topological_ring [topological_space α] [non_assoc_ring α] (h : topological_semiring α) : topological_ring α := { ..h, ..(by { haveI := h.to_has_continuous_mul, exact topological_semiring.has_continuous_neg_of_mul } : has_continuous_neg α) } @[priority 100] -- See note [lower instance priority] instance topological_ring.to_topological_add_group [non_unital_non_assoc_ring α] [topological_space α] [topological_ring α] : topological_add_group α := { ..topological_ring.to_topological_semiring.to_has_continuous_add, ..topological_ring.to_has_continuous_neg } @[priority 50] instance discrete_topology.topological_semiring [topological_space α] [non_unital_non_assoc_semiring α] [discrete_topology α] : topological_semiring α := ⟨⟩ @[priority 50] instance discrete_topology.topological_ring [topological_space α] [non_unital_non_assoc_ring α] [discrete_topology α] : topological_ring α := ⟨⟩ section variables [topological_space α] [semiring α] [topological_semiring α] namespace subsemiring instance (S : subsemiring α) : topological_semiring S := { ..S.to_submonoid.has_continuous_mul, ..S.to_add_submonoid.has_continuous_add } end subsemiring /-- The (topological-space) closure of a subsemiring of a topological semiring is itself a subsemiring. -/ def subsemiring.topological_closure (s : subsemiring α) : subsemiring α := { carrier := closure (s : set α), ..(s.to_submonoid.topological_closure), ..(s.to_add_submonoid.topological_closure ) } @[simp] lemma subsemiring.topological_closure_coe (s : subsemiring α) : (s.topological_closure : set α) = closure (s : set α) := rfl lemma subsemiring.subring_topological_closure (s : subsemiring α) : s ≤ s.topological_closure := subset_closure lemma subsemiring.is_closed_topological_closure (s : subsemiring α) : is_closed (s.topological_closure : set α) := by convert is_closed_closure lemma subsemiring.topological_closure_minimal (s : subsemiring α) {t : subsemiring α} (h : s ≤ t) (ht : is_closed (t : set α)) : s.topological_closure ≤ t := closure_minimal h ht /-- If a subsemiring of a topological semiring is commutative, then so is its topological closure. -/ def subsemiring.comm_semiring_topological_closure [t2_space α] (s : subsemiring α) (hs : ∀ (x y : s), x * y = y * x) : comm_semiring s.topological_closure := { ..s.topological_closure.to_semiring, ..s.to_submonoid.comm_monoid_topological_closure hs } end section variables {β : Type*} [topological_space α] [topological_space β] /-- The product topology on the cartesian product of two topological semirings makes the product into a topological semiring. -/ instance [non_unital_non_assoc_semiring α] [non_unital_non_assoc_semiring β] [topological_semiring α] [topological_semiring β] : topological_semiring (α × β) := {} /-- The product topology on the cartesian product of two topological rings makes the product into a topological ring. -/ instance [non_unital_non_assoc_ring α] [non_unital_non_assoc_ring β] [topological_ring α] [topological_ring β] : topological_ring (α × β) := {} end instance {β : Type*} {C : β → Type*} [∀ b, topological_space (C b)] [Π b, non_unital_non_assoc_semiring (C b)] [Π b, topological_semiring (C b)] : topological_semiring (Π b, C b) := {} instance {β : Type*} {C : β → Type*} [∀ b, topological_space (C b)] [Π b, non_unital_non_assoc_ring (C b)] [Π b, topological_ring (C b)] : topological_ring (Π b, C b) := {} section mul_opposite open mul_opposite instance [non_unital_non_assoc_semiring α] [topological_space α] [has_continuous_add α] : has_continuous_add αᵐᵒᵖ := { continuous_add := continuous_induced_rng.2 $ (@continuous_add α _ _ _).comp (continuous_unop.prod_map continuous_unop) } instance [non_unital_non_assoc_semiring α] [topological_space α] [topological_semiring α] : topological_semiring αᵐᵒᵖ := {} instance [non_unital_non_assoc_ring α] [topological_space α] [has_continuous_neg α] : has_continuous_neg αᵐᵒᵖ := { continuous_neg := continuous_induced_rng.2 $ (@continuous_neg α _ _ _).comp continuous_unop } instance [non_unital_non_assoc_ring α] [topological_space α] [topological_ring α] : topological_ring αᵐᵒᵖ := {} end mul_opposite section add_opposite open add_opposite instance [non_unital_non_assoc_semiring α] [topological_space α] [has_continuous_mul α] : has_continuous_mul αᵃᵒᵖ := { continuous_mul := by convert (continuous_op.comp $ (@continuous_mul α _ _ _).comp $ continuous_unop.prod_map continuous_unop) } instance [non_unital_non_assoc_semiring α] [topological_space α] [topological_semiring α] : topological_semiring αᵃᵒᵖ := {} instance [non_unital_non_assoc_ring α] [topological_space α] [topological_ring α] : topological_ring αᵃᵒᵖ := {} end add_opposite section variables {R : Type*} [non_unital_non_assoc_ring R] [topological_space R] lemma topological_ring.of_add_group_of_nhds_zero [topological_add_group R] (hmul : tendsto (uncurry ((*) : R → R → R)) ((𝓝 0) ×ᶠ (𝓝 0)) $ 𝓝 0) (hmul_left : ∀ (x₀ : R), tendsto (λ x : R, x₀ * x) (𝓝 0) $ 𝓝 0) (hmul_right : ∀ (x₀ : R), tendsto (λ x : R, x * x₀) (𝓝 0) $ 𝓝 0) : topological_ring R := begin refine {..‹topological_add_group R›, ..}, have hleft : ∀ x₀ : R, 𝓝 x₀ = map (λ x, x₀ + x) (𝓝 0), by simp, have hadd : tendsto (uncurry ((+) : R → R → R)) ((𝓝 0) ×ᶠ (𝓝 0)) (𝓝 0), { rw ← nhds_prod_eq, convert continuous_add.tendsto ((0 : R), (0 : R)), rw zero_add }, rw continuous_iff_continuous_at, rintro ⟨x₀, y₀⟩, rw [continuous_at, nhds_prod_eq, hleft x₀, hleft y₀, hleft (x₀*y₀), filter.prod_map_map_eq, tendsto_map'_iff], suffices : tendsto ((λ (x : R), x + x₀ * y₀) ∘ (λ (p : R × R), p.1 + p.2) ∘ (λ (p : R × R), (p.1*y₀ + x₀*p.2, p.1*p.2))) ((𝓝 0) ×ᶠ (𝓝 0)) (map (λ (x : R), x + x₀ * y₀) $ 𝓝 0), { convert this using 1, { ext, simp only [comp_app, mul_add, add_mul], abel }, { simp only [add_comm] } }, refine tendsto_map.comp (hadd.comp (tendsto.prod_mk _ hmul)), exact hadd.comp (((hmul_right y₀).comp tendsto_fst).prod_mk ((hmul_left x₀).comp tendsto_snd)) end lemma topological_ring.of_nhds_zero (hadd : tendsto (uncurry ((+) : R → R → R)) ((𝓝 0) ×ᶠ (𝓝 0)) $ 𝓝 0) (hneg : tendsto (λ x, -x : R → R) (𝓝 0) (𝓝 0)) (hmul : tendsto (uncurry ((*) : R → R → R)) ((𝓝 0) ×ᶠ (𝓝 0)) $ 𝓝 0) (hmul_left : ∀ (x₀ : R), tendsto (λ x : R, x₀ * x) (𝓝 0) $ 𝓝 0) (hmul_right : ∀ (x₀ : R), tendsto (λ x : R, x * x₀) (𝓝 0) $ 𝓝 0) (hleft : ∀ x₀ : R, 𝓝 x₀ = map (λ x, x₀ + x) (𝓝 0)) : topological_ring R := begin haveI := topological_add_group.of_comm_of_nhds_zero hadd hneg hleft, exact topological_ring.of_add_group_of_nhds_zero hmul hmul_left hmul_right end end variables {α} [topological_space α] section variables [non_unital_non_assoc_ring α] [topological_ring α] /-- In a topological semiring, the left-multiplication `add_monoid_hom` is continuous. -/ lemma mul_left_continuous (x : α) : continuous (add_monoid_hom.mul_left x) := continuous_const.mul continuous_id /-- In a topological semiring, the right-multiplication `add_monoid_hom` is continuous. -/ lemma mul_right_continuous (x : α) : continuous (add_monoid_hom.mul_right x) := continuous_id.mul continuous_const end variables [ring α] [topological_ring α] namespace subring instance (S : subring α) : topological_ring S := topological_semiring.to_topological_ring S.to_subsemiring.topological_semiring end subring /-- The (topological-space) closure of a subring of a topological ring is itself a subring. -/ def subring.topological_closure (S : subring α) : subring α := { carrier := closure (S : set α), ..S.to_submonoid.topological_closure, ..S.to_add_subgroup.topological_closure } lemma subring.subring_topological_closure (s : subring α) : s ≤ s.topological_closure := subset_closure lemma subring.is_closed_topological_closure (s : subring α) : is_closed (s.topological_closure : set α) := by convert is_closed_closure lemma subring.topological_closure_minimal (s : subring α) {t : subring α} (h : s ≤ t) (ht : is_closed (t : set α)) : s.topological_closure ≤ t := closure_minimal h ht /-- If a subring of a topological ring is commutative, then so is its topological closure. -/ def subring.comm_ring_topological_closure [t2_space α] (s : subring α) (hs : ∀ (x y : s), x * y = y * x) : comm_ring s.topological_closure := { ..s.topological_closure.to_ring, ..s.to_submonoid.comm_monoid_topological_closure hs } end topological_semiring section topological_ring variables {α : Type*} [topological_space α] [ring α] [topological_ring α] /-- The closure of an ideal in a topological ring as an ideal. -/ def ideal.closure (S : ideal α) : ideal α := { carrier := closure S, smul_mem' := λ c x hx, map_mem_closure (mul_left_continuous _) hx $ λ a, S.mul_mem_left c, ..(add_submonoid.topological_closure S.to_add_submonoid) } @[simp] lemma ideal.coe_closure (S : ideal α) : (S.closure : set α) = closure S := rfl end topological_ring section topological_ring variables {α : Type*} [topological_space α] [comm_ring α] (N : ideal α) open ideal.quotient instance topological_ring_quotient_topology : topological_space (α ⧸ N) := show topological_space (quotient _), by apply_instance -- note for the reader: in the following, `mk` is `ideal.quotient.mk`, the canonical map `R → R/I`. variable [topological_ring α] lemma quotient_ring.is_open_map_coe : is_open_map (mk N) := begin intros s s_op, change is_open (mk N ⁻¹' (mk N '' s)), rw quotient_ring_saturate, exact is_open_Union (λ ⟨n, _⟩, is_open_map_add_left n s s_op) end lemma quotient_ring.quotient_map_coe_coe : quotient_map (λ p : α × α, (mk N p.1, mk N p.2)) := is_open_map.to_quotient_map ((quotient_ring.is_open_map_coe N).prod (quotient_ring.is_open_map_coe N)) ((continuous_quot_mk.comp continuous_fst).prod_mk (continuous_quot_mk.comp continuous_snd)) (by rintro ⟨⟨x⟩, ⟨y⟩⟩; exact ⟨(x, y), rfl⟩) instance topological_ring_quotient : topological_ring (α ⧸ N) := topological_semiring.to_topological_ring { continuous_add := have cont : continuous (mk N ∘ (λ (p : α × α), p.fst + p.snd)) := continuous_quot_mk.comp continuous_add, (quotient_map.continuous_iff (quotient_ring.quotient_map_coe_coe N)).mpr cont, continuous_mul := have cont : continuous (mk N ∘ (λ (p : α × α), p.fst * p.snd)) := continuous_quot_mk.comp continuous_mul, (quotient_map.continuous_iff (quotient_ring.quotient_map_coe_coe N)).mpr cont } end topological_ring /-! ### Lattice of ring topologies We define a type class `ring_topology α` which endows a ring `α` with a topology such that all ring operations are continuous. Ring topologies on a fixed ring `α` are ordered, by reverse inclusion. They form a complete lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology. Any function `f : α → β` induces `coinduced f : topological_space α → ring_topology β`. -/ universes u v /-- A ring topology on a ring `α` is a topology for which addition, negation and multiplication are continuous. -/ @[ext] structure ring_topology (α : Type u) [ring α] extends topological_space α, topological_ring α : Type u namespace ring_topology variables {α : Type*} [ring α] instance inhabited {α : Type u} [ring α] : inhabited (ring_topology α) := ⟨{to_topological_space := ⊤, continuous_add := continuous_top, continuous_mul := continuous_top, continuous_neg := continuous_top}⟩ @[ext] lemma ext' {f g : ring_topology α} (h : f.is_open = g.is_open) : f = g := by { ext, rw h } /-- The ordering on ring topologies on the ring `α`. `t ≤ s` if every set open in `s` is also open in `t` (`t` is finer than `s`). -/ instance : partial_order (ring_topology α) := partial_order.lift ring_topology.to_topological_space $ ext local notation `cont` := @continuous _ _ private def def_Inf (S : set (ring_topology α)) : ring_topology α := let Inf_S' := Inf (to_topological_space '' S) in { to_topological_space := Inf_S', continuous_add := begin apply continuous_Inf_rng.2, rintros _ ⟨⟨t, tr⟩, haS, rfl⟩, resetI, have h := continuous_Inf_dom (set.mem_image_of_mem to_topological_space haS) continuous_id, have h_continuous_id := @continuous.prod_map _ _ _ _ t t Inf_S' Inf_S' _ _ h h, exact @continuous.comp _ _ _ (id _) (id _) t _ _ continuous_add h_continuous_id, end, continuous_mul := begin apply continuous_Inf_rng.2, rintros _ ⟨⟨t, tr⟩, haS, rfl⟩, resetI, have h := continuous_Inf_dom (set.mem_image_of_mem to_topological_space haS) continuous_id, have h_continuous_id := @continuous.prod_map _ _ _ _ t t Inf_S' Inf_S' _ _ h h, exact @continuous.comp _ _ _ (id _) (id _) t _ _ continuous_mul h_continuous_id, end, continuous_neg := begin apply continuous_Inf_rng.2, rintros _ ⟨⟨t, tr⟩, haS, rfl⟩, resetI, have h := continuous_Inf_dom (set.mem_image_of_mem to_topological_space haS) continuous_id, exact @continuous.comp _ _ _ (id _) (id _) t _ _ continuous_neg h, end } /-- Ring topologies on `α` form a complete lattice, with `⊥` the discrete topology and `⊤` the indiscrete topology. The infimum of a collection of ring topologies is the topology generated by all their open sets (which is a ring topology). The supremum of two ring topologies `s` and `t` is the infimum of the family of all ring topologies contained in the intersection of `s` and `t`. -/ instance : complete_semilattice_Inf (ring_topology α) := { Inf := def_Inf, Inf_le := λ S a haS, by { apply topological_space.complete_lattice.Inf_le, use [a, ⟨ haS, rfl⟩] }, le_Inf := begin intros S a hab, apply topological_space.complete_lattice.le_Inf, rintros _ ⟨b, hbS, rfl⟩, exact hab b hbS, end, ..ring_topology.partial_order } instance : complete_lattice (ring_topology α) := complete_lattice_of_complete_semilattice_Inf _ /-- Given `f : α → β` and a topology on `α`, the coinduced ring topology on `β` is the finest topology such that `f` is continuous and `β` is a topological ring. -/ def coinduced {α β : Type*} [t : topological_space α] [ring β] (f : α → β) : ring_topology β := Inf {b : ring_topology β | (topological_space.coinduced f t) ≤ b.to_topological_space} lemma coinduced_continuous {α β : Type*} [t : topological_space α] [ring β] (f : α → β) : cont t (coinduced f).to_topological_space f := begin rw continuous_iff_coinduced_le, refine le_Inf _, rintros _ ⟨t', ht', rfl⟩, exact ht', end /-- The forgetful functor from ring topologies on `a` to additive group topologies on `a`. -/ def to_add_group_topology (t : ring_topology α) : add_group_topology α := { to_topological_space := t.to_topological_space, to_topological_add_group := @topological_ring.to_topological_add_group _ _ t.to_topological_space t.to_topological_ring } /-- The order embedding from ring topologies on `a` to additive group topologies on `a`. -/ def to_add_group_topology.order_embedding : order_embedding (ring_topology α) (add_group_topology α) := { to_fun := λ t, t.to_add_group_topology, inj' := begin intros t₁ t₂ h_eq, dsimp only at h_eq, ext, have h_t₁ : t₁.to_topological_space = t₁.to_add_group_topology.to_topological_space := rfl, rw [h_t₁, h_eq], refl, end, map_rel_iff' := begin intros t₁ t₂, rw [embedding.coe_fn_mk], have h_le : t₁ ≤ t₂ ↔ t₁.to_topological_space ≤ t₂.to_topological_space := by refl, rw h_le, refl, end } end ring_topology
eef9cf905891f339c090c6f6678f0dc3af8ff1a8
785b41b0993f39cbfa9b02fe0940ce3f2f51a57d
/conf/dz.lean
921767719c6d9b484c7a1ef8116d76cd44b69503
[ "MIT" ]
permissive
loso3000/OpenWrt-DIY-1
75b0d70314d703203508218a29acefc3b914d32d
5858be81ee44199908cbaa1a752b17505c9834e8
refs/heads/main
1,690,532,461,283
1,631,008,241,000
1,631,008,241,000
354,817,508
1
0
MIT
1,617,623,493,000
1,617,623,492,000
null
UTF-8
Lean
false
false
15,593
lean
CONFIG_TARGET_x86=y CONFIG_TARGET_x86_64=y CONFIG_TARGET_x86_64_DEVICE_generic=y # 设置固件大小 CONFIG_TARGET_KERNEL_PARTSIZE=64 CONFIG_TARGET_ROOTFS_PARTSIZE=1516 # EFI支持: CONFIG_GRUB_IMAGES=y CONFIG_EFI_IMAGES=y # CONFIG_VMDK_IMAGES is not set # 不压缩efi CONFIG_TARGET_ROOTFS_TARGZ=n # CONFIG_TARGET_IMAGES_GZIP is not set # Wireless # CONFIG_PACKAGE_wpad-basic-wolfssl=n #ipv6 CONFIG_PACKAGE_ipv6helper=y CONFIG_PACKAGE_dnsmasq_full_dhcpv6=y #添加SD卡支持 CONFIG_PACKAGE_kmod-mmc=y CONFIG_PACKAGE_kmod-sdhci=y #添加USB扩展支持 CONFIG_PACKAGE_block-mount=y CONFIG_PACKAGE_librt=y # x86 CONFIG_PACKAGE_kmod-usb-hid=y CONFIG_PACKAGE_qemu-ga=y CONFIG_PACKAGE_lm-sensors-detect=y CONFIG_PACKAGE_kmod-bonding=y CONFIG_PACKAGE_kmod-mmc-spi=y CONFIG_PACKAGE_ppp-mod-pptp=y #VPN客户端 CONFIG_PACKAGE_kmod-vmxnet3=y CONFIG_PACKAGE_kmod-igbvf=y CONFIG_PACKAGE_kmod-ixgbe=y CONFIG_PACKAGE_kmod-pcnet32=y CONFIG_PACKAGE_kmod-r8125=y CONFIG_PACKAGE_kmod-r8168=y CONFIG_PACKAGE_kmod-8139cp=y CONFIG_PACKAGE_kmod-8139too=y CONFIG_PACKAGE_kmod-rtl8xxxu=y CONFIG_PACKAGE_kmod-i40e=y CONFIG_PACKAGE_kmod-i40evf=y CONFIG_PACKAGE_kmod-ath5k=y CONFIG_PACKAGE_kmod-ath9k=y CONFIG_PACKAGE_kmod-ath9k-htc=y CONFIG_PACKAGE_kmod-ath10k=y CONFIG_PACKAGE_kmod-rt2800-usb=y CONFIG_PACKAGE_kmod-mlx4-core=y CONFIG_PACKAGE_kmod-mlx5-core=y CONFIG_PACKAGE_kmod-alx=y CONFIG_PACKAGE_kmod-tulip=y CONFIG_PACKAGE_kmod-tg3=y CONFIG_PACKAGE_kmod-fs-antfs=y # CONFIG_PACKAGE_kmod-fs-ntfs is not set CONFIG_PACKAGE_ath10k-firmware-qca9888=y CONFIG_PACKAGE_ath10k-firmware-qca988x=y CONFIG_PACKAGE_ath10k-firmware-qca9984=y CONFIG_PACKAGE_brcmfmac-firmware-43602a1-pcie=y CONFIG_PACKAGE_kmod-ac97=y CONFIG_PACKAGE_kmod-sound-via82xx=y CONFIG_PACKAGE_alsa-utils=y CONFIG_PACKAGE_kmod-iwlwifi=y #工具 CONFIG_PACKAGE_acpid=y CONFIG_PACKAGE_blkid=y CONFIG_PACKAGE_smartmontools=y # CONFIG_PACKAGE_open-vm-tools=n #虚拟机支持管理性能更好 CONFIG_PACKAGE_ethtool=y #网卡工具 CONFIG_PACKAGE_iperf3=y #局域网测速 CONFIG_PACKAGE_snmpd=n #旁路由穿透显示真机器MAC #CONFIG_PACKAGE_parted=n #128个区分区工具z CONFIG_PACKAGE_fdisk=y #分区工具 CONFIG_PACKAGE_hdparm=y #移动硬盘设置 CONFIG_PACKAGE_curl=y # USB3.0支持: CONFIG_PACKAGE_kmod-usb2=y CONFIG_PACKAGE_kmod-usb2-pci=y CONFIG_PACKAGE_kmod-usb3=y CONFIG_PACKAGE_kmod-usb-audio=y CONFIG_PACKAGE_kmod-usb-printer=y #nfs CONFIG_PACKAGE_kmod-fs-nfsd=y CONFIG_PACKAGE_kmod-fs-nfs=y CONFIG_PACKAGE_kmod-fs-nfs-v4=y #Sound Support CONFIG_PACKAGE_kmod-sound-core=y CONFIG_PACKAGE_kmod-sound-hda-core=y CONFIG_PACKAGE_kmod-sound-hda-codec-realtek=y CONFIG_PACKAGE_kmod-sound-hda-codec-via=y CONFIG_PACKAGE_kmod-sound-hda-intel=y CONFIG_PACKAGE_kmod-sound-hda-codec-hdmi=y #USB net driver CONFIG_PACKAGE_kmod-rtlwifi=y CONFIG_PACKAGE_kmod-rtlwifi-btcoexist=y CONFIG_PACKAGE_kmod-rtlwifi-usb=y CONFIG_PACKAGE_kmod-rtl8812au-ac=y CONFIG_PACKAGE_usb-modeswitch=y CONFIG_PACKAGE_kmod-rtl8192cu=y CONFIG_PACKAGE_kmod-rtl8821cu=y CONFIG_PACKAGE_kmod-mt76=y CONFIG_PACKAGE_kmod-mt76x2u=y CONFIG_PACKAGE_kmod-usb-net-asix=y CONFIG_PACKAGE_kmod-usb-net-asix-ax88179=y CONFIG_PACKAGE_kmod-usb-net-rtl8152-vendor=y CONFIG_PACKAGE_kmod-usb-net-rndis=y CONFIG_PACKAGE_kmod-usb-net-cdc-ether=y CONFIG_PACKAGE_kmod-usb-net-ipheth=y # L2TP CONFIG_PACKAGE_kmod-pppol2tp=y # pptp CONFIG_PACKAGE_kmod-pptp=n CONFIG_PACKAGE_kmod-gre=n CONFIG_PACKAGE_kmod-nf-nathelper-extra=n # ipsec-vpnd CONFIG_PACKAGE_kmod-crypto-authenc=y CONFIG_PACKAGE_kmod-ipsec=y CONFIG_PACKAGE_kmod-ipsec4=y CONFIG_PACKAGE_kmod-ipsec6=y CONFIG_PACKAGE_kmod-ipt-ipsec=y # cifsmount # CONFIG_PACKAGE_kmod-fs-cifs=y CONFIG_PACKAGE_kmod-nls-utf8=y CONFIG_PACKAGE_kmod-crypto-misc=y # eqos CONFIG_PACKAGE_kmod-ifb=y # map CONFIG_PACKAGE_kmod-ip6-tunnel=y CONFIG_PACKAGE_kmod-nat46=y # ebtables CONFIG_PACKAGE_kmod-ebtables=y CONFIG_PACKAGE_kmod-ebtables-ipv4=y CONFIG_PACKAGE_kmod-ebtables-ipv6=y #add upnp # CONFIG_PACKAGE_irqbalance=n # CONFIG_PACKAGE_miniupnpd=y CONFIG_PACKAGE_miniupnpd-igdv1=y # CONFIG_PACKAGE_luci-app-upnp=y # CONFIG_PACKAGE_luci-app-boostupnp=n # CONFIG_PACKAGE_luci-app-wol is not set CONFIG_PACKAGE_luci-app-wolplus=y #base插件 CONFIG_PACKAGE_ddns-scripts_cloudflare.com-v4=y CONFIG_PACKAGE_ddns-scripts=y CONFIG_PACKAGE_ddns-scripts_freedns_42_pl=y CONFIG_PACKAGE_ddns-scripts_godaddy.com-v1=y CONFIG_PACKAGE_ddns-scripts_no-ip_com=y CONFIG_PACKAGE_ddns-scripts_nsupdate=y CONFIG_PACKAGE_ddns-scripts_route53-v1=y # CONFIG_PACKAGE_autosamba is not set CONFIG_PACKAGE_autosamba-ksmbd=n CONFIG_PACKAGE_autosamba-samba4=y # CONFIG_PACKAGE_luci-app-accesscontrol is not set # CONFIG_PACKAGE_luci-app-adbyby-plus is not set CONFIG_PACKAGE_luci-app-adguardhome=y CONFIG_PACKAGE_luci-app-advanced=y # CONFIG_PACKAGE_luci-app-autotimeset=n CONFIG_PACKAGE_luci-app-rebootschedule=y # CONFIG_PACKAGE_luci-app-autoreboot is not set # CONFIG_PACKAGE_luci-app-control-timewol=n CONFIG_PACKAGE_luci-app-control-weburl=y # CONFIG_PACKAGE_luci-app-control-webrestriction=n CONFIG_PACKAGE_luci-app-control-speedlimit=y CONFIG_PACKAGE_luci-app-timecontrol=y # CONFIG_PACKAGE_luci-app-webadmin=n # CONFIG_PACKAGE_luci-app-cpulimit=n CONFIG_PACKAGE_luci-app-diskman=y CONFIG_PACKAGE_luci-app-diskman_INCLUDE_mdadm=y # CONFIG_PACKAGE_luci-app-eqos=n # CONFIG_PACKAGE_luci-app-filetransfer is not set # CONFIG_PACKAGE_luci-app-hd-idle=n CONFIG_PACKAGE_luci-app-jd-dailybonus=y CONFIG_PACKAGE_luci-app-koolproxyR=n CONFIG_PACKAGE_luci-app-netdata=y CONFIG_PACKAGE_luci-app-onliner=n CONFIG_PACKAGE_luci-app-openclash=y # CONFIG_PACKAGE_luci-app-samba is not set CONFIG_PACKAGE_luci-app-samba4=y CONFIG_PACKAGE_luci-app-serverchan=n # CONFIG_PACKAGE_luci-app-sfe is not set # CONFIG_PACKAGE_luci-app-flowoffload is not set CONFIG_PACKAGE_luci-app-smartdns=y CONFIG_PACKAGE_luci-app-passwall=y CONFIG_PACKAGE_luci-app-passwall_INCLUDE_Brook=y CONFIG_PACKAGE_luci-app-passwall_INCLUDE_ChinaDNS_NG=y CONFIG_PACKAGE_luci-app-passwall_INCLUDE_Dns2socks=y CONFIG_PACKAGE_luci-app-passwall_INCLUDE_Haproxy=y CONFIG_PACKAGE_luci-app-passwall_INCLUDE_Kcptun=y CONFIG_PACKAGE_luci-app-passwall_INCLUDE_NaiveProxy=y CONFIG_PACKAGE_luci-app-passwall_INCLUDE_PDNSD=y CONFIG_PACKAGE_luci-app-passwall_INCLUDE_Shadowsocks_Libev_Client=y CONFIG_PACKAGE_luci-app-passwall_INCLUDE_Shadowsocks_Libev_Server=y # CONFIG_PACKAGE_luci-app-passwall_INCLUDE_Shadowsocks_Rust_Client is not set CONFIG_PACKAGE_luci-app-passwall_INCLUDE_ShadowsocksR_Libev_Client=y CONFIG_PACKAGE_luci-app-passwall_INCLUDE_ShadowsocksR_Libev_Server=y CONFIG_PACKAGE_luci-app-passwall_INCLUDE_Simple_Obfs=y CONFIG_PACKAGE_luci-app-passwall_INCLUDE_Trojan_GO=y CONFIG_PACKAGE_luci-app-passwall_INCLUDE_Trojan_Plus=y CONFIG_PACKAGE_luci-app-passwall_INCLUDE_V2ray_Plugin=y CONFIG_PACKAGE_luci-app-passwall_INCLUDE_Xray=y # CONFIG_PACKAGE_luci-app-ssr-plus is not set CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_Kcptun=y CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_NaiveProxy=y CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_Redsocks2=y CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_Shadowsocks_Libev_Client=y CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_Shadowsocks_Libev_Server=y # CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_Shadowsocks_Rust_Client is not set # CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_Shadowsocks_Rust_Server is not set CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_ShadowsocksR_Libev_Client=y CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_ShadowsocksR_Libev_Server=y CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_Simple_Obfs=y CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_Trojan=y CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_V2ray_Plugin=y CONFIG_PACKAGE_luci-app-ssr-plus_INCLUDE_Xray=y CONFIG_PACKAGE_luci-app-ttyd=y CONFIG_PACKAGE_luci-app-turboacc=y # CONFIG_PACKAGE_luci-app-turboacc_INCLUDE_flow-offload=n # CONFIG_PACKAGE_luci-app-turboacc_INCLUDE_shortcut-fe=y CONFIG_PACKAGE_luci-app-vssr=y CONFIG_PACKAGE_luci-app-wrtbwmon=y CONFIG_PACKAGE_luci-app-nlbwmon=y CONFIG_PACKAGE_luci-app-netspeedtest=y CONFIG_PACKAGE_luci-app-dnsto=n CONFIG_PACKAGE_luci-app-bypass=n CONFIG_PACKAGE_luci-app-dnsfilter=y CONFIG_PACKAGE_luci-app-kodexplorer=n CONFIG_PACKAGE_luci-app-uhttpd=n CONFIG_PACKAGE_luci-app-mentohust=n CONFIG_PACKAGE_luci-app-easymesh=n CONFIG_PACKAGE_luci-app-wifimac=y CONFIG_PACKAGE_luci-app-ssrpro=y CONFIG_PACKAGE_luci-app-ssrpro_INCLUDE_Kcptun=y CONFIG_PACKAGE_luci-app-ssrpro_INCLUDE_NaiveProxy=y CONFIG_PACKAGE_luci-app-ssrpro_INCLUDE_Redsocks2=y CONFIG_PACKAGE_luci-app-ssrpro_INCLUDE_Shadowsocks_Libev_Client=y CONFIG_PACKAGE_luci-app-ssrpro_INCLUDE_Shadowsocks_Libev_Server=y CONFIG_PACKAGE_luci-app-ssrpro_INCLUDE_ShadowsocksR_Libev_Client=y CONFIG_PACKAGE_luci-app-ssrpro_INCLUDE_ShadowsocksR_Libev_Server=y CONFIG_PACKAGE_luci-app-ssrpro_INCLUDE_Simple_Obfs=y CONFIG_PACKAGE_luci-app-ssrpro_INCLUDE_Trojan=y CONFIG_PACKAGE_luci-app-ssrpro_INCLUDE_V2ray_Plugin=y CONFIG_PACKAGE_luci-app-ssrpro_INCLUDE_Xray=y CONFIG_PACKAGE_luci-app-ttnode=n CONFIG_PACKAGE_luci-app-adblock-plus=n # CONFIG_PACKAGE_luci-app-vsftpd is not set #主题 CONFIG_PACKAGE_luci-theme-argon_new=n CONFIG_PACKAGE_luci-theme-btmod=n CONFIG_PACKAGE_luci-theme-opentomcat=n CONFIG_PACKAGE_luci-theme-opentopd=n CONFIG_PACKAGE_luci-theme-chuqitopd=y CONFIG_PACKAGE_luci-theme-ffpdboy=n #增加其它插件 CONFIG_PACKAGE_luci-app-ksmbd=n CONFIG_PACKAGE_luci-app-cifsd=n CONFIG_PACKAGE_luci-app-cifs-mount=n # CONFIG_PACKAGE_luci-app-xlnetacc is not set CONFIG_PACKAGE_luci-app-zerotier=y CONFIG_PACKAGE_luci-app-unblockneteasemusic=y CONFIG_PACKAGE_luci-app-unblockmusic=y CONFIG_UnblockNeteaseMusic_Go=y CONFIG_UnblockNeteaseMusic_NodeJS=y CONFIG_PACKAGE_luci-app-mwan3=y # CONFIG_PACKAGE_luci-app-minidlna is not set CONFIG_PACKAGE_luci-app-rclone=n CONFIG_PACKAGE_luci-app-rclone_INCLUDE_fuse-utils=n CONFIG_PACKAGE_luci-app-rclone_INCLUDE_rclone-ng=n CONFIG_PACKAGE_luci-app-rclone_INCLUDE_rclone-webui=n CONFIG_PACKAGE_luci-app-pptp-server=y CONFIG_PACKAGE_luci-app-pppoe-server=n CONFIG_PACKAGE_luci-app-ipsec-vpnd=y CONFIG_PACKAGE_luci-app-ipsec-serve=n CONFIG_PACKAGE_luci-app-ipsec-vpnserver-manyusers=n CONFIG_PACKAGE_luci-app-docker=n CONFIG_PACKAGE_luci-app-dockerman=n CONFIG_PACKAGE_luci-app-koolddns=n CONFIG_PACKAGE_luci-app-syncdial=y CONFIG_PACKAGE_luci-app-softethervpn=y CONFIG_PACKAGE_luci-app-uugamebooster=n CONFIG_DEFAULT_luci-app-cpufreq=n CONFIG_PACKAGE_luci-app-udpxy=n CONFIG_PACKAGE_luci-app-socat=n CONFIG_PACKAGE_luci-app-oaf=n CONFIG_PACKAGE_luci-app-transmission=n CONFIG_PACKAGE_luci-app-usb-printer=n CONFIG_PACKAGE_luci-app-mwan3helper=n CONFIG_PACKAGE_luci-app-qbittorrent=n CONFIG_PACKAGE_luci-app-familycloud=n CONFIG_PACKAGE_luci-app-nps=n CONFIG_PACKAGE_luci-app-frpc=n #CONFIG_PACKAGE_luci-app-nfs=n CONFIG_PACKAGE_luci-app-openvpn-server=n CONFIG_PACKAGE_luci-app-aria2=n CONFIG_PACKAGE_luci-app-openvpn=n #network # CONFIG_PACKAGE_r8169-firmware=y CONFIG_PACKAGE_bnx2x-firmware=y CONFIG_PACKAGE_e100-firmware=y CONFIG_PACKAGE_kmod-3c59x=y CONFIG_PACKAGE_kmod-atl1=y CONFIG_PACKAGE_kmod-atl1c=y CONFIG_PACKAGE_kmod-atl1e=y CONFIG_PACKAGE_kmod-atl2=y CONFIG_PACKAGE_kmod-atm=y CONFIG_PACKAGE_kmod-b44=y CONFIG_PACKAGE_kmod-be2net=y CONFIG_PACKAGE_kmod-bnx2x=y CONFIG_PACKAGE_kmod-dm9000=y CONFIG_PACKAGE_kmod-dummy=y CONFIG_PACKAGE_kmod-e100=y CONFIG_PACKAGE_kmod-et131x=y CONFIG_PACKAGE_kmod-ethoc=y CONFIG_PACKAGE_kmod-hfcmulti=y CONFIG_PACKAGE_kmod-hfcpci=y CONFIG_PACKAGE_kmod-iavf=y CONFIG_PACKAGE_kmod-ixgbevf=y CONFIG_PACKAGE_kmod-lib-crc32c=y CONFIG_PACKAGE_kmod-mdio-gpio=y CONFIG_PACKAGE_kmod-misdn=y CONFIG_PACKAGE_kmod-natsemi=y CONFIG_PACKAGE_kmod-ne2k-pci=y CONFIG_PACKAGE_kmod-niu=y CONFIG_PACKAGE_kmod-of-mdio=y CONFIG_PACKAGE_kmod-phy-bcm84881=y CONFIG_PACKAGE_kmod-phy-broadcom=y CONFIG_PACKAGE_kmod-phy-realtek=y CONFIG_PACKAGE_kmod-phylib-broadcom=y CONFIG_PACKAGE_kmod-phylink=y # CONFIG_PACKAGE_kmod-r8169=n CONFIG_PACKAGE_kmod-random-core=y CONFIG_PACKAGE_kmod-sfp=y CONFIG_PACKAGE_kmod-siit=y CONFIG_PACKAGE_kmod-sis190=y CONFIG_PACKAGE_kmod-sis900=y CONFIG_PACKAGE_kmod-skge=y CONFIG_PACKAGE_kmod-sky2=y CONFIG_PACKAGE_kmod-solos-pci=y CONFIG_PACKAGE_kmod-spi-ks8995=y CONFIG_PACKAGE_kmod-ssb=y CONFIG_PACKAGE_kmod-swconfig=y CONFIG_PACKAGE_kmod-switch-bcm53xx=y CONFIG_PACKAGE_kmod-switch-bcm53xx-mdio=y CONFIG_PACKAGE_kmod-switch-ip17xx=y CONFIG_PACKAGE_kmod-switch-mvsw61xx=y CONFIG_PACKAGE_kmod-switch-rtl8306=y CONFIG_PACKAGE_kmod-switch-rtl8366-smi=y CONFIG_PACKAGE_kmod-switch-rtl8366rb=y CONFIG_PACKAGE_kmod-switch-rtl8366s=y CONFIG_PACKAGE_kmod-switch-rtl8367b=y CONFIG_PACKAGE_kmod-usb-atm=y CONFIG_PACKAGE_kmod-usb-atm-cxacru=y CONFIG_PACKAGE_kmod-usb-atm-speedtouch=y CONFIG_PACKAGE_kmod-usb-atm-ueagle=y CONFIG_PACKAGE_kmod-usb-cm109=y CONFIG_PACKAGE_kmod-usb-dwc2=y CONFIG_PACKAGE_kmod-usb-dwc3=y CONFIG_PACKAGE_kmod-usb-ehci=y CONFIG_PACKAGE_kmod-usb-ledtrig-usbport=y CONFIG_PACKAGE_kmod-usb-net-cdc-eem=y CONFIG_PACKAGE_kmod-usb-net-cdc-mbim=y CONFIG_PACKAGE_kmod-usb-net-cdc-ncm=y CONFIG_PACKAGE_kmod-usb-net-cdc-subset=y CONFIG_PACKAGE_kmod-usb-net-dm9601-ether=y CONFIG_PACKAGE_kmod-usb-net-hso=y CONFIG_PACKAGE_kmod-usb-net-huawei-cdc-ncm=y CONFIG_PACKAGE_kmod-usb-net-kalmia=y CONFIG_PACKAGE_kmod-usb-net-kaweth=y CONFIG_PACKAGE_kmod-usb-net-mcs7830=y CONFIG_PACKAGE_kmod-usb-net-pegasus=y CONFIG_PACKAGE_kmod-usb-net-pl=y CONFIG_PACKAGE_kmod-usb-net-qmi-wwan=y CONFIG_PACKAGE_kmod-usb-net-sierrawireless=y CONFIG_PACKAGE_kmod-usb-net-smsc95xx=y CONFIG_PACKAGE_kmod-usb-net-sr9700=y CONFIG_PACKAGE_kmod-usb-ohci=y CONFIG_PACKAGE_kmod-usb-ohci-pci=y CONFIG_PACKAGE_kmod-usb-uhci=y CONFIG_PACKAGE_kmod-usb-wdm=y CONFIG_PACKAGE_kmod-usb-yealink=y CONFIG_PACKAGE_kmod-usbip=y CONFIG_PACKAGE_kmod-usbip-client=y CONFIG_PACKAGE_kmod-usbip-server=y CONFIG_PACKAGE_kmod-usbmon=y CONFIG_PACKAGE_kmod-via-rhine=y CONFIG_PACKAGE_kmod-via-velocity=y #add drive CONFIG_PACKAGE_kmod-usb-net-rtl8150=y CONFIG_PACKAGE_kmod-usb-storage=y # Block Devices 挂载硬盘支持 CONFIG_PACKAGE_kmod-ata-core=y CONFIG_PACKAGE_kmod-block2mtd=y CONFIG_PACKAGE_kmod-scsi-core=y CONFIG_PACKAGE_kmod-scsi-generic=y CONFIG_PACKAGE_blockd=y CONFIG_PACKAGE_kmod-ata-ahci=y CONFIG_PACKAGE_kmod-ata-artop=y CONFIG_PACKAGE_kmod-ata-marvell-sata=y CONFIG_PACKAGE_kmod-ata-nvidia-sata=y CONFIG_PACKAGE_kmod-ata-pdc202xx-old=y CONFIG_PACKAGE_kmod-ata-piix=y CONFIG_PACKAGE_kmod-ata-sil=y CONFIG_PACKAGE_kmod-ata-sil24=y CONFIG_PACKAGE_kmod-ata-via-sata=y CONFIG_PACKAGE_kmod-dax=y CONFIG_PACKAGE_kmod-dm-raid=y CONFIG_PACKAGE_kmod-fs-autofs4=y CONFIG_PACKAGE_kmod-lib-crc32c=y CONFIG_PACKAGE_kmod-lib-raid6=y CONFIG_PACKAGE_kmod-lib-xor=y CONFIG_PACKAGE_kmod-md-mod=y CONFIG_PACKAGE_kmod-md-raid0=y CONFIG_PACKAGE_kmod-md-raid1=y CONFIG_PACKAGE_kmod-md-raid10=y CONFIG_PACKAGE_kmod-md-raid456=y #3G/4G Support CONFIG_PACKAGE_kmod-usb-serial=y CONFIG_PACKAGE_kmod-usb-serial-option=y CONFIG_PACKAGE_kmod-usb-serial-wwan=y CONFIG_PACKAGE_kmod-mii=y CONFIG_PACKAGE_kmod-usb-acm=y # docker # CONFIG_PACKAGE_kmod-fs-btrfs=y # CONFIG_PACKAGE_kmod-dm=y # CONFIG_PACKAGE_kmod-br-netfilter=y # CONFIG_PACKAGE_kmod-ikconfig=y # CONFIG_PACKAGE_kmod-nf-conntrack-netlink=y # CONFIG_PACKAGE_kmod-nf-ipvs=y # CONFIG_PACKAGE_kmod-veth=y # CONFIG_PACKAGE_kmod-dummy=y
db97822a53bc660cabc59bf2031241e384666857
367134ba5a65885e863bdc4507601606690974c1
/src/topology/continuous_map.lean
e55e30cc063b803cc546229c33aad2cb190e1bb1
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
2,361
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Nicolò Cavalleri. -/ import topology.subset_properties import topology.tactic /-! # Continuous bundled map In this file we define the type `continuous_map` of continuous bundled maps. -/ /-- Bundled continuous maps. -/ @[protect_proj] structure continuous_map (α : Type*) (β : Type*) [topological_space α] [topological_space β] := (to_fun : α → β) (continuous_to_fun : continuous to_fun . tactic.interactive.continuity') notation `C(` α `, ` β `)` := continuous_map α β namespace continuous_map attribute [continuity] continuous_map.continuous_to_fun variables {α : Type*} {β : Type*} {γ : Type*} variables [topological_space α] [topological_space β] [topological_space γ] instance : has_coe_to_fun (C(α, β)) := ⟨_, continuous_map.to_fun⟩ @[simp] lemma to_fun_eq_coe {f : C(α, β)} : f.to_fun = (f : α → β) := rfl variables {α β} {f g : continuous_map α β} protected lemma continuous (f : C(α, β)) : continuous f := f.continuous_to_fun @[continuity] lemma coe_continuous : continuous (f : α → β) := f.continuous_to_fun @[ext] theorem ext (H : ∀ x, f x = g x) : f = g := by cases f; cases g; congr'; exact funext H instance [inhabited β] : inhabited C(α, β) := ⟨{ to_fun := λ _, default _, }⟩ lemma coe_inj ⦃f g : C(α, β)⦄ (h : (f : α → β) = g) : f = g := by cases f; cases g; cases h; refl @[simp] lemma coe_mk (f : α → β) (h : continuous f) : ⇑(⟨f, h⟩ : continuous_map α β) = f := rfl /-- The identity as a continuous map. -/ def id : C(α, α) := ⟨id⟩ @[simp] lemma id_coe : (id : α → α) = id := rfl lemma id_apply (a : α) : id a = a := rfl /-- The composition of continuous maps, as a continuous map. -/ def comp (f : C(β, γ)) (g : C(α, β)) : C(α, γ) := ⟨f ∘ g⟩ @[simp] lemma comp_coe (f : C(β, γ)) (g : C(α, β)) : (comp f g : α → γ) = f ∘ g := rfl lemma comp_apply (f : C(β, γ)) (g : C(α, β)) (a : α) : comp f g a = f (g a) := rfl /-- Constant map as a continuous map -/ def const (b : β) : C(α, β) := ⟨λ x, b⟩ @[simp] lemma const_coe (b : β) : (const b : α → β) = (λ x, b) := rfl lemma const_apply (b : β) (a : α) : const b a = b := rfl end continuous_map
ee3b540df6d0c80d7d32bc987101c228a150d9b2
c777c32c8e484e195053731103c5e52af26a25d1
/archive/sensitivity.lean
c2c46c393fd7923640cfe0591c007982c7c2d89e
[ "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
15,705
lean
/- Copyright (c) 2019 Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis, Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis, Patrick Massot -/ import tactic.fin_cases import tactic.apply_fun import linear_algebra.finite_dimensional import linear_algebra.dual import analysis.normed_space.basic import data.real.sqrt /-! # Huang's sensitivity theorem A formalization of Hao Huang's sensitivity theorem: in the hypercube of dimension n ≥ 1, if one colors more than half the vertices then at least one vertex has at least √n colored neighbors. A fun summer collaboration by Reid Barton, Johan Commelin, Jesse Han, Chris Hughes, Robert Y. Lewis, and Patrick Massot, based on Don Knuth's account of the story (https://www.cs.stanford.edu/~knuth/papers/huang.pdf), using the Lean theorem prover (https://leanprover.github.io/), by Leonardo de Moura at Microsoft Research, and his collaborators (https://leanprover.github.io/people/), and using Lean's user maintained mathematics library (https://github.com/leanprover-community/mathlib). The project was developed at https://github.com/leanprover-community/lean-sensitivity and is now archived at https://github.com/leanprover-community/mathlib/blob/master/archive/sensitivity.lean -/ /-! The next two lines assert we do not want to give a constructive proof, but rather use classical logic. -/ noncomputable theory open_locale classical /-! We also want to use the notation `∑` for sums. -/ open_locale big_operators notation `√` := real.sqrt open function bool linear_map fintype finite_dimensional module.dual_bases /-! ### The hypercube Notations: - `ℕ` denotes natural numbers (including zero). - `fin n` = {0, ⋯ , n - 1}. - `bool` = {`tt`, `ff`}. -/ /-- The hypercube in dimension `n`. -/ @[derive [inhabited, fintype]] def Q (n : ℕ) := fin n → bool /-- The projection from `Q (n + 1)` to `Q n` forgetting the first value (ie. the image of zero). -/ def π {n : ℕ} : Q (n + 1) → Q n := λ p, p ∘ fin.succ namespace Q /-! `n` will always denote a natural number. -/ variable (n : ℕ) /-- `Q 0` has a unique element. -/ instance : unique (Q 0) := ⟨⟨λ _, tt⟩, by { intro, ext x, fin_cases x }⟩ /-- `Q n` has 2^n elements. -/ lemma card : card (Q n) = 2^n := by simp [Q] /-! Until the end of this namespace, `n` will be an implicit argument (still a natural number). -/ variable {n} lemma succ_n_eq (p q : Q (n+1)) : p = q ↔ (p 0 = q 0 ∧ π p = π q) := begin split, { rintro rfl, exact ⟨rfl, rfl⟩, }, { rintros ⟨h₀, h⟩, ext x, by_cases hx : x = 0, { rwa hx }, { rw ← fin.succ_pred x hx, convert congr_fun h (fin.pred x hx) } } end /-- The adjacency relation defining the graph structure on `Q n`: `p.adjacent q` if there is an edge from `p` to `q` in `Q n`. -/ def adjacent {n : ℕ} (p : Q n) : set (Q n) := λ q, ∃! i, p i ≠ q i /-- In `Q 0`, no two vertices are adjacent. -/ lemma not_adjacent_zero (p q : Q 0) : ¬ p.adjacent q := by rintros ⟨v, _⟩; apply fin_zero_elim v /-- If `p` and `q` in `Q (n+1)` have different values at zero then they are adjacent iff their projections to `Q n` are equal. -/ lemma adj_iff_proj_eq {p q : Q (n+1)} (h₀ : p 0 ≠ q 0) : p.adjacent q ↔ π p = π q := begin split, { rintros ⟨i, h_eq, h_uni⟩, ext x, by_contradiction hx, apply fin.succ_ne_zero x, rw [h_uni _ hx, h_uni _ h₀] }, { intro heq, use [0, h₀], intros y hy, contrapose! hy, rw ←fin.succ_pred _ hy, apply congr_fun heq } end /-- If `p` and `q` in `Q (n+1)` have the same value at zero then they are adjacent iff their projections to `Q n` are adjacent. -/ lemma adj_iff_proj_adj {p q : Q (n+1)} (h₀ : p 0 = q 0) : p.adjacent q ↔ (π p).adjacent (π q) := begin split, { rintros ⟨i, h_eq, h_uni⟩, have h_i : i ≠ 0, from λ h_i, absurd h₀ (by rwa h_i at h_eq), use [i.pred h_i, show p (fin.succ (fin.pred i _)) ≠ q (fin.succ (fin.pred i _)), by rwa fin.succ_pred], intros y hy, simp [eq.symm (h_uni _ hy)] }, { rintros ⟨i, h_eq, h_uni⟩, use [i.succ, h_eq], intros y hy, rw [←fin.pred_inj, fin.pred_succ], { apply h_uni, change p (fin.pred _ _).succ ≠ q (fin.pred _ _).succ, simp [hy] }, { contrapose! hy, rw [hy, h₀] }, { apply fin.succ_ne_zero } } end @[symm] lemma adjacent.symm {p q : Q n} : p.adjacent q ↔ q.adjacent p := by simp only [adjacent, ne_comm] end Q /-! ### The vector space -/ /-- The free vector space on vertices of a hypercube, defined inductively. -/ def V : ℕ → Type | 0 := ℝ | (n+1) := V n × V n namespace V variables (n : ℕ) /-! `V n` is a real vector space whose equality relation is computable. -/ instance : decidable_eq (V n) := by { induction n ; { dunfold V, resetI, apply_instance } } instance : add_comm_group (V n) := by { induction n ; { dunfold V, resetI, apply_instance } } instance : module ℝ (V n) := by { induction n ; { dunfold V, resetI, apply_instance } } end V /-- The basis of `V` indexed by the hypercube, defined inductively. -/ noncomputable def e : Π {n}, Q n → V n | 0 := λ _, (1:ℝ) | (n+1) := λ x, cond (x 0) (e (π x), 0) (0, e (π x)) @[simp] lemma e_zero_apply (x : Q 0) : e x = (1 : ℝ) := rfl /-- The dual basis to `e`, defined inductively. -/ noncomputable def ε : Π {n : ℕ} (p : Q n), V n →ₗ[ℝ] ℝ | 0 _ := linear_map.id | (n+1) p := cond (p 0) ((ε $ π p).comp $ linear_map.fst _ _ _) ((ε $ π p).comp $ linear_map.snd _ _ _) variable {n : ℕ} lemma duality (p q : Q n) : ε p (e q) = if p = q then 1 else 0 := begin induction n with n IH, { rw (show p = q, from subsingleton.elim p q), dsimp [ε, e], simp }, { dsimp [ε, e], cases hp : p 0 ; cases hq : q 0, all_goals { repeat {rw cond_tt}, repeat {rw cond_ff}, simp only [linear_map.fst_apply, linear_map.snd_apply, linear_map.comp_apply, IH], try { congr' 1, rw Q.succ_n_eq, finish }, try { erw (ε _).map_zero, have : p ≠ q, { intro h, rw p.succ_n_eq q at h, finish }, simp [this] } } } end /-- Any vector in `V n` annihilated by all `ε p`'s is zero. -/ lemma epsilon_total {v : V n} (h : ∀ p : Q n, (ε p) v = 0) : v = 0 := begin induction n with n ih, { dsimp [ε] at h, exact h (λ _, tt) }, { cases v with v₁ v₂, ext ; change _ = (0 : V n) ; simp only ; apply ih ; intro p ; [ let q : Q (n+1) := λ i, if h : i = 0 then tt else p (i.pred h), let q : Q (n+1) := λ i, if h : i = 0 then ff else p (i.pred h)], all_goals { specialize h q, rw [ε, show q 0 = tt, from rfl, cond_tt] at h <|> rw [ε, show q 0 = ff, from rfl, cond_ff] at h, rwa show p = π q, by { ext, simp [q, fin.succ_ne_zero, π] } } } end open module /-- `e` and `ε` are dual families of vectors. It implies that `e` is indeed a basis and `ε` computes coefficients of decompositions of vectors on that basis. -/ def dual_bases_e_ε (n : ℕ) : dual_bases (@e n) (@ε n) := { eval := duality, total := @epsilon_total _ } /-! We will now derive the dimension of `V`, first as a cardinal in `dim_V` and, since this cardinal is finite, as a natural number in `finrank_V` -/ lemma dim_V : module.rank ℝ (V n) = 2^n := have module.rank ℝ (V n) = (2^n : ℕ), by { rw [rank_eq_card_basis (dual_bases_e_ε _).basis, Q.card]; apply_instance }, by assumption_mod_cast instance : finite_dimensional ℝ (V n) := finite_dimensional.of_fintype_basis (dual_bases_e_ε _).basis lemma finrank_V : finrank ℝ (V n) = 2^n := have _ := @dim_V n, by rw ←finrank_eq_rank at this; assumption_mod_cast /-! ### The linear map -/ /-- The linear operator $f_n$ corresponding to Huang's matrix $A_n$, defined inductively as a ℝ-linear map from `V n` to `V n`. -/ noncomputable def f : Π n, V n →ₗ[ℝ] V n | 0 := 0 | (n+1) := linear_map.prod (linear_map.coprod (f n) linear_map.id) (linear_map.coprod linear_map.id (-f n)) /-! The preceding definition uses linear map constructions to automatically get that `f` is linear, but its values are somewhat buried as a side-effect. The next two lemmas unbury them. -/ @[simp] lemma f_zero : f 0 = 0 := rfl lemma f_succ_apply (v : V (n+1)) : f (n+1) v = (f n v.1 + v.2, v.1 - f n v.2) := begin cases v, rw f, simp only [linear_map.id_apply, linear_map.prod_apply, pi.prod, prod.mk.inj_iff, linear_map.neg_apply, sub_eq_add_neg, linear_map.coprod_apply], exact ⟨rfl, rfl⟩ end /-! In the next statement, the explicit conversion `(n : ℝ)` of `n` to a real number is necessary since otherwise `n • v` refers to the multiplication defined using only the addition of `V`. -/ lemma f_squared : ∀ v : V n, (f n) (f n v) = (n : ℝ) • v := begin induction n with n IH; intro, { simpa only [nat.cast_zero, zero_smul] }, { cases v, simp [f_succ_apply, IH, add_smul, add_assoc], abel } end /-! We now compute the matrix of `f` in the `e` basis (`p` is the line index, `q` the column index). -/ lemma f_matrix : ∀ p q : Q n, |ε q (f n (e p))| = if q.adjacent p then 1 else 0 := begin induction n with n IH, { intros p q, dsimp [f], simp [Q.not_adjacent_zero] }, { intros p q, have ite_nonneg : ite (π q = π p) (1 : ℝ) 0 ≥ 0, { split_ifs ; norm_num }, have f_map_zero := (show (V (n+0)) →ₗ[ℝ] (V n), from f n).map_zero, dsimp [e, ε, f], cases hp : p 0 ; cases hq : q 0, all_goals { repeat {rw cond_tt}, repeat {rw cond_ff}, simp [f_map_zero, hp, hq, IH, duality, abs_of_nonneg ite_nonneg, Q.adj_iff_proj_eq, Q.adj_iff_proj_adj] } } end /-- The linear operator $g_m$ corresponding to Knuth's matrix $B_m$. -/ noncomputable def g (m : ℕ) : V m →ₗ[ℝ] V (m+1) := linear_map.prod (f m + √(m+1) • linear_map.id) linear_map.id /-! In the following lemmas, `m` will denote a natural number. -/ variables {m : ℕ} /-! Again we unpack what are the values of `g`. -/ lemma g_apply : ∀ v, g m v = (f m v + √(m+1) • v, v) := by delta g; simp lemma g_injective : injective (g m) := begin rw g, intros x₁ x₂ h, simp only [linear_map.prod_apply, linear_map.id_apply, prod.mk.inj_iff, pi.prod] at h, exact h.right end lemma f_image_g (w : V (m + 1)) (hv : ∃ v, g m v = w) : f (m + 1) w = √(m + 1) • w := begin rcases hv with ⟨v, rfl⟩, have : √(m+1) * √(m+1) = m+1 := real.mul_self_sqrt (by exact_mod_cast zero_le _), simp [this, f_succ_apply, g_apply, f_squared, smul_add, add_smul, smul_smul], abel end /-! ### The main proof In this section, in order to enforce that `n` is positive, we write it as `m + 1` for some natural number `m`. -/ /-! `dim X` will denote the dimension of a subspace `X` as a cardinal. -/ notation `dim ` X:70 := module.rank ℝ ↥X /-! `fdim X` will denote the (finite) dimension of a subspace `X` as a natural number. -/ notation `fdim` := finrank ℝ /-! `Span S` will denote the ℝ-subspace spanned by `S`. -/ notation `Span` := submodule.span ℝ /-! `Card X` will denote the cardinal of a subset of a finite type, as a natural number. -/ notation `Card ` X:70 := X.to_finset.card /-! In the following, `⊓` and `⊔` will denote intersection and sums of ℝ-subspaces, equipped with their subspace structures. The notations come from the general theory of lattices, with inf and sup (also known as meet and join). -/ /-- If a subset `H` of `Q (m+1)` has cardinal at least `2^m + 1` then the subspace of `V (m+1)` spanned by the corresponding basis vectors non-trivially intersects the range of `g m`. -/ lemma exists_eigenvalue (H : set (Q (m + 1))) (hH : Card H ≥ 2^m + 1) : ∃ y ∈ Span (e '' H) ⊓ (g m).range, y ≠ (0 : _) := begin let W := Span (e '' H), let img := (g m).range, suffices : 0 < dim (W ⊓ img), { simp only [exists_prop], exact_mod_cast exists_mem_ne_zero_of_rank_pos this }, have dim_le : dim (W ⊔ img) ≤ 2^(m + 1), { convert ← rank_submodule_le (W ⊔ img), apply dim_V }, have dim_add : dim (W ⊔ img) + dim (W ⊓ img) = dim W + 2^m, { convert ← submodule.rank_sup_add_rank_inf_eq W img, rw ← rank_eq_of_injective (g m) g_injective, apply dim_V }, have dimW : dim W = card H, { have li : linear_independent ℝ (H.restrict e), { convert (dual_bases_e_ε _).basis.linear_independent.comp _ subtype.val_injective, rw (dual_bases_e_ε _).coe_basis }, have hdW := rank_span li, rw set.range_restrict at hdW, convert hdW, rw [← (dual_bases_e_ε _).coe_basis, cardinal.mk_image_eq (dual_bases_e_ε _).basis.injective, cardinal.mk_fintype] }, rw ← finrank_eq_rank ℝ at ⊢ dim_le dim_add dimW, rw [← finrank_eq_rank ℝ, ← finrank_eq_rank ℝ] at dim_add, norm_cast at ⊢ dim_le dim_add dimW, rw pow_succ' at dim_le, rw set.to_finset_card at hH, linarith end /-- **Huang sensitivity theorem** also known as the **Huang degree theorem** -/ theorem huang_degree_theorem (H : set (Q (m + 1))) (hH : Card H ≥ 2^m + 1) : ∃ q, q ∈ H ∧ √(m + 1) ≤ Card (H ∩ q.adjacent) := begin rcases exists_eigenvalue H hH with ⟨y, ⟨⟨y_mem_H, y_mem_g⟩, y_ne⟩⟩, have coeffs_support : ((dual_bases_e_ε (m+1)).coeffs y).support ⊆ H.to_finset, { intros p p_in, rw finsupp.mem_support_iff at p_in, rw set.mem_to_finset, exact (dual_bases_e_ε _).mem_of_mem_span y_mem_H p p_in }, obtain ⟨q, H_max⟩ : ∃ q : Q (m+1), ∀ q' : Q (m+1), |(ε q' : _) y| ≤ |ε q y|, from finite.exists_max _, have H_q_pos : 0 < |ε q y|, { contrapose! y_ne, exact epsilon_total (λ p, abs_nonpos_iff.mp (le_trans (H_max p) y_ne)) }, refine ⟨q, (dual_bases_e_ε _).mem_of_mem_span y_mem_H q (abs_pos.mp H_q_pos), _⟩, let s := √(m+1), suffices : s * |ε q y| ≤ ↑(_) * |ε q y|, from (mul_le_mul_right H_q_pos).mp ‹_›, let coeffs := (dual_bases_e_ε (m+1)).coeffs, calc s * |ε q y| = |ε q (s • y)| : by rw [map_smul, smul_eq_mul, abs_mul, abs_of_nonneg (real.sqrt_nonneg _)] ... = |ε q (f (m+1) y)| : by rw [← f_image_g y (by simpa using y_mem_g)] ... = |ε q (f (m+1) (lc _ (coeffs y)))| : by rw (dual_bases_e_ε _).lc_coeffs y ... = |(coeffs y).sum (λ (i : Q (m + 1)) (a : ℝ), a • ((ε q) ∘ (f (m + 1)) ∘ λ (i : Q (m + 1)), e i) i)| : by erw [(f $ m + 1).map_finsupp_total, (ε q).map_finsupp_total, finsupp.total_apply] ... ≤ ∑ p in (coeffs y).support, |(coeffs y p) * (ε q $ f (m+1) $ e p)| : norm_sum_le _ $ λ p, coeffs y p * _ ... = ∑ p in (coeffs y).support, |coeffs y p| * ite (q.adjacent p) 1 0 : by simp only [abs_mul, f_matrix] ... = ∑ p in (coeffs y).support.filter (Q.adjacent q), |coeffs y p| : by simp [finset.sum_filter] ... ≤ ∑ p in (coeffs y).support.filter (Q.adjacent q), |coeffs y q| : finset.sum_le_sum (λ p _, H_max p) ... = (((coeffs y).support.filter (Q.adjacent q)).card : ℝ) * |coeffs y q| : by rw [finset.sum_const, nsmul_eq_mul] ... = (((coeffs y).support ∩ (Q.adjacent q).to_finset).card : ℝ) * |coeffs y q| : by { congr' with x, simp, refl } ... ≤ (finset.card ((H ∩ Q.adjacent q).to_finset )) * |ε q y| : begin refine (mul_le_mul_right H_q_pos).2 _, norm_cast, apply finset.card_le_of_subset, rw set.to_finset_inter, convert finset.inter_subset_inter_right coeffs_support end end
89699a0c4bc410451ba12d18e9c4dcd36af86980
2d787ac9a5ab28a7d164cd13cee8a3cdc1e4680a
/src/my_exercises/02_iff_if_and.lean
ec2f91adf076a406f9817390d67aa564db22c9f6
[ "Apache-2.0" ]
permissive
paulzfm/lean3-tutorials
8c113ec2c9494d401c8a877f094db93e5a631fd6
f41baf1c62c251976ec8dd9ccae9e85ec4c4d336
refs/heads/master
1,679,267,488,532
1,614,782,461,000
1,614,782,461,000
344,157,026
0
0
null
null
null
null
UTF-8
Lean
false
false
15,114
lean
import data.real.basic /- In the previous file, we saw how to rewrite using equalities. The analogue operation with mathematical statements is rewriting using equivalences. This is also done using the `rw` tactic. Lean uses ↔ to denote equivalence instead of ⇔. In the following exercises we will use the lemma: sub_nonneg {x y : ℝ} : 0 ≤ y - x ↔ x ≤ y The curly braces around x and y instead of parentheses mean Lean will always try to figure out what x and y are from context, unless we really insist on telling it (we'll see how to insist much later). Let's not worry about that for now. In order to announce an intermediate statement we use: have my_name : my statement, This triggers the apparition of a new goal: proving the statement. After this is done, the statement becomes available under the name `my_name`. We can focus on the current goal by typing tactics between curly braces. -/ example {a b c : ℝ} (hab : a ≤ b) : c + a ≤ c + b := begin rw ← sub_nonneg, have key : (c + b) - (c + a) = b - a, -- Here we introduce an intermediate statement named key { ring, }, -- and prove it between curly braces rw key, -- we can now use the key statement rw sub_nonneg, exact hab, end /- Of course the previous lemma is already in the core library, named `add_le_add_left`, so we can use it below. Let's prove a variation (without invoking commutativity of addition since this would spoil our fun). -/ -- 0009 example {a b : ℝ} (hab : a ≤ b) (c : ℝ) : a + c ≤ b + c := begin rw ← sub_nonneg, have key : (b + c) - (a + c) = b - a, { ring, }, rw key, rw sub_nonneg, exact hab, end /- Let's see how we could use this lemma. It is already in the core library, under the name `add_le_add_right`: add_le_add_right {a b : ℝ} (hab : a ≤ b) (c : ℝ) : a + c ≤ b + c This can be read as: "add_le_add_right is a function that will take as input real numbers a and b, an assumption `hab` claiming a ≤ b and a real number c, and will output a proof of a + c ≤ b + c". In addition, recall that curly braces around a b mean Lean will figure out those arguments unless we insist to help. This is because they can be deduced from the next argument `hab`. So it will be sufficient to feed `hab` and c to this function. -/ example {a b : ℝ} (ha : 0 ≤ a) : b ≤ a + b := begin calc b = 0 + b : by ring ... ≤ a + b : by exact add_le_add_right ha b, end /- In the second line of the above proof, we need to prove 0 + b ≤ a + b. The proof after the colon says: this is exactly lemma `add_le_add_right` applied to ha and b. Actually the `calc` block expects proof terms, and the `by` keyword is used to tell Lean we will use tactics to build such a proof term. But since the only tactic used in this block is `exact`, we can skip tactics entirely, and write: -/ example (a b : ℝ) (ha : 0 ≤ a) : b ≤ a + b := begin calc b = 0 + b : by ring ... ≤ a + b : add_le_add_right ha b, end /- Let's do a variant. -/ -- 0010 example (a b : ℝ) (hb : 0 ≤ b) : a ≤ a + b := begin calc a = a + 0 : by ring ... ≤ a + b : add_le_add_left hb a, end /- The two preceding examples are in the core library : le_add_of_nonneg_left {a b : ℝ} (ha : 0 ≤ a) : b ≤ a + b le_add_of_nonneg_right {a b : ℝ} (hb : 0 ≤ b) : a ≤ a + b Again, there won't be any need to memorize those names, we will soon see how to get rid of such goals automatically. But we can already try to understand how their names are built: "le_add" describe the conclusion "less or equal than some addition" It comes first because we are focussed on proving stuff, and auto-completion works by looking at the beginning of words. "of" introduces assumptions. "nonneg" is Lean's abbreviation for non-negative. "left" or "right" disambiguates between the two variations. Let's use those lemmas by hand for now. Note that you can have several inequalities steps in a `calc` block, transitivity of inequalities will be used automatically to assemble the pieces. -/ -- 0011 example (a b : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b := begin calc 0 ≤ a : ha ... ≤ a + b : le_add_of_nonneg_right hb, end /- And let's combine with our earlier lemmas. -/ -- 0012 example (a b c d : ℝ) (hab : a ≤ b) (hcd : c ≤ d) : a + c ≤ b + d := begin calc a + c ≤ b + c : add_le_add_right hab c ... ≤ b + d : add_le_add_left hcd b, end /- In the above examples, we prepared proofs of assumptions of our lemmas beforehand, so that we could feed them to the lemmas. This is called forward reasonning. The `calc` proofs also belong to this category. We can also announce the use of a lemma, and provide proofs after the fact, using the `apply` tactic. This is called backward reasonning because we get the conclusion first, and provide proofs later. Using `rw` on the goal (rather than on an assumption from the local context) is also backward reasonning. Let's do that using the lemma mul_nonneg {x y : ℝ} (hx : 0 ≤ x) (hy : 0 ≤ y) : 0 ≤ x*y -/ example (a b c : ℝ) (hc : 0 ≤ c) (hab : a ≤ b) : a*c ≤ b*c := begin rw ← sub_nonneg, have key : b*c - a*c = (b - a)*c, { ring }, rw key, apply mul_nonneg, -- Here we don't provide proofs for the lemma's assumptions -- Now we need to provide the proofs. { rw sub_nonneg, exact hab }, { exact hc }, end /- Let's prove the same statement using only forward reasonning: announcing stuff, proving it by working with known facts, moving forward. -/ example (a b c : ℝ) (hc : 0 ≤ c) (hab : a ≤ b) : a*c ≤ b*c := begin have hab' : 0 ≤ b - a, { rw ← sub_nonneg at hab, exact hab, }, have h₁ : 0 ≤ (b - a)*c, { exact mul_nonneg hab' hc }, have h₂ : (b - a)*c = b*c - a*c, { ring, }, have h₃ : 0 ≤ b*c - a*c, { rw h₂ at h₁, exact h₁, }, rw sub_nonneg at h₃, exact h₃, end /- One reason why the backward reasoning proof is shorter is because Lean can infer of lot of things by comparing the goal and the lemma statement. Indeed in the `apply mul_nonneg` line, we didn't need to tell Lean that x = b - a and y = c in the lemma. It was infered by "unification" between the lemma statement and the goal. To be fair to the forward reasoning version, we should introduce a convenient variation on `rw`. The `rwa` tactic performs rewrite and then looks for an assumption matching the goal. We can use it to rewrite our latest proof as: -/ example (a b c : ℝ) (hc : 0 ≤ c) (hab : a ≤ b) : a*c ≤ b*c := begin have hab' : 0 ≤ b - a, { rwa ← sub_nonneg at hab, }, have h₁ : 0 ≤ (b - a)*c, { exact mul_nonneg hab' hc }, have h₂ : (b - a)*c = b*c - a*c, { ring, }, have h₃ : 0 ≤ b*c - a*c, { rwa h₂ at h₁, }, rwa sub_nonneg at h₃, end /- Let's now combine forward and backward reasonning, to get our most efficient proof of this statement. Note in particular how unification is used to know what to prove inside the parentheses in the `mul_nonneg` arguments. -/ example (a b c : ℝ) (hc : 0 ≤ c) (hab : a ≤ b) : a*c ≤ b*c := begin rw ← sub_nonneg, calc 0 ≤ (b - a)*c : mul_nonneg (by rwa sub_nonneg) hc ... = b*c - a*c : by ring, end /- Let's now practice all three styles using: mul_nonneg_of_nonpos_of_nonpos {a b : α} (ha : a ≤ 0) (hb : b ≤ 0) : 0 ≤ a * b sub_nonpos {a b : α} : a - b ≤ 0 ↔ a ≤ b -/ /- First using mostly backward reasonning -/ -- 0013 example (a b c : ℝ) (hc : c ≤ 0) (hab : a ≤ b) : b*c ≤ a*c := begin rw ← sub_nonneg, have h : a * c - b * c = (a - b) * c, { by ring }, rw h, apply mul_nonneg_of_nonpos_of_nonpos, { rw sub_nonpos, exact hab }, { exact hc }, end /- Using forward reasonning -/ -- 0014 example (a b c : ℝ) (hc : c ≤ 0) (hab : a ≤ b) : b*c ≤ a*c := begin have h₁ : a - b ≤ 0, { rw sub_nonpos, exact hab }, have h₂ : 0 ≤ (a - b) * c, from mul_nonneg_of_nonpos_of_nonpos h₁ hc, have h₃ : (a - b) * c = a * c - b * c, by ring, rw h₃ at h₂, rw sub_nonneg at h₂, exact h₂, end /-- Using a combination of both, with a `calc` block -/ -- 0015 example (a b c : ℝ) (hc : c ≤ 0) (hab : a ≤ b) : b*c ≤ a*c := begin rw ← sub_nonneg, rw ← sub_nonpos at hab, calc 0 ≤ (a - b) * c : mul_nonneg_of_nonpos_of_nonpos hab hc ... = a * c - b * c : by ring, end /- Let's now move to proving implications. Lean denotes implications using a simple arrow →, the same it uses for functions (say denoting the type of functions from ℕ to ℕ by ℕ → ℕ). This is because it sees a proof of P ⇒ Q as a function turning a proof of P into a proof Q. Many of the examples that we already met are implications under the hood. For instance we proved le_add_of_nonneg_left (a b : ℝ) (ha : 0 ≤ a) : b ≤ a + b But this can be rephrased as le_add_of_nonneg_left (a b : ℝ) : 0 ≤ a → b ≤ a + b In order to prove P → Q, we use the tactic `intros`, followed by an assumption name. This creates an assumption with that name asserting that P holds, and turns the goal into Q. Let's check we can go from our old version of `le_add_of_nonneg_left` to the new one. -/ example (a b : ℝ): 0 ≤ a → b ≤ a + b := begin intros ha, exact le_add_of_nonneg_left ha, end /- Actually Lean doesn't make any difference between those two versions. It is also happy with -/ example (a b : ℝ): 0 ≤ a → b ≤ a + b := le_add_of_nonneg_left /- No tactic state is shown in the above line because we don't even need to enter tactic mode using `begin` or `by`. Let's practise using `intros`. -/ -- 0016 example (a b : ℝ): 0 ≤ b → a ≤ a + b := begin intros hb, rw add_comm, exact le_add_of_nonneg_left hb, end /- What about lemmas having more than one assumption? For instance: add_nonneg {a b : ℝ} (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b A natural idea is to use the conjunction operator (logical AND), which Lean denotes by ∧. Assumptions built using this operator can be decomposed using the `cases` tactic, which is a very general assumption-decomposing tactic. -/ example {a b : ℝ} : (0 ≤ a ∧ 0 ≤ b) → 0 ≤ a + b := begin intros hyp, cases hyp with ha hb, exact add_nonneg ha hb, end /- Needing that intermediate line invoking `cases` shows this formulation is not what is used by Lean. It rather sees `add_nonneg` as two nested implications: if a is non-negative then if b is non-negative then a+b is non-negative. It reads funny, but it is much more convenient to use in practice. -/ example {a b : ℝ} : 0 ≤ a → (0 ≤ b → 0 ≤ a + b) := add_nonneg /- The above pattern is so common that implications are defined as right-associative operators, hence parentheses are not needed above. Let's prove that the naive conjunction version implies the funny Lean version. For this we need to know how to prove a conjunction. The `split` tactic creates two goals from a conjunction goal. It can also be used to create two implication goals from an equivalence goal. -/ example {a b : ℝ} (H : (0 ≤ a ∧ 0 ≤ b) → 0 ≤ a + b) : 0 ≤ a → (0 ≤ b → 0 ≤ a + b) := begin intros ha, intros hb, apply H, split, exact ha, exact hb, end /- Let's practice `cases` and `split`. In the next exercise, P, Q and R denote unspecified mathematical statements. -/ -- 0017 example (P Q R : Prop) : P ∧ Q → Q ∧ P := begin intros h, cases h with hP hQ, split, exact hQ, exact hP, end /- Of course using `split` only to be able to use `exact` twice in a row feels silly. One can also use the anonymous constructor syntax: ⟨ ⟩ Beware those are not parentheses but angle brackets. This is a generic way of providing compound objects to Lean when Lean already has a very clear idea of what it is waiting for. So we could have replaced the last three lines by: exact ⟨hQ, hP⟩ We can also combine the `intros` steps. We can now compress our earlier proof to: -/ example {a b : ℝ} (H : (0 ≤ a ∧ 0 ≤ b) → 0 ≤ a + b) : 0 ≤ a → (0 ≤ b → 0 ≤ a + b) := begin intros ha hb, exact H ⟨ha, hb⟩, end /- The anonymous contructor trick actually also works in `intros` provided we use its recursive version `rintros`. So we can replace intro h, cases h with h₁ h₂ by rintros ⟨h₁, h₂⟩, Now redo the previous exercise using all those compressing techniques, in exactly two lines. -/ -- 0018 example (P Q R : Prop): P ∧ Q → Q ∧ P := begin rintros ⟨hP, hQ⟩, exact ⟨hQ, hP⟩, end /- We are ready to come back to the equivalence between the different formulations of lemmas having two assumptions. Remember the `split` tactic can be used to split an equivalence into two implications. -/ -- 0019 example (P Q R : Prop) : (P ∧ Q → R) ↔ (P → (Q → R)) := begin split, { intros h hp hq, exact h ⟨hp, hq⟩, }, { rintros h ⟨hp, hq⟩, exact h hp hq } end /- If you used more than five lines in the above exercise then try to compress things (without simply removing line ends). One last compression technique: given a proof h of a conjunction P ∧ Q, one can get a proof of P using h.left and a proof of Q using h.right, without using cases. One can also use the more generic (but less legible) names h.1 and h.2. Similarly, given a proof h of P ↔ Q, one can get a proof of P → Q using h.mp and a proof of Q → P using h.mpr (or the generic h.1 and h.2 that are even less legible in this case). Before the final exercise in this file, let's make sure we'll be able to leave without learning 10 lemma names. The `linarith` tactic will prove any equality or inequality or contradiction that follows by linear combinations of assumptions from the context (with constant coefficients). -/ example (a b : ℝ) (hb : 0 ≤ b) : a ≤ a + b := begin linarith, end /- Now let's enjoy this for a while. -/ -- 0020 example (a b : ℝ) (ha : 0 ≤ a) (hb : 0 ≤ b) : 0 ≤ a + b := begin linarith, end /- And let's combine with our earlier lemmas. -/ -- 0021 example (a b c d : ℝ) (hab : a ≤ b) (hcd : c ≤ d) : a + c ≤ b + d := begin linarith, end /- Final exercise In the last exercise of this file, we will use the divisibility relation on ℕ, denoted by ∣ (beware this is a unicode divisibility bar, not the ASCII pipe character), and the gcd function. The definitions are the usual ones, but our goal is to avoid using these definitions and only use the following three lemmas: dvd_refl (a : ℕ) : a ∣ a dvd_antisymm {a b : ℕ} : a ∣ b → b ∣ a → a = b := dvd_gcd_iff {a b c : ℕ} : c ∣ gcd a b ↔ c ∣ a ∧ c ∣ b -/ -- All functions and lemmas below are about natural numbers. open nat -- 0022 example (a b : ℕ) : a ∣ b ↔ gcd a b = a := begin have h : gcd a b ∣ a ∧ gcd a b ∣ b, { rw ← dvd_gcd_iff, }, split, { intros hab, apply dvd_antisymm, { exact h.1, }, { rw dvd_gcd_iff, exact ⟨dvd_refl a, hab⟩, } }, { intros hab, rw ← hab, exact h.2, } end
f9f3bacb3eb747152f5310c88da7750a25c7eb62
3f7026ea8bef0825ca0339a275c03b911baef64d
/src/ring_theory/maps.lean
7364080b33884ab1422f6cd733ff3f1e7a0099db
[ "Apache-2.0" ]
permissive
rspencer01/mathlib
b1e3afa5c121362ef0881012cc116513ab09f18c
c7d36292c6b9234dc40143c16288932ae38fdc12
refs/heads/master
1,595,010,346,708
1,567,511,503,000
1,567,511,503,000
206,071,681
0
0
Apache-2.0
1,567,513,643,000
1,567,513,643,000
null
UTF-8
Lean
false
false
5,601
lean
/- Copyright (c) 2018 Andreas Swerdlow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Andreas Swerdlow, Kenny Lau -/ import data.equiv.algebra /-! # Ring antihomomorphisms, isomorphisms, antiisomorphisms and involutions This file defines ring antihomomorphisms, antiisomorphism and involutions and proves basic properties of them. ## Notations All types defined in this file are given a coercion to the underlying function. ## References * https://en.wikipedia.org/wiki/Antihomomorphism * https://en.wikipedia.org/wiki/Involution_(mathematics)#Ring_theory ## Tags Ring isomorphism, automorphism, antihomomorphism, antiisomorphism, antiautomorphism, involution -/ variables {R : Type*} {F : Type*} /- The Proposition that a function from a ring to a ring is an antihomomorphism -/ class is_ring_anti_hom [ring R] [ring F] (f : R → F) : Prop := (map_one : f 1 = 1) (map_mul : ∀ {x y : R}, f (x * y) = f y * f x) (map_add : ∀ {x y : R}, f (x + y) = f x + f y) namespace is_ring_anti_hom variables [ring R] [ring F] (f : R → F) [is_ring_anti_hom f] instance : is_add_group_hom f := { to_is_add_hom := ⟨λ x y, is_ring_anti_hom.map_add f⟩ } lemma map_zero : f 0 = 0 := is_add_group_hom.map_zero f lemma map_neg {x} : f (-x) = -f x := is_add_group_hom.map_neg f x lemma map_sub {x y} : f (x - y) = f x - f y := is_add_group_hom.map_sub f x y end is_ring_anti_hom variables (R F) namespace ring_equiv open ring_equiv variables {R F} [ring R] [ring F] (Hs : R ≃r F) (x y : R) instance : has_coe_to_fun (R ≃r F) := ⟨_, λ Hs, Hs.to_fun⟩ lemma map_add : Hs (x + y) = Hs x + Hs y := is_ring_hom.map_add Hs lemma map_zero : Hs 0 = 0 := is_ring_hom.map_zero Hs lemma map_neg : Hs (-x) = -Hs x := is_ring_hom.map_neg Hs lemma map_sub : Hs (x - y) = Hs x - Hs y := is_ring_hom.map_sub Hs lemma map_mul : Hs (x * y) = Hs x * Hs y := is_ring_hom.map_mul Hs lemma map_one : Hs 1 = 1 := is_ring_hom.map_one Hs lemma map_neg_one : Hs (-1) = -1 := Hs.map_one ▸ Hs.map_neg 1 lemma bijective : function.bijective Hs := Hs.to_equiv.bijective lemma map_zero_iff {x : R} : Hs x = 0 ↔ x = 0 := ⟨λ H, Hs.bijective.1 $ H.symm ▸ Hs.map_zero.symm, λ H, H.symm ▸ Hs.map_zero⟩ end ring_equiv /-- A ring antiisomorphism -/ structure ring_anti_equiv [ring R] [ring F] extends R ≃ F := [anti_hom : is_ring_anti_hom to_fun] namespace ring_anti_equiv variables {R F} [ring R] [ring F] (Hs : ring_anti_equiv R F) (x y : R) instance : has_coe_to_fun (ring_anti_equiv R F) := ⟨_, λ Hs, Hs.to_fun⟩ instance : is_ring_anti_hom Hs := Hs.anti_hom lemma map_add : Hs (x + y) = Hs x + Hs y := is_ring_anti_hom.map_add Hs lemma map_zero : Hs 0 = 0 := is_ring_anti_hom.map_zero Hs lemma map_neg : Hs (-x) = -Hs x := is_ring_anti_hom.map_neg Hs lemma map_sub : Hs (x - y) = Hs x - Hs y := is_ring_anti_hom.map_sub Hs lemma map_mul : Hs (x * y) = Hs y * Hs x := is_ring_anti_hom.map_mul Hs lemma map_one : Hs 1 = 1 := is_ring_anti_hom.map_one Hs lemma map_neg_one : Hs (-1) = -1 := Hs.map_one ▸ Hs.map_neg 1 lemma bijective : function.bijective Hs := Hs.to_equiv.bijective lemma map_zero_iff {x : R} : Hs x = 0 ↔ x = 0 := ⟨λ H, Hs.bijective.1 $ H.symm ▸ Hs.map_zero.symm, λ H, H.symm ▸ Hs.map_zero⟩ end ring_anti_equiv /-- A ring involution -/ structure ring_invo [ring R] := (to_fun : R → R) [anti_hom : is_ring_anti_hom to_fun] (to_fun_to_fun : ∀ x, to_fun (to_fun x) = x) open ring_invo namespace ring_invo variables {R} [ring R] (Hi : ring_invo R) (x y : R) instance : has_coe_to_fun (ring_invo R) := ⟨_, λ Hi, Hi.to_fun⟩ instance : is_ring_anti_hom Hi := Hi.anti_hom def to_ring_anti_equiv : ring_anti_equiv R R := { inv_fun := Hi, left_inv := Hi.to_fun_to_fun, right_inv := Hi.to_fun_to_fun, .. Hi } lemma map_add : Hi (x + y) = Hi x + Hi y := Hi.to_ring_anti_equiv.map_add x y lemma map_zero : Hi 0 = 0 := Hi.to_ring_anti_equiv.map_zero lemma map_neg : Hi (-x) = -Hi x := Hi.to_ring_anti_equiv.map_neg x lemma map_sub : Hi (x - y) = Hi x - Hi y := Hi.to_ring_anti_equiv.map_sub x y lemma map_mul : Hi (x * y) = Hi y * Hi x := Hi.to_ring_anti_equiv.map_mul x y lemma map_one : Hi 1 = 1 := Hi.to_ring_anti_equiv.map_one lemma map_neg_one : Hi (-1) = -1 := Hi.to_ring_anti_equiv.map_neg_one lemma bijective : function.bijective Hi := Hi.to_ring_anti_equiv.bijective lemma map_zero_iff {x : R} : Hi x = 0 ↔ x = 0 := Hi.to_ring_anti_equiv.map_zero_iff end ring_invo section comm_ring variables (R F) [comm_ring R] [comm_ring F] protected def ring_invo.id : ring_invo R := { anti_hom := ⟨rfl, mul_comm, λ _ _, rfl⟩, to_fun_to_fun := λ _, rfl, .. equiv.refl R } protected def ring_anti_equiv.refl : ring_anti_equiv R R := (ring_invo.id R).to_ring_anti_equiv variables {R F} theorem comm_ring.hom_to_anti_hom (f : R → F) [is_ring_hom f] : is_ring_anti_hom f := { map_add := λ _ _, is_ring_hom.map_add f, map_mul := λ _ _, by rw [is_ring_hom.map_mul f, mul_comm], map_one := is_ring_hom.map_one f } theorem comm_ring.anti_hom_to_hom (f : R → F) [is_ring_anti_hom f] : is_ring_hom f := { map_add := λ _ _, is_ring_anti_hom.map_add f, map_mul := λ _ _, by rw [is_ring_anti_hom.map_mul f, mul_comm], map_one := is_ring_anti_hom.map_one f } def comm_ring.equiv_to_anti_equiv (Hs : R ≃r F) : ring_anti_equiv R F := { anti_hom := comm_ring.hom_to_anti_hom Hs, .. Hs.to_equiv } def comm_ring.anti_equiv_to_equiv (Hs : ring_anti_equiv R F) : R ≃r F := { hom := comm_ring.anti_hom_to_hom Hs, .. Hs.to_equiv } end comm_ring
2f1a0a1b18830779b4abba45e7269c7da39922e4
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/number_theory/liouville/liouville_constant.lean
e68bf937bea0c73c33d3f823cb94d9b8bd82b25d
[ "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
8,846
lean
/- Copyright (c) 2020 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Damiano Testa, Jujian Zhang -/ import number_theory.liouville.basic /-! # Liouville constants This file contains a construction of a family of Liouville numbers, indexed by a natural number $m$. The most important property is that they are examples of transcendental real numbers. This fact is recorded in `liouville.is_transcendental`. More precisely, for a real number $m$, Liouville's constant is $$ \sum_{i=0}^\infty\frac{1}{m^{i!}}. $$ The series converges only for $1 < m$. However, there is no restriction on $m$, since, if the series does not converge, then the sum of the series is defined to be zero. We prove that, for $m \in \mathbb{N}$ satisfying $2 \le m$, Liouville's constant associated to $m$ is a transcendental number. Classically, the Liouville number for $m = 2$ is the one called ``Liouville's constant''. # Implementation notes The indexing $m$ is eventually a natural number satisfying $2 ≤ m$. However, we prove the first few lemmas for $m \in \mathbb{R}$. -/ noncomputable theory open_locale nat big_operators open real finset namespace liouville /-- For a real number `m`, Liouville's constant is $$ \sum_{i=0}^\infty\frac{1}{m^{i!}}. $$ The series converges only for `1 < m`. However, there is no restriction on `m`, since, if the series does not converge, then the sum of the series is defined to be zero. -/ def liouville_number (m : ℝ) : ℝ := ∑' (i : ℕ), 1 / m ^ i! /-- `liouville_number_initial_terms` is the sum of the first `k + 1` terms of Liouville's constant, i.e. $$ \sum_{i=0}^k\frac{1}{m^{i!}}. $$ -/ def liouville_number_initial_terms (m : ℝ) (k : ℕ) : ℝ := ∑ i in range (k+1), 1 / m ^ i! /-- `liouville_number_tail` is the sum of the series of the terms in `liouville_number m` starting from `k+1`, i.e $$ \sum_{i=k+1}^\infty\frac{1}{m^{i!}}. $$ -/ def liouville_number_tail (m : ℝ) (k : ℕ) : ℝ := ∑' i, 1 / m ^ (i + (k+1))! lemma liouville_number_tail_pos {m : ℝ} (hm : 1 < m) (k : ℕ) : 0 < liouville_number_tail m k := -- replace `0` with the constantly zero series `∑ i : ℕ, 0` calc (0 : ℝ) = ∑' i : ℕ, 0 : tsum_zero.symm ... < liouville_number_tail m k : -- to show that a series with non-negative terms has strictly positive sum it suffices -- to prove that tsum_lt_tsum_of_nonneg -- 1. the terms of the zero series are indeed non-negative (λ _, rfl.le) -- 2. the terms of our series are non-negative (λ i, one_div_nonneg.mpr (pow_nonneg (zero_le_one.trans hm.le) _)) -- 3. one term of our series is strictly positive -- they all are, we use the first term (one_div_pos.mpr (pow_pos (zero_lt_one.trans hm) (0 + (k + 1))!)) $ -- 4. our series converges -- it does since it is the tail of a converging series, though -- this is not the argument here. summable_one_div_pow_of_le hm (λ i, trans le_self_add (nat.self_le_factorial _)) /-- Split the sum definining a Liouville number into the first `k` term and the rest. -/ lemma liouville_number_eq_initial_terms_add_tail {m : ℝ} (hm : 1 < m) (k : ℕ) : liouville_number m = liouville_number_initial_terms m k + liouville_number_tail m k := (sum_add_tsum_nat_add _ (summable_one_div_pow_of_le hm (λ i, i.self_le_factorial))).symm /-! We now prove two useful inequalities, before collecting everything together. -/ /-- Partial inequality, works with `m ∈ ℝ` satisfying `1 < m`. -/ lemma tsum_one_div_pow_factorial_lt (n : ℕ) {m : ℝ} (m1 : 1 < m) : ∑' (i : ℕ), 1 / m ^ (i + (n + 1))! < (1 - 1 / m)⁻¹ * (1 / m ^ (n + 1)!) := -- two useful inequalities have m0 : 0 < m := (zero_lt_one.trans m1), have mi : |1 / m| < 1 := (le_of_eq (abs_of_pos (one_div_pos.mpr m0))).trans_lt ((div_lt_one m0).mpr m1), calc (∑' i, 1 / m ^ (i + (n + 1))!) < ∑' i, 1 / m ^ (i + (n + 1)!) : -- to show the strict inequality between these series, we prove that: tsum_lt_tsum_of_nonneg -- 1. the first series has non-negative terms (λ b, one_div_nonneg.mpr (pow_nonneg m0.le _)) -- 2. the second series dominates the first (λ b, one_div_pow_le_one_div_pow_of_le m1.le (b.add_factorial_succ_le_factorial_add_succ n)) -- 3. the term with index `i = 2` of the first series is strictly smaller than -- the corresponding term of the second series (one_div_pow_strict_mono m1 (n.add_factorial_succ_lt_factorial_add_succ rfl.le)) -- 4. the second series is summable, since its terms grow quickly (summable_one_div_pow_of_le m1 (λ j, nat.le.intro rfl)) ... = ∑' i, (1 / m) ^ i * (1 / m ^ (n + 1)!) : -- split the sum in the exponent and massage by { congr, ext i, rw [pow_add, ← div_div_eq_div_mul, div_eq_mul_one_div, ← one_div_pow i] } -- factor the constant `(1 / m ^ (n + 1)!)` out of the series ... = (∑' i, (1 / m) ^ i) * (1 / m ^ (n + 1)!) : tsum_mul_right ... = (1 - 1 / m)⁻¹ * (1 / m ^ (n + 1)!) : -- the series if the geometric series mul_eq_mul_right_iff.mpr (or.inl (tsum_geometric_of_abs_lt_1 mi)) lemma aux_calc (n : ℕ) {m : ℝ} (hm : 2 ≤ m) : (1 - 1 / m)⁻¹ * (1 / m ^ (n + 1)!) ≤ 1 / (m ^ n!) ^ n := calc (1 - 1 / m)⁻¹ * (1 / m ^ (n + 1)!) ≤ 2 * (1 / m ^ (n + 1)!) : -- the second factors coincide (and are non-negative), -- the first factors, satisfy the inequality `sub_one_div_inv_le_two` mul_mono_nonneg (one_div_nonneg.mpr (pow_nonneg (zero_le_two.trans hm) _)) (sub_one_div_inv_le_two hm) ... = 2 / m ^ (n + 1)! : mul_one_div 2 _ ... = 2 / m ^ (n! * (n + 1)) : congr_arg ((/) 2) (congr_arg (pow m) (mul_comm _ _)) ... ≤ 1 / m ^ (n! * n) : begin -- [ NB: in this block, I do not follow the brace convention for subgoals -- I wait until -- I solve all extraneous goals at once with `exact pow_pos (zero_lt_two.trans_le hm) _`. ] -- Clear denominators and massage* apply (div_le_div_iff _ _).mpr, conv_rhs { rw [one_mul, mul_add, pow_add, mul_one, pow_mul, mul_comm, ← pow_mul] }, -- the second factors coincide, so we prove the inequality of the first factors* apply (mul_le_mul_right _).mpr, -- solve all the inequalities `0 < m ^ ??` any_goals { exact pow_pos (zero_lt_two.trans_le hm) _ }, -- `2 ≤ m ^ n!` is a consequence of monotonicity of exponentiation at `2 ≤ m`. exact trans (trans hm (pow_one _).symm.le) (pow_mono (one_le_two.trans hm) n.factorial_pos) end ... = 1 / (m ^ n!) ^ n : congr_arg ((/) 1) (pow_mul m n! n) /-! Starting from here, we specialize to the case in which `m` is a natural number. -/ /-- The sum of the `k` initial terms of the Liouville number to base `m` is a ratio of natural numbers where the denominator is `m ^ k!`. -/ lemma liouville_number_rat_initial_terms {m : ℕ} (hm : 0 < m) (k : ℕ) : ∃ p : ℕ, liouville_number_initial_terms m k = p / m ^ k! := begin induction k with k h, { exact ⟨1, by rw [liouville_number_initial_terms, range_one, sum_singleton, nat.cast_one]⟩ }, { rcases h with ⟨p_k, h_k⟩, use p_k * (m ^ ((k + 1)! - k!)) + 1, unfold liouville_number_initial_terms at h_k ⊢, rw [sum_range_succ, h_k, div_add_div, div_eq_div_iff, add_mul], { norm_cast, rw [add_mul, one_mul, nat.factorial_succ, show k.succ * k! - k! = (k.succ - 1) * k!, by rw [nat.mul_sub_right_distrib, one_mul], nat.succ_sub_one, nat.succ_eq_add_one, add_mul, one_mul, pow_add], simp [mul_assoc] }, refine mul_ne_zero_iff.mpr ⟨_, _⟩, all_goals { exact pow_ne_zero _ (nat.cast_ne_zero.mpr hm.ne.symm) } } end theorem is_liouville {m : ℕ} (hm : 2 ≤ m) : liouville (liouville_number m) := begin -- two useful inequalities have mZ1 : 1 < (m : ℤ), { norm_cast, exact one_lt_two.trans_le hm }, have m1 : 1 < (m : ℝ), { norm_cast, exact one_lt_two.trans_le hm }, intro n, -- the first `n` terms sum to `p / m ^ k!` rcases liouville_number_rat_initial_terms (zero_lt_two.trans_le hm) n with ⟨p, hp⟩, refine ⟨p, m ^ n!, one_lt_pow mZ1 n.factorial_pos, _⟩, push_cast, -- separate out the sum of the first `n` terms and the rest rw [liouville_number_eq_initial_terms_add_tail m1 n, ← hp, add_sub_cancel', abs_of_nonneg (liouville_number_tail_pos m1 _).le], exact ⟨((lt_add_iff_pos_right _).mpr (liouville_number_tail_pos m1 n)).ne.symm, (tsum_one_div_pow_factorial_lt n m1).trans_le (aux_calc _ (nat.cast_two.symm.le.trans (nat.cast_le.mpr hm)))⟩ end /- Placing this lemma outside of the `open/closed liouville`-namespace would allow to remove `_root_.`, at the cost of some other small weirdness. -/ lemma is_transcendental {m : ℕ} (hm : 2 ≤ m) : _root_.transcendental ℤ (liouville_number m) := transcendental (is_liouville hm) end liouville
a10005ac4003c54f8d584711734a5979decc37b7
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/cdotTuple.lean
5b15e85f3f739fc2a64e6301f8e769b56914b55b
[ "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
193
lean
#eval [1, 2, 3].map (·, 1) #eval (·, ·) 1 2 #eval (·, ·, ·) 1 2 3 theorem ex1 : [1, 2, 3].map (·, 1) = [(1, 1), (2, 1), (3, 1)] := rfl theorem ex2 : (·, ·) 1 2 = (1, 2) := rfl
b182eb4f808262968bf61793427c86bd9fed5981
4efff1f47634ff19e2f786deadd394270a59ecd2
/src/data/nat/parity.lean
e84ac3ada8e0a1fa36d5f806ca4f9720c2b993f7
[ "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
3,949
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The `even` predicate on the natural numbers. -/ import data.nat.modeq namespace nat @[simp] theorem mod_two_ne_one {n : nat} : ¬ n % 2 = 1 ↔ n % 2 = 0 := by cases mod_two_eq_zero_or_one n with h h; simp [h] @[simp] theorem mod_two_ne_zero {n : nat} : ¬ n % 2 = 0 ↔ n % 2 = 1 := by cases mod_two_eq_zero_or_one n with h h; simp [h] /-- A natural number `n` is `even` if `2 | n`. -/ def even (n : nat) : Prop := 2 ∣ n theorem even_iff {n : nat} : even n ↔ n % 2 = 0 := ⟨λ ⟨m, hm⟩, by simp [hm], λ h, ⟨n / 2, (mod_add_div n 2).symm.trans (by simp [h])⟩⟩ lemma not_even_iff {n : ℕ} : ¬ even n ↔ n % 2 = 1 := by rw [even_iff, mod_two_ne_zero] instance : decidable_pred even := λ n, decidable_of_decidable_of_iff (by apply_instance) even_iff.symm mk_simp_attribute parity_simps "Simp attribute for lemmas about `even`" @[simp] theorem even_zero : even 0 := ⟨0, dec_trivial⟩ @[simp] theorem not_even_one : ¬ even 1 := by rw even_iff; apply one_ne_zero @[simp] theorem even_bit0 (n : nat) : even (bit0 n) := ⟨n, by rw [bit0, two_mul]⟩ @[parity_simps] theorem even_add {m n : nat} : even (m + n) ↔ (even m ↔ even n) := begin cases mod_two_eq_zero_or_one m with h₁ h₁; cases mod_two_eq_zero_or_one n with h₂ h₂; simp [even_iff, h₁, h₂], { exact @modeq.modeq_add _ _ 0 _ 0 h₁ h₂ }, { exact @modeq.modeq_add _ _ 0 _ 1 h₁ h₂ }, { exact @modeq.modeq_add _ _ 1 _ 0 h₁ h₂ }, exact @modeq.modeq_add _ _ 1 _ 1 h₁ h₂ end theorem even.add {m n : ℕ} (hm : m.even) (hn : n.even) : (m + n).even := even_add.2 $ by simp only [*] @[simp] theorem not_even_bit1 (n : nat) : ¬ even (bit1 n) := by simp [bit1] with parity_simps lemma two_not_dvd_two_mul_add_one (a : ℕ) : ¬(2 ∣ 2 * a + 1) := begin convert not_even_bit1 a, exact two_mul a, end lemma two_not_dvd_two_mul_sub_one : Π {a : ℕ} (w : 0 < a), ¬(2 ∣ 2 * a - 1) | (a+1) _ := two_not_dvd_two_mul_add_one a @[parity_simps] theorem even_sub {m n : nat} (h : n ≤ m) : even (m - n) ↔ (even m ↔ even n) := begin conv { to_rhs, rw [←nat.sub_add_cancel h, even_add] }, by_cases h : even n; simp [h] end theorem even.sub {m n : ℕ} (hm : m.even) (hn : n.even) : (m - n).even := (le_total n m).elim (λ h, by simp only [even_sub h, *]) (λ h, by simp only [sub_eq_zero_of_le h, even_zero]) @[parity_simps] theorem even_succ {n : nat} : even (succ n) ↔ ¬ even n := by rw [succ_eq_add_one, even_add]; simp [not_even_one] @[parity_simps] theorem even_mul {m n : nat} : even (m * n) ↔ even m ∨ even n := begin cases mod_two_eq_zero_or_one m with h₁ h₁; cases mod_two_eq_zero_or_one n with h₂ h₂; simp [even_iff, h₁, h₂], { exact @modeq.modeq_mul _ _ 0 _ 0 h₁ h₂ }, { exact @modeq.modeq_mul _ _ 0 _ 1 h₁ h₂ }, { exact @modeq.modeq_mul _ _ 1 _ 0 h₁ h₂ }, exact @modeq.modeq_mul _ _ 1 _ 1 h₁ h₂ end @[parity_simps] theorem even_pow {m n : nat} : even (m^n) ↔ even m ∧ n ≠ 0 := by { induction n with n ih; simp [*, nat.pow_succ, even_mul], tauto } lemma even_div {a b : ℕ} : even (a / b) ↔ a % (2 * b) / b = 0 := by rw [even, dvd_iff_mod_eq_zero, nat.div_mod_eq_mod_mul_div, mul_comm] theorem neg_one_pow_eq_one_iff_even {α : Type*} [ring α] {n : ℕ} (h1 : (-1 : α) ≠ 1): (-1 : α) ^ n = 1 ↔ even n := ⟨λ h, n.mod_two_eq_zero_or_one.elim (dvd_iff_mod_eq_zero _ _).2 (λ hn, by rw [neg_one_pow_eq_pow_mod_two, hn, _root_.pow_one] at h; exact (h1 h).elim), λ ⟨m, hm⟩, by rw [neg_one_pow_eq_pow_mod_two, hm]; simp⟩ -- Here are examples of how `parity_simps` can be used with `nat`. example (m n : nat) (h : even m) : ¬ even (n + 3) ↔ even (m^2 + m + n) := by simp [*, (dec_trivial : ¬ 2 = 0)] with parity_simps example : ¬ even 25394535 := by simp end nat
ceabba92b7a57ecf125526b8588d14970a5a9a7d
e0f9ba56b7fedc16ef8697f6caeef5898b435143
/src/data/real/cau_seq_completion.lean
12309f55c30ffb908ce27cc0e41aabc0145683d3
[ "Apache-2.0" ]
permissive
anrddh/mathlib
6a374da53c7e3a35cb0298b0cd67824efef362b4
a4266a01d2dcb10de19369307c986d038c7bb6a6
refs/heads/master
1,656,710,827,909
1,589,560,456,000
1,589,560,456,000
264,271,800
0
0
Apache-2.0
1,589,568,062,000
1,589,568,061,000
null
UTF-8
Lean
false
false
9,452
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Robert Y. Lewis Generalizes the Cauchy completion of (ℚ, abs) to the completion of a commutative ring with absolute value. -/ import data.real.cau_seq namespace cau_seq.completion open cau_seq section parameters {α : Type*} [discrete_linear_ordered_field α] parameters {β : Type*} [comm_ring β] {abv : β → α} [is_absolute_value abv] def Cauchy := @quotient (cau_seq _ abv) cau_seq.equiv def mk : cau_seq _ abv → Cauchy := quotient.mk @[simp] theorem mk_eq_mk (f) : @eq Cauchy ⟦f⟧ (mk f) := rfl theorem mk_eq {f g} : mk f = mk g ↔ f ≈ g := quotient.eq def of_rat (x : β) : Cauchy := mk (const abv x) instance : has_zero Cauchy := ⟨of_rat 0⟩ instance : has_one Cauchy := ⟨of_rat 1⟩ instance : inhabited Cauchy := ⟨0⟩ theorem of_rat_zero : of_rat 0 = 0 := rfl theorem of_rat_one : of_rat 1 = 1 := rfl @[simp] theorem mk_eq_zero {f} : mk f = 0 ↔ lim_zero f := by have : mk f = 0 ↔ lim_zero (f - 0) := quotient.eq; rwa sub_zero at this instance : has_add Cauchy := ⟨λ x y, quotient.lift_on₂ x y (λ f g, mk (f + g)) $ λ f₁ g₁ f₂ g₂ hf hg, quotient.sound $ by simpa [(≈), setoid.r, sub_eq_add_neg, add_comm, add_left_comm] using add_lim_zero hf hg⟩ @[simp] theorem mk_add (f g : cau_seq β abv) : mk f + mk g = mk (f + g) := rfl instance : has_neg Cauchy := ⟨λ x, quotient.lift_on x (λ f, mk (-f)) $ λ f₁ f₂ hf, quotient.sound $ by simpa [(≈), setoid.r] using neg_lim_zero hf⟩ @[simp] theorem mk_neg (f : cau_seq β abv) : -mk f = mk (-f) := rfl instance : has_mul Cauchy := ⟨λ x y, quotient.lift_on₂ x y (λ f g, mk (f * g)) $ λ f₁ g₁ f₂ g₂ hf hg, quotient.sound $ by simpa [(≈), setoid.r, mul_add, mul_comm, sub_eq_add_neg] using add_lim_zero (mul_lim_zero_right g₁ hf) (mul_lim_zero_right f₂ hg)⟩ @[simp] theorem mk_mul (f g : cau_seq β abv) : mk f * mk g = mk (f * g) := rfl theorem of_rat_add (x y : β) : of_rat (x + y) = of_rat x + of_rat y := congr_arg mk (const_add _ _) theorem of_rat_neg (x : β) : of_rat (-x) = -of_rat x := congr_arg mk (const_neg _) theorem of_rat_mul (x y : β) : of_rat (x * y) = of_rat x * of_rat y := congr_arg mk (const_mul _ _) private lemma zero_def : 0 = mk 0 := rfl private lemma one_def : 1 = mk 1 := rfl instance : comm_ring Cauchy := by refine { neg := has_neg.neg, add := (+), zero := 0, mul := (*), one := 1, .. }; { repeat {refine λ a, quotient.induction_on a (λ _, _)}, simp [zero_def, one_def, mul_left_comm, mul_comm, mul_add, add_comm, add_left_comm] } theorem of_rat_sub (x y : β) : of_rat (x - y) = of_rat x - of_rat y := congr_arg mk (const_sub _ _) end open_locale classical section parameters {α : Type*} [discrete_linear_ordered_field α] parameters {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] local notation `Cauchy` := @Cauchy _ _ _ _ abv _ noncomputable instance : has_inv Cauchy := ⟨λ x, quotient.lift_on x (λ f, mk $ if h : lim_zero f then 0 else inv f h) $ λ f g fg, begin have := lim_zero_congr fg, by_cases hf : lim_zero f, { simp [hf, this.1 hf, setoid.refl] }, { have hg := mt this.2 hf, simp [hf, hg], have If : mk (inv f hf) * mk f = 1 := mk_eq.2 (inv_mul_cancel hf), have Ig : mk (inv g hg) * mk g = 1 := mk_eq.2 (inv_mul_cancel hg), rw [mk_eq.2 fg, ← Ig] at If, rw mul_comm at Ig, rw [← mul_one (mk (inv f hf)), ← Ig, ← mul_assoc, If, mul_assoc, Ig, mul_one] } end⟩ @[simp] theorem inv_zero : (0 : Cauchy)⁻¹ = 0 := congr_arg mk $ by rw dif_pos; [refl, exact zero_lim_zero] @[simp] theorem inv_mk {f} (hf) : (@mk α _ β _ abv _ f)⁻¹ = mk (inv f hf) := congr_arg mk $ by rw dif_neg lemma cau_seq_zero_ne_one : ¬ (0 : cau_seq _ abv) ≈ 1 := λ h, have lim_zero (1 - 0), from setoid.symm h, have lim_zero 1, by simpa, one_ne_zero $ const_lim_zero.1 this lemma zero_ne_one : (0 : Cauchy) ≠ 1 := λ h, cau_seq_zero_ne_one $ mk_eq.1 h protected theorem inv_mul_cancel {x : Cauchy} : x ≠ 0 → x⁻¹ * x = 1 := quotient.induction_on x $ λ f hf, begin simp at hf, simp [hf], exact quotient.sound (cau_seq.inv_mul_cancel hf) end noncomputable def field : field Cauchy := { inv := has_inv.inv, mul_inv_cancel := λ x x0, by rw [mul_comm, cau_seq.completion.inv_mul_cancel x0], zero_ne_one := zero_ne_one, inv_zero := inv_zero, ..cau_seq.completion.comm_ring } local attribute [instance] field theorem of_rat_inv (x : β) : of_rat (x⁻¹) = ((of_rat x)⁻¹ : Cauchy) := congr_arg mk $ by split_ifs with h; try {simp [const_lim_zero.1 h]}; refl theorem of_rat_div (x y : β) : of_rat (x / y) = (of_rat x / of_rat y : Cauchy) := by simp only [div_eq_inv_mul, of_rat_inv, of_rat_mul] end end cau_seq.completion variables {α : Type*} [discrete_linear_ordered_field α] namespace cau_seq section variables (β : Type*) [ring β] (abv : β → α) [is_absolute_value abv] class is_complete := (is_complete : ∀ s : cau_seq β abv, ∃ b : β, s ≈ const abv b) end section variables {β : Type*} [ring β] {abv : β → α} [is_absolute_value abv] variable [is_complete β abv] lemma complete : ∀ s : cau_seq β abv, ∃ b : β, s ≈ const abv b := is_complete.is_complete noncomputable def lim (s : cau_seq β abv) := classical.some (complete s) lemma equiv_lim (s : cau_seq β abv) : s ≈ const abv (lim s) := classical.some_spec (complete s) lemma eq_lim_of_const_equiv {f : cau_seq β abv} {x : β} (h : cau_seq.const abv x ≈ f) : x = lim f := const_equiv.mp $ setoid.trans h $ equiv_lim f lemma lim_eq_of_equiv_const {f : cau_seq β abv} {x : β} (h : f ≈ cau_seq.const abv x) : lim f = x := (eq_lim_of_const_equiv $ setoid.symm h).symm lemma lim_eq_lim_of_equiv {f g : cau_seq β abv} (h : f ≈ g) : lim f = lim g := lim_eq_of_equiv_const $ setoid.trans h $ equiv_lim g @[simp] lemma lim_const (x : β) : lim (const abv x) = x := lim_eq_of_equiv_const $ setoid.refl _ lemma lim_add (f g : cau_seq β abv) : lim f + lim g = lim (f + g) := eq_lim_of_const_equiv $ show lim_zero (const abv (lim f + lim g) - (f + g)), by rw [const_add, add_sub_comm]; exact add_lim_zero (setoid.symm (equiv_lim f)) (setoid.symm (equiv_lim g)) lemma lim_mul_lim (f g : cau_seq β abv) : lim f * lim g = lim (f * g) := eq_lim_of_const_equiv $ show lim_zero (const abv (lim f * lim g) - f * g), from have h : const abv (lim f * lim g) - f * g = (const abv (lim f) - f) * g + const abv (lim f) * (const abv (lim g) - g) := by simp [const_mul (lim f), mul_add, add_mul, sub_eq_add_neg, add_comm, add_left_comm], by rw h; exact add_lim_zero (mul_lim_zero_left _ (setoid.symm (equiv_lim _))) (mul_lim_zero_right _ (setoid.symm (equiv_lim _))) lemma lim_mul (f : cau_seq β abv) (x : β) : lim f * x = lim (f * const abv x) := by rw [← lim_mul_lim, lim_const] lemma lim_neg (f : cau_seq β abv) : lim (-f) = -lim f := lim_eq_of_equiv_const (show lim_zero (-f - const abv (-lim f)), by rw [const_neg, sub_neg_eq_add, add_comm]; exact setoid.symm (equiv_lim f)) lemma lim_eq_zero_iff (f : cau_seq β abv) : lim f = 0 ↔ lim_zero f := ⟨assume h, by have hf := equiv_lim f; rw h at hf; exact (lim_zero_congr hf).mpr (const_lim_zero.mpr rfl), assume h, have h₁ : f = (f - const abv 0) := ext (λ n, by simp [sub_apply, const_apply]), by rw h₁ at h; exact lim_eq_of_equiv_const h ⟩ end section variables {β : Type*} [field β] {abv : β → α} [is_absolute_value abv] [is_complete β abv] lemma lim_inv {f : cau_seq β abv} (hf : ¬ lim_zero f) : lim (inv f hf) = (lim f)⁻¹ := have hl : lim f ≠ 0 := by rwa ← lim_eq_zero_iff at hf, lim_eq_of_equiv_const $ show lim_zero (inv f hf - const abv (lim f)⁻¹), from have h₁ : ∀ (g f : cau_seq β abv) (hf : ¬ lim_zero f), lim_zero (g - f * inv f hf * g) := λ g f hf, by rw [← one_mul g, ← mul_assoc, ← sub_mul, mul_one, mul_comm, mul_comm f]; exact mul_lim_zero_right _ (setoid.symm (cau_seq.inv_mul_cancel _)), have h₂ : lim_zero ((inv f hf - const abv (lim f)⁻¹) - (const abv (lim f) - f) * (inv f hf * const abv (lim f)⁻¹)) := by rw [sub_mul, ← sub_add, sub_sub, sub_add_eq_sub_sub, sub_right_comm, sub_add]; exact show lim_zero (inv f hf - const abv (lim f) * (inv f hf * const abv (lim f)⁻¹) - (const abv (lim f)⁻¹ - f * (inv f hf * const abv (lim f)⁻¹))), from sub_lim_zero (by rw [← mul_assoc, mul_right_comm, const_inv hl]; exact h₁ _ _ _) (by rw [← mul_assoc]; exact h₁ _ _ _), (lim_zero_congr h₂).mpr $ mul_lim_zero_left _ (setoid.symm (equiv_lim f)) end section variables [is_complete α abs] lemma lim_le {f : cau_seq α abs} {x : α} (h : f ≤ cau_seq.const abs x) : lim f ≤ x := cau_seq.const_le.1 $ cau_seq.le_of_eq_of_le (setoid.symm (equiv_lim f)) h lemma le_lim {f : cau_seq α abs} {x : α} (h : cau_seq.const abs x ≤ f) : x ≤ lim f := cau_seq.const_le.1 $ cau_seq.le_of_le_of_eq h (equiv_lim f) lemma lt_lim {f : cau_seq α abs} {x : α} (h : cau_seq.const abs x < f) : x < lim f := cau_seq.const_lt.1 $ cau_seq.lt_of_lt_of_eq h (equiv_lim f) lemma lim_lt {f : cau_seq α abs} {x : α} (h : f < cau_seq.const abs x) : lim f < x := cau_seq.const_lt.1 $ cau_seq.lt_of_eq_of_lt (setoid.symm (equiv_lim f)) h end end cau_seq
06d76e974cc15f892900f30780d790dd17e279a4
675b8263050a5d74b89ceab381ac81ce70535688
/src/geometry/euclidean/basic.lean
b48e991a7c07f39e7bb42b91f98bdf4f785903d1
[ "Apache-2.0" ]
permissive
vozor/mathlib
5921f55235ff60c05f4a48a90d616ea167068adf
f7e728ad8a6ebf90291df2a4d2f9255a6576b529
refs/heads/master
1,675,607,702,231
1,609,023,279,000
1,609,023,279,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
46,765
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Joseph Myers. -/ import analysis.normed_space.inner_product import algebra.quadratic_discriminant import analysis.normed_space.add_torsor import data.matrix.notation import linear_algebra.affine_space.finite_dimensional import tactic.fin_cases noncomputable theory open_locale big_operators open_locale classical open_locale real open_locale real_inner_product_space /-! # Euclidean spaces This file makes some definitions and proves very basic geometrical results about real inner product spaces and Euclidean affine spaces. Results about real inner product spaces that involve the norm and inner product but not angles generally go in `analysis.normed_space.inner_product`. Results with longer proofs or more geometrical content generally go in separate files. ## Main definitions * `inner_product_geometry.angle` is the undirected angle between two vectors. * `euclidean_geometry.angle`, with notation `∠`, is the undirected angle determined by three points. * `euclidean_geometry.orthogonal_projection` is the orthogonal projection of a point onto an affine subspace. * `euclidean_geometry.reflection` is the reflection of a point in an affine subspace. ## Implementation notes To declare `P` as the type of points in a Euclidean affine space with `V` as the type of vectors, use `[inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P]`. This works better with `out_param` to make `V` implicit in most cases than having a separate type alias for Euclidean affine spaces. Rather than requiring Euclidean affine spaces to be finite-dimensional (as in the definition on Wikipedia), this is specified only for those theorems that need it. ## References * https://en.wikipedia.org/wiki/Euclidean_space -/ namespace inner_product_geometry /-! ### Geometrical results on real inner product spaces This section develops some geometrical definitions and results on real inner product spaces, where those definitions and results can most conveniently be developed in terms of vectors and then used to deduce corresponding results for Euclidean affine spaces. -/ variables {V : Type*} [inner_product_space ℝ V] /-- The undirected angle between two vectors. If either vector is 0, this is π/2. -/ def angle (x y : V) : ℝ := real.arccos (inner x y / (∥x∥ * ∥y∥)) /-- The cosine of the angle between two vectors. -/ lemma cos_angle (x y : V) : real.cos (angle x y) = inner x y / (∥x∥ * ∥y∥) := real.cos_arccos (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1 (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2 /-- The angle between two vectors does not depend on their order. -/ lemma angle_comm (x y : V) : angle x y = angle y x := begin unfold angle, rw [real_inner_comm, mul_comm] end /-- The angle between the negation of two vectors. -/ @[simp] lemma angle_neg_neg (x y : V) : angle (-x) (-y) = angle x y := begin unfold angle, rw [inner_neg_neg, norm_neg, norm_neg] end /-- The angle between two vectors is nonnegative. -/ lemma angle_nonneg (x y : V) : 0 ≤ angle x y := real.arccos_nonneg _ /-- The angle between two vectors is at most π. -/ lemma angle_le_pi (x y : V) : angle x y ≤ π := real.arccos_le_pi _ /-- The angle between a vector and the negation of another vector. -/ lemma angle_neg_right (x y : V) : angle x (-y) = π - angle x y := begin unfold angle, rw [←real.arccos_neg, norm_neg, inner_neg_right, neg_div] end /-- The angle between the negation of a vector and another vector. -/ lemma angle_neg_left (x y : V) : angle (-x) y = π - angle x y := by rw [←angle_neg_neg, neg_neg, angle_neg_right] /-- The angle between the zero vector and a vector. -/ @[simp] lemma angle_zero_left (x : V) : angle 0 x = π / 2 := begin unfold angle, rw [inner_zero_left, zero_div, real.arccos_zero] end /-- The angle between a vector and the zero vector. -/ @[simp] lemma angle_zero_right (x : V) : angle x 0 = π / 2 := begin unfold angle, rw [inner_zero_right, zero_div, real.arccos_zero] end /-- The angle between a nonzero vector and itself. -/ @[simp] lemma angle_self {x : V} (hx : x ≠ 0) : angle x x = 0 := begin unfold angle, rw [←real_inner_self_eq_norm_square, div_self (λ h, hx (inner_self_eq_zero.1 h)), real.arccos_one] end /-- The angle between a nonzero vector and its negation. -/ @[simp] lemma angle_self_neg_of_nonzero {x : V} (hx : x ≠ 0) : angle x (-x) = π := by rw [angle_neg_right, angle_self hx, sub_zero] /-- The angle between the negation of a nonzero vector and that vector. -/ @[simp] lemma angle_neg_self_of_nonzero {x : V} (hx : x ≠ 0) : angle (-x) x = π := by rw [angle_comm, angle_self_neg_of_nonzero hx] /-- The angle between a vector and a positive multiple of a vector. -/ @[simp] lemma angle_smul_right_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : angle x (r • y) = angle x y := begin unfold angle, rw [inner_smul_right, norm_smul, real.norm_eq_abs, abs_of_nonneg (le_of_lt hr), ←mul_assoc, mul_comm _ r, mul_assoc, mul_div_mul_left _ _ (ne_of_gt hr)] end /-- The angle between a positive multiple of a vector and a vector. -/ @[simp] lemma angle_smul_left_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : angle (r • x) y = angle x y := by rw [angle_comm, angle_smul_right_of_pos y x hr, angle_comm] /-- The angle between a vector and a negative multiple of a vector. -/ @[simp] lemma angle_smul_right_of_neg (x y : V) {r : ℝ} (hr : r < 0) : angle x (r • y) = angle x (-y) := by rw [←neg_neg r, neg_smul, angle_neg_right, angle_smul_right_of_pos x y (neg_pos_of_neg hr), angle_neg_right] /-- The angle between a negative multiple of a vector and a vector. -/ @[simp] lemma angle_smul_left_of_neg (x y : V) {r : ℝ} (hr : r < 0) : angle (r • x) y = angle (-x) y := by rw [angle_comm, angle_smul_right_of_neg y x hr, angle_comm] /-- The cosine of the angle between two vectors, multiplied by the product of their norms. -/ lemma cos_angle_mul_norm_mul_norm (x y : V) : real.cos (angle x y) * (∥x∥ * ∥y∥) = inner x y := begin rw cos_angle, by_cases h : (∥x∥ * ∥y∥) = 0, { rw [h, mul_zero], cases eq_zero_or_eq_zero_of_mul_eq_zero h with hx hy, { rw norm_eq_zero at hx, rw [hx, inner_zero_left] }, { rw norm_eq_zero at hy, rw [hy, inner_zero_right] } }, { exact div_mul_cancel _ h } end /-- The sine of the angle between two vectors, multiplied by the product of their norms. -/ lemma sin_angle_mul_norm_mul_norm (x y : V) : real.sin (angle x y) * (∥x∥ * ∥y∥) = real.sqrt (inner x x * inner y y - inner x y * inner x y) := begin unfold angle, rw [real.sin_arccos (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1 (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2, ←real.sqrt_mul_self (mul_nonneg (norm_nonneg x) (norm_nonneg y)), ←real.sqrt_mul' _ (mul_self_nonneg _), pow_two, real.sqrt_mul_self (mul_nonneg (norm_nonneg x) (norm_nonneg y)), real_inner_self_eq_norm_square, real_inner_self_eq_norm_square], by_cases h : (∥x∥ * ∥y∥) = 0, { rw [(show ∥x∥ * ∥x∥ * (∥y∥ * ∥y∥) = (∥x∥ * ∥y∥) * (∥x∥ * ∥y∥), by ring), h, mul_zero, mul_zero, zero_sub], cases eq_zero_or_eq_zero_of_mul_eq_zero h with hx hy, { rw norm_eq_zero at hx, rw [hx, inner_zero_left, zero_mul, neg_zero] }, { rw norm_eq_zero at hy, rw [hy, inner_zero_right, zero_mul, neg_zero] } }, { field_simp [h], ring } end /-- The angle between two vectors is zero if and only if they are nonzero and one is a positive multiple of the other. -/ lemma angle_eq_zero_iff (x y : V) : angle x y = 0 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) := begin unfold angle, rw [←real_inner_div_norm_mul_norm_eq_one_iff, ←real.arccos_one], split, { intro h, exact real.arccos_inj (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1 (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2 (by norm_num) (by norm_num) h }, { intro h, rw h } end /-- The angle between two vectors is π if and only if they are nonzero and one is a negative multiple of the other. -/ lemma angle_eq_pi_iff (x y : V) : angle x y = π ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) := begin unfold angle, rw [←real_inner_div_norm_mul_norm_eq_neg_one_iff, ←real.arccos_neg_one], split, { intro h, exact real.arccos_inj (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1 (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2 (by norm_num) (by norm_num) h }, { intro h, rw h } end /-- If the angle between two vectors is π, the angles between those vectors and a third vector add to π. -/ lemma angle_add_angle_eq_pi_of_angle_eq_pi {x y : V} (z : V) (h : angle x y = π) : angle x z + angle y z = π := begin rw angle_eq_pi_iff at h, rcases h with ⟨hx, ⟨r, ⟨hr, hxy⟩⟩⟩, rw [hxy, angle_smul_left_of_neg x z hr, angle_neg_left, add_sub_cancel'_right] end /-- Two vectors have inner product 0 if and only if the angle between them is π/2. -/ lemma inner_eq_zero_iff_angle_eq_pi_div_two (x y : V) : ⟪x, y⟫ = 0 ↔ angle x y = π / 2 := begin split, { intro h, unfold angle, rw [h, zero_div, real.arccos_zero] }, { intro h, unfold angle at h, rw ←real.arccos_zero at h, have h2 : inner x y / (∥x∥ * ∥y∥) = 0 := real.arccos_inj (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).1 (abs_le.mp (abs_real_inner_div_norm_mul_norm_le_one x y)).2 (by norm_num) (by norm_num) h, by_cases h : (∥x∥ * ∥y∥) = 0, { cases eq_zero_or_eq_zero_of_mul_eq_zero h with hx hy, { rw norm_eq_zero at hx, rw [hx, inner_zero_left] }, { rw norm_eq_zero at hy, rw [hy, inner_zero_right] } }, { simpa [h, div_eq_zero_iff] using h2 } }, end end inner_product_geometry namespace euclidean_geometry /-! ### Geometrical results on Euclidean affine spaces This section develops some geometrical definitions and results on Euclidean affine spaces. -/ open inner_product_geometry variables {V : Type*} {P : Type*} [inner_product_space ℝ V] [metric_space P] [normed_add_torsor V P] local notation `⟪`x`, `y`⟫` := @inner ℝ V _ x y include V /-- The undirected angle at `p2` between the line segments to `p1` and `p3`. If either of those points equals `p2`, this is π/2. Use `open_locale euclidean_geometry` to access the `∠ p1 p2 p3` notation. -/ def angle (p1 p2 p3 : P) : ℝ := angle (p1 -ᵥ p2 : V) (p3 -ᵥ p2) localized "notation `∠` := euclidean_geometry.angle" in euclidean_geometry /-- The angle at a point does not depend on the order of the other two points. -/ lemma angle_comm (p1 p2 p3 : P) : ∠ p1 p2 p3 = ∠ p3 p2 p1 := angle_comm _ _ /-- The angle at a point is nonnegative. -/ lemma angle_nonneg (p1 p2 p3 : P) : 0 ≤ ∠ p1 p2 p3 := angle_nonneg _ _ /-- The angle at a point is at most π. -/ lemma angle_le_pi (p1 p2 p3 : P) : ∠ p1 p2 p3 ≤ π := angle_le_pi _ _ /-- The angle ∠AAB at a point. -/ lemma angle_eq_left (p1 p2 : P) : ∠ p1 p1 p2 = π / 2 := begin unfold angle, rw vsub_self, exact angle_zero_left _ end /-- The angle ∠ABB at a point. -/ lemma angle_eq_right (p1 p2 : P) : ∠ p1 p2 p2 = π / 2 := by rw [angle_comm, angle_eq_left] /-- The angle ∠ABA at a point. -/ lemma angle_eq_of_ne {p1 p2 : P} (h : p1 ≠ p2) : ∠ p1 p2 p1 = 0 := angle_self (λ he, h (vsub_eq_zero_iff_eq.1 he)) /-- If the angle ∠ABC at a point is π, the angle ∠BAC is 0. -/ lemma angle_eq_zero_of_angle_eq_pi_left {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : ∠ p2 p1 p3 = 0 := begin unfold angle at h, rw angle_eq_pi_iff at h, rcases h with ⟨hp1p2, ⟨r, ⟨hr, hpr⟩⟩⟩, unfold angle, rw angle_eq_zero_iff, rw [←neg_vsub_eq_vsub_rev, neg_ne_zero] at hp1p2, use [hp1p2, -r + 1, add_pos (neg_pos_of_neg hr) zero_lt_one], rw [add_smul, ←neg_vsub_eq_vsub_rev p1 p2, smul_neg], simp [←hpr] end /-- If the angle ∠ABC at a point is π, the angle ∠BCA is 0. -/ lemma angle_eq_zero_of_angle_eq_pi_right {p1 p2 p3 : P} (h : ∠ p1 p2 p3 = π) : ∠ p2 p3 p1 = 0 := begin rw angle_comm at h, exact angle_eq_zero_of_angle_eq_pi_left h end /-- If ∠BCD = π, then ∠ABC = ∠ABD. -/ lemma angle_eq_angle_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ p2 p3 p4 = π) : ∠ p1 p2 p3 = ∠ p1 p2 p4 := begin unfold angle at h, rw angle_eq_pi_iff at h, rcases h with ⟨hp2p3, ⟨r, ⟨hr, hpr⟩⟩⟩, unfold angle, symmetry, convert angle_smul_right_of_pos _ _ (add_pos (neg_pos_of_neg hr) zero_lt_one), rw [add_smul, ←neg_vsub_eq_vsub_rev p2 p3, smul_neg], simp [←hpr] end /-- If ∠BCD = π, then ∠ACB + ∠ACD = π. -/ lemma angle_add_angle_eq_pi_of_angle_eq_pi (p1 : P) {p2 p3 p4 : P} (h : ∠ p2 p3 p4 = π) : ∠ p1 p3 p2 + ∠ p1 p3 p4 = π := begin unfold angle at h, rw [angle_comm p1 p3 p2, angle_comm p1 p3 p4], unfold angle, exact angle_add_angle_eq_pi_of_angle_eq_pi _ h end /-- The inner product of two vectors given with `weighted_vsub`, in terms of the pairwise distances. -/ lemma inner_weighted_vsub {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (p₁ : ι₁ → P) (h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (p₂ : ι₂ → P) (h₂ : ∑ i in s₂, w₂ i = 0) : inner (s₁.weighted_vsub p₁ w₁) (s₂.weighted_vsub p₂ w₂) = (-∑ i₁ in s₁, ∑ i₂ in s₂, w₁ i₁ * w₂ i₂ * (dist (p₁ i₁) (p₂ i₂) * dist (p₁ i₁) (p₂ i₂))) / 2 := begin rw [finset.weighted_vsub_apply, finset.weighted_vsub_apply, inner_sum_smul_sum_smul_of_sum_eq_zero _ h₁ _ h₂], simp_rw [vsub_sub_vsub_cancel_right], rcongr i₁ i₂; rw dist_eq_norm_vsub V (p₁ i₁) (p₂ i₂) end /-- The distance between two points given with `affine_combination`, in terms of the pairwise distances between the points in that combination. -/ lemma dist_affine_combination {ι : Type*} {s : finset ι} {w₁ w₂ : ι → ℝ} (p : ι → P) (h₁ : ∑ i in s, w₁ i = 1) (h₂ : ∑ i in s, w₂ i = 1) : dist (s.affine_combination p w₁) (s.affine_combination p w₂) * dist (s.affine_combination p w₁) (s.affine_combination p w₂) = (-∑ i₁ in s, ∑ i₂ in s, (w₁ - w₂) i₁ * (w₁ - w₂) i₂ * (dist (p i₁) (p i₂) * dist (p i₁) (p i₂))) / 2 := begin rw [dist_eq_norm_vsub V (s.affine_combination p w₁) (s.affine_combination p w₂), ←inner_self_eq_norm_square, finset.affine_combination_vsub], have h : ∑ i in s, (w₁ - w₂) i = 0, { simp_rw [pi.sub_apply, finset.sum_sub_distrib, h₁, h₂, sub_self] }, exact inner_weighted_vsub p h p h end /-- Suppose that `c₁` is equidistant from `p₁` and `p₂`, and the same applies to `c₂`. Then the vector between `c₁` and `c₂` is orthogonal to that between `p₁` and `p₂`. (In two dimensions, this says that the diagonals of a kite are orthogonal.) -/ lemma inner_vsub_vsub_of_dist_eq_of_dist_eq {c₁ c₂ p₁ p₂ : P} (hc₁ : dist p₁ c₁ = dist p₂ c₁) (hc₂ : dist p₁ c₂ = dist p₂ c₂) : ⟪c₂ -ᵥ c₁, p₂ -ᵥ p₁⟫ = 0 := begin have h : ⟪(c₂ -ᵥ c₁) + (c₂ -ᵥ c₁), p₂ -ᵥ p₁⟫ = 0, { conv_lhs { congr, congr, rw ←vsub_sub_vsub_cancel_right c₂ c₁ p₁, skip, rw ←vsub_sub_vsub_cancel_right c₂ c₁ p₂ }, rw [←add_sub_comm, inner_sub_left], conv_lhs { congr, rw ←vsub_sub_vsub_cancel_right p₂ p₁ c₂, skip, rw ←vsub_sub_vsub_cancel_right p₂ p₁ c₁ }, rw [dist_comm p₁, dist_comm p₂, dist_eq_norm_vsub V _ p₁, dist_eq_norm_vsub V _ p₂, ←real_inner_add_sub_eq_zero_iff] at hc₁ hc₂, simp_rw [←neg_vsub_eq_vsub_rev c₁, ←neg_vsub_eq_vsub_rev c₂, sub_neg_eq_add, neg_add_eq_sub, hc₁, hc₂, sub_zero] }, simpa [inner_add_left, ←mul_two, (by norm_num : (2 : ℝ) ≠ 0)] using h end /-- The squared distance between points on a line (expressed as a multiple of a fixed vector added to a point) and another point, expressed as a quadratic. -/ lemma dist_smul_vadd_square (r : ℝ) (v : V) (p₁ p₂ : P) : dist (r • v +ᵥ p₁) p₂ * dist (r • v +ᵥ p₁) p₂ = ⟪v, v⟫ * r * r + 2 * ⟪v, p₁ -ᵥ p₂⟫ * r + ⟪p₁ -ᵥ p₂, p₁ -ᵥ p₂⟫ := begin rw [dist_eq_norm_vsub V _ p₂, ←real_inner_self_eq_norm_square, vadd_vsub_assoc, real_inner_add_add_self, real_inner_smul_left, real_inner_smul_left, real_inner_smul_right], ring end /-- The condition for two points on a line to be equidistant from another point. -/ lemma dist_smul_vadd_eq_dist {v : V} (p₁ p₂ : P) (hv : v ≠ 0) (r : ℝ) : dist (r • v +ᵥ p₁) p₂ = dist p₁ p₂ ↔ (r = 0 ∨ r = -2 * ⟪v, p₁ -ᵥ p₂⟫ / ⟪v, v⟫) := begin conv_lhs { rw [←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, dist_smul_vadd_square, ←sub_eq_zero_iff_eq, add_sub_assoc, dist_eq_norm_vsub V p₁ p₂, ←real_inner_self_eq_norm_square, sub_self] }, have hvi : ⟪v, v⟫ ≠ 0, by simpa using hv, have hd : discrim ⟪v, v⟫ (2 * ⟪v, p₁ -ᵥ p₂⟫) 0 = (2 * inner v (p₁ -ᵥ p₂)) * (2 * inner v (p₁ -ᵥ p₂)), { rw discrim, ring }, rw [quadratic_eq_zero_iff hvi hd, add_left_neg, zero_div, neg_mul_eq_neg_mul, ←mul_sub_right_distrib, sub_eq_add_neg, ←mul_two, mul_assoc, mul_div_assoc, mul_div_mul_left, mul_div_assoc], norm_num end open affine_subspace finite_dimensional /-- Distances `r₁` `r₂` of `p` from two different points `c₁` `c₂` determine at most two points `p₁` `p₂` in a two-dimensional subspace containing those points (two circles intersect in at most two points). -/ lemma eq_of_dist_eq_of_dist_eq_of_mem_of_findim_eq_two {s : affine_subspace ℝ P} [finite_dimensional ℝ s.direction] (hd : findim ℝ s.direction = 2) {c₁ c₂ p₁ p₂ p : P} (hc₁s : c₁ ∈ s) (hc₂s : c₂ ∈ s) (hp₁s : p₁ ∈ s) (hp₂s : p₂ ∈ s) (hps : p ∈ s) {r₁ r₂ : ℝ} (hc : c₁ ≠ c₂) (hp : p₁ ≠ p₂) (hp₁c₁ : dist p₁ c₁ = r₁) (hp₂c₁ : dist p₂ c₁ = r₁) (hpc₁ : dist p c₁ = r₁) (hp₁c₂ : dist p₁ c₂ = r₂) (hp₂c₂ : dist p₂ c₂ = r₂) (hpc₂ : dist p c₂ = r₂) : p = p₁ ∨ p = p₂ := begin have ho : ⟪c₂ -ᵥ c₁, p₂ -ᵥ p₁⟫ = 0 := inner_vsub_vsub_of_dist_eq_of_dist_eq (by cc) (by cc), have hop : ⟪c₂ -ᵥ c₁, p -ᵥ p₁⟫ = 0 := inner_vsub_vsub_of_dist_eq_of_dist_eq (by cc) (by cc), let b : fin 2 → V := ![c₂ -ᵥ c₁, p₂ -ᵥ p₁], have hb : linear_independent ℝ b, { refine linear_independent_of_ne_zero_of_inner_eq_zero _ _, { intro i, fin_cases i; simp [b, hc.symm, hp.symm] }, { intros i j hij, fin_cases i; fin_cases j; try { exact false.elim (hij rfl) }, { exact ho }, { rw real_inner_comm, exact ho } } }, have hbs : submodule.span ℝ (set.range b) = s.direction, { refine eq_of_le_of_findim_eq _ _, { rw [submodule.span_le, set.range_subset_iff], intro i, fin_cases i, { exact vsub_mem_direction hc₂s hc₁s }, { exact vsub_mem_direction hp₂s hp₁s } }, { rw [findim_span_eq_card hb, fintype.card_fin, hd] } }, have hv : ∀ v ∈ s.direction, ∃ t₁ t₂ : ℝ, v = t₁ • (c₂ -ᵥ c₁) + t₂ • (p₂ -ᵥ p₁), { intros v hv, have hr : set.range b = {c₂ -ᵥ c₁, p₂ -ᵥ p₁}, { have hu : (finset.univ : finset (fin 2)) = {0, 1}, by dec_trivial, rw [←fintype.coe_image_univ, hu], simp, refl }, rw [←hbs, hr, submodule.mem_span_insert] at hv, rcases hv with ⟨t₁, v', hv', hv⟩, rw submodule.mem_span_singleton at hv', rcases hv' with ⟨t₂, rfl⟩, exact ⟨t₁, t₂, hv⟩ }, rcases hv (p -ᵥ p₁) (vsub_mem_direction hps hp₁s) with ⟨t₁, t₂, hpt⟩, simp only [hpt, inner_add_right, inner_smul_right, ho, mul_zero, add_zero, mul_eq_zero, inner_self_eq_zero, vsub_eq_zero_iff_eq, hc.symm, or_false] at hop, rw [hop, zero_smul, zero_add, ←eq_vadd_iff_vsub_eq] at hpt, subst hpt, have hp' : (p₂ -ᵥ p₁ : V) ≠ 0, { simp [hp.symm] }, have hp₂ : dist ((1 : ℝ) • (p₂ -ᵥ p₁) +ᵥ p₁) c₁ = r₁, { simp [hp₂c₁] }, rw [←hp₁c₁, dist_smul_vadd_eq_dist _ _ hp'] at hpc₁ hp₂, simp only [one_ne_zero, false_or] at hp₂, rw hp₂.symm at hpc₁, cases hpc₁; simp [hpc₁] end /-- Distances `r₁` `r₂` of `p` from two different points `c₁` `c₂` determine at most two points `p₁` `p₂` in two-dimensional space (two circles intersect in at most two points). -/ lemma eq_of_dist_eq_of_dist_eq_of_findim_eq_two [finite_dimensional ℝ V] (hd : findim ℝ V = 2) {c₁ c₂ p₁ p₂ p : P} {r₁ r₂ : ℝ} (hc : c₁ ≠ c₂) (hp : p₁ ≠ p₂) (hp₁c₁ : dist p₁ c₁ = r₁) (hp₂c₁ : dist p₂ c₁ = r₁) (hpc₁ : dist p c₁ = r₁) (hp₁c₂ : dist p₁ c₂ = r₂) (hp₂c₂ : dist p₂ c₂ = r₂) (hpc₂ : dist p c₂ = r₂) : p = p₁ ∨ p = p₂ := begin have hd' : findim ℝ (⊤ : affine_subspace ℝ P).direction = 2, { rw [direction_top, findim_top], exact hd }, exact eq_of_dist_eq_of_dist_eq_of_mem_of_findim_eq_two hd' (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) (mem_top ℝ V _) hc hp hp₁c₁ hp₂c₁ hpc₁ hp₁c₂ hp₂c₂ hpc₂ end variables {V} /-- The orthogonal projection of a point onto a nonempty affine subspace, whose direction is complete, as an unbundled function. This definition is only intended for use in setting up the bundled version `orthogonal_projection` and should not be used once that is defined. -/ def orthogonal_projection_fn (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : P := classical.some $ inter_eq_singleton_of_nonempty_of_is_compl (nonempty_subtype.mp ‹_›) (mk'_nonempty p s.direction.orthogonal) begin convert submodule.is_compl_orthogonal_of_is_complete (complete_space_coe_iff_is_complete.mp ‹_›), exact direction_mk' p s.direction.orthogonal end /-- The intersection of the subspace and the orthogonal subspace through the given point is the `orthogonal_projection_fn` of that point onto the subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma inter_eq_singleton_orthogonal_projection_fn {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : (s : set P) ∩ (mk' p s.direction.orthogonal) = {orthogonal_projection_fn s p} := classical.some_spec $ inter_eq_singleton_of_nonempty_of_is_compl (nonempty_subtype.mp ‹_›) (mk'_nonempty p s.direction.orthogonal) begin convert submodule.is_compl_orthogonal_of_is_complete (complete_space_coe_iff_is_complete.mp ‹_›), exact direction_mk' p s.direction.orthogonal end /-- The `orthogonal_projection_fn` lies in the given subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p ∈ s := begin rw [←mem_coe, ←set.singleton_subset_iff, ←inter_eq_singleton_orthogonal_projection_fn], exact set.inter_subset_left _ _ end /-- The `orthogonal_projection_fn` lies in the orthogonal subspace. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_mem_orthogonal {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p ∈ mk' p s.direction.orthogonal := begin rw [←mem_coe, ←set.singleton_subset_iff, ←inter_eq_singleton_orthogonal_projection_fn], exact set.inter_subset_right _ _ end /-- Subtracting `p` from its `orthogonal_projection_fn` produces a result in the orthogonal direction. This lemma is only intended for use in setting up the bundled version and should not be used once that is defined. -/ lemma orthogonal_projection_fn_vsub_mem_direction_orthogonal {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p -ᵥ p ∈ s.direction.orthogonal := direction_mk' p s.direction.orthogonal ▸ vsub_mem_direction (orthogonal_projection_fn_mem_orthogonal p) (self_mem_mk' _ _) /-- The orthogonal projection of a point onto a nonempty affine subspace, whose direction is complete. The corresponding linear map (mapping a vector to the difference between the projections of two points whose difference is that vector) is the `orthogonal_projection` for real inner product spaces, onto the direction of the affine subspace being projected onto. -/ def orthogonal_projection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : P →ᵃ[ℝ] s := { to_fun := λ p, ⟨orthogonal_projection_fn s p, orthogonal_projection_fn_mem p⟩, linear := orthogonal_projection s.direction, map_vadd' := λ p v, begin have hs : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈ s := vadd_mem_of_mem_direction (orthogonal_projection s.direction v).2 (orthogonal_projection_fn_mem p), have ho : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈ mk' (v +ᵥ p) s.direction.orthogonal, { rw [←vsub_right_mem_direction_iff_mem (self_mem_mk' _ _) _, direction_mk', vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm, add_sub_assoc], refine submodule.add_mem _ (orthogonal_projection_fn_vsub_mem_direction_orthogonal p) _, rw submodule.mem_orthogonal', intros w hw, rw [←neg_sub, inner_neg_left, orthogonal_projection_inner_eq_zero _ w hw, neg_zero], }, have hm : ((orthogonal_projection s.direction) v : V) +ᵥ orthogonal_projection_fn s p ∈ ({orthogonal_projection_fn s (v +ᵥ p)} : set P), { rw ←inter_eq_singleton_orthogonal_projection_fn (v +ᵥ p), exact set.mem_inter hs ho }, rw set.mem_singleton_iff at hm, ext, exact hm.symm end } @[simp] lemma orthogonal_projection_fn_eq {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection_fn s p = orthogonal_projection s p := rfl /-- The linear map corresponding to `orthogonal_projection`. -/ @[simp] lemma orthogonal_projection_linear {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] : (orthogonal_projection s).linear = _root_.orthogonal_projection s.direction := rfl /-- The intersection of the subspace and the orthogonal subspace through the given point is the `orthogonal_projection` of that point onto the subspace. -/ lemma inter_eq_singleton_orthogonal_projection {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : (s : set P) ∩ (mk' p s.direction.orthogonal) = {orthogonal_projection s p} := begin rw ←orthogonal_projection_fn_eq, exact inter_eq_singleton_orthogonal_projection_fn p end /-- The `orthogonal_projection` lies in the given subspace. -/ lemma orthogonal_projection_mem {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : ↑(orthogonal_projection s p) ∈ s := (orthogonal_projection s p).2 /-- The `orthogonal_projection` lies in the orthogonal subspace. -/ lemma orthogonal_projection_mem_orthogonal (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : ↑(orthogonal_projection s p) ∈ mk' p s.direction.orthogonal := orthogonal_projection_fn_mem_orthogonal p /-- Subtracting a point in the given subspace from the `orthogonal_projection` produces a result in the direction of the given subspace. -/ lemma orthogonal_projection_vsub_mem_direction {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : ↑(orthogonal_projection s p2 -ᵥ ⟨p1, hp1⟩ : s.direction) ∈ s.direction := (orthogonal_projection s p2 -ᵥ ⟨p1, hp1⟩ : s.direction).2 /-- Subtracting the `orthogonal_projection` from a point in the given subspace produces a result in the direction of the given subspace. -/ lemma vsub_orthogonal_projection_mem_direction {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : ↑((⟨p1, hp1⟩ : s) -ᵥ orthogonal_projection s p2 : s.direction) ∈ s.direction := ((⟨p1, hp1⟩ : s) -ᵥ orthogonal_projection s p2 : s.direction).2 /-- A point equals its orthogonal projection if and only if it lies in the subspace. -/ lemma orthogonal_projection_eq_self_iff {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} : ↑(orthogonal_projection s p) = p ↔ p ∈ s := begin split, { exact λ h, h ▸ orthogonal_projection_mem p }, { intro h, have hp : p ∈ ((s : set P) ∩ mk' p s.direction.orthogonal) := ⟨h, self_mem_mk' p _⟩, rw [inter_eq_singleton_orthogonal_projection p] at hp, symmetry, exact hp } end /-- Orthogonal projection is idempotent. -/ @[simp] lemma orthogonal_projection_orthogonal_projection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : orthogonal_projection s (orthogonal_projection s p) = orthogonal_projection s p := begin ext, rw orthogonal_projection_eq_self_iff, exact orthogonal_projection_mem p, end lemma eq_orthogonal_projection_of_eq_subspace {s s' : affine_subspace ℝ P} [nonempty s] [nonempty s'] [complete_space s.direction] [complete_space s'.direction] (h : s = s') (p : P) : (orthogonal_projection s p : P) = (orthogonal_projection s' p : P) := begin change orthogonal_projection_fn s p = orthogonal_projection_fn s' p, congr, exact h end /-- The distance to a point's orthogonal projection is 0 iff it lies in the subspace. -/ lemma dist_orthogonal_projection_eq_zero_iff {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} : dist p (orthogonal_projection s p) = 0 ↔ p ∈ s := by rw [dist_comm, dist_eq_zero, orthogonal_projection_eq_self_iff] /-- The distance between a point and its orthogonal projection is nonzero if it does not lie in the subspace. -/ lemma dist_orthogonal_projection_ne_zero_of_not_mem {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} (hp : p ∉ s) : dist p (orthogonal_projection s p) ≠ 0 := mt dist_orthogonal_projection_eq_zero_iff.mp hp /-- Subtracting `p` from its `orthogonal_projection` produces a result in the orthogonal direction. -/ lemma orthogonal_projection_vsub_mem_direction_orthogonal (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : (orthogonal_projection s p : P) -ᵥ p ∈ s.direction.orthogonal := orthogonal_projection_fn_vsub_mem_direction_orthogonal p /-- Subtracting the `orthogonal_projection` from `p` produces a result in the orthogonal direction. -/ lemma vsub_orthogonal_projection_mem_direction_orthogonal (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : p -ᵥ orthogonal_projection s p ∈ s.direction.orthogonal := direction_mk' p s.direction.orthogonal ▸ vsub_mem_direction (self_mem_mk' _ _) (orthogonal_projection_mem_orthogonal s p) /-- Adding a vector to a point in the given subspace, then taking the orthogonal projection, produces the original point if the vector was in the orthogonal direction. -/ lemma orthogonal_projection_vadd_eq_self {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} (hp : p ∈ s) {v : V} (hv : v ∈ s.direction.orthogonal) : orthogonal_projection s (v +ᵥ p) = ⟨p, hp⟩ := begin have h := vsub_orthogonal_projection_mem_direction_orthogonal s (v +ᵥ p), rw [vadd_vsub_assoc, submodule.add_mem_iff_right _ hv] at h, refine (eq_of_vsub_eq_zero _).symm, ext, refine submodule.disjoint_def.1 s.direction.orthogonal_disjoint _ _ h, exact (_ : s.direction).2 end /-- Adding a vector to a point in the given subspace, then taking the orthogonal projection, produces the original point if the vector is a multiple of the result of subtracting a point's orthogonal projection from that point. -/ lemma orthogonal_projection_vadd_smul_vsub_orthogonal_projection {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (r : ℝ) (hp : p1 ∈ s) : orthogonal_projection s (r • (p2 -ᵥ orthogonal_projection s p2 : V) +ᵥ p1) = ⟨p1, hp⟩ := orthogonal_projection_vadd_eq_self hp (submodule.smul_mem _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s _)) /-- The square of the distance from a point in `s` to `p2` equals the sum of the squares of the distances of the two points to the `orthogonal_projection`. -/ lemma dist_square_eq_dist_orthogonal_projection_square_add_dist_orthogonal_projection_square {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p1 : P} (p2 : P) (hp1 : p1 ∈ s) : dist p1 p2 * dist p1 p2 = dist p1 (orthogonal_projection s p2) * dist p1 (orthogonal_projection s p2) + dist p2 (orthogonal_projection s p2) * dist p2 (orthogonal_projection s p2) := begin rw [metric_space.dist_comm p2 _, dist_eq_norm_vsub V p1 _, dist_eq_norm_vsub V p1 _, dist_eq_norm_vsub V _ p2, ← vsub_add_vsub_cancel p1 (orthogonal_projection s p2) p2, norm_add_square_eq_norm_square_add_norm_square_iff_real_inner_eq_zero], exact submodule.inner_right_of_mem_orthogonal (vsub_orthogonal_projection_mem_direction p2 hp1) (orthogonal_projection_vsub_mem_direction_orthogonal s p2), end /-- The square of the distance between two points constructed by adding multiples of the same orthogonal vector to points in the same subspace. -/ lemma dist_square_smul_orthogonal_vadd_smul_orthogonal_vadd {s : affine_subspace ℝ P} {p1 p2 : P} (hp1 : p1 ∈ s) (hp2 : p2 ∈ s) (r1 r2 : ℝ) {v : V} (hv : v ∈ s.direction.orthogonal) : dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) * dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) = dist p1 p2 * dist p1 p2 + (r1 - r2) * (r1 - r2) * (∥v∥ * ∥v∥) := calc dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) * dist (r1 • v +ᵥ p1) (r2 • v +ᵥ p2) = ∥(p1 -ᵥ p2) + (r1 - r2) • v∥ * ∥(p1 -ᵥ p2) + (r1 - r2) • v∥ : by { rw [dist_eq_norm_vsub V (r1 • v +ᵥ p1), vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, sub_smul], abel } ... = ∥p1 -ᵥ p2∥ * ∥p1 -ᵥ p2∥ + ∥(r1 - r2) • v∥ * ∥(r1 - r2) • v∥ : norm_add_square_eq_norm_square_add_norm_square_real (submodule.inner_right_of_mem_orthogonal (vsub_mem_direction hp1 hp2) (submodule.smul_mem _ _ hv)) ... = ∥(p1 -ᵥ p2 : V)∥ * ∥(p1 -ᵥ p2 : V)∥ + abs (r1 - r2) * abs (r1 - r2) * ∥v∥ * ∥v∥ : by { rw [norm_smul, real.norm_eq_abs], ring } ... = dist p1 p2 * dist p1 p2 + (r1 - r2) * (r1 - r2) * (∥v∥ * ∥v∥) : by { rw [dist_eq_norm_vsub V p1, abs_mul_abs_self, mul_assoc] } /-- Reflection in an affine subspace, which is expected to be nonempty and complete. The word "reflection" is sometimes understood to mean specifically reflection in a codimension-one subspace, and sometimes more generally to cover operations such as reflection in a point. The definition here, of reflection in an affine subspace, is a more general sense of the word that includes both those common cases. If the subspace is empty or not complete, `orthogonal_projection` is defined as the identity map, which results in `reflection` being the identity map in that case as well. -/ def reflection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : P ≃ᵢ P := { to_fun := λ p, (↑(orthogonal_projection s p) -ᵥ p) +ᵥ orthogonal_projection s p, inv_fun := λ p, (↑(orthogonal_projection s p) -ᵥ p) +ᵥ orthogonal_projection s p, left_inv := λ p, by simp [vsub_vadd_eq_vsub_sub, -orthogonal_projection_linear], right_inv := λ p, by simp [vsub_vadd_eq_vsub_sub, -orthogonal_projection_linear], isometry_to_fun := begin dsimp only, rw isometry_emetric_iff_metric, intros p₁ p₂, rw [←mul_self_inj_of_nonneg dist_nonneg dist_nonneg, dist_eq_norm_vsub V ((↑(orthogonal_projection s p₁) -ᵥ p₁) +ᵥ ↑(orthogonal_projection s p₁)), dist_eq_norm_vsub V p₁, ←inner_self_eq_norm_square, ←inner_self_eq_norm_square], calc ⟪((orthogonal_projection s p₁ : P) -ᵥ p₁ +ᵥ (orthogonal_projection s p₁ : P) -ᵥ ((orthogonal_projection s p₂ : P) -ᵥ p₂ +ᵥ orthogonal_projection s p₂)), ((orthogonal_projection s p₁ : P) -ᵥ p₁ +ᵥ (orthogonal_projection s p₁ : P) -ᵥ ((orthogonal_projection s p₂ : P) -ᵥ p₂ +ᵥ orthogonal_projection s p₂))⟫ = ⟪(_root_.orthogonal_projection s.direction (p₁ -ᵥ p₂)) + _root_.orthogonal_projection s.direction (p₁ -ᵥ p₂) - (p₁ -ᵥ p₂), _root_.orthogonal_projection s.direction (p₁ -ᵥ p₂) + _root_.orthogonal_projection s.direction (p₁ -ᵥ p₂) - (p₁ -ᵥ p₂)⟫ : by rw [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm, add_sub_assoc, ←vsub_vadd_eq_vsub_sub, vsub_vadd_comm, vsub_vadd_eq_vsub_sub, ←add_sub_assoc, ←coe_vsub, ←affine_map.linear_map_vsub, orthogonal_projection_linear] ... = -4 * inner (p₁ -ᵥ p₂ - (_root_.orthogonal_projection s.direction (p₁ -ᵥ p₂) : V)) (_root_.orthogonal_projection s.direction (p₁ -ᵥ p₂)) + ⟪p₁ -ᵥ p₂, p₁ -ᵥ p₂⟫ : by { simp [inner_sub_left, inner_sub_right, inner_add_left, inner_add_right, real_inner_comm (p₁ -ᵥ p₂)], ring } ... = ⟪p₁ -ᵥ p₂, p₁ -ᵥ p₂⟫ : by simp, end } /-- The result of reflecting. -/ lemma reflection_apply (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : reflection s p = (↑(orthogonal_projection s p) -ᵥ p) +ᵥ orthogonal_projection s p := rfl lemma eq_reflection_of_eq_subspace {s s' : affine_subspace ℝ P} [nonempty s] [nonempty s'] [complete_space s.direction] [complete_space s'.direction] (h : s = s') (p : P) : (reflection s p : P) = (reflection s' p : P) := by simp [reflection_apply, eq_orthogonal_projection_of_eq_subspace h] /-- Reflection is its own inverse. -/ @[simp] lemma reflection_symm (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : (reflection s).symm = reflection s := rfl /-- Reflecting twice in the same subspace. -/ @[simp] lemma reflection_reflection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p : P) : reflection s (reflection s p) = p := (reflection s).left_inv p /-- Reflection is involutive. -/ lemma reflection_involutive (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] : function.involutive (reflection s) := reflection_reflection s /-- A point is its own reflection if and only if it is in the subspace. -/ lemma reflection_eq_self_iff {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] (p : P) : reflection s p = p ↔ p ∈ s := begin rw [←orthogonal_projection_eq_self_iff, reflection_apply], split, { intro h, rw [←@vsub_eq_zero_iff_eq V, vadd_vsub_assoc, ←two_smul ℝ (↑(orthogonal_projection s p) -ᵥ p), smul_eq_zero] at h, norm_num at h, exact h }, { intro h, simp [h] } end /-- Reflecting a point in two subspaces produces the same result if and only if the point has the same orthogonal projection in each of those subspaces. -/ lemma reflection_eq_iff_orthogonal_projection_eq (s₁ s₂ : affine_subspace ℝ P) [nonempty s₁] [nonempty s₂] [complete_space s₁.direction] [complete_space s₂.direction] (p : P) : reflection s₁ p = reflection s₂ p ↔ (orthogonal_projection s₁ p : P) = orthogonal_projection s₂ p := begin rw [reflection_apply, reflection_apply], split, { intro h, rw [←@vsub_eq_zero_iff_eq V, vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_comm, add_sub_assoc, vsub_sub_vsub_cancel_right, ←two_smul ℝ ((orthogonal_projection s₁ p : P) -ᵥ orthogonal_projection s₂ p), smul_eq_zero] at h, norm_num at h, exact h }, { intro h, rw h } end /-- The distance between `p₁` and the reflection of `p₂` equals that between the reflection of `p₁` and `p₂`. -/ lemma dist_reflection (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] (p₁ p₂ : P) : dist p₁ (reflection s p₂) = dist (reflection s p₁) p₂ := begin conv_lhs { rw ←reflection_reflection s p₁ }, exact (reflection s).dist_eq _ _ end /-- A point in the subspace is equidistant from another point and its reflection. -/ lemma dist_reflection_eq_of_mem (s : affine_subspace ℝ P) [nonempty s] [complete_space s.direction] {p₁ : P} (hp₁ : p₁ ∈ s) (p₂ : P) : dist p₁ (reflection s p₂) = dist p₁ p₂ := begin rw ←reflection_eq_self_iff p₁ at hp₁, convert (reflection s).dist_eq p₁ p₂, rw hp₁ end /-- The reflection of a point in a subspace is contained in any larger subspace containing both the point and the subspace reflected in. -/ lemma reflection_mem_of_le_of_mem {s₁ s₂ : affine_subspace ℝ P} [nonempty s₁] [complete_space s₁.direction] (hle : s₁ ≤ s₂) {p : P} (hp : p ∈ s₂) : reflection s₁ p ∈ s₂ := begin rw [reflection_apply], have ho : ↑(orthogonal_projection s₁ p) ∈ s₂ := hle (orthogonal_projection_mem p), exact vadd_mem_of_mem_direction (vsub_mem_direction ho hp) ho end /-- Reflecting an orthogonal vector plus a point in the subspace produces the negation of that vector plus the point. -/ lemma reflection_orthogonal_vadd {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p : P} (hp : p ∈ s) {v : V} (hv : v ∈ s.direction.orthogonal) : reflection s (v +ᵥ p) = -v +ᵥ p := begin rw [reflection_apply, orthogonal_projection_vadd_eq_self hp hv, vsub_vadd_eq_vsub_sub], simp end /-- Reflecting a vector plus a point in the subspace produces the negation of that vector plus the point if the vector is a multiple of the result of subtracting a point's orthogonal projection from that point. -/ lemma reflection_vadd_smul_vsub_orthogonal_projection {s : affine_subspace ℝ P} [nonempty s] [complete_space s.direction] {p₁ : P} (p₂ : P) (r : ℝ) (hp₁ : p₁ ∈ s) : reflection s (r • (p₂ -ᵥ orthogonal_projection s p₂) +ᵥ p₁) = -(r • (p₂ -ᵥ orthogonal_projection s p₂)) +ᵥ p₁ := reflection_orthogonal_vadd hp₁ (submodule.smul_mem _ _ (vsub_orthogonal_projection_mem_direction_orthogonal s _)) omit V /-- A set of points is cospherical if they are equidistant from some point. In two dimensions, this is the same thing as being concyclic. -/ def cospherical (ps : set P) : Prop := ∃ (center : P) (radius : ℝ), ∀ p ∈ ps, dist p center = radius /-- The definition of `cospherical`. -/ lemma cospherical_def (ps : set P) : cospherical ps ↔ ∃ (center : P) (radius : ℝ), ∀ p ∈ ps, dist p center = radius := iff.rfl /-- A subset of a cospherical set is cospherical. -/ lemma cospherical_subset {ps₁ ps₂ : set P} (hs : ps₁ ⊆ ps₂) (hc : cospherical ps₂) : cospherical ps₁ := begin rcases hc with ⟨c, r, hcr⟩, exact ⟨c, r, λ p hp, hcr p (hs hp)⟩ end include V /-- The empty set is cospherical. -/ lemma cospherical_empty : cospherical (∅ : set P) := begin use add_torsor.nonempty.some, simp, end omit V /-- A single point is cospherical. -/ lemma cospherical_singleton (p : P) : cospherical ({p} : set P) := begin use p, simp end include V /-- Two points are cospherical. -/ lemma cospherical_insert_singleton (p₁ p₂ : P) : cospherical ({p₁, p₂} : set P) := begin use [(2⁻¹ : ℝ) • (p₂ -ᵥ p₁) +ᵥ p₁, (2⁻¹ : ℝ) * (dist p₂ p₁)], intro p, rw [set.mem_insert_iff, set.mem_singleton_iff], rintro ⟨_|_⟩, { rw [dist_eq_norm_vsub V p₁, vsub_vadd_eq_vsub_sub, vsub_self, zero_sub, norm_neg, norm_smul, dist_eq_norm_vsub V p₂], simp }, { rw [H, dist_eq_norm_vsub V p₂, vsub_vadd_eq_vsub_sub, dist_eq_norm_vsub V p₂], conv_lhs { congr, congr, rw ←one_smul ℝ (p₂ -ᵥ p₁ : V) }, rw [←sub_smul, norm_smul], norm_num } end /-- Any three points in a cospherical set are affinely independent. -/ lemma cospherical.affine_independent {s : set P} (hs : cospherical s) {p : fin 3 → P} (hps : set.range p ⊆ s) (hpi : function.injective p) : affine_independent ℝ p := begin rw affine_independent_iff_not_collinear, intro hc, rw collinear_iff_of_mem ℝ (set.mem_range_self (0 : fin 3)) at hc, rcases hc with ⟨v, hv⟩, rw set.forall_range_iff at hv, have hv0 : v ≠ 0, { intro h, have he : p 1 = p 0, by simpa [h] using hv 1, exact (dec_trivial : (1 : fin 3) ≠ 0) (hpi he) }, rcases hs with ⟨c, r, hs⟩, have hs' := λ i, hs (p i) (set.mem_of_mem_of_subset (set.mem_range_self _) hps), choose f hf using hv, have hsd : ∀ i, dist ((f i • v) +ᵥ p 0) c = r, { intro i, rw ←hf, exact hs' i }, have hf0 : f 0 = 0, { have hf0' := hf 0, rw [eq_comm, ←@vsub_eq_zero_iff_eq V, vadd_vsub, smul_eq_zero] at hf0', simpa [hv0] using hf0' }, have hfi : function.injective f, { intros i j h, have hi := hf i, rw [h, ←hf j] at hi, exact hpi hi }, simp_rw [←hsd 0, hf0, zero_smul, zero_vadd, dist_smul_vadd_eq_dist (p 0) c hv0] at hsd, have hfn0 : ∀ i, i ≠ 0 → f i ≠ 0 := λ i, (hfi.ne_iff' hf0).2, have hfn0' : ∀ i, i ≠ 0 → f i = (-2) * ⟪v, (p 0 -ᵥ c)⟫ / ⟪v, v⟫, { intros i hi, have hsdi := hsd i, simpa [hfn0, hi] using hsdi }, have hf12 : f 1 = f 2, { rw [hfn0' 1 dec_trivial, hfn0' 2 dec_trivial] }, exact (dec_trivial : (1 : fin 3) ≠ 2) (hfi hf12) end end euclidean_geometry
95b102e959f8d0511333acb2e6fd4de374c32671
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/rvec.lean
33f184ca79f752a829a496af7f8138c02f38e303
[ "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
586
lean
open nat universe variables u inductive rvec (α : Type u) : nat → Type u | nil {} : rvec 0 | cons : Π {n}, rvec n → α → rvec (succ n) namespace rvec local infix (name := cons) :: := cons variables {α β δ : Type u} def map (f : α → β) : Π {n : nat}, rvec α n → rvec β n | 0 nil := nil | (succ n) (v::a) := map v :: f a def map₂ (f : α → β → δ) : Π {n : nat}, rvec α n → rvec β n → rvec δ n | 0 nil nil := nil | (succ n) (v::a) (w::b) := map₂ v w :: f a b lemma ex1 : map succ (nil::1::2) = nil::2::3 := rfl end rvec
0be7386ba7242f7e7f04c1d6bbcfa26b17a2a34e
75db7e3219bba2fbf41bf5b905f34fcb3c6ca3f2
/hott/algebra/category/constructions/set.hlean
04293f864eb2b4eb7d9cb7f8708636f19ca6aa35
[ "Apache-2.0" ]
permissive
jroesch/lean
30ef0860fa905d35b9ad6f76de1a4f65c9af6871
3de4ec1a6ce9a960feb2a48eeea8b53246fa34f2
refs/heads/master
1,586,090,835,348
1,455,142,203,000
1,455,142,277,000
51,536,958
1
0
null
1,455,215,811,000
1,455,215,811,000
null
UTF-8
Lean
false
false
3,605
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, Jakob von Raumer Category of sets -/ import ..functor.basic ..category types.equiv types.lift open eq category equiv iso is_equiv is_trunc function sigma namespace category definition precategory_hset.{u} [reducible] [constructor] : precategory hset.{u} := precategory.mk (λx y : hset, x → y) (λx y z g f a, g (f a)) (λx a, a) (λx y z w h g f, eq_of_homotopy (λa, idp)) (λx y f, eq_of_homotopy (λa, idp)) (λx y f, eq_of_homotopy (λa, idp)) definition Precategory_hset [reducible] [constructor] : Precategory := Precategory.mk hset precategory_hset abbreviation set [constructor] := Precategory_hset namespace set local attribute is_equiv_subtype_eq [instance] definition iso_of_equiv [constructor] {A B : set} (f : A ≃ B) : A ≅ B := iso.MK (to_fun f) (to_inv f) (eq_of_homotopy (left_inv (to_fun f))) (eq_of_homotopy (right_inv (to_fun f))) definition equiv_of_iso [constructor] {A B : set} (f : A ≅ B) : A ≃ B := begin apply equiv.MK (to_hom f) (iso.to_inv f), exact ap10 (to_right_inverse f), exact ap10 (to_left_inverse f) end definition is_equiv_iso_of_equiv [constructor] (A B : set) : is_equiv (@iso_of_equiv A B) := adjointify _ (λf, equiv_of_iso f) (λf, proof iso_eq idp qed) (λf, equiv_eq idp) local attribute is_equiv_iso_of_equiv [instance] definition iso_of_eq_eq_compose (A B : hset) : @iso_of_eq _ _ A B = @iso_of_equiv A B ∘ @equiv_of_eq A B ∘ subtype_eq_inv _ _ ∘ @ap _ _ (to_fun (trunctype.sigma_char 0)) A B := eq_of_homotopy (λp, eq.rec_on p idp) definition equiv_equiv_iso (A B : set) : (A ≃ B) ≃ (A ≅ B) := equiv.MK (λf, iso_of_equiv f) (λf, proof equiv.MK (to_hom f) (iso.to_inv f) (ap10 (to_right_inverse f)) (ap10 (to_left_inverse f)) qed) (λf, proof iso_eq idp qed) (λf, proof equiv_eq idp qed) definition equiv_eq_iso (A B : set) : (A ≃ B) = (A ≅ B) := ua !equiv_equiv_iso definition is_univalent_hset (A B : set) : is_equiv (iso_of_eq : A = B → A ≅ B) := assert H₁ : is_equiv (@iso_of_equiv A B ∘ @equiv_of_eq A B ∘ subtype_eq_inv _ _ ∘ @ap _ _ (to_fun (trunctype.sigma_char 0)) A B), from @is_equiv_compose _ _ _ _ _ (@is_equiv_compose _ _ _ _ _ (@is_equiv_compose _ _ _ _ _ _ (@is_equiv_subtype_eq_inv _ _ _ _ _)) !univalence) !is_equiv_iso_of_equiv, let H₂ := (iso_of_eq_eq_compose A B)⁻¹ in begin rewrite H₂ at H₁, assumption end end set definition category_hset [instance] [constructor] [reducible] : category hset := category.mk precategory_hset set.is_univalent_hset definition Category_hset [reducible] [constructor] : Category := Category.mk hset category_hset abbreviation cset [constructor] := Category_hset open functor lift definition functor_lift.{u v} [constructor] : set.{u} ⇒ set.{max u v} := functor.mk tlift (λa b, lift_functor) (λa, eq_of_homotopy (λx, by induction x; reflexivity)) (λa b c g f, eq_of_homotopy (λx, by induction x; reflexivity)) end category
e20dfc67b4edca8e2400b8c97e56c8140172a850
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/box_integral/box/subbox_induction.lean
69aa3909f65d6802db18d18d97694ad1f9d8b15b
[ "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,996
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.box_integral.box.basic import analysis.specific_limits.basic /-! # Induction on subboxes In this file we prove the following induction principle for `box_integral.box`, see `box_integral.box.subbox_induction_on`. Let `p` be a predicate on `box_integral.box ι`, let `I` be a box. Suppose that the following two properties hold true. * Consider a smaller box `J ≤ I`. The hyperplanes passing through the center of `J` split it into `2 ^ n` boxes. If `p` holds true on each of these boxes, then it is true on `J`. * For each `z` in the closed box `I.Icc` there exists a neighborhood `U` of `z` within `I.Icc` such that for every box `J ≤ I` such that `z ∈ J.Icc ⊆ U`, if `J` is homothetic to `I` with a coefficient of the form `1 / 2 ^ m`, then `p` is true on `J`. Then `p I` is true. ## Tags rectangular box, induction -/ open set finset function filter metric open_locale classical topological_space filter ennreal noncomputable theory namespace box_integral namespace box variables {ι : Type*} {I J : box ι} /-- For a box `I`, the hyperplanes passing through its center split `I` into `2 ^ card ι` boxes. `box_integral.box.split_center_box I s` is one of these boxes. See also `box_integral.partition.split_center` for the corresponding `box_integral.partition`. -/ def split_center_box (I : box ι) (s : set ι) : box ι := { lower := s.piecewise (λ i, (I.lower i + I.upper i) / 2) I.lower, upper := s.piecewise I.upper (λ i, (I.lower i + I.upper i) / 2), lower_lt_upper := λ i, by { dunfold set.piecewise, split_ifs; simp only [left_lt_add_div_two, add_div_two_lt_right, I.lower_lt_upper] } } lemma mem_split_center_box {s : set ι} {y : ι → ℝ} : y ∈ I.split_center_box s ↔ y ∈ I ∧ ∀ i, (I.lower i + I.upper i) / 2 < y i ↔ i ∈ s := begin simp only [split_center_box, mem_def, ← forall_and_distrib], refine forall_congr (λ i, _), dunfold set.piecewise, split_ifs with hs; simp only [hs, iff_true, iff_false, not_lt], exacts [⟨λ H, ⟨⟨(left_lt_add_div_two.2 (I.lower_lt_upper i)).trans H.1, H.2⟩, H.1⟩, λ H, ⟨H.2, H.1.2⟩⟩, ⟨λ H, ⟨⟨H.1, H.2.trans (add_div_two_lt_right.2 (I.lower_lt_upper i)).le⟩, H.2⟩, λ H, ⟨H.1.1, H.2⟩⟩] end lemma split_center_box_le (I : box ι) (s : set ι) : I.split_center_box s ≤ I := λ x hx, (mem_split_center_box.1 hx).1 lemma disjoint_split_center_box (I : box ι) {s t : set ι} (h : s ≠ t) : disjoint (I.split_center_box s : set (ι → ℝ)) (I.split_center_box t) := begin rintro y ⟨hs, ht⟩, apply h, ext i, rw [mem_coe, mem_split_center_box] at hs ht, rw [← hs.2, ← ht.2] end lemma injective_split_center_box (I : box ι) : injective I.split_center_box := λ s t H, by_contra $ λ Hne, (I.disjoint_split_center_box Hne).ne (nonempty_coe _).ne_empty (H ▸ rfl) @[simp] lemma exists_mem_split_center_box {I : box ι} {x : ι → ℝ} : (∃ s, x ∈ I.split_center_box s) ↔ x ∈ I := ⟨λ ⟨s, hs⟩, I.split_center_box_le s hs, λ hx, ⟨{i | (I.lower i + I.upper i) / 2 < x i}, mem_split_center_box.2 ⟨hx, λ i, iff.rfl⟩⟩⟩ /-- `box_integral.box.split_center_box` bundled as a `function.embedding`. -/ @[simps] def split_center_box_emb (I : box ι) : set ι ↪ box ι := ⟨split_center_box I, injective_split_center_box I⟩ @[simp] lemma Union_coe_split_center_box (I : box ι) : (⋃ s, (I.split_center_box s : set (ι → ℝ))) = I := by { ext x, simp } @[simp] lemma upper_sub_lower_split_center_box (I : box ι) (s : set ι) (i : ι) : (I.split_center_box s).upper i - (I.split_center_box s).lower i = (I.upper i - I.lower i) / 2 := by by_cases hs : i ∈ s; field_simp [split_center_box, hs, mul_two, two_mul] /-- Let `p` be a predicate on `box ι`, let `I` be a box. Suppose that the following two properties hold true. * `H_ind` : Consider a smaller box `J ≤ I`. The hyperplanes passing through the center of `J` split it into `2 ^ n` boxes. If `p` holds true on each of these boxes, then it true on `J`. * `H_nhds` : For each `z` in the closed box `I.Icc` there exists a neighborhood `U` of `z` within `I.Icc` such that for every box `J ≤ I` such that `z ∈ J.Icc ⊆ U`, if `J` is homothetic to `I` with a coefficient of the form `1 / 2 ^ m`, then `p` is true on `J`. Then `p I` is true. See also `box_integral.box.subbox_induction_on` for a version using `box_integral.prepartition.split_center` instead of `box_integral.box.split_center_box`. The proof still works if we assume `H_ind` only for subboxes `J ≤ I` that are homothetic to `I` with a coefficient of the form `2⁻ᵐ` but we do not need this generalization yet. -/ @[elab_as_eliminator] lemma subbox_induction_on' {p : box ι → Prop} (I : box ι) (H_ind : ∀ J ≤ I, (∀ s, p (split_center_box J s)) → p J) (H_nhds : ∀ z ∈ I.Icc, ∃ (U ∈ 𝓝[I.Icc] z), ∀ (J ≤ I) (m : ℕ), z ∈ J.Icc → J.Icc ⊆ U → (∀ i, J.upper i - J.lower i = (I.upper i - I.lower i) / 2 ^ m) → p J) : p I := begin by_contra hpI, -- First we use `H_ind` to construct a decreasing sequence of boxes such that `∀ m, ¬p (J m)`. replace H_ind := λ J hJ, not_imp_not.2 (H_ind J hJ), simp only [exists_imp_distrib, not_forall] at H_ind, choose! s hs using H_ind, set J : ℕ → box ι := λ m, (λ J, split_center_box J (s J))^[m] I, have J_succ : ∀ m, J (m + 1) = split_center_box (J m) (s $ J m) := λ m, iterate_succ_apply' _ _ _, -- Now we prove some properties of `J` have hJmono : antitone J, from antitone_nat_of_succ_le (λ n, by simpa [J_succ] using split_center_box_le _ _), have hJle : ∀ m, J m ≤ I, from λ m, hJmono (zero_le m), have hJp : ∀ m, ¬p (J m), from λ m, nat.rec_on m hpI (λ m, by simpa only [J_succ] using hs (J m) (hJle m)), have hJsub : ∀ m i, (J m).upper i - (J m).lower i = (I.upper i - I.lower i) / 2 ^ m, { intros m i, induction m with m ihm, { simp [J] }, simp only [pow_succ', J_succ, upper_sub_lower_split_center_box, ihm, div_div] }, have h0 : J 0 = I, from rfl, -- Now we clear unneeded assumptions clear_value J, clear hpI hs J_succ s, -- Let `z` be the unique common point of all `(J m).Icc`. Then `H_nhds` proves `p (J m)` for -- sufficiently large `m`. This contradicts `hJp`. set z : ι → ℝ := ⨆ m, (J m).lower, have hzJ : ∀ m, z ∈ (J m).Icc, from mem_Inter.1 (csupr_mem_Inter_Icc_of_antitone_Icc ((@box.Icc ι).monotone.comp_antitone hJmono) (λ m, (J m).lower_le_upper)), have hJl_mem : ∀ m, (J m).lower ∈ I.Icc, from λ m, le_iff_Icc.1 (hJle m) (J m).lower_mem_Icc, have hJu_mem : ∀ m, (J m).upper ∈ I.Icc, from λ m, le_iff_Icc.1 (hJle m) (J m).upper_mem_Icc, have hJlz : tendsto (λ m, (J m).lower) at_top (𝓝 z), from tendsto_at_top_csupr (antitone_lower.comp hJmono) ⟨I.upper, λ x ⟨m, hm⟩, hm ▸ (hJl_mem m).2⟩, have hJuz : tendsto (λ m, (J m).upper) at_top (𝓝 z), { suffices : tendsto (λ m, (J m).upper - (J m).lower) at_top (𝓝 0), by simpa using hJlz.add this, refine tendsto_pi_nhds.2 (λ i, _), simpa [hJsub] using tendsto_const_nhds.div_at_top (tendsto_pow_at_top_at_top_of_one_lt (@one_lt_two ℝ _ _)) }, replace hJlz : tendsto (λ m, (J m).lower) at_top (𝓝[Icc I.lower I.upper] z), from tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ hJlz (eventually_of_forall hJl_mem), replace hJuz : tendsto (λ m, (J m).upper) at_top (𝓝[Icc I.lower I.upper] z), from tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ hJuz (eventually_of_forall hJu_mem), rcases H_nhds z (h0 ▸ hzJ 0) with ⟨U, hUz, hU⟩, rcases (tendsto_lift'.1 (hJlz.Icc hJuz) U hUz).exists with ⟨m, hUm⟩, exact hJp m (hU (J m) (hJle m) m (hzJ m) hUm (hJsub m)) end end box end box_integral
5bb75e4f44acfe24e855123c23d383f13b1a68a8
7b89826c26634aa18c0110f1634f73027851edfe
/my_first_project/src/test.lean
75e59d8ef7da3cc7bb32a969799d3858b0017813
[ "MIT" ]
permissive
marcofavorito/leanings
b7642344d8c9012a1cec74a804c5884297880c4d
581b83be66ff4f8dd946fb6a1bb045d2ddf91076
refs/heads/master
1,672,310,991,244
1,603,031,766,000
1,603,031,766,000
279,163,004
1
0
null
null
null
null
UTF-8
Lean
false
false
48
lean
import topology.basic #check topological_space
b3330ff316a3975b2b5b8f1988ddcfa8ba08f459
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/widget/widget2.lean
6e6730b6da5913d86bad04d007a16ddca1d31259
[ "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
385
lean
open widget /-- A simple counter that can be incremented or decremented with some buttons. -/ meta def counter_widget {π α : Type} : component π α := component.ignore_props $ component.stateful int int (λ _ x, 0 <| x) (λ _ x y, (x + y, none)) (λ _ s, h "div" [] [ button "+" (1 : int), html.of_string $ to_string $ s, button "-" (-1) ] ) #html counter_widget
1af8ee75518f644b1c8f637f194424987944f7ab
80162757f50b09d3cad5564907e4c9b00742e045
/rat.lean
a31715edc9f6bf1adfd6b92065bc11ca7ae3e1f9
[]
no_license
EdAyers/edlib
cc30d0a54fed347a85b6df6045f68e6b48bc71a3
78b8c5d91f023f939c102837d748868e2f3ed27d
refs/heads/master
1,586,459,758,216
1,571,322,179,000
1,571,322,179,000
160,538,917
2
0
null
null
null
null
UTF-8
Lean
false
false
9,961
lean
universe u namespace field structure q (α : Type u) [integral_domain α] := (n : α) (d : α ) (nz : d ≠ 0) lemma q.ext {α : Type u} [integral_domain α] : Π (q1 q2 : q α), q1.n = q2.n → q1.d = q2.d → q1 = q2 |⟨n,d,nz⟩ ⟨_,_,_⟩ rfl rfl := rfl instance (α : Type u) [integral_domain α] : setoid (q α) := { r := (λ a b, a.1 * b.2 = b.1 * a.2) , iseqv := ⟨ λ a, rfl , λ a b p, eq.symm p , λ ⟨n₁,d₁,_⟩ ⟨n₂,d₂,h⟩ ⟨n₃,d₃,_⟩ (p : n₁ * d₂ = n₂ * d₁) (q : n₂ * d₃ = n₃ * d₂), suffices d₂ * (n₁ * d₃) = d₂ * (n₃ * d₁), from eq_of_mul_eq_mul_left h this, calc d₂ * (n₁ * d₃) = (n₁ * d₂) * d₃ : by ac_refl ... = (n₂ * d₁) * d₃ : by rw p ... = (n₂ * d₃) * d₁ : by ac_refl ... = (n₃ * d₂) * d₁ : by rw q ... = d₂ * (n₃ * d₁) : by ac_refl ⟩ } def setoid.restrict {α : Type u} (s : setoid α) (P : set α) : setoid ({a:α // a ∈ P}) := { r := λ a₁ a₂, @setoid.r α s a₁ a₂ , iseqv := let ⟨r,y,t⟩ := setoid.iseqv α in ⟨λ a, r _,λ a₁ a₂ q, y q, λ a1 a2 a3 q p, t q p⟩ } section restrict variables {α β : Type u} [s : setoid α] {P : set α} def quotient.restrict (P : set α) := @quotient _ (setoid.restrict s P) def quotient.mk_restrict (a : α) (aP : a ∈ P) : @quotient.restrict α s P := @quotient.mk _ (setoid.restrict s P) ⟨a,aP⟩ def quotient.restrict_sound (a b : α) (aP : a ∈ P) (bP : b ∈ P) (h : @setoid.r α s a b) : quotient.mk_restrict a aP = quotient.mk_restrict b bP := begin apply quotient.sound, apply h end def quotient.restrict_lift_on (q : quotient.restrict P) (f : Π (a:α), a ∈ P → β) (p : ∀ a b (aP : a ∈ P) (bP : b ∈ P), a ≈ b → f a aP = f b bP) : β := @quotient.lift_on _ β (setoid.restrict s P) q (λ ⟨x,xP⟩, f x xP) (λ ⟨a,aP⟩ ⟨b,bP⟩ r, p a b aP bP r) lemma quotient.lift_beta [setoid α] (f : α → β) (p : _) (q:α) : quotient.lift f p (quotient.mk q) = f q := begin simp [quotient.lift], apply quot.lift_beta, apply p end end restrict def free (α : Type u) [integral_domain α] : Type* := @quotient (q α) (by apply_instance) variables {α : Type u} [integral_domain α] namespace free def mul_neq_zero (a b : α) (anz : a ≠ 0) (bnz : b ≠ 0) : a * b ≠ 0 := λ mz, have o : _, from integral_domain.eq_zero_or_eq_zero_of_mul_eq_zero a b mz, or.rec_on o anz bnz def add : free α → free α → free α := λ x y, quotient.lift_on₂ x y (λ x y, ⟦(⟨x.1 * y.2 + y.1 * x.2, x.2 * y.2, mul_ne_zero x.nz y.nz⟩ : q α)⟧) (λ a1 a2 b1 b2, assume p : a1.1 * b1.2 = b1.1 * a1.2, assume q : a2.1 * b2.2 = b2.1 * a2.2, suffices (a1.1 * a2.2 + a2.1 * a1.2) * (b1.2 * b2.2) = (b1.1 * b2.2 + b2.1 * b1.2) * (a1.2 * a2.2), from quotient.sound this, calc ((a1.1 * a2.2) + (a2.1 * a1.2)) * (b1.2 * b2.2) = ((a1.1 * a2.2) * (b1.2 * b2.2) + (a2.1 * a1.2) * (b1.2 * b2.2)) : by apply integral_domain.right_distrib ... = ((a1.1 * b1.2) * (a2.2 * b2.2) + (b1.2 * a1.2) * (a2.1 * b2.2)) : by ac_refl ... = ((b1.1 * a1.2) * (a2.2 * b2.2) + (b1.2 * a1.2) * (b2.1 * a2.2)) : by rw p; rw q ... = (((b1.1 * b2.2)* (a1.2 * a2.2)) + ((b2.1 * b1.2) * (a1.2 * a2.2))) : by ac_refl ... = (b1.1 * b2.2 + b2.1 * b1.2) * (a1.2 * a2.2) : by apply eq.symm; apply integral_domain.right_distrib ) def neg : free α → free α := λ x, quotient.lift_on x (λ x, ⟦(⟨-x.1,x.2,x.nz⟩ : q α)⟧) (λ a b, assume r : a.1 * b.2 = b.1 * a.2, suffices (-a.1) * b.2 = (- b.1)* a.2, from quotient.sound this, by simp [r] ) instance : has_neg (free α) := ⟨neg⟩ instance : has_add (free α) := ⟨λ a b , add a b⟩ def prod.ext {α β : Type u} : Π (p q : α × β) (l : p.1 = q.1) (r : p.2 = q.2), p = q |⟨p1,p2⟩ ⟨q1,q2⟩ rfl rfl := rfl -- lemma add_assoc (A B C : free α) : (A + B) + C = A + (B + C) := begin apply quotient.induction_on A, apply quotient.induction_on B, apply quotient.induction_on C, intros a b c, apply quot.sound, simp [setoid.r], show (a.n * (c.d * b.d) + (b.n * c.d + c.n * b.d) * a.d) * ((c.d) * ((b.d) * (a.d))) = (c.n * (b.d * a.d) + (a.n * b.d + b.n * a.d) * c.d) * ((c.d * b.d) * a.d), repeat {rw [integral_domain.right_distrib]}, generalize ah₁ : (a.n * (c.d * b.d) * (c.d * (b.d * a.d))) = a₁, generalize ah₂: a.n * b.d * c.d * (c.d * b.d * a.d) = a₂, generalize bh₁: b.n * c.d * a.d * (c.d * (b.d * a.d)) = b₁, generalize bh₂: b.n * a.d * c.d * (c.d * b.d * a.d) = b₂, generalize ch₁: c.n * b.d * a.d * (c.d * (b.d * a.d)) = c₁, generalize ch₂: c.n * (b.d * a.d) * (c.d * b.d * a.d) = c₂, have p : a₁ = a₂, by rw [<-ah₁, <-ah₂]; ac_refl, have q : b₁ = b₂, by rw [<-bh₁, <-bh₂]; ac_refl, have r : c₁ = c₂, by rw [<-ch₁, <-ch₂]; ac_refl, rw [p,q,r], ac_refl end def pure : α → free α := λ a, ⟦⟨a,1,one_ne_zero⟩⟧ def zero : free α := free.pure 0 def one : free α := free.pure 1 lemma zero_add (A : free α) : free.zero + A = A := begin apply quotient.induction_on A, intros a, apply quot.sound, simp [setoid.r], end lemma add_comm (A B : free α) : A + B = B + A := begin apply quotient.induction_on₂ A B, intros a b, apply quot.sound, simp [setoid.r], repeat {rw [integral_domain.right_distrib]}, cc end lemma add_zero (A : free α) : A + free.zero = A := by rw [add_comm]; apply zero_add def nonzero (α : Type*) [integral_domain α] := quotient.restrict ({x: q α| x.1 ≠ 0}) def inv_guard (x: nonzero α) : free α := quotient.restrict_lift_on x (λ p nez, quotient.mk $ ⟨p.2,p.1,nez⟩) (λ a b az bz, assume r : a.1 * b.2 = b.1 * a.2, quotient.sound $ show a.d * (b.n) = b.d * a.n, from begin apply eq.symm, rw [integral_domain.mul_comm, r], ac_refl end ) def mul : free α → free α → free α := λ x y, quotient.lift_on₂ x y (λ x y, ⟦(⟨x.1 * y.1, x.2 * y.2, mul_ne_zero x.nz y.nz⟩ : q α)⟧) (λ a1 a2 b1 b2, assume p : a1.1 * b1.2 = b1.1 * a1.2, assume q : a2.1 * b2.2 = b2.1 * a2.2, suffices (a1.1 * a2.1) * (b1.2 * b2.2) = (b1.1* b2.1) * (a1.2 * a2.2), from quotient.sound this, calc (a1.1 * a2.1) * (b1.2 * b2.2) = (a1.1 * b1.2) * (a2.1 * b2.2) : by ac_refl ... = (b1.1 * a1.2) * (b2.1 * a2.2) : by rw [p,q] ... = (b1.1* b2.1) * (a1.2 * a2.2) : by ac_refl ) instance : has_mul (free α) := ⟨mul⟩ def mul_comm (A B : free α) : A * B = B * A := begin apply quotient.induction_on₂ A B, intros a b, apply quot.sound, simp [setoid.r], ac_refl end def mul_assoc (A B C : free α) : (A * B )* C = A * (B * C) := begin apply quotient.induction_on₂ A B, intros a b, apply quotient.induction_on C, intro c, apply quot.sound, simp [setoid.r], ac_refl end #check field.add_left_neg lemma add_left_neg (A : free α) : (-A) + A = free.zero := begin apply quotient.induction_on A, intros a, apply quot.sound, simp [setoid.r], repeat {rw [integral_domain.right_distrib]}, end lemma add_right_neg (A : free α) : (A) + (-A) = free.zero := begin apply quotient.induction_on A, intros a, apply quot.sound, simp [setoid.r], repeat {rw [integral_domain.right_distrib]}, end lemma one_mul (A : free α) : free.one * A = A := begin apply quotient.induction_on A, intros a, apply quot.sound, simp [setoid.r], end lemma mul_one (A : free α) : A * free.one = A := begin apply quotient.induction_on A, intros a, apply quot.sound, simp [setoid.r], end #check congr_arg def congr_arg2 {α β γ : Type*} {f : α → β → γ} : ∀ {a₁ a₂ : α} {b₁ b₂ : β} , (a₁ = a₂) → (b₁ = b₂) → f a₁ b₁ = f a₂ b₂ |_ _ _ _ rfl rfl := rfl lemma right_distrib (A B C : free α) : (A + B) * C = A * C + B * C := begin apply quotient.induction_on A, apply quotient.induction_on B, apply quotient.induction_on C, intros a b c, apply quot.sound, simp [setoid.r], repeat {rw [integral_domain.right_distrib]}, --rw [integral_domain.add_comm], apply congr_arg2, ac_refl, ac_refl end #eval 1 + 2 lemma left_distrib (A B C : free α) : A * ( B + C) = A * B + A * C := begin apply quotient.induction_on A, apply quotient.induction_on B, apply quotient.induction_on C, intros a b c, apply quot.sound, simp [setoid.r], repeat {rw [integral_domain.right_distrib]}, repeat {rw [integral_domain.left_distrib]}, repeat {rw [integral_domain.right_distrib]}, --rw [integral_domain.add_comm], apply congr_arg2, ac_refl, ac_refl end instance : comm_ring (free α) := { zero := zero , mul := mul , add := add , one := one , neg := neg , add_assoc := add_assoc , zero_add := zero_add , add_zero := add_zero , add_comm := add_comm , mul_comm := mul_comm , mul_assoc := mul_assoc , add_left_neg := add_left_neg , one_mul:=one_mul , mul_one:=mul_one , right_distrib:=right_distrib , left_distrib:=left_distrib } -- -- def add : free α → free α → free α -- -- |⟦⟨a,b⟩⟧ ⟦⟨x,y⟩⟧ := ⟦⟨a * y + x * b, b * y⟩⟧ -- -- [TODO] : prove it's a division ring -- instance : division_ring (free α) := sorry -- instance [comm_ring α] : field (free α) := sorry -- -- instance [comm_ring α] [ordered_ring α] : ordered_field (free α) := sorry -- -- [TODO] : the idea is to prove a chain of adjunctions, then show that division ring -> field is reflective. -- -- lots of things lift in ways that I find interesting. Eg ring -> field lifts orderings. -- -- [TODO] : write a functor (ordered field -> complete field) -- -- I wonder if you do universal algebra first, you can get all of this structure for free? end free end field
e4f0df2502b03799893b397ca6f91a9416b3ad08
246309748072bf9f8da313401699689ebbecd94d
/src/algebra/group_power.lean
b20c887113889bea3b720e8e98c5bc28af58a8f3
[ "Apache-2.0" ]
permissive
YJMD/mathlib
b703a641e5f32a996f7842f7c0043bab2b462ee2
7310eab9fa8c1b1229dca42682f1fa6bfb7dbbf9
refs/heads/master
1,670,714,479,314
1,599,035,445,000
1,599,035,445,000
292,279,930
0
0
null
1,599,050,561,000
1,599,050,560,000
null
UTF-8
Lean
false
false
38,021
lean
/- Copyright (c) 2015 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Robert Y. Lewis -/ import algebra.opposites import data.list.basic import data.int.cast import data.equiv.basic import deprecated.group /-! # Power operations on monoids and groups The power operation on monoids and groups. We separate this from group, because it depends on `ℕ`, which in turn depends on other parts of algebra. ## Notation The class `has_pow α β` provides the notation `a^b` for powers. We define instances of `has_pow M ℕ`, for monoids `M`, and `has_pow G ℤ` for groups `G`. We also define infix operators `•ℕ` and `•ℤ` for scalar multiplication by a natural and an integer numbers, respectively. ## Implementation details We adopt the convention that `0^0 = 1`. -/ universes u v w x y z u₁ u₂ variables {M : Type u} {N : Type v} {G : Type w} {H : Type x} {A : Type y} {B : Type z} {R : Type u₁} {S : Type u₂} /-- The power operation in a monoid. `a^n = a*a*...*a` n times. -/ def monoid.pow [has_mul M] [has_one M] (a : M) : ℕ → M | 0 := 1 | (n+1) := a * monoid.pow n /-- The scalar multiplication in an additive monoid. `n •ℕ a = a+a+...+a` n times. -/ def nsmul [has_add A] [has_zero A] (n : ℕ) (a : A) : A := @monoid.pow (multiplicative A) _ { one := (0 : A) } a n infix ` •ℕ `:70 := nsmul @[priority 5] instance monoid.has_pow [monoid M] : has_pow M ℕ := ⟨monoid.pow⟩ /-! ### Commutativity First we prove some facts about `semiconj_by` and `commute`. They do not require any theory about `pow` and/or `nsmul` and will be useful later in this file. -/ namespace semiconj_by variables [monoid M] @[simp] lemma pow_right {a x y : M} (h : semiconj_by a x y) (n : ℕ) : semiconj_by a (x^n) (y^n) := nat.rec_on n (one_right a) $ λ n ihn, h.mul_right ihn end semiconj_by namespace commute variables [monoid M] {a b : M} @[simp] theorem pow_right (h : commute a b) (n : ℕ) : commute a (b ^ n) := h.pow_right n @[simp] theorem pow_left (h : commute a b) (n : ℕ) : commute (a ^ n) b := (h.symm.pow_right n).symm @[simp] theorem pow_pow (h : commute a b) (m n : ℕ) : commute (a ^ m) (b ^ n) := (h.pow_left m).pow_right n @[simp] theorem self_pow (a : M) (n : ℕ) : commute a (a ^ n) := (commute.refl a).pow_right n @[simp] theorem pow_self (a : M) (n : ℕ) : commute (a ^ n) a := (commute.refl a).pow_left n @[simp] theorem pow_pow_self (a : M) (m n : ℕ) : commute (a ^ m) (a ^ n) := (commute.refl a).pow_pow m n end commute /-! ### (Additive) monoid -/ section monoid variables [monoid M] [monoid N] [add_monoid A] [add_monoid B] @[simp] theorem pow_zero (a : M) : a^0 = 1 := rfl @[simp] theorem zero_nsmul (a : A) : 0 •ℕ a = 0 := rfl theorem pow_succ (a : M) (n : ℕ) : a^(n+1) = a * a^n := rfl theorem succ_nsmul (a : A) (n : ℕ) : (n+1) •ℕ a = a + n •ℕ a := rfl @[simp] theorem pow_one (a : M) : a^1 = a := mul_one _ @[simp] theorem one_nsmul (a : A) : 1 •ℕ a = a := add_zero _ @[simp] lemma pow_ite (P : Prop) [decidable P] (a : M) (b c : ℕ) : a ^ (if P then b else c) = if P then a ^ b else a ^ c := by split_ifs; refl @[simp] lemma ite_pow (P : Prop) [decidable P] (a b : M) (c : ℕ) : (if P then a else b) ^ c = if P then a ^ c else b ^ c := by split_ifs; refl @[simp] lemma pow_boole (P : Prop) [decidable P] (a : M) : a ^ (if P then 1 else 0) = if P then a else 1 := by simp theorem pow_mul_comm' (a : M) (n : ℕ) : a^n * a = a * a^n := commute.pow_self a n theorem nsmul_add_comm' : ∀ (a : A) (n : ℕ), n •ℕ a + a = a + n •ℕ a := @pow_mul_comm' (multiplicative A) _ theorem pow_succ' (a : M) (n : ℕ) : a^(n+1) = a^n * a := by rw [pow_succ, pow_mul_comm'] theorem succ_nsmul' (a : A) (n : ℕ) : (n+1) •ℕ a = n •ℕ a + a := @pow_succ' (multiplicative A) _ _ _ theorem pow_two (a : M) : a^2 = a * a := show a*(a*1)=a*a, by rw mul_one theorem two_nsmul (a : A) : 2 •ℕ a = a + a := @pow_two (multiplicative A) _ a theorem pow_add (a : M) (m n : ℕ) : a^(m + n) = a^m * a^n := by induction n with n ih; [rw [add_zero, pow_zero, mul_one], rw [pow_succ', ← mul_assoc, ← ih, ← pow_succ', add_assoc]] theorem add_nsmul : ∀ (a : A) (m n : ℕ), (m + n) •ℕ a = m •ℕ a + n •ℕ a := @pow_add (multiplicative A) _ @[simp] theorem one_pow (n : ℕ) : (1 : M)^n = 1 := by induction n with n ih; [refl, rw [pow_succ, ih, one_mul]] @[simp] theorem nsmul_zero (n : ℕ) : n •ℕ (0 : A) = 0 := by induction n with n ih; [refl, rw [succ_nsmul, ih, zero_add]] theorem pow_mul (a : M) (m n : ℕ) : a^(m * n) = (a^m)^n := by induction n with n ih; [rw mul_zero, rw [nat.mul_succ, pow_add, pow_succ', ih]]; refl theorem mul_nsmul' : ∀ (a : A) (m n : ℕ), m * n •ℕ a = n •ℕ (m •ℕ a) := @pow_mul (multiplicative A) _ theorem pow_mul' (a : M) (m n : ℕ) : a^(m * n) = (a^n)^m := by rw [mul_comm, pow_mul] theorem mul_nsmul (a : A) (m n : ℕ) : m * n •ℕ a = m •ℕ (n •ℕ a) := @pow_mul' (multiplicative A) _ a m n @[simp] theorem nsmul_one [has_one A] : ∀ n : ℕ, n •ℕ (1 : A) = n := add_monoid_hom.eq_nat_cast ⟨λ n, n •ℕ (1 : A), zero_nsmul _, λ _ _, add_nsmul _ _ _⟩ (one_nsmul _) theorem pow_bit0 (a : M) (n : ℕ) : a ^ bit0 n = a^n * a^n := pow_add _ _ _ theorem bit0_nsmul (a : A) (n : ℕ) : bit0 n •ℕ a = n •ℕ a + n •ℕ a := add_nsmul _ _ _ theorem pow_bit1 (a : M) (n : ℕ) : a ^ bit1 n = a^n * a^n * a := by rw [bit1, pow_succ', pow_bit0] theorem bit1_nsmul : ∀ (a : A) (n : ℕ), bit1 n •ℕ a = n •ℕ a + n •ℕ a + a := @pow_bit1 (multiplicative A) _ theorem pow_mul_comm (a : M) (m n : ℕ) : a^m * a^n = a^n * a^m := commute.pow_pow_self a m n theorem nsmul_add_comm : ∀ (a : A) (m n : ℕ), m •ℕ a + n •ℕ a = n •ℕ a + m •ℕ a := @pow_mul_comm (multiplicative A) _ @[simp, priority 500] theorem list.prod_repeat (a : M) (n : ℕ) : (list.repeat a n).prod = a ^ n := begin induction n with n ih, { refl }, { rw [list.repeat_succ, list.prod_cons, ih], refl, } end @[simp, priority 500] theorem list.sum_repeat : ∀ (a : A) (n : ℕ), (list.repeat a n).sum = n •ℕ a := @list.prod_repeat (multiplicative A) _ theorem monoid_hom.map_pow (f : M →* N) (a : M) : ∀(n : ℕ), f (a ^ n) = (f a) ^ n | 0 := f.map_one | (n+1) := by rw [pow_succ, pow_succ, f.map_mul, monoid_hom.map_pow] theorem add_monoid_hom.map_nsmul (f : A →+ B) (a : A) (n : ℕ) : f (n •ℕ a) = n •ℕ f a := f.to_multiplicative.map_pow a n theorem is_monoid_hom.map_pow (f : M → N) [is_monoid_hom f] (a : M) : ∀(n : ℕ), f (a ^ n) = (f a) ^ n := (monoid_hom.of f).map_pow a theorem is_add_monoid_hom.map_nsmul (f : A → B) [is_add_monoid_hom f] (a : A) (n : ℕ) : f (n •ℕ a) = n •ℕ f a := (add_monoid_hom.of f).map_nsmul a n @[simp, norm_cast] lemma units.coe_pow (u : units M) (n : ℕ) : ((u ^ n : units M) : M) = u ^ n := (units.coe_hom M).map_pow u n lemma commute.mul_pow {a b : M} (h : commute a b) (n : ℕ) : (a * b) ^ n = a ^ n * b ^ n := nat.rec_on n (by simp) $ λ n ihn, by simp only [pow_succ, ihn, ← mul_assoc, (h.pow_left n).right_comm] theorem neg_pow [ring R] (a : R) (n : ℕ) : (- a) ^ n = (-1) ^ n * a ^ n := (neg_one_mul a) ▸ (commute.neg_one_left a).mul_pow n end monoid @[simp] theorem nat.pow_eq_pow (p q : ℕ) : @has_pow.pow _ _ monoid.has_pow p q = p ^ q := by induction q with q ih; [refl, rw [nat.pow_succ, pow_succ', ih]] theorem nat.nsmul_eq_mul (m n : ℕ) : m •ℕ n = m * n := by induction m with m ih; [rw [zero_nsmul, zero_mul], rw [succ_nsmul', ih, nat.succ_mul]] /-! ### Commutative (additive) monoid -/ section comm_monoid variables [comm_monoid M] [add_comm_monoid A] theorem mul_pow (a b : M) (n : ℕ) : (a * b)^n = a^n * b^n := (commute.all a b).mul_pow n theorem nsmul_add : ∀ (a b : A) (n : ℕ), n •ℕ (a + b) = n •ℕ a + n •ℕ b := @mul_pow (multiplicative A) _ instance pow.is_monoid_hom (n : ℕ) : is_monoid_hom ((^ n) : M → M) := { map_mul := λ _ _, mul_pow _ _ _, map_one := one_pow _ } instance nsmul.is_add_monoid_hom (n : ℕ) : is_add_monoid_hom (nsmul n : A → A) := { map_add := λ _ _, nsmul_add _ _ _, map_zero := nsmul_zero _ } lemma dvd_pow {x y : M} : ∀ {n : ℕ} (hxy : x ∣ y) (hn : n ≠ 0), x ∣ y^n | 0 hxy hn := (hn rfl).elim | (n+1) hxy hn := by { rw [pow_succ], exact dvd_mul_of_dvd_left hxy _ } end comm_monoid section group variables [group G] [group H] [add_group A] [add_group B] section nat @[simp] theorem inv_pow (a : G) (n : ℕ) : (a⁻¹)^n = (a^n)⁻¹ := by induction n with n ih; [exact one_inv.symm, rw [pow_succ', pow_succ, ih, mul_inv_rev]] @[simp] theorem neg_nsmul : ∀ (a : A) (n : ℕ), n •ℕ (-a) = -(n •ℕ a) := @inv_pow (multiplicative A) _ theorem pow_sub (a : G) {m n : ℕ} (h : n ≤ m) : a^(m - n) = a^m * (a^n)⁻¹ := have h1 : m - n + n = m, from nat.sub_add_cancel h, have h2 : a^(m - n) * a^n = a^m, by rw [←pow_add, h1], eq_mul_inv_of_mul_eq h2 theorem nsmul_sub : ∀ (a : A) {m n : ℕ}, n ≤ m → (m - n) •ℕ a = m •ℕ a - n •ℕ a := @pow_sub (multiplicative A) _ theorem pow_inv_comm (a : G) (m n : ℕ) : (a⁻¹)^m * a^n = a^n * (a⁻¹)^m := (commute.refl a).inv_left.pow_pow m n theorem nsmul_neg_comm : ∀ (a : A) (m n : ℕ), m •ℕ (-a) + n •ℕ a = n •ℕ a + m •ℕ (-a) := @pow_inv_comm (multiplicative A) _ end nat open int /-- The power operation in a group. This extends `monoid.pow` to negative integers with the definition `a^(-n) = (a^n)⁻¹`. -/ def gpow (a : G) : ℤ → G | (of_nat n) := a^n | -[1+n] := (a^(nat.succ n))⁻¹ /-- The scalar multiplication by integers on an additive group. This extends `nsmul` to negative integers with the definition `(-n) •ℤ a = -(n •ℕ a)`. -/ def gsmul (n : ℤ) (a : A) : A := @gpow (multiplicative A) _ a n @[priority 10] instance group.has_pow : has_pow G ℤ := ⟨gpow⟩ infix ` •ℤ `:70 := gsmul @[simp] theorem gpow_coe_nat (a : G) (n : ℕ) : a ^ (n:ℤ) = a ^ n := rfl @[simp] theorem gsmul_coe_nat (a : A) (n : ℕ) : n •ℤ a = n •ℕ a := rfl theorem gpow_of_nat (a : G) (n : ℕ) : a ^ of_nat n = a ^ n := rfl theorem gsmul_of_nat (a : A) (n : ℕ) : of_nat n •ℤ a = n •ℕ a := rfl @[simp] theorem gpow_neg_succ_of_nat (a : G) (n : ℕ) : a ^ -[1+n] = (a ^ n.succ)⁻¹ := rfl @[simp] theorem gsmul_neg_succ_of_nat (a : A) (n : ℕ) : -[1+n] •ℤ a = - (n.succ •ℕ a) := rfl local attribute [ematch] le_of_lt open nat @[simp] theorem gpow_zero (a : G) : a ^ (0:ℤ) = 1 := rfl @[simp] theorem zero_gsmul (a : A) : (0:ℤ) •ℤ a = 0 := rfl @[simp] theorem gpow_one (a : G) : a ^ (1:ℤ) = a := pow_one a @[simp] theorem one_gsmul (a : A) : (1:ℤ) •ℤ a = a := add_zero _ @[simp] theorem one_gpow : ∀ (n : ℤ), (1 : G) ^ n = 1 | (n : ℕ) := one_pow _ | -[1+ n] := show _⁻¹=(1:G), by rw [_root_.one_pow, one_inv] @[simp] theorem gsmul_zero : ∀ (n : ℤ), n •ℤ (0 : A) = 0 := @one_gpow (multiplicative A) _ @[simp] theorem gpow_neg (a : G) : ∀ (n : ℤ), a ^ -n = (a ^ n)⁻¹ | (n+1:ℕ) := rfl | 0 := one_inv.symm | -[1+ n] := (inv_inv _).symm lemma mul_gpow_neg_one (a b : G) : (a*b)^(-(1:ℤ)) = b^(-(1:ℤ))*a^(-(1:ℤ)) := by simp only [mul_inv_rev, gpow_one, gpow_neg] @[simp] theorem neg_gsmul : ∀ (a : A) (n : ℤ), -n •ℤ a = -(n •ℤ a) := @gpow_neg (multiplicative A) _ theorem gpow_neg_one (x : G) : x ^ (-1:ℤ) = x⁻¹ := congr_arg has_inv.inv $ pow_one x theorem neg_one_gsmul (x : A) : (-1:ℤ) •ℤ x = -x := congr_arg has_neg.neg $ one_nsmul x theorem gsmul_one [has_one A] (n : ℤ) : n •ℤ (1 : A) = n := by cases n; simp theorem inv_gpow (a : G) : ∀n:ℤ, a⁻¹ ^ n = (a ^ n)⁻¹ | (n : ℕ) := inv_pow a n | -[1+ n] := congr_arg has_inv.inv $ inv_pow a (n+1) theorem gsmul_neg (a : A) (n : ℤ) : gsmul n (- a) = - gsmul n a := @inv_gpow (multiplicative A) _ a n lemma gpow_add_one (a : G) : ∀ n : ℤ, a ^ (n + 1) = a ^ n * a | (of_nat n) := by simp [← int.coe_nat_succ, pow_succ'] | -[1+0] := by simp [int.neg_succ_of_nat_eq] | -[1+(n+1)] := by rw [int.neg_succ_of_nat_eq, gpow_neg, neg_add, neg_add_cancel_right, gpow_neg, ← int.coe_nat_succ, gpow_coe_nat, gpow_coe_nat, _root_.pow_succ _ (n + 1), mul_inv_rev, inv_mul_cancel_right] theorem add_one_gsmul : ∀ (a : A) (i : ℤ), (i + 1) •ℤ a = i •ℤ a + a := @gpow_add_one (multiplicative A) _ lemma gpow_sub_one (a : G) (n : ℤ) : a ^ (n - 1) = a ^ n * a⁻¹ := calc a ^ (n - 1) = a ^ (n - 1) * a * a⁻¹ : (mul_inv_cancel_right _ _).symm ... = a^n * a⁻¹ : by rw [← gpow_add_one, sub_add_cancel] lemma gpow_add (a : G) (m n : ℤ) : a ^ (m + n) = a ^ m * a ^ n := begin induction n using int.induction_on with n ihn n ihn, case hz : { simp }, { simp only [← add_assoc, gpow_add_one, ihn, mul_assoc] }, { rw [gpow_sub_one, ← mul_assoc, ← ihn, ← gpow_sub_one, add_sub_assoc] } end lemma mul_self_gpow (b : G) (m : ℤ) : b*b^m = b^(m+1) := by { conv_lhs {congr, rw ← gpow_one b }, rw [← gpow_add, add_comm] } lemma mul_gpow_self (b : G) (m : ℤ) : b^m*b = b^(m+1) := by { conv_lhs {congr, skip, rw ← gpow_one b }, rw [← gpow_add, add_comm] } theorem add_gsmul : ∀ (a : A) (i j : ℤ), (i + j) •ℤ a = i •ℤ a + j •ℤ a := @gpow_add (multiplicative A) _ lemma gpow_sub (a : G) (m n : ℤ) : a ^ (m - n) = a ^ m * (a ^ n)⁻¹ := by rw [sub_eq_add_neg, gpow_add, gpow_neg] lemma sub_gsmul (m n : ℤ) (a : A) : (m - n) •ℤ a = m •ℤ a - n •ℤ a := @gpow_sub (multiplicative A) _ _ _ _ theorem gpow_one_add (a : G) (i : ℤ) : a ^ (1 + i) = a * a ^ i := by rw [gpow_add, gpow_one] theorem one_add_gsmul : ∀ (a : A) (i : ℤ), (1 + i) •ℤ a = a + i •ℤ a := @gpow_one_add (multiplicative A) _ theorem gpow_mul_comm (a : G) (i j : ℤ) : a ^ i * a ^ j = a ^ j * a ^ i := by rw [← gpow_add, ← gpow_add, add_comm] theorem gsmul_add_comm : ∀ (a : A) (i j), i •ℤ a + j •ℤ a = j •ℤ a + i •ℤ a := @gpow_mul_comm (multiplicative A) _ theorem gpow_mul (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ m) ^ n := int.induction_on n (by simp) (λ n ihn, by simp [mul_add, gpow_add, ihn]) (λ n ihn, by simp only [mul_sub, gpow_sub, ihn, mul_one, gpow_one]) theorem gsmul_mul' : ∀ (a : A) (m n : ℤ), m * n •ℤ a = n •ℤ (m •ℤ a) := @gpow_mul (multiplicative A) _ theorem gpow_mul' (a : G) (m n : ℤ) : a ^ (m * n) = (a ^ n) ^ m := by rw [mul_comm, gpow_mul] theorem gsmul_mul (a : A) (m n : ℤ) : m * n •ℤ a = m •ℤ (n •ℤ a) := by rw [mul_comm, gsmul_mul'] theorem gpow_bit0 (a : G) (n : ℤ) : a ^ bit0 n = a ^ n * a ^ n := gpow_add _ _ _ theorem bit0_gsmul (a : A) (n : ℤ) : bit0 n •ℤ a = n •ℤ a + n •ℤ a := gpow_add _ _ _ theorem gpow_bit1 (a : G) (n : ℤ) : a ^ bit1 n = a ^ n * a ^ n * a := by rw [bit1, gpow_add]; simp [gpow_bit0] theorem bit1_gsmul : ∀ (a : A) (n : ℤ), bit1 n •ℤ a = n •ℤ a + n •ℤ a + a := @gpow_bit1 (multiplicative A) _ theorem monoid_hom.map_gpow (f : G →* H) (a : G) (n : ℤ) : f (a ^ n) = f a ^ n := by cases n; [exact f.map_pow _ _, exact (f.map_inv _).trans (congr_arg _ $ f.map_pow _ _)] theorem add_monoid_hom.map_gsmul (f : A →+ B) (a : A) (n : ℤ) : f (n •ℤ a) = n •ℤ f a := f.to_multiplicative.map_gpow a n @[simp, norm_cast] lemma units.coe_gpow (u : units G) (n : ℤ) : ((u ^ n : units G) : G) = u ^ n := (units.coe_hom G).map_gpow u n theorem commute.mul_gpow {a b : G} (h : commute a b) : ∀ n : ℤ, (a * b) ^ n = a ^ n * b ^ n | (n : ℕ) := h.mul_pow n | -[1+n] := by simp [h.mul_pow, (h.pow_pow n.succ n.succ).inv_inv.symm.eq] end group section comm_group variables [comm_group G] [add_comm_group A] theorem mul_gpow (a b : G) (n : ℤ) : (a * b)^n = a^n * b^n := (commute.all a b).mul_gpow n theorem gsmul_add : ∀ (a b : A) (n : ℤ), n •ℤ (a + b) = n •ℤ a + n •ℤ b := @mul_gpow (multiplicative A) _ theorem gsmul_sub (a b : A) (n : ℤ) : gsmul n (a - b) = gsmul n a - gsmul n b := by simp only [gsmul_add, gsmul_neg, sub_eq_add_neg] instance gpow.is_group_hom (n : ℤ) : is_group_hom ((^ n) : G → G) := { map_mul := λ _ _, mul_gpow _ _ n } instance gsmul.is_add_group_hom (n : ℤ) : is_add_group_hom (gsmul n : A → A) := { map_add := λ _ _, gsmul_add _ _ n } end comm_group @[simp] lemma with_bot.coe_nsmul [add_monoid A] (a : A) (n : ℕ) : ((nsmul n a : A) : with_bot A) = nsmul n a := add_monoid_hom.map_nsmul ⟨(coe : A → with_bot A), with_bot.coe_zero, with_bot.coe_add⟩ a n theorem nsmul_eq_mul' [semiring R] (a : R) (n : ℕ) : n •ℕ a = a * n := by induction n with n ih; [rw [zero_nsmul, nat.cast_zero, mul_zero], rw [succ_nsmul', ih, nat.cast_succ, mul_add, mul_one]] @[simp] theorem nsmul_eq_mul [semiring R] (n : ℕ) (a : R) : n •ℕ a = n * a := by rw [nsmul_eq_mul', (n.cast_commute a).eq] theorem mul_nsmul_left [semiring R] (a b : R) (n : ℕ) : n •ℕ (a * b) = a * (n •ℕ b) := by rw [nsmul_eq_mul', nsmul_eq_mul', mul_assoc] theorem mul_nsmul_assoc [semiring R] (a b : R) (n : ℕ) : n •ℕ (a * b) = n •ℕ a * b := by rw [nsmul_eq_mul, nsmul_eq_mul, mul_assoc] lemma zero_pow [monoid_with_zero R] : ∀ {n : ℕ}, 0 < n → (0 : R) ^ n = 0 | (n+1) _ := zero_mul _ @[simp, norm_cast] theorem nat.cast_pow [semiring R] (n m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := by induction m with m ih; [exact nat.cast_one, rw [nat.pow_succ, pow_succ', nat.cast_mul, ih]] @[simp, norm_cast] theorem int.coe_nat_pow (n m : ℕ) : ((n ^ m : ℕ) : ℤ) = n ^ m := by induction m with m ih; [exact int.coe_nat_one, rw [nat.pow_succ, pow_succ', int.coe_nat_mul, ih]] theorem int.nat_abs_pow (n : ℤ) (k : ℕ) : int.nat_abs (n ^ k) = (int.nat_abs n) ^ k := by induction k with k ih; [refl, rw [pow_succ', int.nat_abs_mul, nat.pow_succ, ih]] namespace ring_hom variables [semiring R] [semiring S] @[simp] lemma map_pow (f : R →+* S) (a) : ∀ n : ℕ, f (a ^ n) = (f a) ^ n := f.to_monoid_hom.map_pow a end ring_hom theorem neg_one_pow_eq_or [ring R] : ∀ n : ℕ, (-1 : R)^n = 1 ∨ (-1 : R)^n = -1 | 0 := or.inl rfl | (n+1) := (neg_one_pow_eq_or n).swap.imp (λ h, by rw [pow_succ, h, neg_one_mul, neg_neg]) (λ h, by rw [pow_succ, h, mul_one]) lemma pow_dvd_pow [monoid R] (a : R) {m n : ℕ} (h : m ≤ n) : a ^ m ∣ a ^ n := ⟨a ^ (n - m), by rw [← pow_add, nat.add_sub_cancel' h]⟩ theorem pow_dvd_pow_of_dvd [comm_monoid R] {a b : R} (h : a ∣ b) : ∀ n : ℕ, a ^ n ∣ b ^ n | 0 := dvd_refl _ | (n+1) := mul_dvd_mul h (pow_dvd_pow_of_dvd n) lemma pow_two_sub_pow_two {R : Type*} [comm_ring R] (a b : R) : a ^ 2 - b ^ 2 = (a + b) * (a - b) := by simp only [pow_two, mul_sub, add_mul, sub_sub, add_sub, mul_comm, sub_add_cancel] lemma eq_or_eq_neg_of_pow_two_eq_pow_two [integral_domain R] (a b : R) (h : a ^ 2 = b ^ 2) : a = b ∨ a = -b := by rwa [← add_eq_zero_iff_eq_neg, ← sub_eq_zero, or_comm, ← mul_eq_zero, ← pow_two_sub_pow_two a b, sub_eq_zero] -- The next four lemmas allow us to replace multiplication by a numeral with a `gsmul` expression. -- They are used by the `noncomm_ring` tactic, to normalise expressions before passing to `abel`. lemma bit0_mul [ring R] {n r : R} : bit0 n * r = gsmul 2 (n * r) := by { dsimp [bit0], rw [add_mul, add_gsmul, one_gsmul], } lemma mul_bit0 [ring R] {n r : R} : r * bit0 n = gsmul 2 (r * n) := by { dsimp [bit0], rw [mul_add, add_gsmul, one_gsmul], } lemma bit1_mul [ring R] {n r : R} : bit1 n * r = gsmul 2 (n * r) + r := by { dsimp [bit1], rw [add_mul, bit0_mul, one_mul], } lemma mul_bit1 [ring R] {n r : R} : r * bit1 n = gsmul 2 (r * n) + r := by { dsimp [bit1], rw [mul_add, mul_bit0, mul_one], } @[simp] theorem gsmul_eq_mul [ring R] (a : R) : ∀ n, n •ℤ a = n * a | (n : ℕ) := nsmul_eq_mul _ _ | -[1+ n] := show -(_ •ℕ _)=-_*_, by rw [neg_mul_eq_neg_mul_symm, nsmul_eq_mul, nat.cast_succ] theorem gsmul_eq_mul' [ring R] (a : R) (n : ℤ) : n •ℤ a = a * n := by rw [gsmul_eq_mul, (n.cast_commute a).eq] theorem mul_gsmul_left [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = a * (n •ℤ b) := by rw [gsmul_eq_mul', gsmul_eq_mul', mul_assoc] theorem mul_gsmul_assoc [ring R] (a b : R) (n : ℤ) : n •ℤ (a * b) = n •ℤ a * b := by rw [gsmul_eq_mul, gsmul_eq_mul, mul_assoc] @[simp] lemma gsmul_int_int (a b : ℤ) : a •ℤ b = a * b := by simp [gsmul_eq_mul] lemma gsmul_int_one (n : ℤ) : n •ℤ 1 = n := by simp @[simp, norm_cast] theorem int.cast_pow [ring R] (n : ℤ) (m : ℕ) : (↑(n ^ m) : R) = ↑n ^ m := by induction m with m ih; [exact int.cast_one, rw [pow_succ, pow_succ, int.cast_mul, ih]] lemma neg_one_pow_eq_pow_mod_two [ring R] {n : ℕ} : (-1 : R) ^ n = (-1) ^ (n % 2) := by rw [← nat.mod_add_div n 2, pow_add, pow_mul]; simp [pow_two] theorem sq_sub_sq [comm_ring R] (a b : R) : a ^ 2 - b ^ 2 = (a + b) * (a - b) := by rw [pow_two, pow_two, mul_self_sub_mul_self] theorem pow_eq_zero [monoid_with_zero R] [no_zero_divisors R] {x : R} {n : ℕ} (H : x^n = 0) : x = 0 := begin induction n with n ih, { rw pow_zero at H, rw [← mul_one x, H, mul_zero] }, exact or.cases_on (mul_eq_zero.1 H) id ih end @[field_simps] theorem pow_ne_zero [monoid_with_zero R] [no_zero_divisors R] {a : R} (n : ℕ) (h : a ≠ 0) : a ^ n ≠ 0 := mt pow_eq_zero h theorem nsmul_nonneg [ordered_add_comm_monoid R] {a : R} (H : 0 ≤ a) : ∀ n : ℕ, 0 ≤ n •ℕ a | 0 := le_refl _ | (n+1) := add_nonneg H (nsmul_nonneg n) lemma pow_abs [decidable_linear_ordered_comm_ring R] (a : R) (n : ℕ) : (abs a)^n = abs (a^n) := by induction n with n ih; [exact (abs_one).symm, rw [pow_succ, pow_succ, ih, abs_mul]] lemma abs_neg_one_pow [decidable_linear_ordered_comm_ring R] (n : ℕ) : abs ((-1 : R)^n) = 1 := by rw [←pow_abs, abs_neg, abs_one, one_pow] section add_monoid variable [ordered_add_comm_monoid A] theorem nsmul_le_nsmul {a : A} {n m : ℕ} (ha : 0 ≤ a) (h : n ≤ m) : n •ℕ a ≤ m •ℕ a := let ⟨k, hk⟩ := nat.le.dest h in calc n •ℕ a = n •ℕ a + 0 : (add_zero _).symm ... ≤ n •ℕ a + k •ℕ a : add_le_add_left (nsmul_nonneg ha _) _ ... = m •ℕ a : by rw [← hk, add_nsmul] lemma nsmul_le_nsmul_of_le_right {a b : A} (hab : a ≤ b) : ∀ i : ℕ, i •ℕ a ≤ i •ℕ b | 0 := by simp | (k+1) := add_le_add hab (nsmul_le_nsmul_of_le_right _) end add_monoid namespace canonically_ordered_semiring variable [canonically_ordered_comm_semiring R] theorem pow_pos {a : R} (H : 0 < a) : ∀ n : ℕ, 0 < a ^ n | 0 := canonically_ordered_semiring.zero_lt_one | (n+1) := canonically_ordered_semiring.mul_pos.2 ⟨H, pow_pos n⟩ lemma pow_le_pow_of_le_left {a b : R} (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i | 0 := by simp | (k+1) := canonically_ordered_semiring.mul_le_mul hab (pow_le_pow_of_le_left k) theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) (n : ℕ) : 1 ≤ a ^ n := by simpa only [one_pow] using pow_le_pow_of_le_left H n theorem pow_le_one {a : R} (H : a ≤ 1) (n : ℕ) : a ^ n ≤ 1:= by simpa only [one_pow] using pow_le_pow_of_le_left H n end canonically_ordered_semiring section linear_ordered_semiring variable [linear_ordered_semiring R] theorem pow_pos {a : R} (H : 0 < a) : ∀ (n : ℕ), 0 < a ^ n | 0 := zero_lt_one | (n+1) := mul_pos H (pow_pos _) theorem pow_nonneg {a : R} (H : 0 ≤ a) : ∀ (n : ℕ), 0 ≤ a ^ n | 0 := zero_le_one | (n+1) := mul_nonneg H (pow_nonneg _) theorem pow_lt_pow_of_lt_left {x y : R} {n : ℕ} (Hxy : x < y) (Hxpos : 0 ≤ x) (Hnpos : 0 < n) : x ^ n < y ^ n := begin cases lt_or_eq_of_le Hxpos, { rw ←nat.sub_add_cancel Hnpos, induction (n - 1), { simpa only [pow_one] }, rw [pow_add, pow_add, nat.succ_eq_add_one, pow_one, pow_one], apply mul_lt_mul ih (le_of_lt Hxy) h (le_of_lt (pow_pos (lt_trans h Hxy) _)) }, { rw [←h, zero_pow Hnpos], apply pow_pos (by rwa ←h at Hxy : 0 < y),} end theorem pow_left_inj {x y : R} {n : ℕ} (Hxpos : 0 ≤ x) (Hypos : 0 ≤ y) (Hnpos : 0 < n) (Hxyn : x ^ n = y ^ n) : x = y := begin rcases lt_trichotomy x y with hxy | rfl | hyx, { exact absurd Hxyn (ne_of_lt (pow_lt_pow_of_lt_left hxy Hxpos Hnpos)) }, { refl }, { exact absurd Hxyn (ne_of_gt (pow_lt_pow_of_lt_left hyx Hypos Hnpos)) }, end theorem one_le_pow_of_one_le {a : R} (H : 1 ≤ a) : ∀ (n : ℕ), 1 ≤ a ^ n | 0 := le_refl _ | (n+1) := by simpa only [mul_one] using mul_le_mul H (one_le_pow_of_one_le n) zero_le_one (le_trans zero_le_one H) /-- Bernoulli's inequality. This version works for semirings but requires an additional hypothesis `0 ≤ a * a`. -/ theorem one_add_mul_le_pow' {a : R} (Hsqr : 0 ≤ a * a) (H : 0 ≤ 1 + a) : ∀ (n : ℕ), 1 + n •ℕ a ≤ (1 + a) ^ n | 0 := le_of_eq $ add_zero _ | (n+1) := calc 1 + (n + 1) •ℕ a ≤ (1 + a) * (1 + n •ℕ a) : by simpa [succ_nsmul, mul_add, add_mul, mul_nsmul_left, add_comm, add_left_comm] using nsmul_nonneg Hsqr n ... ≤ (1 + a)^(n+1) : mul_le_mul_of_nonneg_left (one_add_mul_le_pow' n) H theorem pow_le_pow {a : R} {n m : ℕ} (ha : 1 ≤ a) (h : n ≤ m) : a ^ n ≤ a ^ m := let ⟨k, hk⟩ := nat.le.dest h in calc a ^ n = a ^ n * 1 : (mul_one _).symm ... ≤ a ^ n * a ^ k : mul_le_mul_of_nonneg_left (one_le_pow_of_one_le ha _) (pow_nonneg (le_trans zero_le_one ha) _) ... = a ^ m : by rw [←hk, pow_add] lemma pow_lt_pow {a : R} {n m : ℕ} (h : 1 < a) (h2 : n < m) : a ^ n < a ^ m := begin have h' : 1 ≤ a := le_of_lt h, have h'' : 0 < a := lt_trans zero_lt_one h, cases m, cases h2, rw [pow_succ, ←one_mul (a ^ n)], exact mul_lt_mul h (pow_le_pow h' (nat.le_of_lt_succ h2)) (pow_pos h'' _) (le_of_lt h'') end lemma pow_le_pow_of_le_left {a b : R} (ha : 0 ≤ a) (hab : a ≤ b) : ∀ i : ℕ, a^i ≤ b^i | 0 := by simp | (k+1) := mul_le_mul hab (pow_le_pow_of_le_left _) (pow_nonneg ha _) (le_trans ha hab) lemma lt_of_pow_lt_pow {a b : R} (n : ℕ) (hb : 0 ≤ b) (h : a ^ n < b ^ n) : a < b := lt_of_not_ge $ λ hn, not_lt_of_ge (pow_le_pow_of_le_left hb hn _) h private lemma pow_lt_pow_of_lt_one_aux {a : R} (h : 0 < a) (ha : a < 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k + 1) < a ^ i | 0 := begin simp only [add_zero], rw ←one_mul (a^i), exact mul_lt_mul ha (le_refl _) (pow_pos h _) zero_le_one end | (k+1) := begin rw ←one_mul (a^i), apply mul_lt_mul ha _ _ zero_le_one, { apply le_of_lt, apply pow_lt_pow_of_lt_one_aux }, { show 0 < a ^ (i + (k + 1) + 0), apply pow_pos h } end private lemma pow_le_pow_of_le_one_aux {a : R} (h : 0 ≤ a) (ha : a ≤ 1) (i : ℕ) : ∀ k : ℕ, a ^ (i + k) ≤ a ^ i | 0 := by simp | (k+1) := by rw [←add_assoc, ←one_mul (a^i)]; exact mul_le_mul ha (pow_le_pow_of_le_one_aux _) (pow_nonneg h _) zero_le_one lemma pow_lt_pow_of_lt_one {a : R} (h : 0 < a) (ha : a < 1) {i j : ℕ} (hij : i < j) : a ^ j < a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_lt hij in by rw hk; exact pow_lt_pow_of_lt_one_aux h ha _ _ lemma pow_le_pow_of_le_one {a : R} (h : 0 ≤ a) (ha : a ≤ 1) {i j : ℕ} (hij : i ≤ j) : a ^ j ≤ a ^ i := let ⟨k, hk⟩ := nat.exists_eq_add_of_le hij in by rw hk; exact pow_le_pow_of_le_one_aux h ha _ _ lemma pow_le_one {x : R} : ∀ (n : ℕ) (h0 : 0 ≤ x) (h1 : x ≤ 1), x ^ n ≤ 1 | 0 h0 h1 := le_refl (1 : R) | (n+1) h0 h1 := mul_le_one h1 (pow_nonneg h0 _) (pow_le_one n h0 h1) end linear_ordered_semiring theorem pow_two_nonneg [linear_ordered_ring R] (a : R) : 0 ≤ a ^ 2 := by { rw pow_two, exact mul_self_nonneg _ } theorem pow_two_pos_of_ne_zero [linear_ordered_ring R] (a : R) (h : a ≠ 0) : 0 < a ^ 2 := lt_of_le_of_ne (pow_two_nonneg a) (pow_ne_zero 2 h).symm /-- Bernoulli's inequality for `n : ℕ`, `-2 ≤ a`. -/ theorem one_add_mul_le_pow [linear_ordered_ring R] {a : R} (H : -2 ≤ a) : ∀ (n : ℕ), 1 + n •ℕ a ≤ (1 + a) ^ n | 0 := le_of_eq $ add_zero _ | 1 := by simp | (n+2) := have H' : 0 ≤ 2 + a, from neg_le_iff_add_nonneg.1 H, have 0 ≤ n •ℕ (a * a * (2 + a)) + a * a, from add_nonneg (nsmul_nonneg (mul_nonneg (mul_self_nonneg a) H') n) (mul_self_nonneg a), calc 1 + (n + 2) •ℕ a ≤ 1 + (n + 2) •ℕ a + (n •ℕ (a * a * (2 + a)) + a * a) : (le_add_iff_nonneg_right _).2 this ... = (1 + a) * (1 + a) * (1 + n •ℕ a) : by { simp only [add_mul, mul_add, mul_two, mul_one, one_mul, succ_nsmul, nsmul_add, mul_nsmul_assoc, (mul_nsmul_left _ _ _).symm], ac_refl } ... ≤ (1 + a) * (1 + a) * (1 + a)^n : mul_le_mul_of_nonneg_left (one_add_mul_le_pow n) (mul_self_nonneg (1 + a)) ... = (1 + a)^(n + 2) : by simp only [pow_succ, mul_assoc] /-- Bernoulli's inequality reformulated to estimate `a^n`. -/ theorem one_add_sub_mul_le_pow [linear_ordered_ring R] {a : R} (H : -1 ≤ a) (n : ℕ) : 1 + n •ℕ (a - 1) ≤ a ^ n := have -2 ≤ a - 1, by { rw [bit0, neg_add], exact sub_le_sub_right H 1 }, by simpa only [add_sub_cancel'_right] using one_add_mul_le_pow this n namespace int lemma units_pow_two (u : units ℤ) : u ^ 2 = 1 := (units_eq_one_or u).elim (λ h, h.symm ▸ rfl) (λ h, h.symm ▸ rfl) lemma units_pow_eq_pow_mod_two (u : units ℤ) (n : ℕ) : u ^ n = u ^ (n % 2) := by conv {to_lhs, rw ← nat.mod_add_div n 2}; rw [pow_add, pow_mul, units_pow_two, one_pow, mul_one] @[simp] lemma nat_abs_pow_two (x : ℤ) : (x.nat_abs ^ 2 : ℤ) = x ^ 2 := by rw [pow_two, int.nat_abs_mul_self', pow_two] end int @[simp] lemma neg_square {α} [ring α] (z : α) : (-z)^2 = z^2 := by simp [pow, monoid.pow] lemma of_add_nsmul [add_monoid A] (x : A) (n : ℕ) : multiplicative.of_add (n •ℕ x) = (multiplicative.of_add x)^n := rfl lemma of_add_gsmul [add_group A] (x : A) (n : ℤ) : multiplicative.of_add (n •ℤ x) = (multiplicative.of_add x)^n := rfl variables (M G A) /-- Monoid homomorphisms from `multiplicative ℕ` are defined by the image of `multiplicative.of_add 1`. -/ def powers_hom [monoid M] : M ≃ (multiplicative ℕ →* M) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, pow_zero x, λ m n, pow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := pow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_pow, ← of_add_nsmul] } } /-- Monoid homomorphisms from `multiplicative ℤ` are defined by the image of `multiplicative.of_add 1`. -/ def gpowers_hom [group G] : G ≃ (multiplicative ℤ →* G) := { to_fun := λ x, ⟨λ n, x ^ n.to_add, gpow_zero x, λ m n, gpow_add x m n⟩, inv_fun := λ f, f (multiplicative.of_add 1), left_inv := gpow_one, right_inv := λ f, monoid_hom.ext $ λ n, by { simp [← f.map_gpow, ← of_add_gsmul ] } } /-- Additive homomorphisms from `ℕ` are defined by the image of `1`. -/ def multiples_hom [add_monoid A] : A ≃ (ℕ →+ A) := { to_fun := λ x, ⟨λ n, n •ℕ x, zero_nsmul x, λ m n, add_nsmul _ _ _⟩, inv_fun := λ f, f 1, left_inv := one_nsmul, right_inv := λ f, add_monoid_hom.ext_nat $ one_nsmul (f 1) } /-- Additive homomorphisms from `ℤ` are defined by the image of `1`. -/ def gmultiples_hom [add_group A] : A ≃ (ℤ →+ A) := { to_fun := λ x, ⟨λ n, n •ℤ x, zero_gsmul x, λ m n, add_gsmul _ _ _⟩, inv_fun := λ f, f 1, left_inv := one_gsmul, right_inv := λ f, add_monoid_hom.ext_int $ one_gsmul (f 1) } variables {M G A} @[simp] lemma powers_hom_apply [monoid M] (x : M) (n : multiplicative ℕ) : powers_hom M x n = x ^ n.to_add := rfl @[simp] lemma powers_hom_symm_apply [monoid M] (f : multiplicative ℕ →* M) : (powers_hom M).symm f = f (multiplicative.of_add 1) := rfl lemma mnat_monoid_hom_eq [monoid M] (f : multiplicative ℕ →* M) (n : multiplicative ℕ) : f n = (f (multiplicative.of_add 1)) ^ n.to_add := by rw [← powers_hom_symm_apply, ← powers_hom_apply, equiv.apply_symm_apply] lemma mnat_monoid_hom_ext [monoid M] ⦃f g : multiplicative ℕ →* M⦄ (h : f (multiplicative.of_add 1) = g (multiplicative.of_add 1)) : f = g := monoid_hom.ext $ λ n, by rw [mnat_monoid_hom_eq f, mnat_monoid_hom_eq g, h] /-! ### Commutativity (again) Facts about `semiconj_by` and `commute` that require `gpow` or `gsmul`, or the fact that integer multiplication equals semiring multiplication. -/ namespace semiconj_by section variables [semiring R] {a x y : R} @[simp] lemma cast_nat_mul_right (h : semiconj_by a x y) (n : ℕ) : semiconj_by a ((n : R) * x) (n * y) := semiconj_by.mul_right (nat.commute_cast _ _) h @[simp] lemma cast_nat_mul_left (h : semiconj_by a x y) (n : ℕ) : semiconj_by ((n : R) * a) x y := semiconj_by.mul_left (nat.cast_commute _ _) h @[simp] lemma cast_nat_mul_cast_nat_mul (h : semiconj_by a x y) (m n : ℕ) : semiconj_by ((m : R) * a) (n * x) (n * y) := (h.cast_nat_mul_left m).cast_nat_mul_right n end variables [monoid M] [group G] [ring R] @[simp] lemma units_gpow_right {a : M} {x y : units M} (h : semiconj_by a x y) : ∀ m : ℤ, semiconj_by a (↑(x^m)) (↑(y^m)) | (n : ℕ) := by simp only [gpow_coe_nat, units.coe_pow, h, pow_right] | -[1+n] := by simp only [gpow_neg_succ_of_nat, units.coe_pow, units_inv_right, h, pow_right] @[simp] lemma gpow_right {a x y : G} (h : semiconj_by a x y) : ∀ m : ℤ, semiconj_by a (x^m) (y^m) | (n : ℕ) := h.pow_right n | -[1+n] := (h.pow_right n.succ).inv_right variables {a b x y x' y' : R} @[simp] lemma cast_int_mul_right (h : semiconj_by a x y) (m : ℤ) : semiconj_by a ((m : ℤ) * x) (m * y) := semiconj_by.mul_right (int.commute_cast _ _) h @[simp] lemma cast_int_mul_left (h : semiconj_by a x y) (m : ℤ) : semiconj_by ((m : R) * a) x y := semiconj_by.mul_left (int.cast_commute _ _) h @[simp] lemma cast_int_mul_cast_int_mul (h : semiconj_by a x y) (m n : ℤ) : semiconj_by ((m : R) * a) (n * x) (n * y) := (h.cast_int_mul_left m).cast_int_mul_right n end semiconj_by namespace commute section variables [semiring R] {a b : R} @[simp] theorem cast_nat_mul_right (h : commute a b) (n : ℕ) : commute a ((n : R) * b) := h.cast_nat_mul_right n @[simp] theorem cast_nat_mul_left (h : commute a b) (n : ℕ) : commute ((n : R) * a) b := h.cast_nat_mul_left n @[simp] theorem cast_nat_mul_cast_nat_mul (h : commute a b) (m n : ℕ) : commute ((m : R) * a) (n * b) := h.cast_nat_mul_cast_nat_mul m n @[simp] theorem self_cast_nat_mul (n : ℕ) : commute a (n * a) := (commute.refl a).cast_nat_mul_right n @[simp] theorem cast_nat_mul_self (n : ℕ) : commute ((n : R) * a) a := (commute.refl a).cast_nat_mul_left n @[simp] theorem self_cast_nat_mul_cast_nat_mul (m n : ℕ) : commute ((m : R) * a) (n * a) := (commute.refl a).cast_nat_mul_cast_nat_mul m n end variables [monoid M] [group G] [ring R] @[simp] lemma units_gpow_right {a : M} {u : units M} (h : commute a u) (m : ℤ) : commute a (↑(u^m)) := h.units_gpow_right m @[simp] lemma units_gpow_left {u : units M} {a : M} (h : commute ↑u a) (m : ℤ) : commute (↑(u^m)) a := (h.symm.units_gpow_right m).symm section variables {a b : G} @[simp] lemma gpow_right (h : commute a b) (m : ℤ) : commute a (b^m) := h.gpow_right m @[simp] lemma gpow_left (h : commute a b) (m : ℤ) : commute (a^m) b := (h.symm.gpow_right m).symm lemma gpow_gpow (h : commute a b) (m n : ℤ) : commute (a^m) (b^n) := (h.gpow_left m).gpow_right n variables (a) (m n : ℕ) @[simp] theorem self_gpow : commute a (a ^ n) := (commute.refl a).gpow_right n @[simp] theorem gpow_self : commute (a ^ n) a := (commute.refl a).gpow_left n @[simp] theorem gpow_gpow_self : commute (a ^ m) (a ^ n) := (commute.refl a).gpow_gpow m n end variables {a b : R} @[simp] lemma cast_int_mul_right (h : commute a b) (m : ℤ) : commute a (m * b) := h.cast_int_mul_right m @[simp] lemma cast_int_mul_left (h : commute a b) (m : ℤ) : commute ((m : R) * a) b := h.cast_int_mul_left m lemma cast_int_mul_cast_int_mul (h : commute a b) (m n : ℤ) : commute ((m : R) * a) (n * b) := h.cast_int_mul_cast_int_mul m n variables (a) (m n : ℤ) @[simp] theorem self_cast_int_mul : commute a (n * a) := (commute.refl a).cast_int_mul_right n @[simp] theorem cast_int_mul_self : commute ((n : R) * a) a := (commute.refl a).cast_int_mul_left n theorem self_cast_int_mul_cast_int_mul : commute ((m : R) * a) (n * a) := (commute.refl a).cast_int_mul_cast_int_mul m n end commute section multiplicative open multiplicative @[simp] lemma nat.to_add_pow (a : multiplicative ℕ) (b : ℕ) : to_add (a ^ b) = to_add a * b := begin induction b with b ih, { erw [pow_zero, to_add_one, mul_zero] }, { simp [*, pow_succ, add_comm, nat.mul_succ] } end @[simp] lemma nat.of_add_mul (a b : ℕ) : of_add (a * b) = of_add a ^ b := (nat.to_add_pow _ _).symm @[simp] lemma int.to_add_pow (a : multiplicative ℤ) (b : ℕ) : to_add (a ^ b) = to_add a * b := by induction b; simp [*, mul_add, pow_succ, add_comm] @[simp] lemma int.to_add_gpow (a : multiplicative ℤ) (b : ℤ) : to_add (a ^ b) = to_add a * b := int.induction_on b (by simp) (by simp [gpow_add, mul_add] {contextual := tt}) (by simp [gpow_add, mul_add, sub_eq_add_neg] {contextual := tt}) @[simp] lemma int.of_add_mul (a b : ℤ) : of_add (a * b) = of_add a ^ b := (int.to_add_gpow _ _).symm end multiplicative namespace units variables [monoid M] lemma conj_pow (u : units M) (x : M) (n : ℕ) : (↑u * x * ↑(u⁻¹))^n = u * x^n * ↑(u⁻¹) := (divp_eq_iff_mul_eq.2 ((u.mk_semiconj_by x).pow_right n).eq.symm).symm lemma conj_pow' (u : units M) (x : M) (n : ℕ) : (↑(u⁻¹) * x * u)^n = ↑(u⁻¹) * x^n * u:= (u⁻¹).conj_pow x n open opposite /-- Moving to the opposite monoid commutes with taking powers. -/ @[simp] lemma op_pow (x : M) (n : ℕ) : op (x ^ n) = (op x) ^ n := begin induction n with n h, { simp }, { rw [pow_succ', op_mul, h, pow_succ] } end @[simp] lemma unop_pow (x : Mᵒᵖ) (n : ℕ) : unop (x ^ n) = (unop x) ^ n := begin induction n with n h, { simp }, { rw [pow_succ', unop_mul, h, pow_succ] } end end units
5cee045b96fddc5993bb36af4d2dfc405ff91542
26ac254ecb57ffcb886ff709cf018390161a9225
/src/algebra/pi_instances.lean
c5d507075ccdb2e709a793203b362f7d196c93b1
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
19,231
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 ## Implementation notes We don't use `by pi_instance` directly because currently instances generated by this tactic have slightly wrong definitions (extra `id`s and `group.mul` instead of `has_mul.mul`). These little bugs prevent Lean from applying a `simp` lemma about `pi.has_one` to `1` coming from `pi.group`. ## TODO Properly fix `tactic.pi_instance`. -/ 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) @[to_additive] instance has_one [∀ i, has_one $ f i] : has_one (Π i : I, f i) := ⟨λ _, 1⟩ @[simp, to_additive] lemma one_apply [∀ i, has_one $ f i] : (1 : Π i, f i) i = 1 := rfl @[to_additive] instance has_mul [∀ i, has_mul $ f i] : has_mul (Π i : I, f i) := ⟨λ f g i, f i * g i⟩ @[simp, to_additive] lemma mul_apply [∀ i, has_mul $ f i] : (x * y) i = x i * y i := rfl @[to_additive] instance has_inv [∀ i, has_inv $ f i] : has_inv (Π i : I, f i) := ⟨λ f i, (f i)⁻¹⟩ @[simp, to_additive] lemma inv_apply [∀ i, has_inv $ f i] : x⁻¹ i = (x i)⁻¹ := rfl 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 has_scalar' {g : I → Type*} [Π i, has_scalar (f i) (g i)] : has_scalar (Π i, f i) (Π i : I, g i) := ⟨λ s x, λ i, (s i) • (x i)⟩ @[simp] lemma smul_apply' {g : I → Type*} [∀ i, has_scalar (f i) (g i)] (s : Π i, f i) (x : Π i, g i) : (s • x) i = s i • x i := rfl @[to_additive add_semigroup] instance semigroup [∀ i, semigroup $ f i] : semigroup (Π i : I, f i) := by refine_struct { mul := (*), .. }; tactic.pi_instance_derive_field @[to_additive add_comm_semigroup] instance comm_semigroup [∀ i, comm_semigroup $ f i] : comm_semigroup (Π i : I, f i) := by refine_struct { mul := (*), .. }; tactic.pi_instance_derive_field @[to_additive add_monoid] instance monoid [∀ i, monoid $ f i] : monoid (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field @[to_additive add_comm_monoid] instance comm_monoid [∀ i, comm_monoid $ f i] : comm_monoid (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field @[to_additive add_group] instance group [∀ i, group $ f i] : group (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), inv := has_inv.inv, .. }; tactic.pi_instance_derive_field @[to_additive add_comm_group] instance comm_group [∀ i, comm_group $ f i] : comm_group (Π i : I, f i) := by refine_struct { one := (1 : Π i, f i), mul := (*), inv := has_inv.inv, .. }; tactic.pi_instance_derive_field instance mul_zero_class [Π i, mul_zero_class $ f i] : mul_zero_class (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), mul := (*), .. }; tactic.pi_instance_derive_field instance distrib [Π i, distrib $ f i] : distrib (Π i : I, f i) := by refine_struct { add := (+), mul := (*), .. }; tactic.pi_instance_derive_field instance semiring [∀ i, semiring $ f i] : semiring (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), one := 1, add := (+), mul := (*), .. }; tactic.pi_instance_derive_field instance ring [∀ i, ring $ f i] : ring (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), one := 1, add := (+), mul := (*), neg := has_neg.neg, .. }; tactic.pi_instance_derive_field instance comm_ring [∀ i, comm_ring $ f i] : comm_ring (Π i : I, f i) := by refine_struct { zero := (0 : Π i, f i), one := 1, add := (+), mul := (*), neg := has_neg.neg, .. }; tactic.pi_instance_derive_field instance mul_action (α) {m : monoid α} [Π i, mul_action α $ f i] : @mul_action α (Π i : I, f i) m := { smul := (•), mul_smul := λ r s f, funext $ λ i, mul_smul _ _ _, one_smul := λ f, funext $ λ i, one_smul α _ } instance mul_action' {g : I → Type*} {m : Π i, monoid (f i)} [Π i, mul_action (f i) (g i)] : @mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) := { smul := (•), 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 _ } instance distrib_mul_action' {g : I → Type*} {m : Π i, monoid (f i)} {n : Π i, add_monoid $ g i} [Π i, distrib_mul_action (f i) (g i)] : @distrib_mul_action (Π i, f i) (Π i : I, g i) (@pi.monoid I f m) (@pi.add_monoid I g n) := { smul_add := by { intros, ext x, apply smul_add }, smul_zero := by { intros, ext x, apply smul_zero } } 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 semimodule' {g : I → Type*} {r : Π i, semiring (f i)} {m : Π i, add_comm_monoid (g i)} [Π i, semimodule (f i) (g i)] : semimodule (Π i, f i) (Π i, g i) := { add_smul := by { intros, ext1, apply add_smul }, zero_smul := by { intros, ext1, apply zero_smul } } @[to_additive add_left_cancel_semigroup] instance left_cancel_semigroup [∀ i, left_cancel_semigroup $ f i] : left_cancel_semigroup (Π i : I, f i) := by refine_struct { mul := (*) }; tactic.pi_instance_derive_field @[to_additive add_right_cancel_semigroup] instance right_cancel_semigroup [∀ i, right_cancel_semigroup $ f i] : right_cancel_semigroup (Π i : I, f i) := by refine_struct { mul := (*) }; tactic.pi_instance_derive_field @[to_additive ordered_cancel_add_comm_monoid] instance ordered_cancel_comm_monoid [∀ i, ordered_cancel_comm_monoid $ f i] : ordered_cancel_comm_monoid (Π i : I, f i) := by refine_struct { mul := (*), one := (1 : Π i, f i), le := (≤), lt := (<), .. pi.partial_order }; tactic.pi_instance_derive_field @[to_additive ordered_add_comm_group] instance ordered_comm_group [∀ i, ordered_comm_group $ f i] : ordered_comm_group (Π i : I, f i) := { mul_le_mul_left := λ x y hxy c i, mul_le_mul_left' (hxy i) _, ..pi.comm_group, ..pi.partial_order } @[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)] -- we need `apply`+`convert` because Lean fails to unify different `add_monoid` instances -- on `Π i, f i` @[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 apply ring_hom.coe_add_monoid_hom_injective, convert add_monoid_hom.functions_ext _ _ _ _; assumption 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
151cb39f5aa8efc2738a35791474f73e66cf53ae
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/special_functions/trigonometric/angle.lean
ef263b8b5c0ad0dedabc85ffe01b06ee298cf143
[ "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
35,780
lean
/- Copyright (c) 2019 Calle Sönne. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Calle Sönne -/ import analysis.special_functions.trigonometric.basic import analysis.normed.group.add_circle import algebra.char_zero.quotient import topology.instances.sign /-! # The type of angles > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we define `real.angle` to be the quotient group `ℝ/2πℤ` and prove a few simple lemmas about trigonometric functions and angles. -/ open_locale real noncomputable theory namespace real /-- The type of angles -/ @[derive [normed_add_comm_group, inhabited, has_coe_t ℝ]] def angle : Type := add_circle (2 * π) namespace angle instance : circular_order real.angle := @add_circle.circular_order _ _ _ _ _ ⟨by norm_num [pi_pos]⟩ _ @[continuity] lemma continuous_coe : continuous (coe : ℝ → angle) := continuous_quotient_mk /-- Coercion `ℝ → angle` as an additive homomorphism. -/ def coe_hom : ℝ →+ angle := quotient_add_group.mk' _ @[simp] lemma coe_coe_hom : (coe_hom : ℝ → angle) = coe := rfl /-- An induction principle to deduce results for `angle` from those for `ℝ`, used with `induction θ using real.angle.induction_on`. -/ @[elab_as_eliminator] protected lemma induction_on {p : angle → Prop} (θ : angle) (h : ∀ x : ℝ, p x) : p θ := quotient.induction_on' θ h @[simp] lemma coe_zero : ↑(0 : ℝ) = (0 : angle) := rfl @[simp] lemma coe_add (x y : ℝ) : ↑(x + y : ℝ) = (↑x + ↑y : angle) := rfl @[simp] lemma coe_neg (x : ℝ) : ↑(-x : ℝ) = -(↑x : angle) := rfl @[simp] lemma coe_sub (x y : ℝ) : ↑(x - y : ℝ) = (↑x - ↑y : angle) := rfl lemma coe_nsmul (n : ℕ) (x : ℝ) : ↑(n • x : ℝ) = (n • ↑x : angle) := rfl lemma coe_zsmul (z : ℤ) (x : ℝ) : ↑(z • x : ℝ) = (z • ↑x : angle) := rfl @[simp, norm_cast] lemma coe_nat_mul_eq_nsmul (x : ℝ) (n : ℕ) : ↑((n : ℝ) * x) = n • (↑x : angle) := by simpa only [nsmul_eq_mul] using coe_hom.map_nsmul x n @[simp, norm_cast] lemma coe_int_mul_eq_zsmul (x : ℝ) (n : ℤ) : ↑((n : ℝ) * x : ℝ) = n • (↑x : angle) := by simpa only [zsmul_eq_mul] using coe_hom.map_zsmul x n lemma angle_eq_iff_two_pi_dvd_sub {ψ θ : ℝ} : (θ : angle) = ψ ↔ ∃ k : ℤ, θ - ψ = 2 * π * k := by simp only [quotient_add_group.eq, add_subgroup.zmultiples_eq_closure, add_subgroup.mem_closure_singleton, zsmul_eq_mul', (sub_eq_neg_add _ _).symm, eq_comm] @[simp] lemma coe_two_pi : ↑(2 * π : ℝ) = (0 : angle) := angle_eq_iff_two_pi_dvd_sub.2 ⟨1, by rw [sub_zero, int.cast_one, mul_one]⟩ @[simp] lemma neg_coe_pi : -(π : angle) = π := begin rw [←coe_neg, angle_eq_iff_two_pi_dvd_sub], use -1, simp [two_mul, sub_eq_add_neg] end @[simp] lemma two_nsmul_coe_div_two (θ : ℝ) : (2 : ℕ) • (↑(θ / 2) : angle) = θ := by rw [←coe_nsmul, two_nsmul, add_halves] @[simp] lemma two_zsmul_coe_div_two (θ : ℝ) : (2 : ℤ) • (↑(θ / 2) : angle) = θ := by rw [←coe_zsmul, two_zsmul, add_halves] @[simp] lemma two_nsmul_neg_pi_div_two : (2 : ℕ) • (↑(-π / 2) : angle) = π := by rw [two_nsmul_coe_div_two, coe_neg, neg_coe_pi] @[simp] lemma two_zsmul_neg_pi_div_two : (2 : ℤ) • (↑(-π / 2) : angle) = π := by rw [two_zsmul, ←two_nsmul, two_nsmul_neg_pi_div_two] lemma sub_coe_pi_eq_add_coe_pi (θ : angle) : θ - π = θ + π := by rw [sub_eq_add_neg, neg_coe_pi] @[simp] lemma two_nsmul_coe_pi : (2 : ℕ) • (π : angle) = 0 := by simp [←coe_nat_mul_eq_nsmul] @[simp] lemma two_zsmul_coe_pi : (2 : ℤ) • (π : angle) = 0 := by simp [←coe_int_mul_eq_zsmul] @[simp] lemma coe_pi_add_coe_pi : (π : real.angle) + π = 0 := by rw [←two_nsmul, two_nsmul_coe_pi] lemma zsmul_eq_iff {ψ θ : angle} {z : ℤ} (hz : z ≠ 0) : z • ψ = z • θ ↔ (∃ k : fin z.nat_abs, ψ = θ + (k : ℕ) • (2 * π / z : ℝ)) := quotient_add_group.zmultiples_zsmul_eq_zsmul_iff hz lemma nsmul_eq_iff {ψ θ : angle} {n : ℕ} (hz : n ≠ 0) : n • ψ = n • θ ↔ (∃ k : fin n, ψ = θ + (k : ℕ) • (2 * π / n : ℝ)) := quotient_add_group.zmultiples_nsmul_eq_nsmul_iff hz lemma two_zsmul_eq_iff {ψ θ : angle} : (2 : ℤ) • ψ = (2 : ℤ) • θ ↔ (ψ = θ ∨ ψ = θ + π) := by rw [zsmul_eq_iff two_ne_zero, int.nat_abs_bit0, int.nat_abs_one, fin.exists_fin_two, fin.coe_zero, fin.coe_one, zero_smul, add_zero, one_smul, int.cast_two, mul_div_cancel_left (_ : ℝ) two_ne_zero] lemma two_nsmul_eq_iff {ψ θ : angle} : (2 : ℕ) • ψ = (2 : ℕ) • θ ↔ (ψ = θ ∨ ψ = θ + π) := by simp_rw [←coe_nat_zsmul, int.coe_nat_bit0, int.coe_nat_one, two_zsmul_eq_iff] lemma two_nsmul_eq_zero_iff {θ : angle} : (2 : ℕ) • θ = 0 ↔ (θ = 0 ∨ θ = π) := by convert two_nsmul_eq_iff; simp lemma two_nsmul_ne_zero_iff {θ : angle} : (2 : ℕ) • θ ≠ 0 ↔ θ ≠ 0 ∧ θ ≠ π := by rw [←not_or_distrib, ←two_nsmul_eq_zero_iff] lemma two_zsmul_eq_zero_iff {θ : angle} : (2 : ℤ) • θ = 0 ↔ (θ = 0 ∨ θ = π) := by simp_rw [two_zsmul, ←two_nsmul, two_nsmul_eq_zero_iff] lemma two_zsmul_ne_zero_iff {θ : angle} : (2 : ℤ) • θ ≠ 0 ↔ θ ≠ 0 ∧ θ ≠ π := by rw [←not_or_distrib, ←two_zsmul_eq_zero_iff] lemma eq_neg_self_iff {θ : angle} : θ = -θ ↔ θ = 0 ∨ θ = π := by rw [←add_eq_zero_iff_eq_neg, ←two_nsmul, two_nsmul_eq_zero_iff] lemma ne_neg_self_iff {θ : angle} : θ ≠ -θ ↔ θ ≠ 0 ∧ θ ≠ π := by rw [←not_or_distrib, ←eq_neg_self_iff.not] lemma neg_eq_self_iff {θ : angle} : -θ = θ ↔ θ = 0 ∨ θ = π := by rw [eq_comm, eq_neg_self_iff] lemma neg_ne_self_iff {θ : angle} : -θ ≠ θ ↔ θ ≠ 0 ∧ θ ≠ π := by rw [←not_or_distrib, ←neg_eq_self_iff.not] lemma two_nsmul_eq_pi_iff {θ : angle} : (2 : ℕ) • θ = π ↔ (θ = (π / 2 : ℝ) ∨ θ = (-π / 2 : ℝ)) := begin have h : (π : angle) = (2 : ℕ) • (π / 2 : ℝ), { rw [two_nsmul, ←coe_add, add_halves] }, nth_rewrite 0 h, rw [two_nsmul_eq_iff], congr', rw [add_comm, ←coe_add, ←sub_eq_zero, ←coe_sub, add_sub_assoc, neg_div, sub_neg_eq_add, add_halves, ←two_mul, coe_two_pi] end lemma two_zsmul_eq_pi_iff {θ : angle} : (2 : ℤ) • θ = π ↔ (θ = (π / 2 : ℝ) ∨ θ = (-π / 2 : ℝ)) := by rw [two_zsmul, ←two_nsmul, two_nsmul_eq_pi_iff] theorem cos_eq_iff_coe_eq_or_eq_neg {θ ψ : ℝ} : cos θ = cos ψ ↔ (θ : angle) = ψ ∨ (θ : angle) = -ψ := begin split, { intro Hcos, rw [← sub_eq_zero, cos_sub_cos, mul_eq_zero, mul_eq_zero, neg_eq_zero, eq_false_intro (two_ne_zero' ℝ), false_or, sin_eq_zero_iff, sin_eq_zero_iff] at Hcos, rcases Hcos with ⟨n, hn⟩ | ⟨n, hn⟩, { right, rw [eq_div_iff_mul_eq (two_ne_zero' ℝ), ← sub_eq_iff_eq_add] at hn, rw [← hn, coe_sub, eq_neg_iff_add_eq_zero, sub_add_cancel, mul_assoc, coe_int_mul_eq_zsmul, mul_comm, coe_two_pi, zsmul_zero] }, { left, rw [eq_div_iff_mul_eq (two_ne_zero' ℝ), eq_sub_iff_add_eq] at hn, rw [← hn, coe_add, mul_assoc, coe_int_mul_eq_zsmul, mul_comm, coe_two_pi, zsmul_zero, zero_add] }, }, { rw [angle_eq_iff_two_pi_dvd_sub, ← coe_neg, angle_eq_iff_two_pi_dvd_sub], rintro (⟨k, H⟩ | ⟨k, H⟩), rw [← sub_eq_zero, cos_sub_cos, H, mul_assoc 2 π k, mul_div_cancel_left _ (two_ne_zero' ℝ), mul_comm π _, sin_int_mul_pi, mul_zero], rw [← sub_eq_zero, cos_sub_cos, ← sub_neg_eq_add, H, mul_assoc 2 π k, mul_div_cancel_left _ (two_ne_zero' ℝ), mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul] } end theorem sin_eq_iff_coe_eq_or_add_eq_pi {θ ψ : ℝ} : sin θ = sin ψ ↔ (θ : angle) = ψ ∨ (θ : angle) + ψ = π := begin split, { intro Hsin, rw [← cos_pi_div_two_sub, ← cos_pi_div_two_sub] at Hsin, cases cos_eq_iff_coe_eq_or_eq_neg.mp Hsin with h h, { left, rw [coe_sub, coe_sub] at h, exact sub_right_inj.1 h }, right, rw [coe_sub, coe_sub, eq_neg_iff_add_eq_zero, add_sub, sub_add_eq_add_sub, ← coe_add, add_halves, sub_sub, sub_eq_zero] at h, exact h.symm }, { rw [angle_eq_iff_two_pi_dvd_sub, ←eq_sub_iff_add_eq, ←coe_sub, angle_eq_iff_two_pi_dvd_sub], rintro (⟨k, H⟩ | ⟨k, H⟩), rw [← sub_eq_zero, sin_sub_sin, H, mul_assoc 2 π k, mul_div_cancel_left _ (two_ne_zero' ℝ), mul_comm π _, sin_int_mul_pi, mul_zero, zero_mul], have H' : θ + ψ = (2 * k) * π + π := by rwa [←sub_add, sub_add_eq_add_sub, sub_eq_iff_eq_add, mul_assoc, mul_comm π _, ←mul_assoc] at H, rw [← sub_eq_zero, sin_sub_sin, H', add_div, mul_assoc 2 _ π, mul_div_cancel_left _ (two_ne_zero' ℝ), cos_add_pi_div_two, sin_int_mul_pi, neg_zero, mul_zero] } end theorem cos_sin_inj {θ ψ : ℝ} (Hcos : cos θ = cos ψ) (Hsin : sin θ = sin ψ) : (θ : angle) = ψ := begin cases cos_eq_iff_coe_eq_or_eq_neg.mp Hcos with hc hc, { exact hc }, cases sin_eq_iff_coe_eq_or_add_eq_pi.mp Hsin with hs hs, { exact hs }, rw [eq_neg_iff_add_eq_zero, hs] at hc, obtain ⟨n, hn⟩ : ∃ n, n • _ = _ := quotient_add_group.left_rel_apply.mp (quotient.exact' hc), rw [← neg_one_mul, add_zero, ← sub_eq_zero, zsmul_eq_mul, ← mul_assoc, ← sub_mul, mul_eq_zero, eq_false_intro (ne_of_gt pi_pos), or_false, sub_neg_eq_add, ← int.cast_zero, ← int.cast_one, ← int.cast_bit0, ← int.cast_mul, ← int.cast_add, int.cast_inj] at hn, have : (n * 2 + 1) % (2:ℤ) = 0 % (2:ℤ) := congr_arg (%(2:ℤ)) hn, rw [add_comm, int.add_mul_mod_self] at this, exact absurd this one_ne_zero end /-- The sine of a `real.angle`. -/ def sin (θ : angle) : ℝ := sin_periodic.lift θ @[simp] lemma sin_coe (x : ℝ) : sin (x : angle) = real.sin x := rfl @[continuity] lemma continuous_sin : continuous sin := real.continuous_sin.quotient_lift_on' _ /-- The cosine of a `real.angle`. -/ def cos (θ : angle) : ℝ := cos_periodic.lift θ @[simp] lemma cos_coe (x : ℝ) : cos (x : angle) = real.cos x := rfl @[continuity] lemma continuous_cos : continuous cos := real.continuous_cos.quotient_lift_on' _ lemma cos_eq_real_cos_iff_eq_or_eq_neg {θ : angle} {ψ : ℝ} : cos θ = real.cos ψ ↔ θ = ψ ∨ θ = -ψ := begin induction θ using real.angle.induction_on, exact cos_eq_iff_coe_eq_or_eq_neg end lemma cos_eq_iff_eq_or_eq_neg {θ ψ : angle} : cos θ = cos ψ ↔ θ = ψ ∨ θ = -ψ := begin induction ψ using real.angle.induction_on, exact cos_eq_real_cos_iff_eq_or_eq_neg end lemma sin_eq_real_sin_iff_eq_or_add_eq_pi {θ : angle} {ψ : ℝ} : sin θ = real.sin ψ ↔ θ = ψ ∨ θ + ψ = π := begin induction θ using real.angle.induction_on, exact sin_eq_iff_coe_eq_or_add_eq_pi end lemma sin_eq_iff_eq_or_add_eq_pi {θ ψ : angle} : sin θ = sin ψ ↔ θ = ψ ∨ θ + ψ = π := begin induction ψ using real.angle.induction_on, exact sin_eq_real_sin_iff_eq_or_add_eq_pi end @[simp] lemma sin_zero : sin (0 : angle) = 0 := by rw [←coe_zero, sin_coe, real.sin_zero] @[simp] lemma sin_coe_pi : sin (π : angle) = 0 := by rw [sin_coe, real.sin_pi] lemma sin_eq_zero_iff {θ : angle} : sin θ = 0 ↔ θ = 0 ∨ θ = π := begin nth_rewrite 0 ←sin_zero, rw sin_eq_iff_eq_or_add_eq_pi, simp end lemma sin_ne_zero_iff {θ : angle} : sin θ ≠ 0 ↔ θ ≠ 0 ∧ θ ≠ π := by rw [←not_or_distrib, ←sin_eq_zero_iff] @[simp] lemma sin_neg (θ : angle) : sin (-θ) = -sin θ := begin induction θ using real.angle.induction_on, exact real.sin_neg _ end lemma sin_antiperiodic : function.antiperiodic sin (π : angle) := begin intro θ, induction θ using real.angle.induction_on, exact real.sin_antiperiodic θ end @[simp] lemma sin_add_pi (θ : angle) : sin (θ + π) = -sin θ := sin_antiperiodic θ @[simp] lemma sin_sub_pi (θ : angle) : sin (θ - π) = -sin θ := sin_antiperiodic.sub_eq θ @[simp] lemma cos_zero : cos (0 : angle) = 1 := by rw [←coe_zero, cos_coe, real.cos_zero] @[simp] lemma cos_coe_pi : cos (π : angle) = -1 := by rw [cos_coe, real.cos_pi] @[simp] lemma cos_neg (θ : angle) : cos (-θ) = cos θ := begin induction θ using real.angle.induction_on, exact real.cos_neg _ end lemma cos_antiperiodic : function.antiperiodic cos (π : angle) := begin intro θ, induction θ using real.angle.induction_on, exact real.cos_antiperiodic θ end @[simp] lemma cos_add_pi (θ : angle) : cos (θ + π) = -cos θ := cos_antiperiodic θ @[simp] lemma cos_sub_pi (θ : angle) : cos (θ - π) = -cos θ := cos_antiperiodic.sub_eq θ lemma cos_eq_zero_iff {θ : angle} : cos θ = 0 ↔ (θ = (π / 2 : ℝ) ∨ θ = (-π / 2 : ℝ)) := by rw [← cos_pi_div_two, ← cos_coe, cos_eq_iff_eq_or_eq_neg, ← coe_neg, ← neg_div] lemma sin_add (θ₁ θ₂ : real.angle) : sin (θ₁ + θ₂) = sin θ₁ * cos θ₂ + cos θ₁ * sin θ₂ := begin induction θ₁ using real.angle.induction_on, induction θ₂ using real.angle.induction_on, exact real.sin_add θ₁ θ₂ end lemma cos_add (θ₁ θ₂ : real.angle) : cos (θ₁ + θ₂) = cos θ₁ * cos θ₂ - sin θ₁ * sin θ₂ := begin induction θ₂ using real.angle.induction_on, induction θ₁ using real.angle.induction_on, exact real.cos_add θ₁ θ₂, end @[simp] lemma cos_sq_add_sin_sq (θ : real.angle) : cos θ ^ 2 + sin θ ^ 2 = 1 := begin induction θ using real.angle.induction_on, exact real.cos_sq_add_sin_sq θ, end lemma sin_add_pi_div_two (θ : angle) : sin (θ + ↑(π / 2)) = cos θ := begin induction θ using real.angle.induction_on, exact sin_add_pi_div_two _ end lemma sin_sub_pi_div_two (θ : angle) : sin (θ - ↑(π / 2)) = -cos θ := begin induction θ using real.angle.induction_on, exact sin_sub_pi_div_two _ end lemma sin_pi_div_two_sub (θ : angle) : sin (↑(π / 2) - θ) = cos θ := begin induction θ using real.angle.induction_on, exact sin_pi_div_two_sub _ end lemma cos_add_pi_div_two (θ : angle) : cos (θ + ↑(π / 2)) = -sin θ := begin induction θ using real.angle.induction_on, exact cos_add_pi_div_two _ end lemma cos_sub_pi_div_two (θ : angle) : cos (θ - ↑(π / 2)) = sin θ := begin induction θ using real.angle.induction_on, exact cos_sub_pi_div_two _ end lemma cos_pi_div_two_sub (θ : angle) : cos (↑(π / 2) - θ) = sin θ := begin induction θ using real.angle.induction_on, exact cos_pi_div_two_sub _ end lemma abs_sin_eq_of_two_nsmul_eq {θ ψ : angle} (h : (2 : ℕ) • θ = (2 : ℕ) • ψ) : |sin θ| = |sin ψ| := begin rw two_nsmul_eq_iff at h, rcases h with rfl | rfl, { refl }, { rw [sin_add_pi, abs_neg] } end lemma abs_sin_eq_of_two_zsmul_eq {θ ψ : angle} (h : (2 : ℤ) • θ = (2 : ℤ) • ψ) : |sin θ| = |sin ψ| := begin simp_rw [two_zsmul, ←two_nsmul] at h, exact abs_sin_eq_of_two_nsmul_eq h end lemma abs_cos_eq_of_two_nsmul_eq {θ ψ : angle} (h : (2 : ℕ) • θ = (2 : ℕ) • ψ) : |cos θ| = |cos ψ| := begin rw two_nsmul_eq_iff at h, rcases h with rfl | rfl, { refl }, { rw [cos_add_pi, abs_neg] } end lemma abs_cos_eq_of_two_zsmul_eq {θ ψ : angle} (h : (2 : ℤ) • θ = (2 : ℤ) • ψ) : |cos θ| = |cos ψ| := begin simp_rw [two_zsmul, ←two_nsmul] at h, exact abs_cos_eq_of_two_nsmul_eq h end @[simp] lemma coe_to_Ico_mod (θ ψ : ℝ) : ↑(to_Ico_mod two_pi_pos ψ θ) = (θ : angle) := begin rw angle_eq_iff_two_pi_dvd_sub, refine ⟨-to_Ico_div two_pi_pos ψ θ, _⟩, rw [to_Ico_mod_sub_self, zsmul_eq_mul, mul_comm] end @[simp] lemma coe_to_Ioc_mod (θ ψ : ℝ) : ↑(to_Ioc_mod two_pi_pos ψ θ) = (θ : angle) := begin rw angle_eq_iff_two_pi_dvd_sub, refine ⟨-to_Ioc_div two_pi_pos ψ θ, _⟩, rw [to_Ioc_mod_sub_self, zsmul_eq_mul, mul_comm] end /-- Convert a `real.angle` to a real number in the interval `Ioc (-π) π`. -/ def to_real (θ : angle) : ℝ := (to_Ioc_mod_periodic two_pi_pos (-π)).lift θ lemma to_real_coe (θ : ℝ) : (θ : angle).to_real = to_Ioc_mod two_pi_pos (-π) θ := rfl lemma to_real_coe_eq_self_iff {θ : ℝ} : (θ : angle).to_real = θ ↔ -π < θ ∧ θ ≤ π := begin rw [to_real_coe, to_Ioc_mod_eq_self two_pi_pos], ring_nf end lemma to_real_coe_eq_self_iff_mem_Ioc {θ : ℝ} : (θ : angle).to_real = θ ↔ θ ∈ set.Ioc (-π) π := by rw [to_real_coe_eq_self_iff, ←set.mem_Ioc] lemma to_real_injective : function.injective to_real := begin intros θ ψ h, induction θ using real.angle.induction_on, induction ψ using real.angle.induction_on, simpa [to_real_coe, to_Ioc_mod_eq_to_Ioc_mod, zsmul_eq_mul, mul_comm _ (2 * π), ←angle_eq_iff_two_pi_dvd_sub, eq_comm] using h, end @[simp] lemma to_real_inj {θ ψ : angle} : θ.to_real = ψ.to_real ↔ θ = ψ := to_real_injective.eq_iff @[simp] lemma coe_to_real (θ : angle): (θ.to_real : angle) = θ := begin induction θ using real.angle.induction_on, exact coe_to_Ioc_mod _ _ end lemma neg_pi_lt_to_real (θ : angle) : -π < θ.to_real := begin induction θ using real.angle.induction_on, exact left_lt_to_Ioc_mod _ _ _ end lemma to_real_le_pi (θ : angle) : θ.to_real ≤ π := begin induction θ using real.angle.induction_on, convert to_Ioc_mod_le_right two_pi_pos _ _, ring end lemma abs_to_real_le_pi (θ : angle) : |θ.to_real| ≤ π := abs_le.2 ⟨(neg_pi_lt_to_real _).le, to_real_le_pi _⟩ lemma to_real_mem_Ioc (θ : angle) : θ.to_real ∈ set.Ioc (-π) π := ⟨neg_pi_lt_to_real _, to_real_le_pi _⟩ @[simp] lemma to_Ioc_mod_to_real (θ : angle): to_Ioc_mod two_pi_pos (-π) θ.to_real = θ.to_real := begin induction θ using real.angle.induction_on, rw to_real_coe, exact to_Ioc_mod_to_Ioc_mod _ _ _ _ end @[simp] lemma to_real_zero : (0 : angle).to_real = 0 := begin rw [←coe_zero, to_real_coe_eq_self_iff], exact ⟨(left.neg_neg_iff.2 real.pi_pos), real.pi_pos.le⟩ end @[simp] lemma to_real_eq_zero_iff {θ : angle} : θ.to_real = 0 ↔ θ = 0 := begin nth_rewrite 0 ←to_real_zero, exact to_real_inj end @[simp] lemma to_real_pi : (π : angle).to_real = π := begin rw [to_real_coe_eq_self_iff], exact ⟨left.neg_lt_self real.pi_pos, le_refl _⟩ end @[simp] lemma to_real_eq_pi_iff {θ : angle} : θ.to_real = π ↔ θ = π := by rw [← to_real_inj, to_real_pi] lemma pi_ne_zero : (π : angle) ≠ 0 := begin rw [←to_real_injective.ne_iff, to_real_pi, to_real_zero], exact pi_ne_zero end @[simp] lemma to_real_pi_div_two : ((π / 2 : ℝ) : angle).to_real = π / 2 := to_real_coe_eq_self_iff.2 $ by split; linarith [pi_pos] @[simp] lemma to_real_eq_pi_div_two_iff {θ : angle} : θ.to_real = π / 2 ↔ θ = (π / 2 : ℝ) := by rw [← to_real_inj, to_real_pi_div_two] @[simp] lemma to_real_neg_pi_div_two : ((-π / 2 : ℝ) : angle).to_real = -π / 2 := to_real_coe_eq_self_iff.2 $ by split; linarith [pi_pos] @[simp] lemma to_real_eq_neg_pi_div_two_iff {θ : angle} : θ.to_real = -π / 2 ↔ θ = (-π / 2 : ℝ) := by rw [← to_real_inj, to_real_neg_pi_div_two] lemma pi_div_two_ne_zero : ((π / 2 : ℝ) : angle) ≠ 0 := begin rw [←to_real_injective.ne_iff, to_real_pi_div_two, to_real_zero], exact div_ne_zero real.pi_ne_zero two_ne_zero end lemma neg_pi_div_two_ne_zero : ((-π / 2 : ℝ) : angle) ≠ 0 := begin rw [←to_real_injective.ne_iff, to_real_neg_pi_div_two, to_real_zero], exact div_ne_zero (neg_ne_zero.2 real.pi_ne_zero) two_ne_zero end lemma abs_to_real_coe_eq_self_iff {θ : ℝ} : |(θ : angle).to_real| = θ ↔ 0 ≤ θ ∧ θ ≤ π := ⟨λ h, h ▸ ⟨abs_nonneg _, abs_to_real_le_pi _⟩, λ h, (to_real_coe_eq_self_iff.2 ⟨(left.neg_neg_iff.2 real.pi_pos).trans_le h.1, h.2⟩).symm ▸ abs_eq_self.2 h.1⟩ lemma abs_to_real_neg_coe_eq_self_iff {θ : ℝ} : |(-θ : angle).to_real| = θ ↔ 0 ≤ θ ∧ θ ≤ π := begin refine ⟨λ h, h ▸ ⟨abs_nonneg _, abs_to_real_le_pi _⟩, λ h, _⟩, by_cases hnegpi : θ = π, { simp [hnegpi, real.pi_pos.le] }, rw [←coe_neg, to_real_coe_eq_self_iff.2 ⟨neg_lt_neg (lt_of_le_of_ne h.2 hnegpi), (neg_nonpos.2 h.1).trans real.pi_pos.le⟩, abs_neg, abs_eq_self.2 h.1] end lemma abs_to_real_eq_pi_div_two_iff {θ : angle} : |θ.to_real| = π / 2 ↔ (θ = (π / 2 : ℝ) ∨ θ = (-π / 2 : ℝ)) := by rw [abs_eq (div_nonneg real.pi_pos.le two_pos.le), ←neg_div, to_real_eq_pi_div_two_iff, to_real_eq_neg_pi_div_two_iff] lemma nsmul_to_real_eq_mul {n : ℕ} (h : n ≠ 0) {θ : angle} : (n • θ).to_real = n * θ.to_real ↔ θ.to_real ∈ set.Ioc (-π / n) (π / n) := begin nth_rewrite 0 ←coe_to_real θ, have h' : 0 < (n : ℝ), { exact_mod_cast nat.pos_of_ne_zero h }, rw [←coe_nsmul, nsmul_eq_mul, to_real_coe_eq_self_iff, set.mem_Ioc, div_lt_iff' h', le_div_iff' h'] end lemma two_nsmul_to_real_eq_two_mul {θ : angle} : ((2 : ℕ) • θ).to_real = 2 * θ.to_real ↔ θ.to_real ∈ set.Ioc (-π / 2) (π / 2) := by exact_mod_cast nsmul_to_real_eq_mul two_ne_zero lemma two_zsmul_to_real_eq_two_mul {θ : angle} : ((2 : ℤ) • θ).to_real = 2 * θ.to_real ↔ θ.to_real ∈ set.Ioc (-π / 2) (π / 2) := by rw [two_zsmul, ←two_nsmul, two_nsmul_to_real_eq_two_mul] lemma to_real_coe_eq_self_sub_two_mul_int_mul_pi_iff {θ : ℝ} {k : ℤ} : (θ : angle).to_real = θ - 2 * k * π ↔ θ ∈ set.Ioc ((2 * k - 1 : ℝ) * π) ((2 * k + 1) * π) := begin rw [←sub_zero (θ : angle), ←zsmul_zero k, ←coe_two_pi, ←coe_zsmul, ←coe_sub, zsmul_eq_mul, ←mul_assoc, mul_comm (k : ℝ), to_real_coe_eq_self_iff, set.mem_Ioc], exact ⟨λ h, ⟨by linarith, by linarith⟩, λ h, ⟨by linarith, by linarith⟩⟩ end lemma to_real_coe_eq_self_sub_two_pi_iff {θ : ℝ} : (θ : angle).to_real = θ - 2 * π ↔ θ ∈ set.Ioc π (3 * π) := by { convert @to_real_coe_eq_self_sub_two_mul_int_mul_pi_iff θ 1; norm_num } lemma to_real_coe_eq_self_add_two_pi_iff {θ : ℝ} : (θ : angle).to_real = θ + 2 * π ↔ θ ∈ set.Ioc (-3 * π) (-π) := by { convert @to_real_coe_eq_self_sub_two_mul_int_mul_pi_iff θ (-1); norm_num } lemma two_nsmul_to_real_eq_two_mul_sub_two_pi {θ : angle} : ((2 : ℕ) • θ).to_real = 2 * θ.to_real - 2 * π ↔ π / 2 < θ.to_real := begin nth_rewrite 0 ←coe_to_real θ, rw [←coe_nsmul, two_nsmul, ←two_mul, to_real_coe_eq_self_sub_two_pi_iff, set.mem_Ioc], exact ⟨λ h, by linarith, λ h, ⟨(div_lt_iff' (zero_lt_two' ℝ)).1 h, by linarith [pi_pos, to_real_le_pi θ]⟩⟩ end lemma two_zsmul_to_real_eq_two_mul_sub_two_pi {θ : angle} : ((2 : ℤ) • θ).to_real = 2 * θ.to_real - 2 * π ↔ π / 2 < θ.to_real := by rw [two_zsmul, ←two_nsmul, two_nsmul_to_real_eq_two_mul_sub_two_pi] lemma two_nsmul_to_real_eq_two_mul_add_two_pi {θ : angle} : ((2 : ℕ) • θ).to_real = 2 * θ.to_real + 2 * π ↔ θ.to_real ≤ -π / 2 := begin nth_rewrite 0 ←coe_to_real θ, rw [←coe_nsmul, two_nsmul, ←two_mul, to_real_coe_eq_self_add_two_pi_iff, set.mem_Ioc], refine ⟨λ h, by linarith, λ h, ⟨by linarith [pi_pos, neg_pi_lt_to_real θ], (le_div_iff' (zero_lt_two' ℝ)).1 h⟩⟩ end lemma two_zsmul_to_real_eq_two_mul_add_two_pi {θ : angle} : ((2 : ℤ) • θ).to_real = 2 * θ.to_real + 2 * π ↔ θ.to_real ≤ -π / 2 := by rw [two_zsmul, ←two_nsmul, two_nsmul_to_real_eq_two_mul_add_two_pi] @[simp] lemma sin_to_real (θ : angle) : real.sin θ.to_real = sin θ := by conv_rhs { rw [← coe_to_real θ, sin_coe] } @[simp] lemma cos_to_real (θ : angle) : real.cos θ.to_real = cos θ := by conv_rhs { rw [← coe_to_real θ, cos_coe] } lemma cos_nonneg_iff_abs_to_real_le_pi_div_two {θ : angle} : 0 ≤ cos θ ↔ |θ.to_real| ≤ π / 2 := begin nth_rewrite 0 ←coe_to_real θ, rw [abs_le, cos_coe], refine ⟨λ h, _, cos_nonneg_of_mem_Icc⟩, by_contra hn, rw [not_and_distrib, not_le, not_le] at hn, refine (not_lt.2 h) _, rcases hn with hn | hn, { rw ←real.cos_neg, refine cos_neg_of_pi_div_two_lt_of_lt (by linarith) _, linarith [neg_pi_lt_to_real θ] }, { refine cos_neg_of_pi_div_two_lt_of_lt hn _, linarith [to_real_le_pi θ] } end lemma cos_pos_iff_abs_to_real_lt_pi_div_two {θ : angle} : 0 < cos θ ↔ |θ.to_real| < π / 2 := begin rw [lt_iff_le_and_ne, lt_iff_le_and_ne, cos_nonneg_iff_abs_to_real_le_pi_div_two, ←and_congr_right], rintro -, rw [ne.def, ne.def, not_iff_not, @eq_comm ℝ 0, abs_to_real_eq_pi_div_two_iff, cos_eq_zero_iff] end lemma cos_neg_iff_pi_div_two_lt_abs_to_real {θ : angle} : cos θ < 0 ↔ π / 2 < |θ.to_real| := by rw [←not_le, ←not_le, not_iff_not, cos_nonneg_iff_abs_to_real_le_pi_div_two] lemma abs_cos_eq_abs_sin_of_two_nsmul_add_two_nsmul_eq_pi {θ ψ : angle} (h : (2 : ℕ) • θ + (2 : ℕ) • ψ = π) : |cos θ| = |sin ψ| := begin rw [←eq_sub_iff_add_eq, ←two_nsmul_coe_div_two, ←nsmul_sub, two_nsmul_eq_iff] at h, rcases h with rfl | rfl; simp [cos_pi_div_two_sub] end lemma abs_cos_eq_abs_sin_of_two_zsmul_add_two_zsmul_eq_pi {θ ψ : angle} (h : (2 : ℤ) • θ + (2 : ℤ) • ψ = π) : |cos θ| = |sin ψ| := begin simp_rw [two_zsmul, ←two_nsmul] at h, exact abs_cos_eq_abs_sin_of_two_nsmul_add_two_nsmul_eq_pi h end /-- The tangent of a `real.angle`. -/ def tan (θ : angle) : ℝ := sin θ / cos θ lemma tan_eq_sin_div_cos (θ : angle) : tan θ = sin θ / cos θ := rfl @[simp] lemma tan_coe (x : ℝ) : tan (x : angle) = real.tan x := by rw [tan, sin_coe, cos_coe, real.tan_eq_sin_div_cos] @[simp] lemma tan_zero : tan (0 : angle) = 0 := by rw [←coe_zero, tan_coe, real.tan_zero] @[simp] lemma tan_coe_pi : tan (π : angle) = 0 := by rw [tan_eq_sin_div_cos, sin_coe_pi, zero_div] lemma tan_periodic : function.periodic tan (π : angle) := begin intro θ, induction θ using real.angle.induction_on, rw [←coe_add, tan_coe, tan_coe], exact real.tan_periodic θ end @[simp] lemma tan_add_pi (θ : angle) : tan (θ + π) = tan θ := tan_periodic θ @[simp] lemma tan_sub_pi (θ : angle) : tan (θ - π) = tan θ := tan_periodic.sub_eq θ @[simp] lemma tan_to_real (θ : angle) : real.tan θ.to_real = tan θ := by conv_rhs { rw [←coe_to_real θ, tan_coe] } lemma tan_eq_of_two_nsmul_eq {θ ψ : angle} (h : (2 : ℕ) • θ = (2 : ℕ) • ψ) : tan θ = tan ψ := begin rw two_nsmul_eq_iff at h, rcases h with rfl | rfl, { refl }, { exact tan_add_pi _ } end lemma tan_eq_of_two_zsmul_eq {θ ψ : angle} (h : (2 : ℤ) • θ = (2 : ℤ) • ψ) : tan θ = tan ψ := begin simp_rw [two_zsmul, ←two_nsmul] at h, exact tan_eq_of_two_nsmul_eq h end lemma tan_eq_inv_of_two_nsmul_add_two_nsmul_eq_pi {θ ψ : angle} (h : (2 : ℕ) • θ + (2 : ℕ) • ψ = π) : tan ψ = (tan θ)⁻¹ := begin induction θ using real.angle.induction_on, induction ψ using real.angle.induction_on, rw [←smul_add, ←coe_add, ←coe_nsmul, two_nsmul, ←two_mul, angle_eq_iff_two_pi_dvd_sub] at h, rcases h with ⟨k, h⟩, rw [sub_eq_iff_eq_add, ←mul_inv_cancel_left₀ two_ne_zero π, mul_assoc, ←mul_add, mul_right_inj' (two_ne_zero' ℝ), ←eq_sub_iff_add_eq', mul_inv_cancel_left₀ two_ne_zero π, inv_mul_eq_div, mul_comm] at h, rw [tan_coe, tan_coe, ←tan_pi_div_two_sub, h, add_sub_assoc, add_comm], exact real.tan_periodic.int_mul _ _ end lemma tan_eq_inv_of_two_zsmul_add_two_zsmul_eq_pi {θ ψ : angle} (h : (2 : ℤ) • θ + (2 : ℤ) • ψ = π) : tan ψ = (tan θ)⁻¹ := begin simp_rw [two_zsmul, ←two_nsmul] at h, exact tan_eq_inv_of_two_nsmul_add_two_nsmul_eq_pi h end /-- The sign of a `real.angle` is `0` if the angle is `0` or `π`, `1` if the angle is strictly between `0` and `π` and `-1` is the angle is strictly between `-π` and `0`. It is defined as the sign of the sine of the angle. -/ def sign (θ : angle) : sign_type := sign (sin θ) @[simp] lemma sign_zero : (0 : angle).sign = 0 := by rw [sign, sin_zero, sign_zero] @[simp] lemma sign_coe_pi : (π : angle).sign = 0 := by rw [sign, sin_coe_pi, _root_.sign_zero] @[simp] lemma sign_neg (θ : angle) : (-θ).sign = - θ.sign := by simp_rw [sign, sin_neg, left.sign_neg] lemma sign_antiperiodic : function.antiperiodic sign (π : angle) := λ θ, by rw [sign, sign, sin_add_pi, left.sign_neg] @[simp] lemma sign_add_pi (θ : angle) : (θ + π).sign = -θ.sign := sign_antiperiodic θ @[simp] lemma sign_pi_add (θ : angle) : ((π : angle) + θ).sign = -θ.sign := by rw [add_comm, sign_add_pi] @[simp] lemma sign_sub_pi (θ : angle) : (θ - π).sign = -θ.sign := sign_antiperiodic.sub_eq θ @[simp] lemma sign_pi_sub (θ : angle) : ((π : angle) - θ).sign = θ.sign := by simp [sign_antiperiodic.sub_eq'] lemma sign_eq_zero_iff {θ : angle} : θ.sign = 0 ↔ θ = 0 ∨ θ = π := by rw [sign, sign_eq_zero_iff, sin_eq_zero_iff] lemma sign_ne_zero_iff {θ : angle} : θ.sign ≠ 0 ↔ θ ≠ 0 ∧ θ ≠ π := by rw [←not_or_distrib, ←sign_eq_zero_iff] lemma to_real_neg_iff_sign_neg {θ : angle} : θ.to_real < 0 ↔ θ.sign = -1 := begin rw [sign, ←sin_to_real, sign_eq_neg_one_iff], rcases lt_trichotomy θ.to_real 0 with (h|h|h), { exact ⟨λ _, real.sin_neg_of_neg_of_neg_pi_lt h (neg_pi_lt_to_real θ), λ _, h⟩ }, { simp [h] }, { exact ⟨λ hn, false.elim (h.asymm hn), λ hn, false.elim (hn.not_le (sin_nonneg_of_nonneg_of_le_pi h.le (to_real_le_pi θ)))⟩ } end lemma to_real_nonneg_iff_sign_nonneg {θ : angle} : 0 ≤ θ.to_real ↔ 0 ≤ θ.sign := begin rcases lt_trichotomy θ.to_real 0 with (h|h|h), { refine ⟨λ hn, false.elim (h.not_le hn), λ hn, _⟩, rw [to_real_neg_iff_sign_neg.1 h] at hn, exact false.elim (hn.not_lt dec_trivial) }, { simp [h, sign, ←sin_to_real] }, { refine ⟨λ _, _, λ _, h.le⟩, rw [sign, ←sin_to_real, sign_nonneg_iff], exact sin_nonneg_of_nonneg_of_le_pi h.le (to_real_le_pi θ) } end @[simp] lemma sign_to_real {θ : angle} (h : θ ≠ π) : _root_.sign θ.to_real = θ.sign := begin rcases lt_trichotomy θ.to_real 0 with (ht|ht|ht), { simp [ht, to_real_neg_iff_sign_neg.1 ht] }, { simp [sign, ht, ←sin_to_real] }, { rw [sign, ←sin_to_real, sign_pos ht, sign_pos (sin_pos_of_pos_of_lt_pi ht ((to_real_le_pi θ).lt_of_ne (to_real_eq_pi_iff.not.2 h)))] } end lemma coe_abs_to_real_of_sign_nonneg {θ : angle} (h : 0 ≤ θ.sign) : ↑|θ.to_real| = θ := by rw [abs_eq_self.2 (to_real_nonneg_iff_sign_nonneg.2 h), coe_to_real] lemma neg_coe_abs_to_real_of_sign_nonpos {θ : angle} (h : θ.sign ≤ 0) : -↑|θ.to_real| = θ := begin rw sign_type.nonpos_iff at h, rcases h with h|h, { rw [abs_of_neg (to_real_neg_iff_sign_neg.2 h), coe_neg, neg_neg, coe_to_real] }, { rw sign_eq_zero_iff at h, rcases h with rfl|rfl; simp [abs_of_pos real.pi_pos] } end lemma eq_iff_sign_eq_and_abs_to_real_eq {θ ψ : angle} : θ = ψ ↔ θ.sign = ψ.sign ∧ |θ.to_real| = |ψ.to_real| := begin refine ⟨_, λ h, _⟩, { rintro rfl, exact ⟨rfl, rfl⟩ }, rcases h with ⟨hs, hr⟩, rw abs_eq_abs at hr, rcases hr with (hr|hr), { exact to_real_injective hr }, { by_cases h : θ = π, { rw [h, to_real_pi, ← neg_eq_iff_eq_neg] at hr, exact false.elim ((neg_pi_lt_to_real ψ).ne hr) }, { by_cases h' : ψ = π, { rw [h', to_real_pi] at hr, exact false.elim ((neg_pi_lt_to_real θ).ne hr.symm) }, { rw [←sign_to_real h, ←sign_to_real h', hr, left.sign_neg, sign_type.neg_eq_self_iff, _root_.sign_eq_zero_iff, to_real_eq_zero_iff] at hs, rw [hs, to_real_zero, neg_zero, to_real_eq_zero_iff] at hr, rw [hr, hs] } } } end lemma eq_iff_abs_to_real_eq_of_sign_eq {θ ψ : angle} (h : θ.sign = ψ.sign) : θ = ψ ↔ |θ.to_real| = |ψ.to_real| := by simpa [h] using @eq_iff_sign_eq_and_abs_to_real_eq θ ψ @[simp] lemma sign_coe_pi_div_two : (↑(π / 2) : angle).sign = 1 := by rw [sign, sin_coe, sin_pi_div_two, sign_one] @[simp] lemma sign_coe_neg_pi_div_two : (↑(-π / 2) : angle).sign = -1 := by rw [sign, sin_coe, neg_div, real.sin_neg, sin_pi_div_two, left.sign_neg, sign_one] lemma sign_coe_nonneg_of_nonneg_of_le_pi {θ : ℝ} (h0 : 0 ≤ θ) (hpi : θ ≤ π) : 0 ≤ (θ : angle).sign := begin rw [sign, sign_nonneg_iff], exact sin_nonneg_of_nonneg_of_le_pi h0 hpi end lemma sign_neg_coe_nonpos_of_nonneg_of_le_pi {θ : ℝ} (h0 : 0 ≤ θ) (hpi : θ ≤ π) : (-θ : angle).sign ≤ 0 := begin rw [sign, sign_nonpos_iff, sin_neg, left.neg_nonpos_iff], exact sin_nonneg_of_nonneg_of_le_pi h0 hpi end lemma sign_two_nsmul_eq_sign_iff {θ : angle} : ((2 : ℕ) • θ).sign = θ.sign ↔ (θ = π ∨ |θ.to_real| < π / 2) := begin by_cases hpi : θ = π, { simp [hpi] }, rw or_iff_right hpi, refine ⟨λ h, _, λ h, _⟩, { by_contra hle, rw [not_lt, le_abs, le_neg] at hle, have hpi' : θ.to_real ≠ π, { simpa using hpi }, rcases hle with hle | hle; rcases hle.eq_or_lt with heq | hlt, { rw [←coe_to_real θ, ←heq] at h, simpa using h }, { rw [←sign_to_real hpi, sign_pos (pi_div_two_pos.trans hlt), ←sign_to_real, two_nsmul_to_real_eq_two_mul_sub_two_pi.2 hlt, _root_.sign_neg] at h, { simpa using h }, { rw ←mul_sub, exact mul_neg_of_pos_of_neg two_pos (sub_neg.2 ((to_real_le_pi _).lt_of_ne hpi')) }, { intro he, simpa [he] using h } }, { rw [←coe_to_real θ, heq] at h, simpa using h }, { rw [←sign_to_real hpi, _root_.sign_neg (hlt.trans (left.neg_neg_iff.2 pi_div_two_pos)), ←sign_to_real] at h, swap, { intro he, simpa [he] using h }, rw ←neg_div at hlt, rw [two_nsmul_to_real_eq_two_mul_add_two_pi.2 hlt.le, sign_pos] at h, { simpa using h }, { linarith [neg_pi_lt_to_real θ] } } }, { have hpi' : (2 : ℕ) • θ ≠ π, { rw [ne.def, two_nsmul_eq_pi_iff, not_or_distrib], split, { rintro rfl, simpa [pi_pos, div_pos, abs_of_pos] using h }, { rintro rfl, rw [to_real_neg_pi_div_two] at h, simpa [pi_pos, div_pos, neg_div, abs_of_pos] using h } }, rw [abs_lt, ←neg_div] at h, rw [←sign_to_real hpi, ←sign_to_real hpi', two_nsmul_to_real_eq_two_mul.2 ⟨h.1, h.2.le⟩, sign_mul, sign_pos (zero_lt_two' ℝ), one_mul] } end lemma sign_two_zsmul_eq_sign_iff {θ : angle} : ((2 : ℤ) • θ).sign = θ.sign ↔ (θ = π ∨ |θ.to_real| < π / 2) := by rw [two_zsmul, ←two_nsmul, sign_two_nsmul_eq_sign_iff] lemma continuous_at_sign {θ : angle} (h0 : θ ≠ 0) (hpi : θ ≠ π) : continuous_at sign θ := (continuous_at_sign_of_ne_zero (sin_ne_zero_iff.2 ⟨h0, hpi⟩)).comp continuous_sin.continuous_at lemma _root_.continuous_on.angle_sign_comp {α : Type*} [topological_space α] {f : α → angle} {s : set α} (hf : continuous_on f s) (hs : ∀ z ∈ s, f z ≠ 0 ∧ f z ≠ π) : continuous_on (sign ∘ f) s := begin refine (continuous_at.continuous_on (λ θ hθ, _)).comp hf (set.maps_to_image f s), obtain ⟨z, hz, rfl⟩ := hθ, exact continuous_at_sign (hs _ hz).1 (hs _ hz).2 end /-- Suppose a function to angles is continuous on a connected set and never takes the values `0` or `π` on that set. Then the values of the function on that set all have the same sign. -/ lemma sign_eq_of_continuous_on {α : Type*} [topological_space α] {f : α → angle} {s : set α} {x y : α} (hc : is_connected s) (hf : continuous_on f s) (hs : ∀ z ∈ s, f z ≠ 0 ∧ f z ≠ π) (hx : x ∈ s) (hy : y ∈ s) : (f y).sign = (f x).sign := (hc.image _ (hf.angle_sign_comp hs)).is_preconnected.subsingleton (set.mem_image_of_mem _ hy) (set.mem_image_of_mem _ hx) end angle end real
97e96ef9d2fbe8cc0457fe2012203a0c7f445aa3
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/topology/algebra/multilinear.lean
d09d6bdc23d6931fe08c1936c874a0b28e5a6522
[ "Apache-2.0" ]
permissive
gebner/mathlib
eab0150cc4f79ec45d2016a8c21750244a2e7ff0
cc6a6edc397c55118df62831e23bfbd6e6c6b4ab
refs/heads/master
1,625,574,853,976
1,586,712,827,000
1,586,712,827,000
99,101,412
1
0
Apache-2.0
1,586,716,389,000
1,501,667,958,000
Lean
UTF-8
Lean
false
false
11,882
lean
/- Copyright (c) 2020 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.algebra.module linear_algebra.multilinear /-! # Continuous multilinear maps We define continuous multilinear maps as maps from `Π(i : ι), M₁ i` to `M₂` which are multilinear and continuous, by extending the space of multilinear maps with a continuity assumption. Here, `M₁ i` and `M₂` are modules over a ring `R`, and `ι` is an arbitrary type, and all these spaces are also topological spaces. ## Main definitions * `continuous_multilinear_map R M₁ M₂` is the space of continuous multilinear maps from `Π(i : ι), M₁ i` to `M₂`. We show that it is an `R`-module. ## Implementation notes We mostly follow the API of multilinear maps. ## Notation We introduce the notation `M [×n]→L[R] M'` for the space of continuous `n`-multilinear maps from `M^n` to `M'`. This is a particular case of the general notion (where we allow varying dependent types as the arguments of our continuous multilinear maps), but arguably the most important one, especially when defining iterated derivatives. -/ open function fin set universes u v w w₁ w₂ w₃ w₄ variables {R : Type u} {ι : Type v} {n : ℕ} {M : fin n.succ → Type w} {M₁ : ι → Type w₁} {M₂ : Type w₂} {M₃ : Type w₃} {M₄ : Type w₄} [decidable_eq ι] /-- Continuous multilinear maps over the ring `R`, from `Πi, M₁ i` to `M₂` where `M₁ i` and `M₂` are modules over `R` with a topological structure. In applications, there will be compatibility conditions between the algebraic and the topological structures, but this is not needed for the definition. -/ structure continuous_multilinear_map (R : Type u) {ι : Type v} (M₁ : ι → Type w₁) (M₂ : Type w₂) [decidable_eq ι] [ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [∀i, module R (M₁ i)] [module R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂] extends multilinear_map R M₁ M₂ := (cont : continuous to_fun) notation M `[×`:25 n `]→L[`:25 R `] ` M' := continuous_multilinear_map R (λ (i : fin n), M) M' namespace continuous_multilinear_map section ring variables [ring R] [∀i, add_comm_group (M i)] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [add_comm_group M₃] [add_comm_group M₄] [∀i, module R (M i)] [∀i, module R (M₁ i)] [module R M₂] [module R M₃] [module R M₄] [∀i, topological_space (M i)] [∀i, topological_space (M₁ i)] [topological_space M₂] [topological_space M₃] [topological_space M₄] (f f' : continuous_multilinear_map R M₁ M₂) instance : has_coe_to_fun (continuous_multilinear_map R M₁ M₂) := ⟨_, λ f, f.to_multilinear_map.to_fun⟩ @[ext] theorem ext {f f' : continuous_multilinear_map R M₁ M₂} (H : ∀ x, f x = f' x) : f = f' := by { cases f, cases f', congr, ext x, exact H x } @[simp] lemma map_add (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x + y)) = f (update m i x) + f (update m i y) := f.add m i x y @[simp] lemma map_smul (m : Πi, M₁ i) (i : ι) (c : R) (x : M₁ i) : f (update m i (c • x)) = c • f (update m i x) := f.smul m i c x @[simp] lemma map_sub (m : Πi, M₁ i) (i : ι) (x y : M₁ i) : f (update m i (x - y)) = f (update m i x) - f (update m i y) := f.to_multilinear_map.map_sub _ _ _ _ lemma map_coord_zero {m : Πi, M₁ i} (i : ι) (h : m i = 0) : f m = 0 := f.to_multilinear_map.map_coord_zero i h @[simp] lemma map_zero [nonempty ι] : f 0 = 0 := f.to_multilinear_map.map_zero instance : has_zero (continuous_multilinear_map R M₁ M₂) := ⟨{ cont := continuous_const, ..(0 : multilinear_map R M₁ M₂) }⟩ instance : inhabited (continuous_multilinear_map R M₁ M₂) := ⟨0⟩ @[simp] lemma zero_apply (m : Πi, M₁ i) : (0 : continuous_multilinear_map R M₁ M₂) m = 0 := rfl section topological_add_group variable [topological_add_group M₂] instance : has_add (continuous_multilinear_map R M₁ M₂) := ⟨λ f f', {cont := f.cont.add f'.cont, ..(f.to_multilinear_map + f'.to_multilinear_map)}⟩ @[simp] lemma add_apply (m : Πi, M₁ i) : (f + f') m = f m + f' m := rfl instance : has_neg (continuous_multilinear_map R M₁ M₂) := ⟨λ f, {cont := f.cont.neg, ..(-f.to_multilinear_map)}⟩ @[simp] lemma neg_apply (m : Πi, M₁ i) : (-f) m = - (f m) := rfl instance : add_comm_group (continuous_multilinear_map R M₁ M₂) := by refine {zero := 0, add := (+), neg := has_neg.neg, ..}; intros; ext; simp [add_comm, add_left_comm] @[simp] lemma sub_apply (m : Πi, M₁ i) : (f - f') m = f m - f' m := rfl @[simp] lemma sum_apply {α : Type*} (f : α → continuous_multilinear_map R M₁ M₂) (m : Πi, M₁ i) : ∀ {s : finset α}, (s.sum f) m = s.sum (λ a, f a m) := begin classical, apply finset.induction, { rw finset.sum_empty, simp }, { assume a s has H, rw finset.sum_insert has, simp [H, has] } end end topological_add_group /-- If `f` is a continuous multilinear map, then `f.to_continuous_linear_map m i` is the continuous linear map obtained by fixing all coordinates but `i` equal to those of `m`, and varying the `i`-th coordinate. -/ def to_continuous_linear_map (m : Πi, M₁ i) (i : ι) : M₁ i →L[R] M₂ := { cont := f.cont.comp continuous_update, ..(f.to_multilinear_map.to_linear_map m i) } /-- The cartesian product of two continuous multilinear maps, as a continuous multilinear map. -/ def prod (f : continuous_multilinear_map R M₁ M₂) (g : continuous_multilinear_map R M₁ M₃) : continuous_multilinear_map R M₁ (M₂ × M₃) := { cont := f.cont.prod_mk g.cont, .. f.to_multilinear_map.prod g.to_multilinear_map } @[simp] lemma prod_apply (f : continuous_multilinear_map R M₁ M₂) (g : continuous_multilinear_map R M₁ M₃) (m : Πi, M₁ i) : (f.prod g) m = (f m, g m) := rfl /- If `R` and `M₃` are implicit in the next definition, Lean is never able to inder them, even given `g` and `f`. Therefore, we make them explicit. -/ variables (R M₃) /-- If `g` is continuous multilinear and `f` is continuous linear, then `g (f m₁, ..., f mₙ)` is again a continuous multilinear map, that we call `g.comp_continuous_linear_map f`. -/ def comp_continuous_linear_map (g : continuous_multilinear_map R (λ (i : ι), M₃) M₄) (f : M₂ →L[R] M₃) : continuous_multilinear_map R (λ (i : ι), M₂) M₄ := { cont := g.cont.comp $ continuous_pi $ λj, f.cont.comp $ continuous_apply _, .. g.to_multilinear_map.comp_linear_map f.to_linear_map } variables {R M₃} /-- In the specific case of continuous multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the additivity of a multilinear map along the first variable. -/ lemma cons_add (f : continuous_multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (x y : M 0) : f (cons (x+y) m) = f (cons x m) + f (cons y m) := f.to_multilinear_map.cons_add m x y /-- In the specific case of continuous multilinear maps on spaces indexed by `fin (n+1)`, where one can build an element of `Π(i : fin (n+1)), M i` using `cons`, one can express directly the multiplicativity of a multilinear map along the first variable. -/ lemma cons_smul (f : continuous_multilinear_map R M M₂) (m : Π(i : fin n), M i.succ) (c : R) (x : M 0) : f (cons (c • x) m) = c • f (cons x m) := f.to_multilinear_map.cons_smul m c x lemma map_piecewise_add (m m' : Πi, M₁ i) (t : finset ι) : f (t.piecewise (m + m') m') = t.powerset.sum (λ s, f (s.piecewise m m')) := f.to_multilinear_map.map_piecewise_add _ _ _ /-- Additivity of a continuous multilinear map along all coordinates at the same time, writing `f (m + m')` as the sum of `f (s.piecewise m m')` over all sets `s`. -/ lemma map_add_univ [fintype ι] (m m' : Πi, M₁ i) : f (m + m') = (finset.univ : finset (finset ι)).sum (λ s, f (s.piecewise m m')) := f.to_multilinear_map.map_add_univ _ _ section apply_sum open fintype finset variables {α : ι → Type*} [fintype ι] (g : Π i, α i → M₁ i) (A : Π i, finset (α i)) /-- If `f` is continuous multilinear, then `f (Σ_{j₁ ∈ A₁} g₁ j₁, ..., Σ_{jₙ ∈ Aₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions with `r 1 ∈ A₁`, ..., `r n ∈ Aₙ`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum_finset : f (λ i, (A i).sum (g i)) = (pi_finset A).sum (λ r, f (λ i, g i (r i))) := f.to_multilinear_map.map_sum_finset _ _ /-- If `f` is continuous multilinear, then `f (Σ_{j₁} g₁ j₁, ..., Σ_{jₙ} gₙ jₙ)` is the sum of `f (g₁ (r 1), ..., gₙ (r n))` where `r` ranges over all functions `r`. This follows from multilinearity by expanding successively with respect to each coordinate. -/ lemma map_sum [∀ i, fintype (α i)] : f (λ i, finset.univ.sum (g i)) = finset.univ.sum (λ (r : Π i, α i), f (λ i, g i (r i))) := f.to_multilinear_map.map_sum _ end apply_sum end ring section comm_ring variables [comm_ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [∀i, module R (M₁ i)] [module R M₂] [∀i, topological_space (M₁ i)] [topological_space M₂] (f : continuous_multilinear_map R M₁ M₂) lemma map_piecewise_smul (c : ι → R) (m : Πi, M₁ i) (s : finset ι) : f (s.piecewise (λ i, c i • m i) m) = s.prod c • f m := f.to_multilinear_map.map_piecewise_smul _ _ _ /-- Multiplicativity of a continuous multilinear map along all coordinates at the same time, writing `f (λ i, c i • m i)` as `univ.prod c • f m`. -/ lemma map_smul_univ [fintype ι] (c : ι → R) (m : Πi, M₁ i) : f (λ i, c i • m i) = finset.univ.prod c • f m := f.to_multilinear_map.map_smul_univ _ _ variables [topological_space R] [topological_module R M₂] instance : has_scalar R (continuous_multilinear_map R M₁ M₂) := ⟨λ c f, { cont := continuous.smul continuous_const f.cont, .. c • f.to_multilinear_map }⟩ @[simp] lemma smul_apply (c : R) (m : Πi, M₁ i) : (c • f) m = c • f m := rfl /-- The space of continuous multilinear maps is a module over `R`, for the pointwise addition and scalar multiplication. -/ instance [topological_add_group M₂] : module R (continuous_multilinear_map R M₁ M₂) := module.of_core $ by refine { smul := (•), ..}; intros; ext; simp [smul_add, add_smul, smul_smul] /-- Linear map version of the map `to_multilinear_map` associating to a continuous multilinear map the corresponding multilinear map. -/ def to_multilinear_map_linear [topological_add_group M₂] : (continuous_multilinear_map R M₁ M₂) →ₗ[R] (multilinear_map R M₁ M₂) := { to_fun := λ f, f.to_multilinear_map, add := λ f g, rfl, smul := λ c f, rfl } end comm_ring end continuous_multilinear_map namespace continuous_linear_map variables [ring R] [∀i, add_comm_group (M₁ i)] [add_comm_group M₂] [add_comm_group M₃] [∀i, module R (M₁ i)] [module R M₂] [module R M₃] [∀i, topological_space (M₁ i)] [topological_space M₂] [topological_space M₃] /-- Composing a continuous multilinear map with a continuous linear map gives again a continuous multilinear map. -/ def comp_continuous_multilinear_map (g : M₂ →L[R] M₃) (f : continuous_multilinear_map R M₁ M₂) : continuous_multilinear_map R M₁ M₃ := { cont := g.cont.comp f.cont, .. g.to_linear_map.comp_multilinear_map f.to_multilinear_map } @[simp] lemma comp_continuous_multilinear_map_coe (g : M₂ →L[R] M₃) (f : continuous_multilinear_map R M₁ M₂) : ((g.comp_continuous_multilinear_map f) : (Πi, M₁ i) → M₃) = (g : M₂ → M₃) ∘ (f : (Πi, M₁ i) → M₂) := by { ext m, refl } end continuous_linear_map
a85ea25fac6c0dca7a4c5c8230ed579c7e1f3b81
367134ba5a65885e863bdc4507601606690974c1
/src/linear_algebra/exterior_algebra.lean
2b616e4b78a005b7f0b4a8d685764568d39c401e
[ "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
10,209
lean
/- Copyright (c) 2020 Adam Topaz. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhangir Azerbayev, Adam Topaz, Eric Wieser. -/ import algebra.ring_quot import linear_algebra.tensor_algebra import linear_algebra.alternating import group_theory.perm.sign /-! # Exterior Algebras We construct the exterior algebra of a semimodule `M` over a commutative semiring `R`. ## Notation The exterior algebra of the `R`-semimodule `M` is denoted as `exterior_algebra R M`. It is endowed with the structure of an `R`-algebra. Given a linear morphism `f : M → A` from a semimodule `M` to another `R`-algebra `A`, such that `cond : ∀ m : M, f m * f m = 0`, there is a (unique) lift of `f` to an `R`-algebra morphism, which is denoted `exterior_algebra.lift R f cond`. The canonical linear map `M → exterior_algebra R M` is denoted `exterior_algebra.ι R`. ## Theorems The main theorems proved ensure that `exterior_algebra R M` satisfies the universal property of the exterior algebra. 1. `ι_comp_lift` is fact that the composition of `ι R` with `lift R f cond` agrees with `f`. 2. `lift_unique` ensures the uniqueness of `lift R f cond` with respect to 1. ## Definitions * `ι_multi` is the `alternating_map` corresponding to the wedge product of `ι R m` terms. ## Implementation details The exterior algebra of `M` is constructed as a quotient of the tensor algebra, as follows. 1. We define a relation `exterior_algebra.rel R M` on `tensor_algebra R M`. This is the smallest relation which identifies squares of elements of `M` with `0`. 2. The exterior algebra is the quotient of the tensor algebra by this relation. -/ variables (R : Type*) [comm_semiring R] variables (M : Type*) [add_comm_monoid M] [semimodule R M] namespace exterior_algebra open tensor_algebra /-- `rel` relates each `ι m * ι m`, for `m : M`, with `0`. The exterior algebra of `M` is defined as the quotient modulo this relation. -/ inductive rel : tensor_algebra R M → tensor_algebra R M → Prop | of (m : M) : rel ((ι R m) * (ι R m)) 0 end exterior_algebra /-- The exterior algebra of an `R`-semimodule `M`. -/ @[derive [inhabited, semiring, algebra R]] def exterior_algebra := ring_quot (exterior_algebra.rel R M) namespace exterior_algebra variables {M} -- typeclass resolution times out here, so we give it a hand instance {S : Type*} [comm_ring S] [semimodule S M] : ring (exterior_algebra S M) := let i : ring (tensor_algebra S M) := infer_instance in @ring_quot.ring (tensor_algebra S M) i (exterior_algebra.rel S M) /-- The canonical linear map `M →ₗ[R] exterior_algebra R M`. -/ def ι : M →ₗ[R] exterior_algebra R M := (ring_quot.mk_alg_hom R _).to_linear_map.comp (tensor_algebra.ι R) variables {R} /-- As well as being linear, `ι m` squares to zero -/ @[simp] theorem ι_square_zero (m : M) : (ι R m) * (ι R m) = 0 := begin erw [←alg_hom.map_mul, ring_quot.mk_alg_hom_rel R (rel.of m), alg_hom.map_zero _], end variables {A : Type*} [semiring A] [algebra R A] @[simp] theorem comp_ι_square_zero (g : exterior_algebra R M →ₐ[R] A) (m : M) : g (ι R m) * g (ι R m) = 0 := by rw [←alg_hom.map_mul, ι_square_zero, alg_hom.map_zero] variables (R) /-- Given a linear map `f : M →ₗ[R] A` into an `R`-algebra `A`, which satisfies the condition: `cond : ∀ m : M, f m * f m = 0`, this is the canonical lift of `f` to a morphism of `R`-algebras from `exterior_algebra R M` to `A`. -/ @[simps symm_apply] def lift : {f : M →ₗ[R] A // ∀ m, f m * f m = 0} ≃ (exterior_algebra R M →ₐ[R] A) := { to_fun := λ f, ring_quot.lift_alg_hom R ⟨tensor_algebra.lift R (f : M →ₗ[R] A), λ x y (h : rel R M x y), by { induction h, rw [alg_hom.map_zero, alg_hom.map_mul, tensor_algebra.lift_ι_apply, f.prop] }⟩, inv_fun := λ F, ⟨F.to_linear_map.comp (ι R), λ m, by rw [ linear_map.comp_apply, alg_hom.to_linear_map_apply, comp_ι_square_zero]⟩, left_inv := λ f, by { ext, simp [ι] }, right_inv := λ F, by { ext, simp [ι] } } @[simp] theorem ι_comp_lift (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = 0) : (lift R ⟨f, cond⟩).to_linear_map.comp (ι R) = f := (subtype.mk_eq_mk.mp $ (lift R).symm_apply_apply ⟨f, cond⟩) @[simp] theorem lift_ι_apply (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = 0) (x) : lift R ⟨f, cond⟩ (ι R x) = f x := (linear_map.ext_iff.mp $ ι_comp_lift R f cond) x @[simp] theorem lift_unique (f : M →ₗ[R] A) (cond : ∀ m, f m * f m = 0) (g : exterior_algebra R M →ₐ[R] A) : g.to_linear_map.comp (ι R) = f ↔ g = lift R ⟨f, cond⟩ := begin convert (lift R).symm_apply_eq, rw lift_symm_apply, simp only, end attribute [irreducible] ι lift -- Marking `exterior_algebra` irreducible makes our `ring` instances inaccessible. -- https://leanprover.zulipchat.com/#narrow/stream/113488-general/topic/algebra.2Esemiring_to_ring.20breaks.20semimodule.20typeclass.20lookup/near/212580241 -- For now, we avoid this by not marking it irreducible. variables {R M} @[simp] theorem lift_comp_ι (g : exterior_algebra R M →ₐ[R] A) : lift R ⟨g.to_linear_map.comp (ι R), comp_ι_square_zero _⟩ = g := begin convert (lift R).apply_symm_apply g, rw lift_symm_apply, refl, end /-- See note [partially-applied ext lemmas]. -/ @[ext] theorem hom_ext {f g : exterior_algebra R M →ₐ[R] A} (h : f.to_linear_map.comp (ι R) = g.to_linear_map.comp (ι R)) : f = g := begin apply (lift R).symm.injective, rw [lift_symm_apply, lift_symm_apply], simp only [h], end /-- If `C` holds for the `algebra_map` of `r : R` into `exterior_algebra R M`, the `ι` of `x : M`, and is preserved under addition and muliplication, then it holds for all of `exterior_algebra R M`. -/ -- This proof closely follows `tensor_algebra.induction` @[elab_as_eliminator] lemma induction {C : exterior_algebra R M → Prop} (h_grade0 : ∀ r, C (algebra_map R (exterior_algebra R M) r)) (h_grade1 : ∀ x, C (ι R x)) (h_mul : ∀ a b, C a → C b → C (a * b)) (h_add : ∀ a b, C a → C b → C (a + b)) (a : exterior_algebra R M) : C a := begin -- the arguments are enough to construct a subalgebra, and a mapping into it from M let s : subalgebra R (exterior_algebra R M) := { carrier := C, mul_mem' := h_mul, add_mem' := h_add, algebra_map_mem' := h_grade0, }, let of : { f : M →ₗ[R] s // ∀ m, f m * f m = 0 } := ⟨(ι R).cod_restrict s.to_submodule h_grade1, λ m, subtype.eq $ ι_square_zero m ⟩, -- the mapping through the subalgebra is the identity have of_id : alg_hom.id R (exterior_algebra R M) = s.val.comp (lift R of), { ext, simp [of], }, -- finding a proof is finding an element of the subalgebra convert subtype.prop (lift R of a), exact alg_hom.congr_fun of_id a, end /-- The left-inverse of `algebra_map`. -/ def algebra_map_inv : exterior_algebra R M →ₐ[R] R := exterior_algebra.lift R ⟨(0 : M →ₗ[R] R), λ m, by simp⟩ lemma algebra_map_left_inverse : function.left_inverse algebra_map_inv (algebra_map R $ exterior_algebra R M) := λ x, by simp [algebra_map_inv] /-- The left-inverse of `ι`. As an implementation detail, we implement this using `triv_sq_zero_ext` which has a suitable algebra structure. -/ def ι_inv : exterior_algebra R M →ₗ[R] M := (triv_sq_zero_ext.snd_hom R M).comp (lift R ⟨triv_sq_zero_ext.inr_hom R M, λ m, triv_sq_zero_ext.inr_mul_inr R _ m m⟩).to_linear_map lemma ι_left_inverse : function.left_inverse ι_inv (ι R : M → exterior_algebra R M) := λ x, by simp [ι_inv] @[simp] lemma ι_add_mul_swap (x y : M) : ι R x * ι R y + ι R y * ι R x = 0 := calc _ = ι R (x + y) * ι R (x + y) : by simp [mul_add, add_mul] ... = _ : ι_square_zero _ lemma ι_mul_prod_list {n : ℕ} (f : fin n → M) (i : fin n) : (ι R $ f i) * (list.of_fn $ λ i, ι R $ f i).prod = 0 := begin induction n with n hn, { exact i.elim0, }, { rw [list.of_fn_succ, list.prod_cons, ←mul_assoc], by_cases h : i = 0, { rw [h, ι_square_zero, zero_mul], }, { replace hn := congr_arg ((*) $ ι R $ f 0) (hn (λ i, f $ fin.succ i) (i.pred h)), simp only at hn, rw [fin.succ_pred, ←mul_assoc, mul_zero] at hn, refine (eq_zero_iff_eq_zero_of_add_eq_zero _).mp hn, rw [← add_mul, ι_add_mul_swap, zero_mul], } } end variables (R) /-- The product of `n` terms of the form `ι R m` is an alternating map. This is a special case of `multilinear_map.mk_pi_algebra_fin` -/ def ι_multi (n : ℕ) : alternating_map R M (exterior_algebra R M) (fin n) := let F := (multilinear_map.mk_pi_algebra_fin R n (exterior_algebra R M)).comp_linear_map (λ i, ι R) in { map_eq_zero_of_eq' := λ f x y hfxy hxy, begin rw [multilinear_map.comp_linear_map_apply, multilinear_map.mk_pi_algebra_fin_apply], wlog h : x < y := lt_or_gt_of_ne hxy using x y, clear hxy, induction n with n hn generalizing x y, { exact x.elim0, }, { rw [list.of_fn_succ, list.prod_cons], by_cases hx : x = 0, -- one of the repeated terms is on the left { rw hx at hfxy h, rw [hfxy, ←fin.succ_pred y (ne_of_lt h).symm], exact ι_mul_prod_list (f ∘ fin.succ) _, }, -- ignore the left-most term and induct on the remaining ones, decrementing indices { convert mul_zero _, refine hn (λ i, f $ fin.succ i) (x.pred hx) (y.pred (ne_of_lt $ lt_of_le_of_lt x.zero_le h).symm) (fin.pred_lt_pred_iff.mpr h) _, simp only [fin.succ_pred], exact hfxy, } } end, to_fun := F, ..F} variables {R} lemma ι_multi_apply {n : ℕ} (v : fin n → M) : ι_multi R n v = (list.of_fn $ λ i, ι R (v i)).prod := rfl end exterior_algebra namespace tensor_algebra variables {R M} /-- The canonical image of the `tensor_algebra` in the `exterior_algebra`, which maps `tensor_algebra.ι R x` to `exterior_algebra.ι R x`. -/ def to_exterior : tensor_algebra R M →ₐ[R] exterior_algebra R M := tensor_algebra.lift R (exterior_algebra.ι R) @[simp] lemma to_exterior_ι (m : M) : (tensor_algebra.ι R m).to_exterior = exterior_algebra.ι R m := by simp [to_exterior] end tensor_algebra
21b7d30a74662d14e39c774b04c5ea0301a8e505
4727251e0cd73359b15b664c3170e5d754078599
/src/measure_theory/integral/exp_decay.lean
87843c8693b1733a15702f845fbfc92227616af7
[ "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,651
lean
/- Copyright (c) 2022 David Loeffler. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Loeffler -/ import measure_theory.integral.interval_integral import analysis.special_functions.exponential import analysis.special_functions.integrals import measure_theory.integral.integral_eq_improper /-! # Integrals with exponential decay at ∞ As easy special cases of general theorems in the library, we prove the following test for integrability: * `integrable_of_is_O_exp_neg`: If `f` is continuous on `[a,∞)`, for some `a ∈ ℝ`, and there exists `b > 0` such that `f(x) = O(exp(-b x))` as `x → ∞`, then `f` is integrable on `(a, ∞)`. -/ noncomputable theory open real interval_integral measure_theory set filter /-- Integral of `exp (-b * x)` over `(a, X)` is bounded as `X → ∞`. -/ lemma integral_exp_neg_le {b : ℝ} (a X : ℝ) (h2 : 0 < b) : (∫ x in a .. X, exp (-b * x)) ≤ exp (-b * a) / b := begin rw integral_deriv_eq_sub' (λ x, -exp (-b * x) / b), -- goal 1/4: F(X) - F(a) is bounded { simp only [tsub_le_iff_right], rw [neg_div b (exp (-b * a)), neg_div b (exp (-b * X)), add_neg_self, neg_le, neg_zero], exact (div_pos (exp_pos _) h2).le, }, -- goal 2/4: the derivative of F is exp(-b x) { ext1, simp [h2.ne'] }, -- goal 3/4: F is differentiable { intros x hx, simp [h2.ne'], }, -- goal 4/4: exp(-b x) is continuous { apply continuous.continuous_on, continuity } end /-- `exp (-b * x)` is integrable on `(a, ∞)`. -/ lemma exp_neg_integrable_on_Ioi (a : ℝ) {b : ℝ} (h : 0 < b) : integrable_on (λ x : ℝ, exp (-b * x)) (Ioi a) := begin have : ∀ (X : ℝ), integrable_on (λ x : ℝ, exp (-b * x) ) (Ioc a X), { intro X, exact (continuous_const.mul continuous_id).exp.integrable_on_Ioc }, apply (integrable_on_Ioi_of_interval_integral_norm_bounded (exp (-b * a) / b) a this tendsto_id), simp only [eventually_at_top, norm_of_nonneg (exp_pos _).le], exact ⟨a, λ b2 hb2, integral_exp_neg_le a b2 h⟩, end /-- If `f` is continuous on `[a, ∞)`, and is `O (exp (-b * x))` at `∞` for some `b > 0`, then `f` is integrable on `(a, ∞)`. -/ lemma integrable_of_is_O_exp_neg {f : ℝ → ℝ} {a b : ℝ} (h0 : 0 < b) (h1 : continuous_on f (Ici a)) (h2 : asymptotics.is_O f (λ x, exp (-b * x)) at_top) : integrable_on f (Ioi a) := begin cases h2.is_O_with with c h3, rw [asymptotics.is_O_with_iff, eventually_at_top] at h3, cases h3 with r bdr, let v := max a r, -- show integrable on `(a, v]` from continuity have int_left : integrable_on f (Ioc a v), { rw ←(interval_integrable_iff_integrable_Ioc_of_le (le_max_left a r)), have u : Icc a v ⊆ Ici a := Icc_subset_Ici_self, exact (h1.mono u).interval_integrable_of_Icc (le_max_left a r), }, suffices : integrable_on f (Ioi v), { have t : integrable_on f (Ioc a v ∪ Ioi v) := integrable_on_union.mpr ⟨int_left, this⟩, simpa only [Ioc_union_Ioi_eq_Ioi, le_max_iff, le_refl, true_or] using t }, -- now show integrable on `(v, ∞)` from asymptotic split, { exact (h1.mono $ Ioi_subset_Ici $ le_max_left a r).ae_strongly_measurable measurable_set_Ioi }, have : has_finite_integral (λ x : ℝ, c * exp (-b * x)) (volume.restrict (Ioi v)), { exact (exp_neg_integrable_on_Ioi v h0).has_finite_integral.const_mul c }, apply this.mono, refine (ae_restrict_iff' measurable_set_Ioi).mpr _, refine ae_of_all _ (λ x h1x, _), rw [norm_mul, norm_eq_abs], rw [mem_Ioi] at h1x, specialize bdr x ((le_max_right a r).trans h1x.le), exact bdr.trans (mul_le_mul_of_nonneg_right (le_abs_self c) (norm_nonneg _)) end
bbef7fb8620286b16900f092f41670535b142615
2a70b774d16dbdf5a533432ee0ebab6838df0948
/_target/deps/mathlib/src/category_theory/monad/monadicity.lean
3c5e24c6cba10c3194d7c5444f371e30c2099749
[ "Apache-2.0" ]
permissive
hjvromen/lewis
40b035973df7c77ebf927afab7878c76d05ff758
105b675f73630f028ad5d890897a51b3c1146fb0
refs/heads/master
1,677,944,636,343
1,676,555,301,000
1,676,555,301,000
327,553,599
0
0
null
null
null
null
UTF-8
Lean
false
false
14,514
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.limits.shapes.reflexive import category_theory.limits.preserves.limits import category_theory.monad.limits import category_theory.monad.coequalizer /-! # Monadicity theorems We prove monadicity theorems which can establish a given functor is monadic. In particular, we show three versions of Beck's monadicity theorem, and the reflexive (crude) monadicity theorem: `G` is a monadic right adjoint if it has a right adjoint, and: * `D` has, `G` preserves and reflects `G`-split coequalizers, see `category_theory.monad.monadic_of_has_preserves_reflects_G_split_coequalizers` * `G` creates `G`-split coequalizers, see `category_theory.monad.monadic_of_creates_G_split_coequalizers` (The converse of this is also shown, see `category_theory.monad.creates_G_split_coequalizers_of_monadic`) * `D` has and `G` preserves `G`-split coequalizers, and `G` reflects isomorphisms, see `category_theory.monad.monadic_of_has_preserves_G_split_coequalizers_of_reflects_isomorphisms` * `D` has and `G` preserves reflexive coequalizers, and `G` reflects isomorphisms, see `category_theory.monad.monadic_of_has_preserves_reflexive_coequalizers_of_reflects_isomorphisms` ## Tags Beck, monadicity, descent ## TODO Dualise to show comonadicity theorems. -/ universes v₁ v₂ u₁ u₂ namespace category_theory namespace monad open limits noncomputable theory -- Hide the implementation details in this namespace. namespace monadicity_internal section -- We use these parameters and notations to simplify the statements of internal constructions -- here. parameters {C : Type u₁} {D : Type u₂} parameters [category.{v₁} C] [category.{v₁} D] parameters {G : D ⥤ C} [is_right_adjoint G] local notation `F` := left_adjoint G local notation `adj` := adjunction.of_right_adjoint G /-- The "main pair" for an algebra `(A, α)` is the pair of morphisms `(F α, ε_FA)`. It is always a reflexive pair, and will be used to construct the left adjoint to the comparison functor and show it is an equivalence. -/ instance main_pair_reflexive (A : algebra (F ⋙ G)) : is_reflexive_pair (F .map A.a) (adj .counit.app (F .obj A.A)) := begin apply is_reflexive_pair.mk' (F .map (adj .unit.app _)) _ _, { rw [← F .map_comp, ← F .map_id], exact congr_arg (λ _, F .map _) A.unit }, { rw adj .left_triangle_components, refl }, end /-- The "main pair" for an algebra `(A, α)` is the pair of morphisms `(F α, ε_FA)`. It is always a `G`-split pair, and will be used to construct the left adjoint to the comparison functor and show it is an equivalence. -/ instance main_pair_G_split (A : algebra (F ⋙ G)) : G.is_split_pair (F .map A.a) (adj .counit.app (F .obj A.A)) := { splittable := ⟨_, _, ⟨beck_split_coequalizer A⟩⟩ } /-- The object function for the left adjoint to the comparison functor. -/ def comparison_left_adjoint_obj (A : algebra (F ⋙ G)) [has_coequalizer (F .map A.a) (adj .counit.app _)] : D := coequalizer (F .map A.a) (adj .counit.app _) /-- We have a bijection of homsets which will be used to construct the left adjoint to the comparison functor. -/ @[simps] def comparison_left_adjoint_hom_equiv (A : algebra (F ⋙ G)) (B : D) [has_coequalizer (F .map A.a) (adj .counit.app (F .obj A.A))] : (comparison_left_adjoint_obj A ⟶ B) ≃ (A ⟶ (comparison G).obj B) := calc (comparison_left_adjoint_obj A ⟶ B) ≃ {f : F .obj A.A ⟶ B // _} : cofork.is_colimit.hom_iso (colimit.is_colimit _) B ... ≃ {g : A.A ⟶ G.obj B // G.map (F .map g) ≫ G.map (adj .counit.app B) = A.a ≫ g} : begin refine (adj .hom_equiv _ _).subtype_congr _, intro f, rw [← (adj .hom_equiv _ _).injective.eq_iff, adjunction.hom_equiv_naturality_left, adj .hom_equiv_unit, adj .hom_equiv_unit, G.map_comp], dsimp, rw [adj .right_triangle_components_assoc, ← G.map_comp, F .map_comp, category.assoc, adj .counit_naturality, adj .left_triangle_components_assoc], apply eq_comm, end ... ≃ (A ⟶ (comparison G).obj B) : { to_fun := λ g, { f := _, h' := g.prop }, inv_fun := λ f, ⟨f.f, f.h⟩, left_inv := λ g, begin ext, refl end, right_inv := λ f, begin ext, refl end } /-- Construct the adjunction to the comparison functor. -/ def left_adjoint_comparison [∀ (A : algebra (F ⋙ G)), has_coequalizer (F .map A.a) (adj .counit.app (F .obj A.A))] : algebra (F ⋙ G) ⥤ D := begin refine @adjunction.left_adjoint_of_equiv _ _ _ _ (comparison G) (λ A, comparison_left_adjoint_obj A) (λ A B, _) _, { apply comparison_left_adjoint_hom_equiv }, { intros A B B' g h, ext1, dsimp [comparison_left_adjoint_hom_equiv], rw [← adj .hom_equiv_naturality_right, category.assoc] }, end /-- Provided we have the appropriate coequalizers, we have an adjunction to the comparison functor. -/ @[simps counit] def comparison_adjunction [∀ (A : algebra (F ⋙ G)), has_coequalizer (F .map A.a) (adj .counit.app (F .obj A.A))] : left_adjoint_comparison ⊣ comparison G := adjunction.adjunction_of_equiv_left _ _ lemma comparison_adjunction_unit_f_aux [∀ (A : algebra (F ⋙ G)), has_coequalizer (F .map A.a) (adj .counit.app (F .obj A.A))] (A : algebra (F ⋙ G)) : (comparison_adjunction.unit.app A).f = adj .hom_equiv A.A _ (coequalizer.π (F .map A.a) (adj .counit.app (F .obj A.A))) := congr_arg (adj .hom_equiv _ _) (category.comp_id _) /-- This is a cofork which is helpful for establishing monadicity: the morphism from the Beck coequalizer to this cofork is the unit for the adjunction on the comparison functor. -/ @[simps] def unit_cofork (A : algebra (F ⋙ G)) [has_coequalizer (F .map A.a) (adj .counit.app (F .obj A.A))] : cofork (G.map (F .map A.a)) (G.map (adj .counit.app (F .obj A.A))) := cofork.of_π (G.map (coequalizer.π (F .map A.a) (adj .counit.app (F .obj A.A)))) begin change _ = G.map _ ≫ _, rw [← G.map_comp, coequalizer.condition, G.map_comp], end lemma comparison_adjunction_unit_f [∀ (A : algebra (F ⋙ G)), has_coequalizer (F .map A.a) (adj .counit.app (F .obj A.A))] (A : algebra (F ⋙ G)) : (comparison_adjunction.unit.app A).f = (beck_coequalizer A).desc (unit_cofork A) := begin apply limits.cofork.is_colimit.hom_ext (beck_coequalizer A), rw is_colimit.fac, dsimp only [cofork.π_eq_app_one, beck_cofork_ι_app, unit_cofork_ι_app], rw [comparison_adjunction_unit_f_aux, ← adj .hom_equiv_naturality_left A.a, coequalizer.condition, adj .hom_equiv_naturality_right, adj .hom_equiv_unit, category.assoc], apply adj .right_triangle_components_assoc, end /-- The cofork which describes the counit of the adjunction: the morphism from the coequalizer of this pair to this morphism is the counit. -/ @[simps] def counit_cofork (B : D) : cofork (F .map (G.map (adj .counit.app B))) (adj .counit.app (F .obj (G.obj B))) := cofork.of_π (adj .counit.app B) (adj .counit_naturality _) /-- The unit cofork is a colimit provided `G` preserves it. -/ def unit_colimit_of_preserves_coequalizer (A : algebra (F ⋙ G)) [has_coequalizer (F .map A.a) (adj .counit.app (F .obj A.A))] [preserves_colimit (parallel_pair (F .map A.a) (adj .counit.app (F .obj A.A))) G] : is_colimit (unit_cofork A) := is_colimit_of_has_coequalizer_of_preserves_colimit G _ _ /-- The counit cofork is a colimit provided `G` reflects it. -/ def counit_coequalizer_of_reflects_coequalizer (B : D) [reflects_colimit (parallel_pair (F .map (G.map (adj .counit.app B))) (adj .counit.app (F .obj (G.obj B)))) G] : is_colimit (counit_cofork B) := is_colimit_of_is_colimit_cofork_map G _ (beck_coequalizer ((comparison G).obj B)) lemma comparison_adjunction_counit_app [∀ (A : algebra (F ⋙ G)), has_coequalizer (F .map A.a) (adj .counit.app (F .obj A.A))] (B : D) : comparison_adjunction.counit.app B = colimit.desc _ (counit_cofork B) := begin apply coequalizer.hom_ext, change coequalizer.π _ _ ≫ coequalizer.desc ((adj .hom_equiv _ B).symm (𝟙 _)) _ = coequalizer.π _ _ ≫ coequalizer.desc _ _, simp, end end end monadicity_internal open monadicity_internal variables {C : Type u₁} {D : Type u₂} variables [category.{v₁} C] [category.{v₁} D] variables (G : D ⥤ C) /-- If `G` is monadic, it creates colimits of `G`-split pairs. This is the "boring" direction of Beck's monadicity theorem, the converse is given in `monadic_of_creates_G_split_coequalizers`. -/ def creates_G_split_coequalizers_of_monadic [monadic_right_adjoint G] ⦃A B⦄ (f g : A ⟶ B) [G.is_split_pair f g] : creates_colimit (parallel_pair f g) G := begin apply monadic_creates_colimit_of_preserves_colimit _ _, apply_instance, { apply preserves_colimit_of_iso_diagram _ (diagram_iso_parallel_pair _).symm, dsimp, apply_instance }, { apply preserves_colimit_of_iso_diagram _ (diagram_iso_parallel_pair _).symm, dsimp, apply_instance } end variables [is_right_adjoint G] section beck_monadicity /-- To show `G` is a monadic right adjoint, we can show it preserves and reflects `G`-split coequalizers, and `C` has them. -/ def monadic_of_has_preserves_reflects_G_split_coequalizers [∀ ⦃A B⦄ (f g : A ⟶ B) [G.is_split_pair f g], has_coequalizer f g] [∀ ⦃A B⦄ (f g : A ⟶ B) [G.is_split_pair f g], preserves_colimit (parallel_pair f g) G] [∀ ⦃A B⦄ (f g : A ⟶ B) [G.is_split_pair f g], reflects_colimit (parallel_pair f g) G] : monadic_right_adjoint G := begin let L : algebra (left_adjoint G ⋙ G) ⥤ D := left_adjoint_comparison, letI i : is_right_adjoint (comparison G) := ⟨_, comparison_adjunction⟩, constructor, let : Π (X : algebra (left_adjoint G ⋙ G)), is_iso ((adjunction.of_right_adjoint (comparison G)).unit.app X), { intro X, apply is_iso_of_reflects_iso _ (monad.forget (left_adjoint G ⋙ G)), { change is_iso (comparison_adjunction.unit.app X).f, rw comparison_adjunction_unit_f, change is_iso (is_colimit.cocone_point_unique_up_to_iso (beck_coequalizer X) (unit_colimit_of_preserves_coequalizer X)).hom, refine is_iso.of_iso (is_colimit.cocone_point_unique_up_to_iso _ _) } }, let : Π (Y : D), is_iso ((adjunction.of_right_adjoint (comparison G)).counit.app Y), { intro Y, change is_iso (comparison_adjunction.counit.app Y), rw comparison_adjunction_counit_app, change is_iso (is_colimit.cocone_point_unique_up_to_iso _ _).hom, apply_instance, apply counit_coequalizer_of_reflects_coequalizer _, letI : G.is_split_pair ((left_adjoint G).map (G.map ((adjunction.of_right_adjoint G).counit.app Y))) ((adjunction.of_right_adjoint G).counit.app ((left_adjoint G).obj (G.obj Y))) := monadicity_internal.main_pair_G_split ((comparison G).obj Y), apply_instance }, exactI adjunction.is_right_adjoint_to_is_equivalence, end /-- Beck's monadicity theorem. If `G` has a right adjoint and creates coequalizers of `G`-split pairs, then it is monadic. This is the converse of `creates_G_split_of_monadic`. -/ def monadic_of_creates_G_split_coequalizers [∀ ⦃A B⦄ (f g : A ⟶ B) [G.is_split_pair f g], creates_colimit (parallel_pair f g) G] : monadic_right_adjoint G := begin letI : ∀ ⦃A B⦄ (f g : A ⟶ B) [G.is_split_pair f g], has_colimit (parallel_pair f g ⋙ G), { introsI A B f g i, apply has_colimit_of_iso (diagram_iso_parallel_pair _), change has_coequalizer (G.map f) (G.map g), apply_instance }, apply monadic_of_has_preserves_reflects_G_split_coequalizers _, { apply_instance }, { introsI A B f g i, apply has_colimit_of_created (parallel_pair f g) G }, { introsI A B f g i, apply_instance }, { introsI A B f g i, apply_instance } end /-- An alternate version of Beck's monadicity theorem. If `G` reflects isomorphisms, preserves coequalizers of `G`-split pairs and `C` has coequalizers of `G`-split pairs, then it is monadic. -/ def monadic_of_has_preserves_G_split_coequalizers_of_reflects_isomorphisms [reflects_isomorphisms G] [∀ ⦃A B⦄ (f g : A ⟶ B) [G.is_split_pair f g], has_coequalizer f g] [∀ ⦃A B⦄ (f g : A ⟶ B) [G.is_split_pair f g], preserves_colimit (parallel_pair f g) G] : monadic_right_adjoint G := begin apply monadic_of_has_preserves_reflects_G_split_coequalizers _, { apply_instance }, { assumption }, { assumption }, { introsI A B f g i, apply reflects_colimit_of_reflects_isomorphisms }, end end beck_monadicity section reflexive_monadicity variables [has_reflexive_coequalizers D] [reflects_isomorphisms G] variables [∀ ⦃A B⦄ (f g : A ⟶ B) [is_reflexive_pair f g], preserves_colimit (parallel_pair f g) G] /-- Reflexive (crude) monadicity theorem. If `G` has a right adjoint, `D` has and `G` preserves reflexive coequalizers and `G` reflects isomorphisms, then `G` is monadic. -/ def monadic_of_has_preserves_reflexive_coequalizers_of_reflects_isomorphisms : monadic_right_adjoint G := begin let L : algebra (left_adjoint G ⋙ G) ⥤ D := left_adjoint_comparison, letI i : is_right_adjoint (comparison G) := ⟨_, comparison_adjunction⟩, constructor, let : Π (X : algebra (left_adjoint G ⋙ G)), is_iso ((adjunction.of_right_adjoint (comparison G)).unit.app X), { intro X, apply is_iso_of_reflects_iso _ (monad.forget (left_adjoint G ⋙ G)), { change is_iso (comparison_adjunction.unit.app X).f, rw comparison_adjunction_unit_f, change is_iso (is_colimit.cocone_point_unique_up_to_iso (beck_coequalizer X) (unit_colimit_of_preserves_coequalizer X)).hom, apply is_iso.of_iso (is_colimit.cocone_point_unique_up_to_iso _ _) } }, let : Π (Y : D), is_iso ((adjunction.of_right_adjoint (comparison G)).counit.app Y), { intro Y, change is_iso (comparison_adjunction.counit.app Y), rw comparison_adjunction_counit_app, change is_iso (is_colimit.cocone_point_unique_up_to_iso _ _).hom, apply_instance, apply counit_coequalizer_of_reflects_coequalizer _, apply reflects_colimit_of_reflects_isomorphisms }, exactI adjunction.is_right_adjoint_to_is_equivalence, end end reflexive_monadicity end monad end category_theory
8f5b95b1905c9072965cf815140c7126987f2138
c777c32c8e484e195053731103c5e52af26a25d1
/src/topology/algebra/infinite_sum/basic.lean
9d0486d2144d3e998d4b8fe8ad275bc0db4a26ad
[ "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
53,265
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.nat.parity import logic.encodable.lattice import topology.algebra.uniform_group import topology.algebra.star /-! # Infinite sum over a topological monoid > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This sum is known as unconditionally convergent, as it sums to the same value under all possible permutations. For Euclidean spaces (finite dimensional Banach spaces) this is equivalent to absolute convergence. Note: There are summable sequences which are not unconditionally convergent! The other way holds generally, see `has_sum.tendsto_sum_nat`. ## References * Bourbaki: General Topology (1995), Chapter 3 §5 (Infinite sums in commutative groups) -/ noncomputable theory open classical filter finset function open_locale big_operators classical topology variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} section has_sum variables [add_comm_monoid α] [topological_space α] /-- Infinite sum on a topological monoid The `at_top` filter on `finset β` is the limit of all finite sets towards the entire type. So we sum up bigger and bigger sets. This sum operation is invariant under reordering. In particular, the function `ℕ → ℝ` sending `n` to `(-1)^n / (n+1)` does not have a sum for this definition, but a series which is absolutely convergent will have the correct sum. This is based on Mario Carneiro's [infinite sum `df-tsms` in Metamath](http://us.metamath.org/mpeuni/df-tsms.html). For the definition or many statements, `α` does not need to be a topological monoid. We only add this assumption later, for the lemmas where it is relevant. -/ def has_sum (f : β → α) (a : α) : Prop := tendsto (λs:finset β, ∑ b in s, f b) at_top (𝓝 a) /-- `summable f` means that `f` has some (infinite) sum. Use `tsum` to get the value. -/ def summable (f : β → α) : Prop := ∃a, has_sum f a /-- `∑' i, f i` is the sum of `f` it exists, or 0 otherwise -/ @[irreducible] def tsum {β} (f : β → α) := if h : summable f then classical.some h else 0 -- see Note [operator precedence of big operators] notation `∑'` binders `, ` r:(scoped:67 f, tsum f) := r variables {f g : β → α} {a b : α} {s : finset β} lemma summable.has_sum (ha : summable f) : has_sum f (∑'b, f b) := by simp [ha, tsum]; exact some_spec ha lemma has_sum.summable (h : has_sum f a) : summable f := ⟨a, h⟩ /-- Constant zero function has sum `0` -/ lemma has_sum_zero : has_sum (λb, 0 : β → α) 0 := by simp [has_sum, tendsto_const_nhds] lemma has_sum_empty [is_empty β] : has_sum f 0 := by convert has_sum_zero lemma summable_zero : summable (λb, 0 : β → α) := has_sum_zero.summable lemma summable_empty [is_empty β] : summable f := has_sum_empty.summable lemma tsum_eq_zero_of_not_summable (h : ¬ summable f) : ∑'b, f b = 0 := by simp [tsum, h] lemma summable_congr (hfg : ∀b, f b = g b) : summable f ↔ summable g := iff_of_eq (congr_arg summable $ funext hfg) lemma summable.congr (hf : summable f) (hfg : ∀b, f b = g b) : summable g := (summable_congr hfg).mp hf lemma has_sum.has_sum_of_sum_eq {g : γ → α} (h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b) (hf : has_sum g a) : has_sum f a := le_trans (map_at_top_finset_sum_le_of_sum_eq h_eq) hf lemma has_sum_iff_has_sum {g : γ → α} (h₁ : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∑ x in u', g x = ∑ b in v', f b) (h₂ : ∀v:finset β, ∃u:finset γ, ∀u', u ⊆ u' → ∃v', v ⊆ v' ∧ ∑ b in v', f b = ∑ x in u', g x) : has_sum f a ↔ has_sum g a := ⟨has_sum.has_sum_of_sum_eq h₂, has_sum.has_sum_of_sum_eq h₁⟩ lemma function.injective.has_sum_iff {g : γ → β} (hg : injective g) (hf : ∀ x ∉ set.range g, f x = 0) : has_sum (f ∘ g) a ↔ has_sum f a := by simp only [has_sum, tendsto, hg.map_at_top_finset_sum_eq hf] lemma function.injective.summable_iff {g : γ → β} (hg : injective g) (hf : ∀ x ∉ set.range g, f x = 0) : summable (f ∘ g) ↔ summable f := exists_congr $ λ _, hg.has_sum_iff hf lemma has_sum_subtype_iff_of_support_subset {s : set β} (hf : support f ⊆ s) : has_sum (f ∘ coe : s → α) a ↔ has_sum f a := subtype.coe_injective.has_sum_iff $ by simpa using support_subset_iff'.1 hf lemma has_sum_subtype_iff_indicator {s : set β} : has_sum (f ∘ coe : s → α) a ↔ has_sum (s.indicator f) a := by rw [← set.indicator_range_comp, subtype.range_coe, has_sum_subtype_iff_of_support_subset set.support_indicator_subset] lemma summable_subtype_iff_indicator {s : set β} : summable (f ∘ coe : s → α) ↔ summable (s.indicator f) := exists_congr (λ _, has_sum_subtype_iff_indicator) @[simp] lemma has_sum_subtype_support : has_sum (f ∘ coe : support f → α) a ↔ has_sum f a := has_sum_subtype_iff_of_support_subset $ set.subset.refl _ lemma has_sum_fintype [fintype β] (f : β → α) : has_sum f (∑ b, f b) := order_top.tendsto_at_top_nhds _ protected lemma finset.has_sum (s : finset β) (f : β → α) : has_sum (f ∘ coe : (↑s : set β) → α) (∑ b in s, f b) := by { rw ← sum_attach, exact has_sum_fintype _ } protected lemma finset.summable (s : finset β) (f : β → α) : summable (f ∘ coe : (↑s : set β) → α) := (s.has_sum f).summable protected lemma set.finite.summable {s : set β} (hs : s.finite) (f : β → α) : summable (f ∘ coe : s → α) := by convert hs.to_finset.summable f; simp only [hs.coe_to_finset] /-- If a function `f` vanishes outside of a finite set `s`, then it `has_sum` `∑ b in s, f b`. -/ lemma has_sum_sum_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : has_sum f (∑ b in s, f b) := (has_sum_subtype_iff_of_support_subset $ support_subset_iff'.2 hf).1 $ s.has_sum f lemma summable_of_ne_finset_zero (hf : ∀b∉s, f b = 0) : summable f := (has_sum_sum_of_ne_finset_zero hf).summable lemma has_sum_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : has_sum f (f b) := suffices has_sum f (∑ b' in {b}, f b'), by simpa using this, has_sum_sum_of_ne_finset_zero $ by simpa [hf] lemma has_sum_ite_eq (b : β) [decidable_pred (= b)] (a : α) : has_sum (λb', if b' = b then a else 0) a := begin convert has_sum_single b _, { exact (if_pos rfl).symm }, assume b' hb', exact if_neg hb' end lemma has_sum_pi_single [decidable_eq β] (b : β) (a : α) : has_sum (pi.single b a) a := show has_sum (λ x, pi.single b a x) a, by simpa only [pi.single_apply] using has_sum_ite_eq b a lemma equiv.has_sum_iff (e : γ ≃ β) : has_sum (f ∘ e) a ↔ has_sum f a := e.injective.has_sum_iff $ by simp lemma function.injective.has_sum_range_iff {g : γ → β} (hg : injective g) : has_sum (λ x : set.range g, f x) a ↔ has_sum (f ∘ g) a := (equiv.of_injective g hg).has_sum_iff.symm lemma equiv.summable_iff (e : γ ≃ β) : summable (f ∘ e) ↔ summable f := exists_congr $ λ a, e.has_sum_iff lemma summable.prod_symm {f : β × γ → α} (hf : summable f) : summable (λ p : γ × β, f p.swap) := (equiv.prod_comm γ β).summable_iff.2 hf lemma equiv.has_sum_iff_of_support {g : γ → α} (e : support f ≃ support g) (he : ∀ x : support f, g (e x) = f x) : has_sum f a ↔ has_sum g a := have (g ∘ coe) ∘ e = f ∘ coe, from funext he, by rw [← has_sum_subtype_support, ← this, e.has_sum_iff, has_sum_subtype_support] lemma has_sum_iff_has_sum_of_ne_zero_bij {g : γ → α} (i : support g → β) (hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y) (hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) : has_sum f a ↔ has_sum g a := iff.symm $ equiv.has_sum_iff_of_support (equiv.of_bijective (λ x, ⟨i x, λ hx, x.coe_prop $ hfg x ▸ hx⟩) ⟨λ x y h, subtype.ext $ hi $ subtype.ext_iff.1 h, λ y, (hf y.coe_prop).imp $ λ x hx, subtype.ext hx⟩) hfg lemma equiv.summable_iff_of_support {g : γ → α} (e : support f ≃ support g) (he : ∀ x : support f, g (e x) = f x) : summable f ↔ summable g := exists_congr $ λ _, e.has_sum_iff_of_support he protected lemma has_sum.map [add_comm_monoid γ] [topological_space γ] (hf : has_sum f a) {G} [add_monoid_hom_class G α γ] (g : G) (hg : continuous g) : has_sum (g ∘ f) (g a) := have g ∘ (λs:finset β, ∑ b in s, f b) = (λs:finset β, ∑ b in s, g (f b)), from funext $ map_sum g _, show tendsto (λs:finset β, ∑ b in s, g (f b)) at_top (𝓝 (g a)), from this ▸ (hg.tendsto a).comp hf protected lemma summable.map [add_comm_monoid γ] [topological_space γ] (hf : summable f) {G} [add_monoid_hom_class G α γ] (g : G) (hg : continuous g) : summable (g ∘ f) := (hf.has_sum.map g hg).summable protected lemma summable.map_iff_of_left_inverse [add_comm_monoid γ] [topological_space γ] {G G'} [add_monoid_hom_class G α γ] [add_monoid_hom_class G' γ α] (g : G) (g' : G') (hg : continuous g) (hg' : continuous g') (hinv : function.left_inverse g' g) : summable (g ∘ f) ↔ summable f := ⟨λ h, begin have := h.map _ hg', rwa [←function.comp.assoc, hinv.id] at this, end, λ h, h.map _ hg⟩ /-- A special case of `summable.map_iff_of_left_inverse` for convenience -/ protected lemma summable.map_iff_of_equiv [add_comm_monoid γ] [topological_space γ] {G} [add_equiv_class G α γ] (g : G) (hg : continuous g) (hg' : continuous (add_equiv_class.inv g : γ → α)) : summable (g ∘ f) ↔ summable f := summable.map_iff_of_left_inverse g (g : α ≃+ γ).symm hg hg' (add_equiv_class.left_inv g) /-- If `f : ℕ → α` has sum `a`, then the partial sums `∑_{i=0}^{n-1} f i` converge to `a`. -/ lemma has_sum.tendsto_sum_nat {f : ℕ → α} (h : has_sum f a) : tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := h.comp tendsto_finset_range lemma has_sum.unique {a₁ a₂ : α} [t2_space α] : has_sum f a₁ → has_sum f a₂ → a₁ = a₂ := tendsto_nhds_unique lemma summable.has_sum_iff_tendsto_nat [t2_space α] {f : ℕ → α} {a : α} (hf : summable f) : has_sum f a ↔ tendsto (λn:ℕ, ∑ i in range n, f i) at_top (𝓝 a) := begin refine ⟨λ h, h.tendsto_sum_nat, λ h, _⟩, rw tendsto_nhds_unique h hf.has_sum.tendsto_sum_nat, exact hf.has_sum end lemma function.surjective.summable_iff_of_has_sum_iff {α' : Type*} [add_comm_monoid α'] [topological_space α'] {e : α' → α} (hes : function.surjective e) {f : β → α} {g : γ → α'} (he : ∀ {a}, has_sum f (e a) ↔ has_sum g a) : summable f ↔ summable g := hes.exists.trans $ exists_congr $ @he variable [has_continuous_add α] lemma has_sum.add (hf : has_sum f a) (hg : has_sum g b) : has_sum (λb, f b + g b) (a + b) := by simp only [has_sum, sum_add_distrib]; exact hf.add hg lemma summable.add (hf : summable f) (hg : summable g) : summable (λb, f b + g b) := (hf.has_sum.add hg.has_sum).summable lemma has_sum_sum {f : γ → β → α} {a : γ → α} {s : finset γ} : (∀i∈s, has_sum (f i) (a i)) → has_sum (λb, ∑ i in s, f i b) (∑ i in s, a i) := finset.induction_on s (by simp only [has_sum_zero, sum_empty, forall_true_iff]) (by simp only [has_sum.add, sum_insert, mem_insert, forall_eq_or_imp, forall_2_true_iff, not_false_iff, forall_true_iff] {contextual := tt}) lemma summable_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : summable (λb, ∑ i in s, f i b) := (has_sum_sum $ assume i hi, (hf i hi).has_sum).summable lemma has_sum.add_disjoint {s t : set β} (hs : disjoint s t) (ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : t → α) b) : has_sum (f ∘ coe : s ∪ t → α) (a + b) := begin rw has_sum_subtype_iff_indicator at *, rw set.indicator_union_of_disjoint hs, exact ha.add hb end lemma has_sum_sum_disjoint {ι} (s : finset ι) {t : ι → set β} {a : ι → α} (hs : (s : set ι).pairwise (disjoint on t)) (hf : ∀ i ∈ s, has_sum (f ∘ coe : t i → α) (a i)) : has_sum (f ∘ coe : (⋃ i ∈ s, t i) → α) (∑ i in s, a i) := begin simp_rw has_sum_subtype_iff_indicator at *, rw set.indicator_finset_bUnion _ _ hs, exact has_sum_sum hf, end lemma has_sum.add_is_compl {s t : set β} (hs : is_compl s t) (ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : t → α) b) : has_sum f (a + b) := by simpa [← hs.compl_eq] using (has_sum_subtype_iff_indicator.1 ha).add (has_sum_subtype_iff_indicator.1 hb) lemma has_sum.add_compl {s : set β} (ha : has_sum (f ∘ coe : s → α) a) (hb : has_sum (f ∘ coe : sᶜ → α) b) : has_sum f (a + b) := ha.add_is_compl is_compl_compl hb lemma summable.add_compl {s : set β} (hs : summable (f ∘ coe : s → α)) (hsc : summable (f ∘ coe : sᶜ → α)) : summable f := (hs.has_sum.add_compl hsc.has_sum).summable lemma has_sum.compl_add {s : set β} (ha : has_sum (f ∘ coe : sᶜ → α) a) (hb : has_sum (f ∘ coe : s → α) b) : has_sum f (a + b) := ha.add_is_compl is_compl_compl.symm hb lemma has_sum.even_add_odd {f : ℕ → α} (he : has_sum (λ k, f (2 * k)) a) (ho : has_sum (λ k, f (2 * k + 1)) b) : has_sum f (a + b) := begin have := mul_right_injective₀ (two_ne_zero' ℕ), replace he := this.has_sum_range_iff.2 he, replace ho := ((add_left_injective 1).comp this).has_sum_range_iff.2 ho, refine he.add_is_compl _ ho, simpa [(∘)] using nat.is_compl_even_odd end lemma summable.compl_add {s : set β} (hs : summable (f ∘ coe : sᶜ → α)) (hsc : summable (f ∘ coe : s → α)) : summable f := (hs.has_sum.compl_add hsc.has_sum).summable lemma summable.even_add_odd {f : ℕ → α} (he : summable (λ k, f (2 * k))) (ho : summable (λ k, f (2 * k + 1))) : summable f := (he.has_sum.even_add_odd ho.has_sum).summable lemma has_sum.sigma [regular_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (ha : has_sum f a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) : has_sum g a := begin refine (at_top_basis.tendsto_iff (closed_nhds_basis a)).mpr _, rintros s ⟨hs, hsc⟩, rcases mem_at_top_sets.mp (ha hs) with ⟨u, hu⟩, use [u.image sigma.fst, trivial], intros bs hbs, simp only [set.mem_preimage, ge_iff_le, finset.le_iff_subset] at hu, have : tendsto (λ t : finset (Σ b, γ b), ∑ p in t.filter (λ p, p.1 ∈ bs), f p) at_top (𝓝 $ ∑ b in bs, g b), { simp only [← sigma_preimage_mk, sum_sigma], refine tendsto_finset_sum _ (λ b hb, _), change tendsto (λ t, (λ t, ∑ s in t, f ⟨b, s⟩) (preimage t (sigma.mk b) _)) at_top (𝓝 (g b)), exact tendsto.comp (hf b) (tendsto_finset_preimage_at_top_at_top _) }, refine hsc.mem_of_tendsto this (eventually_at_top.2 ⟨u, λ t ht, hu _ (λ x hx, _)⟩), exact mem_filter.2 ⟨ht hx, hbs $ mem_image_of_mem _ hx⟩ end /-- If a series `f` on `β × γ` has sum `a` and for each `b` the restriction of `f` to `{b} × γ` has sum `g b`, then the series `g` has sum `a`. -/ lemma has_sum.prod_fiberwise [regular_space α] {f : β × γ → α} {g : β → α} {a : α} (ha : has_sum f a) (hf : ∀b, has_sum (λc, f (b, c)) (g b)) : has_sum g a := has_sum.sigma ((equiv.sigma_equiv_prod β γ).has_sum_iff.2 ha) hf lemma summable.sigma' [regular_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) (hf : ∀b, summable (λc, f ⟨b, c⟩)) : summable (λb, ∑'c, f ⟨b, c⟩) := (ha.has_sum.sigma (assume b, (hf b).has_sum)).summable lemma has_sum.sigma_of_has_sum [t3_space α] {γ : β → Type*} {f : (Σ b:β, γ b) → α} {g : β → α} {a : α} (ha : has_sum g a) (hf : ∀b, has_sum (λc, f ⟨b, c⟩) (g b)) (hf' : summable f) : has_sum f a := by simpa [(hf'.has_sum.sigma hf).unique ha] using hf'.has_sum /-- Version of `has_sum.update` for `add_comm_monoid` rather than `add_comm_group`. Rather than showing that `f.update` has a specific sum in terms of `has_sum`, it gives a relationship between the sums of `f` and `f.update` given that both exist. -/ lemma has_sum.update' {α β : Type*} [topological_space α] [add_comm_monoid α] [t2_space α] [has_continuous_add α] {f : β → α} {a a' : α} (hf : has_sum f a) (b : β) (x : α) (hf' : has_sum (f.update b x) a') : a + x = a' + f b := begin have : ∀ b', f b' + ite (b' = b) x 0 = f.update b x b' + ite (b' = b) (f b) 0, { intro b', split_ifs with hb', { simpa only [function.update_apply, hb', eq_self_iff_true] using add_comm (f b) x }, { simp only [function.update_apply, hb', if_false] } }, have h := hf.add ((has_sum_ite_eq b x)), simp_rw this at h, exact has_sum.unique h (hf'.add (has_sum_ite_eq b (f b))) end /-- Version of `has_sum_ite_sub_has_sum` for `add_comm_monoid` rather than `add_comm_group`. Rather than showing that the `ite` expression has a specific sum in terms of `has_sum`, it gives a relationship between the sums of `f` and `ite (n = b) 0 (f n)` given that both exist. -/ lemma eq_add_of_has_sum_ite {α β : Type*} [topological_space α] [add_comm_monoid α] [t2_space α] [has_continuous_add α] {f : β → α} {a : α} (hf : has_sum f a) (b : β) (a' : α) (hf' : has_sum (λ n, ite (n = b) 0 (f n)) a') : a = a' + f b := begin refine (add_zero a).symm.trans (hf.update' b 0 _), convert hf', exact funext (f.update_apply b 0), end end has_sum section tsum variables [add_comm_monoid α] [topological_space α] lemma tsum_congr_subtype (f : β → α) {s t : set β} (h : s = t) : ∑' (x : s), f x = ∑' (x : t), f x := by rw h lemma tsum_zero' (hz : is_closed ({0} : set α)) : ∑' b : β, (0 : α) = 0 := begin classical, rw [tsum, dif_pos summable_zero], suffices : ∀ (x : α), has_sum (λ (b : β), (0 : α)) x → x = 0, { exact this _ (classical.some_spec _) }, intros x hx, contrapose! hx, simp only [has_sum, tendsto_nhds, finset.sum_const_zero, filter.mem_at_top_sets, ge_iff_le, finset.le_eq_subset, set.mem_preimage, not_forall, not_exists, exists_prop, exists_and_distrib_right], refine ⟨{0}ᶜ, ⟨is_open_compl_iff.mpr hz, _⟩, λ y, ⟨⟨y, subset_refl _⟩, _⟩⟩, { simpa using hx }, { simp } end @[simp] lemma tsum_zero [t1_space α] : ∑' b : β, (0 : α) = 0 := tsum_zero' is_closed_singleton variables [t2_space α] {f g : β → α} {a a₁ a₂ : α} lemma has_sum.tsum_eq (ha : has_sum f a) : ∑'b, f b = a := (summable.has_sum ⟨a, ha⟩).unique ha lemma summable.has_sum_iff (h : summable f) : has_sum f a ↔ ∑'b, f b = a := iff.intro has_sum.tsum_eq (assume eq, eq ▸ h.has_sum) @[simp] lemma tsum_empty [is_empty β] : ∑'b, f b = 0 := has_sum_empty.tsum_eq lemma tsum_eq_sum {f : β → α} {s : finset β} (hf : ∀b∉s, f b = 0) : ∑' b, f b = ∑ b in s, f b := (has_sum_sum_of_ne_finset_zero hf).tsum_eq lemma sum_eq_tsum_indicator (f : β → α) (s : finset β) : ∑ x in s, f x = ∑' x, set.indicator ↑s f x := have ∀ x ∉ s, set.indicator ↑s f x = 0, from λ x hx, set.indicator_apply_eq_zero.2 (λ hx', (hx $ finset.mem_coe.1 hx').elim), (finset.sum_congr rfl (λ x hx, (set.indicator_apply_eq_self.2 $ λ hx', (hx' $ finset.mem_coe.2 hx).elim).symm)).trans (tsum_eq_sum this).symm lemma tsum_congr {α β : Type*} [add_comm_monoid α] [topological_space α] {f g : β → α} (hfg : ∀ b, f b = g b) : ∑' b, f b = ∑' b, g b := congr_arg tsum (funext hfg) lemma tsum_fintype [fintype β] (f : β → α) : ∑'b, f b = ∑ b, f b := (has_sum_fintype f).tsum_eq lemma tsum_bool (f : bool → α) : ∑' i : bool, f i = f false + f true := by { rw [tsum_fintype, finset.sum_eq_add]; simp } lemma tsum_eq_single {f : β → α} (b : β) (hf : ∀b' ≠ b, f b' = 0) : ∑'b, f b = f b := (has_sum_single b hf).tsum_eq lemma tsum_tsum_eq_single (f : β → γ → α) (b : β) (c : γ) (hfb : ∀ b' ≠ b, f b' c = 0) (hfc : ∀ (b' : β) (c' : γ), c' ≠ c → f b' c' = 0) : ∑' b' c', f b' c' = f b c := calc ∑' b' c', f b' c' = ∑' b', f b' c : tsum_congr $ λ b', tsum_eq_single _ (hfc b') ... = f b c : tsum_eq_single _ hfb @[simp] lemma tsum_ite_eq (b : β) [decidable_pred (= b)] (a : α) : ∑' b', (if b' = b then a else 0) = a := (has_sum_ite_eq b a).tsum_eq @[simp] lemma tsum_pi_single [decidable_eq β] (b : β) (a : α) : ∑' b', pi.single b a b' = a := (has_sum_pi_single b a).tsum_eq lemma tsum_dite_right (P : Prop) [decidable P] (x : β → ¬ P → α) : ∑' (b : β), (if h : P then (0 : α) else x b h) = if h : P then (0 : α) else ∑' (b : β), x b h := by by_cases hP : P; simp [hP] lemma tsum_dite_left (P : Prop) [decidable P] (x : β → P → α) : ∑' (b : β), (if h : P then x b h else 0) = if h : P then (∑' (b : β), x b h) else 0 := by by_cases hP : P; simp [hP] lemma function.surjective.tsum_eq_tsum_of_has_sum_iff_has_sum {α' : Type*} [add_comm_monoid α'] [topological_space α'] {e : α' → α} (hes : function.surjective e) (h0 : e 0 = 0) {f : β → α} {g : γ → α'} (h : ∀ {a}, has_sum f (e a) ↔ has_sum g a) : ∑' b, f b = e (∑' c, g c) := by_cases (assume : summable g, (h.mpr this.has_sum).tsum_eq) (assume hg : ¬ summable g, have hf : ¬ summable f, from mt (hes.summable_iff_of_has_sum_iff @h).1 hg, by simp [tsum, hf, hg, h0]) lemma tsum_eq_tsum_of_has_sum_iff_has_sum {f : β → α} {g : γ → α} (h : ∀{a}, has_sum f a ↔ has_sum g a) : ∑'b, f b = ∑'c, g c := surjective_id.tsum_eq_tsum_of_has_sum_iff_has_sum rfl @h lemma equiv.tsum_eq (j : γ ≃ β) (f : β → α) : ∑'c, f (j c) = ∑'b, f b := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ a, j.has_sum_iff lemma equiv.tsum_eq_tsum_of_support {f : β → α} {g : γ → α} (e : support f ≃ support g) (he : ∀ x, g (e x) = f x) : (∑' x, f x) = ∑' y, g y := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, e.has_sum_iff_of_support he lemma tsum_eq_tsum_of_ne_zero_bij {g : γ → α} (i : support g → β) (hi : ∀ ⦃x y⦄, i x = i y → (x : γ) = y) (hf : support f ⊆ set.range i) (hfg : ∀ x, f (i x) = g x) : ∑' x, f x = ∑' y, g y := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_iff_has_sum_of_ne_zero_bij i hi hf hfg /-! ### `tsum` on subsets -/ @[simp] lemma finset.tsum_subtype (s : finset β) (f : β → α) : ∑' x : {x // x ∈ s}, f x = ∑ x in s, f x := (s.has_sum f).tsum_eq @[simp] lemma finset.tsum_subtype' (s : finset β) (f : β → α) : ∑' x : (s : set β), f x = ∑ x in s, f x := s.tsum_subtype f lemma tsum_subtype (s : set β) (f : β → α) : ∑' x : s, f x = ∑' x, s.indicator f x := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ _, has_sum_subtype_iff_indicator lemma tsum_subtype_eq_of_support_subset {f : β → α} {s : set β} (hs : support f ⊆ s) : ∑' x : s, f x = ∑' x, f x := tsum_eq_tsum_of_has_sum_iff_has_sum $ λ x, has_sum_subtype_iff_of_support_subset hs @[simp] lemma tsum_univ (f : β → α) : ∑' x : (set.univ : set β), f x = ∑' x, f x := tsum_subtype_eq_of_support_subset $ set.subset_univ _ @[simp] lemma tsum_singleton (b : β) (f : β → α) : ∑' x : ({b} : set β), f x = f b := begin rw [tsum_subtype, tsum_eq_single b], { simp }, { intros b' hb', rw set.indicator_of_not_mem, rwa set.mem_singleton_iff }, { apply_instance } end lemma tsum_image {g : γ → β} (f : β → α) {s : set γ} (hg : set.inj_on g s) : ∑' x : g '' s, f x = ∑' x : s, f (g x) := ((equiv.set.image_of_inj_on _ _ hg).tsum_eq (λ x, f x)).symm lemma tsum_range {g : γ → β} (f : β → α) (hg : injective g) : ∑' x : set.range g, f x = ∑' x, f (g x) := by rw [← set.image_univ, tsum_image f (hg.inj_on _), tsum_univ (f ∘ g)] section has_continuous_add variable [has_continuous_add α] lemma tsum_add (hf : summable f) (hg : summable g) : ∑'b, (f b + g b) = (∑'b, f b) + (∑'b, g b) := (hf.has_sum.add hg.has_sum).tsum_eq lemma tsum_sum {f : γ → β → α} {s : finset γ} (hf : ∀i∈s, summable (f i)) : ∑'b, ∑ i in s, f i b = ∑ i in s, ∑'b, f i b := (has_sum_sum $ assume i hi, (hf i hi).has_sum).tsum_eq /-- Version of `tsum_eq_add_tsum_ite` for `add_comm_monoid` rather than `add_comm_group`. Requires a different convergence assumption involving `function.update`. -/ lemma tsum_eq_add_tsum_ite' {f : β → α} (b : β) (hf : summable (f.update b 0)) : ∑' x, f x = f b + ∑' x, ite (x = b) 0 (f x) := calc ∑' x, f x = ∑' x, ((ite (x = b) (f x) 0) + (f.update b 0 x)) : tsum_congr (λ n, by split_ifs; simp [function.update_apply, h]) ... = ∑' x, ite (x = b) (f x) 0 + ∑' x, f.update b 0 x : tsum_add ⟨ite (b = b) (f b) 0, has_sum_single b (λ b hb, if_neg hb)⟩ (hf) ... = (ite (b = b) (f b) 0) + ∑' x, f.update b 0 x : by { congr, exact (tsum_eq_single b (λ b' hb', if_neg hb')) } ... = f b + ∑' x, ite (x = b) 0 (f x) : by simp only [function.update, eq_self_iff_true, if_true, eq_rec_constant, dite_eq_ite] variables [add_comm_monoid δ] [topological_space δ] [t3_space δ] [has_continuous_add δ] lemma tsum_sigma' {γ : β → Type*} {f : (Σb:β, γ b) → δ} (h₁ : ∀b, summable (λc, f ⟨b, c⟩)) (h₂ : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ := (h₂.has_sum.sigma (assume b, (h₁ b).has_sum)).tsum_eq.symm lemma tsum_prod' {f : β × γ → δ} (h : summable f) (h₁ : ∀b, summable (λc, f (b, c))) : ∑'p, f p = ∑'b c, f (b, c) := (h.has_sum.prod_fiberwise (assume b, (h₁ b).has_sum)).tsum_eq.symm lemma tsum_comm' {f : β → γ → δ} (h : summable (function.uncurry f)) (h₁ : ∀b, summable (f b)) (h₂ : ∀ c, summable (λ b, f b c)) : ∑' c b, f b c = ∑' b c, f b c := begin erw [← tsum_prod' h h₁, ← tsum_prod' h.prod_symm h₂, ← (equiv.prod_comm γ β).tsum_eq (uncurry f)], refl end end has_continuous_add open encodable section encodable variable [encodable γ] /-- You can compute a sum over an encodably type by summing over the natural numbers and taking a supremum. This is useful for outer measures. -/ theorem tsum_supr_decode₂ [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (s : γ → β) : ∑' i : ℕ, m (⨆ b ∈ decode₂ γ i, s b) = ∑' b : γ, m (s b) := begin have H : ∀ n, m (⨆ b ∈ decode₂ γ n, s b) ≠ 0 → (decode₂ γ n).is_some, { intros n h, cases decode₂ γ n with b, { refine (h $ by simp [m0]).elim }, { exact rfl } }, symmetry, refine tsum_eq_tsum_of_ne_zero_bij (λ a, option.get (H a.1 a.2)) _ _ _, { rintros ⟨m, hm⟩ ⟨n, hn⟩ e, have := mem_decode₂.1 (option.get_mem (H n hn)), rwa [← e, mem_decode₂.1 (option.get_mem (H m hm))] at this }, { intros b h, refine ⟨⟨encode b, _⟩, _⟩, { simp only [mem_support, encodek₂] at h ⊢, convert h, simp [set.ext_iff, encodek₂] }, { exact option.get_of_mem _ (encodek₂ _) } }, { rintros ⟨n, h⟩, dsimp only [subtype.coe_mk], transitivity, swap, rw [show decode₂ γ n = _, from option.get_mem (H n h)], congr, simp [ext_iff, -option.some_get] } end /-- `tsum_supr_decode₂` specialized to the complete lattice of sets. -/ theorem tsum_Union_decode₂ (m : set β → α) (m0 : m ∅ = 0) (s : γ → set β) : ∑' i, m (⋃ b ∈ decode₂ γ i, s b) = ∑' b, m (s b) := tsum_supr_decode₂ m m0 s end encodable /-! Some properties about measure-like functions. These could also be functions defined on complete sublattices of sets, with the property that they are countably sub-additive. `R` will probably be instantiated with `(≤)` in all applications. -/ section countable variables [countable γ] /-- If a function is countably sub-additive then it is sub-additive on countable types -/ theorem rel_supr_tsum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) ∑' i, m (s i)) (s : γ → β) : R (m (⨆ b : γ, s b)) ∑' b : γ, m (s b) := by { casesI nonempty_encodable γ, rw [←supr_decode₂, ←tsum_supr_decode₂ _ m0 s], exact m_supr _ } /-- If a function is countably sub-additive then it is sub-additive on finite sets -/ theorem rel_supr_sum [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i))) (s : δ → β) (t : finset δ) : R (m (⨆ d ∈ t, s d)) (∑ d in t, m (s d)) := by { rw [supr_subtype', ←finset.tsum_subtype], exact rel_supr_tsum m m0 R m_supr _ } /-- If a function is countably sub-additive then it is binary sub-additive -/ theorem rel_sup_add [complete_lattice β] (m : β → α) (m0 : m ⊥ = 0) (R : α → α → Prop) (m_supr : ∀(s : ℕ → β), R (m (⨆ i, s i)) (∑' i, m (s i))) (s₁ s₂ : β) : R (m (s₁ ⊔ s₂)) (m s₁ + m s₂) := begin convert rel_supr_tsum m m0 R m_supr (λ b, cond b s₁ s₂), { simp only [supr_bool_eq, cond] }, { rw [tsum_fintype, fintype.sum_bool, cond, cond] } end end countable variables [has_continuous_add α] lemma tsum_add_tsum_compl {s : set β} (hs : summable (f ∘ coe : s → α)) (hsc : summable (f ∘ coe : sᶜ → α)) : (∑' x : s, f x) + (∑' x : sᶜ, f x) = ∑' x, f x := (hs.has_sum.add_compl hsc.has_sum).tsum_eq.symm lemma tsum_union_disjoint {s t : set β} (hd : disjoint s t) (hs : summable (f ∘ coe : s → α)) (ht : summable (f ∘ coe : t → α)) : (∑' x : s ∪ t, f x) = (∑' x : s, f x) + (∑' x : t, f x) := (hs.has_sum.add_disjoint hd ht.has_sum).tsum_eq lemma tsum_finset_bUnion_disjoint {ι} {s : finset ι} {t : ι → set β} (hd : (s : set ι).pairwise (disjoint on t)) (hf : ∀ i ∈ s, summable (f ∘ coe : t i → α)) : (∑' x : (⋃ i ∈ s, t i), f x) = ∑ i in s, ∑' x : t i, f x := (has_sum_sum_disjoint _ hd (λ i hi, (hf i hi).has_sum)).tsum_eq lemma tsum_even_add_odd {f : ℕ → α} (he : summable (λ k, f (2 * k))) (ho : summable (λ k, f (2 * k + 1))) : (∑' k, f (2 * k)) + (∑' k, f (2 * k + 1)) = ∑' k, f k := (he.has_sum.even_add_odd ho.has_sum).tsum_eq.symm end tsum section topological_group variables [add_comm_group α] [topological_space α] [topological_add_group α] variables {f g : β → α} {a a₁ a₂ : α} -- `by simpa using` speeds up elaboration. Why? lemma has_sum.neg (h : has_sum f a) : has_sum (λb, - f b) (- a) := by simpa only using h.map (-add_monoid_hom.id α) continuous_neg lemma summable.neg (hf : summable f) : summable (λb, - f b) := hf.has_sum.neg.summable lemma summable.of_neg (hf : summable (λb, - f b)) : summable f := by simpa only [neg_neg] using hf.neg lemma summable_neg_iff : summable (λ b, - f b) ↔ summable f := ⟨summable.of_neg, summable.neg⟩ lemma has_sum.sub (hf : has_sum f a₁) (hg : has_sum g a₂) : has_sum (λb, f b - g b) (a₁ - a₂) := by { simp only [sub_eq_add_neg], exact hf.add hg.neg } lemma summable.sub (hf : summable f) (hg : summable g) : summable (λb, f b - g b) := (hf.has_sum.sub hg.has_sum).summable lemma summable.trans_sub (hg : summable g) (hfg : summable (λb, f b - g b)) : summable f := by simpa only [sub_add_cancel] using hfg.add hg lemma summable_iff_of_summable_sub (hfg : summable (λb, f b - g b)) : summable f ↔ summable g := ⟨λ hf, hf.trans_sub $ by simpa only [neg_sub] using hfg.neg, λ hg, hg.trans_sub hfg⟩ lemma has_sum.update (hf : has_sum f a₁) (b : β) [decidable_eq β] (a : α) : has_sum (update f b a) (a - f b + a₁) := begin convert ((has_sum_ite_eq b _).add hf), ext b', by_cases h : b' = b, { rw [h, update_same], simp only [eq_self_iff_true, if_true, sub_add_cancel] }, simp only [h, update_noteq, if_false, ne.def, zero_add, not_false_iff], end lemma summable.update (hf : summable f) (b : β) [decidable_eq β] (a : α) : summable (update f b a) := (hf.has_sum.update b a).summable lemma has_sum.has_sum_compl_iff {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) : has_sum (f ∘ coe : sᶜ → α) a₂ ↔ has_sum f (a₁ + a₂) := begin refine ⟨λ h, hf.add_compl h, λ h, _⟩, rw [has_sum_subtype_iff_indicator] at hf ⊢, rw [set.indicator_compl], simpa only [add_sub_cancel'] using h.sub hf end lemma has_sum.has_sum_iff_compl {s : set β} (hf : has_sum (f ∘ coe : s → α) a₁) : has_sum f a₂ ↔ has_sum (f ∘ coe : sᶜ → α) (a₂ - a₁) := iff.symm $ hf.has_sum_compl_iff.trans $ by rw [add_sub_cancel'_right] lemma summable.summable_compl_iff {s : set β} (hf : summable (f ∘ coe : s → α)) : summable (f ∘ coe : sᶜ → α) ↔ summable f := ⟨λ ⟨a, ha⟩, (hf.has_sum.has_sum_compl_iff.1 ha).summable, λ ⟨a, ha⟩, (hf.has_sum.has_sum_iff_compl.1 ha).summable⟩ protected lemma finset.has_sum_compl_iff (s : finset β) : has_sum (λ x : {x // x ∉ s}, f x) a ↔ has_sum f (a + ∑ i in s, f i) := (s.has_sum f).has_sum_compl_iff.trans $ by rw [add_comm] protected lemma finset.has_sum_iff_compl (s : finset β) : has_sum f a ↔ has_sum (λ x : {x // x ∉ s}, f x) (a - ∑ i in s, f i) := (s.has_sum f).has_sum_iff_compl protected lemma finset.summable_compl_iff (s : finset β) : summable (λ x : {x // x ∉ s}, f x) ↔ summable f := (s.summable f).summable_compl_iff lemma set.finite.summable_compl_iff {s : set β} (hs : s.finite) : summable (f ∘ coe : sᶜ → α) ↔ summable f := (hs.summable f).summable_compl_iff lemma has_sum_ite_sub_has_sum [decidable_eq β] (hf : has_sum f a) (b : β) : has_sum (λ n, ite (n = b) 0 (f n)) (a - f b) := begin convert hf.update b 0 using 1, { ext n, rw function.update_apply, }, { rw [sub_add_eq_add_sub, zero_add], }, end section tsum variables [t2_space α] lemma tsum_neg : ∑'b, - f b = - ∑'b, f b := begin by_cases hf : summable f, { exact hf.has_sum.neg.tsum_eq, }, { simp [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable (mt summable.of_neg hf)] }, end lemma tsum_sub (hf : summable f) (hg : summable g) : ∑'b, (f b - g b) = ∑'b, f b - ∑'b, g b := (hf.has_sum.sub hg.has_sum).tsum_eq lemma sum_add_tsum_compl {s : finset β} (hf : summable f) : (∑ x in s, f x) + (∑' x : (↑s : set β)ᶜ, f x) = ∑' x, f x := ((s.has_sum f).add_compl (s.summable_compl_iff.2 hf).has_sum).tsum_eq.symm /-- Let `f : β → α` be a sequence with summable series and let `b ∈ β` be an index. Lemma `tsum_eq_add_tsum_ite` writes `Σ f n` as the sum of `f b` plus the series of the remaining terms. -/ lemma tsum_eq_add_tsum_ite [decidable_eq β] (hf : summable f) (b : β) : ∑' n, f n = f b + ∑' n, ite (n = b) 0 (f n) := begin rw (has_sum_ite_sub_has_sum hf.has_sum b).tsum_eq, exact (add_sub_cancel'_right _ _).symm, end end tsum /-! ### Sums on nat We show the formula `(∑ i in range k, f i) + (∑' i, f (i + k)) = (∑' i, f i)`, in `sum_add_tsum_nat_add`, as well as several results relating sums on `ℕ` and `ℤ`. -/ section nat lemma has_sum_nat_add_iff {f : ℕ → α} (k : ℕ) {a : α} : has_sum (λ n, f (n + k)) a ↔ has_sum f (a + ∑ i in range k, f i) := begin refine iff.trans _ ((range k).has_sum_compl_iff), rw [← (not_mem_range_equiv k).symm.has_sum_iff], refl end lemma summable_nat_add_iff {f : ℕ → α} (k : ℕ) : summable (λ n, f (n + k)) ↔ summable f := iff.symm $ (equiv.add_right (∑ i in range k, f i)).surjective.summable_iff_of_has_sum_iff $ λ a, (has_sum_nat_add_iff k).symm lemma has_sum_nat_add_iff' {f : ℕ → α} (k : ℕ) {a : α} : has_sum (λ n, f (n + k)) (a - ∑ i in range k, f i) ↔ has_sum f a := by simp [has_sum_nat_add_iff] lemma sum_add_tsum_nat_add [t2_space α] {f : ℕ → α} (k : ℕ) (h : summable f) : (∑ i in range k, f i) + (∑' i, f (i + k)) = ∑' i, f i := by simpa only [add_comm] using ((has_sum_nat_add_iff k).1 ((summable_nat_add_iff k).2 h).has_sum).unique h.has_sum lemma tsum_eq_zero_add [t2_space α] {f : ℕ → α} (hf : summable f) : ∑'b, f b = f 0 + ∑'b, f (b + 1) := by simpa only [sum_range_one] using (sum_add_tsum_nat_add 1 hf).symm /-- For `f : ℕ → α`, then `∑' k, f (k + i)` tends to zero. This does not require a summability assumption on `f`, as otherwise all sums are zero. -/ lemma tendsto_sum_nat_add [t2_space α] (f : ℕ → α) : tendsto (λ i, ∑' k, f (k + i)) at_top (𝓝 0) := begin by_cases hf : summable f, { have h₀ : (λ i, (∑' i, f i) - ∑ j in range i, f j) = λ i, ∑' (k : ℕ), f (k + i), { ext1 i, rw [sub_eq_iff_eq_add, add_comm, sum_add_tsum_nat_add i hf] }, have h₁ : tendsto (λ i : ℕ, ∑' i, f i) at_top (𝓝 (∑' i, f i)) := tendsto_const_nhds, simpa only [h₀, sub_self] using tendsto.sub h₁ hf.has_sum.tendsto_sum_nat }, { convert tendsto_const_nhds, ext1 i, rw ← summable_nat_add_iff i at hf, { exact tsum_eq_zero_of_not_summable hf }, { apply_instance } } end /-- If `f₀, f₁, f₂, ...` and `g₀, g₁, g₂, ...` are both convergent then so is the `ℤ`-indexed sequence: `..., g₂, g₁, g₀, f₀, f₁, f₂, ...`. -/ lemma has_sum.int_rec {b : α} {f g : ℕ → α} (hf : has_sum f a) (hg : has_sum g b) : @has_sum α _ _ _ (@int.rec (λ _, α) f g : ℤ → α) (a + b) := begin -- note this proof works for any two-case inductive have h₁ : injective (coe : ℕ → ℤ) := @int.of_nat.inj, have h₂ : injective int.neg_succ_of_nat := @int.neg_succ_of_nat.inj, have : is_compl (set.range (coe : ℕ → ℤ)) (set.range int.neg_succ_of_nat), { split, { rw disjoint_iff_inf_le, rintros _ ⟨⟨i, rfl⟩, ⟨j, ⟨⟩⟩⟩ }, { rw codisjoint_iff_le_sup, rintros (i | j) h, exacts [or.inl ⟨_, rfl⟩, or.inr ⟨_, rfl⟩] } }, exact has_sum.add_is_compl this (h₁.has_sum_range_iff.mpr hf) (h₂.has_sum_range_iff.mpr hg), end lemma has_sum.nonneg_add_neg {b : α} {f : ℤ → α} (hnonneg : has_sum (λ n : ℕ, f n) a) (hneg : has_sum (λ (n : ℕ), f (-n.succ)) b) : has_sum f (a + b) := begin simp_rw ← int.neg_succ_of_nat_coe at hneg, convert hnonneg.int_rec hneg using 1, ext (i | j); refl, end lemma has_sum.pos_add_zero_add_neg {b : α} {f : ℤ → α} (hpos : has_sum (λ n:ℕ, f(n + 1)) a) (hneg : has_sum (λ (n : ℕ), f (-n.succ)) b) : has_sum f (a + f 0 + b) := begin have : ∀ g : ℕ → α, has_sum (λ k, g (k + 1)) a → has_sum g (a + g 0), { intros g hg, simpa using (has_sum_nat_add_iff _).mp hg }, exact (this (λ n, f n) hpos).nonneg_add_neg hneg, end lemma summable_int_of_summable_nat {f : ℤ → α} (hp : summable (λ n:ℕ, f n)) (hn : summable (λ n:ℕ, f (-n))) : summable f := (has_sum.nonneg_add_neg hp.has_sum $ summable.has_sum $ (summable_nat_add_iff 1).mpr hn).summable lemma has_sum.sum_nat_of_sum_int {α : Type*} [add_comm_monoid α] [topological_space α] [has_continuous_add α] {a : α} {f : ℤ → α} (hf : has_sum f a) : has_sum (λ n:ℕ, f n + f (-n)) (a + f 0) := begin apply (hf.add (has_sum_ite_eq (0 : ℤ) (f 0))).has_sum_of_sum_eq (λ u, _), refine ⟨u.image int.nat_abs, λ v' hv', _⟩, let u1 := v'.image (λ (x : ℕ), (x : ℤ)), let u2 := v'.image (λ (x : ℕ), - (x : ℤ)), have A : u ⊆ u1 ∪ u2, { assume x hx, simp only [mem_union, mem_image, exists_prop], rcases le_total 0 x with h'x|h'x, { left, refine ⟨int.nat_abs x, hv' _, _⟩, { simp only [mem_image, exists_prop], exact ⟨x, hx, rfl⟩ }, { simp only [h'x, int.coe_nat_abs, abs_eq_self] } }, { right, refine ⟨int.nat_abs x, hv' _, _⟩, { simp only [mem_image, exists_prop], exact ⟨x, hx, rfl⟩ }, { simp only [abs_of_nonpos h'x, int.coe_nat_abs, neg_neg] } } }, refine ⟨u1 ∪ u2, A, _⟩, calc ∑ x in u1 ∪ u2, (f x + ite (x = 0) (f 0) 0) = ∑ x in u1 ∪ u2, f x + ∑ x in u1 ∩ u2, f x : begin rw sum_add_distrib, congr' 1, refine (sum_subset_zero_on_sdiff inter_subset_union _ _).symm, { assume x hx, suffices : x ≠ 0, by simp only [this, if_false], rintros rfl, simpa only [mem_sdiff, mem_union, mem_image, neg_eq_zero, or_self, mem_inter, and_self, and_not_self] using hx }, { assume x hx, simp only [mem_inter, mem_image, exists_prop] at hx, have : x = 0, { apply le_antisymm, { rcases hx.2 with ⟨a, ha, rfl⟩, simp only [right.neg_nonpos_iff, nat.cast_nonneg] }, { rcases hx.1 with ⟨a, ha, rfl⟩, simp only [nat.cast_nonneg] } }, simp only [this, eq_self_iff_true, if_true] } end ... = ∑ x in u1, f x + ∑ x in u2, f x : sum_union_inter ... = ∑ b in v', f b + ∑ b in v', f (-b) : by simp only [sum_image, nat.cast_inj, imp_self, implies_true_iff, neg_inj] ... = ∑ b in v', (f b + f (-b)) : sum_add_distrib.symm end end nat end topological_group section uniform_group variables [add_comm_group α] [uniform_space α] /-- The **Cauchy criterion** for infinite sums, also known as the **Cauchy convergence test** -/ lemma summable_iff_cauchy_seq_finset [complete_space α] {f : β → α} : summable f ↔ cauchy_seq (λ (s : finset β), ∑ b in s, f b) := cauchy_map_iff_exists_tendsto.symm variables [uniform_add_group α] {f g : β → α} {a a₁ a₂ : α} lemma cauchy_seq_finset_iff_vanishing : cauchy_seq (λ (s : finset β), ∑ b in s, f b) ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) := begin simp only [cauchy_seq, cauchy_map_iff, and_iff_right at_top_ne_bot, prod_at_top_at_top_eq, uniformity_eq_comap_nhds_zero α, tendsto_comap_iff, (∘)], rw [tendsto_at_top'], split, { assume h e he, rcases h e he with ⟨⟨s₁, s₂⟩, h⟩, use [s₁ ∪ s₂], assume t ht, specialize h (s₁ ∪ s₂, (s₁ ∪ s₂) ∪ t) ⟨le_sup_left, le_sup_of_le_left le_sup_right⟩, simpa only [finset.sum_union ht.symm, add_sub_cancel'] using h }, { assume h e he, rcases exists_nhds_half_neg he with ⟨d, hd, hde⟩, rcases h d hd with ⟨s, h⟩, use [(s, s)], rintros ⟨t₁, t₂⟩ ⟨ht₁, ht₂⟩, have : ∑ b in t₂, f b - ∑ b in t₁, f b = ∑ b in t₂ \ s, f b - ∑ b in t₁ \ s, f b, { simp only [(finset.sum_sdiff ht₁).symm, (finset.sum_sdiff ht₂).symm, add_sub_add_right_eq_sub] }, simp only [this], exact hde _ (h _ finset.sdiff_disjoint) _ (h _ finset.sdiff_disjoint) } end /-- The sum over the complement of a finset tends to `0` when the finset grows to cover the whole space. This does not need a summability assumption, as otherwise all sums are zero. -/ lemma tendsto_tsum_compl_at_top_zero (f : β → α) : tendsto (λ (s : finset β), ∑' b : {x // x ∉ s}, f b) at_top (𝓝 0) := begin by_cases H : summable f, { assume e he, rcases exists_mem_nhds_is_closed_subset he with ⟨o, ho, o_closed, oe⟩, simp only [le_eq_subset, set.mem_preimage, mem_at_top_sets, filter.mem_map, ge_iff_le], obtain ⟨s, hs⟩ : ∃ (s : finset β), ∀ (t : finset β), disjoint t s → ∑ (b : β) in t, f b ∈ o := cauchy_seq_finset_iff_vanishing.1 (tendsto.cauchy_seq H.has_sum) o ho, refine ⟨s, λ a sa, oe _⟩, have A : summable (λ b : {x // x ∉ a}, f b) := a.summable_compl_iff.2 H, apply is_closed.mem_of_tendsto o_closed A.has_sum (eventually_of_forall (λ b, _)), have : disjoint (finset.image (λ (i : {x // x ∉ a}), (i : β)) b) s, { apply disjoint_left.2 (λ i hi his, _), rcases mem_image.1 hi with ⟨i', hi', rfl⟩, exact i'.2 (sa his), }, convert hs _ this using 1, rw sum_image, assume i hi j hj hij, exact subtype.ext hij }, { convert tendsto_const_nhds, ext s, apply tsum_eq_zero_of_not_summable, rwa finset.summable_compl_iff } end variable [complete_space α] lemma summable_iff_vanishing : summable f ↔ ∀ e ∈ 𝓝 (0:α), (∃s:finset β, ∀t, disjoint t s → ∑ b in t, f b ∈ e) := by rw [summable_iff_cauchy_seq_finset, cauchy_seq_finset_iff_vanishing] /- TODO: generalize to monoid with a uniform continuous subtraction operator: `(a + b) - b = a` -/ lemma summable.summable_of_eq_zero_or_self (hf : summable f) (h : ∀b, g b = 0 ∨ g b = f b) : summable g := summable_iff_vanishing.2 $ assume e he, let ⟨s, hs⟩ := summable_iff_vanishing.1 hf e he in ⟨s, assume t ht, have eq : ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t, g b := calc ∑ b in t.filter (λb, g b = f b), f b = ∑ b in t.filter (λb, g b = f b), g b : finset.sum_congr rfl (assume b hb, (finset.mem_filter.1 hb).2.symm) ... = ∑ b in t, g b : begin refine finset.sum_subset (finset.filter_subset _ _) _, assume b hbt hb, simp only [(∉), finset.mem_filter, and_iff_right hbt] at hb, exact (h b).resolve_right hb end, eq ▸ hs _ $ finset.disjoint_of_subset_left (finset.filter_subset _ _) ht⟩ protected lemma summable.indicator (hf : summable f) (s : set β) : summable (s.indicator f) := hf.summable_of_eq_zero_or_self $ set.indicator_eq_zero_or_self _ _ lemma summable.comp_injective {i : γ → β} (hf : summable f) (hi : injective i) : summable (f ∘ i) := begin simpa only [set.indicator_range_comp] using (hi.summable_iff _).2 (hf.indicator (set.range i)), exact λ x hx, set.indicator_of_not_mem hx _ end lemma summable.subtype (hf : summable f) (s : set β) : summable (f ∘ coe : s → α) := hf.comp_injective subtype.coe_injective lemma summable_subtype_and_compl {s : set β} : summable (λ x : s, f x) ∧ summable (λ x : sᶜ, f x) ↔ summable f := ⟨and_imp.2 summable.add_compl, λ h, ⟨h.subtype s, h.subtype sᶜ⟩⟩ lemma summable.sigma_factor {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) (b : β) : summable (λc, f ⟨b, c⟩) := ha.comp_injective sigma_mk_injective lemma summable.sigma {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) : summable (λb, ∑'c, f ⟨b, c⟩) := ha.sigma' (λ b, ha.sigma_factor b) lemma summable.prod_factor {f : β × γ → α} (h : summable f) (b : β) : summable (λ c, f (b, c)) := h.comp_injective $ λ c₁ c₂ h, (prod.ext_iff.1 h).2 section loc_instances -- enable inferring a T3-topological space from a topological group local attribute [instance] topological_add_group.t3_space -- disable getting a T0-space from a T3-space as this causes loops local attribute [-instance] t3_space.to_t0_space lemma tsum_sigma [t0_space α] {γ : β → Type*} {f : (Σb:β, γ b) → α} (ha : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ := tsum_sigma' (λ b, ha.sigma_factor b) ha lemma tsum_prod [t0_space α] {f : β × γ → α} (h : summable f) : ∑'p, f p = ∑'b c, f ⟨b, c⟩ := tsum_prod' h h.prod_factor lemma tsum_comm [t0_space α] {f : β → γ → α} (h : summable (function.uncurry f)) : ∑' c b, f b c = ∑' b c, f b c := tsum_comm' h h.prod_factor h.prod_symm.prod_factor end loc_instances lemma tsum_subtype_add_tsum_subtype_compl [t2_space α] {f : β → α} (hf : summable f) (s : set β) : ∑' x : s, f x + ∑' x : sᶜ, f x = ∑' x, f x := ((hf.subtype s).has_sum.add_compl (hf.subtype {x | x ∉ s}).has_sum).unique hf.has_sum lemma sum_add_tsum_subtype_compl [t2_space α] {f : β → α} (hf : summable f) (s : finset β) : ∑ x in s, f x + ∑' x : {x // x ∉ s}, f x = ∑' x, f x := begin rw ← tsum_subtype_add_tsum_subtype_compl hf s, simp only [finset.tsum_subtype', add_right_inj], refl, end end uniform_group section topological_group variables {G : Type*} [topological_space G] [add_comm_group G] [topological_add_group G] {f : α → G} lemma summable.vanishing (hf : summable f) ⦃e : set G⦄ (he : e ∈ 𝓝 (0 : G)) : ∃ s : finset α, ∀ t, disjoint t s → ∑ k in t, f k ∈ e := begin letI : uniform_space G := topological_add_group.to_uniform_space G, letI : uniform_add_group G := topological_add_comm_group_is_uniform, rcases hf with ⟨y, hy⟩, exact cauchy_seq_finset_iff_vanishing.1 hy.cauchy_seq e he end /-- Series divergence test: if `f` is a convergent series, then `f x` tends to zero along `cofinite`. -/ lemma summable.tendsto_cofinite_zero (hf : summable f) : tendsto f cofinite (𝓝 0) := begin intros e he, rw [filter.mem_map], rcases hf.vanishing he with ⟨s, hs⟩, refine s.eventually_cofinite_nmem.mono (λ x hx, _), by simpa using hs {x} (disjoint_singleton_left.2 hx) end lemma summable.tendsto_at_top_zero {f : ℕ → G} (hf : summable f) : tendsto f at_top (𝓝 0) := by { rw ←nat.cofinite_eq_at_top, exact hf.tendsto_cofinite_zero } end topological_group section const_smul variables [monoid γ] [topological_space α] [add_comm_monoid α] [distrib_mul_action γ α] [has_continuous_const_smul γ α] {f : β → α} lemma has_sum.const_smul {a : α} (b : γ) (hf : has_sum f a) : has_sum (λ i, b • f i) (b • a) := hf.map (distrib_mul_action.to_add_monoid_hom α _) $ continuous_const_smul _ lemma summable.const_smul (b : γ) (hf : summable f) : summable (λ i, b • f i) := (hf.has_sum.const_smul _).summable lemma tsum_const_smul [t2_space α] (b : γ) (hf : summable f) : ∑' i, b • f i = b • ∑' i, f i := (hf.has_sum.const_smul _).tsum_eq end const_smul /-! ### Product and pi types -/ section prod variables [add_comm_monoid α] [topological_space α] [add_comm_monoid γ] [topological_space γ] lemma has_sum.prod_mk {f : β → α} {g : β → γ} {a : α} {b : γ} (hf : has_sum f a) (hg : has_sum g b) : has_sum (λ x, (⟨f x, g x⟩ : α × γ)) ⟨a, b⟩ := by simp [has_sum, ← prod_mk_sum, filter.tendsto.prod_mk_nhds hf hg] end prod section pi variables {ι : Type*} {π : α → Type*} [∀ x, add_comm_monoid (π x)] [∀ x, topological_space (π x)] lemma pi.has_sum {f : ι → ∀ x, π x} {g : ∀ x, π x} : has_sum f g ↔ ∀ x, has_sum (λ i, f i x) (g x) := by simp only [has_sum, tendsto_pi_nhds, sum_apply] lemma pi.summable {f : ι → ∀ x, π x} : summable f ↔ ∀ x, summable (λ i, f i x) := by simp only [summable, pi.has_sum, skolem] lemma tsum_apply [∀ x, t2_space (π x)] {f : ι → ∀ x, π x}{x : α} (hf : summable f) : (∑' i, f i) x = ∑' i, f i x := (pi.has_sum.mp hf.has_sum x).tsum_eq.symm end pi /-! ### Multiplicative opposite -/ section mul_opposite open mul_opposite variables [add_comm_monoid α] [topological_space α] {f : β → α} {a : α} lemma has_sum.op (hf : has_sum f a) : has_sum (λ a, op (f a)) (op a) := (hf.map (@op_add_equiv α _) continuous_op : _) lemma summable.op (hf : summable f) : summable (op ∘ f) := hf.has_sum.op.summable lemma has_sum.unop {f : β → αᵐᵒᵖ} {a : αᵐᵒᵖ} (hf : has_sum f a) : has_sum (λ a, unop (f a)) (unop a) := (hf.map (@op_add_equiv α _).symm continuous_unop : _) lemma summable.unop {f : β → αᵐᵒᵖ} (hf : summable f) : summable (unop ∘ f) := hf.has_sum.unop.summable @[simp] lemma has_sum_op : has_sum (λ a, op (f a)) (op a) ↔ has_sum f a := ⟨has_sum.unop, has_sum.op⟩ @[simp] lemma has_sum_unop {f : β → αᵐᵒᵖ} {a : αᵐᵒᵖ} : has_sum (λ a, unop (f a)) (unop a) ↔ has_sum f a := ⟨has_sum.op, has_sum.unop⟩ @[simp] lemma summable_op : summable (λ a, op (f a)) ↔ summable f := ⟨summable.unop, summable.op⟩ @[simp] lemma summable_unop {f : β → αᵐᵒᵖ} : summable (λ a, unop (f a)) ↔ summable f := ⟨summable.op, summable.unop⟩ variables [t2_space α] lemma tsum_op : ∑' x, mul_opposite.op (f x) = mul_opposite.op (∑' x, f x) := begin by_cases h : summable f, { exact h.has_sum.op.tsum_eq }, { have ho := summable_op.not.mpr h, rw [tsum_eq_zero_of_not_summable h, tsum_eq_zero_of_not_summable ho, mul_opposite.op_zero] } end lemma tsum_unop {f : β → αᵐᵒᵖ} : ∑' x, mul_opposite.unop (f x) = mul_opposite.unop (∑' x, f x) := mul_opposite.op_injective tsum_op.symm end mul_opposite /-! ### Interaction with the star -/ section has_continuous_star variables [add_comm_monoid α] [topological_space α] [star_add_monoid α] [has_continuous_star α] {f : β → α} {a : α} lemma has_sum.star (h : has_sum f a) : has_sum (λ b, star (f b)) (star a) := by simpa only using h.map (star_add_equiv : α ≃+ α) continuous_star lemma summable.star (hf : summable f) : summable (λ b, star (f b)) := hf.has_sum.star.summable lemma summable.of_star (hf : summable (λ b, star (f b))) : summable f := by simpa only [star_star] using hf.star @[simp] lemma summable_star_iff : summable (λ b, star (f b)) ↔ summable f := ⟨summable.of_star, summable.star⟩ @[simp] lemma summable_star_iff' : summable (star f) ↔ summable f := summable_star_iff variables [t2_space α] lemma tsum_star : star (∑' b, f b) = ∑' b, star (f b) := begin by_cases hf : summable f, { exact hf.has_sum.star.tsum_eq.symm, }, { rw [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable (mt summable.of_star hf), star_zero] }, end end has_continuous_star
f63678136a77ebbf63e1e9e0ee6a2a2762c9b295
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/matrix/finite_dimensional.lean
55796c37dfd9f0335a445a61123a9e374c8a7f02
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
1,414
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 -/ import data.matrix.basic import linear_algebra.finite_dimensional /-! # The finite-dimensional space of matrices This file shows that `m` by `n` matrices form a finite-dimensional space, and proves the `finrank` of that space is equal to `card m * card n`. ## Main definitions * `matrix.finite_dimensional`: matrices form a finite dimensional vector space over a field `K` * `matrix.finrank_matrix`: the `finrank` of `matrix m n R` is `card m * card n` ## Tags matrix, finite dimensional, findim, finrank -/ universes u v namespace matrix section finite_dimensional variables {m n : Type*} {R : Type v} [field R] instance [finite m] [finite n] : finite_dimensional R (matrix m n R) := linear_equiv.finite_dimensional (linear_equiv.curry R m n) /-- The dimension of the space of finite dimensional matrices is the product of the number of rows and columns. -/ @[simp] lemma finrank_matrix [fintype m] [fintype n] : finite_dimensional.finrank R (matrix m n R) = fintype.card m * fintype.card n := by rw [@linear_equiv.finrank_eq R (matrix m n R) _ _ _ _ _ _ (linear_equiv.curry R m n).symm, finite_dimensional.finrank_fintype_fun_eq_card, fintype.card_prod] end finite_dimensional end matrix
c1788672e78be120b462ff81e36c7579109e64ce
9dc8cecdf3c4634764a18254e94d43da07142918
/src/topology/continuous_function/basic.lean
09d7365e936a1dd1dd257f50d9909ce884955590
[ "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
11,946
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 α β section set_option old_structure_cmd true /-- `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) end 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)`. -/ @[simps] 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 /-- The restriction of a continuous map onto the preimage of a set. -/ @[simps] def restrict_preimage (f : C(α, β)) (s : set β) : C(f ⁻¹' s, s) := ⟨s.restrict_preimage f, continuous_iff_continuous_at.mpr $ λ x, f.2.continuous_at.restrict_preimage⟩ 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 namespace homeomorph variables {α β γ : Type*} [topological_space α] [topological_space β] [topological_space γ] variables (f : α ≃ₜ β) (g : β ≃ₜ γ) /-- The forward direction of a homeomorphism, as a bundled continuous map. -/ @[simps] def to_continuous_map (e : α ≃ₜ β) : C(α, β) := ⟨e⟩ /--`homeomorph.to_continuous_map` as a coercion. -/ instance : has_coe (α ≃ₜ β) C(α, β) := ⟨homeomorph.to_continuous_map⟩ lemma to_continuous_map_as_coe : f.to_continuous_map = f := rfl @[simp] lemma coe_refl : (homeomorph.refl α : C(α, α)) = continuous_map.id α := rfl @[simp] lemma coe_trans : (f.trans g : C(α, γ)) = (g : C(β, γ)).comp f := rfl /-- Left inverse to a continuous map from a homeomorphism, mirroring `equiv.symm_comp_self`. -/ @[simp] lemma symm_comp_to_continuous_map : (f.symm : C(β, α)).comp (f : C(α, β)) = continuous_map.id α := by rw [← coe_trans, self_trans_symm, coe_refl] /-- Right inverse to a continuous map from a homeomorphism, mirroring `equiv.self_comp_symm`. -/ @[simp] lemma to_continuous_map_comp_symm : (f : C(α, β)).comp (f.symm : C(β, α)) = continuous_map.id β := by rw [← coe_trans, symm_trans_self, coe_refl] end homeomorph