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
7850b484df3d3a4f68f284777b5ceca5d752bbf0
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/integral_closure.lean
fa887f467ad126d2eb130685fde56f2785344d81
[ "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
47,480
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 data.polynomial.expand import linear_algebra.finite_dimensional import linear_algebra.matrix.charpoly.linear_map import ring_theory.adjoin.fg import ring_theory.finite_type import ring_theory.polynomial.scale_roots import ring_theory.polynomial.tower import ring_theory.tensor_product /-! # Integral closure of a subring. > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. If A is an R-algebra then `a : A` is integral over R if it is a root of a monic polynomial with coefficients in R. Enough theory is developed to prove that integral elements form a sub-R-algebra of A. ## Main definitions Let `R` be a `comm_ring` and let `A` be an R-algebra. * `ring_hom.is_integral_elem (f : R →+* A) (x : A)` : `x` is integral with respect to the map `f`, * `is_integral (x : A)` : `x` is integral over `R`, i.e., is a root of a monic polynomial with coefficients in `R`. * `integral_closure R A` : the integral closure of `R` in `A`, regarded as a sub-`R`-algebra of `A`. -/ open_locale classical open_locale big_operators polynomial open polynomial submodule section ring variables {R S A : Type*} variables [comm_ring R] [ring A] [ring S] (f : R →+* S) /-- An element `x` of `A` is said to be integral over `R` with respect to `f` if it is a root of a monic polynomial `p : R[X]` evaluated under `f` -/ def ring_hom.is_integral_elem (f : R →+* A) (x : A) := ∃ p : R[X], monic p ∧ eval₂ f x p = 0 /-- A ring homomorphism `f : R →+* A` is said to be integral if every element `A` is integral with respect to the map `f` -/ def ring_hom.is_integral (f : R →+* A) := ∀ x : A, f.is_integral_elem x variables [algebra R A] (R) /-- An element `x` of an algebra `A` over a commutative ring `R` is said to be *integral*, if it is a root of some monic polynomial `p : R[X]`. Equivalently, the element is integral over `R` with respect to the induced `algebra_map` -/ def is_integral (x : A) : Prop := (algebra_map R A).is_integral_elem x variable (A) /-- An algebra is integral if every element of the extension is integral over the base ring -/ protected def algebra.is_integral : Prop := (algebra_map R A).is_integral variables {R A} lemma ring_hom.is_integral_map {x : R} : f.is_integral_elem (f x) := ⟨X - C x, monic_X_sub_C _, by simp⟩ theorem is_integral_algebra_map {x : R} : is_integral R (algebra_map R A x) := (algebra_map R A).is_integral_map theorem is_integral_of_noetherian (H : is_noetherian R A) (x : A) : is_integral R x := begin let leval : (R[X] →ₗ[R] A) := (aeval x).to_linear_map, let D : ℕ → submodule R A := λ n, (degree_le R n).map leval, let M := well_founded.min (is_noetherian_iff_well_founded.1 H) (set.range D) ⟨_, ⟨0, rfl⟩⟩, have HM : M ∈ set.range D := well_founded.min_mem _ _ _, cases HM with N HN, have HM : ¬M < D (N+1) := well_founded.not_lt_min (is_noetherian_iff_well_founded.1 H) (set.range D) _ ⟨N+1, rfl⟩, rw ← HN at HM, have HN2 : D (N+1) ≤ D N := classical.by_contradiction (λ H, HM (lt_of_le_not_le (map_mono (degree_le_mono (with_bot.coe_le_coe.2 (nat.le_succ N)))) H)), have HN3 : leval (X^(N+1)) ∈ D N, { exact HN2 (mem_map_of_mem (mem_degree_le.2 (degree_X_pow_le _))) }, rcases HN3 with ⟨p, hdp, hpe⟩, refine ⟨X^(N+1) - p, monic_X_pow_sub (mem_degree_le.1 hdp), _⟩, show leval (X ^ (N + 1) - p) = 0, rw [linear_map.map_sub, hpe, sub_self] end theorem is_integral_of_submodule_noetherian (S : subalgebra R A) (H : is_noetherian R S.to_submodule) (x : A) (hx : x ∈ S) : is_integral R x := begin suffices : is_integral R (show S, from ⟨x, hx⟩), { rcases this with ⟨p, hpm, hpx⟩, replace hpx := congr_arg S.val hpx, refine ⟨p, hpm, eq.trans _ hpx⟩, simp only [aeval_def, eval₂, sum_def], rw S.val.map_sum, refine finset.sum_congr rfl (λ n hn, _), rw [S.val.map_mul, S.val.map_pow, S.val.commutes, S.val_apply, subtype.coe_mk], }, refine is_integral_of_noetherian H ⟨x, hx⟩ end end ring section variables {R A B S : Type*} variables [comm_ring R] [comm_ring A] [comm_ring B] [comm_ring S] variables [algebra R A] [algebra R B] (f : R →+* S) lemma map_is_integral {B C F : Type*} [ring B] [ring C] [algebra R B] [algebra A B] [algebra R C] [is_scalar_tower R A B] [algebra A C] [is_scalar_tower R A C] {b : B} [alg_hom_class F A B C] (f : F) (hb : is_integral R b) : is_integral R (f b) := begin obtain ⟨P, hP⟩ := hb, refine ⟨P, hP.1, _⟩, rw [← aeval_def, show (aeval (f b)) P = (aeval (f b)) (P.map (algebra_map R A)), by simp, aeval_alg_hom_apply, aeval_map_algebra_map, aeval_def, hP.2, _root_.map_zero] end lemma is_integral_map_of_comp_eq_of_is_integral {R S T U : Type*} [comm_ring R] [comm_ring S] [comm_ring T] [comm_ring U] [algebra R S] [algebra T U] (φ : R →+* T) (ψ : S →+* U) (h : (algebra_map T U).comp φ = ψ.comp (algebra_map R S)) {a : S} (ha : is_integral R a) : is_integral T (ψ a) := begin rw [is_integral, ring_hom.is_integral_elem] at ⊢ ha, obtain ⟨p, hp⟩ := ha, refine ⟨p.map φ, hp.left.map _, _⟩, rw [← eval_map, map_map, h, ← map_map, eval_map, eval₂_at_apply, eval_map, hp.right, ring_hom.map_zero], end theorem is_integral_alg_hom_iff {A B : Type*} [ring A] [ring B] [algebra R A] [algebra R B] (f : A →ₐ[R] B) (hf : function.injective f) {x : A} : is_integral R (f x) ↔ is_integral R x := begin refine ⟨_, map_is_integral f⟩, rintros ⟨p, hp, hx⟩, use [p, hp], rwa [← f.comp_algebra_map, ← alg_hom.coe_to_ring_hom, ← polynomial.hom_eval₂, alg_hom.coe_to_ring_hom, map_eq_zero_iff f hf] at hx end @[simp] theorem is_integral_alg_equiv {A B : Type*} [ring A] [ring B] [algebra R A] [algebra R B] (f : A ≃ₐ[R] B) {x : A} : is_integral R (f x) ↔ is_integral R x := ⟨λ h, by simpa using map_is_integral f.symm.to_alg_hom h, map_is_integral f.to_alg_hom⟩ theorem is_integral_of_is_scalar_tower [algebra A B] [is_scalar_tower R A B] {x : B} (hx : is_integral R x) : is_integral A x := let ⟨p, hp, hpx⟩ := hx in ⟨p.map $ algebra_map R A, hp.map _, by rw [← aeval_def, aeval_map_algebra_map, aeval_def, hpx]⟩ lemma map_is_integral_int {B C F : Type*} [ring B] [ring C] {b : B} [ring_hom_class F B C] (f : F) (hb : is_integral ℤ b) : is_integral ℤ (f b) := map_is_integral (f : B →+* C).to_int_alg_hom hb theorem is_integral_of_subring {x : A} (T : subring R) (hx : is_integral T x) : is_integral R x := is_integral_of_is_scalar_tower hx lemma is_integral.algebra_map [algebra A B] [is_scalar_tower R A B] {x : A} (h : is_integral R x) : is_integral R (algebra_map A B x) := begin rcases h with ⟨f, hf, hx⟩, use [f, hf], rw [is_scalar_tower.algebra_map_eq R A B, ← hom_eval₂, hx, ring_hom.map_zero] end lemma is_integral_algebra_map_iff [algebra A B] [is_scalar_tower R A B] {x : A} (hAB : function.injective (algebra_map A B)) : is_integral R (algebra_map A B x) ↔ is_integral R x := is_integral_alg_hom_iff (is_scalar_tower.to_alg_hom R A B) hAB theorem is_integral_iff_is_integral_closure_finite {r : A} : is_integral R r ↔ ∃ s : set R, s.finite ∧ is_integral (subring.closure s) r := begin split; intro hr, { rcases hr with ⟨p, hmp, hpr⟩, refine ⟨_, finset.finite_to_set _, p.restriction, monic_restriction.2 hmp, _⟩, rw [← aeval_def, ← aeval_map_algebra_map R r p.restriction, map_restriction, aeval_def, hpr], }, rcases hr with ⟨s, hs, hsr⟩, exact is_integral_of_subring _ hsr end theorem fg_adjoin_singleton_of_integral (x : A) (hx : is_integral R x) : (algebra.adjoin R ({x} : set A)).to_submodule.fg := begin rcases hx with ⟨f, hfm, hfx⟩, existsi finset.image ((^) x) (finset.range (nat_degree f + 1)), apply le_antisymm, { rw span_le, intros s hs, rw finset.mem_coe at hs, rcases finset.mem_image.1 hs with ⟨k, hk, rfl⟩, clear hk, exact (algebra.adjoin R {x}).pow_mem (algebra.subset_adjoin (set.mem_singleton _)) k }, intros r hr, change r ∈ algebra.adjoin R ({x} : set A) at hr, rw algebra.adjoin_singleton_eq_range_aeval at hr, rcases (aeval x).mem_range.mp hr with ⟨p, rfl⟩, rw ← mod_by_monic_add_div p hfm, rw ← aeval_def at hfx, rw [alg_hom.map_add, alg_hom.map_mul, hfx, zero_mul, add_zero], have : degree (p %ₘ f) ≤ degree f := degree_mod_by_monic_le p hfm, generalize_hyp : p %ₘ f = q at this ⊢, rw [← sum_C_mul_X_pow_eq q, aeval_def, eval₂_sum, sum_def], refine sum_mem (λ k hkq, _), rw [eval₂_mul, eval₂_C, eval₂_pow, eval₂_X, ← algebra.smul_def], refine smul_mem _ _ (subset_span _), rw finset.mem_coe, refine finset.mem_image.2 ⟨_, _, rfl⟩, rw [finset.mem_range, nat.lt_succ_iff], refine le_of_not_lt (λ hk, _), rw [degree_le_iff_coeff_zero] at this, rw [mem_support_iff] at hkq, apply hkq, apply this, exact lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 hk) end theorem fg_adjoin_of_finite {s : set A} (hfs : s.finite) (his : ∀ x ∈ s, is_integral R x) : (algebra.adjoin R s).to_submodule.fg := set.finite.induction_on hfs (λ _, ⟨{1}, submodule.ext $ λ x, by { erw [algebra.adjoin_empty, finset.coe_singleton, ← one_eq_span, one_eq_range, linear_map.mem_range, algebra.mem_bot], refl }⟩) (λ a s has hs ih his, by rw [← set.union_singleton, algebra.adjoin_union_coe_submodule]; exact fg.mul (ih $ λ i hi, his i $ set.mem_insert_of_mem a hi) (fg_adjoin_singleton_of_integral _ $ his a $ set.mem_insert a s)) his lemma is_noetherian_adjoin_finset [is_noetherian_ring R] (s : finset A) (hs : ∀ x ∈ s, is_integral R x) : is_noetherian R (algebra.adjoin R (↑s : set A)) := is_noetherian_of_fg_of_noetherian _ (fg_adjoin_of_finite s.finite_to_set hs) /-- If `S` is a sub-`R`-algebra of `A` and `S` is finitely-generated as an `R`-module, then all elements of `S` are integral over `R`. -/ theorem is_integral_of_mem_of_fg (S : subalgebra R A) (HS : S.to_submodule.fg) (x : A) (hx : x ∈ S) : is_integral R x := begin -- say `x ∈ S`. We want to prove that `x` is integral over `R`. -- Say `S` is generated as an `R`-module by the set `y`. cases HS with y hy, -- We can write `x` as `∑ rᵢ yᵢ` for `yᵢ ∈ Y`. obtain ⟨lx, hlx1, hlx2⟩ : ∃ (l : A →₀ R) (H : l ∈ finsupp.supported R R ↑y), (finsupp.total A A R id) l = x, { rwa [←(@finsupp.mem_span_image_iff_total A A R _ _ _ id ↑y x), set.image_id ↑y, hy] }, -- Note that `y ⊆ S`. have hyS : ∀ {p}, p ∈ y → p ∈ S := λ p hp, show p ∈ S.to_submodule, by { rw ← hy, exact subset_span hp }, -- Now `S` is a subalgebra so the product of two elements of `y` is also in `S`. have : ∀ (jk : (↑(y ×ˢ y) : set (A × A))), jk.1.1 * jk.1.2 ∈ S.to_submodule := λ jk, S.mul_mem (hyS (finset.mem_product.1 jk.2).1) (hyS (finset.mem_product.1 jk.2).2), rw [← hy, ← set.image_id ↑y] at this, simp only [finsupp.mem_span_image_iff_total] at this, -- Say `yᵢyⱼ = ∑rᵢⱼₖ yₖ` choose ly hly1 hly2, -- Now let `S₀` be the subring of `R` generated by the `rᵢ` and the `rᵢⱼₖ`. let S₀ : subring R := subring.closure ↑(lx.frange ∪ finset.bUnion finset.univ (finsupp.frange ∘ ly)), -- It suffices to prove that `x` is integral over `S₀`. refine is_integral_of_subring S₀ _, letI : comm_ring S₀ := subring_class.to_comm_ring S₀, letI : algebra S₀ A := algebra.of_subring S₀, -- Claim: the `S₀`-module span (in `A`) of the set `y ∪ {1}` is closed under -- multiplication (indeed, this is the motivation for the definition of `S₀`). have : span S₀ (insert 1 ↑y : set A) * span S₀ (insert 1 ↑y : set A) ≤ span S₀ (insert 1 ↑y : set A), { rw span_mul_span, refine span_le.2 (λ z hz, _), rcases set.mem_mul.1 hz with ⟨p, q, rfl | hp, hq, rfl⟩, { rw one_mul, exact subset_span hq }, rcases hq with rfl | hq, { rw mul_one, exact subset_span (or.inr hp) }, erw ← hly2 ⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩, rw [finsupp.total_apply, finsupp.sum], refine (span S₀ (insert 1 ↑y : set A)).sum_mem (λ t ht, _), have : ly ⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩ t ∈ S₀ := subring.subset_closure (finset.mem_union_right _ $ finset.mem_bUnion.2 ⟨⟨(p, q), finset.mem_product.2 ⟨hp, hq⟩⟩, finset.mem_univ _, finsupp.mem_frange.2 ⟨finsupp.mem_support_iff.1 ht, _, rfl⟩⟩), change (⟨_, this⟩ : S₀) • t ∈ _, exact smul_mem _ _ (subset_span $ or.inr $ hly1 _ ht) }, -- Hence this span is a subring. Call this subring `S₁`. let S₁ : subring A := { carrier := span S₀ (insert 1 ↑y : set A), one_mem' := subset_span $ or.inl rfl, mul_mem' := λ p q hp hq, this $ mul_mem_mul hp hq, zero_mem' := (span S₀ (insert 1 ↑y : set A)).zero_mem, add_mem' := λ _ _, (span S₀ (insert 1 ↑y : set A)).add_mem, neg_mem' := λ _, (span S₀ (insert 1 ↑y : set A)).neg_mem }, have : S₁ = subalgebra.to_subring (algebra.adjoin S₀ (↑y : set A)), { ext z, suffices : z ∈ span ↥S₀ (insert 1 ↑y : set A) ↔ z ∈ (algebra.adjoin ↥S₀ (y : set A)).to_submodule, { simpa }, split; intro hz, { exact (span_le.2 (set.insert_subset.2 ⟨(algebra.adjoin S₀ ↑y).one_mem, algebra.subset_adjoin⟩)) hz }, { rw [subalgebra.mem_to_submodule, algebra.mem_adjoin_iff] at hz, suffices : subring.closure (set.range ⇑(algebra_map ↥S₀ A) ∪ ↑y) ≤ S₁, { exact this hz }, refine subring.closure_le.2 (set.union_subset _ (λ t ht, subset_span $ or.inr ht)), rw set.range_subset_iff, intro y, rw algebra.algebra_map_eq_smul_one, exact smul_mem _ y (subset_span (or.inl rfl)) } }, have foo : ∀ z, z ∈ S₁ ↔ z ∈ algebra.adjoin ↥S₀ (y : set A), simp [this], haveI : is_noetherian_ring ↥S₀ := is_noetherian_subring_closure _ (finset.finite_to_set _), refine is_integral_of_submodule_noetherian (algebra.adjoin S₀ ↑y) (is_noetherian_of_fg_of_noetherian _ ⟨insert 1 y, by { rw [finset.coe_insert], ext z, simp [S₁], convert foo z}⟩) _ _, rw [← hlx2, finsupp.total_apply, finsupp.sum], refine subalgebra.sum_mem _ (λ r hr, _), have : lx r ∈ S₀ := subring.subset_closure (finset.mem_union_left _ (finset.mem_image_of_mem _ hr)), change (⟨_, this⟩ : S₀) • r ∈ _, rw finsupp.mem_supported at hlx1, exact subalgebra.smul_mem _ (algebra.subset_adjoin $ hlx1 hr) _ end lemma module.End.is_integral {M : Type*} [add_comm_group M] [module R M] [module.finite R M] : algebra.is_integral R (module.End R M) := linear_map.exists_monic_and_aeval_eq_zero R /-- Suppose `A` is an `R`-algebra, `M` is an `A`-module such that `a • m ≠ 0` for all non-zero `a` and `m`. If `x : A` fixes a nontrivial f.g. `R`-submodule `N` of `M`, then `x` is `R`-integral. -/ lemma is_integral_of_smul_mem_submodule {M : Type*} [add_comm_group M] [module R M] [module A M] [is_scalar_tower R A M] [no_zero_smul_divisors A M] (N : submodule R M) (hN : N ≠ ⊥) (hN' : N.fg) (x : A) (hx : ∀ n ∈ N, x • n ∈ N) : is_integral R x := begin let A' : subalgebra R A := { carrier := { x | ∀ n ∈ N, x • n ∈ N }, mul_mem' := λ a b ha hb n hn, smul_smul a b n ▸ ha _ (hb _ hn), one_mem' := λ n hn, (one_smul A n).symm ▸ hn, add_mem' := λ a b ha hb n hn, (add_smul a b n).symm ▸ N.add_mem (ha _ hn) (hb _ hn), zero_mem' := λ n hn, (zero_smul A n).symm ▸ N.zero_mem, algebra_map_mem' := λ r n hn, (algebra_map_smul A r n).symm ▸ N.smul_mem r hn }, let f : A' →ₐ[R] module.End R N := alg_hom.of_linear_map { to_fun := λ x, (distrib_mul_action.to_linear_map R M x).restrict x.prop, map_add' := λ x y, linear_map.ext $ λ n, subtype.ext $ add_smul x y n, map_smul' := λ r s, linear_map.ext $ λ n, subtype.ext $ smul_assoc r s n } (linear_map.ext $ λ n, subtype.ext $ one_smul _ _) (λ x y, linear_map.ext $ λ n, subtype.ext $ mul_smul x y n), obtain ⟨a, ha₁, ha₂⟩ : ∃ a ∈ N, a ≠ (0 : M), { by_contra h', push_neg at h', apply hN, rwa eq_bot_iff }, have : function.injective f, { show function.injective f.to_linear_map, rw [← linear_map.ker_eq_bot, eq_bot_iff], intros s hs, have : s.1 • a = 0 := congr_arg subtype.val (linear_map.congr_fun hs ⟨a, ha₁⟩), exact subtype.ext ((eq_zero_or_eq_zero_of_smul_eq_zero this).resolve_right ha₂) }, show is_integral R (A'.val ⟨x, hx⟩), rw [is_integral_alg_hom_iff A'.val subtype.val_injective, ← is_integral_alg_hom_iff f this], haveI : module.finite R N := by rwa [module.finite_def, submodule.fg_top], apply module.End.is_integral, end variables {f} lemma ring_hom.finite.to_is_integral (h : f.finite) : f.is_integral := by { letI := f.to_algebra, exact λ x, is_integral_of_mem_of_fg ⊤ h.1 _ trivial } alias ring_hom.finite.to_is_integral ← ring_hom.is_integral.of_finite lemma ring_hom.is_integral.to_finite (h : f.is_integral) (h' : f.finite_type) : f.finite := begin letI := f.to_algebra, unfreezingI { obtain ⟨s, hs⟩ := h' }, constructor, change (⊤ : subalgebra R S).to_submodule.fg, rw ← hs, exact fg_adjoin_of_finite (set.to_finite _) (λ x _, h x) end alias ring_hom.is_integral.to_finite ← ring_hom.finite.of_is_integral_of_finite_type /-- finite = integral + finite type -/ lemma ring_hom.finite_iff_is_integral_and_finite_type : f.finite ↔ f.is_integral ∧ f.finite_type := ⟨λ h, ⟨h.to_is_integral, h.to_finite_type⟩, λ ⟨h, h'⟩, h.to_finite h'⟩ lemma algebra.is_integral.finite (h : algebra.is_integral R A) [h' : algebra.finite_type R A] : module.finite R A := begin have := h.to_finite (by { delta ring_hom.finite_type, convert h', ext, exact (algebra.smul_def _ _).symm }), delta ring_hom.finite at this, convert this, ext, exact algebra.smul_def _ _, end lemma algebra.is_integral.of_finite [h : module.finite R A] : algebra.is_integral R A := begin apply ring_hom.finite.to_is_integral, delta ring_hom.finite, convert h, ext, exact (algebra.smul_def _ _).symm, end /-- finite = integral + finite type -/ lemma algebra.finite_iff_is_integral_and_finite_type : module.finite R A ↔ algebra.is_integral R A ∧ algebra.finite_type R A := ⟨λ h, by exactI ⟨algebra.is_integral.of_finite, infer_instance⟩, λ ⟨h, h'⟩, by exactI h.finite⟩ variables (f) lemma ring_hom.is_integral_of_mem_closure {x y z : S} (hx : f.is_integral_elem x) (hy : f.is_integral_elem y) (hz : z ∈ subring.closure ({x, y} : set S)) : f.is_integral_elem z := begin letI : algebra R S := f.to_algebra, have := (fg_adjoin_singleton_of_integral x hx).mul (fg_adjoin_singleton_of_integral y hy), rw [← algebra.adjoin_union_coe_submodule, set.singleton_union] at this, exact is_integral_of_mem_of_fg (algebra.adjoin R {x, y}) this z (algebra.mem_adjoin_iff.2 $ subring.closure_mono (set.subset_union_right _ _) hz), end theorem is_integral_of_mem_closure {x y z : A} (hx : is_integral R x) (hy : is_integral R y) (hz : z ∈ subring.closure ({x, y} : set A)) : is_integral R z := (algebra_map R A).is_integral_of_mem_closure hx hy hz lemma ring_hom.is_integral_zero : f.is_integral_elem 0 := f.map_zero ▸ f.is_integral_map theorem is_integral_zero : is_integral R (0:A) := (algebra_map R A).is_integral_zero lemma ring_hom.is_integral_one : f.is_integral_elem 1 := f.map_one ▸ f.is_integral_map theorem is_integral_one : is_integral R (1:A) := (algebra_map R A).is_integral_one lemma ring_hom.is_integral_add {x y : S} (hx : f.is_integral_elem x) (hy : f.is_integral_elem y) : f.is_integral_elem (x + y) := f.is_integral_of_mem_closure hx hy $ subring.add_mem _ (subring.subset_closure (or.inl rfl)) (subring.subset_closure (or.inr rfl)) theorem is_integral_add {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x + y) := (algebra_map R A).is_integral_add hx hy lemma ring_hom.is_integral_neg {x : S} (hx : f.is_integral_elem x) : f.is_integral_elem (-x) := f.is_integral_of_mem_closure hx hx (subring.neg_mem _ (subring.subset_closure (or.inl rfl))) theorem is_integral_neg {x : A} (hx : is_integral R x) : is_integral R (-x) := (algebra_map R A).is_integral_neg hx lemma ring_hom.is_integral_sub {x y : S} (hx : f.is_integral_elem x) (hy : f.is_integral_elem y) : f.is_integral_elem (x - y) := by simpa only [sub_eq_add_neg] using f.is_integral_add hx (f.is_integral_neg hy) theorem is_integral_sub {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x - y) := (algebra_map R A).is_integral_sub hx hy lemma ring_hom.is_integral_mul {x y : S} (hx : f.is_integral_elem x) (hy : f.is_integral_elem y) : f.is_integral_elem (x * y) := f.is_integral_of_mem_closure hx hy (subring.mul_mem _ (subring.subset_closure (or.inl rfl)) (subring.subset_closure (or.inr rfl))) theorem is_integral_mul {x y : A} (hx : is_integral R x) (hy : is_integral R y) : is_integral R (x * y) := (algebra_map R A).is_integral_mul hx hy lemma is_integral_smul [algebra S A] [algebra R S] [is_scalar_tower R S A] {x : A} (r : R) (hx : is_integral S x) : is_integral S (r • x) := begin rw [algebra.smul_def, is_scalar_tower.algebra_map_apply R S A], exact is_integral_mul is_integral_algebra_map hx, end lemma is_integral_of_pow {x : A} {n : ℕ} (hn : 0 < n) (hx : is_integral R $ x ^ n) : is_integral R x := begin rcases hx with ⟨p, ⟨hmonic, heval⟩⟩, exact ⟨expand R n p, monic.expand hn hmonic, by rwa [eval₂_eq_eval_map, map_expand, expand_eval, ← eval₂_eq_eval_map]⟩ end variables (R A) /-- The integral closure of R in an R-algebra A. -/ def integral_closure : subalgebra R A := { carrier := { r | is_integral R r }, zero_mem' := is_integral_zero, one_mem' := is_integral_one, add_mem' := λ _ _, is_integral_add, mul_mem' := λ _ _, is_integral_mul, algebra_map_mem' := λ x, is_integral_algebra_map } theorem mem_integral_closure_iff_mem_fg {r : A} : r ∈ integral_closure R A ↔ ∃ M : subalgebra R A, M.to_submodule.fg ∧ r ∈ M := ⟨λ hr, ⟨algebra.adjoin R {r}, fg_adjoin_singleton_of_integral _ hr, algebra.subset_adjoin rfl⟩, λ ⟨M, Hf, hrM⟩, is_integral_of_mem_of_fg M Hf _ hrM⟩ variables {R} {A} lemma adjoin_le_integral_closure {x : A} (hx : is_integral R x) : algebra.adjoin R {x} ≤ integral_closure R A := begin rw [algebra.adjoin_le_iff], simp only [set_like.mem_coe, set.singleton_subset_iff], exact hx end lemma le_integral_closure_iff_is_integral {S : subalgebra R A} : S ≤ integral_closure R A ↔ algebra.is_integral R S := set_like.forall.symm.trans (forall_congr (λ x, show is_integral R (algebra_map S A x) ↔ is_integral R x, from is_integral_algebra_map_iff subtype.coe_injective)) lemma is_integral_sup {S T : subalgebra R A} : algebra.is_integral R ↥(S ⊔ T) ↔ algebra.is_integral R S ∧ algebra.is_integral R T := by simp only [←le_integral_closure_iff_is_integral, sup_le_iff] /-- Mapping an integral closure along an `alg_equiv` gives the integral closure. -/ lemma integral_closure_map_alg_equiv (f : A ≃ₐ[R] B) : (integral_closure R A).map (f : A →ₐ[R] B) = integral_closure R B := begin ext y, rw subalgebra.mem_map, split, { rintros ⟨x, hx, rfl⟩, exact map_is_integral f hx }, { intro hy, use [f.symm y, map_is_integral (f.symm : B →ₐ[R] A) hy], simp } end lemma integral_closure.is_integral (x : integral_closure R A) : is_integral R x := let ⟨p, hpm, hpx⟩ := x.2 in ⟨p, hpm, subtype.eq $ by rwa [← aeval_def, subtype.val_eq_coe, ← subalgebra.val_apply, aeval_alg_hom_apply] at hpx⟩ lemma ring_hom.is_integral_of_is_integral_mul_unit (x y : S) (r : R) (hr : f r * y = 1) (hx : f.is_integral_elem (x * y)) : f.is_integral_elem x := begin obtain ⟨p, ⟨p_monic, hp⟩⟩ := hx, refine ⟨scale_roots p r, ⟨(monic_scale_roots_iff r).2 p_monic, _⟩⟩, convert scale_roots_eval₂_eq_zero f hp, rw [mul_comm x y, ← mul_assoc, hr, one_mul], end theorem is_integral_of_is_integral_mul_unit {x y : A} {r : R} (hr : algebra_map R A r * y = 1) (hx : is_integral R (x * y)) : is_integral R x := (algebra_map R A).is_integral_of_is_integral_mul_unit x y r hr hx /-- Generalization of `is_integral_of_mem_closure` bootstrapped up from that lemma -/ lemma is_integral_of_mem_closure' (G : set A) (hG : ∀ x ∈ G, is_integral R x) : ∀ x ∈ (subring.closure G), is_integral R x := λ x hx, subring.closure_induction hx hG is_integral_zero is_integral_one (λ _ _, is_integral_add) (λ _, is_integral_neg) (λ _ _, is_integral_mul) lemma is_integral_of_mem_closure'' {S : Type*} [comm_ring S] {f : R →+* S} (G : set S) (hG : ∀ x ∈ G, f.is_integral_elem x) : ∀ x ∈ (subring.closure G), f.is_integral_elem x := λ x hx, @is_integral_of_mem_closure' R S _ _ f.to_algebra G hG x hx lemma is_integral.pow {x : A} (h : is_integral R x) (n : ℕ) : is_integral R (x ^ n) := (integral_closure R A).pow_mem h n lemma is_integral.nsmul {x : A} (h : is_integral R x) (n : ℕ) : is_integral R (n • x) := (integral_closure R A).nsmul_mem h n lemma is_integral.zsmul {x : A} (h : is_integral R x) (n : ℤ) : is_integral R (n • x) := (integral_closure R A).zsmul_mem h n lemma is_integral.multiset_prod {s : multiset A} (h : ∀ x ∈ s, is_integral R x) : is_integral R s.prod := (integral_closure R A).multiset_prod_mem h lemma is_integral.multiset_sum {s : multiset A} (h : ∀ x ∈ s, is_integral R x) : is_integral R s.sum := (integral_closure R A).multiset_sum_mem h lemma is_integral.prod {α : Type*} {s : finset α} (f : α → A) (h : ∀ x ∈ s, is_integral R (f x)) : is_integral R (∏ x in s, f x) := (integral_closure R A).prod_mem h lemma is_integral.sum {α : Type*} {s : finset α} (f : α → A) (h : ∀ x ∈ s, is_integral R (f x)) : is_integral R (∑ x in s, f x) := (integral_closure R A).sum_mem h lemma is_integral.det {n : Type*} [fintype n] [decidable_eq n] {M : matrix n n A} (h : ∀ i j, is_integral R (M i j)) : is_integral R M.det := begin rw [matrix.det_apply], exact is_integral.sum _ (λ σ hσ, is_integral.zsmul (is_integral.prod _ (λ i hi, h _ _)) _) end @[simp] lemma is_integral.pow_iff {x : A} {n : ℕ} (hn : 0 < n) : is_integral R (x ^ n) ↔ is_integral R x := ⟨is_integral_of_pow hn, λ hx, is_integral.pow hx n⟩ open_locale tensor_product lemma is_integral.tmul (x : A) {y : B} (h : is_integral R y) : is_integral A (x ⊗ₜ[R] y) := begin obtain ⟨p, hp, hp'⟩ := h, refine ⟨(p.map (algebra_map R A)).scale_roots x, _, _⟩, { rw polynomial.monic_scale_roots_iff, exact hp.map _ }, convert @polynomial.scale_roots_eval₂_mul (A ⊗[R] B) A _ _ _ algebra.tensor_product.include_left.to_ring_hom (1 ⊗ₜ y) x using 2, { simp only [alg_hom.to_ring_hom_eq_coe, alg_hom.coe_to_ring_hom, mul_one, one_mul, algebra.tensor_product.include_left_apply, algebra.tensor_product.tmul_mul_tmul] }, convert (mul_zero _).symm, rw [polynomial.eval₂_map, algebra.tensor_product.include_left_comp_algebra_map, ← polynomial.eval₂_map], convert polynomial.eval₂_at_apply algebra.tensor_product.include_right.to_ring_hom y, rw [polynomial.eval_map, hp', _root_.map_zero], end section variables (p : R[X]) (x : S) /-- The monic polynomial whose roots are `p.leading_coeff * x` for roots `x` of `p`. -/ noncomputable def normalize_scale_roots (p : R[X]) : R[X] := ∑ i in p.support, monomial i (if i = p.nat_degree then 1 else p.coeff i * p.leading_coeff ^ (p.nat_degree - 1 - i)) lemma normalize_scale_roots_coeff_mul_leading_coeff_pow (i : ℕ) (hp : 1 ≤ nat_degree p) : (normalize_scale_roots p).coeff i * p.leading_coeff ^ i = p.coeff i * p.leading_coeff ^ (p.nat_degree - 1) := begin simp only [normalize_scale_roots, finset_sum_coeff, coeff_monomial, finset.sum_ite_eq', one_mul, zero_mul, mem_support_iff, ite_mul, ne.def, ite_not], split_ifs with h₁ h₂, { simp [h₁], }, { rw [h₂, leading_coeff, ← pow_succ, tsub_add_cancel_of_le hp], }, { rw [mul_assoc, ← pow_add, tsub_add_cancel_of_le], apply nat.le_pred_of_lt, rw lt_iff_le_and_ne, exact ⟨le_nat_degree_of_ne_zero h₁, h₂⟩, }, end lemma leading_coeff_smul_normalize_scale_roots (p : R[X]) : p.leading_coeff • normalize_scale_roots p = scale_roots p p.leading_coeff := begin ext, simp only [coeff_scale_roots, normalize_scale_roots, coeff_monomial, coeff_smul, finset.smul_sum, ne.def, finset.sum_ite_eq', finset_sum_coeff, smul_ite, smul_zero, mem_support_iff], split_ifs with h₁ h₂, { simp [*] }, { simp [*] }, { rw [algebra.id.smul_eq_mul, mul_comm, mul_assoc, ← pow_succ', tsub_right_comm, tsub_add_cancel_of_le], rw nat.succ_le_iff, exact tsub_pos_of_lt (lt_of_le_of_ne (le_nat_degree_of_ne_zero h₁) h₂) }, end lemma normalize_scale_roots_support : (normalize_scale_roots p).support ≤ p.support := begin intro x, contrapose, simp only [not_mem_support_iff, normalize_scale_roots, finset_sum_coeff, coeff_monomial, finset.sum_ite_eq', mem_support_iff, ne.def, not_not, ite_eq_right_iff], intros h₁ h₂, exact (h₂ h₁).rec _, end lemma normalize_scale_roots_degree : (normalize_scale_roots p).degree = p.degree := begin apply le_antisymm, { exact finset.sup_mono (normalize_scale_roots_support p) }, { rw [← degree_scale_roots, ← leading_coeff_smul_normalize_scale_roots], exact degree_smul_le _ _ } end lemma normalize_scale_roots_eval₂_leading_coeff_mul (h : 1 ≤ p.nat_degree) (f : R →+* S) (x : S) : (normalize_scale_roots p).eval₂ f (f p.leading_coeff * x) = f p.leading_coeff ^ (p.nat_degree - 1) * (p.eval₂ f x) := begin rw [eval₂_eq_sum_range, eval₂_eq_sum_range, finset.mul_sum], apply finset.sum_congr, { rw nat_degree_eq_of_degree_eq (normalize_scale_roots_degree p) }, intros n hn, rw [mul_pow, ← mul_assoc, ← f.map_pow, ← f.map_mul, normalize_scale_roots_coeff_mul_leading_coeff_pow _ _ h, f.map_mul, f.map_pow], ring, end lemma normalize_scale_roots_monic (h : p ≠ 0) : (normalize_scale_roots p).monic := begin delta monic leading_coeff, rw nat_degree_eq_of_degree_eq (normalize_scale_roots_degree p), suffices : p = 0 → (0 : R) = 1, { simpa [normalize_scale_roots, coeff_monomial] }, exact λ h', (h h').rec _, end /-- Given a `p : R[X]` and a `x : S` such that `p.eval₂ f x = 0`, `f p.leading_coeff * x` is integral. -/ lemma ring_hom.is_integral_elem_leading_coeff_mul (h : p.eval₂ f x = 0) : f.is_integral_elem (f p.leading_coeff * x) := begin by_cases h' : 1 ≤ p.nat_degree, { use normalize_scale_roots p, have : p ≠ 0 := λ h'', by { rw [h'', nat_degree_zero] at h', exact nat.not_succ_le_zero 0 h' }, use normalize_scale_roots_monic p this, rw [normalize_scale_roots_eval₂_leading_coeff_mul p h' f x, h, mul_zero] }, { by_cases hp : p.map f = 0, { apply_fun (λ q, coeff q p.nat_degree) at hp, rw [coeff_map, coeff_zero, coeff_nat_degree] at hp, rw [hp, zero_mul], exact f.is_integral_zero }, { rw [nat.one_le_iff_ne_zero, not_not] at h', rw [eq_C_of_nat_degree_eq_zero h', eval₂_C] at h, suffices : p.map f = 0, { exact (hp this).rec _ }, rw [eq_C_of_nat_degree_eq_zero h', map_C, h, C_eq_zero] } } end /-- Given a `p : R[X]` and a root `x : S`, then `p.leading_coeff • x : S` is integral over `R`. -/ lemma is_integral_leading_coeff_smul [algebra R S] (h : aeval x p = 0) : is_integral R (p.leading_coeff • x) := begin rw aeval_def at h, rw algebra.smul_def, exact (algebra_map R S).is_integral_elem_leading_coeff_mul p x h, end end end section is_integral_closure /-- `is_integral_closure A R B` is the characteristic predicate stating `A` is the integral closure of `R` in `B`, i.e. that an element of `B` is integral over `R` iff it is an element of (the image of) `A`. -/ class is_integral_closure (A R B : Type*) [comm_ring R] [comm_semiring A] [comm_ring B] [algebra R B] [algebra A B] : Prop := (algebra_map_injective [] : function.injective (algebra_map A B)) (is_integral_iff : ∀ {x : B}, is_integral R x ↔ ∃ y, algebra_map A B y = x) instance integral_closure.is_integral_closure (R A : Type*) [comm_ring R] [comm_ring A] [algebra R A] : is_integral_closure (integral_closure R A) R A := ⟨subtype.coe_injective, λ x, ⟨λ h, ⟨⟨x, h⟩, rfl⟩, by { rintro ⟨⟨_, h⟩, rfl⟩, exact h }⟩⟩ namespace is_integral_closure variables {R A B : Type*} [comm_ring R] [comm_ring A] [comm_ring B] variables [algebra R B] [algebra A B] [is_integral_closure A R B] variables (R) {A} (B) protected theorem is_integral [algebra R A] [is_scalar_tower R A B] (x : A) : is_integral R x := (is_integral_algebra_map_iff (algebra_map_injective A R B)).mp $ show is_integral R (algebra_map A B x), from is_integral_iff.mpr ⟨x, rfl⟩ theorem is_integral_algebra [algebra R A] [is_scalar_tower R A B] : algebra.is_integral R A := λ x, is_integral_closure.is_integral R B x theorem no_zero_smul_divisors [algebra R A] [is_scalar_tower R A B] [no_zero_smul_divisors R B] : no_zero_smul_divisors R A := begin refine function.injective.no_zero_smul_divisors _ (is_integral_closure.algebra_map_injective A R B) (map_zero _) (λ _ _, _), simp only [algebra.algebra_map_eq_smul_one, is_scalar_tower.smul_assoc], end variables {R} (A) {B} /-- If `x : B` is integral over `R`, then it is an element of the integral closure of `R` in `B`. -/ noncomputable def mk' (x : B) (hx : is_integral R x) : A := classical.some (is_integral_iff.mp hx) @[simp] lemma algebra_map_mk' (x : B) (hx : is_integral R x) : algebra_map A B (mk' A x hx) = x := classical.some_spec (is_integral_iff.mp hx) @[simp] lemma mk'_one (h : is_integral R (1 : B) := is_integral_one) : mk' A 1 h = 1 := algebra_map_injective A R B $ by rw [algebra_map_mk', ring_hom.map_one] @[simp] lemma mk'_zero (h : is_integral R (0 : B) := is_integral_zero) : mk' A 0 h = 0 := algebra_map_injective A R B $ by rw [algebra_map_mk', ring_hom.map_zero] @[simp] lemma mk'_add (x y : B) (hx : is_integral R x) (hy : is_integral R y) : mk' A (x + y) (is_integral_add hx hy) = mk' A x hx + mk' A y hy := algebra_map_injective A R B $ by simp only [algebra_map_mk', ring_hom.map_add] @[simp] lemma mk'_mul (x y : B) (hx : is_integral R x) (hy : is_integral R y) : mk' A (x * y) (is_integral_mul hx hy) = mk' A x hx * mk' A y hy := algebra_map_injective A R B $ by simp only [algebra_map_mk', ring_hom.map_mul] @[simp] lemma mk'_algebra_map [algebra R A] [is_scalar_tower R A B] (x : R) (h : is_integral R (algebra_map R B x) := is_integral_algebra_map) : is_integral_closure.mk' A (algebra_map R B x) h = algebra_map R A x := algebra_map_injective A R B $ by rw [algebra_map_mk', ← is_scalar_tower.algebra_map_apply] section lift variables {R} (A B) {S : Type*} [comm_ring S] [algebra R S] [algebra S B] [is_scalar_tower R S B] variables [algebra R A] [is_scalar_tower R A B] (h : algebra.is_integral R S) /-- If `B / S / R` is a tower of ring extensions where `S` is integral over `R`, then `S` maps (uniquely) into an integral closure `B / A / R`. -/ noncomputable def lift : S →ₐ[R] A := { to_fun := λ x, mk' A (algebra_map S B x) (is_integral.algebra_map (h x)), map_one' := by simp only [ring_hom.map_one, mk'_one], map_zero' := by simp only [ring_hom.map_zero, mk'_zero], map_add' := λ x y, by simp_rw [← mk'_add, ring_hom.map_add], map_mul' := λ x y, by simp_rw [← mk'_mul, ring_hom.map_mul], commutes' := λ x, by simp_rw [← is_scalar_tower.algebra_map_apply, mk'_algebra_map] } @[simp] lemma algebra_map_lift (x : S) : algebra_map A B (lift A B h x) = algebra_map S B x := algebra_map_mk' _ _ _ end lift section equiv variables (R A B) (A' : Type*) [comm_ring A'] [algebra A' B] [is_integral_closure A' R B] variables [algebra R A] [algebra R A'] [is_scalar_tower R A B] [is_scalar_tower R A' B] /-- Integral closures are all isomorphic to each other. -/ noncomputable def equiv : A ≃ₐ[R] A' := alg_equiv.of_alg_hom (lift _ B (is_integral_algebra R B)) (lift _ B (is_integral_algebra R B)) (by { ext x, apply algebra_map_injective A' R B, simp }) (by { ext x, apply algebra_map_injective A R B, simp }) @[simp] lemma algebra_map_equiv (x : A) : algebra_map A' B (equiv R A B A' x) = algebra_map A B x := algebra_map_lift _ _ _ _ end equiv end is_integral_closure end is_integral_closure section algebra open algebra variables {R A B S T : Type*} variables [comm_ring R] [comm_ring A] [comm_ring B] [comm_ring S] [comm_ring T] variables [algebra A B] [algebra R B] (f : R →+* S) (g : S →+* T) lemma is_integral_trans_aux (x : B) {p : A[X]} (pmonic : monic p) (hp : aeval x p = 0) : is_integral (adjoin R (↑(p.map $ algebra_map A B).frange : set B)) x := begin generalize hS : (↑(p.map $ algebra_map A B).frange : set B) = S, have coeffs_mem : ∀ i, (p.map $ algebra_map A B).coeff i ∈ adjoin R S, { intro i, by_cases hi : (p.map $ algebra_map A B).coeff i = 0, { rw hi, exact subalgebra.zero_mem _ }, rw ← hS, exact subset_adjoin (coeff_mem_frange _ _ hi) }, obtain ⟨q, hq⟩ : ∃ q : (adjoin R S)[X], q.map (algebra_map (adjoin R S) B) = (p.map $ algebra_map A B), { rw ← set.mem_range, exact (polynomial.mem_map_range _).2 (λ i, ⟨⟨_, coeffs_mem i⟩, rfl⟩) }, use q, split, { suffices h : (q.map (algebra_map (adjoin R S) B)).monic, { refine monic_of_injective _ h, exact subtype.val_injective }, { rw hq, exact pmonic.map _ } }, { convert hp using 1, replace hq := congr_arg (eval x) hq, convert hq using 1; symmetry; apply eval_map }, end variables [algebra R A] [is_scalar_tower R A B] /-- If A is an R-algebra all of whose elements are integral over R, and x is an element of an A-algebra that is integral over A, then x is integral over R.-/ lemma is_integral_trans (A_int : algebra.is_integral R A) (x : B) (hx : is_integral A x) : is_integral R x := begin rcases hx with ⟨p, pmonic, hp⟩, let S : set B := ↑(p.map $ algebra_map A B).frange, refine is_integral_of_mem_of_fg (adjoin R (S ∪ {x})) _ _ (subset_adjoin $ or.inr rfl), refine fg_trans (fg_adjoin_of_finite (finset.finite_to_set _) (λ x hx, _)) _, { rw [finset.mem_coe, frange, finset.mem_image] at hx, rcases hx with ⟨i, _, rfl⟩, rw coeff_map, exact map_is_integral (is_scalar_tower.to_alg_hom R A B) (A_int _) }, { apply fg_adjoin_singleton_of_integral, exact is_integral_trans_aux _ pmonic hp } end /-- If A is an R-algebra all of whose elements are integral over R, and B is an A-algebra all of whose elements are integral over A, then all elements of B are integral over R.-/ lemma algebra.is_integral_trans (hA : algebra.is_integral R A) (hB : algebra.is_integral A B) : algebra.is_integral R B := λ x, is_integral_trans hA x (hB x) lemma ring_hom.is_integral_trans (hf : f.is_integral) (hg : g.is_integral) : (g.comp f).is_integral := @algebra.is_integral_trans R S T _ _ _ g.to_algebra (g.comp f).to_algebra f.to_algebra (@is_scalar_tower.of_algebra_map_eq R S T _ _ _ f.to_algebra g.to_algebra (g.comp f).to_algebra (ring_hom.comp_apply g f)) hf hg lemma ring_hom.is_integral_of_surjective (hf : function.surjective f) : f.is_integral := λ x, (hf x).rec_on (λ y hy, (hy ▸ f.is_integral_map : f.is_integral_elem x)) lemma is_integral_of_surjective (h : function.surjective (algebra_map R A)) : algebra.is_integral R A := (algebra_map R A).is_integral_of_surjective h /-- If `R → A → B` is an algebra tower with `A → B` injective, then if the entire tower is an integral extension so is `R → A` -/ lemma is_integral_tower_bot_of_is_integral (H : function.injective (algebra_map A B)) {x : A} (h : is_integral R (algebra_map A B x)) : is_integral R x := begin rcases h with ⟨p, ⟨hp, hp'⟩⟩, refine ⟨p, ⟨hp, _⟩⟩, rw [is_scalar_tower.algebra_map_eq R A B, ← eval₂_map, eval₂_hom, ← ring_hom.map_zero (algebra_map A B)] at hp', rw [eval₂_eq_eval_map], exact H hp', end lemma ring_hom.is_integral_tower_bot_of_is_integral (hg : function.injective g) (hfg : (g.comp f).is_integral) : f.is_integral := λ x, @is_integral_tower_bot_of_is_integral R S T _ _ _ g.to_algebra (g.comp f).to_algebra f.to_algebra (@is_scalar_tower.of_algebra_map_eq R S T _ _ _ f.to_algebra g.to_algebra (g.comp f).to_algebra (ring_hom.comp_apply g f)) hg x (hfg (g x)) lemma is_integral_tower_bot_of_is_integral_field {R A B : Type*} [comm_ring R] [field A] [comm_ring B] [nontrivial B] [algebra R A] [algebra A B] [algebra R B] [is_scalar_tower R A B] {x : A} (h : is_integral R (algebra_map A B x)) : is_integral R x := is_integral_tower_bot_of_is_integral (algebra_map A B).injective h lemma ring_hom.is_integral_elem_of_is_integral_elem_comp {x : T} (h : (g.comp f).is_integral_elem x) : g.is_integral_elem x := let ⟨p, ⟨hp, hp'⟩⟩ := h in ⟨p.map f, hp.map f, by rwa ← eval₂_map at hp'⟩ lemma ring_hom.is_integral_tower_top_of_is_integral (h : (g.comp f).is_integral) : g.is_integral := λ x, ring_hom.is_integral_elem_of_is_integral_elem_comp f g (h x) /-- If `R → A → B` is an algebra tower, then if the entire tower is an integral extension so is `A → B`. -/ lemma is_integral_tower_top_of_is_integral {x : B} (h : is_integral R x) : is_integral A x := begin rcases h with ⟨p, ⟨hp, hp'⟩⟩, refine ⟨p.map (algebra_map R A), ⟨hp.map (algebra_map R A), _⟩⟩, rw [is_scalar_tower.algebra_map_eq R A B, ← eval₂_map] at hp', exact hp', end lemma ring_hom.is_integral_quotient_of_is_integral {I : ideal S} (hf : f.is_integral) : (ideal.quotient_map I f le_rfl).is_integral := begin rintros ⟨x⟩, obtain ⟨p, ⟨p_monic, hpx⟩⟩ := hf x, refine ⟨p.map (ideal.quotient.mk _), ⟨p_monic.map _, _⟩⟩, simpa only [hom_eval₂, eval₂_map] using congr_arg (ideal.quotient.mk I) hpx end lemma is_integral_quotient_of_is_integral {I : ideal A} (hRA : algebra.is_integral R A) : algebra.is_integral (R ⧸ I.comap (algebra_map R A)) (A ⧸ I) := (algebra_map R A).is_integral_quotient_of_is_integral hRA lemma is_integral_quotient_map_iff {I : ideal S} : (ideal.quotient_map I f le_rfl).is_integral ↔ ((ideal.quotient.mk I).comp f : R →+* S ⧸ I).is_integral := begin let g := ideal.quotient.mk (I.comap f), have := ideal.quotient_map_comp_mk le_rfl, refine ⟨λ h, _, λ h, ring_hom.is_integral_tower_top_of_is_integral g _ (this ▸ h)⟩, refine this ▸ ring_hom.is_integral_trans g (ideal.quotient_map I f le_rfl) _ h, exact ring_hom.is_integral_of_surjective g ideal.quotient.mk_surjective, end /-- If the integral extension `R → S` is injective, and `S` is a field, then `R` is also a field. -/ lemma is_field_of_is_integral_of_is_field {R S : Type*} [comm_ring R] [nontrivial R] [comm_ring S] [is_domain S] [algebra R S] (H : algebra.is_integral R S) (hRS : function.injective (algebra_map R S)) (hS : is_field S) : is_field R := begin refine ⟨⟨0, 1, zero_ne_one⟩, mul_comm, λ a ha, _⟩, -- Let `a_inv` be the inverse of `algebra_map R S a`, -- then we need to show that `a_inv` is of the form `algebra_map R S b`. obtain ⟨a_inv, ha_inv⟩ := hS.mul_inv_cancel (λ h, ha (hRS (trans h (ring_hom.map_zero _).symm))), -- Let `p : R[X]` be monic with root `a_inv`, -- and `q` be `p` with coefficients reversed (so `q(a) = q'(a) * a + 1`). -- We claim that `q(a) = 0`, so `-q'(a)` is the inverse of `a`. obtain ⟨p, p_monic, hp⟩ := H a_inv, use -∑ (i : ℕ) in finset.range p.nat_degree, (p.coeff i) * a ^ (p.nat_degree - i - 1), -- `q(a) = 0`, because multiplying everything with `a_inv^n` gives `p(a_inv) = 0`. -- TODO: this could be a lemma for `polynomial.reverse`. have hq : ∑ (i : ℕ) in finset.range (p.nat_degree + 1), (p.coeff i) * a ^ (p.nat_degree - i) = 0, { apply (injective_iff_map_eq_zero (algebra_map R S)).mp hRS, have a_inv_ne_zero : a_inv ≠ 0 := right_ne_zero_of_mul (mt ha_inv.symm.trans one_ne_zero), refine (mul_eq_zero.mp _).resolve_right (pow_ne_zero p.nat_degree a_inv_ne_zero), rw [eval₂_eq_sum_range] at hp, rw [ring_hom.map_sum, finset.sum_mul], refine (finset.sum_congr rfl (λ i hi, _)).trans hp, rw [ring_hom.map_mul, mul_assoc], congr, have : a_inv ^ p.nat_degree = a_inv ^ (p.nat_degree - i) * a_inv ^ i, { rw [← pow_add a_inv, tsub_add_cancel_of_le (nat.le_of_lt_succ (finset.mem_range.mp hi))] }, rw [ring_hom.map_pow, this, ← mul_assoc, ← mul_pow, ha_inv, one_pow, one_mul] }, -- Since `q(a) = 0` and `q(a) = q'(a) * a + 1`, we have `a * -q'(a) = 1`. -- TODO: we could use a lemma for `polynomial.div_X` here. rw [finset.sum_range_succ_comm, p_monic.coeff_nat_degree, one_mul, tsub_self, pow_zero, add_eq_zero_iff_eq_neg, eq_comm] at hq, rw [mul_comm, neg_mul, finset.sum_mul], convert hq using 2, refine finset.sum_congr rfl (λ i hi, _), have : 1 ≤ p.nat_degree - i := le_tsub_of_add_le_left (finset.mem_range.mp hi), rw [mul_assoc, ← pow_succ', tsub_add_cancel_of_le this] end lemma is_field_of_is_integral_of_is_field' {R S : Type*} [comm_ring R] [comm_ring S] [is_domain S] [algebra R S] (H : algebra.is_integral R S) (hR : is_field R) : is_field S := begin letI := hR.to_field, refine ⟨⟨0, 1, zero_ne_one⟩, mul_comm, λ x hx, _⟩, let A := algebra.adjoin R ({x} : set S), haveI : is_noetherian R A := is_noetherian_of_fg_of_noetherian A.to_submodule (fg_adjoin_singleton_of_integral x (H x)), haveI : module.finite R A := module.is_noetherian.finite R A, obtain ⟨y, hy⟩ := linear_map.surjective_of_injective (@linear_map.mul_left_injective R A _ _ _ _ ⟨x, subset_adjoin (set.mem_singleton x)⟩ (λ h, hx (subtype.ext_iff.mp h))) 1, exact ⟨y, subtype.ext_iff.mp hy⟩, end lemma algebra.is_integral.is_field_iff_is_field {R S : Type*} [comm_ring R] [nontrivial R] [comm_ring S] [is_domain S] [algebra R S] (H : algebra.is_integral R S) (hRS : function.injective (algebra_map R S)) : is_field R ↔ is_field S := ⟨is_field_of_is_integral_of_is_field' H, is_field_of_is_integral_of_is_field H hRS⟩ end algebra theorem integral_closure_idem {R : Type*} {A : Type*} [comm_ring R] [comm_ring A] [algebra R A] : integral_closure (integral_closure R A : set A) A = ⊥ := eq_bot_iff.2 $ λ x hx, algebra.mem_bot.2 ⟨⟨x, @is_integral_trans _ _ _ _ _ _ _ _ (integral_closure R A).algebra _ integral_closure.is_integral x hx⟩, rfl⟩ section is_domain variables {R S : Type*} [comm_ring R] [comm_ring S] [is_domain S] [algebra R S] instance : is_domain (integral_closure R S) := infer_instance theorem roots_mem_integral_closure {f : R[X]} (hf : f.monic) {a : S} (ha : a ∈ (f.map $ algebra_map R S).roots) : a ∈ integral_closure R S := ⟨f, hf, (eval₂_eq_eval_map _).trans $ (mem_roots $ (hf.map _).ne_zero).1 ha⟩ end is_domain
ba5303e5d8d8d73fddfe7d31085587e9298aae03
a047a4718edfa935d17231e9e6ecec8c7b701e05
/src/logic/embedding.lean
a3d1697c9bececdb954e829ac72c899d9afa42b7
[ "Apache-2.0" ]
permissive
utensil-contrib/mathlib
bae0c9fafe5e2bdb516efc89d6f8c1502ecc9767
b91909e77e219098a2f8cc031f89d595fe274bd2
refs/heads/master
1,668,048,976,965
1,592,442,701,000
1,592,442,701,000
273,197,855
0
0
null
1,592,472,812,000
1,592,472,811,000
null
UTF-8
Lean
false
false
9,706
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro -/ import data.equiv.basic /-! # Injective functions -/ universes u v w x namespace function /-- `α ↪ β` is a bundled injective function. -/ structure embedding (α : Sort*) (β : Sort*) := (to_fun : α → β) (inj' : injective to_fun) infixr ` ↪ `:25 := embedding instance {α : Sort u} {β : Sort v} : has_coe_to_fun (α ↪ β) := ⟨_, embedding.to_fun⟩ end function /-- Convert an `α ≃ β` to `α ↪ β`. -/ protected def equiv.to_embedding {α : Sort u} {β : Sort v} (f : α ≃ β) : α ↪ β := ⟨f, f.injective⟩ @[simp] theorem equiv.to_embedding_coe_fn {α : Sort u} {β : Sort v} (f : α ≃ β) : (f.to_embedding : α → β) = f := rfl namespace function namespace embedding @[ext] lemma ext {α β} {f g : embedding α β} (h : ∀ x, f x = g x) : f = g := by cases f; cases g; simpa using funext h lemma ext_iff {α β} {f g : embedding α β} : (∀ x, f x = g x) ↔ f = g := ⟨ext, λ h _, by rw h⟩ @[simp] theorem to_fun_eq_coe {α β} (f : α ↪ β) : to_fun f = f := rfl @[simp] theorem coe_fn_mk {α β} (f : α → β) (i) : (@mk _ _ f i : α → β) = f := rfl theorem inj {α β} (f : α ↪ β) : injective f := f.inj' @[refl] protected def refl (α : Sort*) : α ↪ α := ⟨id, injective_id⟩ @[trans] protected def trans {α β γ} (f : α ↪ β) (g : β ↪ γ) : α ↪ γ := ⟨g ∘ f, g.inj.comp f.inj⟩ @[simp] theorem refl_apply {α} (x : α) : embedding.refl α x = x := rfl @[simp] theorem trans_apply {α β γ} (f : α ↪ β) (g : β ↪ γ) (a : α) : (f.trans g) a = g (f a) := rfl @[simp] lemma equiv_to_embedding_trans_symm_to_embedding {α β : Sort*} (e : α ≃ β) : function.embedding.trans (e.to_embedding) (e.symm.to_embedding) = function.embedding.refl _ := by { ext, simp, } @[simp] lemma equiv_symm_to_embedding_trans_to_embedding {α β : Sort*} (e : α ≃ β) : function.embedding.trans (e.symm.to_embedding) (e.to_embedding) = function.embedding.refl _ := by { ext, simp, } protected def congr {α : Sort u} {β : Sort v} {γ : Sort w} {δ : Sort x} (e₁ : α ≃ β) (e₂ : γ ≃ δ) (f : α ↪ γ) : (β ↪ δ) := (equiv.to_embedding e₁.symm).trans (f.trans e₂.to_embedding) /-- A right inverse `surj_inv` of a surjective function as an `embedding`. -/ protected noncomputable def of_surjective {α β} (f : β → α) (hf : surjective f) : α ↪ β := ⟨surj_inv hf, injective_surj_inv _⟩ /-- Convert a surjective `embedding` to an `equiv` -/ protected noncomputable def equiv_of_surjective {α β} (f : α ↪ β) (hf : surjective f) : α ≃ β := equiv.of_bijective f ⟨f.inj, hf⟩ protected def of_not_nonempty {α β} (hα : ¬ nonempty α) : α ↪ β := ⟨λa, (hα ⟨a⟩).elim, assume a, (hα ⟨a⟩).elim⟩ /-- Change the value of an embedding `f` at one point. If the prescribed image is already occupied by some `f a'`, then swap the values at these two points. -/ def set_value {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)] [∀ a', decidable (f a' = b)] : α ↪ β := ⟨λ a', if a' = a then b else if f a' = b then f a else f a', begin intros x y h, dsimp at h, unfreezeI, split_ifs at h; try { subst b }; try { simp only [f.inj.eq_iff] at * }; cc end⟩ theorem set_value_eq {α β} (f : α ↪ β) (a : α) (b : β) [∀ a', decidable (a' = a)] [∀ a', decidable (f a' = b)] : set_value f a b a = b := by simp [set_value] /-- Embedding into `option` -/ protected def some {α} : α ↪ option α := ⟨some, option.injective_some α⟩ /-- Embedding of a `subtype`. -/ def subtype {α} (p : α → Prop) : subtype p ↪ α := ⟨subtype.val, λ _ _, subtype.eq'⟩ /-- Choosing an element `b : β` gives an embedding of `punit` into `β`. -/ def punit {β : Sort*} (b : β) : punit ↪ β := ⟨λ _, b, by { rintros ⟨⟩ ⟨⟩ _, refl, }⟩ /-- Fixing an element `b : β` gives an embedding `α ↪ α × β`. -/ def sectl (α : Sort*) {β : Sort*} (b : β) : α ↪ α × β := ⟨λ a, (a, b), λ a a' h, congr_arg prod.fst h⟩ /-- Fixing an element `a : α` gives an embedding `β ↪ α × β`. -/ def sectr {α : Sort*} (a : α) (β : Sort*): β ↪ α × β := ⟨λ b, (a, b), λ b b' h, congr_arg prod.snd h⟩ /-- Restrict the codomain of an embedding. -/ def cod_restrict {α β} (p : set β) (f : α ↪ β) (H : ∀ a, f a ∈ p) : α ↪ p := ⟨λ a, ⟨f a, H a⟩, λ a b h, f.inj (@congr_arg _ _ _ _ subtype.val h)⟩ @[simp] theorem cod_restrict_apply {α β} (p) (f : α ↪ β) (H a) : cod_restrict p f H a = ⟨f a, H a⟩ := rfl def prod_congr {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α × γ ↪ β × δ := ⟨assume ⟨a, b⟩, (e₁ a, e₂ b), assume ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ h, have a₁ = a₂ ∧ b₁ = b₂, from (prod.mk.inj h).imp (assume h, e₁.inj h) (assume h, e₂.inj h), this.left ▸ this.right ▸ rfl⟩ section sum open sum def sum_congr {α β γ δ : Type*} (e₁ : α ↪ β) (e₂ : γ ↪ δ) : α ⊕ γ ↪ β ⊕ δ := ⟨assume s, match s with inl a := inl (e₁ a) | inr b := inr (e₂ b) end, assume s₁ s₂ h, match s₁, s₂, h with | inl a₁, inl a₂, h := congr_arg inl $ e₁.inj $ inl.inj h | inr b₁, inr b₂, h := congr_arg inr $ e₂.inj $ inr.inj h end⟩ @[simp] theorem sum_congr_apply_inl {α β γ δ} (e₁ : α ↪ β) (e₂ : γ ↪ δ) (a) : sum_congr e₁ e₂ (inl a) = inl (e₁ a) := rfl @[simp] theorem sum_congr_apply_inr {α β γ δ} (e₁ : α ↪ β) (e₂ : γ ↪ δ) (b) : sum_congr e₁ e₂ (inr b) = inr (e₂ b) := rfl /-- The embedding of `α` into the sum `α ⊕ β`. -/ def inl {α β : Type*} : α ↪ α ⊕ β := ⟨sum.inl, λ a b, sum.inl.inj⟩ /-- The embedding of `β` into the sum `α ⊕ β`. -/ def inr {α β : Type*} : β ↪ α ⊕ β := ⟨sum.inr, λ a b, sum.inr.inj⟩ end sum section sigma open sigma def sigma_congr_right {α : Type*} {β γ : α → Type*} (e : ∀ a, β a ↪ γ a) : sigma β ↪ sigma γ := ⟨λ ⟨a, b⟩, ⟨a, e a b⟩, λ ⟨a₁, b₁⟩ ⟨a₂, b₂⟩ h, begin injection h with h₁ h₂, subst a₂, congr, exact (e a₁).2 (eq_of_heq h₂) end⟩ end sigma def Pi_congr_right {α : Sort*} {β γ : α → Sort*} (e : ∀ a, β a ↪ γ a) : (Π a, β a) ↪ (Π a, γ a) := ⟨λf a, e a (f a), λ f₁ f₂ h, funext $ λ a, (e a).inj (congr_fun h a)⟩ def arrow_congr_left {α : Sort u} {β : Sort v} {γ : Sort w} (e : α ↪ β) : (γ → α) ↪ (γ → β) := Pi_congr_right (λ _, e) noncomputable def arrow_congr_right {α : Sort u} {β : Sort v} {γ : Sort w} [inhabited γ] (e : α ↪ β) : (α → γ) ↪ (β → γ) := by haveI := classical.prop_decidable; exact let f' : (α → γ) → (β → γ) := λf b, if h : ∃c, e c = b then f (classical.some h) else default γ in ⟨f', assume f₁ f₂ h, funext $ assume c, have ∃c', e c' = e c, from ⟨c, rfl⟩, have eq' : f' f₁ (e c) = f' f₂ (e c), from congr_fun h _, have eq_b : classical.some this = c, from e.inj $ classical.some_spec this, by simp [f', this, if_pos, eq_b] at eq'; assumption⟩ protected def subtype_map {α β} {p : α → Prop} {q : β → Prop} (f : α ↪ β) (h : ∀{{x}}, p x → q (f x)) : {x : α // p x} ↪ {y : β // q y} := ⟨subtype.map f h, subtype.map_injective h f.2⟩ open set /-- `set.image` as an embedding `set α ↪ set β`. -/ protected def image {α β} (f : α ↪ β) : set α ↪ set β := ⟨image f, injective_image f.2⟩ @[simp] lemma coe_image {α β} (f : α ↪ β) : ⇑f.image = image f := rfl end embedding end function namespace equiv @[simp] lemma refl_to_embedding {α : Type*} : (equiv.refl α).to_embedding = function.embedding.refl α := rfl @[simp] lemma trans_to_embedding {α β γ : Type*} (e : α ≃ β) (f : β ≃ γ) : (e.trans f).to_embedding = e.to_embedding.trans f.to_embedding := rfl end equiv namespace set /-- The injection map is an embedding between subsets. -/ def embedding_of_subset {α} (s t : set α) (h : s ⊆ t) : s ↪ t := ⟨λ x, ⟨x.1, h x.2⟩, λ ⟨x, hx⟩ ⟨y, hy⟩ h, by congr; injection h⟩ @[simp] lemma embedding_of_subset_apply_mk {α} {s t : set α} (h : s ⊆ t) (x : α) (hx : x ∈ s) : embedding_of_subset s t h ⟨x, hx⟩ = ⟨x, h hx⟩ := rfl @[simp] lemma coe_embedding_of_subset_apply {α} {s t : set α} (h : s ⊆ t) (x : s) : (embedding_of_subset s t h x : α) = x := rfl end set /-- The embedding of a left cancellative semigroup into itself by left multiplication by a fixed element. -/ @[to_additive "The embedding of a left cancellative additive semigroup into itself by left translation by a fixed element."] def mul_left_embedding {G : Type u} [left_cancel_semigroup G] (g : G) : G ↪ G := { to_fun := λ h, g * h, inj' := λ h h', (mul_right_inj g).mp, } @[simp] lemma mul_left_embedding_apply {G : Type u} [left_cancel_semigroup G] (g h : G) : mul_left_embedding g h = g * h := rfl /-- The embedding of a right cancellative semigroup into itself by right multiplication by a fixed element. -/ @[to_additive "The embedding of a right cancellative additive semigroup into itself by right translation by a fixed element."] def mul_right_embedding {G : Type u} [right_cancel_semigroup G] (g : G) : G ↪ G := { to_fun := λ h, h * g, inj' := λ h h', (mul_left_inj g).mp, } @[simp] lemma mul_right_embedding_apply {G : Type u} [right_cancel_semigroup G] (g h : G) : mul_right_embedding g h = h * g := rfl
d716bdb465ab1f532810c515f230893aa64f1c6e
b32d3853770e6eaf06817a1b8c52064baaed0ef1
/src/super/eqn_lemmas.lean
bce2d1790eb5f99c4b45aad212007b3a4976353a
[]
no_license
gebner/super2
4d58b7477b6f7d945d5d866502982466db33ab0b
9bc5256c31750021ab97d6b59b7387773e54b384
refs/heads/master
1,635,021,682,021
1,634,886,326,000
1,634,886,326,000
225,600,688
4
2
null
1,598,209,306,000
1,575,371,550,000
Lean
UTF-8
Lean
false
false
2,344
lean
import super.utils super.clause import tactic.binder_matching open tactic expr namespace super meta def get_eqn_lemma_clauses (n : name) : tactic (list clause) := do els ← get_eqn_lemmas_for tt n, els.mmap clause.of_const meta def mk_inst_equations_core : expr → expr → tactic (list expr) | lhs rhs := do type ← infer_type lhs, (type_args, tgt) ← open_pis_whnf type, tgt ← whnf tgt, let str := tgt.get_app_fn.const_name, is_cls ← has_attribute' `class str, e ← get_env, if is_cls ∧ e.is_structure str then do if type_args ≠ [] then do let lhs := lhs.mk_app type_args, let rhs := rhs.instantiate_lambdas_or_apps type_args, eqns ← mk_inst_equations_core lhs rhs, pure $ eqns.map (mk_lambdas type_args) else do lhs ← whnf lhs transparency.reducible, projs ← e.structure_fields_full str, [intro] ← return $ e.constructors_of str | fail "unreachable code (3)", let params := get_app_args tgt, -- the parameters of the structure rhs ← whnf rhs, if is_constant_of rhs.get_app_fn intro then do -- if the value is a constructor application let rhs_args := rhs.get_app_args.drop params.length, -- the fields of the structure guard (rhs_args.length = projs.length) <|> fail "unreachable code (2)", list.join <$> (projs.zip rhs_args).mmap (λ ⟨proj, new_rhs⟩, do new_type ← infer_type new_rhs, b ← is_prop new_type, if b then -- Prop field pure [] else do new_lhs ← mk_mapp proj ((params ++ [lhs]).map some), mk_inst_equations_core new_lhs new_rhs) else do -- class subfield that doesn't reduce to a constructor pure [] else do -- non-class field e ← mk_mapp ``eq [none, lhs, rhs], prfl ← mk_eq_refl lhs, pure <$> (expr.app <$> mk_mapp ``id_rhs [e] <*> pure prfl) meta def mk_inst_equations (n : name) : tactic (list expr) := do lhs ← mk_const n, rhs ← whnf lhs, mk_inst_equations_core lhs rhs meta def mk_inst_eqn_clauses (n : name) : tactic (list clause) := do prfs ← mk_inst_equations n, prfs.mmap $ λ prf, clause.of_proof prf >>= clause.clone meta def get_aux_lemma_clauses (n : name) : tactic (list clause) := do is_inst ← has_attribute' `instance n, if is_inst then mk_inst_eqn_clauses n else get_eqn_lemma_clauses n end super
dd8682a2642cb4a8b0abac8362132e826f6fec2f
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/algebra/uniform_group.lean
75f99ea12ad07d416de67b07ebbe503fc8ab0aca
[ "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
20,870
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 topology.uniform_space.uniform_convergence import topology.uniform_space.uniform_embedding import topology.uniform_space.complete_separated import topology.algebra.group import tactic.abel /-! # Uniform structure on topological groups * `topological_add_group.to_uniform_space` and `topological_add_group_is_uniform` can be used to construct a canonical uniformity for a topological add group. * extension of ℤ-bilinear maps to complete groups (useful for ring completions) -/ noncomputable theory open_locale classical uniformity topological_space filter section uniform_group open filter set variables {α : Type*} {β : Type*} /-- A uniform group is a group in which multiplication and inversion are uniformly continuous. -/ class uniform_group (α : Type*) [uniform_space α] [group α] : Prop := (uniform_continuous_div : uniform_continuous (λp:α×α, p.1 / p.2)) /-- A uniform additive group is an additive group in which addition and negation are uniformly continuous.-/ class uniform_add_group (α : Type*) [uniform_space α] [add_group α] : Prop := (uniform_continuous_sub : uniform_continuous (λp:α×α, p.1 - p.2)) attribute [to_additive] uniform_group @[to_additive] theorem uniform_group.mk' {α} [uniform_space α] [group α] (h₁ : uniform_continuous (λp:α×α, p.1 * p.2)) (h₂ : uniform_continuous (λp:α, p⁻¹)) : uniform_group α := ⟨by simpa only [div_eq_mul_inv] using h₁.comp (uniform_continuous_fst.prod_mk (h₂.comp uniform_continuous_snd))⟩ variables [uniform_space α] [group α] [uniform_group α] @[to_additive] lemma uniform_continuous_div : uniform_continuous (λp:α×α, p.1 / p.2) := uniform_group.uniform_continuous_div @[to_additive] lemma uniform_continuous.div [uniform_space β] {f : β → α} {g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λx, f x / g x) := uniform_continuous_div.comp (hf.prod_mk hg) @[to_additive] lemma uniform_continuous.inv [uniform_space β] {f : β → α} (hf : uniform_continuous f) : uniform_continuous (λx, (f x)⁻¹) := have uniform_continuous (λx, 1 / f x), from uniform_continuous_const.div hf, by simp * at * @[to_additive] lemma uniform_continuous_inv : uniform_continuous (λx:α, x⁻¹) := uniform_continuous_id.inv @[to_additive] lemma uniform_continuous.mul [uniform_space β] {f : β → α} {g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λx, f x * g x) := have uniform_continuous (λx, f x / (g x)⁻¹), from hf.div hg.inv, by simp * at * @[to_additive] lemma uniform_continuous_mul : uniform_continuous (λp:α×α, p.1 * p.2) := uniform_continuous_fst.mul uniform_continuous_snd @[priority 10, to_additive] instance uniform_group.to_topological_group : topological_group α := { continuous_mul := uniform_continuous_mul.continuous, continuous_inv := uniform_continuous_inv.continuous } @[to_additive] instance [uniform_space β] [group β] [uniform_group β] : uniform_group (α × β) := ⟨((uniform_continuous_fst.comp uniform_continuous_fst).div (uniform_continuous_fst.comp uniform_continuous_snd)).prod_mk ((uniform_continuous_snd.comp uniform_continuous_fst).div (uniform_continuous_snd.comp uniform_continuous_snd))⟩ @[to_additive] lemma uniformity_translate_mul (a : α) : (𝓤 α).map (λx:α×α, (x.1 * a, x.2 * a)) = 𝓤 α := le_antisymm (uniform_continuous_id.mul uniform_continuous_const) (calc 𝓤 α = ((𝓤 α).map (λx:α×α, (x.1 * a⁻¹, x.2 * a⁻¹))).map (λx:α×α, (x.1 * a, x.2 * a)) : by simp [filter.map_map, (∘)]; exact filter.map_id.symm ... ≤ (𝓤 α).map (λx:α×α, (x.1 * a, x.2 * a)) : filter.map_mono (uniform_continuous_id.mul uniform_continuous_const)) @[to_additive] lemma uniform_embedding_translate_mul (a : α) : uniform_embedding (λx:α, x * a) := { comap_uniformity := begin rw [← uniformity_translate_mul a, comap_map] {occs := occurrences.pos [1]}, rintros ⟨p₁, p₂⟩ ⟨q₁, q₂⟩, simp [prod.eq_iff_fst_eq_snd_eq] {contextual := tt} end, inj := mul_left_injective a } section variables (α) @[to_additive] lemma uniformity_eq_comap_nhds_one : 𝓤 α = comap (λx:α×α, x.2 / x.1) (𝓝 (1:α)) := begin rw [nhds_eq_comap_uniformity, filter.comap_comap], refine le_antisymm (filter.map_le_iff_le_comap.1 _) _, { assume s hs, rcases mem_uniformity_of_uniform_continuous_invariant uniform_continuous_div hs with ⟨t, ht, hts⟩, refine mem_map.2 (mem_of_superset ht _), rintros ⟨a, b⟩, simpa [subset_def] using hts a b a }, { assume s hs, rcases mem_uniformity_of_uniform_continuous_invariant uniform_continuous_mul hs with ⟨t, ht, hts⟩, refine ⟨_, ht, _⟩, rintros ⟨a, b⟩, simpa [subset_def] using hts 1 (b / a) a } end end @[to_additive] lemma group_separation_rel (x y : α) : (x, y) ∈ separation_rel α ↔ x / y ∈ closure ({1} : set α) := have embedding (λa, a * (y / x)), from (uniform_embedding_translate_mul (y / x)).embedding, show (x, y) ∈ ⋂₀ (𝓤 α).sets ↔ x / y ∈ closure ({1} : set α), begin rw [this.closure_eq_preimage_closure_image, uniformity_eq_comap_nhds_one α, sInter_comap_sets], simp [mem_closure_iff_nhds, inter_singleton_nonempty, sub_eq_add_neg, add_assoc] end @[to_additive] lemma uniform_continuous_of_tendsto_one [uniform_space β] [group β] [uniform_group β] {f : α →* β} (h : tendsto f (𝓝 1) (𝓝 1)) : uniform_continuous f := begin have : ((λx:β×β, x.2 / x.1) ∘ (λx:α×α, (f x.1, f x.2))) = (λx:α×α, f (x.2 / x.1)), { simp only [f.map_div] }, rw [uniform_continuous, uniformity_eq_comap_nhds_one α, uniformity_eq_comap_nhds_one β, tendsto_comap_iff, this], exact tendsto.comp h tendsto_comap end @[to_additive] lemma monoid_hom.uniform_continuous_of_continuous_at_one [uniform_space β] [group β] [uniform_group β] (f : α →* β) (hf : continuous_at f 1) : uniform_continuous f := uniform_continuous_of_tendsto_one (by simpa using hf.tendsto) @[to_additive] lemma uniform_continuous_monoid_hom_of_continuous [uniform_space β] [group β] [uniform_group β] {f : α →* β} (h : continuous f) : uniform_continuous f := uniform_continuous_of_tendsto_one $ suffices tendsto f (𝓝 1) (𝓝 (f 1)), by rwa f.map_one at this, h.tendsto 1 @[to_additive] lemma cauchy_seq.mul {ι : Type*} [semilattice_sup ι] {u v : ι → α} (hu : cauchy_seq u) (hv : cauchy_seq v) : cauchy_seq (u * v) := uniform_continuous_mul.comp_cauchy_seq (hu.prod hv) end uniform_group section topological_comm_group open filter variables (G : Type*) [comm_group G] [topological_space G] [topological_group G] /-- The right uniformity on a topological group. -/ @[to_additive "The right uniformity on a topological group"] def topological_group.to_uniform_space : uniform_space G := { uniformity := comap (λp:G×G, p.2 / p.1) (𝓝 1), refl := by refine map_le_iff_le_comap.1 (le_trans _ (pure_le_nhds 1)); simp [set.subset_def] {contextual := tt}, symm := begin suffices : tendsto (λp:G×G, (p.2 / p.1)⁻¹) (comap (λp:G×G, p.2 / p.1) (𝓝 1)) (𝓝 1⁻¹), { simpa [tendsto_comap_iff], }, exact tendsto.comp (tendsto.inv tendsto_id) tendsto_comap end, comp := begin intros D H, rw mem_lift'_sets, { rcases H with ⟨U, U_nhds, U_sub⟩, rcases exists_nhds_one_split U_nhds with ⟨V, ⟨V_nhds, V_sum⟩⟩, existsi ((λp:G×G, p.2 / p.1) ⁻¹' V), have H : (λp:G×G, p.2 / p.1) ⁻¹' V ∈ comap (λp:G×G, p.2 / p.1) (𝓝 (1 : G)), by existsi [V, V_nhds] ; refl, existsi H, have comp_rel_sub : comp_rel ((λp:G×G, p.2 / p.1) ⁻¹' V) ((λp, p.2 / p.1) ⁻¹' V) ⊆ (λp:G×G, p.2 / p.1) ⁻¹' U, begin intros p p_comp_rel, rcases p_comp_rel with ⟨z, ⟨Hz1, Hz2⟩⟩, simpa [sub_eq_add_neg, add_comm, add_left_comm] using V_sum _ Hz1 _ Hz2 end, exact set.subset.trans comp_rel_sub U_sub }, { exact monotone_comp_rel monotone_id monotone_id } end, is_open_uniformity := begin intro S, let S' := λ x, {p : G × G | p.1 = x → p.2 ∈ S}, show is_open S ↔ ∀ (x : G), x ∈ S → S' x ∈ comap (λp:G×G, p.2 / p.1) (𝓝 (1 : G)), rw [is_open_iff_mem_nhds], refine forall₂_congr (λ a ha, _), rw [← nhds_translation_div, mem_comap, mem_comap], refine exists₂_congr (λ t ht, _), show (λ (y : G), y / a) ⁻¹' t ⊆ S ↔ (λ (p : G × G), p.snd / p.fst) ⁻¹' t ⊆ S' a, split, { rintros h ⟨x, y⟩ hx rfl, exact h hx }, { rintros h x hx, exact @h (a, x) hx rfl } end } variables {G} @[to_additive] lemma topological_group.tendsto_uniformly_iff {ι α : Type*} (F : ι → α → G) (f : α → G) (p : filter ι) : @tendsto_uniformly α G ι (topological_group.to_uniform_space G) F f p ↔ ∀ u ∈ 𝓝 (1 : G), ∀ᶠ i in p, ∀ a, F i a / f a ∈ u := ⟨λ h u hu, h _ ⟨u, hu, λ _, id⟩, λ h v ⟨u, hu, hv⟩, mem_of_superset (h u hu) (λ i hi a, hv (by exact hi a))⟩ @[to_additive] lemma topological_group.tendsto_uniformly_on_iff {ι α : Type*} (F : ι → α → G) (f : α → G) (p : filter ι) (s : set α) : @tendsto_uniformly_on α G ι (topological_group.to_uniform_space G) F f p s ↔ ∀ u ∈ 𝓝 (1 : G), ∀ᶠ i in p, ∀ a ∈ s, F i a / f a ∈ u := ⟨λ h u hu, h _ ⟨u, hu, λ _, id⟩, λ h v ⟨u, hu, hv⟩, mem_of_superset (h u hu) (λ i hi a ha, hv (by exact hi a ha))⟩ @[to_additive] lemma topological_group.tendsto_locally_uniformly_iff {ι α : Type*} [topological_space α] (F : ι → α → G) (f : α → G) (p : filter ι) : @tendsto_locally_uniformly α G ι (topological_group.to_uniform_space G) _ F f p ↔ ∀ (u ∈ 𝓝 (1 : G)) (x : α), ∃ (t ∈ 𝓝 x), ∀ᶠ i in p, ∀ a ∈ t, F i a / f a ∈ u := ⟨λ h u hu, h _ ⟨u, hu, λ _, id⟩, λ h v ⟨u, hu, hv⟩ x, exists_imp_exists (by exact λ a, exists_imp_exists (λ ha hp, mem_of_superset hp (λ i hi a ha, hv (by exact hi a ha)))) (h u hu x)⟩ @[to_additive] lemma topological_group.tendsto_locally_uniformly_on_iff {ι α : Type*} [topological_space α] (F : ι → α → G) (f : α → G) (p : filter ι) (s : set α) : @tendsto_locally_uniformly_on α G ι (topological_group.to_uniform_space G) _ F f p s ↔ ∀ (u ∈ 𝓝 (1 : G)) (x ∈ s), ∃ (t ∈ 𝓝[s] x), ∀ᶠ i in p, ∀ a ∈ t, F i a / f a ∈ u := ⟨λ h u hu, h _ ⟨u, hu, λ _, id⟩, λ h v ⟨u, hu, hv⟩ x, exists_imp_exists (by exact λ a, exists_imp_exists (λ ha hp, mem_of_superset hp (λ i hi a ha, hv (by exact hi a ha)))) ∘ h u hu x⟩ end topological_comm_group section topological_comm_group universes u v w x open filter variables (G : Type*) [comm_group G] [topological_space G] [topological_group G] section local attribute [instance] topological_group.to_uniform_space @[to_additive] lemma uniformity_eq_comap_nhds_one' : 𝓤 G = comap (λp:G×G, p.2 / p.1) (𝓝 (1 : G)) := rfl variable {G} @[to_additive] lemma topological_group_is_uniform : uniform_group G := have tendsto ((λp:(G×G), p.1 / p.2) ∘ (λp:(G×G)×(G×G), (p.1.2 / p.1.1, p.2.2 / p.2.1))) (comap (λp:(G×G)×(G×G), (p.1.2 / p.1.1, p.2.2 / p.2.1)) ((𝓝 1).prod (𝓝 1))) (𝓝 (1 / 1)) := (tendsto_fst.div' tendsto_snd).comp tendsto_comap, begin constructor, rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, uniformity_eq_comap_nhds_one' G, tendsto_comap_iff, prod_comap_comap_eq], simpa [(∘), div_eq_mul_inv, mul_comm, mul_left_comm] using this end local attribute [instance] topological_group_is_uniform open set @[to_additive] lemma topological_group.separated_iff_one_closed : separated_space G ↔ is_closed ({1} : set G) := begin rw [separated_space_iff, ← closure_eq_iff_is_closed], split; intro h, { apply subset.antisymm, { intros x x_in, have := group_separation_rel x 1, rw div_one' at this, rw [← this, h] at x_in, change x = 1 at x_in, simp [x_in] }, { exact subset_closure } }, { ext p, cases p with x y, rw [group_separation_rel x, h, mem_singleton_iff, div_eq_one], refl } end @[to_additive] lemma topological_group.separated_of_one_sep (H : ∀ x : G, x ≠ 1 → ∃ U ∈ nhds (1 : G), x ∉ U) : separated_space G:= begin rw [topological_group.separated_iff_one_closed, ← is_open_compl_iff, is_open_iff_mem_nhds], intros x x_not, have : x ≠ 1, from mem_compl_singleton_iff.mp x_not, rcases H x this with ⟨U, U_in, xU⟩, rw ← nhds_one_symm G at U_in, rcases U_in with ⟨W, W_in, UW⟩, rw ← nhds_translation_mul_inv, use [W, W_in], rw subset_compl_comm, suffices : x⁻¹ ∉ W, by simpa, exact λ h, xU (UW h) end end @[to_additive] lemma uniform_group.to_uniform_space_eq {G : Type*} [u : uniform_space G] [comm_group G] [uniform_group G] : topological_group.to_uniform_space G = u := begin ext : 1, show @uniformity G (topological_group.to_uniform_space G) = 𝓤 G, rw [uniformity_eq_comap_nhds_one' G, uniformity_eq_comap_nhds_one G] end end topological_comm_group open comm_group filter set function section variables {α : Type*} {β : Type*} variables [topological_space α] [comm_group α] [topological_group α] -- β is a dense subgroup of α, inclusion is denoted by e variables [topological_space β] [comm_group β] variables {e : β →* α} (de : dense_inducing e) include de @[to_additive] lemma tendsto_div_comap_self (x₀ : α) : tendsto (λt:β×β, t.2 / t.1) (comap (λp:β×β, (e p.1, e p.2)) $ 𝓝 (x₀, x₀)) (𝓝 1) := begin have comm : (λx:α×α, x.2/x.1) ∘ (λt:β×β, (e t.1, e t.2)) = e ∘ (λt:β×β, t.2 / t.1), { ext t, change e t.2 / e t.1 = e (t.2 / t.1), rwa ← e.map_div t.2 t.1 }, have lim : tendsto (λ x : α × α, x.2/x.1) (𝓝 (x₀, x₀)) (𝓝 (e 1)), { simpa using (continuous_div'.comp (@continuous_swap α α _ _)).tendsto (x₀, x₀) }, simpa using de.tendsto_comap_nhds_nhds lim comm end end namespace dense_inducing variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables {G : Type*} -- β is a dense subgroup of α, inclusion is denoted by e -- δ is a dense subgroup of γ, inclusion is denoted by f variables [topological_space α] [add_comm_group α] [topological_add_group α] variables [topological_space β] [add_comm_group β] [topological_add_group β] variables [topological_space γ] [add_comm_group γ] [topological_add_group γ] variables [topological_space δ] [add_comm_group δ] [topological_add_group δ] variables [uniform_space G] [add_comm_group G] [uniform_add_group G] [separated_space G] [complete_space G] variables {e : β →+ α} (de : dense_inducing e) variables {f : δ →+ γ} (df : dense_inducing f) variables {φ : β →+ δ →+ G} local notation `Φ` := λ p : β × δ, φ p.1 p.2 variables (hφ : continuous Φ) include de df hφ variables {W' : set G} (W'_nhd : W' ∈ 𝓝 (0 : G)) include W'_nhd private lemma extend_Z_bilin_aux (x₀ : α) (y₁ : δ) : ∃ U₂ ∈ comap e (𝓝 x₀), ∀ x x' ∈ U₂, Φ (x' - x, y₁) ∈ W' := begin let Nx := 𝓝 x₀, let ee := λ u : β × β, (e u.1, e u.2), have lim1 : tendsto (λ a : β × β, (a.2 - a.1, y₁)) (comap e Nx ×ᶠ comap e Nx) (𝓝 (0, y₁)), { have := tendsto.prod_mk (tendsto_sub_comap_self de x₀) (tendsto_const_nhds : tendsto (λ (p : β × β), y₁) (comap ee $ 𝓝 (x₀, x₀)) (𝓝 y₁)), rw [nhds_prod_eq, prod_comap_comap_eq, ←nhds_prod_eq], exact (this : _) }, have lim2 : tendsto Φ (𝓝 (0, y₁)) (𝓝 0), by simpa using hφ.tendsto (0, y₁), have lim := lim2.comp lim1, rw tendsto_prod_self_iff at lim, simp_rw ball_mem_comm, exact lim W' W'_nhd end private lemma extend_Z_bilin_key (x₀ : α) (y₀ : γ) : ∃ U ∈ comap e (𝓝 x₀), ∃ V ∈ comap f (𝓝 y₀), ∀ x x' ∈ U, ∀ y y' ∈ V, Φ (x', y') - Φ (x, y) ∈ W' := begin let Nx := 𝓝 x₀, let Ny := 𝓝 y₀, let dp := dense_inducing.prod de df, let ee := λ u : β × β, (e u.1, e u.2), let ff := λ u : δ × δ, (f u.1, f u.2), have lim_φ : filter.tendsto Φ (𝓝 (0, 0)) (𝓝 0), { simpa using hφ.tendsto (0, 0) }, have lim_φ_sub_sub : tendsto (λ (p : (β × β) × (δ × δ)), Φ (p.1.2 - p.1.1, p.2.2 - p.2.1)) ((comap ee $ 𝓝 (x₀, x₀)) ×ᶠ (comap ff $ 𝓝 (y₀, y₀))) (𝓝 0), { have lim_sub_sub : tendsto (λ (p : (β × β) × δ × δ), (p.1.2 - p.1.1, p.2.2 - p.2.1)) ((comap ee (𝓝 (x₀, x₀))) ×ᶠ (comap ff (𝓝 (y₀, y₀)))) (𝓝 0 ×ᶠ 𝓝 0), { have := filter.prod_mono (tendsto_sub_comap_self de x₀) (tendsto_sub_comap_self df y₀), rwa prod_map_map_eq at this }, rw ← nhds_prod_eq at lim_sub_sub, exact tendsto.comp lim_φ lim_sub_sub }, rcases exists_nhds_zero_quarter W'_nhd with ⟨W, W_nhd, W4⟩, have : ∃ U₁ ∈ comap e (𝓝 x₀), ∃ V₁ ∈ comap f (𝓝 y₀), ∀ x x' ∈ U₁, ∀ y y' ∈ V₁, Φ (x'-x, y'-y) ∈ W, { have := tendsto_prod_iff.1 lim_φ_sub_sub W W_nhd, repeat { rw [nhds_prod_eq, ←prod_comap_comap_eq] at this }, rcases this with ⟨U, U_in, V, V_in, H⟩, rw [mem_prod_same_iff] at U_in V_in, rcases U_in with ⟨U₁, U₁_in, HU₁⟩, rcases V_in with ⟨V₁, V₁_in, HV₁⟩, existsi [U₁, U₁_in, V₁, V₁_in], intros x x_in x' x'_in y y_in y' y'_in, exact H _ _ (HU₁ (mk_mem_prod x_in x'_in)) (HV₁ (mk_mem_prod y_in y'_in)) }, rcases this with ⟨U₁, U₁_nhd, V₁, V₁_nhd, H⟩, obtain ⟨x₁, x₁_in⟩ : U₁.nonempty := ((de.comap_nhds_ne_bot _).nonempty_of_mem U₁_nhd), obtain ⟨y₁, y₁_in⟩ : V₁.nonempty := ((df.comap_nhds_ne_bot _).nonempty_of_mem V₁_nhd), have cont_flip : continuous (λ p : δ × β, φ.flip p.1 p.2), { show continuous (Φ ∘ prod.swap), from hφ.comp continuous_swap }, rcases (extend_Z_bilin_aux de df hφ W_nhd x₀ y₁) with ⟨U₂, U₂_nhd, HU⟩, rcases (extend_Z_bilin_aux df de cont_flip W_nhd y₀ x₁) with ⟨V₂, V₂_nhd, HV⟩, existsi [U₁ ∩ U₂, inter_mem U₁_nhd U₂_nhd, V₁ ∩ V₂, inter_mem V₁_nhd V₂_nhd], rintros x ⟨xU₁, xU₂⟩ x' ⟨x'U₁, x'U₂⟩ y ⟨yV₁, yV₂⟩ y' ⟨y'V₁, y'V₂⟩, have key_formula : φ x' y' - φ x y = φ(x' - x) y₁ + φ (x' - x) (y' - y₁) + φ x₁ (y' - y) + φ (x - x₁) (y' - y), { simp, abel }, rw key_formula, have h₁ := HU x xU₂ x' x'U₂, have h₂ := H x xU₁ x' x'U₁ y₁ y₁_in y' y'V₁, have h₃ := HV y yV₂ y' y'V₂, have h₄ := H x₁ x₁_in x xU₁ y yV₁ y' y'V₁, exact W4 h₁ h₂ h₃ h₄ end omit W'_nhd open dense_inducing /-- Bourbaki GT III.6.5 Theorem I: ℤ-bilinear continuous maps from dense images into a complete Hausdorff group extend by continuity. Note: Bourbaki assumes that α and β are also complete Hausdorff, but this is not necessary. -/ theorem extend_Z_bilin : continuous (extend (de.prod df) Φ) := begin refine continuous_extend_of_cauchy _ _, rintro ⟨x₀, y₀⟩, split, { apply ne_bot.map, apply comap_ne_bot, intros U h, rcases mem_closure_iff_nhds.1 ((de.prod df).dense (x₀, y₀)) U h with ⟨x, x_in, ⟨z, z_x⟩⟩, existsi z, cc }, { suffices : map (λ (p : (β × δ) × (β × δ)), Φ p.2 - Φ p.1) (comap (λ (p : (β × δ) × β × δ), ((e p.1.1, f p.1.2), (e p.2.1, f p.2.2))) (𝓝 (x₀, y₀) ×ᶠ 𝓝 (x₀, y₀))) ≤ 𝓝 0, by rwa [uniformity_eq_comap_nhds_zero G, prod_map_map_eq, ←map_le_iff_le_comap, filter.map_map, prod_comap_comap_eq], intros W' W'_nhd, have key := extend_Z_bilin_key de df hφ W'_nhd x₀ y₀, rcases key with ⟨U, U_nhd, V, V_nhd, h⟩, rw mem_comap at U_nhd, rcases U_nhd with ⟨U', U'_nhd, U'_sub⟩, rw mem_comap at V_nhd, rcases V_nhd with ⟨V', V'_nhd, V'_sub⟩, rw [mem_map, mem_comap, nhds_prod_eq], existsi (U' ×ˢ V') ×ˢ (U' ×ˢ V'), rw mem_prod_same_iff, simp only [exists_prop], split, { change U' ∈ 𝓝 x₀ at U'_nhd, change V' ∈ 𝓝 y₀ at V'_nhd, have := prod_mem_prod U'_nhd V'_nhd, tauto }, { intros p h', simp only [set.mem_preimage, set.prod_mk_mem_set_prod_eq] at h', rcases p with ⟨⟨x, y⟩, ⟨x', y'⟩⟩, apply h ; tauto } } end end dense_inducing
e2aa0c2a84e08769b87047e78e80c2486c54aee4
d123c25a3db52270abe622eca989f9be39b4fd4e
/test.lean
4d81475f97038acebb1c1a5a730badcfd7f9a363
[]
no_license
mwpb/leanCT
248da6bf0f0088b3ac1cc4c0e8c70ac7e00b6a1a
1813106178780680b4214dd895c631f2ce9932a4
refs/heads/master
1,610,827,463,815
1,502,651,067,000
1,502,651,067,000
100,198,392
0
0
null
null
null
null
UTF-8
Lean
false
false
858
lean
open string constant category: Type constant object: Π C: category, Type constant hom: Π {C: category}, object C -> object C -> Type constant comp: Π {C: category} {a b c: object C}, hom a b → hom b c → hom a c constant e: Π {C: category} x:object C, hom x x infix * := comp constant leftId: Π {C: category} (x y: object C) (f: hom x y), e x * f = f constant rightId: Π {C: category} (x y: object C) (f: hom x y), f * e y = f variable C:category variable x:object C variable y:object C variable z:object C variable f:hom x y variable g:hom y z variable h:hom y z #check leftId #check f*g #check e #check f*(e y) constant left_intro : Π {C: category} {x y z: object C} {f:hom x y} {g h : hom y z}, g=h → f*g = f*h #check left_intro variable Hcd : g=h theorem trivia: f*g = f*h := calc f*g = f*h : left_intro Hcd #check trivia
025879ed321a45a6d5d0f5cac4fb94b81ad5ace0
02005f45e00c7ecf2c8ca5db60251bd1e9c860b5
/src/data/mv_polynomial/monad.lean
c0cb532b70256768b92d1f1fda13c13371a72e5d
[ "Apache-2.0" ]
permissive
anthony2698/mathlib
03cd69fe5c280b0916f6df2d07c614c8e1efe890
407615e05814e98b24b2ff322b14e8e3eb5e5d67
refs/heads/master
1,678,792,774,873
1,614,371,563,000
1,614,371,563,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,436
lean
/- Copyright (c) 2020 Johan Commelin and Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin and Robert Y. Lewis -/ import data.mv_polynomial.rename /-! # Monad operations on `mv_polynomial` This file defines two monadic operations on `mv_polynomial`. Given `p : mv_polynomial σ R`, * `mv_polynomial.bind₁` and `mv_polynomial.join₁` operate on the variable type `σ`. * `mv_polynomial.bind₂` and `mv_polynomial.join₂` operate on the coefficient type `R`. - `mv_polynomial.bind₁ f φ` with `f : σ → mv_polynomial τ R` and `φ : mv_polynomial σ R`, is the polynomial `φ(f 1, ..., f i, ...) : mv_polynomial τ R`. - `mv_polynomial.join₁ φ` with `φ : mv_polynomial (mv_polynomial σ R) R` collapses `φ` to a `mv_polynomial σ R`, by evaluating `φ` under the map `X f ↦ f` for `f : mv_polynomial σ R`. In other words, if you have a polynomial `φ` in a set of variables indexed by a polynomial ring, you evaluate the polynomial in these indexing polynomials. - `mv_polynomial.bind₂ f φ` with `f : R →+* mv_polynomial σ S` and `φ : mv_polynomial σ R` is the `mv_polynomial σ S` obtained from `φ` by mapping the coefficients of `φ` through `f` and considering the resulting polynomial as polynomial expression in `mv_polynomial σ R`. - `mv_polynomial.join₂ φ` with `φ : mv_polynomial σ (mv_polynomial σ R)` collapses `φ` to a `mv_polynomial σ R`, by considering `φ` as polynomial expression in `mv_polynomial σ R`. These operations themselves have algebraic structure: `mv_polynomial.bind₁` and `mv_polynomial.join₁` are algebra homs and `mv_polynomial.bind₂` and `mv_polynomial.join₂` are ring homs. They interact in convenient ways with `mv_polynomial.rename`, `mv_polynomial.map`, `mv_polynomial.vars`, and other polynomial operations. Indeed, `mv_polynomial.rename` is the "map" operation for the (`bind₁`, `join₁`) pair, whereas `mv_polynomial.map` is the "map" operation for the other pair. ## Implementation notes We add an `is_lawful_monad` instance for the (`bind₁`, `join₁`) pair. The second pair cannot be instantiated as a `monad`, since it is not a monad in `Type` but in `CommRing` (or rather `CommSemiRing`). -/ open_locale big_operators noncomputable theory namespace mv_polynomial open finsupp variables {σ : Type*} {τ : Type*} variables {R S T : Type*} [comm_semiring R] [comm_semiring S] [comm_semiring T] /-- `bind₁` is the "left hand side" bind operation on `mv_polynomial`, operating on the variable type. Given a polynomial `p : mv_polynomial σ R` and a map `f : σ → mv_polynomial τ R` taking variables in `p` to polynomials in the variable type `τ`, `bind₁ f p` replaces each variable in `p` with its value under `f`, producing a new polynomial in `τ`. The coefficient type remains the same. This operation is an algebra hom. -/ def bind₁ (f : σ → mv_polynomial τ R) : mv_polynomial σ R →ₐ[R] mv_polynomial τ R := aeval f /-- `bind₂` is the "right hand side" bind operation on `mv_polynomial`, operating on the coefficient type. Given a polynomial `p : mv_polynomial σ R` and a map `f : R → mv_polynomial σ S` taking coefficients in `p` to polynomials over a new ring `S`, `bind₂ f p` replaces each coefficient in `p` with its value under `f`, producing a new polynomial over `S`. The variable type remains the same. This operation is a ring hom. -/ def bind₂ (f : R →+* mv_polynomial σ S) : mv_polynomial σ R →+* mv_polynomial σ S := eval₂_hom f X /-- `join₁` is the monadic join operation corresponding to `mv_polynomial.bind₁`. Given a polynomial `p` with coefficients in `R` whose variables are polynomials in `σ` with coefficients in `R`, `join₁ p` collapses `p` to a polynomial with variables in `σ` and coefficients in `R`. This operation is an algebra hom. -/ def join₁ : mv_polynomial (mv_polynomial σ R) R →ₐ[R] mv_polynomial σ R := aeval id /-- `join₂` is the monadic join operation corresponding to `mv_polynomial.bind₂`. Given a polynomial `p` with variables in `σ` whose coefficients are polynomials in `σ` with coefficients in `R`, `join₂ p` collapses `p` to a polynomial with variables in `σ` and coefficients in `R`. This operation is a ring hom. -/ def join₂ : mv_polynomial σ (mv_polynomial σ R) →+* mv_polynomial σ R := eval₂_hom (ring_hom.id _) X @[simp] lemma aeval_eq_bind₁ (f : σ → mv_polynomial τ R) : aeval f = bind₁ f := rfl @[simp] lemma eval₂_hom_C_eq_bind₁ (f : σ → mv_polynomial τ R) : eval₂_hom C f = bind₁ f := rfl @[simp] lemma eval₂_hom_eq_bind₂ (f : R →+* mv_polynomial σ S) : eval₂_hom f X = bind₂ f := rfl section variables (σ R) @[simp] lemma aeval_id_eq_join₁ : aeval id = @join₁ σ R _ := rfl lemma eval₂_hom_C_id_eq_join₁ (φ : mv_polynomial (mv_polynomial σ R) R) : eval₂_hom C id φ = join₁ φ := rfl @[simp] lemma eval₂_hom_id_X_eq_join₂ : eval₂_hom (ring_hom.id _) X = @join₂ σ R _ := rfl end -- In this file, we don't want to use these simp lemmas, -- because we first need to show how these new definitions interact -- and the proofs fall back on unfolding the definitions and call simp afterwards local attribute [-simp] aeval_eq_bind₁ eval₂_hom_C_eq_bind₁ eval₂_hom_eq_bind₂ aeval_id_eq_join₁ eval₂_hom_id_X_eq_join₂ @[simp] lemma bind₁_X_right (f : σ → mv_polynomial τ R) (i : σ) : bind₁ f (X i) = f i := aeval_X f i @[simp] lemma bind₂_X_right (f : R →+* mv_polynomial σ S) (i : σ) : bind₂ f (X i) = X i := eval₂_hom_X' f X i @[simp] lemma bind₁_X_left : bind₁ (X : σ → mv_polynomial σ R) = alg_hom.id R _ := by { ext1 i, simp } lemma aeval_X_left : aeval (X : σ → mv_polynomial σ R) = alg_hom.id R _ := by rw [aeval_eq_bind₁, bind₁_X_left] lemma aeval_X_left_apply (φ : mv_polynomial σ R) : aeval X φ = φ := by rw [aeval_eq_bind₁, bind₁_X_left, alg_hom.id_apply] variable (f : σ → mv_polynomial τ R) @[simp] lemma bind₁_C_right (f : σ → mv_polynomial τ R) (x) : bind₁ f (C x) = C x := by simp [bind₁, C, aeval_monomial, finsupp.prod_zero_index]; refl @[simp] lemma bind₂_C_right (f : R →+* mv_polynomial σ S) (r : R) : bind₂ f (C r) = f r := eval₂_hom_C f X r @[simp] lemma bind₂_C_left : bind₂ (C : R →+* mv_polynomial σ R) = ring_hom.id _ := by { ext1; simp } @[simp] lemma bind₂_comp_C (f : R →+* mv_polynomial σ S) : (bind₂ f).comp C = f := ring_hom.ext $ bind₂_C_right _ @[simp] lemma join₂_map (f : R →+* mv_polynomial σ S) (φ : mv_polynomial σ R) : join₂ (map f φ) = bind₂ f φ := by simp only [join₂, bind₂, eval₂_hom_map_hom, ring_hom.id_comp] @[simp] lemma join₂_comp_map (f : R →+* mv_polynomial σ S) : join₂.comp (map f) = bind₂ f := ring_hom.ext $ join₂_map _ lemma aeval_id_rename (f : σ → mv_polynomial τ R) (p : mv_polynomial σ R) : aeval id (rename f p) = aeval f p := by rw [aeval_rename, function.comp.left_id] @[simp] lemma join₁_rename (f : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : join₁ (rename f φ) = bind₁ f φ := aeval_id_rename _ _ @[simp] lemma bind₁_id : bind₁ (@id (mv_polynomial σ R)) = join₁ := rfl @[simp] lemma bind₂_id : bind₂ (ring_hom.id (mv_polynomial σ R)) = join₂ := rfl lemma bind₁_bind₁ {υ : Type*} (f : σ → mv_polynomial τ R) (g : τ → mv_polynomial υ R) (φ : mv_polynomial σ R) : (bind₁ g) (bind₁ f φ) = bind₁ (λ i, bind₁ g (f i)) φ := by simp [bind₁, ← comp_aeval] lemma bind₁_comp_bind₁ {υ : Type*} (f : σ → mv_polynomial τ R) (g : τ → mv_polynomial υ R) : (bind₁ g).comp (bind₁ f) = bind₁ (λ i, bind₁ g (f i)) := by { ext1, apply bind₁_bind₁ } lemma bind₂_comp_bind₂ (f : R →+* mv_polynomial σ S) (g : S →+* mv_polynomial σ T) : (bind₂ g).comp (bind₂ f) = bind₂ ((bind₂ g).comp f) := by { ext1; simp } lemma bind₂_bind₂ (f : R →+* mv_polynomial σ S) (g : S →+* mv_polynomial σ T) (φ : mv_polynomial σ R) : (bind₂ g) (bind₂ f φ) = bind₂ ((bind₂ g).comp f) φ := ring_hom.congr_fun (bind₂_comp_bind₂ f g) φ lemma rename_comp_bind₁ {υ : Type*} (f : σ → mv_polynomial τ R) (g : τ → υ) : (rename g).comp (bind₁ f) = bind₁ (λ i, rename g $ f i) := by { ext1 i, simp } lemma rename_bind₁ {υ : Type*} (f : σ → mv_polynomial τ R) (g : τ → υ) (φ : mv_polynomial σ R) : rename g (bind₁ f φ) = bind₁ (λ i, rename g $ f i) φ := alg_hom.congr_fun (rename_comp_bind₁ f g) φ lemma map_bind₂ (f : R →+* mv_polynomial σ S) (g : S →+* T) (φ : mv_polynomial σ R) : map g (bind₂ f φ) = bind₂ ((map g).comp f) φ := begin simp only [bind₂, eval₂_comp_right, coe_eval₂_hom, eval₂_map], congr' 1 with : 1, simp only [function.comp_app, map_X] end lemma bind₁_comp_rename {υ : Type*} (f : τ → mv_polynomial υ R) (g : σ → τ) : (bind₁ f).comp (rename g) = bind₁ (f ∘ g) := by { ext1 i, simp } lemma bind₁_rename {υ : Type*} (f : τ → mv_polynomial υ R) (g : σ → τ) (φ : mv_polynomial σ R) : bind₁ f (rename g φ) = bind₁ (f ∘ g) φ := alg_hom.congr_fun (bind₁_comp_rename f g) φ lemma bind₂_map (f : S →+* mv_polynomial σ T) (g : R →+* S) (φ : mv_polynomial σ R) : bind₂ f (map g φ) = bind₂ (f.comp g) φ := by simp [bind₂] @[simp] lemma map_comp_C (f : R →+* S) : (map f).comp (C : R →+* mv_polynomial σ R) = C.comp f := by { ext1, apply map_C } -- mixing the two monad structures lemma hom_bind₁ (f : mv_polynomial τ R →+* S) (g : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : f (bind₁ g φ) = eval₂_hom (f.comp C) (λ i, f (g i)) φ := by rw [bind₁, map_aeval, algebra_map_eq] lemma map_bind₁ (f : R →+* S) (g : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : map f (bind₁ g φ) = bind₁ (λ (i : σ), (map f) (g i)) (map f φ) := by { rw [hom_bind₁, map_comp_C, ← eval₂_hom_map_hom], refl } @[simp] lemma eval₂_hom_comp_C (f : R →+* S) (g : σ → S) : (eval₂_hom f g).comp C = f := by { ext1 r, exact eval₂_C f g r } lemma eval₂_hom_bind₁ (f : R →+* S) (g : τ → S) (h : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : eval₂_hom f g (bind₁ h φ) = eval₂_hom f (λ i, eval₂_hom f g (h i)) φ := by rw [hom_bind₁, eval₂_hom_comp_C] lemma aeval_bind₁ [algebra R S] (f : τ → S) (g : σ → mv_polynomial τ R) (φ : mv_polynomial σ R) : aeval f (bind₁ g φ) = aeval (λ i, aeval f (g i)) φ := eval₂_hom_bind₁ _ _ _ _ lemma aeval_comp_bind₁ [algebra R S] (f : τ → S) (g : σ → mv_polynomial τ R) : (aeval f).comp (bind₁ g) = aeval (λ i, aeval f (g i)) := by { ext1, apply aeval_bind₁ } lemma eval₂_hom_comp_bind₂ (f : S →+* T) (g : σ → T) (h : R →+* mv_polynomial σ S) : (eval₂_hom f g).comp (bind₂ h) = eval₂_hom ((eval₂_hom f g).comp h) g := by { ext1; simp } lemma eval₂_hom_bind₂ (f : S →+* T) (g : σ → T) (h : R →+* mv_polynomial σ S) (φ : mv_polynomial σ R) : eval₂_hom f g (bind₂ h φ) = eval₂_hom ((eval₂_hom f g).comp h) g φ := ring_hom.congr_fun (eval₂_hom_comp_bind₂ f g h) φ lemma aeval_bind₂ [algebra S T] (f : σ → T) (g : R →+* mv_polynomial σ S) (φ : mv_polynomial σ R) : aeval f (bind₂ g φ) = eval₂_hom ((@aeval S T σ _ f _ _ : mv_polynomial σ S →+* T).comp g) f φ := eval₂_hom_bind₂ _ _ _ _ lemma eval₂_hom_C_left (f : σ → mv_polynomial τ R) : eval₂_hom C f = bind₁ f := rfl lemma bind₁_monomial (f : σ → mv_polynomial τ R) (d : σ →₀ ℕ) (r : R) : bind₁ f (monomial d r) = C r * ∏ i in d.support, f i ^ d i := by simp only [monomial_eq, alg_hom.map_mul, bind₁_C_right, finsupp.prod, alg_hom.map_prod, alg_hom.map_pow, bind₁_X_right] lemma bind₂_monomial (f : R →+* mv_polynomial σ S) (d : σ →₀ ℕ) (r : R) : bind₂ f (monomial d r) = f r * monomial d 1 := by simp only [monomial_eq, ring_hom.map_mul, bind₂_C_right, finsupp.prod, ring_hom.map_prod, ring_hom.map_pow, bind₂_X_right, C_1, one_mul] @[simp] lemma bind₂_monomial_one (f : R →+* mv_polynomial σ S) (d : σ →₀ ℕ) : bind₂ f (monomial d 1) = monomial d 1 := by rw [bind₂_monomial, f.map_one, one_mul] instance monad : monad (λ σ, mv_polynomial σ R) := { map := λ α β f p, rename f p, pure := λ _, X, bind := λ _ _ p f, bind₁ f p } instance is_lawful_functor : is_lawful_functor (λ σ, mv_polynomial σ R) := { id_map := by intros; simp [(<$>)], comp_map := by intros; simp [(<$>)] } instance is_lawful_monad : is_lawful_monad (λ σ, mv_polynomial σ R) := { pure_bind := by intros; simp [pure, bind], bind_assoc := by intros; simp [bind, ← bind₁_comp_bind₁] } /- Possible TODO for the future: Enable the following definitions, and write a lot of supporting lemmas. def bind (f : R →+* mv_polynomial τ S) (g : σ → mv_polynomial τ S) : mv_polynomial σ R →+* mv_polynomial τ S := eval₂_hom f g def join (f : R →+* S) : mv_polynomial (mv_polynomial σ R) S →ₐ[S] mv_polynomial σ S := aeval (map f) def ajoin [algebra R S] : mv_polynomial (mv_polynomial σ R) S →ₐ[S] mv_polynomial σ S := join (algebra_map R S) -/ end mv_polynomial
24f6e62e1d43bf033aef8d56c4295be614b285ca
3dd1b66af77106badae6edb1c4dea91a146ead30
/library/standard/bool.lean
12ea0188fb58317b7697ed3c50eba029d3ff4a1c
[ "Apache-2.0" ]
permissive
silky/lean
79c20c15c93feef47bb659a2cc139b26f3614642
df8b88dca2f8da1a422cb618cd476ef5be730546
refs/heads/master
1,610,737,587,697
1,406,574,534,000
1,406,574,534,000
22,362,176
1
0
null
null
null
null
UTF-8
Lean
false
false
4,438
lean
-- Copyright (c) 2014 Microsoft Corporation. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Author: Leonardo de Moura import logic decidable using eq_proofs decidable namespace bool inductive bool : Type := | b0 : bool | b1 : bool notation `'0`:max := b0 notation `'1`:max := b1 theorem induction_on {p : bool → Prop} (b : bool) (H0 : p '0) (H1 : p '1) : p b := bool_rec H0 H1 b theorem inhabited_bool [instance] : inhabited bool := inhabited_intro b0 definition cond {A : Type} (b : bool) (t e : A) := bool_rec e t b theorem dichotomy (b : bool) : b = '0 ∨ b = '1 := induction_on b (or_inl (refl '0)) (or_inr (refl '1)) theorem cond_b0 {A : Type} (t e : A) : cond '0 t e = e := refl (cond '0 t e) theorem cond_b1 {A : Type} (t e : A) : cond '1 t e = t := refl (cond '1 t e) theorem b0_ne_b1 : ¬ '0 = '1 := assume H : '0 = '1, absurd (calc true = cond '1 true false : (cond_b1 _ _)⁻¹ ... = cond '0 true false : {H⁻¹} ... = false : cond_b0 _ _) true_ne_false theorem decidable_eq [instance] (a b : bool) : decidable (a = b) := bool_rec (bool_rec (inl (refl '0)) (inr b0_ne_b1) b) (bool_rec (inr (ne_symm b0_ne_b1)) (inl (refl '1)) b) a definition bor (a b : bool) := bool_rec (bool_rec '0 '1 b) '1 a theorem bor_b1_left (a : bool) : bor '1 a = '1 := refl (bor '1 a) infixl `||`:65 := bor theorem bor_b1_right (a : bool) : a || '1 = '1 := induction_on a (refl ('0 || '1)) (refl ('1 || '1)) theorem bor_b0_left (a : bool) : '0 || a = a := induction_on a (refl ('0 || '0)) (refl ('0 || '1)) theorem bor_b0_right (a : bool) : a || '0 = a := induction_on a (refl ('0 || '0)) (refl ('1 || '0)) theorem bor_id (a : bool) : a || a = a := induction_on a (refl ('0 || '0)) (refl ('1 || '1)) theorem bor_comm (a b : bool) : a || b = b || a := induction_on a (induction_on b (refl ('0 || '0)) (refl ('0 || '1))) (induction_on b (refl ('1 || '0)) (refl ('1 || '1))) theorem bor_assoc (a b c : bool) : (a || b) || c = a || (b || c) := induction_on a (calc ('0 || b) || c = b || c : {bor_b0_left b} ... = '0 || (b || c) : bor_b0_left (b || c)⁻¹) (calc ('1 || b) || c = '1 || c : {bor_b1_left b} ... = '1 : bor_b1_left c ... = '1 || (b || c) : bor_b1_left (b || c)⁻¹) theorem bor_to_or {a b : bool} : a || b = '1 → a = '1 ∨ b = '1 := bool_rec (assume H : '0 || b = '1, have Hb : b = '1, from (bor_b0_left b) ▸ H, or_inr Hb) (assume H, or_inl (refl '1)) a definition band (a b : bool) := bool_rec '0 (bool_rec '0 '1 b) a infixl `&&`:75 := band theorem band_b0_left (a : bool) : '0 && a = '0 := refl ('0 && a) theorem band_b1_left (a : bool) : '1 && a = a := induction_on a (refl ('1 && '0)) (refl ('1 && '1)) theorem band_b0_right (a : bool) : a && '0 = '0 := induction_on a (refl ('0 && '0)) (refl ('1 && '0)) theorem band_b1_right (a : bool) : a && '1 = a := induction_on a (refl ('0 && '1)) (refl ('1 && '1)) theorem band_id (a : bool) : a && a = a := induction_on a (refl ('0 && '0)) (refl ('1 && '1)) theorem band_comm (a b : bool) : a && b = b && a := induction_on a (induction_on b (refl ('0 && '0)) (refl ('0 && '1))) (induction_on b (refl ('1 && '0)) (refl ('1 && '1))) theorem band_assoc (a b c : bool) : (a && b) && c = a && (b && c) := induction_on a (calc ('0 && b) && c = '0 && c : {band_b0_left b} ... = '0 : band_b0_left c ... = '0 && (b && c) : band_b0_left (b && c)⁻¹) (calc ('1 && b) && c = b && c : {band_b1_left b} ... = '1 && (b && c) : band_b1_left (b && c)⁻¹) theorem band_eq_b1_elim_left {a b : bool} (H : a && b = '1) : a = '1 := or_elim (dichotomy a) (assume H0 : a = '0, absurd_elim (a = '1) (calc '0 = '0 && b : (band_b0_left _)⁻¹ ... = a && b : {H0⁻¹} ... = '1 : H) b0_ne_b1) (assume H1 : a = '1, H1) theorem band_eq_b1_elim_right {a b : bool} (H : a && b = '1) : b = '1 := band_eq_b1_elim_left (trans (band_comm b a) H) definition bnot (a : bool) := bool_rec '1 '0 a prefix `!`:85 := bnot theorem bnot_bnot (a : bool) : !!a = a := induction_on a (refl (!!'0)) (refl (!!'1)) theorem bnot_false : !'0 = '1 := refl _ theorem bnot_true : !'1 = '0 := refl _
9c34255c9cf1e8c456570c2c0bf85433f6980286
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/wlog.lean
f93d507f48a514b4cc2b9012a14c25af51b1034e
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
1,098
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Johan Commelin -/ import tactic.wlog section wlog example {x y : ℕ} : true := begin wlog h : x ≤ y, { guard_hyp h : ¬x ≤ y, guard_hyp this : ∀ {x y : ℕ}, x ≤ y → true, -- `wlog` generalizes by default guard_target true, trivial }, { guard_hyp h : x ≤ y, guard_target true, trivial }, end example {x y : ℕ} : true := begin wlog h : x ≤ y generalizing x, { guard_hyp h : ¬x ≤ y, guard_hyp this : ∀ {x : ℕ}, x ≤ y → true, -- only `x` was generalized guard_target true, trivial }, { guard_hyp h : x ≤ y, guard_target true, trivial }, end example {x y z : ℕ} : true := begin wlog h : x ≤ y + z with H, { guard_hyp h : ¬ x ≤ y + z, guard_hyp H : ∀ {x y z : ℕ}, x ≤ y + z → true, -- wlog-claim is named `H` instead of `this` guard_target true, trivial }, { guard_hyp h : x ≤ y + z, guard_target true, trivial }, end end wlog
603b715a2c48bd3c5458d01cbfa8ddf020b0bf6a
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/dedekind_domain/basic.lean
7a4715fa81bafe756eac339ba925acc1f333ff56
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,934
lean
/- Copyright (c) 2020 Kenji Nakagawa. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenji Nakagawa, Anne Baanen, Filippo A. E. Nuccio -/ import ring_theory.ideal.over import ring_theory.polynomial.rational_root /-! # Dedekind domains > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the notion of a Dedekind domain (or Dedekind ring), as a Noetherian integrally closed commutative ring of Krull dimension at most one. ## Main definitions - `is_dedekind_domain` defines a Dedekind domain as a commutative ring that is Noetherian, integrally closed in its field of fractions and has Krull dimension at most one. `is_dedekind_domain_iff` shows that this does not depend on the choice of field of fractions. ## Implementation notes The definitions that involve a field of fractions choose a canonical field of fractions, but are independent of that choice. The `..._iff` lemmas express this independence. Often, definitions assume that Dedekind domains are not fields. We found it more practical to add a `(h : ¬ is_field A)` assumption whenever this is explicitly needed. ## References * [D. Marcus, *Number Fields*][marcus1977number] * [J.W.S. Cassels, A. Frölich, *Algebraic Number Theory*][cassels1967algebraic] * [J. Neukirch, *Algebraic Number Theory*][Neukirch1992] ## Tags dedekind domain, dedekind ring -/ variables (R A K : Type*) [comm_ring R] [comm_ring A] [field K] open_locale non_zero_divisors polynomial /-- A ring `R` has Krull dimension at most one if all nonzero prime ideals are maximal. -/ def ring.dimension_le_one : Prop := ∀ p ≠ (⊥ : ideal R), p.is_prime → p.is_maximal open ideal ring namespace ring lemma dimension_le_one.principal_ideal_ring [is_domain A] [is_principal_ideal_ring A] : dimension_le_one A := λ p nonzero prime, by { haveI := prime, exact is_prime.to_maximal_ideal nonzero } lemma dimension_le_one.is_integral_closure (B : Type*) [comm_ring B] [is_domain B] [nontrivial R] [algebra R A] [algebra R B] [algebra B A] [is_scalar_tower R B A] [is_integral_closure B R A] (h : dimension_le_one R) : dimension_le_one B := λ p ne_bot prime, by exactI is_integral_closure.is_maximal_of_is_maximal_comap A p (h _ (is_integral_closure.comap_ne_bot A ne_bot) infer_instance) lemma dimension_le_one.integral_closure [nontrivial R] [is_domain A] [algebra R A] (h : dimension_le_one R) : dimension_le_one (integral_closure R A) := h.is_integral_closure R A (integral_closure R A) variables {R} lemma dimension_le_one.not_lt_lt (h : ring.dimension_le_one R) (p₀ p₁ p₂ : ideal R) [hp₁ : p₁.is_prime] [hp₂ : p₂.is_prime] : ¬ (p₀ < p₁ ∧ p₁ < p₂) | ⟨h01, h12⟩ := h12.ne ((h p₁ (bot_le.trans_lt h01).ne' hp₁).eq_of_le hp₂.ne_top h12.le) lemma dimension_le_one.eq_bot_of_lt (h : ring.dimension_le_one R) (p P : ideal R) [hp : p.is_prime] [hP : P.is_prime] (hpP : p < P) : p = ⊥ := by_contra (λ hp0, h.not_lt_lt ⊥ p P ⟨ne.bot_lt hp0, hpP⟩) end ring variables [is_domain A] /-- A Dedekind domain is an integral domain that is Noetherian, integrally closed, and has Krull dimension at most one. This is definition 3.2 of [Neukirch1992]. The integral closure condition is independent of the choice of field of fractions: use `is_dedekind_domain_iff` to prove `is_dedekind_domain` for a given `fraction_map`. This is the default implementation, but there are equivalent definitions, `is_dedekind_domain_dvr` and `is_dedekind_domain_inv`. TODO: Prove that these are actually equivalent definitions. -/ class is_dedekind_domain : Prop := (is_noetherian_ring : is_noetherian_ring A) (dimension_le_one : dimension_le_one A) (is_integrally_closed : is_integrally_closed A) -- See library note [lower instance priority] attribute [instance, priority 100] is_dedekind_domain.is_noetherian_ring is_dedekind_domain.is_integrally_closed /-- An integral domain is a Dedekind domain iff and only if it is Noetherian, has dimension ≤ 1, and is integrally closed in a given fraction field. In particular, this definition does not depend on the choice of this fraction field. -/ lemma is_dedekind_domain_iff (K : Type*) [field K] [algebra A K] [is_fraction_ring A K] : is_dedekind_domain A ↔ is_noetherian_ring A ∧ dimension_le_one A ∧ (∀ {x : K}, is_integral A x → ∃ y, algebra_map A K y = x) := ⟨λ ⟨hr, hd, hi⟩, ⟨hr, hd, λ x, (is_integrally_closed_iff K).mp hi⟩, λ ⟨hr, hd, hi⟩, ⟨hr, hd, (is_integrally_closed_iff K).mpr @hi⟩⟩ @[priority 100] -- See library note [lower instance priority] instance is_principal_ideal_ring.is_dedekind_domain [is_principal_ideal_ring A] : is_dedekind_domain A := ⟨principal_ideal_ring.is_noetherian_ring, ring.dimension_le_one.principal_ideal_ring A, unique_factorization_monoid.is_integrally_closed⟩
6ddbef88d387d267491fa41ee946d23cf3ca862e
0d2e44896897eda703992595d71a0b19ed30b8a1
/uexp/src/uexp/u_semiring.lean
749e0eecb0d39fb1331ed6dd7b3447381e9f6292
[ "BSD-2-Clause" ]
permissive
wwombat/Cosette
a87312aabefdb53ea8b67c37731bd58c7485afb6
4c5dc6172e24d3546c9818ac1fad06f72fe1c991
refs/heads/master
1,619,479,568,051
1,520,292,502,000
1,520,292,502,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,997
lean
-- definition of u-semiring class denotation (A: Type) (B:Type) := (denote : A → B) --def denote {A B: Type} [denotation A B] : A → B := @denotation.denote constant datatype: Type inductive tree (A:Type) | node : tree → tree → tree | leaf : A → tree | empty {} : tree definition Schema := tree datatype constant denote : datatype → Type def Tuple : Schema → Type | (tree.node t0 t1) := (Tuple t0) × (Tuple t1) | (tree.leaf A) := denote A | tree.empty := unit constant usr : Type constant usr.one : usr constant usr.zero : usr constant usr.plus : usr → usr → usr constant usr.time : usr → usr → usr constant usr.sig {s: Schema}: (Tuple s → usr) → usr constant usr.squash : usr → usr constant usr.not : usr → usr constant usr.ueq {s : Schema} : Tuple s → Tuple s → usr notation `∑` binders `, ` r:(scoped p, usr.sig p) := r notation `∥` u `∥` := usr.squash u noncomputable instance : has_append Schema := ⟨tree.node⟩ infix `≃`:50 := usr.ueq noncomputable instance usr_has_add : has_add usr := ⟨usr.plus⟩ noncomputable instance usr_has_mul : has_mul usr := ⟨usr.time⟩ noncomputable instance usr_has_zero : has_zero usr := ⟨usr.zero⟩ noncomputable instance usr_has_one : has_one usr := ⟨usr.one⟩ -- commutative semiring axioms @[simp] axiom plus_comm (a b : usr) : a + b = b + a @[simp] axiom plus_zero (a : usr) : a + 0 = a @[simp] axiom plus_assoc (a b c : usr) : a + b + c = a + (b + c) @[simp] axiom time_comm (a b : usr) : a * b = b * a @[simp] axiom time_assoc (a b c : usr) : a * b * c = a * (b * c) @[simp] axiom time_distrib_l (a b c : usr) : a * (b + c) = a * b + a * c @[simp] axiom time_distrib_r (a b c : usr) : (a + b) * c = a * c + b * c @[simp] axiom time_zero (a : usr): a * 0 = 0 @[simp] axiom time_one (a : usr): a * 1 = a noncomputable instance : comm_semiring usr := { add_assoc := plus_assoc, add_zero := plus_zero, zero_add := by intros; rw plus_comm; simp, add_comm := plus_comm, mul_assoc := time_assoc, mul_one := time_one, one_mul := by intros; rw time_comm; simp, left_distrib := time_distrib_l, right_distrib := time_distrib_r, mul_zero := time_zero, zero_mul := by intros; rw time_comm; simp, mul_comm := time_comm, ..usr_has_add, ..usr_has_mul, ..usr_has_zero, ..usr_has_one } @[simp] axiom sig_distr_plus {s : Schema} (f₁ f₂ : Tuple s → usr) : (∑ t, f₁ t + f₂ t) = (∑ t, f₁ t) + (∑ t, f₂ t) @[simp] axiom sig_commute {s t: Schema} (f: Tuple s → Tuple t → usr): (∑ t₁ t₂, f t₁ t₂) = (∑ t₂ t₁, f t₁ t₂) @[simp] axiom sig_distr_time {s : Schema} (a: usr) (f: Tuple s → usr): (∑ t, a * (f t)) = a * (∑ t, f t) @[simp] axiom squash_zero : usr.squash 0 = 0 @[simp] axiom squash_one : usr.squash 1 = 1 @[simp] axiom squash_add_squash (x y : usr) : ∥ ∥ x ∥ + y ∥ = ∥ x + y ∥ @[simp] axiom squash_time (x y : usr) : ∥ x ∥ * ∥ y ∥ = ∥ x * y ∥ @[simp] axiom squash_squared (x : usr) : ∥ x ∥ * ∥ x ∥ = ∥ x ∥ @[simp] axiom squash_eq_if_square_eq (x : usr) : x * x = x → ∥ x ∥ = x @[simp] axiom not_zero : usr.not 0 = 1 @[simp] axiom not_time (x y : usr) : usr.not (x * y) = ∥ usr.not x + usr.not y ∥ @[simp] axiom not_plus (x y : usr) : usr.not (x + y) = usr.not x * usr.not y @[simp] axiom not_squash (x : usr) : usr.not ∥ x ∥ = ∥ usr.not x ∥ @[simp] axiom squash_not (x : usr) : ∥ usr.not x ∥ = usr.not x -- axioms about predicates @[simp] axiom eq_subst_l {s: Schema} (t₁ t₂: Tuple s) (R: Tuple s → usr): (t₁ ≃ t₂) * (R t₁) = (t₁ ≃ t₂) * (R t₂) @[simp] axiom eq_subst_r {s: Schema} (t₁ t₂: Tuple s) (R: Tuple s → usr): (R t₁) *(t₁ ≃ t₂) = (R t₂) * (t₁ ≃ t₂) @[simp] axiom em {s: Schema} (t₁ t₂ : Tuple s) : (t₁ ≃ t₂) + usr.not (t₁ ≃ t₂) = 1 @[simp] axiom eq_unique {s: Schema} (t' : Tuple s) : (∑ t, t ≃ t') = 1
6d0712afd8c21a01d5323f14604558086e1122e4
9dc8cecdf3c4634764a18254e94d43da07142918
/src/measure_theory/measure/haar_lebesgue.lean
b42d1140e8211bd6a2a6b7f60e1bd15067d4ed04
[ "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
40,225
lean
/- Copyright (c) 2021 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Sébastien Gouëzel -/ import measure_theory.measure.lebesgue import measure_theory.measure.haar import linear_algebra.finite_dimensional import analysis.normed_space.pointwise import measure_theory.group.pointwise /-! # Relationship between the Haar and Lebesgue measures We prove that the Haar measure and Lebesgue measure are equal on `ℝ` and on `ℝ^ι`, in `measure_theory.add_haar_measure_eq_volume` and `measure_theory.add_haar_measure_eq_volume_pi`. We deduce basic properties of any Haar measure on a finite dimensional real vector space: * `map_linear_map_add_haar_eq_smul_add_haar`: a linear map rescales the Haar measure by the absolute value of its determinant. * `add_haar_preimage_linear_map` : when `f` is a linear map with nonzero determinant, the measure of `f ⁻¹' s` is the measure of `s` multiplied by the absolute value of the inverse of the determinant of `f`. * `add_haar_image_linear_map` : when `f` is a linear map, the measure of `f '' s` is the measure of `s` multiplied by the absolute value of the determinant of `f`. * `add_haar_submodule` : a strict submodule has measure `0`. * `add_haar_smul` : the measure of `r • s` is `|r| ^ dim * μ s`. * `add_haar_ball`: the measure of `ball x r` is `r ^ dim * μ (ball 0 1)`. * `add_haar_closed_ball`: the measure of `closed_ball x r` is `r ^ dim * μ (ball 0 1)`. * `add_haar_sphere`: spheres have zero measure. We also show that a Lebesgue density point `x` of a set `s` (with respect to closed balls) has density one for the rescaled copies `{x} + r • t` of a given set `t` with positive measure, in `tendsto_add_haar_inter_smul_one_of_density_one`. In particular, `s` intersects `{x} + r • t` for small `r`, see `eventually_nonempty_inter_smul_of_density_one`. -/ open topological_space set filter metric open_locale ennreal pointwise topological_space /-- The interval `[0,1]` as a compact set with non-empty interior. -/ def topological_space.positive_compacts.Icc01 : positive_compacts ℝ := { carrier := Icc 0 1, compact' := is_compact_Icc, interior_nonempty' := by simp_rw [interior_Icc, nonempty_Ioo, zero_lt_one] } universe u /-- The set `[0,1]^ι` as a compact set with non-empty interior. -/ def topological_space.positive_compacts.pi_Icc01 (ι : Type*) [fintype ι] : positive_compacts (ι → ℝ) := { carrier := pi univ (λ i, Icc 0 1), compact' := is_compact_univ_pi (λ i, is_compact_Icc), interior_nonempty' := by simp only [interior_pi_set, set.to_finite, interior_Icc, univ_pi_nonempty_iff, nonempty_Ioo, implies_true_iff, zero_lt_one] } namespace measure_theory open measure topological_space.positive_compacts finite_dimensional /-! ### The Lebesgue measure is a Haar measure on `ℝ` and on `ℝ^ι`. -/ /-- The Haar measure equals the Lebesgue measure on `ℝ`. -/ lemma add_haar_measure_eq_volume : add_haar_measure Icc01 = volume := by { convert (add_haar_measure_unique volume Icc01).symm, simp [Icc01] } instance : is_add_haar_measure (volume : measure ℝ) := by { rw ← add_haar_measure_eq_volume, apply_instance } /-- The Haar measure equals the Lebesgue measure on `ℝ^ι`. -/ lemma add_haar_measure_eq_volume_pi (ι : Type*) [fintype ι] : add_haar_measure (pi_Icc01 ι) = volume := begin convert (add_haar_measure_unique volume (pi_Icc01 ι)).symm, simp only [pi_Icc01, volume_pi_pi (λ i, Icc (0 : ℝ) 1), positive_compacts.coe_mk, compacts.coe_mk, finset.prod_const_one, ennreal.of_real_one, real.volume_Icc, one_smul, sub_zero], end instance is_add_haar_measure_volume_pi (ι : Type*) [fintype ι] : is_add_haar_measure (volume : measure (ι → ℝ)) := by { rw ← add_haar_measure_eq_volume_pi, apply_instance } namespace measure /-! ### Strict subspaces have zero measure -/ /-- If a set is disjoint of its translates by infinitely many bounded vectors, then it has measure zero. This auxiliary lemma proves this assuming additionally that the set is bounded. -/ lemma add_haar_eq_zero_of_disjoint_translates_aux {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [measurable_space E] [borel_space E] [finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ] {s : set E} (u : ℕ → E) (sb : bounded s) (hu : bounded (range u)) (hs : pairwise (disjoint on (λ n, {u n} + s))) (h's : measurable_set s) : μ s = 0 := begin by_contra h, apply lt_irrefl ∞, calc ∞ = ∑' (n : ℕ), μ s : (ennreal.tsum_const_eq_top_of_ne_zero h).symm ... = ∑' (n : ℕ), μ ({u n} + s) : by { congr' 1, ext1 n, simp only [image_add_left, measure_preimage_add, singleton_add] } ... = μ (⋃ n, {u n} + s) : by rw measure_Union hs (λ n, by simpa only [image_add_left, singleton_add] using measurable_id.const_add _ h's) ... = μ (range u + s) : by rw [← Union_add, Union_singleton_eq_range] ... < ∞ : bounded.measure_lt_top (hu.add sb) end /-- If a set is disjoint of its translates by infinitely many bounded vectors, then it has measure zero. -/ lemma add_haar_eq_zero_of_disjoint_translates {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [measurable_space E] [borel_space E] [finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ] {s : set E} (u : ℕ → E) (hu : bounded (range u)) (hs : pairwise (disjoint on (λ n, {u n} + s))) (h's : measurable_set s) : μ s = 0 := begin suffices H : ∀ R, μ (s ∩ closed_ball 0 R) = 0, { apply le_antisymm _ (zero_le _), calc μ s ≤ ∑' (n : ℕ), μ (s ∩ closed_ball 0 n) : by { conv_lhs { rw ← Union_inter_closed_ball_nat s 0 }, exact measure_Union_le _ } ... = 0 : by simp only [H, tsum_zero] }, assume R, apply add_haar_eq_zero_of_disjoint_translates_aux μ u (bounded.mono (inter_subset_right _ _) bounded_closed_ball) hu _ (h's.inter (measurable_set_closed_ball)), apply pairwise_disjoint.mono hs (λ n, _), exact add_subset_add (subset.refl _) (inter_subset_left _ _) end /-- A strict vector subspace has measure zero. -/ lemma add_haar_submodule {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [measurable_space E] [borel_space E] [finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ] (s : submodule ℝ E) (hs : s ≠ ⊤) : μ s = 0 := begin obtain ⟨x, hx⟩ : ∃ x, x ∉ s, by simpa only [submodule.eq_top_iff', not_exists, ne.def, not_forall] using hs, obtain ⟨c, cpos, cone⟩ : ∃ (c : ℝ), 0 < c ∧ c < 1 := ⟨1/2, by norm_num, by norm_num⟩, have A : bounded (range (λ (n : ℕ), (c ^ n) • x)), { have : tendsto (λ (n : ℕ), (c ^ n) • x) at_top (𝓝 ((0 : ℝ) • x)) := (tendsto_pow_at_top_nhds_0_of_lt_1 cpos.le cone).smul_const x, exact bounded_range_of_tendsto _ this }, apply add_haar_eq_zero_of_disjoint_translates μ _ A _ (submodule.closed_of_finite_dimensional s).measurable_set, assume m n hmn, simp only [function.on_fun, image_add_left, singleton_add, disjoint_left, mem_preimage, set_like.mem_coe], assume y hym hyn, have A : (c ^ n - c ^ m) • x ∈ s, { convert s.sub_mem hym hyn, simp only [sub_smul, neg_sub_neg, add_sub_add_right_eq_sub] }, have H : c ^ n - c ^ m ≠ 0, by simpa only [sub_eq_zero, ne.def] using (strict_anti_pow cpos cone).injective.ne hmn.symm, have : x ∈ s, { convert s.smul_mem (c ^ n - c ^ m)⁻¹ A, rw [smul_smul, inv_mul_cancel H, one_smul] }, exact hx this end /-- A strict affine subspace has measure zero. -/ lemma add_haar_affine_subspace {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [measurable_space E] [borel_space E] [finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ] (s : affine_subspace ℝ E) (hs : s ≠ ⊤) : μ s = 0 := begin rcases s.eq_bot_or_nonempty with rfl|hne, { rw [affine_subspace.bot_coe, measure_empty] }, rw [ne.def, ← affine_subspace.direction_eq_top_iff_of_nonempty hne] at hs, rcases hne with ⟨x, hx : x ∈ s⟩, simpa only [affine_subspace.coe_direction_eq_vsub_set_right hx, vsub_eq_sub, sub_eq_add_neg, image_add_right, neg_neg, measure_preimage_add_right] using add_haar_submodule μ s.direction hs end /-! ### Applying a linear map rescales Haar measure by the determinant We first prove this on `ι → ℝ`, using that this is already known for the product Lebesgue measure (thanks to matrices computations). Then, we extend this to any finite-dimensional real vector space by using a linear equiv with a space of the form `ι → ℝ`, and arguing that such a linear equiv maps Haar measure to Haar measure. -/ lemma map_linear_map_add_haar_pi_eq_smul_add_haar {ι : Type*} [finite ι] {f : (ι → ℝ) →ₗ[ℝ] (ι → ℝ)} (hf : f.det ≠ 0) (μ : measure (ι → ℝ)) [is_add_haar_measure μ] : measure.map f μ = ennreal.of_real (abs (f.det)⁻¹) • μ := begin casesI nonempty_fintype ι, /- We have already proved the result for the Lebesgue product measure, using matrices. We deduce it for any Haar measure by uniqueness (up to scalar multiplication). -/ have := add_haar_measure_unique μ (pi_Icc01 ι), rw [this, add_haar_measure_eq_volume_pi, measure.map_smul, real.map_linear_map_volume_pi_eq_smul_volume_pi hf, smul_comm], end lemma map_linear_map_add_haar_eq_smul_add_haar {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [measurable_space E] [borel_space E] [finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ] {f : E →ₗ[ℝ] E} (hf : f.det ≠ 0) : measure.map f μ = ennreal.of_real (abs (f.det)⁻¹) • μ := begin -- we reduce to the case of `E = ι → ℝ`, for which we have already proved the result using -- matrices in `map_linear_map_add_haar_pi_eq_smul_add_haar`. let ι := fin (finrank ℝ E), haveI : finite_dimensional ℝ (ι → ℝ) := by apply_instance, have : finrank ℝ E = finrank ℝ (ι → ℝ), by simp, have e : E ≃ₗ[ℝ] ι → ℝ := linear_equiv.of_finrank_eq E (ι → ℝ) this, -- next line is to avoid `g` getting reduced by `simp`. obtain ⟨g, hg⟩ : ∃ g, g = (e : E →ₗ[ℝ] (ι → ℝ)).comp (f.comp (e.symm : (ι → ℝ) →ₗ[ℝ] E)) := ⟨_, rfl⟩, have gdet : g.det = f.det, by { rw [hg], exact linear_map.det_conj f e }, rw ← gdet at hf ⊢, have fg : f = (e.symm : (ι → ℝ) →ₗ[ℝ] E).comp (g.comp (e : E →ₗ[ℝ] (ι → ℝ))), { ext x, simp only [linear_equiv.coe_coe, function.comp_app, linear_map.coe_comp, linear_equiv.symm_apply_apply, hg] }, simp only [fg, linear_equiv.coe_coe, linear_map.coe_comp], have Ce : continuous e := (e : E →ₗ[ℝ] (ι → ℝ)).continuous_of_finite_dimensional, have Cg : continuous g := linear_map.continuous_of_finite_dimensional g, have Cesymm : continuous e.symm := (e.symm : (ι → ℝ) →ₗ[ℝ] E).continuous_of_finite_dimensional, rw [← map_map Cesymm.measurable (Cg.comp Ce).measurable, ← map_map Cg.measurable Ce.measurable], haveI : is_add_haar_measure (map e μ) := is_add_haar_measure_map μ e.to_add_equiv Ce Cesymm, have ecomp : (e.symm) ∘ e = id, by { ext x, simp only [id.def, function.comp_app, linear_equiv.symm_apply_apply] }, rw [map_linear_map_add_haar_pi_eq_smul_add_haar hf (map e μ), measure.map_smul, map_map Cesymm.measurable Ce.measurable, ecomp, measure.map_id] end /-- The preimage of a set `s` under a linear map `f` with nonzero determinant has measure equal to `μ s` times the absolute value of the inverse of the determinant of `f`. -/ @[simp] lemma add_haar_preimage_linear_map {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [measurable_space E] [borel_space E] [finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ] {f : E →ₗ[ℝ] E} (hf : f.det ≠ 0) (s : set E) : μ (f ⁻¹' s) = ennreal.of_real (abs (f.det)⁻¹) * μ s := calc μ (f ⁻¹' s) = measure.map f μ s : ((f.equiv_of_det_ne_zero hf).to_continuous_linear_equiv.to_homeomorph .to_measurable_equiv.map_apply s).symm ... = ennreal.of_real (abs (f.det)⁻¹) * μ s : by { rw map_linear_map_add_haar_eq_smul_add_haar μ hf, refl } /-- The preimage of a set `s` under a continuous linear map `f` with nonzero determinant has measure equal to `μ s` times the absolute value of the inverse of the determinant of `f`. -/ @[simp] lemma add_haar_preimage_continuous_linear_map {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [measurable_space E] [borel_space E] [finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ] {f : E →L[ℝ] E} (hf : linear_map.det (f : E →ₗ[ℝ] E) ≠ 0) (s : set E) : μ (f ⁻¹' s) = ennreal.of_real (abs (linear_map.det (f : E →ₗ[ℝ] E))⁻¹) * μ s := add_haar_preimage_linear_map μ hf s /-- The preimage of a set `s` under a linear equiv `f` has measure equal to `μ s` times the absolute value of the inverse of the determinant of `f`. -/ @[simp] lemma add_haar_preimage_linear_equiv {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [measurable_space E] [borel_space E] [finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ] (f : E ≃ₗ[ℝ] E) (s : set E) : μ (f ⁻¹' s) = ennreal.of_real (abs (f.symm : E →ₗ[ℝ] E).det) * μ s := begin have A : (f : E →ₗ[ℝ] E).det ≠ 0 := (linear_equiv.is_unit_det' f).ne_zero, convert add_haar_preimage_linear_map μ A s, simp only [linear_equiv.det_coe_symm] end /-- The preimage of a set `s` under a continuous linear equiv `f` has measure equal to `μ s` times the absolute value of the inverse of the determinant of `f`. -/ @[simp] lemma add_haar_preimage_continuous_linear_equiv {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [measurable_space E] [borel_space E] [finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ] (f : E ≃L[ℝ] E) (s : set E) : μ (f ⁻¹' s) = ennreal.of_real (abs (f.symm : E →ₗ[ℝ] E).det) * μ s := add_haar_preimage_linear_equiv μ _ s /-- The image of a set `s` under a linear map `f` has measure equal to `μ s` times the absolute value of the determinant of `f`. -/ @[simp] lemma add_haar_image_linear_map {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [measurable_space E] [borel_space E] [finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ] (f : E →ₗ[ℝ] E) (s : set E) : μ (f '' s) = ennreal.of_real (abs f.det) * μ s := begin rcases ne_or_eq f.det 0 with hf|hf, { let g := (f.equiv_of_det_ne_zero hf).to_continuous_linear_equiv, change μ (g '' s) = _, rw [continuous_linear_equiv.image_eq_preimage g s, add_haar_preimage_continuous_linear_equiv], congr, ext x, simp only [linear_equiv.coe_to_continuous_linear_equiv, linear_equiv.of_is_unit_det_apply, linear_equiv.coe_coe, continuous_linear_equiv.symm_symm], }, { simp only [hf, zero_mul, ennreal.of_real_zero, abs_zero], have : μ f.range = 0 := add_haar_submodule μ _ (linear_map.range_lt_top_of_det_eq_zero hf).ne, exact le_antisymm (le_trans (measure_mono (image_subset_range _ _)) this.le) (zero_le _) } end /-- The image of a set `s` under a continuous linear map `f` has measure equal to `μ s` times the absolute value of the determinant of `f`. -/ @[simp] lemma add_haar_image_continuous_linear_map {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [measurable_space E] [borel_space E] [finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ] (f : E →L[ℝ] E) (s : set E) : μ (f '' s) = ennreal.of_real (abs (f : E →ₗ[ℝ] E).det) * μ s := add_haar_image_linear_map μ _ s /-- The image of a set `s` under a continuous linear equiv `f` has measure equal to `μ s` times the absolute value of the determinant of `f`. -/ @[simp] lemma add_haar_image_continuous_linear_equiv {E : Type*} [normed_add_comm_group E] [normed_space ℝ E] [measurable_space E] [borel_space E] [finite_dimensional ℝ E] (μ : measure E) [is_add_haar_measure μ] (f : E ≃L[ℝ] E) (s : set E) : μ (f '' s) = ennreal.of_real (abs (f : E →ₗ[ℝ] E).det) * μ s := μ.add_haar_image_linear_map (f : E →ₗ[ℝ] E) s /-! ### Basic properties of Haar measures on real vector spaces -/ variables {E : Type*} [normed_add_comm_group E] [measurable_space E] [normed_space ℝ E] [finite_dimensional ℝ E] [borel_space E] (μ : measure E) [is_add_haar_measure μ] lemma map_add_haar_smul {r : ℝ} (hr : r ≠ 0) : measure.map ((•) r) μ = ennreal.of_real (abs (r ^ (finrank ℝ E))⁻¹) • μ := begin let f : E →ₗ[ℝ] E := r • 1, change measure.map f μ = _, have hf : f.det ≠ 0, { simp only [mul_one, linear_map.det_smul, ne.def, monoid_hom.map_one], assume h, exact hr (pow_eq_zero h) }, simp only [map_linear_map_add_haar_eq_smul_add_haar μ hf, mul_one, linear_map.det_smul, monoid_hom.map_one], end @[simp] lemma add_haar_preimage_smul {r : ℝ} (hr : r ≠ 0) (s : set E) : μ (((•) r) ⁻¹' s) = ennreal.of_real (abs (r ^ (finrank ℝ E))⁻¹) * μ s := calc μ (((•) r) ⁻¹' s) = measure.map ((•) r) μ s : ((homeomorph.smul (is_unit_iff_ne_zero.2 hr).unit).to_measurable_equiv.map_apply s).symm ... = ennreal.of_real (abs (r^(finrank ℝ E))⁻¹) * μ s : by { rw map_add_haar_smul μ hr, refl } /-- Rescaling a set by a factor `r` multiplies its measure by `abs (r ^ dim)`. -/ @[simp] lemma add_haar_smul (r : ℝ) (s : set E) : μ (r • s) = ennreal.of_real (abs (r ^ (finrank ℝ E))) * μ s := begin rcases ne_or_eq r 0 with h|rfl, { rw [← preimage_smul_inv₀ h, add_haar_preimage_smul μ (inv_ne_zero h), inv_pow, inv_inv] }, rcases eq_empty_or_nonempty s with rfl|hs, { simp only [measure_empty, mul_zero, smul_set_empty] }, rw [zero_smul_set hs, ← singleton_zero], by_cases h : finrank ℝ E = 0, { haveI : subsingleton E := finrank_zero_iff.1 h, simp only [h, one_mul, ennreal.of_real_one, abs_one, subsingleton.eq_univ_of_nonempty hs, pow_zero, subsingleton.eq_univ_of_nonempty (singleton_nonempty (0 : E))] }, { haveI : nontrivial E := nontrivial_of_finrank_pos (bot_lt_iff_ne_bot.2 h), simp only [h, zero_mul, ennreal.of_real_zero, abs_zero, ne.def, not_false_iff, zero_pow', measure_singleton] } end @[simp] lemma add_haar_image_homothety (x : E) (r : ℝ) (s : set E) : μ (affine_map.homothety x r '' s) = ennreal.of_real (abs (r ^ (finrank ℝ E))) * μ s := calc μ (affine_map.homothety x r '' s) = μ ((λ y, y + x) '' (r • ((λ y, y + (-x)) '' s))) : by { simp only [← image_smul, image_image, ← sub_eq_add_neg], refl } ... = ennreal.of_real (abs (r ^ (finrank ℝ E))) * μ s : by simp only [image_add_right, measure_preimage_add_right, add_haar_smul] /-! We don't need to state `map_add_haar_neg` here, because it has already been proved for general Haar measures on general commutative groups. -/ /-! ### Measure of balls -/ lemma add_haar_ball_center {E : Type*} [normed_add_comm_group E] [measurable_space E] [borel_space E] (μ : measure E) [is_add_haar_measure μ] (x : E) (r : ℝ) : μ (ball x r) = μ (ball (0 : E) r) := begin have : ball (0 : E) r = ((+) x) ⁻¹' (ball x r), by simp [preimage_add_ball], rw [this, measure_preimage_add] end lemma add_haar_closed_ball_center {E : Type*} [normed_add_comm_group E] [measurable_space E] [borel_space E] (μ : measure E) [is_add_haar_measure μ] (x : E) (r : ℝ) : μ (closed_ball x r) = μ (closed_ball (0 : E) r) := begin have : closed_ball (0 : E) r = ((+) x) ⁻¹' (closed_ball x r), by simp [preimage_add_closed_ball], rw [this, measure_preimage_add] end lemma add_haar_ball_mul_of_pos (x : E) {r : ℝ} (hr : 0 < r) (s : ℝ) : μ (ball x (r * s)) = ennreal.of_real (r ^ (finrank ℝ E)) * μ (ball 0 s) := begin have : ball (0 : E) (r * s) = r • ball 0 s, by simp only [smul_ball hr.ne' (0 : E) s, real.norm_eq_abs, abs_of_nonneg hr.le, smul_zero], simp only [this, add_haar_smul, abs_of_nonneg hr.le, add_haar_ball_center, abs_pow], end lemma add_haar_ball_of_pos (x : E) {r : ℝ} (hr : 0 < r) : μ (ball x r) = ennreal.of_real (r ^ (finrank ℝ E)) * μ (ball 0 1) := by rw [← add_haar_ball_mul_of_pos μ x hr, mul_one] lemma add_haar_ball_mul [nontrivial E] (x : E) {r : ℝ} (hr : 0 ≤ r) (s : ℝ) : μ (ball x (r * s)) = ennreal.of_real (r ^ (finrank ℝ E)) * μ (ball 0 s) := begin rcases has_le.le.eq_or_lt hr with h|h, { simp only [← h, zero_pow finrank_pos, measure_empty, zero_mul, ennreal.of_real_zero, ball_zero] }, { exact add_haar_ball_mul_of_pos μ x h s } end lemma add_haar_ball [nontrivial E] (x : E) {r : ℝ} (hr : 0 ≤ r) : μ (ball x r) = ennreal.of_real (r ^ (finrank ℝ E)) * μ (ball 0 1) := by rw [← add_haar_ball_mul μ x hr, mul_one] lemma add_haar_closed_ball_mul_of_pos (x : E) {r : ℝ} (hr : 0 < r) (s : ℝ) : μ (closed_ball x (r * s)) = ennreal.of_real (r ^ (finrank ℝ E)) * μ (closed_ball 0 s) := begin have : closed_ball (0 : E) (r * s) = r • closed_ball 0 s, by simp [smul_closed_ball' hr.ne' (0 : E), abs_of_nonneg hr.le], simp only [this, add_haar_smul, abs_of_nonneg hr.le, add_haar_closed_ball_center, abs_pow], end lemma add_haar_closed_ball_mul (x : E) {r : ℝ} (hr : 0 ≤ r) {s : ℝ} (hs : 0 ≤ s) : μ (closed_ball x (r * s)) = ennreal.of_real (r ^ (finrank ℝ E)) * μ (closed_ball 0 s) := begin have : closed_ball (0 : E) (r * s) = r • closed_ball 0 s, by simp [smul_closed_ball r (0 : E) hs, abs_of_nonneg hr], simp only [this, add_haar_smul, abs_of_nonneg hr, add_haar_closed_ball_center, abs_pow], end /-- The measure of a closed ball can be expressed in terms of the measure of the closed unit ball. Use instead `add_haar_closed_ball`, which uses the measure of the open unit ball as a standard form. -/ lemma add_haar_closed_ball' (x : E) {r : ℝ} (hr : 0 ≤ r) : μ (closed_ball x r) = ennreal.of_real (r ^ (finrank ℝ E)) * μ (closed_ball 0 1) := by rw [← add_haar_closed_ball_mul μ x hr zero_le_one, mul_one] lemma add_haar_closed_unit_ball_eq_add_haar_unit_ball : μ (closed_ball (0 : E) 1) = μ (ball 0 1) := begin apply le_antisymm _ (measure_mono ball_subset_closed_ball), have A : tendsto (λ (r : ℝ), ennreal.of_real (r ^ (finrank ℝ E)) * μ (closed_ball (0 : E) 1)) (𝓝[<] 1) (𝓝 (ennreal.of_real (1 ^ (finrank ℝ E)) * μ (closed_ball (0 : E) 1))), { refine ennreal.tendsto.mul _ (by simp) tendsto_const_nhds (by simp), exact ennreal.tendsto_of_real ((tendsto_id'.2 nhds_within_le_nhds).pow _) }, simp only [one_pow, one_mul, ennreal.of_real_one] at A, refine le_of_tendsto A _, refine mem_nhds_within_Iio_iff_exists_Ioo_subset.2 ⟨(0 : ℝ), by simp, λ r hr, _⟩, dsimp, rw ← add_haar_closed_ball' μ (0 : E) hr.1.le, exact measure_mono (closed_ball_subset_ball hr.2) end lemma add_haar_closed_ball (x : E) {r : ℝ} (hr : 0 ≤ r) : μ (closed_ball x r) = ennreal.of_real (r ^ (finrank ℝ E)) * μ (ball 0 1) := by rw [add_haar_closed_ball' μ x hr, add_haar_closed_unit_ball_eq_add_haar_unit_ball] lemma add_haar_sphere_of_ne_zero (x : E) {r : ℝ} (hr : r ≠ 0) : μ (sphere x r) = 0 := begin rcases hr.lt_or_lt with h|h, { simp only [empty_diff, measure_empty, ← closed_ball_diff_ball, closed_ball_eq_empty.2 h] }, { rw [← closed_ball_diff_ball, measure_diff ball_subset_closed_ball measurable_set_ball measure_ball_lt_top.ne, add_haar_ball_of_pos μ _ h, add_haar_closed_ball μ _ h.le, tsub_self]; apply_instance } end lemma add_haar_sphere [nontrivial E] (x : E) (r : ℝ) : μ (sphere x r) = 0 := begin rcases eq_or_ne r 0 with rfl|h, { rw [sphere_zero, measure_singleton] }, { exact add_haar_sphere_of_ne_zero μ x h } end lemma add_haar_singleton_add_smul_div_singleton_add_smul {r : ℝ} (hr : r ≠ 0) (x y : E) (s t : set E) : μ ({x} + r • s) / μ ({y} + r • t) = μ s / μ t := calc μ ({x} + r • s) / μ ({y} + r • t) = ennreal.of_real (|r| ^ finrank ℝ E) * μ s * (ennreal.of_real (|r| ^ finrank ℝ E) * μ t)⁻¹ : by simp only [div_eq_mul_inv, add_haar_smul, image_add_left, measure_preimage_add, abs_pow, singleton_add] ... = ennreal.of_real (|r| ^ finrank ℝ E) * (ennreal.of_real (|r| ^ finrank ℝ E))⁻¹ * (μ s * (μ t)⁻¹) : begin rw ennreal.mul_inv, { ring }, { simp only [pow_pos (abs_pos.mpr hr), ennreal.of_real_eq_zero, not_le, ne.def, true_or] }, { simp only [ennreal.of_real_ne_top, true_or, ne.def, not_false_iff] }, end ... = μ s / μ t : begin rw [ennreal.mul_inv_cancel, one_mul, div_eq_mul_inv], { simp only [pow_pos (abs_pos.mpr hr), ennreal.of_real_eq_zero, not_le, ne.def], }, { simp only [ennreal.of_real_ne_top, ne.def, not_false_iff] } end /-! ### Density points Besicovitch covering theorem ensures that, for any locally finite measure on a finite-dimensional real vector space, almost every point of a set `s` is a density point, i.e., `μ (s ∩ closed_ball x r) / μ (closed_ball x r)` tends to `1` as `r` tends to `0` (see `besicovitch.ae_tendsto_measure_inter_div`). When `μ` is a Haar measure, one can deduce the same property for any rescaling sequence of sets, of the form `{x} + r • t` where `t` is a set with positive finite measure, instead of the sequence of closed balls. We argue first for the dual property, i.e., if `s` has density `0` at `x`, then `μ (s ∩ ({x} + r • t)) / μ ({x} + r • t)` tends to `0`. First when `t` is contained in the ball of radius `1`, in `tendsto_add_haar_inter_smul_zero_of_density_zero_aux1`, (by arguing by inclusion). Then when `t` is bounded, reducing to the previous one by rescaling, in `tendsto_add_haar_inter_smul_zero_of_density_zero_aux2`. Then for a general set `t`, by cutting it into a bounded part and a part with small measure, in `tendsto_add_haar_inter_smul_zero_of_density_zero`. Going to the complement, one obtains the desired property at points of density `1`, first when `s` is measurable in `tendsto_add_haar_inter_smul_one_of_density_one_aux`, and then without this assumption in `tendsto_add_haar_inter_smul_one_of_density_one` by applying the previous lemma to the measurable hull `to_measurable μ s` -/ lemma tendsto_add_haar_inter_smul_zero_of_density_zero_aux1 (s : set E) (x : E) (h : tendsto (λ r, μ (s ∩ closed_ball x r) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 0)) (t : set E) (u : set E) (h'u : μ u ≠ 0) (t_bound : t ⊆ closed_ball 0 1) : tendsto (λ (r : ℝ), μ (s ∩ ({x} + r • t)) / μ ({x} + r • u)) (𝓝[>] 0) (𝓝 0) := begin have A : tendsto (λ (r : ℝ), μ (s ∩ ({x} + r • t)) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 0), { apply tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds h (eventually_of_forall (λ b, zero_le _)), filter_upwards [self_mem_nhds_within], rintros r (rpos : 0 < r), apply ennreal.mul_le_mul (measure_mono (inter_subset_inter_right _ _)) le_rfl, assume y hy, have : y - x ∈ r • closed_ball (0 : E) 1, { apply smul_set_mono t_bound, simpa [neg_add_eq_sub] using hy }, simpa only [smul_closed_ball _ _ zero_le_one, real.norm_of_nonneg rpos.le, mem_closed_ball_iff_norm, mul_one, sub_zero, smul_zero] }, have B : tendsto (λ (r : ℝ), μ (closed_ball x r) / μ ({x} + r • u)) (𝓝[>] 0) (𝓝 (μ (closed_ball x 1) / μ ({x} + u))), { apply tendsto_const_nhds.congr' _, filter_upwards [self_mem_nhds_within], rintros r (rpos : 0 < r), have : closed_ball x r = {x} + r • closed_ball 0 1, by simp only [smul_closed_ball, real.norm_of_nonneg rpos.le, zero_le_one, add_zero, mul_one, singleton_add_closed_ball, smul_zero], simp only [this, add_haar_singleton_add_smul_div_singleton_add_smul μ rpos.ne'], simp only [add_haar_closed_ball_center, image_add_left, measure_preimage_add, singleton_add] }, have C : tendsto (λ (r : ℝ), (μ (s ∩ ({x} + r • t)) / μ (closed_ball x r)) * (μ (closed_ball x r) / μ ({x} + r • u))) (𝓝[>] 0) (𝓝 (0 * (μ (closed_ball x 1) / μ ({x} + u)))), { apply ennreal.tendsto.mul A _ B (or.inr ennreal.zero_ne_top), simp only [ennreal.div_eq_top, h'u, measure_closed_ball_lt_top.ne, false_or, image_add_left, eq_self_iff_true, not_true, ne.def, not_false_iff, measure_preimage_add, singleton_add, and_false, false_and] }, simp only [zero_mul] at C, apply C.congr' _, filter_upwards [self_mem_nhds_within], rintros r (rpos : 0 < r), calc μ (s ∩ ({x} + r • t)) / μ (closed_ball x r) * (μ (closed_ball x r) / μ ({x} + r • u)) = (μ (closed_ball x r) * (μ (closed_ball x r))⁻¹) * (μ (s ∩ ({x} + r • t)) / μ ({x} + r • u)) : by { simp only [div_eq_mul_inv], ring } ... = μ (s ∩ ({x} + r • t)) / μ ({x} + r • u) : by rw [ennreal.mul_inv_cancel (measure_closed_ball_pos μ x rpos).ne' measure_closed_ball_lt_top.ne, one_mul], end lemma tendsto_add_haar_inter_smul_zero_of_density_zero_aux2 (s : set E) (x : E) (h : tendsto (λ r, μ (s ∩ closed_ball x r) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 0)) (t : set E) (u : set E) (h'u : μ u ≠ 0) (R : ℝ) (Rpos : 0 < R) (t_bound : t ⊆ closed_ball 0 R) : tendsto (λ (r : ℝ), μ (s ∩ ({x} + r • t)) / μ ({x} + r • u)) (𝓝[>] 0) (𝓝 0) := begin set t' := R⁻¹ • t with ht', set u' := R⁻¹ • u with hu', have A : tendsto (λ (r : ℝ), μ (s ∩ ({x} + r • t')) / μ ({x} + r • u')) (𝓝[>] 0) (𝓝 0), { apply tendsto_add_haar_inter_smul_zero_of_density_zero_aux1 μ s x h t' u', { simp only [h'u, (pow_pos Rpos _).ne', abs_nonpos_iff, add_haar_smul, not_false_iff, ennreal.of_real_eq_zero, inv_eq_zero, inv_pow, ne.def, or_self, mul_eq_zero] }, { convert smul_set_mono t_bound, rw [smul_closed_ball _ _ Rpos.le, smul_zero, real.norm_of_nonneg (inv_nonneg.2 Rpos.le), inv_mul_cancel Rpos.ne'] } }, have B : tendsto (λ (r : ℝ), R * r) (𝓝[>] 0) (𝓝[>] (R * 0)), { apply tendsto_nhds_within_of_tendsto_nhds_of_eventually_within, { exact (tendsto_const_nhds.mul tendsto_id).mono_left nhds_within_le_nhds }, { filter_upwards [self_mem_nhds_within], assume r rpos, rw mul_zero, exact mul_pos Rpos rpos } }, rw mul_zero at B, apply (A.comp B).congr' _, filter_upwards [self_mem_nhds_within], rintros r (rpos : 0 < r), have T : (R * r) • t' = r • t, by rw [mul_comm, ht', smul_smul, mul_assoc, mul_inv_cancel Rpos.ne', mul_one], have U : (R * r) • u' = r • u, by rw [mul_comm, hu', smul_smul, mul_assoc, mul_inv_cancel Rpos.ne', mul_one], dsimp, rw [T, U], end /-- Consider a point `x` at which a set `s` has density zero, with respect to closed balls. Then it also has density zero with respect to any measurable set `t`: the proportion of points in `s` belonging to a rescaled copy `{x} + r • t` of `t` tends to zero as `r` tends to zero. -/ lemma tendsto_add_haar_inter_smul_zero_of_density_zero (s : set E) (x : E) (h : tendsto (λ r, μ (s ∩ closed_ball x r) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 0)) (t : set E) (ht : measurable_set t) (h''t : μ t ≠ ∞) : tendsto (λ (r : ℝ), μ (s ∩ ({x} + r • t)) / μ ({x} + r • t)) (𝓝[>] 0) (𝓝 0) := begin refine tendsto_order.2 ⟨λ a' ha', (ennreal.not_lt_zero ha').elim, λ ε (εpos : 0 < ε), _⟩, rcases eq_or_ne (μ t) 0 with h't|h't, { apply eventually_of_forall (λ r, _), suffices H : μ (s ∩ ({x} + r • t)) = 0, by { rw H, simpa only [ennreal.zero_div] using εpos }, apply le_antisymm _ (zero_le _), calc μ (s ∩ ({x} + r • t)) ≤ μ ({x} + r • t) : measure_mono (inter_subset_right _ _) ... = 0 : by simp only [h't, add_haar_smul, image_add_left, measure_preimage_add, singleton_add, mul_zero] }, obtain ⟨n, npos, hn⟩ : ∃ (n : ℕ), 0 < n ∧ μ (t \ closed_ball 0 n) < (ε / 2) * μ t, { have A : tendsto (λ (n : ℕ), μ (t \ closed_ball 0 n)) at_top (𝓝 (μ (⋂ (n : ℕ), t \ closed_ball 0 n))), { have N : ∃ (n : ℕ), μ (t \ closed_ball 0 n) ≠ ∞ := ⟨0, ((measure_mono (diff_subset t _)).trans_lt h''t.lt_top).ne⟩, refine tendsto_measure_Inter (λ n, ht.diff measurable_set_closed_ball) (λ m n hmn, _) N, exact diff_subset_diff subset.rfl (closed_ball_subset_closed_ball (nat.cast_le.2 hmn)) }, have : (⋂ (n : ℕ), t \ closed_ball 0 n) = ∅, by simp_rw [diff_eq, ← inter_Inter, Inter_eq_compl_Union_compl, compl_compl, Union_closed_ball_nat, compl_univ, inter_empty], simp only [this, measure_empty] at A, have I : 0 < (ε / 2) * μ t := ennreal.mul_pos (ennreal.half_pos εpos.ne').ne' h't, exact (eventually.and (Ioi_mem_at_top 0) ((tendsto_order.1 A).2 _ I)).exists }, have L : tendsto (λ (r : ℝ), μ (s ∩ ({x} + r • (t ∩ closed_ball 0 n))) / μ ({x} + r • t)) (𝓝[>] 0) (𝓝 0) := tendsto_add_haar_inter_smul_zero_of_density_zero_aux2 μ s x h _ t h't n (nat.cast_pos.2 npos) (inter_subset_right _ _), filter_upwards [(tendsto_order.1 L).2 _ (ennreal.half_pos εpos.ne'), self_mem_nhds_within], rintros r hr (rpos : 0 < r), have I : μ (s ∩ ({x} + r • t)) ≤ μ (s ∩ ({x} + r • (t ∩ closed_ball 0 n))) + μ ({x} + r • (t \ closed_ball 0 n)) := calc μ (s ∩ ({x} + r • t)) = μ ((s ∩ ({x} + r • (t ∩ closed_ball 0 n))) ∪ (s ∩ ({x} + r • (t \ closed_ball 0 n)))) : by rw [← inter_union_distrib_left, ← add_union, ← smul_set_union, inter_union_diff] ... ≤ μ (s ∩ ({x} + r • (t ∩ closed_ball 0 n))) + μ (s ∩ ({x} + r • (t \ closed_ball 0 n))) : measure_union_le _ _ ... ≤ μ (s ∩ ({x} + r • (t ∩ closed_ball 0 n))) + μ ({x} + r • (t \ closed_ball 0 n)) : add_le_add le_rfl (measure_mono (inter_subset_right _ _)), calc μ (s ∩ ({x} + r • t)) / μ ({x} + r • t) ≤ (μ (s ∩ ({x} + r • (t ∩ closed_ball 0 n))) + μ ({x} + r • (t \ closed_ball 0 n))) / μ ({x} + r • t) : ennreal.mul_le_mul I le_rfl ... < ε / 2 + ε / 2 : begin rw ennreal.add_div, apply ennreal.add_lt_add hr _, rwa [add_haar_singleton_add_smul_div_singleton_add_smul μ rpos.ne', ennreal.div_lt_iff (or.inl h't) (or.inl h''t)], end ... = ε : ennreal.add_halves _ end lemma tendsto_add_haar_inter_smul_one_of_density_one_aux (s : set E) (hs : measurable_set s) (x : E) (h : tendsto (λ r, μ (s ∩ closed_ball x r) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 1)) (t : set E) (ht : measurable_set t) (h't : μ t ≠ 0) (h''t : μ t ≠ ∞) : tendsto (λ (r : ℝ), μ (s ∩ ({x} + r • t)) / μ ({x} + r • t)) (𝓝[>] 0) (𝓝 1) := begin have I : ∀ u v, μ u ≠ 0 → μ u ≠ ∞ → measurable_set v → μ u / μ u - μ (vᶜ ∩ u) / μ u = μ (v ∩ u) / μ u, { assume u v uzero utop vmeas, simp_rw [div_eq_mul_inv], rw ← ennreal.sub_mul, swap, { simp only [uzero, ennreal.inv_eq_top, implies_true_iff, ne.def, not_false_iff] }, congr' 1, apply ennreal.sub_eq_of_add_eq (ne_top_of_le_ne_top utop (measure_mono (inter_subset_right _ _))), rw [inter_comm _ u, inter_comm _ u], exact measure_inter_add_diff u vmeas }, have L : tendsto (λ r, μ (sᶜ ∩ closed_ball x r) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 0), { have A : tendsto (λ r, μ (closed_ball x r) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 1), { apply tendsto_const_nhds.congr' _, filter_upwards [self_mem_nhds_within], assume r hr, rw [div_eq_mul_inv, ennreal.mul_inv_cancel], { exact (measure_closed_ball_pos μ _ hr).ne' }, { exact measure_closed_ball_lt_top.ne } }, have B := ennreal.tendsto.sub A h (or.inl ennreal.one_ne_top), simp only [tsub_self] at B, apply B.congr' _, filter_upwards [self_mem_nhds_within], rintros r (rpos : 0 < r), convert I (closed_ball x r) sᶜ (measure_closed_ball_pos μ _ rpos).ne' (measure_closed_ball_lt_top).ne hs.compl, rw compl_compl }, have L' : tendsto (λ (r : ℝ), μ (sᶜ ∩ ({x} + r • t)) / μ ({x} + r • t)) (𝓝[>] 0) (𝓝 0) := tendsto_add_haar_inter_smul_zero_of_density_zero μ sᶜ x L t ht h''t, have L'' : tendsto (λ (r : ℝ), μ ({x} + r • t) / μ ({x} + r • t)) (𝓝[>] 0) (𝓝 1), { apply tendsto_const_nhds.congr' _, filter_upwards [self_mem_nhds_within], rintros r (rpos : 0 < r), rw [add_haar_singleton_add_smul_div_singleton_add_smul μ rpos.ne', ennreal.div_self h't h''t] }, have := ennreal.tendsto.sub L'' L' (or.inl ennreal.one_ne_top), simp only [tsub_zero] at this, apply this.congr' _, filter_upwards [self_mem_nhds_within], rintros r (rpos : 0 < r), refine I ({x} + r • t) s _ _ hs, { simp only [h't, abs_of_nonneg rpos.le, pow_pos rpos, add_haar_smul, image_add_left, ennreal.of_real_eq_zero, not_le, or_false, ne.def, measure_preimage_add, abs_pow, singleton_add, mul_eq_zero] }, { simp only [h''t, ennreal.of_real_ne_top, add_haar_smul, image_add_left, with_top.mul_eq_top_iff, ne.def, not_false_iff, measure_preimage_add, singleton_add, and_false, false_and, or_self] } end /-- Consider a point `x` at which a set `s` has density one, with respect to closed balls (i.e., a Lebesgue density point of `s`). Then `s` has also density one at `x` with respect to any measurable set `t`: the proportion of points in `s` belonging to a rescaled copy `{x} + r • t` of `t` tends to one as `r` tends to zero. -/ lemma tendsto_add_haar_inter_smul_one_of_density_one (s : set E) (x : E) (h : tendsto (λ r, μ (s ∩ closed_ball x r) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 1)) (t : set E) (ht : measurable_set t) (h't : μ t ≠ 0) (h''t : μ t ≠ ∞) : tendsto (λ (r : ℝ), μ (s ∩ ({x} + r • t)) / μ ({x} + r • t)) (𝓝[>] 0) (𝓝 1) := begin have : tendsto (λ (r : ℝ), μ (to_measurable μ s ∩ ({x} + r • t)) / μ ({x} + r • t)) (𝓝[>] 0) (𝓝 1), { apply tendsto_add_haar_inter_smul_one_of_density_one_aux μ _ (measurable_set_to_measurable _ _) _ _ t ht h't h''t, apply tendsto_of_tendsto_of_tendsto_of_le_of_le' h tendsto_const_nhds, { apply eventually_of_forall (λ r, _), apply ennreal.mul_le_mul _ le_rfl, exact measure_mono (inter_subset_inter_left _ (subset_to_measurable _ _)) }, { filter_upwards [self_mem_nhds_within], rintros r (rpos : 0 < r), apply ennreal.div_le_of_le_mul, rw one_mul, exact measure_mono (inter_subset_right _ _) } }, apply this.congr (λ r, _), congr' 1, apply measure_to_measurable_inter_of_sigma_finite, simp only [image_add_left, singleton_add], apply (continuous_add_left (-x)).measurable (ht.const_smul₀ r) end /-- Consider a point `x` at which a set `s` has density one, with respect to closed balls (i.e., a Lebesgue density point of `s`). Then `s` intersects the rescaled copies `{x} + r • t` of a given set `t` with positive measure, for any small enough `r`. -/ lemma eventually_nonempty_inter_smul_of_density_one (s : set E) (x : E) (h : tendsto (λ r, μ (s ∩ closed_ball x r) / μ (closed_ball x r)) (𝓝[>] 0) (𝓝 1)) (t : set E) (ht : measurable_set t) (h't : μ t ≠ 0) : ∀ᶠ r in 𝓝[>] (0 : ℝ), (s ∩ ({x} + r • t)).nonempty := begin obtain ⟨t', t'_meas, t't, t'pos, t'top⟩ : ∃ t', measurable_set t' ∧ t' ⊆ t ∧ 0 < μ t' ∧ μ t' < ⊤ := exists_subset_measure_lt_top ht h't.bot_lt, filter_upwards [(tendsto_order.1 (tendsto_add_haar_inter_smul_one_of_density_one μ s x h t' t'_meas t'pos.ne' t'top.ne)).1 0 ennreal.zero_lt_one], assume r hr, have : μ (s ∩ ({x} + r • t')) ≠ 0 := λ h', by simpa only [ennreal.not_lt_zero, ennreal.zero_div, h'] using hr, have : (s ∩ ({x} + r • t')).nonempty := nonempty_of_measure_ne_zero this, apply this.mono (inter_subset_inter subset.rfl _), exact add_subset_add subset.rfl (smul_set_mono t't), end end measure end measure_theory
613c46728a0a5c68b305d088c9ea8c8f4cc871aa
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/topology/metric_space/basic.lean
db77971b3e7949671982e8422b9bc7ce0ef71370
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
75,175
lean
/- Copyright (c) 2015, 2017 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Metric spaces. Authors: Jeremy Avigad, Robert Y. Lewis, Johannes Hölzl, Mario Carneiro, Sébastien Gouëzel Many definitions and theorems expected on metric spaces are already introduced on uniform spaces and topological spaces. For example: open and closed sets, compactness, completeness, continuity and uniform continuity -/ import topology.metric_space.emetric_space import topology.algebra.ordered open set filter classical topological_space noncomputable theory open_locale uniformity topological_space big_operators filter universes u v w variables {α : Type u} {β : Type v} {γ : Type w} /-- Construct a uniform structure from a distance function and metric space axioms -/ def uniform_space_of_dist (dist : α → α → ℝ) (dist_self : ∀ x : α, dist x x = 0) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) : uniform_space α := uniform_space.of_core { uniformity := (⨅ ε>0, 𝓟 {p:α×α | dist p.1 p.2 < ε}), refl := le_infi $ assume ε, le_infi $ by simp [set.subset_def, id_rel, dist_self, (>)] {contextual := tt}, comp := le_infi $ assume ε, le_infi $ assume h, lift'_le (mem_infi_sets (ε / 2) $ mem_infi_sets (div_pos h two_pos) (subset.refl _)) $ have ∀ (a b c : α), dist a c < ε / 2 → dist c b < ε / 2 → dist a b < ε, from assume a b c hac hcb, calc dist a b ≤ dist a c + dist c b : dist_triangle _ _ _ ... < ε / 2 + ε / 2 : add_lt_add hac hcb ... = ε : by rw [div_add_div_same, add_self_div_two], by simpa [comp_rel], symm := tendsto_infi.2 $ assume ε, tendsto_infi.2 $ assume h, tendsto_infi' ε $ tendsto_infi' h $ tendsto_principal_principal.2 $ by simp [dist_comm] } /-- The distance function (given an ambient metric space on `α`), which returns a nonnegative real number `dist x y` given `x y : α`. -/ class has_dist (α : Type*) := (dist : α → α → ℝ) export has_dist (dist) -- the uniform structure and the emetric space structure are embedded in the metric space structure -- to avoid instance diamond issues. See Note [forgetful inheritance]. /-- Metric space Each metric space induces a canonical `uniform_space` and hence a canonical `topological_space`. This is enforced in the type class definition, by extending the `uniform_space` structure. When instantiating a `metric_space` structure, the uniformity fields are not necessary, they will be filled in by default. In the same way, each metric space induces an emetric space structure. It is included in the structure, but filled in by default. -/ class metric_space (α : Type u) extends has_dist α : Type u := (dist_self : ∀ x : α, dist x x = 0) (eq_of_dist_eq_zero : ∀ {x y : α}, dist x y = 0 → x = y) (dist_comm : ∀ x y : α, dist x y = dist y x) (dist_triangle : ∀ x y z : α, dist x z ≤ dist x y + dist y z) (edist : α → α → ennreal := λx y, ennreal.of_real (dist x y)) (edist_dist : ∀ x y : α, edist x y = ennreal.of_real (dist x y) . control_laws_tac) (to_uniform_space : uniform_space α := uniform_space_of_dist dist dist_self dist_comm dist_triangle) (uniformity_dist : 𝓤 α = ⨅ ε>0, 𝓟 {p:α×α | dist p.1 p.2 < ε} . control_laws_tac) variables [metric_space α] @[priority 100] -- see Note [lower instance priority] instance metric_space.to_uniform_space' : uniform_space α := metric_space.to_uniform_space @[priority 200] -- see Note [lower instance priority] instance metric_space.to_has_edist : has_edist α := ⟨metric_space.edist⟩ @[simp] theorem dist_self (x : α) : dist x x = 0 := metric_space.dist_self x theorem eq_of_dist_eq_zero {x y : α} : dist x y = 0 → x = y := metric_space.eq_of_dist_eq_zero theorem dist_comm (x y : α) : dist x y = dist y x := metric_space.dist_comm x y theorem edist_dist (x y : α) : edist x y = ennreal.of_real (dist x y) := metric_space.edist_dist x y @[simp] theorem dist_eq_zero {x y : α} : dist x y = 0 ↔ x = y := iff.intro eq_of_dist_eq_zero (assume : x = y, this ▸ dist_self _) @[simp] theorem zero_eq_dist {x y : α} : 0 = dist x y ↔ x = y := by rw [eq_comm, dist_eq_zero] theorem dist_triangle (x y z : α) : dist x z ≤ dist x y + dist y z := metric_space.dist_triangle x y z theorem dist_triangle_left (x y z : α) : dist x y ≤ dist z x + dist z y := by rw dist_comm z; apply dist_triangle theorem dist_triangle_right (x y z : α) : dist x y ≤ dist x z + dist y z := by rw dist_comm y; apply dist_triangle lemma dist_triangle4 (x y z w : α) : dist x w ≤ dist x y + dist y z + dist z w := calc dist x w ≤ dist x z + dist z w : dist_triangle x z w ... ≤ (dist x y + dist y z) + dist z w : add_le_add_right (metric_space.dist_triangle x y z) _ lemma dist_triangle4_left (x₁ y₁ x₂ y₂ : α) : dist x₂ y₂ ≤ dist x₁ y₁ + (dist x₁ x₂ + dist y₁ y₂) := by rw [add_left_comm, dist_comm x₁, ← add_assoc]; apply dist_triangle4 lemma dist_triangle4_right (x₁ y₁ x₂ y₂ : α) : dist x₁ y₁ ≤ dist x₁ x₂ + dist y₁ y₂ + dist x₂ y₂ := by rw [add_right_comm, dist_comm y₁]; apply dist_triangle4 /-- The triangle (polygon) inequality for sequences of points; `finset.Ico` version. -/ lemma dist_le_Ico_sum_dist (f : ℕ → α) {m n} (h : m ≤ n) : dist (f m) (f n) ≤ ∑ i in finset.Ico m n, dist (f i) (f (i + 1)) := begin revert n, apply nat.le_induction, { simp only [finset.sum_empty, finset.Ico.self_eq_empty, dist_self] }, { assume n hn hrec, calc dist (f m) (f (n+1)) ≤ dist (f m) (f n) + dist _ _ : dist_triangle _ _ _ ... ≤ ∑ i in finset.Ico m n, _ + _ : add_le_add hrec (le_refl _) ... = ∑ i in finset.Ico m (n+1), _ : by rw [finset.Ico.succ_top hn, finset.sum_insert, add_comm]; simp } end /-- The triangle (polygon) inequality for sequences of points; `finset.range` version. -/ lemma dist_le_range_sum_dist (f : ℕ → α) (n : ℕ) : dist (f 0) (f n) ≤ ∑ i in finset.range n, dist (f i) (f (i + 1)) := finset.Ico.zero_bot n ▸ dist_le_Ico_sum_dist f (nat.zero_le n) /-- A version of `dist_le_Ico_sum_dist` with each intermediate distance replaced with an upper estimate. -/ lemma dist_le_Ico_sum_of_dist_le {f : ℕ → α} {m n} (hmn : m ≤ n) {d : ℕ → ℝ} (hd : ∀ {k}, m ≤ k → k < n → dist (f k) (f (k + 1)) ≤ d k) : dist (f m) (f n) ≤ ∑ i in finset.Ico m n, d i := le_trans (dist_le_Ico_sum_dist f hmn) $ finset.sum_le_sum $ λ k hk, hd (finset.Ico.mem.1 hk).1 (finset.Ico.mem.1 hk).2 /-- A version of `dist_le_range_sum_dist` with each intermediate distance replaced with an upper estimate. -/ lemma dist_le_range_sum_of_dist_le {f : ℕ → α} (n : ℕ) {d : ℕ → ℝ} (hd : ∀ {k}, k < n → dist (f k) (f (k + 1)) ≤ d k) : dist (f 0) (f n) ≤ ∑ i in finset.range n, d i := finset.Ico.zero_bot n ▸ dist_le_Ico_sum_of_dist_le (zero_le n) (λ _ _, hd) theorem swap_dist : function.swap (@dist α _) = dist := by funext x y; exact dist_comm _ _ theorem abs_dist_sub_le (x y z : α) : abs (dist x z - dist y z) ≤ dist x y := abs_sub_le_iff.2 ⟨sub_le_iff_le_add.2 (dist_triangle _ _ _), sub_le_iff_le_add.2 (dist_triangle_left _ _ _)⟩ theorem dist_nonneg {x y : α} : 0 ≤ dist x y := have 2 * dist x y ≥ 0, from calc 2 * dist x y = dist x y + dist y x : by rw [dist_comm x y, two_mul] ... ≥ 0 : by rw ← dist_self x; apply dist_triangle, nonneg_of_mul_nonneg_left this two_pos @[simp] theorem dist_le_zero {x y : α} : dist x y ≤ 0 ↔ x = y := by simpa [le_antisymm_iff, dist_nonneg] using @dist_eq_zero _ _ x y @[simp] theorem dist_pos {x y : α} : 0 < dist x y ↔ x ≠ y := by simpa only [not_le] using not_congr dist_le_zero @[simp] theorem abs_dist {a b : α} : abs (dist a b) = dist a b := abs_of_nonneg dist_nonneg theorem eq_of_forall_dist_le {x y : α} (h : ∀ ε > 0, dist x y ≤ ε) : x = y := eq_of_dist_eq_zero (eq_of_le_of_forall_le_of_dense dist_nonneg h) /-- Distance as a nonnegative real number. -/ def nndist (a b : α) : nnreal := ⟨dist a b, dist_nonneg⟩ /--Express `nndist` in terms of `edist`-/ lemma nndist_edist (x y : α) : nndist x y = (edist x y).to_nnreal := by simp [nndist, edist_dist, nnreal.of_real, max_eq_left dist_nonneg, ennreal.of_real] /--Express `edist` in terms of `nndist`-/ lemma edist_nndist (x y : α) : edist x y = ↑(nndist x y) := by { rw [edist_dist, nndist, ennreal.of_real_eq_coe_nnreal] } /--In a metric space, the extended distance is always finite-/ lemma edist_ne_top (x y : α) : edist x y ≠ ⊤ := by rw [edist_dist x y]; apply ennreal.coe_ne_top /--In a metric space, the extended distance is always finite-/ lemma edist_lt_top {α : Type*} [metric_space α] (x y : α) : edist x y < ⊤ := ennreal.lt_top_iff_ne_top.2 (edist_ne_top x y) /--`nndist x x` vanishes-/ @[simp] lemma nndist_self (a : α) : nndist a a = 0 := (nnreal.coe_eq_zero _).1 (dist_self a) /--Express `dist` in terms of `nndist`-/ lemma dist_nndist (x y : α) : dist x y = ↑(nndist x y) := rfl /--Express `nndist` in terms of `dist`-/ lemma nndist_dist (x y : α) : nndist x y = nnreal.of_real (dist x y) := by rw [dist_nndist, nnreal.of_real_coe] /--Deduce the equality of points with the vanishing of the nonnegative distance-/ theorem eq_of_nndist_eq_zero {x y : α} : nndist x y = 0 → x = y := by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero] theorem nndist_comm (x y : α) : nndist x y = nndist y x := by simpa only [dist_nndist, nnreal.coe_eq] using dist_comm x y /--Characterize the equality of points with the vanishing of the nonnegative distance-/ @[simp] theorem nndist_eq_zero {x y : α} : nndist x y = 0 ↔ x = y := by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, dist_eq_zero] @[simp] theorem zero_eq_nndist {x y : α} : 0 = nndist x y ↔ x = y := by simp only [← nnreal.eq_iff, ← dist_nndist, imp_self, nnreal.coe_zero, zero_eq_dist] /--Triangle inequality for the nonnegative distance-/ theorem nndist_triangle (x y z : α) : nndist x z ≤ nndist x y + nndist y z := by simpa [nnreal.coe_le_coe] using dist_triangle x y z theorem nndist_triangle_left (x y z : α) : nndist x y ≤ nndist z x + nndist z y := by simpa [nnreal.coe_le_coe] using dist_triangle_left x y z theorem nndist_triangle_right (x y z : α) : nndist x y ≤ nndist x z + nndist y z := by simpa [nnreal.coe_le_coe] using dist_triangle_right x y z /--Express `dist` in terms of `edist`-/ lemma dist_edist (x y : α) : dist x y = (edist x y).to_real := by rw [edist_dist, ennreal.to_real_of_real (dist_nonneg)] namespace metric /- instantiate metric space as a topology -/ variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α} /-- `ball x ε` is the set of all points `y` with `dist y x < ε` -/ def ball (x : α) (ε : ℝ) : set α := {y | dist y x < ε} @[simp] theorem mem_ball : y ∈ ball x ε ↔ dist y x < ε := iff.rfl theorem mem_ball' : y ∈ ball x ε ↔ dist x y < ε := by rw dist_comm; refl @[simp] lemma nonempty_ball (h : 0 < ε) : (ball x ε).nonempty := ⟨x, by simp [h]⟩ lemma ball_eq_ball (ε : ℝ) (x : α) : uniform_space.ball x {p | dist p.2 p.1 < ε} = metric.ball x ε := rfl lemma ball_eq_ball' (ε : ℝ) (x : α) : uniform_space.ball x {p | dist p.1 p.2 < ε} = metric.ball x ε := by { ext, simp [dist_comm, uniform_space.ball] } /-- `closed_ball x ε` is the set of all points `y` with `dist y x ≤ ε` -/ def closed_ball (x : α) (ε : ℝ) := {y | dist y x ≤ ε} /-- `sphere x ε` is the set of all points `y` with `dist y x = ε` -/ def sphere (x : α) (ε : ℝ) := {y | dist y x = ε} @[simp] theorem mem_closed_ball : y ∈ closed_ball x ε ↔ dist y x ≤ ε := iff.rfl lemma nonempty_closed_ball (h : 0 ≤ ε) : (closed_ball x ε).nonempty := ⟨x, by simp [h]⟩ theorem ball_subset_closed_ball : ball x ε ⊆ closed_ball x ε := assume y (hy : _ < _), le_of_lt hy theorem sphere_subset_closed_ball : sphere x ε ⊆ closed_ball x ε := λ y, le_of_eq theorem sphere_disjoint_ball : disjoint (sphere x ε) (ball x ε) := λ y ⟨hy₁, hy₂⟩, absurd hy₁ $ ne_of_lt hy₂ @[simp] theorem ball_union_sphere : ball x ε ∪ sphere x ε = closed_ball x ε := set.ext $ λ y, (@le_iff_lt_or_eq ℝ _ _ _).symm @[simp] theorem sphere_union_ball : sphere x ε ∪ ball x ε = closed_ball x ε := by rw [union_comm, ball_union_sphere] @[simp] theorem closed_ball_diff_sphere : closed_ball x ε \ sphere x ε = ball x ε := by rw [← ball_union_sphere, set.union_diff_cancel_right sphere_disjoint_ball.symm] @[simp] theorem closed_ball_diff_ball : closed_ball x ε \ ball x ε = sphere x ε := by rw [← ball_union_sphere, set.union_diff_cancel_left sphere_disjoint_ball.symm] theorem pos_of_mem_ball (hy : y ∈ ball x ε) : 0 < ε := lt_of_le_of_lt dist_nonneg hy theorem mem_ball_self (h : 0 < ε) : x ∈ ball x ε := show dist x x < ε, by rw dist_self; assumption theorem mem_closed_ball_self (h : 0 ≤ ε) : x ∈ closed_ball x ε := show dist x x ≤ ε, by rw dist_self; assumption theorem mem_ball_comm : x ∈ ball y ε ↔ y ∈ ball x ε := by simp [dist_comm] theorem ball_subset_ball (h : ε₁ ≤ ε₂) : ball x ε₁ ⊆ ball x ε₂ := λ y (yx : _ < ε₁), lt_of_lt_of_le yx h theorem closed_ball_subset_closed_ball {α : Type u} [metric_space α] {ε₁ ε₂ : ℝ} {x : α} (h : ε₁ ≤ ε₂) : closed_ball x ε₁ ⊆ closed_ball x ε₂ := λ y (yx : _ ≤ ε₁), le_trans yx h theorem ball_disjoint (h : ε₁ + ε₂ ≤ dist x y) : ball x ε₁ ∩ ball y ε₂ = ∅ := eq_empty_iff_forall_not_mem.2 $ λ z ⟨h₁, h₂⟩, not_lt_of_le (dist_triangle_left x y z) (lt_of_lt_of_le (add_lt_add h₁ h₂) h) theorem ball_disjoint_same (h : ε ≤ dist x y / 2) : ball x ε ∩ ball y ε = ∅ := ball_disjoint $ by rwa [← two_mul, ← le_div_iff' (@two_pos ℝ _)] theorem ball_subset (h : dist x y ≤ ε₂ - ε₁) : ball x ε₁ ⊆ ball y ε₂ := λ z zx, by rw ← add_sub_cancel'_right ε₁ ε₂; exact lt_of_le_of_lt (dist_triangle z x y) (add_lt_add_of_lt_of_le zx h) theorem ball_half_subset (y) (h : y ∈ ball x (ε / 2)) : ball y (ε / 2) ⊆ ball x ε := ball_subset $ by rw sub_self_div_two; exact le_of_lt h theorem exists_ball_subset_ball (h : y ∈ ball x ε) : ∃ ε' > 0, ball y ε' ⊆ ball x ε := ⟨_, sub_pos.2 h, ball_subset $ by rw sub_sub_self⟩ @[simp] theorem ball_eq_empty_iff_nonpos : ball x ε = ∅ ↔ ε ≤ 0 := eq_empty_iff_forall_not_mem.trans ⟨λ h, le_of_not_gt $ λ ε0, h _ $ mem_ball_self ε0, λ ε0 y h, not_lt_of_le ε0 $ pos_of_mem_ball h⟩ @[simp] theorem closed_ball_eq_empty_iff_neg : closed_ball x ε = ∅ ↔ ε < 0 := eq_empty_iff_forall_not_mem.trans ⟨λ h, not_le.1 $ λ ε0, h x $ mem_closed_ball_self ε0, λ ε0 y h, not_lt_of_le (mem_closed_ball.1 h) (lt_of_lt_of_le ε0 dist_nonneg)⟩ @[simp] lemma ball_zero : ball x 0 = ∅ := by rw [ball_eq_empty_iff_nonpos] @[simp] lemma closed_ball_zero : closed_ball x 0 = {x} := set.ext $ λ y, dist_le_zero theorem uniformity_basis_dist : (𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 < ε}) := begin rw ← metric_space.uniformity_dist.symm, refine has_basis_binfi_principal _ nonempty_Ioi, exact λ r (hr : 0 < r) p (hp : 0 < p), ⟨min r p, lt_min hr hp, λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_left r p), λ x (hx : dist _ _ < _), lt_of_lt_of_le hx (min_le_right r p)⟩ end /-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then `f i`-neighborhoods of the diagonal form a basis of `𝓤 α`. For specific bases see `uniformity_basis_dist`, `uniformity_basis_dist_inv_nat_succ`, and `uniformity_basis_dist_inv_nat_pos`. -/ protected theorem mk_uniformity_basis {β : Type*} {p : β → Prop} {f : β → ℝ} (hf₀ : ∀ i, p i → 0 < f i) (hf : ∀ ⦃ε⦄, 0 < ε → ∃ i (hi : p i), f i ≤ ε) : (𝓤 α).has_basis p (λ i, {p:α×α | dist p.1 p.2 < f i}) := begin refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, obtain ⟨i, hi, H⟩ : ∃ i (hi : p i), f i ≤ ε, from hf ε₀, exact ⟨i, hi, λ x (hx : _ < _), hε $ lt_of_lt_of_le hx H⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, H⟩ } end theorem uniformity_basis_dist_inv_nat_succ : (𝓤 α).has_basis (λ _, true) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / (↑n+1) }) := metric.mk_uniformity_basis (λ n _, div_pos zero_lt_one $ nat.cast_add_one_pos n) (λ ε ε0, (exists_nat_one_div_lt ε0).imp $ λ n hn, ⟨trivial, le_of_lt hn⟩) theorem uniformity_basis_dist_inv_nat_pos : (𝓤 α).has_basis (λ n:ℕ, 0<n) (λ n:ℕ, {p:α×α | dist p.1 p.2 < 1 / ↑n }) := metric.mk_uniformity_basis (λ n hn, div_pos zero_lt_one $ nat.cast_pos.2 hn) (λ ε ε0, let ⟨n, hn⟩ := exists_nat_one_div_lt ε0 in ⟨n+1, nat.succ_pos n, le_of_lt hn⟩) /-- Given `f : β → ℝ`, if `f` sends `{i | p i}` to a set of positive numbers accumulating to zero, then closed neighborhoods of the diagonal of sizes `{f i | p i}` form a basis of `𝓤 α`. Currently we have only one specific basis `uniformity_basis_dist_le` based on this constructor. More can be easily added if needed in the future. -/ protected theorem mk_uniformity_basis_le {β : Type*} {p : β → Prop} {f : β → ℝ} (hf₀ : ∀ x, p x → 0 < f x) (hf : ∀ ε, 0 < ε → ∃ x (hx : p x), f x ≤ ε) : (𝓤 α).has_basis p (λ x, {p:α×α | dist p.1 p.2 ≤ f x}) := begin refine ⟨λ s, uniformity_basis_dist.mem_iff.trans _⟩, split, { rintros ⟨ε, ε₀, hε⟩, rcases dense ε₀ with ⟨ε', hε'⟩, rcases hf ε' hε'.1 with ⟨i, hi, H⟩, exact ⟨i, hi, λ x (hx : _ ≤ _), hε $ lt_of_le_of_lt (le_trans hx H) hε'.2⟩ }, { exact λ ⟨i, hi, H⟩, ⟨f i, hf₀ i hi, λ x (hx : _ < _), H (le_of_lt hx)⟩ } end /-- Contant size closed neighborhoods of the diagonal form a basis of the uniformity filter. -/ theorem uniformity_basis_dist_le : (𝓤 α).has_basis (λ ε : ℝ, 0 < ε) (λ ε, {p:α×α | dist p.1 p.2 ≤ ε}) := metric.mk_uniformity_basis_le (λ _, id) (λ ε ε₀, ⟨ε, ε₀, le_refl ε⟩) theorem mem_uniformity_dist {s : set (α×α)} : s ∈ 𝓤 α ↔ (∃ε>0, ∀{a b:α}, dist a b < ε → (a, b) ∈ s) := uniformity_basis_dist.mem_uniformity_iff /-- A constant size neighborhood of the diagonal is an entourage. -/ theorem dist_mem_uniformity {ε:ℝ} (ε0 : 0 < ε) : {p:α×α | dist p.1 p.2 < ε} ∈ 𝓤 α := mem_uniformity_dist.2 ⟨ε, ε0, λ a b, id⟩ theorem uniform_continuous_iff [metric_space β] {f : α → β} : uniform_continuous f ↔ ∀ ε > 0, ∃ δ > 0, ∀{a b:α}, dist a b < δ → dist (f a) (f b) < ε := uniformity_basis_dist.uniform_continuous_iff uniformity_basis_dist lemma uniform_continuous_on_iff [metric_space β] {f : α → β} {s : set α} : uniform_continuous_on f s ↔ ∀ ε > 0, ∃ δ > 0, ∀ x y ∈ s, dist x y < δ → dist (f x) (f y) < ε := begin dsimp [uniform_continuous_on], rw (metric.uniformity_basis_dist.inf_principal (s.prod s)).tendsto_iff metric.uniformity_basis_dist, simp only [and_imp, exists_prop, prod.forall, mem_inter_eq, gt_iff_lt, mem_set_of_eq, mem_prod], finish, end theorem uniform_embedding_iff [metric_space β] {f : α → β} : uniform_embedding f ↔ function.injective f ∧ uniform_continuous f ∧ ∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ := uniform_embedding_def'.trans $ and_congr iff.rfl $ and_congr iff.rfl ⟨λ H δ δ0, let ⟨t, tu, ht⟩ := H _ (dist_mem_uniformity δ0), ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 tu in ⟨ε, ε0, λ a b h, ht _ _ (hε h)⟩, λ H s su, let ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 su, ⟨ε, ε0, hε⟩ := H _ δ0 in ⟨_, dist_mem_uniformity ε0, λ a b h, hδ (hε h)⟩⟩ /-- A map between metric spaces is a uniform embedding if and only if the distance between `f x` and `f y` is controlled in terms of the distance between `x` and `y` and conversely. -/ theorem uniform_embedding_iff' [metric_space β] {f : α → β} : uniform_embedding f ↔ (∀ ε > 0, ∃ δ > 0, ∀ {a b : α}, dist a b < δ → dist (f a) (f b) < ε) ∧ (∀ δ > 0, ∃ ε > 0, ∀ {a b : α}, dist (f a) (f b) < ε → dist a b < δ) := begin split, { assume h, exact ⟨uniform_continuous_iff.1 (uniform_embedding_iff.1 h).2.1, (uniform_embedding_iff.1 h).2.2⟩ }, { rintros ⟨h₁, h₂⟩, refine uniform_embedding_iff.2 ⟨_, uniform_continuous_iff.2 h₁, h₂⟩, assume x y hxy, have : dist x y ≤ 0, { refine le_of_forall_lt' (λδ δpos, _), rcases h₂ δ δpos with ⟨ε, εpos, hε⟩, have : dist (f x) (f y) < ε, by simpa [hxy], exact hε this }, simpa using this } end theorem totally_bounded_iff {s : set α} : totally_bounded s ↔ ∀ ε > 0, ∃t : set α, finite t ∧ s ⊆ ⋃y∈t, ball y ε := ⟨λ H ε ε0, H _ (dist_mem_uniformity ε0), λ H r ru, let ⟨ε, ε0, hε⟩ := mem_uniformity_dist.1 ru, ⟨t, ft, h⟩ := H ε ε0 in ⟨t, ft, subset.trans h $ Union_subset_Union $ λ y, Union_subset_Union $ λ yt z, hε⟩⟩ /-- A metric space space is totally bounded if one can reconstruct up to any ε>0 any element of the space from finitely many data. -/ lemma totally_bounded_of_finite_discretization {s : set α} (H : ∀ε > (0 : ℝ), ∃ (β : Type u) [fintype β] (F : s → β), ∀x y, F x = F y → dist (x:α) y < ε) : totally_bounded s := begin cases s.eq_empty_or_nonempty with hs hs, { rw hs, exact totally_bounded_empty }, rcases hs with ⟨x0, hx0⟩, haveI : inhabited s := ⟨⟨x0, hx0⟩⟩, refine totally_bounded_iff.2 (λ ε ε0, _), rcases H ε ε0 with ⟨β, fβ, F, hF⟩, resetI, let Finv := function.inv_fun F, refine ⟨range (subtype.val ∘ Finv), finite_range _, λ x xs, _⟩, let x' := Finv (F ⟨x, xs⟩), have : F x' = F ⟨x, xs⟩ := function.inv_fun_eq ⟨⟨x, xs⟩, rfl⟩, simp only [set.mem_Union, set.mem_range], exact ⟨_, ⟨F ⟨x, xs⟩, rfl⟩, hF _ _ this.symm⟩ end theorem finite_approx_of_totally_bounded {s : set α} (hs : totally_bounded s) : ∀ ε > 0, ∃ t ⊆ s, finite t ∧ s ⊆ ⋃y∈t, ball y ε := begin intros ε ε_pos, rw totally_bounded_iff_subset at hs, exact hs _ (dist_mem_uniformity ε_pos), end /-- Expressing locally uniform convergence on a set using `dist`. -/ lemma tendsto_locally_uniformly_on_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_locally_uniformly_on F f p s ↔ ∀ ε > 0, ∀ x ∈ s, ∃ t ∈ 𝓝[s] x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε := begin refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu x hx, _⟩, rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩, rcases H ε εpos x hx with ⟨t, ht, Ht⟩, exact ⟨t, ht, Ht.mono (λ n hs x hx, hε (hs x hx))⟩ end /-- Expressing uniform convergence on a set using `dist`. -/ lemma tendsto_uniformly_on_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} {s : set β} : tendsto_uniformly_on F f p s ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x ∈ s, dist (f x) (F n x) < ε := begin refine ⟨λ H ε hε, H _ (dist_mem_uniformity hε), λ H u hu, _⟩, rcases mem_uniformity_dist.1 hu with ⟨ε, εpos, hε⟩, exact (H ε εpos).mono (λ n hs x hx, hε (hs x hx)) end /-- Expressing locally uniform convergence using `dist`. -/ lemma tendsto_locally_uniformly_iff {ι : Type*} [topological_space β] {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_locally_uniformly F f p ↔ ∀ ε > 0, ∀ (x : β), ∃ t ∈ 𝓝 x, ∀ᶠ n in p, ∀ y ∈ t, dist (f y) (F n y) < ε := by simp only [← tendsto_locally_uniformly_on_univ, tendsto_locally_uniformly_on_iff, nhds_within_univ, mem_univ, forall_const, exists_prop] /-- Expressing uniform convergence using `dist`. -/ lemma tendsto_uniformly_iff {ι : Type*} {F : ι → β → α} {f : β → α} {p : filter ι} : tendsto_uniformly F f p ↔ ∀ ε > 0, ∀ᶠ n in p, ∀ x, dist (f x) (F n x) < ε := by { rw [← tendsto_uniformly_on_univ, tendsto_uniformly_on_iff], simp } protected lemma cauchy_iff {f : filter α} : cauchy f ↔ ne_bot f ∧ ∀ ε > 0, ∃ t ∈ f, ∀ x y ∈ t, dist x y < ε := uniformity_basis_dist.cauchy_iff theorem nhds_basis_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (ball x) := nhds_basis_uniformity uniformity_basis_dist theorem mem_nhds_iff : s ∈ 𝓝 x ↔ ∃ε>0, ball x ε ⊆ s := nhds_basis_ball.mem_iff theorem nhds_basis_closed_ball : (𝓝 x).has_basis (λ ε:ℝ, 0 < ε) (closed_ball x) := nhds_basis_uniformity uniformity_basis_dist_le theorem nhds_basis_ball_inv_nat_succ : (𝓝 x).has_basis (λ _, true) (λ n:ℕ, ball x (1 / (↑n+1))) := nhds_basis_uniformity uniformity_basis_dist_inv_nat_succ theorem nhds_basis_ball_inv_nat_pos : (𝓝 x).has_basis (λ n, 0<n) (λ n:ℕ, ball x (1 / ↑n)) := nhds_basis_uniformity uniformity_basis_dist_inv_nat_pos theorem is_open_iff : is_open s ↔ ∀x∈s, ∃ε>0, ball x ε ⊆ s := by simp only [is_open_iff_mem_nhds, mem_nhds_iff] theorem is_open_ball : is_open (ball x ε) := is_open_iff.2 $ λ y, exists_ball_subset_ball theorem ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : ball x ε ∈ 𝓝 x := mem_nhds_sets is_open_ball (mem_ball_self ε0) theorem closed_ball_mem_nhds (x : α) {ε : ℝ} (ε0 : 0 < ε) : closed_ball x ε ∈ 𝓝 x := mem_sets_of_superset (ball_mem_nhds x ε0) ball_subset_closed_ball theorem nhds_within_basis_ball {s : set α} : (𝓝[s] x).has_basis (λ ε:ℝ, 0 < ε) (λ ε, ball x ε ∩ s) := nhds_within_has_basis nhds_basis_ball s theorem mem_nhds_within_iff {t : set α} : s ∈ 𝓝[t] x ↔ ∃ε>0, ball x ε ∩ t ⊆ s := nhds_within_basis_ball.mem_iff theorem tendsto_nhds_within_nhds_within [metric_space β] {t : set β} {f : α → β} {a b} : tendsto f (𝓝[s] a) (𝓝[t] b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → f x ∈ t ∧ dist (f x) b < ε := (nhds_within_basis_ball.tendsto_iff nhds_within_basis_ball).trans $ by simp only [inter_comm, mem_inter_iff, and_imp, mem_ball] theorem tendsto_nhds_within_nhds [metric_space β] {f : α → β} {a b} : tendsto f (𝓝[s] a) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) b < ε := by { rw [← nhds_within_univ b, tendsto_nhds_within_nhds_within], simp only [mem_univ, true_and] } theorem tendsto_nhds_nhds [metric_space β] {f : α → β} {a b} : tendsto f (𝓝 a) (𝓝 b) ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) b < ε := nhds_basis_ball.tendsto_iff nhds_basis_ball theorem continuous_at_iff [metric_space β] {f : α → β} {a : α} : continuous_at f a ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, dist x a < δ → dist (f x) (f a) < ε := by rw [continuous_at, tendsto_nhds_nhds] theorem continuous_within_at_iff [metric_space β] {f : α → β} {a : α} {s : set α} : continuous_within_at f s a ↔ ∀ ε > 0, ∃ δ > 0, ∀{x:α}, x ∈ s → dist x a < δ → dist (f x) (f a) < ε := by rw [continuous_within_at, tendsto_nhds_within_nhds] theorem continuous_on_iff [metric_space β] {f : α → β} {s : set α} : continuous_on f s ↔ ∀ (b ∈ s) (ε > 0), ∃ δ > 0, ∀a ∈ s, dist a b < δ → dist (f a) (f b) < ε := by simp [continuous_on, continuous_within_at_iff] theorem continuous_iff [metric_space β] {f : α → β} : continuous f ↔ ∀b (ε > 0), ∃ δ > 0, ∀a, dist a b < δ → dist (f a) (f b) < ε := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds_nhds theorem tendsto_nhds {f : filter β} {u : β → α} {a : α} : tendsto u f (𝓝 a) ↔ ∀ ε > 0, ∀ᶠ x in f, dist (u x) a < ε := nhds_basis_ball.tendsto_right_iff theorem continuous_at_iff' [topological_space β] {f : β → α} {b : β} : continuous_at f b ↔ ∀ ε > 0, ∀ᶠ x in 𝓝 b, dist (f x) (f b) < ε := by rw [continuous_at, tendsto_nhds] theorem continuous_within_at_iff' [topological_space β] {f : β → α} {b : β} {s : set β} : continuous_within_at f s b ↔ ∀ ε > 0, ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε := by rw [continuous_within_at, tendsto_nhds] theorem continuous_on_iff' [topological_space β] {f : β → α} {s : set β} : continuous_on f s ↔ ∀ (b ∈ s) (ε > 0), ∀ᶠ x in 𝓝[s] b, dist (f x) (f b) < ε := by simp [continuous_on, continuous_within_at_iff'] theorem continuous_iff' [topological_space β] {f : β → α} : continuous f ↔ ∀a (ε > 0), ∀ᶠ x in 𝓝 a, dist (f x) (f a) < ε := continuous_iff_continuous_at.trans $ forall_congr $ λ b, tendsto_nhds theorem tendsto_at_top [nonempty β] [semilattice_sup β] {u : β → α} {a : α} : tendsto u at_top (𝓝 a) ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) a < ε := (at_top_basis.tendsto_iff nhds_basis_ball).trans $ by { simp only [exists_prop, true_and], refl } end metric open metric @[priority 100] -- see Note [lower instance priority] instance metric_space.to_separated : separated_space α := separated_def.2 $ λ x y h, eq_of_forall_dist_le $ λ ε ε0, le_of_lt (h _ (dist_mem_uniformity ε0)) /-Instantiate a metric space as an emetric space. Before we can state the instance, we need to show that the uniform structure coming from the edistance and the distance coincide. -/ /-- Expressing the uniformity in terms of `edist` -/ protected lemma metric.uniformity_basis_edist : (𝓤 α).has_basis (λ ε:ennreal, 0 < ε) (λ ε, {p | edist p.1 p.2 < ε}) := ⟨begin intro t, refine mem_uniformity_dist.trans ⟨_, _⟩; rintro ⟨ε, ε0, Hε⟩, { use [ennreal.of_real ε, ennreal.of_real_pos.2 ε0], rintros ⟨a, b⟩, simp only [edist_dist, ennreal.of_real_lt_of_real_iff ε0], exact Hε }, { rcases ennreal.lt_iff_exists_real_btwn.1 ε0 with ⟨ε', _, ε0', hε⟩, rw [ennreal.of_real_pos] at ε0', refine ⟨ε', ε0', λ a b h, Hε (lt_trans _ hε)⟩, rwa [edist_dist, ennreal.of_real_lt_of_real_iff ε0'] } end⟩ theorem metric.uniformity_edist : 𝓤 α = (⨅ ε>0, 𝓟 {p:α×α | edist p.1 p.2 < ε}) := metric.uniformity_basis_edist.eq_binfi /-- A metric space induces an emetric space -/ @[priority 100] -- see Note [lower instance priority] instance metric_space.to_emetric_space : emetric_space α := { edist := edist, edist_self := by simp [edist_dist], eq_of_edist_eq_zero := assume x y h, by simpa [edist_dist] using h, edist_comm := by simp only [edist_dist, dist_comm]; simp, edist_triangle := assume x y z, begin simp only [edist_dist, ← ennreal.of_real_add, dist_nonneg], rw ennreal.of_real_le_of_real_iff _, { exact dist_triangle _ _ _ }, { simpa using add_le_add (dist_nonneg : 0 ≤ dist x y) dist_nonneg } end, uniformity_edist := metric.uniformity_edist, ..‹metric_space α› } /-- Balls defined using the distance or the edistance coincide -/ lemma metric.emetric_ball {x : α} {ε : ℝ} : emetric.ball x (ennreal.of_real ε) = ball x ε := begin ext y, simp only [emetric.mem_ball, mem_ball, edist_dist], exact ennreal.of_real_lt_of_real_iff_of_nonneg dist_nonneg end /-- Balls defined using the distance or the edistance coincide -/ lemma metric.emetric_ball_nnreal {x : α} {ε : nnreal} : emetric.ball x ε = ball x ε := by { convert metric.emetric_ball, simp } /-- Closed balls defined using the distance or the edistance coincide -/ lemma metric.emetric_closed_ball {x : α} {ε : ℝ} (h : 0 ≤ ε) : emetric.closed_ball x (ennreal.of_real ε) = closed_ball x ε := by ext y; simp [edist_dist]; rw ennreal.of_real_le_of_real_iff h /-- Closed balls defined using the distance or the edistance coincide -/ lemma metric.emetric_closed_ball_nnreal {x : α} {ε : nnreal} : emetric.closed_ball x ε = closed_ball x ε := by { convert metric.emetric_closed_ball ε.2, simp } /-- Build a new metric space from an old one where the bundled uniform structure is provably (but typically non-definitionaly) equal to some given uniform structure. See Note [forgetful inheritance]. -/ def metric_space.replace_uniformity {α} [U : uniform_space α] (m : metric_space α) (H : @uniformity _ U = @uniformity _ emetric_space.to_uniform_space') : metric_space α := { dist := @dist _ m.to_has_dist, dist_self := dist_self, eq_of_dist_eq_zero := @eq_of_dist_eq_zero _ _, dist_comm := dist_comm, dist_triangle := dist_triangle, edist := edist, edist_dist := edist_dist, to_uniform_space := U, uniformity_dist := H.trans metric_space.uniformity_dist } /-- One gets a metric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the metric space and the emetric space. In this definition, the distance is given separately, to be able to prescribe some expression which is not defeq to the push-forward of the edistance to reals. -/ def emetric_space.to_metric_space_of_dist {α : Type u} [e : emetric_space α] (dist : α → α → ℝ) (edist_ne_top : ∀x y: α, edist x y ≠ ⊤) (h : ∀x y, dist x y = ennreal.to_real (edist x y)) : metric_space α := let m : metric_space α := { dist := dist, eq_of_dist_eq_zero := λx y hxy, by simpa [h, ennreal.to_real_eq_zero_iff, edist_ne_top x y] using hxy, dist_self := λx, by simp [h], dist_comm := λx y, by simp [h, emetric_space.edist_comm], dist_triangle := λx y z, begin simp only [h], rw [← ennreal.to_real_add (edist_ne_top _ _) (edist_ne_top _ _), ennreal.to_real_le_to_real (edist_ne_top _ _)], { exact edist_triangle _ _ _ }, { simp [ennreal.add_eq_top, edist_ne_top] } end, edist := λx y, edist x y, edist_dist := λx y, by simp [h, ennreal.of_real_to_real, edist_ne_top] } in m.replace_uniformity $ by { rw [uniformity_edist, metric.uniformity_edist], refl } /-- One gets a metric space from an emetric space if the edistance is everywhere finite, by pushing the edistance to reals. We set it up so that the edist and the uniformity are defeq in the metric space and the emetric space. -/ def emetric_space.to_metric_space {α : Type u} [e : emetric_space α] (h : ∀x y: α, edist x y ≠ ⊤) : metric_space α := emetric_space.to_metric_space_of_dist (λx y, ennreal.to_real (edist x y)) h (λx y, rfl) /-- A very useful criterion to show that a space is complete is to show that all sequences which satisfy a bound of the form `dist (u n) (u m) < B N` for all `n m ≥ N` are converging. This is often applied for `B N = 2^{-N}`, i.e., with a very fast convergence to `0`, which makes it possible to use arguments of converging series, while this is impossible to do in general for arbitrary Cauchy sequences. -/ theorem metric.complete_of_convergent_controlled_sequences (B : ℕ → real) (hB : ∀n, 0 < B n) (H : ∀u : ℕ → α, (∀N n m : ℕ, N ≤ n → N ≤ m → dist (u n) (u m) < B N) → ∃x, tendsto u at_top (𝓝 x)) : complete_space α := begin -- this follows from the same criterion in emetric spaces. We just need to translate -- the convergence assumption from `dist` to `edist` apply emetric.complete_of_convergent_controlled_sequences (λn, ennreal.of_real (B n)), { simp [hB] }, { assume u Hu, apply H, assume N n m hn hm, rw [← ennreal.of_real_lt_of_real_iff (hB N), ← edist_dist], exact Hu N n m hn hm } end theorem metric.complete_of_cauchy_seq_tendsto : (∀ u : ℕ → α, cauchy_seq u → ∃a, tendsto u at_top (𝓝 a)) → complete_space α := emetric.complete_of_cauchy_seq_tendsto section real /-- Instantiate the reals as a metric space. -/ instance real.metric_space : metric_space ℝ := { dist := λx y, abs (x - y), dist_self := by simp [abs_zero], eq_of_dist_eq_zero := by simp [sub_eq_zero], dist_comm := assume x y, abs_sub _ _, dist_triangle := assume x y z, abs_sub_le _ _ _ } theorem real.dist_eq (x y : ℝ) : dist x y = abs (x - y) := rfl theorem real.dist_0_eq_abs (x : ℝ) : dist x 0 = abs x := by simp [real.dist_eq] instance : order_topology ℝ := order_topology_of_nhds_abs $ λ x, begin simp only [show ∀ r, {b : ℝ | abs (x - b) < r} = ball x r, by simp [abs_sub, ball, real.dist_eq]], apply le_antisymm, { simp [le_infi_iff], exact λ ε ε0, mem_nhds_sets (is_open_ball) (mem_ball_self ε0) }, { intros s h, rcases mem_nhds_iff.1 h with ⟨ε, ε0, ss⟩, exact mem_infi_sets _ (mem_infi_sets ε0 (mem_principal_sets.2 ss)) }, end lemma closed_ball_Icc {x r : ℝ} : closed_ball x r = Icc (x-r) (x+r) := by ext y; rw [mem_closed_ball, dist_comm, real.dist_eq, abs_sub_le_iff, mem_Icc, ← sub_le_iff_le_add', sub_le] /-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the general case. -/ lemma squeeze_zero' {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀ᶠ t in t₀, 0 ≤ f t) (hft : ∀ᶠ t in t₀, f t ≤ g t) (g0 : tendsto g t₀ (nhds 0)) : tendsto f t₀ (nhds 0) := tendsto_of_tendsto_of_tendsto_of_le_of_le' tendsto_const_nhds g0 hf hft /-- Special case of the sandwich theorem; see `tendsto_of_tendsto_of_tendsto_of_le_of_le` and `tendsto_of_tendsto_of_tendsto_of_le_of_le'` for the general case. -/ lemma squeeze_zero {α} {f g : α → ℝ} {t₀ : filter α} (hf : ∀t, 0 ≤ f t) (hft : ∀t, f t ≤ g t) (g0 : tendsto g t₀ (𝓝 0)) : tendsto f t₀ (𝓝 0) := squeeze_zero' (eventually_of_forall hf) (eventually_of_forall hft) g0 theorem metric.uniformity_eq_comap_nhds_zero : 𝓤 α = comap (λp:α×α, dist p.1 p.2) (𝓝 (0 : ℝ)) := by { ext s, simp [mem_uniformity_dist, (nhds_basis_ball.comap _).mem_iff, subset_def, real.dist_0_eq_abs] } lemma cauchy_seq_iff_tendsto_dist_at_top_0 [nonempty β] [semilattice_sup β] {u : β → α} : cauchy_seq u ↔ tendsto (λ (n : β × β), dist (u n.1) (u n.2)) at_top (𝓝 0) := by rw [cauchy_seq_iff_tendsto, metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff, prod.map_def] lemma tendsto_uniformity_iff_dist_tendsto_zero {ι : Type*} {f : ι → α × α} {p : filter ι} : tendsto f p (𝓤 α) ↔ tendsto (λ x, dist (f x).1 (f x).2) p (𝓝 0) := by rw [metric.uniformity_eq_comap_nhds_zero, tendsto_comap_iff] lemma filter.tendsto.congr_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α} (h₁ : tendsto f₁ p (𝓝 a)) (h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) : tendsto f₂ p (𝓝 a) := h₁.congr_uniformity $ tendsto_uniformity_iff_dist_tendsto_zero.2 h alias filter.tendsto.congr_dist ← tendsto_of_tendsto_of_dist lemma tendsto_iff_of_dist {ι : Type*} {f₁ f₂ : ι → α} {p : filter ι} {a : α} (h : tendsto (λ x, dist (f₁ x) (f₂ x)) p (𝓝 0)) : tendsto f₁ p (𝓝 a) ↔ tendsto f₂ p (𝓝 a) := uniform.tendsto_congr $ tendsto_uniformity_iff_dist_tendsto_zero.2 h end real section cauchy_seq variables [nonempty β] [semilattice_sup β] /-- In a metric space, Cauchy sequences are characterized by the fact that, eventually, the distance between its elements is arbitrarily small -/ @[nolint ge_or_gt] -- see Note [nolint_ge] theorem metric.cauchy_seq_iff {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀m n≥N, dist (u m) (u n) < ε := uniformity_basis_dist.cauchy_seq_iff /-- A variation around the metric characterization of Cauchy sequences -/ theorem metric.cauchy_seq_iff' {u : β → α} : cauchy_seq u ↔ ∀ε>0, ∃N, ∀n≥N, dist (u n) (u N) < ε := uniformity_basis_dist.cauchy_seq_iff' /-- If the distance between `s n` and `s m`, `n, m ≥ N` is bounded above by `b N` and `b` converges to zero, then `s` is a Cauchy sequence. -/ lemma cauchy_seq_of_le_tendsto_0 {s : β → α} (b : β → ℝ) (h : ∀ n m N : β, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) (h₀ : tendsto b at_top (nhds 0)) : cauchy_seq s := metric.cauchy_seq_iff.2 $ λ ε ε0, (metric.tendsto_at_top.1 h₀ ε ε0).imp $ λ N hN m n hm hn, calc dist (s m) (s n) ≤ b N : h m n N hm hn ... ≤ abs (b N) : le_abs_self _ ... = dist (b N) 0 : by rw real.dist_0_eq_abs; refl ... < ε : (hN _ (le_refl N)) /-- A Cauchy sequence on the natural numbers is bounded. -/ theorem cauchy_seq_bdd {u : ℕ → α} (hu : cauchy_seq u) : ∃ R > 0, ∀ m n, dist (u m) (u n) < R := begin rcases metric.cauchy_seq_iff'.1 hu 1 zero_lt_one with ⟨N, hN⟩, suffices : ∃ R > 0, ∀ n, dist (u n) (u N) < R, { rcases this with ⟨R, R0, H⟩, exact ⟨_, add_pos R0 R0, λ m n, lt_of_le_of_lt (dist_triangle_right _ _ _) (add_lt_add (H m) (H n))⟩ }, let R := finset.sup (finset.range N) (λ n, nndist (u n) (u N)), refine ⟨↑R + 1, add_pos_of_nonneg_of_pos R.2 zero_lt_one, λ n, _⟩, cases le_or_lt N n, { exact lt_of_lt_of_le (hN _ h) (le_add_of_nonneg_left R.2) }, { have : _ ≤ R := finset.le_sup (finset.mem_range.2 h), exact lt_of_le_of_lt this (lt_add_of_pos_right _ zero_lt_one) } end /-- Yet another metric characterization of Cauchy sequences on integers. This one is often the most efficient. -/ lemma cauchy_seq_iff_le_tendsto_0 {s : ℕ → α} : cauchy_seq s ↔ ∃ b : ℕ → ℝ, (∀ n, 0 ≤ b n) ∧ (∀ n m N : ℕ, N ≤ n → N ≤ m → dist (s n) (s m) ≤ b N) ∧ tendsto b at_top (𝓝 0) := ⟨λ hs, begin /- `s` is a Cauchy sequence. The sequence `b` will be constructed by taking the supremum of the distances between `s n` and `s m` for `n m ≥ N`. First, we prove that all these distances are bounded, as otherwise the Sup would not make sense. -/ let S := λ N, (λ(p : ℕ × ℕ), dist (s p.1) (s p.2)) '' {p | p.1 ≥ N ∧ p.2 ≥ N}, have hS : ∀ N, ∃ x, ∀ y ∈ S N, y ≤ x, { rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩, refine λ N, ⟨R, _⟩, rintro _ ⟨⟨m, n⟩, _, rfl⟩, exact le_of_lt (hR m n) }, have bdd : bdd_above (range (λ(p : ℕ × ℕ), dist (s p.1) (s p.2))), { rcases cauchy_seq_bdd hs with ⟨R, R0, hR⟩, use R, rintro _ ⟨⟨m, n⟩, rfl⟩, exact le_of_lt (hR m n) }, -- Prove that it bounds the distances of points in the Cauchy sequence have ub : ∀ m n N, N ≤ m → N ≤ n → dist (s m) (s n) ≤ Sup (S N) := λ m n N hm hn, real.le_Sup _ (hS N) ⟨⟨_, _⟩, ⟨hm, hn⟩, rfl⟩, have S0m : ∀ n, (0:ℝ) ∈ S n := λ n, ⟨⟨n, n⟩, ⟨le_refl _, le_refl _⟩, dist_self _⟩, have S0 := λ n, real.le_Sup _ (hS n) (S0m n), -- Prove that it tends to `0`, by using the Cauchy property of `s` refine ⟨λ N, Sup (S N), S0, ub, metric.tendsto_at_top.2 (λ ε ε0, _)⟩, refine (metric.cauchy_seq_iff.1 hs (ε/2) (half_pos ε0)).imp (λ N hN n hn, _), rw [real.dist_0_eq_abs, abs_of_nonneg (S0 n)], refine lt_of_le_of_lt (real.Sup_le_ub _ ⟨_, S0m _⟩ _) (half_lt_self ε0), rintro _ ⟨⟨m', n'⟩, ⟨hm', hn'⟩, rfl⟩, exact le_of_lt (hN _ _ (le_trans hn hm') (le_trans hn hn')) end, λ ⟨b, _, b_bound, b_lim⟩, cauchy_seq_of_le_tendsto_0 b b_bound b_lim⟩ end cauchy_seq /-- Metric space structure pulled back by an injective function. Injectivity is necessary to ensure that `dist x y = 0` only if `x = y`. -/ def metric_space.induced {α β} (f : α → β) (hf : function.injective f) (m : metric_space β) : metric_space α := { dist := λ x y, dist (f x) (f y), dist_self := λ x, dist_self _, eq_of_dist_eq_zero := λ x y h, hf (dist_eq_zero.1 h), dist_comm := λ x y, dist_comm _ _, dist_triangle := λ x y z, dist_triangle _ _ _, edist := λ x y, edist (f x) (f y), edist_dist := λ x y, edist_dist _ _, to_uniform_space := uniform_space.comap f m.to_uniform_space, uniformity_dist := begin apply @uniformity_dist_of_mem_uniformity _ _ _ _ _ (λ x y, dist (f x) (f y)), refine λ s, mem_comap_sets.trans _, split; intro H, { rcases H with ⟨r, ru, rs⟩, rcases mem_uniformity_dist.1 ru with ⟨ε, ε0, hε⟩, refine ⟨ε, ε0, λ a b h, rs (hε _)⟩, exact h }, { rcases H with ⟨ε, ε0, hε⟩, exact ⟨_, dist_mem_uniformity ε0, λ ⟨a, b⟩, hε⟩ } end } instance subtype.metric_space {α : Type*} {p : α → Prop} [t : metric_space α] : metric_space (subtype p) := metric_space.induced coe (λ x y, subtype.ext) t theorem subtype.dist_eq {p : α → Prop} (x y : subtype p) : dist x y = dist (x : α) y := rfl section nnreal instance : metric_space nnreal := by unfold nnreal; apply_instance lemma nnreal.dist_eq (a b : nnreal) : dist a b = abs ((a:ℝ) - b) := rfl lemma nnreal.nndist_eq (a b : nnreal) : nndist a b = max (a - b) (b - a) := begin wlog h : a ≤ b, { apply nnreal.coe_eq.1, rw [nnreal.sub_eq_zero h, max_eq_right (zero_le $ b - a), ← dist_nndist, nnreal.dist_eq, nnreal.coe_sub h, abs, neg_sub], apply max_eq_right, linarith [nnreal.coe_le_coe.2 h] }, rwa [nndist_comm, max_comm] end end nnreal section prod instance prod.metric_space_max [metric_space β] : metric_space (α × β) := { dist := λ x y, max (dist x.1 y.1) (dist x.2 y.2), dist_self := λ x, by simp, eq_of_dist_eq_zero := λ x y h, begin cases max_le_iff.1 (le_of_eq h) with h₁ h₂, exact prod.ext_iff.2 ⟨dist_le_zero.1 h₁, dist_le_zero.1 h₂⟩ end, dist_comm := λ x y, by simp [dist_comm], dist_triangle := λ x y z, max_le (le_trans (dist_triangle _ _ _) (add_le_add (le_max_left _ _) (le_max_left _ _))) (le_trans (dist_triangle _ _ _) (add_le_add (le_max_right _ _) (le_max_right _ _))), edist := λ x y, max (edist x.1 y.1) (edist x.2 y.2), edist_dist := assume x y, begin have : monotone ennreal.of_real := assume x y h, ennreal.of_real_le_of_real h, rw [edist_dist, edist_dist, ← this.map_max] end, uniformity_dist := begin refine uniformity_prod.trans _, simp only [uniformity_basis_dist.eq_binfi, comap_infi], rw ← infi_inf_eq, congr, funext, rw ← infi_inf_eq, congr, funext, simp [inf_principal, ext_iff, max_lt_iff] end, to_uniform_space := prod.uniform_space } lemma prod.dist_eq [metric_space β] {x y : α × β} : dist x y = max (dist x.1 y.1) (dist x.2 y.2) := rfl end prod theorem uniform_continuous_dist : uniform_continuous (λp:α×α, dist p.1 p.2) := metric.uniform_continuous_iff.2 (λ ε ε0, ⟨ε/2, half_pos ε0, begin suffices, { intros p q h, cases p with p₁ p₂, cases q with q₁ q₂, cases max_lt_iff.1 h with h₁ h₂, clear h, dsimp at h₁ h₂ ⊢, rw real.dist_eq, refine abs_sub_lt_iff.2 ⟨_, _⟩, { revert p₁ p₂ q₁ q₂ h₁ h₂, exact this }, { apply this; rwa dist_comm } }, intros p₁ p₂ q₁ q₂ h₁ h₂, have := add_lt_add (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₁ q₁ p₂) h₁)).1 (abs_sub_lt_iff.1 (lt_of_le_of_lt (abs_dist_sub_le p₂ q₂ q₁) h₂)).1, rwa [add_halves, dist_comm p₂, sub_add_sub_cancel, dist_comm q₂] at this end⟩) theorem uniform_continuous.dist [uniform_space β] {f g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λb, dist (f b) (g b)) := uniform_continuous_dist.comp (hf.prod_mk hg) theorem continuous_dist : continuous (λp:α×α, dist p.1 p.2) := uniform_continuous_dist.continuous theorem continuous.dist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, dist (f b) (g b)) := continuous_dist.comp (hf.prod_mk hg) theorem filter.tendsto.dist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, dist (f x) (g x)) x (𝓝 (dist a b)) := (continuous_dist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) lemma nhds_comap_dist (a : α) : (𝓝 (0 : ℝ)).comap (λa', dist a' a) = 𝓝 a := by simp only [@nhds_eq_comap_uniformity α, metric.uniformity_eq_comap_nhds_zero, comap_comap, (∘), dist_comm] lemma tendsto_iff_dist_tendsto_zero {f : β → α} {x : filter β} {a : α} : (tendsto f x (𝓝 a)) ↔ (tendsto (λb, dist (f b) a) x (𝓝 0)) := by rw [← nhds_comap_dist a, tendsto_comap_iff] lemma uniform_continuous_nndist : uniform_continuous (λp:α×α, nndist p.1 p.2) := uniform_continuous_subtype_mk uniform_continuous_dist _ lemma uniform_continuous.nndist [uniform_space β] {f g : β → α} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (λ b, nndist (f b) (g b)) := uniform_continuous_nndist.comp (hf.prod_mk hg) lemma continuous_nndist : continuous (λp:α×α, nndist p.1 p.2) := uniform_continuous_nndist.continuous lemma continuous.nndist [topological_space β] {f g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λb, nndist (f b) (g b)) := continuous_nndist.comp (hf.prod_mk hg) theorem filter.tendsto.nndist {f g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (𝓝 a)) (hg : tendsto g x (𝓝 b)) : tendsto (λx, nndist (f x) (g x)) x (𝓝 (nndist a b)) := (continuous_nndist.tendsto (a, b)).comp (hf.prod_mk_nhds hg) namespace metric variables {x y z : α} {ε ε₁ ε₂ : ℝ} {s : set α} theorem is_closed_ball : is_closed (closed_ball x ε) := is_closed_le (continuous_id.dist continuous_const) continuous_const lemma is_closed_sphere : is_closed (sphere x ε) := is_closed_eq (continuous_id.dist continuous_const) continuous_const @[simp] theorem closure_closed_ball : closure (closed_ball x ε) = closed_ball x ε := is_closed_ball.closure_eq theorem closure_ball_subset_closed_ball : closure (ball x ε) ⊆ closed_ball x ε := closure_minimal ball_subset_closed_ball is_closed_ball theorem frontier_ball_subset_sphere : frontier (ball x ε) ⊆ sphere x ε := frontier_lt_subset_eq (continuous_id.dist continuous_const) continuous_const theorem frontier_closed_ball_subset_sphere : frontier (closed_ball x ε) ⊆ sphere x ε := frontier_le_subset_eq (continuous_id.dist continuous_const) continuous_const theorem ball_subset_interior_closed_ball : ball x ε ⊆ interior (closed_ball x ε) := interior_maximal ball_subset_closed_ball is_open_ball /-- ε-characterization of the closure in metric spaces-/ theorem mem_closure_iff {α : Type u} [metric_space α] {s : set α} {a : α} : a ∈ closure s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε := (mem_closure_iff_nhds_basis nhds_basis_ball).trans $ by simp only [mem_ball, dist_comm] lemma mem_closure_range_iff {α : Type u} [metric_space α] {e : β → α} {a : α} : a ∈ closure (range e) ↔ ∀ε>0, ∃ k : β, dist a (e k) < ε := by simp only [mem_closure_iff, exists_range_iff] lemma mem_closure_range_iff_nat {α : Type u} [metric_space α] {e : β → α} {a : α} : a ∈ closure (range e) ↔ ∀n : ℕ, ∃ k : β, dist a (e k) < 1 / ((n : ℝ) + 1) := (mem_closure_iff_nhds_basis nhds_basis_ball_inv_nat_succ).trans $ by simp only [mem_ball, dist_comm, exists_range_iff, forall_const] theorem mem_of_closed' {α : Type u} [metric_space α] {s : set α} (hs : is_closed s) {a : α} : a ∈ s ↔ ∀ε>0, ∃b ∈ s, dist a b < ε := by simpa only [hs.closure_eq] using @mem_closure_iff _ _ s a end metric section pi open finset variables {π : β → Type*} [fintype β] [∀b, metric_space (π b)] /-- A finite product of metric spaces is a metric space, with the sup distance. -/ instance metric_space_pi : metric_space (Πb, π b) := begin /- we construct the instance from the emetric space instance to avoid checking again that the uniformity is the same as the product uniformity, but we register nevertheless a nice formula for the distance -/ refine emetric_space.to_metric_space_of_dist (λf g, ((sup univ (λb, nndist (f b) (g b)) : nnreal) : ℝ)) _ _, show ∀ (x y : Π (b : β), π b), edist x y ≠ ⊤, { assume x y, rw ← lt_top_iff_ne_top, have : (⊥ : ennreal) < ⊤ := ennreal.coe_lt_top, simp [edist, this], assume b, rw lt_top_iff_ne_top, exact edist_ne_top (x b) (y b) }, show ∀ (x y : Π (b : β), π b), ↑(sup univ (λ (b : β), nndist (x b) (y b))) = ennreal.to_real (sup univ (λ (b : β), edist (x b) (y b))), { assume x y, have : sup univ (λ (b : β), edist (x b) (y b)) = ↑(sup univ (λ (b : β), nndist (x b) (y b))), { simp [edist_nndist], refine eq.symm (comp_sup_eq_sup_comp_of_is_total _ _ _), exact (assume x y h, ennreal.coe_le_coe.2 h), refl }, rw this, refl } end lemma dist_pi_def (f g : Πb, π b) : dist f g = (sup univ (λb, nndist (f b) (g b)) : nnreal) := rfl lemma dist_pi_lt_iff {f g : Πb, π b} {r : ℝ} (hr : 0 < r) : dist f g < r ↔ ∀b, dist (f b) (g b) < r := begin lift r to nnreal using le_of_lt hr, rw_mod_cast [dist_pi_def, finset.sup_lt_iff], { simp [nndist], refl }, { exact hr } end lemma dist_pi_le_iff {f g : Πb, π b} {r : ℝ} (hr : 0 ≤ r) : dist f g ≤ r ↔ ∀b, dist (f b) (g b) ≤ r := begin lift r to nnreal using hr, rw_mod_cast [dist_pi_def, finset.sup_le_iff], simp [nndist], refl end /-- An open ball in a product space is a product of open balls. The assumption `0 < r` is necessary for the case of the empty product. -/ lemma ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 < r) : ball x r = { y | ∀b, y b ∈ ball (x b) r } := by { ext p, simp [dist_pi_lt_iff hr] } /-- A closed ball in a product space is a product of closed balls. The assumption `0 ≤ r` is necessary for the case of the empty product. -/ lemma closed_ball_pi (x : Πb, π b) {r : ℝ} (hr : 0 ≤ r) : closed_ball x r = { y | ∀b, y b ∈ closed_ball (x b) r } := by { ext p, simp [dist_pi_le_iff hr] } end pi section compact /-- Any compact set in a metric space can be covered by finitely many balls of a given positive radius -/ lemma finite_cover_balls_of_compact {α : Type u} [metric_space α] {s : set α} (hs : is_compact s) {e : ℝ} (he : 0 < e) : ∃t ⊆ s, finite t ∧ s ⊆ ⋃x∈t, ball x e := begin apply hs.elim_finite_subcover_image, { simp [is_open_ball] }, { intros x xs, simp, exact ⟨x, ⟨xs, by simpa⟩⟩ } end alias finite_cover_balls_of_compact ← is_compact.finite_cover_balls end compact section proper_space open metric /-- A metric space is proper if all closed balls are compact. -/ class proper_space (α : Type u) [metric_space α] : Prop := (compact_ball : ∀x:α, ∀r, is_compact (closed_ball x r)) /-- If all closed balls of large enough radius are compact, then the space is proper. Especially useful when the lower bound for the radius is 0. -/ lemma proper_space_of_compact_closed_ball_of_le (R : ℝ) (h : ∀x:α, ∀r, R ≤ r → is_compact (closed_ball x r)) : proper_space α := ⟨begin assume x r, by_cases hr : R ≤ r, { exact h x r hr }, { have : closed_ball x r = closed_ball x R ∩ closed_ball x r, { symmetry, apply inter_eq_self_of_subset_right, exact closed_ball_subset_closed_ball (le_of_lt (not_le.1 hr)) }, rw this, exact (h x R (le_refl _)).inter_right is_closed_ball } end⟩ /- A compact metric space is proper -/ @[priority 100] -- see Note [lower instance priority] instance proper_of_compact [compact_space α] : proper_space α := ⟨assume x r, compact_of_is_closed_subset compact_univ is_closed_ball (subset_univ _)⟩ /-- A proper space is locally compact -/ @[priority 100] -- see Note [lower instance priority] instance locally_compact_of_proper [proper_space α] : locally_compact_space α := begin apply locally_compact_of_compact_nhds, intros x, existsi closed_ball x 1, split, { apply mem_nhds_iff.2, existsi (1 : ℝ), simp, exact ⟨zero_lt_one, ball_subset_closed_ball⟩ }, { apply proper_space.compact_ball } end /-- A proper space is complete -/ @[priority 100] -- see Note [lower instance priority] instance complete_of_proper [proper_space α] : complete_space α := ⟨begin intros f hf, /- We want to show that the Cauchy filter `f` is converging. It suffices to find a closed ball (therefore compact by properness) where it is nontrivial. -/ have A : ∃ t ∈ f, ∀ x y ∈ t, dist x y < 1 := (metric.cauchy_iff.1 hf).2 1 zero_lt_one, rcases A with ⟨t, ⟨t_fset, ht⟩⟩, rcases hf.1.nonempty_of_mem t_fset with ⟨x, xt⟩, have : t ⊆ closed_ball x 1 := by intros y yt; simp [dist_comm]; apply le_of_lt (ht x y xt yt), have : closed_ball x 1 ∈ f := f.sets_of_superset t_fset this, rcases (compact_iff_totally_bounded_complete.1 (proper_space.compact_ball x 1)).2 f hf (le_principal_iff.2 this) with ⟨y, _, hy⟩, exact ⟨y, hy⟩ end⟩ /-- A proper metric space is separable, and therefore second countable. Indeed, any ball is compact, and therefore admits a countable dense subset. Taking a countable union over the balls centered at a fixed point and with integer radius, one obtains a countable set which is dense in the whole space. -/ @[priority 100] -- see Note [lower instance priority] instance second_countable_of_proper [proper_space α] : second_countable_topology α := begin /- We show that the space admits a countable dense subset. The case where the space is empty is special, and trivial. -/ have A : (univ : set α) = ∅ → ∃(s : set α), countable s ∧ closure s = (univ : set α) := assume H, ⟨∅, ⟨by simp, by simp; exact H.symm⟩⟩, have B : (univ : set α).nonempty → ∃(s : set α), countable s ∧ closure s = (univ : set α) := begin /- When the space is not empty, we take a point `x` in the space, and then a countable set `T r` which is dense in the closed ball `closed_ball x r` for each `r`. Then the set `t = ⋃ T n` (where the union is over all integers `n`) is countable, as a countable union of countable sets, and dense in the space by construction. -/ rintros ⟨x, x_univ⟩, choose T a using show ∀ (r:ℝ), ∃ t ⊆ closed_ball x r, (countable (t : set α) ∧ closed_ball x r = closure t), from assume r, emetric.countable_closure_of_compact (proper_space.compact_ball _ _), let t := (⋃n:ℕ, T (n : ℝ)), have T₁ : countable t := by finish [countable_Union], have T₂ : closure t ⊆ univ := by simp, have T₃ : univ ⊆ closure t := begin intros y y_univ, rcases exists_nat_gt (dist y x) with ⟨n, n_large⟩, have h : y ∈ closed_ball x (n : ℝ) := by simp; apply le_of_lt n_large, have h' : closed_ball x (n : ℝ) = closure (T (n : ℝ)) := by finish, have : y ∈ closure (T (n : ℝ)) := by rwa h' at h, show y ∈ closure t, from mem_of_mem_of_subset this (by apply closure_mono; apply subset_Union (λ(n:ℕ), T (n:ℝ))), end, exact ⟨t, ⟨T₁, subset.antisymm T₂ T₃⟩⟩ end, haveI : separable_space α := ⟨(eq_empty_or_nonempty univ).elim A B⟩, apply emetric.second_countable_of_separable, end /-- A finite product of proper spaces is proper. -/ instance pi_proper_space {π : β → Type*} [fintype β] [∀b, metric_space (π b)] [h : ∀b, proper_space (π b)] : proper_space (Πb, π b) := begin refine proper_space_of_compact_closed_ball_of_le 0 (λx r hr, _), rw closed_ball_pi _ hr, apply compact_pi_infinite (λb, _), apply (h b).compact_ball end end proper_space namespace metric section second_countable open topological_space /-- A metric space is second countable if, for every `ε > 0`, there is a countable set which is `ε`-dense. -/ lemma second_countable_of_almost_dense_set (H : ∀ε > (0 : ℝ), ∃ s : set α, countable s ∧ (∀x, ∃y ∈ s, dist x y ≤ ε)) : second_countable_topology α := begin choose T T_dense using H, have I1 : ∀n:ℕ, (n:ℝ) + 1 > 0 := λn, lt_of_lt_of_le zero_lt_one (le_add_of_nonneg_left (nat.cast_nonneg _)), have I : ∀n:ℕ, (n+1 : ℝ)⁻¹ > 0 := λn, inv_pos.2 (I1 n), let t := ⋃n:ℕ, T (n+1)⁻¹ (I n), have count_t : countable t := by finish [countable_Union], have clos_t : closure t = univ, { refine subset.antisymm (subset_univ _) (λx xuniv, mem_closure_iff.2 (λε εpos, _)), rcases exists_nat_gt ε⁻¹ with ⟨n, hn⟩, have : ε⁻¹ < n + 1 := lt_of_lt_of_le hn (le_add_of_nonneg_right zero_le_one), have nε : ((n:ℝ)+1)⁻¹ < ε := (inv_lt (I1 n) εpos).2 this, rcases (T_dense (n+1)⁻¹ (I n)).2 x with ⟨y, yT, Dxy⟩, have : y ∈ t := mem_of_mem_of_subset yT (by apply subset_Union (λ (n:ℕ), T (n+1)⁻¹ (I n))), exact ⟨y, this, lt_of_le_of_lt Dxy nε⟩ }, haveI : separable_space α := ⟨⟨t, ⟨count_t, clos_t⟩⟩⟩, exact emetric.second_countable_of_separable α end /-- A metric space space is second countable if one can reconstruct up to any `ε>0` any element of the space from countably many data. -/ lemma second_countable_of_countable_discretization {α : Type u} [metric_space α] (H : ∀ε > (0 : ℝ), ∃ (β : Type*) [encodable β] (F : α → β), ∀x y, F x = F y → dist x y ≤ ε) : second_countable_topology α := begin cases (univ : set α).eq_empty_or_nonempty with hs hs, { haveI : compact_space α := ⟨by rw hs; exact compact_empty⟩, by apply_instance }, rcases hs with ⟨x0, hx0⟩, letI : inhabited α := ⟨x0⟩, refine second_countable_of_almost_dense_set (λε ε0, _), rcases H ε ε0 with ⟨β, fβ, F, hF⟩, resetI, let Finv := function.inv_fun F, refine ⟨range Finv, ⟨countable_range _, λx, _⟩⟩, let x' := Finv (F x), have : F x' = F x := function.inv_fun_eq ⟨x, rfl⟩, exact ⟨x', mem_range_self _, hF _ _ this.symm⟩ end end second_countable end metric lemma lebesgue_number_lemma_of_metric {s : set α} {ι} {c : ι → set α} (hs : is_compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ δ > 0, ∀ x ∈ s, ∃ i, ball x δ ⊆ c i := let ⟨n, en, hn⟩ := lebesgue_number_lemma hs hc₁ hc₂, ⟨δ, δ0, hδ⟩ := mem_uniformity_dist.1 en in ⟨δ, δ0, assume x hx, let ⟨i, hi⟩ := hn x hx in ⟨i, assume y hy, hi (hδ (mem_ball'.mp hy))⟩⟩ lemma lebesgue_number_lemma_of_metric_sUnion {s : set α} {c : set (set α)} (hs : is_compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ δ > 0, ∀ x ∈ s, ∃ t ∈ c, ball x δ ⊆ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma_of_metric hs (by simpa) hc₂ namespace metric /-- Boundedness of a subset of a metric space. We formulate the definition to work even in the empty space. -/ def bounded (s : set α) : Prop := ∃C, ∀x y ∈ s, dist x y ≤ C section bounded variables {x : α} {s t : set α} {r : ℝ} @[simp] lemma bounded_empty : bounded (∅ : set α) := ⟨0, by simp⟩ lemma bounded_iff_mem_bounded : bounded s ↔ ∀ x ∈ s, bounded s := ⟨λ h _ _, h, λ H, s.eq_empty_or_nonempty.elim (λ hs, hs.symm ▸ bounded_empty) (λ ⟨x, hx⟩, H x hx)⟩ /-- Subsets of a bounded set are also bounded -/ lemma bounded.subset (incl : s ⊆ t) : bounded t → bounded s := Exists.imp $ λ C hC x y hx hy, hC x y (incl hx) (incl hy) /-- Closed balls are bounded -/ lemma bounded_closed_ball : bounded (closed_ball x r) := ⟨r + r, λ y z hy hz, begin simp only [mem_closed_ball] at *, calc dist y z ≤ dist y x + dist z x : dist_triangle_right _ _ _ ... ≤ r + r : add_le_add hy hz end⟩ /-- Open balls are bounded -/ lemma bounded_ball : bounded (ball x r) := bounded_closed_ball.subset ball_subset_closed_ball /-- Given a point, a bounded subset is included in some ball around this point -/ lemma bounded_iff_subset_ball (c : α) : bounded s ↔ ∃r, s ⊆ closed_ball c r := begin split; rintro ⟨C, hC⟩, { cases s.eq_empty_or_nonempty with h h, { subst s, exact ⟨0, by simp⟩ }, { rcases h with ⟨x, hx⟩, exact ⟨C + dist x c, λ y hy, calc dist y c ≤ dist y x + dist x c : dist_triangle _ _ _ ... ≤ C + dist x c : add_le_add_right (hC y x hy hx) _⟩ } }, { exact bounded_closed_ball.subset hC } end lemma bounded_closure_of_bounded (h : bounded s) : bounded (closure s) := begin cases h with C h, replace h : ∀ p : α × α, p ∈ set.prod s s → dist p.1 p.2 ∈ { d | d ≤ C }, { rintros ⟨x, y⟩ ⟨x_in, y_in⟩, exact h x y x_in y_in }, use C, suffices : ∀ p : α × α, p ∈ closure (set.prod s s) → dist p.1 p.2 ∈ { d | d ≤ C }, { rw closure_prod_eq at this, intros x y x_in y_in, exact this (x, y) (mk_mem_prod x_in y_in) }, intros p p_in, have := mem_closure continuous_dist p_in h, rwa (is_closed_le' C).closure_eq at this end alias bounded_closure_of_bounded ← bounded.closure /-- The union of two bounded sets is bounded iff each of the sets is bounded -/ @[simp] lemma bounded_union : bounded (s ∪ t) ↔ bounded s ∧ bounded t := ⟨λh, ⟨h.subset (by simp), h.subset (by simp)⟩, begin rintro ⟨hs, ht⟩, refine bounded_iff_mem_bounded.2 (λ x _, _), rw bounded_iff_subset_ball x at hs ht ⊢, rcases hs with ⟨Cs, hCs⟩, rcases ht with ⟨Ct, hCt⟩, exact ⟨max Cs Ct, union_subset (subset.trans hCs $ closed_ball_subset_closed_ball $ le_max_left _ _) (subset.trans hCt $ closed_ball_subset_closed_ball $ le_max_right _ _)⟩, end⟩ /-- A finite union of bounded sets is bounded -/ lemma bounded_bUnion {I : set β} {s : β → set α} (H : finite I) : bounded (⋃i∈I, s i) ↔ ∀i ∈ I, bounded (s i) := finite.induction_on H (by simp) $ λ x I _ _ IH, by simp [or_imp_distrib, forall_and_distrib, IH] /-- A compact set is bounded -/ lemma bounded_of_compact {s : set α} (h : is_compact s) : bounded s := -- We cover the compact set by finitely many balls of radius 1, -- and then argue that a finite union of bounded sets is bounded let ⟨t, ht, fint, subs⟩ := finite_cover_balls_of_compact h zero_lt_one in bounded.subset subs $ (bounded_bUnion fint).2 $ λ i hi, bounded_ball alias bounded_of_compact ← is_compact.bounded /-- A finite set is bounded -/ lemma bounded_of_finite {s : set α} (h : finite s) : bounded s := h.is_compact.bounded /-- A singleton is bounded -/ lemma bounded_singleton {x : α} : bounded ({x} : set α) := bounded_of_finite $ finite_singleton _ /-- Characterization of the boundedness of the range of a function -/ lemma bounded_range_iff {f : β → α} : bounded (range f) ↔ ∃C, ∀x y, dist (f x) (f y) ≤ C := exists_congr $ λ C, ⟨ λ H x y, H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩, by rintro H _ _ ⟨x, rfl⟩ ⟨y, rfl⟩; exact H x y⟩ /-- In a compact space, all sets are bounded -/ lemma bounded_of_compact_space [compact_space α] : bounded s := compact_univ.bounded.subset (subset_univ _) /-- The Heine–Borel theorem: In a proper space, a set is compact if and only if it is closed and bounded -/ lemma compact_iff_closed_bounded [proper_space α] : is_compact s ↔ is_closed s ∧ bounded s := ⟨λ h, ⟨h.is_closed, h.bounded⟩, begin rintro ⟨hc, hb⟩, cases s.eq_empty_or_nonempty with h h, {simp [h, compact_empty]}, rcases h with ⟨x, hx⟩, rcases (bounded_iff_subset_ball x).1 hb with ⟨r, hr⟩, exact compact_of_is_closed_subset (proper_space.compact_ball x r) hc hr end⟩ /-- The image of a proper space under an expanding onto map is proper. -/ lemma proper_image_of_proper [proper_space α] [metric_space β] (f : α → β) (f_cont : continuous f) (hf : range f = univ) (C : ℝ) (hC : ∀x y, dist x y ≤ C * dist (f x) (f y)) : proper_space β := begin apply proper_space_of_compact_closed_ball_of_le 0 (λx₀ r hr, _), let K := f ⁻¹' (closed_ball x₀ r), have A : is_closed K := continuous_iff_is_closed.1 f_cont (closed_ball x₀ r) is_closed_ball, have B : bounded K := ⟨max C 0 * (r + r), λx y hx hy, calc dist x y ≤ C * dist (f x) (f y) : hC x y ... ≤ max C 0 * dist (f x) (f y) : mul_le_mul_of_nonneg_right (le_max_left _ _) (dist_nonneg) ... ≤ max C 0 * (dist (f x) x₀ + dist (f y) x₀) : mul_le_mul_of_nonneg_left (dist_triangle_right (f x) (f y) x₀) (le_max_right _ _) ... ≤ max C 0 * (r + r) : begin simp only [mem_closed_ball, mem_preimage] at hx hy, exact mul_le_mul_of_nonneg_left (add_le_add hx hy) (le_max_right _ _) end⟩, have : is_compact K := compact_iff_closed_bounded.2 ⟨A, B⟩, have C : is_compact (f '' K) := this.image f_cont, have : f '' K = closed_ball x₀ r, by { rw image_preimage_eq_of_subset, rw hf, exact subset_univ _ }, rwa this at C end end bounded section diam variables {s : set α} {x y z : α} /-- The diameter of a set in a metric space. To get controllable behavior even when the diameter should be infinite, we express it in terms of the emetric.diameter -/ def diam (s : set α) : ℝ := ennreal.to_real (emetric.diam s) /-- The diameter of a set is always nonnegative -/ lemma diam_nonneg : 0 ≤ diam s := ennreal.to_real_nonneg lemma diam_subsingleton (hs : s.subsingleton) : diam s = 0 := by simp only [diam, emetric.diam_subsingleton hs, ennreal.zero_to_real] /-- The empty set has zero diameter -/ @[simp] lemma diam_empty : diam (∅ : set α) = 0 := diam_subsingleton subsingleton_empty /-- A singleton has zero diameter -/ @[simp] lemma diam_singleton : diam ({x} : set α) = 0 := diam_subsingleton subsingleton_singleton -- Does not work as a simp-lemma, since {x, y} reduces to (insert y {x}) lemma diam_pair : diam ({x, y} : set α) = dist x y := by simp only [diam, emetric.diam_pair, dist_edist] -- Does not work as a simp-lemma, since {x, y, z} reduces to (insert z (insert y {x})) lemma diam_triple : metric.diam ({x, y, z} : set α) = max (max (dist x y) (dist x z)) (dist y z) := begin simp only [metric.diam, emetric.diam_triple, dist_edist], rw [ennreal.to_real_max, ennreal.to_real_max]; apply_rules [ne_of_lt, edist_lt_top, max_lt] end /-- If the distance between any two points in a set is bounded by some constant `C`, then `ennreal.of_real C` bounds the emetric diameter of this set. -/ lemma ediam_le_of_forall_dist_le {C : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : emetric.diam s ≤ ennreal.of_real C := emetric.diam_le_of_forall_edist_le $ λ x hx y hy, (edist_dist x y).symm ▸ ennreal.of_real_le_of_real (h x hx y hy) /-- If the distance between any two points in a set is bounded by some non-negative constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_dist_le {C : ℝ} (h₀ : 0 ≤ C) (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : diam s ≤ C := ennreal.to_real_le_of_le_of_real h₀ (ediam_le_of_forall_dist_le h) /-- If the distance between any two points in a nonempty set is bounded by some constant, this constant bounds the diameter. -/ lemma diam_le_of_forall_dist_le_of_nonempty (hs : s.nonempty) {C : ℝ} (h : ∀ (x ∈ s) (y ∈ s), dist x y ≤ C) : diam s ≤ C := have h₀ : 0 ≤ C, from let ⟨x, hx⟩ := hs in le_trans dist_nonneg (h x hx x hx), diam_le_of_forall_dist_le h₀ h /-- The distance between two points in a set is controlled by the diameter of the set. -/ lemma dist_le_diam_of_mem' (h : emetric.diam s ≠ ⊤) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s := begin rw [diam, dist_edist], rw ennreal.to_real_le_to_real (edist_ne_top _ _) h, exact emetric.edist_le_diam_of_mem hx hy end /-- Characterize the boundedness of a set in terms of the finiteness of its emetric.diameter. -/ lemma bounded_iff_ediam_ne_top : bounded s ↔ emetric.diam s ≠ ⊤ := iff.intro (λ ⟨C, hC⟩, ne_top_of_le_ne_top ennreal.of_real_ne_top (ediam_le_of_forall_dist_le $ λ x hx y hy, hC x y hx hy)) (λ h, ⟨diam s, λ x y hx hy, dist_le_diam_of_mem' h hx hy⟩) lemma bounded.ediam_ne_top (h : bounded s) : emetric.diam s ≠ ⊤ := bounded_iff_ediam_ne_top.1 h /-- The distance between two points in a set is controlled by the diameter of the set. -/ lemma dist_le_diam_of_mem (h : bounded s) (hx : x ∈ s) (hy : y ∈ s) : dist x y ≤ diam s := dist_le_diam_of_mem' h.ediam_ne_top hx hy /-- An unbounded set has zero diameter. If you would prefer to get the value ∞, use `emetric.diam`. This lemma makes it possible to avoid side conditions in some situations -/ lemma diam_eq_zero_of_unbounded (h : ¬(bounded s)) : diam s = 0 := begin simp only [bounded_iff_ediam_ne_top, not_not, ne.def] at h, simp [diam, h] end /-- If `s ⊆ t`, then the diameter of `s` is bounded by that of `t`, provided `t` is bounded. -/ lemma diam_mono {s t : set α} (h : s ⊆ t) (ht : bounded t) : diam s ≤ diam t := begin unfold diam, rw ennreal.to_real_le_to_real (bounded.subset h ht).ediam_ne_top ht.ediam_ne_top, exact emetric.diam_mono h end /-- The diameter of a union is controlled by the sum of the diameters, and the distance between any two points in each of the sets. This lemma is true without any side condition, since it is obviously true if `s ∪ t` is unbounded. -/ lemma diam_union {t : set α} (xs : x ∈ s) (yt : y ∈ t) : diam (s ∪ t) ≤ diam s + dist x y + diam t := begin classical, by_cases H : bounded (s ∪ t), { have hs : bounded s, from H.subset (subset_union_left _ _), have ht : bounded t, from H.subset (subset_union_right _ _), rw [bounded_iff_ediam_ne_top] at H hs ht, rw [dist_edist, diam, diam, diam, ← ennreal.to_real_add, ← ennreal.to_real_add, ennreal.to_real_le_to_real]; repeat { apply ennreal.add_ne_top.2; split }; try { assumption }; try { apply edist_ne_top }, exact emetric.diam_union xs yt }, { rw [diam_eq_zero_of_unbounded H], apply_rules [add_nonneg, diam_nonneg, dist_nonneg] } end /-- If two sets intersect, the diameter of the union is bounded by the sum of the diameters. -/ lemma diam_union' {t : set α} (h : (s ∩ t).nonempty) : diam (s ∪ t) ≤ diam s + diam t := begin rcases h with ⟨x, ⟨xs, xt⟩⟩, simpa using diam_union xs xt end /-- The diameter of a closed ball of radius `r` is at most `2 r`. -/ lemma diam_closed_ball {r : ℝ} (h : 0 ≤ r) : diam (closed_ball x r) ≤ 2 * r := diam_le_of_forall_dist_le (mul_nonneg (le_of_lt two_pos) h) $ λa ha b hb, calc dist a b ≤ dist a x + dist b x : dist_triangle_right _ _ _ ... ≤ r + r : add_le_add ha hb ... = 2 * r : by simp [mul_two, mul_comm] /-- The diameter of a ball of radius `r` is at most `2 r`. -/ lemma diam_ball {r : ℝ} (h : 0 ≤ r) : diam (ball x r) ≤ 2 * r := le_trans (diam_mono ball_subset_closed_ball bounded_closed_ball) (diam_closed_ball h) end diam end metric
a080d55a10f695a60092db7bd848efc54ff17cf6
bb31430994044506fa42fd667e2d556327e18dfe
/src/combinatorics/set_family/kleitman.lean
3fe9a533bc0c8016b36cb7725622fa2c65c3e5c7
[ "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
3,771
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import combinatorics.set_family.harris_kleitman import combinatorics.set_family.intersecting /-! # Kleitman's bound on the size of intersecting families An intersecting family on `n` elements has size at most `2ⁿ⁻¹`, so we could naïvely think that two intersecting families could cover all `2ⁿ` sets. But actually that's not case because for example none of them can contain the empty set. Intersecting families are in some sense correlated. Kleitman's bound stipulates that `k` intersecting families cover at most `2ⁿ - 2ⁿ⁻ᵏ` sets. ## Main declarations * `finset.card_bUnion_le_of_intersecting`: Kleitman's theorem. ## References * [D. J. Kleitman, *Families of non-disjoint subsets*][kleitman1966] -/ open finset fintype (card) variables {ι α : Type*} [fintype α] [decidable_eq α] [nonempty α] /-- **Kleitman's theorem**. An intersecting family on `n` elements contains at most `2ⁿ⁻¹` sets, and each further intersecting family takes at most half of the sets that are in no previous family. -/ lemma finset.card_bUnion_le_of_intersecting (s : finset ι) (f : ι → finset (finset α)) (hf : ∀ i ∈ s, (f i : set (finset α)).intersecting) : (s.bUnion f).card ≤ 2 ^ card α - 2 ^ (card α - s.card) := begin obtain hs | hs := le_total (card α) s.card, { rw [tsub_eq_zero_of_le hs, pow_zero], refine (card_le_of_subset $ bUnion_subset.2 $ λ i hi a ha, mem_compl.2 $ not_mem_singleton.2 $ (hf _ hi).ne_bot ha).trans_eq _, rw [card_compl, fintype.card_finset, card_singleton] }, induction s using finset.cons_induction with i s hi ih generalizing f, { simp }, classical, set f' : ι → finset (finset α) := λ j, if hj : j ∈ cons i s hi then (hf j hj).exists_card_eq.some else ∅ with hf', have hf₁ : ∀ j, j ∈ cons i s hi → f j ⊆ f' j ∧ 2 * (f' j).card = 2 ^ card α ∧ (f' j : set (finset α)).intersecting, { rintro j hj, simp_rw [hf', dif_pos hj, ←fintype.card_finset], exact classical.some_spec (hf j hj).exists_card_eq }, have hf₂ : ∀ j, j ∈ cons i s hi → is_upper_set (f' j : set (finset α)), { refine λ j hj, (hf₁ _ hj).2.2.is_upper_set' ((hf₁ _ hj).2.2.is_max_iff_card_eq.2 _), rw fintype.card_finset, exact (hf₁ _ hj).2.1 }, refine (card_le_of_subset $ bUnion_mono $ λ j hj, (hf₁ _ hj).1).trans _, nth_rewrite 0 cons_eq_insert i, rw bUnion_insert, refine (card_mono $ @le_sup_sdiff _ _ _ $ f' i).trans ((card_union_le _ _).trans _), rw [union_sdiff_left, sdiff_eq_inter_compl], refine le_of_mul_le_mul_left _ (pow_pos zero_lt_two $ card α + 1), rw [pow_succ', mul_add, mul_assoc, mul_comm _ 2, mul_assoc], refine (add_le_add ((mul_le_mul_left $ pow_pos (zero_lt_two' ℕ) _).2 (hf₁ _ $ mem_cons_self _ _).2.2.card_le) $ (mul_le_mul_left $ zero_lt_two' ℕ).2 $ is_upper_set.card_inter_le_finset _ _).trans _, { rw coe_bUnion, exact is_upper_set_Union₂ (λ i hi, hf₂ _ $ subset_cons _ hi) }, { rw coe_compl, exact (hf₂ _ $ mem_cons_self _ _).compl }, rw [mul_tsub, card_compl, fintype.card_finset, mul_left_comm, mul_tsub, (hf₁ _ $ mem_cons_self _ _).2.1, two_mul, add_tsub_cancel_left, ←mul_tsub, ←mul_two, mul_assoc, ←add_mul, mul_comm], refine mul_le_mul_left' _ _, refine (add_le_add_left (ih ((card_le_of_subset $ subset_cons _).trans hs) _ $ λ i hi, (hf₁ _ $ subset_cons _ hi).2.2) _).trans _, rw [mul_tsub, two_mul, ←pow_succ, ←add_tsub_assoc_of_le (pow_le_pow' (one_le_two : (1 : ℕ) ≤ 2) tsub_le_self), tsub_add_eq_add_tsub hs, card_cons, add_tsub_add_eq_tsub_right], end
1993193ef7c702ce15e51c5fe03d4871266f724d
bdd56e6eb0f467437e368d613de75299495d4054
/src/tactic/fattribute.lean
d55229d3887ccd797015728822fda85f94a6a03b
[]
no_license
truong111000/formalabstracts
49a04c268ccee136e48e24e9d5dcb6fedea4b53e
93a89a5c05c6fbc23eb9b914b60dcc353e609cd2
refs/heads/master
1,589,551,767,824
1,555,708,723,000
1,555,708,723,000
182,326,292
0
0
null
1,555,708,332,000
1,555,708,331,000
null
UTF-8
Lean
false
false
2,114
lean
/- Copyright (c) 2019 Koundinya Vajjha. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Koundinya Vajjha The fabstract user attribute. -/ import tactic.metadata import system.io open interactive interactive.types lean.parser tactic native io @[user_attribute] meta def fabstract_attr : user_attribute (rb_map name (string)) (list name) := { name := `fabstract, descr := "The fabstract user attribute. Used to mark lemmas captured in order to capture meta data.", parser := many ident <|> pure [], cache_cfg := ⟨ λ ns, ( do l ← mmap (trace_metadata_JSON) ns, pure $ rb_map.of_list (list.zip ns l)) , [] ⟩ } /- Tests -/ /-- Well, hello there! -/ -- @[fabstract ABC000 ABC200] def test₁ : 1+1 =2 := by simp -- @[fabstract ABC101 ABC200] def test₂ : 1+1 =2 := by simp @[fabstract ABC101 XYZ200] def welp : 1+1 =2 := by simp @[fabstract JBX190 AXX200] def woolp : 1+1 =2 := by simp @[fabstract] def flump : 1+1 =2 := by simp meta def query_cache (n : name) : tactic (string) := do m ← fabstract_attr.get_cache, v ← m.find n, pure v meta def prod_list_to_JSON {key : Type} {data : Type} [has_to_format key][has_to_format data]: list (key × data) → string | [] := " " | ((k,v) :: kvs) := if list.length kvs = 0 then to_string (format!"\"{k}\" :{v}}") else to_string (format!"\"{k}\" :{v},") ++ prod_list_to_JSON kvs meta def rb_map_to_JSON {key : Type} {data : Type} [has_to_format key][has_to_format data] (m : rb_map key data) : tactic string := pure $ "{" ++ (prod_list_to_JSON $ rb_map.to_list m) def write_json (cnts : string) : io unit := do h ← mk_file_handle "fabstract.json" io.mode.write, io.fs.write h cnts.to_char_buffer, io.fs.close h meta def mk_JSON_dump : tactic unit := do m ← fabstract_attr.get_cache >>= rb_map_to_JSON, unsafe_run_io $ write_json m, skip -- #check fabstract_attr.get_cache -- run_cmd attribute.get_instances `fabstract >>= tactic.trace -- run_cmd mk_JSON_dump run_cmd do m ← fabstract_attr.get_cache, l ← rb_map_to_JSON m, tactic.trace l, skip
3c908733e66f99638453b6f42a3f8a8241f2098a
8cb37a089cdb4af3af9d8bf1002b417e407a8e9e
/library/init/coe.lean
604ed49d359eeb06687e85504e3b481708e11a79
[ "Apache-2.0" ]
permissive
kbuzzard/lean
ae3c3db4bb462d750dbf7419b28bafb3ec983ef7
ed1788fd674bb8991acffc8fca585ec746711928
refs/heads/master
1,620,983,366,617
1,618,937,600,000
1,618,937,600,000
359,886,396
1
0
Apache-2.0
1,618,936,987,000
1,618,936,987,000
null
UTF-8
Lean
false
false
7,183
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 -/ /- The elaborator tries to insert coercions automatically. Only instances of has_coe type class are considered in the process. Lean also provides a "lifting" operator: ↑a. It uses all instances of has_lift type class. Every has_coe instance is also a has_lift instance. We recommend users only use has_coe for coercions that do not produce a lot of ambiguity. All coercions and lifts can be identified with the constant coe. We use the has_coe_to_fun type class for encoding coercions from a type to a function space. We use the has_coe_to_sort type class for encoding coercions from a type to a sort. -/ prelude import init.data.list.basic init.data.subtype.basic init.data.prod universes u v /-- Can perform a lifting operation `↑a`. -/ class has_lift (a : Sort u) (b : Sort v) := (lift : a → b) /-- Auxiliary class that contains the transitive closure of has_lift. -/ class has_lift_t (a : Sort u) (b : Sort v) := (lift : a → b) class has_coe (a : Sort u) (b : Sort v) := (coe : a → b) /-- Auxiliary class that contains the transitive closure of has_coe. -/ class has_coe_t (a : Sort u) (b : Sort v) := (coe : a → b) class has_coe_to_fun (a : Sort u) : Sort (max u (v+1)) := (F : a → Sort v) (coe : Π x, F x) class has_coe_to_sort (a : Sort u) : Type (max u (v+1)) := (S : Sort v) (coe : a → S) def lift {a : Sort u} {b : Sort v} [has_lift a b] : a → b := @has_lift.lift a b _ def lift_t {a : Sort u} {b : Sort v} [has_lift_t a b] : a → b := @has_lift_t.lift a b _ def coe_b {a : Sort u} {b : Sort v} [has_coe a b] : a → b := @has_coe.coe a b _ def coe_t {a : Sort u} {b : Sort v} [has_coe_t a b] : a → b := @has_coe_t.coe a b _ def coe_fn_b {a : Sort u} [has_coe_to_fun.{u v} a] : Π x : a, has_coe_to_fun.F.{u v} x := has_coe_to_fun.coe /- User level coercion operators -/ @[reducible] def coe {a : Sort u} {b : Sort v} [has_lift_t a b] : a → b := lift_t @[reducible] def coe_fn {a : Sort u} [has_coe_to_fun.{u v} a] : Π x : a, has_coe_to_fun.F.{u v} x := has_coe_to_fun.coe @[reducible] def coe_sort {a : Sort u} [has_coe_to_sort.{u v} a] : a → has_coe_to_sort.S.{u v} a := has_coe_to_sort.coe /- Notation -/ notation `↑`:max x:max := coe x notation `⇑`:max x:max := coe_fn x notation `↥`:max x:max := coe_sort x universes u₁ u₂ u₃ /- Transitive closure for has_lift, has_coe, has_coe_to_fun -/ instance lift_trans {a : Sort u₁} {b : Sort u₂} {c : Sort u₃} [has_lift_t b c] [has_lift a b] : has_lift_t a c := ⟨λ x, lift_t (lift x : b)⟩ instance lift_base {a : Sort u} {b : Sort v} [has_lift a b] : has_lift_t a b := ⟨lift⟩ instance coe_trans {a : Sort u₁} {b : Sort u₂} {c : Sort u₃} [has_coe_t b c] [has_coe a b] : has_coe_t a c := ⟨λ x, coe_t (coe_b x : b)⟩ instance coe_base {a : Sort u} {b : Sort v} [has_coe a b] : has_coe_t a b := ⟨coe_b⟩ /- We add this instance directly into has_coe_t to avoid non-termination. Suppose coe_option had type (has_coe a (option a)). Then, we can loop when searching a coercion from α to β (has_coe_t α β) 1- coe_trans at (has_coe_t α β) (has_coe α ?b₁) and (has_coe_t ?b₁ c) 2- coe_option at (has_coe α ?b₁) ?b₁ := option α 3- coe_trans at (has_coe_t (option α) β) (has_coe (option α) ?b₂) and (has_coe_t ?b₂ β) 4- coe_option at (has_coe (option α) ?b₂) ?b₂ := option (option α)) ... -/ instance coe_option {a : Type u} : has_coe_t a (option a) := ⟨λ x, some x⟩ /- Auxiliary transitive closure for has_coe which does not contain instances such as coe_option. They would produce non-termination when combined with coe_fn_trans and coe_sort_trans. -/ class has_coe_t_aux (a : Sort u) (b : Sort v) := (coe : a → b) instance coe_trans_aux {a : Sort u₁} {b : Sort u₂} {c : Sort u₃} [has_coe_t_aux b c] [has_coe a b] : has_coe_t_aux a c := ⟨λ x : a, @has_coe_t_aux.coe b c _ (coe_b x)⟩ instance coe_base_aux {a : Sort u} {b : Sort v} [has_coe a b] : has_coe_t_aux a b := ⟨coe_b⟩ instance coe_fn_trans {a : Sort u₁} {b : Sort u₂} [has_coe_to_fun.{u₂ u₃} b] [has_coe_t_aux a b] : has_coe_to_fun.{u₁ u₃} a := { F := λ x, @has_coe_to_fun.F.{u₂ u₃} b _ (@has_coe_t_aux.coe a b _ x), coe := λ x, coe_fn (@has_coe_t_aux.coe a b _ x) } instance coe_sort_trans {a : Sort u₁} {b : Sort u₂} [has_coe_to_sort.{u₂ u₃} b] [has_coe_t_aux a b] : has_coe_to_sort.{u₁ u₃} a := { S := has_coe_to_sort.S.{u₂ u₃} b, coe := λ x, coe_sort (@has_coe_t_aux.coe a b _ x) } /- Every coercion is also a lift -/ instance coe_to_lift {a : Sort u} {b : Sort v} [has_coe_t a b] : has_lift_t a b := ⟨coe_t⟩ /- basic coercions -/ instance coe_bool_to_Prop : has_coe bool Prop := ⟨λ y, y = tt⟩ /- Tactics such as the simplifier only unfold reducible constants when checking whether two terms are definitionally equal or a term is a proposition. The motivation is performance. In particular, when simplifying `p -> q`, the tactic `simp` only visits `p` if it can establish that it is a proposition. Thus, we mark the following instance as @[reducible], otherwise `simp` will not visit `↑p` when simplifying `↑p -> q`. -/ @[reducible] instance coe_sort_bool : has_coe_to_sort bool := ⟨Prop, λ y, y = tt⟩ instance coe_decidable_eq (x : bool) : decidable (coe x) := show decidable (x = tt), from bool.decidable_eq x tt instance coe_subtype {a : Sort u} {p : a → Prop} : has_coe {x // p x} a := ⟨subtype.val⟩ /- basic lifts -/ universes ua ua₁ ua₂ ub ub₁ ub₂ /- Remark: we can't use [has_lift_t a₂ a₁] since it will produce non-termination whenever a type class resolution problem does not have a solution. -/ instance lift_fn {a₁ : Sort ua₁} {a₂ : Sort ua₂} {b₁ : Sort ub₁} {b₂ : Sort ub₂} [has_lift a₂ a₁] [has_lift_t b₁ b₂] : has_lift (a₁ → b₁) (a₂ → b₂) := ⟨λ f x, ↑(f ↑x)⟩ instance lift_fn_range {a : Sort ua} {b₁ : Sort ub₁} {b₂ : Sort ub₂} [has_lift_t b₁ b₂] : has_lift (a → b₁) (a → b₂) := ⟨λ f x, ↑(f x)⟩ instance lift_fn_dom {a₁ : Sort ua₁} {a₂ : Sort ua₂} {b : Sort ub} [has_lift a₂ a₁] : has_lift (a₁ → b) (a₂ → b) := ⟨λ f x, f ↑x⟩ instance lift_pair {a₁ : Type ua₁} {a₂ : Type ub₂} {b₁ : Type ub₁} {b₂ : Type ub₂} [has_lift_t a₁ a₂] [has_lift_t b₁ b₂] : has_lift (a₁ × b₁) (a₂ × b₂) := ⟨λ p, prod.cases_on p (λ x y, (↑x, ↑y))⟩ instance lift_pair₁ {a₁ : Type ua₁} {a₂ : Type ua₂} {b : Type ub} [has_lift_t a₁ a₂] : has_lift (a₁ × b) (a₂ × b) := ⟨λ p, prod.cases_on p (λ x y, (↑x, y))⟩ instance lift_pair₂ {a : Type ua} {b₁ : Type ub₁} {b₂ : Type ub₂} [has_lift_t b₁ b₂] : has_lift (a × b₁) (a × b₂) := ⟨λ p, prod.cases_on p (λ x y, (x, ↑y))⟩ instance lift_list {a : Type u} {b : Type v} [has_lift_t a b] : has_lift (list a) (list b) := ⟨λ l, list.map (@coe a b _) l⟩
27f6e8a5f914b6bdde574c99444ad5d14a1e9290
92b50235facfbc08dfe7f334827d47281471333b
/library/algebra/relation.lean
e30160483394faa6a9da7fbe4bc963fe4afbb2aa
[ "Apache-2.0" ]
permissive
htzh/lean
24f6ed7510ab637379ec31af406d12584d31792c
d70c79f4e30aafecdfc4a60b5d3512199200ab6e
refs/heads/master
1,607,677,731,270
1,437,089,952,000
1,437,089,952,000
37,078,816
0
0
null
1,433,780,956,000
1,433,780,955,000
null
UTF-8
Lean
false
false
4,425
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Jeremy Avigad General properties of relations, and classes for equivalence relations and congruences. -/ namespace relation /- properties of binary relations -/ section variables {T : Type} (R : T → T → Type) definition reflexive : Type := ∀x, R x x definition symmetric : Type := ∀⦃x y⦄, R x y → R y x definition transitive : Type := ∀⦃x y z⦄, R x y → R y z → R x z end /- classes for equivalence relations -/ structure is_reflexive [class] {T : Type} (R : T → T → Type) := (refl : reflexive R) structure is_symmetric [class] {T : Type} (R : T → T → Type) := (symm : symmetric R) structure is_transitive [class] {T : Type} (R : T → T → Type) := (trans : transitive R) structure is_equivalence [class] {T : Type} (R : T → T → Type) extends is_reflexive R, is_symmetric R, is_transitive R -- partial equivalence relation structure is_PER {T : Type} (R : T → T → Type) extends is_symmetric R, is_transitive R -- Generic notation. For example, is_refl R is the reflexivity of R, if that can be -- inferred by type class inference section variables {T : Type} (R : T → T → Type) definition rel_refl [C : is_reflexive R] := is_reflexive.refl R definition rel_symm [C : is_symmetric R] := is_symmetric.symm R definition rel_trans [C : is_transitive R] := is_transitive.trans R end /- classes for unary and binary congruences with respect to arbitrary relations -/ structure is_congruence [class] {T1 : Type} (R1 : T1 → T1 → Prop) {T2 : Type} (R2 : T2 → T2 → Prop) (f : T1 → T2) := (congr : ∀{x y}, R1 x y → R2 (f x) (f y)) structure is_congruence2 [class] {T1 : Type} (R1 : T1 → T1 → Prop) {T2 : Type} (R2 : T2 → T2 → Prop) {T3 : Type} (R3 : T3 → T3 → Prop) (f : T1 → T2 → T3) := (congr2 : ∀{x1 y1 : T1} {x2 y2 : T2}, R1 x1 y1 → R2 x2 y2 → R3 (f x1 x2) (f y1 y2)) namespace is_congruence -- makes the type class explicit definition app {T1 : Type} {R1 : T1 → T1 → Prop} {T2 : Type} {R2 : T2 → T2 → Prop} {f : T1 → T2} (C : is_congruence R1 R2 f) ⦃x y : T1⦄ : R1 x y → R2 (f x) (f y) := is_congruence.rec (λu, u) C x y definition app2 {T1 : Type} {R1 : T1 → T1 → Prop} {T2 : Type} {R2 : T2 → T2 → Prop} {T3 : Type} {R3 : T3 → T3 → Prop} {f : T1 → T2 → T3} (C : is_congruence2 R1 R2 R3 f) ⦃x1 y1 : T1⦄ ⦃x2 y2 : T2⦄ : R1 x1 y1 → R2 x2 y2 → R3 (f x1 x2) (f y1 y2) := is_congruence2.rec (λu, u) C x1 y1 x2 y2 /- tools to build instances -/ theorem compose {T2 : Type} {R2 : T2 → T2 → Prop} {T3 : Type} {R3 : T3 → T3 → Prop} {g : T2 → T3} (C2 : is_congruence R2 R3 g) ⦃T1 : Type⦄ {R1 : T1 → T1 → Prop} {f : T1 → T2} [C1 : is_congruence R1 R2 f] : is_congruence R1 R3 (λx, g (f x)) := is_congruence.mk (λx1 x2 H, app C2 (app C1 H)) theorem compose21 {T2 : Type} {R2 : T2 → T2 → Prop} {T3 : Type} {R3 : T3 → T3 → Prop} {T4 : Type} {R4 : T4 → T4 → Prop} {g : T2 → T3 → T4} (C3 : is_congruence2 R2 R3 R4 g) ⦃T1 : Type⦄ {R1 : T1 → T1 → Prop} {f1 : T1 → T2} [C1 : is_congruence R1 R2 f1] {f2 : T1 → T3} [C2 : is_congruence R1 R3 f2] : is_congruence R1 R4 (λx, g (f1 x) (f2 x)) := is_congruence.mk (λx1 x2 H, app2 C3 (app C1 H) (app C2 H)) theorem const {T2 : Type} (R2 : T2 → T2 → Prop) (H : relation.reflexive R2) ⦃T1 : Type⦄ (R1 : T1 → T1 → Prop) (c : T2) : is_congruence R1 R2 (λu : T1, c) := is_congruence.mk (λx y H1, H c) end is_congruence theorem congruence_const [instance] {T2 : Type} (R2 : T2 → T2 → Prop) [C : is_reflexive R2] ⦃T1 : Type⦄ (R1 : T1 → T1 → Prop) (c : T2) : is_congruence R1 R2 (λu : T1, c) := is_congruence.const R2 (is_reflexive.refl R2) R1 c theorem congruence_trivial [instance] {T : Type} (R : T → T → Prop) : is_congruence R R (λu, u) := is_congruence.mk (λx y H, H) /- relations that can be coerced to functions / implications-/ structure mp_like [class] (R : Type → Type → Type) := (app : Π{a b : Type}, R a b → (a → b)) definition rel_mp (R : Type → Type → Type) [C : mp_like R] {a b : Type} (H : R a b) := mp_like.app H end relation
672f979d96c14d04be995fd27894d81119220204
69bc7d0780be17e452d542a93f9599488f1c0c8e
/10-24-2019.lean
8f906367d0ffcd93feebf090b5faf4fae25cfbcb
[]
no_license
joek13/cs2102-notes
b7352285b1d1184fae25594f89f5926d74e6d7b4
25bb18788641b20af9cf3c429afe1da9b2f5eafb
refs/heads/master
1,673,461,162,867
1,575,561,090,000
1,575,561,090,000
207,573,549
0
0
null
null
null
null
UTF-8
Lean
false
false
180
lean
-- Notes 10/24/2019 /- A truth table could be represented as n binary bits (where n is the number of variables) We could imagine this also as a list of interpretation functions -/
0880a1322e05c4cbf82af2e3361bd900bc9efb42
b328e8ebb2ba923140e5137c83f09fa59516b793
/stage0/src/Init/System/FilePath.lean
be9b05e7bc7160adc33ada90026af8e8700d7855
[ "Apache-2.0" ]
permissive
DrMaxis/lean4
a781bcc095511687c56ab060e816fd948553e162
5a02c4facc0658aad627cfdcc3db203eac0cb544
refs/heads/master
1,677,051,517,055
1,611,876,226,000
1,611,876,226,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,824
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 -/ prelude import Init.System.Platform import Init.Data.String.Basic namespace System namespace FilePath open Platform /-- The character that separates directories. In the case where more than one character is possible, `pathSeparator` is the 'ideal' one. -/ def pathSeparator : Char := if isWindows then '\\' else '/' /-- The list of all possible separators. -/ def pathSeparators : List Char := if isWindows then ['\\', '/'] else ['/'] /-- The character that is used to separate the entries in the $PATH environment variable. -/ def searchPathSeparator : Char := if isWindows then ';' else ':' /-- The list of all possible separators. -/ def searchPathSeparators : List Char := if isWindows then [';', ':'] else [':'] def splitSearchPath (s : String) : List String := s.split (fun c => searchPathSeparators.elem c) /-- File extension character -/ def extSeparator : Char := '.' def exeSuffix : String := if isWindows then ".exe" else "" /-- Case-insensitive file system -/ def isCaseInsensitive : Bool := isWindows || isOSX def normalizePath (fname : String) : String := if pathSeparators.length == 1 && !isCaseInsensitive then fname else fname.map fun c => if pathSeparators.any (fun c' => c == c') then pathSeparator -- else if isCaseInsensitive then c.toLower else c def dirName (fname : String) : String := let fname := normalizePath fname match fname.revPosOf pathSeparator with | none => "." | some pos => { str := fname, startPos := 0, stopPos := pos : Substring }.toString end FilePath def mkFilePath (parts : List String) : String := String.intercalate FilePath.pathSeparator.toString parts end System
baf3cb9e58aa194fe0ebb835971d93e69c626bbb
42c01158c2730cc6ac3e058c1339c18cb90366e2
/broken_field.lean
dd73cd45a7211b857b74831151af025105f9b353
[]
no_license
ChrisHughes24/xena
c80d94355d0c2ae8deddda9d01e6d31bc21c30ae
337a0d7c9f0e255e08d6d0a383e303c080c6ec0c
refs/heads/master
1,631,059,898,392
1,511,200,551,000
1,511,200,551,000
111,468,589
1
0
null
null
null
null
UTF-8
Lean
false
false
5,434
lean
import data.rat tactic.norm_num #print one_div_eq_inv local attribute [instance] classical.decidable_inhabited classical.prop_decidable -- because I don't know how to do inverses sensibly otherwise; -- I needed to know that if z was non-zero then either its rat part -- was non-zero or its imaginary part was non-zero. structure myrat : Type := (q : rat) namespace myrat -- handy checks for equality etc theorem eta (z : myrat) : myrat.mk z.q = z := cases_on z (λ _, rfl) theorem eq_of_q_eq (z w : myrat) : z.q=w.q → z=w := begin intro H,rw [←eta z,←eta w,H], end theorem eq_iff_q_eq (z w : myrat) : z=w ↔ z.q=w.q := begin split, intro H, rw [H], exact eq_of_q_eq _ _, end lemma proj_q (q0 : rat) : (myrat.mk q0).q = q0 := rfl local attribute [simp] eq_iff_q_eq proj_q def of_rat : rat → myrat := λ q0, myrat.mk q0 -- Am I right in -- thinking that the end user should not need to -- have to use this function? -- does one name these instances or not? I've named a random selection instance : has_zero myrat := ⟨of_rat 0⟩ instance : has_one myrat := ⟨of_rat 1⟩ instance inhabited_myrat : inhabited myrat := ⟨0⟩ def add : myrat → myrat → myrat := λ z w, ⟨z.q+w.q⟩ def neg : myrat → myrat := λ z, ⟨-z.q⟩ def mul : myrat → myrat → myrat := λ z w, ⟨z.q*w.q⟩ def inv : myrat → myrat := λ z, ⟨1/z.q⟩ instance : has_add myrat := ⟨myrat.add⟩ instance : has_neg myrat := ⟨myrat.neg⟩ instance : has_sub myrat := ⟨λx y, x + - y⟩ instance : has_mul myrat := ⟨myrat.mul⟩ instance : has_inv myrat := ⟨myrat.inv⟩ instance : has_div myrat := ⟨λx y, x + y⟩ lemma proj_zero_q : (0:myrat).q=0 := rfl lemma proj_one_q : (1:myrat).q=1 := rfl lemma proj_add_q (z w: myrat) : (z+w).q=z.q+w.q := rfl lemma proj_neg_q (z: myrat) : (-z).q=-z.q := rfl lemma proj_neg_q' (z: myrat) : (neg z).q=-z.q := rfl lemma proj_sub_q (z w : myrat) : (z-w).q=z.q-w.q := rfl lemma proj_mul_q (z w: myrat) : (z*w).q=z.q*w.q := rfl lemma proj_of_rat_q (r:rat) : (of_rat r).q = r := rfl local attribute [simp] proj_zero_q proj_one_q local attribute [simp] proj_add_q proj_neg_q local attribute [simp] proj_neg_q' proj_sub_q local attribute [simp] proj_mul_q proj_of_rat_q -- I don't know how to set up -- rat.cast_zero etc lemma of_rat_injective : function.injective of_rat := begin intros x₁ x₂ H, exact congr_arg myrat.q H, end lemma of_rat_zero : (0:myrat) = of_rat 0 := rfl lemma of_rat_one : (1:myrat) = of_rat 1 := rfl -- amateurish but it works! meta def crunch : tactic unit := do `[intros], `[rw [eq_iff_q_eq]], `[simp[add_mul,mul_add]] lemma of_rat_neg (r : rat) : -of_rat r = of_rat (-r) := by crunch lemma of_rat_add (r s: rat) : of_rat r + of_rat s = of_rat (r+s) := by crunch lemma of_rat_sub (r s:rat) : of_rat r - of_rat s = of_rat(r-s) := by crunch lemma of_rat_mul (r s:rat) : of_rat r * of_rat s = of_rat (r*s) := by crunch lemma of_rat_inv (r:rat) : (of_rat r)⁻¹ = of_rat (r⁻¹) := begin rw [eq_iff_q_eq], simp, unfold has_inv.inv inv, simp, unfold has_inv.inv inv, end lemma add_comm : ∀ (a b : myrat), a + b = b + a := by crunch local attribute [simp] of_rat_zero of_rat_one of_rat_neg of_rat_add local attribute [simp] of_rat_sub of_rat_mul of_rat_inv instance : field myrat := { field . zero := 0, add := (+), neg := myrat.neg, zero_add := by crunch, add_zero := by crunch, add_comm := by crunch, add_assoc := by crunch, add_left_neg := by crunch, one := 1, mul := (*), inv := has_inv.inv, mul_one := by crunch, one_mul := by crunch, mul_comm := by crunch, mul_assoc := by crunch, left_distrib := begin intros, apply eq_of_q_eq, simp [add_mul,mul_add,add_comm_group.add], end, right_distrib := begin intros, apply eq_of_q_eq, simp [add_mul,mul_add,add_comm_group.add], end, zero_ne_one := begin intro H, suffices : (0:myrat).q = (1:myrat).q, revert this, apply zero_ne_one, rw [←H], end, mul_inv_cancel := begin intros z H, apply eq_of_q_eq, unfold has_inv.inv inv has_inv.inv, rw [proj_mul_q], simp, refine mul_inv_cancel _, intro H2, apply H, apply eq_of_q_eq, rw H2, rw [proj_zero_q], end, inv_mul_cancel := begin -- let's try cut and pasting mul_inv_cancel proof intros z H, apply eq_of_q_eq, unfold has_inv.inv inv has_inv.inv, rw [proj_mul_q], simp, refine mul_inv_cancel _, intro H2, apply H, apply eq_of_q_eq, rw H2, rw [proj_zero_q], end -- it worked without modification! /- inv_zero := begin unfold has_inv.inv inv add_comm_group.zero, apply eq_of_q_eq, simp [zero_div], refl, end, -/ } #check myrat example : field myrat := by apply_instance #check div_mul_cancel example : division_ring myrat := by apply_instance theorem T : (of_rat 1) / (of_rat 1) * (of_rat 1) = of_rat 2 := begin unfold has_div.div, apply eq_of_q_eq, rw [of_rat_add,of_rat_mul], simp, by norm_num, end #check T -- T : of_rat 1 / of_rat 1 * of_rat 1 = of_rat 2 set_option pp.all false -- attempt to stop error being crazy example : (of_rat 1) / (of_rat 1) * (of_rat 1) = of_rat 1 := begin exact @div_mul_cancel myrat _ (of_rat 1) (of_rat 1) _, end #check @div_mul_cancel end myrat
fb1d2d513919ec7b7566b23feec3c9c6848c1f9b
0d7f5899c0475f9e105a439896d9377f80c0d7c3
/src/ualg.lean
3250fa6f1cc221a08e29d0858fe77e94d344a643
[]
no_license
adamtopaz/UnivAlg
127038f320e68cdf3efcd0c084c9af02fdb8da3d
2458d47a6e4fd0525e3a25b07cb7dd518ac173ef
refs/heads/master
1,670,320,985,286
1,597,350,882,000
1,597,350,882,000
280,585,500
4
0
null
1,597,350,883,000
1,595,048,527,000
Lean
UTF-8
Lean
false
false
3,099
lean
import .lang /- The `has_app` typeclass provides an interpretation of a language. -/ class has_app (L : lang) (A : Type*) := (app {n} : L n → ftuple A n → A) notation `applyo` := has_app.app /- A morphism of raw algebras relative to a language L. Use the notation `A →$[L] B`. -/ structure ralg_hom (L : lang) (A : Type*) (B : Type*) [has_app L A] [has_app L B] := (to_fn : A → B) (applyo_map' {n} {t : L n} {as : ftuple A n} : applyo t (as.map to_fn) = to_fn (applyo t as)) notation A ` →$[`:25 L:25 `] `:0 B:0 := ralg_hom L A B namespace ralg_hom instance {L : lang} {A : Type*} {B : Type*} [has_app L A] [has_app L B] : has_coe_to_fun (A →$[L] B ) := ⟨_,to_fn⟩ theorem applyo_map {n} {L : lang} {A : Type*} {B : Type*} [has_app L A] [has_app L B] (f : A →$[L] B) (t : L n) (as : ftuple A n) : applyo t (as.map f) = f (applyo t as) := by apply ralg_hom.applyo_map' def comp {L : lang} {A : Type*} {B : Type*} {C : Type*} [has_app L A] [has_app L B] [has_app L C] : (A →$[L] B) → (B →$[L] C) → (A →$[L] C) := λ f g, { to_fn := g ∘ f, applyo_map' := begin intros n t as, change _ = g _, simp_rw ←applyo_map, refl, end } @[ext] theorem ext {L : lang} {A : Type*} {B : Type*} [has_app L A] [has_app L B] (f g : A →$[L] B) : ⇑f = g → f = g := by {cases f, cases g, finish} theorem comp_assoc {L : lang} {A : Type*} {B : Type*} {C : Type*} {D : Type*} [has_app L A] [has_app L B] [has_app L C] [has_app L D] (f : A →$[L] B) (g : B →$[L] C) (h : C →$[L] D) : (f.comp g).comp h = f.comp (g.comp h) := by {apply ext, refl} end ralg_hom def applyt {n} {L : lang} {A : Type*} [has_app L A] (t : L.gen n) : ftuple A n → A := lang.term.rec_on t (λ _, applyo) (λ as, as 0) (λ _ _ f _ h as, h (as.proj f)) (λ _ _ _ _ h1 h2 as, as.compl h1 h2) (λ _ _ _ _ h1 h2 as, as.compr h1 h2) namespace ralg_hom lemma applyt_map {n} {L : lang} {A : Type*} {B : Type*} [has_app L A] [has_app L B] (f : A →$[L] B) (t : L.gen n) (as : ftuple A n) : applyt t (as.map f) = f (applyt t as) := begin induction t with _ _ _ _ _ _ h _ _ t1 t2 h1 h2 _ _ t1 t2 h1 h2, { apply ralg_hom.applyo_map,}, { refl, }, { apply h }, repeat { change applyt t2 (ftuple.append (ftuple.of $ applyt t1 _) _) = _ <|> change applyt t2 (ftuple.append _ (ftuple.of $ applyt t1 _)) = _, simp only [←ftuple.map_init, h1, ←ftuple.map_of, ←ftuple.map_last, ←ftuple.map_append, h2], refl }, end end ralg_hom --instance {L : lang} {A : Type*} [has_app L A] : has_app L.gen A := ⟨λ n, applyt⟩ /- namespace ralg_hom def gen {L : lang} {A : Type*} {B : Type*} [has_app L A] [has_app L B] (f : A →$[L] B) : A →$[L.gen] B := ⟨f,λ _, by apply gen.applyt_map⟩ end ralg_hom -/ class ualg {L : lang} (R : rules L) (A : Type*) extends has_app L A := (cond_eq {n} (t1 t2 : L.gen n) (as : ftuple A n) : R t1 t2 → applyt t1 as = applyt t2 as) /- namespace vac instance {L} {A : Type*} [has_app L A] : ualg L.vac A := { cond_eq := by tauto, ..show has_app L A, by apply_instance } end vac -/
809f44729945d036bb23863649fef43179051cac
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/eq4.lean
923c97005ee437209e0a2a0e99f488a99fc98e9c
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
300
lean
open nat definition half : nat → nat | half 0 := 0 | half 1 := 0 | half (x+2) := half x + 1 theorem half0 : half 0 = 0 := rfl theorem half1 : half 1 = 0 := rfl theorem half_succ_succ (a : nat) : half (a + 2) = half a + 1 := rfl example : half 5 = 2 := rfl example : half 8 = 4 := rfl
c5c887e876e9b51a5c5fe027b6e2f3a95e6f574f
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/local_homeomorph.lean
a362dcc1b96f54bea049eee89bd26d891758b167
[ "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
54,391
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 logic.equiv.local_equiv import topology.sets.opens /-! # Local homeomorphisms This file defines homeomorphisms between open subsets of topological spaces. An element `e` of `local_homeomorph α β` is an extension of `local_equiv α β`, i.e., it is a pair of functions `e.to_fun` and `e.inv_fun`, inverse of each other on the sets `e.source` and `e.target`. Additionally, we require that these sets are open, and that the functions are continuous on them. Equivalently, they are homeomorphisms there. As in equivs, we register a coercion to functions, and we use `e x` and `e.symm x` throughout instead of `e.to_fun x` and `e.inv_fun x`. ## Main definitions `homeomorph.to_local_homeomorph`: associating a local homeomorphism to a homeomorphism, with source = target = univ `local_homeomorph.symm` : the inverse of a local homeomorphism `local_homeomorph.trans` : the composition of two local homeomorphisms `local_homeomorph.refl` : the identity local homeomorphism `local_homeomorph.of_set`: the identity on a set `s` `eq_on_source` : equivalence relation describing the "right" notion of equality for local homeomorphisms ## Implementation notes Most statements are copied from their local_equiv versions, although some care is required especially when restricting to subsets, as these should be open subsets. For design notes, see `local_equiv.lean`. ### Local coding conventions If a lemma deals with the intersection of a set with either source or target of a `local_equiv`, then it should use `e.source ∩ s` or `e.target ∩ t`, not `s ∩ e.source` or `t ∩ e.target`. -/ open function set filter topological_space (second_countable_topology) open_locale topological_space variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] /-- local homeomorphisms, defined on open subsets of the space -/ @[nolint has_nonempty_instance] structure local_homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β] extends local_equiv α β := (open_source : is_open source) (open_target : is_open target) (continuous_to_fun : continuous_on to_fun source) (continuous_inv_fun : continuous_on inv_fun target) namespace local_homeomorph variables (e : local_homeomorph α β) (e' : local_homeomorph β γ) instance : has_coe_to_fun (local_homeomorph α β) (λ _, α → β) := ⟨λ e, e.to_fun⟩ /-- The inverse of a local homeomorphism -/ protected def symm : local_homeomorph β α := { open_source := e.open_target, open_target := e.open_source, continuous_to_fun := e.continuous_inv_fun, continuous_inv_fun := e.continuous_to_fun, ..e.to_local_equiv.symm } /-- See Note [custom simps projection]. We need to specify this projection explicitly in this case, because it is a composition of multiple projections. -/ def simps.apply (e : local_homeomorph α β) : α → β := e /-- See Note [custom simps projection] -/ def simps.symm_apply (e : local_homeomorph α β) : β → α := e.symm initialize_simps_projections local_homeomorph (to_local_equiv_to_fun → apply, to_local_equiv_inv_fun → symm_apply, to_local_equiv_source → source, to_local_equiv_target → target, -to_local_equiv) protected lemma continuous_on : continuous_on e e.source := e.continuous_to_fun lemma continuous_on_symm : continuous_on e.symm e.target := e.continuous_inv_fun @[simp, mfld_simps] lemma mk_coe (e : local_equiv α β) (a b c d) : (local_homeomorph.mk e a b c d : α → β) = e := rfl @[simp, mfld_simps] lemma mk_coe_symm (e : local_equiv α β) (a b c d) : ((local_homeomorph.mk e a b c d).symm : β → α) = e.symm := rfl lemma to_local_equiv_injective : injective (to_local_equiv : local_homeomorph α β → local_equiv α β) | ⟨e, h₁, h₂, h₃, h₄⟩ ⟨e', h₁', h₂', h₃', h₄'⟩ rfl := rfl /- Register a few simp lemmas to make sure that `simp` puts the application of a local homeomorphism in its normal form, i.e., in terms of its coercion to a function. -/ @[simp, mfld_simps] lemma to_fun_eq_coe (e : local_homeomorph α β) : e.to_fun = e := rfl @[simp, mfld_simps] lemma inv_fun_eq_coe (e : local_homeomorph α β) : e.inv_fun = e.symm := rfl @[simp, mfld_simps] lemma coe_coe : (e.to_local_equiv : α → β) = e := rfl @[simp, mfld_simps] lemma coe_coe_symm : (e.to_local_equiv.symm : β → α) = e.symm := rfl @[simp, mfld_simps] lemma map_source {x : α} (h : x ∈ e.source) : e x ∈ e.target := e.map_source' h @[simp, mfld_simps] lemma map_target {x : β} (h : x ∈ e.target) : e.symm x ∈ e.source := e.map_target' h @[simp, mfld_simps] lemma left_inv {x : α} (h : x ∈ e.source) : e.symm (e x) = x := e.left_inv' h @[simp, mfld_simps] lemma right_inv {x : β} (h : x ∈ e.target) : e (e.symm x) = x := e.right_inv' h lemma eq_symm_apply {x : α} {y : β} (hx : x ∈ e.source) (hy : y ∈ e.target) : x = e.symm y ↔ e x = y := e.to_local_equiv.eq_symm_apply hx hy protected lemma maps_to : maps_to e e.source e.target := λ x, e.map_source protected lemma symm_maps_to : maps_to e.symm e.target e.source := e.symm.maps_to protected lemma left_inv_on : left_inv_on e.symm e e.source := λ x, e.left_inv protected lemma right_inv_on : right_inv_on e.symm e e.target := λ x, e.right_inv protected lemma inv_on : inv_on e.symm e e.source e.target := ⟨e.left_inv_on, e.right_inv_on⟩ protected lemma inj_on : inj_on e e.source := e.left_inv_on.inj_on protected lemma bij_on : bij_on e e.source e.target := e.inv_on.bij_on e.maps_to e.symm_maps_to protected lemma surj_on : surj_on e e.source e.target := e.bij_on.surj_on /-- A homeomorphism induces a local homeomorphism on the whole space -/ @[simps {simp_rhs := tt, .. mfld_cfg}] def _root_.homeomorph.to_local_homeomorph (e : α ≃ₜ β) : local_homeomorph α β := { open_source := is_open_univ, open_target := is_open_univ, continuous_to_fun := by { erw ← continuous_iff_continuous_on_univ, exact e.continuous_to_fun }, continuous_inv_fun := by { erw ← continuous_iff_continuous_on_univ, exact e.continuous_inv_fun }, ..e.to_equiv.to_local_equiv } /-- Replace `to_local_equiv` field to provide better definitional equalities. -/ def replace_equiv (e : local_homeomorph α β) (e' : local_equiv α β) (h : e.to_local_equiv = e') : local_homeomorph α β := { to_local_equiv := e', open_source := h ▸ e.open_source, open_target := h ▸ e.open_target, continuous_to_fun := h ▸ e.continuous_to_fun, continuous_inv_fun := h ▸ e.continuous_inv_fun } lemma replace_equiv_eq_self (e : local_homeomorph α β) (e' : local_equiv α β) (h : e.to_local_equiv = e') : e.replace_equiv e' h = e := by { cases e, subst e', refl } lemma source_preimage_target : e.source ⊆ e ⁻¹' e.target := e.maps_to lemma eq_of_local_equiv_eq {e e' : local_homeomorph α β} (h : e.to_local_equiv = e'.to_local_equiv) : e = e' := by { cases e, cases e', cases h, refl } lemma eventually_left_inverse (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : ∀ᶠ y in 𝓝 x, e.symm (e y) = y := (e.open_source.eventually_mem hx).mono e.left_inv' lemma eventually_left_inverse' (e : local_homeomorph α β) {x} (hx : x ∈ e.target) : ∀ᶠ y in 𝓝 (e.symm x), e.symm (e y) = y := e.eventually_left_inverse (e.map_target hx) lemma eventually_right_inverse (e : local_homeomorph α β) {x} (hx : x ∈ e.target) : ∀ᶠ y in 𝓝 x, e (e.symm y) = y := (e.open_target.eventually_mem hx).mono e.right_inv' lemma eventually_right_inverse' (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : ∀ᶠ y in 𝓝 (e x), e (e.symm y) = y := e.eventually_right_inverse (e.map_source hx) lemma eventually_ne_nhds_within (e : local_homeomorph α β) {x} (hx : x ∈ e.source) : ∀ᶠ x' in 𝓝[≠] x, e x' ≠ e x := eventually_nhds_within_iff.2 $ (e.eventually_left_inverse hx).mono $ λ x' hx', mt $ λ h, by rw [mem_singleton_iff, ← e.left_inv hx, ← h, hx'] lemma nhds_within_source_inter {x} (hx : x ∈ e.source) (s : set α) : 𝓝[e.source ∩ s] x = 𝓝[s] x := nhds_within_inter_of_mem (mem_nhds_within_of_mem_nhds $ is_open.mem_nhds e.open_source hx) lemma nhds_within_target_inter {x} (hx : x ∈ e.target) (s : set β) : 𝓝[e.target ∩ s] x = 𝓝[s] x := e.symm.nhds_within_source_inter hx s lemma image_eq_target_inter_inv_preimage {s : set α} (h : s ⊆ e.source) : e '' s = e.target ∩ e.symm ⁻¹' s := e.to_local_equiv.image_eq_target_inter_inv_preimage h lemma image_source_inter_eq' (s : set α) : e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' s := e.to_local_equiv.image_source_inter_eq' s lemma image_source_inter_eq (s : set α) : e '' (e.source ∩ s) = e.target ∩ e.symm ⁻¹' (e.source ∩ s) := e.to_local_equiv.image_source_inter_eq s lemma symm_image_eq_source_inter_preimage {s : set β} (h : s ⊆ e.target) : e.symm '' s = e.source ∩ e ⁻¹' s := e.symm.image_eq_target_inter_inv_preimage h lemma symm_image_target_inter_eq (s : set β) : e.symm '' (e.target ∩ s) = e.source ∩ e ⁻¹' (e.target ∩ s) := e.symm.image_source_inter_eq _ lemma source_inter_preimage_inv_preimage (s : set α) : e.source ∩ e ⁻¹' (e.symm ⁻¹' s) = e.source ∩ s := e.to_local_equiv.source_inter_preimage_inv_preimage s lemma target_inter_inv_preimage_preimage (s : set β) : e.target ∩ e.symm ⁻¹' (e ⁻¹' s) = e.target ∩ s := e.symm.source_inter_preimage_inv_preimage _ lemma source_inter_preimage_target_inter (s : set β) : e.source ∩ (e ⁻¹' (e.target ∩ s)) = e.source ∩ (e ⁻¹' s) := e.to_local_equiv.source_inter_preimage_target_inter s lemma image_source_eq_target (e : local_homeomorph α β) : e '' e.source = e.target := e.to_local_equiv.image_source_eq_target lemma symm_image_target_eq_source (e : local_homeomorph α β) : e.symm '' e.target = e.source := e.symm.image_source_eq_target /-- Two local homeomorphisms are equal when they have equal `to_fun`, `inv_fun` and `source`. It is not sufficient to have equal `to_fun` and `source`, as this only determines `inv_fun` on the target. This would only be true for a weaker notion of equality, arguably the right one, called `eq_on_source`. -/ @[ext] protected lemma ext (e' : local_homeomorph α β) (h : ∀x, e x = e' x) (hinv : ∀x, e.symm x = e'.symm x) (hs : e.source = e'.source) : e = e' := eq_of_local_equiv_eq (local_equiv.ext h hinv hs) protected lemma ext_iff {e e' : local_homeomorph α β} : e = e' ↔ (∀ x, e x = e' x) ∧ (∀ x, e.symm x = e'.symm x) ∧ e.source = e'.source := ⟨by { rintro rfl, exact ⟨λ x, rfl, λ x, rfl, rfl⟩ }, λ h, e.ext e' h.1 h.2.1 h.2.2⟩ @[simp, mfld_simps] lemma symm_to_local_equiv : e.symm.to_local_equiv = e.to_local_equiv.symm := rfl -- The following lemmas are already simp via local_equiv lemma symm_source : e.symm.source = e.target := rfl lemma symm_target : e.symm.target = e.source := rfl @[simp, mfld_simps] lemma symm_symm : e.symm.symm = e := eq_of_local_equiv_eq $ by simp /-- A local homeomorphism is continuous at any point of its source -/ protected lemma continuous_at {x : α} (h : x ∈ e.source) : continuous_at e x := (e.continuous_on x h).continuous_at (e.open_source.mem_nhds h) /-- A local homeomorphism inverse is continuous at any point of its target -/ lemma continuous_at_symm {x : β} (h : x ∈ e.target) : continuous_at e.symm x := e.symm.continuous_at h lemma tendsto_symm {x} (hx : x ∈ e.source) : tendsto e.symm (𝓝 (e x)) (𝓝 x) := by simpa only [continuous_at, e.left_inv hx] using e.continuous_at_symm (e.map_source hx) lemma map_nhds_eq {x} (hx : x ∈ e.source) : map e (𝓝 x) = 𝓝 (e x) := le_antisymm (e.continuous_at hx) $ le_map_of_right_inverse (e.eventually_right_inverse' hx) (e.tendsto_symm hx) lemma symm_map_nhds_eq {x} (hx : x ∈ e.source) : map e.symm (𝓝 (e x)) = 𝓝 x := (e.symm.map_nhds_eq $ e.map_source hx).trans $ by rw e.left_inv hx lemma image_mem_nhds {x} (hx : x ∈ e.source) {s : set α} (hs : s ∈ 𝓝 x) : e '' s ∈ 𝓝 (e x) := e.map_nhds_eq hx ▸ filter.image_mem_map hs lemma map_nhds_within_eq (e : local_homeomorph α β) {x} (hx : x ∈ e.source) (s : set α) : map e (𝓝[s] x) = 𝓝[e '' (e.source ∩ s)] (e x) := calc map e (𝓝[s] x) = map e (𝓝[e.source ∩ s] x) : congr_arg (map e) (e.nhds_within_source_inter hx _).symm ... = 𝓝[e '' (e.source ∩ s)] (e x) : (e.left_inv_on.mono $ inter_subset_left _ _).map_nhds_within_eq (e.left_inv hx) (e.continuous_at_symm (e.map_source hx)).continuous_within_at (e.continuous_at hx).continuous_within_at lemma map_nhds_within_preimage_eq (e : local_homeomorph α β) {x} (hx : x ∈ e.source) (s : set β) : map e (𝓝[e ⁻¹' s] x) = 𝓝[s] (e x) := by rw [e.map_nhds_within_eq hx, e.image_source_inter_eq', e.target_inter_inv_preimage_preimage, e.nhds_within_target_inter (e.map_source hx)] lemma eventually_nhds (e : local_homeomorph α β) {x : α} (p : β → Prop) (hx : x ∈ e.source) : (∀ᶠ y in 𝓝 (e x), p y) ↔ ∀ᶠ x in 𝓝 x, p (e x) := iff.trans (by rw [e.map_nhds_eq hx]) eventually_map lemma eventually_nhds' (e : local_homeomorph α β) {x : α} (p : α → Prop) (hx : x ∈ e.source) : (∀ᶠ y in 𝓝 (e x), p (e.symm y)) ↔ ∀ᶠ x in 𝓝 x, p x := begin rw [e.eventually_nhds _ hx], refine eventually_congr ((e.eventually_left_inverse hx).mono $ λ y hy, _), rw [hy] end lemma eventually_nhds_within (e : local_homeomorph α β) {x : α} (p : β → Prop) {s : set α} (hx : x ∈ e.source) : (∀ᶠ y in 𝓝[e.symm ⁻¹' s] (e x), p y) ↔ ∀ᶠ x in 𝓝[s] x, p (e x) := begin refine iff.trans _ eventually_map, rw [e.map_nhds_within_eq hx, e.image_source_inter_eq', e.nhds_within_target_inter (e.maps_to hx)] end lemma eventually_nhds_within' (e : local_homeomorph α β) {x : α} (p : α → Prop) {s : set α} (hx : x ∈ e.source) : (∀ᶠ y in 𝓝[e.symm ⁻¹' s] (e x), p (e.symm y)) ↔ ∀ᶠ x in 𝓝[s] x, p x := begin rw [e.eventually_nhds_within _ hx], refine eventually_congr ((eventually_nhds_within_of_eventually_nhds $ e.eventually_left_inverse hx).mono $ λ y hy, _), rw [hy] end /-- This lemma is useful in the manifold library in the case that `e` is a chart. It states that locally around `e x` the set `e.symm ⁻¹' s` is the same as the set intersected with the target of `e` and some other neighborhood of `f x` (which will be the source of a chart on `γ`). -/ lemma preimage_eventually_eq_target_inter_preimage_inter {e : local_homeomorph α β} {s : set α} {t : set γ} {x : α} {f : α → γ} (hf : continuous_within_at f s x) (hxe : x ∈ e.source) (ht : t ∈ 𝓝 (f x)) : e.symm ⁻¹' s =ᶠ[𝓝 (e x)] (e.target ∩ e.symm ⁻¹' (s ∩ f ⁻¹' t) : set β) := begin rw [eventually_eq_set, e.eventually_nhds _ hxe], filter_upwards [(e.open_source.mem_nhds hxe), mem_nhds_within_iff_eventually.mp (hf.preimage_mem_nhds_within ht)], intros y hy hyu, simp_rw [mem_inter_iff, mem_preimage, mem_inter_iff, e.maps_to hy, true_and, iff_self_and, e.left_inv hy, iff_true_intro hyu] end lemma preimage_open_of_open {s : set β} (hs : is_open s) : is_open (e.source ∩ e ⁻¹' s) := e.continuous_on.preimage_open_of_open e.open_source hs /-! ### `local_homeomorph.is_image` relation We say that `t : set β` is an image of `s : set α` under a local homeomorphism `e` if any of the following equivalent conditions hold: * `e '' (e.source ∩ s) = e.target ∩ t`; * `e.source ∩ e ⁻¹ t = e.source ∩ s`; * `∀ x ∈ e.source, e x ∈ t ↔ x ∈ s` (this one is used in the definition). This definition is a restatement of `local_equiv.is_image` for local homeomorphisms. In this section we transfer API about `local_equiv.is_image` to local homeomorphisms and add a few `local_homeomorph`-specific lemmas like `local_homeomorph.is_image.closure`. -/ /-- We say that `t : set β` is an image of `s : set α` under a local homeomorphism `e` if any of the following equivalent conditions hold: * `e '' (e.source ∩ s) = e.target ∩ t`; * `e.source ∩ e ⁻¹ t = e.source ∩ s`; * `∀ x ∈ e.source, e x ∈ t ↔ x ∈ s` (this one is used in the definition). -/ def is_image (s : set α) (t : set β) : Prop := ∀ ⦃x⦄, x ∈ e.source → (e x ∈ t ↔ x ∈ s) namespace is_image variables {e} {s : set α} {t : set β} {x : α} {y : β} lemma to_local_equiv (h : e.is_image s t) : e.to_local_equiv.is_image s t := h lemma apply_mem_iff (h : e.is_image s t) (hx : x ∈ e.source) : e x ∈ t ↔ x ∈ s := h hx protected lemma symm (h : e.is_image s t) : e.symm.is_image t s := h.to_local_equiv.symm lemma symm_apply_mem_iff (h : e.is_image s t) (hy : y ∈ e.target) : (e.symm y ∈ s ↔ y ∈ t) := h.symm hy @[simp] lemma symm_iff : e.symm.is_image t s ↔ e.is_image s t := ⟨λ h, h.symm, λ h, h.symm⟩ protected lemma maps_to (h : e.is_image s t) : maps_to e (e.source ∩ s) (e.target ∩ t) := h.to_local_equiv.maps_to lemma symm_maps_to (h : e.is_image s t) : maps_to e.symm (e.target ∩ t) (e.source ∩ s) := h.symm.maps_to lemma image_eq (h : e.is_image s t) : e '' (e.source ∩ s) = e.target ∩ t := h.to_local_equiv.image_eq lemma symm_image_eq (h : e.is_image s t) : e.symm '' (e.target ∩ t) = e.source ∩ s := h.symm.image_eq lemma iff_preimage_eq : e.is_image s t ↔ e.source ∩ e ⁻¹' t = e.source ∩ s := local_equiv.is_image.iff_preimage_eq alias iff_preimage_eq ↔ preimage_eq of_preimage_eq lemma iff_symm_preimage_eq : e.is_image s t ↔ e.target ∩ e.symm ⁻¹' s = e.target ∩ t := symm_iff.symm.trans iff_preimage_eq alias iff_symm_preimage_eq ↔ symm_preimage_eq of_symm_preimage_eq lemma iff_symm_preimage_eq' : e.is_image s t ↔ e.target ∩ e.symm ⁻¹' (e.source ∩ s) = e.target ∩ t := by rw [iff_symm_preimage_eq, ← image_source_inter_eq, ← image_source_inter_eq'] alias iff_symm_preimage_eq' ↔ symm_preimage_eq' of_symm_preimage_eq' lemma iff_preimage_eq' : e.is_image s t ↔ e.source ∩ e ⁻¹' (e.target ∩ t) = e.source ∩ s := symm_iff.symm.trans iff_symm_preimage_eq' alias iff_preimage_eq' ↔ preimage_eq' of_preimage_eq' lemma of_image_eq (h : e '' (e.source ∩ s) = e.target ∩ t) : e.is_image s t := local_equiv.is_image.of_image_eq h lemma of_symm_image_eq (h : e.symm '' (e.target ∩ t) = e.source ∩ s) : e.is_image s t := local_equiv.is_image.of_symm_image_eq h protected lemma compl (h : e.is_image s t) : e.is_image sᶜ tᶜ := λ x hx, not_congr (h hx) protected lemma inter {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') : e.is_image (s ∩ s') (t ∩ t') := λ x hx, and_congr (h hx) (h' hx) protected lemma union {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') : e.is_image (s ∪ s') (t ∪ t') := λ x hx, or_congr (h hx) (h' hx) protected lemma diff {s' t'} (h : e.is_image s t) (h' : e.is_image s' t') : e.is_image (s \ s') (t \ t') := h.inter h'.compl lemma left_inv_on_piecewise {e' : local_homeomorph α β} [∀ i, decidable (i ∈ s)] [∀ i, decidable (i ∈ t)] (h : e.is_image s t) (h' : e'.is_image s t) : left_inv_on (t.piecewise e.symm e'.symm) (s.piecewise e e') (s.ite e.source e'.source) := h.to_local_equiv.left_inv_on_piecewise h' lemma inter_eq_of_inter_eq_of_eq_on {e' : local_homeomorph α β} (h : e.is_image s t) (h' : e'.is_image s t) (hs : e.source ∩ s = e'.source ∩ s) (Heq : eq_on e e' (e.source ∩ s)) : e.target ∩ t = e'.target ∩ t := h.to_local_equiv.inter_eq_of_inter_eq_of_eq_on h' hs Heq lemma symm_eq_on_of_inter_eq_of_eq_on {e' : local_homeomorph α β} (h : e.is_image s t) (hs : e.source ∩ s = e'.source ∩ s) (Heq : eq_on e e' (e.source ∩ s)) : eq_on e.symm e'.symm (e.target ∩ t) := h.to_local_equiv.symm_eq_on_of_inter_eq_of_eq_on hs Heq lemma map_nhds_within_eq (h : e.is_image s t) (hx : x ∈ e.source) : map e (𝓝[s] x) = 𝓝[t] (e x) := by rw [e.map_nhds_within_eq hx, h.image_eq, e.nhds_within_target_inter (e.map_source hx)] protected lemma closure (h : e.is_image s t) : e.is_image (closure s) (closure t) := λ x hx, by simp only [mem_closure_iff_nhds_within_ne_bot, ← h.map_nhds_within_eq hx, map_ne_bot_iff] protected lemma interior (h : e.is_image s t) : e.is_image (interior s) (interior t) := by simpa only [closure_compl, compl_compl] using h.compl.closure.compl protected lemma frontier (h : e.is_image s t) : e.is_image (frontier s) (frontier t) := h.closure.diff h.interior lemma is_open_iff (h : e.is_image s t) : is_open (e.source ∩ s) ↔ is_open (e.target ∩ t) := ⟨λ hs, h.symm_preimage_eq' ▸ e.symm.preimage_open_of_open hs, λ hs, h.preimage_eq' ▸ e.preimage_open_of_open hs⟩ /-- Restrict a `local_homeomorph` to a pair of corresponding open sets. -/ @[simps to_local_equiv] def restr (h : e.is_image s t) (hs : is_open (e.source ∩ s)) : local_homeomorph α β := { to_local_equiv := h.to_local_equiv.restr, open_source := hs, open_target := h.is_open_iff.1 hs, continuous_to_fun := e.continuous_on.mono (inter_subset_left _ _), continuous_inv_fun := e.symm.continuous_on.mono (inter_subset_left _ _) } end is_image lemma is_image_source_target : e.is_image e.source e.target := e.to_local_equiv.is_image_source_target lemma is_image_source_target_of_disjoint (e' : local_homeomorph α β) (hs : disjoint e.source e'.source) (ht : disjoint e.target e'.target) : e.is_image e'.source e'.target := e.to_local_equiv.is_image_source_target_of_disjoint e'.to_local_equiv hs ht /-- Preimage of interior or interior of preimage coincide for local homeomorphisms, when restricted to the source. -/ lemma preimage_interior (s : set β) : e.source ∩ e ⁻¹' (interior s) = e.source ∩ interior (e ⁻¹' s) := (is_image.of_preimage_eq rfl).interior.preimage_eq lemma preimage_closure (s : set β) : e.source ∩ e ⁻¹' (closure s) = e.source ∩ closure (e ⁻¹' s) := (is_image.of_preimage_eq rfl).closure.preimage_eq lemma preimage_frontier (s : set β) : e.source ∩ e ⁻¹' (frontier s) = e.source ∩ frontier (e ⁻¹' s) := (is_image.of_preimage_eq rfl).frontier.preimage_eq lemma preimage_open_of_open_symm {s : set α} (hs : is_open s) : is_open (e.target ∩ e.symm ⁻¹' s) := e.symm.continuous_on.preimage_open_of_open e.open_target hs /-- The image of an open set in the source is open. -/ lemma image_open_of_open {s : set α} (hs : is_open s) (h : s ⊆ e.source) : is_open (e '' s) := begin have : e '' s = e.target ∩ e.symm ⁻¹' s := e.to_local_equiv.image_eq_target_inter_inv_preimage h, rw this, exact e.continuous_on_symm.preimage_open_of_open e.open_target hs end /-- The image of the restriction of an open set to the source is open. -/ lemma image_open_of_open' {s : set α} (hs : is_open s) : is_open (e '' (e.source ∩ s)) := image_open_of_open _ (is_open.inter e.open_source hs) (inter_subset_left _ _) /-- A `local_equiv` with continuous open forward map and an open source is a `local_homeomorph`. -/ def of_continuous_open_restrict (e : local_equiv α β) (hc : continuous_on e e.source) (ho : is_open_map (e.source.restrict e)) (hs : is_open e.source) : local_homeomorph α β := { to_local_equiv := e, open_source := hs, open_target := by simpa only [range_restrict, e.image_source_eq_target] using ho.is_open_range, continuous_to_fun := hc, continuous_inv_fun := e.image_source_eq_target ▸ ho.continuous_on_image_of_left_inv_on e.left_inv_on } /-- A `local_equiv` with continuous open forward map and an open source is a `local_homeomorph`. -/ def of_continuous_open (e : local_equiv α β) (hc : continuous_on e e.source) (ho : is_open_map e) (hs : is_open e.source) : local_homeomorph α β := of_continuous_open_restrict e hc (ho.restrict hs) hs /-- Restricting a local homeomorphism `e` to `e.source ∩ s` when `s` is open. This is sometimes hard to use because of the openness assumption, but it has the advantage that when it can be used then its local_equiv is defeq to local_equiv.restr -/ protected def restr_open (s : set α) (hs : is_open s) : local_homeomorph α β := (@is_image.of_symm_preimage_eq α β _ _ e s (e.symm ⁻¹' s) rfl).restr (is_open.inter e.open_source hs) @[simp, mfld_simps] lemma restr_open_to_local_equiv (s : set α) (hs : is_open s) : (e.restr_open s hs).to_local_equiv = e.to_local_equiv.restr s := rfl -- Already simp via local_equiv lemma restr_open_source (s : set α) (hs : is_open s) : (e.restr_open s hs).source = e.source ∩ s := rfl /-- Restricting a local homeomorphism `e` to `e.source ∩ interior s`. We use the interior to make sure that the restriction is well defined whatever the set s, since local homeomorphisms are by definition defined on open sets. In applications where `s` is open, this coincides with the restriction of local equivalences -/ @[simps apply symm_apply (mfld_cfg), simps source target {attrs := []}] protected def restr (s : set α) : local_homeomorph α β := e.restr_open (interior s) is_open_interior @[simp, mfld_simps] lemma restr_to_local_equiv (s : set α) : (e.restr s).to_local_equiv = (e.to_local_equiv).restr (interior s) := rfl lemma restr_source' (s : set α) (hs : is_open s) : (e.restr s).source = e.source ∩ s := by rw [e.restr_source, hs.interior_eq] lemma restr_to_local_equiv' (s : set α) (hs : is_open s): (e.restr s).to_local_equiv = e.to_local_equiv.restr s := by rw [e.restr_to_local_equiv, hs.interior_eq] lemma restr_eq_of_source_subset {e : local_homeomorph α β} {s : set α} (h : e.source ⊆ s) : e.restr s = e := begin apply eq_of_local_equiv_eq, rw restr_to_local_equiv, apply local_equiv.restr_eq_of_source_subset, exact interior_maximal h e.open_source end @[simp, mfld_simps] lemma restr_univ {e : local_homeomorph α β} : e.restr univ = e := restr_eq_of_source_subset (subset_univ _) lemma restr_source_inter (s : set α) : e.restr (e.source ∩ s) = e.restr s := begin refine local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) _, simp [e.open_source.interior_eq, ← inter_assoc] end /-- The identity on the whole space as a local homeomorphism. -/ @[simps apply (mfld_cfg), simps source target {attrs := []}] protected def refl (α : Type*) [topological_space α] : local_homeomorph α α := (homeomorph.refl α).to_local_homeomorph @[simp, mfld_simps] lemma refl_local_equiv : (local_homeomorph.refl α).to_local_equiv = local_equiv.refl α := rfl @[simp, mfld_simps] lemma refl_symm : (local_homeomorph.refl α).symm = local_homeomorph.refl α := rfl section variables {s : set α} (hs : is_open s) /-- The identity local equiv on a set `s` -/ @[simps apply (mfld_cfg), simps source target {attrs := []}] def of_set (s : set α) (hs : is_open s) : local_homeomorph α α := { open_source := hs, open_target := hs, continuous_to_fun := continuous_id.continuous_on, continuous_inv_fun := continuous_id.continuous_on, ..local_equiv.of_set s } @[simp, mfld_simps] lemma of_set_to_local_equiv : (of_set s hs).to_local_equiv = local_equiv.of_set s := rfl @[simp, mfld_simps] lemma of_set_symm : (of_set s hs).symm = of_set s hs := rfl @[simp, mfld_simps] lemma of_set_univ_eq_refl : of_set univ is_open_univ = local_homeomorph.refl α := by ext; simp end /-- Composition of two local homeomorphisms when the target of the first and the source of the second coincide. -/ protected def trans' (h : e.target = e'.source) : local_homeomorph α γ := { open_source := e.open_source, open_target := e'.open_target, continuous_to_fun := begin apply e'.continuous_to_fun.comp e.continuous_to_fun, rw ← h, exact e.to_local_equiv.source_subset_preimage_target end, continuous_inv_fun := begin apply e.continuous_inv_fun.comp e'.continuous_inv_fun, rw h, exact e'.to_local_equiv.target_subset_preimage_source end, ..local_equiv.trans' e.to_local_equiv e'.to_local_equiv h } /-- Composing two local homeomorphisms, by restricting to the maximal domain where their composition is well defined. -/ protected def trans : local_homeomorph α γ := local_homeomorph.trans' (e.symm.restr_open e'.source e'.open_source).symm (e'.restr_open e.target e.open_target) (by simp [inter_comm]) @[simp, mfld_simps] lemma trans_to_local_equiv : (e.trans e').to_local_equiv = e.to_local_equiv.trans e'.to_local_equiv := rfl @[simp, mfld_simps] lemma coe_trans : (e.trans e' : α → γ) = e' ∘ e := rfl @[simp, mfld_simps] lemma coe_trans_symm : ((e.trans e').symm : γ → α) = e.symm ∘ e'.symm := rfl lemma trans_apply {x : α} : (e.trans e') x = e' (e x) := rfl lemma trans_symm_eq_symm_trans_symm : (e.trans e').symm = e'.symm.trans e.symm := by cases e; cases e'; refl /- This could be considered as a simp lemma, but there are many situations where it makes something simple into something more complicated. -/ lemma trans_source : (e.trans e').source = e.source ∩ e ⁻¹' e'.source := local_equiv.trans_source e.to_local_equiv e'.to_local_equiv lemma trans_source' : (e.trans e').source = e.source ∩ e ⁻¹' (e.target ∩ e'.source) := local_equiv.trans_source' e.to_local_equiv e'.to_local_equiv lemma trans_source'' : (e.trans e').source = e.symm '' (e.target ∩ e'.source) := local_equiv.trans_source'' e.to_local_equiv e'.to_local_equiv lemma image_trans_source : e '' (e.trans e').source = e.target ∩ e'.source := local_equiv.image_trans_source e.to_local_equiv e'.to_local_equiv lemma trans_target : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' e.target := rfl lemma trans_target' : (e.trans e').target = e'.target ∩ e'.symm ⁻¹' (e'.source ∩ e.target) := trans_source' e'.symm e.symm lemma trans_target'' : (e.trans e').target = e' '' (e'.source ∩ e.target) := trans_source'' e'.symm e.symm lemma inv_image_trans_target : e'.symm '' (e.trans e').target = e'.source ∩ e.target := image_trans_source e'.symm e.symm lemma trans_assoc (e'' : local_homeomorph γ δ) : (e.trans e').trans e'' = e.trans (e'.trans e'') := eq_of_local_equiv_eq $ local_equiv.trans_assoc e.to_local_equiv e'.to_local_equiv e''.to_local_equiv @[simp, mfld_simps] lemma trans_refl : e.trans (local_homeomorph.refl β) = e := eq_of_local_equiv_eq $ local_equiv.trans_refl e.to_local_equiv @[simp, mfld_simps] lemma refl_trans : (local_homeomorph.refl α).trans e = e := eq_of_local_equiv_eq $ local_equiv.refl_trans e.to_local_equiv lemma trans_of_set {s : set β} (hs : is_open s) : e.trans (of_set s hs) = e.restr (e ⁻¹' s) := local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) $ by simp [local_equiv.trans_source, (e.preimage_interior _).symm, hs.interior_eq] lemma trans_of_set' {s : set β} (hs : is_open s) : e.trans (of_set s hs) = e.restr (e.source ∩ e ⁻¹' s) := by rw [trans_of_set, restr_source_inter] lemma of_set_trans {s : set α} (hs : is_open s) : (of_set s hs).trans e = e.restr s := local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) $ by simp [local_equiv.trans_source, hs.interior_eq, inter_comm] lemma of_set_trans' {s : set α} (hs : is_open s) : (of_set s hs).trans e = e.restr (e.source ∩ s) := by rw [of_set_trans, restr_source_inter] @[simp, mfld_simps] lemma of_set_trans_of_set {s : set α} (hs : is_open s) {s' : set α} (hs' : is_open s') : (of_set s hs).trans (of_set s' hs') = of_set (s ∩ s') (is_open.inter hs hs') := begin rw (of_set s hs).trans_of_set hs', ext; simp [hs'.interior_eq] end lemma restr_trans (s : set α) : (e.restr s).trans e' = (e.trans e').restr s := eq_of_local_equiv_eq $ local_equiv.restr_trans e.to_local_equiv e'.to_local_equiv (interior s) /-- Postcompose a local homeomorphism with an homeomorphism. We modify the source and target to have better definitional behavior. -/ @[simps {fully_applied := ff}] def trans_homeomorph (e' : β ≃ₜ γ) : local_homeomorph α γ := { to_local_equiv := e.to_local_equiv.trans_equiv e'.to_equiv, open_source := e.open_source, open_target := e.open_target.preimage e'.symm.continuous, continuous_to_fun := e'.continuous.comp_continuous_on e.continuous_on, continuous_inv_fun := e.symm.continuous_on.comp e'.symm.continuous.continuous_on (λ x h, h) } lemma trans_equiv_eq_trans (e' : β ≃ₜ γ) : e.trans_homeomorph e' = e.trans e'.to_local_homeomorph := to_local_equiv_injective $ local_equiv.trans_equiv_eq_trans _ _ /-- Precompose a local homeomorphism with an homeomorphism. We modify the source and target to have better definitional behavior. -/ @[simps {fully_applied := ff}] def _root_.homeomorph.trans_local_homeomorph (e : α ≃ₜ β) : local_homeomorph α γ := { to_local_equiv := e.to_equiv.trans_local_equiv e'.to_local_equiv, open_source := e'.open_source.preimage e.continuous, open_target := e'.open_target, continuous_to_fun := e'.continuous_on.comp e.continuous.continuous_on (λ x h, h), continuous_inv_fun := e.symm.continuous.comp_continuous_on e'.symm.continuous_on } lemma _root_.homeomorph.trans_local_homeomorph_eq_trans (e : α ≃ₜ β) : e.trans_local_homeomorph e' = e.to_local_homeomorph.trans e' := to_local_equiv_injective $ equiv.trans_local_equiv_eq_trans _ _ /-- `eq_on_source e e'` means that `e` and `e'` have the same source, and coincide there. They should really be considered the same local equiv. -/ def eq_on_source (e e' : local_homeomorph α β) : Prop := e.source = e'.source ∧ (eq_on e e' e.source) lemma eq_on_source_iff (e e' : local_homeomorph α β) : eq_on_source e e' ↔ local_equiv.eq_on_source e.to_local_equiv e'.to_local_equiv := iff.rfl /-- `eq_on_source` is an equivalence relation -/ instance : setoid (local_homeomorph α β) := { r := eq_on_source, iseqv := ⟨ λe, (@local_equiv.eq_on_source_setoid α β).iseqv.1 e.to_local_equiv, λe e' h, (@local_equiv.eq_on_source_setoid α β).iseqv.2.1 ((eq_on_source_iff e e').1 h), λe e' e'' h h', (@local_equiv.eq_on_source_setoid α β).iseqv.2.2 ((eq_on_source_iff e e').1 h) ((eq_on_source_iff e' e'').1 h')⟩ } lemma eq_on_source_refl : e ≈ e := setoid.refl _ /-- If two local homeomorphisms are equivalent, so are their inverses -/ lemma eq_on_source.symm' {e e' : local_homeomorph α β} (h : e ≈ e') : e.symm ≈ e'.symm := local_equiv.eq_on_source.symm' h /-- Two equivalent local homeomorphisms have the same source -/ lemma eq_on_source.source_eq {e e' : local_homeomorph α β} (h : e ≈ e') : e.source = e'.source := h.1 /-- Two equivalent local homeomorphisms have the same target -/ lemma eq_on_source.target_eq {e e' : local_homeomorph α β} (h : e ≈ e') : e.target = e'.target := h.symm'.1 /-- Two equivalent local homeomorphisms have coinciding `to_fun` on the source -/ lemma eq_on_source.eq_on {e e' : local_homeomorph α β} (h : e ≈ e') : eq_on e e' e.source := h.2 /-- Two equivalent local homeomorphisms have coinciding `inv_fun` on the target -/ lemma eq_on_source.symm_eq_on_target {e e' : local_homeomorph α β} (h : e ≈ e') : eq_on e.symm e'.symm e.target := h.symm'.2 /-- Composition of local homeomorphisms respects equivalence -/ lemma eq_on_source.trans' {e e' : local_homeomorph α β} {f f' : local_homeomorph β γ} (he : e ≈ e') (hf : f ≈ f') : e.trans f ≈ e'.trans f' := local_equiv.eq_on_source.trans' he hf /-- Restriction of local homeomorphisms respects equivalence -/ lemma eq_on_source.restr {e e' : local_homeomorph α β} (he : e ≈ e') (s : set α) : e.restr s ≈ e'.restr s := local_equiv.eq_on_source.restr he _ lemma set.eq_on.restr_eq_on_source {e e' : local_homeomorph α β} (h : eq_on e e' (e.source ∩ e'.source)) : e.restr e'.source ≈ e'.restr e.source := begin split, { rw e'.restr_source' _ e.open_source, rw e.restr_source' _ e'.open_source, exact set.inter_comm _ _ }, { rw e.restr_source' _ e'.open_source, refine (eq_on.trans _ h).trans _; simp only with mfld_simps }, end /-- Composition of a local homeomorphism and its inverse is equivalent to the restriction of the identity to the source -/ lemma trans_self_symm : e.trans e.symm ≈ local_homeomorph.of_set e.source e.open_source := local_equiv.trans_self_symm _ lemma trans_symm_self : e.symm.trans e ≈ local_homeomorph.of_set e.target e.open_target := e.symm.trans_self_symm lemma eq_of_eq_on_source_univ {e e' : local_homeomorph α β} (h : e ≈ e') (s : e.source = univ) (t : e.target = univ) : e = e' := eq_of_local_equiv_eq $ local_equiv.eq_of_eq_on_source_univ _ _ h s t section prod /-- The product of two local homeomorphisms, as a local homeomorphism on the product space. -/ @[simps to_local_equiv apply (mfld_cfg), simps source target symm_apply {attrs := []}] def prod (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : local_homeomorph (α × γ) (β × δ) := { open_source := e.open_source.prod e'.open_source, open_target := e.open_target.prod e'.open_target, continuous_to_fun := e.continuous_on.prod_map e'.continuous_on, continuous_inv_fun := e.continuous_on_symm.prod_map e'.continuous_on_symm, to_local_equiv := e.to_local_equiv.prod e'.to_local_equiv } @[simp, mfld_simps] lemma prod_symm (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').symm = (e.symm.prod e'.symm) := rfl @[simp] lemma refl_prod_refl {α β : Type*} [topological_space α] [topological_space β] : (local_homeomorph.refl α).prod (local_homeomorph.refl β) = local_homeomorph.refl (α × β) := by { ext1 ⟨x, y⟩, { refl }, { rintro ⟨x, y⟩, refl }, exact univ_prod_univ } @[simp, mfld_simps] lemma prod_trans {η : Type*} {ε : Type*} [topological_space η] [topological_space ε] (e : local_homeomorph α β) (f : local_homeomorph β γ) (e' : local_homeomorph δ η) (f' : local_homeomorph η ε) : (e.prod e').trans (f.prod f') = (e.trans f).prod (e'.trans f') := local_homeomorph.eq_of_local_equiv_eq $ by dsimp only [trans_to_local_equiv, prod_to_local_equiv]; apply local_equiv.prod_trans lemma prod_eq_prod_of_nonempty {e₁ e₁' : local_homeomorph α β} {e₂ e₂' : local_homeomorph γ δ} (h : (e₁.prod e₂).source.nonempty) : e₁.prod e₂ = e₁'.prod e₂' ↔ e₁ = e₁' ∧ e₂ = e₂' := begin obtain ⟨⟨x, y⟩, -⟩ := id h, haveI : nonempty α := ⟨x⟩, haveI : nonempty β := ⟨e₁ x⟩, haveI : nonempty γ := ⟨y⟩, haveI : nonempty δ := ⟨e₂ y⟩, simp_rw [local_homeomorph.ext_iff, prod_apply, prod_symm_apply, prod_source, prod.ext_iff, set.prod_eq_prod_iff_of_nonempty h, forall_and_distrib, prod.forall, forall_const, forall_forall_const, and_assoc, and.left_comm] end lemma prod_eq_prod_of_nonempty' {e₁ e₁' : local_homeomorph α β} {e₂ e₂' : local_homeomorph γ δ} (h : (e₁'.prod e₂').source.nonempty) : e₁.prod e₂ = e₁'.prod e₂' ↔ e₁ = e₁' ∧ e₂ = e₂' := by rw [eq_comm, prod_eq_prod_of_nonempty h, eq_comm, @eq_comm _ e₂'] end prod section piecewise /-- Combine two `local_homeomorph`s using `set.piecewise`. The source of the new `local_homeomorph` is `s.ite e.source e'.source = e.source ∩ s ∪ e'.source \ s`, and similarly for target. The function sends `e.source ∩ s` to `e.target ∩ t` using `e` and `e'.source \ s` to `e'.target \ t` using `e'`, and similarly for the inverse function. To ensure that the maps `to_fun` and `inv_fun` are inverse of each other on the new `source` and `target`, the definition assumes that the sets `s` and `t` are related both by `e.is_image` and `e'.is_image`. To ensure that the new maps are continuous on `source`/`target`, it also assumes that `e.source` and `e'.source` meet `frontier s` on the same set and `e x = e' x` on this intersection. -/ @[simps to_local_equiv apply {fully_applied := ff}] def piecewise (e e' : local_homeomorph α β) (s : set α) (t : set β) [∀ x, decidable (x ∈ s)] [∀ y, decidable (y ∈ t)] (H : e.is_image s t) (H' : e'.is_image s t) (Hs : e.source ∩ frontier s = e'.source ∩ frontier s) (Heq : eq_on e e' (e.source ∩ frontier s)) : local_homeomorph α β := { to_local_equiv := e.to_local_equiv.piecewise e'.to_local_equiv s t H H', open_source := e.open_source.ite e'.open_source Hs, open_target := e.open_target.ite e'.open_target $ H.frontier.inter_eq_of_inter_eq_of_eq_on H'.frontier Hs Heq, continuous_to_fun := continuous_on_piecewise_ite e.continuous_on e'.continuous_on Hs Heq, continuous_inv_fun := continuous_on_piecewise_ite e.continuous_on_symm e'.continuous_on_symm (H.frontier.inter_eq_of_inter_eq_of_eq_on H'.frontier Hs Heq) (H.frontier.symm_eq_on_of_inter_eq_of_eq_on Hs Heq) } @[simp] lemma symm_piecewise (e e' : local_homeomorph α β) {s : set α} {t : set β} [∀ x, decidable (x ∈ s)] [∀ y, decidable (y ∈ t)] (H : e.is_image s t) (H' : e'.is_image s t) (Hs : e.source ∩ frontier s = e'.source ∩ frontier s) (Heq : eq_on e e' (e.source ∩ frontier s)) : (e.piecewise e' s t H H' Hs Heq).symm = e.symm.piecewise e'.symm t s H.symm H'.symm (H.frontier.inter_eq_of_inter_eq_of_eq_on H'.frontier Hs Heq) (H.frontier.symm_eq_on_of_inter_eq_of_eq_on Hs Heq) := rfl /-- Combine two `local_homeomorph`s with disjoint sources and disjoint targets. We reuse `local_homeomorph.piecewise` then override `to_local_equiv` to `local_equiv.disjoint_union`. This way we have better definitional equalities for `source` and `target`. -/ def disjoint_union (e e' : local_homeomorph α β) [∀ x, decidable (x ∈ e.source)] [∀ y, decidable (y ∈ e.target)] (Hs : disjoint e.source e'.source) (Ht : disjoint e.target e'.target) : local_homeomorph α β := (e.piecewise e' e.source e.target e.is_image_source_target (e'.is_image_source_target_of_disjoint e Hs.symm Ht.symm) (by rw [e.open_source.inter_frontier_eq, (Hs.symm.frontier_right e'.open_source).inter_eq]) (by { rw e.open_source.inter_frontier_eq, exact eq_on_empty _ _ })).replace_equiv (e.to_local_equiv.disjoint_union e'.to_local_equiv Hs Ht) (local_equiv.disjoint_union_eq_piecewise _ _ _ _).symm end piecewise section pi variables {ι : Type*} [fintype ι] {Xi Yi : ι → Type*} [Π i, topological_space (Xi i)] [Π i, topological_space (Yi i)] (ei : Π i, local_homeomorph (Xi i) (Yi i)) /-- The product of a finite family of `local_homeomorph`s. -/ @[simps to_local_equiv] def pi : local_homeomorph (Π i, Xi i) (Π i, Yi i) := { to_local_equiv := local_equiv.pi (λ i, (ei i).to_local_equiv), open_source := is_open_set_pi finite_univ $ λ i hi, (ei i).open_source, open_target := is_open_set_pi finite_univ $ λ i hi, (ei i).open_target, continuous_to_fun := continuous_on_pi.2 $ λ i, (ei i).continuous_on.comp (continuous_apply _).continuous_on (λ f hf, hf i trivial), continuous_inv_fun := continuous_on_pi.2 $ λ i, (ei i).continuous_on_symm.comp (continuous_apply _).continuous_on (λ f hf, hf i trivial) } end pi section continuity /-- Continuity within a set at a point can be read under right composition with a local homeomorphism, if the point is in its target -/ lemma continuous_within_at_iff_continuous_within_at_comp_right {f : β → γ} {s : set β} {x : β} (h : x ∈ e.target) : continuous_within_at f s x ↔ continuous_within_at (f ∘ e) (e ⁻¹' s) (e.symm x) := by simp_rw [continuous_within_at, ← @tendsto_map'_iff _ _ _ _ e, e.map_nhds_within_preimage_eq (e.map_target h), (∘), e.right_inv h] /-- Continuity at a point can be read under right composition with a local homeomorphism, if the point is in its target -/ lemma continuous_at_iff_continuous_at_comp_right {f : β → γ} {x : β} (h : x ∈ e.target) : continuous_at f x ↔ continuous_at (f ∘ e) (e.symm x) := by rw [← continuous_within_at_univ, e.continuous_within_at_iff_continuous_within_at_comp_right h, preimage_univ, continuous_within_at_univ] /-- A function is continuous on a set if and only if its composition with a local homeomorphism on the right is continuous on the corresponding set. -/ lemma continuous_on_iff_continuous_on_comp_right {f : β → γ} {s : set β} (h : s ⊆ e.target) : continuous_on f s ↔ continuous_on (f ∘ e) (e.source ∩ e ⁻¹' s) := begin simp only [← e.symm_image_eq_source_inter_preimage h, continuous_on, ball_image_iff], refine forall₂_congr (λ x hx, _), rw [e.continuous_within_at_iff_continuous_within_at_comp_right (h hx), e.symm_image_eq_source_inter_preimage h, inter_comm, continuous_within_at_inter], exact is_open.mem_nhds e.open_source (e.map_target (h hx)) end /-- Continuity within a set at a point can be read under left composition with a local homeomorphism if a neighborhood of the initial point is sent to the source of the local homeomorphism-/ lemma continuous_within_at_iff_continuous_within_at_comp_left {f : γ → α} {s : set γ} {x : γ} (hx : f x ∈ e.source) (h : f ⁻¹' e.source ∈ 𝓝[s] x) : continuous_within_at f s x ↔ continuous_within_at (e ∘ f) s x := begin refine ⟨(e.continuous_at hx).comp_continuous_within_at, λ fe_cont, _⟩, rw [← continuous_within_at_inter' h] at fe_cont ⊢, have : continuous_within_at (e.symm ∘ (e ∘ f)) (s ∩ f ⁻¹' e.source) x, { have : continuous_within_at e.symm univ (e (f x)) := (e.continuous_at_symm (e.map_source hx)).continuous_within_at, exact continuous_within_at.comp this fe_cont (subset_univ _) }, exact this.congr (λy hy, by simp [e.left_inv hy.2]) (by simp [e.left_inv hx]) end /-- Continuity at a point can be read under left composition with a local homeomorphism if a neighborhood of the initial point is sent to the source of the local homeomorphism-/ lemma continuous_at_iff_continuous_at_comp_left {f : γ → α} {x : γ} (h : f ⁻¹' e.source ∈ 𝓝 x) : continuous_at f x ↔ continuous_at (e ∘ f) x := begin have hx : f x ∈ e.source := (mem_of_mem_nhds h : _), have h' : f ⁻¹' e.source ∈ 𝓝[univ] x, by rwa nhds_within_univ, rw [← continuous_within_at_univ, ← continuous_within_at_univ, e.continuous_within_at_iff_continuous_within_at_comp_left hx h'] end /-- A function is continuous on a set if and only if its composition with a local homeomorphism on the left is continuous on the corresponding set. -/ lemma continuous_on_iff_continuous_on_comp_left {f : γ → α} {s : set γ} (h : s ⊆ f ⁻¹' e.source) : continuous_on f s ↔ continuous_on (e ∘ f) s := forall₂_congr $ λ x hx, e.continuous_within_at_iff_continuous_within_at_comp_left (h hx) (mem_of_superset self_mem_nhds_within h) /-- A function is continuous if and only if its composition with a local homeomorphism on the left is continuous and its image is contained in the source. -/ lemma continuous_iff_continuous_comp_left {f : γ → α} (h : f ⁻¹' e.source = univ) : continuous f ↔ continuous (e ∘ f) := begin simp only [continuous_iff_continuous_on_univ], exact e.continuous_on_iff_continuous_on_comp_left (eq.symm h).subset, end end continuity /-- The homeomorphism obtained by restricting a `local_homeomorph` to a subset of the source. -/ @[simps] def homeomorph_of_image_subset_source {s : set α} {t : set β} (hs : s ⊆ e.source) (ht : e '' s = t) : s ≃ₜ t := { to_fun := λ a, ⟨e a, (congr_arg ((∈) (e a)) ht).mp ⟨a, a.2, rfl⟩⟩, inv_fun := λ b, ⟨e.symm b, let ⟨a, ha1, ha2⟩ := (congr_arg ((∈) ↑b) ht).mpr b.2 in ha2 ▸ (e.left_inv (hs ha1)).symm ▸ ha1⟩, left_inv := λ a, subtype.ext (e.left_inv (hs a.2)), right_inv := λ b, let ⟨a, ha1, ha2⟩ := (congr_arg ((∈) ↑b) ht).mpr b.2 in subtype.ext (e.right_inv (ha2 ▸ e.map_source (hs ha1))), continuous_to_fun := (continuous_on_iff_continuous_restrict.mp (e.continuous_on.mono hs)).subtype_mk _, continuous_inv_fun := (continuous_on_iff_continuous_restrict.mp (e.continuous_on_symm.mono (λ b hb, let ⟨a, ha1, ha2⟩ := show b ∈ e '' s, from ht.symm ▸ hb in ha2 ▸ e.map_source (hs ha1)))).subtype_mk _ } /-- A local homeomrphism defines a homeomorphism between its source and target. -/ def to_homeomorph_source_target : e.source ≃ₜ e.target := e.homeomorph_of_image_subset_source subset_rfl e.image_source_eq_target lemma second_countable_topology_source [second_countable_topology β] (e : local_homeomorph α β) : second_countable_topology e.source := e.to_homeomorph_source_target.second_countable_topology /-- If a local homeomorphism has source and target equal to univ, then it induces a homeomorphism between the whole spaces, expressed in this definition. -/ @[simps apply symm_apply (mfld_cfg)] def to_homeomorph_of_source_eq_univ_target_eq_univ (h : e.source = (univ : set α)) (h' : e.target = univ) : α ≃ₜ β := { to_fun := e, inv_fun := e.symm, left_inv := λx, e.left_inv $ by { rw h, exact mem_univ _ }, right_inv := λx, e.right_inv $ by { rw h', exact mem_univ _ }, continuous_to_fun := begin rw [continuous_iff_continuous_on_univ], convert e.continuous_to_fun, rw h end, continuous_inv_fun := begin rw [continuous_iff_continuous_on_univ], convert e.continuous_inv_fun, rw h' end } /-- A local homeomorphism whose source is all of `α` defines an open embedding of `α` into `β`. The converse is also true; see `open_embedding.to_local_homeomorph`. -/ lemma to_open_embedding (h : e.source = set.univ) : open_embedding e := begin apply open_embedding_of_continuous_injective_open, { apply continuous_iff_continuous_on_univ.mpr, rw ← h, exact e.continuous_to_fun }, { apply set.injective_iff_inj_on_univ.mpr, rw ← h, exact e.inj_on }, { intros U hU, simpa only [h, subset_univ] with mfld_simps using e.image_open_of_open hU} end end local_homeomorph namespace homeomorph variables (e : α ≃ₜ β) (e' : β ≃ₜ γ) /- Register as simp lemmas that the fields of a local homeomorphism built from a homeomorphism correspond to the fields of the original homeomorphism. -/ @[simp, mfld_simps] lemma refl_to_local_homeomorph : (homeomorph.refl α).to_local_homeomorph = local_homeomorph.refl α := rfl @[simp, mfld_simps] lemma symm_to_local_homeomorph : e.symm.to_local_homeomorph = e.to_local_homeomorph.symm := rfl @[simp, mfld_simps] lemma trans_to_local_homeomorph : (e.trans e').to_local_homeomorph = e.to_local_homeomorph.trans e'.to_local_homeomorph := local_homeomorph.eq_of_local_equiv_eq $ equiv.trans_to_local_equiv _ _ end homeomorph namespace open_embedding variables (f : α → β) (h : open_embedding f) /-- An open embedding of `α` into `β`, with `α` nonempty, defines a local homeomorphism whose source is all of `α`. The converse is also true; see `local_homeomorph.to_open_embedding`. -/ @[simps apply source target (mfld_cfg)] noncomputable def to_local_homeomorph [nonempty α] : local_homeomorph α β := local_homeomorph.of_continuous_open ((h.to_embedding.inj.inj_on univ).to_local_equiv _ _) h.continuous.continuous_on h.is_open_map is_open_univ lemma continuous_at_iff {f : α → β} {g : β → γ} (hf : open_embedding f) {x : α} : continuous_at (g ∘ f) x ↔ continuous_at g (f x) := begin haveI : nonempty α := ⟨x⟩, convert (((hf.to_local_homeomorph f).continuous_at_iff_continuous_at_comp_right) _).symm, { apply (local_homeomorph.left_inv _ _).symm, simp, }, { simp, }, end end open_embedding namespace topological_space.opens open topological_space variables (s : opens α) [nonempty s] /-- The inclusion of an open subset `s` of a space `α` into `α` is a local homeomorphism from the subtype `s` to `α`. -/ noncomputable def local_homeomorph_subtype_coe : local_homeomorph s α := open_embedding.to_local_homeomorph _ s.2.open_embedding_subtype_coe @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_coe : (s.local_homeomorph_subtype_coe : s → α) = coe := rfl @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_source : s.local_homeomorph_subtype_coe.source = set.univ := rfl @[simp, mfld_simps] lemma local_homeomorph_subtype_coe_target : s.local_homeomorph_subtype_coe.target = s := by { simp only [local_homeomorph_subtype_coe, subtype.range_coe_subtype] with mfld_simps, refl } end topological_space.opens namespace local_homeomorph open topological_space variables (e : local_homeomorph α β) variables (s : opens α) [nonempty s] /-- The restriction of a local homeomorphism `e` to an open subset `s` of the domain type produces a local homeomorphism whose domain is the subtype `s`.-/ noncomputable def subtype_restr : local_homeomorph s β := s.local_homeomorph_subtype_coe.trans e lemma subtype_restr_def : e.subtype_restr s = s.local_homeomorph_subtype_coe.trans e := rfl @[simp, mfld_simps] lemma subtype_restr_coe : ((e.subtype_restr s : local_homeomorph s β) : s → β) = set.restrict ↑s (e : α → β) := rfl @[simp, mfld_simps] lemma subtype_restr_source : (e.subtype_restr s).source = coe ⁻¹' e.source := by simp only [subtype_restr_def] with mfld_simps /- This lemma characterizes the transition functions of an open subset in terms of the transition functions of the original space. -/ lemma subtype_restr_symm_trans_subtype_restr (f f' : local_homeomorph α β) : (f.subtype_restr s).symm.trans (f'.subtype_restr s) ≈ (f.symm.trans f').restr (f.target ∩ (f.symm) ⁻¹' s) := begin simp only [subtype_restr_def, trans_symm_eq_symm_trans_symm], have openness₁ : is_open (f.target ∩ f.symm ⁻¹' s) := f.preimage_open_of_open_symm s.2, rw [← of_set_trans _ openness₁, ← trans_assoc, ← trans_assoc], refine eq_on_source.trans' _ (eq_on_source_refl _), -- f' has been eliminated !!! have sets_identity : f.symm.source ∩ (f.target ∩ (f.symm) ⁻¹' s) = f.symm.source ∩ f.symm ⁻¹' s, { mfld_set_tac }, have openness₂ : is_open (s : set α) := s.2, rw [of_set_trans', sets_identity, ← trans_of_set' _ openness₂, trans_assoc], refine eq_on_source.trans' (eq_on_source_refl _) _, -- f has been eliminated !!! refine setoid.trans (trans_symm_self s.local_homeomorph_subtype_coe) _, simp only with mfld_simps, end end local_homeomorph
05ef761ffee47eca0d8ea94639f130e4c2137311
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/rewrite_with_beta.lean
b64f34981ef9c590f3d4bf6ef3234d9abacb3bc3
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
266
lean
import data.stream open nat namespace stream variable A : Type theorem mem_cons_of_mem₂ {a : A} {s : stream A} (b : A) : a ∈ s → a ∈ b :: s := assume ains, obtain n h, from ains, exists.intro (succ n) begin rewrite [nth_succ, tail_cons, h] end end stream
00e9f5a839db71e14a995880d2793b828fe86e9a
57aec6ee746bc7e3a3dd5e767e53bd95beb82f6d
/stage0/src/Init/Util.lean
fecba7a1298131f9b52d0d905c32d2b69b5889c3
[ "Apache-2.0" ]
permissive
collares/lean4
861a9269c4592bce49b71059e232ff0bfe4594cc
52a4f535d853a2c7c7eea5fee8a4fa04c682c1ee
refs/heads/master
1,691,419,031,324
1,618,678,138,000
1,618,678,138,000
358,989,750
0
0
Apache-2.0
1,618,696,333,000
1,618,696,333,000
null
UTF-8
Lean
false
false
2,667
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 -/ prelude import Init.Data.String.Basic import Init.Data.ToString.Basic universes u v /- debugging helper functions -/ @[neverExtract, extern "lean_dbg_trace"] def dbgTrace {α : Type u} (s : String) (f : Unit → α) : α := f () def dbgTraceVal {α : Type u} [ToString α] (a : α) : α := dbgTrace (toString a) (fun _ => a) /- Display the given message if `a` is shared, that is, RC(a) > 1 -/ @[neverExtract, extern "lean_dbg_trace_if_shared"] def dbgTraceIfShared {α : Type u} (s : String) (a : α) : α := a @[extern "lean_dbg_sleep"] def dbgSleep {α : Type u} (ms : UInt32) (f : Unit → α) : α := f () @[noinline] private def mkPanicMessage (modName : String) (line col : Nat) (msg : String) : String := "PANIC at " ++ modName ++ ":" ++ toString line ++ ":" ++ toString col ++ ": " ++ msg @[neverExtract, inline] def panicWithPos {α : Type u} [Inhabited α] (modName : String) (line col : Nat) (msg : String) : α := panic (mkPanicMessage modName line col msg) @[noinline] private def mkPanicMessageWithDecl (modName : String) (declName : String) (line col : Nat) (msg : String) : String := "PANIC at " ++ declName ++ " " ++ modName ++ ":" ++ toString line ++ ":" ++ toString col ++ ": " ++ msg @[neverExtract, inline] def panicWithPosWithDecl {α : Type u} [Inhabited α] (modName : String) (declName : String) (line col : Nat) (msg : String) : α := panic (mkPanicMessageWithDecl modName declName line col msg) @[extern "lean_ptr_addr"] unsafe def ptrAddrUnsafe {α : Type u} (a : @& α) : USize := 0 @[inline] unsafe def withPtrAddrUnsafe {α : Type u} {β : Type v} (a : α) (k : USize → β) (h : ∀ u₁ u₂, k u₁ = k u₂) : β := k (ptrAddrUnsafe a) @[inline] unsafe def withPtrEqUnsafe {α : Type u} (a b : α) (k : Unit → Bool) (h : a = b → k () = true) : Bool := if ptrAddrUnsafe a == ptrAddrUnsafe b then true else k () @[implementedBy withPtrEqUnsafe] def withPtrEq {α : Type u} (a b : α) (k : Unit → Bool) (h : a = b → k () = true) : Bool := k () /-- `withPtrEq` for `DecidableEq` -/ @[inline] def withPtrEqDecEq {α : Type u} (a b : α) (k : Unit → Decidable (a = b)) : Decidable (a = b) := let b := withPtrEq a b (fun _ => toBoolUsing (k ())) (toBoolUsingEqTrue (k ())); match h:b with | true => isTrue (ofBoolUsingEqTrue h) | false => isFalse (ofBoolUsingEqFalse h) @[implementedBy withPtrAddrUnsafe] def withPtrAddr {α : Type u} {β : Type v} (a : α) (k : USize → β) (h : ∀ u₁ u₂, k u₁ = k u₂) : β := k 0
d1355f2f0f692357a181ec9511c94ca96b887ab3
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/topology/uniform_space/abstract_completion.lean
7650ef29d325cbcbec37d8aadd8be0974d1db0df
[ "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,219
lean
/- Copyright (c) 2019 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.uniform_space.cauchy import topology.uniform_space.uniform_embedding /-! # Abstract theory of Hausdorff completions of uniform spaces This file characterizes Hausdorff completions of a uniform space α as complete Hausdorff spaces equipped with a map from α which has dense image and induce the original uniform structure on α. Assuming these properties we "extend" uniformly continuous maps from α to complete Hausdorff spaces to the completions of α. This is the universal property expected from a completion. It is then used to extend uniformly continuous maps from α to α' to maps between completions of α and α'. This file does not construct any such completion, it only study consequences of their existence. The first advantage is that formal properties are clearly highlighted without interference from construction details. The second advantage is that this framework can then be used to compare different completion constructions. See `topology/uniform_space/compare_reals` for an example. Of course the comparison comes from the universal property as usual. A general explicit construction of completions is done in `uniform_space/completion`, leading to a functor from uniform spaces to complete Hausdorff uniform spaces that is left adjoint to the inclusion, see `uniform_space/UniformSpace` for the category packaging. ## Implementation notes A tiny technical advantage of using a characteristic predicate such as the properties listed in `abstract_completion` instead of stating the universal property is that the universal property derived from the predicate is more universe polymorphic. ## References We don't know any traditional text discussing this. Real world mathematics simply silently identify the results of any two constructions that lead to something one could reasonnably call a completion. ## Tags uniform spaces, completion, universal property -/ noncomputable theory local attribute [instance, priority 10] classical.prop_decidable open filter set function universes u /-- A completion of `α` is the data of a complete separated uniform space (from the same universe) and a map from `α` with dense range and inducing the original uniform structure on `α`. -/ structure abstract_completion (α : Type u) [uniform_space α] := (space : Type u) (coe : α → space) (uniform_struct : uniform_space space) (complete : complete_space space) (separation : separated space) (uniform_inducing : uniform_inducing coe) (dense : dense_range coe) local attribute [instance] abstract_completion.uniform_struct abstract_completion.complete abstract_completion.separation namespace abstract_completion variables {α : Type*} [uniform_space α] (pkg : abstract_completion α) local notation `hatα` := pkg.space local notation `ι` := pkg.coe lemma dense' : closure (range ι) = univ := pkg.dense.closure_range lemma dense_inducing : dense_inducing ι := ⟨pkg.uniform_inducing.inducing, pkg.dense⟩ lemma uniform_continuous_coe : uniform_continuous ι := uniform_inducing.uniform_continuous pkg.uniform_inducing lemma continuous_coe : continuous ι := pkg.uniform_continuous_coe.continuous @[elab_as_eliminator] lemma induction_on {p : hatα → Prop} (a : hatα) (hp : is_closed {a | p a}) (ih : ∀ a, p (ι a)) : p a := is_closed_property pkg.dense hp ih a variables {β : Type*} [uniform_space β] protected lemma funext [t2_space β] {f g : hatα → β} (hf : continuous f) (hg : continuous g) (h : ∀ a, f (ι a) = g (ι a)) : f = g := funext $ assume a, pkg.induction_on a (is_closed_eq hf hg) h section extend /-- Extension of maps to completions -/ protected def extend (f : α → β) : hatα → β := if uniform_continuous f then pkg.dense_inducing.extend f else λ x, f (classical.inhabited_of_nonempty $ pkg.dense.nonempty.2 ⟨x⟩).default variables {f : α → β} lemma extend_def (hf : uniform_continuous f) : pkg.extend f = pkg.dense_inducing.extend f := if_pos hf lemma extend_coe [t2_space β] (hf : uniform_continuous f) (a : α) : (pkg.extend f) (ι a) = f a := begin rw pkg.extend_def hf, exact pkg.dense_inducing.extend_eq_of_cont hf.continuous a end variables [complete_space β] [separated β] lemma uniform_continuous_extend : uniform_continuous (pkg.extend f) := begin by_cases hf : uniform_continuous f, { rw pkg.extend_def hf, exact uniform_continuous_uniformly_extend (pkg.uniform_inducing) (pkg.dense) hf }, { change uniform_continuous (ite _ _ _), rw if_neg hf, exact uniform_continuous_of_const (assume a b, by congr) } end lemma continuous_extend : continuous (pkg.extend f) := pkg.uniform_continuous_extend.continuous lemma extend_unique (hf : uniform_continuous f) {g : hatα → β} (hg : uniform_continuous g) (h : ∀ a : α, f a = g (ι a)) : pkg.extend f = g := begin apply pkg.funext pkg.continuous_extend hg.continuous, simpa only [pkg.extend_coe hf] using h end @[simp] lemma extend_comp_coe {f : hatα → β} (hf : uniform_continuous f) : pkg.extend (f ∘ ι) = f := funext $ λ x, pkg.induction_on x (is_closed_eq pkg.continuous_extend hf.continuous) (λ y, pkg.extend_coe (hf.comp $ pkg.uniform_continuous_coe) y) end extend section map_sec variables (pkg' : abstract_completion β) local notation `hatβ` := pkg'.space local notation `ι'` := pkg'.coe /-- Lifting maps to completions -/ protected def map (f : α → β) : hatα → hatβ := pkg.extend (ι' ∘ f) local notation `map` := pkg.map pkg' variables (f : α → β) lemma uniform_continuous_map : uniform_continuous (map f) := pkg.uniform_continuous_extend lemma continuous_map : continuous (map f) := pkg.continuous_extend variables {f} @[simp] lemma map_coe (hf : uniform_continuous f) (a : α) : map f (ι a) = ι' (f a) := pkg.extend_coe (pkg'.uniform_continuous_coe.comp hf) a lemma map_unique {f : α → β} {g : hatα → hatβ} (hg : uniform_continuous g) (h : ∀ a, ι' (f a) = g (ι a)) : map f = g := pkg.funext (pkg.continuous_map _ _) hg.continuous $ begin intro a, change pkg.extend (ι' ∘ f) _ = _, simp only [(∘), h], rw [pkg.extend_coe (hg.comp pkg.uniform_continuous_coe)] end @[simp] lemma map_id : pkg.map pkg id = id := pkg.map_unique pkg uniform_continuous_id (assume a, rfl) variables {γ : Type*} [uniform_space γ] lemma extend_map [complete_space γ] [separated γ] {f : β → γ} {g : α → β} (hf : uniform_continuous f) (hg : uniform_continuous g) : pkg'.extend f ∘ map g = pkg.extend (f ∘ g) := pkg.funext (pkg'.continuous_extend.comp (pkg.continuous_map pkg' _)) pkg.continuous_extend $ λ a, by rw [pkg.extend_coe (hf.comp hg), comp_app, pkg.map_coe pkg' hg, pkg'.extend_coe hf] variables (pkg'' : abstract_completion γ) lemma map_comp {g : β → γ} {f : α → β} (hg : uniform_continuous g) (hf : uniform_continuous f) : (pkg'.map pkg'' g) ∘ (pkg.map pkg' f) = pkg.map pkg'' (g ∘ f) := pkg.extend_map pkg' (pkg''.uniform_continuous_coe.comp hg) hf end map_sec section compare -- We can now compare two completion packages for the same uniform space variables (pkg' : abstract_completion α) /-- The comparison map between two completions of the same uniform space. -/ def compare : pkg.space → pkg'.space := pkg.extend pkg'.coe lemma uniform_continuous_compare : uniform_continuous (pkg.compare pkg') := pkg.uniform_continuous_extend lemma compare_coe (a : α) : pkg.compare pkg' (pkg.coe a) = pkg'.coe a := pkg.extend_coe pkg'.uniform_continuous_coe a lemma inverse_compare : (pkg.compare pkg') ∘ (pkg'.compare pkg) = id := begin have uc := pkg.uniform_continuous_compare pkg', have uc' := pkg'.uniform_continuous_compare pkg, apply pkg'.funext (uc.comp uc').continuous continuous_id, intro a, rw [comp_app, pkg'.compare_coe pkg, pkg.compare_coe pkg'], refl end /-- The bijection between two completions of the same uniform space. -/ def compare_equiv : pkg.space ≃ pkg'.space := { to_fun := pkg.compare pkg', inv_fun := pkg'.compare pkg, left_inv := congr_fun (pkg'.inverse_compare pkg), right_inv := congr_fun (pkg.inverse_compare pkg') } lemma uniform_continuous_compare_equiv : uniform_continuous (pkg.compare_equiv pkg') := pkg.uniform_continuous_compare pkg' lemma uniform_continuous_compare_equiv_symm : uniform_continuous (pkg.compare_equiv pkg').symm := pkg'.uniform_continuous_compare pkg end compare section prod variables (pkg' : abstract_completion β) local notation `hatβ` := pkg'.space local notation `ι'` := pkg'.coe /-- Products of completions -/ protected def prod : abstract_completion (α × β) := { space := hatα × hatβ, coe := λ p, ⟨ι p.1, ι' p.2⟩, uniform_struct := prod.uniform_space, complete := by apply_instance, separation := by apply_instance, uniform_inducing := uniform_inducing.prod pkg.uniform_inducing pkg'.uniform_inducing, dense := pkg.dense.prod pkg'.dense } end prod section extension₂ variables (pkg' : abstract_completion β) local notation `hatβ` := pkg'.space local notation `ι'` := pkg'.coe variables {γ : Type*} [uniform_space γ] open function /-- Extend two variable map to completions. -/ protected def extend₂ (f : α → β → γ) : hatα → hatβ → γ := curry $ (pkg.prod pkg').extend (uncurry' f) variables [separated γ] {f : α → β → γ} lemma extension₂_coe_coe (hf : uniform_continuous $ uncurry' f) (a : α) (b : β) : pkg.extend₂ pkg' f (ι a) (ι' b) = f a b := show (pkg.prod pkg').extend (uncurry' f) ((pkg.prod pkg').coe (a, b)) = uncurry' f (a, b), from (pkg.prod pkg').extend_coe hf _ variables [complete_space γ] (f) lemma uniform_continuous_extension₂ : uniform_continuous₂ (pkg.extend₂ pkg' f) := begin rw [uniform_continuous₂_def, abstract_completion.extend₂, uncurry'_curry], apply uniform_continuous_extend end end extension₂ section map₂ variables (pkg' : abstract_completion β) local notation `hatβ` := pkg'.space local notation `ι'` := pkg'.coe variables {γ : Type*} [uniform_space γ] (pkg'' : abstract_completion γ) local notation `hatγ` := pkg''.space local notation `ι''` := pkg''.coe local notation f `∘₂` g := bicompr f g /-- Lift two variable maps to completions. -/ protected def map₂ (f : α → β → γ) : hatα → hatβ → hatγ := pkg.extend₂ pkg' (pkg''.coe ∘₂ f) lemma uniform_continuous_map₂ (f : α → β → γ) : uniform_continuous (uncurry' $ pkg.map₂ pkg' pkg'' f) := pkg.uniform_continuous_extension₂ pkg' _ lemma continuous_map₂ {δ} [topological_space δ] {f : α → β → γ} {a : δ → hatα} {b : δ → hatβ} (ha : continuous a) (hb : continuous b) : continuous (λd:δ, pkg.map₂ pkg' pkg'' f (a d) (b d)) := ((pkg.uniform_continuous_map₂ pkg' pkg'' f).continuous.comp (continuous.prod_mk ha hb) : _) lemma map₂_coe_coe (a : α) (b : β) (f : α → β → γ) (hf : uniform_continuous₂ f) : pkg.map₂ pkg' pkg'' f (ι a) (ι' b) = ι'' (f a b) := pkg.extension₂_coe_coe pkg' (pkg''.uniform_continuous_coe.comp hf) a b end map₂ end abstract_completion
b22188baea8e8d2baf5410209bc0ba165b794a44
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/tactic/abel.lean
b1cc1c24668b6fb4fa6c1c242e97980f03e83eda
[ "Apache-2.0" ]
permissive
keeferrowan/mathlib
f2818da875dbc7780830d09bd4c526b0764a4e50
aad2dfc40e8e6a7e258287a7c1580318e865817e
refs/heads/master
1,661,736,426,952
1,590,438,032,000
1,590,438,032,000
266,892,663
0
0
Apache-2.0
1,590,445,835,000
1,590,445,835,000
null
UTF-8
Lean
false
false
13,194
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import tactic.norm_num /-! # The `abel` tactic Evaluate expressions in the language of additive, commutative monoids and groups. -/ namespace tactic namespace abel meta structure cache := (α : expr) (univ : level) (α0 : expr) (is_group : bool) (inst : expr) meta def mk_cache (e : expr) : tactic cache := do α ← infer_type e, c ← mk_app ``add_comm_monoid [α] >>= mk_instance, cg ← try_core (mk_app ``add_comm_group [α] >>= mk_instance), u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, α0 ← expr.of_nat α 0, match cg with | (some cg) := return ⟨α, u, α0, tt, cg⟩ | _ := return ⟨α, u, α0, ff, c⟩ end meta def cache.app (c : cache) (n : name) (inst : expr) : list expr → expr := (@expr.const tt n [c.univ] c.α inst).mk_app meta def cache.mk_app (c : cache) (n inst : name) (l : list expr) : tactic expr := do m ← mk_instance ((expr.const inst [c.univ] : expr) c.α), return $ c.app n m l meta def add_g : name → name | (name.mk_string s p) := name.mk_string (s ++ "g") p | n := n meta def cache.iapp (c : cache) (n : name) : list expr → expr := c.app (if c.is_group then add_g n else n) c.inst def term {α} [add_comm_monoid α] (n : ℕ) (x a : α) : α := add_monoid.smul n x + a def termg {α} [add_comm_group α] (n : ℤ) (x a : α) : α := gsmul n x + a meta def cache.mk_term (c : cache) (n x a : expr) : expr := c.iapp ``term [n, x, a] meta def cache.int_to_expr (c : cache) (n : ℤ) : tactic expr := expr.of_int (if c.is_group then `(ℤ) else `(ℕ)) n meta inductive normal_expr : Type | zero (e : expr) : normal_expr | nterm (e : expr) (n : expr × ℤ) (x : expr) (a : normal_expr) : normal_expr meta def normal_expr.e : normal_expr → expr | (normal_expr.zero e) := e | (normal_expr.nterm e _ _ _) := e meta instance : has_coe normal_expr expr := ⟨normal_expr.e⟩ meta instance : has_coe_to_fun normal_expr := ⟨_, λ e, ((e : expr) : expr → expr)⟩ meta def normal_expr.term' (c : cache) (n : expr × ℤ) (x : expr) (a : normal_expr) : normal_expr := normal_expr.nterm (c.mk_term n.1 x a) n x a meta def normal_expr.zero' (c : cache) : normal_expr := normal_expr.zero c.α0 meta def normal_expr.to_list : normal_expr → list (ℤ × expr) | (normal_expr.zero _) := [] | (normal_expr.nterm _ (_, n) x a) := (n, x) :: a.to_list open normal_expr meta def normal_expr.to_string (e : normal_expr) : string := " + ".intercalate $ (to_list e).map $ λ ⟨n, e⟩, to_string n ++ " • (" ++ to_string e ++ ")" meta def normal_expr.pp (e : normal_expr) : tactic format := do l ← (to_list e).mmap (λ ⟨n, e⟩, do pe ← pp e, return (to_fmt n ++ " • (" ++ pe ++ ")")), return $ format.join $ l.intersperse ↑" + " meta instance : has_to_tactic_format normal_expr := ⟨normal_expr.pp⟩ meta def normal_expr.refl_conv (e : normal_expr) : tactic (normal_expr × expr) := do p ← mk_eq_refl e, return (e, p) theorem const_add_term {α} [add_comm_monoid α] (k n x a a') (h : k + a = a') : k + @term α _ n x a = term n x a' := by simp [h.symm, term]; ac_refl theorem const_add_termg {α} [add_comm_group α] (k n x a a') (h : k + a = a') : k + @termg α _ n x a = termg n x a' := by simp [h.symm, termg]; ac_refl theorem term_add_const {α} [add_comm_monoid α] (n x a k a') (h : a + k = a') : @term α _ n x a + k = term n x a' := by simp [h.symm, term, add_assoc] theorem term_add_constg {α} [add_comm_group α] (n x a k a') (h : a + k = a') : @termg α _ n x a + k = termg n x a' := by simp [h.symm, termg, add_assoc] theorem term_add_term {α} [add_comm_monoid α] (n₁ x a₁ n₂ a₂ n' a') (h₁ : n₁ + n₂ = n') (h₂ : a₁ + a₂ = a') : @term α _ n₁ x a₁ + @term α _ n₂ x a₂ = term n' x a' := by simp [h₁.symm, h₂.symm, term, add_monoid.add_smul]; ac_refl theorem term_add_termg {α} [add_comm_group α] (n₁ x a₁ n₂ a₂ n' a') (h₁ : n₁ + n₂ = n') (h₂ : a₁ + a₂ = a') : @termg α _ n₁ x a₁ + @termg α _ n₂ x a₂ = termg n' x a' := by simp [h₁.symm, h₂.symm, termg, add_gsmul]; ac_refl theorem zero_term {α} [add_comm_monoid α] (x a) : @term α _ 0 x a = a := by simp [term] theorem zero_termg {α} [add_comm_group α] (x a) : @termg α _ 0 x a = a := by simp [termg] meta def eval_add (c : cache) : normal_expr → normal_expr → tactic (normal_expr × expr) | (zero _) e₂ := do p ← mk_app ``zero_add [e₂], return (e₂, p) | e₁ (zero _) := do p ← mk_app ``add_zero [e₁], return (e₁, p) | he₁@(nterm e₁ n₁ x₁ a₁) he₂@(nterm e₂ n₂ x₂ a₂) := if expr.lex_lt x₁ x₂ then do (a', h) ← eval_add a₁ he₂, return (term' c n₁ x₁ a', c.iapp ``term_add_const [n₁.1, x₁, a₁, e₂, a', h]) else if x₁ ≠ x₂ then do (a', h) ← eval_add he₁ a₂, return (term' c n₂ x₂ a', c.iapp ``const_add_term [e₁, n₂.1, x₂, a₂, a', h]) else do (n', h₁) ← mk_app ``has_add.add [n₁.1, n₂.1] >>= norm_num.derive', (a', h₂) ← eval_add a₁ a₂, let k := n₁.2 + n₂.2, let p₁ := c.iapp ``term_add_term [n₁.1, x₁, a₁, n₂.1, a₂, n', a', h₁, h₂], if k = 0 then do p ← mk_eq_trans p₁ (c.iapp ``zero_term [x₁, a']), return (a', p) else return (term' c (n', k) x₁ a', p₁) theorem term_neg {α} [add_comm_group α] (n x a n' a') (h₁ : -n = n') (h₂ : -a = a') : -@termg α _ n x a = termg n' x a' := by simp [h₂.symm, h₁.symm, termg]; ac_refl meta def eval_neg (c : cache) : normal_expr → tactic (normal_expr × expr) | (zero e) := do p ← c.mk_app ``neg_zero ``add_group [], return (zero' c, p) | (nterm e n x a) := do (n', h₁) ← mk_app ``has_neg.neg [n.1] >>= norm_num.derive', (a', h₂) ← eval_neg a, return (term' c (n', -n.2) x a', c.app ``term_neg c.inst [n.1, x, a, n', a', h₁, h₂]) def smul {α} [add_comm_monoid α] (n : ℕ) (x : α) : α := add_monoid.smul n x def smulg {α} [add_comm_group α] (n : ℤ) (x : α) : α := gsmul n x theorem zero_smul {α} [add_comm_monoid α] (c) : smul c (0 : α) = 0 := by simp [smul] theorem zero_smulg {α} [add_comm_group α] (c) : smulg c (0 : α) = 0 := by simp [smulg] theorem term_smul {α} [add_comm_monoid α] (c n x a n' a') (h₁ : c * n = n') (h₂ : smul c a = a') : smul c (@term α _ n x a) = term n' x a' := by simp [h₂.symm, h₁.symm, term, smul, add_monoid.smul_add, add_monoid.mul_smul] theorem term_smulg {α} [add_comm_group α] (c n x a n' a') (h₁ : c * n = n') (h₂ : smulg c a = a') : smulg c (@termg α _ n x a) = termg n' x a' := by simp [h₂.symm, h₁.symm, termg, smulg, gsmul_add, gsmul_mul] meta def eval_smul (c : cache) (k : expr × ℤ) : normal_expr → tactic (normal_expr × expr) | (zero _) := return (zero' c, c.iapp ``zero_smul [k.1]) | (nterm e n x a) := do (n', h₁) ← mk_app ``has_mul.mul [k.1, n.1] >>= norm_num.derive', (a', h₂) ← eval_smul a, return (term' c (n', k.2 * n.2) x a', c.iapp ``term_smul [k.1, n.1, x, a, n', a', h₁, h₂]) theorem term_atom {α} [add_comm_monoid α] (x : α) : x = term 1 x 0 := by simp [term] theorem term_atomg {α} [add_comm_group α] (x : α) : x = termg 1 x 0 := by simp [termg] meta def eval_atom (c : cache) (e : expr) : tactic (normal_expr × expr) := do n1 ← c.int_to_expr 1, return (term' c (n1, 1) e (zero' c), c.iapp ``term_atom [e]) lemma unfold_sub {α} [add_group α] (a b c : α) (h : a + -b = c) : a - b = c := h theorem unfold_smul {α} [add_comm_monoid α] (n) (x y : α) (h : smul n x = y) : add_monoid.smul n x = y := h theorem unfold_smulg {α} [add_comm_group α] (n : ℕ) (x y : α) (h : smulg (int.of_nat n) x = y) : add_monoid.smul n x = y := h theorem unfold_gsmul {α} [add_comm_group α] (n : ℤ) (x y : α) (h : smulg n x = y) : gsmul n x = y := h lemma subst_into_smul {α} [add_comm_monoid α] (l r tl tr t) (prl : l = tl) (prr : r = tr) (prt : @smul α _ tl tr = t) : smul l r = t := by simp [prl, prr, prt] lemma subst_into_smulg {α} [add_comm_group α] (l r tl tr t) (prl : l = tl) (prr : r = tr) (prt : @smulg α _ tl tr = t) : smulg l r = t := by simp [prl, prr, prt] meta def eval (c : cache) : expr → tactic (normal_expr × expr) | `(%%e₁ + %%e₂) := do (e₁', p₁) ← eval e₁, (e₂', p₂) ← eval e₂, (e', p') ← eval_add c e₁' e₂', p ← c.mk_app ``norm_num.subst_into_add ``has_add [e₁, e₂, e₁', e₂', e', p₁, p₂, p'], return (e', p) | `(%%e₁ - %%e₂) := do e₂' ← mk_app ``has_neg.neg [e₂], e ← mk_app ``has_add.add [e₁, e₂'], (e', p) ← eval e, p' ← c.mk_app ``unfold_sub ``add_group [e₁, e₂, e', p], return (e', p') | `(- %%e) := do (e₁, p₁) ← eval e, (e₂, p₂) ← eval_neg c e₁, p ← c.mk_app ``norm_num.subst_into_neg ``has_neg [e, e₁, e₂, p₁, p₂], return (e₂, p) | `(add_monoid.smul %%e₁ %%e₂) := do n ← if c.is_group then mk_app ``int.of_nat [e₁] else return e₁, (e', p) ← eval $ c.iapp ``smul [n, e₂], return (e', c.iapp ``unfold_smul [e₁, e₂, e', p]) | `(gsmul %%e₁ %%e₂) := do guardb c.is_group, (e', p) ← eval $ c.iapp ``smul [e₁, e₂], return (e', c.app ``unfold_gsmul c.inst [e₁, e₂, e', p]) | `(smul %%e₁ %%e₂) := do guard (¬ c.is_group), (e₁', p₁) ← norm_num.derive e₁ <|> refl_conv e₁, n ← e₁'.to_nat, (e₂', p₂) ← eval e₂, (e', p) ← eval_smul c (e₁', n) e₂', return (e', c.iapp ``subst_into_smul [e₁, e₂, e₁', e₂', e', p₁, p₂, p]) | `(smulg %%e₁ %%e₂) := do guardb c.is_group, (e₁', p₁) ← norm_num.derive e₁ <|> refl_conv e₁, n ← e₁'.to_int, (e₂', p₂) ← eval e₂, (e', p) ← eval_smul c (e₁', n) e₂', return (e', c.iapp ``subst_into_smul [e₁, e₂, e₁', e₂', e', p₁, p₂, p]) | e := eval_atom c e meta def eval' (c : cache) (e : expr) : tactic (expr × expr) := do (e', p) ← eval c e, return (e', p) @[derive has_reflect] inductive normalize_mode | raw | term instance : inhabited normalize_mode := ⟨normalize_mode.term⟩ meta def normalize (mode := normalize_mode.term) (e : expr) : tactic (expr × expr) := do pow_lemma ← simp_lemmas.mk.add_simp ``pow_one, let lemmas := match mode with | normalize_mode.term := [``term.equations._eqn_1, ``termg.equations._eqn_1, ``add_zero, ``add_monoid.one_smul, ``one_gsmul] | _ := [] end, lemmas ← lemmas.mfoldl simp_lemmas.add_simp simp_lemmas.mk, (_, e', pr) ← ext_simplify_core () {} simp_lemmas.mk (λ _, failed) (λ _ _ _ _ e, do c ← mk_cache e, (new_e, pr) ← match mode with | normalize_mode.raw := eval' c | normalize_mode.term := trans_conv (eval' c) (simplify lemmas []) end e, guard (¬ new_e =ₐ e), return ((), new_e, some pr, ff)) (λ _ _ _ _ _, failed) `eq e, return (e', pr) end abel namespace interactive open interactive interactive.types lean.parser open tactic.abel local postfix `?`:9001 := optional /-- Tactic for solving equations in the language of *additive*, commutative monoids and groups. This version of `abel` fails if the target is not an equality that is provable by the axioms of commutative monoids/groups. -/ meta def abel1 : tactic unit := do `(%%e₁ = %%e₂) ← target, c ← mk_cache e₁, (e₁', p₁) ← eval c e₁, (e₂', p₂) ← eval c e₂, is_def_eq e₁' e₂', p ← mk_eq_symm p₂ >>= mk_eq_trans p₁, tactic.exact p meta def abel.mode : lean.parser abel.normalize_mode := with_desc "(raw|term)?" $ do mode ← ident?, match mode with | none := return abel.normalize_mode.term | some `term := return abel.normalize_mode.term | some `raw := return abel.normalize_mode.raw | _ := failed end /-- Evaluate expressions in the language of *additive*, commutative monoids and groups. It attempts to prove the goal outright if there is no `at` specifier and the target is an equality, but if this fails, it falls back to rewriting all monoid expressions into a normal form. If there is an `at` specifier, it rewrites the given target into a normal form. ```lean example {α : Type*} {a b : α} [add_comm_monoid α] : a + (b + a) = a + a + b := by abel example {α : Type*} {a b : α} [add_comm_group α] : (a + b) - ((b + a) + a) = -a := by abel example {α : Type*} {a b : α} [add_comm_group α] (hyp : a + a - a = b - b) : a = 0 := by { abel at hyp, exact hyp } ``` -/ meta def abel (SOP : parse abel.mode) (loc : parse location) : tactic unit := match loc with | interactive.loc.ns [none] := abel1 | _ := failed end <|> do ns ← loc.get_locals, tt ← tactic.replace_at (normalize SOP) ns loc.include_goal | fail "abel failed to simplify", when loc.include_goal $ try tactic.reflexivity add_tactic_doc { name := "abel", category := doc_category.tactic, decl_names := [`tactic.interactive.abel], tags := ["arithmetic", "decision procedure"] } end interactive end tactic
ec2a6e18641795a84840741dc243c147590ab05e
e9706a48d2f8c9c320a939f0e06d9d743b3fd7f9
/src/fib.lean
90b6dac6bc838ce48918d467cfab3c69efd4426e
[ "Apache-2.0" ]
permissive
bryangingechen/lean-fibonacci
59241eb05edb4492b1a325cf2d615a54df7de158
8ac73044b17ff0c5f6b50cab7ee10456d54dba87
refs/heads/master
1,636,788,695,940
1,636,444,154,000
1,636,444,154,000
198,952,656
1
1
NOASSERTION
1,636,444,155,000
1,564,119,249,000
Lean
UTF-8
Lean
false
false
5,025
lean
import data.list.range import data.list.join @[reducible] def fibonacci : ℕ → ℕ | 0 := 0 | 1 := 1 | (n+2) := fibonacci n + fibonacci (n+1) open nat list --- @[reducible] def fib_sum (n : ℕ) : ℕ := ((range n).map fibonacci).sum @[reducible] def fib_odd_sum (n : ℕ) : ℕ := ((range n).map (λ m, fibonacci (2*m + 1))).sum @[reducible] def fib_even_sum (n : ℕ) : ℕ := ((range n).map (λ m, fibonacci (2*m))).sum --- theorem fib_odd_sum_eq : ∀ (n : ℕ), fib_odd_sum n = fibonacci (2*n) | 0 := rfl | (n+1) := by rw [fib_odd_sum, sum_range_succ, ←fib_odd_sum, fib_odd_sum_eq, mul_add, mul_one, fibonacci] --- theorem fib_even_sum_eq : ∀ {n : ℕ} (h : n > 0), fib_even_sum n + 1 = fibonacci (2*n - 1) | 0 h := (gt_irrefl 0 h).elim | 1 _ := rfl | (n+2) _ := have H : fib_even_sum (n+1) + 1 = fibonacci (2*(n+1) - 1) := fib_even_sum_eq (succ_pos n), begin rw [fib_even_sum, sum_range_succ, ←fib_even_sum, add_right_comm, H, mul_add, mul_one, mul_add], change fibonacci (2*n + 1) + fibonacci (2*n + 1 + 1) = fibonacci (2*n + 1 + 2), rw [←fibonacci], end --- theorem fib_sum_eq : ∀ (n : ℕ), fib_sum n + 1 = fibonacci (n+1) | 0 := rfl | (n+1) := begin rw [fibonacci, ←fib_sum_eq n], simp [range_succ, fib_sum, add_left_comm, add_comm], end inductive bee : Type | queen : bee | worker : bee | drone : bee open bee list instance : has_repr bee := ⟨λ s, match s with | queen := "Q" | worker := "W" | drone := "D" end⟩ --- namespace bee def parents : bee → list bee | queen := [queen, drone] | worker := [queen, drone] | drone := [queen] def ancestors (b : bee) : ℕ → list bee | 0 := [b] | (n+1) := ((ancestors n).map parents).join --- def tree_json : bee → ℕ → string | b 0 := "{\"name\":\"" ++ repr b ++ "\"}" | b (n+1) := "{\"name\":\"" ++ repr b ++ "\",\"children\":[" ++ string.intercalate "," (b.parents.map (λ p, p.tree_json n)) ++ "]}" --- lemma drone_ancestors_concat : ∀ (n : ℕ), drone.ancestors (n+2) = drone.ancestors (n+1) ++ drone.ancestors n | 0 := rfl | (n+1) := begin change ((ancestors _ (n+2)).map _).join = _, conv { to_lhs, rw [drone_ancestors_concat n, map_append, join_append], }, refl, end --- theorem drone_ancestors_length_eq_fib_succ : ∀ (n : ℕ), (drone.ancestors n).length = fibonacci (n+1) | 0 := rfl | 1 := rfl | (n+2) := begin rw [drone_ancestors_concat, length_append, drone_ancestors_length_eq_fib_succ n, drone_ancestors_length_eq_fib_succ (n+1), add_comm], refl, end end bee --- inductive car : Type | rabbit : car | cadillac : car open car list nat instance : has_repr car := ⟨λ s, match s with | rabbit := "R" | cadillac := "C" end⟩ --- namespace car @[reducible] def size : car → ℕ | rabbit := 1 | cadillac := 2 @[reducible] def sum_size (cs : list car) : ℕ := (cs.map size).sum lemma sum_size_cons (c : car) (cs : list car) : sum_size (c :: cs) = sum_size cs + c.size := by simp only [sum_size, sum_cons, map, add_comm] --- @[reducible] def packings : ℕ → list (list car) | 0 := [[]] | 1 := [[rabbit]] | (n+2) := (packings (n+1)).map (cons rabbit) ++ (packings n).map (cons cadillac) --- theorem num_packings_eq_fib : ∀ (n : ℕ), (packings n).length = fibonacci (n+1) | 0 := rfl | 1 := rfl | (n+2) := begin simp [packings, fibonacci, add_left_comm, add_comm], rw [num_packings_eq_fib n, num_packings_eq_fib (n+1), add_left_comm, add_right_inj, fibonacci], end --- theorem packings_size : ∀ {n : ℕ} {cs : list car} (h : cs ∈ packings n), sum_size cs = n | 0 cs h := begin rw mem_singleton.1 h, refl, end | 1 cs h := begin rw mem_singleton.1 h, refl, end | (n+2) cs h := begin simp [packings] at h, rcases h with ⟨cs', h₁, h₂⟩ | ⟨cs', h₁, h₂⟩, all_goals { rw [←h₂, sum_size_cons, size, packings_size h₁], }, end --- lemma car_size_ne_zero (c : car) : size c ≠ 0 := by cases c; contradiction lemma sum_size_zero : ∀ {cs : list car} (h : sum_size cs = 0), cs = [] | [] _ := rfl | (c::cs) h := begin exfalso, rw [sum_size_cons, add_eq_zero_iff] at h, exact car_size_ne_zero c h.2, end --- lemma sum_size_one : ∀ {cs : list car} (h : sum_size cs = 1), cs = [rabbit] | [] h := by contradiction | (rabbit::cs) h := begin rw [sum_size_cons] at h, simp, exact sum_size_zero (succ.inj h), end | (cadillac::cs) h := begin rw [sum_size_cons] at h, have : sum_size cs + 1 = 0 := succ.inj h, contradiction, end --- theorem all_packings : ∀ {n : ℕ} {cs : list car} (h : sum_size cs = n), cs ∈ packings n | 0 cs h := by simp [packings, sum_size_zero h] | 1 cs h := by simp [packings, sum_size_one h] | (n+2) [] h := by contradiction | (n+2) (rabbit::cs) h := begin rw [sum_size_cons, add_left_inj 1] at h, simp [packings, all_packings, h], end | (n+2) (cadillac::cs) h := begin rw [sum_size_cons, add_left_inj 2] at h, simp [packings, all_packings, h], end end car
171f7f315b51f944b96ef4e64bc3d119af426c1b
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/algebra/ring.lean
debd9fff6db8d991bc62bd9650b9b9c374259285
[ "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
21,414
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 -/ import algebra.group /-! # Properties and homomorphisms of semirings and rings This file proves simple properties of semirings, rings and domains and their unit groups. It also defines homomorphisms of semirings and rings, both unbundled (e.g. `is_semiring_hom f`) and bundled (e.g. `ring_hom a β`, a.k.a. `α →+* β`). The unbundled ones are deprecated and the plan is to slowly remove them from mathlib. ## Main definitions semiring_hom, is_semiring_hom (deprecated), is_ring_hom (deprecated), nonzero_comm_semiring, nonzero_comm_ring, domain ## Notations →+* for bundled semiring homs (also use for ring 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 `ring_hom` -- the idea is that `semiring_hom` is used. The constructor for `ring_hom` needs a proof of `map_zero`, `map_one` and `map_add` as well as `map_mul`; a separate constructor `semiring_hom.mk'` will construct ring homs (i.e. semiring homs between additive commutative groups) from monoid homs given only a proof that addition is preserved. ## Tags is_ring_hom, is_semiring_hom, ring_hom, semiring, comm_semiring, ring, comm_ring, domain, integral_domain, nonzero_comm_semiring, nonzero_comm_ring, units -/ universes u v variable {α : Type u} section variable [semiring α] 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 variable (α) /-- Either zero and one are nonequal in a semiring, or the semiring is the zero ring. -/ lemma zero_ne_one_or_forall_eq_0 : (0 : α) ≠ 1 ∨ (∀a:α, a = 0) := by haveI := classical.dec; refine not_or_of_imp (λ h a, _); simpa using congr_arg ((*) a) h.symm /-- If zero equals one in a semiring, the semiring is the zero ring. -/ lemma eq_zero_of_zero_eq_one (h : (0 : α) = 1) : (∀a:α, a = 0) := (zero_ne_one_or_forall_eq_0 α).neg_resolve_left h /-- If zero equals one in a semiring, all elements of that semiring are equal. -/ theorem subsingleton_of_zero_eq_one (h : (0 : α) = 1) : subsingleton α := ⟨λa b, by rw [eq_zero_of_zero_eq_one α h a, eq_zero_of_zero_eq_one α h b]⟩ end 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] protected theorem coe_neg (u : units α) : (↑-u : α) = -u := 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 instance [semiring α] : semiring (with_zero α) := { left_distrib := λ a b c, begin cases a with a, {refl}, cases b with b; cases c with c; try {refl}, exact congr_arg some (left_distrib _ _ _) end, right_distrib := λ a b c, begin cases c with c, { change (a + b) * 0 = a * 0 + b * 0, simp }, cases a with a; cases b with b; try {refl}, exact congr_arg some (right_distrib _ _ _) end, ..with_zero.add_comm_monoid, ..with_zero.mul_zero_class, ..with_zero.monoid } attribute [refl] dvd_refl attribute [trans] dvd.trans /-- Predicate for semiring homomorphisms (deprecated -- use the bundled `semiring_hom` version). -/ class is_semiring_hom {α : Type u} {β : Type v} [semiring α] [semiring β] (f : α → β) : Prop := (map_zero : f 0 = 0) (map_one : f 1 = 1) (map_add : ∀ {x y}, f (x + y) = f x + f y) (map_mul : ∀ {x y}, f (x * y) = f x * f y) namespace is_semiring_hom variables {β : Type v} [semiring α] [semiring β] variables (f : α → β) [is_semiring_hom f] {x y : α} /-- The identity map is a semiring homomorphism. -/ instance id : is_semiring_hom (@id α) := by refine {..}; intros; refl /-- The composition of two semiring homomorphisms is a semiring homomorphism. -/ instance comp {γ} [semiring γ] (g : β → γ) [is_semiring_hom g] : is_semiring_hom (g ∘ f) := { map_zero := by simp [map_zero f]; exact map_zero g, map_one := by simp [map_one f]; exact map_one g, map_add := λ x y, by simp [map_add f]; rw map_add g; refl, map_mul := λ x y, by simp [map_mul f]; rw map_mul g; refl } /-- A semiring homomorphism is an additive monoid homomorphism. -/ instance : is_add_monoid_hom f := { ..‹is_semiring_hom f› } /-- A semiring homomorphism is a monoid homomorphism. -/ instance : is_monoid_hom f := { ..‹is_semiring_hom f› } end is_semiring_hom section variables [ring α] (a b c d e : α) /-- 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 ... ↔ a * e + c - b * e = d : iff.intro (λ h, begin simp [h] end) (λ h, begin simp [h.symm] end) ... ↔ (a - b) * e + c = d : begin simp [@sub_eq_add_neg α, @right_distrib α] 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_eq_add_neg α, @right_distrib α] end ... = d : begin rw h, simp [@add_sub_cancel α] end /-- If the product of two elements of a ring is nonzero, both elements are nonzero. -/ theorem ne_zero_and_ne_zero_of_mul_ne_zero {a b : α} (h : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 := begin split, { intro ha, apply h, simp [ha] }, { intro hb, apply h, simp [hb] } end end /-- Given an element a of a commutative semiring, there exists another element whose product with zero equals a iff a equals zero. -/ @[simp] lemma zero_dvd_iff [comm_semiring α] {a : α} : 0 ∣ a ↔ a = 0 := ⟨eq_zero_of_zero_dvd, λ h, by rw h⟩ section comm_ring variable [comm_ring α] /-- 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 {a b c : α} (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 {a b c : α} (h : a ∣ b) : a ∣ b + c ↔ a ∣ c := (dvd_add_iff_right h).symm end comm_ring /-- Predicate for ring homomorphisms (deprecated -- use the bundled `semiring_hom` version). -/ class is_ring_hom {α : Type u} {β : Type v} [ring α] [ring β] (f : α → β) : Prop := (map_one : f 1 = 1) (map_mul : ∀ {x y}, f (x * y) = f x * f y) (map_add : ∀ {x y}, f (x + y) = f x + f y) namespace is_ring_hom variables {β : Type v} [ring α] [ring β] /-- A map of rings that is a semiring homomorphism is also a ring homomorphism. -/ def of_semiring (f : α → β) [H : is_semiring_hom f] : is_ring_hom f := {..H} variables (f : α → β) [is_ring_hom f] {x y : α} /-- Ring homomorphisms map zero to zero. -/ lemma map_zero : f 0 = 0 := calc f 0 = f (0 + 0) - f 0 : by rw [map_add f]; simp ... = 0 : by simp /-- Ring homomorphisms preserve additive inverses. -/ lemma map_neg : f (-x) = -f x := calc f (-x) = f (-x + x) - f x : by rw [map_add f]; simp ... = -f x : by simp [map_zero f] /-- Ring homomorphisms preserve subtraction. -/ lemma map_sub : f (x - y) = f x - f y := by simp [map_add f, map_neg f] /-- The identity map is a ring homomorphism. -/ instance id : is_ring_hom (@id α) := by refine {..}; intros; refl /-- The composition of two ring homomorphisms is a ring homomorphism. -/ instance comp {γ} [ring γ] (g : β → γ) [is_ring_hom g] : is_ring_hom (g ∘ f) := { map_add := λ x y, by simp [map_add f]; rw map_add g; refl, map_mul := λ x y, by simp [map_mul f]; rw map_mul g; refl, map_one := by simp [map_one f]; exact map_one g } /-- A ring homomorphism is also a semiring homomorphism. -/ instance : is_semiring_hom f := { map_zero := map_zero f, ..‹is_ring_hom f› } instance : is_add_group_hom f := { } end is_ring_hom set_option old_structure_cmd true /-- Bundled semiring homomorphisms; use this for bundled ring homomorphisms too. -/ structure semiring_hom (α : Type*) (β : Type*) [semiring α] [semiring β] extends monoid_hom α β, add_monoid_hom α β infixr ` →+* `:25 := semiring_hom instance {α : Type*} {β : Type*} [semiring α] [semiring β] : has_coe_to_fun (α →+* β) := ⟨_, semiring_hom.to_fun⟩ namespace semiring_hom variables {β : Type v} [semiring α] [semiring β] variables (f : α →+* β) {x y : α} @[extensionality] theorem ext (f g : α →+* β) (h : (f : α → β) = g) : f = g := by cases f; cases g; cases h; refl /-- Semiring homomorphisms map zero to zero. -/ @[simp] lemma map_zero (f : α →+* β) : f 0 = 0 := f.map_zero' /-- Semiring homomorphisms map one to one. -/ @[simp] lemma map_one (f : α →+* β) : f 1 = 1 := f.map_one' /-- Semiring homomorphisms preserve addition. -/ @[simp] lemma map_add (f : α →+* β) (a b : α) : f (a + b) = f a + f b := f.map_add' a b /-- Semiring homomorphisms preserve multiplication. -/ @[simp] lemma map_mul (f : α →+* β) (a b : α) : f (a * b) = f a * f b := f.map_mul' a b instance {α : Type*} {β : Type*} [semiring α] [semiring β] (f : α →+* β) : is_semiring_hom f := { map_zero := f.map_zero, map_one := f.map_one, map_add := f.map_add, map_mul := f.map_mul } /-- A semiring homomorphism of rings is a ring homomorphism. -/ instance {α γ} [ring α] [ring γ] {g : α →+* γ} : is_ring_hom g := is_ring_hom.of_semiring g /-- The identity map from a semiring to itself. -/ def id (α : Type*) [semiring α] : α →+* α := by refine {to_fun := id, ..}; intros; refl /-- Composition of semiring homomorphisms is a semiring homomorphism. -/ def comp {γ} [semiring γ] (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} /-- Ring homomorphisms preserve additive inverse. -/ @[simp] theorem map_neg {α β} [ring α] [ring β] (f : α →+* β) (x : α) : f (-x) = -(f x) := eq_neg_of_add_eq_zero $ by rw [←f.map_add, neg_add_self, f.map_zero] /-- Ring homomorphisms preserve subtraction. -/ @[simp] theorem map_sub {α β} [ring α] [ring β] (f : α →+* β) (x y : α) : f (x - y) = (f x) - (f y) := by simp /-- Makes a ring homomomorphism from a proof that the monoid homomorphism preserves addition. -/ def mk' {γ} [ring γ] (f : α →* γ) (map_add : ∀ a b : α, f (a + b) = f a + f b) : α →+* γ := { to_fun := f, map_zero' := add_self_iff_eq_zero.1 $ by rw [←map_add, add_zero], map_one' := f.map_one, map_mul' := f.map_mul, map_add' := map_add } end semiring_hom /-- Predicate for commutative semirings in which zero does not equal one. -/ class nonzero_comm_semiring (α : Type*) extends comm_semiring α, zero_ne_one_class α /-- Predicate for commutative rings in which zero does not equal one. -/ class nonzero_comm_ring (α : Type*) extends comm_ring α, zero_ne_one_class α /-- A nonzero commutative ring is a nonzero commutative semiring. -/ instance nonzero_comm_ring.to_nonzero_comm_semiring {α : Type*} [I : nonzero_comm_ring α] : nonzero_comm_semiring α := { zero_ne_one := by convert zero_ne_one, ..show comm_semiring α, by apply_instance } /-- An integral domain is a nonzero commutative ring. -/ instance integral_domain.to_nonzero_comm_ring (α : Type*) [id : integral_domain α] : nonzero_comm_ring α := { ..id } /-- An element of the unit group of a nonzero commutative semiring represented as an element of the semiring is nonzero. -/ lemma units.coe_ne_zero [nonzero_comm_semiring α] (u : units α) : (u : α) ≠ 0 := λ h : u.1 = 0, by simpa [h, zero_ne_one] using u.3 /-- Makes a nonzero commutative ring from a commutative ring containing at least two distinct elements. -/ def nonzero_comm_ring.of_ne [comm_ring α] {x y : α} (h : x ≠ y) : nonzero_comm_ring α := { one := 1, zero := 0, zero_ne_one := λ h01, h $ by rw [← one_mul x, ← one_mul y, ← h01, zero_mul, zero_mul], ..show comm_ring α, by apply_instance } /-- Makes a nonzero commutative semiring from a commutative semiring containing at least two distinct elements. -/ def nonzero_comm_semiring.of_ne [comm_semiring α] {x y : α} (h : x ≠ y) : nonzero_comm_semiring α := { one := 1, zero := 0, zero_ne_one := λ h01, h $ by rw [← one_mul x, ← one_mul y, ← h01, zero_mul, zero_mul], ..show comm_semiring α, by apply_instance } /-- this is needed for compatibility between Lean 3.4.2 and Lean 3.5.0c -/ def has_div_of_division_ring [division_ring α] : has_div α := division_ring_has_div /-- 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. -/ class domain (α : Type u) extends ring α, no_zero_divisors α, zero_ne_one_class α section domain variable [domain α] /-- Simplification theorems for the definition of a domain. -/ @[simp] theorem mul_eq_zero {a b : α} : a * b = 0 ↔ a = 0 ∨ b = 0 := ⟨eq_zero_or_eq_zero_of_mul_eq_zero, λo, or.elim o (λh, by rw h; apply zero_mul) (λh, by rw h; apply mul_zero)⟩ @[simp] theorem zero_eq_mul {a b : α} : 0 = a * b ↔ a = 0 ∨ b = 0 := by rw [eq_comm, mul_eq_zero] /-- The product of two nonzero elements of a domain is nonzero. -/ theorem mul_ne_zero' {a b : α} (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a * b ≠ 0 := λ h, or.elim (eq_zero_or_eq_zero_of_mul_eq_zero h) h₁ h₂ /-- Right multiplication by a nonzero element in a domain is injective. -/ theorem domain.mul_right_inj {a b c : α} (ha : a ≠ 0) : b * a = c * a ↔ b = c := by rw [← sub_eq_zero, ← mul_sub_right_distrib, mul_eq_zero]; simp [ha]; exact sub_eq_zero /-- Left multiplication by a nonzero element in a domain is injective. -/ theorem domain.mul_left_inj {a b c : α} (ha : a ≠ 0) : a * b = a * c ↔ b = c := by rw [← sub_eq_zero, ← mul_sub_left_distrib, mul_eq_zero]; simp [ha]; exact sub_eq_zero /-- An element of a domain fixed by right multiplication by an element other than one must be zero. -/ theorem eq_zero_of_mul_eq_self_right' {a b : α} (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 := by apply (mul_eq_zero.1 _).resolve_right (sub_ne_zero.2 h₁); rw [mul_sub_left_distrib, mul_one, sub_eq_zero, h₂] /-- An element of a domain fixed by left multiplication by an element other than one must be zero. -/ theorem eq_zero_of_mul_eq_self_left' {a b : α} (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 := by apply (mul_eq_zero.1 _).resolve_left (sub_ne_zero.2 h₁); rw [mul_sub_right_distrib, one_mul, sub_eq_zero, h₂] /-- For elements a, b of a domain, if a*b is nonzero, so is b*a. -/ theorem mul_ne_zero_comm' {a b : α} (h : a * b ≠ 0) : b * a ≠ 0 := mul_ne_zero' (ne_zero_of_mul_ne_zero_left h) (ne_zero_of_mul_ne_zero_right h) end domain /- integral domains -/ section variables [s : integral_domain α] (a b c d e : α) include s /-- An integral domain is a domain. -/ instance integral_domain.to_domain : domain α := {..s} /-- Right multiplcation by a nonzero element of an integral domain is injective. -/ theorem eq_of_mul_eq_mul_right_of_ne_zero {a b c : α} (ha : a ≠ 0) (h : b * a = c * a) : b = c := have b * a - c * a = 0, by simp [h], have (b - c) * a = 0, by rw [mul_sub_right_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_right ha, eq_of_sub_eq_zero this /-- Left multiplication by a nonzero element of an integral domain is injective. -/ theorem eq_of_mul_eq_mul_left_of_ne_zero {a b c : α} (ha : a ≠ 0) (h : a * b = a * c) : b = c := have a * b - a * c = 0, by simp [h], have a * (b - c) = 0, by rw [mul_sub_left_distrib, this], have b - c = 0, from (eq_zero_or_eq_zero_of_mul_eq_zero this).resolve_left ha, eq_of_sub_eq_zero this /-- Given two elements b, c of an integral domain and a nonzero element a, a*b divides a*c iff b divides c. -/ theorem mul_dvd_mul_iff_left {a b c : α} (ha : a ≠ 0) : a * b ∣ a * c ↔ b ∣ c := exists_congr $ λ d, by rw [mul_assoc, domain.mul_left_inj ha] /-- Given two elements a, b of an integral domain and a nonzero element c, a*c divides b*c iff a divides b. -/ theorem mul_dvd_mul_iff_right {a b c : α} (hc : c ≠ 0) : a * c ∣ b * c ↔ a ∣ b := exists_congr $ λ d, by rw [mul_right_comm, domain.mul_right_inj hc] /-- 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 conv {to_lhs, rw [inv_eq_iff_mul_eq_one, ← mul_one (1 : units α), units.ext_iff, units.coe_mul, units.coe_mul, mul_self_eq_mul_self_iff, ← units.ext_iff, ← units.coe_neg, ← units.ext_iff] } end /- units in various rings -/ namespace units section comm_semiring variables [comm_semiring α] (a b : α) (u : units α) /-- Elements of the unit group of a commutative semiring represented as elements of the semiring divide any element of the semiring. -/ @[simp] lemma coe_dvd : ↑u ∣ a := ⟨↑u⁻¹ * a, by simp⟩ /-- In a commutative semiring, an element a divides an element b iff a divides all associates of b. -/ @[simp] lemma dvd_coe_mul : a ∣ b * u ↔ a ∣ b := iff.intro (assume ⟨c, eq⟩, ⟨c * ↑u⁻¹, by rw [← mul_assoc, ← eq, units.mul_inv_cancel_right]⟩) (assume ⟨c, eq⟩, eq.symm ▸ dvd_mul_of_dvd_left (dvd_mul_right _ _) _) /-- An element of a commutative semiring divides a unit iff the element divides one. -/ @[simp] lemma dvd_coe : a ∣ ↑u ↔ a ∣ 1 := suffices a ∣ 1 * ↑u ↔ a ∣ 1, by simpa, dvd_coe_mul _ _ _ /-- In a commutative semiring, an element a divides an element b iff all associates of a divide b.-/ @[simp] lemma coe_mul_dvd : a * u ∣ b ↔ a ∣ b := iff.intro (assume ⟨c, eq⟩, ⟨c * ↑u, eq.symm ▸ by ac_refl⟩) (assume h, suffices a * ↑u ∣ b * 1, by simpa, mul_dvd_mul h (coe_dvd _ _)) end comm_semiring section domain variables [domain α] /-- Every unit in a domain is nonzero. -/ @[simp] theorem ne_zero : ∀(u : units α), (↑u : α) ≠ 0 | ⟨u, v, (huv : 0 * v = 1), hvu⟩ rfl := by simpa using huv end domain end units
f3012f6bbdd449e80e02d9f5c39116fcf656cddd
8034095e1be60c0b8f6559c39220bd537d1f9933
/lambda/default.lean
59256944b66734f852293ce45924b3f9e67f27f2
[]
no_license
teodorov/lambda
40c573e2dd268824641702d9f94cf61e019ae6c5
4dc4d595dd0ee20c59913ef0171fd33eb0d637a1
refs/heads/master
1,585,318,070,303
1,530,364,515,000
1,530,364,515,000
146,645,753
1
0
null
1,535,569,435,000
1,535,569,434,000
null
UTF-8
Lean
false
false
5,306
lean
import lambda.parsing lambda.types lambda.unicode import system.io data.buffer.parser open parsing types parser def mk_env (env : list (string × term)) (t : term) : term := match list.unzip env with | (names, terms) := multi_app (multi_lam names t) terms end def add_to_env (env : list (string × term)) : string × term → sum string (list (string × term)) | (name, t) := if name ∈ env.unzip.fst then sum.inl $ sformat! "error: term “{name}” is already defined" else sum.inr $ env ++ pure (name, t) namespace io.error def avoid_error {α : Type} (m : io α) : io.error → io α | (io.error.other s) := (io.put_str_ln s) >> m | (io.error.sys n) := (io.put_str_ln $ sformat! "System error #{n}") >> m end io.error def help : string := " :help print this summary or command-specific help :quit exit the interpreter :env show variables in the scope :show_depth show current recursion depth :depth [nat] set recursion depth :show_import_depth show current import depth :import_depth [nat] set import depth :clear_env clear environment :load [filename] load file “filename” let name := body creates a new variable “name” with value “body”" structure repl_configuration := (env : list (string × term)) (recursion_depth : nat) (import_depth : nat) def read_from_file : nat → repl_configuration → string → io repl_configuration | 0 conf _ := pure conf | (nat.succ n) conf filename := do filehandle ← io.mk_file_handle filename io.mode.read, new_conf ← io.iterate conf (λ (conf : repl_configuration), do eof ← io.fs.is_eof filehandle, if eof then pure none else do line ← (flip option.get_or_else "") <$> unicode.utf8_to_string <$> io.fs.get_line filehandle, let file_eval := eval conf.recursion_depth ∘ mk_env conf.env, match run_string Command line with | (sum.inr $ repl_command.term t) := do let (evaluated, info) := file_eval t, io.put_str_ln $ sformat! "{line} ⇒ {evaluated} ({info})", pure conf | (sum.inr $ repl_command.bind name t) := match add_to_env conf.env (name, (file_eval t).1) with | sum.inr new_env := pure $ some { conf with env := new_env } | sum.inl error_msg := io.fail error_msg end | (sum.inr $ repl_command.load filename) := some <$> (read_from_file n conf filename) | (sum.inl er) := do io.put_str_ln er, pure none | _ := pure $ some conf end), io.fs.close filehandle, pure new_conf def loop : repl_configuration → io (option repl_configuration) | conf := let repl_eval := eval conf.recursion_depth ∘ mk_env conf.env in do io.put_str "λ> ", line ← io.get_line, match run_string Command line with | (sum.inr repl_command.quit) := pure none | (sum.inr repl_command.help) := io.put_str_ln help >> pure conf | (sum.inr repl_command.env) := do list.foldl (>>) (pure ()) $ list.map (λ (var : string × term), io.put_str_ln $ sformat! "{var.1} := {var.2}") conf.env, pure conf | (sum.inr repl_command.clear_env) := pure $ some { conf with env := [] } | (sum.inr $ repl_command.load filename) := some <$> read_from_file conf.import_depth conf filename | (sum.inr $ repl_command.depth depth) := pure $ some { conf with recursion_depth := depth } | (sum.inr $ repl_command.import_depth depth) := pure $ some { conf with import_depth := depth } | (sum.inr repl_command.show_depth) := do io.put_str_ln $ to_string conf.recursion_depth, pure conf | (sum.inr repl_command.show_import_depth) := do io.put_str_ln $ to_string conf.import_depth, pure conf | (sum.inr $ repl_command.bind name t) := match add_to_env conf.env (name, (repl_eval t).1) with | sum.inr new_env := pure $ some { conf with env := new_env } | sum.inl error_msg := io.put_str_ln error_msg >> pure (some conf) end | (sum.inr $ repl_command.term t) := let res := repl_eval t in do io.put_str_ln $ sformat! "{res.1}\n-- {res.2}", pure conf | (sum.inr repl_command.nothing) := pure conf | (sum.inl er) := do io.put_str_ln er, pure conf end def basic_env : list (string × term) := [("I", term.lam "x" (term.var "x")), ("K", multi_lam ["x", "y"] (term.var "x")), ("S", multi_lam ["f", "g", "x"] (term.app (term.app (term.var "f") (term.var "x")) (term.app (term.var "g") (term.var "x"))))] def initial_conf : repl_configuration := { import_depth := 1000, recursion_depth := 1000, env := basic_env } def load_from_files (files : list string) : io repl_configuration := list.foldl (λ (c : io repl_configuration) (filename : string), do conf ← c, io.put_str_ln $ sformat! "Loading file “{filename}”.", read_from_file conf.import_depth conf filename) (pure initial_conf) files def main : io unit := do args ← io.cmdline_args, conf ← load_from_files args, io.put_str_ln "Type “:help” for help.", io.iterate conf (λ (c : repl_configuration), io.catch (loop c) (io.error.avoid_error $ pure c)) >> pure ()
cdbbf694cef1477f2b193b347deef31a68b1f58e
c777c32c8e484e195053731103c5e52af26a25d1
/src/measure_theory/measure/vector_measure.lean
f29742363b51f02dff498463bd075ab6944ed6d4
[ "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
50,119
lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import measure_theory.measure.measure_space import analysis.complex.basic /-! # Vector valued measures This file defines vector valued measures, which are σ-additive functions from a set to a add monoid `M` such that it maps the empty set and non-measurable sets to zero. In the case that `M = ℝ`, we called the vector measure a signed measure and write `signed_measure α`. Similarly, when `M = ℂ`, we call the measure a complex measure and write `complex_measure α`. ## Main definitions * `measure_theory.vector_measure` is a vector valued, σ-additive function that maps the empty and non-measurable set to zero. * `measure_theory.vector_measure.map` is the pushforward of a vector measure along a function. * `measure_theory.vector_measure.restrict` is the restriction of a vector measure on some set. ## Notation * `v ≤[i] w` means that the vector measure `v` restricted on the set `i` is less than or equal to the vector measure `w` restricted on `i`, i.e. `v.restrict i ≤ w.restrict i`. ## Implementation notes We require all non-measurable sets to be mapped to zero in order for the extensionality lemma to only compare the underlying functions for measurable sets. We use `has_sum` instead of `tsum` in the definition of vector measures in comparison to `measure` since this provides summablity. ## Tags vector measure, signed measure, complex measure -/ noncomputable theory open_locale classical big_operators nnreal ennreal measure_theory namespace measure_theory variables {α β : Type*} {m : measurable_space α} /-- A vector measure on a measurable space `α` is a σ-additive `M`-valued function (for some `M` an add monoid) such that the empty set and non-measurable sets are mapped to zero. -/ structure vector_measure (α : Type*) [measurable_space α] (M : Type*) [add_comm_monoid M] [topological_space M] := (measure_of' : set α → M) (empty' : measure_of' ∅ = 0) (not_measurable' ⦃i : set α⦄ : ¬ measurable_set i → measure_of' i = 0) (m_Union' ⦃f : ℕ → set α⦄ : (∀ i, measurable_set (f i)) → pairwise (disjoint on f) → has_sum (λ i, measure_of' (f i)) (measure_of' (⋃ i, f i))) /-- A `signed_measure` is a `ℝ`-vector measure. -/ abbreviation signed_measure (α : Type*) [measurable_space α] := vector_measure α ℝ /-- A `complex_measure` is a `ℂ`-vector_measure. -/ abbreviation complex_measure (α : Type*) [measurable_space α] := vector_measure α ℂ open set measure_theory namespace vector_measure section variables {M : Type*} [add_comm_monoid M] [topological_space M] include m instance : has_coe_to_fun (vector_measure α M) (λ _, set α → M) := ⟨vector_measure.measure_of'⟩ initialize_simps_projections vector_measure (measure_of' → apply) @[simp] lemma measure_of_eq_coe (v : vector_measure α M) : v.measure_of' = v := rfl @[simp] lemma empty (v : vector_measure α M) : v ∅ = 0 := v.empty' lemma not_measurable (v : vector_measure α M) {i : set α} (hi : ¬ measurable_set i) : v i = 0 := v.not_measurable' hi lemma m_Union (v : vector_measure α M) {f : ℕ → set α} (hf₁ : ∀ i, measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) : has_sum (λ i, v (f i)) (v (⋃ i, f i)) := v.m_Union' hf₁ hf₂ lemma of_disjoint_Union_nat [t2_space M] (v : vector_measure α M) {f : ℕ → set α} (hf₁ : ∀ i, measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) : v (⋃ i, f i) = ∑' i, v (f i) := (v.m_Union hf₁ hf₂).tsum_eq.symm lemma coe_injective : @function.injective (vector_measure α M) (set α → M) coe_fn := λ v w h, by { cases v, cases w, congr' } lemma ext_iff' (v w : vector_measure α M) : v = w ↔ ∀ i : set α, v i = w i := by rw [← coe_injective.eq_iff, function.funext_iff] lemma ext_iff (v w : vector_measure α M) : v = w ↔ ∀ i : set α, measurable_set i → v i = w i := begin split, { rintro rfl _ _, refl }, { rw ext_iff', intros h i, by_cases hi : measurable_set i, { exact h i hi }, { simp_rw [not_measurable _ hi] } } end @[ext] lemma ext {s t : vector_measure α M} (h : ∀ i : set α, measurable_set i → s i = t i) : s = t := (ext_iff s t).2 h variables [t2_space M] {v : vector_measure α M} {f : ℕ → set α} lemma has_sum_of_disjoint_Union [countable β] {f : β → set α} (hf₁ : ∀ i, measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) : has_sum (λ i, v (f i)) (v (⋃ i, f i)) := begin casesI nonempty_encodable β, set g := λ i : ℕ, ⋃ (b : β) (H : b ∈ encodable.decode₂ β i), f b with hg, have hg₁ : ∀ i, measurable_set (g i), { exact λ _, measurable_set.Union (λ b, measurable_set.Union $ λ _, hf₁ b) }, have hg₂ : pairwise (disjoint on g), { exact encodable.Union_decode₂_disjoint_on hf₂ }, have := v.of_disjoint_Union_nat hg₁ hg₂, rw [hg, encodable.Union_decode₂] at this, have hg₃ : (λ (i : β), v (f i)) = (λ i, v (g (encodable.encode i))), { ext, rw hg, simp only, congr, ext y, simp only [exists_prop, mem_Union, option.mem_def], split, { intro hy, refine ⟨x, (encodable.decode₂_is_partial_inv _ _).2 rfl, hy⟩ }, { rintro ⟨b, hb₁, hb₂⟩, rw (encodable.decode₂_is_partial_inv _ _) at hb₁, rwa ← encodable.encode_injective hb₁ } }, rw [summable.has_sum_iff, this, ← tsum_Union_decode₂], { exact v.empty }, { rw hg₃, change summable ((λ i, v (g i)) ∘ encodable.encode), rw function.injective.summable_iff encodable.encode_injective, { exact (v.m_Union hg₁ hg₂).summable }, { intros x hx, convert v.empty, simp only [Union_eq_empty, option.mem_def, not_exists, mem_range] at ⊢ hx, intros i hi, exact false.elim ((hx i) ((encodable.decode₂_is_partial_inv _ _).1 hi)) } } end lemma of_disjoint_Union [countable β] {f : β → set α} (hf₁ : ∀ i, measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) : v (⋃ i, f i) = ∑' i, v (f i) := (has_sum_of_disjoint_Union hf₁ hf₂).tsum_eq.symm lemma of_union {A B : set α} (h : disjoint A B) (hA : measurable_set A) (hB : measurable_set B) : v (A ∪ B) = v A + v B := begin rw [union_eq_Union, of_disjoint_Union, tsum_fintype, fintype.sum_bool, cond, cond], exacts [λ b, bool.cases_on b hB hA, pairwise_disjoint_on_bool.2 h] end lemma of_add_of_diff {A B : set α} (hA : measurable_set A) (hB : measurable_set B) (h : A ⊆ B) : v A + v (B \ A) = v B := begin rw [← of_union disjoint_sdiff_right hA (hB.diff hA), union_diff_cancel h], apply_instance, end lemma of_diff {M : Type*} [add_comm_group M] [topological_space M] [t2_space M] {v : vector_measure α M} {A B : set α} (hA : measurable_set A) (hB : measurable_set B) (h : A ⊆ B) : v (B \ A) = v B - (v A) := begin rw [← of_add_of_diff hA hB h, add_sub_cancel'], apply_instance, end lemma of_diff_of_diff_eq_zero {A B : set α} (hA : measurable_set A) (hB : measurable_set B) (h' : v (B \ A) = 0) : v (A \ B) + v B = v A := begin symmetry, calc v A = v (A \ B ∪ A ∩ B) : by simp only [set.diff_union_inter] ... = v (A \ B) + v (A ∩ B) : by { rw of_union, { rw disjoint.comm, exact set.disjoint_of_subset_left (A.inter_subset_right B) disjoint_sdiff_self_right }, { exact hA.diff hB }, { exact hA.inter hB } } ... = v (A \ B) + v (A ∩ B ∪ B \ A) : by { rw [of_union, h', add_zero], { exact set.disjoint_of_subset_left (A.inter_subset_left B) disjoint_sdiff_self_right }, { exact hA.inter hB }, { exact hB.diff hA } } ... = v (A \ B) + v B : by { rw [set.union_comm, set.inter_comm, set.diff_union_inter] } end lemma of_Union_nonneg {M : Type*} [topological_space M] [ordered_add_comm_monoid M] [order_closed_topology M] {v : vector_measure α M} (hf₁ : ∀ i, measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) (hf₃ : ∀ i, 0 ≤ v (f i)) : 0 ≤ v (⋃ i, f i) := (v.of_disjoint_Union_nat hf₁ hf₂).symm ▸ tsum_nonneg hf₃ lemma of_Union_nonpos {M : Type*} [topological_space M] [ordered_add_comm_monoid M] [order_closed_topology M] {v : vector_measure α M} (hf₁ : ∀ i, measurable_set (f i)) (hf₂ : pairwise (disjoint on f)) (hf₃ : ∀ i, v (f i) ≤ 0) : v (⋃ i, f i) ≤ 0 := (v.of_disjoint_Union_nat hf₁ hf₂).symm ▸ tsum_nonpos hf₃ lemma of_nonneg_disjoint_union_eq_zero {s : signed_measure α} {A B : set α} (h : disjoint A B) (hA₁ : measurable_set A) (hB₁ : measurable_set B) (hA₂ : 0 ≤ s A) (hB₂ : 0 ≤ s B) (hAB : s (A ∪ B) = 0) : s A = 0 := begin rw of_union h hA₁ hB₁ at hAB, linarith, apply_instance, end lemma of_nonpos_disjoint_union_eq_zero {s : signed_measure α} {A B : set α} (h : disjoint A B) (hA₁ : measurable_set A) (hB₁ : measurable_set B) (hA₂ : s A ≤ 0) (hB₂ : s B ≤ 0) (hAB : s (A ∪ B) = 0) : s A = 0 := begin rw of_union h hA₁ hB₁ at hAB, linarith, apply_instance, end end section has_smul variables {M : Type*} [add_comm_monoid M] [topological_space M] variables {R : Type*} [semiring R] [distrib_mul_action R M] [has_continuous_const_smul R M] include m /-- Given a real number `r` and a signed measure `s`, `smul r s` is the signed measure corresponding to the function `r • s`. -/ def smul (r : R) (v : vector_measure α M) : vector_measure α M := { measure_of' := r • v, empty' := by rw [pi.smul_apply, empty, smul_zero], not_measurable' := λ _ hi, by rw [pi.smul_apply, v.not_measurable hi, smul_zero], m_Union' := λ _ hf₁ hf₂, has_sum.const_smul _ (v.m_Union hf₁ hf₂) } instance : has_smul R (vector_measure α M) := ⟨smul⟩ @[simp] lemma coe_smul (r : R) (v : vector_measure α M) : ⇑(r • v) = r • v := rfl lemma smul_apply (r : R) (v : vector_measure α M) (i : set α) : (r • v) i = r • v i := rfl end has_smul section add_comm_monoid variables {M : Type*} [add_comm_monoid M] [topological_space M] include m instance : has_zero (vector_measure α M) := ⟨⟨0, rfl, λ _ _, rfl, λ _ _ _, has_sum_zero⟩⟩ instance : inhabited (vector_measure α M) := ⟨0⟩ @[simp] lemma coe_zero : ⇑(0 : vector_measure α M) = 0 := rfl lemma zero_apply (i : set α) : (0 : vector_measure α M) i = 0 := rfl variables [has_continuous_add M] /-- The sum of two vector measure is a vector measure. -/ def add (v w : vector_measure α M) : vector_measure α M := { measure_of' := v + w, empty' := by simp, not_measurable' := λ _ hi, by simp [v.not_measurable hi, w.not_measurable hi], m_Union' := λ f hf₁ hf₂, has_sum.add (v.m_Union hf₁ hf₂) (w.m_Union hf₁ hf₂) } instance : has_add (vector_measure α M) := ⟨add⟩ @[simp] lemma coe_add (v w : vector_measure α M) : ⇑(v + w) = v + w := rfl lemma add_apply (v w : vector_measure α M) (i : set α) : (v + w) i = v i + w i := rfl instance : add_comm_monoid (vector_measure α M) := function.injective.add_comm_monoid _ coe_injective coe_zero coe_add (λ _ _, coe_smul _ _) /-- `coe_fn` is an `add_monoid_hom`. -/ @[simps] def coe_fn_add_monoid_hom : vector_measure α M →+ (set α → M) := { to_fun := coe_fn, map_zero' := coe_zero, map_add' := coe_add } end add_comm_monoid section add_comm_group variables {M : Type*} [add_comm_group M] [topological_space M] [topological_add_group M] include m /-- The negative of a vector measure is a vector measure. -/ def neg (v : vector_measure α M) : vector_measure α M := { measure_of' := -v, empty' := by simp, not_measurable' := λ _ hi, by simp [v.not_measurable hi], m_Union' := λ f hf₁ hf₂, has_sum.neg $ v.m_Union hf₁ hf₂ } instance : has_neg (vector_measure α M) := ⟨neg⟩ @[simp] lemma coe_neg (v : vector_measure α M) : ⇑(-v) = - v := rfl lemma neg_apply (v : vector_measure α M) (i : set α) :(-v) i = - v i := rfl /-- The difference of two vector measure is a vector measure. -/ def sub (v w : vector_measure α M) : vector_measure α M := { measure_of' := v - w, empty' := by simp, not_measurable' := λ _ hi, by simp [v.not_measurable hi, w.not_measurable hi], m_Union' := λ f hf₁ hf₂, has_sum.sub (v.m_Union hf₁ hf₂) (w.m_Union hf₁ hf₂) } instance : has_sub (vector_measure α M) := ⟨sub⟩ @[simp] lemma coe_sub (v w : vector_measure α M) : ⇑(v - w) = v - w := rfl lemma sub_apply (v w : vector_measure α M) (i : set α) : (v - w) i = v i - w i := rfl instance : add_comm_group (vector_measure α M) := function.injective.add_comm_group _ coe_injective coe_zero coe_add coe_neg coe_sub (λ _ _, coe_smul _ _) (λ _ _, coe_smul _ _) end add_comm_group section distrib_mul_action variables {M : Type*} [add_comm_monoid M] [topological_space M] variables {R : Type*} [semiring R] [distrib_mul_action R M] [has_continuous_const_smul R M] include m instance [has_continuous_add M] : distrib_mul_action R (vector_measure α M) := function.injective.distrib_mul_action coe_fn_add_monoid_hom coe_injective coe_smul end distrib_mul_action section module variables {M : Type*} [add_comm_monoid M] [topological_space M] variables {R : Type*} [semiring R] [module R M] [has_continuous_const_smul R M] include m instance [has_continuous_add M] : module R (vector_measure α M) := function.injective.module R coe_fn_add_monoid_hom coe_injective coe_smul end module end vector_measure namespace measure include m /-- A finite measure coerced into a real function is a signed measure. -/ @[simps] def to_signed_measure (μ : measure α) [hμ : is_finite_measure μ] : signed_measure α := { measure_of' := λ i : set α, if measurable_set i then (μ.measure_of i).to_real else 0, empty' := by simp [μ.empty], not_measurable' := λ _ hi, if_neg hi, m_Union' := begin intros _ hf₁ hf₂, rw [μ.m_Union hf₁ hf₂, ennreal.tsum_to_real_eq, if_pos (measurable_set.Union hf₁), summable.has_sum_iff], { congr, ext n, rw if_pos (hf₁ n) }, { refine @summable_of_nonneg_of_le _ (ennreal.to_real ∘ μ ∘ f) _ _ _ _, { intro, split_ifs, exacts [ennreal.to_real_nonneg, le_rfl] }, { intro, split_ifs, exacts [le_rfl, ennreal.to_real_nonneg] }, exact summable_measure_to_real hf₁ hf₂ }, { intros a ha, apply ne_of_lt hμ.measure_univ_lt_top, rw [eq_top_iff, ← ha, outer_measure.measure_of_eq_coe, coe_to_outer_measure], exact measure_mono (set.subset_univ _) } end } lemma to_signed_measure_apply_measurable {μ : measure α} [is_finite_measure μ] {i : set α} (hi : measurable_set i) : μ.to_signed_measure i = (μ i).to_real := if_pos hi -- Without this lemma, `singular_part_neg` in `measure_theory.decomposition.lebesgue` is -- extremely slow lemma to_signed_measure_congr {μ ν : measure α} [is_finite_measure μ] [is_finite_measure ν] (h : μ = ν) : μ.to_signed_measure = ν.to_signed_measure := by { congr, exact h } lemma to_signed_measure_eq_to_signed_measure_iff {μ ν : measure α} [is_finite_measure μ] [is_finite_measure ν] : μ.to_signed_measure = ν.to_signed_measure ↔ μ = ν := begin refine ⟨λ h, _, λ h, _⟩, { ext1 i hi, have : μ.to_signed_measure i = ν.to_signed_measure i, { rw h }, rwa [to_signed_measure_apply_measurable hi, to_signed_measure_apply_measurable hi, ennreal.to_real_eq_to_real] at this; { exact measure_ne_top _ _ } }, { congr, assumption } end @[simp] lemma to_signed_measure_zero : (0 : measure α).to_signed_measure = 0 := by { ext i hi, simp } @[simp] lemma to_signed_measure_add (μ ν : measure α) [is_finite_measure μ] [is_finite_measure ν] : (μ + ν).to_signed_measure = μ.to_signed_measure + ν.to_signed_measure := begin ext i hi, rw [to_signed_measure_apply_measurable hi, add_apply, ennreal.to_real_add (ne_of_lt (measure_lt_top _ _ )) (ne_of_lt (measure_lt_top _ _)), vector_measure.add_apply, to_signed_measure_apply_measurable hi, to_signed_measure_apply_measurable hi], all_goals { apply_instance } end @[simp] lemma to_signed_measure_smul (μ : measure α) [is_finite_measure μ] (r : ℝ≥0) : (r • μ).to_signed_measure = r • μ.to_signed_measure := begin ext i hi, rw [to_signed_measure_apply_measurable hi, vector_measure.smul_apply, to_signed_measure_apply_measurable hi, coe_smul, pi.smul_apply, ennreal.to_real_smul], end /-- A measure is a vector measure over `ℝ≥0∞`. -/ @[simps] def to_ennreal_vector_measure (μ : measure α) : vector_measure α ℝ≥0∞ := { measure_of' := λ i : set α, if measurable_set i then μ i else 0, empty' := by simp [μ.empty], not_measurable' := λ _ hi, if_neg hi, m_Union' := λ _ hf₁ hf₂, begin rw summable.has_sum_iff ennreal.summable, { rw [if_pos (measurable_set.Union hf₁), measure_theory.measure_Union hf₂ hf₁], exact tsum_congr (λ n, if_pos (hf₁ n)) }, end } lemma to_ennreal_vector_measure_apply_measurable {μ : measure α} {i : set α} (hi : measurable_set i) : μ.to_ennreal_vector_measure i = μ i := if_pos hi @[simp] lemma to_ennreal_vector_measure_zero : (0 : measure α).to_ennreal_vector_measure = 0 := by { ext i hi, simp } @[simp] lemma to_ennreal_vector_measure_add (μ ν : measure α) : (μ + ν).to_ennreal_vector_measure = μ.to_ennreal_vector_measure + ν.to_ennreal_vector_measure := begin refine measure_theory.vector_measure.ext (λ i hi, _), rw [to_ennreal_vector_measure_apply_measurable hi, add_apply, vector_measure.add_apply, to_ennreal_vector_measure_apply_measurable hi, to_ennreal_vector_measure_apply_measurable hi] end lemma to_signed_measure_sub_apply {μ ν : measure α} [is_finite_measure μ] [is_finite_measure ν] {i : set α} (hi : measurable_set i) : (μ.to_signed_measure - ν.to_signed_measure) i = (μ i).to_real - (ν i).to_real := begin rw [vector_measure.sub_apply, to_signed_measure_apply_measurable hi, measure.to_signed_measure_apply_measurable hi, sub_eq_add_neg] end end measure namespace vector_measure open measure section /-- A vector measure over `ℝ≥0∞` is a measure. -/ def ennreal_to_measure {m : measurable_space α} (v : vector_measure α ℝ≥0∞) : measure α := of_measurable (λ s _, v s) v.empty (λ f hf₁ hf₂, v.of_disjoint_Union_nat hf₁ hf₂) lemma ennreal_to_measure_apply {m : measurable_space α} {v : vector_measure α ℝ≥0∞} {s : set α} (hs : measurable_set s) : ennreal_to_measure v s = v s := by rw [ennreal_to_measure, of_measurable_apply _ hs] /-- The equiv between `vector_measure α ℝ≥0∞` and `measure α` formed by `measure_theory.vector_measure.ennreal_to_measure` and `measure_theory.measure.to_ennreal_vector_measure`. -/ @[simps] def equiv_measure [measurable_space α] : vector_measure α ℝ≥0∞ ≃ measure α := { to_fun := ennreal_to_measure, inv_fun := to_ennreal_vector_measure, left_inv := λ _, ext (λ s hs, by rw [to_ennreal_vector_measure_apply_measurable hs, ennreal_to_measure_apply hs]), right_inv := λ _, measure.ext (λ s hs, by rw [ennreal_to_measure_apply hs, to_ennreal_vector_measure_apply_measurable hs]) } end section variables [measurable_space α] [measurable_space β] variables {M : Type*} [add_comm_monoid M] [topological_space M] variables (v : vector_measure α M) /-- The pushforward of a vector measure along a function. -/ def map (v : vector_measure α M) (f : α → β) : vector_measure β M := if hf : measurable f then { measure_of' := λ s, if measurable_set s then v (f ⁻¹' s) else 0, empty' := by simp, not_measurable' := λ i hi, if_neg hi, m_Union' := begin intros g hg₁ hg₂, convert v.m_Union (λ i, hf (hg₁ i)) (λ i j hij, (hg₂ hij).preimage _), { ext i, rw if_pos (hg₁ i) }, { rw [preimage_Union, if_pos (measurable_set.Union hg₁)] }, end } else 0 lemma map_not_measurable {f : α → β} (hf : ¬ measurable f) : v.map f = 0 := dif_neg hf lemma map_apply {f : α → β} (hf : measurable f) {s : set β} (hs : measurable_set s) : v.map f s = v (f ⁻¹' s) := by { rw [map, dif_pos hf], exact if_pos hs } @[simp] lemma map_id : v.map id = v := ext (λ i hi, by rw [map_apply v measurable_id hi, preimage_id]) @[simp] lemma map_zero (f : α → β) : (0 : vector_measure α M).map f = 0 := begin by_cases hf : measurable f, { ext i hi, rw [map_apply _ hf hi, zero_apply, zero_apply] }, { exact dif_neg hf } end section variables {N : Type*} [add_comm_monoid N] [topological_space N] /-- Given a vector measure `v` on `M` and a continuous add_monoid_hom `f : M → N`, `f ∘ v` is a vector measure on `N`. -/ def map_range (v : vector_measure α M) (f : M →+ N) (hf : continuous f) : vector_measure α N := { measure_of' := λ s, f (v s), empty' := by rw [empty, add_monoid_hom.map_zero], not_measurable' := λ i hi, by rw [not_measurable v hi, add_monoid_hom.map_zero], m_Union' := λ g hg₁ hg₂, has_sum.map (v.m_Union hg₁ hg₂) f hf } @[simp] lemma map_range_apply {f : M →+ N} (hf : continuous f) {s : set α} : v.map_range f hf s = f (v s) := rfl @[simp] lemma map_range_id : v.map_range (add_monoid_hom.id M) continuous_id = v := by { ext, refl } @[simp] lemma map_range_zero {f : M →+ N} (hf : continuous f) : map_range (0 : vector_measure α M) f hf = 0 := by { ext, simp } section has_continuous_add variables [has_continuous_add M] [has_continuous_add N] @[simp] lemma map_range_add {v w : vector_measure α M} {f : M →+ N} (hf : continuous f) : (v + w).map_range f hf = v.map_range f hf + w.map_range f hf := by { ext, simp } /-- Given a continuous add_monoid_hom `f : M → N`, `map_range_hom` is the add_monoid_hom mapping the vector measure `v` on `M` to the vector measure `f ∘ v` on `N`. -/ def map_range_hom (f : M →+ N) (hf : continuous f) : vector_measure α M →+ vector_measure α N := { to_fun := λ v, v.map_range f hf, map_zero' := map_range_zero hf, map_add' := λ _ _, map_range_add hf } end has_continuous_add section module variables {R : Type*} [semiring R] [module R M] [module R N] variables [has_continuous_add M] [has_continuous_add N] [has_continuous_const_smul R M] [has_continuous_const_smul R N] /-- Given a continuous linear map `f : M → N`, `map_rangeₗ` is the linear map mapping the vector measure `v` on `M` to the vector measure `f ∘ v` on `N`. -/ def map_rangeₗ (f : M →ₗ[R] N) (hf : continuous f) : vector_measure α M →ₗ[R] vector_measure α N := { to_fun := λ v, v.map_range f.to_add_monoid_hom hf, map_add' := λ _ _, map_range_add hf, map_smul' := by { intros, ext, simp } } end module end /-- The restriction of a vector measure on some set. -/ def restrict (v : vector_measure α M) (i : set α) : vector_measure α M := if hi : measurable_set i then { measure_of' := λ s, if measurable_set s then v (s ∩ i) else 0, empty' := by simp, not_measurable' := λ i hi, if_neg hi, m_Union' := begin intros f hf₁ hf₂, convert v.m_Union (λ n, (hf₁ n).inter hi) (hf₂.mono $ λ i j, disjoint.mono inf_le_left inf_le_left), { ext n, rw if_pos (hf₁ n) }, { rw [Union_inter, if_pos (measurable_set.Union hf₁)] } end } else 0 lemma restrict_not_measurable {i : set α} (hi : ¬ measurable_set i) : v.restrict i = 0 := dif_neg hi lemma restrict_apply {i : set α} (hi : measurable_set i) {j : set α} (hj : measurable_set j) : v.restrict i j = v (j ∩ i) := by { rw [restrict, dif_pos hi], exact if_pos hj } lemma restrict_eq_self {i : set α} (hi : measurable_set i) {j : set α} (hj : measurable_set j) (hij : j ⊆ i) : v.restrict i j = v j := by rw [restrict_apply v hi hj, inter_eq_left_iff_subset.2 hij] @[simp] lemma restrict_empty : v.restrict ∅ = 0 := ext (λ i hi, by rw [restrict_apply v measurable_set.empty hi, inter_empty, v.empty, zero_apply]) @[simp] lemma restrict_univ : v.restrict univ = v := ext (λ i hi, by rw [restrict_apply v measurable_set.univ hi, inter_univ]) @[simp] lemma restrict_zero {i : set α} : (0 : vector_measure α M).restrict i = 0 := begin by_cases hi : measurable_set i, { ext j hj, rw [restrict_apply 0 hi hj], refl }, { exact dif_neg hi } end section has_continuous_add variables [has_continuous_add M] lemma map_add (v w : vector_measure α M) (f : α → β) : (v + w).map f = v.map f + w.map f := begin by_cases hf : measurable f, { ext i hi, simp [map_apply _ hf hi] }, { simp [map, dif_neg hf] } end /-- `vector_measure.map` as an additive monoid homomorphism. -/ @[simps] def map_gm (f : α → β) : vector_measure α M →+ vector_measure β M := { to_fun := λ v, v.map f, map_zero' := map_zero f, map_add' := λ _ _, map_add _ _ f } lemma restrict_add (v w : vector_measure α M) (i : set α) : (v + w).restrict i = v.restrict i + w.restrict i := begin by_cases hi : measurable_set i, { ext j hj, simp [restrict_apply _ hi hj] }, { simp [restrict_not_measurable _ hi] } end /--`vector_measure.restrict` as an additive monoid homomorphism. -/ @[simps] def restrict_gm (i : set α) : vector_measure α M →+ vector_measure α M := { to_fun := λ v, v.restrict i, map_zero' := restrict_zero, map_add' := λ _ _, restrict_add _ _ i } end has_continuous_add end section variables [measurable_space β] variables {M : Type*} [add_comm_monoid M] [topological_space M] variables {R : Type*} [semiring R] [distrib_mul_action R M] [has_continuous_const_smul R M] include m @[simp] lemma map_smul {v : vector_measure α M} {f : α → β} (c : R) : (c • v).map f = c • v.map f := begin by_cases hf : measurable f, { ext i hi, simp [map_apply _ hf hi] }, { simp only [map, dif_neg hf], -- `smul_zero` does not work since we do not require `has_continuous_add` ext i hi, simp } end @[simp] lemma restrict_smul {v :vector_measure α M} {i : set α} (c : R) : (c • v).restrict i = c • v.restrict i := begin by_cases hi : measurable_set i, { ext j hj, simp [restrict_apply _ hi hj] }, { simp only [restrict_not_measurable _ hi], -- `smul_zero` does not work since we do not require `has_continuous_add` ext j hj, simp } end end section variables [measurable_space β] variables {M : Type*} [add_comm_monoid M] [topological_space M] variables {R : Type*} [semiring R] [module R M] [has_continuous_const_smul R M] [has_continuous_add M] include m /-- `vector_measure.map` as a linear map. -/ @[simps] def mapₗ (f : α → β) : vector_measure α M →ₗ[R] vector_measure β M := { to_fun := λ v, v.map f, map_add' := λ _ _, map_add _ _ f, map_smul' := λ _ _, map_smul _ } /-- `vector_measure.restrict` as an additive monoid homomorphism. -/ @[simps] def restrictₗ (i : set α) : vector_measure α M →ₗ[R] vector_measure α M := { to_fun := λ v, v.restrict i, map_add' := λ _ _, restrict_add _ _ i, map_smul' := λ _ _, restrict_smul _ } end section variables {M : Type*} [topological_space M] [add_comm_monoid M] [partial_order M] include m /-- Vector measures over a partially ordered monoid is partially ordered. This definition is consistent with `measure.partial_order`. -/ instance : partial_order (vector_measure α M) := { le := λ v w, ∀ i, measurable_set i → v i ≤ w i, le_refl := λ v i hi, le_rfl, le_trans := λ u v w h₁ h₂ i hi, le_trans (h₁ i hi) (h₂ i hi), le_antisymm := λ v w h₁ h₂, ext (λ i hi, le_antisymm (h₁ i hi) (h₂ i hi)) } variables {u v w : vector_measure α M} lemma le_iff : v ≤ w ↔ ∀ i, measurable_set i → v i ≤ w i := iff.rfl lemma le_iff' : v ≤ w ↔ ∀ i, v i ≤ w i := begin refine ⟨λ h i, _, λ h i hi, h i⟩, by_cases hi : measurable_set i, { exact h i hi }, { rw [v.not_measurable hi, w.not_measurable hi] } end end localized "notation (name := vector_measure.restrict) v ` ≤[`:50 i:50 `] `:0 w:50 := measure_theory.vector_measure.restrict v i ≤ measure_theory.vector_measure.restrict w i" in measure_theory section variables {M : Type*} [topological_space M] [add_comm_monoid M] [partial_order M] variables (v w : vector_measure α M) lemma restrict_le_restrict_iff {i : set α} (hi : measurable_set i) : v ≤[i] w ↔ ∀ ⦃j⦄, measurable_set j → j ⊆ i → v j ≤ w j := ⟨λ h j hj₁ hj₂, (restrict_eq_self v hi hj₁ hj₂) ▸ (restrict_eq_self w hi hj₁ hj₂) ▸ h j hj₁, λ h, le_iff.1 (λ j hj, (restrict_apply v hi hj).symm ▸ (restrict_apply w hi hj).symm ▸ h (hj.inter hi) (set.inter_subset_right j i))⟩ lemma subset_le_of_restrict_le_restrict {i : set α} (hi : measurable_set i) (hi₂ : v ≤[i] w) {j : set α} (hj : j ⊆ i) : v j ≤ w j := begin by_cases hj₁ : measurable_set j, { exact (restrict_le_restrict_iff _ _ hi).1 hi₂ hj₁ hj }, { rw [v.not_measurable hj₁, w.not_measurable hj₁] }, end lemma restrict_le_restrict_of_subset_le {i : set α} (h : ∀ ⦃j⦄, measurable_set j → j ⊆ i → v j ≤ w j) : v ≤[i] w := begin by_cases hi : measurable_set i, { exact (restrict_le_restrict_iff _ _ hi).2 h }, { rw [restrict_not_measurable v hi, restrict_not_measurable w hi], exact le_rfl }, end lemma restrict_le_restrict_subset {i j : set α} (hi₁ : measurable_set i) (hi₂ : v ≤[i] w) (hij : j ⊆ i) : v ≤[j] w := restrict_le_restrict_of_subset_le v w (λ k hk₁ hk₂, subset_le_of_restrict_le_restrict v w hi₁ hi₂ (set.subset.trans hk₂ hij)) lemma le_restrict_empty : v ≤[∅] w := begin intros j hj, rw [restrict_empty, restrict_empty] end lemma le_restrict_univ_iff_le : v ≤[univ] w ↔ v ≤ w := begin split, { intros h s hs, have := h s hs, rwa [restrict_apply _ measurable_set.univ hs, inter_univ, restrict_apply _ measurable_set.univ hs, inter_univ] at this }, { intros h s hs, rw [restrict_apply _ measurable_set.univ hs, inter_univ, restrict_apply _ measurable_set.univ hs, inter_univ], exact h s hs } end end section variables {M : Type*} [topological_space M] [ordered_add_comm_group M] [topological_add_group M] variables (v w : vector_measure α M) lemma neg_le_neg {i : set α} (hi : measurable_set i) (h : v ≤[i] w) : -w ≤[i] -v := begin intros j hj₁, rw [restrict_apply _ hi hj₁, restrict_apply _ hi hj₁, neg_apply, neg_apply], refine neg_le_neg _, rw [← restrict_apply _ hi hj₁, ← restrict_apply _ hi hj₁], exact h j hj₁, end @[simp] lemma neg_le_neg_iff {i : set α} (hi : measurable_set i) : -w ≤[i] -v ↔ v ≤[i] w := ⟨λ h, neg_neg v ▸ neg_neg w ▸ neg_le_neg _ _ hi h, λ h, neg_le_neg _ _ hi h⟩ end section variables {M : Type*} [topological_space M] [ordered_add_comm_monoid M] [order_closed_topology M] variables (v w : vector_measure α M) {i j : set α} lemma restrict_le_restrict_Union {f : ℕ → set α} (hf₁ : ∀ n, measurable_set (f n)) (hf₂ : ∀ n, v ≤[f n] w) : v ≤[⋃ n, f n] w := begin refine restrict_le_restrict_of_subset_le v w (λ a ha₁ ha₂, _), have ha₃ : (⋃ n, a ∩ disjointed f n) = a, { rwa [← inter_Union, Union_disjointed, inter_eq_left_iff_subset] }, have ha₄ : pairwise (disjoint on (λ n, a ∩ disjointed f n)), { exact (disjoint_disjointed _).mono (λ i j, disjoint.mono inf_le_right inf_le_right) }, rw [← ha₃, v.of_disjoint_Union_nat _ ha₄, w.of_disjoint_Union_nat _ ha₄], refine tsum_le_tsum (λ n, (restrict_le_restrict_iff v w (hf₁ n)).1 (hf₂ n) _ _) _ _, { exact (ha₁.inter (measurable_set.disjointed hf₁ n)) }, { exact set.subset.trans (set.inter_subset_right _ _) (disjointed_subset _ _) }, { refine (v.m_Union (λ n, _) _).summable, { exact ha₁.inter (measurable_set.disjointed hf₁ n) }, { exact (disjoint_disjointed _).mono (λ i j, disjoint.mono inf_le_right inf_le_right) } }, { refine (w.m_Union (λ n, _) _).summable, { exact ha₁.inter (measurable_set.disjointed hf₁ n) }, { exact (disjoint_disjointed _).mono (λ i j, disjoint.mono inf_le_right inf_le_right) } }, { intro n, exact (ha₁.inter (measurable_set.disjointed hf₁ n)) }, { exact λ n, ha₁.inter (measurable_set.disjointed hf₁ n) } end lemma restrict_le_restrict_countable_Union [countable β] {f : β → set α} (hf₁ : ∀ b, measurable_set (f b)) (hf₂ : ∀ b, v ≤[f b] w) : v ≤[⋃ b, f b] w := begin casesI nonempty_encodable β, rw ← encodable.Union_decode₂, refine restrict_le_restrict_Union v w _ _, { intro n, measurability }, { intro n, cases encodable.decode₂ β n with b, { simp }, { simp [hf₂ b] } } end lemma restrict_le_restrict_union (hi₁ : measurable_set i) (hi₂ : v ≤[i] w) (hj₁ : measurable_set j) (hj₂ : v ≤[j] w) : v ≤[i ∪ j] w := begin rw union_eq_Union, refine restrict_le_restrict_countable_Union v w _ _, { measurability }, { rintro (_ | _); simpa } end end section variables {M : Type*} [topological_space M] [ordered_add_comm_monoid M] variables (v w : vector_measure α M) {i j : set α} lemma nonneg_of_zero_le_restrict (hi₂ : 0 ≤[i] v) : 0 ≤ v i := begin by_cases hi₁ : measurable_set i, { exact (restrict_le_restrict_iff _ _ hi₁).1 hi₂ hi₁ set.subset.rfl }, { rw v.not_measurable hi₁ }, end lemma nonpos_of_restrict_le_zero (hi₂ : v ≤[i] 0) : v i ≤ 0 := begin by_cases hi₁ : measurable_set i, { exact (restrict_le_restrict_iff _ _ hi₁).1 hi₂ hi₁ set.subset.rfl }, { rw v.not_measurable hi₁ } end lemma zero_le_restrict_not_measurable (hi : ¬ measurable_set i) : 0 ≤[i] v := begin rw [restrict_zero, restrict_not_measurable _ hi], exact le_rfl, end lemma restrict_le_zero_of_not_measurable (hi : ¬ measurable_set i) : v ≤[i] 0 := begin rw [restrict_zero, restrict_not_measurable _ hi], exact le_rfl, end lemma measurable_of_not_zero_le_restrict (hi : ¬ 0 ≤[i] v) : measurable_set i := not.imp_symm (zero_le_restrict_not_measurable _) hi lemma measurable_of_not_restrict_le_zero (hi : ¬ v ≤[i] 0) : measurable_set i := not.imp_symm (restrict_le_zero_of_not_measurable _) hi lemma zero_le_restrict_subset (hi₁ : measurable_set i) (hij : j ⊆ i) (hi₂ : 0 ≤[i] v): 0 ≤[j] v := restrict_le_restrict_of_subset_le _ _ (λ k hk₁ hk₂, (restrict_le_restrict_iff _ _ hi₁).1 hi₂ hk₁ (set.subset.trans hk₂ hij)) lemma restrict_le_zero_subset (hi₁ : measurable_set i) (hij : j ⊆ i) (hi₂ : v ≤[i] 0): v ≤[j] 0 := restrict_le_restrict_of_subset_le _ _ (λ k hk₁ hk₂, (restrict_le_restrict_iff _ _ hi₁).1 hi₂ hk₁ (set.subset.trans hk₂ hij)) end section variables {M : Type*} [topological_space M] [linear_ordered_add_comm_monoid M] variables (v w : vector_measure α M) {i j : set α} include m lemma exists_pos_measure_of_not_restrict_le_zero (hi : ¬ v ≤[i] 0) : ∃ j : set α, measurable_set j ∧ j ⊆ i ∧ 0 < v j := begin have hi₁ : measurable_set i := measurable_of_not_restrict_le_zero _ hi, rw [restrict_le_restrict_iff _ _ hi₁] at hi, push_neg at hi, obtain ⟨j, hj₁, hj₂, hj⟩ := hi, exact ⟨j, hj₁, hj₂, hj⟩, end end section variables {M : Type*} [topological_space M] [add_comm_monoid M] [partial_order M] [covariant_class M M (+) (≤)] [has_continuous_add M] include m instance covariant_add_le : covariant_class (vector_measure α M) (vector_measure α M) (+) (≤) := ⟨λ u v w h i hi, add_le_add_left (h i hi) _⟩ end section variables {L M N : Type*} variables [add_comm_monoid L] [topological_space L] [add_comm_monoid M] [topological_space M] [add_comm_monoid N] [topological_space N] include m /-- A vector measure `v` is absolutely continuous with respect to a measure `μ` if for all sets `s`, `μ s = 0`, we have `v s = 0`. -/ def absolutely_continuous (v : vector_measure α M) (w : vector_measure α N) := ∀ ⦃s : set α⦄, w s = 0 → v s = 0 localized "infix (name := vector_measure.absolutely_continuous) ` ≪ᵥ `:50 := measure_theory.vector_measure.absolutely_continuous" in measure_theory open_locale measure_theory namespace absolutely_continuous variables {v : vector_measure α M} {w : vector_measure α N} lemma mk (h : ∀ ⦃s : set α⦄, measurable_set s → w s = 0 → v s = 0) : v ≪ᵥ w := begin intros s hs, by_cases hmeas : measurable_set s, { exact h hmeas hs }, { exact not_measurable v hmeas } end lemma eq {w : vector_measure α M} (h : v = w) : v ≪ᵥ w := λ s hs, h.symm ▸ hs @[refl] lemma refl (v : vector_measure α M) : v ≪ᵥ v := eq rfl @[trans] lemma trans {u : vector_measure α L} {v : vector_measure α M} {w : vector_measure α N} (huv : u ≪ᵥ v) (hvw : v ≪ᵥ w) : u ≪ᵥ w := λ _ hs, huv $ hvw hs lemma zero (v : vector_measure α N) : (0 : vector_measure α M) ≪ᵥ v := λ s _, vector_measure.zero_apply s lemma neg_left {M : Type*} [add_comm_group M] [topological_space M] [topological_add_group M] {v : vector_measure α M} {w : vector_measure α N} (h : v ≪ᵥ w) : -v ≪ᵥ w := λ s hs, by { rw [neg_apply, h hs, neg_zero] } lemma neg_right {N : Type*} [add_comm_group N] [topological_space N] [topological_add_group N] {v : vector_measure α M} {w : vector_measure α N} (h : v ≪ᵥ w) : v ≪ᵥ -w := begin intros s hs, rw [neg_apply, neg_eq_zero] at hs, exact h hs end lemma add [has_continuous_add M] {v₁ v₂ : vector_measure α M} {w : vector_measure α N} (hv₁ : v₁ ≪ᵥ w) (hv₂ : v₂ ≪ᵥ w) : v₁ + v₂ ≪ᵥ w := λ s hs, by { rw [add_apply, hv₁ hs, hv₂ hs, zero_add] } lemma sub {M : Type*} [add_comm_group M] [topological_space M] [topological_add_group M] {v₁ v₂ : vector_measure α M} {w : vector_measure α N} (hv₁ : v₁ ≪ᵥ w) (hv₂ : v₂ ≪ᵥ w) : v₁ - v₂ ≪ᵥ w := λ s hs, by { rw [sub_apply, hv₁ hs, hv₂ hs, zero_sub, neg_zero] } lemma smul {R : Type*} [semiring R] [distrib_mul_action R M] [has_continuous_const_smul R M] {r : R} {v : vector_measure α M} {w : vector_measure α N} (h : v ≪ᵥ w) : r • v ≪ᵥ w := λ s hs, by { rw [smul_apply, h hs, smul_zero] } lemma map [measure_space β] (h : v ≪ᵥ w) (f : α → β) : v.map f ≪ᵥ w.map f := begin by_cases hf : measurable f, { refine mk (λ s hs hws, _), rw map_apply _ hf hs at hws ⊢, exact h hws }, { intros s hs, rw [map_not_measurable v hf, zero_apply] } end lemma ennreal_to_measure {μ : vector_measure α ℝ≥0∞} : (∀ ⦃s : set α⦄, μ.ennreal_to_measure s = 0 → v s = 0) ↔ v ≪ᵥ μ := begin split; intro h, { refine mk (λ s hmeas hs, h _), rw [← hs, ennreal_to_measure_apply hmeas] }, { intros s hs, by_cases hmeas : measurable_set s, { rw ennreal_to_measure_apply hmeas at hs, exact h hs }, { exact not_measurable v hmeas } }, end end absolutely_continuous /-- Two vector measures `v` and `w` are said to be mutually singular if there exists a measurable set `s`, such that for all `t ⊆ s`, `v t = 0` and for all `t ⊆ sᶜ`, `w t = 0`. We note that we do not require the measurability of `t` in the definition since this makes it easier to use. This is equivalent to the definition which requires measurability. To prove `mutually_singular` with the measurability condition, use `measure_theory.vector_measure.mutually_singular.mk`. -/ def mutually_singular (v : vector_measure α M) (w : vector_measure α N) : Prop := ∃ (s : set α), measurable_set s ∧ (∀ t ⊆ s, v t = 0) ∧ (∀ t ⊆ sᶜ, w t = 0) localized "infix (name := vector_measure.mutually_singular) ` ⟂ᵥ `:60 := measure_theory.vector_measure.mutually_singular" in measure_theory namespace mutually_singular variables {v v₁ v₂ : vector_measure α M} {w w₁ w₂ : vector_measure α N} lemma mk (s : set α) (hs : measurable_set s) (h₁ : ∀ t ⊆ s, measurable_set t → v t = 0) (h₂ : ∀ t ⊆ sᶜ, measurable_set t → w t = 0) : v ⟂ᵥ w := begin refine ⟨s, hs, λ t hst, _, λ t hst, _⟩; by_cases ht : measurable_set t, { exact h₁ t hst ht }, { exact not_measurable v ht }, { exact h₂ t hst ht }, { exact not_measurable w ht } end lemma symm (h : v ⟂ᵥ w) : w ⟂ᵥ v := let ⟨s, hmeas, hs₁, hs₂⟩ := h in ⟨sᶜ, hmeas.compl, hs₂, λ t ht, hs₁ _ (compl_compl s ▸ ht : t ⊆ s)⟩ lemma zero_right : v ⟂ᵥ (0 : vector_measure α N) := ⟨∅, measurable_set.empty, λ t ht, (subset_empty_iff.1 ht).symm ▸ v.empty, λ _ _, zero_apply _⟩ lemma zero_left : (0 : vector_measure α M) ⟂ᵥ w := zero_right.symm lemma add_left [t2_space N] [has_continuous_add M] (h₁ : v₁ ⟂ᵥ w) (h₂ : v₂ ⟂ᵥ w) : v₁ + v₂ ⟂ᵥ w := begin obtain ⟨u, hmu, hu₁, hu₂⟩ := h₁, obtain ⟨v, hmv, hv₁, hv₂⟩ := h₂, refine mk (u ∩ v) (hmu.inter hmv) (λ t ht hmt, _) (λ t ht hmt, _), { rw [add_apply, hu₁ _ (subset_inter_iff.1 ht).1, hv₁ _ (subset_inter_iff.1 ht).2, zero_add] }, { rw compl_inter at ht, rw [(_ : t = (uᶜ ∩ t) ∪ (vᶜ \ uᶜ ∩ t)), of_union _ (hmu.compl.inter hmt) ((hmv.compl.diff hmu.compl).inter hmt), hu₂, hv₂, add_zero], { exact subset.trans (inter_subset_left _ _) (diff_subset _ _) }, { exact inter_subset_left _ _ }, { apply_instance }, { exact disjoint_sdiff_self_right.mono (inter_subset_left _ _) (inter_subset_left _ _) }, { apply subset.antisymm; intros x hx, { by_cases hxu' : x ∈ uᶜ, { exact or.inl ⟨hxu', hx⟩ }, rcases ht hx with (hxu | hxv), exacts [false.elim (hxu' hxu), or.inr ⟨⟨hxv, hxu'⟩, hx⟩] }, { rcases hx; exact hx.2 } } }, end lemma add_right [t2_space M] [has_continuous_add N] (h₁ : v ⟂ᵥ w₁) (h₂ : v ⟂ᵥ w₂) : v ⟂ᵥ w₁ + w₂ := (add_left h₁.symm h₂.symm).symm lemma smul_right {R : Type*} [semiring R] [distrib_mul_action R N] [has_continuous_const_smul R N] (r : R) (h : v ⟂ᵥ w) : v ⟂ᵥ r • w := let ⟨s, hmeas, hs₁, hs₂⟩ := h in ⟨s, hmeas, hs₁, λ t ht, by simp only [coe_smul, pi.smul_apply, hs₂ t ht, smul_zero]⟩ lemma smul_left {R : Type*} [semiring R] [distrib_mul_action R M] [has_continuous_const_smul R M] (r : R) (h : v ⟂ᵥ w) : r • v ⟂ᵥ w := (smul_right r h.symm).symm lemma neg_left {M : Type*} [add_comm_group M] [topological_space M] [topological_add_group M] {v : vector_measure α M} {w : vector_measure α N} (h : v ⟂ᵥ w) : -v ⟂ᵥ w := begin obtain ⟨u, hmu, hu₁, hu₂⟩ := h, refine ⟨u, hmu, λ s hs, _, hu₂⟩, rw [neg_apply v s, neg_eq_zero], exact hu₁ s hs end lemma neg_right {N : Type*} [add_comm_group N] [topological_space N] [topological_add_group N] {v : vector_measure α M} {w : vector_measure α N} (h : v ⟂ᵥ w) : v ⟂ᵥ -w := h.symm.neg_left.symm @[simp] lemma neg_left_iff {M : Type*} [add_comm_group M] [topological_space M] [topological_add_group M] {v : vector_measure α M} {w : vector_measure α N} : -v ⟂ᵥ w ↔ v ⟂ᵥ w := ⟨λ h, neg_neg v ▸ h.neg_left, neg_left⟩ @[simp] lemma neg_right_iff {N : Type*} [add_comm_group N] [topological_space N] [topological_add_group N] {v : vector_measure α M} {w : vector_measure α N} : v ⟂ᵥ -w ↔ v ⟂ᵥ w := ⟨λ h, neg_neg w ▸ h.neg_right, neg_right⟩ end mutually_singular section trim omit m /-- Restriction of a vector measure onto a sub-σ-algebra. -/ @[simps] def trim {m n : measurable_space α} (v : vector_measure α M) (hle : m ≤ n) : @vector_measure α m M _ _ := { measure_of' := λ i, if measurable_set[m] i then v i else 0, empty' := by rw [if_pos measurable_set.empty, v.empty], not_measurable' := λ i hi, by rw if_neg hi, m_Union' := λ f hf₁ hf₂, begin have hf₁' : ∀ k, measurable_set[n] (f k) := λ k, hle _ (hf₁ k), convert v.m_Union hf₁' hf₂, { ext n, rw if_pos (hf₁ n) }, { rw if_pos (@measurable_set.Union _ _ m _ _ hf₁) } end } variables {n : measurable_space α} {v : vector_measure α M} lemma trim_eq_self : v.trim le_rfl = v := begin ext1 i hi, exact if_pos hi, end @[simp] lemma zero_trim (hle : m ≤ n) : (0 : vector_measure α M).trim hle = 0 := begin ext1 i hi, exact if_pos hi, end lemma trim_measurable_set_eq (hle : m ≤ n) {i : set α} (hi : measurable_set[m] i) : v.trim hle i = v i := if_pos hi lemma restrict_trim (hle : m ≤ n) {i : set α} (hi : measurable_set[m] i) : @vector_measure.restrict α m M _ _ (v.trim hle) i = (v.restrict i).trim hle := begin ext j hj, rw [restrict_apply, trim_measurable_set_eq hle hj, restrict_apply, trim_measurable_set_eq], all_goals { measurability } end end trim end end vector_measure namespace signed_measure open vector_measure open_locale measure_theory include m /-- The underlying function for `signed_measure.to_measure_of_zero_le`. -/ def to_measure_of_zero_le' (s : signed_measure α) (i : set α) (hi : 0 ≤[i] s) (j : set α) (hj : measurable_set j) : ℝ≥0∞ := @coe ℝ≥0 ℝ≥0∞ _ ⟨s.restrict i j, le_trans (by simp) (hi j hj)⟩ /-- Given a signed measure `s` and a positive measurable set `i`, `to_measure_of_zero_le` provides the measure, mapping measurable sets `j` to `s (i ∩ j)`. -/ def to_measure_of_zero_le (s : signed_measure α) (i : set α) (hi₁ : measurable_set i) (hi₂ : 0 ≤[i] s) : measure α := measure.of_measurable (s.to_measure_of_zero_le' i hi₂) (by { simp_rw [to_measure_of_zero_le', s.restrict_apply hi₁ measurable_set.empty, set.empty_inter i, s.empty], refl }) begin intros f hf₁ hf₂, have h₁ : ∀ n, measurable_set (i ∩ f n) := λ n, hi₁.inter (hf₁ n), have h₂ : pairwise (disjoint on λ (n : ℕ), i ∩ f n), { intros n m hnm, exact (((hf₂ hnm).inf_left' i).inf_right' i) }, simp only [to_measure_of_zero_le', s.restrict_apply hi₁ (measurable_set.Union hf₁), set.inter_comm, set.inter_Union, s.of_disjoint_Union_nat h₁ h₂, ennreal.some_eq_coe, id.def], have h : ∀ n, 0 ≤ s (i ∩ f n) := λ n, s.nonneg_of_zero_le_restrict (s.zero_le_restrict_subset hi₁ (inter_subset_left _ _) hi₂), rw [nnreal.coe_tsum_of_nonneg h, ennreal.coe_tsum], { refine tsum_congr (λ n, _), simp_rw [s.restrict_apply hi₁ (hf₁ n), set.inter_comm] }, { exact (nnreal.summable_coe_of_nonneg h).2 (s.m_Union h₁ h₂).summable } end variables (s : signed_measure α) {i j : set α} lemma to_measure_of_zero_le_apply (hi : 0 ≤[i] s) (hi₁ : measurable_set i) (hj₁ : measurable_set j) : s.to_measure_of_zero_le i hi₁ hi j = @coe ℝ≥0 ℝ≥0∞ _ ⟨s (i ∩ j), nonneg_of_zero_le_restrict s (zero_le_restrict_subset s hi₁ (set.inter_subset_left _ _) hi)⟩ := by simp_rw [to_measure_of_zero_le, measure.of_measurable_apply _ hj₁, to_measure_of_zero_le', s.restrict_apply hi₁ hj₁, set.inter_comm] /-- Given a signed measure `s` and a negative measurable set `i`, `to_measure_of_le_zero` provides the measure, mapping measurable sets `j` to `-s (i ∩ j)`. -/ def to_measure_of_le_zero (s : signed_measure α) (i : set α) (hi₁ : measurable_set i) (hi₂ : s ≤[i] 0) : measure α := to_measure_of_zero_le (-s) i hi₁ $ (@neg_zero (vector_measure α ℝ) _) ▸ neg_le_neg _ _ hi₁ hi₂ lemma to_measure_of_le_zero_apply (hi : s ≤[i] 0) (hi₁ : measurable_set i) (hj₁ : measurable_set j) : s.to_measure_of_le_zero i hi₁ hi j = @coe ℝ≥0 ℝ≥0∞ _ ⟨-s (i ∩ j), neg_apply s (i ∩ j) ▸ nonneg_of_zero_le_restrict _ (zero_le_restrict_subset _ hi₁ (set.inter_subset_left _ _) ((@neg_zero (vector_measure α ℝ) _) ▸ neg_le_neg _ _ hi₁ hi))⟩ := begin erw [to_measure_of_zero_le_apply], { simp }, { assumption }, end /-- `signed_measure.to_measure_of_zero_le` is a finite measure. -/ instance to_measure_of_zero_le_finite (hi : 0 ≤[i] s) (hi₁ : measurable_set i) : is_finite_measure (s.to_measure_of_zero_le i hi₁ hi) := { measure_univ_lt_top := begin rw [to_measure_of_zero_le_apply s hi hi₁ measurable_set.univ], exact ennreal.coe_lt_top, end } /-- `signed_measure.to_measure_of_le_zero` is a finite measure. -/ instance to_measure_of_le_zero_finite (hi : s ≤[i] 0) (hi₁ : measurable_set i) : is_finite_measure (s.to_measure_of_le_zero i hi₁ hi) := { measure_univ_lt_top := begin rw [to_measure_of_le_zero_apply s hi hi₁ measurable_set.univ], exact ennreal.coe_lt_top, end } lemma to_measure_of_zero_le_to_signed_measure (hs : 0 ≤[univ] s) : (s.to_measure_of_zero_le univ measurable_set.univ hs).to_signed_measure = s := begin ext i hi, simp [measure.to_signed_measure_apply_measurable hi, to_measure_of_zero_le_apply _ _ _ hi], end lemma to_measure_of_le_zero_to_signed_measure (hs : s ≤[univ] 0) : (s.to_measure_of_le_zero univ measurable_set.univ hs).to_signed_measure = -s := begin ext i hi, simp [measure.to_signed_measure_apply_measurable hi, to_measure_of_le_zero_apply _ _ _ hi], end end signed_measure namespace measure open vector_measure variables (μ : measure α) [is_finite_measure μ] lemma zero_le_to_signed_measure : 0 ≤ μ.to_signed_measure := begin rw ← le_restrict_univ_iff_le, refine restrict_le_restrict_of_subset_le _ _ (λ j hj₁ _, _), simp only [measure.to_signed_measure_apply_measurable hj₁, coe_zero, pi.zero_apply, ennreal.to_real_nonneg, vector_measure.coe_zero] end lemma to_signed_measure_to_measure_of_zero_le : μ.to_signed_measure.to_measure_of_zero_le univ measurable_set.univ ((le_restrict_univ_iff_le _ _).2 (zero_le_to_signed_measure μ)) = μ := begin refine measure.ext (λ i hi, _), lift μ i to ℝ≥0 using (measure_lt_top _ _).ne with m hm, simp [signed_measure.to_measure_of_zero_le_apply _ _ _ hi, measure.to_signed_measure_apply_measurable hi, ← hm], end end measure end measure_theory
0f34a0f34fbb47c3173dd238118d539247d4e3eb
b561a44b48979a98df50ade0789a21c79ee31288
/src/Lean/Elab/BuiltinNotation.lean
060befbeac6bd91c23559186a4a1e2dfe24cb808
[ "Apache-2.0" ]
permissive
3401ijk/lean4
97659c475ebd33a034fed515cb83a85f75ccfb06
a5b1b8de4f4b038ff752b9e607b721f15a9a4351
refs/heads/master
1,693,933,007,651
1,636,424,845,000
1,636,424,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,817
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 Init.Data.ToString import Lean.Compiler.BorrowedAnnotation import Lean.Meta.KAbstract import Lean.Meta.Transform import Lean.Elab.App import Lean.Elab.SyntheticMVars namespace Lean.Elab.Term open Meta @[builtinTermElab anonymousCtor] def elabAnonymousCtor : TermElab := fun stx expectedType? => match stx with | `(⟨$args,*⟩) => do tryPostponeIfNoneOrMVar expectedType? match expectedType? with | some expectedType => let expectedType ← whnf expectedType matchConstInduct expectedType.getAppFn (fun _ => throwError "invalid constructor ⟨...⟩, expected type must be an inductive type {indentExpr expectedType}") (fun ival us => do match ival.ctors with | [ctor] => let cinfo ← getConstInfoCtor ctor let numExplicitFields ← forallTelescopeReducing cinfo.type fun xs _ => do let mut n := 0 for i in [cinfo.numParams:xs.size] do if (← getFVarLocalDecl xs[i]).binderInfo.isExplicit then n := n + 1 return n let args := args.getElems if args.size < numExplicitFields then throwError "invalid constructor ⟨...⟩, insufficient number of arguments, constructs '{ctor}' has #{numExplicitFields} explicit fields, but only #{args.size} provided" let newStx ← if args.size == numExplicitFields then `($(mkCIdentFrom stx ctor) $(args)*) else if numExplicitFields == 0 then throwError "invalid constructor ⟨...⟩, insufficient number of arguments, constructs '{ctor}' does not have explicit fields, but #{args.size} provided" else let extra := args[numExplicitFields-1:args.size] let newLast ← `(⟨$[$extra],*⟩) let newArgs := args[0:numExplicitFields-1].toArray.push newLast `($(mkCIdentFrom stx ctor) $(newArgs)*) withMacroExpansion stx newStx $ elabTerm newStx expectedType? | _ => throwError "invalid constructor ⟨...⟩, expected type must be an inductive type with only one constructor {indentExpr expectedType}") | none => throwError "invalid constructor ⟨...⟩, expected type must be known" | _ => throwUnsupportedSyntax @[builtinTermElab borrowed] def elabBorrowed : TermElab := fun stx expectedType? => match stx with | `(@& $e) => return markBorrowed (← elabTerm e expectedType?) | _ => throwUnsupportedSyntax @[builtinMacro Lean.Parser.Term.show] def expandShow : Macro := fun stx => match stx with | `(show $type from $val) => let thisId := mkIdentFrom stx `this; `(let_fun $thisId : $type := $val; $thisId) | `(show $type by%$b $tac:tacticSeq) => `(show $type from by%$b $tac:tacticSeq) | _ => Macro.throwUnsupported @[builtinMacro Lean.Parser.Term.have] def expandHave : Macro := fun stx => let thisId := mkIdentFrom stx `this match stx with | `(have $x $bs* $[: $type]? := $val $[;]? $body) => `(let_fun $x $bs* $[: $type]? := $val; $body) | `(have $[: $type]? := $val $[;]? $body) => `(have $thisId:ident $[: $type]? := $val; $body) | `(have $x $bs* $[: $type]? $alts:matchAlts $[;]? $body) => `(let_fun $x $bs* $[: $type]? $alts:matchAlts; $body) | `(have $[: $type]? $alts:matchAlts $[;]? $body) => `(have $thisId:ident $[: $type]? $alts:matchAlts; $body) | `(have $pattern:term $[: $type]? := $val:term $[;]? $body) => `(let_fun $pattern:term $[: $type]? := $val:term ; $body) | _ => Macro.throwUnsupported @[builtinMacro Lean.Parser.Term.suffices] def expandSuffices : Macro | `(suffices $[$x :]? $type from $val $[;]? $body) => `(have $[$x]? : $type := $body; $val) | `(suffices $[$x :]? $type by%$b $tac:tacticSeq $[;]? $body) => `(have $[$x]? : $type := $body; by%$b $tac:tacticSeq) | _ => Macro.throwUnsupported open Lean.Parser in private def elabParserMacroAux (prec : Syntax) (e : Syntax) : TermElabM Syntax := do let (some declName) ← getDeclName? | throwError "invalid `leading_parser` macro, it must be used in definitions" match extractMacroScopes declName with | { name := Name.str _ s _, scopes := scps, .. } => let kind := quote declName let s := quote s -- if the parser decl is hidden by hygiene, it doesn't make sense to provide an antiquotation kind let antiquotKind ← if scps == [] then `(some $kind) else `(none) ``(withAntiquot (mkAntiquot $s $antiquotKind) (leadingNode $kind $prec $e)) | _ => throwError "invalid `leading_parser` macro, unexpected declaration name" @[builtinTermElab «leading_parser»] def elabLeadingParserMacro : TermElab := adaptExpander fun stx => match stx with | `(leading_parser $e) => elabParserMacroAux (quote Parser.maxPrec) e | `(leading_parser : $prec $e) => elabParserMacroAux prec e | _ => throwUnsupportedSyntax private def elabTParserMacroAux (prec lhsPrec : Syntax) (e : Syntax) : TermElabM Syntax := do let declName? ← getDeclName? match declName? with | some declName => let kind := quote declName; ``(Lean.Parser.trailingNode $kind $prec $lhsPrec $e) | none => throwError "invalid `trailing_parser` macro, it must be used in definitions" @[builtinTermElab «trailing_parser»] def elabTrailingParserMacro : TermElab := adaptExpander fun stx => match stx with | `(trailing_parser$[:$prec?]?$[:$lhsPrec?]? $e) => elabTParserMacroAux (prec?.getD <| quote Parser.maxPrec) (lhsPrec?.getD <| quote 0) e | _ => throwUnsupportedSyntax @[builtinTermElab panic] def elabPanic : TermElab := fun stx expectedType? => do let arg := stx[1] let pos ← getRefPosition let env ← getEnv let stxNew ← match (← getDeclName?) with | some declName => `(panicWithPosWithDecl $(quote (toString env.mainModule)) $(quote (toString declName)) $(quote pos.line) $(quote pos.column) $arg) | none => `(panicWithPos $(quote (toString env.mainModule)) $(quote pos.line) $(quote pos.column) $arg) withMacroExpansion stx stxNew $ elabTerm stxNew expectedType? @[builtinMacro Lean.Parser.Term.unreachable] def expandUnreachable : Macro := fun stx => `(panic! "unreachable code has been reached") @[builtinMacro Lean.Parser.Term.assert] def expandAssert : Macro := fun stx => -- TODO: support for disabling runtime assertions let cond := stx[1] let body := stx[3] match cond.reprint with | some code => `(if $cond then $body else panic! ("assertion violation: " ++ $(quote code))) | none => `(if $cond then $body else panic! ("assertion violation")) @[builtinMacro Lean.Parser.Term.dbgTrace] def expandDbgTrace : Macro := fun stx => let arg := stx[1] let body := stx[3] if arg.getKind == interpolatedStrKind then `(dbgTrace (s! $arg) fun _ => $body) else `(dbgTrace (toString $arg) fun _ => $body) @[builtinTermElab «sorry»] def elabSorry : TermElab := fun stx expectedType? => do logWarning "declaration uses 'sorry'" let stxNew ← `(sorryAx _ false) withMacroExpansion stx stxNew <| elabTerm stxNew expectedType? /-- Return syntax `Prod.mk elems[0] (Prod.mk elems[1] ... (Prod.mk elems[elems.size - 2] elems[elems.size - 1])))` -/ partial def mkPairs (elems : Array Syntax) : MacroM Syntax := let rec loop (i : Nat) (acc : Syntax) := do if i > 0 then let i := i - 1 let elem := elems[i] let acc ← `(Prod.mk $elem $acc) loop i acc else pure acc loop (elems.size - 1) elems.back private partial def hasCDot : Syntax → Bool | Syntax.node _ k args => if k == ``Lean.Parser.Term.paren then false else if k == ``Lean.Parser.Term.cdot then true else args.any hasCDot | _ => false /-- Return `some` if succeeded expanding `·` notation occurring in the given syntax. Otherwise, return `none`. Examples: - `· + 1` => `fun _a_1 => _a_1 + 1` - `f · · b` => `fun _a_1 _a_2 => f _a_1 _a_2 b` -/ partial def expandCDot? (stx : Syntax) : MacroM (Option Syntax) := do if hasCDot stx then let (newStx, binders) ← (go stx).run #[]; `(fun $binders* => $newStx) else pure none where /-- Auxiliary function for expanding the `·` notation. The extra state `Array Syntax` contains the new binder names. If `stx` is a `·`, we create a fresh identifier, store in the extra state, and return it. Otherwise, we just return `stx`. -/ go : Syntax → StateT (Array Syntax) MacroM Syntax | stx@(Syntax.node i k args) => if k == ``Lean.Parser.Term.paren then pure stx else if k == ``Lean.Parser.Term.cdot then withFreshMacroScope do let id ← `(a) modify fun s => s.push id; pure id else do let args ← args.mapM go pure $ Syntax.node i k args | stx => pure stx /-- Helper method for elaborating terms such as `(.+.)` where a constant name is expected. This method is usually used to implement tactics that function names as arguments (e.g., `simp`). -/ def elabCDotFunctionAlias? (stx : Syntax) : TermElabM (Option Expr) := do let some stx ← liftMacroM <| expandCDotArg? stx | pure none let stx ← liftMacroM <| expandMacros stx match stx with | `(fun $binders* => $f:ident $args*) => if binders == args then try Term.resolveId? f catch _ => return none else return none | `(fun $binders* => binop% $f:ident $a $b) => if binders == #[a, b] then try Term.resolveId? f catch _ => return none else return none | _ => return none where expandCDotArg? (stx : Syntax) : MacroM (Option Syntax) := match stx with | `(($e)) => Term.expandCDot? e | _ => Term.expandCDot? stx /-- Try to expand `·` notation. Recall that in Lean the `·` notation must be surrounded by parentheses. We may change this is the future, but right now, here are valid examples - `(· + 1)` - `(f ⟨·, 1⟩ ·)` - `(· + ·)` - `(f · a b)` -/ @[builtinMacro Lean.Parser.Term.paren] def expandParen : Macro | `(()) => `(Unit.unit) | `(($e : $type)) => do match (← expandCDot? e) with | some e => `(($e : $type)) | none => Macro.throwUnsupported | `(($e)) => return (← expandCDot? e).getD e | `(($e, $es,*)) => do let pairs ← mkPairs (#[e] ++ es) (← expandCDot? pairs).getD pairs | stx => if !stx[1][0].isMissing && stx[1][1].isMissing then -- parsed `(` and `term`, assume it's a basic parenthesis to get any elaboration output at all `(($(stx[1][0]))) else throw <| Macro.Exception.error stx "unexpected parentheses notation" @[builtinTermElab paren] def elabParen : TermElab := fun stx expectedType? => do match stx with | `(($e : $type)) => let type ← withSynthesize (mayPostpone := true) <| elabType type let e ← elabTerm e type ensureHasType type e | _ => throwUnsupportedSyntax @[builtinTermElab subst] def elabSubst : TermElab := fun stx expectedType? => do let expectedType ← tryPostponeIfHasMVars expectedType? "invalid `▸` notation" match stx with | `($heq ▸ $h) => do let mut heq ← elabTerm heq none let heqType ← inferType heq let heqType ← instantiateMVars heqType match (← Meta.matchEq? heqType) with | none => throwError "invalid `▸` notation, argument{indentExpr heq}\nhas type{indentExpr heqType}\nequality expected" | some (α, lhs, rhs) => let mut lhs := lhs let mut rhs := rhs let mkMotive (typeWithLooseBVar : Expr) := do withLocalDeclD (← mkFreshUserName `x) α fun x => do mkLambdaFVars #[x] $ typeWithLooseBVar.instantiate1 x let mut expectedAbst ← kabstract expectedType rhs unless expectedAbst.hasLooseBVars do expectedAbst ← kabstract expectedType lhs unless expectedAbst.hasLooseBVars do throwError "invalid `▸` notation, expected type{indentExpr expectedType}\ndoes contain equation left-hand-side nor right-hand-side{indentExpr heqType}" heq ← mkEqSymm heq (lhs, rhs) := (rhs, lhs) let hExpectedType := expectedAbst.instantiate1 lhs let h ← withRef h do let h ← elabTerm h hExpectedType try ensureHasType hExpectedType h catch ex => -- if `rhs` occurs in `hType`, we try to apply `heq` to `h` too let hType ← inferType h let hTypeAbst ← kabstract hType rhs unless hTypeAbst.hasLooseBVars do throw ex let hTypeNew := hTypeAbst.instantiate1 lhs unless (← isDefEq hExpectedType hTypeNew) do throw ex mkEqNDRec (← mkMotive hTypeAbst) h (← mkEqSymm heq) mkEqNDRec (← mkMotive expectedAbst) h heq | _ => throwUnsupportedSyntax @[builtinTermElab stateRefT] def elabStateRefT : TermElab := fun stx _ => do let σ ← elabType stx[1] let mut mStx := stx[2] if mStx.getKind == ``Lean.Parser.Term.macroDollarArg then mStx := mStx[1] let m ← elabTerm mStx (← mkArrow (mkSort levelOne) (mkSort levelOne)) let ω ← mkFreshExprMVar (mkSort levelOne) let stWorld ← mkAppM ``STWorld #[ω, m] discard <| mkInstMVar stWorld mkAppM ``StateRefT' #[ω, σ, m] @[builtinTermElab noindex] def elabNoindex : TermElab := fun stx expectedType? => do let e ← elabTerm stx[1] expectedType? return DiscrTree.mkNoindexAnnotation e end Lean.Elab.Term
d376710003dfc8c5bec64e29b6a3f008ec5f5d17
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/limits/constructions/finite_products_of_binary_products.lean
e53af1ae1650c429e8c2ff3fdb1bd618e2c64744
[ "Apache-2.0" ]
permissive
jjgarzella/mathlib
96a345378c4e0bf26cf604aed84f90329e4896a2
395d8716c3ad03747059d482090e2bb97db612c8
refs/heads/master
1,686,480,124,379
1,625,163,323,000
1,625,163,323,000
281,190,421
2
0
Apache-2.0
1,595,268,170,000
1,595,268,169,000
null
UTF-8
Lean
false
false
13,627
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.finite_products import category_theory.limits.shapes.binary_products import category_theory.limits.preserves.shapes.products import category_theory.limits.preserves.shapes.binary_products import category_theory.limits.shapes.pullbacks import category_theory.pempty import data.equiv.fin /-! # Constructing finite products from binary products and terminal. If a category has binary products and a terminal object then it has finite products. If a functor preserves binary products and the terminal object then it preserves finite products. # TODO Provide the dual results. Show the analogous results for functors which reflect or create (co)limits. -/ universes v u u' noncomputable theory open category_theory category_theory.category category_theory.limits namespace category_theory variables {J : Type v} [small_category J] variables {C : Type u} [category.{v} C] variables {D : Type u'} [category.{v} D] /-- Given `n+1` objects of `C`, a fan for the last `n` with point `c₁.X` and a binary fan on `c₁.X` and `f 0`, we can build a fan for all `n+1`. In `extend_fan_is_limit` we show that if the two given fans are limits, then this fan is also a limit. -/ @[simps {rhs_md := semireducible}] def extend_fan {n : ℕ} {f : ulift (fin (n+1)) → C} (c₁ : fan (λ (i : ulift (fin n)), f ⟨i.down.succ⟩)) (c₂ : binary_fan (f ⟨0⟩) c₁.X) : fan f := fan.mk c₂.X begin rintro ⟨i⟩, revert i, refine fin.cases _ _, { apply c₂.fst }, { intro i, apply c₂.snd ≫ c₁.π.app (ulift.up i) }, end /-- Show that if the two given fans in `extend_fan` are limits, then the constructed fan is also a limit. -/ def extend_fan_is_limit {n : ℕ} (f : ulift (fin (n+1)) → C) {c₁ : fan (λ (i : ulift (fin n)), f ⟨i.down.succ⟩)} {c₂ : binary_fan (f ⟨0⟩) c₁.X} (t₁ : is_limit c₁) (t₂ : is_limit c₂) : is_limit (extend_fan c₁ c₂) := { lift := λ s, begin apply (binary_fan.is_limit.lift' t₂ (s.π.app ⟨0⟩) _).1, apply t₁.lift ⟨_, discrete.nat_trans (λ i, s.π.app ⟨i.down.succ⟩)⟩ end, fac' := λ s, begin rintro ⟨j⟩, apply fin.induction_on j, { apply (binary_fan.is_limit.lift' t₂ _ _).2.1 }, { rintro i -, dsimp only [extend_fan_π_app], rw [fin.cases_succ, ← assoc, (binary_fan.is_limit.lift' t₂ _ _).2.2, t₁.fac], refl } end, uniq' := λ s m w, begin apply binary_fan.is_limit.hom_ext t₂, { rw (binary_fan.is_limit.lift' t₂ _ _).2.1, apply w ⟨0⟩ }, { rw (binary_fan.is_limit.lift' t₂ _ _).2.2, apply t₁.uniq ⟨_, _⟩, rintro ⟨j⟩, rw assoc, dsimp only [discrete.nat_trans_app], rw ← w ⟨j.succ⟩, dsimp only [extend_fan_π_app], rw fin.cases_succ } end } section variables [has_binary_products.{v} C] [has_terminal C] /-- If `C` has a terminal object and binary products, then it has a product for objects indexed by `ulift (fin n)`. This is a helper lemma for `has_finite_products_of_has_binary_and_terminal`, which is more general than this. -/ private lemma has_product_ulift_fin : Π (n : ℕ) (f : ulift (fin n) → C), has_product f | 0 := λ f, begin letI : has_limits_of_shape (discrete (ulift (fin 0))) C := has_limits_of_shape_of_equivalence (discrete.equivalence (equiv.ulift.trans fin_zero_equiv').symm), apply_instance, end | (n+1) := λ f, begin haveI := has_product_ulift_fin n, apply has_limit.mk ⟨_, extend_fan_is_limit f (limit.is_limit _) (limit.is_limit _)⟩, end /-- If `C` has a terminal object and binary products, then it has limits of shape `discrete (ulift (fin n))` for any `n : ℕ`. This is a helper lemma for `has_finite_products_of_has_binary_and_terminal`, which is more general than this. -/ private lemma has_limits_of_shape_ulift_fin (n : ℕ) : has_limits_of_shape (discrete (ulift (fin n))) C := { has_limit := λ K, begin letI := has_product_ulift_fin n K.obj, let : discrete.functor K.obj ≅ K := discrete.nat_iso (λ i, iso.refl _), apply has_limit_of_iso this, end } /-- If `C` has a terminal object and binary products, then it has finite products. -/ lemma has_finite_products_of_has_binary_and_terminal : has_finite_products C := ⟨λ J 𝒥₁ 𝒥₂, begin resetI, let e := fintype.equiv_fin J, apply has_limits_of_shape_of_equivalence (discrete.equivalence (e.trans equiv.ulift.symm)).symm, refine has_limits_of_shape_ulift_fin (fintype.card J), end⟩ end section preserves variables (F : C ⥤ D) variables [preserves_limits_of_shape (discrete walking_pair) F] variables [preserves_limits_of_shape (discrete pempty) F] variables [has_finite_products.{v} C] /-- If `F` preserves the terminal object and binary products, then it preserves products indexed by `ulift (fin n)` for any `n`. -/ noncomputable def preserves_fin_of_preserves_binary_and_terminal : Π (n : ℕ) (f : ulift (fin n) → C), preserves_limit (discrete.functor f) F | 0 := λ f, begin letI : preserves_limits_of_shape (discrete (ulift (fin 0))) F := preserves_limits_of_shape_of_equiv (discrete.equivalence (equiv.ulift.trans fin_zero_equiv').symm) _, apply_instance, end | (n+1) := begin haveI := preserves_fin_of_preserves_binary_and_terminal n, intro f, refine preserves_limit_of_preserves_limit_cone (extend_fan_is_limit f (limit.is_limit _) (limit.is_limit _)) _, apply (is_limit_map_cone_fan_mk_equiv _ _ _).symm _, let := extend_fan_is_limit (λ i, F.obj (f i)) (is_limit_of_has_product_of_preserves_limit F _) (is_limit_of_has_binary_product_of_preserves_limit F _ _), refine is_limit.of_iso_limit this _, apply cones.ext _ _, apply iso.refl _, rintro ⟨j⟩, apply fin.induction_on j, { apply (category.id_comp _).symm }, { rintro i -, dsimp only [extend_fan_π_app, iso.refl_hom, fan.mk_π_app], rw [fin.cases_succ, fin.cases_succ], change F.map _ ≫ _ = 𝟙 _ ≫ _, rw [id_comp, ←F.map_comp], refl } end /-- If `F` preserves the terminal object and binary products, then it preserves limits of shape `discrete (ulift (fin n))`. -/ def preserves_ulift_fin_of_preserves_binary_and_terminal (n : ℕ) : preserves_limits_of_shape (discrete (ulift (fin n))) F := { preserves_limit := λ K, begin let : discrete.functor K.obj ≅ K := discrete.nat_iso (λ i, iso.refl _), haveI := preserves_fin_of_preserves_binary_and_terminal F n K.obj, apply preserves_limit_of_iso_diagram F this, end } /-- If `F` preserves the terminal object and binary products then it preserves finite products. -/ def preserves_finite_products_of_preserves_binary_and_terminal (J : Type v) [fintype J] : preserves_limits_of_shape.{v} (discrete J) F := begin classical, let e := fintype.equiv_fin J, haveI := preserves_ulift_fin_of_preserves_binary_and_terminal F (fintype.card J), apply preserves_limits_of_shape_of_equiv (discrete.equivalence (e.trans equiv.ulift.symm)).symm, end end preserves /-- Given `n+1` objects of `C`, a cofan for the last `n` with point `c₁.X` and a binary cofan on `c₁.X` and `f 0`, we can build a cofan for all `n+1`. In `extend_cofan_is_colimit` we show that if the two given cofans are colimits, then this cofan is also a colimit. -/ @[simps {rhs_md := semireducible}] def extend_cofan {n : ℕ} {f : ulift (fin (n+1)) → C} (c₁ : cofan (λ (i : ulift (fin n)), f ⟨i.down.succ⟩)) (c₂ : binary_cofan (f ⟨0⟩) c₁.X) : cofan f := cofan.mk c₂.X begin rintro ⟨i⟩, revert i, refine fin.cases _ _, { apply c₂.inl }, { intro i, apply c₁.ι.app (ulift.up i) ≫ c₂.inr }, end /-- Show that if the two given cofans in `extend_cofan` are colimits, then the constructed cofan is also a colimit. -/ def extend_cofan_is_colimit {n : ℕ} (f : ulift (fin (n+1)) → C) {c₁ : cofan (λ (i : ulift (fin n)), f ⟨i.down.succ⟩)} {c₂ : binary_cofan (f ⟨0⟩) c₁.X} (t₁ : is_colimit c₁) (t₂ : is_colimit c₂) : is_colimit (extend_cofan c₁ c₂) := { desc := λ s, begin apply (binary_cofan.is_colimit.desc' t₂ (s.ι.app ⟨0⟩) _).1, apply t₁.desc ⟨_, discrete.nat_trans (λ i, s.ι.app ⟨i.down.succ⟩)⟩ end, fac' := λ s, begin rintro ⟨j⟩, apply fin.induction_on j, { apply (binary_cofan.is_colimit.desc' t₂ _ _).2.1 }, { rintro i -, dsimp only [extend_cofan_ι_app], rw [fin.cases_succ, assoc, (binary_cofan.is_colimit.desc' t₂ _ _).2.2, t₁.fac], refl } end, uniq' := λ s m w, begin apply binary_cofan.is_colimit.hom_ext t₂, { rw (binary_cofan.is_colimit.desc' t₂ _ _).2.1, apply w ⟨0⟩ }, { rw (binary_cofan.is_colimit.desc' t₂ _ _).2.2, apply t₁.uniq ⟨_, _⟩, rintro ⟨j⟩, dsimp only [discrete.nat_trans_app], rw ← w ⟨j.succ⟩, dsimp only [extend_cofan_ι_app], rw [fin.cases_succ, assoc], } end } section variables [has_binary_coproducts.{v} C] [has_initial C] /-- If `C` has an initial object and binary coproducts, then it has a coproduct for objects indexed by `ulift (fin n)`. This is a helper lemma for `has_cofinite_products_of_has_binary_and_terminal`, which is more general than this. -/ private lemma has_coproduct_ulift_fin : Π (n : ℕ) (f : ulift (fin n) → C), has_coproduct f | 0 := λ f, begin letI : has_colimits_of_shape (discrete (ulift (fin 0))) C := has_colimits_of_shape_of_equivalence (discrete.equivalence (equiv.ulift.trans fin_zero_equiv').symm), apply_instance, end | (n+1) := λ f, begin haveI := has_coproduct_ulift_fin n, apply has_colimit.mk ⟨_, extend_cofan_is_colimit f (colimit.is_colimit _) (colimit.is_colimit _)⟩, end /-- If `C` has an initial object and binary coproducts, then it has colimits of shape `discrete (ulift (fin n))` for any `n : ℕ`. This is a helper lemma for `has_cofinite_products_of_has_binary_and_terminal`, which is more general than this. -/ private lemma has_colimits_of_shape_ulift_fin (n : ℕ) : has_colimits_of_shape (discrete (ulift (fin n))) C := { has_colimit := λ K, begin letI := has_coproduct_ulift_fin n K.obj, let : K ≅ discrete.functor K.obj := discrete.nat_iso (λ i, iso.refl _), apply has_colimit_of_iso this, end } /-- If `C` has an initial object and binary coproducts, then it has finite coproducts. -/ lemma has_finite_coproducts_of_has_binary_and_terminal : has_finite_coproducts C := ⟨λ J 𝒥₁ 𝒥₂, begin resetI, let e := fintype.equiv_fin J, apply has_colimits_of_shape_of_equivalence (discrete.equivalence (e.trans equiv.ulift.symm)).symm, refine has_colimits_of_shape_ulift_fin (fintype.card J), end⟩ end section preserves variables (F : C ⥤ D) variables [preserves_colimits_of_shape (discrete walking_pair) F] variables [preserves_colimits_of_shape (discrete pempty) F] variables [has_finite_coproducts.{v} C] /-- If `F` preserves the initial object and binary coproducts, then it preserves products indexed by `ulift (fin n)` for any `n`. -/ noncomputable def preserves_fin_of_preserves_binary_and_initial : Π (n : ℕ) (f : ulift (fin n) → C), preserves_colimit (discrete.functor f) F | 0 := λ f, begin letI : preserves_colimits_of_shape (discrete (ulift (fin 0))) F := preserves_colimits_of_shape_of_equiv (discrete.equivalence (equiv.ulift.trans fin_zero_equiv').symm) _, apply_instance, end | (n+1) := begin haveI := preserves_fin_of_preserves_binary_and_initial n, intro f, refine preserves_colimit_of_preserves_colimit_cocone (extend_cofan_is_colimit f (colimit.is_colimit _) (colimit.is_colimit _)) _, apply (is_colimit_map_cocone_cofan_mk_equiv _ _ _).symm _, let := extend_cofan_is_colimit (λ i, F.obj (f i)) (is_colimit_of_has_coproduct_of_preserves_colimit F _) (is_colimit_of_has_binary_coproduct_of_preserves_colimit F _ _), refine is_colimit.of_iso_colimit this _, apply cocones.ext _ _, apply iso.refl _, rintro ⟨j⟩, apply fin.induction_on j, { apply category.comp_id }, { rintro i -, dsimp only [extend_cofan_ι_app, iso.refl_hom, cofan.mk_ι_app], rw [fin.cases_succ, fin.cases_succ], erw [comp_id, ←F.map_comp], refl, } end /-- If `F` preserves the initial object and binary coproducts, then it preserves colimits of shape `discrete (ulift (fin n))`. -/ def preserves_ulift_fin_of_preserves_binary_and_initial (n : ℕ) : preserves_colimits_of_shape (discrete (ulift (fin n))) F := { preserves_colimit := λ K, begin let : discrete.functor K.obj ≅ K := discrete.nat_iso (λ i, iso.refl _), haveI := preserves_fin_of_preserves_binary_and_initial F n K.obj, apply preserves_colimit_of_iso_diagram F this, end } /-- If `F` preserves the initial object and binary coproducts then it preserves finite products. -/ def preserves_finite_coproducts_of_preserves_binary_and_initial (J : Type v) [fintype J] : preserves_colimits_of_shape.{v} (discrete J) F := begin classical, let e := fintype.equiv_fin J, haveI := preserves_ulift_fin_of_preserves_binary_and_initial F (fintype.card J), apply preserves_colimits_of_shape_of_equiv (discrete.equivalence (e.trans equiv.ulift.symm)).symm, end end preserves end category_theory
af2d9f7fc2ab52ee9d1ac37d4d63da839810cad8
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/inner_product_space/basic.lean
784261db2756ae5c9bc99c982b8101af9cb8fb27
[ "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
103,627
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou, Sébastien Gouëzel, Frédéric Dupuis -/ import algebra.direct_sum.module import analysis.complex.basic import analysis.normed_space.bounded_linear_maps import analysis.convex.strict_convex_space import linear_algebra.bilinear_form import linear_algebra.sesquilinear_form /-! # Inner product space This file defines inner product spaces and proves the basic properties. We do not formally define Hilbert spaces, but they can be obtained using the pair of assumptions `[inner_product_space 𝕜 E] [complete_space E]`. An inner product space is a vector space endowed with an inner product. It generalizes the notion of dot product in `ℝ^n` and provides the means of defining the length of a vector and the angle between two vectors. In particular vectors `x` and `y` are orthogonal if their inner product equals zero. We define both the real and complex cases at the same time using the `is_R_or_C` typeclass. This file proves general results on inner product spaces. For the specific construction of an inner product structure on `n → 𝕜` for `𝕜 = ℝ` or `ℂ`, see `euclidean_space` in `analysis.inner_product_space.pi_L2`. ## Main results - We define the class `inner_product_space 𝕜 E` extending `normed_space 𝕜 E` with a number of basic properties, most notably the Cauchy-Schwarz inequality. Here `𝕜` is understood to be either `ℝ` or `ℂ`, through the `is_R_or_C` typeclass. - We show that the inner product is continuous, `continuous_inner`, and bundle it as the the continuous sesquilinear map `innerSL` (see also `innerₛₗ` for the non-continuous version). - We define `orthonormal`, a predicate on a function `v : ι → E`, and prove the existence of a maximal orthonormal set, `exists_maximal_orthonormal`. Bessel's inequality, `orthonormal.tsum_inner_products_le`, states that given an orthonormal set `v` and a vector `x`, the sum of the norm-squares of the inner products `⟪v i, x⟫` is no more than the norm-square of `x`. For the existence of orthonormal bases, Hilbert bases, etc., see the file `analysis.inner_product_space.projection`. - The `orthogonal_complement` of a submodule `K` is defined, and basic API established. Some of the more subtle results about the orthogonal complement are delayed to `analysis.inner_product_space.projection`. ## Notation We globally denote the real and complex inner products by `⟪·, ·⟫_ℝ` and `⟪·, ·⟫_ℂ` respectively. We also provide two notation namespaces: `real_inner_product_space`, `complex_inner_product_space`, which respectively introduce the plain notation `⟪·, ·⟫` for the real and complex inner product. The orthogonal complement of a submodule `K` is denoted by `Kᗮ`. ## Implementation notes We choose the convention that inner products are conjugate linear in the first argument and linear in the second. ## Tags inner product space, Hilbert space, norm ## References * [Clément & Martin, *The Lax-Milgram Theorem. A detailed proof to be formalized in Coq*] * [Clément & Martin, *A Coq formal proof of the Lax–Milgram theorem*] The Coq code is available at the following address: <http://www.lri.fr/~sboldo/elfic/index.html> -/ noncomputable theory open is_R_or_C real filter open_locale big_operators topological_space complex_conjugate variables {𝕜 E F : Type*} [is_R_or_C 𝕜] /-- Syntactic typeclass for types endowed with an inner product -/ class has_inner (𝕜 E : Type*) := (inner : E → E → 𝕜) export has_inner (inner) notation `⟪`x`, `y`⟫_ℝ` := @inner ℝ _ _ x y notation `⟪`x`, `y`⟫_ℂ` := @inner ℂ _ _ x y section notations localized "notation `⟪`x`, `y`⟫` := @inner ℝ _ _ x y" in real_inner_product_space localized "notation `⟪`x`, `y`⟫` := @inner ℂ _ _ x y" in complex_inner_product_space end notations /-- An inner product space is a vector space with an additional operation called inner product. The norm could be derived from the inner product, instead we require the existence of a norm and the fact that `∥x∥^2 = re ⟪x, x⟫` to be able to put instances on `𝕂` or product spaces. To construct a norm from an inner product, see `inner_product_space.of_core`. -/ class inner_product_space (𝕜 : Type*) (E : Type*) [is_R_or_C 𝕜] extends normed_group E, normed_space 𝕜 E, has_inner 𝕜 E := (norm_sq_eq_inner : ∀ (x : E), ∥x∥^2 = re (inner x x)) (conj_sym : ∀ x y, conj (inner y x) = inner x y) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y) attribute [nolint dangerous_instance] inner_product_space.to_normed_group -- note [is_R_or_C instance] /-! ### Constructing a normed space structure from an inner product In the definition of an inner product space, we require the existence of a norm, which is equal (but maybe not defeq) to the square root of the scalar product. This makes it possible to put an inner product space structure on spaces with a preexisting norm (for instance `ℝ`), with good properties. However, sometimes, one would like to define the norm starting only from a well-behaved scalar product. This is what we implement in this paragraph, starting from a structure `inner_product_space.core` stating that we have a nice scalar product. Our goal here is not to develop a whole theory with all the supporting API, as this will be done below for `inner_product_space`. Instead, we implement the bare minimum to go as directly as possible to the construction of the norm and the proof of the triangular inequality. Warning: Do not use this `core` structure if the space you are interested in already has a norm instance defined on it, otherwise this will create a second non-defeq norm instance! -/ /-- A structure requiring that a scalar product is positive definite and symmetric, from which one can construct an `inner_product_space` instance in `inner_product_space.of_core`. -/ @[nolint has_inhabited_instance] structure inner_product_space.core (𝕜 : Type*) (F : Type*) [is_R_or_C 𝕜] [add_comm_group F] [module 𝕜 F] := (inner : F → F → 𝕜) (conj_sym : ∀ x y, conj (inner y x) = inner x y) (nonneg_re : ∀ x, 0 ≤ re (inner x x)) (definite : ∀ x, inner x x = 0 → x = 0) (add_left : ∀ x y z, inner (x + y) z = inner x z + inner y z) (smul_left : ∀ x y r, inner (r • x) y = (conj r) * inner x y) /- We set `inner_product_space.core` to be a class as we will use it as such in the construction of the normed space structure that it produces. However, all the instances we will use will be local to this proof. -/ attribute [class] inner_product_space.core namespace inner_product_space.of_core variables [add_comm_group F] [module 𝕜 F] [c : inner_product_space.core 𝕜 F] include c local notation `⟪`x`, `y`⟫` := @inner 𝕜 F _ x y local notation `norm_sqK` := @is_R_or_C.norm_sq 𝕜 _ local notation `reK` := @is_R_or_C.re 𝕜 _ local notation `absK` := @is_R_or_C.abs 𝕜 _ local notation `ext_iff` := @is_R_or_C.ext_iff 𝕜 _ local postfix `†`:90 := star_ring_end _ /-- Inner product defined by the `inner_product_space.core` structure. -/ def to_has_inner : has_inner 𝕜 F := { inner := c.inner } local attribute [instance] to_has_inner /-- The norm squared function for `inner_product_space.core` structure. -/ def norm_sq (x : F) := reK ⟪x, x⟫ local notation `norm_sqF` := @norm_sq 𝕜 F _ _ _ _ lemma inner_conj_sym (x y : F) : ⟪y, x⟫† = ⟪x, y⟫ := c.conj_sym x y lemma inner_self_nonneg {x : F} : 0 ≤ re ⟪x, x⟫ := c.nonneg_re _ lemma inner_self_nonneg_im {x : F} : im ⟪x, x⟫ = 0 := by rw [← @of_real_inj 𝕜, im_eq_conj_sub]; simp [inner_conj_sym] lemma inner_self_im_zero {x : F} : im ⟪x, x⟫ = 0 := inner_self_nonneg_im lemma inner_add_left {x y z : F} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ := c.add_left _ _ _ lemma inner_add_right {x y z : F} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ := by rw [←inner_conj_sym, inner_add_left, ring_hom.map_add]; simp only [inner_conj_sym] lemma inner_norm_sq_eq_inner_self (x : F) : (norm_sqF x : 𝕜) = ⟪x, x⟫ := begin rw ext_iff, exact ⟨by simp only [of_real_re]; refl, by simp only [inner_self_nonneg_im, of_real_im]⟩ end lemma inner_re_symm {x y : F} : re ⟪x, y⟫ = re ⟪y, x⟫ := by rw [←inner_conj_sym, conj_re] lemma inner_im_symm {x y : F} : im ⟪x, y⟫ = -im ⟪y, x⟫ := by rw [←inner_conj_sym, conj_im] lemma inner_smul_left {x y : F} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ := c.smul_left _ _ _ lemma inner_smul_right {x y : F} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ := by rw [←inner_conj_sym, inner_smul_left]; simp only [conj_conj, inner_conj_sym, ring_hom.map_mul] lemma inner_zero_left {x : F} : ⟪0, x⟫ = 0 := by rw [←zero_smul 𝕜 (0 : F), inner_smul_left]; simp only [zero_mul, ring_hom.map_zero] lemma inner_zero_right {x : F} : ⟪x, 0⟫ = 0 := by rw [←inner_conj_sym, inner_zero_left]; simp only [ring_hom.map_zero] lemma inner_self_eq_zero {x : F} : ⟪x, x⟫ = 0 ↔ x = 0 := iff.intro (c.definite _) (by { rintro rfl, exact inner_zero_left }) lemma inner_self_re_to_K {x : F} : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by norm_num [ext_iff, inner_self_nonneg_im] lemma inner_abs_conj_sym {x y : F} : abs ⟪x, y⟫ = abs ⟪y, x⟫ := by rw [←inner_conj_sym, abs_conj] lemma inner_neg_left {x y : F} : ⟪-x, y⟫ = -⟪x, y⟫ := by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp } lemma inner_neg_right {x y : F} : ⟪x, -y⟫ = -⟪x, y⟫ := by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_hom.map_neg, inner_conj_sym] lemma inner_sub_left {x y z : F} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ := by { simp [sub_eq_add_neg, inner_add_left, inner_neg_left] } lemma inner_sub_right {x y z : F} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ := by { simp [sub_eq_add_neg, inner_add_right, inner_neg_right] } lemma inner_mul_conj_re_abs {x y : F} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) := by { rw [←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), } /-- Expand `inner (x + y) (x + y)` -/ lemma inner_add_add_self {x y : F} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_add_left, inner_add_right]; ring /- Expand `inner (x - y) (x - y)` -/ lemma inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_sub_left, inner_sub_right]; ring /-- **Cauchy–Schwarz inequality**. This proof follows "Proof 2" on Wikipedia. We need this for the `core` structure to prove the triangle inequality below when showing the core is a normed group. -/ lemma inner_mul_inner_self_le (x y : F) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ := begin by_cases hy : y = 0, { rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] }, { change y ≠ 0 at hy, have hy' : ⟪y, y⟫ ≠ 0 := λ h, by rw [inner_self_eq_zero] at h; exact hy h, set T := ⟪y, x⟫ / ⟪y, y⟫ with hT, have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm, have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm, have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫, { rw [mul_div_assoc], have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ := by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul], rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] }, have h₄ : ⟪y, y⟫ = re ⟪y, y⟫ := by simp only [inner_self_re_to_K], have h₅ : re ⟪y, y⟫ > 0, { refine lt_of_le_of_ne inner_self_nonneg _, intro H, apply hy', rw ext_iff, exact ⟨by simp only [H, zero_re'], by simp only [inner_self_nonneg_im, add_monoid_hom.map_zero]⟩ }, have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅, have hmain := calc 0 ≤ re ⟪x - T • y, x - T • y⟫ : inner_self_nonneg ... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫ : by simp only [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂, neg_mul, add_monoid_hom.map_add, mul_re, conj_im, add_monoid_hom.map_sub, mul_neg, conj_re, neg_neg] ... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫) : by simp only [inner_smul_left, inner_smul_right, mul_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫) : by field_simp [-mul_re, inner_conj_sym, hT, ring_hom.map_div, h₁, h₃] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫) : by rw ←mul_div_right_comm ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / re ⟪y, y⟫) : by conv_lhs { rw [h₄] } ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [div_re_of_real] ... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [inner_mul_conj_re_abs] ... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ : by rw is_R_or_C.abs_mul, have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith, have := (mul_le_mul_right h₅).mpr hmain', rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this } end /-- Norm constructed from a `inner_product_space.core` structure, defined to be the square root of the scalar product. -/ def to_has_norm : has_norm F := { norm := λ x, sqrt (re ⟪x, x⟫) } local attribute [instance] to_has_norm lemma norm_eq_sqrt_inner (x : F) : ∥x∥ = sqrt (re ⟪x, x⟫) := rfl lemma inner_self_eq_norm_mul_norm (x : F) : re ⟪x, x⟫ = ∥x∥ * ∥x∥ := by rw [norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫), sqrt_mul_self inner_self_nonneg] lemma sqrt_norm_sq_eq_norm {x : F} : sqrt (norm_sqF x) = ∥x∥ := rfl /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : F) : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := nonneg_le_nonneg_of_sq_le_sq (mul_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) begin have H : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = re ⟪y, y⟫ * re ⟪x, x⟫, { simp only [inner_self_eq_norm_mul_norm], ring, }, rw H, conv begin to_lhs, congr, rw [inner_abs_conj_sym], end, exact inner_mul_inner_self_le y x, end /-- Normed group structure constructed from an `inner_product_space.core` structure -/ def to_normed_group : normed_group F := normed_group.of_core F { norm_eq_zero_iff := assume x, begin split, { intro H, change sqrt (re ⟪x, x⟫) = 0 at H, rw [sqrt_eq_zero inner_self_nonneg] at H, apply (inner_self_eq_zero : ⟪x, x⟫ = 0 ↔ x = 0).mp, rw ext_iff, exact ⟨by simp [H], by simp [inner_self_im_zero]⟩ }, { rintro rfl, change sqrt (re ⟪0, 0⟫) = 0, simp only [sqrt_zero, inner_zero_right, add_monoid_hom.map_zero] } end, triangle := assume x y, begin have h₁ : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := abs_inner_le_norm _ _, have h₂ : re ⟪x, y⟫ ≤ abs ⟪x, y⟫ := re_le_abs _, have h₃ : re ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := by linarith, have h₄ : re ⟪y, x⟫ ≤ ∥x∥ * ∥y∥ := by rwa [←inner_conj_sym, conj_re], have : ∥x + y∥ * ∥x + y∥ ≤ (∥x∥ + ∥y∥) * (∥x∥ + ∥y∥), { simp [←inner_self_eq_norm_mul_norm, inner_add_add_self, add_mul, mul_add, mul_comm], linarith }, exact nonneg_le_nonneg_of_sq_le_sq (add_nonneg (sqrt_nonneg _) (sqrt_nonneg _)) this end, norm_neg := λ x, by simp only [norm, inner_neg_left, neg_neg, inner_neg_right] } local attribute [instance] to_normed_group /-- Normed space structure constructed from a `inner_product_space.core` structure -/ def to_normed_space : normed_space 𝕜 F := { norm_smul_le := assume r x, begin rw [norm_eq_sqrt_inner, inner_smul_left, inner_smul_right, ←mul_assoc], rw [conj_mul_eq_norm_sq_left, of_real_mul_re, sqrt_mul, ←inner_norm_sq_eq_inner_self, of_real_re], { simp [sqrt_norm_sq_eq_norm, is_R_or_C.sqrt_norm_sq_eq_norm] }, { exact norm_sq_nonneg r } end } end inner_product_space.of_core /-- Given a `inner_product_space.core` structure on a space, one can use it to turn the space into an inner product space, constructing the norm out of the inner product -/ def inner_product_space.of_core [add_comm_group F] [module 𝕜 F] (c : inner_product_space.core 𝕜 F) : inner_product_space 𝕜 F := begin letI : normed_group F := @inner_product_space.of_core.to_normed_group 𝕜 F _ _ _ c, letI : normed_space 𝕜 F := @inner_product_space.of_core.to_normed_space 𝕜 F _ _ _ c, exact { norm_sq_eq_inner := λ x, begin have h₁ : ∥x∥^2 = (sqrt (re (c.inner x x))) ^ 2 := rfl, have h₂ : 0 ≤ re (c.inner x x) := inner_product_space.of_core.inner_self_nonneg, simp [h₁, sq_sqrt, h₂], end, ..c } end /-! ### Properties of inner product spaces -/ variables [inner_product_space 𝕜 E] [inner_product_space ℝ F] variables [dec_E : decidable_eq E] local notation `⟪`x`, `y`⟫` := @inner 𝕜 _ _ x y local notation `IK` := @is_R_or_C.I 𝕜 _ local notation `absR` := has_abs.abs local notation `absK` := @is_R_or_C.abs 𝕜 _ local postfix `†`:90 := star_ring_end _ export inner_product_space (norm_sq_eq_inner) section basic_properties @[simp] lemma inner_conj_sym (x y : E) : ⟪y, x⟫† = ⟪x, y⟫ := inner_product_space.conj_sym _ _ lemma real_inner_comm (x y : F) : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := @inner_conj_sym ℝ _ _ _ x y lemma inner_eq_zero_sym {x y : E} : ⟪x, y⟫ = 0 ↔ ⟪y, x⟫ = 0 := ⟨λ h, by simp [←inner_conj_sym, h], λ h, by simp [←inner_conj_sym, h]⟩ @[simp] lemma inner_self_nonneg_im {x : E} : im ⟪x, x⟫ = 0 := by rw [← @of_real_inj 𝕜, im_eq_conj_sub]; simp lemma inner_self_im_zero {x : E} : im ⟪x, x⟫ = 0 := inner_self_nonneg_im lemma inner_add_left {x y z : E} : ⟪x + y, z⟫ = ⟪x, z⟫ + ⟪y, z⟫ := inner_product_space.add_left _ _ _ lemma inner_add_right {x y z : E} : ⟪x, y + z⟫ = ⟪x, y⟫ + ⟪x, z⟫ := by { rw [←inner_conj_sym, inner_add_left, ring_hom.map_add], simp only [inner_conj_sym] } lemma inner_re_symm {x y : E} : re ⟪x, y⟫ = re ⟪y, x⟫ := by rw [←inner_conj_sym, conj_re] lemma inner_im_symm {x y : E} : im ⟪x, y⟫ = -im ⟪y, x⟫ := by rw [←inner_conj_sym, conj_im] lemma inner_smul_left {x y : E} {r : 𝕜} : ⟪r • x, y⟫ = r† * ⟪x, y⟫ := inner_product_space.smul_left _ _ _ lemma real_inner_smul_left {x y : F} {r : ℝ} : ⟪r • x, y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_left lemma inner_smul_real_left {x y : E} {r : ℝ} : ⟪(r : 𝕜) • x, y⟫ = r • ⟪x, y⟫ := by { rw [inner_smul_left, conj_of_real, algebra.smul_def], refl } lemma inner_smul_right {x y : E} {r : 𝕜} : ⟪x, r • y⟫ = r * ⟪x, y⟫ := by rw [←inner_conj_sym, inner_smul_left, ring_hom.map_mul, conj_conj, inner_conj_sym] lemma real_inner_smul_right {x y : F} {r : ℝ} : ⟪x, r • y⟫_ℝ = r * ⟪x, y⟫_ℝ := inner_smul_right lemma inner_smul_real_right {x y : E} {r : ℝ} : ⟪x, (r : 𝕜) • y⟫ = r • ⟪x, y⟫ := by { rw [inner_smul_right, algebra.smul_def], refl } /-- The inner product as a sesquilinear form. -/ @[simps] def sesq_form_of_inner : E →ₗ[𝕜] E →ₗ⋆[𝕜] 𝕜 := linear_map.mk₂'ₛₗ (ring_hom.id 𝕜) (star_ring_end _) (λ x y, ⟪y, x⟫) (λ x y z, inner_add_right) (λ r x y, inner_smul_right) (λ x y z, inner_add_left) (λ r x y, inner_smul_left) /-- The real inner product as a bilinear form. -/ @[simps] def bilin_form_of_real_inner : bilin_form ℝ F := { bilin := inner, bilin_add_left := λ x y z, inner_add_left, bilin_smul_left := λ a x y, inner_smul_left, bilin_add_right := λ x y z, inner_add_right, bilin_smul_right := λ a x y, inner_smul_right } /-- An inner product with a sum on the left. -/ lemma sum_inner {ι : Type*} (s : finset ι) (f : ι → E) (x : E) : ⟪∑ i in s, f i, x⟫ = ∑ i in s, ⟪f i, x⟫ := (sesq_form_of_inner x).map_sum /-- An inner product with a sum on the right. -/ lemma inner_sum {ι : Type*} (s : finset ι) (f : ι → E) (x : E) : ⟪x, ∑ i in s, f i⟫ = ∑ i in s, ⟪x, f i⟫ := (linear_map.flip sesq_form_of_inner x).map_sum /-- An inner product with a sum on the left, `finsupp` version. -/ lemma finsupp.sum_inner {ι : Type*} (l : ι →₀ 𝕜) (v : ι → E) (x : E) : ⟪l.sum (λ (i : ι) (a : 𝕜), a • v i), x⟫ = l.sum (λ (i : ι) (a : 𝕜), (conj a) • ⟪v i, x⟫) := by { convert sum_inner l.support (λ a, l a • v a) x, simp [inner_smul_left, finsupp.sum] } /-- An inner product with a sum on the right, `finsupp` version. -/ lemma finsupp.inner_sum {ι : Type*} (l : ι →₀ 𝕜) (v : ι → E) (x : E) : ⟪x, l.sum (λ (i : ι) (a : 𝕜), a • v i)⟫ = l.sum (λ (i : ι) (a : 𝕜), a • ⟪x, v i⟫) := by { convert inner_sum l.support (λ a, l a • v a) x, simp [inner_smul_right, finsupp.sum] } lemma dfinsupp.sum_inner {ι : Type*} [dec : decidable_eq ι] {α : ι → Type*} [Π i, add_zero_class (α i)] [Π i (x : α i), decidable (x ≠ 0)] (f : Π i, α i → E) (l : Π₀ i, α i) (x : E) : ⟪l.sum f, x⟫ = l.sum (λ i a, ⟪f i a, x⟫) := by simp [dfinsupp.sum, sum_inner] {contextual := tt} lemma dfinsupp.inner_sum {ι : Type*} [dec : decidable_eq ι] {α : ι → Type*} [Π i, add_zero_class (α i)] [Π i (x : α i), decidable (x ≠ 0)] (f : Π i, α i → E) (l : Π₀ i, α i) (x : E) : ⟪x, l.sum f⟫ = l.sum (λ i a, ⟪x, f i a⟫) := by simp [dfinsupp.sum, inner_sum] {contextual := tt} @[simp] lemma inner_zero_left {x : E} : ⟪0, x⟫ = 0 := by rw [← zero_smul 𝕜 (0:E), inner_smul_left, ring_hom.map_zero, zero_mul] lemma inner_re_zero_left {x : E} : re ⟪0, x⟫ = 0 := by simp only [inner_zero_left, add_monoid_hom.map_zero] @[simp] lemma inner_zero_right {x : E} : ⟪x, 0⟫ = 0 := by rw [←inner_conj_sym, inner_zero_left, ring_hom.map_zero] lemma inner_re_zero_right {x : E} : re ⟪x, 0⟫ = 0 := by simp only [inner_zero_right, add_monoid_hom.map_zero] lemma inner_self_nonneg {x : E} : 0 ≤ re ⟪x, x⟫ := by rw [←norm_sq_eq_inner]; exact pow_nonneg (norm_nonneg x) 2 lemma real_inner_self_nonneg {x : F} : 0 ≤ ⟪x, x⟫_ℝ := @inner_self_nonneg ℝ F _ _ x @[simp] lemma inner_self_eq_zero {x : E} : ⟪x, x⟫ = 0 ↔ x = 0 := begin split, { intro h, have h₁ : re ⟪x, x⟫ = 0 := by rw is_R_or_C.ext_iff at h; simp [h.1], rw [←norm_sq_eq_inner x] at h₁, rw [←norm_eq_zero], exact pow_eq_zero h₁ }, { rintro rfl, exact inner_zero_left } end @[simp] lemma inner_self_nonpos {x : E} : re ⟪x, x⟫ ≤ 0 ↔ x = 0 := begin split, { intro h, rw ←inner_self_eq_zero, have H₁ : re ⟪x, x⟫ ≥ 0, exact inner_self_nonneg, have H₂ : re ⟪x, x⟫ = 0, exact le_antisymm h H₁, rw is_R_or_C.ext_iff, exact ⟨by simp [H₂], by simp [inner_self_nonneg_im]⟩ }, { rintro rfl, simp only [inner_zero_left, add_monoid_hom.map_zero] } end lemma real_inner_self_nonpos {x : F} : ⟪x, x⟫_ℝ ≤ 0 ↔ x = 0 := by { have h := @inner_self_nonpos ℝ F _ _ x, simpa using h } @[simp] lemma inner_self_re_to_K {x : E} : (re ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by rw is_R_or_C.ext_iff; exact ⟨by simp, by simp [inner_self_nonneg_im]⟩ lemma inner_self_eq_norm_sq_to_K (x : E) : ⟪x, x⟫ = (∥x∥ ^ 2 : 𝕜) := begin suffices : (is_R_or_C.re ⟪x, x⟫ : 𝕜) = ∥x∥ ^ 2, { simpa [inner_self_re_to_K] using this }, exact_mod_cast (norm_sq_eq_inner x).symm end lemma inner_self_re_abs {x : E} : re ⟪x, x⟫ = abs ⟪x, x⟫ := begin conv_rhs { rw [←inner_self_re_to_K] }, symmetry, exact is_R_or_C.abs_of_nonneg inner_self_nonneg, end lemma inner_self_abs_to_K {x : E} : (absK ⟪x, x⟫ : 𝕜) = ⟪x, x⟫ := by { rw [←inner_self_re_abs], exact inner_self_re_to_K } lemma real_inner_self_abs {x : F} : absR ⟪x, x⟫_ℝ = ⟪x, x⟫_ℝ := by { have h := @inner_self_abs_to_K ℝ F _ _ x, simpa using h } lemma inner_abs_conj_sym {x y : E} : abs ⟪x, y⟫ = abs ⟪y, x⟫ := by rw [←inner_conj_sym, abs_conj] @[simp] lemma inner_neg_left {x y : E} : ⟪-x, y⟫ = -⟪x, y⟫ := by { rw [← neg_one_smul 𝕜 x, inner_smul_left], simp } @[simp] lemma inner_neg_right {x y : E} : ⟪x, -y⟫ = -⟪x, y⟫ := by rw [←inner_conj_sym, inner_neg_left]; simp only [ring_hom.map_neg, inner_conj_sym] lemma inner_neg_neg {x y : E} : ⟪-x, -y⟫ = ⟪x, y⟫ := by simp @[simp] lemma inner_self_conj {x : E} : ⟪x, x⟫† = ⟪x, x⟫ := by rw [is_R_or_C.ext_iff]; exact ⟨by rw [conj_re], by rw [conj_im, inner_self_im_zero, neg_zero]⟩ lemma inner_sub_left {x y z : E} : ⟪x - y, z⟫ = ⟪x, z⟫ - ⟪y, z⟫ := by { simp [sub_eq_add_neg, inner_add_left] } lemma inner_sub_right {x y z : E} : ⟪x, y - z⟫ = ⟪x, y⟫ - ⟪x, z⟫ := by { simp [sub_eq_add_neg, inner_add_right] } lemma inner_mul_conj_re_abs {x y : E} : re (⟪x, y⟫ * ⟪y, x⟫) = abs (⟪x, y⟫ * ⟪y, x⟫) := by { rw [←inner_conj_sym, mul_comm], exact re_eq_abs_of_mul_conj (inner y x), } /-- Expand `⟪x + y, x + y⟫` -/ lemma inner_add_add_self {x y : E} : ⟪x + y, x + y⟫ = ⟪x, x⟫ + ⟪x, y⟫ + ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_add_left, inner_add_right]; ring /-- Expand `⟪x + y, x + y⟫_ℝ` -/ lemma real_inner_add_add_self {x y : F} : ⟪x + y, x + y⟫_ℝ = ⟪x, x⟫_ℝ + 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := begin have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, simp [inner_add_add_self, this], ring, end /- Expand `⟪x - y, x - y⟫` -/ lemma inner_sub_sub_self {x y : E} : ⟪x - y, x - y⟫ = ⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫ := by simp only [inner_sub_left, inner_sub_right]; ring /-- Expand `⟪x - y, x - y⟫_ℝ` -/ lemma real_inner_sub_sub_self {x y : F} : ⟪x - y, x - y⟫_ℝ = ⟪x, x⟫_ℝ - 2 * ⟪x, y⟫_ℝ + ⟪y, y⟫_ℝ := begin have : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, simp [inner_sub_sub_self, this], ring, end /-- Parallelogram law -/ lemma parallelogram_law {x y : E} : ⟪x + y, x + y⟫ + ⟪x - y, x - y⟫ = 2 * (⟪x, x⟫ + ⟪y, y⟫) := by simp [inner_add_add_self, inner_sub_sub_self, two_mul, sub_eq_add_neg, add_comm, add_left_comm] /-- Cauchy–Schwarz inequality. This proof follows "Proof 2" on Wikipedia. -/ lemma inner_mul_inner_self_le (x y : E) : abs ⟪x, y⟫ * abs ⟪y, x⟫ ≤ re ⟪x, x⟫ * re ⟪y, y⟫ := begin by_cases hy : y = 0, { rw [hy], simp only [is_R_or_C.abs_zero, inner_zero_left, mul_zero, add_monoid_hom.map_zero] }, { change y ≠ 0 at hy, have hy' : ⟪y, y⟫ ≠ 0 := λ h, by rw [inner_self_eq_zero] at h; exact hy h, set T := ⟪y, x⟫ / ⟪y, y⟫ with hT, have h₁ : re ⟪y, x⟫ = re ⟪x, y⟫ := inner_re_symm, have h₂ : im ⟪y, x⟫ = -im ⟪x, y⟫ := inner_im_symm, have h₃ : ⟪y, x⟫ * ⟪x, y⟫ * ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = ⟪y, x⟫ * ⟪x, y⟫ / ⟪y, y⟫, { rw [mul_div_assoc], have : ⟪y, y⟫ / (⟪y, y⟫ * ⟪y, y⟫) = 1 / ⟪y, y⟫ := by rw [div_mul_eq_div_mul_one_div, div_self hy', one_mul], rw [this, div_eq_mul_inv, one_mul, ←div_eq_mul_inv] }, have h₄ : ⟪y, y⟫ = re ⟪y, y⟫ := by simp, have h₅ : re ⟪y, y⟫ > 0, { refine lt_of_le_of_ne inner_self_nonneg _, intro H, apply hy', rw is_R_or_C.ext_iff, exact ⟨by simp only [H, zero_re'], by simp only [inner_self_nonneg_im, add_monoid_hom.map_zero]⟩ }, have h₆ : re ⟪y, y⟫ ≠ 0 := ne_of_gt h₅, have hmain := calc 0 ≤ re ⟪x - T • y, x - T • y⟫ : inner_self_nonneg ... = re ⟪x, x⟫ - re ⟪T • y, x⟫ - re ⟪x, T • y⟫ + re ⟪T • y, T • y⟫ : by simp only [inner_sub_sub_self, inner_smul_left, inner_smul_right, h₁, h₂, neg_mul, add_monoid_hom.map_add, conj_im, add_monoid_hom.map_sub, mul_neg, conj_re, neg_neg, mul_re] ... = re ⟪x, x⟫ - re (T† * ⟪y, x⟫) - re (T * ⟪x, y⟫) + re (T * T† * ⟪y, y⟫) : by simp only [inner_smul_left, inner_smul_right, mul_assoc] ... = re ⟪x, x⟫ - re (⟪x, y⟫ / ⟪y, y⟫ * ⟪y, x⟫) : by field_simp [-mul_re, hT, ring_hom.map_div, h₁, h₃, inner_conj_sym] ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / ⟪y, y⟫) : by rw ←mul_div_right_comm ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫ / re ⟪y, y⟫) : by conv_lhs { rw [h₄] } ... = re ⟪x, x⟫ - re (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [div_re_of_real] ... = re ⟪x, x⟫ - abs (⟪x, y⟫ * ⟪y, x⟫) / re ⟪y, y⟫ : by rw [inner_mul_conj_re_abs] ... = re ⟪x, x⟫ - abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ : by rw is_R_or_C.abs_mul, have hmain' : abs ⟪x, y⟫ * abs ⟪y, x⟫ / re ⟪y, y⟫ ≤ re ⟪x, x⟫ := by linarith, have := (mul_le_mul_right h₅).mpr hmain', rwa [div_mul_cancel (abs ⟪x, y⟫ * abs ⟪y, x⟫) h₆] at this } end /-- Cauchy–Schwarz inequality for real inner products. -/ lemma real_inner_mul_inner_self_le (x y : F) : ⟪x, y⟫_ℝ * ⟪x, y⟫_ℝ ≤ ⟪x, x⟫_ℝ * ⟪y, y⟫_ℝ := begin have h₁ : ⟪y, x⟫_ℝ = ⟪x, y⟫_ℝ := by rw [←inner_conj_sym]; refl, have h₂ := @inner_mul_inner_self_le ℝ F _ _ x y, dsimp at h₂, have h₃ := abs_mul_abs_self ⟪x, y⟫_ℝ, rw [h₁] at h₂, simpa [h₃] using h₂, end /-- A family of vectors is linearly independent if they are nonzero and orthogonal. -/ lemma linear_independent_of_ne_zero_of_inner_eq_zero {ι : Type*} {v : ι → E} (hz : ∀ i, v i ≠ 0) (ho : ∀ i j, i ≠ j → ⟪v i, v j⟫ = 0) : linear_independent 𝕜 v := begin rw linear_independent_iff', intros s g hg i hi, have h' : g i * inner (v i) (v i) = inner (v i) (∑ j in s, g j • v j), { rw inner_sum, symmetry, convert finset.sum_eq_single i _ _, { rw inner_smul_right }, { intros j hj hji, rw [inner_smul_right, ho i j hji.symm, mul_zero] }, { exact λ h, false.elim (h hi) } }, simpa [hg, hz] using h' end end basic_properties section orthonormal_sets variables {ι : Type*} [dec_ι : decidable_eq ι] (𝕜) include 𝕜 /-- An orthonormal set of vectors in an `inner_product_space` -/ def orthonormal (v : ι → E) : Prop := (∀ i, ∥v i∥ = 1) ∧ (∀ {i j}, i ≠ j → ⟪v i, v j⟫ = 0) omit 𝕜 variables {𝕜} include dec_ι /-- `if ... then ... else` characterization of an indexed set of vectors being orthonormal. (Inner product equals Kronecker delta.) -/ lemma orthonormal_iff_ite {v : ι → E} : orthonormal 𝕜 v ↔ ∀ i j, ⟪v i, v j⟫ = if i = j then (1:𝕜) else (0:𝕜) := begin split, { intros hv i j, split_ifs, { simp [h, inner_self_eq_norm_sq_to_K, hv.1] }, { exact hv.2 h } }, { intros h, split, { intros i, have h' : ∥v i∥ ^ 2 = 1 ^ 2 := by simp [norm_sq_eq_inner, h i i], have h₁ : 0 ≤ ∥v i∥ := norm_nonneg _, have h₂ : (0:ℝ) ≤ 1 := zero_le_one, rwa sq_eq_sq h₁ h₂ at h' }, { intros i j hij, simpa [hij] using h i j } } end omit dec_ι include dec_E /-- `if ... then ... else` characterization of a set of vectors being orthonormal. (Inner product equals Kronecker delta.) -/ theorem orthonormal_subtype_iff_ite {s : set E} : orthonormal 𝕜 (coe : s → E) ↔ (∀ v ∈ s, ∀ w ∈ s, ⟪v, w⟫ = if v = w then 1 else 0) := begin rw orthonormal_iff_ite, split, { intros h v hv w hw, convert h ⟨v, hv⟩ ⟨w, hw⟩ using 1, simp }, { rintros h ⟨v, hv⟩ ⟨w, hw⟩, convert h v hv w hw using 1, simp } end omit dec_E /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_right_finsupp {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι →₀ 𝕜) (i : ι) : ⟪v i, finsupp.total ι E 𝕜 v l⟫ = l i := by classical; simp [finsupp.total_apply, finsupp.inner_sum, orthonormal_iff_ite.mp hv] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_right_sum {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) {s : finset ι} {i : ι} (hi : i ∈ s) : ⟪v i, ∑ i in s, (l i) • (v i)⟫ = l i := by classical; simp [inner_sum, inner_smul_right, orthonormal_iff_ite.mp hv, hi] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_right_fintype [fintype ι] {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) (i : ι) : ⟪v i, ∑ i : ι, (l i) • (v i)⟫ = l i := hv.inner_right_sum l (finset.mem_univ _) /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_left_finsupp {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι →₀ 𝕜) (i : ι) : ⟪finsupp.total ι E 𝕜 v l, v i⟫ = conj (l i) := by rw [← inner_conj_sym, hv.inner_right_finsupp] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_left_sum {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) {s : finset ι} {i : ι} (hi : i ∈ s) : ⟪∑ i in s, (l i) • (v i), v i⟫ = conj (l i) := by classical; simp [sum_inner, inner_smul_left, orthonormal_iff_ite.mp hv, hi] /-- The inner product of a linear combination of a set of orthonormal vectors with one of those vectors picks out the coefficient of that vector. -/ lemma orthonormal.inner_left_fintype [fintype ι] {v : ι → E} (hv : orthonormal 𝕜 v) (l : ι → 𝕜) (i : ι) : ⟪∑ i : ι, (l i) • (v i), v i⟫ = conj (l i) := hv.inner_left_sum l (finset.mem_univ _) /-- The inner product of two linear combinations of a set of orthonormal vectors, expressed as a sum over the first `finsupp`. -/ lemma orthonormal.inner_finsupp_eq_sum_left {v : ι → E} (hv : orthonormal 𝕜 v) (l₁ l₂ : ι →₀ 𝕜) : ⟪finsupp.total ι E 𝕜 v l₁, finsupp.total ι E 𝕜 v l₂⟫ = l₁.sum (λ i y, conj y * l₂ i) := by simp [finsupp.total_apply _ l₁, finsupp.sum_inner, hv.inner_right_finsupp] /-- The inner product of two linear combinations of a set of orthonormal vectors, expressed as a sum over the second `finsupp`. -/ lemma orthonormal.inner_finsupp_eq_sum_right {v : ι → E} (hv : orthonormal 𝕜 v) (l₁ l₂ : ι →₀ 𝕜) : ⟪finsupp.total ι E 𝕜 v l₁, finsupp.total ι E 𝕜 v l₂⟫ = l₂.sum (λ i y, conj (l₁ i) * y) := by simp [finsupp.total_apply _ l₂, finsupp.inner_sum, hv.inner_left_finsupp, mul_comm] /-- The inner product of two linear combinations of a set of orthonormal vectors, expressed as a sum. -/ lemma orthonormal.inner_sum {v : ι → E} (hv : orthonormal 𝕜 v) (l₁ l₂ : ι → 𝕜) (s : finset ι) : ⟪∑ i in s, l₁ i • v i, ∑ i in s, l₂ i • v i⟫ = ∑ i in s, conj (l₁ i) * l₂ i := begin simp_rw [sum_inner, inner_smul_left], refine finset.sum_congr rfl (λ i hi, _), rw hv.inner_right_sum l₂ hi end /-- The double sum of weighted inner products of pairs of vectors from an orthonormal sequence is the sum of the weights. -/ lemma orthonormal.inner_left_right_finset {s : finset ι} {v : ι → E} (hv : orthonormal 𝕜 v) {a : ι → ι → 𝕜} : ∑ i in s, ∑ j in s, (a i j) • ⟪v j, v i⟫ = ∑ k in s, a k k := by classical; simp [orthonormal_iff_ite.mp hv, finset.sum_ite_of_true] /-- An orthonormal set is linearly independent. -/ lemma orthonormal.linear_independent {v : ι → E} (hv : orthonormal 𝕜 v) : linear_independent 𝕜 v := begin rw linear_independent_iff, intros l hl, ext i, have key : ⟪v i, finsupp.total ι E 𝕜 v l⟫ = ⟪v i, 0⟫ := by rw hl, simpa [hv.inner_right_finsupp] using key end /-- A subfamily of an orthonormal family (i.e., a composition with an injective map) is an orthonormal family. -/ lemma orthonormal.comp {ι' : Type*} {v : ι → E} (hv : orthonormal 𝕜 v) (f : ι' → ι) (hf : function.injective f) : orthonormal 𝕜 (v ∘ f) := begin classical, rw orthonormal_iff_ite at ⊢ hv, intros i j, convert hv (f i) (f j) using 1, simp [hf.eq_iff] end /-- A linear combination of some subset of an orthonormal set is orthogonal to other members of the set. -/ lemma orthonormal.inner_finsupp_eq_zero {v : ι → E} (hv : orthonormal 𝕜 v) {s : set ι} {i : ι} (hi : i ∉ s) {l : ι →₀ 𝕜} (hl : l ∈ finsupp.supported 𝕜 𝕜 s) : ⟪finsupp.total ι E 𝕜 v l, v i⟫ = 0 := begin rw finsupp.mem_supported' at hl, simp [hv.inner_left_finsupp, hl i hi], end /-- Given an orthonormal family, a second family of vectors is orthonormal if every vector equals the corresponding vector in the original family or its negation. -/ lemma orthonormal.orthonormal_of_forall_eq_or_eq_neg {v w : ι → E} (hv : orthonormal 𝕜 v) (hw : ∀ i, w i = v i ∨ w i = -(v i)) : orthonormal 𝕜 w := begin classical, rw orthonormal_iff_ite at *, intros i j, cases hw i with hi hi; cases hw j with hj hj; split_ifs with h; simpa [hi, hj, h] using hv i j end /- The material that follows, culminating in the existence of a maximal orthonormal subset, is adapted from the corresponding development of the theory of linearly independents sets. See `exists_linear_independent` in particular. -/ variables (𝕜 E) lemma orthonormal_empty : orthonormal 𝕜 (λ x, x : (∅ : set E) → E) := by classical; simp [orthonormal_subtype_iff_ite] variables {𝕜 E} lemma orthonormal_Union_of_directed {η : Type*} {s : η → set E} (hs : directed (⊆) s) (h : ∀ i, orthonormal 𝕜 (λ x, x : s i → E)) : orthonormal 𝕜 (λ x, x : (⋃ i, s i) → E) := begin classical, rw orthonormal_subtype_iff_ite, rintros x ⟨_, ⟨i, rfl⟩, hxi⟩ y ⟨_, ⟨j, rfl⟩, hyj⟩, obtain ⟨k, hik, hjk⟩ := hs i j, have h_orth : orthonormal 𝕜 (λ x, x : (s k) → E) := h k, rw orthonormal_subtype_iff_ite at h_orth, exact h_orth x (hik hxi) y (hjk hyj) end lemma orthonormal_sUnion_of_directed {s : set (set E)} (hs : directed_on (⊆) s) (h : ∀ a ∈ s, orthonormal 𝕜 (λ x, x : (a : set E) → E)) : orthonormal 𝕜 (λ x, x : (⋃₀ s) → E) := by rw set.sUnion_eq_Union; exact orthonormal_Union_of_directed hs.directed_coe (by simpa using h) /-- Given an orthonormal set `v` of vectors in `E`, there exists a maximal orthonormal set containing it. -/ lemma exists_maximal_orthonormal {s : set E} (hs : orthonormal 𝕜 (coe : s → E)) : ∃ w ⊇ s, orthonormal 𝕜 (coe : w → E) ∧ ∀ u ⊇ w, orthonormal 𝕜 (coe : u → E) → u = w := begin obtain ⟨b, bi, sb, h⟩ := zorn_subset_nonempty {b | orthonormal 𝕜 (coe : b → E)} _ _ hs, { refine ⟨b, sb, bi, _⟩, exact λ u hus hu, h u hu hus }, { refine λ c hc cc c0, ⟨⋃₀ c, _, _⟩, { exact orthonormal_sUnion_of_directed cc.directed_on (λ x xc, hc xc) }, { exact λ _, set.subset_sUnion_of_mem } } end lemma orthonormal.ne_zero {v : ι → E} (hv : orthonormal 𝕜 v) (i : ι) : v i ≠ 0 := begin have : ∥v i∥ ≠ 0, { rw hv.1 i, norm_num }, simpa using this end open finite_dimensional /-- A family of orthonormal vectors with the correct cardinality forms a basis. -/ def basis_of_orthonormal_of_card_eq_finrank [fintype ι] [nonempty ι] {v : ι → E} (hv : orthonormal 𝕜 v) (card_eq : fintype.card ι = finrank 𝕜 E) : basis ι 𝕜 E := basis_of_linear_independent_of_card_eq_finrank hv.linear_independent card_eq @[simp] lemma coe_basis_of_orthonormal_of_card_eq_finrank [fintype ι] [nonempty ι] {v : ι → E} (hv : orthonormal 𝕜 v) (card_eq : fintype.card ι = finrank 𝕜 E) : (basis_of_orthonormal_of_card_eq_finrank hv card_eq : ι → E) = v := coe_basis_of_linear_independent_of_card_eq_finrank _ _ end orthonormal_sets section norm lemma norm_eq_sqrt_inner (x : E) : ∥x∥ = sqrt (re ⟪x, x⟫) := begin have h₁ : ∥x∥^2 = re ⟪x, x⟫ := norm_sq_eq_inner x, have h₂ := congr_arg sqrt h₁, simpa using h₂, end lemma norm_eq_sqrt_real_inner (x : F) : ∥x∥ = sqrt ⟪x, x⟫_ℝ := by { have h := @norm_eq_sqrt_inner ℝ F _ _ x, simpa using h } lemma inner_self_eq_norm_mul_norm (x : E) : re ⟪x, x⟫ = ∥x∥ * ∥x∥ := by rw [norm_eq_sqrt_inner, ←sqrt_mul inner_self_nonneg (re ⟪x, x⟫), sqrt_mul_self inner_self_nonneg] lemma inner_self_eq_norm_sq (x : E) : re ⟪x, x⟫ = ∥x∥^2 := by rw [pow_two, inner_self_eq_norm_mul_norm] lemma real_inner_self_eq_norm_mul_norm (x : F) : ⟪x, x⟫_ℝ = ∥x∥ * ∥x∥ := by { have h := @inner_self_eq_norm_mul_norm ℝ F _ _ x, simpa using h } lemma real_inner_self_eq_norm_sq (x : F) : ⟪x, x⟫_ℝ = ∥x∥^2 := by rw [pow_two, real_inner_self_eq_norm_mul_norm] /-- Expand the square -/ lemma norm_add_sq {x y : E} : ∥x + y∥^2 = ∥x∥^2 + 2 * (re ⟪x, y⟫) + ∥y∥^2 := begin repeat {rw [sq, ←inner_self_eq_norm_mul_norm]}, rw [inner_add_add_self, two_mul], simp only [add_assoc, add_left_inj, add_right_inj, add_monoid_hom.map_add], rw [←inner_conj_sym, conj_re], end alias norm_add_sq ← norm_add_pow_two /-- Expand the square -/ lemma norm_add_sq_real {x y : F} : ∥x + y∥^2 = ∥x∥^2 + 2 * ⟪x, y⟫_ℝ + ∥y∥^2 := by { have h := @norm_add_sq ℝ F _ _, simpa using h } alias norm_add_sq_real ← norm_add_pow_two_real /-- Expand the square -/ lemma norm_add_mul_self {x y : E} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * (re ⟪x, y⟫) + ∥y∥ * ∥y∥ := by { repeat {rw [← sq]}, exact norm_add_sq } /-- Expand the square -/ lemma norm_add_mul_self_real {x y : F} : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + 2 * ⟪x, y⟫_ℝ + ∥y∥ * ∥y∥ := by { have h := @norm_add_mul_self ℝ F _ _, simpa using h } /-- Expand the square -/ lemma norm_sub_sq {x y : E} : ∥x - y∥^2 = ∥x∥^2 - 2 * (re ⟪x, y⟫) + ∥y∥^2 := begin repeat {rw [sq, ←inner_self_eq_norm_mul_norm]}, rw [inner_sub_sub_self], calc re (⟪x, x⟫ - ⟪x, y⟫ - ⟪y, x⟫ + ⟪y, y⟫) = re ⟪x, x⟫ - re ⟪x, y⟫ - re ⟪y, x⟫ + re ⟪y, y⟫ : by simp ... = -re ⟪y, x⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by ring ... = -re (⟪x, y⟫†) - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw [inner_conj_sym] ... = -re ⟪x, y⟫ - re ⟪x, y⟫ + re ⟪x, x⟫ + re ⟪y, y⟫ : by rw [conj_re] ... = re ⟪x, x⟫ - 2*re ⟪x, y⟫ + re ⟪y, y⟫ : by ring end alias norm_sub_sq ← norm_sub_pow_two /-- Expand the square -/ lemma norm_sub_sq_real {x y : F} : ∥x - y∥^2 = ∥x∥^2 - 2 * ⟪x, y⟫_ℝ + ∥y∥^2 := norm_sub_sq alias norm_sub_sq_real ← norm_sub_pow_two_real /-- Expand the square -/ lemma norm_sub_mul_self {x y : E} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * re ⟪x, y⟫ + ∥y∥ * ∥y∥ := by { repeat {rw [← sq]}, exact norm_sub_sq } /-- Expand the square -/ lemma norm_sub_mul_self_real {x y : F} : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ - 2 * ⟪x, y⟫_ℝ + ∥y∥ * ∥y∥ := by { have h := @norm_sub_mul_self ℝ F _ _, simpa using h } /-- Cauchy–Schwarz inequality with norm -/ lemma abs_inner_le_norm (x y : E) : abs ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := nonneg_le_nonneg_of_sq_le_sq (mul_nonneg (norm_nonneg _) (norm_nonneg _)) begin have : ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥) = (re ⟪x, x⟫) * (re ⟪y, y⟫), simp only [inner_self_eq_norm_mul_norm], ring, rw this, conv_lhs { congr, skip, rw [inner_abs_conj_sym] }, exact inner_mul_inner_self_le _ _ end lemma norm_inner_le_norm (x y : E) : ∥⟪x, y⟫∥ ≤ ∥x∥ * ∥y∥ := (is_R_or_C.norm_eq_abs _).le.trans (abs_inner_le_norm x y) lemma nnnorm_inner_le_nnnorm (x y : E) : ∥⟪x, y⟫∥₊ ≤ ∥x∥₊ * ∥y∥₊ := norm_inner_le_norm x y lemma re_inner_le_norm (x y : E) : re ⟪x, y⟫ ≤ ∥x∥ * ∥y∥ := le_trans (re_le_abs (inner x y)) (abs_inner_le_norm x y) /-- Cauchy–Schwarz inequality with norm -/ lemma abs_real_inner_le_norm (x y : F) : absR ⟪x, y⟫_ℝ ≤ ∥x∥ * ∥y∥ := by { have h := @abs_inner_le_norm ℝ F _ _ x y, simpa using h } /-- Cauchy–Schwarz inequality with norm -/ lemma real_inner_le_norm (x y : F) : ⟪x, y⟫_ℝ ≤ ∥x∥ * ∥y∥ := le_trans (le_abs_self _) (abs_real_inner_le_norm _ _) include 𝕜 lemma parallelogram_law_with_norm (x y : E) : ∥x + y∥ * ∥x + y∥ + ∥x - y∥ * ∥x - y∥ = 2 * (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥) := begin simp only [← inner_self_eq_norm_mul_norm], rw [← re.map_add, parallelogram_law, two_mul, two_mul], simp only [re.map_add], end lemma parallelogram_law_with_nnnorm (x y : E) : ∥x + y∥₊ * ∥x + y∥₊ + ∥x - y∥₊ * ∥x - y∥₊ = 2 * (∥x∥₊ * ∥x∥₊ + ∥y∥₊ * ∥y∥₊) := subtype.ext $ parallelogram_law_with_norm x y omit 𝕜 /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : E) : re ⟪x, y⟫ = (∥x + y∥ * ∥x + y∥ - ∥x∥ * ∥x∥ - ∥y∥ * ∥y∥) / 2 := by { rw norm_add_mul_self, ring } /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : E) : re ⟪x, y⟫ = (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ - ∥x - y∥ * ∥x - y∥) / 2 := by { rw [norm_sub_mul_self], ring } /-- Polarization identity: The real part of the inner product, in terms of the norm. -/ lemma re_inner_eq_norm_add_mul_self_sub_norm_sub_mul_self_div_four (x y : E) : re ⟪x, y⟫ = (∥x + y∥ * ∥x + y∥ - ∥x - y∥ * ∥x - y∥) / 4 := by { rw [norm_add_mul_self, norm_sub_mul_self], ring } /-- Polarization identity: The imaginary part of the inner product, in terms of the norm. -/ lemma im_inner_eq_norm_sub_I_smul_mul_self_sub_norm_add_I_smul_mul_self_div_four (x y : E) : im ⟪x, y⟫ = (∥x - IK • y∥ * ∥x - IK • y∥ - ∥x + IK • y∥ * ∥x + IK • y∥) / 4 := by { simp only [norm_add_mul_self, norm_sub_mul_self, inner_smul_right, I_mul_re], ring } /-- Polarization identity: The inner product, in terms of the norm. -/ lemma inner_eq_sum_norm_sq_div_four (x y : E) : ⟪x, y⟫ = (∥x + y∥ ^ 2 - ∥x - y∥ ^ 2 + (∥x - IK • y∥ ^ 2 - ∥x + IK • y∥ ^ 2) * IK) / 4 := begin rw [← re_add_im ⟪x, y⟫, re_inner_eq_norm_add_mul_self_sub_norm_sub_mul_self_div_four, im_inner_eq_norm_sub_I_smul_mul_self_sub_norm_add_I_smul_mul_self_div_four], push_cast, simp only [sq, ← mul_div_right_comm, ← add_div] end section complex variables {V : Type*} [inner_product_space ℂ V] /-- A complex polarization identity, with a linear map -/ lemma inner_map_polarization (T : V →ₗ[ℂ] V) (x y : V): ⟪ T y, x ⟫_ℂ = (⟪T (x + y) , x + y⟫_ℂ - ⟪T (x - y) , x - y⟫_ℂ + complex.I * ⟪T (x + complex.I • y) , x + complex.I • y⟫_ℂ - complex.I * ⟪T (x - complex.I • y), x - complex.I • y ⟫_ℂ) / 4 := begin simp only [map_add, map_sub, inner_add_left, inner_add_right, linear_map.map_smul, inner_smul_left, inner_smul_right, complex.conj_I, ←pow_two, complex.I_sq, inner_sub_left, inner_sub_right, mul_add, ←mul_assoc, mul_neg, neg_neg, sub_neg_eq_add, one_mul, neg_one_mul, mul_sub, sub_sub], ring, end lemma inner_map_polarization' (T : V →ₗ[ℂ] V) (x y : V): ⟪ T x, y ⟫_ℂ = (⟪T (x + y) , x + y⟫_ℂ - ⟪T (x - y) , x - y⟫_ℂ - complex.I * ⟪T (x + complex.I • y) , x + complex.I • y⟫_ℂ + complex.I * ⟪T (x - complex.I • y), x - complex.I • y ⟫_ℂ) / 4 := begin simp only [map_add, map_sub, inner_add_left, inner_add_right, linear_map.map_smul, inner_smul_left, inner_smul_right, complex.conj_I, ←pow_two, complex.I_sq, inner_sub_left, inner_sub_right, mul_add, ←mul_assoc, mul_neg, neg_neg, sub_neg_eq_add, one_mul, neg_one_mul, mul_sub, sub_sub], ring, end /-- If `⟪T x, x⟫_ℂ = 0` for all x, then T = 0. -/ lemma inner_map_self_eq_zero (T : V →ₗ[ℂ] V) : (∀ (x : V), ⟪T x, x⟫_ℂ = 0) ↔ T = 0 := begin split, { intro hT, ext x, simp only [linear_map.zero_apply, ← inner_self_eq_zero, inner_map_polarization, hT], norm_num }, { rintro rfl x, simp only [linear_map.zero_apply, inner_zero_left] } end end complex section variables {ι : Type*} {ι' : Type*} {ι'' : Type*} variables {E' : Type*} [inner_product_space 𝕜 E'] variables {E'' : Type*} [inner_product_space 𝕜 E''] /-- A linear isometry preserves the inner product. -/ @[simp] lemma linear_isometry.inner_map_map (f : E →ₗᵢ[𝕜] E') (x y : E) : ⟪f x, f y⟫ = ⟪x, y⟫ := by simp [inner_eq_sum_norm_sq_div_four, ← f.norm_map] /-- A linear isometric equivalence preserves the inner product. -/ @[simp] lemma linear_isometry_equiv.inner_map_map (f : E ≃ₗᵢ[𝕜] E') (x y : E) : ⟪f x, f y⟫ = ⟪x, y⟫ := f.to_linear_isometry.inner_map_map x y /-- A linear map that preserves the inner product is a linear isometry. -/ def linear_map.isometry_of_inner (f : E →ₗ[𝕜] E') (h : ∀ x y, ⟪f x, f y⟫ = ⟪x, y⟫) : E →ₗᵢ[𝕜] E' := ⟨f, λ x, by simp only [norm_eq_sqrt_inner, h]⟩ @[simp] lemma linear_map.coe_isometry_of_inner (f : E →ₗ[𝕜] E') (h) : ⇑(f.isometry_of_inner h) = f := rfl @[simp] lemma linear_map.isometry_of_inner_to_linear_map (f : E →ₗ[𝕜] E') (h) : (f.isometry_of_inner h).to_linear_map = f := rfl /-- A linear equivalence that preserves the inner product is a linear isometric equivalence. -/ def linear_equiv.isometry_of_inner (f : E ≃ₗ[𝕜] E') (h : ∀ x y, ⟪f x, f y⟫ = ⟪x, y⟫) : E ≃ₗᵢ[𝕜] E' := ⟨f, ((f : E →ₗ[𝕜] E').isometry_of_inner h).norm_map⟩ @[simp] lemma linear_equiv.coe_isometry_of_inner (f : E ≃ₗ[𝕜] E') (h) : ⇑(f.isometry_of_inner h) = f := rfl @[simp] lemma linear_equiv.isometry_of_inner_to_linear_equiv (f : E ≃ₗ[𝕜] E') (h) : (f.isometry_of_inner h).to_linear_equiv = f := rfl /-- A linear isometry preserves the property of being orthonormal. -/ lemma orthonormal.comp_linear_isometry {v : ι → E} (hv : orthonormal 𝕜 v) (f : E →ₗᵢ[𝕜] E') : orthonormal 𝕜 (f ∘ v) := begin classical, simp_rw [orthonormal_iff_ite, linear_isometry.inner_map_map, ←orthonormal_iff_ite], exact hv end /-- A linear isometric equivalence preserves the property of being orthonormal. -/ lemma orthonormal.comp_linear_isometry_equiv {v : ι → E} (hv : orthonormal 𝕜 v) (f : E ≃ₗᵢ[𝕜] E') : orthonormal 𝕜 (f ∘ v) := hv.comp_linear_isometry f.to_linear_isometry /-- A linear isometric equivalence, applied with `basis.map`, preserves the property of being orthonormal. --/ lemma orthonormal.map_linear_isometry_equiv {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (f : E ≃ₗᵢ[𝕜] E') : orthonormal 𝕜 (v.map f.to_linear_equiv) := hv.comp_linear_isometry_equiv f /-- A linear map that sends an orthonormal basis to orthonormal vectors is a linear isometry. -/ def linear_map.isometry_of_orthonormal (f : E →ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : E →ₗᵢ[𝕜] E' := f.isometry_of_inner $ λ x y, by rw [←v.total_repr x, ←v.total_repr y, finsupp.apply_total, finsupp.apply_total, hv.inner_finsupp_eq_sum_left, hf.inner_finsupp_eq_sum_left] @[simp] lemma linear_map.coe_isometry_of_orthonormal (f : E →ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : ⇑(f.isometry_of_orthonormal hv hf) = f := rfl @[simp] lemma linear_map.isometry_of_orthonormal_to_linear_map (f : E →ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : (f.isometry_of_orthonormal hv hf).to_linear_map = f := rfl /-- A linear equivalence that sends an orthonormal basis to orthonormal vectors is a linear isometric equivalence. -/ def linear_equiv.isometry_of_orthonormal (f : E ≃ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : E ≃ₗᵢ[𝕜] E' := f.isometry_of_inner $ λ x y, begin rw ←linear_equiv.coe_coe at hf, rw [←v.total_repr x, ←v.total_repr y, ←linear_equiv.coe_coe, finsupp.apply_total, finsupp.apply_total, hv.inner_finsupp_eq_sum_left, hf.inner_finsupp_eq_sum_left] end @[simp] lemma linear_equiv.coe_isometry_of_orthonormal (f : E ≃ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : ⇑(f.isometry_of_orthonormal hv hf) = f := rfl @[simp] lemma linear_equiv.isometry_of_orthonormal_to_linear_equiv (f : E ≃ₗ[𝕜] E') {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) (hf : orthonormal 𝕜 (f ∘ v)) : (f.isometry_of_orthonormal hv hf).to_linear_equiv = f := rfl /-- A linear isometric equivalence that sends an orthonormal basis to a given orthonormal basis. -/ def orthonormal.equiv {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') : E ≃ₗᵢ[𝕜] E' := (v.equiv v' e).isometry_of_orthonormal hv begin have h : (v.equiv v' e) ∘ v = v' ∘ e, { ext i, simp }, rw h, exact hv'.comp _ e.injective end @[simp] lemma orthonormal.equiv_to_linear_equiv {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') : (hv.equiv hv' e).to_linear_equiv = v.equiv v' e := rfl @[simp] lemma orthonormal.equiv_apply {ι' : Type*} {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') (i : ι) : hv.equiv hv' e (v i) = v' (e i) := basis.equiv_apply _ _ _ _ @[simp] lemma orthonormal.equiv_refl {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) : hv.equiv hv (equiv.refl ι) = linear_isometry_equiv.refl 𝕜 E := v.ext_linear_isometry_equiv $ λ i, by simp @[simp] lemma orthonormal.equiv_symm {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') : (hv.equiv hv' e).symm = hv'.equiv hv e.symm := v'.ext_linear_isometry_equiv $ λ i, (hv.equiv hv' e).injective (by simp) @[simp] lemma orthonormal.equiv_trans {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') {v'' : basis ι'' 𝕜 E''} (hv'' : orthonormal 𝕜 v'') (e' : ι' ≃ ι'') : (hv.equiv hv' e).trans (hv'.equiv hv'' e') = hv.equiv hv'' (e.trans e') := v.ext_linear_isometry_equiv $ λ i, by simp lemma orthonormal.map_equiv {v : basis ι 𝕜 E} (hv : orthonormal 𝕜 v) {v' : basis ι' 𝕜 E'} (hv' : orthonormal 𝕜 v') (e : ι ≃ ι') : v.map ((hv.equiv hv' e).to_linear_equiv) = v'.reindex e.symm := v.map_equiv _ _ end /-- Polarization identity: The real inner product, in terms of the norm. -/ lemma real_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two (x y : F) : ⟪x, y⟫_ℝ = (∥x + y∥ * ∥x + y∥ - ∥x∥ * ∥x∥ - ∥y∥ * ∥y∥) / 2 := re_to_real.symm.trans $ re_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two x y /-- Polarization identity: The real inner product, in terms of the norm. -/ lemma real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two (x y : F) : ⟪x, y⟫_ℝ = (∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ - ∥x - y∥ * ∥x - y∥) / 2 := re_to_real.symm.trans $ re_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two x y /-- Pythagorean theorem, if-and-only-if vector inner product form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero (x y : F) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ = 0 := begin rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero], norm_num end /-- Pythagorean theorem, vector inner product form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_of_inner_eq_zero (x y : E) (h : ⟪x, y⟫ = 0) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := begin rw [norm_add_mul_self, add_right_cancel_iff, add_right_eq_self, mul_eq_zero], apply or.inr, simp only [h, zero_re'], end /-- Pythagorean theorem, vector inner product form. -/ lemma norm_add_sq_eq_norm_sq_add_norm_sq_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) : ∥x + y∥ * ∥x + y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_add_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero x y).2 h /-- Pythagorean theorem, subtracting vectors, if-and-only-if vector inner product form. -/ lemma norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero (x y : F) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ = 0 := begin rw [norm_sub_mul_self, add_right_cancel_iff, sub_eq_add_neg, add_right_eq_self, neg_eq_zero, mul_eq_zero], norm_num end /-- Pythagorean theorem, subtracting vectors, vector inner product form. -/ lemma norm_sub_sq_eq_norm_sq_add_norm_sq_real {x y : F} (h : ⟪x, y⟫_ℝ = 0) : ∥x - y∥ * ∥x - y∥ = ∥x∥ * ∥x∥ + ∥y∥ * ∥y∥ := (norm_sub_sq_eq_norm_sq_add_norm_sq_iff_real_inner_eq_zero x y).2 h /-- The sum and difference of two vectors are orthogonal if and only if they have the same norm. -/ lemma real_inner_add_sub_eq_zero_iff (x y : F) : ⟪x + y, x - y⟫_ℝ = 0 ↔ ∥x∥ = ∥y∥ := begin conv_rhs { rw ←mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _) }, simp only [←inner_self_eq_norm_mul_norm, inner_add_left, inner_sub_right, real_inner_comm y x, sub_eq_zero, re_to_real], split, { intro h, rw [add_comm] at h, linarith }, { intro h, linarith } end /-- Given two orthogonal vectors, their sum and difference have equal norms. -/ lemma norm_sub_eq_norm_add {v w : E} (h : ⟪v, w⟫ = 0) : ∥w - v∥ = ∥w + v∥ := begin rw ←mul_self_inj_of_nonneg (norm_nonneg _) (norm_nonneg _), simp [h, ←inner_self_eq_norm_mul_norm, inner_add_left, inner_add_right, inner_sub_left, inner_sub_right, inner_re_symm] end /-- The real inner product of two vectors, divided by the product of their norms, has absolute value at most 1. -/ lemma abs_real_inner_div_norm_mul_norm_le_one (x y : F) : absR (⟪x, y⟫_ℝ / (∥x∥ * ∥y∥)) ≤ 1 := begin rw _root_.abs_div, by_cases h : 0 = absR (∥x∥ * ∥y∥), { rw [←h, div_zero], norm_num }, { change 0 ≠ absR (∥x∥ * ∥y∥) at h, rw div_le_iff' (lt_of_le_of_ne (ge_iff_le.mp (_root_.abs_nonneg (∥x∥ * ∥y∥))) h), convert abs_real_inner_le_norm x y using 1, rw [_root_.abs_mul, _root_.abs_of_nonneg (norm_nonneg x), _root_.abs_of_nonneg (norm_nonneg y), mul_one] } end /-- The inner product of a vector with a multiple of itself. -/ lemma real_inner_smul_self_left (x : F) (r : ℝ) : ⟪r • x, x⟫_ℝ = r * (∥x∥ * ∥x∥) := by rw [real_inner_smul_left, ←real_inner_self_eq_norm_mul_norm] /-- The inner product of a vector with a multiple of itself. -/ lemma real_inner_smul_self_right (x : F) (r : ℝ) : ⟪x, r • x⟫_ℝ = r * (∥x∥ * ∥x∥) := by rw [inner_smul_right, ←real_inner_self_eq_norm_mul_norm] /-- The inner product of a nonzero vector with a nonzero multiple of itself, divided by the product of their norms, has absolute value 1. -/ lemma abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : E} {r : 𝕜} (hx : x ≠ 0) (hr : r ≠ 0) : abs ⟪x, r • x⟫ / (∥x∥ * ∥r • x∥) = 1 := begin have hx' : ∥x∥ ≠ 0 := by simp [norm_eq_zero, hx], have hr' : abs r ≠ 0 := by simp [is_R_or_C.abs_eq_zero, hr], rw [inner_smul_right, is_R_or_C.abs_mul, ←inner_self_re_abs, inner_self_eq_norm_mul_norm, norm_smul], rw [is_R_or_C.norm_eq_abs, ←mul_assoc, ←div_div, mul_div_cancel _ hx', ←div_div, mul_comm, mul_div_cancel _ hr', div_self hx'], end /-- The inner product of a nonzero vector with a nonzero multiple of itself, divided by the product of their norms, has absolute value 1. -/ lemma abs_real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : r ≠ 0) : absR ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = 1 := begin rw ← abs_to_real, exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr end /-- The inner product of a nonzero vector with a positive multiple of itself, divided by the product of their norms, has value 1. -/ lemma real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : 0 < r) : ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = 1 := begin rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (absR r), mul_assoc, _root_.abs_of_nonneg (le_of_lt hr), div_self], exact mul_ne_zero (ne_of_gt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of a nonzero vector with a negative multiple of itself, divided by the product of their norms, has value -1. -/ lemma real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul {x : F} {r : ℝ} (hx : x ≠ 0) (hr : r < 0) : ⟪x, r • x⟫_ℝ / (∥x∥ * ∥r • x∥) = -1 := begin rw [real_inner_smul_self_right, norm_smul, real.norm_eq_abs, ←mul_assoc ∥x∥, mul_comm _ (absR r), mul_assoc, abs_of_neg hr, neg_mul, div_neg_eq_neg_div, div_self], exact mul_ne_zero (ne_of_lt hr) (λ h, hx (norm_eq_zero.1 (eq_zero_of_mul_self_eq_zero h))) end /-- The inner product of two vectors, divided by the product of their norms, has absolute value 1 if and only if they are nonzero and one is a multiple of the other. One form of equality case for Cauchy-Schwarz. -/ lemma abs_inner_div_norm_mul_norm_eq_one_iff (x y : E) : abs (⟪x, y⟫ / (∥x∥ * ∥y∥)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x) := begin split, { intro h, have hx0 : x ≠ 0, { intro hx0, rw [hx0, inner_zero_left, zero_div] at h, norm_num at h, }, refine and.intro hx0 _, set r := ⟪x, y⟫ / (∥x∥ * ∥x∥) with hr, use r, set t := y - r • x with ht, have ht0 : ⟪x, t⟫ = 0, { rw [ht, inner_sub_right, inner_smul_right, hr], norm_cast, rw [←inner_self_eq_norm_mul_norm, inner_self_re_to_K, div_mul_cancel _ (λ h, hx0 (inner_self_eq_zero.1 h)), sub_self] }, replace h : ∥r • x∥ / ∥t + r • x∥ = 1, { rw [←sub_add_cancel y (r • x), ←ht, inner_add_right, ht0, zero_add, inner_smul_right, is_R_or_C.abs_div, is_R_or_C.abs_mul, ←inner_self_re_abs, inner_self_eq_norm_mul_norm] at h, norm_cast at h, rwa [_root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm, ←mul_assoc, mul_comm, mul_div_mul_left _ _ (λ h, hx0 (norm_eq_zero.1 h)), ←is_R_or_C.norm_eq_abs, ←norm_smul] at h }, have hr0 : r ≠ 0, { intro hr0, rw [hr0, zero_smul, norm_zero, zero_div] at h, norm_num at h }, refine and.intro hr0 _, have h2 : ∥r • x∥ ^ 2 = ∥t + r • x∥ ^ 2, { rw [eq_of_div_eq_one h] }, replace h2 : ⟪r • x, r • x⟫ = ⟪t, t⟫ + ⟪t, r • x⟫ + ⟪r • x, t⟫ + ⟪r • x, r • x⟫, { rw [sq, sq, ←inner_self_eq_norm_mul_norm, ←inner_self_eq_norm_mul_norm ] at h2, have h2' := congr_arg (λ z : ℝ, (z : 𝕜)) h2, simp_rw [inner_self_re_to_K, inner_add_add_self] at h2', exact h2' }, conv at h2 in ⟪r • x, t⟫ { rw [inner_smul_left, ht0, mul_zero] }, symmetry' at h2, have h₁ : ⟪t, r • x⟫ = 0 := by { rw [inner_smul_right, ←inner_conj_sym, ht0], simp }, rw [add_zero, h₁, add_left_eq_self, add_zero, inner_self_eq_zero] at h2, rw h2 at ht, exact eq_of_sub_eq_zero ht.symm }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw [hy, is_R_or_C.abs_div], norm_cast, rw [_root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm], exact abs_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_ne_zero_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has absolute value 1 if and only if they are nonzero and one is a multiple of the other. One form of equality case for Cauchy-Schwarz. -/ lemma abs_real_inner_div_norm_mul_norm_eq_one_iff (x y : F) : absR (⟪x, y⟫_ℝ / (∥x∥ * ∥y∥)) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r ≠ 0 ∧ y = r • x) := begin have := @abs_inner_div_norm_mul_norm_eq_one_iff ℝ F _ _ x y, simpa [coe_real_eq_id] using this, end /-- If the inner product of two vectors is equal to the product of their norms, then the two vectors are multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `inner_eq_norm_mul_iff`, which takes the stronger hypothesis `⟪x, y⟫ = ∥x∥ * ∥y∥`. -/ lemma abs_inner_eq_norm_iff (x y : E) (hx0 : x ≠ 0) (hy0 : y ≠ 0): abs ⟪x, y⟫ = ∥x∥ * ∥y∥ ↔ ∃ (r : 𝕜), r ≠ 0 ∧ y = r • x := begin have hx0' : ∥x∥ ≠ 0 := by simp [norm_eq_zero, hx0], have hy0' : ∥y∥ ≠ 0 := by simp [norm_eq_zero, hy0], have hxy0 : ∥x∥ * ∥y∥ ≠ 0 := by simp [hx0', hy0'], have h₁ : abs ⟪x, y⟫ = ∥x∥ * ∥y∥ ↔ abs (⟪x, y⟫ / (∥x∥ * ∥y∥)) = 1, { refine ⟨_ ,_⟩, { intro h, norm_cast, rw [is_R_or_C.abs_div, h, abs_of_real, _root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm], exact div_self hxy0 }, { intro h, norm_cast at h, rwa [is_R_or_C.abs_div, abs_of_real, _root_.abs_mul, abs_norm_eq_norm, abs_norm_eq_norm, div_eq_one_iff_eq hxy0] at h } }, rw [h₁, abs_inner_div_norm_mul_norm_eq_one_iff x y], simp [hx0] end /-- The inner product of two vectors, divided by the product of their norms, has value 1 if and only if they are nonzero and one is a positive multiple of the other. -/ lemma real_inner_div_norm_mul_norm_eq_one_iff (x y : F) : ⟪x, y⟫_ℝ / (∥x∥ * ∥y∥) = 1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), 0 < r ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun absR at ha, norm_num at ha, rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrneg, rw hy at h, rw real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx (lt_of_le_of_ne (le_of_not_lt hrneg) hr) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx hr } end /-- The inner product of two vectors, divided by the product of their norms, has value -1 if and only if they are nonzero and one is a negative multiple of the other. -/ lemma real_inner_div_norm_mul_norm_eq_neg_one_iff (x y : F) : ⟪x, y⟫_ℝ / (∥x∥ * ∥y∥) = -1 ↔ (x ≠ 0 ∧ ∃ (r : ℝ), r < 0 ∧ y = r • x) := begin split, { intro h, have ha := h, apply_fun absR at ha, norm_num at ha, rcases (abs_real_inner_div_norm_mul_norm_eq_one_iff x y).1 ha with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, use [hx, r], refine and.intro _ hy, by_contradiction hrpos, rw hy at h, rw real_inner_div_norm_mul_norm_eq_one_of_ne_zero_of_pos_mul hx (lt_of_le_of_ne (le_of_not_lt hrpos) hr.symm) at h, norm_num at h }, { intro h, rcases h with ⟨hx, ⟨r, ⟨hr, hy⟩⟩⟩, rw hy, exact real_inner_div_norm_mul_norm_eq_neg_one_of_ne_zero_of_neg_mul hx hr } end /-- If the inner product of two vectors is equal to the product of their norms (i.e., `⟪x, y⟫ = ∥x∥ * ∥y∥`), then the two vectors are nonnegative real multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `abs_inner_eq_norm_iff`, which takes the weaker hypothesis `abs ⟪x, y⟫ = ∥x∥ * ∥y∥`. -/ lemma inner_eq_norm_mul_iff {x y : E} : ⟪x, y⟫ = (∥x∥ : 𝕜) * ∥y∥ ↔ (∥y∥ : 𝕜) • x = (∥x∥ : 𝕜) • y := begin by_cases h : (x = 0 ∨ y = 0), -- WLOG `x` and `y` are nonzero { cases h; simp [h] }, calc ⟪x, y⟫ = (∥x∥ : 𝕜) * ∥y∥ ↔ ∥x∥ * ∥y∥ = re ⟪x, y⟫ : begin norm_cast, split, { intros h', simp [h'] }, { have cauchy_schwarz := abs_inner_le_norm x y, intros h', rw h' at ⊢ cauchy_schwarz, rwa re_eq_self_of_le } end ... ↔ 2 * ∥x∥ * ∥y∥ * (∥x∥ * ∥y∥ - re ⟪x, y⟫) = 0 : by simp [h, show (2:ℝ) ≠ 0, by norm_num, sub_eq_zero] ... ↔ ∥(∥y∥:𝕜) • x - (∥x∥:𝕜) • y∥ * ∥(∥y∥:𝕜) • x - (∥x∥:𝕜) • y∥ = 0 : begin simp only [norm_sub_mul_self, inner_smul_left, inner_smul_right, norm_smul, conj_of_real, is_R_or_C.norm_eq_abs, abs_of_real, of_real_im, of_real_re, mul_re, abs_norm_eq_norm], refine eq.congr _ rfl, ring end ... ↔ (∥y∥ : 𝕜) • x = (∥x∥ : 𝕜) • y : by simp [norm_sub_eq_zero_iff] end /-- If the inner product of two vectors is equal to the product of their norms (i.e., `⟪x, y⟫ = ∥x∥ * ∥y∥`), then the two vectors are nonnegative real multiples of each other. One form of the equality case for Cauchy-Schwarz. Compare `abs_inner_eq_norm_iff`, which takes the weaker hypothesis `abs ⟪x, y⟫ = ∥x∥ * ∥y∥`. -/ lemma inner_eq_norm_mul_iff_real {x y : F} : ⟪x, y⟫_ℝ = ∥x∥ * ∥y∥ ↔ ∥y∥ • x = ∥x∥ • y := inner_eq_norm_mul_iff /-- An inner product space is strictly convex. We do not register this as an instance for an inner space over `𝕜`, `is_R_or_C 𝕜`, because there is no order of the typeclass argument that does not lead to a search of `[is_scalar_tower ℝ ?m E]` with unknown `?m`. -/ instance inner_product_space.strict_convex_space : strict_convex_space ℝ F := begin refine strict_convex_space.of_norm_add (λ x y h, _), rw [same_ray_iff_norm_smul_eq, eq_comm, ← inner_eq_norm_mul_iff_real, real_inner_eq_norm_add_mul_self_sub_norm_mul_self_sub_norm_mul_self_div_two, h, add_mul_self_eq, sub_sub, add_sub_add_right_eq_sub, add_sub_cancel', mul_assoc, mul_div_cancel_left], exact _root_.two_ne_zero end /-- If the inner product of two unit vectors is `1`, then the two vectors are equal. One form of the equality case for Cauchy-Schwarz. -/ lemma inner_eq_norm_mul_iff_of_norm_one {x y : E} (hx : ∥x∥ = 1) (hy : ∥y∥ = 1) : ⟪x, y⟫ = 1 ↔ x = y := by { convert inner_eq_norm_mul_iff using 2; simp [hx, hy] } lemma inner_lt_norm_mul_iff_real {x y : F} : ⟪x, y⟫_ℝ < ∥x∥ * ∥y∥ ↔ ∥y∥ • x ≠ ∥x∥ • y := calc ⟪x, y⟫_ℝ < ∥x∥ * ∥y∥ ↔ ⟪x, y⟫_ℝ ≠ ∥x∥ * ∥y∥ : ⟨ne_of_lt, lt_of_le_of_ne (real_inner_le_norm _ _)⟩ ... ↔ ∥y∥ • x ≠ ∥x∥ • y : not_congr inner_eq_norm_mul_iff_real /-- If the inner product of two unit vectors is strictly less than `1`, then the two vectors are distinct. One form of the equality case for Cauchy-Schwarz. -/ lemma inner_lt_one_iff_real_of_norm_one {x y : F} (hx : ∥x∥ = 1) (hy : ∥y∥ = 1) : ⟪x, y⟫_ℝ < 1 ↔ x ≠ y := by { convert inner_lt_norm_mul_iff_real; simp [hx, hy] } /-- The inner product of two weighted sums, where the weights in each sum add to 0, in terms of the norms of pairwise differences. -/ lemma inner_sum_smul_sum_smul_of_sum_eq_zero {ι₁ : Type*} {s₁ : finset ι₁} {w₁ : ι₁ → ℝ} (v₁ : ι₁ → F) (h₁ : ∑ i in s₁, w₁ i = 0) {ι₂ : Type*} {s₂ : finset ι₂} {w₂ : ι₂ → ℝ} (v₂ : ι₂ → F) (h₂ : ∑ i in s₂, w₂ i = 0) : ⟪(∑ i₁ in s₁, w₁ i₁ • v₁ i₁), (∑ i₂ in s₂, w₂ i₂ • v₂ i₂)⟫_ℝ = (-∑ i₁ in s₁, ∑ i₂ in s₂, w₁ i₁ * w₂ i₂ * (∥v₁ i₁ - v₂ i₂∥ * ∥v₁ i₁ - v₂ i₂∥)) / 2 := by simp_rw [sum_inner, inner_sum, real_inner_smul_left, real_inner_smul_right, real_inner_eq_norm_mul_self_add_norm_mul_self_sub_norm_sub_mul_self_div_two, ←div_sub_div_same, ←div_add_div_same, mul_sub_left_distrib, left_distrib, finset.sum_sub_distrib, finset.sum_add_distrib, ←finset.mul_sum, ←finset.sum_mul, h₁, h₂, zero_mul, mul_zero, finset.sum_const_zero, zero_add, zero_sub, finset.mul_sum, neg_div, finset.sum_div, mul_div_assoc, mul_assoc] /-- The inner product as a sesquilinear map. -/ def innerₛₗ : E →ₗ⋆[𝕜] E →ₗ[𝕜] 𝕜 := linear_map.mk₂'ₛₗ _ _ (λ v w, ⟪v, w⟫) (λ _ _ _, inner_add_left) (λ _ _ _, inner_smul_left) (λ _ _ _, inner_add_right) (λ _ _ _, inner_smul_right) @[simp] lemma innerₛₗ_apply_coe (v : E) : (innerₛₗ v : E → 𝕜) = λ w, ⟪v, w⟫ := rfl @[simp] lemma innerₛₗ_apply (v w : E) : innerₛₗ v w = ⟪v, w⟫ := rfl /-- The inner product as a continuous sesquilinear map. Note that `to_dual_map` (resp. `to_dual`) in `inner_product_space.dual` is a version of this given as a linear isometry (resp. linear isometric equivalence). -/ def innerSL : E →L⋆[𝕜] E →L[𝕜] 𝕜 := linear_map.mk_continuous₂ innerₛₗ 1 (λ x y, by simp only [norm_inner_le_norm, one_mul, innerₛₗ_apply]) @[simp] lemma innerSL_apply_coe (v : E) : (innerSL v : E → 𝕜) = λ w, ⟪v, w⟫ := rfl @[simp] lemma innerSL_apply (v w : E) : innerSL v w = ⟪v, w⟫ := rfl /-- `innerSL` is an isometry. Note that the associated `linear_isometry` is defined in `inner_product_space.dual` as `to_dual_map`. -/ @[simp] lemma innerSL_apply_norm {x : E} : ∥(innerSL x : E →L[𝕜] 𝕜)∥ = ∥x∥ := begin refine le_antisymm ((innerSL x).op_norm_le_bound (norm_nonneg _) (λ y, norm_inner_le_norm _ _)) _, cases eq_or_lt_of_le (norm_nonneg x) with h h, { have : x = 0 := norm_eq_zero.mp (eq.symm h), simp [this] }, { refine (mul_le_mul_right h).mp _, calc ∥x∥ * ∥x∥ = ∥x∥ ^ 2 : by ring ... = re ⟪x, x⟫ : norm_sq_eq_inner _ ... ≤ abs ⟪x, x⟫ : re_le_abs _ ... = ∥innerSL x x∥ : by { rw [←is_R_or_C.norm_eq_abs], refl } ... ≤ ∥innerSL x∥ * ∥x∥ : (innerSL x).le_op_norm _ } end /-- The inner product as a continuous sesquilinear map, with the two arguments flipped. -/ def innerSL_flip : E →L[𝕜] E →L⋆[𝕜] 𝕜 := @continuous_linear_map.flipₗᵢ' 𝕜 𝕜 𝕜 E E 𝕜 _ _ _ _ _ _ _ _ _ (ring_hom.id 𝕜) (star_ring_end 𝕜) _ _ innerSL @[simp] lemma innerSL_flip_apply {x y : E} : innerSL_flip x y = ⟪y, x⟫ := rfl namespace continuous_linear_map variables {E' : Type*} [inner_product_space 𝕜 E'] /-- Given `f : E →L[𝕜] E'`, construct the continuous sesquilinear form `λ x y, ⟪x, A y⟫`, given as a continuous linear map. -/ def to_sesq_form : (E →L[𝕜] E') →L[𝕜] E' →L⋆[𝕜] E →L[𝕜] 𝕜 := ↑((continuous_linear_map.flipₗᵢ' E E' 𝕜 (star_ring_end 𝕜) (ring_hom.id 𝕜)).to_continuous_linear_equiv) ∘L (continuous_linear_map.compSL E E' (E' →L⋆[𝕜] 𝕜) (ring_hom.id 𝕜) (ring_hom.id 𝕜) innerSL_flip) @[simp] lemma to_sesq_form_apply_coe (f : E →L[𝕜] E') (x : E') : to_sesq_form f x = (innerSL x).comp f := rfl lemma to_sesq_form_apply_norm_le {f : E →L[𝕜] E'} {v : E'} : ∥to_sesq_form f v∥ ≤ ∥f∥ * ∥v∥ := begin refine op_norm_le_bound _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) _, intro x, have h₁ : ∥f x∥ ≤ ∥f∥ * ∥x∥ := le_op_norm _ _, have h₂ := @norm_inner_le_norm 𝕜 E' _ _ v (f x), calc ∥⟪v, f x⟫∥ ≤ ∥v∥ * ∥f x∥ : h₂ ... ≤ ∥v∥ * (∥f∥ * ∥x∥) : mul_le_mul_of_nonneg_left h₁ (norm_nonneg v) ... = ∥f∥ * ∥v∥ * ∥x∥ : by ring, end end continuous_linear_map /-- When an inner product space `E` over `𝕜` is considered as a real normed space, its inner product satisfies `is_bounded_bilinear_map`. In order to state these results, we need a `normed_space ℝ E` instance. We will later establish such an instance by restriction-of-scalars, `inner_product_space.is_R_or_C_to_real 𝕜 E`, but this instance may be not definitionally equal to some other “natural” instance. So, we assume `[normed_space ℝ E]`. -/ lemma is_bounded_bilinear_map_inner [normed_space ℝ E] : is_bounded_bilinear_map ℝ (λ p : E × E, ⟪p.1, p.2⟫) := { add_left := λ _ _ _, inner_add_left, smul_left := λ r x y, by simp only [← algebra_map_smul 𝕜 r x, algebra_map_eq_of_real, inner_smul_real_left], add_right := λ _ _ _, inner_add_right, smul_right := λ r x y, by simp only [← algebra_map_smul 𝕜 r y, algebra_map_eq_of_real, inner_smul_real_right], bound := ⟨1, zero_lt_one, λ x y, by { rw [one_mul], exact norm_inner_le_norm x y, }⟩ } end norm section bessels_inequality variables {ι: Type*} (x : E) {v : ι → E} /-- Bessel's inequality for finite sums. -/ lemma orthonormal.sum_inner_products_le {s : finset ι} (hv : orthonormal 𝕜 v) : ∑ i in s, ∥⟪v i, x⟫∥ ^ 2 ≤ ∥x∥ ^ 2 := begin have h₂ : ∑ i in s, ∑ j in s, ⟪v i, x⟫ * ⟪x, v j⟫ * ⟪v j, v i⟫ = (∑ k in s, (⟪v k, x⟫ * ⟪x, v k⟫) : 𝕜), { exact hv.inner_left_right_finset }, have h₃ : ∀ z : 𝕜, re (z * conj (z)) = ∥z∥ ^ 2, { intro z, simp only [mul_conj, norm_sq_eq_def'], norm_cast, }, suffices hbf: ∥x - ∑ i in s, ⟪v i, x⟫ • (v i)∥ ^ 2 = ∥x∥ ^ 2 - ∑ i in s, ∥⟪v i, x⟫∥ ^ 2, { rw [←sub_nonneg, ←hbf], simp only [norm_nonneg, pow_nonneg], }, rw [norm_sub_sq, sub_add], simp only [inner_product_space.norm_sq_eq_inner, inner_sum], simp only [sum_inner, two_mul, inner_smul_right, inner_conj_sym, ←mul_assoc, h₂, ←h₃, inner_conj_sym, add_monoid_hom.map_sum, finset.mul_sum, ←finset.sum_sub_distrib, inner_smul_left, add_sub_cancel'], end /-- Bessel's inequality. -/ lemma orthonormal.tsum_inner_products_le (hv : orthonormal 𝕜 v) : ∑' i, ∥⟪v i, x⟫∥ ^ 2 ≤ ∥x∥ ^ 2 := begin refine tsum_le_of_sum_le' _ (λ s, hv.sum_inner_products_le x), simp only [norm_nonneg, pow_nonneg] end /-- The sum defined in Bessel's inequality is summable. -/ lemma orthonormal.inner_products_summable (hv : orthonormal 𝕜 v) : summable (λ i, ∥⟪v i, x⟫∥ ^ 2) := begin use ⨆ s : finset ι, ∑ i in s, ∥⟪v i, x⟫∥ ^ 2, apply has_sum_of_is_lub_of_nonneg, { intro b, simp only [norm_nonneg, pow_nonneg], }, { refine is_lub_csupr _, use ∥x∥ ^ 2, rintro y ⟨s, rfl⟩, exact hv.sum_inner_products_le x } end end bessels_inequality /-- A field `𝕜` satisfying `is_R_or_C` is itself a `𝕜`-inner product space. -/ instance is_R_or_C.inner_product_space : inner_product_space 𝕜 𝕜 := { inner := (λ x y, (conj x) * y), norm_sq_eq_inner := λ x, by { unfold inner, rw [mul_comm, mul_conj, of_real_re, norm_sq_eq_def'] }, conj_sym := λ x y, by simp [mul_comm], add_left := λ x y z, by simp [inner, add_mul], smul_left := λ x y z, by simp [inner, mul_assoc] } @[simp] lemma is_R_or_C.inner_apply (x y : 𝕜) : ⟪x, y⟫ = (conj x) * y := rfl /-! ### Inner product space structure on subspaces -/ /-- Induced inner product on a submodule. -/ instance submodule.inner_product_space (W : submodule 𝕜 E) : inner_product_space 𝕜 W := { inner := λ x y, ⟪(x:E), (y:E)⟫, conj_sym := λ _ _, inner_conj_sym _ _ , norm_sq_eq_inner := λ _, norm_sq_eq_inner _, add_left := λ _ _ _ , inner_add_left, smul_left := λ _ _ _, inner_smul_left, ..submodule.normed_space W } /-- The inner product on submodules is the same as on the ambient space. -/ @[simp] lemma submodule.coe_inner (W : submodule 𝕜 E) (x y : W) : ⟪x, y⟫ = ⟪(x:E), ↑y⟫ := rfl /-! ### Families of mutually-orthogonal subspaces of an inner product space -/ section orthogonal_family variables {ι : Type*} [dec_ι : decidable_eq ι] (𝕜) open_locale direct_sum /-- An indexed family of mutually-orthogonal subspaces of an inner product space `E`. The simple way to express this concept would be as a condition on `V : ι → submodule 𝕜 E`. We We instead implement it as a condition on a family of inner product spaces each equipped with an isometric embedding into `E`, thus making it a property of morphisms rather than subobjects. This definition is less lightweight, but allows for better definitional properties when the inner product space structure on each of the submodules is important -- for example, when considering their Hilbert sum (`pi_lp V 2`). For example, given an orthonormal set of vectors `v : ι → E`, we have an associated orthogonal family of one-dimensional subspaces of `E`, which it is convenient to be able to discuss using `ι → 𝕜` rather than `Π i : ι, span 𝕜 (v i)`. -/ def orthogonal_family {G : ι → Type*} [Π i, inner_product_space 𝕜 (G i)] (V : Π i, G i →ₗᵢ[𝕜] E) : Prop := ∀ ⦃i j⦄, i ≠ j → ∀ v : G i, ∀ w : G j, ⟪V i v, V j w⟫ = 0 variables {𝕜} {G : ι → Type*} [Π i, inner_product_space 𝕜 (G i)] {V : Π i, G i →ₗᵢ[𝕜] E} (hV : orthogonal_family 𝕜 V) [dec_V : Π i (x : G i), decidable (x ≠ 0)] lemma orthonormal.orthogonal_family {v : ι → E} (hv : orthonormal 𝕜 v) : @orthogonal_family 𝕜 _ _ _ _ (λ i : ι, 𝕜) _ (λ i, linear_isometry.to_span_singleton 𝕜 E (hv.1 i)) := λ i j hij a b, by simp [inner_smul_left, inner_smul_right, hv.2 hij] include hV dec_ι lemma orthogonal_family.eq_ite {i j : ι} (v : G i) (w : G j) : ⟪V i v, V j w⟫ = ite (i = j) ⟪V i v, V j w⟫ 0 := begin split_ifs, { refl }, { exact hV h v w } end include dec_V lemma orthogonal_family.inner_right_dfinsupp (l : ⨁ i, G i) (i : ι) (v : G i) : ⟪V i v, l.sum (λ j, V j)⟫ = ⟪v, l i⟫ := calc ⟪V i v, l.sum (λ j, V j)⟫ = l.sum (λ j, λ w, ⟪V i v, V j w⟫) : dfinsupp.inner_sum (λ j, V j) l (V i v) ... = l.sum (λ j, λ w, ite (i=j) ⟪V i v, V j w⟫ 0) : congr_arg l.sum $ funext $ λ j, funext $ hV.eq_ite v ... = ⟪v, l i⟫ : begin simp only [dfinsupp.sum, submodule.coe_inner, finset.sum_ite_eq, ite_eq_left_iff, dfinsupp.mem_support_to_fun], split_ifs with h h, { simp }, { simp [of_not_not h] }, end omit dec_ι dec_V lemma orthogonal_family.inner_right_fintype [fintype ι] (l : Π i, G i) (i : ι) (v : G i) : ⟪V i v, ∑ j : ι, V j (l j)⟫ = ⟪v, l i⟫ := by classical; calc ⟪V i v, ∑ j : ι, V j (l j)⟫ = ∑ j : ι, ⟪V i v, V j (l j)⟫: by rw inner_sum ... = ∑ j, ite (i = j) ⟪V i v, V j (l j)⟫ 0 : congr_arg (finset.sum finset.univ) $ funext $ λ j, (hV.eq_ite v (l j)) ... = ⟪v, l i⟫ : by simp lemma orthogonal_family.inner_sum (l₁ l₂ : Π i, G i) (s : finset ι) : ⟪∑ i in s, V i (l₁ i), ∑ j in s, V j (l₂ j)⟫ = ∑ i in s, ⟪l₁ i, l₂ i⟫ := by classical; calc ⟪∑ i in s, V i (l₁ i), ∑ j in s, V j (l₂ j)⟫ = ∑ j in s, ∑ i in s, ⟪V i (l₁ i), V j (l₂ j)⟫ : by simp [sum_inner, inner_sum] ... = ∑ j in s, ∑ i in s, ite (i = j) ⟪V i (l₁ i), V j (l₂ j)⟫ 0 : begin congr' with i, congr' with j, apply hV.eq_ite, end ... = ∑ i in s, ⟪l₁ i, l₂ i⟫ : by simp [finset.sum_ite_of_true] lemma orthogonal_family.norm_sum (l : Π i, G i) (s : finset ι) : ∥∑ i in s, V i (l i)∥ ^ 2 = ∑ i in s, ∥l i∥ ^ 2 := begin have : (∥∑ i in s, V i (l i)∥ ^ 2 : 𝕜) = ∑ i in s, ∥l i∥ ^ 2, { simp [← inner_self_eq_norm_sq_to_K, hV.inner_sum] }, exact_mod_cast this, end /-- The composition of an orthogonal family of subspaces with an injective function is also an orthogonal family. -/ lemma orthogonal_family.comp {γ : Type*} {f : γ → ι} (hf : function.injective f) : orthogonal_family 𝕜 (λ g : γ, (V (f g) : G (f g) →ₗᵢ[𝕜] E)) := λ i j hij v w, hV (hf.ne hij) v w lemma orthogonal_family.orthonormal_sigma_orthonormal {α : ι → Type*} {v_family : Π i, (α i) → G i} (hv_family : ∀ i, orthonormal 𝕜 (v_family i)) : orthonormal 𝕜 (λ a : Σ i, α i, V a.1 (v_family a.1 a.2)) := begin split, { rintros ⟨i, v⟩, simpa using (hv_family i).1 v }, rintros ⟨i, v⟩ ⟨j, w⟩ hvw, by_cases hij : i = j, { subst hij, have : v ≠ w := by simpa using hvw, simpa using (hv_family i).2 this }, { exact hV hij (v_family i v) (v_family j w) } end include dec_ι lemma orthogonal_family.norm_sq_diff_sum (f : Π i, G i) (s₁ s₂ : finset ι) : ∥∑ i in s₁, V i (f i) - ∑ i in s₂, V i (f i)∥ ^ 2 = ∑ i in s₁ \ s₂, ∥f i∥ ^ 2 + ∑ i in s₂ \ s₁, ∥f i∥ ^ 2 := begin rw [← finset.sum_sdiff_sub_sum_sdiff, sub_eq_add_neg, ← finset.sum_neg_distrib], let F : Π i, G i := λ i, if i ∈ s₁ then f i else - (f i), have hF₁ : ∀ i ∈ s₁ \ s₂, F i = f i := λ i hi, if_pos (finset.sdiff_subset _ _ hi), have hF₂ : ∀ i ∈ s₂ \ s₁, F i = - f i := λ i hi, if_neg (finset.mem_sdiff.mp hi).2, have hF : ∀ i, ∥F i∥ = ∥f i∥, { intros i, dsimp [F], split_ifs; simp, }, have : ∥∑ i in s₁ \ s₂, V i (F i) + ∑ i in s₂ \ s₁, V i (F i)∥ ^ 2 = ∑ i in s₁ \ s₂, ∥F i∥ ^ 2 + ∑ i in s₂ \ s₁, ∥F i∥ ^ 2, { have hs : disjoint (s₁ \ s₂) (s₂ \ s₁) := disjoint_sdiff_sdiff, simpa only [finset.sum_union hs] using hV.norm_sum F (s₁ \ s₂ ∪ s₂ \ s₁) }, convert this using 4, { refine finset.sum_congr rfl (λ i hi, _), simp [hF₁ i hi] }, { refine finset.sum_congr rfl (λ i hi, _), simp [hF₂ i hi] }, { simp [hF] }, { simp [hF] }, end omit dec_ι /-- A family `f` of mutually-orthogonal elements of `E` is summable, if and only if `(λ i, ∥f i∥ ^ 2)` is summable. -/ lemma orthogonal_family.summable_iff_norm_sq_summable [complete_space E] (f : Π i, G i) : summable (λ i, V i (f i)) ↔ summable (λ i, ∥f i∥ ^ 2) := begin classical, simp only [summable_iff_cauchy_seq_finset, normed_group.cauchy_seq_iff, real.norm_eq_abs], split, { intros hf ε hε, obtain ⟨a, H⟩ := hf _ (sqrt_pos.mpr hε), use a, intros s₁ hs₁ s₂ hs₂, rw ← finset.sum_sdiff_sub_sum_sdiff, refine (_root_.abs_sub _ _).trans_lt _, have : ∀ i, 0 ≤ ∥f i∥ ^ 2 := λ i : ι, sq_nonneg _, simp only [finset.abs_sum_of_nonneg' this], have : ∑ i in s₁ \ s₂, ∥f i∥ ^ 2 + ∑ i in s₂ \ s₁, ∥f i∥ ^ 2 < (sqrt ε) ^ 2, { rw ← hV.norm_sq_diff_sum, apply sq_lt_sq, rw [_root_.abs_of_nonneg (sqrt_nonneg _), _root_.abs_of_nonneg (norm_nonneg _)], exact H s₁ hs₁ s₂ hs₂ }, have hη := sq_sqrt (le_of_lt hε), linarith }, { intros hf ε hε, have hε' : 0 < ε ^ 2 / 2 := half_pos (sq_pos_of_pos hε), obtain ⟨a, H⟩ := hf _ hε', use a, intros s₁ hs₁ s₂ hs₂, refine (abs_lt_of_sq_lt_sq' _ (le_of_lt hε)).2, have has : a ≤ s₁ ⊓ s₂ := le_inf hs₁ hs₂, rw hV.norm_sq_diff_sum, have Hs₁ : ∑ (x : ι) in s₁ \ s₂, ∥f x∥ ^ 2 < ε ^ 2 / 2, { convert H _ hs₁ _ has, have : s₁ ⊓ s₂ ⊆ s₁ := finset.inter_subset_left _ _, rw [← finset.sum_sdiff this, add_tsub_cancel_right, finset.abs_sum_of_nonneg'], { simp }, { exact λ i, sq_nonneg _ } }, have Hs₂ : ∑ (x : ι) in s₂ \ s₁, ∥f x∥ ^ 2 < ε ^ 2 /2, { convert H _ hs₂ _ has, have : s₁ ⊓ s₂ ⊆ s₂ := finset.inter_subset_right _ _, rw [← finset.sum_sdiff this, add_tsub_cancel_right, finset.abs_sum_of_nonneg'], { simp }, { exact λ i, sq_nonneg _ } }, linarith }, end omit hV /-- An orthogonal family forms an independent family of subspaces; that is, any collection of elements each from a different subspace in the family is linearly independent. In particular, the pairwise intersections of elements of the family are 0. -/ lemma orthogonal_family.independent {V : ι → submodule 𝕜 E} (hV : @orthogonal_family 𝕜 _ _ _ _ (λ i, V i) _ (λ i, (V i).subtypeₗᵢ)) : complete_lattice.independent V := begin classical, apply complete_lattice.independent_of_dfinsupp_lsum_injective, rw [← @linear_map.ker_eq_bot _ _ _ _ _ _ (direct_sum.add_comm_group (λ i, V i)), submodule.eq_bot_iff], intros v hv, rw linear_map.mem_ker at hv, ext i, suffices : ⟪(v i : E), v i⟫ = 0, { simpa using this }, calc ⟪(v i : E), v i⟫ = ⟪(v i : E), dfinsupp.lsum ℕ (λ i, (V i).subtype) v⟫ : by simpa [dfinsupp.sum_add_hom_apply, submodule.coe_subtype] using (hV.inner_right_dfinsupp v i (v i)).symm ... = 0 : by simp [hv], end include dec_ι lemma direct_sum.submodule_is_internal.collected_basis_orthonormal {V : ι → submodule 𝕜 E} (hV : @orthogonal_family 𝕜 _ _ _ _ (λ i, V i) _ (λ i, (V i).subtypeₗᵢ)) (hV_sum : direct_sum.submodule_is_internal (λ i, V i)) {α : ι → Type*} {v_family : Π i, basis (α i) 𝕜 (V i)} (hv_family : ∀ i, orthonormal 𝕜 (v_family i)) : orthonormal 𝕜 (hV_sum.collected_basis v_family) := by simpa using hV.orthonormal_sigma_orthonormal hv_family end orthogonal_family section is_R_or_C_to_real variables {G : Type*} variables (𝕜 E) include 𝕜 /-- A general inner product implies a real inner product. This is not registered as an instance since it creates problems with the case `𝕜 = ℝ`. -/ def has_inner.is_R_or_C_to_real : has_inner ℝ E := { inner := λ x y, re ⟪x, y⟫ } /-- A general inner product space structure implies a real inner product structure. This is not registered as an instance since it creates problems with the case `𝕜 = ℝ`, but in can be used in a proof to obtain a real inner product space structure from a given `𝕜`-inner product space structure. -/ def inner_product_space.is_R_or_C_to_real : inner_product_space ℝ E := { norm_sq_eq_inner := norm_sq_eq_inner, conj_sym := λ x y, inner_re_symm, add_left := λ x y z, by { change re ⟪x + y, z⟫ = re ⟪x, z⟫ + re ⟪y, z⟫, simp [inner_add_left] }, smul_left := λ x y r, by { change re ⟪(r : 𝕜) • x, y⟫ = r * re ⟪x, y⟫, simp [inner_smul_left] }, ..has_inner.is_R_or_C_to_real 𝕜 E, ..normed_space.restrict_scalars ℝ 𝕜 E } variable {E} lemma real_inner_eq_re_inner (x y : E) : @has_inner.inner ℝ E (has_inner.is_R_or_C_to_real 𝕜 E) x y = re ⟪x, y⟫ := rfl lemma real_inner_I_smul_self (x : E) : @has_inner.inner ℝ E (has_inner.is_R_or_C_to_real 𝕜 E) x ((I : 𝕜) • x) = 0 := by simp [real_inner_eq_re_inner, inner_smul_right] omit 𝕜 /-- A complex inner product implies a real inner product -/ instance inner_product_space.complex_to_real [inner_product_space ℂ G] : inner_product_space ℝ G := inner_product_space.is_R_or_C_to_real ℂ G end is_R_or_C_to_real section continuous /-! ### Continuity of the inner product -/ lemma continuous_inner : continuous (λ p : E × E, ⟪p.1, p.2⟫) := begin letI : inner_product_space ℝ E := inner_product_space.is_R_or_C_to_real 𝕜 E, exact is_bounded_bilinear_map_inner.continuous end variables {α : Type*} lemma filter.tendsto.inner {f g : α → E} {l : filter α} {x y : E} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) : tendsto (λ t, ⟪f t, g t⟫) l (𝓝 ⟪x, y⟫) := (continuous_inner.tendsto _).comp (hf.prod_mk_nhds hg) variables [topological_space α] {f g : α → E} {x : α} {s : set α} include 𝕜 lemma continuous_within_at.inner (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (λ t, ⟪f t, g t⟫) s x := hf.inner hg lemma continuous_at.inner (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (λ t, ⟪f t, g t⟫) x := hf.inner hg lemma continuous_on.inner (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λ t, ⟪f t, g t⟫) s := λ x hx, (hf x hx).inner (hg x hx) lemma continuous.inner (hf : continuous f) (hg : continuous g) : continuous (λ t, ⟪f t, g t⟫) := continuous_iff_continuous_at.2 $ λ x, hf.continuous_at.inner hg.continuous_at end continuous section re_apply_inner_self /-- Extract a real bilinear form from an operator `T`, by taking the pairing `λ x, re ⟪T x, x⟫`. -/ def continuous_linear_map.re_apply_inner_self (T : E →L[𝕜] E) (x : E) : ℝ := re ⟪T x, x⟫ lemma continuous_linear_map.re_apply_inner_self_apply (T : E →L[𝕜] E) (x : E) : T.re_apply_inner_self x = re ⟪T x, x⟫ := rfl lemma continuous_linear_map.re_apply_inner_self_continuous (T : E →L[𝕜] E) : continuous T.re_apply_inner_self := re_clm.continuous.comp $ T.continuous.inner continuous_id lemma continuous_linear_map.re_apply_inner_self_smul (T : E →L[𝕜] E) (x : E) {c : 𝕜} : T.re_apply_inner_self (c • x) = ∥c∥ ^ 2 * T.re_apply_inner_self x := by simp only [continuous_linear_map.map_smul, continuous_linear_map.re_apply_inner_self_apply, inner_smul_left, inner_smul_right, ← mul_assoc, mul_conj, norm_sq_eq_def', ← smul_re, algebra.smul_def (∥c∥ ^ 2) ⟪T x, x⟫, algebra_map_eq_of_real] end re_apply_inner_self /-! ### The orthogonal complement -/ section orthogonal variables (K : submodule 𝕜 E) /-- The subspace of vectors orthogonal to a given subspace. -/ def submodule.orthogonal : submodule 𝕜 E := { carrier := {v | ∀ u ∈ K, ⟪u, v⟫ = 0}, zero_mem' := λ _ _, inner_zero_right, add_mem' := λ x y hx hy u hu, by rw [inner_add_right, hx u hu, hy u hu, add_zero], smul_mem' := λ c x hx u hu, by rw [inner_smul_right, hx u hu, mul_zero] } notation K`ᗮ`:1200 := submodule.orthogonal K /-- When a vector is in `Kᗮ`. -/ lemma submodule.mem_orthogonal (v : E) : v ∈ Kᗮ ↔ ∀ u ∈ K, ⟪u, v⟫ = 0 := iff.rfl /-- When a vector is in `Kᗮ`, with the inner product the other way round. -/ lemma submodule.mem_orthogonal' (v : E) : v ∈ Kᗮ ↔ ∀ u ∈ K, ⟪v, u⟫ = 0 := by simp_rw [submodule.mem_orthogonal, inner_eq_zero_sym] variables {K} /-- A vector in `K` is orthogonal to one in `Kᗮ`. -/ lemma submodule.inner_right_of_mem_orthogonal {u v : E} (hu : u ∈ K) (hv : v ∈ Kᗮ) : ⟪u, v⟫ = 0 := (K.mem_orthogonal v).1 hv u hu /-- A vector in `Kᗮ` is orthogonal to one in `K`. -/ lemma submodule.inner_left_of_mem_orthogonal {u v : E} (hu : u ∈ K) (hv : v ∈ Kᗮ) : ⟪v, u⟫ = 0 := by rw [inner_eq_zero_sym]; exact submodule.inner_right_of_mem_orthogonal hu hv /-- A vector in `(𝕜 ∙ u)ᗮ` is orthogonal to `u`. -/ lemma inner_right_of_mem_orthogonal_singleton (u : E) {v : E} (hv : v ∈ (𝕜 ∙ u)ᗮ) : ⟪u, v⟫ = 0 := submodule.inner_right_of_mem_orthogonal (submodule.mem_span_singleton_self u) hv /-- A vector in `(𝕜 ∙ u)ᗮ` is orthogonal to `u`. -/ lemma inner_left_of_mem_orthogonal_singleton (u : E) {v : E} (hv : v ∈ (𝕜 ∙ u)ᗮ) : ⟪v, u⟫ = 0 := submodule.inner_left_of_mem_orthogonal (submodule.mem_span_singleton_self u) hv /-- A vector orthogonal to `u` lies in `(𝕜 ∙ u)ᗮ`. -/ lemma mem_orthogonal_singleton_of_inner_right (u : E) {v : E} (hv : ⟪u, v⟫ = 0) : v ∈ (𝕜 ∙ u)ᗮ := begin intros w hw, rw submodule.mem_span_singleton at hw, obtain ⟨c, rfl⟩ := hw, simp [inner_smul_left, hv], end /-- A vector orthogonal to `u` lies in `(𝕜 ∙ u)ᗮ`. -/ lemma mem_orthogonal_singleton_of_inner_left (u : E) {v : E} (hv : ⟪v, u⟫ = 0) : v ∈ (𝕜 ∙ u)ᗮ := mem_orthogonal_singleton_of_inner_right u $ inner_eq_zero_sym.2 hv variables (K) /-- `K` and `Kᗮ` have trivial intersection. -/ lemma submodule.inf_orthogonal_eq_bot : K ⊓ Kᗮ = ⊥ := begin rw submodule.eq_bot_iff, intros x, rw submodule.mem_inf, exact λ ⟨hx, ho⟩, inner_self_eq_zero.1 (ho x hx) end /-- `K` and `Kᗮ` have trivial intersection. -/ lemma submodule.orthogonal_disjoint : disjoint K Kᗮ := by simp [disjoint_iff, K.inf_orthogonal_eq_bot] /-- `Kᗮ` can be characterized as the intersection of the kernels of the operations of inner product with each of the elements of `K`. -/ lemma orthogonal_eq_inter : Kᗮ = ⨅ v : K, (innerSL (v:E)).ker := begin apply le_antisymm, { rw le_infi_iff, rintros ⟨v, hv⟩ w hw, simpa using hw _ hv }, { intros v hv w hw, simp only [submodule.mem_infi] at hv, exact hv ⟨w, hw⟩ } end /-- The orthogonal complement of any submodule `K` is closed. -/ lemma submodule.is_closed_orthogonal : is_closed (Kᗮ : set E) := begin rw orthogonal_eq_inter K, convert is_closed_Inter (λ v : K, (innerSL (v:E)).is_closed_ker), simp end /-- In a complete space, the orthogonal complement of any submodule `K` is complete. -/ instance [complete_space E] : complete_space Kᗮ := K.is_closed_orthogonal.complete_space_coe variables (𝕜 E) /-- `submodule.orthogonal` gives a `galois_connection` between `submodule 𝕜 E` and its `order_dual`. -/ lemma submodule.orthogonal_gc : @galois_connection (submodule 𝕜 E) (submodule 𝕜 E)ᵒᵈ _ _ submodule.orthogonal submodule.orthogonal := λ K₁ K₂, ⟨λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu), λ h v hv u hu, submodule.inner_left_of_mem_orthogonal hv (h hu)⟩ variables {𝕜 E} /-- `submodule.orthogonal` reverses the `≤` ordering of two subspaces. -/ lemma submodule.orthogonal_le {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) : K₂ᗮ ≤ K₁ᗮ := (submodule.orthogonal_gc 𝕜 E).monotone_l h /-- `submodule.orthogonal.orthogonal` preserves the `≤` ordering of two subspaces. -/ lemma submodule.orthogonal_orthogonal_monotone {K₁ K₂ : submodule 𝕜 E} (h : K₁ ≤ K₂) : K₁ᗮᗮ ≤ K₂ᗮᗮ := submodule.orthogonal_le (submodule.orthogonal_le h) /-- `K` is contained in `Kᗮᗮ`. -/ lemma submodule.le_orthogonal_orthogonal : K ≤ Kᗮᗮ := (submodule.orthogonal_gc 𝕜 E).le_u_l _ /-- The inf of two orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.inf_orthogonal (K₁ K₂ : submodule 𝕜 E) : K₁ᗮ ⊓ K₂ᗮ = (K₁ ⊔ K₂)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_sup.symm /-- The inf of an indexed family of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.infi_orthogonal {ι : Type*} (K : ι → submodule 𝕜 E) : (⨅ i, (K i)ᗮ) = (supr K)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_supr.symm /-- The inf of a set of orthogonal subspaces equals the subspace orthogonal to the sup. -/ lemma submodule.Inf_orthogonal (s : set $ submodule 𝕜 E) : (⨅ K ∈ s, Kᗮ) = (Sup s)ᗮ := (submodule.orthogonal_gc 𝕜 E).l_Sup.symm @[simp] lemma submodule.top_orthogonal_eq_bot : (⊤ : submodule 𝕜 E)ᗮ = ⊥ := begin ext, rw [submodule.mem_bot, submodule.mem_orthogonal], exact ⟨λ h, inner_self_eq_zero.mp (h x submodule.mem_top), by { rintro rfl, simp }⟩ end @[simp] lemma submodule.bot_orthogonal_eq_top : (⊥ : submodule 𝕜 E)ᗮ = ⊤ := begin rw [← submodule.top_orthogonal_eq_bot, eq_top_iff], exact submodule.le_orthogonal_orthogonal ⊤ end @[simp] lemma submodule.orthogonal_eq_top_iff : Kᗮ = ⊤ ↔ K = ⊥ := begin refine ⟨_, by { rintro rfl, exact submodule.bot_orthogonal_eq_top }⟩, intro h, have : K ⊓ Kᗮ = ⊥ := K.orthogonal_disjoint.eq_bot, rwa [h, inf_comm, top_inf_eq] at this end end orthogonal /-! ### Self-adjoint operators -/ namespace inner_product_space /-- A (not necessarily bounded) operator on an inner product space is self-adjoint, if for all `x`, `y`, we have `⟪T x, y⟫ = ⟪x, T y⟫`. -/ def is_self_adjoint (T : E →ₗ[𝕜] E) : Prop := ∀ x y, ⟪T x, y⟫ = ⟪x, T y⟫ /-- An operator `T` on a `ℝ`-inner product space is self-adjoint if and only if it is `bilin_form.is_self_adjoint` with respect to the bilinear form given by the inner product. -/ lemma is_self_adjoint_iff_bilin_form (T : F →ₗ[ℝ] F) : is_self_adjoint T ↔ bilin_form_of_real_inner.is_self_adjoint T := by simp [is_self_adjoint, bilin_form.is_self_adjoint, bilin_form.is_adjoint_pair] lemma is_self_adjoint.conj_inner_sym {T : E →ₗ[𝕜] E} (hT : is_self_adjoint T) (x y : E) : conj ⟪T x, y⟫ = ⟪T y, x⟫ := by rw [hT x y, inner_conj_sym] @[simp] lemma is_self_adjoint.apply_clm {T : E →L[𝕜] E} (hT : is_self_adjoint (T : E →ₗ[𝕜] E)) (x y : E) : ⟪T x, y⟫ = ⟪x, T y⟫ := hT x y /-- For a self-adjoint operator `T`, the function `λ x, ⟪T x, x⟫` is real-valued. -/ @[simp] lemma is_self_adjoint.coe_re_apply_inner_self_apply {T : E →L[𝕜] E} (hT : is_self_adjoint (T : E →ₗ[𝕜] E)) (x : E) : (T.re_apply_inner_self x : 𝕜) = ⟪T x, x⟫ := begin suffices : ∃ r : ℝ, ⟪T x, x⟫ = r, { obtain ⟨r, hr⟩ := this, simp [hr, T.re_apply_inner_self_apply] }, rw ← eq_conj_iff_real, exact hT.conj_inner_sym x x end /-- If a self-adjoint operator preserves a submodule, its restriction to that submodule is self-adjoint. -/ lemma is_self_adjoint.restrict_invariant {T : E →ₗ[𝕜] E} (hT : is_self_adjoint T) {V : submodule 𝕜 E} (hV : ∀ v ∈ V, T v ∈ V) : is_self_adjoint (T.restrict hV) := λ v w, hT v w section complex variables {V : Type*} [inner_product_space ℂ V] /-- A linear operator on a complex inner product space is self-adjoint precisely when `⟪T v, v⟫_ℂ` is real for all v.-/ lemma is_self_adjoint_iff_inner_map_self_real (T : V →ₗ[ℂ] V): is_self_adjoint T ↔ ∀ (v : V), conj ⟪T v, v⟫_ℂ = ⟪T v, v⟫_ℂ := begin split, { intros hT v, apply is_self_adjoint.conj_inner_sym hT }, { intros h x y, nth_rewrite 1 ← inner_conj_sym, nth_rewrite 1 inner_map_polarization, simp only [star_ring_end_apply, star_div', star_sub, star_add, star_mul], simp only [← star_ring_end_apply], rw [h (x + y), h (x - y), h (x + complex.I • y), h (x - complex.I • y)], simp only [complex.conj_I], rw inner_map_polarization', norm_num, ring }, end end complex end inner_product_space
22d44834ebb02d405a902d5f3049aee7ca924c1a
95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990
/src/topology/uniform_space/basic.lean
0daeb1b10a0aa357cfe127d6eb61047b3af4a1c2
[ "Apache-2.0" ]
permissive
uniformity1/mathlib
829341bad9dfa6d6be9adaacb8086a8a492e85a4
dd0e9bd8f2e5ec267f68e72336f6973311909105
refs/heads/master
1,588,592,015,670
1,554,219,842,000
1,554,219,842,000
179,110,702
0
0
Apache-2.0
1,554,220,076,000
1,554,220,076,000
null
UTF-8
Lean
false
false
42,348
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot Theory of uniform spaces. Uniform spaces are a generalization of metric spaces and topological groups. Many concepts directly generalize to uniform spaces, e.g. * completeness * extension of uniform continuous functions to complete spaces * uniform contiunuity & embedding * totally bounded * totally bounded ∧ complete → compact The central concept of uniform spaces is its uniformity: a filter relating two elements of the space. This filter is reflexive, symmetric and transitive. So a set (i.e. a relation) in this filter represents a 'distance': it is reflexive, symmetric and the uniformity contains a set for which the `triangular` rule holds. The formalization is mostly based on the books: N. Bourbaki: General Topology I. M. James: Topologies and Uniformities A major difference is that this formalization is heavily based on the filter library. -/ import order.filter order.filter.lift data.quot topology.constructions open set lattice filter classical local attribute [instance, priority 0] prop_decidable set_option eqn_compiler.zeta true universes u section variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} /-- The identity relation, or the graph of the identity function -/ def id_rel {α : Type*} := {p : α × α | p.1 = p.2} @[simp] theorem mem_id_rel {a b : α} : (a, b) ∈ @id_rel α ↔ a = b := iff.rfl @[simp] theorem id_rel_subset {s : set (α × α)} : id_rel ⊆ s ↔ ∀ a, (a, a) ∈ s := by simp [subset_def]; exact forall_congr (λ a, by simp) /-- The composition of relations -/ def comp_rel {α : Type u} (r₁ r₂ : set (α×α)) := {p : α × α | ∃z:α, (p.1, z) ∈ r₁ ∧ (z, p.2) ∈ r₂} @[simp] theorem mem_comp_rel {r₁ r₂ : set (α×α)} {x y : α} : (x, y) ∈ comp_rel r₁ r₂ ↔ ∃ z, (x, z) ∈ r₁ ∧ (z, y) ∈ r₂ := iff.rfl @[simp] theorem swap_id_rel : prod.swap '' id_rel = @id_rel α := set.ext $ assume ⟨a, b⟩, by simp [image_swap_eq_preimage_swap]; exact eq_comm theorem monotone_comp_rel [preorder β] {f g : β → set (α×α)} (hf : monotone f) (hg : monotone g) : monotone (λx, comp_rel (f x) (g x)) := assume a b h p ⟨z, h₁, h₂⟩, ⟨z, hf h h₁, hg h h₂⟩ lemma prod_mk_mem_comp_rel {a b c : α} {s t : set (α×α)} (h₁ : (a, c) ∈ s) (h₂ : (c, b) ∈ t) : (a, b) ∈ comp_rel s t := ⟨c, h₁, h₂⟩ @[simp] lemma id_comp_rel {r : set (α×α)} : comp_rel id_rel r = r := set.ext $ assume ⟨a, b⟩, by simp lemma comp_rel_assoc {r s t : set (α×α)} : comp_rel (comp_rel r s) t = comp_rel r (comp_rel s t) := by ext p; cases p; simp only [mem_comp_rel]; tauto /-- This core description of a uniform space is outside of the type class hierarchy. It is useful for constructions of uniform spaces, when the topology is derived from the uniform space. -/ structure uniform_space.core (α : Type u) := (uniformity : filter (α × α)) (refl : principal id_rel ≤ uniformity) (symm : tendsto prod.swap uniformity uniformity) (comp : uniformity.lift' (λs, comp_rel s s) ≤ uniformity) def uniform_space.core.mk' {α : Type u} (U : filter (α × α)) (refl : ∀ (r ∈ U) x, (x, x) ∈ r) (symm : ∀ r ∈ U, {p | prod.swap p ∈ r} ∈ U) (comp : ∀ r ∈ U, ∃ t ∈ U, comp_rel t t ⊆ r) : uniform_space.core α := ⟨U, λ r ru, id_rel_subset.2 (refl _ ru), symm, begin intros r ru, rw [mem_lift'_sets], exact comp _ ru, apply monotone_comp_rel; exact monotone_id, end⟩ /-- A uniform space generates a topological space -/ def uniform_space.core.to_topological_space {α : Type u} (u : uniform_space.core α) : topological_space α := { is_open := λs, ∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ u.uniformity, is_open_univ := by simp; intro; exact univ_mem_sets, is_open_inter := assume s t hs ht x ⟨xs, xt⟩, by filter_upwards [hs x xs, ht x xt]; simp {contextual := tt}, is_open_sUnion := assume s hs x ⟨t, ts, xt⟩, by filter_upwards [hs t ts x xt] assume p ph h, ⟨t, ts, ph h⟩ } lemma uniform_space.core_eq : ∀{u₁ u₂ : uniform_space.core α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | ⟨u₁, _, _, _⟩ ⟨u₂, _, _, _⟩ h := have u₁ = u₂, from h, by simp [*] /-- A uniform space is a generalization of the "uniform" topological aspects of a metric space. It consists of a filter on `α × α` called the "uniformity", which satisfies properties analogous to the reflexivity, symmetry, and triangle properties of a metric. A metric space has a natural uniformity, and a uniform space has a natural topology. A topological group also has a natural uniformity, even when it is not metrizable. -/ class uniform_space (α : Type u) extends topological_space α, uniform_space.core α := (is_open_uniformity : ∀s, is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ uniformity)) @[pattern] def uniform_space.mk' {α} (t : topological_space α) (c : uniform_space.core α) (is_open_uniformity : ∀s:set α, t.is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ c.uniformity)) : uniform_space α := ⟨c, is_open_uniformity⟩ def uniform_space.of_core {α : Type u} (u : uniform_space.core α) : uniform_space α := { to_core := u, to_topological_space := u.to_topological_space, is_open_uniformity := assume a, iff.refl _ } def uniform_space.of_core_eq {α : Type u} (u : uniform_space.core α) (t : topological_space α) (h : t = u.to_topological_space) : uniform_space α := { to_core := u, to_topological_space := t, is_open_uniformity := assume a, h.symm ▸ iff.refl _ } lemma uniform_space.to_core_to_topological_space (u : uniform_space α) : u.to_core.to_topological_space = u.to_topological_space := topological_space_eq $ funext $ assume s, by rw [uniform_space.core.to_topological_space, uniform_space.is_open_uniformity] @[extensionality] lemma uniform_space_eq : ∀{u₁ u₂ : uniform_space α}, u₁.uniformity = u₂.uniformity → u₁ = u₂ | (uniform_space.mk' t₁ u₁ o₁) (uniform_space.mk' t₂ u₂ o₂) h := have u₁ = u₂, from uniform_space.core_eq h, have t₁ = t₂, from topological_space_eq $ funext $ assume s, by rw [o₁, o₂]; simp [this], by simp [*] lemma uniform_space.of_core_eq_to_core (u : uniform_space α) (t : topological_space α) (h : t = u.to_core.to_topological_space) : uniform_space.of_core_eq u.to_core t h = u := uniform_space_eq rfl section uniform_space variables [uniform_space α] /-- The uniformity is a filter on α × α (inferred from an ambient uniform space structure on α). -/ def uniformity (α : Type u) [uniform_space α] : filter (α × α) := (@uniform_space.to_core α _).uniformity local notation `𝓤` := uniformity lemma is_open_uniformity {s : set α} : is_open s ↔ (∀x∈s, { p : α × α | p.1 = x → p.2 ∈ s } ∈ 𝓤 α) := uniform_space.is_open_uniformity s lemma refl_le_uniformity : principal id_rel ≤ 𝓤 α := (@uniform_space.to_core α _).refl lemma refl_mem_uniformity {x : α} {s : set (α × α)} (h : s ∈ 𝓤 α) : (x, x) ∈ s := refl_le_uniformity h rfl lemma symm_le_uniformity : map (@prod.swap α α) (𝓤 _) ≤ (𝓤 _) := (@uniform_space.to_core α _).symm lemma comp_le_uniformity : (𝓤 α).lift' (λs:set (α×α), comp_rel s s) ≤ 𝓤 α := (@uniform_space.to_core α _).comp lemma tendsto_swap_uniformity : tendsto (@prod.swap α α) (𝓤 α) (𝓤 α) := symm_le_uniformity lemma tendsto_const_uniformity {a : α} {f : filter β} : tendsto (λ _, (a, a)) f (𝓤 α) := assume s hs, show {x | (a, a) ∈ s} ∈ f, from univ_mem_sets' $ assume b, refl_mem_uniformity hs lemma comp_mem_uniformity_sets {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, comp_rel t t ⊆ s := have s ∈ (𝓤 α).lift' (λt:set (α×α), comp_rel t t), from comp_le_uniformity hs, (mem_lift'_sets $ monotone_comp_rel monotone_id monotone_id).mp this lemma symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀a b, (a, b) ∈ t → (b, a) ∈ t) ∧ t ⊆ s := have preimage prod.swap s ∈ 𝓤 α, from symm_le_uniformity hs, ⟨s ∩ preimage prod.swap s, inter_mem_sets hs this, assume a b ⟨h₁, h₂⟩, ⟨h₂, h₁⟩, inter_subset_left _ _⟩ lemma comp_symm_of_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : ∃ t ∈ 𝓤 α, (∀{a b}, (a, b) ∈ t → (b, a) ∈ t) ∧ comp_rel t t ⊆ s := let ⟨t, ht₁, ht₂⟩ := comp_mem_uniformity_sets hs in let ⟨t', ht', ht'₁, ht'₂⟩ := symm_of_uniformity ht₁ in ⟨t', ht', ht'₁, subset.trans (monotone_comp_rel monotone_id monotone_id ht'₂) ht₂⟩ lemma uniformity_le_symm : 𝓤 α ≤ (@prod.swap α α) <$> 𝓤 α := by rw [map_swap_eq_comap_swap]; from map_le_iff_le_comap.1 tendsto_swap_uniformity lemma uniformity_eq_symm : 𝓤 α = (@prod.swap α α) <$> 𝓤 α := le_antisymm uniformity_le_symm symm_le_uniformity theorem uniformity_lift_le_swap {g : set (α×α) → filter β} {f : filter β} (hg : monotone g) (h : (𝓤 α).lift (λs, g (preimage prod.swap s)) ≤ f) : (𝓤 α).lift g ≤ f := calc (𝓤 α).lift g ≤ (filter.map (@prod.swap α α) $ 𝓤 α).lift g : lift_mono uniformity_le_symm (le_refl _) ... ≤ _ : by rw [map_lift_eq2 hg, image_swap_eq_preimage_swap]; exact h lemma uniformity_lift_le_comp {f : set (α×α) → filter β} (h : monotone f): (𝓤 α).lift (λs, f (comp_rel s s)) ≤ (𝓤 α).lift f := calc (𝓤 α).lift (λs, f (comp_rel s s)) = ((𝓤 α).lift' (λs:set (α×α), comp_rel s s)).lift f : begin rw [lift_lift'_assoc], exact monotone_comp_rel monotone_id monotone_id, exact h end ... ≤ (𝓤 α).lift f : lift_mono comp_le_uniformity (le_refl _) lemma comp_le_uniformity3 : (𝓤 α).lift' (λs:set (α×α), comp_rel s (comp_rel s s)) ≤ (𝓤 α) := calc (𝓤 α).lift' (λd, comp_rel d (comp_rel d d)) = (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), comp_rel s (comp_rel t t))) : begin rw [lift_lift'_same_eq_lift'], exact (assume x, monotone_comp_rel monotone_const $ monotone_comp_rel monotone_id monotone_id), exact (assume x, monotone_comp_rel monotone_id monotone_const), end ... ≤ (𝓤 α).lift (λs, (𝓤 α).lift' (λt:set(α×α), comp_rel s t)) : lift_mono' $ assume s hs, @uniformity_lift_le_comp α _ _ (principal ∘ comp_rel s) $ monotone_comp (monotone_comp_rel monotone_const monotone_id) monotone_principal ... = (𝓤 α).lift' (λs:set(α×α), comp_rel s s) : lift_lift'_same_eq_lift' (assume s, monotone_comp_rel monotone_const monotone_id) (assume s, monotone_comp_rel monotone_id monotone_const) ... ≤ (𝓤 α) : comp_le_uniformity lemma mem_nhds_uniformity_iff {x : α} {s : set α} : s ∈ nhds x ↔ {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α := ⟨ begin simp only [mem_nhds_sets_iff, is_open_uniformity, and_imp, exists_imp_distrib], exact assume t ts ht xt, by filter_upwards [ht x xt] assume ⟨x', y⟩ h eq, ts $ h eq end, assume hs, mem_nhds_sets_iff.mpr ⟨{x | {p : α × α | p.1 = x → p.2 ∈ s} ∈ 𝓤 α}, assume x' hx', refl_mem_uniformity hx' rfl, is_open_uniformity.mpr $ assume x' hx', let ⟨t, ht, tr⟩ := comp_mem_uniformity_sets hx' in by filter_upwards [ht] assume ⟨a, b⟩ hp' (hax' : a = x'), by filter_upwards [ht] assume ⟨a, b'⟩ hp'' (hab : a = b), have hp : (x', b) ∈ t, from hax' ▸ hp', have (b, b') ∈ t, from hab ▸ hp'', have (x', b') ∈ comp_rel t t, from ⟨b, hp, this⟩, show b' ∈ s, from tr this rfl, hs⟩⟩ lemma nhds_eq_comap_uniformity {x : α} : nhds x = (𝓤 α).comap (prod.mk x) := by ext s; rw [mem_nhds_uniformity_iff, mem_comap_sets]; from iff.intro (assume hs, ⟨_, hs, assume x hx, hx rfl⟩) (assume ⟨t, h, ht⟩, (𝓤 α).sets_of_superset h $ assume ⟨p₁, p₂⟩ hp (h : p₁ = x), ht $ by simp [h.symm, hp]) lemma nhds_eq_uniformity {x : α} : nhds x = (𝓤 α).lift' (λs:set (α×α), {y | (x, y) ∈ s}) := begin ext s, rw [mem_lift'_sets], tactic.swap, apply monotone_preimage, simp [mem_nhds_uniformity_iff], exact ⟨assume h, ⟨_, h, assume y h, h rfl⟩, assume ⟨t, h₁, h₂⟩, (𝓤 α).sets_of_superset h₁ $ assume ⟨x', y⟩ hp (eq : x' = x), h₂ $ show (x, y) ∈ t, from eq ▸ hp⟩ end lemma mem_nhds_left (x : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {y : α | (x, y) ∈ s} ∈ nhds x := have nhds x ≤ principal {y : α | (x, y) ∈ s}, by rw [nhds_eq_uniformity]; exact infi_le_of_le s (infi_le _ h), by simp at this; assumption lemma mem_nhds_right (y : α) {s : set (α×α)} (h : s ∈ 𝓤 α) : {x : α | (x, y) ∈ s} ∈ nhds y := mem_nhds_left _ (symm_le_uniformity h) lemma tendsto_right_nhds_uniformity {a : α} : tendsto (λa', (a', a)) (nhds a) (𝓤 α) := assume s, mem_nhds_right a lemma tendsto_left_nhds_uniformity {a : α} : tendsto (λa', (a, a')) (nhds a) (𝓤 α) := assume s, mem_nhds_left a lemma lift_nhds_left {x : α} {g : set α → filter β} (hg : monotone g) : (nhds x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) := eq.trans begin rw [nhds_eq_uniformity], exact (filter.lift_assoc $ monotone_comp monotone_preimage $ monotone_comp monotone_preimage monotone_principal) end (congr_arg _ $ funext $ assume s, filter.lift_principal hg) lemma lift_nhds_right {x : α} {g : set α → filter β} (hg : monotone g) : (nhds x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (y, x) ∈ s}) := calc (nhds x).lift g = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : lift_nhds_left hg ... = ((@prod.swap α α) <$> (𝓤 α)).lift (λs:set (α×α), g {y | (x, y) ∈ s}) : by rw [←uniformity_eq_symm] ... = (𝓤 α).lift (λs:set (α×α), g {y | (x, y) ∈ image prod.swap s}) : map_lift_eq2 $ monotone_comp monotone_preimage hg ... = _ : by simp [image_swap_eq_preimage_swap] lemma nhds_nhds_eq_uniformity_uniformity_prod {a b : α} : filter.prod (nhds a) (nhds b) = (𝓤 α).lift (λs:set (α×α), (𝓤 α).lift' (λt:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ t})) := begin rw [prod_def], show (nhds a).lift (λs:set α, (nhds b).lift (λt:set α, principal (set.prod s t))) = _, rw [lift_nhds_right], apply congr_arg, funext s, rw [lift_nhds_left], refl, exact monotone_comp (monotone_prod monotone_const monotone_id) monotone_principal, exact (monotone_lift' monotone_const $ monotone_lam $ assume x, monotone_prod monotone_id monotone_const) end lemma nhds_eq_uniformity_prod {a b : α} : nhds (a, b) = (𝓤 α).lift' (λs:set (α×α), set.prod {y : α | (y, a) ∈ s} {y : α | (b, y) ∈ s}) := begin rw [nhds_prod_eq, nhds_nhds_eq_uniformity_uniformity_prod, lift_lift'_same_eq_lift'], { intro s, exact monotone_prod monotone_const monotone_preimage }, { intro t, exact monotone_prod monotone_preimage monotone_const } end lemma nhdset_of_mem_uniformity {d : set (α×α)} (s : set (α×α)) (hd : d ∈ 𝓤 α) : ∃(t : set (α×α)), is_open t ∧ s ⊆ t ∧ t ⊆ {p | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} := let cl_d := {p:α×α | ∃x y, (p.1, x) ∈ d ∧ (x, y) ∈ s ∧ (y, p.2) ∈ d} in have ∀p ∈ s, ∃t ⊆ cl_d, is_open t ∧ p ∈ t, from assume ⟨x, y⟩ hp, mem_nhds_sets_iff.mp $ show cl_d ∈ nhds (x, y), begin rw [nhds_eq_uniformity_prod, mem_lift'_sets], exact ⟨d, hd, assume ⟨a, b⟩ ⟨ha, hb⟩, ⟨x, y, ha, hp, hb⟩⟩, exact monotone_prod monotone_preimage monotone_preimage end, have ∃t:(Π(p:α×α) (h:p ∈ s), set (α×α)), ∀p, ∀h:p ∈ s, t p h ⊆ cl_d ∧ is_open (t p h) ∧ p ∈ t p h, by simp [classical.skolem] at this; simp; assumption, match this with | ⟨t, ht⟩ := ⟨(⋃ p:α×α, ⋃ h : p ∈ s, t p h : set (α×α)), is_open_Union $ assume (p:α×α), is_open_Union $ assume hp, (ht p hp).right.left, assume ⟨a, b⟩ hp, begin simp; exact ⟨a, b, hp, (ht (a,b) hp).right.right⟩ end, Union_subset $ assume p, Union_subset $ assume hp, (ht p hp).left⟩ end lemma closure_eq_inter_uniformity {t : set (α×α)} : closure t = (⋂ d ∈ 𝓤 α, comp_rel d (comp_rel t d)) := set.ext $ assume ⟨a, b⟩, calc (a, b) ∈ closure t ↔ (nhds (a, b) ⊓ principal t ≠ ⊥) : by simp [closure_eq_nhds] ... ↔ (((@prod.swap α α) <$> 𝓤 α).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by rw [←uniformity_eq_symm, nhds_eq_uniformity_prod] ... ↔ ((map (@prod.swap α α) (𝓤 α)).lift' (λ (s : set (α × α)), set.prod {x : α | (x, a) ∈ s} {y : α | (b, y) ∈ s}) ⊓ principal t ≠ ⊥) : by refl ... ↔ ((𝓤 α).lift' (λ (s : set (α × α)), set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s}) ⊓ principal t ≠ ⊥) : begin rw [map_lift'_eq2], simp [image_swap_eq_preimage_swap, function.comp], exact monotone_prod monotone_preimage monotone_preimage end ... ↔ (∀s ∈ 𝓤 α, ∃x, x ∈ set.prod {y : α | (a, y) ∈ s} {x : α | (x, b) ∈ s} ∩ t) : begin rw [lift'_inf_principal_eq, lift'_neq_bot_iff], apply forall_congr, intro s, rw [ne_empty_iff_exists_mem], exact monotone_inter (monotone_prod monotone_preimage monotone_preimage) monotone_const end ... ↔ (∀ s ∈ 𝓤 α, (a, b) ∈ comp_rel s (comp_rel t s)) : forall_congr $ assume s, forall_congr $ assume hs, ⟨assume ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩, ⟨x, hx, y, hxyt, hy⟩, assume ⟨x, hx, y, hxyt, hy⟩, ⟨⟨x, y⟩, ⟨⟨hx, hy⟩, hxyt⟩⟩⟩ ... ↔ _ : by simp lemma uniformity_eq_uniformity_closure : 𝓤 α = (𝓤 α).lift' closure := le_antisymm (le_infi $ assume s, le_infi $ assume hs, by simp; filter_upwards [hs] subset_closure) (calc (𝓤 α).lift' closure ≤ (𝓤 α).lift' (λd, comp_rel d (comp_rel d d)) : lift'_mono' (by intros s hs; rw [closure_eq_inter_uniformity]; exact bInter_subset_of_mem hs) ... ≤ (𝓤 α) : comp_le_uniformity3) lemma uniformity_eq_uniformity_interior : 𝓤 α = (𝓤 α).lift' interior := le_antisymm (le_infi $ assume d, le_infi $ assume hd, let ⟨s, hs, hs_comp⟩ := (mem_lift'_sets $ monotone_comp_rel monotone_id $ monotone_comp_rel monotone_id monotone_id).mp (comp_le_uniformity3 hd) in let ⟨t, ht, hst, ht_comp⟩ := nhdset_of_mem_uniformity s hs in have s ⊆ interior d, from calc s ⊆ t : hst ... ⊆ interior d : (subset_interior_iff_subset_of_open ht).mpr $ assume x, assume : x ∈ t, let ⟨x, y, h₁, h₂, h₃⟩ := ht_comp this in hs_comp ⟨x, h₁, y, h₂, h₃⟩, have interior d ∈ 𝓤 α, by filter_upwards [hs] this, by simp [this]) (assume s hs, ((𝓤 α).lift' interior).sets_of_superset (mem_lift' hs) interior_subset) lemma interior_mem_uniformity {s : set (α × α)} (hs : s ∈ 𝓤 α) : interior s ∈ 𝓤 α := by rw [uniformity_eq_uniformity_interior]; exact mem_lift' hs lemma mem_uniformity_is_closed [uniform_space α] {s : set (α×α)} (h : s ∈ 𝓤 α) : ∃t ∈ 𝓤 α, is_closed t ∧ t ⊆ s := have s ∈ (𝓤 α).lift' closure, by rwa [uniformity_eq_uniformity_closure] at h, have ∃ t ∈ 𝓤 α, closure t ⊆ s, by rwa [mem_lift'_sets] at this; apply closure_mono, let ⟨t, ht, hst⟩ := this in ⟨closure t, (𝓤 α).sets_of_superset ht subset_closure, is_closed_closure, hst⟩ /- uniform continuity -/ def uniform_continuous [uniform_space β] (f : α → β) := tendsto (λx:α×α, (f x.1, f x.2)) (𝓤 α) (𝓤 β) theorem uniform_continuous_def [uniform_space β] {f : α → β} : uniform_continuous f ↔ ∀ r ∈ 𝓤 β, {x : α × α | (f x.1, f x.2) ∈ r} ∈ 𝓤 α := iff.rfl lemma uniform_continuous_of_const [uniform_space β] {c : α → β} (h : ∀a b, c a = c b) : uniform_continuous c := have (λ (x : α × α), (c (x.fst), c (x.snd))) ⁻¹' id_rel = univ, from eq_univ_iff_forall.2 $ assume ⟨a, b⟩, h a b, le_trans (map_le_iff_le_comap.2 $ by simp [comap_principal, this, univ_mem_sets]) refl_le_uniformity lemma uniform_continuous_id : uniform_continuous (@id α) := by simp [uniform_continuous]; exact tendsto_id lemma uniform_continuous_const [uniform_space β] {b : β} : uniform_continuous (λa:α, b) := @tendsto_const_uniformity _ _ _ b (𝓤 α) lemma uniform_continuous.comp [uniform_space β] [uniform_space γ] {f : α → β} {g : β → γ} (hf : uniform_continuous f) (hg : uniform_continuous g) : uniform_continuous (g ∘ f) := hf.comp hg lemma uniform_continuous.continuous [uniform_space β] {f : α → β} (hf : uniform_continuous f) : continuous f := continuous_iff_continuous_at.mpr $ assume a, calc map f (nhds a) ≤ (map (λp:α×α, (f p.1, f p.2)) (𝓤 α)).lift' (λs:set (β×β), {y | (f a, y) ∈ s}) : begin rw [nhds_eq_uniformity, map_lift'_eq, map_lift'_eq2], exact (lift'_mono' $ assume s hs b ⟨a', (ha' : (_, a') ∈ s), a'_eq⟩, ⟨(a, a'), ha', show (f a, f a') = (f a, b), from a'_eq ▸ rfl⟩), exact monotone_preimage, exact monotone_preimage end ... ≤ nhds (f a) : by rw [nhds_eq_uniformity]; exact lift'_mono hf (le_refl _) end uniform_space end local notation `𝓤` := uniformity section constructions variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} {ι : Sort*} instance : partial_order (uniform_space α) := { le := λt s, s.uniformity ≤ t.uniformity, le_antisymm := assume t s h₁ h₂, uniform_space_eq $ le_antisymm h₂ h₁, le_refl := assume t, le_refl _, le_trans := assume a b c h₁ h₂, @le_trans _ _ c.uniformity b.uniformity a.uniformity h₂ h₁ } instance : has_Sup (uniform_space α) := ⟨assume s, uniform_space.of_core { uniformity := (⨅u∈s, @uniformity α u), refl := le_infi $ assume u, le_infi $ assume hu, u.refl, symm := le_infi $ assume u, le_infi $ assume hu, le_trans (map_mono $ infi_le_of_le _ $ infi_le _ hu) u.symm, comp := le_infi $ assume u, le_infi $ assume hu, le_trans (lift'_mono (infi_le_of_le _ $ infi_le _ hu) $ le_refl _) u.comp }⟩ private lemma le_Sup {tt : set (uniform_space α)} {t : uniform_space α} (h : t ∈ tt) : t ≤ Sup tt := show (⨅u∈tt, @uniformity α u) ≤ t.uniformity, from infi_le_of_le t $ infi_le _ h private lemma Sup_le {tt : set (uniform_space α)} {t : uniform_space α} (h : ∀t'∈tt, t' ≤ t) : Sup tt ≤ t := show t.uniformity ≤ (⨅u∈tt, @uniformity α u), from le_infi $ assume t', le_infi $ assume ht', h t' ht' instance : has_bot (uniform_space α) := ⟨uniform_space.of_core { uniformity := ⊤, refl := le_top, symm := le_top, comp := le_top }⟩ instance : has_top (uniform_space α) := ⟨{ to_topological_space := ⊤, uniformity := principal id_rel, refl := le_refl _, symm := by simp [tendsto]; apply subset.refl, comp := begin rw [lift'_principal], {simp}, exact monotone_comp_rel monotone_id monotone_id end, is_open_uniformity := assume s, by simp [is_open_fold, subset_def, id_rel] {contextual := tt } } ⟩ instance : complete_lattice (uniform_space α) := { sup := λa b, Sup {a, b}, le_sup_left := assume a b, le_Sup $ by simp, le_sup_right := assume a b, le_Sup $ by simp, sup_le := assume a b c h₁ h₂, Sup_le $ assume t', begin simp, intro h, cases h with h h, repeat { subst h; assumption } end, inf := λa b, Sup {x | x ≤ a ∧ x ≤ b}, le_inf := assume a b c h₁ h₂, le_Sup ⟨h₁, h₂⟩, inf_le_left := assume a b, Sup_le $ assume x ⟨ha, hb⟩, ha, inf_le_right := assume a b, Sup_le $ assume x ⟨ha, hb⟩, hb, top := ⊤, le_top := assume u, u.refl, bot := ⊥, bot_le := assume a, show a.uniformity ≤ ⊤, from le_top, Sup := Sup, le_Sup := assume s u, le_Sup, Sup_le := assume s u, Sup_le, Inf := λtt, Sup {t | ∀t'∈tt, t ≤ t'}, le_Inf := assume s a hs, le_Sup hs, Inf_le := assume s a ha, Sup_le $ assume u hs, hs _ ha, ..uniform_space.partial_order } lemma supr_uniformity {ι : Sort*} {u : ι → uniform_space α} : (supr u).uniformity = (⨅i, (u i).uniformity) := show (⨅a (h : ∃i:ι, u i = a), a.uniformity) = _, from le_antisymm (le_infi $ assume i, infi_le_of_le (u i) $ infi_le _ ⟨i, rfl⟩) (le_infi $ assume a, le_infi $ assume ⟨i, (ha : u i = a)⟩, ha ▸ infi_le _ _) lemma sup_uniformity {u v : uniform_space α} : (u ⊔ v).uniformity = u.uniformity ⊓ v.uniformity := have (u ⊔ v) = (⨆i (h : i = u ∨ i = v), i), by simp [supr_or, supr_sup_eq], calc (u ⊔ v).uniformity = ((⨆i (h : i = u ∨ i = v), i) : uniform_space α).uniformity : by rw [this] ... = _ : by simp [supr_uniformity, infi_or, infi_inf_eq] instance inhabited_uniform_space : inhabited (uniform_space α) := ⟨⊤⟩ /-- Given `f : α → β` and a uniformity `u` on `β`, the inverse image of `u` under `f` is the inverse image in the filter sense of the induced function `α × α → β × β`. -/ def uniform_space.comap (f : α → β) (u : uniform_space β) : uniform_space α := { uniformity := u.uniformity.comap (λp:α×α, (f p.1, f p.2)), to_topological_space := u.to_topological_space.induced f, refl := le_trans (by simp; exact assume ⟨a, b⟩ (h : a = b), h ▸ rfl) (comap_mono u.refl), symm := by simp [tendsto_comap_iff, prod.swap, (∘)]; exact tendsto_comap.comp tendsto_swap_uniformity, comp := le_trans begin rw [comap_lift'_eq, comap_lift'_eq2], exact (lift'_mono' $ assume s hs ⟨a₁, a₂⟩ ⟨x, h₁, h₂⟩, ⟨f x, h₁, h₂⟩), repeat { exact monotone_comp_rel monotone_id monotone_id } end (comap_mono u.comp), is_open_uniformity := λ s, begin change (@is_open α (u.to_topological_space.induced f) s ↔ _), simp [is_open_iff_nhds, nhds_induced_eq_comap, mem_nhds_uniformity_iff, filter.comap, and_comm], refine ball_congr (λ x hx, ⟨_, _⟩), { rintro ⟨t, hts, ht⟩, refine ⟨_, ht, _⟩, rintro ⟨x₁, x₂⟩ h rfl, exact hts (h rfl) }, { rintro ⟨t, ht, hts⟩, exact ⟨{y | (f x, y) ∈ t}, λ y hy, @hts (x, y) hy rfl, mem_nhds_uniformity_iff.1 $ mem_nhds_left _ ht⟩ } end } lemma uniform_space_comap_id {α : Type*} : uniform_space.comap (id : α → α) = id := by ext u ; dsimp [uniform_space.comap] ; rw [prod.id_prod, filter.comap_id] lemma uniform_space.comap_comap_comp {α β γ} [uγ : uniform_space γ] {f : α → β} {g : β → γ} : uniform_space.comap (g ∘ f) uγ = uniform_space.comap f (uniform_space.comap g uγ) := by ext ; dsimp [uniform_space.comap] ; rw filter.comap_comap_comp lemma uniform_continuous_iff {α β} [uα : uniform_space α] [uβ : uniform_space β] (f : α → β) : uniform_continuous f ↔ uβ.comap f ≤ uα := filter.map_le_iff_le_comap lemma uniform_continuous_comap {f : α → β} [u : uniform_space β] : @uniform_continuous α β (uniform_space.comap f u) u f := tendsto_comap theorem to_topological_space_comap {f : α → β} {u : uniform_space β} : @uniform_space.to_topological_space _ (uniform_space.comap f u) = topological_space.induced f (@uniform_space.to_topological_space β u) := eq_of_nhds_eq_nhds $ assume a, begin simp [nhds_induced_eq_comap, nhds_eq_uniformity, nhds_eq_uniformity], change comap f ((𝓤 β).lift' (preimage (λb, (f a, b)))) = (u.uniformity.comap (λp:α×α, (f p.1, f p.2))).lift' (preimage (λa', (a, a'))), rw [comap_lift'_eq monotone_preimage, comap_lift'_eq2 monotone_preimage], exact rfl end lemma uniform_continuous_comap' {f : γ → β} {g : α → γ} [v : uniform_space β] [u : uniform_space α] (h : uniform_continuous (f ∘ g)) : @uniform_continuous α γ u (uniform_space.comap f v) g := tendsto_comap_iff.2 h lemma to_topological_space_mono {u₁ u₂ : uniform_space α} (h : u₁ ≤ u₂) : @uniform_space.to_topological_space _ u₁ ≤ @uniform_space.to_topological_space _ u₂ := le_of_nhds_le_nhds $ assume a, by rw [@nhds_eq_uniformity α u₁ a, @nhds_eq_uniformity α u₂ a]; exact (lift'_mono h $ le_refl _) lemma to_topological_space_top : @uniform_space.to_topological_space α ⊤ = ⊤ := rfl lemma to_topological_space_bot : @uniform_space.to_topological_space α ⊥ = ⊥ := bot_unique $ assume s hs, classical.by_cases (assume : s = ∅, this.symm ▸ @is_open_empty _ ⊥) (assume : s ≠ ∅, let ⟨x, hx⟩ := exists_mem_of_ne_empty this in have s = univ, from top_unique $ assume y hy, hs x hx (x, y) rfl, this.symm ▸ @is_open_univ _ ⊥) lemma to_topological_space_supr {ι : Sort*} {u : ι → uniform_space α} : @uniform_space.to_topological_space α (supr u) = (⨆i, @uniform_space.to_topological_space α (u i)) := classical.by_cases (assume h : nonempty ι, eq_of_nhds_eq_nhds $ assume a, begin rw [nhds_supr, nhds_eq_uniformity], change _ = (supr u).uniformity.lift' (preimage $ prod.mk a), begin rw [supr_uniformity, lift'_infi], exact (congr_arg _ $ funext $ assume i, @nhds_eq_uniformity α (u i) a), exact h, exact assume a b, rfl end end) (assume : ¬ nonempty ι, le_antisymm (have supr u = ⊥, from bot_unique $ supr_le $ assume i, (this ⟨i⟩).elim, have @uniform_space.to_topological_space _ (supr u) = ⊥, from this.symm ▸ to_topological_space_bot, this.symm ▸ bot_le) (supr_le $ assume i, to_topological_space_mono $ le_supr _ _)) lemma to_topological_space_Sup {s : set (uniform_space α)} : @uniform_space.to_topological_space α (Sup s) = (⨆i∈s, @uniform_space.to_topological_space α i) := begin rw [Sup_eq_supr, to_topological_space_supr], apply congr rfl, funext x, exact to_topological_space_supr end lemma to_topological_space_sup {u v : uniform_space α} : @uniform_space.to_topological_space α (u ⊔ v) = @uniform_space.to_topological_space α u ⊔ @uniform_space.to_topological_space α v := ord_continuous_sup $ assume s, to_topological_space_Sup instance : uniform_space empty := ⊤ instance : uniform_space unit := ⊤ instance : uniform_space bool := ⊤ instance : uniform_space ℕ := ⊤ instance : uniform_space ℤ := ⊤ instance {p : α → Prop} [t : uniform_space α] : uniform_space (subtype p) := uniform_space.comap subtype.val t lemma uniformity_subtype {p : α → Prop} [t : uniform_space α] : 𝓤 (subtype p) = comap (λq:subtype p × subtype p, (q.1.1, q.2.1)) (𝓤 α) := rfl lemma uniform_continuous_subtype_val {p : α → Prop} [uniform_space α] : uniform_continuous (subtype.val : {a : α // p a} → α) := uniform_continuous_comap lemma uniform_continuous_subtype_mk {p : α → Prop} [uniform_space α] [uniform_space β] {f : β → α} (hf : uniform_continuous f) (h : ∀x, p (f x)) : uniform_continuous (λx, ⟨f x, h x⟩ : β → subtype p) := uniform_continuous_comap' hf lemma tendsto_of_uniform_continuous_subtype [uniform_space α] [uniform_space β] {f : α → β} {s : set α} {a : α} (hf : uniform_continuous (λx:s, f x.val)) (ha : s ∈ nhds a) : tendsto f (nhds a) (nhds (f a)) := by rw [(@map_nhds_subtype_val_eq α _ s a (mem_of_nhds ha) ha).symm]; exact tendsto_map' (continuous_iff_continuous_at.mp hf.continuous _) section prod /- a similar product space is possible on the function space (uniformity of pointwise convergence), but we want to have the uniformity of uniform convergence on function spaces -/ instance [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α × β) := uniform_space.of_core_eq (u₁.comap prod.fst ⊔ u₂.comap prod.snd).to_core prod.topological_space (calc prod.topological_space = (u₁.comap prod.fst ⊔ u₂.comap prod.snd).to_topological_space : by rw [to_topological_space_sup, to_topological_space_comap, to_topological_space_comap]; refl ... = _ : by rw [uniform_space.to_core_to_topological_space]) theorem uniformity_prod [uniform_space α] [uniform_space β] : @uniformity (α × β) _ = (𝓤 α).comap (λp:(α × β) × α × β, (p.1.1, p.2.1)) ⊓ (𝓤 β).comap (λp:(α × β) × α × β, (p.1.2, p.2.2)) := sup_uniformity lemma uniformity_prod_eq_prod [uniform_space α] [uniform_space β] : 𝓤 (α×β) = map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) (filter.prod (𝓤 α) (𝓤 β)) := have map (λp:(α×α)×(β×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))) = comap (λp:(α×β)×(α×β), ((p.1.1, p.2.1), (p.1.2, p.2.2))), from funext $ assume f, map_eq_comap_of_inverse (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl) (funext $ assume ⟨⟨_, _⟩, ⟨_, _⟩⟩, rfl), by rw [this, uniformity_prod, filter.prod, comap_inf, comap_comap_comp, comap_comap_comp] lemma mem_map_sets_iff' {α : Type*} {β : Type*} {f : filter α} {m : α → β} {t : set β} : t ∈ (map m f).sets ↔ (∃s∈f, m '' s ⊆ t) := mem_map_sets_iff lemma mem_uniformity_of_uniform_continuous_invarant [uniform_space α] {s:set (α×α)} {f : α → α → α} (hf : uniform_continuous (λp:α×α, f p.1 p.2)) (hs : s ∈ 𝓤 α) : ∃u∈𝓤 α, ∀a b c, (a, b) ∈ u → (f a c, f b c) ∈ s := begin rw [uniform_continuous, uniformity_prod_eq_prod, tendsto_map'_iff, (∘)] at hf, rcases mem_map_sets_iff'.1 (hf hs) with ⟨t, ht, hts⟩, clear hf, rcases mem_prod_iff.1 ht with ⟨u, hu, v, hv, huvt⟩, clear ht, refine ⟨u, hu, assume a b c hab, hts $ (mem_image _ _ _).2 ⟨⟨⟨a, b⟩, ⟨c, c⟩⟩, huvt ⟨_, _⟩, _⟩⟩, exact hab, exact refl_mem_uniformity hv, refl end lemma mem_uniform_prod [t₁ : uniform_space α] [t₂ : uniform_space β] {a : set (α × α)} {b : set (β × β)} (ha : a ∈ 𝓤 α) (hb : b ∈ 𝓤 β) : {p:(α×β)×(α×β) | (p.1.1, p.2.1) ∈ a ∧ (p.1.2, p.2.2) ∈ b } ∈ (@uniformity (α × β) _) := by rw [uniformity_prod]; exact inter_mem_inf_sets (preimage_mem_comap ha) (preimage_mem_comap hb) lemma tendsto_prod_uniformity_fst [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.1, p.2.1)) (𝓤 (α × β)) (𝓤 α) := le_trans (map_mono (@le_sup_left (uniform_space (α×β)) _ _ _)) map_comap_le lemma tendsto_prod_uniformity_snd [uniform_space α] [uniform_space β] : tendsto (λp:(α×β)×(α×β), (p.1.2, p.2.2)) (𝓤 (α × β)) (𝓤 β) := le_trans (map_mono (@le_sup_right (uniform_space (α×β)) _ _ _)) map_comap_le lemma uniform_continuous_fst [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.1) := tendsto_prod_uniformity_fst lemma uniform_continuous_snd [uniform_space α] [uniform_space β] : uniform_continuous (λp:α×β, p.2) := tendsto_prod_uniformity_snd variables [uniform_space α] [uniform_space β] [uniform_space γ] lemma uniform_continuous.prod_mk {f₁ : α → β} {f₂ : α → γ} (h₁ : uniform_continuous f₁) (h₂ : uniform_continuous f₂) : uniform_continuous (λa, (f₁ a, f₂ a)) := by rw [uniform_continuous, uniformity_prod]; exact tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma uniform_continuous.prod_mk_left {f : α × β → γ} (h : uniform_continuous f) (b) : uniform_continuous (λ a, f (a,b)) := (uniform_continuous_id.prod_mk uniform_continuous_const).comp h lemma uniform_continuous.prod_mk_right {f : α × β → γ} (h : uniform_continuous f) (a) : uniform_continuous (λ b, f (a,b)) := (uniform_continuous_const.prod_mk uniform_continuous_id).comp h lemma to_topological_space_prod [u : uniform_space α] [v : uniform_space β] : @uniform_space.to_topological_space (α × β) prod.uniform_space = @prod.topological_space α β u.to_topological_space v.to_topological_space := rfl end prod lemma to_topological_space_subtype [u : uniform_space α] {p : α → Prop} : @uniform_space.to_topological_space (subtype p) subtype.uniform_space = @subtype.topological_space α p u.to_topological_space := rfl section sum variables [uniform_space α] [uniform_space β] open sum /-- Uniformity on a disjoint union. Entourages of the diagonal in the union are obtained by taking independently an entourage of the diagonal in the first part, and an entourage of the diagonal in the second part. -/ def uniform_space.core.sum : uniform_space.core (α ⊕ β) := uniform_space.core.mk' (map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β)) (λ r ⟨H₁, H₂⟩ x, by cases x; [apply refl_mem_uniformity H₁, apply refl_mem_uniformity H₂]) (λ r ⟨H₁, H₂⟩, ⟨symm_le_uniformity H₁, symm_le_uniformity H₂⟩) (λ r ⟨Hrα, Hrβ⟩, begin rcases comp_mem_uniformity_sets Hrα with ⟨tα, htα, Htα⟩, rcases comp_mem_uniformity_sets Hrβ with ⟨tβ, htβ, Htβ⟩, refine ⟨_, ⟨mem_map_sets_iff.2 ⟨tα, htα, subset_union_left _ _⟩, mem_map_sets_iff.2 ⟨tβ, htβ, subset_union_right _ _⟩⟩, _⟩, rintros ⟨_, _⟩ ⟨z, ⟨⟨a, b⟩, hab, ⟨⟩⟩ | ⟨⟨a, b⟩, hab, ⟨⟩⟩, ⟨⟨_, c⟩, hbc, ⟨⟩⟩ | ⟨⟨_, c⟩, hbc, ⟨⟩⟩⟩, { have A : (a, c) ∈ comp_rel tα tα := ⟨b, hab, hbc⟩, exact Htα A }, { have A : (a, c) ∈ comp_rel tβ tβ := ⟨b, hab, hbc⟩, exact Htβ A } end) /-- The union of an entourage of the diagonal in each set of a disjoint union is again an entourage of the diagonal. -/ lemma union_mem_uniformity_sum {a : set (α × α)} (ha : a ∈ 𝓤 α) {b : set (β × β)} (hb : b ∈ 𝓤 β) : ((λ p : (α × α), (inl p.1, inl p.2)) '' a ∪ (λ p : (β × β), (inr p.1, inr p.2)) '' b) ∈ (@uniform_space.core.sum α β _ _).uniformity := ⟨mem_map_sets_iff.2 ⟨_, ha, subset_union_left _ _⟩, mem_map_sets_iff.2 ⟨_, hb, subset_union_right _ _⟩⟩ /- To prove that the topology defined by the uniform structure on the disjoint union coincides with the disjoint union topology, we need two lemmas saying that open sets can be characterized by the uniform structure -/ lemma uniformity_sum_of_open_aux {s : set (α ⊕ β)} (hs : is_open s) {x : α ⊕ β} (xs : x ∈ s) : { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity := begin cases x, { refine mem_sets_of_superset (union_mem_uniformity_sum (mem_nhds_uniformity_iff.1 (mem_nhds_sets hs.1 xs)) univ_mem_sets) (union_subset _ _); rintro _ ⟨⟨_, b⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, { refine mem_sets_of_superset (union_mem_uniformity_sum univ_mem_sets (mem_nhds_uniformity_iff.1 (mem_nhds_sets hs.2 xs))) (union_subset _ _); rintro _ ⟨⟨a, _⟩, h, ⟨⟩⟩ ⟨⟩, exact h rfl }, end lemma open_of_uniformity_sum_aux {s : set (α ⊕ β)} (hs : ∀x ∈ s, { p : ((α ⊕ β) × (α ⊕ β)) | p.1 = x → p.2 ∈ s } ∈ (@uniform_space.core.sum α β _ _).uniformity) : is_open s := begin split, { refine (@is_open_iff_mem_nhds α _ _).2 (λ a ha, mem_nhds_uniformity_iff.2 _), rcases mem_map_sets_iff.1 (hs _ ha).1 with ⟨t, ht, st⟩, refine mem_sets_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl }, { refine (@is_open_iff_mem_nhds β _ _).2 (λ b hb, mem_nhds_uniformity_iff.2 _), rcases mem_map_sets_iff.1 (hs _ hb).2 with ⟨t, ht, st⟩, refine mem_sets_of_superset ht _, rintro p pt rfl, exact st ⟨_, pt, rfl⟩ rfl } end /- We can now define the uniform structure on the disjoint union -/ instance sum.uniform_space [u₁ : uniform_space α] [u₂ : uniform_space β] : uniform_space (α ⊕ β) := { to_core := uniform_space.core.sum, is_open_uniformity := λ s, ⟨uniformity_sum_of_open_aux, open_of_uniformity_sum_aux⟩ } lemma sum.uniformity [uniform_space α] [uniform_space β] : 𝓤 (α ⊕ β) = map (λ p : α × α, (inl p.1, inl p.2)) (𝓤 α) ⊔ map (λ p : β × β, (inr p.1, inr p.2)) (𝓤 β) := rfl end sum end constructions lemma lebesgue_number_lemma {α : Type u} [uniform_space α] {s : set α} {ι} {c : ι → set α} (hs : compact s) (hc₁ : ∀ i, is_open (c i)) (hc₂ : s ⊆ ⋃ i, c i) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ i, {y | (x, y) ∈ n} ⊆ c i := begin let u := λ n, {x | ∃ i (m ∈ 𝓤 α), {y | (x, y) ∈ comp_rel m n} ⊆ c i}, have hu₁ : ∀ n ∈ 𝓤 α, is_open (u n), { refine λ n hn, is_open_uniformity.2 _, rintro x ⟨i, m, hm, h⟩, rcases comp_mem_uniformity_sets hm with ⟨m', hm', mm'⟩, apply (𝓤 α).sets_of_superset hm', rintros ⟨x, y⟩ hp rfl, refine ⟨i, m', hm', λ z hz, h (monotone_comp_rel monotone_id monotone_const mm' _)⟩, dsimp at hz ⊢, rw comp_rel_assoc, exact ⟨y, hp, hz⟩ }, have hu₂ : s ⊆ ⋃ n ∈ 𝓤 α, u n, { intros x hx, rcases mem_Union.1 (hc₂ hx) with ⟨i, h⟩, rcases comp_mem_uniformity_sets (is_open_uniformity.1 (hc₁ i) x h) with ⟨m', hm', mm'⟩, exact mem_bUnion hm' ⟨i, _, hm', λ y hy, mm' hy rfl⟩ }, rcases compact_elim_finite_subcover_image hs hu₁ hu₂ with ⟨b, bu, b_fin, b_cover⟩, refine ⟨_, Inter_mem_sets b_fin bu, λ x hx, _⟩, rcases mem_bUnion_iff.1 (b_cover hx) with ⟨n, bn, i, m, hm, h⟩, refine ⟨i, λ y hy, h _⟩, exact prod_mk_mem_comp_rel (refl_mem_uniformity hm) (bInter_subset_of_mem bn hy) end lemma lebesgue_number_lemma_sUnion {α : Type u} [uniform_space α] {s : set α} {c : set (set α)} (hs : compact s) (hc₁ : ∀ t ∈ c, is_open t) (hc₂ : s ⊆ ⋃₀ c) : ∃ n ∈ 𝓤 α, ∀ x ∈ s, ∃ t ∈ c, ∀ y, (x, y) ∈ n → y ∈ t := by rw sUnion_eq_Union at hc₂; simpa using lebesgue_number_lemma hs (by simpa) hc₂
708a654445d939982c372f811c890ec15fbe00b2
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/eq12.lean
5bc9830f633718ee91613d21950d464b6affe22f
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
498
lean
open nat bool inhabited definition diag : bool → bool → bool → nat | diag _ tt ff := 1 | diag ff _ tt := 2 | diag tt ff _ := 3 | diag _ _ _ := arbitrary nat theorem diag1 (a : bool) : diag a tt ff = 1 := bool.cases_on a rfl rfl theorem diag2 (a : bool) : diag ff a tt = 2 := bool.cases_on a rfl rfl theorem diag3 (a : bool) : diag tt ff a = 3 := bool.cases_on a rfl rfl theorem diag4_1 : diag ff ff ff = arbitrary nat := rfl theorem diag4_2 : diag tt tt tt = arbitrary nat := rfl
b08fa16bb7ff1a3ca88dd94ead08865e6decc6b9
7cdf3413c097e5d36492d12cdd07030eb991d394
/world_experiments/world8/level12.lean
a7cdd843824325b37cf9cefd1b89d207722ee1ae
[]
no_license
alreadydone/natural_number_game
3135b9385a9f43e74cfbf79513fc37e69b99e0b3
1a39e693df4f4e871eb449890d3c7715a25c2ec9
refs/heads/master
1,599,387,390,105
1,573,200,587,000
1,573,200,691,000
220,397,084
0
0
null
1,573,192,734,000
1,573,192,733,000
null
UTF-8
Lean
false
false
1,115
lean
import game.world3.level11 -- hide import game.world2.level13 -- add_left_eq_zero -- hide namespace mynat -- hide /- # Multiplication World ## Level 12: `mul_left_cancel` This is the last but one of the bonus multiplication levels. `mul_left_cancel` will be useful in inequality world. But before that we have a relatively short power world. -/ /- Theorem If $a \neq 0$, $b$ and $c$ are natural numbers such that $$ a * b = a * c, $$ then $b = c$. -/ theorem mul_left_cancel ⦃a b c : mynat⦄ (ha : a ≠ 0) : a * b = a * c → b = c := begin [less_leaky] revert b, induction c with d hd, { intro b, rw mul_zero, intro h, cases (eq_zero_or_eq_zero_of_mul_eq_zero h), exfalso, apply ha, assumption, assumption }, { intros b hb, cases b with c, { rw mul_zero at hb, rw mul_succ at hb, exfalso, apply ha, rw eq_comm at hb, apply add_left_eq_zero hb, }, { congr, -- c = d -> succ c = succ d apply hd, rw mul_succ at hb, rw mul_succ at hb, apply add_right_cancel hb } } end end mynat -- hide
857d1c4560546792bf62cd6e3356045f49475da1
958488bc7f3c2044206e0358e56d7690b6ae696c
/lean/inaccessible.lean
552a287d56afc890630c611c7c8fab81e139b8e8
[]
no_license
possientis/Prog
a08eec1c1b121c2fd6c70a8ae89e2fbef952adb4
d4b3debc37610a88e0dac3ac5914903604fd1d1f
refs/heads/master
1,692,263,717,723
1,691,757,179,000
1,691,757,179,000
40,361,602
3
0
null
1,679,896,438,000
1,438,953,859,000
Coq
UTF-8
Lean
false
false
607
lean
universe u inductive ImageOf {α β : Type u} (f : α → β) : β → Type u | Imf : ∀ (x : α), ImageOf (f x) open ImageOf def inverse {α β : Type u} {f : α → β} : ∀ (y : β), ImageOf f y → α | .(f x) (Imf .(f) x) := x inductive Vec (α : Type u) : ℕ → Type u | Nil {} : Vec 0 | Cons : ∀ {n : ℕ}, α → Vec n → Vec (n + 1) open Vec namespace Vec local notation x :: xs := Cons x xs variable {α : Type u} def add [has_add α] : ∀ {n : ℕ}, Vec α n → Vec α n → Vec α n | 0 Nil Nil := Nil | (n + 1) (Cons x xs) (Cons y ys) := Cons (x + y) (add xs ys) end Vec
c8db5dbbe074738ac7a16a25c47ac73a69688b6e
9dc8cecdf3c4634764a18254e94d43da07142918
/src/linear_algebra/matrix/determinant.lean
8c398e048380fe43c2dab19b8d8efefe119ca910
[ "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
31,771
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Chris Hughes, Tim Baanen -/ import data.matrix.pequiv import data.matrix.block import data.matrix.notation import data.fintype.card import group_theory.perm.fin import group_theory.perm.sign import algebra.algebra.basic import tactic.ring import linear_algebra.alternating import linear_algebra.pi /-! # Determinant of a matrix This file defines the determinant of a matrix, `matrix.det`, and its essential properties. ## Main definitions - `matrix.det`: the determinant of a square matrix, as a sum over permutations - `matrix.det_row_alternating`: the determinant, as an `alternating_map` in the rows of the matrix ## Main results - `det_mul`: the determinant of `A ⬝ B` is the product of determinants - `det_zero_of_row_eq`: the determinant is zero if there is a repeated row - `det_block_diagonal`: the determinant of a block diagonal matrix is a product of the blocks' determinants ## Implementation notes It is possible to configure `simp` to compute determinants. See the file `test/matrix.lean` for some examples. -/ universes u v w z open equiv equiv.perm finset function namespace matrix open_locale matrix big_operators variables {m n : Type*} [decidable_eq n] [fintype n] [decidable_eq m] [fintype m] variables {R : Type v} [comm_ring R] local notation `ε ` σ:max := ((sign σ : ℤ) : R) /-- `det` is an `alternating_map` in the rows of the matrix. -/ def det_row_alternating : alternating_map R (n → R) R n := ((multilinear_map.mk_pi_algebra R n R).comp_linear_map (linear_map.proj)).alternatization /-- The determinant of a matrix given by the Leibniz formula. -/ abbreviation det (M : matrix n n R) : R := det_row_alternating M lemma det_apply (M : matrix n n R) : M.det = ∑ σ : perm n, σ.sign • ∏ i, M (σ i) i := multilinear_map.alternatization_apply _ M -- This is what the old definition was. We use it to avoid having to change the old proofs below lemma det_apply' (M : matrix n n R) : M.det = ∑ σ : perm n, ε σ * ∏ i, M (σ i) i := by simp [det_apply, units.smul_def] @[simp] lemma det_diagonal {d : n → R} : det (diagonal d) = ∏ i, d i := begin rw det_apply', refine (finset.sum_eq_single 1 _ _).trans _, { intros σ h1 h2, cases not_forall.1 (mt equiv.ext h2) with x h3, convert mul_zero _, apply finset.prod_eq_zero, { change x ∈ _, simp }, exact if_neg h3 }, { simp }, { simp } end @[simp] lemma det_zero (h : nonempty n) : det (0 : matrix n n R) = 0 := (det_row_alternating : alternating_map R (n → R) R n).map_zero @[simp] lemma det_one : det (1 : matrix n n R) = 1 := by rw [← diagonal_one]; simp [-diagonal_one] lemma det_is_empty [is_empty n] {A : matrix n n R} : det A = 1 := by simp [det_apply] @[simp] lemma coe_det_is_empty [is_empty n] : (det : matrix n n R → R) = function.const _ 1 := by { ext, exact det_is_empty, } lemma det_eq_one_of_card_eq_zero {A : matrix n n R} (h : fintype.card n = 0) : det A = 1 := begin haveI : is_empty n := fintype.card_eq_zero_iff.mp h, exact det_is_empty, end /-- If `n` has only one element, the determinant of an `n` by `n` matrix is just that element. Although `unique` implies `decidable_eq` and `fintype`, the instances might not be syntactically equal. Thus, we need to fill in the args explicitly. -/ @[simp] lemma det_unique {n : Type*} [unique n] [decidable_eq n] [fintype n] (A : matrix n n R) : det A = A default default := by simp [det_apply, univ_unique] lemma det_eq_elem_of_subsingleton [subsingleton n] (A : matrix n n R) (k : n) : det A = A k k := begin convert det_unique _, exact unique_of_subsingleton k end lemma det_eq_elem_of_card_eq_one {A : matrix n n R} (h : fintype.card n = 1) (k : n) : det A = A k k := begin haveI : subsingleton n := fintype.card_le_one_iff_subsingleton.mp h.le, exact det_eq_elem_of_subsingleton _ _ end lemma det_mul_aux {M N : matrix n n R} {p : n → n} (H : ¬bijective p) : ∑ σ : perm n, (ε σ) * ∏ x, (M (σ x) (p x) * N (p x) x) = 0 := begin obtain ⟨i, j, hpij, hij⟩ : ∃ i j, p i = p j ∧ i ≠ j, { rw [← finite.injective_iff_bijective, injective] at H, push_neg at H, exact H }, exact sum_involution (λ σ _, σ * swap i j) (λ σ _, have ∏ x, M (σ x) (p x) = ∏ x, M ((σ * swap i j) x) (p x), from fintype.prod_equiv (swap i j) _ _ (by simp [apply_swap_eq_self hpij]), by simp [this, sign_swap hij, prod_mul_distrib]) (λ σ _ _, (not_congr mul_swap_eq_iff).mpr hij) (λ _ _, mem_univ _) (λ σ _, mul_swap_involutive i j σ) end @[simp] lemma det_mul (M N : matrix n n R) : det (M ⬝ N) = det M * det N := calc det (M ⬝ N) = ∑ p : n → n, ∑ σ : perm n, ε σ * ∏ i, (M (σ i) (p i) * N (p i) i) : by simp only [det_apply', mul_apply, prod_univ_sum, mul_sum, fintype.pi_finset_univ]; rw [finset.sum_comm] ... = ∑ p in (@univ (n → n) _).filter bijective, ∑ σ : perm n, ε σ * ∏ i, (M (σ i) (p i) * N (p i) i) : eq.symm $ sum_subset (filter_subset _ _) (λ f _ hbij, det_mul_aux $ by simpa only [true_and, mem_filter, mem_univ] using hbij) ... = ∑ τ : perm n, ∑ σ : perm n, ε σ * ∏ i, (M (σ i) (τ i) * N (τ i) i) : sum_bij (λ p h, equiv.of_bijective p (mem_filter.1 h).2) (λ _ _, mem_univ _) (λ _ _, rfl) (λ _ _ _ _ h, by injection h) (λ b _, ⟨b, mem_filter.2 ⟨mem_univ _, b.bijective⟩, coe_fn_injective rfl⟩) ... = ∑ σ : perm n, ∑ τ : perm n, (∏ i, N (σ i) i) * ε τ * (∏ j, M (τ j) (σ j)) : by simp only [mul_comm, mul_left_comm, prod_mul_distrib, mul_assoc] ... = ∑ σ : perm n, ∑ τ : perm n, (((∏ i, N (σ i) i) * (ε σ * ε τ)) * ∏ i, M (τ i) i) : sum_congr rfl (λ σ _, fintype.sum_equiv (equiv.mul_right σ⁻¹) _ _ (λ τ, have ∏ j, M (τ j) (σ j) = ∏ j, M ((τ * σ⁻¹) j) j, by { rw ← (σ⁻¹ : _ ≃ _).prod_comp, simp only [equiv.perm.coe_mul, apply_inv_self] }, have h : ε σ * ε (τ * σ⁻¹) = ε τ := calc ε σ * ε (τ * σ⁻¹) = ε ((τ * σ⁻¹) * σ) : by { rw [mul_comm, sign_mul (τ * σ⁻¹)], simp only [int.cast_mul, units.coe_mul] } ... = ε τ : by simp only [inv_mul_cancel_right], by { simp_rw [equiv.coe_mul_right, h], simp only [this] })) ... = det M * det N : by simp only [det_apply', finset.mul_sum, mul_comm, mul_left_comm] /-- The determinant of a matrix, as a monoid homomorphism. -/ def det_monoid_hom : matrix n n R →* R := { to_fun := det, map_one' := det_one, map_mul' := det_mul } @[simp] lemma coe_det_monoid_hom : (det_monoid_hom : matrix n n R → R) = det := rfl /-- On square matrices, `mul_comm` applies under `det`. -/ lemma det_mul_comm (M N : matrix m m R) : det (M ⬝ N) = det (N ⬝ M) := by rw [det_mul, det_mul, mul_comm] /-- On square matrices, `mul_left_comm` applies under `det`. -/ lemma det_mul_left_comm (M N P : matrix m m R) : det (M ⬝ (N ⬝ P)) = det (N ⬝ (M ⬝ P)) := by rw [←matrix.mul_assoc, ←matrix.mul_assoc, det_mul, det_mul_comm M N, ←det_mul] /-- On square matrices, `mul_right_comm` applies under `det`. -/ lemma det_mul_right_comm (M N P : matrix m m R) : det (M ⬝ N ⬝ P) = det (M ⬝ P ⬝ N) := by rw [matrix.mul_assoc, matrix.mul_assoc, det_mul, det_mul_comm N P, ←det_mul] lemma det_units_conj (M : (matrix m m R)ˣ) (N : matrix m m R) : det (↑M ⬝ N ⬝ ↑M⁻¹ : matrix m m R) = det N := by rw [det_mul_right_comm, ←mul_eq_mul, ←mul_eq_mul, units.mul_inv, one_mul] lemma det_units_conj' (M : (matrix m m R)ˣ) (N : matrix m m R) : det (↑M⁻¹ ⬝ N ⬝ ↑M : matrix m m R) = det N := det_units_conj M⁻¹ N /-- Transposing a matrix preserves the determinant. -/ @[simp] lemma det_transpose (M : matrix n n R) : Mᵀ.det = M.det := begin rw [det_apply', det_apply'], refine fintype.sum_bijective _ inv_involutive.bijective _ _ _, intros σ, rw sign_inv, congr' 1, apply fintype.prod_equiv σ, intros, simp end /-- Permuting the columns changes the sign of the determinant. -/ lemma det_permute (σ : perm n) (M : matrix n n R) : matrix.det (λ i, M (σ i)) = σ.sign * M.det := ((det_row_alternating : alternating_map R (n → R) R n).map_perm M σ).trans (by simp [units.smul_def]) /-- Permuting rows and columns with the same equivalence has no effect. -/ @[simp] lemma det_submatrix_equiv_self (e : n ≃ m) (A : matrix m m R) : det (A.submatrix e e) = det A := begin rw [det_apply', det_apply'], apply fintype.sum_equiv (equiv.perm_congr e), intro σ, rw equiv.perm.sign_perm_congr e σ, congr' 1, apply fintype.prod_equiv e, intro i, rw [equiv.perm_congr_apply, equiv.symm_apply_apply, submatrix_apply], end /-- Reindexing both indices along the same equivalence preserves the determinant. For the `simp` version of this lemma, see `det_submatrix_equiv_self`; this one is unsuitable because `matrix.reindex_apply` unfolds `reindex` first. -/ lemma det_reindex_self (e : m ≃ n) (A : matrix m m R) : det (reindex e e A) = det A := det_submatrix_equiv_self e.symm A /-- The determinant of a permutation matrix equals its sign. -/ @[simp] lemma det_permutation (σ : perm n) : matrix.det (σ.to_pequiv.to_matrix : matrix n n R) = σ.sign := by rw [←matrix.mul_one (σ.to_pequiv.to_matrix : matrix n n R), pequiv.to_pequiv_mul_matrix, det_permute, det_one, mul_one] lemma det_smul (A : matrix n n R) (c : R) : det (c • A) = c ^ fintype.card n * det A := calc det (c • A) = det (matrix.mul (diagonal (λ _, c)) A) : by rw [smul_eq_diagonal_mul] ... = det (diagonal (λ _, c)) * det A : det_mul _ _ ... = c ^ fintype.card n * det A : by simp [card_univ] @[simp] lemma det_smul_of_tower {α} [monoid α] [distrib_mul_action α R] [is_scalar_tower α R R] [smul_comm_class α R R] (c : α) (A : matrix n n R) : det (c • A) = c ^ fintype.card n • det A := by rw [←smul_one_smul R c A, det_smul, smul_pow, one_pow, smul_mul_assoc, one_mul] lemma det_neg (A : matrix n n R) : det (-A) = (-1) ^ fintype.card n * det A := by rw [←det_smul, neg_one_smul] /-- A variant of `matrix.det_neg` with scalar multiplication by `units ℤ` instead of multiplication by `R`. -/ lemma det_neg_eq_smul (A : matrix n n R) : det (-A) = (-1 : units ℤ) ^ fintype.card n • det A := by rw [←det_smul_of_tower, units.neg_smul, one_smul] /-- Multiplying each row by a fixed `v i` multiplies the determinant by the product of the `v`s. -/ lemma det_mul_row (v : n → R) (A : matrix n n R) : det (of $ λ i j, v j * A i j) = (∏ i, v i) * det A := calc det (of $ λ i j, v j * A i j) = det (A ⬝ diagonal v) : congr_arg det $ by { ext, simp [mul_comm] } ... = (∏ i, v i) * det A : by rw [det_mul, det_diagonal, mul_comm] /-- Multiplying each column by a fixed `v j` multiplies the determinant by the product of the `v`s. -/ lemma det_mul_column (v : n → R) (A : matrix n n R) : det (of $ λ i j, v i * A i j) = (∏ i, v i) * det A := multilinear_map.map_smul_univ _ v A @[simp] lemma det_pow (M : matrix m m R) (n : ℕ) : det (M ^ n) = (det M) ^ n := (det_monoid_hom : matrix m m R →* R).map_pow M n section hom_map variables {S : Type w} [comm_ring S] lemma _root_.ring_hom.map_det (f : R →+* S) (M : matrix n n R) : f M.det = matrix.det (f.map_matrix M) := by simp [matrix.det_apply', f.map_sum, f.map_prod] lemma _root_.ring_equiv.map_det (f : R ≃+* S) (M : matrix n n R) : f M.det = matrix.det (f.map_matrix M) := f.to_ring_hom.map_det _ lemma _root_.alg_hom.map_det [algebra R S] {T : Type z} [comm_ring T] [algebra R T] (f : S →ₐ[R] T) (M : matrix n n S) : f M.det = matrix.det (f.map_matrix M) := f.to_ring_hom.map_det _ lemma _root_.alg_equiv.map_det [algebra R S] {T : Type z} [comm_ring T] [algebra R T] (f : S ≃ₐ[R] T) (M : matrix n n S) : f M.det = matrix.det (f.map_matrix M) := f.to_alg_hom.map_det _ end hom_map @[simp] lemma det_conj_transpose [star_ring R] (M : matrix m m R) : det (Mᴴ) = star (det M) := ((star_ring_end R).map_det _).symm.trans $ congr_arg star M.det_transpose section det_zero /-! ### `det_zero` section Prove that a matrix with a repeated column has determinant equal to zero. -/ lemma det_eq_zero_of_row_eq_zero {A : matrix n n R} (i : n) (h : ∀ j, A i j = 0) : det A = 0 := (det_row_alternating : alternating_map R (n → R) R n).map_coord_zero i (funext h) lemma det_eq_zero_of_column_eq_zero {A : matrix n n R} (j : n) (h : ∀ i, A i j = 0) : det A = 0 := by { rw ← det_transpose, exact det_eq_zero_of_row_eq_zero j h, } variables {M : matrix n n R} {i j : n} /-- If a matrix has a repeated row, the determinant will be zero. -/ theorem det_zero_of_row_eq (i_ne_j : i ≠ j) (hij : M i = M j) : M.det = 0 := (det_row_alternating : alternating_map R (n → R) R n).map_eq_zero_of_eq M hij i_ne_j /-- If a matrix has a repeated column, the determinant will be zero. -/ theorem det_zero_of_column_eq (i_ne_j : i ≠ j) (hij : ∀ k, M k i = M k j) : M.det = 0 := by { rw [← det_transpose, det_zero_of_row_eq i_ne_j], exact funext hij } end det_zero lemma det_update_row_add (M : matrix n n R) (j : n) (u v : n → R) : det (update_row M j $ u + v) = det (update_row M j u) + det (update_row M j v) := (det_row_alternating : alternating_map R (n → R) R n).map_add M j u v lemma det_update_column_add (M : matrix n n R) (j : n) (u v : n → R) : det (update_column M j $ u + v) = det (update_column M j u) + det (update_column M j v) := begin rw [← det_transpose, ← update_row_transpose, det_update_row_add], simp [update_row_transpose, det_transpose] end lemma det_update_row_smul (M : matrix n n R) (j : n) (s : R) (u : n → R) : det (update_row M j $ s • u) = s * det (update_row M j u) := (det_row_alternating : alternating_map R (n → R) R n).map_smul M j s u lemma det_update_column_smul (M : matrix n n R) (j : n) (s : R) (u : n → R) : det (update_column M j $ s • u) = s * det (update_column M j u) := begin rw [← det_transpose, ← update_row_transpose, det_update_row_smul], simp [update_row_transpose, det_transpose] end lemma det_update_row_smul' (M : matrix n n R) (j : n) (s : R) (u : n → R) : det (update_row (s • M) j u) = s ^ (fintype.card n - 1) * det (update_row M j u) := multilinear_map.map_update_smul _ M j s u lemma det_update_column_smul' (M : matrix n n R) (j : n) (s : R) (u : n → R) : det (update_column (s • M) j u) = s ^ (fintype.card n - 1) * det (update_column M j u) := begin rw [← det_transpose, ← update_row_transpose, transpose_smul, det_update_row_smul'], simp [update_row_transpose, det_transpose] end section det_eq /-! ### `det_eq` section Lemmas showing the determinant is invariant under a variety of operations. -/ lemma det_eq_of_eq_mul_det_one {A B : matrix n n R} (C : matrix n n R) (hC : det C = 1) (hA : A = B ⬝ C) : det A = det B := calc det A = det (B ⬝ C) : congr_arg _ hA ... = det B * det C : det_mul _ _ ... = det B : by rw [hC, mul_one] lemma det_eq_of_eq_det_one_mul {A B : matrix n n R} (C : matrix n n R) (hC : det C = 1) (hA : A = C ⬝ B) : det A = det B := calc det A = det (C ⬝ B) : congr_arg _ hA ... = det C * det B : det_mul _ _ ... = det B : by rw [hC, one_mul] lemma det_update_row_add_self (A : matrix n n R) {i j : n} (hij : i ≠ j) : det (update_row A i (A i + A j)) = det A := by simp [det_update_row_add, det_zero_of_row_eq hij ((update_row_self).trans (update_row_ne hij.symm).symm)] lemma det_update_column_add_self (A : matrix n n R) {i j : n} (hij : i ≠ j) : det (update_column A i (λ k, A k i + A k j)) = det A := by { rw [← det_transpose, ← update_row_transpose, ← det_transpose A], exact det_update_row_add_self Aᵀ hij } lemma det_update_row_add_smul_self (A : matrix n n R) {i j : n} (hij : i ≠ j) (c : R) : det (update_row A i (A i + c • A j)) = det A := by simp [det_update_row_add, det_update_row_smul, det_zero_of_row_eq hij ((update_row_self).trans (update_row_ne hij.symm).symm)] lemma det_update_column_add_smul_self (A : matrix n n R) {i j : n} (hij : i ≠ j) (c : R) : det (update_column A i (λ k, A k i + c • A k j)) = det A := by { rw [← det_transpose, ← update_row_transpose, ← det_transpose A], exact det_update_row_add_smul_self Aᵀ hij c } lemma det_eq_of_forall_row_eq_smul_add_const_aux {A B : matrix n n R} {s : finset n} : ∀ (c : n → R) (hs : ∀ i, i ∉ s → c i = 0) (k : n) (hk : k ∉ s) (A_eq : ∀ i j, A i j = B i j + c i * B k j), det A = det B := begin revert B, refine s.induction_on _ _, { intros A c hs k hk A_eq, have : ∀ i, c i = 0, { intros i, specialize hs i, contrapose! hs, simp [hs] }, congr, ext i j, rw [A_eq, this, zero_mul, add_zero], }, { intros i s hi ih B c hs k hk A_eq, have hAi : A i = B i + c i • B k := funext (A_eq i), rw [@ih (update_row B i (A i)) (function.update c i 0), hAi, det_update_row_add_smul_self], { exact mt (λ h, show k ∈ insert i s, from h ▸ finset.mem_insert_self _ _) hk }, { intros i' hi', rw function.update_apply, split_ifs with hi'i, { refl }, { exact hs i' (λ h, hi' ((finset.mem_insert.mp h).resolve_left hi'i)) } }, { exact λ h, hk (finset.mem_insert_of_mem h) }, { intros i' j', rw [update_row_apply, function.update_apply], split_ifs with hi'i, { simp [hi'i] }, rw [A_eq, update_row_ne (λ (h : k = i), hk $ h ▸ finset.mem_insert_self k s)] } } end /-- If you add multiples of row `B k` to other rows, the determinant doesn't change. -/ lemma det_eq_of_forall_row_eq_smul_add_const {A B : matrix n n R} (c : n → R) (k : n) (hk : c k = 0) (A_eq : ∀ i j, A i j = B i j + c i * B k j) : det A = det B := det_eq_of_forall_row_eq_smul_add_const_aux c (λ i, not_imp_comm.mp $ λ hi, finset.mem_erase.mpr ⟨mt (λ (h : i = k), show c i = 0, from h.symm ▸ hk) hi, finset.mem_univ i⟩) k (finset.not_mem_erase k finset.univ) A_eq lemma det_eq_of_forall_row_eq_smul_add_pred_aux {n : ℕ} (k : fin (n + 1)) : ∀ (c : fin n → R) (hc : ∀ (i : fin n), k < i.succ → c i = 0) {M N : matrix (fin n.succ) (fin n.succ) R} (h0 : ∀ j, M 0 j = N 0 j) (hsucc : ∀ (i : fin n) j, M i.succ j = N i.succ j + c i * M i.cast_succ j), det M = det N := begin refine fin.induction _ (λ k ih, _) k; intros c hc M N h0 hsucc, { congr, ext i j, refine fin.cases (h0 j) (λ i, _) i, rw [hsucc, hc i (fin.succ_pos _), zero_mul, add_zero] }, set M' := update_row M k.succ (N k.succ) with hM', have hM : M = update_row M' k.succ (M' k.succ + c k • M k.cast_succ), { ext i j, by_cases hi : i = k.succ, { simp [hi, hM', hsucc, update_row_self] }, rw [update_row_ne hi, hM', update_row_ne hi] }, have k_ne_succ : k.cast_succ ≠ k.succ := (fin.cast_succ_lt_succ k).ne, have M_k : M k.cast_succ = M' k.cast_succ := (update_row_ne k_ne_succ).symm, rw [hM, M_k, det_update_row_add_smul_self M' k_ne_succ.symm, ih (function.update c k 0)], { intros i hi, rw [fin.lt_iff_coe_lt_coe, fin.coe_cast_succ, fin.coe_succ, nat.lt_succ_iff] at hi, rw function.update_apply, split_ifs with hik, { refl }, exact hc _ (fin.succ_lt_succ_iff.mpr (lt_of_le_of_ne hi (ne.symm hik))) }, { rwa [hM', update_row_ne (fin.succ_ne_zero _).symm] }, intros i j, rw function.update_apply, split_ifs with hik, { rw [zero_mul, add_zero, hM', hik, update_row_self] }, rw [hM', update_row_ne ((fin.succ_injective _).ne hik), hsucc], by_cases hik2 : k < i, { simp [hc i (fin.succ_lt_succ_iff.mpr hik2)] }, rw update_row_ne, apply ne_of_lt, rwa [fin.lt_iff_coe_lt_coe, fin.coe_cast_succ, fin.coe_succ, nat.lt_succ_iff, ← not_lt] end /-- If you add multiples of previous rows to the next row, the determinant doesn't change. -/ lemma det_eq_of_forall_row_eq_smul_add_pred {n : ℕ} {A B : matrix (fin (n + 1)) (fin (n + 1)) R} (c : fin n → R) (A_zero : ∀ j, A 0 j = B 0 j) (A_succ : ∀ (i : fin n) j, A i.succ j = B i.succ j + c i * A i.cast_succ j) : det A = det B := det_eq_of_forall_row_eq_smul_add_pred_aux (fin.last _) c (λ i hi, absurd hi (not_lt_of_ge (fin.le_last _))) A_zero A_succ /-- If you add multiples of previous columns to the next columns, the determinant doesn't change. -/ lemma det_eq_of_forall_col_eq_smul_add_pred {n : ℕ} {A B : matrix (fin (n + 1)) (fin (n + 1)) R} (c : fin n → R) (A_zero : ∀ i, A i 0 = B i 0) (A_succ : ∀ i (j : fin n), A i j.succ = B i j.succ + c j * A i j.cast_succ) : det A = det B := by { rw [← det_transpose A, ← det_transpose B], exact det_eq_of_forall_row_eq_smul_add_pred c A_zero (λ i j, A_succ j i) } end det_eq @[simp] lemma det_block_diagonal {o : Type*} [fintype o] [decidable_eq o] (M : o → matrix n n R) : (block_diagonal M).det = ∏ k, (M k).det := begin -- Rewrite the determinants as a sum over permutations. simp_rw [det_apply'], -- The right hand side is a product of sums, rewrite it as a sum of products. rw finset.prod_sum, simp_rw [finset.mem_univ, finset.prod_attach_univ, finset.univ_pi_univ], -- We claim that the only permutations contributing to the sum are those that -- preserve their second component. let preserving_snd : finset (equiv.perm (n × o)) := finset.univ.filter (λ σ, ∀ x, (σ x).snd = x.snd), have mem_preserving_snd : ∀ {σ : equiv.perm (n × o)}, σ ∈ preserving_snd ↔ ∀ x, (σ x).snd = x.snd := λ σ, finset.mem_filter.trans ⟨λ h, h.2, λ h, ⟨finset.mem_univ _, h⟩⟩, rw ← finset.sum_subset (finset.subset_univ preserving_snd) _, -- And that these are in bijection with `o → equiv.perm m`. rw (finset.sum_bij (λ (σ : ∀ (k : o), k ∈ finset.univ → equiv.perm n) _, prod_congr_left (λ k, σ k (finset.mem_univ k))) _ _ _ _).symm, { intros σ _, rw mem_preserving_snd, rintros ⟨k, x⟩, simp only [prod_congr_left_apply] }, { intros σ _, rw [finset.prod_mul_distrib, ←finset.univ_product_univ, finset.prod_product_right], simp only [sign_prod_congr_left, units.coe_prod, int.cast_prod, block_diagonal_apply_eq, prod_congr_left_apply] }, { intros σ σ' _ _ eq, ext x hx k, simp only at eq, have : ∀ k x, prod_congr_left (λ k, σ k (finset.mem_univ _)) (k, x) = prod_congr_left (λ k, σ' k (finset.mem_univ _)) (k, x) := λ k x, by rw eq, simp only [prod_congr_left_apply, prod.mk.inj_iff] at this, exact (this k x).1 }, { intros σ hσ, rw mem_preserving_snd at hσ, have hσ' : ∀ x, (σ⁻¹ x).snd = x.snd, { intro x, conv_rhs { rw [← perm.apply_inv_self σ x, hσ] } }, have mk_apply_eq : ∀ k x, ((σ (x, k)).fst, k) = σ (x, k), { intros k x, ext, { simp only}, { simp only [hσ] } }, have mk_inv_apply_eq : ∀ k x, ((σ⁻¹ (x, k)).fst, k) = σ⁻¹ (x, k), { intros k x, conv_lhs { rw ← perm.apply_inv_self σ (x, k) }, ext, { simp only [apply_inv_self] }, { simp only [hσ'] } }, refine ⟨λ k _, ⟨λ x, (σ (x, k)).fst, λ x, (σ⁻¹ (x, k)).fst, _, _⟩, _, _⟩, { intro x, simp only [mk_apply_eq, inv_apply_self] }, { intro x, simp only [mk_inv_apply_eq, apply_inv_self] }, { apply finset.mem_univ }, { ext ⟨k, x⟩, { simp only [coe_fn_mk, prod_congr_left_apply] }, { simp only [prod_congr_left_apply, hσ] } } }, { intros σ _ hσ, rw mem_preserving_snd at hσ, obtain ⟨⟨k, x⟩, hkx⟩ := not_forall.mp hσ, rw [finset.prod_eq_zero (finset.mem_univ (k, x)), mul_zero], rw [← @prod.mk.eta _ _ (σ (k, x)), block_diagonal_apply_ne], exact hkx } end /-- The determinant of a 2×2 block matrix with the lower-left block equal to zero is the product of the determinants of the diagonal blocks. For the generalization to any number of blocks, see `matrix.det_of_upper_triangular`. -/ @[simp] lemma det_from_blocks_zero₂₁ (A : matrix m m R) (B : matrix m n R) (D : matrix n n R) : (matrix.from_blocks A B 0 D).det = A.det * D.det := begin classical, simp_rw det_apply', convert (sum_subset (subset_univ ((sum_congr_hom m n).range : set (perm (m ⊕ n))).to_finset) _).symm, rw sum_mul_sum, simp_rw univ_product_univ, rw (sum_bij (λ (σ : perm m × perm n) _, equiv.sum_congr σ.fst σ.snd) _ _ _ _).symm, { intros σ₁₂ h, simp only [], erw [set.mem_to_finset, monoid_hom.mem_range], use σ₁₂, simp only [sum_congr_hom_apply] }, { simp only [forall_prop_of_true, prod.forall, mem_univ], intros σ₁ σ₂, rw fintype.prod_sum_type, simp_rw [equiv.sum_congr_apply, sum.map_inr, sum.map_inl, from_blocks_apply₁₁, from_blocks_apply₂₂], rw mul_mul_mul_comm, congr, rw [sign_sum_congr, units.coe_mul, int.cast_mul] }, { intros σ₁ σ₂ h₁ h₂, dsimp only [], intro h, have h2 : ∀ x, perm.sum_congr σ₁.fst σ₁.snd x = perm.sum_congr σ₂.fst σ₂.snd x, { intro x, exact congr_fun (congr_arg to_fun h) x }, simp only [sum.map_inr, sum.map_inl, perm.sum_congr_apply, sum.forall] at h2, ext, { exact h2.left x }, { exact h2.right x }}, { intros σ hσ, erw [set.mem_to_finset, monoid_hom.mem_range] at hσ, obtain ⟨σ₁₂, hσ₁₂⟩ := hσ, use σ₁₂, rw ←hσ₁₂, simp }, { intros σ hσ hσn, have h1 : ¬ (∀ x, ∃ y, sum.inl y = σ (sum.inl x)), { by_contradiction, rw set.mem_to_finset at hσn, apply absurd (mem_sum_congr_hom_range_of_perm_maps_to_inl _) hσn, rintros x ⟨a, ha⟩, rw [←ha], exact h a }, obtain ⟨a, ha⟩ := not_forall.mp h1, cases hx : σ (sum.inl a) with a2 b, { have hn := (not_exists.mp ha) a2, exact absurd hx.symm hn }, { rw [finset.prod_eq_zero (finset.mem_univ (sum.inl a)), mul_zero], rw [hx, from_blocks_apply₂₁], refl }} end /-- The determinant of a 2×2 block matrix with the upper-right block equal to zero is the product of the determinants of the diagonal blocks. For the generalization to any number of blocks, see `matrix.det_of_lower_triangular`. -/ @[simp] lemma det_from_blocks_zero₁₂ (A : matrix m m R) (C : matrix n m R) (D : matrix n n R) : (matrix.from_blocks A 0 C D).det = A.det * D.det := by rw [←det_transpose, from_blocks_transpose, transpose_zero, det_from_blocks_zero₂₁, det_transpose, det_transpose] /-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along column 0. -/ lemma det_succ_column_zero {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) : det A = ∑ i : fin n.succ, (-1) ^ (i : ℕ) * A i 0 * det (A.submatrix i.succ_above fin.succ) := begin rw [matrix.det_apply, finset.univ_perm_fin_succ, ← finset.univ_product_univ], simp only [finset.sum_map, equiv.to_embedding_apply, finset.sum_product, matrix.submatrix], refine finset.sum_congr rfl (λ i _, fin.cases _ (λ i, _) i), { simp only [fin.prod_univ_succ, matrix.det_apply, finset.mul_sum, equiv.perm.decompose_fin_symm_apply_zero, fin.coe_zero, one_mul, equiv.perm.decompose_fin.symm_sign, equiv.swap_self, if_true, id.def, eq_self_iff_true, equiv.perm.decompose_fin_symm_apply_succ, fin.succ_above_zero, equiv.coe_refl, pow_zero, mul_smul_comm, of_apply] }, -- `univ_perm_fin_succ` gives a different embedding of `perm (fin n)` into -- `perm (fin n.succ)` than the determinant of the submatrix we want, -- permute `A` so that we get the correct one. have : (-1 : R) ^ (i : ℕ) = i.cycle_range.sign, { simp [fin.sign_cycle_range] }, rw [fin.coe_succ, pow_succ, this, mul_assoc, mul_assoc, mul_left_comm ↑(equiv.perm.sign _), ← det_permute, matrix.det_apply, finset.mul_sum, finset.mul_sum], -- now we just need to move the corresponding parts to the same place refine finset.sum_congr rfl (λ σ _, _), rw [equiv.perm.decompose_fin.symm_sign, if_neg (fin.succ_ne_zero i)], calc ((-1) * σ.sign : ℤ) • ∏ i', A (equiv.perm.decompose_fin.symm (fin.succ i, σ) i') i' = ((-1) * σ.sign : ℤ) • (A (fin.succ i) 0 * ∏ i', A (((fin.succ i).succ_above) (fin.cycle_range i (σ i'))) i'.succ) : by simp only [fin.prod_univ_succ, fin.succ_above_cycle_range, equiv.perm.decompose_fin_symm_apply_zero, equiv.perm.decompose_fin_symm_apply_succ] ... = (-1) * (A (fin.succ i) 0 * (σ.sign : ℤ) • ∏ i', A (((fin.succ i).succ_above) (fin.cycle_range i (σ i'))) i'.succ) : by simp only [mul_assoc, mul_comm, _root_.neg_mul, one_mul, zsmul_eq_mul, neg_inj, neg_smul, fin.succ_above_cycle_range], end /-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along row 0. -/ lemma det_succ_row_zero {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) : det A = ∑ j : fin n.succ, (-1) ^ (j : ℕ) * A 0 j * det (A.submatrix fin.succ j.succ_above) := by { rw [← det_transpose A, det_succ_column_zero], refine finset.sum_congr rfl (λ i _, _), rw [← det_transpose], simp only [transpose_apply, transpose_submatrix, transpose_transpose] } /-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along row `i`. -/ lemma det_succ_row {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) (i : fin n.succ) : det A = ∑ j : fin n.succ, (-1) ^ (i + j : ℕ) * A i j * det (A.submatrix i.succ_above j.succ_above) := begin simp_rw [pow_add, mul_assoc, ← mul_sum], have : det A = (-1 : R) ^ (i : ℕ) * (i.cycle_range⁻¹).sign * det A, { calc det A = ↑((-1 : ℤˣ) ^ (i : ℕ) * (-1 : ℤˣ) ^ (i : ℕ) : ℤˣ) * det A : by simp ... = (-1 : R) ^ (i : ℕ) * (i.cycle_range⁻¹).sign * det A : by simp [-int.units_mul_self] }, rw [this, mul_assoc], congr, rw [← det_permute, det_succ_row_zero], refine finset.sum_congr rfl (λ j _, _), rw [mul_assoc, matrix.submatrix, matrix.submatrix], congr, { rw [equiv.perm.inv_def, fin.cycle_range_symm_zero] }, { ext i' j', rw [equiv.perm.inv_def, fin.cycle_range_symm_succ] }, end /-- Laplacian expansion of the determinant of an `n+1 × n+1` matrix along column `j`. -/ lemma det_succ_column {n : ℕ} (A : matrix (fin n.succ) (fin n.succ) R) (j : fin n.succ) : det A = ∑ i : fin n.succ, (-1) ^ (i + j : ℕ) * A i j * det (A.submatrix i.succ_above j.succ_above) := by { rw [← det_transpose, det_succ_row _ j], refine finset.sum_congr rfl (λ i _, _), rw [add_comm, ← det_transpose, transpose_apply, transpose_submatrix, transpose_transpose] } /-- Determinant of 0x0 matrix -/ @[simp] lemma det_fin_zero {A : matrix (fin 0) (fin 0) R} : det A = 1 := det_is_empty /-- Determinant of 1x1 matrix -/ lemma det_fin_one (A : matrix (fin 1) (fin 1) R) : det A = A 0 0 := det_unique A lemma det_fin_one_of (a : R) : det !![a] = a := det_fin_one _ /-- Determinant of 2x2 matrix -/ lemma det_fin_two (A : matrix (fin 2) (fin 2) R) : det A = A 0 0 * A 1 1 - A 0 1 * A 1 0 := begin simp [matrix.det_succ_row_zero, fin.sum_univ_succ], ring end @[simp] lemma det_fin_two_of (a b c d : R) : matrix.det !![a, b; c, d] = a * d - b * c := det_fin_two _ /-- Determinant of 3x3 matrix -/ lemma det_fin_three (A : matrix (fin 3) (fin 3) R) : det A = A 0 0 * A 1 1 * A 2 2 - A 0 0 * A 1 2 * A 2 1 - A 0 1 * A 1 0 * A 2 2 + A 0 1 * A 1 2 * A 2 0 + A 0 2 * A 1 0 * A 2 1 - A 0 2 * A 1 1 * A 2 0 := begin simp [matrix.det_succ_row_zero, fin.sum_univ_succ], ring end end matrix
1e43b51620afe441c60e2b169dcc7c7db8f09d4c
9c2e8d73b5c5932ceb1333265f17febc6a2f0a39
/src/S4/size.lean
3d2cf5161f2051f56ca130e77a250ac639c59090
[ "MIT" ]
permissive
minchaowu/ModalTab
2150392108dfdcaffc620ff280a8b55fe13c187f
9bb0bf17faf0554d907ef7bdd639648742889178
refs/heads/master
1,626,266,863,244
1,592,056,874,000
1,592,056,874,000
153,314,364
12
1
null
null
null
null
UTF-8
Lean
false
false
4,071
lean
import .S4_defs .data open nnf prod list namespace prod universe u def measure_lex {α : Sort u} : (α → ℕ × ℕ) → α → α → Prop := inv_image $ lex (<) (<) def measure_lex' {α : Sort u} : (α → ℕ × ℕ × ℕ) → α → α → Prop := inv_image $ lex (<) (measure_lex (λ x, x)) def measure_lex_wf {α : Sort u} (f : α → ℕ × ℕ) : well_founded (measure_lex f) := inv_image.wf f (lex_wf nat.lt_wf nat.lt_wf) def measure_lex_wf' {α : Sort u} (f : α → ℕ × ℕ × ℕ) : well_founded (measure_lex' f) := inv_image.wf f (lex_wf nat.lt_wf (measure_lex_wf (λ x, x))) end prod def sseqt_size (s : sseqt) : ℕ × ℕ × ℕ := ((closure s.goal).length - s.b.length, (closure s.goal).length - s.h.length, node_size s.m) instance : has_well_founded sseqt := ⟨prod.measure_lex' sseqt_size, prod.measure_lex_wf' sseqt_size⟩ lemma size_erase_add_eq_size_sum {φ} : Π (Γ : list nnf) (h : φ ∈ Γ), node_size (Γ.erase φ) + sizeof φ = node_size Γ | [] h := absurd h $ not_mem_nil _ | (hd :: tl) h := begin by_cases eq : φ = hd, {dsimp [list.erase], rw if_pos, rw eq, apply add_comm, rw eq}, {dsimp [list.erase], rw if_neg, dsimp, rw [add_assoc], have : node_size (list.erase tl φ) + sizeof φ = node_size tl, {apply size_erase_add_eq_size_sum, cases h, contradiction, assumption}, rw this, intro h', rw h' at eq, contradiction} end theorem split_lt_and_size {φ ψ} (Γ : list nnf) (h : nnf.and φ ψ ∈ Γ) : node_size (φ :: ψ :: Γ.erase (nnf.and φ ψ)) < node_size Γ := begin dsimp [node_size], rw ←size_erase_add_eq_size_sum Γ, swap, exact h, rw [←add_assoc, add_comm], apply add_lt_add_left, dsimp [sizeof, has_sizeof.sizeof, nnf.sizeof], rw [add_assoc], rw [nat.one_add], apply nat.lt_succ_self end theorem split_lt_and_seqt {φ ψ} (Γ : sseqt) (h : nnf.and φ ψ ∈ Γ.m) : prod.measure_lex' sseqt_size (and_child Γ h) Γ := begin right, right, simp only [and_child], apply split_lt_and_size _ h end theorem split_lt_or_size_left {φ ψ} (Γ : list nnf) (h : nnf.or φ ψ ∈ Γ) : node_size (φ :: Γ.erase (nnf.or φ ψ)) < node_size Γ := begin dsimp, rw ←size_erase_add_eq_size_sum Γ, swap, exact h, rw [add_comm], apply add_lt_add_left, dsimp [sizeof, has_sizeof.sizeof, nnf.sizeof], rw [add_comm, ←add_assoc], apply nat.lt_add_of_pos_left, apply nat.succ_pos end theorem split_lt_or_size_right {φ ψ} (Γ : list nnf) (h : nnf.or φ ψ ∈ Γ) : node_size (ψ :: Γ.erase (nnf.or φ ψ)) < node_size Γ := begin dsimp, rw ←size_erase_add_eq_size_sum Γ, swap, exact h, rw [add_comm], apply add_lt_add_left, dsimp [sizeof, has_sizeof.sizeof, nnf.sizeof], apply nat.lt_add_of_pos_left, rw nat.one_add, apply nat.succ_pos end theorem split_lt_or_seqt_left {φ ψ} (Γ : sseqt) (h : nnf.or φ ψ ∈ Γ.m) : prod.measure_lex' sseqt_size (or_child_left Γ h) Γ := begin right, right, simp only [or_child_left], apply split_lt_or_size_left _ h end theorem split_lt_or_seqt_right {φ ψ} (Γ : sseqt) (h : nnf.or φ ψ ∈ Γ.m) : prod.measure_lex' sseqt_size (or_child_right Γ h) Γ := begin right, right, simp only [or_child_right], apply split_lt_or_size_right _ h end theorem copy_lt_size {φ} (Γ : list nnf) (h : nnf.box φ ∈ Γ) : node_size (φ :: Γ.erase (nnf.box φ)) < node_size Γ := begin dsimp [node_size], rw ←size_erase_add_eq_size_sum Γ, swap, exact h, rw [add_comm], simp [sizeof,has_sizeof.sizeof, nnf.sizeof] end theorem copy_lt_seqt {φ} (Γ : sseqt) (h : nnf.box φ ∈ Γ.m) : prod.measure_lex' sseqt_size (box_child Γ h) Γ := begin right, right, simp only [box_child], apply copy_lt_size _ h end theorem box_new_lt_seqt {φ} (Γ : sseqt) (h₁ : nnf.box φ ∈ Γ.m) (h₂ : nnf.box φ ∉ Γ.b) : prod.measure_lex' sseqt_size (box_child_new Γ h₁ h₂) Γ := begin left, apply length_sub_lt_of_nodup_subperm, {dsimp [box_child_new], exact Γ.spb}, {dsimp [box_child_new], apply Γ.sbm, exact h₁}, {exact h₂}, {exact Γ.ndb} end
80fc55da1f01fba1c21b5b9597a9c5d553dae7ba
4727251e0cd73359b15b664c3170e5d754078599
/src/order/hom/bounded.lean
e35a40a93b5e48cd8a3e9fedb1bb37bff87f4e00
[ "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
20,098
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import order.hom.basic import order.bounded_order /-! # Bounded order homomorphisms This file defines (bounded) order homomorphisms. 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. ## Types of morphisms * `top_hom`: Maps which preserve `⊤`. * `bot_hom`: Maps which preserve `⊥`. * `bounded_order_hom`: Bounded order homomorphisms. Monotone maps which preserve `⊤` and `⊥`. ## Typeclasses * `top_hom_class` * `bot_hom_class` * `bounded_order_hom_class` -/ open function order_dual variables {F α β γ δ : Type*} /-- The type of `⊤`-preserving functions from `α` to `β`. -/ structure top_hom (α β : Type*) [has_top α] [has_top β] := (to_fun : α → β) (map_top' : to_fun ⊤ = ⊤) /-- The type of `⊥`-preserving functions from `α` to `β`. -/ structure bot_hom (α β : Type*) [has_bot α] [has_bot β] := (to_fun : α → β) (map_bot' : to_fun ⊥ = ⊥) /-- The type of bounded order homomorphisms from `α` to `β`. -/ structure bounded_order_hom (α β : Type*) [preorder α] [preorder β] [bounded_order α] [bounded_order β] extends order_hom α β := (map_top' : to_fun ⊤ = ⊤) (map_bot' : to_fun ⊥ = ⊥) /-- `top_hom_class F α β` states that `F` is a type of `⊤`-preserving morphisms. You should extend this class when you extend `top_hom`. -/ class top_hom_class (F : Type*) (α β : out_param $ Type*) [has_top α] [has_top β] extends fun_like F α (λ _, β) := (map_top (f : F) : f ⊤ = ⊤) /-- `bot_hom_class F α β` states that `F` is a type of `⊥`-preserving morphisms. You should extend this class when you extend `bot_hom`. -/ class bot_hom_class (F : Type*) (α β : out_param $ Type*) [has_bot α] [has_bot β] extends fun_like F α (λ _, β) := (map_bot (f : F) : f ⊥ = ⊥) /-- `bounded_order_hom_class F α β` states that `F` is a type of bounded order morphisms. You should extend this class when you extend `bounded_order_hom`. -/ class bounded_order_hom_class (F : Type*) (α β : out_param $ Type*) [has_le α] [has_le β] [bounded_order α] [bounded_order β] extends rel_hom_class F ((≤) : α → α → Prop) ((≤) : β → β → Prop) := (map_top (f : F) : f ⊤ = ⊤) (map_bot (f : F) : f ⊥ = ⊥) export top_hom_class (map_top) bot_hom_class (map_bot) attribute [simp] map_top map_bot @[priority 100] -- See note [lower instance priority] instance bounded_order_hom_class.to_top_hom_class [has_le α] [has_le β] [bounded_order α] [bounded_order β] [bounded_order_hom_class F α β] : top_hom_class F α β := { .. ‹bounded_order_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance bounded_order_hom_class.to_bot_hom_class [has_le α] [has_le β] [bounded_order α] [bounded_order β] [bounded_order_hom_class F α β] : bot_hom_class F α β := { .. ‹bounded_order_hom_class F α β› } @[priority 100] -- See note [lower instance priority] instance order_iso_class.to_top_hom_class [has_le α] [order_top α] [partial_order β] [order_top β] [order_iso_class F α β] : top_hom_class F α β := ⟨λ f, top_le_iff.1 $ (map_inv_le_iff f).1 le_top⟩ @[priority 100] -- See note [lower instance priority] instance order_iso_class.to_bot_hom_class [has_le α] [order_bot α] [partial_order β] [order_bot β] [order_iso_class F α β] : bot_hom_class F α β := ⟨λ f, le_bot_iff.1 $ (le_map_inv_iff f).1 bot_le⟩ @[priority 100] -- See note [lower instance priority] instance order_iso_class.to_bounded_order_hom_class [has_le α] [bounded_order α] [partial_order β] [bounded_order β] [order_iso_class F α β] : bounded_order_hom_class F α β := { ..order_iso_class.to_top_hom_class, ..order_iso_class.to_bot_hom_class } @[simp] lemma map_eq_top_iff [has_le α] [order_top α] [partial_order β] [order_top β] [order_iso_class F α β] (f : F) {a : α} : f a = ⊤ ↔ a = ⊤ := by rw [←map_top f, (equiv_like.injective f).eq_iff] @[simp] lemma map_eq_bot_iff [has_le α] [order_bot α] [partial_order β] [order_bot β] [order_iso_class F α β] (f : F) {a : α} : f a = ⊥ ↔ a = ⊥ := by rw [←map_bot f, (equiv_like.injective f).eq_iff] instance [has_top α] [has_top β] [top_hom_class F α β] : has_coe_t F (top_hom α β) := ⟨λ f, ⟨f, map_top f⟩⟩ instance [has_bot α] [has_bot β] [bot_hom_class F α β] : has_coe_t F (bot_hom α β) := ⟨λ f, ⟨f, map_bot f⟩⟩ instance [preorder α] [preorder β] [bounded_order α] [bounded_order β] [bounded_order_hom_class F α β] : has_coe_t F (bounded_order_hom α β) := ⟨λ f, { to_fun := f, map_top' := map_top f, map_bot' := map_bot f, ..(f : α →o β) }⟩ /-! ### Top homomorphisms -/ namespace top_hom variables [has_top α] section has_top variables [has_top β] [has_top γ] [has_top δ] instance : top_hom_class (top_hom α β) α β := { coe := top_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_top := top_hom.map_top' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (top_hom α β) (λ _, α → β) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : top_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : top_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `top_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : top_hom α β) (f' : α → β) (h : f' = f) : top_hom α β := { to_fun := f', map_top' := h.symm ▸ f.map_top' } instance : inhabited (top_hom α β) := ⟨⟨λ _, ⊤, rfl⟩⟩ variables (α) /-- `id` as a `top_hom`. -/ protected def id : top_hom α α := ⟨id, rfl⟩ @[simp] lemma coe_id : ⇑(top_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : top_hom.id α a = a := rfl /-- Composition of `top_hom`s as a `top_hom`. -/ def comp (f : top_hom β γ) (g : top_hom α β) : top_hom α γ := { to_fun := f ∘ g, map_top' := by rw [comp_apply, map_top, map_top] } @[simp] lemma coe_comp (f : top_hom β γ) (g : top_hom α β) : (f.comp g : α → γ) = f ∘ g := rfl @[simp] lemma comp_apply (f : top_hom β γ) (g : top_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma comp_assoc (f : top_hom γ δ) (g : top_hom β γ) (h : top_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : top_hom α β) : f.comp (top_hom.id α) = f := top_hom.ext $ λ a, rfl @[simp] lemma id_comp (f : top_hom α β) : (top_hom.id β).comp f = f := top_hom.ext $ λ a, rfl lemma cancel_right {g₁ g₂ : top_hom β γ} {f : top_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, top_hom.ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : top_hom β γ} {f₁ f₂ : top_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, top_hom.ext $ λ a, hg $ by rw [←top_hom.comp_apply, h, top_hom.comp_apply], congr_arg _⟩ end has_top instance [preorder β] [has_top β] : preorder (top_hom α β) := preorder.lift (coe_fn : top_hom α β → α → β) instance [partial_order β] [has_top β] : partial_order (top_hom α β) := partial_order.lift _ fun_like.coe_injective section order_top variables [preorder β] [order_top β] instance : order_top (top_hom α β) := ⟨⟨⊤, rfl⟩, λ _, le_top⟩ @[simp] lemma coe_top : ⇑(⊤ : top_hom α β) = ⊤ := rfl @[simp] lemma top_apply (a : α) : (⊤ : top_hom α β) a = ⊤ := rfl end order_top section semilattice_inf variables [semilattice_inf β] [order_top β] (f g : top_hom α β) instance : has_inf (top_hom α β) := ⟨λ f g, ⟨f ⊓ g, by rw [pi.inf_apply, map_top, map_top, inf_top_eq]⟩⟩ instance : semilattice_inf (top_hom α β) := fun_like.coe_injective.semilattice_inf _ $ λ _ _, rfl @[simp] lemma coe_inf : ⇑(f ⊓ g) = f ⊓ g := rfl @[simp] lemma inf_apply (a : α) : (f ⊓ g) a = f a ⊓ g a := rfl end semilattice_inf section semilattice_sup variables [semilattice_sup β] [order_top β] (f g : top_hom α β) instance : has_sup (top_hom α β) := ⟨λ f g, ⟨f ⊔ g, by rw [pi.sup_apply, map_top, map_top, sup_top_eq]⟩⟩ instance : semilattice_sup (top_hom α β) := fun_like.coe_injective.semilattice_sup _ $ λ _ _, rfl @[simp] lemma coe_sup : ⇑(f ⊔ g) = f ⊔ g := rfl @[simp] lemma sup_apply (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl end semilattice_sup instance [lattice β] [order_top β] : lattice (top_hom α β) := fun_like.coe_injective.lattice _ (λ _ _, rfl) (λ _ _, rfl) instance [distrib_lattice β] [order_top β] : distrib_lattice (top_hom α β) := fun_like.coe_injective.distrib_lattice _ (λ _ _, rfl) (λ _ _, rfl) end top_hom /-! ### Bot homomorphisms -/ namespace bot_hom variables [has_bot α] section has_bot variables [has_bot β] [has_bot γ] [has_bot δ] instance : bot_hom_class (bot_hom α β) α β := { coe := bot_hom.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr', map_bot := bot_hom.map_bot' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (bot_hom α β) (λ _, α → β) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : bot_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : bot_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `bot_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : bot_hom α β) (f' : α → β) (h : f' = f) : bot_hom α β := { to_fun := f', map_bot' := h.symm ▸ f.map_bot' } instance : inhabited (bot_hom α β) := ⟨⟨λ _, ⊥, rfl⟩⟩ variables (α) /-- `id` as a `bot_hom`. -/ protected def id : bot_hom α α := ⟨id, rfl⟩ @[simp] lemma coe_id : ⇑(bot_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : bot_hom.id α a = a := rfl /-- Composition of `bot_hom`s as a `bot_hom`. -/ def comp (f : bot_hom β γ) (g : bot_hom α β) : bot_hom α γ := { to_fun := f ∘ g, map_bot' := by rw [comp_apply, map_bot, map_bot] } @[simp] lemma coe_comp (f : bot_hom β γ) (g : bot_hom α β) : (f.comp g : α → γ) = f ∘ g := rfl @[simp] lemma comp_apply (f : bot_hom β γ) (g : bot_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma comp_assoc (f : bot_hom γ δ) (g : bot_hom β γ) (h : bot_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : bot_hom α β) : f.comp (bot_hom.id α) = f := bot_hom.ext $ λ a, rfl @[simp] lemma id_comp (f : bot_hom α β) : (bot_hom.id β).comp f = f := bot_hom.ext $ λ a, rfl lemma cancel_right {g₁ g₂ : bot_hom β γ} {f : bot_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, bot_hom.ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : bot_hom β γ} {f₁ f₂ : bot_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, bot_hom.ext $ λ a, hg $ by rw [←bot_hom.comp_apply, h, bot_hom.comp_apply], congr_arg _⟩ end has_bot instance [preorder β] [has_bot β] : preorder (bot_hom α β) := preorder.lift (coe_fn : bot_hom α β → α → β) instance [partial_order β] [has_bot β] : partial_order (bot_hom α β) := partial_order.lift _ fun_like.coe_injective section order_bot variables [preorder β] [order_bot β] instance : order_bot (bot_hom α β) := ⟨⟨⊥, rfl⟩, λ _, bot_le⟩ @[simp] lemma coe_bot : ⇑(⊥ : bot_hom α β) = ⊥ := rfl @[simp] lemma bot_apply (a : α) : (⊥ : bot_hom α β) a = ⊥ := rfl end order_bot section semilattice_inf variables [semilattice_inf β] [order_bot β] (f g : bot_hom α β) instance : has_inf (bot_hom α β) := ⟨λ f g, ⟨f ⊓ g, by rw [pi.inf_apply, map_bot, map_bot, inf_bot_eq]⟩⟩ instance : semilattice_inf (bot_hom α β) := fun_like.coe_injective.semilattice_inf _ $ λ _ _, rfl @[simp] lemma coe_inf : ⇑(f ⊓ g) = f ⊓ g := rfl @[simp] lemma inf_apply (a : α) : (f ⊓ g) a = f a ⊓ g a := rfl end semilattice_inf section semilattice_sup variables [semilattice_sup β] [order_bot β] (f g : bot_hom α β) instance : has_sup (bot_hom α β) := ⟨λ f g, ⟨f ⊔ g, by rw [pi.sup_apply, map_bot, map_bot, sup_bot_eq]⟩⟩ instance : semilattice_sup (bot_hom α β) := fun_like.coe_injective.semilattice_sup _ $ λ _ _, rfl @[simp] lemma coe_sup : ⇑(f ⊔ g) = f ⊔ g := rfl @[simp] lemma sup_apply (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl end semilattice_sup instance [lattice β] [order_bot β] : lattice (bot_hom α β) := fun_like.coe_injective.lattice _ (λ _ _, rfl) (λ _ _, rfl) instance [distrib_lattice β] [order_bot β] : distrib_lattice (bot_hom α β) := fun_like.coe_injective.distrib_lattice _ (λ _ _, rfl) (λ _ _, rfl) end bot_hom /-! ### Bounded order homomorphisms -/ namespace bounded_order_hom variables [preorder α] [preorder β] [preorder γ] [preorder δ] [bounded_order α] [bounded_order β] [bounded_order γ] [bounded_order δ] /-- Reinterpret a `bounded_order_hom` as a `top_hom`. -/ def to_top_hom (f : bounded_order_hom α β) : top_hom α β := { ..f } /-- Reinterpret a `bounded_order_hom` as a `bot_hom`. -/ def to_bot_hom (f : bounded_order_hom α β) : bot_hom α β := { ..f } instance : bounded_order_hom_class (bounded_order_hom α β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by obtain ⟨⟨_, _⟩, _⟩ := f; obtain ⟨⟨_, _⟩, _⟩ := g; congr', map_rel := λ f, f.monotone', map_top := λ f, f.map_top', map_bot := λ f, f.map_bot' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (bounded_order_hom α β) (λ _, α → β) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : bounded_order_hom α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : bounded_order_hom α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `bounded_order_hom` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : bounded_order_hom α β) (f' : α → β) (h : f' = f) : bounded_order_hom α β := { .. f.to_order_hom.copy f' h, .. f.to_top_hom.copy f' h, .. f.to_bot_hom.copy f' h } variables (α) /-- `id` as a `bounded_order_hom`. -/ protected def id : bounded_order_hom α α := { ..order_hom.id, ..top_hom.id α, ..bot_hom.id α } instance : inhabited (bounded_order_hom α α) := ⟨bounded_order_hom.id α⟩ @[simp] lemma coe_id : ⇑(bounded_order_hom.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : bounded_order_hom.id α a = a := rfl /-- Composition of `bounded_order_hom`s as a `bounded_order_hom`. -/ def comp (f : bounded_order_hom β γ) (g : bounded_order_hom α β) : bounded_order_hom α γ := { ..f.to_order_hom.comp g.to_order_hom, ..f.to_top_hom.comp g.to_top_hom, ..f.to_bot_hom.comp g.to_bot_hom } @[simp] lemma coe_comp (f : bounded_order_hom β γ) (g : bounded_order_hom α β) : (f.comp g : α → γ) = f ∘ g := rfl @[simp] lemma comp_apply (f : bounded_order_hom β γ) (g : bounded_order_hom α β) (a : α) : (f.comp g) a = f (g a) := rfl @[simp] lemma coe_comp_order_hom (f : bounded_order_hom β γ) (g : bounded_order_hom α β) : (f.comp g : order_hom α γ) = (f : order_hom β γ).comp g := rfl @[simp] lemma coe_comp_top_hom (f : bounded_order_hom β γ) (g : bounded_order_hom α β) : (f.comp g : top_hom α γ) = (f : top_hom β γ).comp g := rfl @[simp] lemma coe_comp_bot_hom (f : bounded_order_hom β γ) (g : bounded_order_hom α β) : (f.comp g : bot_hom α γ) = (f : bot_hom β γ).comp g := rfl @[simp] lemma comp_assoc (f : bounded_order_hom γ δ) (g : bounded_order_hom β γ) (h : bounded_order_hom α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : bounded_order_hom α β) : f.comp (bounded_order_hom.id α) = f := bounded_order_hom.ext $ λ a, rfl @[simp] lemma id_comp (f : bounded_order_hom α β) : (bounded_order_hom.id β).comp f = f := bounded_order_hom.ext $ λ a, rfl lemma cancel_right {g₁ g₂ : bounded_order_hom β γ} {f : bounded_order_hom α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, bounded_order_hom.ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : bounded_order_hom β γ} {f₁ f₂ : bounded_order_hom α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, bounded_order_hom.ext $ λ a, hg $ by rw [←bounded_order_hom.comp_apply, h, bounded_order_hom.comp_apply], congr_arg _⟩ end bounded_order_hom /-! ### Dual homs -/ namespace top_hom variables [has_le α] [order_top α] [has_le β] [order_top β] [has_le γ] [order_top γ] /-- Reinterpret a top homomorphism as a bot homomorphism between the dual lattices. -/ @[simps] protected def dual : top_hom α β ≃ bot_hom αᵒᵈ βᵒᵈ := { to_fun := λ f, ⟨f, f.map_top'⟩, inv_fun := λ f, ⟨f, f.map_bot'⟩, left_inv := λ f, top_hom.ext $ λ _, rfl, right_inv := λ f, bot_hom.ext $ λ _, rfl } @[simp] lemma dual_id : (top_hom.id α).dual = bot_hom.id _ := rfl @[simp] lemma dual_comp (g : top_hom β γ) (f : top_hom α β) : (g.comp f).dual = g.dual.comp f.dual := rfl @[simp] lemma symm_dual_id : top_hom.dual.symm (bot_hom.id _) = top_hom.id α := rfl @[simp] lemma symm_dual_comp (g : bot_hom βᵒᵈ γᵒᵈ) (f : bot_hom αᵒᵈ βᵒᵈ) : top_hom.dual.symm (g.comp f) = (top_hom.dual.symm g).comp (top_hom.dual.symm f) := rfl end top_hom namespace bot_hom variables [has_le α] [order_bot α] [has_le β] [order_bot β] [has_le γ] [order_bot γ] /-- Reinterpret a bot homomorphism as a top homomorphism between the dual lattices. -/ @[simps] protected def dual : bot_hom α β ≃ top_hom αᵒᵈ βᵒᵈ := { to_fun := λ f, ⟨f, f.map_bot'⟩, inv_fun := λ f, ⟨f, f.map_top'⟩, left_inv := λ f, bot_hom.ext $ λ _, rfl, right_inv := λ f, top_hom.ext $ λ _, rfl } @[simp] lemma dual_id : (bot_hom.id α).dual = top_hom.id _ := rfl @[simp] lemma dual_comp (g : bot_hom β γ) (f : bot_hom α β) : (g.comp f).dual = g.dual.comp f.dual := rfl @[simp] lemma symm_dual_id : bot_hom.dual.symm (top_hom.id _) = bot_hom.id α := rfl @[simp] lemma symm_dual_comp (g : top_hom βᵒᵈ γᵒᵈ) (f : top_hom αᵒᵈ βᵒᵈ) : bot_hom.dual.symm (g.comp f) = (bot_hom.dual.symm g).comp (bot_hom.dual.symm f) := rfl end bot_hom namespace bounded_order_hom variables [preorder α] [bounded_order α] [preorder β] [bounded_order β] [preorder γ] [bounded_order γ] /-- Reinterpret a bounded order homomorphism as a bounded order homomorphism between the dual orders. -/ @[simps] protected def dual : bounded_order_hom α β ≃ bounded_order_hom αᵒᵈ βᵒᵈ := { to_fun := λ f, ⟨f.to_order_hom.dual, f.map_bot', f.map_top'⟩, inv_fun := λ f, ⟨order_hom.dual.symm f.to_order_hom, f.map_bot', f.map_top'⟩, left_inv := λ f, ext $ λ a, rfl, right_inv := λ f, ext $ λ a, rfl } @[simp] lemma dual_id : (bounded_order_hom.id α).dual = bounded_order_hom.id _ := rfl @[simp] lemma dual_comp (g : bounded_order_hom β γ) (f : bounded_order_hom α β) : (g.comp f).dual = g.dual.comp f.dual := rfl @[simp] lemma symm_dual_id : bounded_order_hom.dual.symm (bounded_order_hom.id _) = bounded_order_hom.id α := rfl @[simp] lemma symm_dual_comp (g : bounded_order_hom βᵒᵈ γᵒᵈ) (f : bounded_order_hom αᵒᵈ βᵒᵈ) : bounded_order_hom.dual.symm (g.comp f) = (bounded_order_hom.dual.symm g).comp (bounded_order_hom.dual.symm f) := rfl end bounded_order_hom
6a1e7f6791a43dadd38b4585561d630da362a824
359199d7253811b032ab92108191da7336eba86e
/src/instructor/lectures/lecture_10.lean
80f20077d7a3f22e5c89adb3e52443b4162d7932
[]
no_license
arte-et-marte/my_cs2120f21
0bc6215cb5018a3b7c90d9d399a173233f587064
91609c3609ad81fda895bee8b97cc76813241e17
refs/heads/main
1,693,298,928,348
1,634,931,202,000
1,634,931,202,000
399,946,705
0
0
null
null
null
null
UTF-8
Lean
false
false
12,904
lean
/- In today's class, we'll continue with our exploration of the proposition, "false", its elimination rule, and their vital uses in logical reasoning: especially in **True has only an introduction rule, whereas false has only an elimination rule.** - proof of ¬P by negation **(¬ = "not")** **(not P = P implies false, P → false)** - proof of P by false elimination **What is negation and false elimination?** Here are the inference rules in display notation: NEGATION INTRODUCTION The first, proof by negation, says that from a proof of P → false you can derive a proof of ¬P. Indeed! It's definitional. Recall: def not (P : Prop) := P → false. (P : Prop) (np : P → false) --------------------------- [by defn'n] (pf : ¬P) This rule is the foundation for "proof by negation." To prove ¬P you first assume P, is true, then you show that in this context you can derive a contradiction. What you have then shown, of course, is P → false. So, to prove ¬P, assume P and show that in this context there is a contradiction. **(show that there is a contradiction, you are in a situation that can't happen; how do I do this?)** This is proof by negation. It is not to be confused with proof by contradition, which is a different thing entirely. (Proof by contradiction. You can use this approach to a proposition, P, by assuming ¬P and showing that this assumption leads to a contradiction. That proves ¬¬P. Then you use the *indepedent* axiom of negation elimination to infer P from ¬¬P.) **Proof (of ¬P) by "negation":** **- Given a proof of P → false, you can get a proof of ¬P.** **- Given a proof of not P...you can get...a proof of not P...** **So how do we prove P → false?** FALSE ELIMINATION The second rule says that if you have a proof of false and any other proposition, P, the logic is useless and so you might as well just admit that P is true. Why is the logic useless? Well, if false is true then there's no longer a difference! In this situation, tHere's sense in reasoning any further, and you can just dismiss it. A contradiction makes a logic inconsistent. (P : Prop) (f : false) ---------------------- (false_elim f) (pf : P) -/ -- **Proof (of P) by "false elimination":** ---- **Given a proof of false and a proposition P, you can get a proof of P.** /- We covered the relatively simpler notion of negation introduction last time, so today we will start by focusing on false elimination. Understanding why it's not magic and in fact makes perfect sense takes a bit of thought. -/ /- To make sense of false elimination, think in terms of case analysis. Proof by case analysis says that if the truth of some proposition, Y, follows from *any possible form of proof* of X, then you've proved X → Y. **(no possible proofs? return proof of Y trivially)** If X is a disjunction, P ∨ Q (so now you want to prove P ∨ Q → Y) you must consider two cases: one where P is assumed true and one where Q is assumed true. If X is a proposition with just one form of proof (e.g., the proposition, true), there's just one case to consider. -/ -- two cases **(could I use this for hw?)** example : true ∨ false → true := begin assume h, cases h, assumption, -- context has exact proof | true → true contradiction, -- context has contradiction | true → false end -- one case example : true → true := begin assume t, cases t, -- just one case exact true.intro, end /- How many cases must you consider if you putatively have a putative proof of false? ZERO! To consider *all* cases you need consider exactly zero cases. Proving all cases when the number of cases is zero is trivial, so the conclusion *follows*. -/ example : false → false := begin assume f, cases f, -- case analysis: there are no cases! end -- **false elim - no possible cases here, can just return** /- In fact, it doesn't matter what your conclusion is: it will always be true in a context in which you have a proof of false. And this makes sense, because if you have a proof of false, then false is true, so whether a given proposition is true or false, it's true, because even if it's false, well, false is true, so it's also true! -/ theorem false_elim : ∀ (P : Prop), false → P := begin assume P, assume f, cases f, -- do case analysis, there's 0 cases, trivially satisfies cases, you're done (cz there's nothing to do) end -- **for all props P, false implies P aka Ex false quod libet. From false anything follows** /- This, then, is the general principle for false elimination: ANYTHING FOLLOWS FROM FALSE. This principle gives you a powerful way to prove any proposition is true (conditional on your having a proof that can't exist). The theorem states that if you're given any proposition, P, and a proof, f, of false, then in that context, you can return a proof of P by using false elimination. The only problem with this super-power is that in reality, there is no proof of false, so there's no real danger of any old proposition being automatically true! The rule of false elimination tells you that if you're in a situation that can't happen, then no worries, be happy, you're done (just use false elimination). -/ /- The elimination principle for false is called false.elim in Lean. If you are given or can derive a proof, f, of false, then all you have to do to finish your proof is to say, "this is situation can't happen, so we need not consider it any further." Or, formally, (false.elim f). -/ -- Suppose P is *any* (an arbitrary) proposition axiom P : Prop example : false → P := begin assume f, exact false.elim f, -- Using Lean's version -- P is implicit argument end /- SOME THEOREMS INVOLVING FALSE AND NEGATION -/ -- NO CONTRADICTION theorem no_contradiction : ∀ (P : Prop), ¬(P ∧ ¬P) := begin assume P, -- Goal is to prove NOT something, so if it were true, it'd be a contradiction; -- self: need to prove an implication if P ∧ ¬P, then FALSE, the next step is just to assume ("implies" intro rule) assume h, -- h : P ∧ ¬P -- not is the same thing as an implication (for false)!!! -- what's in my context? have p := h.left, --and.elim_left h have np := h.right, -- i have a proof of p and a proof of np; np is a proof of p implies false apply np p, -- or have f := np p, apply the imp (if p then false) to a proof of p to get f (false) end -- if you have a proof of negation (¬P), you have a function you can apply -- EXCLUDED MIDDLE /- The so-called "law" (it's really an axiom) of the excluded middle says that any proposition is either true or false. There's no middle ground. But in the constructive logic of Lean, this isn't true. **The "Law" of the Excluded Middle** To prove P ∨ ¬P, as you recall, we need to have either a proof of P (in this case use or.intro_left) or a proof of ¬P, in which case we use or.intro_right to prove P ∨ ¬P. But what if we don't have a proof either way? There are many important questions in computer science and mathematics where we don't know either way. If you call one of those propositions, P, and try to prove P ∨ ¬P in Lean, you just get stuck. -/ theorem excluded_middle' : ∀ (P : Prop), (P ∨ ¬P) := begin assume P, -- we don't have a proof of either P or of ¬P! -- no neither or.inl nor or.inr applies end /- Here's a concrete example: Goldbach's Conjecture Let P be the conjecture, "every even whole number greater than 2 is the sum of two prime numbers." This conjecture, dating (in a slightly different form) to a letter from Goldback to Euler in 1742 is still neither proved nor disproved! Below you will find a placeholder for a proof. Just fill it in (correctly) and you will win $1M and probably a Fields Medal (the "Nobel Prize" in mathematics). -/ -- just assume that we have evenness and primeness predicates axioms (ev : ℕ → Prop) (prime : ℕ → Prop) -- here's the statment of Goldbach's conjecture def goldbach_conjecture := ∀ (n : ℕ), n > 2 → (∃ h k : ℕ, n = h + k ∧ prime h ∧ prime k) -- can you prove it true? theorem goldbach_conjecture_true : goldbach_conjecture := _ -- can you prove it false? theorem goldbach_conjecture_false : ¬goldbach_conjecture := _ -- or haven't you yet proved it either way? /- So is it true that Goldbach's conjecture is either true or it's false, with no other possibility? Well, yes, but only if you admit the axiom of the excluded middle into our logic. -/ example : goldbach_conjecture ∨ ¬goldbach_conjecture := _ /- Without this axiom, our only options are or.intro_left or or.intro_right applied to proofs/arguments that we do not have. The axioms of the constructive logic of Lean are not strong enough to prove the "law of the excluded middle." Rather, if we want to use it, we have to accept it as an additional axiom. We thus have two different logics: one without and one with the law of the excluded middle! -/ -- **Logic in Lean: has or does not have the Law of the Excluded Middle factored in.** axiom excluded_middle : ∀ (P : Prop), (P ∨ ¬P) example : goldbach_conjecture ∨ ¬goldbach_conjecture := excluded_middle goldbach_conjecture -- **Apply the Law of the Excluded Middle on your proposition.** /- That is all it took to add this axiom to our logic. In the official Lean libraries, it's called classical.em. -/ #check classical.em -- Understand what this is saying! example : goldbach_conjecture ∨ ¬goldbach_conjecture := classical.em goldbach_conjecture /- HOW TO USE EXCLUDED MIDDLE. The real power is in how we *use* this new axiom. **You give it a proposition, P, it gives you a proof of a disjunction (P ∨ ¬P).** Well, what do you do with a proof of a disjunction? Answer: a case analysis. Given a proposition, P, the "strategy," then, is to a case analysis on "em P." Remember "em P" gives you a proof of P ∨ ¬P, and its on this proof, of this disjunction, that you do a case analysis. In one case P is assumed true; in the other case, ¬P is assumed true; *and there are no other cases.* -/ /- At this point you should see that a proof in the constructive logic of Lean is *informative*. It tells you *why* a given proposition is true. But with excluded middle, a proof of P ∨ ¬P is not informative, in that it no longer contains a proof of either side. -/ /- Here is an example where we apply excluded middle to the proposition, ItsRaining, to obtain a proof of ItsRaining ∨ ¬ItsRaining. -/ axiom ItsRaining : Prop -- assume ItsRaining is any proposition #check excluded_middle ItsRaining -- apply em to ItsRaining theorem example_em : ItsRaining ∨ ¬ItsRaining := excluded_middle ItsRaining -- apply excluded_middle directly to ItsRaining -- to return a proof of ItsRaining ∨ ¬ItsRaining -- by universal instantiation of excluded middle /- In Lean's official libraries, excluded middle is called classical.em (the name is em in the classical namespace). -/ theorem example_em' : ItsRaining ∨ ¬ItsRaining := classical.em ItsRaining /- PROOF BY NEGATION, AGAIN -/ /- Next we return to the negation connective, which in logic is pronounced "not." Given any proposition, P, ¬P is also a proposition; and what it means is, exactly, P → false. If P is true, then false is true, and false cannot possibly be true, so P must not be. Thus, to prove ¬P you prove P → false. Another way to read P → false is that, if we assume that P is true, we can derive a contradiction, proof of false that cannot exist, so P must not be true. MEMORIZE THIS REASONING. Again, to prove ¬P, *assume P* and show that in that context you can derive a contradiction in the form of a proof of false. This is the strategy call proof by negation. (THERE WAS A TYPO HERE) -/ /- How about we prove ¬(0 = 1) in English. Proof. By negation. Assume 0 = 1 and show that this leads to a contradiction. That is, show 0 = 1 → false. The rest of the proof is by case analysis on the assumed proof of 0 = 1. The only way to have a proof of equality is by the reflexive property of =. But the reflexive property doesn't imply that there's a proof of 0 = 1. So there can be no proof of 0 = 1, and the assumption that 0 = 1 is thus a contradiction. We finish the proof by case analysis on the possible proofs of 0 = 1, of which there are zero. So in all (zero!) cases, the conclusion (false) follows. Therefore 0 = 1 → false, which is to say, ¬(0 = 1) is proved and thus true. QED. -/ example : ¬0 = 1 := begin show 0 = 1 → false, -- rewrite goal to a definitionally equal goal assume h, cases h, -- there are *zero* ways to build a proof of 0 = 1 -- case analysis discharges our "proof obligation" end
cd347ff49e673ffc9bf8ac2757a90b637a5240ec
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/ubscalar.lean
11dc60fa5b28b7a92fd53531bbda441ca704e64b
[ "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
318
lean
structure Foo := (flag : Bool := false) (x : UInt16 := 0) (z : UInt32 := 0) (w : UInt64 := 0) (h : USize := 0) (xs : List Nat := []) set_option trace.compiler.ir.init true def f (s : Foo) : Foo := { s with x := s.x + 1 } def g (flag : Bool) : Foo := let s : Foo := { x := 10, flag := flag }; f s
aaeb3452537d0346cb259656cfa3142cb09e209b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/ring_theory/laurent_series.lean
430e199e496ea561c2f05416a9725b6e8bbcede4
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
8,436
lean
/- Copyright (c) 2021 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import ring_theory.hahn_series import ring_theory.localization.fraction_ring /-! # Laurent Series > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. ## Main Definitions * Defines `laurent_series` as an abbreviation for `hahn_series ℤ`. * Provides a coercion `power_series R` into `laurent_series R` given by `hahn_series.of_power_series`. * Defines `laurent_series.power_series_part` * Defines the localization map `laurent_series.of_power_series_localization` which evaluates to `hahn_series.of_power_series`. -/ open hahn_series open_locale big_operators classical polynomial noncomputable theory universe u /-- A `laurent_series` is implemented as a `hahn_series` with value group `ℤ`. -/ abbreviation laurent_series (R : Type*) [has_zero R] := hahn_series ℤ R variables {R : Type u} namespace laurent_series section semiring variable [semiring R] instance : has_coe (power_series R) (laurent_series R) := ⟨hahn_series.of_power_series ℤ R⟩ lemma coe_power_series (x : power_series R) : (x : laurent_series R) = hahn_series.of_power_series ℤ R x := rfl @[simp] lemma coeff_coe_power_series (x : power_series R) (n : ℕ) : hahn_series.coeff (x : laurent_series R) n = power_series.coeff R n x := by rw [coe_power_series, of_power_series_apply_coeff] /-- This is a power series that can be multiplied by an integer power of `X` to give our Laurent series. If the Laurent series is nonzero, `power_series_part` has a nonzero constant term. -/ def power_series_part (x : laurent_series R) : power_series R := power_series.mk (λ n, x.coeff (x.order + n)) @[simp] lemma power_series_part_coeff (x : laurent_series R) (n : ℕ) : power_series.coeff R n x.power_series_part = x.coeff (x.order + n) := power_series.coeff_mk _ _ @[simp] lemma power_series_part_zero : power_series_part (0 : laurent_series R) = 0 := by { ext, simp } @[simp] lemma power_series_part_eq_zero (x : laurent_series R) : x.power_series_part = 0 ↔ x = 0 := begin split, { contrapose!, intro h, rw [power_series.ext_iff, not_forall], refine ⟨0, _⟩, simp [coeff_order_ne_zero h] }, { rintro rfl, simp } end @[simp] lemma single_order_mul_power_series_part (x : laurent_series R) : (single x.order 1 : laurent_series R) * x.power_series_part = x := begin ext n, rw [← sub_add_cancel n x.order, single_mul_coeff_add, sub_add_cancel, one_mul], by_cases h : x.order ≤ n, { rw [int.eq_nat_abs_of_zero_le (sub_nonneg_of_le h), coeff_coe_power_series, power_series_part_coeff, ← int.eq_nat_abs_of_zero_le (sub_nonneg_of_le h), add_sub_cancel'_right] }, { rw [coe_power_series, of_power_series_apply, emb_domain_notin_range], { contrapose! h, exact order_le_of_coeff_ne_zero h.symm }, { contrapose! h, simp only [set.mem_range, rel_embedding.coe_fn_mk, function.embedding.coe_fn_mk] at h, obtain ⟨m, hm⟩ := h, rw [← sub_nonneg, ← hm], exact int.zero_le_of_nat _ } } end lemma of_power_series_power_series_part (x : laurent_series R) : of_power_series ℤ R x.power_series_part = single (-x.order) 1 * x := begin refine eq.trans _ (congr rfl x.single_order_mul_power_series_part), rw [← mul_assoc, single_mul_single, neg_add_self, mul_one, ← C_apply, C_one, one_mul, coe_power_series], end end semiring instance [comm_semiring R] : algebra (power_series R) (laurent_series R) := (hahn_series.of_power_series ℤ R).to_algebra @[simp] lemma coe_algebra_map [comm_semiring R] : ⇑(algebra_map (power_series R) (laurent_series R)) = hahn_series.of_power_series ℤ R := rfl /-- The localization map from power series to Laurent series. -/ @[simps] instance of_power_series_localization [comm_ring R] : is_localization (submonoid.powers (power_series.X : power_series R)) (laurent_series R) := { map_units := (begin rintro ⟨_, n, rfl⟩, refine ⟨⟨single (n : ℤ) 1, single (-n : ℤ) 1, _, _⟩, _⟩, { simp only [single_mul_single, mul_one, add_right_neg], refl }, { simp only [single_mul_single, mul_one, add_left_neg], refl }, { simp } end), surj := (begin intro z, by_cases h : 0 ≤ z.order, { refine ⟨⟨power_series.X ^ (int.nat_abs z.order) * power_series_part z, 1⟩, _⟩, simp only [ring_hom.map_one, mul_one, ring_hom.map_mul, coe_algebra_map, of_power_series_X_pow, submonoid.coe_one], rw [int.nat_abs_of_nonneg h, ← coe_power_series, single_order_mul_power_series_part] }, { refine ⟨⟨power_series_part z, power_series.X ^ (int.nat_abs z.order), ⟨_, rfl⟩⟩, _⟩, simp only [coe_algebra_map, of_power_series_power_series_part], rw [mul_comm _ z], refine congr rfl _, rw [subtype.coe_mk, of_power_series_X_pow, int.of_nat_nat_abs_of_nonpos], exact le_of_not_ge h } end), eq_iff_exists := (begin intros x y, rw [coe_algebra_map, of_power_series_injective.eq_iff], split, { rintro rfl, exact ⟨1, rfl⟩ }, { rintro ⟨⟨_, n, rfl⟩, hc⟩, rw [← sub_eq_zero, ← mul_sub, power_series.ext_iff] at hc, rw [← sub_eq_zero, power_series.ext_iff], intro m, have h := hc (m + n), rwa [linear_map.map_zero, subtype.coe_mk, power_series.X_pow_eq, power_series.monomial, add_comm m, power_series.coeff, finsupp.single_add, mv_power_series.coeff_add_monomial_mul, one_mul] at h } end) } instance {K : Type u} [field K] : is_fraction_ring (power_series K) (laurent_series K) := is_localization.of_le (submonoid.powers (power_series.X : power_series K)) _ (powers_le_non_zero_divisors_of_no_zero_divisors power_series.X_ne_zero) (λ f hf, is_unit_of_mem_non_zero_divisors $ map_mem_non_zero_divisors _ hahn_series.of_power_series_injective hf) end laurent_series namespace power_series open laurent_series variables {R' : Type*} [semiring R] [ring R'] (f g : power_series R) (f' g' : power_series R') @[simp, norm_cast] lemma coe_zero : ((0 : power_series R) : laurent_series R) = 0 := (of_power_series ℤ R).map_zero @[simp, norm_cast] lemma coe_one : ((1 : power_series R) : laurent_series R) = 1 := (of_power_series ℤ R).map_one @[simp, norm_cast] lemma coe_add : ((f + g : power_series R) : laurent_series R) = f + g := (of_power_series ℤ R).map_add _ _ @[simp, norm_cast] lemma coe_sub : ((f' - g' : power_series R') : laurent_series R') = f' - g' := (of_power_series ℤ R').map_sub _ _ @[simp, norm_cast] lemma coe_neg : ((-f' : power_series R') : laurent_series R') = -f' := (of_power_series ℤ R').map_neg _ @[simp, norm_cast] lemma coe_mul : ((f * g : power_series R) : laurent_series R) = f * g := (of_power_series ℤ R).map_mul _ _ lemma coeff_coe (i : ℤ) : ((f : power_series R) : laurent_series R).coeff i = if i < 0 then 0 else power_series.coeff R i.nat_abs f := begin cases i, { rw [int.nat_abs_of_nat_core, int.of_nat_eq_coe, coeff_coe_power_series, if_neg (int.coe_nat_nonneg _).not_lt] }, { rw [coe_power_series, of_power_series_apply, emb_domain_notin_image_support, if_pos (int.neg_succ_lt_zero _)], simp only [not_exists, rel_embedding.coe_fn_mk, set.mem_image, not_and, function.embedding.coe_fn_mk, ne.def, to_power_series_symm_apply_coeff, mem_support, int.coe_nat_eq, implies_true_iff, not_false_iff] } end @[simp, norm_cast] lemma coe_C (r : R) : ((C R r : power_series R) : laurent_series R) = hahn_series.C r := of_power_series_C _ @[simp] lemma coe_X : ((X : power_series R) : laurent_series R) = single 1 1 := of_power_series_X @[simp, norm_cast] lemma coe_smul {S : Type*} [semiring S] [module R S] (r : R) (x : power_series S) : ((r • x : power_series S) : laurent_series S) = r • x := by { ext, simp [coeff_coe, coeff_smul, smul_ite] } @[simp, norm_cast] lemma coe_bit0 : ((bit0 f : power_series R) : laurent_series R) = bit0 f := (of_power_series ℤ R).map_bit0 _ @[simp, norm_cast] lemma coe_bit1 : ((bit1 f : power_series R) : laurent_series R) = bit1 f := (of_power_series ℤ R).map_bit1 _ @[simp, norm_cast] lemma coe_pow (n : ℕ) : ((f ^ n : power_series R) : laurent_series R) = f ^ n := (of_power_series ℤ R).map_pow _ _ end power_series
0963e5d73289f578094c98984c71ca3a27683300
d751a70f46ed26dc0111a87f5bbe83e5c6648904
/Code/src/inst/exec/propagate.lean
9f0c2ab51a389bd589a2213e160af2386cb787aa
[]
no_license
marcusrossel/bachelors-thesis
92cb12ae8436c10fbfab9bfe4929a0081e615b37
d1ec2c2b5c3c6700a506f2e3cc93f1160e44b422
refs/heads/main
1,682,873,547,703
1,619,795,735,000
1,619,795,735,000
306,041,494
2
0
null
null
null
null
UTF-8
Lean
false
false
15,427
lean
import inst.network.graph open reactor.ports -- Cf. inst/primitives.lean variables {υ : Type*} [decidable_eq υ] namespace inst namespace network namespace graph -- Propagates the source value to the desination port for a given edge. noncomputable def propagate_edge (η : graph υ) (e : graph.edge) : graph υ := η.update_port role.input e.dst (η.port role.output e.src) -- Propagating an edge produces an equivalent network graph. lemma propagate_edge_equiv (η : graph υ) (e : graph.edge) : propagate_edge η e ≈ η := by simp [propagate_edge, graph.equiv_symm, graph.update_port_equiv] -- Propagating an edge that ends in a port, which is independent of a given reaction, -- produces a reactor which is equal relative to that reaction. lemma propagate_edge_eq_rel_to {η : graph υ} {i : reaction.id} {e : graph.edge} (h : e.dst ∉ η.deps i role.input) : (η.propagate_edge e).rtr i.rtr =i.rcn= η.rtr i.rtr := begin unfold propagate_edge update_port, by_cases hc : i.rtr = e.dst.rtr, { have hₘ, from (not_iff_not.mpr mem_deps_iff_mem_rcn_deps).mp h, have hₘ', from not_and.mp hₘ hc, unfold reaction.deps at hₘ', simp only [rcn, hc, update_reactor_eq_rtr] at hₘ' ⊢, have hₑ, from reactor.eq_rel_to.single (refl ((η.rtr e.dst.rtr).update role.input e.dst.prt (η.port role.output e.src))) hₘ', exact reactor.eq_rel_to_symm hₑ }, { rw update_reactor_ne_rtr _ _ (ne.symm hc), exact reactor.eq_rel_to_refl _ _ } end -- Under the right conditions, running a reaction and propagating and edge can be swapped in their order. lemma propagate_edge_run_local_comm {η : graph υ} {e : graph.edge} {i : reaction.id} (hᵢ : e.dst ∉ η.deps i role.input) (hₒ : e.src ∉ η.deps i role.output) : (η.propagate_edge e).run_local i = (η.run_local i).propagate_edge e := begin have hqₗ, from equiv_trans (run_local_equiv (η.propagate_edge e) i) (propagate_edge_equiv η e), have hqᵣ, from equiv_trans (propagate_edge_equiv (η.run_local i) e) (run_local_equiv η i), have hq, from equiv_trans hqₗ (equiv_symm hqᵣ), ext1, exact hq.right.left, simp only [propagate_edge, run_local_output_eq hₒ, symm (run_local_update_input_comm _ hᵢ)], exact hq.left end -- Under the right conditions, the order in which edges are propagated can be swapped. lemma propagate_edge_comm {η : network.graph υ} {e e' : graph.edge} (hᵤ : η.has_unique_port_ins) (hₘ : e ∈ η.edges) (hₘ' : e' ∈ η.edges) : propagate_edge (propagate_edge η e) e' = propagate_edge (propagate_edge η e') e := begin by_cases h : e = e', rw h, { unfold propagate_edge, repeat { rw update_port_opposite_eq }, rw update_port_comm, rw graph.has_unique_port_ins at hᵤ, exact (hᵤ _ _ hₘ hₘ' h) } end -- Propagates the source values to the desination ports for a given set of edges. noncomputable def propagate_edges (η : graph υ) (es : list graph.edge) : graph υ := es.foldl propagate_edge η -- Propagating edges produces an equivalent network graph. lemma propagate_edges_equiv (η : graph υ) (es : list graph.edge) : propagate_edges η es ≈ η := begin unfold propagate_edges, induction es generalizing η, case list.nil { simp }, case list.cons : eₕ eₜ hᵢ { rw list.foldl_cons, transitivity, exact hᵢ (propagate_edge η eₕ), exact propagate_edge_equiv η eₕ } end -- Propagating edges that end in ports, which are independent of a given reaction, -- produces a reactor which is equal relative to that reaction. lemma propagate_edges_eq_rel_to {η : graph υ} {i : reaction.id} {es : list graph.edge} (h : ∀ e : graph.edge, e ∈ es → e.dst ∉ η.deps i role.input) : (η.propagate_edges es).rtr i.rtr =i.rcn= η.rtr i.rtr := begin unfold propagate_edges, induction es generalizing η, case list.nil { exact reactor.eq_rel_to_refl (η.rtr i.rtr) i.rcn }, case list.cons { rw list.foldl_cons, have hᵣ, from propagate_edge_eq_rel_to (h es_hd (list.mem_cons_self _ _)), suffices hₘ : ∀ (e : edge), e ∈ es_tl → e.dst ∉ (η.propagate_edge es_hd).deps i role.input, from reactor.eq_rel_to.multiple (es_ih hₘ) hᵣ, intros e hₑ, have hq, from propagate_edge_equiv η es_hd, rw [deps, rcn, ←(hq.right.right i.rtr).right] at h, exact h e (list.mem_cons_of_mem _ hₑ) } end -- Under the right conditions, running a reaction and propagating edges can be swapped in their order. lemma propagate_edges_run_local_comm {η : graph υ} {es : list graph.edge} {i : reaction.id} (h : ∀ e : edge, e ∈ es → (e.dst ∉ η.deps i role.input) ∧ (e.src ∉ η.deps i role.output)) : (η.propagate_edges es).run_local i = (η.run_local i).propagate_edges es := begin induction es generalizing η, case list.nil { simp [propagate_edges] }, case list.cons { simp only [propagate_edges, list.foldl_cons] at es_ih ⊢, have h', from h es_hd (list.mem_cons_self _ _), rw ←(propagate_edge_run_local_comm h'.left h'.right), suffices hg : ∀ (e : edge), e ∈ es_tl → e.dst ∉ (η.propagate_edge es_hd).deps i role.input ∧ e.src ∉ (η.propagate_edge es_hd).deps i role.output, from es_ih hg, intros e hₑ, replace h := h e (list.mem_cons_of_mem _ hₑ), unfold deps rcn at h, have hq, from propagate_edge_equiv η es_hd, rw ←(hq.right.right i.rtr).right at h, exact h } end -- Under the right conditions, the order in which edges are propagated can be swapped. lemma propagate_edges_comm' {η : graph υ} {es : list graph.edge} {e : graph.edge} (hᵤ : η.has_unique_port_ins) (hₘ : e ∈ η.edges) (hₘ' : ∀ e' ∈ es, e' ∈ η.edges) : (η.propagate_edges es).propagate_edge e = (η.propagate_edge e).propagate_edges es := begin induction es generalizing η, case list.nil { simp [propagate_edges] }, case list.cons { simp only [propagate_edges, list.foldl_cons] at es_ih ⊢, have h', from hₘ' es_hd (list.mem_cons_self _ _), rw propagate_edge_comm hᵤ hₘ h', have hᵤ' : (η.propagate_edge es_hd).has_unique_port_ins, from eq_edges_unique_port_ins (propagate_edge_equiv η es_hd).left hᵤ, suffices hg : ∀ (e' : edge), e' ∈ es_tl → e' ∈ η.edges, from es_ih hᵤ' hₘ hg, intros e' hₑ, exact hₘ' e' (list.mem_cons_of_mem _ hₑ) } end -- Under the right conditions, the order in which edges are propagated can be swapped. lemma propagate_edges_comm {η : graph υ} {es es' : list graph.edge} (hᵤ : η.has_unique_port_ins) (hₘ : ∀ e ∈ es, e ∈ η.edges) (hₘ' : ∀ e' ∈ es', e' ∈ η.edges) : (η.propagate_edges es).propagate_edges es' = (η.propagate_edges es').propagate_edges es := begin induction es generalizing η, case list.nil { simp [propagate_edges] }, case list.cons { simp only [propagate_edges, list.foldl_cons] at es_ih ⊢, have hc, from propagate_edges_comm' hᵤ (hₘ es_hd (list.mem_cons_self _ _)) hₘ', rw propagate_edges at hc, simp only [hc, propagate_edges], have hᵤ' : (η.propagate_edge es_hd).has_unique_port_ins, from eq_edges_unique_port_ins (propagate_edge_equiv η es_hd).left hᵤ, suffices hg : ∀ (e : edge), e ∈ es_tl → e ∈ η.edges, from es_ih hᵤ' hg hₘ', intros e hₑ, exact hₘ e (list.mem_cons_of_mem _ hₑ) } end -- For all edges `e` with `e.src = p`, set `e.dst` to `v`. noncomputable def propagate_port (η : graph υ) (p : port.id) : graph υ := η.propagate_edges (η.eₒ p).val.to_list -- Propagating a port produces an equivalent network graph. lemma propagate_port_equiv (η : graph υ) (p : port.id) : propagate_port η p ≈ η := begin unfold propagate_port, induction (η.eₒ p).val.to_list ; apply propagate_edges_equiv end -- Propagating a port that connects only to ports, which are independent of a given reaction, -- produces a reactor which is equal relative to that reaction. lemma propagate_port_eq_rel_to {η : graph υ} {i : reaction.id} {p : port.id} (h : ∀ e : edge, e ∈ η.eₒ p → e.dst ∉ η.deps i role.input) : (η.propagate_port p).rtr i.rtr =i.rcn= η.rtr i.rtr := begin unfold propagate_port, suffices h' : ∀ (e : edge), e ∈ (η.eₒ p).val.to_list → e.dst ∉ η.deps i role.input, from propagate_edges_eq_rel_to h', intros e hₑ, rw multiset.mem_to_list at hₑ, exact h e hₑ end -- Under the right conditions, running a reaction and propagating a port can be swapped in their order. lemma propagate_port_run_local_comm {η : graph υ} {p : port.id} {i : reaction.id} (h : ∀ e : edge, (e ∈ η.eₒ p) → (e.dst ∉ η.deps i role.input) ∧ (e.src ∉ η.deps i role.output)) : (η.propagate_port p).run_local i = (η.run_local i).propagate_port p := begin unfold propagate_port, suffices hg : ∀ (e : edge), e ∈ (η.eₒ p).val.to_list → e.dst ∉ η.deps i role.input ∧ e.src ∉ η.deps i role.output, from propagate_edges_run_local_comm hg, intros e hₑ, rw multiset.mem_to_list at hₑ, exact h e hₑ end -- Under the right conditions, the order in which ports are propagated can be swapped. lemma propagate_port_comm {η : graph υ} (p p' : port.id) (hᵤ : η.has_unique_port_ins) : propagate_port (propagate_port η p) p' = propagate_port (propagate_port η p') p := begin unfold propagate_port, have h : ∀ x x', (propagate_edges η (η.eₒ x).val.to_list).eₒ x' = η.eₒ x', { intros x x', unfold graph.eₒ, rw (propagate_edges_equiv η _).left }, repeat { rw h }, have h' : ∀ x e, e ∈ (η.eₒ x).val.to_list → e ∈ η.edges, { intros x e hₑ, rw multiset.mem_to_list at hₑ, unfold eₒ at hₑ, exact (finset.mem_filter.mp hₑ).left }, exact propagate_edges_comm hᵤ (h' p) (h' p') end -- For all edges `e` with `e.src ∈ ps`, set `e.dst` to `rtr.output.nth e.src`. noncomputable def propagate_ports (η : graph υ) (ps : list port.id) : graph υ := ps.foldl propagate_port η -- Propagating ports produces an equivalent network graph. lemma propagate_ports_equiv (η : graph υ) (ps : list port.id) : propagate_ports η ps ≈ η := begin induction ps with pₕ pₜ hᵢ generalizing η, case list.nil { simp [propagate_ports] }, case list.cons { simp only [propagate_ports, list.foldl_cons], transitivity, exact hᵢ (propagate_port η pₕ), exact propagate_port_equiv η pₕ } end -- Propagating ports that connect only to ports, which are independent of a given reaction, -- produces a reactor which is equal relative to that reaction. lemma propagate_ports_eq_rel_to {η : graph υ} {i : reaction.id} {ps : list port.id} (h : ∀ p ∈ ps, ∀ e : edge, e ∈ η.eₒ p → e.dst ∉ η.deps i role.input) : (η.propagate_ports ps).rtr i.rtr =i.rcn= η.rtr i.rtr := begin induction ps generalizing η, case list.nil { unfold propagate_ports, exact reactor.eq_rel_to_refl _ _, }, case list.cons { simp only [propagate_ports, list.foldl_cons] at ps_ih ⊢, have hᵣ, from propagate_port_eq_rel_to (h ps_hd (list.mem_cons_self _ _)), simp at hᵣ, suffices hₘ : (∀ (p : port.id), p ∈ ps_tl → ∀ (e : edge), e ∈ (η.propagate_port ps_hd).eₒ p → e.dst ∉ (η.propagate_port ps_hd).deps i role.input), from reactor.eq_rel_to.multiple (ps_ih hₘ) hᵣ, intros x hₓ e hₑ, have hq, from propagate_port_equiv η ps_hd, rw [deps, rcn, ←(hq.right.right i.rtr).right] at h, rw [eₒ, hq.left] at hₑ, exact (h x (list.mem_cons_of_mem _ hₓ) e) hₑ } end -- Under the right conditions, running a reaction and propagating ports can be swapped in their order. lemma propagate_ports_run_local_comm {η : graph υ} {ps : list port.id} {i : reaction.id} (h : ∀ (p ∈ ps) (e : edge), (e ∈ η.eₒ p) → e.dst ∉ (η.deps i role.input) ∧ (e.src ∉ η.deps i role.output)) : (η.propagate_ports ps).run_local i = (η.run_local i).propagate_ports ps := begin induction ps generalizing η, case list.nil { simp [propagate_ports] }, case list.cons { simp only [propagate_ports, list.foldl_cons] at ps_ih ⊢, have h', from h ps_hd (list.mem_cons_self _ _), rw ←(propagate_port_run_local_comm h'), suffices hg : ∀ (p : port.id), p ∈ ps_tl → ∀ (e : edge), e ∈ (η.propagate_port ps_hd).eₒ p → e.dst ∉ (η.propagate_port ps_hd).deps i role.input ∧ e.src ∉ (η.propagate_port ps_hd).deps i role.output, from ps_ih hg, intros p hₚ e hₑ, replace h := h p (list.mem_cons_of_mem _ hₚ) e, unfold eₒ at hₑ, have hq, from propagate_port_equiv η ps_hd, rw hq.left at hₑ, replace h := h hₑ, unfold deps rcn at h, rw ←(hq.right.right i.rtr).right at h, exact h } end -- Under the right conditions, the order in which ports are propagated can be swapped. lemma propagate_ports_comm' {η : graph υ} (p : port.id) (ps : list port.id) (hᵤ : η.has_unique_port_ins) : (η.propagate_ports ps).propagate_port p = (η.propagate_port p).propagate_ports ps := begin induction ps generalizing η, case list.nil { simp [propagate_ports] }, case list.cons { simp only [propagate_ports, list.foldl_cons] at ps_ih ⊢, rw propagate_port_comm _ _ hᵤ, exact ps_ih (eq_edges_unique_port_ins (symm (propagate_port_equiv η ps_hd).left) hᵤ) } end -- Under the right conditions, the order in which ports are propagated can be swapped. lemma propagate_ports_comm {η : graph υ} (ps ps' : list port.id) (hᵤ : η.has_unique_port_ins) : (η.propagate_ports ps).propagate_ports ps' = (η.propagate_ports ps').propagate_ports ps := begin induction ps generalizing η, case list.nil { simp [propagate_ports] }, case list.cons { simp only [propagate_ports, list.foldl_cons] at ps_ih ⊢, have hc, from propagate_ports_comm' ps_hd ps' hᵤ, rw propagate_ports at hc, simp only [hc, propagate_ports], from ps_ih (eq_edges_unique_port_ins (symm (propagate_port_equiv η ps_hd).left) hᵤ) } end end graph end network end inst
5ebaa9a4499581835e503cce3900e400ef3abfb7
5bcdf53ae59d93bf05c4a6b7780107f9bba8a987
/2_StackMachine.lean
bc3b4b6b7e0833bc89f5d038843f820ad7bdafc8
[]
no_license
joshpoll/CPDT-examples-in-Lean
3241734e80c8507934a9fbf2ddfed9eedc1ed27b
287aebec9a4a9dc4a07b8e4cc885c81afe400f1a
refs/heads/master
1,611,267,038,438
1,498,610,301,000
1,498,610,301,000
95,181,904
0
0
null
null
null
null
UTF-8
Lean
false
false
8,389
lean
import tools.auto.finish import _target.deps.mini_crush.src.mini_crush namespace arith -- *Artihmetic Expressions Over Natural Numbers -- **Source Language -- binary operation syntax inductive binop : Type | Plus | Times -- arithmetic expression syntax inductive exp : Type | Const : ℕ → exp | Binop : binop → exp → exp → exp -- binop denotational semantics def binopDenote : binop → ℕ → ℕ → ℕ | binop.Plus := nat.add | binop.Times := nat.mul -- exp denotational semantics def expDenote : exp → ℕ | (exp.Const n) := n | (exp.Binop b e1 e2) := (binopDenote b) (expDenote e1) (expDenote e2) -- tests using both #reduce and #eval #reduce (decidable.to_bool(expDenote (exp.Const 42) = 42)) #eval (decidable.to_bool(expDenote (exp.Const 42) = 42)) #reduce (decidable.to_bool(expDenote (exp.Binop binop.Plus (exp.Const 2) (exp.Const 2)) = 4)) #eval (decidable.to_bool(expDenote (exp.Binop binop.Plus (exp.Const 2) (exp.Const 2)) = 4)) #reduce (decidable.to_bool(expDenote (exp.Binop binop.Times (exp.Binop binop.Plus (exp.Const 2) (exp.Const 2)) (exp.Const 7)) = 28)) #eval (decidable.to_bool(expDenote (exp.Binop binop.Times (exp.Binop binop.Plus (exp.Const 2) (exp.Const 2)) (exp.Const 7)) = 28)) -- **Target Language -- instruction syntax inductive instr : Type | iConst : ℕ → instr | iBinop : binop → instr -- program and stack syntax -- mark as reducible so lean can unfold the definitions during typechecking @[reducible] def prog : Type := list instr @[reducible] def stack : Type := list ℕ -- instr denotational semantics def instrDenote (i : instr) (s : stack) : option stack := match i with | (instr.iConst n) := some (n :: s) | (instr.iBinop b) := match s with | arg1 :: arg2 :: s' := some ((binopDenote b) arg1 arg2 :: s') | _ := none end end -- prog denotational semantics def progDenote : prog → stack → option stack | [] s := some s | (i :: p') s := match instrDenote i s with | none := none | some s' := progDenote p' s' end -- **Translation def compile : exp → prog | (exp.Const n) := instr.iConst n :: [] | (exp.Binop b e1 e2) := compile e2 ++ compile e1 ++ instr.iBinop b :: [] -- compilation examples #reduce compile (exp.Const 42) #reduce compile (exp.Binop binop.Plus (exp.Const 2) (exp.Const 2)) #reduce compile (exp.Binop binop.Times (exp.Binop binop.Plus (exp.Const 2) (exp.Const 2))(exp.Const 7)) -- compilation-evaluation examples #reduce progDenote (compile (exp.Const 42)) [] #reduce progDenote (compile (exp.Binop binop.Plus (exp.Const 2) (exp.Const 2))) [] #reduce progDenote (compile (exp.Binop binop.Times (exp.Binop binop.Plus (exp.Const 2) (exp.Const 2))(exp.Const 7))) [] -- **Translation Correctness lemma compile_correct' (e : exp) : ∀ p s, progDenote (compile e ++ p) s = progDenote p (expDenote e :: s) := begin induction e; intros, case exp.Const { unfold compile, unfold expDenote, simp, unfold progDenote, unfold instrDenote, simp, unfold instrDenote._match_1, unfold progDenote._match_1, refl }, case exp.Binop { unfold compile, unfold expDenote, simp, /- can replace these lines with simph -/ rw ih_2, /- -/ rw ih_1, /- -/ unfold progDenote, unfold instrDenote, simp, unfold instrDenote._match_1, unfold instrDenote._match_2, unfold progDenote._match_1, refl } end lemma compile_correct'_lean (e : exp) : ∀ p s, progDenote (compile e ++ p) s = progDenote p (expDenote e :: s) := begin induction e; intros, case exp.Const {refl}, case exp.Binop { unfold compile expDenote, simph, refl } end @[simp] lemma compile_correct'_crush (e : exp) : ∀ p s, progDenote (compile e ++ p) s = progDenote p (expDenote e :: s) := by mini_crush lemma app_nil_end {A : Type} (l : list A) : l = l ++ list.nil := by induction l; simph theorem compile_correct (e : exp) : progDenote (compile e) [] = some (expDenote e :: []) := begin rw app_nil_end (compile e), rw compile_correct', refl end -- TODO: excessive memory consumption theorem compile_correct_crush (e : exp) : progDenote (compile e) [] = some (expDenote e :: []) := by mini_crush end arith namespace typed -- *Typed Expressions -- **Source Language -- atomic types inductive type : Type | Nat | Bool open type -- binop types inductive tbinop : type → type → type → Type | TPlus : tbinop Nat Nat Nat | TTimes : tbinop Nat Nat Nat | TEq : ∀ t, tbinop t t Bool | TLt : tbinop Nat Nat Bool open tbinop -- expression types inductive texp : type → Type | TNConst : ℕ → texp Nat | TBConst : bool → texp Bool | TBinop : ∀ {t1 t2 t}, tbinop t1 t2 t → texp t1 → texp t2 → texp t open texp -- type denotational semantics def typeDenote : type → Type | Nat := ℕ | Bool := bool -- tbinop denotational semantics def tbinopDenote : ∀ {arg1 arg2 res} (b : tbinop arg1 arg2 res), typeDenote arg1 → typeDenote arg2 → typeDenote res | ._ ._ ._ TPlus := nat.add | ._ ._ ._ TTimes := nat.mul | ._ ._ ._ (TEq Nat) := (λ x y, decidable.to_bool $ x = y) | ._ ._ ._ (TEq Bool) := (λ x y, decidable.to_bool $ x = y) | ._ ._ ._ TLt := (λ x y, decidable.to_bool $ nat.le x y) -- texp denotational semantics def texpDenote : ∀ {t}, texp t → typeDenote t | ._ (TNConst n) := n | ._ (TBConst b) := b | ._ (@TBinop _ _ _ b e1 e2) := (tbinopDenote b) (texpDenote e1) (texpDenote e2) #reduce texpDenote (TNConst 42) #reduce texpDenote (TBConst true) -- TODO: is there a way to remove need for _'s? #reduce texpDenote (TBinop TTimes (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)) #reduce texpDenote (TBinop (TEq Nat) (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)) #reduce texpDenote (TBinop TLt (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)) -- **Target Language -- stack type to describe how expressions affect the stack @[reducible] def tstack := list type inductive tinstr : tstack → tstack → Type | TiNConst : ∀ s, ℕ → tinstr s (Nat :: s) | TiBConst : ∀ s, bool → tinstr s (Bool :: s) | TiBinop : ∀ arg1 arg2 res s, tbinop arg1 arg2 res → tinstr (arg1 :: arg2 :: s) (res :: s) open tinstr inductive tprog : tstack → tstack → Type | TNil : ∀ s, tprog s s | TCons : ∀ s1 s2 s3, tinstr s1 s2 → tprog s2 s3 → tprog s1 s3 open tprog def vstack : tstack → Type | [] := unit | (t :: ts) := typeDenote t × vstack ts def tinstrDenote : ∀ {ts} {ts'}, tinstr ts ts' → vstack ts → vstack ts' | ._ ._ (TiNConst _ n) := (λ s, (n, s)) | ._ ._ (TiBConst _ b) := (λ s, (b, s)) | ._ ._ (TiBinop _ _ _ _ b) := (λ s, let (arg1, (arg2, s')) := s in ((tbinopDenote b) arg1 arg2, s')) def tprogDenote : ∀ {ts} {ts'}, tprog ts ts' → vstack ts → vstack ts' | ._ ._ (TNil _) := (λ s, s) | ._ ._ (TCons _ _ _ i p) := (λ s, tprogDenote p (tinstrDenote i s)) -- **Translation def tconcat : ∀ {ts} {ts'} {ts''}, tprog ts ts' → tprog ts' ts'' → tprog ts ts'' | ._ ._ ts'' (TNil _) := (λ p, p) | ._ ._ ts'' (TCons _ _ _ i p1) := (λ p, TCons _ _ _ i (tconcat p1 p)) def tcompile : ∀ {t} (e : texp t) (ts : tstack), tprog ts (t :: ts) | ._ (TNConst n) _ := TCons _ _ _ (TiNConst _ n) (TNil _) | ._ (TBConst b) _ := TCons _ _ _ (TiBConst _ b) (TNil _) | ._ (@TBinop _ _ _ b e1 e2) _ := tconcat (tcompile e2 _) (tconcat (tcompile e1 _) (TCons _ _ _ (TiBinop _ _ _ _ b) (TNil _))) #reduce tprogDenote (tcompile (TNConst 42) []) () #reduce tprogDenote (tcompile (TBConst true) []) () #reduce tprogDenote (tcompile (TBinop TTimes (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)) []) () #reduce tprogDenote (tcompile (TBinop (TEq Nat) (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)) []) () #reduce tprogDenote (tcompile (TBinop TLt (TBinop TPlus (TNConst 2) (TNConst 2)) (TNConst 7)) []) () -- **Translation Correctness @[simp] lemma tconcat_correct : ∀ ts ts' ts'' (p : tprog ts ts') (p' : tprog ts' ts'') (s : vstack ts), tprogDenote (tconcat p p') s = tprogDenote p' (tprogDenote p s) := by mini_crush @[simp] lemma tcompile_correct' : ∀ t (e : texp t) ts (s : vstack ts), tprogDenote (tcompile e ts) s = (texpDenote e, s) := by mini_crush theorem tcompile_correct : ∀ t (e : texp t), tprogDenote (tcompile e []) () = (texpDenote e, ()) := by mini_crush end typed
4d7e3f8eb149bc6a757b62d4bfea4c8c5203ef19
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/set_theory/ordinal.lean
b7eeae6d679f6f7e8b24bceaaaa8dd8a31add190
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
58,121
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn -/ import set_theory.cardinal import order.conditionally_complete_lattice /-! # Ordinals Ordinals are defined as equivalences of well-ordered sets under order isomorphism. They are endowed with a total order, where an ordinal is smaller than another one if it embeds into it as an initial segment (or, equivalently, in any way). This total order is well founded. ## Main definitions * `initial_seg r s`: type of order embeddings of `r` into `s` for which the range is an initial segment (i.e., if `b` belongs to the range, then any `b' < b` also belongs to the range). It is denoted by `r ≼i s`. * `principal_seg r s`: Type of order embeddings of `r` into `s` for which the range is a principal segment, i.e., an interval of the form `(-∞, top)` for some element `top`. It is denoted by `r ≺i s`. * `ordinal`: the type of ordinals (in a given universe) * `ordinal.type r`: given a well-founded order `r`, this is the corresponding ordinal * `ordinal.typein r a`: given a well-founded order `r` on a type `α`, and `a : α`, the ordinal corresponding to all elements smaller than `a`. * `enum r o h`: given a well-order `r` on a type `α`, and an ordinal `o` strictly smaller than the ordinal corresponding to `r` (this is the assumption `h`), returns the `o`-th element of `α`. In other words, the elements of `α` can be enumerated using ordinals up to `type r`. * `ordinal.card o`: the cardinality of an ordinal `o`. * `ordinal.lift` lifts an ordinal in universe `u` to an ordinal in universe `max u v`. For a version registering additionally that this is an initial segment embedding, see `ordinal.lift.initial_seg`. For a version regiserting that it is a principal segment embedding if `u < v`, see `ordinal.lift.principal_seg`. * `ordinal.omega` is the first infinite ordinal. It is the order type of `ℕ`. * `o₁ + o₂` is the order on the disjoint union of `o₁` and `o₂` obtained by declaring that every element of `o₁` is smaller than every element of `o₂`. The main properties of addition (and the other operations on ordinals) are stated and proved in `ordinal_arithmetic.lean`. Here, we only introduce it and prove its basic properties to deduce the fact that the order on ordinals is total (and well founded). * `succ o` is the successor of the ordinal `o`. * `ordinal.min`: the minimal element of a nonempty indexed family of ordinals * `ordinal.omin` : the minimal element of a nonempty set of ordinals * `cardinal.ord c`: when `c` is a cardinal, `ord c` is the smallest ordinal with this cardinality. It is the canonical way to represent a cardinal with an ordinal. A conditionally complete linear order with bot structure is registered on ordinals, where `⊥` is `0`, the ordinal corresponding to the empty type, and `Inf` is `ordinal.omin` for nonempty sets and `0` for the empty set by convention. ## Notations * `r ≼i s`: the type of initial segment embeddings of `r` into `s`. * `r ≺i s`: the type of principal segment embeddings of `r` into `s`. * `ω` is a notation for the first infinite ordinal in the locale `ordinal`. -/ noncomputable theory open function cardinal set equiv open_locale classical cardinal universes u v w variables {α : Type*} {β : Type*} {γ : Type*} {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} /-! ### Initial segments Order embeddings whose range is an initial segment of `s` (i.e., if `b` belongs to the range, then any `b' < b` also belongs to the range). The type of these embeddings from `r` to `s` is called `initial_seg r s`, and denoted by `r ≼i s`. -/ /-- If `r` is a relation on `α` and `s` in a relation on `β`, then `f : r ≼i s` is an order embedding whose range is an initial segment. That is, whenever `b < f a` in `β` then `b` is in the range of `f`. -/ @[nolint has_inhabited_instance] structure initial_seg {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends r ↪r s := (init : ∀ a b, s b (to_rel_embedding a) → ∃ a', to_rel_embedding a' = b) local infix ` ≼i `:25 := initial_seg namespace initial_seg instance : has_coe (r ≼i s) (r ↪r s) := ⟨initial_seg.to_rel_embedding⟩ instance : has_coe_to_fun (r ≼i s) (λ _, α → β) := ⟨λ f x, (f : r ↪r s) x⟩ @[simp] theorem coe_fn_mk (f : r ↪r s) (o) : (@initial_seg.mk _ _ r s f o : α → β) = f := rfl @[simp] theorem coe_fn_to_rel_embedding (f : r ≼i s) : (f.to_rel_embedding : α → β) = f := rfl @[simp] theorem coe_coe_fn (f : r ≼i s) : ((f : r ↪r s) : α → β) = f := rfl theorem init' (f : r ≼i s) {a : α} {b : β} : s b (f a) → ∃ a', f a' = b := f.init _ _ theorem init_iff (f : r ≼i s) {a : α} {b : β} : s b (f a) ↔ ∃ a', f a' = b ∧ r a' a := ⟨λ h, let ⟨a', e⟩ := f.init' h in ⟨a', e, (f : r ↪r s).map_rel_iff.1 (e.symm ▸ h)⟩, λ ⟨a', e, h⟩, e ▸ (f : r ↪r s).map_rel_iff.2 h⟩ /-- An order isomorphism is an initial segment -/ def of_iso (f : r ≃r s) : r ≼i s := ⟨f, λ a b h, ⟨f.symm b, rel_iso.apply_symm_apply f _⟩⟩ /-- The identity function shows that `≼i` is reflexive -/ @[refl] protected def refl (r : α → α → Prop) : r ≼i r := ⟨rel_embedding.refl _, λ a b h, ⟨_, rfl⟩⟩ /-- Composition of functions shows that `≼i` is transitive -/ @[trans] protected def trans (f : r ≼i s) (g : s ≼i t) : r ≼i t := ⟨f.1.trans g.1, λ a c h, begin simp at h ⊢, rcases g.2 _ _ h with ⟨b, rfl⟩, have h := g.1.map_rel_iff.1 h, rcases f.2 _ _ h with ⟨a', rfl⟩, exact ⟨a', rfl⟩ end⟩ @[simp] theorem refl_apply (x : α) : initial_seg.refl r x = x := rfl @[simp] theorem trans_apply (f : r ≼i s) (g : s ≼i t) (a : α) : (f.trans g) a = g (f a) := rfl theorem unique_of_extensional [is_extensional β s] : well_founded r → subsingleton (r ≼i s) | ⟨h⟩ := ⟨λ f g, begin suffices : (f : α → β) = g, { cases f, cases g, congr, exact rel_embedding.coe_fn_injective this }, funext a, have := h a, induction this with a H IH, refine @is_extensional.ext _ s _ _ _ (λ x, ⟨λ h, _, λ h, _⟩), { rcases f.init_iff.1 h with ⟨y, rfl, h'⟩, rw IH _ h', exact (g : r ↪r s).map_rel_iff.2 h' }, { rcases g.init_iff.1 h with ⟨y, rfl, h'⟩, rw ← IH _ h', exact (f : r ↪r s).map_rel_iff.2 h' } end⟩ instance [is_well_order β s] : subsingleton (r ≼i s) := ⟨λ a, @subsingleton.elim _ (unique_of_extensional (@rel_embedding.well_founded _ _ r s a is_well_order.wf)) a⟩ protected theorem eq [is_well_order β s] (f g : r ≼i s) (a) : f a = g a := by rw subsingleton.elim f g theorem antisymm.aux [is_well_order α r] (f : r ≼i s) (g : s ≼i r) : left_inverse g f := initial_seg.eq (f.trans g) (initial_seg.refl _) /-- If we have order embeddings between `α` and `β` whose images are initial segments, and `β` is a well-order then `α` and `β` are order-isomorphic. -/ def antisymm [is_well_order β s] (f : r ≼i s) (g : s ≼i r) : r ≃r s := by haveI := f.to_rel_embedding.is_well_order; exact ⟨⟨f, g, antisymm.aux f g, antisymm.aux g f⟩, f.map_rel_iff'⟩ @[simp] theorem antisymm_to_fun [is_well_order β s] (f : r ≼i s) (g : s ≼i r) : (antisymm f g : α → β) = f := rfl @[simp] theorem antisymm_symm [is_well_order α r] [is_well_order β s] (f : r ≼i s) (g : s ≼i r) : (antisymm f g).symm = antisymm g f := rel_iso.coe_fn_injective rfl theorem eq_or_principal [is_well_order β s] (f : r ≼i s) : surjective f ∨ ∃ b, ∀ x, s x b ↔ ∃ y, f y = x := or_iff_not_imp_right.2 $ λ h b, acc.rec_on (is_well_order.wf.apply b : acc s b) $ λ x H IH, not_forall_not.1 $ λ hn, h ⟨x, λ y, ⟨(IH _), λ ⟨a, e⟩, by rw ← e; exact (trichotomous _ _).resolve_right (not_or (hn a) (λ hl, not_exists.2 hn (f.init' hl)))⟩⟩ /-- Restrict the codomain of an initial segment -/ def cod_restrict (p : set β) (f : r ≼i s) (H : ∀ a, f a ∈ p) : r ≼i subrel s p := ⟨rel_embedding.cod_restrict p f H, λ a ⟨b, m⟩ (h : s b (f a)), let ⟨a', e⟩ := f.init' h in ⟨a', by clear _let_match; subst e; refl⟩⟩ @[simp] theorem cod_restrict_apply (p) (f : r ≼i s) (H a) : cod_restrict p f H a = ⟨f a, H a⟩ := rfl /-- Initial segment embedding of an order `r` into the disjoint union of `r` and `s`. -/ def le_add (r : α → α → Prop) (s : β → β → Prop) : r ≼i sum.lex r s := ⟨⟨⟨sum.inl, λ _ _, sum.inl.inj⟩, λ a b, sum.lex_inl_inl⟩, λ a b, by cases b; [exact λ _, ⟨_, rfl⟩, exact false.elim ∘ sum.lex_inr_inl]⟩ @[simp] theorem le_add_apply (r : α → α → Prop) (s : β → β → Prop) (a) : le_add r s a = sum.inl a := rfl end initial_seg /-! ### Principal segments Order embeddings whose range is a principal segment of `s` (i.e., an interval of the form `(-∞, top)` for some element `top` of `β`). The type of these embeddings from `r` to `s` is called `principal_seg r s`, and denoted by `r ≺i s`. Principal segments are in particular initial segments. -/ /-- If `r` is a relation on `α` and `s` in a relation on `β`, then `f : r ≺i s` is an order embedding whose range is an open interval `(-∞, top)` for some element `top` of `β`. Such order embeddings are called principal segments -/ @[nolint has_inhabited_instance] structure principal_seg {α β : Type*} (r : α → α → Prop) (s : β → β → Prop) extends r ↪r s := (top : β) (down : ∀ b, s b top ↔ ∃ a, to_rel_embedding a = b) local infix ` ≺i `:25 := principal_seg namespace principal_seg instance : has_coe (r ≺i s) (r ↪r s) := ⟨principal_seg.to_rel_embedding⟩ instance : has_coe_to_fun (r ≺i s) (λ _, α → β) := ⟨λ f, f⟩ @[simp] theorem coe_fn_mk (f : r ↪r s) (t o) : (@principal_seg.mk _ _ r s f t o : α → β) = f := rfl @[simp] theorem coe_fn_to_rel_embedding (f : r ≺i s) : (f.to_rel_embedding : α → β) = f := rfl @[simp] theorem coe_coe_fn (f : r ≺i s) : ((f : r ↪r s) : α → β) = f := rfl theorem down' (f : r ≺i s) {b : β} : s b f.top ↔ ∃ a, f a = b := f.down _ theorem lt_top (f : r ≺i s) (a : α) : s (f a) f.top := f.down'.2 ⟨_, rfl⟩ theorem init [is_trans β s] (f : r ≺i s) {a : α} {b : β} (h : s b (f a)) : ∃ a', f a' = b := f.down'.1 $ trans h $ f.lt_top _ /-- A principal segment is in particular an initial segment. -/ instance has_coe_initial_seg [is_trans β s] : has_coe (r ≺i s) (r ≼i s) := ⟨λ f, ⟨f.to_rel_embedding, λ a b, f.init⟩⟩ theorem coe_coe_fn' [is_trans β s] (f : r ≺i s) : ((f : r ≼i s) : α → β) = f := rfl theorem init_iff [is_trans β s] (f : r ≺i s) {a : α} {b : β} : s b (f a) ↔ ∃ a', f a' = b ∧ r a' a := @initial_seg.init_iff α β r s f a b theorem irrefl (r : α → α → Prop) [is_well_order α r] (f : r ≺i r) : false := begin have := f.lt_top f.top, rw [show f f.top = f.top, from initial_seg.eq ↑f (initial_seg.refl r) f.top] at this, exact irrefl _ this end /-- Composition of a principal segment with an initial segment, as a principal segment -/ def lt_le (f : r ≺i s) (g : s ≼i t) : r ≺i t := ⟨@rel_embedding.trans _ _ _ r s t f g, g f.top, λ a, by simp only [g.init_iff, f.down', exists_and_distrib_left.symm, exists_swap, rel_embedding.trans_apply, exists_eq_right']; refl⟩ @[simp] theorem lt_le_apply (f : r ≺i s) (g : s ≼i t) (a : α) : (f.lt_le g) a = g (f a) := rel_embedding.trans_apply _ _ _ @[simp] theorem lt_le_top (f : r ≺i s) (g : s ≼i t) : (f.lt_le g).top = g f.top := rfl /-- Composition of two principal segments as a principal segment -/ @[trans] protected def trans [is_trans γ t] (f : r ≺i s) (g : s ≺i t) : r ≺i t := lt_le f g @[simp] theorem trans_apply [is_trans γ t] (f : r ≺i s) (g : s ≺i t) (a : α) : (f.trans g) a = g (f a) := lt_le_apply _ _ _ @[simp] theorem trans_top [is_trans γ t] (f : r ≺i s) (g : s ≺i t) : (f.trans g).top = g f.top := rfl /-- Composition of an order isomorphism with a principal segment, as a principal segment -/ def equiv_lt (f : r ≃r s) (g : s ≺i t) : r ≺i t := ⟨@rel_embedding.trans _ _ _ r s t f g, g.top, λ c, suffices (∃ (a : β), g a = c) ↔ ∃ (a : α), g (f a) = c, by simpa [g.down], ⟨λ ⟨b, h⟩, ⟨f.symm b, by simp only [h, rel_iso.apply_symm_apply, rel_iso.coe_coe_fn]⟩, λ ⟨a, h⟩, ⟨f a, h⟩⟩⟩ /-- Composition of a principal segment with an order isomorphism, as a principal segment -/ def lt_equiv {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} (f : principal_seg r s) (g : s ≃r t) : principal_seg r t := ⟨@rel_embedding.trans _ _ _ r s t f g, g f.top, begin intro x, rw [← g.apply_symm_apply x, g.map_rel_iff, f.down', exists_congr], intro y, exact ⟨congr_arg g, λ h, g.to_equiv.bijective.1 h⟩ end⟩ @[simp] theorem equiv_lt_apply (f : r ≃r s) (g : s ≺i t) (a : α) : (equiv_lt f g) a = g (f a) := rel_embedding.trans_apply _ _ _ @[simp] theorem equiv_lt_top (f : r ≃r s) (g : s ≺i t) : (equiv_lt f g).top = g.top := rfl /-- Given a well order `s`, there is a most one principal segment embedding of `r` into `s`. -/ instance [is_well_order β s] : subsingleton (r ≺i s) := ⟨λ f g, begin have ef : (f : α → β) = g, { show ((f : r ≼i s) : α → β) = g, rw @subsingleton.elim _ _ (f : r ≼i s) g, refl }, have et : f.top = g.top, { refine @is_extensional.ext _ s _ _ _ (λ x, _), simp only [f.down, g.down, ef, coe_fn_to_rel_embedding] }, cases f, cases g, have := rel_embedding.coe_fn_injective ef; congr' end⟩ theorem top_eq [is_well_order γ t] (e : r ≃r s) (f : r ≺i t) (g : s ≺i t) : f.top = g.top := by rw subsingleton.elim f (principal_seg.equiv_lt e g); refl lemma top_lt_top {r : α → α → Prop} {s : β → β → Prop} {t : γ → γ → Prop} [is_well_order γ t] (f : principal_seg r s) (g : principal_seg s t) (h : principal_seg r t) : t h.top g.top := by { rw [subsingleton.elim h (f.trans g)], apply principal_seg.lt_top } /-- Any element of a well order yields a principal segment -/ def of_element {α : Type*} (r : α → α → Prop) (a : α) : subrel r {b | r b a} ≺i r := ⟨subrel.rel_embedding _ _, a, λ b, ⟨λ h, ⟨⟨_, h⟩, rfl⟩, λ ⟨⟨_, h⟩, rfl⟩, h⟩⟩ @[simp] theorem of_element_apply {α : Type*} (r : α → α → Prop) (a : α) (b) : of_element r a b = b.1 := rfl @[simp] theorem of_element_top {α : Type*} (r : α → α → Prop) (a : α) : (of_element r a).top = a := rfl /-- Restrict the codomain of a principal segment -/ def cod_restrict (p : set β) (f : r ≺i s) (H : ∀ a, f a ∈ p) (H₂ : f.top ∈ p) : r ≺i subrel s p := ⟨rel_embedding.cod_restrict p f H, ⟨f.top, H₂⟩, λ ⟨b, h⟩, f.down'.trans $ exists_congr $ λ a, show (⟨f a, H a⟩ : p).1 = _ ↔ _, from ⟨subtype.eq, congr_arg _⟩⟩ @[simp] theorem cod_restrict_apply (p) (f : r ≺i s) (H H₂ a) : cod_restrict p f H H₂ a = ⟨f a, H a⟩ := rfl @[simp] theorem cod_restrict_top (p) (f : r ≺i s) (H H₂) : (cod_restrict p f H H₂).top = ⟨f.top, H₂⟩ := rfl end principal_seg /-! ### Properties of initial and principal segments -/ /-- To an initial segment taking values in a well order, one can associate either a principal segment (if the range is not everything, hence one can take as top the minimum of the complement of the range) or an order isomorphism (if the range is everything). -/ def initial_seg.lt_or_eq [is_well_order β s] (f : r ≼i s) : (r ≺i s) ⊕ (r ≃r s) := if h : surjective f then sum.inr (rel_iso.of_surjective f h) else have h' : _, from (initial_seg.eq_or_principal f).resolve_left h, sum.inl ⟨f, classical.some h', classical.some_spec h'⟩ theorem initial_seg.lt_or_eq_apply_left [is_well_order β s] (f : r ≼i s) (g : r ≺i s) (a : α) : g a = f a := @initial_seg.eq α β r s _ g f a theorem initial_seg.lt_or_eq_apply_right [is_well_order β s] (f : r ≼i s) (g : r ≃r s) (a : α) : g a = f a := initial_seg.eq (initial_seg.of_iso g) f a /-- Composition of an initial segment taking values in a well order and a principal segment. -/ def initial_seg.le_lt [is_well_order β s] [is_trans γ t] (f : r ≼i s) (g : s ≺i t) : r ≺i t := match f.lt_or_eq with | sum.inl f' := f'.trans g | sum.inr f' := principal_seg.equiv_lt f' g end @[simp] theorem initial_seg.le_lt_apply [is_well_order β s] [is_trans γ t] (f : r ≼i s) (g : s ≺i t) (a : α) : (f.le_lt g) a = g (f a) := begin delta initial_seg.le_lt, cases h : f.lt_or_eq with f' f', { simp only [principal_seg.trans_apply, f.lt_or_eq_apply_left] }, { simp only [principal_seg.equiv_lt_apply, f.lt_or_eq_apply_right] } end namespace rel_embedding /-- Given an order embedding into a well order, collapse the order embedding by filling the gaps, to obtain an initial segment. Here, we construct the collapsed order embedding pointwise, but the proof of the fact that it is an initial segment will be given in `collapse`. -/ def collapse_F [is_well_order β s] (f : r ↪r s) : Π a, {b // ¬ s (f a) b} := (rel_embedding.well_founded f $ is_well_order.wf).fix $ λ a IH, begin let S := {b | ∀ a h, s (IH a h).1 b}, have : f a ∈ S, from λ a' h, ((trichotomous _ _) .resolve_left $ λ h', (IH a' h).2 $ trans (f.map_rel_iff.2 h) h') .resolve_left $ λ h', (IH a' h).2 $ h' ▸ f.map_rel_iff.2 h, exact ⟨is_well_order.wf.min S ⟨_, this⟩, is_well_order.wf.not_lt_min _ _ this⟩ end theorem collapse_F.lt [is_well_order β s] (f : r ↪r s) {a : α} : ∀ {a'}, r a' a → s (collapse_F f a').1 (collapse_F f a).1 := show (collapse_F f a).1 ∈ {b | ∀ a' (h : r a' a), s (collapse_F f a').1 b}, begin unfold collapse_F, rw well_founded.fix_eq, apply well_founded.min_mem _ _ end theorem collapse_F.not_lt [is_well_order β s] (f : r ↪r s) (a : α) {b} (h : ∀ a' (h : r a' a), s (collapse_F f a').1 b) : ¬ s b (collapse_F f a).1 := begin unfold collapse_F, rw well_founded.fix_eq, exact well_founded.not_lt_min _ _ _ (show b ∈ {b | ∀ a' (h : r a' a), s (collapse_F f a').1 b}, from h) end /-- Construct an initial segment from an order embedding into a well order, by collapsing it to fill the gaps. -/ def collapse [is_well_order β s] (f : r ↪r s) : r ≼i s := by haveI := rel_embedding.is_well_order f; exact ⟨rel_embedding.of_monotone (λ a, (collapse_F f a).1) (λ a b, collapse_F.lt f), λ a b, acc.rec_on (is_well_order.wf.apply b : acc s b) (λ b H IH a h, begin let S := {a | ¬ s (collapse_F f a).1 b}, have : S.nonempty := ⟨_, asymm h⟩, existsi (is_well_order.wf : well_founded r).min S this, refine ((@trichotomous _ s _ _ _).resolve_left _).resolve_right _, { exact (is_well_order.wf : well_founded r).min_mem S this }, { refine collapse_F.not_lt f _ (λ a' h', _), by_contradiction hn, exact is_well_order.wf.not_lt_min S this hn h' } end) a⟩ theorem collapse_apply [is_well_order β s] (f : r ↪r s) (a) : collapse f a = (collapse_F f a).1 := rfl end rel_embedding /-! ### Well order on an arbitrary type -/ section well_ordering_thm parameter {σ : Type u} open function theorem nonempty_embedding_to_cardinal : nonempty (σ ↪ cardinal.{u}) := embedding.total.resolve_left $ λ ⟨⟨f, hf⟩⟩, let g : σ → cardinal.{u} := inv_fun f in let ⟨x, (hx : g x = 2 ^ sum g)⟩ := inv_fun_surjective hf (2 ^ sum g) in have g x ≤ sum g, from le_sum.{u u} g x, not_le_of_gt (by rw hx; exact cantor _) this /-- An embedding of any type to the set of cardinals. -/ def embedding_to_cardinal : σ ↪ cardinal.{u} := classical.choice nonempty_embedding_to_cardinal /-- Any type can be endowed with a well order, obtained by pulling back the well order over cardinals by some embedding. -/ def well_ordering_rel : σ → σ → Prop := embedding_to_cardinal ⁻¹'o (<) instance well_ordering_rel.is_well_order : is_well_order σ well_ordering_rel := (rel_embedding.preimage _ _).is_well_order end well_ordering_thm /-! ### Definition of ordinals -/ /-- Bundled structure registering a well order on a type. Ordinals will be defined as a quotient of this type. -/ structure Well_order : Type (u+1) := (α : Type u) (r : α → α → Prop) (wo : is_well_order α r) attribute [instance] Well_order.wo namespace Well_order instance : inhabited Well_order := ⟨⟨pempty, _, empty_relation.is_well_order⟩⟩ end Well_order /-- Equivalence relation on well orders on arbitrary types in universe `u`, given by order isomorphism. -/ instance ordinal.is_equivalent : setoid Well_order := { r := λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≃r s), iseqv := ⟨λ⟨α, r, _⟩, ⟨rel_iso.refl _⟩, λ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨e⟩, ⟨e.symm⟩, λ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨e₁⟩ ⟨e₂⟩, ⟨e₁.trans e₂⟩⟩ } /-- `ordinal.{u}` is the type of well orders in `Type u`, up to order isomorphism. -/ def ordinal : Type (u + 1) := quotient ordinal.is_equivalent namespace ordinal /-- The order type of a well order is an ordinal. -/ def type (r : α → α → Prop) [wo : is_well_order α r] : ordinal := ⟦⟨α, r, wo⟩⟧ /-- The order type of an element inside a well order. For the embedding as a principal segment, see `typein.principal_seg`. -/ def typein (r : α → α → Prop) [is_well_order α r] (a : α) : ordinal := type (subrel r {b | r b a}) theorem type_def (r : α → α → Prop) [wo : is_well_order α r] : @eq ordinal ⟦⟨α, r, wo⟩⟧ (type r) := rfl @[simp] theorem type_def' (r : α → α → Prop) [is_well_order α r] {wo} : @eq ordinal ⟦⟨α, r, wo⟩⟧ (type r) := rfl theorem type_eq {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r = type s ↔ nonempty (r ≃r s) := quotient.eq @[simp] lemma type_out (o : ordinal) : type o.out.r = o := by { refine eq.trans _ (by rw [←quotient.out_eq o]), cases quotient.out o, refl } @[elab_as_eliminator] theorem induction_on {C : ordinal → Prop} (o : ordinal) (H : ∀ α r [is_well_order α r], by exactI C (type r)) : C o := quot.induction_on o $ λ ⟨α, r, wo⟩, @H α r wo /-! ### The order on ordinals -/ /-- Ordinal less-equal is defined such that well orders `r` and `s` satisfy `type r ≤ type s` if there exists a function embedding `r` as an initial segment of `s`. -/ protected def le (a b : ordinal) : Prop := quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≼i s)) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, propext ⟨ λ ⟨h⟩, ⟨(initial_seg.of_iso f.symm).trans $ h.trans (initial_seg.of_iso g)⟩, λ ⟨h⟩, ⟨(initial_seg.of_iso f).trans $ h.trans (initial_seg.of_iso g.symm)⟩⟩ instance : has_le ordinal := ⟨ordinal.le⟩ theorem type_le {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r ≤ type s ↔ nonempty (r ≼i s) := iff.rfl theorem type_le' {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r ≤ type s ↔ nonempty (r ↪r s) := ⟨λ ⟨f⟩, ⟨f⟩, λ ⟨f⟩, ⟨f.collapse⟩⟩ /-- Ordinal less-than is defined such that well orders `r` and `s` satisfy `type r < type s` if there exists a function embedding `r` as a principal segment of `s`. -/ def lt (a b : ordinal) : Prop := quotient.lift_on₂ a b (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, nonempty (r ≺i s)) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, by exactI propext ⟨ λ ⟨h⟩, ⟨principal_seg.equiv_lt f.symm $ h.lt_le (initial_seg.of_iso g)⟩, λ ⟨h⟩, ⟨principal_seg.equiv_lt f $ h.lt_le (initial_seg.of_iso g.symm)⟩⟩ instance : has_lt ordinal := ⟨ordinal.lt⟩ @[simp] theorem type_lt {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] : type r < type s ↔ nonempty (r ≺i s) := iff.rfl instance : partial_order ordinal := { le := (≤), lt := (<), le_refl := quot.ind $ by exact λ ⟨α, r, wo⟩, ⟨initial_seg.refl _⟩, le_trans := λ a b c, quotient.induction_on₃ a b c $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨f⟩ ⟨g⟩, ⟨f.trans g⟩, lt_iff_le_not_le := λ a b, quotient.induction_on₂ a b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩, by exactI ⟨λ ⟨f⟩, ⟨⟨f⟩, λ ⟨g⟩, (f.lt_le g).irrefl _⟩, λ ⟨⟨f⟩, h⟩, sum.rec_on f.lt_or_eq (λ g, ⟨g⟩) (λ g, (h ⟨initial_seg.of_iso g.symm⟩).elim)⟩, le_antisymm := λ x b, show x ≤ b → b ≤ x → x = b, from quotient.induction_on₂ x b $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨h₁⟩ ⟨h₂⟩, by exactI quot.sound ⟨initial_seg.antisymm h₁ h₂⟩ } /-- Given two ordinals `α ≤ β`, then `initial_seg_out α β` is the initial segment embedding of `α` to `β`, as map from a model type for `α` to a model type for `β`. -/ def initial_seg_out {α β : ordinal} (h : α ≤ β) : initial_seg α.out.r β.out.r := begin rw [←quotient.out_eq α, ←quotient.out_eq β] at h, revert h, cases quotient.out α, cases quotient.out β, exact classical.choice end /-- Given two ordinals `α < β`, then `principal_seg_out α β` is the principal segment embedding of `α` to `β`, as map from a model type for `α` to a model type for `β`. -/ def principal_seg_out {α β : ordinal} (h : α < β) : principal_seg α.out.r β.out.r := begin rw [←quotient.out_eq α, ←quotient.out_eq β] at h, revert h, cases quotient.out α, cases quotient.out β, exact classical.choice end /-- Given two ordinals `α = β`, then `rel_iso_out α β` is the order isomorphism between two model types for `α` and `β`. -/ def rel_iso_out {α β : ordinal} (h : α = β) : α.out.r ≃r β.out.r := begin rw [←quotient.out_eq α, ←quotient.out_eq β] at h, revert h, cases quotient.out α, cases quotient.out β, exact classical.choice ∘ quotient.exact end theorem typein_lt_type (r : α → α → Prop) [is_well_order α r] (a : α) : typein r a < type r := ⟨principal_seg.of_element _ _⟩ @[simp] theorem typein_top {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≺i s) : typein s f.top = type r := eq.symm $ quot.sound ⟨rel_iso.of_surjective (rel_embedding.cod_restrict _ f f.lt_top) (λ ⟨a, h⟩, by rcases f.down'.1 h with ⟨b, rfl⟩; exact ⟨b, rfl⟩)⟩ @[simp] theorem typein_apply {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≼i s) (a : α) : ordinal.typein s (f a) = ordinal.typein r a := eq.symm $ quotient.sound ⟨rel_iso.of_surjective (rel_embedding.cod_restrict _ ((subrel.rel_embedding _ _).trans f) (λ ⟨x, h⟩, by rw [rel_embedding.trans_apply]; exact f.to_rel_embedding.map_rel_iff.2 h)) (λ ⟨y, h⟩, by rcases f.init' h with ⟨a, rfl⟩; exact ⟨⟨a, f.to_rel_embedding.map_rel_iff.1 h⟩, subtype.eq $ rel_embedding.trans_apply _ _ _⟩)⟩ @[simp] theorem typein_lt_typein (r : α → α → Prop) [is_well_order α r] {a b : α} : typein r a < typein r b ↔ r a b := ⟨λ ⟨f⟩, begin have : f.top.1 = a, { let f' := principal_seg.of_element r a, let g' := f.trans (principal_seg.of_element r b), have : g'.top = f'.top, {rw subsingleton.elim f' g'}, exact this }, rw ← this, exact f.top.2 end, λ h, ⟨principal_seg.cod_restrict _ (principal_seg.of_element r a) (λ x, @trans _ r _ _ _ _ x.2 h) h⟩⟩ theorem typein_surj (r : α → α → Prop) [is_well_order α r] {o} (h : o < type r) : ∃ a, typein r a = o := induction_on o (λ β s _ ⟨f⟩, by exactI ⟨f.top, typein_top _⟩) h lemma typein_injective (r : α → α → Prop) [is_well_order α r] : injective (typein r) := injective_of_increasing r (<) (typein r) (λ x y, (typein_lt_typein r).2) theorem typein_inj (r : α → α → Prop) [is_well_order α r] {a b} : typein r a = typein r b ↔ a = b := injective.eq_iff (typein_injective r) /-! ### Enumerating elements in a well-order with ordinals. -/ /-- `enum r o h` is the `o`-th element of `α` ordered by `r`. That is, `enum` maps an initial segment of the ordinals, those less than the order type of `r`, to the elements of `α`. -/ def enum (r : α → α → Prop) [is_well_order α r] (o) : o < type r → α := quot.rec_on o (λ ⟨β, s, _⟩ h, (classical.choice h).top) $ λ ⟨β, s, _⟩ ⟨γ, t, _⟩ ⟨h⟩, begin resetI, refine funext (λ (H₂ : type t < type r), _), have H₁ : type s < type r, {rwa type_eq.2 ⟨h⟩}, have : ∀ {o e} (H : o < type r), @@eq.rec (λ (o : ordinal), o < type r → α) (λ (h : type s < type r), (classical.choice h).top) e H = (classical.choice H₁).top, {intros, subst e}, exact (this H₂).trans (principal_seg.top_eq h (classical.choice H₁) (classical.choice H₂)) end theorem enum_type {α β} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : s ≺i r) {h : type s < type r} : enum r (type s) h = f.top := principal_seg.top_eq (rel_iso.refl _) _ _ @[simp] theorem enum_typein (r : α → α → Prop) [is_well_order α r] (a : α) {h : typein r a < type r} : enum r (typein r a) h = a := enum_type (principal_seg.of_element r a) @[simp] theorem typein_enum (r : α → α → Prop) [is_well_order α r] {o} (h : o < type r) : typein r (enum r o h) = o := let ⟨a, e⟩ := typein_surj r h in by clear _let_match; subst e; rw enum_typein /-- A well order `r` is order isomorphic to the set of ordinals strictly smaller than the ordinal version of `r`. -/ def typein_iso (r : α → α → Prop) [is_well_order α r] : r ≃r subrel (<) (< type r) := ⟨⟨λ x, ⟨typein r x, typein_lt_type r x⟩, λ x, enum r x.1 x.2, λ y, enum_typein r y, λ ⟨y, hy⟩, subtype.eq (typein_enum r hy)⟩, λ a b, (typein_lt_typein r)⟩ theorem enum_lt {r : α → α → Prop} [is_well_order α r] {o₁ o₂ : ordinal} (h₁ : o₁ < type r) (h₂ : o₂ < type r) : r (enum r o₁ h₁) (enum r o₂ h₂) ↔ o₁ < o₂ := by rw [← typein_lt_typein r, typein_enum, typein_enum] lemma rel_iso_enum' {α β : Type u} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≃r s) (o : ordinal) : ∀(hr : o < type r) (hs : o < type s), f (enum r o hr) = enum s o hs := begin refine induction_on o _, rintros γ t wo ⟨g⟩ ⟨h⟩, resetI, rw [enum_type g, enum_type (principal_seg.lt_equiv g f)], refl end lemma rel_iso_enum {α β : Type u} {r : α → α → Prop} {s : β → β → Prop} [is_well_order α r] [is_well_order β s] (f : r ≃r s) (o : ordinal) (hr : o < type r) : f (enum r o hr) = enum s o (by {convert hr using 1, apply quotient.sound, exact ⟨f.symm⟩ }) := rel_iso_enum' _ _ _ _ theorem wf : @well_founded ordinal (<) := ⟨λ a, induction_on a $ λ α r wo, by exactI suffices ∀ a, acc (<) (typein r a), from ⟨_, λ o h, let ⟨a, e⟩ := typein_surj r h in e ▸ this a⟩, λ a, acc.rec_on (wo.wf.apply a) $ λ x H IH, ⟨_, λ o h, begin rcases typein_surj r (lt_trans h (typein_lt_type r _)) with ⟨b, rfl⟩, exact IH _ ((typein_lt_typein r).1 h) end⟩⟩ instance : has_well_founded ordinal := ⟨(<), wf⟩ /-- Reformulation of well founded induction on ordinals as a lemma that works with the `induction` tactic, as in `induction i using ordinal.induction with i IH`. -/ lemma induction {p : ordinal.{u} → Prop} (i : ordinal.{u}) (h : ∀ j, (∀ k, k < j → p k) → p j) : p i := ordinal.wf.induction i h /-- Principal segment version of the `typein` function, embedding a well order into ordinals as a principal segment. -/ def typein.principal_seg {α : Type u} (r : α → α → Prop) [is_well_order α r] : @principal_seg α ordinal.{u} r (<) := ⟨rel_embedding.of_monotone (typein r) (λ a b, (typein_lt_typein r).2), type r, λ b, ⟨λ h, ⟨enum r _ h, typein_enum r h⟩, λ ⟨a, e⟩, e ▸ typein_lt_type _ _⟩⟩ @[simp] theorem typein.principal_seg_coe (r : α → α → Prop) [is_well_order α r] : (typein.principal_seg r : α → ordinal) = typein r := rfl /-! ### Cardinality of ordinals -/ /-- The cardinal of an ordinal is the cardinal of any set with that order type. -/ def card (o : ordinal) : cardinal := quot.lift_on o (λ ⟨α, r, _⟩, #α) $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨e⟩, quotient.sound ⟨e.to_equiv⟩ @[simp] theorem card_type (r : α → α → Prop) [is_well_order α r] : card (type r) = #α := rfl lemma card_typein {r : α → α → Prop} [wo : is_well_order α r] (x : α) : #{y // r y x} = (typein r x).card := rfl theorem card_le_card {o₁ o₂ : ordinal} : o₁ ≤ o₂ → card o₁ ≤ card o₂ := induction_on o₁ $ λ α r _, induction_on o₂ $ λ β s _ ⟨⟨⟨f, _⟩, _⟩⟩, ⟨f⟩ instance : has_zero ordinal := ⟨⟦⟨pempty, empty_relation, by apply_instance⟩⟧⟩ instance : inhabited ordinal := ⟨0⟩ theorem zero_eq_type_empty : 0 = @type empty empty_relation _ := quotient.sound ⟨⟨empty_equiv_pempty.symm, λ _ _, iff.rfl⟩⟩ @[simp] theorem card_zero : card 0 = 0 := rfl protected theorem zero_le (o : ordinal) : 0 ≤ o := induction_on o $ λ α r _, ⟨⟨⟨embedding.of_is_empty, is_empty_elim⟩, is_empty_elim⟩⟩ @[simp] protected theorem le_zero {o : ordinal} : o ≤ 0 ↔ o = 0 := by simp only [le_antisymm_iff, ordinal.zero_le, and_true] protected theorem pos_iff_ne_zero {o : ordinal} : 0 < o ↔ o ≠ 0 := by simp only [lt_iff_le_and_ne, ordinal.zero_le, true_and, ne.def, eq_comm] instance : has_one ordinal := ⟨⟦⟨punit, empty_relation, by apply_instance⟩⟧⟩ theorem one_eq_type_unit : 1 = @type unit empty_relation _ := quotient.sound ⟨⟨punit_equiv_punit, λ _ _, iff.rfl⟩⟩ @[simp] theorem card_one : card 1 = 1 := rfl /-! ### Lifting ordinals to a higher universe -/ /-- The universe lift operation for ordinals, which embeds `ordinal.{u}` as a proper initial segment of `ordinal.{v}` for `v > u`. For the initial segment version, see `lift.initial_seg`. -/ def lift (o : ordinal.{v}) : ordinal.{max v u} := quotient.lift_on o (λ ⟨α, r, wo⟩, @type _ _ (@rel_embedding.is_well_order _ _ (@equiv.ulift.{u} α ⁻¹'o r) r (rel_iso.preimage equiv.ulift.{u} r) wo)) $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨f⟩, quot.sound ⟨(rel_iso.preimage equiv.ulift r).trans $ f.trans (rel_iso.preimage equiv.ulift s).symm⟩ theorem lift_type {α} (r : α → α → Prop) [is_well_order α r] : ∃ wo', lift (type r) = @type _ (@equiv.ulift.{v} α ⁻¹'o r) wo' := ⟨_, rfl⟩ theorem lift_umax : lift.{(max u v) u} = lift.{v u} := funext $ λ a, induction_on a $ λ α r _, quotient.sound ⟨(rel_iso.preimage equiv.ulift r).trans (rel_iso.preimage equiv.ulift r).symm⟩ theorem lift_id' (a : ordinal) : lift a = a := induction_on a $ λ α r _, quotient.sound ⟨rel_iso.preimage equiv.ulift r⟩ @[simp] theorem lift_id : ∀ a, lift.{u u} a = a := lift_id'.{u u} @[simp] theorem lift_lift (a : ordinal) : lift.{w} (lift.{v} a) = lift.{(max v w)} a := induction_on a $ λ α r _, quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans $ (rel_iso.preimage equiv.ulift _).trans (rel_iso.preimage equiv.ulift _).symm⟩ theorem lift_type_le {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] : lift.{(max v w)} (type r) ≤ lift.{(max u w)} (type s) ↔ nonempty (r ≼i s) := ⟨λ ⟨f⟩, ⟨(initial_seg.of_iso (rel_iso.preimage equiv.ulift r).symm).trans $ f.trans (initial_seg.of_iso (rel_iso.preimage equiv.ulift s))⟩, λ ⟨f⟩, ⟨(initial_seg.of_iso (rel_iso.preimage equiv.ulift r)).trans $ f.trans (initial_seg.of_iso (rel_iso.preimage equiv.ulift s).symm)⟩⟩ theorem lift_type_eq {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] : lift.{(max v w)} (type r) = lift.{(max u w)} (type s) ↔ nonempty (r ≃r s) := quotient.eq.trans ⟨λ ⟨f⟩, ⟨(rel_iso.preimage equiv.ulift r).symm.trans $ f.trans (rel_iso.preimage equiv.ulift s)⟩, λ ⟨f⟩, ⟨(rel_iso.preimage equiv.ulift r).trans $ f.trans (rel_iso.preimage equiv.ulift s).symm⟩⟩ theorem lift_type_lt {α : Type u} {β : Type v} {r s} [is_well_order α r] [is_well_order β s] : lift.{(max v w)} (type r) < lift.{(max u w)} (type s) ↔ nonempty (r ≺i s) := by haveI := @rel_embedding.is_well_order _ _ (@equiv.ulift.{(max v w)} α ⁻¹'o r) r (rel_iso.preimage equiv.ulift.{(max v w)} r) _; haveI := @rel_embedding.is_well_order _ _ (@equiv.ulift.{(max u w)} β ⁻¹'o s) s (rel_iso.preimage equiv.ulift.{(max u w)} s) _; exact ⟨λ ⟨f⟩, ⟨(f.equiv_lt (rel_iso.preimage equiv.ulift r).symm).lt_le (initial_seg.of_iso (rel_iso.preimage equiv.ulift s))⟩, λ ⟨f⟩, ⟨(f.equiv_lt (rel_iso.preimage equiv.ulift r)).lt_le (initial_seg.of_iso (rel_iso.preimage equiv.ulift s).symm)⟩⟩ @[simp] theorem lift_le {a b : ordinal} : lift.{u v} a ≤ lift b ↔ a ≤ b := induction_on a $ λ α r _, induction_on b $ λ β s _, by rw ← lift_umax; exactI lift_type_le @[simp] theorem lift_inj {a b : ordinal} : lift a = lift b ↔ a = b := by simp only [le_antisymm_iff, lift_le] @[simp] theorem lift_lt {a b : ordinal} : lift a < lift b ↔ a < b := by simp only [lt_iff_le_not_le, lift_le] @[simp] theorem lift_zero : lift 0 = 0 := quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans ⟨pempty_equiv_pempty, λ a b, iff.rfl⟩⟩ theorem zero_eq_lift_type_empty : 0 = lift.{u} (@type empty empty_relation _) := by rw [← zero_eq_type_empty, lift_zero] @[simp] theorem lift_one : lift 1 = 1 := quotient.sound ⟨(rel_iso.preimage equiv.ulift _).trans ⟨punit_equiv_punit, λ a b, iff.rfl⟩⟩ theorem one_eq_lift_type_unit : 1 = lift.{u} (@type unit empty_relation _) := by rw [← one_eq_type_unit, lift_one] @[simp] theorem lift_card (a) : (card a).lift = card (lift a) := induction_on a $ λ α r _, rfl theorem lift_down' {a : cardinal.{u}} {b : ordinal.{max u v}} (h : card b ≤ a.lift) : ∃ a', lift a' = b := let ⟨c, e⟩ := cardinal.lift_down h in cardinal.induction_on c (λ α, induction_on b $ λ β s _ e', begin resetI, rw [card_type, ← cardinal.lift_id'.{(max u v) u} (#β), ← cardinal.lift_umax.{u v}, lift_mk_eq.{u (max u v) (max u v)}] at e', cases e' with f, have g := rel_iso.preimage f s, haveI := (g : ⇑f ⁻¹'o s ↪r s).is_well_order, have := lift_type_eq.{u (max u v) (max u v)}.2 ⟨g⟩, rw [lift_id, lift_umax.{u v}] at this, exact ⟨_, this⟩ end) e theorem lift_down {a : ordinal.{u}} {b : ordinal.{max u v}} (h : b ≤ lift a) : ∃ a', lift a' = b := @lift_down' (card a) _ (by rw lift_card; exact card_le_card h) theorem le_lift_iff {a : ordinal.{u}} {b : ordinal.{max u v}} : b ≤ lift a ↔ ∃ a', lift a' = b ∧ a' ≤ a := ⟨λ h, let ⟨a', e⟩ := lift_down h in ⟨a', e, lift_le.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_le.2 h⟩ theorem lt_lift_iff {a : ordinal.{u}} {b : ordinal.{max u v}} : b < lift a ↔ ∃ a', lift a' = b ∧ a' < a := ⟨λ h, let ⟨a', e⟩ := lift_down (le_of_lt h) in ⟨a', e, lift_lt.1 $ e.symm ▸ h⟩, λ ⟨a', e, h⟩, e ▸ lift_lt.2 h⟩ /-- Initial segment version of the lift operation on ordinals, embedding `ordinal.{u}` in `ordinal.{v}` as an initial segment when `u ≤ v`. -/ def lift.initial_seg : @initial_seg ordinal.{u} ordinal.{max u v} (<) (<) := ⟨⟨⟨lift.{v}, λ a b, lift_inj.1⟩, λ a b, lift_lt⟩, λ a b h, lift_down (le_of_lt h)⟩ @[simp] theorem lift.initial_seg_coe : (lift.initial_seg : ordinal → ordinal) = lift := rfl /-! ### The first infinite ordinal `omega` -/ /-- `ω` is the first infinite ordinal, defined as the order type of `ℕ`. -/ def omega : ordinal.{u} := lift $ @type ℕ (<) _ localized "notation `ω` := ordinal.omega.{0}" in ordinal theorem card_omega : card omega = cardinal.omega := rfl @[simp] theorem lift_omega : lift omega = omega := lift_lift _ /-! ### Definition and first properties of addition on ordinals In this paragraph, we introduce the addition on ordinals, and prove just enough properties to deduce that the order on ordinals is total (and therefore well-founded). Further properties of the addition, together with properties of the other operations, are proved in `ordinal_arithmetic.lean`. -/ /-- `o₁ + o₂` is the order on the disjoint union of `o₁` and `o₂` obtained by declaring that every element of `o₁` is smaller than every element of `o₂`. -/ instance : has_add ordinal.{u} := ⟨λo₁ o₂, quotient.lift_on₂ o₁ o₂ (λ ⟨α, r, wo⟩ ⟨β, s, wo'⟩, ⟦⟨α ⊕ β, sum.lex r s, by exactI sum.lex.is_well_order⟩⟧ : Well_order → Well_order → ordinal) $ λ ⟨α₁, r₁, o₁⟩ ⟨α₂, r₂, o₂⟩ ⟨β₁, s₁, p₁⟩ ⟨β₂, s₂, p₂⟩ ⟨f⟩ ⟨g⟩, quot.sound ⟨rel_iso.sum_lex_congr f g⟩⟩ @[simp] theorem card_add (o₁ o₂ : ordinal) : card (o₁ + o₂) = card o₁ + card o₂ := induction_on o₁ $ λ α r _, induction_on o₂ $ λ β s _, rfl @[simp] theorem card_nat (n : ℕ) : card.{u} n = n := by induction n; [refl, simp only [card_add, card_one, nat.cast_succ, *]] @[simp] theorem type_add {α β : Type u} (r : α → α → Prop) (s : β → β → Prop) [is_well_order α r] [is_well_order β s] : type r + type s = type (sum.lex r s) := rfl /-- The ordinal successor is the smallest ordinal larger than `o`. It is defined as `o + 1`. -/ def succ (o : ordinal) : ordinal := o + 1 theorem succ_eq_add_one (o) : succ o = o + 1 := rfl instance : add_monoid ordinal.{u} := { add := (+), zero := 0, zero_add := λ o, induction_on o $ λ α r _, eq.symm $ quotient.sound ⟨⟨(empty_sum pempty α).symm, λ a b, sum.lex_inr_inr⟩⟩, add_zero := λ o, induction_on o $ λ α r _, eq.symm $ quotient.sound ⟨⟨(sum_empty α pempty).symm, λ a b, sum.lex_inl_inl⟩⟩, add_assoc := λ o₁ o₂ o₃, quotient.induction_on₃ o₁ o₂ o₃ $ λ ⟨α, r, _⟩ ⟨β, s, _⟩ ⟨γ, t, _⟩, quot.sound ⟨⟨sum_assoc _ _ _, λ a b, begin rcases a with ⟨a|a⟩|a; rcases b with ⟨b|b⟩|b; simp only [sum_assoc_apply_in1, sum_assoc_apply_in2, sum_assoc_apply_in3, sum.lex_inl_inl, sum.lex_inr_inr, sum.lex.sep, sum.lex_inr_inl] end⟩⟩ } theorem add_le_add_left {a b : ordinal} : a ≤ b → ∀ c, c + a ≤ c + b := induction_on a $ λ α₁ r₁ _, induction_on b $ λ α₂ r₂ _ ⟨⟨⟨f, fo⟩, fi⟩⟩ c, induction_on c $ λ β s _, ⟨⟨⟨(embedding.refl _).sum_map f, λ a b, match a, b with | sum.inl a, sum.inl b := sum.lex_inl_inl.trans sum.lex_inl_inl.symm | sum.inl a, sum.inr b := by apply iff_of_true; apply sum.lex.sep | sum.inr a, sum.inl b := by apply iff_of_false; exact sum.lex_inr_inl | sum.inr a, sum.inr b := sum.lex_inr_inr.trans $ fo.trans sum.lex_inr_inr.symm end⟩, λ a b H, match a, b, H with | _, sum.inl b, _ := ⟨sum.inl b, rfl⟩ | sum.inl a, sum.inr b, H := (sum.lex_inr_inl H).elim | sum.inr a, sum.inr b, H := let ⟨w, h⟩ := fi _ _ (sum.lex_inr_inr.1 H) in ⟨sum.inr w, congr_arg sum.inr h⟩ end⟩⟩ theorem le_add_right (a b : ordinal) : a ≤ a + b := by simpa only [add_zero] using add_le_add_left (ordinal.zero_le b) a theorem add_le_add_right {a b : ordinal} : a ≤ b → ∀ c, a + c ≤ b + c := induction_on a $ λ α₁ r₁ hr₁, induction_on b $ λ α₂ r₂ hr₂ ⟨⟨⟨f, fo⟩, fi⟩⟩ c, induction_on c $ λ β s hs, (@type_le' _ _ _ _ (@sum.lex.is_well_order _ _ _ _ hr₁ hs) (@sum.lex.is_well_order _ _ _ _ hr₂ hs)).2 ⟨⟨f.sum_map (embedding.refl _), λ a b, begin split; intro H, { cases a with a a; cases b with b b; cases H; constructor; [rwa ← fo, assumption] }, { cases H; constructor; [rwa fo, assumption] } end⟩⟩ theorem le_add_left (a b : ordinal) : a ≤ b + a := by simpa only [zero_add] using add_le_add_right (ordinal.zero_le b) a theorem lt_succ_self (o : ordinal.{u}) : o < succ o := induction_on o $ λ α r _, ⟨⟨⟨⟨λ x, sum.inl x, λ _ _, sum.inl.inj⟩, λ _ _, sum.lex_inl_inl⟩, sum.inr punit.star, λ b, sum.rec_on b (λ x, ⟨λ _, ⟨x, rfl⟩, λ _, sum.lex.sep _ _⟩) (λ x, sum.lex_inr_inr.trans ⟨false.elim, λ ⟨x, H⟩, sum.inl_ne_inr H⟩)⟩⟩ theorem succ_le {a b : ordinal} : succ a ≤ b ↔ a < b := ⟨lt_of_lt_of_le (lt_succ_self _), induction_on a $ λ α r hr, induction_on b $ λ β s hs ⟨⟨f, t, hf⟩⟩, begin refine ⟨⟨@rel_embedding.of_monotone (α ⊕ punit) β _ _ (@sum.lex.is_well_order _ _ _ _ hr _).1.1 (@is_asymm_of_is_trans_of_is_irrefl _ _ hs.1.2.2 hs.1.2.1) (sum.rec _ _) (λ a b, _), λ a b, _⟩⟩, { exact f }, { exact λ _, t }, { rcases a with a|_; rcases b with b|_, { simpa only [sum.lex_inl_inl] using f.map_rel_iff.2 }, { intro _, rw hf, exact ⟨_, rfl⟩ }, { exact false.elim ∘ sum.lex_inr_inl }, { exact false.elim ∘ sum.lex_inr_inr.1 } }, { rcases a with a|_, { intro h, have := @principal_seg.init _ _ _ _ hs.1.2.2 ⟨f, t, hf⟩ _ _ h, cases this with w h, exact ⟨sum.inl w, h⟩ }, { intro h, cases (hf b).1 h with w h, exact ⟨sum.inl w, h⟩ } } end⟩ theorem le_total (a b : ordinal) : a ≤ b ∨ b ≤ a := match lt_or_eq_of_le (le_add_left b a), lt_or_eq_of_le (le_add_right a b) with | or.inr h, _ := by rw h; exact or.inl (le_add_right _ _) | _, or.inr h := by rw h; exact or.inr (le_add_left _ _) | or.inl h₁, or.inl h₂ := induction_on a (λ α₁ r₁ _, induction_on b $ λ α₂ r₂ _ ⟨f⟩ ⟨g⟩, begin resetI, rw [← typein_top f, ← typein_top g, le_iff_lt_or_eq, le_iff_lt_or_eq, typein_lt_typein, typein_lt_typein], rcases trichotomous_of (sum.lex r₁ r₂) g.top f.top with h|h|h; [exact or.inl (or.inl h), {left, right, rw h}, exact or.inr (or.inl h)] end) h₁ h₂ end instance : linear_order ordinal := { le_total := le_total, decidable_le := classical.dec_rel _, ..ordinal.partial_order } instance : is_well_order ordinal (<) := ⟨wf⟩ @[simp] lemma typein_le_typein (r : α → α → Prop) [is_well_order α r] {x x' : α} : typein r x ≤ typein r x' ↔ ¬r x' x := by rw [←not_lt, typein_lt_typein] lemma enum_le_enum (r : α → α → Prop) [is_well_order α r] {o o' : ordinal} (ho : o < type r) (ho' : o' < type r) : ¬r (enum r o' ho') (enum r o ho) ↔ o ≤ o' := by rw [←@not_lt _ _ o' o, enum_lt ho'] /-- `univ.{u v}` is the order type of the ordinals of `Type u` as a member of `ordinal.{v}` (when `u < v`). It is an inaccessible cardinal. -/ @[nolint check_univs] -- intended to be used with explicit universe parameters def univ : ordinal.{max (u + 1) v} := lift.{v (u+1)} (@type ordinal.{u} (<) _) theorem univ_id : univ.{u (u+1)} = @type ordinal.{u} (<) _ := lift_id _ @[simp] theorem lift_univ : lift.{w} univ.{u v} = univ.{u (max v w)} := lift_lift _ theorem univ_umax : univ.{u (max (u+1) v)} = univ.{u v} := congr_fun lift_umax _ /-- Principal segment version of the lift operation on ordinals, embedding `ordinal.{u}` in `ordinal.{v}` as a principal segment when `u < v`. -/ def lift.principal_seg : @principal_seg ordinal.{u} ordinal.{max (u+1) v} (<) (<) := ⟨↑lift.initial_seg.{u (max (u+1) v)}, univ.{u v}, begin refine λ b, induction_on b _, introsI β s _, rw [univ, ← lift_umax], split; intro h, { rw ← lift_id (type s) at h ⊢, cases lift_type_lt.1 h with f, cases f with f a hf, existsi a, revert hf, apply induction_on a, introsI α r _ hf, refine lift_type_eq.{u (max (u+1) v) (max (u+1) v)}.2 ⟨(rel_iso.of_surjective (rel_embedding.of_monotone _ _) _).symm⟩, { exact λ b, enum r (f b) ((hf _).2 ⟨_, rfl⟩) }, { refine λ a b h, (typein_lt_typein r).1 _, rw [typein_enum, typein_enum], exact f.map_rel_iff.2 h }, { intro a', cases (hf _).1 (typein_lt_type _ a') with b e, existsi b, simp, simp [e] } }, { cases h with a e, rw [← e], apply induction_on a, introsI α r _, exact lift_type_lt.{u (u+1) (max (u+1) v)}.2 ⟨typein.principal_seg r⟩ } end⟩ @[simp] theorem lift.principal_seg_coe : (lift.principal_seg.{u v} : ordinal → ordinal) = lift.{(max (u+1) v)} := rfl @[simp] theorem lift.principal_seg_top : lift.principal_seg.top = univ := rfl theorem lift.principal_seg_top' : lift.principal_seg.{u (u+1)}.top = @type ordinal.{u} (<) _ := by simp only [lift.principal_seg_top, univ_id] /-! ### Minimum -/ /-- The minimal element of a nonempty family of ordinals -/ def min {ι} (I : nonempty ι) (f : ι → ordinal) : ordinal := wf.min (set.range f) (let ⟨i⟩ := I in ⟨_, set.mem_range_self i⟩) theorem min_eq {ι} (I) (f : ι → ordinal) : ∃ i, min I f = f i := let ⟨i, e⟩ := wf.min_mem (set.range f) _ in ⟨i, e.symm⟩ theorem min_le {ι I} (f : ι → ordinal) (i) : min I f ≤ f i := le_of_not_gt $ wf.not_lt_min (set.range f) _ (set.mem_range_self i) theorem le_min {ι I} {f : ι → ordinal} {a} : a ≤ min I f ↔ ∀ i, a ≤ f i := ⟨λ h i, le_trans h (min_le _ _), λ h, let ⟨i, e⟩ := min_eq I f in e.symm ▸ h i⟩ /-- The minimal element of a nonempty set of ordinals -/ def omin (S : set ordinal.{u}) (H : ∃ x, x ∈ S) : ordinal.{u} := @min.{(u+2) u} S (let ⟨x, px⟩ := H in ⟨⟨x, px⟩⟩) subtype.val theorem omin_mem (S H) : omin S H ∈ S := let ⟨⟨i, h⟩, e⟩ := @min_eq S _ _ in (show omin S H = i, from e).symm ▸ h theorem le_omin {S H a} : a ≤ omin S H ↔ ∀ i ∈ S, a ≤ i := le_min.trans set_coe.forall theorem omin_le {S H i} (h : i ∈ S) : omin S H ≤ i := le_omin.1 (le_refl _) _ h @[simp] theorem lift_min {ι} (I) (f : ι → ordinal) : lift (min I f) = min I (lift ∘ f) := le_antisymm (le_min.2 $ λ a, lift_le.2 $ min_le _ a) $ let ⟨i, e⟩ := min_eq I (lift ∘ f) in by rw e; exact lift_le.2 (le_min.2 $ λ j, lift_le.1 $ by have := min_le (lift ∘ f) j; rwa e at this) instance : conditionally_complete_linear_order_bot ordinal := wf.conditionally_complete_linear_order_with_bot 0 $ le_antisymm (ordinal.zero_le _) $ not_lt.1 (wf.not_lt_min set.univ ⟨0, mem_univ _⟩ (mem_univ 0)) @[simp] lemma bot_eq_zero : (⊥ : ordinal) = 0 := rfl lemma Inf_eq_omin {s : set ordinal} (hs : s.nonempty) : Inf s = omin s hs := begin simp only [Inf, conditionally_complete_lattice.Inf, omin, conditionally_complete_linear_order.Inf, conditionally_complete_linear_order_bot.Inf, hs, dif_pos], congr, rw subtype.range_val, end lemma Inf_mem {s : set ordinal} (hs : s.nonempty) : Inf s ∈ s := by { rw Inf_eq_omin hs, exact omin_mem _ hs } instance : no_top_order ordinal := ⟨λ a, ⟨a.succ, lt_succ_self a⟩⟩ end ordinal /-! ### Representing a cardinal with an ordinal -/ namespace cardinal open ordinal /-- The ordinal corresponding to a cardinal `c` is the least ordinal whose cardinal is `c`. For the order-embedding version, see `ord.order_embedding`. -/ def ord (c : cardinal) : ordinal := begin let ι := λ α, {r // is_well_order α r}, have : Π α, ι α := λ α, ⟨well_ordering_rel, by apply_instance⟩, let F := λ α, ordinal.min ⟨this _⟩ (λ i:ι α, ⟦⟨α, i.1, i.2⟩⟧), refine quot.lift_on c F _, suffices : ∀ {α β}, α ≈ β → F α ≤ F β, from λ α β h, le_antisymm (this h) (this (setoid.symm h)), intros α β h, cases h with f, refine ordinal.le_min.2 (λ i, _), haveI := @rel_embedding.is_well_order _ _ (f ⁻¹'o i.1) _ ↑(rel_iso.preimage f i.1) i.2, rw ← show type (f ⁻¹'o i.1) = ⟦⟨β, i.1, i.2⟩⟧, from quot.sound ⟨rel_iso.preimage f i.1⟩, exact ordinal.min_le (λ i:ι α, ⟦⟨α, i.1, i.2⟩⟧) ⟨_, _⟩ end lemma ord_eq_min (α : Type u) : ord (#α) = @ordinal.min {r // is_well_order α r} ⟨⟨well_ordering_rel, by apply_instance⟩⟩ (λ i, ⟦⟨α, i.1, i.2⟩⟧) := rfl theorem ord_eq (α) : ∃ (r : α → α → Prop) [wo : is_well_order α r], ord (#α) = @type α r wo := let ⟨⟨r, wo⟩, h⟩ := @ordinal.min_eq {r // is_well_order α r} ⟨⟨well_ordering_rel, by apply_instance⟩⟩ (λ i:{r // is_well_order α r}, ⟦⟨α, i.1, i.2⟩⟧) in ⟨r, wo, h⟩ theorem ord_le_type (r : α → α → Prop) [is_well_order α r] : ord (#α) ≤ ordinal.type r := @ordinal.min_le {r // is_well_order α r} ⟨⟨well_ordering_rel, by apply_instance⟩⟩ (λ i:{r // is_well_order α r}, ⟦⟨α, i.1, i.2⟩⟧) ⟨r, _⟩ theorem ord_le {c o} : ord c ≤ o ↔ c ≤ o.card := induction_on c $ λ α, ordinal.induction_on o $ λ β s _, let ⟨r, _, e⟩ := ord_eq α in begin resetI, simp only [card_type], split; intro h, { rw e at h, exact let ⟨f⟩ := h in ⟨f.to_embedding⟩ }, { cases h with f, have g := rel_embedding.preimage f s, haveI := rel_embedding.is_well_order g, exact le_trans (ord_le_type _) (type_le'.2 ⟨g⟩) } end theorem lt_ord {c o} : o < ord c ↔ o.card < c := by rw [← not_le, ← not_le, ord_le] @[simp] theorem card_ord (c) : (ord c).card = c := quotient.induction_on c $ λ α, let ⟨r, _, e⟩ := ord_eq α in by simp only [mk_def, e, card_type] theorem ord_card_le (o : ordinal) : o.card.ord ≤ o := ord_le.2 (le_refl _) lemma lt_ord_succ_card (o : ordinal) : o < o.card.succ.ord := by { rw [lt_ord], apply cardinal.lt_succ_self } @[simp] theorem ord_le_ord {c₁ c₂} : ord c₁ ≤ ord c₂ ↔ c₁ ≤ c₂ := by simp only [ord_le, card_ord] @[simp] theorem ord_lt_ord {c₁ c₂} : ord c₁ < ord c₂ ↔ c₁ < c₂ := by simp only [lt_ord, card_ord] @[simp] theorem ord_zero : ord 0 = 0 := le_antisymm (ord_le.2 $ zero_le _) (ordinal.zero_le _) @[simp] theorem ord_nat (n : ℕ) : ord n = n := le_antisymm (ord_le.2 $ by simp only [card_nat]) $ begin induction n with n IH, { apply ordinal.zero_le }, { exact (@ordinal.succ_le n _).2 (lt_of_le_of_lt IH $ ord_lt_ord.2 $ nat_cast_lt.2 (nat.lt_succ_self n)) } end @[simp] theorem lift_ord (c) : (ord c).lift = ord (lift c) := eq_of_forall_ge_iff $ λ o, le_iff_le_iff_lt_iff_lt.2 $ begin split; intro h, { rcases ordinal.lt_lift_iff.1 h with ⟨a, e, h⟩, rwa [← e, lt_ord, ← lift_card, lift_lt, ← lt_ord] }, { rw lt_ord at h, rcases lift_down' (le_of_lt h) with ⟨o, rfl⟩, rw [← lift_card, lift_lt] at h, rwa [ordinal.lift_lt, lt_ord] } end lemma mk_ord_out (c : cardinal) : #c.ord.out.α = c := by rw [←card_type c.ord.out.r, type_out, card_ord] lemma card_typein_lt (r : α → α → Prop) [is_well_order α r] (x : α) (h : ord (#α) = type r) : card (typein r x) < #α := by { rw [←ord_lt_ord, h], refine lt_of_le_of_lt (ord_card_le _) (typein_lt_type r x) } lemma card_typein_out_lt (c : cardinal) (x : c.ord.out.α) : card (typein c.ord.out.r x) < c := by { convert card_typein_lt c.ord.out.r x _, rw [mk_ord_out], rw [type_out, mk_ord_out] } lemma ord_injective : injective ord := by { intros c c' h, rw [←card_ord c, ←card_ord c', h] } /-- The ordinal corresponding to a cardinal `c` is the least ordinal whose cardinal is `c`. This is the order-embedding version. For the regular function, see `ord`. -/ def ord.order_embedding : cardinal ↪o ordinal := rel_embedding.order_embedding_of_lt_embedding (rel_embedding.of_monotone cardinal.ord $ λ a b, cardinal.ord_lt_ord.2) @[simp] theorem ord.order_embedding_coe : (ord.order_embedding : cardinal → ordinal) = ord := rfl /-- The cardinal `univ` is the cardinality of ordinal `univ`, or equivalently the cardinal of `ordinal.{u}`, or `cardinal.{u}`, as an element of `cardinal.{v}` (when `u < v`). -/ @[nolint check_univs] -- intended to be used with explicit universe parameters def univ := lift.{v (u+1)} (#ordinal) theorem univ_id : univ.{u (u+1)} = #ordinal := lift_id _ @[simp] theorem lift_univ : lift.{w} univ.{u v} = univ.{u (max v w)} := lift_lift _ theorem univ_umax : univ.{u (max (u+1) v)} = univ.{u v} := congr_fun lift_umax _ theorem lift_lt_univ (c : cardinal) : lift.{(u+1) u} c < univ.{u (u+1)} := by simpa only [lift.principal_seg_coe, lift_ord, lift_succ, ord_le, succ_le] using le_of_lt (lift.principal_seg.{u (u+1)}.lt_top (succ c).ord) theorem lift_lt_univ' (c : cardinal) : lift.{(max (u+1) v) u} c < univ.{u v} := by simpa only [lift_lift, lift_univ, univ_umax] using lift_lt.{_ (max (u+1) v)}.2 (lift_lt_univ c) @[simp] theorem ord_univ : ord univ.{u v} = ordinal.univ.{u v} := le_antisymm (ord_card_le _) $ le_of_forall_lt $ λ o h, lt_ord.2 begin rcases lift.principal_seg.{u v}.down'.1 (by simpa only [lift.principal_seg_coe] using h) with ⟨o', rfl⟩, simp only [lift.principal_seg_coe], rw [← lift_card], apply lift_lt_univ' end theorem lt_univ {c} : c < univ.{u (u+1)} ↔ ∃ c', c = lift.{(u+1) u} c' := ⟨λ h, begin have := ord_lt_ord.2 h, rw ord_univ at this, cases lift.principal_seg.{u (u+1)}.down'.1 (by simpa only [lift.principal_seg_top]) with o e, have := card_ord c, rw [← e, lift.principal_seg_coe, ← lift_card] at this, exact ⟨_, this.symm⟩ end, λ ⟨c', e⟩, e.symm ▸ lift_lt_univ _⟩ theorem lt_univ' {c} : c < univ.{u v} ↔ ∃ c', c = lift.{(max (u+1) v) u} c' := ⟨λ h, let ⟨a, e, h'⟩ := lt_lift_iff.1 h in begin rw [← univ_id] at h', rcases lt_univ.{u}.1 h' with ⟨c', rfl⟩, exact ⟨c', by simp only [e.symm, lift_lift]⟩ end, λ ⟨c', e⟩, e.symm ▸ lift_lt_univ' _⟩ end cardinal namespace ordinal @[simp] theorem card_univ : card univ = cardinal.univ := rfl end ordinal
9d58b329996fbd40335925076cf40d62b5140a67
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/number_theory/lucas_lehmer.lean
3d46db2c374bab00c900a0bc2f9e312c1901a6df
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
17,233
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Scott Morrison, Ainsley Pahljina -/ import tactic.ring_exp import tactic.interval_cases import data.nat.parity import data.zmod.basic import group_theory.order_of_element import ring_theory.fintype /-! # The Lucas-Lehmer test for Mersenne primes. We define `lucas_lehmer_residue : Π p : ℕ, zmod (2^p - 1)`, and prove `lucas_lehmer_residue p = 0 → prime (mersenne p)`. We construct a tactic `lucas_lehmer.run_test`, which iteratively certifies the arithmetic required to calculate the residue, and enables us to prove ``` example : prime (mersenne 127) := lucas_lehmer_sufficiency _ (by norm_num) (by lucas_lehmer.run_test) ``` ## TODO - Show reverse implication. - Speed up the calculations using `n ≡ (n % 2^p) + (n / 2^p) [MOD 2^p - 1]`. - Find some bigger primes! ## History This development began as a student project by Ainsley Pahljina, and was then cleaned up for mathlib by Scott Morrison. The tactic for certified computation of Lucas-Lehmer residues was provided by Mario Carneiro. -/ /-- The Mersenne numbers, 2^p - 1. -/ def mersenne (p : ℕ) : ℕ := 2^p - 1 lemma mersenne_pos {p : ℕ} (h : 0 < p) : 0 < mersenne p := begin dsimp [mersenne], calc 0 < 2^1 - 1 : by norm_num ... ≤ 2^p - 1 : nat.pred_le_pred (nat.pow_le_pow_of_le_right (nat.succ_pos 1) h) end @[simp] lemma succ_mersenne (k : ℕ) : mersenne k + 1 = 2 ^ k := begin rw [mersenne, tsub_add_cancel_of_le], exact one_le_pow_of_one_le (by norm_num) k end namespace lucas_lehmer open nat /-! We now define three(!) different versions of the recurrence `s (i+1) = (s i)^2 - 2`. These versions take values either in `ℤ`, in `zmod (2^p - 1)`, or in `ℤ` but applying `% (2^p - 1)` at each step. They are each useful at different points in the proof, so we take a moment setting up the lemmas relating them. -/ /-- The recurrence `s (i+1) = (s i)^2 - 2` in `ℤ`. -/ def s : ℕ → ℤ | 0 := 4 | (i+1) := (s i)^2 - 2 /-- The recurrence `s (i+1) = (s i)^2 - 2` in `zmod (2^p - 1)`. -/ def s_zmod (p : ℕ) : ℕ → zmod (2^p - 1) | 0 := 4 | (i+1) := (s_zmod i)^2 - 2 /-- The recurrence `s (i+1) = ((s i)^2 - 2) % (2^p - 1)` in `ℤ`. -/ def s_mod (p : ℕ) : ℕ → ℤ | 0 := 4 % (2^p - 1) | (i+1) := ((s_mod i)^2 - 2) % (2^p - 1) lemma mersenne_int_ne_zero (p : ℕ) (w : 0 < p) : (2^p - 1 : ℤ) ≠ 0 := begin apply ne_of_gt, simp only [gt_iff_lt, sub_pos], exact_mod_cast nat.one_lt_two_pow p w, end lemma s_mod_nonneg (p : ℕ) (w : 0 < p) (i : ℕ) : 0 ≤ s_mod p i := begin cases i; dsimp [s_mod], { exact sup_eq_left.mp rfl }, { apply int.mod_nonneg, exact mersenne_int_ne_zero p w }, end lemma s_mod_mod (p i : ℕ) : s_mod p i % (2^p - 1) = s_mod p i := by cases i; simp [s_mod] lemma s_mod_lt (p : ℕ) (w : 0 < p) (i : ℕ) : s_mod p i < 2^p - 1 := begin rw ←s_mod_mod, convert int.mod_lt _ _, { refine (abs_of_nonneg _).symm, simp only [sub_nonneg, ge_iff_le], exact_mod_cast nat.one_le_two_pow p, }, { exact mersenne_int_ne_zero p w, }, end lemma s_zmod_eq_s (p' : ℕ) (i : ℕ) : s_zmod (p'+2) i = (s i : zmod (2^(p'+2) - 1)):= begin induction i with i ih, { dsimp [s, s_zmod], norm_num, }, { push_cast [s, s_zmod, ih] }, end -- These next two don't make good `norm_cast` lemmas. lemma int.coe_nat_pow_pred (b p : ℕ) (w : 0 < b) : ((b^p - 1 : ℕ) : ℤ) = (b^p - 1 : ℤ) := begin have : 1 ≤ b^p := nat.one_le_pow p b w, push_cast [this], end lemma int.coe_nat_two_pow_pred (p : ℕ) : ((2^p - 1 : ℕ) : ℤ) = (2^p - 1 : ℤ) := int.coe_nat_pow_pred 2 p dec_trivial lemma s_zmod_eq_s_mod (p : ℕ) (i : ℕ) : s_zmod p i = (s_mod p i : zmod (2^p - 1)) := by induction i; push_cast [←int.coe_nat_two_pow_pred p, s_mod, s_zmod, *] /-- The Lucas-Lehmer residue is `s p (p-2)` in `zmod (2^p - 1)`. -/ def lucas_lehmer_residue (p : ℕ) : zmod (2^p - 1) := s_zmod p (p-2) lemma residue_eq_zero_iff_s_mod_eq_zero (p : ℕ) (w : 1 < p) : lucas_lehmer_residue p = 0 ↔ s_mod p (p-2) = 0 := begin dsimp [lucas_lehmer_residue], rw s_zmod_eq_s_mod p, split, { -- We want to use that fact that `0 ≤ s_mod p (p-2) < 2^p - 1` -- and `lucas_lehmer_residue p = 0 → 2^p - 1 ∣ s_mod p (p-2)`. intro h, simp [zmod.int_coe_zmod_eq_zero_iff_dvd] at h, apply int.eq_zero_of_dvd_of_nonneg_of_lt _ _ h; clear h, apply s_mod_nonneg _ (nat.lt_of_succ_lt w), convert s_mod_lt _ (nat.lt_of_succ_lt w) (p-2), push_cast [nat.one_le_two_pow p], refl, }, { intro h, rw h, simp, }, end /-- A Mersenne number `2^p-1` is prime if and only if the Lucas-Lehmer residue `s p (p-2) % (2^p - 1)` is zero. -/ @[derive decidable_pred] def lucas_lehmer_test (p : ℕ) : Prop := lucas_lehmer_residue p = 0 /-- `q` is defined as the minimum factor of `mersenne p`, bundled as an `ℕ+`. -/ def q (p : ℕ) : ℕ+ := ⟨nat.min_fac (mersenne p), nat.min_fac_pos (mersenne p)⟩ local attribute [instance] lemma fact_pnat_pos (q : ℕ+) : fact (0 < (q : ℕ)) := ⟨q.2⟩ /-- We construct the ring `X q` as ℤ/qℤ + √3 ℤ/qℤ. -/ -- It would be nice to define this as (ℤ/qℤ)[x] / (x^2 - 3), -- obtaining the ring structure for free, -- but that seems to be more trouble than it's worth; -- if it were easy to make the definition, -- cardinality calculations would be somewhat more involved, too. @[derive [add_comm_group, decidable_eq, fintype, inhabited]] def X (q : ℕ+) : Type := (zmod q) × (zmod q) namespace X variable {q : ℕ+} @[ext] lemma ext {x y : X q} (h₁ : x.1 = y.1) (h₂ : x.2 = y.2) : x = y := begin cases x, cases y, congr; assumption end @[simp] lemma add_fst (x y : X q) : (x + y).1 = x.1 + y.1 := rfl @[simp] lemma add_snd (x y : X q) : (x + y).2 = x.2 + y.2 := rfl @[simp] lemma neg_fst (x : X q) : (-x).1 = -x.1 := rfl @[simp] lemma neg_snd (x : X q) : (-x).2 = -x.2 := rfl instance : has_mul (X q) := { mul := λ x y, (x.1*y.1 + 3*x.2*y.2, x.1*y.2 + x.2*y.1) } @[simp] lemma mul_fst (x y : X q) : (x * y).1 = x.1 * y.1 + 3 * x.2 * y.2 := rfl @[simp] lemma mul_snd (x y : X q) : (x * y).2 = x.1 * y.2 + x.2 * y.1 := rfl instance : has_one (X q) := { one := ⟨1,0⟩ } @[simp] lemma one_fst : (1 : X q).1 = 1 := rfl @[simp] lemma one_snd : (1 : X q).2 = 0 := rfl @[simp] lemma bit0_fst (x : X q) : (bit0 x).1 = bit0 x.1 := rfl @[simp] lemma bit0_snd (x : X q) : (bit0 x).2 = bit0 x.2 := rfl @[simp] lemma bit1_fst (x : X q) : (bit1 x).1 = bit1 x.1 := rfl @[simp] lemma bit1_snd (x : X q) : (bit1 x).2 = bit0 x.2 := by { dsimp [bit1], simp, } instance : monoid (X q) := { mul_assoc := λ x y z, by { ext; { dsimp, ring }, }, one := ⟨1,0⟩, one_mul := λ x, by { ext; simp, }, mul_one := λ x, by { ext; simp, }, ..(infer_instance : has_mul (X q)) } lemma left_distrib (x y z : X q) : x * (y + z) = x * y + x * z := by { ext; { dsimp, ring }, } lemma right_distrib (x y z : X q) : (x + y) * z = x * z + y * z := by { ext; { dsimp, ring }, } instance : ring (X q) := { left_distrib := left_distrib, right_distrib := right_distrib, ..(infer_instance : add_comm_group (X q)), ..(infer_instance : monoid (X q)) } instance : comm_ring (X q) := { mul_comm := λ x y, by { ext; { dsimp, ring }, }, ..(infer_instance : ring (X q))} instance [fact (1 < (q : ℕ))] : nontrivial (X q) := ⟨⟨0, 1, λ h, by { injection h with h1 _, exact zero_ne_one h1 } ⟩⟩ @[simp] lemma nat_coe_fst (n : ℕ) : (n : X q).fst = (n : zmod q) := begin induction n, { refl, }, { dsimp, simp only [add_left_inj], exact n_ih, } end @[simp] lemma nat_coe_snd (n : ℕ) : (n : X q).snd = (0 : zmod q) := begin induction n, { refl, }, { dsimp, simp only [add_zero], exact n_ih, } end @[simp] lemma int_coe_fst (n : ℤ) : (n : X q).fst = (n : zmod q) := by { induction n; simp, } @[simp] lemma int_coe_snd (n : ℤ) : (n : X q).snd = (0 : zmod q) := by { induction n; simp, } @[norm_cast] lemma coe_mul (n m : ℤ) : ((n * m : ℤ) : X q) = (n : X q) * (m : X q) := by { ext; simp; ring } @[norm_cast] lemma coe_nat (n : ℕ) : ((n : ℤ) : X q) = (n : X q) := by { ext; simp, } /-- The cardinality of `X` is `q^2`. -/ lemma X_card : fintype.card (X q) = q^2 := begin dsimp [X], rw [fintype.card_prod, zmod.card q], ring, end /-- There are strictly fewer than `q^2` units, since `0` is not a unit. -/ lemma units_card (w : 1 < q) : fintype.card (units (X q)) < q^2 := begin haveI : fact (1 < (q:ℕ)) := ⟨w⟩, convert card_units_lt (X q), rw X_card, end /-- We define `ω = 2 + √3`. -/ def ω : X q := (2, 1) /-- We define `ωb = 2 - √3`, which is the inverse of `ω`. -/ def ωb : X q := (2, -1) lemma ω_mul_ωb (q : ℕ+) : (ω : X q) * ωb = 1 := begin dsimp [ω, ωb], ext; simp; ring, end lemma ωb_mul_ω (q : ℕ+) : (ωb : X q) * ω = 1 := begin dsimp [ω, ωb], ext; simp; ring, end /-- A closed form for the recurrence relation. -/ lemma closed_form (i : ℕ) : (s i : X q) = (ω : X q)^(2^i) + (ωb : X q)^(2^i) := begin induction i with i ih, { dsimp [s, ω, ωb], ext; { simp; refl, }, }, { calc (s (i + 1) : X q) = ((s i)^2 - 2 : ℤ) : rfl ... = ((s i : X q)^2 - 2) : by push_cast ... = (ω^(2^i) + ωb^(2^i))^2 - 2 : by rw ih ... = (ω^(2^i))^2 + (ωb^(2^i))^2 + 2*(ωb^(2^i)*ω^(2^i)) - 2 : by ring ... = (ω^(2^i))^2 + (ωb^(2^i))^2 : by rw [←mul_pow ωb ω, ωb_mul_ω, one_pow, mul_one, add_sub_cancel] ... = ω^(2^(i+1)) + ωb^(2^(i+1)) : by rw [←pow_mul, ←pow_mul, pow_succ'] } end end X open X /-! Here and below, we introduce `p' = p - 2`, in order to avoid using subtraction in `ℕ`. -/ /-- If `1 < p`, then `q p`, the smallest prime factor of `mersenne p`, is more than 2. -/ lemma two_lt_q (p' : ℕ) : 2 < q (p'+2) := begin by_contradiction H, simp at H, interval_cases q (p'+2); clear H, { -- If q = 1, we get a contradiction from 2^p = 2 dsimp [q] at h, injection h with h', clear h, simp [mersenne] at h', exact lt_irrefl 2 (calc 2 ≤ p'+2 : nat.le_add_left _ _ ... < 2^(p'+2) : nat.lt_two_pow _ ... = 2 : nat.pred_inj (nat.one_le_two_pow _) dec_trivial h'), }, { -- If q = 2, we get a contradiction from 2 ∣ 2^p - 1 dsimp [q] at h, injection h with h', clear h, rw [mersenne, pnat.one_coe, nat.min_fac_eq_two_iff, pow_succ] at h', exact nat.two_not_dvd_two_mul_sub_one (nat.one_le_two_pow _) h', } end theorem ω_pow_formula (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : ∃ (k : ℤ), (ω : X (q (p'+2)))^(2^(p'+1)) = k * (mersenne (p'+2)) * ((ω : X (q (p'+2)))^(2^p')) - 1 := begin dsimp [lucas_lehmer_residue] at h, rw s_zmod_eq_s p' at h, simp [zmod.int_coe_zmod_eq_zero_iff_dvd] at h, cases h with k h, use k, replace h := congr_arg (λ (n : ℤ), (n : X (q (p'+2)))) h, -- coercion from ℤ to X q dsimp at h, rw closed_form at h, replace h := congr_arg (λ x, ω^2^p' * x) h, dsimp at h, have t : 2^p' + 2^p' = 2^(p'+1) := by ring_exp, rw [mul_add, ←pow_add ω, t, ←mul_pow ω ωb (2^p'), ω_mul_ωb, one_pow] at h, rw [mul_comm, coe_mul] at h, rw [mul_comm _ (k : X (q (p'+2)))] at h, replace h := eq_sub_of_add_eq h, exact_mod_cast h, end /-- `q` is the minimum factor of `mersenne p`, so `M p = 0` in `X q`. -/ theorem mersenne_coe_X (p : ℕ) : (mersenne p : X (q p)) = 0 := begin ext; simp [mersenne, q, zmod.nat_coe_zmod_eq_zero_iff_dvd, -pow_pos], apply nat.min_fac_dvd, end theorem ω_pow_eq_neg_one (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : (ω : X (q (p'+2)))^(2^(p'+1)) = -1 := begin cases ω_pow_formula p' h with k w, rw [mersenne_coe_X] at w, simpa using w, end theorem ω_pow_eq_one (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : (ω : X (q (p'+2)))^(2^(p'+2)) = 1 := calc (ω : X (q (p'+2)))^2^(p'+2) = (ω^(2^(p'+1)))^2 : by rw [←pow_mul, ←pow_succ'] ... = (-1)^2 : by rw ω_pow_eq_neg_one p' h ... = 1 : by simp /-- `ω` as an element of the group of units. -/ def ω_unit (p : ℕ) : units (X (q p)) := { val := ω, inv := ωb, val_inv := by simp [ω_mul_ωb], inv_val := by simp [ωb_mul_ω], } @[simp] lemma ω_unit_coe (p : ℕ) : (ω_unit p : X (q p)) = ω := rfl /-- The order of `ω` in the unit group is exactly `2^p`. -/ theorem order_ω (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : order_of (ω_unit (p'+2)) = 2^(p'+2) := begin apply nat.eq_prime_pow_of_dvd_least_prime_pow, -- the order of ω divides 2^p { norm_num, }, { intro o, have ω_pow := order_of_dvd_iff_pow_eq_one.1 o, replace ω_pow := congr_arg (units.coe_hom (X (q (p'+2))) : units (X (q (p'+2))) → X (q (p'+2))) ω_pow, simp at ω_pow, have h : (1 : zmod (q (p'+2))) = -1 := congr_arg (prod.fst) ((ω_pow.symm).trans (ω_pow_eq_neg_one p' h)), haveI : fact (2 < (q (p'+2) : ℕ)) := ⟨two_lt_q _⟩, apply zmod.neg_one_ne_one h.symm, }, { apply order_of_dvd_iff_pow_eq_one.2, apply units.ext, push_cast, exact ω_pow_eq_one p' h, } end lemma order_ineq (p' : ℕ) (h : lucas_lehmer_residue (p'+2) = 0) : 2^(p'+2) < (q (p'+2) : ℕ)^2 := calc 2^(p'+2) = order_of (ω_unit (p'+2)) : (order_ω p' h).symm ... ≤ fintype.card (units (X _)) : order_of_le_card_univ ... < (q (p'+2) : ℕ)^2 : units_card (nat.lt_of_succ_lt (two_lt_q _)) end lucas_lehmer export lucas_lehmer (lucas_lehmer_test lucas_lehmer_residue) open lucas_lehmer theorem lucas_lehmer_sufficiency (p : ℕ) (w : 1 < p) : lucas_lehmer_test p → (mersenne p).prime := begin let p' := p - 2, have z : p = p' + 2 := (tsub_eq_iff_eq_add_of_le w.nat_succ_le).mp rfl, have w : 1 < p' + 2 := (nat.lt_of_sub_eq_succ rfl), contrapose, intros a t, rw z at a, rw z at t, have h₁ := order_ineq p' t, have h₂ := nat.min_fac_sq_le_self (mersenne_pos (nat.lt_of_succ_lt w)) a, have h := lt_of_lt_of_le h₁ h₂, exact not_lt_of_ge (nat.sub_le _ _) h, end -- Here we calculate the residue, very inefficiently, using `dec_trivial`. We can do much better. example : (mersenne 5).prime := lucas_lehmer_sufficiency 5 (by norm_num) dec_trivial -- Next we use `norm_num` to calculate each `s p i`. namespace lucas_lehmer open tactic meta instance nat_pexpr : has_to_pexpr ℕ := ⟨pexpr.of_expr ∘ λ n, reflect n⟩ meta instance int_pexpr : has_to_pexpr ℤ := ⟨pexpr.of_expr ∘ λ n, reflect n⟩ lemma s_mod_succ {p a i b c} (h1 : (2^p - 1 : ℤ) = a) (h2 : s_mod p i = b) (h3 : (b * b - 2) % a = c) : s_mod p (i+1) = c := by { dsimp [s_mod, mersenne], rw [h1, h2, sq, h3] } /-- Given a goal of the form `lucas_lehmer_test p`, attempt to do the calculation using `norm_num` to certify each step. -/ meta def run_test : tactic unit := do `(lucas_lehmer_test %%p) ← target, `[dsimp [lucas_lehmer_test]], `[rw lucas_lehmer.residue_eq_zero_iff_s_mod_eq_zero, swap, norm_num], p ← eval_expr ℕ p, -- Calculate the candidate Mersenne prime let M : ℤ := 2^p - 1, t ← to_expr ``(2^%%p - 1 = %%M), v ← to_expr ``(by norm_num : 2^%%p - 1 = %%M), w ← assertv `w t v, -- Unfortunately this creates something like `w : 2^5 - 1 = int.of_nat 31`. -- We could make a better `has_to_pexpr ℤ` instance, or just: `[simp only [int.coe_nat_zero, int.coe_nat_succ, int.of_nat_eq_coe, zero_add, int.coe_nat_bit1] at w], -- base case t ← to_expr ``(s_mod %%p 0 = 4), v ← to_expr ``(by norm_num [lucas_lehmer.s_mod] : s_mod %%p 0 = 4), h ← assertv `h t v, -- step case, repeated p-2 times iterate_exactly (p-2) `[replace h := lucas_lehmer.s_mod_succ w h (by { norm_num, refl })], -- now close the goal h ← get_local `h, exact h end lucas_lehmer /-- We verify that the tactic works to prove `127.prime`. -/ example : (mersenne 7).prime := lucas_lehmer_sufficiency _ (by norm_num) (by lucas_lehmer.run_test). /-! This implementation works successfully to prove `(2^127 - 1).prime`, and all the Mersenne primes up to this point appear in [archive/examples/mersenne_primes.lean]. `(2^127 - 1).prime` takes about 5 minutes to run (depending on your CPU!), and unfortunately the next Mersenne prime `(2^521 - 1)`, which was the first "computer era" prime, is out of reach with the current implementation. There's still low hanging fruit available to do faster computations based on the formula n ≡ (n % 2^p) + (n / 2^p) [MOD 2^p - 1] and the fact that `% 2^p` and `/ 2^p` can be very efficient on the binary representation. Someone should do this, too! -/ lemma modeq_mersenne (n k : ℕ) : k ≡ ((k / 2^n) + (k % 2^n)) [MOD 2^n - 1] := -- See https://leanprover.zulipchat.com/#narrow/stream/113489-new-members/topic/help.20finding.20a.20lemma/near/177698446 begin conv in k { rw ← nat.div_add_mod k (2^n) }, refine nat.modeq.add_right _ _, conv { congr, skip, skip, rw ← one_mul (k/2^n) }, exact (nat.modeq_sub $ pow_pos (by norm_num : 0 < 2) _).mul_right _, end -- It's hard to know what the limiting factor for large Mersenne primes would be. -- In the purely computational world, I think it's the squaring operation in `s`.
d710fff7a431d5021c5f6a666aa201eeca9ab1e4
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/tactic/fix_reflect_string_auto.lean
d8e213b40a2948b99db6b4f86aea4c40a8a9ebdc
[]
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
899
lean
/- Copyright (c) 2020 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.PostPort namespace Mathlib /-! # Workaround for stack overflows with `has_reflect string` The default `has_reflect string` instance in Lean only work for strings up to few thousand characters. Anything larger than that will trigger a stack overflow because the string is represented as a very deeply nested expression: https://github.com/leanprover-community/lean/issues/144 This file adds a higher-priority instance for `has_reflect string`, which behaves exactly the same for small strings (up to 256 characters). Larger strings are carefully converted into a call to `string.join`. -/ /-- Splits a string into chunks of at most `size` characters. -/ end Mathlib
8b65c4ab632d0eb9432995d9ac3fac58f0f76818
b82c5bb4c3b618c23ba67764bc3e93f4999a1a39
/src/formal_ml/real_measurable_space.lean
514cdb24bf239c2c9b680fc7efe5e22e9f583491
[ "Apache-2.0" ]
permissive
nouretienne/formal-ml
83c4261016955bf9bcb55bd32b4f2621b44163e0
40b6da3b6e875f47412d50c7cd97936cb5091a2b
refs/heads/master
1,671,216,448,724
1,600,472,285,000
1,600,472,285,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
25,896
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 measure_theory.measurable_space import measure_theory.measure_space import measure_theory.outer_measure import measure_theory.lebesgue_measure import measure_theory.integration import measure_theory.borel_space import formal_ml.set import formal_ml.measurable_space import formal_ml.topological_space /- The big question is how to introduce a measurable function over the reals. The topology over the reals is induced by a metric space, using absolute difference as a measure of distance. This metric space induces a topological_space. The measurable space is the borel space on top of this topological space. A key result is borel_eq_generate_from_of_subbasis. which shows that if a basis generates a second countable topology, it generates the borel space as well. For example, consider an arbitrary open sets on the real line. For any point x in the open set, there exists a real number e such that the open interval (x-e,x+e) is in the set. Moreover, there is a rational number p in the interval (x-e,x) and another in (x,x+e), implying x is in (p,q). If we take union of all the intervals (p,q) for each x in U, then we get U. So, the set of all open intervals with rational endpoints is a countable basis, implying the reals are a second order topology. It is also immediately obvious that any open set can be formed with a countable union for the reals. However, let's look at an arbitrary second countable topology. The generalization of Lindelöf's lemma shows that for a second countable topology, there is a set of open sets such that any open set is the countable union. For Munkres, the definition of second countable topology is that there exists a countable basis. The definition of basis from Munkres is that for every point is contained in at least one basis set, and for any element x in the intersection of two basis sets A and B, there is a basis set C containing x that is a subset of B and C. set, and to generate the topology, one considers arbitrary union of elements in the bases. Thus, any union of a subset of a countable set must be representable as a countable union. So, there is a countable union. The more interesting part of borel_eq_generate_from_of_subbasis is that ANY set that generates a second countable topology is a basis for the borel space. I am not exactly sure how this works: regardless, the theorem gives great insights into second countable topologies (especially, reals, nnreals, ennreals, et cetera) and borel measures. To start with, this implies that the cartesian product of the borel spaces is the same as the borel space of the cartesian product of the topologies (i.e. it commutes). So, results about continuous functions on two real variables (e.g., add, multiply, power) translate to measurable functions on measurable spaces. -/ /- We begin with basic guarantees about intervals and measurable functions. -/ set_option pp.implicit true lemma nnreal_measurable_space_def:nnreal.measurable_space = borel nnreal := rfl lemma real_measurable_space_def:real.measurable_space = borel real := rfl lemma ennreal_measurable_space_def:ennreal.measurable_space = borel ennreal := rfl lemma borel_eq_generate_Iic (α:Type*) [topological_space α] [topological_space.second_countable_topology α] [linear_order α] [order_topology α] : borel α = measurable_space.generate_from (set.range set.Iic) := begin rw borel_eq_generate_Ioi α, apply le_antisymm, { rw measurable_space.generate_from_le_iff, rw set.subset_def, intros V A1, simp, simp at A1, cases A1 with y A1, subst V, --apply measurable_space.is_measurable_generate_from, rw ← set.compl_Iic, apply measurable_space.generate_measurable.compl, apply measurable_space.generate_measurable.basic, simp, }, { rw measurable_space.generate_from_le_iff, rw set.subset_def, intros V A1, simp, simp at A1, cases A1 with y A1, subst V, --apply measurable_space.is_measurable_generate_from, rw ← set.compl_Ioi, apply measurable_space.generate_measurable.compl, apply measurable_space.generate_measurable.basic, simp, }, end lemma is_measurable_intro_Iio (α β: Type*) [M:measurable_space α] [_inst_1 : topological_space β] [_inst_2 : @topological_space.second_countable_topology β _inst_1] [_inst_3 : linear_order β] [_inst_4 : @order_topology β _inst_1 (@partial_order.to_preorder β (@linear_order.to_partial_order β _inst_3))] (f:α → β):(∀ b:β, is_measurable (set.preimage f {y|y < b})) → (@measurable α β M (borel β) f) := begin intros A1, rw borel_eq_generate_Iio β, apply generate_from_measurable, refl, intros, cases H with z A2, subst B, unfold set.Iio, apply A1, end lemma is_nnreal_measurable_intro_Iio {α:Type*} [M:measurable_space α] (f:α → nnreal): (∀ x:nnreal, is_measurable (set.preimage f {y|y < x})) → (measurable f) := begin rw nnreal_measurable_space_def, apply is_measurable_intro_Iio, end lemma is_ennreal_measurable_intro_Iio {α:Type*} [M:measurable_space α] (f:α → ennreal): (∀ x:ennreal, is_measurable (set.preimage f {y|y < x})) → (measurable f) := begin rw ennreal_measurable_space_def, apply is_measurable_intro_Iio, end lemma is_real_measurable_intro_Iio {α:Type*} [M:measurable_space α] (f:α → real): (∀ x:real, is_measurable (set.preimage f {y|y < x})) → (measurable f) := begin rw real_measurable_space_def, apply is_measurable_intro_Iio, end lemma is_is_measurable_intro_Iio (β: Type*) [_inst_1 : topological_space β] [_inst_2 : @topological_space.second_countable_topology β _inst_1] [_inst_3 : linear_order β] [_inst_4 : @order_topology β _inst_1 (@partial_order.to_preorder β (@linear_order.to_partial_order β _inst_3))] (b:β):@is_measurable β (borel β) {y|y < b} := begin rw (@borel_eq_generate_Iio β _ _ _ _), apply measurable_space.is_measurable_generate_from, simp, unfold set.Iio, apply exists.intro b, refl, end lemma is_nnreal_is_measurable_intro_Iio (x:nnreal): (is_measurable {y|y < x}) := begin rw nnreal_measurable_space_def, apply is_is_measurable_intro_Iio, end lemma is_ennreal_is_measurable_intro_Iio (x:ennreal): (is_measurable {y|y < x}) := begin rw ennreal_measurable_space_def, apply is_is_measurable_intro_Iio, end lemma is_real_is_measurable_intro_Iio (x:real): (is_measurable {y|y < x}) := begin rw real_measurable_space_def, apply is_is_measurable_intro_Iio, end lemma is_is_measurable_intro_Ioi (β: Type*) [_inst_1 : topological_space β] [_inst_2 : @topological_space.second_countable_topology β _inst_1] [_inst_3 : linear_order β] [_inst_4 : @order_topology β _inst_1 (@partial_order.to_preorder β (@linear_order.to_partial_order β _inst_3))] (b:β):@is_measurable β (borel β) {y|b < y} := begin rw (@borel_eq_generate_Ioi β _ _ _ _), apply measurable_space.is_measurable_generate_from, simp, unfold set.Ioi, apply exists.intro b, refl, end lemma is_nnreal_is_measurable_intro_Ioi (x:nnreal): (is_measurable {y|x < y}) := begin rw nnreal_measurable_space_def, apply is_is_measurable_intro_Ioi, end lemma is_ennreal_is_measurable_intro_Ioi (x:ennreal): (is_measurable {y|x < y}) := begin rw ennreal_measurable_space_def, apply is_is_measurable_intro_Ioi, end lemma is_real_is_measurable_intro_Ioi (x:real): (is_measurable {y|x < y}) := begin rw real_measurable_space_def, apply is_is_measurable_intro_Ioi, end lemma is_measurable_intro_Ioi (α β: Type*) [M:measurable_space α] [_inst_1 : topological_space β] [_inst_2 : @topological_space.second_countable_topology β _inst_1] [_inst_3 : linear_order β] [_inst_4 : @order_topology β _inst_1 (@partial_order.to_preorder β (@linear_order.to_partial_order β _inst_3))] (f:α → β):(∀ b:β, is_measurable (set.preimage f {y|b< y})) → (@measurable α β M (borel β) f) := begin intros A1, rw borel_eq_generate_Ioi β, apply generate_from_measurable, refl, intros, cases H with z A2, subst B, unfold set.Ioi, apply A1, end lemma is_nnreal_measurable_intro_Ioi {α:Type*} [M:measurable_space α] (f:α → nnreal): (∀ x:nnreal, is_measurable (set.preimage f {y|x < y})) → (measurable f) := begin rw nnreal_measurable_space_def, apply is_measurable_intro_Ioi, end lemma is_ennreal_measurable_intro_Ioi {α:Type*} [M:measurable_space α] (f:α → ennreal): (∀ x:ennreal, is_measurable (set.preimage f {y|x < y})) → (measurable f) := begin rw ennreal_measurable_space_def, apply is_measurable_intro_Ioi, end lemma is_real_measurable_intro_Ioi {α:Type*} [M:measurable_space α] (f:α → real): (∀ x:real, is_measurable (set.preimage f {y|x < y})) → (measurable f) := begin rw real_measurable_space_def, apply is_measurable_intro_Ioi, end lemma Iic_Iio_compl (β: Type*) [L : linear_order β] (x:β):{y:β|y ≤ x}ᶜ={y:β|x < y} := begin intros, ext,split;intros A1, { simp, simp at A1, exact A1, }, { simp, simp at A1, exact A1, } end lemma Iio_Ici_compl (β: Type*) [L : linear_order β] (x:β):{y:β|x < y}={y:β|y ≤ x}ᶜ := begin intros, ext,split;intros A1, { simp, simp at A1, exact A1, }, { simp, simp at A1, exact A1, } end lemma Ioi_Ici_compl (β: Type*) [L : linear_order β] (x:β):{y:β|x ≤ y}={y:β|y < x}ᶜ := begin intros, ext,split;intros A1, { simp, simp at A1, exact A1, }, { simp, simp at A1, exact A1, } end lemma is_measurable_intro_Iic (α β: Type*) [M:measurable_space α] [_inst_1 : topological_space β] [_inst_2 : @topological_space.second_countable_topology β _inst_1] [_inst_3 : linear_order β] [_inst_4 : @order_topology β _inst_1 (@partial_order.to_preorder β (@linear_order.to_partial_order β _inst_3))] (f:α → β):(∀ b:β, is_measurable (set.preimage f {y|y ≤ b})) → (@measurable α β M (borel β) f) := begin intros A1, apply is_measurable_intro_Ioi, intros x, rw ← Iic_Iio_compl, apply is_measurable.compl, apply A1, end lemma is_nnreal_measurable_intro_Iic {α:Type*} [M:measurable_space α] (f:α → nnreal): (∀ x:nnreal, is_measurable (set.preimage f {y|y ≤ x})) → (measurable f) := begin rw nnreal_measurable_space_def, apply is_measurable_intro_Iic, end lemma is_measurable_elim_Iio (α β: Type*) [M:measurable_space α] [_inst_1 : topological_space β] [_inst_2 : @topological_space.second_countable_topology β _inst_1] [_inst_3 : linear_order β] [_inst_4 : @order_topology β _inst_1 (@partial_order.to_preorder β (@linear_order.to_partial_order β _inst_3))] (f:α → β) (b:β):(@measurable α β M (borel β) f) → (is_measurable (set.preimage f {y|y < b})) := begin intros A1, apply @measurable_elim α β M (borel β), apply A1, rw borel_eq_generate_Iio β, apply measurable_space.is_measurable_generate_from, simp, apply exists.intro b, unfold set.Iio, end lemma is_nnreal_measurable_elim_Iio {α:Type*} [M:measurable_space α] (f:α → nnreal) (x:nnreal): (measurable f) → is_measurable (set.preimage f {y|y < x}) := begin rw nnreal_measurable_space_def, apply is_measurable_elim_Iio, end lemma is_measurable_elim_Iic (α β: Type*) [M:measurable_space α] [_inst_1 : topological_space β] [_inst_2 : @topological_space.second_countable_topology β _inst_1] [_inst_3 : linear_order β] [_inst_4 : @order_topology β _inst_1 (@partial_order.to_preorder β (@linear_order.to_partial_order β _inst_3))] (f:α → β) (b:β):(@measurable α β M (borel β) f) → (is_measurable (set.preimage f {y|y ≤ b})) := begin intro A1, apply @measurable_elim α β M (borel β), apply A1, rw borel_eq_generate_Ioi β, have A2:{y|y ≤ b}={y|b<y}ᶜ, { ext,split; intro A2A, { simp, simp at A2A, exact A2A, }, { simp, simp at A2A, exact A2A, } }, rw A2, apply is_measurable.compl, apply measurable_space.is_measurable_generate_from, simp, apply exists.intro b, refl, end lemma is_nnreal_measurable_elim_Iic {α:Type*} [M:measurable_space α] (f:α → nnreal) (x:nnreal): (measurable f) → (is_measurable (set.preimage f {y|y ≤ x})) := begin rw nnreal_measurable_space_def, apply is_measurable_elim_Iic, end lemma is_real_measurable_elim_Iic {α:Type*} [M:measurable_space α] (f:α → real) (x:real): (measurable f) → (is_measurable (set.preimage f {y|y ≤ x})) := begin rw real_measurable_space_def, apply is_measurable_elim_Iic, end /- Many more elimination rules can be added here. -/ lemma borel_def {α:Type*} [topological_space α]:(borel α) = measurable_space.generate_from {s : set α | is_open s} := rfl lemma continuous_measurable {α β:Type*} [topological_space α] [topological_space β] (f:α → β): continuous f → @measurable α β (borel α) (borel β) f := begin intros A1, rw borel_def, rw borel_def, apply generate_from_measurable, { refl, }, { intros, apply measurable_space.is_measurable_generate_from, unfold continuous at A1, apply A1, apply H, } end lemma borel_def_prod_second_countable {α β:Type*} [Tα:topological_space α] [Tβ:topological_space β] [SCα:topological_space.second_countable_topology α] [SCβ:topological_space.second_countable_topology β] :(@prod.measurable_space α β (borel α) (borel β)) = (@borel (α × β) (@prod.topological_space α β Tα Tβ)) := begin /- Note that the second countable property is required here. For instance the topology with a basis [x,y) is not second countable, and its product has a set that is open, but not coverable with a countable number of sets (e.g., the line y = -x). So, this would not work. The general idea is that since each topology has a countable basis the product topology has a countable basis as well. -/ have A1:∃b:set (set α), set.countable b ∧ Tα = topological_space.generate_from b, { apply SCα.is_open_generated_countable, }, cases A1 with basisα A1, cases A1 with A2 A3, rw (@borel_eq_generate_from_of_subbasis α basisα _ _ A3), have A4:∃b:set (set β), set.countable b ∧ Tβ = topological_space.generate_from b, { apply SCβ.is_open_generated_countable, }, cases A4 with basisβ A4, cases A4 with A5 A6, rw (@borel_eq_generate_from_of_subbasis β basisβ _ _ A6), rw prod_measurable_space_def, rw @borel_eq_generate_from_of_subbasis, rw A3, rw A6, rw prod_topological_space_def, end lemma continuous_measurable_binary {α β γ:Type*} [topological_space α] [topological_space β] [topological_space γ] [topological_space.second_countable_topology α] [topological_space.second_countable_topology β] (f:α × β → γ): continuous f → (@measurable (α × β) γ (@prod.measurable_space α β (borel α) (borel β)) (borel γ) f) := begin rw borel_def_prod_second_countable, apply continuous_measurable, end -- Note: there used to be theorems like this in mathlib, but they disappeared lemma is_measurable_of_is_open {α:Type*} [topological_space α] (S:set α):is_open S → measurable_space.is_measurable (borel α) S := begin rw borel_def, apply measurable_space.is_measurable_generate_from, end lemma is_measurable_of_is_closed {α:Type*} [topological_space α] (S:set α):is_closed S → measurable_space.is_measurable (borel α) S := begin intro A1, unfold is_closed at A1, have A2:S = ((Sᶜ)ᶜ), { rw set.compl_compl, }, rw A2, apply measurable_space.is_measurable_compl, apply is_measurable_of_is_open, apply A1, end lemma is_open_is_measurable_binary {α β:Type*} [topological_space α] [topological_space β] [topological_space.second_countable_topology α] [topological_space.second_countable_topology β] (S:set (α × β)):is_open S → measurable_space.is_measurable (@prod.measurable_space α β (borel α) (borel β)) S := begin rw borel_def_prod_second_countable, apply is_measurable_of_is_open, end lemma is_closed_is_measurable_binary {α β:Type*} [topological_space α] [topological_space β] [topological_space.second_countable_topology α] [topological_space.second_countable_topology β] (S:set (α × β)):is_closed S → measurable_space.is_measurable (@prod.measurable_space α β (borel α) (borel β)) S := begin rw borel_def_prod_second_countable, apply is_measurable_of_is_closed, end lemma SC_composition {Ω:Type*} [MΩ:measurable_space Ω] {β:Type*} [Tβ:topological_space β] [CT:topological_space.second_countable_topology β] (f:Ω → β) (g:Ω → β) (h:β → β → β): (@measurable Ω β MΩ (borel β) f) → (@measurable Ω β MΩ (borel β) g) → continuous2 h → @measurable Ω β MΩ (borel β) (λ ω:Ω, h (f ω) (g ω)) := begin intros A1 A2 A3, have A4:@measurable Ω (β × β) MΩ (@prod.measurable_space β β (borel β) (borel β)) (λ ω:Ω, prod.mk (f ω) (g ω)), { apply measurable_fun_product_measurable;assumption, }, have A5:@measurable (β × β) β (@prod.measurable_space β β (borel β) (borel β)) (borel β) (λ p: (β × β), h (p.fst) (p.snd)), { rw continuous2_def at A3, apply continuous_measurable_binary, apply A3, }, have A6:(λ ω:Ω, h (f ω) (g ω))=(λ p: (β × β), h (p.fst) (p.snd)) ∘ (λ ω:Ω, prod.mk (f ω) (g ω)), { simp, }, rw A6, apply @compose_measurable_fun_measurable Ω (β × β) β MΩ (@prod.measurable_space β β (borel β) (borel β)) (borel β) (λ p: (β × β), h (p.fst) (p.snd)) (λ ω:Ω, prod.mk (f ω) (g ω)) A5 A4, end lemma nnreal_composition {Ω:Type*} [MΩ:measurable_space Ω] (f:Ω → nnreal) (g:Ω → nnreal) (h:nnreal → nnreal → nnreal): measurable f → measurable g → continuous2 h → measurable (λ ω:Ω, h (f ω) (g ω)) := begin apply SC_composition, end lemma SC_sum_measurable {Ω:Type*} [MΩ:measurable_space Ω] {β:Type*} {T:topological_space β} {SC:topological_space.second_countable_topology β} {CSR:add_monoid β} {TA:has_continuous_add β} (X Y:Ω → β): (@measurable _ _ _ (borel β) X) → (@measurable _ _ _ (borel β) Y) → (@measurable _ _ _ (borel β) (λ ω:Ω, (X ω + Y ω))) := begin intros A1 A2, apply @SC_composition Ω MΩ β T SC X Y, apply A1, apply A2, apply TA.continuous_add, end lemma SC_neg_measurable {Ω:Type*} [MΩ:measurable_space Ω] {β:Type*} {T:topological_space β} {SC:topological_space.second_countable_topology β} {CSR:add_group β} {TA:topological_add_group β} (X:Ω → β): (@measurable _ _ _ (borel β) X) → (@measurable _ _ _ (borel β) (λ ω:Ω, (-X ω))) := begin intros A1, have A2:(λ (ω:Ω), -X ω)=has_neg.neg ∘ X := rfl, rw A2, apply @compose_measurable_fun_measurable Ω β β MΩ (borel β) (borel β), { apply continuous_measurable, apply topological_add_group.continuous_neg, }, { apply A1, }, end --const_measurable {Ω:Type*} [measurable_space Ω] {β:Type*} [measurable_space β] (c:β) /- ∀ {α : Type u_1} {β : Type u_2} [_inst_1 : measurable_space α] [_inst_2 : measurable_space β] {a : α}, @measurable β α _inst_2 _inst_1 (λ (b : β), a) -/ def SC_sum_measurable_is_add_submonoid {Ω:Type*} [MΩ:measurable_space Ω] {β:Type*} {T:topological_space β} {SC:topological_space.second_countable_topology β} {CSR:add_monoid β} {TA:has_continuous_add β}: is_add_submonoid (@measurable Ω β MΩ (borel β)) := { zero_mem := @measurable_const β Ω (borel β) MΩ (0:β), add_mem := @SC_sum_measurable Ω MΩ β T SC CSR TA, } def SC_sum_measurable_is_add_subgroup {Ω:Type*} [MΩ:measurable_space Ω] {β:Type*} {T:topological_space β} {SC:topological_space.second_countable_topology β} {CSR:add_group β} {TA:topological_add_group β}: is_add_subgroup (@measurable Ω β MΩ (borel β)) := { zero_mem := @measurable_const β Ω (borel β) MΩ (0:β), add_mem := @SC_sum_measurable Ω MΩ β T SC (add_group.to_add_monoid β) (topological_add_group.to_has_continuous_add), neg_mem := @SC_neg_measurable Ω MΩ β T SC CSR TA, } lemma SC_mul_measurable {Ω:Type*} [MΩ:measurable_space Ω] {β:Type*} {T:topological_space β} {SC:topological_space.second_countable_topology β} {CSR:monoid β} {TA:has_continuous_mul β} (X Y:Ω → β): (@measurable _ _ _ (borel β) X) → (@measurable _ _ _ (borel β) Y) → (@measurable _ _ _ (borel β) (λ ω:Ω, (X ω * Y ω))) := begin intros A1 A2, apply @SC_composition Ω MΩ β T SC X Y, apply A1, apply A2, apply TA.continuous_mul, end def SC_mul_measurable_is_submonoid {Ω:Type*} [MΩ:measurable_space Ω] {β:Type*} {T:topological_space β} {SC:topological_space.second_countable_topology β} {CSR:monoid β} {TA:has_continuous_mul β}: is_submonoid (@measurable Ω β MΩ (borel β)) := { one_mem := @measurable_const β Ω (borel β) MΩ (1:β), mul_mem := @SC_mul_measurable Ω MΩ β T SC CSR TA, } lemma nnreal_sum_measurable {Ω:Type*} [MΩ:measurable_space Ω] (X Y:Ω → nnreal): (measurable X) → (measurable Y) → measurable (λ ω:Ω, (X ω + Y ω)) := begin apply SC_sum_measurable, apply nnreal.topological_space.second_countable_topology, apply nnreal.topological_semiring.to_has_continuous_add, end lemma finset_sum_measurable {Ω β:Type*} [measurable_space Ω] [decidable_eq β] {γ:Type*} {T:topological_space γ} {SC:topological_space.second_countable_topology γ} {CSR:add_comm_monoid γ} {TA:has_continuous_add γ} (S:finset β) (X:β → Ω → γ): (∀ b:β, @measurable Ω γ _ (borel γ) (X b)) → @measurable Ω γ _ (borel γ) (λ ω:Ω, S.sum (λ b:β, ((X b) ω))) := begin apply finset.induction_on S, { intros A1, simp, apply const_measurable, }, { intros b T A2 A3 A4, -- A3, -- A4 B, have A5:(λ (ω : Ω), finset.sum (insert b T) (λ (b : β), X b ω)) = (λ (ω : Ω), (X b ω) + finset.sum T (λ (b : β), X b ω)), { ext, rw finset.sum_insert, exact A2, }, rw A5, apply SC_sum_measurable, { apply SC, }, { apply TA, }, { apply A4, }, { apply A3, exact A4, } } end lemma finset_sum_measurable_classical {Ω β:Type*} [MΩ:measurable_space Ω] {γ:Type*} {T:topological_space γ} {SC:topological_space.second_countable_topology γ} {CSR:add_comm_monoid γ} {TA:has_continuous_add γ} (S:finset β) (X:β → Ω → γ): (∀ b:β, @measurable Ω γ _ (borel γ) (X b)) → @measurable Ω γ _ (borel γ) (λ ω:Ω, S.sum (λ b:β, ((X b) ω))) := begin have D:decidable_eq β, { apply classical.decidable_eq β, }, apply @finset_sum_measurable Ω β MΩ D γ T SC CSR TA S X, end lemma nnreal_finset_sum_measurable {Ω β:Type*} [measurable_space Ω] [decidable_eq β] (S:finset β) (X:β → Ω → nnreal): (∀ b:β, measurable (X b)) → measurable (λ ω:Ω, S.sum (λ b:β, ((X b) ω))) := begin apply finset_sum_measurable, apply_instance, apply_instance, end lemma fintype_sum_measurable {Ω β:Type*} [F:fintype β] (X:β → Ω → nnreal) [M:measurable_space Ω]: (∀ b:β, measurable (X b)) → measurable (λ ω:Ω, F.elems.sum (λ b:β, ((X b) ω))) := begin have A1:decidable_eq β, { apply classical.decidable_eq, }, apply @nnreal_finset_sum_measurable Ω β M A1, end lemma nnreal_fintype_sum_measurable {Ω β:Type*} [F:fintype β] (X:β → Ω → nnreal) [M:measurable_space Ω]: (∀ b:β, measurable (X b)) → measurable (λ ω:Ω, F.elems.sum (λ b:β, ((X b) ω))) := begin have A1:decidable_eq β, { apply classical.decidable_eq, }, apply @nnreal_finset_sum_measurable Ω β M A1, end lemma nnreal_div_mul (x y:nnreal):(x/y = x * y⁻¹) := begin refl, end ----------------Measurable Sets For Inequalities --------------------------------------------------- -- These are basic results about order topologies. lemma is_closed_le_alt {α:Type*} [T:topological_space α] [P:linear_order α] [OT:order_topology α]:is_closed {p:α × α|p.fst ≤ p.snd} := begin have A1:order_closed_topology α, { apply @order_topology.to_order_closed_topology, }, apply A1.is_closed_le', end lemma is_measurable_of_le {α:Type*} [T:topological_space α] [SC:topological_space.second_countable_topology α] [P:linear_order α] [OT:order_topology α]:measurable_space.is_measurable (@prod.measurable_space α α (borel α) (borel α)) {p:α × α|p.fst ≤ p.snd} := begin apply is_closed_is_measurable_binary, apply is_closed_le_alt, end lemma is_measurable_of_eq {α:Type*} [T:topological_space α] [SC:topological_space.second_countable_topology α] [T2:t2_space α]:measurable_space.is_measurable (@prod.measurable_space α α (borel α) (borel α)) {p:α × α|p.fst = p.snd} := begin apply is_closed_is_measurable_binary, apply is_closed_diagonal, end
81068350673143c3c26c182257007c75ba7df1e6
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/tactic/interactive.lean
327e904ba35788286881674d3da1bb74a17dd488
[ "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
27,962
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Sebastien Gouezel, Scott Morrison -/ import tactic.core data.list.defs data.string.defs open lean open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic namespace interactive open interactive interactive.types expr /-- `try_for n { tac }` executes `tac` for `n` ticks, otherwise uses `sorry` to close the goal. Never fails. Useful for debugging. -/ meta def try_for (max : parse parser.pexpr) (tac : itactic) : tactic unit := do max ← i_to_expr_strict max >>= tactic.eval_expr nat, λ s, match _root_.try_for max (tac s) with | some r := r | none := (tactic.trace "try_for timeout, using sorry" >> admit) s end /-- Multiple subst. `substs x y z` is the same as `subst x, subst y, subst z`. -/ meta def substs (l : parse ident*) : tactic unit := l.mmap' (λ h, get_local h >>= tactic.subst) >> try (tactic.reflexivity reducible) /-- Unfold coercion-related definitions -/ meta def unfold_coes (loc : parse location) : tactic unit := unfold [ ``coe, ``coe_t, ``has_coe_t.coe, ``coe_b,``has_coe.coe, ``lift, ``has_lift.lift, ``lift_t, ``has_lift_t.lift, ``coe_fn, ``has_coe_to_fun.coe, ``coe_sort, ``has_coe_to_sort.coe] loc /-- Unfold auxiliary definitions associated with the current declaration. -/ meta def unfold_aux : tactic unit := do tgt ← target, name ← decl_name, let to_unfold := (tgt.list_names_with_prefix name), guard (¬ to_unfold.empty), -- should we be using simp_lemmas.mk_default? simp_lemmas.mk.dsimplify to_unfold.to_list tgt >>= tactic.change /-- For debugging only. This tactic checks the current state for any missing dropped goals and restores them. Useful when there are no goals to solve but "result contains meta-variables". -/ meta def recover : tactic unit := metavariables >>= tactic.set_goals /-- Like `try { tac }`, but in the case of failure it continues from the failure state instead of reverting to the original state. -/ meta def continue (tac : itactic) : tactic unit := λ s, result.cases_on (tac s) (λ a, result.success ()) (λ e ref, result.success ()) /-- Move goal `n` to the front. -/ meta def swap (n := 2) : tactic unit := do gs ← get_goals, match gs.nth (n-1) with | (some g) := set_goals (g :: gs.remove_nth (n-1)) | _ := skip end /-- `rotate n` cyclically shifts the goals `n` times. `rotate` defaults to `rotate 1`. -/ meta def rotate (n := 1) : tactic unit := tactic.rotate n /-- Clear all hypotheses starting with `_`, like `_match` and `_let_match`. -/ meta def clear_ : tactic unit := tactic.repeat $ do l ← local_context, l.reverse.mfirst $ λ h, do name.mk_string s p ← return $ local_pp_name h, guard (s.front = '_'), cl ← infer_type h >>= is_class, guard (¬ cl), tactic.clear h meta def apply_iff_congr_core : tactic unit := applyc ``iff_of_eq meta def congr_core' : tactic unit := do tgt ← target, apply_eq_congr_core tgt <|> apply_heq_congr_core <|> apply_iff_congr_core <|> fail "congr tactic failed" /-- Same as the `congr` tactic, but takes an optional argument which gives the depth of recursive applications. This is useful when `congr` is too aggressive in breaking down the goal. For example, given `⊢ f (g (x + y)) = f (g (y + x))`, `congr'` produces the goals `⊢ x = y` and `⊢ y = x`, while `congr' 2` produces the intended `⊢ x + y = y + x`. -/ meta def congr' : parse (with_desc "n" small_nat)? → tactic unit | (some 0) := failed | o := focus1 (assumption <|> (congr_core' >> all_goals (reflexivity <|> `[apply proof_irrel_heq] <|> `[apply proof_irrel] <|> try (congr' (nat.pred <$> o))))) /-- Acts like `have`, but removes a hypothesis with the same name as this one. For example if the state is `h : p ⊢ goal` and `f : p → q`, then after `replace h := f h` the goal will be `h : q ⊢ goal`, where `have h := f h` would result in the state `h : p, h : q ⊢ goal`. This can be used to simulate the `specialize` and `apply at` tactics of Coq. -/ meta def replace (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := do let h := h.get_or_else `this, old ← try_core (get_local h), «have» h q₁ q₂, match old, q₂ with | none, _ := skip | some o, some _ := tactic.clear o | some o, none := swap >> tactic.clear o >> swap end /-- Make every propositions in the context decidable -/ meta def classical := tactic.classical private meta def generalize_arg_p_aux : pexpr → parser (pexpr × name) | (app (app (macro _ [const `eq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def generalize_arg_p : parser (pexpr × name) := with_desc "expr = id" $ parser.pexpr 0 >>= generalize_arg_p_aux lemma {u} generalize_a_aux {α : Sort u} (h : ∀ x : Sort u, (α → x) → x) : α := h α id /-- Like `generalize` but also considers assumptions specified by the user. The user can also specify to omit the goal. -/ meta def generalize_hyp (h : parse ident?) (_ : parse $ tk ":") (p : parse generalize_arg_p) (l : parse location) : tactic unit := do h' ← get_unused_name `h, x' ← get_unused_name `x, g ← if ¬ l.include_goal then do refine ``(generalize_a_aux _), some <$> (prod.mk <$> tactic.intro x' <*> tactic.intro h') else pure none, n ← l.get_locals >>= tactic.revert_lst, generalize h () p, intron n, match g with | some (x',h') := do tactic.apply h', tactic.clear h', tactic.clear x' | none := return () end /-- Similar to `refine` but generates equality proof obligations for every discrepancy between the goal and the type of the rule. `convert e using n` (with `n : ℕ`) bounds the depth of the search for discrepancies, analogous to `congr' n`. -/ meta def convert (sym : parse (with_desc "←" (tk "<-")?)) (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit := do v ← mk_mvar, if sym.is_some then refine ``(eq.mp %%v %%r) else refine ``(eq.mpr %%v %%r), gs ← get_goals, set_goals [v], try (congr' n), gs' ← get_goals, set_goals $ gs' ++ gs meta def compact_decl_aux : list name → binder_info → expr → list expr → tactic (list (list name × binder_info × expr)) | ns bi t [] := pure [(ns.reverse, bi, t)] | ns bi t (v'@(local_const n pp bi' t') :: xs) := do t' ← infer_type v', if bi = bi' ∧ t = t' then compact_decl_aux (pp :: ns) bi t xs else do vs ← compact_decl_aux [pp] bi' t' xs, pure $ (ns.reverse, bi, t) :: vs | ns bi t (_ :: xs) := compact_decl_aux ns bi t xs meta def compact_decl : list expr → tactic (list (list name × binder_info × expr)) | [] := pure [] | (v@(local_const n pp bi t) :: xs) := do t ← infer_type v, compact_decl_aux [pp] bi t xs | (_ :: xs) := compact_decl xs meta def clean_ids : list name := [``id, ``id_rhs, ``id_delta, ``hidden] /-- Remove identity functions from a term. These are normally automatically generated with terms like `show t, from p` or `(p : t)` which translate to some variant on `@id t p` in order to retain the type. -/ meta def clean (q : parse texpr) : tactic unit := do tgt : expr ← target, e ← i_to_expr_strict ``(%%q : %%tgt), tactic.exact $ e.replace (λ e n, match e with | (app (app (const n _) _) e') := if n ∈ clean_ids then some e' else none | (app (lam _ _ _ (var 0)) e') := some e' | _ := none end) meta def source_fields (missing : list name) (e : pexpr) : tactic (list (name × pexpr)) := do e ← to_expr e, t ← infer_type e, let struct_n : name := t.get_app_fn.const_name, fields ← expanded_field_list struct_n, let exp_fields := fields.filter (λ x, x.2 ∈ missing), exp_fields.mmap $ λ ⟨p,n⟩, (prod.mk n ∘ to_pexpr) <$> mk_mapp (n.update_prefix p) [none,some e] meta def collect_struct' : pexpr → state_t (list $ expr×structure_instance_info) tactic pexpr | e := do some str ← pure (e.get_structure_instance_info) | e.traverse collect_struct', v ← monad_lift mk_mvar, modify (list.cons (v,str)), pure $ to_pexpr v meta def collect_struct (e : pexpr) : tactic $ pexpr × list (expr×structure_instance_info) := prod.map id list.reverse <$> (collect_struct' e).run [] meta def refine_one (str : structure_instance_info) : tactic $ list (expr×structure_instance_info) := do tgt ← target, let struct_n : name := tgt.get_app_fn.const_name, exp_fields ← expanded_field_list struct_n, let missing_f := exp_fields.filter (λ f, (f.2 : name) ∉ str.field_names), (src_field_names,src_field_vals) ← (@list.unzip name _ ∘ list.join) <$> str.sources.mmap (source_fields $ missing_f.map prod.snd), let provided := exp_fields.filter (λ f, (f.2 : name) ∈ str.field_names), let missing_f' := missing_f.filter (λ x, x.2 ∉ src_field_names), vs ← mk_mvar_list missing_f'.length, (field_values,new_goals) ← list.unzip <$> (str.field_values.mmap collect_struct : tactic _), e' ← to_expr $ pexpr.mk_structure_instance { struct := some struct_n , field_names := str.field_names ++ missing_f'.map prod.snd ++ src_field_names , field_values := field_values ++ vs.map to_pexpr ++ src_field_vals }, tactic.exact e', gs ← with_enable_tags ( mzip_with (λ (n : name × name) v, do set_goals [v], try (interactive.unfold (provided.map $ λ ⟨s,f⟩, f.update_prefix s) (loc.ns [none])), apply_auto_param <|> apply_opt_param <|> (set_main_tag [`_field,n.2,n.1]), get_goals) missing_f' vs), set_goals gs.join, return new_goals.join meta def refine_recursively : expr × structure_instance_info → tactic (list expr) | (e,str) := do set_goals [e], rs ← refine_one str, gs ← get_goals, gs' ← rs.mmap refine_recursively, return $ gs'.join ++ gs /-- `refine_struct { .. }` acts like `refine` but works only with structure instance literals. It creates a goal for each missing field and tags it with the name of the field so that `have_field` can be used to generically refer to the field currently being refined. As an example, we can use `refine_struct` to automate the construction semigroup instances: ``` refine_struct ( { .. } : semigroup α ), -- case semigroup, mul -- α : Type u, -- ⊢ α → α → α -- case semigroup, mul_assoc -- α : Type u, -- ⊢ ∀ (a b c : α), a * b * c = a * (b * c) ``` -/ meta def refine_struct : parse texpr → tactic unit | e := do (x,xs) ← collect_struct e, refine x, gs ← get_goals, xs' ← xs.mmap refine_recursively, set_goals (xs'.join ++ gs) /-- `guard_hyp h := t` fails if the hypothesis `h` does not have type `t`. We use this tactic for writing tests. Fixes `guard_hyp` by instantiating meta variables -/ meta def guard_hyp' (n : parse ident) (p : parse $ tk ":=" *> texpr) : tactic unit := do h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_eq h p /-- `guard_expr_strict t := e` fails if the expr `t` is not equal to `e`. By contrast to `guard_expr`, this tests strict (syntactic) equality. We use this tactic for writing tests. -/ meta def guard_expr_strict (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, guard (t = e) /-- `guard_target_strict t` fails if the target of the main goal is not syntactically `t`. We use this tactic for writing tests. -/ meta def guard_target_strict (p : parse texpr) : tactic unit := do t ← target, guard_expr_strict t p /-- `guard_hyp_strict h := t` fails if the hypothesis `h` does not have type syntactically equal to `t`. We use this tactic for writing tests. -/ meta def guard_hyp_strict (n : parse ident) (p : parse $ tk ":=" *> texpr) : tactic unit := do h ← get_local n >>= infer_type >>= instantiate_mvars, guard_expr_strict h p meta def guard_hyp_nums (n : ℕ) : tactic unit := do k ← local_context, guard (n = k.length) <|> fail format!"{k.length} hypotheses found" meta def guard_tags (tags : parse ident*) : tactic unit := do (t : list name) ← get_main_tag, guard (t = tags) /-- `success_if_fail_with_msg { tac } msg` succeeds if the interactive tactic `tac` fails with error message `msg` (for test writing purposes). -/ meta def success_if_fail_with_msg (tac : tactic.interactive.itactic) := tactic.success_if_fail_with_msg tac meta def get_current_field : tactic name := do [_,field,str] ← get_main_tag, expr.const_name <$> resolve_name (field.update_prefix str) meta def field (n : parse ident) (tac : itactic) : tactic unit := do gs ← get_goals, ts ← gs.mmap get_tag, ([g],gs') ← pure $ (list.zip gs ts).partition (λ x, x.snd.nth 1 = some n), set_goals [g.1], tac, done, set_goals $ gs'.map prod.fst /-- `have_field`, used after `refine_struct _` poses `field` as a local constant with the type of the field of the current goal: ``` refine_struct ({ .. } : semigroup α), { have_field, ... }, { have_field, ... }, ``` behaves like ``` refine_struct ({ .. } : semigroup α), { have field := @semigroup.mul, ... }, { have field := @semigroup.mul_assoc, ... }, ``` -/ meta def have_field : tactic unit := propagate_tags $ get_current_field >>= mk_const >>= note `field none >> return () /-- `apply_field` functions as `have_field, apply field, clear field` -/ meta def apply_field : tactic unit := propagate_tags $ get_current_field >>= applyc /--`apply_rules hs n`: apply the list of rules `hs` (given as pexpr) and `assumption` on the first goal and the resulting subgoals, iteratively, at most `n` times. `n` is 50 by default. `hs` can contain user attributes: in this case all theorems with this attribute are added to the list of rules. example, with or without user attribute: ``` @[user_attribute] meta def mono_rules : user_attribute := { name := `mono_rules, descr := "lemmas usable to prove monotonicity" } attribute [mono_rules] add_le_add mul_le_mul_of_nonneg_right lemma my_test {a b c d e : real} (h1 : a ≤ b) (h2 : c ≤ d) (h3 : 0 ≤ e) : a + c * e + a + c + 0 ≤ b + d * e + b + d + e := by apply_rules mono_rules -- any of the following lines would also work: -- add_le_add (add_le_add (add_le_add (add_le_add h1 (mul_le_mul_of_nonneg_right h2 h3)) h1 ) h2) h3 -- by apply_rules [add_le_add, mul_le_mul_of_nonneg_right] -- by apply_rules [mono_rules] ``` -/ meta def apply_rules (hs : parse pexpr_list_or_texpr) (n : nat := 50) : tactic unit := tactic.apply_rules hs n meta def return_cast (f : option expr) (t : option (expr × expr)) (es : list (expr × expr × expr)) (e x x' eq_h : expr) : tactic (option (expr × expr) × list (expr × expr × expr)) := (do guard (¬ e.has_var), unify x x', u ← mk_meta_univ, f ← f <|> mk_mapp ``_root_.id [(expr.sort u : expr)], t' ← infer_type e, some (f',t) ← pure t | return (some (f,t'), (e,x',eq_h) :: es), infer_type e >>= is_def_eq t, unify f f', return (some (f,t), (e,x',eq_h) :: es)) <|> return (t, es) meta def list_cast_of_aux (x : expr) (t : option (expr × expr)) (es : list (expr × expr × expr)) : expr → tactic (option (expr × expr) × list (expr × expr × expr)) | e@`(cast %%eq_h %%x') := return_cast none t es e x x' eq_h | e@`(eq.mp %%eq_h %%x') := return_cast none t es e x x' eq_h | e@`(eq.mpr %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast none t es e x x' | e@`(@eq.subst %%α %%p %%a %%b %%eq_h %%x') := return_cast p t es e x x' eq_h | e@`(@eq.substr %%α %%p %%a %%b %%eq_h %%x') := mk_eq_symm eq_h >>= return_cast p t es e x x' | e@`(@eq.rec %%α %%a %%f %%x' _ %%eq_h) := return_cast f t es e x x' eq_h | e@`(@eq.rec_on %%α %%a %%f %%b %%eq_h %%x') := return_cast f t es e x x' eq_h | e := return (t,es) meta def list_cast_of (x tgt : expr) : tactic (list (expr × expr × expr)) := (list.reverse ∘ prod.snd) <$> tgt.mfold (none, []) (λ e i es, list_cast_of_aux x es.1 es.2 e) private meta def h_generalize_arg_p_aux : pexpr → parser (pexpr × name) | (app (app (macro _ [const `heq _ ]) h) (local_const x _ _ _)) := pure (h, x) | _ := fail "parse error" private meta def h_generalize_arg_p : parser (pexpr × name) := with_desc "expr == id" $ parser.pexpr 0 >>= h_generalize_arg_p_aux /-- `h_generalize Hx : e == x` matches on `cast _ e` in the goal and replaces it with `x`. It also adds `Hx : e == x` as an assumption. If `cast _ e` appears multiple times (not necessarily with the same proof), they are all replaced by `x`. `cast` `eq.mp`, `eq.mpr`, `eq.subst`, `eq.substr`, `eq.rec` and `eq.rec_on` are all treated as casts. `h_generalize Hx : e == x with h` adds hypothesis `α = β` with `e : α, x : β`. `h_generalize Hx : e == x with _` chooses automatically chooses the name of assumption `α = β`. `h_generalize! Hx : e == x` reverts `Hx`. when `Hx` is omitted, assumption `Hx : e == x` is not added. -/ meta def h_generalize (rev : parse (tk "!")?) (h : parse ident_?) (_ : parse (tk ":")) (arg : parse h_generalize_arg_p) (eqs_h : parse ( (tk "with" >> pure <$> ident_) <|> pure [])) : tactic unit := do let (e,n) := arg, let h' := if h = `_ then none else h, h' ← (h' : tactic name) <|> get_unused_name ("h" ++ n.to_string : string), e ← to_expr e, tgt ← target, ((e,x,eq_h)::es) ← list_cast_of e tgt | fail "no cast found", interactive.generalize h' () (to_pexpr e, n), asm ← get_local h', v ← get_local n, hs ← es.mmap (λ ⟨e,_⟩, mk_app `eq [e,v]), (eqs_h.zip [e]).mmap' (λ ⟨h,e⟩, do h ← if h ≠ `_ then pure h else get_unused_name `h, () <$ note h none eq_h ), hs.mmap' (λ h, do h' ← assert `h h, tactic.exact asm, try (rewrite_target h'), tactic.clear h' ), when h.is_some (do (to_expr ``(heq_of_eq_rec_left %%eq_h %%asm) <|> to_expr ``(heq_of_eq_mp %%eq_h %%asm)) >>= note h' none >> pure ()), tactic.clear asm, when rev.is_some (interactive.revert [n]) /-- `choose a b h using hyp` takes an hypothesis `hyp` of the form `∀ (x : X) (y : Y), ∃ (a : A) (b : B), P x y a b` for some `P : X → Y → A → B → Prop` and outputs into context a function `a : X → Y → A`, `b : X → Y → B` and a proposition `h` stating `∀ (x : X) (y : Y), P x y (a x y) (b x y)`. It presumably also works with dependent versions. Example: ```lean example (h : ∀n m : ℕ, ∃i j, m = n + i ∨ m + j = n) : true := begin choose i j h using h, guard_hyp i := ℕ → ℕ → ℕ, guard_hyp j := ℕ → ℕ → ℕ, guard_hyp h := ∀ (n m : ℕ), m = n + i n m ∨ m + j n m = n, trivial end ``` -/ meta def choose (first : parse ident) (names : parse ident*) (tgt : parse (tk "using" *> texpr)?) : tactic unit := do tgt ← match tgt with | none := get_local `this | some e := tactic.i_to_expr_strict e end, tactic.choose tgt (first :: names), try (interactive.simp none tt [simp_arg_type.expr ``(exists_prop)] [] (loc.ns $ some <$> names)), try (tactic.clear tgt) meta def guard_expr_eq' (t : expr) (p : parse $ tk ":=" *> texpr) : tactic unit := do e ← to_expr p, is_def_eq t e /-- `guard_target t` fails if the target of the main goal is not `t`. We use this tactic for writing tests. -/ meta def guard_target' (p : parse texpr) : tactic unit := do t ← target, guard_expr_eq' t p /-- a weaker version of `trivial` that tries to solve the goal by reflexivity or by reducing it to true, unfolding only `reducible` constants. -/ meta def triv : tactic unit := tactic.triv' <|> tactic.reflexivity reducible <|> tactic.contradiction <|> fail "triv tactic failed" /-- Similar to `existsi`. `use x` will instantiate the first term of an `∃` or `Σ` goal with `x`. Unlike `existsi`, `x` is elaborated with respect to the expected type. `use` will alternatively take a list of terms `[x0, ..., xn]`. `use` will work with constructors of arbitrary inductive types. Examples: example (α : Type) : ∃ S : set α, S = S := by use ∅ example : ∃ x : ℤ, x = x := by use 42 example : ∃ a b c : ℤ, a + b + c = 6 := by use [1, 2, 3] example : ∃ p : ℤ × ℤ, p.1 = 1 := by use ⟨1, 42⟩ example : Σ x y : ℤ, (ℤ × ℤ) × ℤ := by use [1, 2, 3, 4, 5] inductive foo | mk : ℕ → bool × ℕ → ℕ → foo example : foo := by use [100, tt, 4, 3] -/ meta def use (l : parse pexpr_list_or_texpr) : tactic unit := tactic.use l >> try triv /-- `clear_aux_decl` clears every `aux_decl` in the local context for the current goal. This includes the induction hypothesis when using the equation compiler and `_let_match` and `_fun_match`. It is useful when using a tactic such as `finish`, `simp *` or `subst` that may use these auxiliary declarations, and produce an error saying the recursion is not well founded. -/ meta def clear_aux_decl : tactic unit := tactic.clear_aux_decl meta def loc.get_local_pp_names : loc → tactic (list name) | loc.wildcard := list.map expr.local_pp_name <$> local_context | (loc.ns l) := return l.reduce_option meta def loc.get_local_uniq_names (l : loc) : tactic (list name) := list.map expr.local_uniq_name <$> l.get_locals /-- The logic of `change x with y at l` fails when there are dependencies. `change'` mimics the behavior of `change`, except in the case of `change x with y at l`. In this case, it will correctly replace occurences of `x` with `y` at all possible hypotheses in `l`. As long as `x` and `y` are defeq, it should never fail. -/ meta def change' (q : parse texpr) : parse (tk "with" *> texpr)? → parse location → tactic unit | none (loc.ns [none]) := do e ← i_to_expr q, change_core e none | none (loc.ns [some h]) := do eq ← i_to_expr q, eh ← get_local h, change_core eq (some eh) | none _ := fail "change-at does not support multiple locations" | (some w) l := do l' ← loc.get_local_pp_names l, l'.mmap' (λ e, try (change_with_at q w e)), when l.include_goal $ change q w (loc.ns [none]) meta def convert_to_core (r : pexpr) : tactic unit := do tgt ← target, h ← to_expr ``(_ : %%tgt = %%r), rewrite_target h, swap /-- `convert_to g using n` attempts to change the current goal to `g`, using `congr' n` to resolve discrepancies. `convert_to g` defaults to using `congr' 1`. -/ meta def convert_to (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit := match n with | none := convert_to_core r >> `[congr' 1] | (some 0) := convert_to_core r | (some o) := convert_to_core r >> congr' o end /-- `ac_change g using n` is `convert_to g using n; try {ac_refl}` -/ meta def ac_change (r : parse texpr) (n : parse (tk "using" *> small_nat)?) : tactic unit := convert_to r n; try ac_refl private meta def opt_dir_with : parser (option (bool × name)) := (do tk "with", arrow ← (tk "<-")?, h ← ident, return (arrow.is_some, h)) <|> return none /-- `set a := t with h` is a variant of `let a := t`. It adds the hypothesis `h : a = t` to the local context and replaces `t` with `a` everywhere it can. `set a := t with ←h` will add `h : t = a` instead. `set! a := t with h` does not do any replacing. -/ meta def set (h_simp : parse (tk "!")?) (a : parse ident) (tp : parse ((tk ":") >> texpr)?) (_ : parse (tk ":=")) (pv : parse texpr) (rev_name : parse opt_dir_with) := do let vt := match tp with | some t := t | none := pexpr.mk_placeholder end, let pv := ``(%%pv : %%vt), v ← to_expr pv, tp ← infer_type v, definev a tp v, when h_simp.is_none $ change' pv (some (expr.const a [])) loc.wildcard, match rev_name with | some (flip, id) := do nv ← get_local a, pf ← to_expr (cond flip ``(%%pv = %%nv) ``(%%nv = %%pv)) >>= assert id, reflexivity | none := skip end /-- `clear_except h₀ h₁` deletes all the assumptions it can except for `h₀` and `h₁`. -/ meta def clear_except (xs : parse ident *) : tactic unit := do let ns := name_set.of_list xs, local_context >>= mmap' (λ h : expr, when (¬ ns.contains h.local_pp_name) $ try $ tactic.clear h) ∘ list.reverse meta def format_names (ns : list name) : format := format.join $ list.intersperse " " (ns.map to_fmt) private meta def format_binders : list name × binder_info × expr → tactic format | (ns, binder_info.default, t) := pformat!"({format_names ns} : {t})" | (ns, binder_info.implicit, t) := pformat!"{{{format_names ns} : {t}}" | (ns, binder_info.strict_implicit, t) := pformat!"⦃{format_names ns} : {t}⦄" | ([n], binder_info.inst_implicit, t) := if "_".is_prefix_of n.to_string then pformat!"[{t}]" else pformat!"[{format_names [n]} : {t}]" | (ns, binder_info.inst_implicit, t) := pformat!"[{format_names ns} : {t}]" | (ns, binder_info.aux_decl, t) := pformat!"({format_names ns} : {t})" meta def mk_paragraph_aux (right_margin : ℕ) : format → format → ℕ → list format → format | par ln len [] := par ++ format.line ++ ln | par ln len (x :: xs) := let len' := x.to_string.length in if len + len' ≤ right_margin then mk_paragraph_aux par (ln ++ x ++ " ") (len + len' + 1) xs else mk_paragraph_aux (par ++ format.line ++ ln) (" " ++ x ++ " ") len' xs /-- `mk_paragraph right_margin ls` packs `ls` into a paragraph where the lines have length at most `right_margin` -/ meta def mk_paragraph (right_margin : ℕ) : list format → format := mk_paragraph_aux right_margin "" "" 0 /-- Format the current goal as a stand-alone example. Useful for testing tactic. * `extract_goal`: formats the statement as an `example` declaration * `extract_goal my_decl`: formats the statement as a `lemma` or `def` declaration called `my_decl` * `extract_goal with i j k:` only use local constants `i`, `j`, `k` in the declaration Examples: ```lean example (i j k : ℕ) (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := begin extract_goal, -- prints: -- example {i j k : ℕ} (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := -- begin -- end extract_goal my_lemma -- lemma my_lemma {i j k : ℕ} (h₀ : i ≤ j) (h₁ : j ≤ k) : i ≤ k := -- begin -- end end example {i j k x y z w p q r m n : ℕ} (h₀ : i ≤ j) (h₁ : j ≤ k) (h₁ : k ≤ p) (h₁ : p ≤ q) : i ≤ k := begin extract_goal my_lemma, -- prints: -- lemma my_lemma {i j k x y z w p q r m n : ℕ} (h₀ : i ≤ j) (h₁ : j ≤ k) -- (h₁ : k ≤ p) (h₁ : p ≤ q) : i ≤ k := -- begin -- end extract_goal my_lemma with i j k -- prints: -- lemma my_lemma {i j k : ℕ} : i ≤ k := -- begin -- end end ``` -/ meta def extract_goal (n : parse ident?) (vs : parse with_ident_list) : tactic unit := do (cxt,_) ← solve_aux `(true) $ when (¬ vs.empty) (clear_except vs) >> local_context, tgt ← target, is_prop ← is_prop tgt, let title := match n, is_prop with | none, _ := to_fmt "example" | (some n), tt := format!"lemma {n}" | (some n), ff := format!"def {n}" end, cxt ← compact_decl cxt, cxt' ← cxt.init.mmap format_binders, cxt'' ← cxt.last'.traverse $ λ x, pformat!"{format_binders x} :", stmt ← pformat!"{tgt} :=", let fmt := mk_paragraph 80 $ title :: cxt' ++ [cxt''.get_or_else ":", stmt], trace fmt, trace!"begin\n \nend" /-- `symmetry'` behaves like `symmetry` but also offers the option `symmetry' at h` to apply symmetry to assumption `h` -/ meta def symmetry' : parse location → tactic unit | l@loc.wildcard := l.try_apply symmetry_hyp symmetry | (loc.ns hs) := (loc.ns hs.reverse).apply symmetry_hyp symmetry end interactive end tactic
cd7b4e8a0882967ac23bbbab62ea29495bd4573b
f10d66a159ce037d07005bd6021cee6bbd6d5ff0
/unique_factorization_domain.lean
76c5d3deab1af29de317e4db85358ff0a654d07b
[]
no_license
johoelzl/mason-stother
0c78bca183eb729d7f0f93e87ce073bc8cd8808d
573ecfaada288176462c03c87b80ad05bdab4644
refs/heads/master
1,631,751,973,492
1,528,923,934,000
1,528,923,934,000
109,133,224
0
1
null
null
null
null
UTF-8
Lean
false
false
48,315
lean
import data.finsupp import algebra.ring import .to_finset import .to_multiset import associated_quotient noncomputable theory local infix ^ := monoid.pow open classical local attribute [instance] prop_decidable universe u variable {α : Type u} --Would it have been smart to define units as a type that lives in Prop?? --Or would this have been pointless because a Prop cannot contain data? It could have been made with exisential quatifier, but than we are in the same situation that we are in now. /- lemma is_unit_unit {t : Type u}[h : semiring t] (u : units t) : @is_unit t h u := ⟨u, rfl⟩ -/ open associated open multiset --can the priority be set better? Because now we often have to provide parentheses local notation a `~ᵤ` b : 50 := associated a b class unique_factorization_domain (α : Type u) extends integral_domain α := (fac : ∀{x : α}, x ≠ 0 → ¬ is_unit x → ∃ p : multiset α, x = p.prod ∧ (∀x∈p, irreducible x)) (unique : ∀{f g : multiset α}, (∀x∈f, irreducible x) → (∀x∈g, irreducible x) → f.prod = g.prod → rel_multiset associated f g) --Lemma that every element not zero can be represented as a product of a unit with prod primes. lemma factorization [unique_factorization_domain α] : ∀{x : α}, x ≠ 0 → ∃ u : units α, ∃ p : multiset α, x = u*p.prod ∧ (∀x∈p, irreducible x) := begin intros x h1, by_cases h2 : (is_unit x), { rcases h2 with ⟨u, hu⟩, refine ⟨u, 0, by simp * at *⟩, }, { rcases (unique_factorization_domain.fac h1 h2) with ⟨f, hf⟩, rcases is_unit_one with ⟨u, hu⟩, refine ⟨u, f, _⟩, rwa [←hu, one_mul], } end --To prove, that a field is an instance of an unique_fac_dom /- first to prove that a field is an intergral domain: instance discrete_field.to_integral_domain [s : discrete_field α] : integral_domain α := { eq_zero_or_eq_zero_of_mul_eq_zero := discrete_field.eq_zero_or_eq_zero_of_mul_eq_zero, ..s } -/ --is there a conversion from a division ring to a group over the multiplication? namespace associated local attribute [instance] setoid -- Can we Prove the existence of a gcd here? Problem is has_dvd, why is it not defined here?? --If we can show the existence of a gcd here, we can reuse some lemmas variables {α} [unique_factorization_domain α] /- lemma irred_iff_ne_zero {a : quot α} : irred a ↔ a ≠ 0 := begin constructor, { apply quotient.induction_on a, intro a, intro h1, rw [ne.def, ← mk_def, mk_eq_zero_iff_eq_zero], have h2 : irreducible a, from h1, exact and.elim_left h1, }, end-/ lemma representation (a' : quot α) : a' ≠ 0 → ∃p : multiset (quot α), (∀a∈p, irred a) ∧ a' = p.prod := quotient.induction_on a' $ assume a, begin intro h1, have h2 : a ≠ 0, { rw [ne.def],rw [ ← mk_eq_zero_iff_eq_zero], exact h1}, have h3 : ∃ u : units α, ∃ p : multiset α, a = u*p.prod ∧ (∀x∈p, irreducible x), from factorization h2, let u := some h3, have h4: ∃ p : multiset α, a = u*p.prod ∧ (∀x∈p, irreducible x), from some_spec h3, let p := some h4, have h5: a = u*p.prod ∧ (∀x∈p, irreducible x), from some_spec h4, have h5a : a = ↑u * multiset.prod p, from and.elim_left h5, have h5b : ∀ (x : α), x ∈ p → irreducible x, from and.elim_right h5, fapply exists.intro, { exact multiset.map mk p, }, { constructor, { intros b' h6, rw multiset.mem_map at h6, let b := some h6, have h7 : b ∈ p ∧ mk b = b', from some_spec h6, have h8 : irreducible b, from h5b _ (and.elim_left h7), rw ←(and.elim_right h7), exact h8 }, { rw h5a, rw [←mk, mul_mk], simp, rw prod_mk } } end lemma some_spec_representation (a' : quot α) (h : a' ≠ 0) : (∀a∈(some (representation a' h)), irred a) ∧ a' = (some (representation a' h)).prod := some_spec (representation a' h) lemma uniqueness (p q : multiset (quot α)) (hp : ∀a∈p, irred a) (hq : ∀a∈q, irred a) (h : p.prod = q.prod) : p = q := begin by_cases h1a : (p = 0), { rw h1a at h, simp at h, have h2 : multiset.prod q = 1, from eq.symm h, rw prod_irred_quot_eq_one_iff_eq_zero hq at h2, simp *, }, { by_cases h1b : (q = 0), { rw h1b at h, simp at h, rw prod_irred_quot_eq_one_iff_eq_zero hp at h, simp *, }, { have h1 : ∃p':multiset α, p = p'.map mk, from exists_eq_map_mk p, have h2 : ∃q':multiset α, q = q'.map mk, from exists_eq_map_mk q, let p' := some h1, have h3 : p = p'.map mk, from some_spec h1, let q' := some h2, have h4 : q = q'.map mk, from some_spec h2, have h5 : p' ≠ 0, { by_contradiction h6, simp at h6, rw h6 at h3, simp at h3, contradiction, }, have h6 : q' ≠ 0, { by_contradiction h6, simp at h6, rw h6 at h4, simp at h4, contradiction, }, --attempt rw [h3, h4, prod_mk, prod_mk] at h, have h7 : (multiset.prod p' ~ᵤ multiset.prod q'), from complete h, rw associated at h7, let u := some h7, have h8 : multiset.prod p' = ↑u * multiset.prod q', from some_spec h7, have h9 : ∃ h, h ∈ q', from multiset.exists_mem_of_ne_zero h6, let h := some h9, have h10 : h ∈ q', from some_spec h9, have h11 : ∃ t, q' = h :: t, from multiset.exists_cons_of_mem h10, let t := some h11, have h12 : q' = h :: t, from some_spec h11, rw h12 at h8, simp at h8, rw ←mul_assoc at h8, let h' := ↑u * h, have h13 : ∀ (a : α), a ∈ p' → irreducible a, { intros a h1, have h13 : mk a ∈ p, { rw h3, exact multiset.mem_map_of_mem mk h1, }, exact hp _ h13, }, have h14 : ∀ (a : α), a ∈ q' → irreducible a, { intros a h1, have h14 : mk a ∈ q, { rw h4, exact multiset.mem_map_of_mem mk h1, }, exact hq _ h14, }, have h15 : multiset.prod p' = multiset.prod (h'::t), {simp [h8],}, have h16 : ∀ (a : α), a ∈ (h' :: t) → irreducible a, { intros a h1, rw multiset.mem_cons at h1, cases h1 with ha ha, rw ha, apply unit_mul_irreducible_is_irreducible', --rw is_unit, exact ⟨u, rfl⟩, exact h14 _ h10, have h16 : a ∈ h :: t, {simp [ha], }, rw ← h12 at h16, exact h14 _ h16, }, have h17 : rel_multiset associated p' (h' :: t), from unique_factorization_domain.unique h13 h16 h15, rw multiset_eq at h17, have h18 : multiset.map mk (h' :: t) = multiset.map mk q', { have h18 : mk h' = mk h, { rw mul_mk, simp, }, rw h12, simp, exact complete h18, }, rw [←h17, ← h3, ← h4] at h18, exact h18, } } end lemma prod_eq_prod_iff_eq (p q : multiset (quot α)) (hp : ∀a∈p, irred a) (hq : ∀a∈q, irred a) : p.prod = q.prod ↔ p = q := iff.intro (uniqueness p q hp hq) (assume h, h ▸ rfl) def to_multiset (a : quot α) : multiset (quot α) := if h : a = 0 then 0 else classical.some (representation a h) @[simp] lemma to_multiset_zero : to_multiset (0 : quot α) = 0 := begin simp [to_multiset] end --Name is a bit wrong should have been prod_to_multiset_eq lemma to_multiset_prod_eq (a : quot α) (h : a ≠ 0) : (to_multiset a).prod = a := begin rw to_multiset, --rw ne.def at h, simp * at *, have h1 : a = multiset.prod (some _), from and.elim_right (some_spec (representation a h)), exact eq.symm h1, end lemma to_multiset_irred' (a : quot α) (h : a ≠ 0) : ∀ x ∈ to_multiset a, irred x := begin intros x h1, have h2 : (∀ (x : quot α), x ∈ (to_multiset a) → irred x) ∧ a = multiset.prod (to_multiset a), { rw [to_multiset], simp * at *, from (some_spec (representation a h)), }, apply and.elim_left h2, exact h1, end lemma to_multiset_irred (a : quot α) : ∀x∈to_multiset a, irred x := begin by_cases h : a = 0, { simp [*] }, { exact to_multiset_irred' _ h } end @[simp] lemma to_multiset_one : to_multiset (1 : quot α) = 0 := begin by_contradiction h1, have h2 : ∃x, x ∈ (to_multiset 1), from exists_mem_of_ne_zero h1, rcases h2 with ⟨x, hx⟩, have h3 : ∃t, (to_multiset 1) = x :: t, from exists_cons_of_mem hx, rcases h3 with ⟨t, ht⟩, have h4 : irred x, from to_multiset_irred _ _ hx, have h5 : (to_multiset (1 : quot α)).prod = 1, from to_multiset_prod_eq _ (@ne.symm (quot α) _ _ zero_ne_one), rw ht at h5, simp at h5, have h6 : is_unit_quot x, from is_unit_quot_of_mul_eq_one_left h5, have : ¬ is_unit_quot x, from not_is_unit_quot_of_irred h4, contradiction, end lemma to_multiset_mul {a b : quot α} (h1 : a ≠ 0) (h2 : b ≠ 0): to_multiset (a * b) = to_multiset a + to_multiset b := begin have h3 : a * b ≠ 0, from mul_ne_zero h1 h2, have h4 : multiset.prod (to_multiset (a * b)) = a * b, from to_multiset_prod_eq _ h3, have h5 : multiset.prod (to_multiset (a)) = a, from to_multiset_prod_eq _ h1, have h6 : multiset.prod (to_multiset (b)) = b, from to_multiset_prod_eq _ h2, apply uniqueness, { apply to_multiset_irred }, { intros x h7, simp at h7, cases h7, { apply to_multiset_irred, exact h7, }, { apply to_multiset_irred, exact h7, } }, rw multiset.prod_add, simp * at *, end def inf (a b : quot α) := if a = 0 then b else if b = 0 then a else (to_multiset a ∩ to_multiset b).prod def sup (a b : quot α) := if a = 0 then 0 else if b = 0 then 0 else (to_multiset a ∪ to_multiset b).prod lemma inf_comm (a b : quot α) : inf a b = inf b a := by by_cases ha0 : a = 0; by_cases hb0 : b = 0; simp [*, inf, inter_comm] --left or right? @[simp] lemma sup_zero_eq_zero_left {a : quot α} : sup 0 a = 0 := by simp [sup] @[simp] lemma sup_zero_eq_zero_right {a : quot α} : sup a 0 = 0 := by simp [sup] lemma sup_comm {a b : quot α} : sup a b = sup b a := by by_cases ha0 : a = 0; by_cases hb0 : b = 0; simp [*, sup, union_comm] --should be le lemma prod_le_prod_iff_subset {p q : multiset (quot α)} (hp : ∀a∈p, irred a) (hq : ∀a∈q, irred a) : p.prod ≤ q.prod ↔ p ≤ q := begin constructor, { intro h1, simp only [has_le.le, preorder.le, partial_order.le] at h1, let c := some h1, have h2 : multiset.prod p * c = multiset.prod q, from some_spec h1, by_cases h3 : (c = 0), { rw h3 at h2, simp [mul_zero] at h2, by_cases h4 : (q = 0), { rw h4 at h2, simp at h2, by_contradiction h5, exact zero_ne_one h2, }, { have h5 : multiset.prod q ≠ 0, from prod_ne_zero_of_irred hq, have h6 : multiset.prod q = 0, from eq.symm h2, contradiction, } }, { have h4 : ∃p : multiset (quot α), (∀a∈p, irred a) ∧ c = p.prod, from representation _ h3, let c' := some h4, have h5 : (∀a∈c', irred a) ∧ c = c'.prod, from some_spec h4, have h5b : c = c'.prod, from and.elim_right h5, rw h5b at h2, rw ←multiset.prod_add at h2, have h6 : ∀ (a : quot α), a ∈ (p + c') → irred a, { simp, intros a h6, cases h6, exact hp a h6, exact (and.elim_left h5) a h6, }, have h7 : p + c' = q, from uniqueness _ _ h6 hq h2, rw ← h7, exact multiset.le_add_right _ _, } }, { exact prod_le_prod_of_le, } end lemma le_sup_left {a b : quot α} : a ≤ sup a b := begin by_cases ha0 : a = 0, {simp *,}, by_cases hb0 : b = 0, {simp [*, zero_is_top],}, { simp [sup, *], exact calc a = (to_multiset a).prod : eq.symm $ to_multiset_prod_eq _ ha0 ... ≤ prod (to_multiset a ∪ to_multiset b) : begin rw prod_le_prod_iff_subset, exact le_union_left _ _, exact to_multiset_irred _, intros x h, simp at *, cases h ; {apply to_multiset_irred, assumption} end } end lemma le_sup_right {a b : quot α} : b ≤ sup a b:= by rw [sup_comm]; exact le_sup_left lemma inf_le_left {a b : quot α} : inf a b ≤ a := begin by_cases ha0 : a = 0, { simp [ha0, zero_is_top] }, by_cases hb0 : b = 0, { simp [inf, *] }, { simp [inf, *], exact calc prod (to_multiset a ∩ to_multiset b) ≤ prod (to_multiset a) : by rw [prod_le_prod_iff_subset]; simp [to_multiset_irred a, multiset.inter_le_left] {contextual := tt} ... = a : to_multiset_prod_eq _ ha0 } end lemma inf_le_right {a b : quot α} : inf a b ≤ b := by rw [inf_comm]; exact inf_le_left lemma sup_le {a b c : quot α} (hab : b ≤ a) (hac : c ≤ a) : sup b c ≤ a := begin by_cases hb0 : b = 0, { simp [sup, hb0, hac] at *, assumption}, by_cases hc0 : c = 0, { simp [sup, hb0, hc0, hab] at *, assumption }, by_cases ha0 : a = 0, {simp [*, zero_is_top] at *}, simp [sup, *], rw [←to_multiset_prod_eq a ha0] at *, rw [←to_multiset_prod_eq b hb0] at hab, rw [←to_multiset_prod_eq c hc0] at hac, rw prod_le_prod_iff_subset at *, exact union_le hab hac, --union in multiset acts like the sup on our type. simp * at *, intros x h1, cases h1 ; {apply to_multiset_irred, assumption}, repeat {apply to_multiset_irred}, end lemma le_inf {a b c : quot α} (hab : a ≤ b) (hac : a ≤ c) : a ≤ inf b c := begin by_cases hb0 : b = 0, { simp [inf, hb0, hac] }, by_cases hc0 : c = 0, { simp [inf, hb0, hc0, hab] }, rcases hab with ⟨ab, hb⟩, rcases hac with ⟨ac, hc⟩, have ha0 : a ≠ 0, { intro ha0, simp [*, zero_mul] at * }, have hab0 : ab ≠ 0, { intro ha0, simp [*, mul_zero] at * }, have hac0 : ac ≠ 0, { intro ha0, simp [*, mul_zero] at * }, simp [inf, hb0, hc0], rw [← hb, ← hc, to_multiset_mul ha0 hab0, to_multiset_mul ha0 hac0, ← add_inter_distrib, ← to_multiset_prod_eq a ha0] {occs := occurrences.pos [1]}, rw [prod_le_prod_iff_subset (to_multiset_irred a)], exact multiset.le_add_right _ _, simp [or_imp_distrib, (to_multiset_irred ab)] {contextual := tt}, exact (to_multiset_irred a) end open lattice instance : bounded_lattice (quot α) := { inf := inf, inf_le_left := assume a b, inf_le_left, inf_le_right := assume a b, inf_le_right, le_inf := assume a b c, le_inf, top := 0, le_top := assume a, zero_is_top _, sup := sup, le_sup_left := assume a b, le_sup_left, le_sup_right := assume a b, le_sup_right, sup_le := assume a b c, sup_le, bot := 1, bot_le := assume a, one_le _, .. associated.partial_order } lemma sup_def {a b : quot α} : a ⊔ b = if a = 0 then 0 else if b = 0 then 0 else (to_multiset a ∪ to_multiset b).prod := rfl lemma inf_def {a b : quot α} : a ⊓ b = if a = 0 then b else if b = 0 then a else (to_multiset a ∩ to_multiset b).prod := rfl @[simp] lemma inf_zero {a : quot α} : a ⊓ 0 = a := @inf_top_eq (quot α) _ a @[simp] lemma zero_inf {a : quot α} : 0 ⊓ a = a := @top_inf_eq (quot α) _ a @[simp] lemma sup_zero {a : quot α} : a ⊔ 0 = 0 := @sup_top_eq (quot α) _ a @[simp] lemma zero_sup {a : quot α} : 0 ⊔ a = 0 := @top_sup_eq (quot α) _ a lemma mul_inf {a b c : quot α} : a * (b ⊓ c) = (a * b) ⊓ (a * c) := begin by_cases a = 0, { simp [h, zero_mul] }, have : a ≤ (a * b) ⊓ (a * c), from le_inf ⟨b, rfl⟩ ⟨c, rfl⟩, rcases this with ⟨x, hx⟩, exact le_antisymm (le_inf (mul_mono (le_refl a) inf_le_left) (mul_mono (le_refl a) inf_le_right)) begin rw [← hx], apply mul_mono (le_refl a), apply le_inf (le_of_mul_le_mul h _) (le_of_mul_le_mul h _), { rw [hx], apply inf_le_left }, { rw [hx], apply inf_le_right } end end --Easier proof then the proof above! Note that there is a latice isomorfime, from the set of multiset of irreducible elements to α excluding 0. --Can this be used for a more efficient omplementation. lemma mul_inf' {a b c : quot α} : a * (b ⊓ c) = (a * b) ⊓ (a * c) := begin by_cases ha0 : a = 0, { simp * at *,}, by_cases hb0: b = 0, {simp * at *,}, by_cases hc0: c = 0, {simp * at *,}, have hab : a * b ≠ 0, from mul_ne_zero ha0 hb0, have hac : a * c ≠ 0, from mul_ne_zero ha0 hc0, simp [inf_def, sup_def, to_multiset_mul, *], rw [multiset.add_comm (to_multiset a) _, multiset.add_comm (to_multiset a) _], rw [ ←multiset.inter_add_distrib], rw [←prod_mul_prod_eq_add_prod, to_multiset_prod_eq _ ha0, mul_comm], end lemma sup_mul_inf {a b : quot α} : (a ⊔ b) * (a ⊓ b) = a * b := begin by_cases ha0 : a = 0, {simp [*] at *}, by_cases hb0 : b = 0, {simp [*] at *}, simp [inf_def, sup_def, *], rw [←to_multiset_prod_eq a ha0, ←to_multiset_prod_eq b hb0] {occs := occurrences.pos [3]}, rw [prod_mul_prod_eq_add_prod, prod_mul_prod_eq_add_prod], simp [multiset.union_add_inter], --Again the properties from multiset carry over end --I have a duplicate of this lemma with wrong naming: see dvd_right bla bla --Do we use the case c = 0. lemma le_of_le_mul_of_le_of_inf_eq_one {a b c : quot α} (h1 : a ⊓ b = 1) (h2 : a ≤ (c * b)) : a ≤ c := begin have h4: (c * a) ⊓ (c * b) = c, { rw ←mul_inf, simp *, }, have h5 : a ≤ (c * a) ⊓ (c * b), from le_inf le_mul_left h2, simp * at *, end lemma inf_assoc {a b c : quot α} : a ⊓ b ⊓ c = a ⊓ (b ⊓ c) := lattice.inf_assoc --We need to prove the following lemma mul_inf_eq_inf_of_inf_eq_one {a b c : quot α} (h : c ⊓ b = 1) : (c * a) ⊓ b = a ⊓ b := begin apply le_antisymm, { apply @le_of_le_mul_of_le_of_inf_eq_one _ _ _ c, rw lattice.inf_comm at h, rw @inf_assoc _ _ (c * a ) b _, simp *, exact inf_bot_eq, rw [mul_comm _ c, mul_inf], apply lattice.le_inf, exact inf_le_left, have h1 : c * a ⊓ b ≤ b, from inf_le_right, apply le_trans h1, exact le_mul_left, }, exact (inf_le_inf le_mul_left (le_refl b)), end --naming?? lemma mul_le_of_le_of_le_of_coprime {a b c : quot α} (h1 : a ⊓ b = 1) (h2 : a ≤ c) (h3 : b ≤ c) : a * b ≤ c := begin rw [← sup_mul_inf], simp * at *, end lemma inf_def' {a b : quot α} : a ⊓ b = inf a b := rfl lemma inf_le_inf_mul {a b c : quot α} : a ⊓ b ≤ a ⊓ (b * c) := begin apply le_inf, exact inf_le_left, exact le_trans inf_le_right le_mul_right end lemma inf_le_mul_inf {a b c : quot α} : a ⊓ b ≤ (a * c) ⊓ b:= begin rw [@lattice.inf_comm _ _ a _, @lattice.inf_comm _ _ _ b], exact inf_le_inf_mul, end lemma inf_mul_eq_one_iff_inf_eq_one_and_inf_eq_one {a b c : quot α} : a ⊓ (b * c) = 1 ↔ (a ⊓ b = 1 ∧ a ⊓ c = 1) := begin split, { intro h, have h1 : a ⊓ b ≤ a ⊓ (b * c), from inf_le_inf_mul, have h2 : a ⊓ c ≤ a ⊓ (b * c), { rw mul_comm at *, exact inf_le_inf_mul, }, rw h at *, simp [bot_unique h1, bot_unique h2, bot_def, *] at *, }, { intro h, rw [lattice.inf_comm], rw [mul_inf_eq_inf_of_inf_eq_one] ; simp [lattice.inf_comm, *] at *, } end lemma mul_inf_eq_one_iff_inf_eq_one_and_inf_eq_one {a b c : quot α} : a * b ⊓ c = 1 ↔ (a ⊓ c = 1 ∧ b ⊓ c = 1) := begin rw [@lattice.inf_comm _ _ (a * b) c, @lattice.inf_comm _ _ a c, @lattice.inf_comm _ _ b c], exact inf_mul_eq_one_iff_inf_eq_one_and_inf_eq_one, end --le_antisymm --_ --(inf_le_inf le_mul_left (le_refl b)) lemma inf_eq_zero_iff_eq_zero_and_eq_zero {a b : quot α} : a ⊓ b = 0 ↔ a = 0 ∧ b = 0 := begin split, { by_cases ha : a = 0, {simp * at *}, by_cases hb : b = 0, {simp * at *}, simp [inf_def, *], intro h, have : prod (to_multiset a ∩ to_multiset b) ≠ 0, { apply prod_ne_zero_of_irred, intros x h1, simp at h1, apply to_multiset_irred a, exact h1.1, }, contradiction, }, { intro h, rw [h.1, h.2], simp [inf_def] } end lemma prod_to_mulitset_eq_one_iff_to_multiset_eq_zero {a : quot α} : (to_multiset a).prod = 1 ↔ (to_multiset a) = 0 := begin split, { intro h, by_contradiction h4, have : prod (to_multiset a) ≠ 1, from prod_ne_one_of_ne_zero_of_irred h4 (to_multiset_irred _), contradiction, }, { intro h, simp * at *, } end lemma to_multiset_ne_zero_of_ne_zero_of_ne_one {a : quot α} (h : a ≠ 0) (h1 : a ≠ 1): to_multiset a ≠ 0 := begin by_contradiction h2, simp at h2, have h3 : prod (to_multiset a) = a, from to_multiset_prod_eq _ h, simp * at *, end lemma to_multiset_eq_zero_iff_eq_zero_or_eq_one{a : quot α} : to_multiset a = 0 ↔ (a = 0 ∨ a = 1) := begin split, { rw [←not_imp_not, not_or_distrib], intro h, exact to_multiset_ne_zero_of_ne_zero_of_ne_one h.1 h.2, }, { intro h, cases h, simp * at *, simp * at *, } end --Should be made stronger: all factors that are in a are in b --We might delete this one, because we have a stronger statement with a smaller proof. lemma exists_mem_to_multiset_of_le {a b : quot α} (ha : a ≠ 0) (ha1 : a ≠ 1) (hb : b ≠ 0) (hb1 : b ≠ 1) (h : a ≤ b) : ∃x, x ∈ to_multiset a ∧ x ∈ to_multiset b := begin rw [le_def] at h, rcases h with ⟨c, hc⟩, by_cases h1 : c = 0, {simp * at *}, rw [←to_multiset_prod_eq a ha, ←to_multiset_prod_eq b hb, ← to_multiset_prod_eq c h1] at hc, rw [prod_mul_prod_eq_add_prod, prod_eq_prod_iff_eq] at hc, have h2 : (to_multiset a + to_multiset c).to_finset = (to_multiset b).to_finset, {simp * at *}, rw finset.ext at h2, have h3 : to_multiset a ≠ 0, from to_multiset_ne_zero_of_ne_zero_of_ne_one ha ha1, rcases (exists_mem_of_ne_zero h3) with ⟨x, hx⟩, have h4 : x ∈ to_multiset b, { rw ← hc, simp [hx], }, exact ⟨x, hx, h4⟩, {--Bad structuring simp, intros a h, cases h ; exact to_multiset_irred _ _ h, }, exact to_multiset_irred _, end --Can this one be a iff? lemma to_multiset_le_to_multiset_of_le {a b : quot α} (hb : b ≠ 0) (h : a ≤ b) : to_multiset a ≤ to_multiset b := begin by_cases ha : a = 0, {simp * at *}, { rcases h with ⟨c, hc⟩, rw [←hc, to_multiset_mul], simp, exact ha, by_contradiction h1, simp * at *, } end lemma le_of_to_multiset_le_to_multiset {a b : quot α} (ha : a ≠ 0) (h : to_multiset a ≤ to_multiset b) : a ≤ b := begin by_cases hb : b = 0, {simp [*, zero_is_top] at *,}, rw [←to_multiset_prod_eq a ha, ←to_multiset_prod_eq b hb, prod_le_prod_iff_subset], simp [*], exact to_multiset_irred _, exact to_multiset_irred _, end lemma le_iff_to_multiset_le_to_multiset_of_ne_zero_of_ne_zero {a b : quot α} (ha : a ≠ 0) (hb : b ≠ 0) : a ≤ b ↔ to_multiset a ≤ to_multiset b := iff.intro (to_multiset_le_to_multiset_of_le hb) (le_of_to_multiset_le_to_multiset ha) lemma exists_mem_to_multiset_inf_ne_zero_of_inf_ne_one {a b : quot α} (ha : a ≠ 0) (hb : b ≠ 0) (h1 : a ⊓ b ≠ 0) (h2 : a ⊓ b ≠ 1) : ∃x, x ∈ to_multiset a ∧ x ∈ to_multiset b := begin have h3 : a ⊓ b ≤ a, from inf_le_left, have h4 : a ⊓ b ≤ b, from inf_le_right, have h5 : to_multiset (a ⊓ b) ≤ to_multiset a, {rw ←le_iff_to_multiset_le_to_multiset_of_ne_zero_of_ne_zero ; assumption}, have h6 : to_multiset (a ⊓ b) ≤ to_multiset b, {rw ←le_iff_to_multiset_le_to_multiset_of_ne_zero_of_ne_zero ; assumption}, have h7 : to_multiset (a ⊓ b) ≠ 0, from to_multiset_ne_zero_of_ne_zero_of_ne_one h1 h2, rcases (exists_mem_of_ne_zero h7) with ⟨x, hx⟩, have h8 : x ∈ to_multiset a, from mem_of_le h5 hx, have h9 : x ∈ to_multiset b, from mem_of_le h6 hx, exact ⟨x, (by simp *)⟩, end --Do we need a right variant here? lemma mul_inf_eq_self {a b : quot α}: a * b ⊓ a = a := begin apply le_antisymm, apply inf_le_right, apply le_inf le_mul_right; simp, end /- We already have this one and problem in naming lemma dvd_right_of_dvd_mul_inf_eq_one [unique_factorization_domain α] {a b c : quot α} (h1 : a ≤ b * c) (h2 : a ⊓ b = 1) : a ≤ c := begin apply lattice.le_of_inf_eq, rcases h1 with ⟨d, hd⟩, have h3 : (a * d) ⊓ a = (b * c) ⊓ a, { rw hd, }, simp [mul_inf_eq_self, mul_inf_eq_inf_of_inf_eq_one h2] at h3, rw lattice.inf_comm at h2, rw [mul_inf_eq_inf_of_inf_eq_one h2, lattice.inf_comm] at h3, exact h3.symm, end -/ end associated open associated open unique_factorization_domain lemma prime_of_irreducible {α : Type u}[unique_factorization_domain α] {p : α} (h1 : irreducible p) : prime p := begin constructor, exact and.elim_left h1, constructor, exact and.elim_left (and.elim_right h1), { intros b c h2, by_cases h3 : (b = 0), { simp *}, { by_cases h4 : (c = 0), {simp *}, { by_cases h5 : (is_unit b), { have h6 : b * c ∣ c, from is_unit_mul_div h5, have h7 : p ∣ c, {exact dvd.trans h2 h6}, simp *, }, { by_cases h5b : (is_unit c), { have h6 : b * c ∣ b, from mul_is_unit_div h5b, have h7 : p ∣ b, from dvd.trans h2 h6, simp *, }, { rcases h2 with ⟨ d, h6 ⟩, by_cases h7 : (d = 0), { simp * at *, have : b * c ≠ 0, from mul_ne_zero h3 h4, contradiction, }, { by_cases h8 : (is_unit d), { revert h6, generalize h9 : p * d = p', intros h10, have h11 : irreducible p', { apply irreducible_of_associated h1, exact associated_of_mul_is_unit h8 h9, }, rw [irreducible_iff_irreducible', irreducible'] at h11, have h12 : is_unit b ∨ is_unit c, from h11.2.2 b c h10.symm, cases h12 ; contradiction, }, { rcases (fac h3 h5) with ⟨b', h9⟩, rcases (fac h4 h5b) with ⟨c', h10⟩, rcases (fac h7 h8) with ⟨d', h11⟩, rw [and.elim_left h9, and.elim_left h10, and.elim_left h11, multiset.prod_mul_prod_eq_add_prod, ← multiset.prod_cons] at h6, have h12 : ∀ x ∈ b' + c', irreducible x, { simp, intros x h12, cases h12, exact h9.right _ h12, exact h10.right _ h12, }, have h13 : ∀ (x : α), x ∈ p :: d' → irreducible x, { simp, intros x h13, cases h13, rwa h13, exact h11.right _ h13, }, have h14 : rel_multiset associated (b' + c') (p :: d'), {apply unique_factorization_domain.unique ; assumption}, have h15 : b' ≠ 0, { by_contradiction h15, simp at h15, simp [h15] at h9, have h16 : is_unit b, {simp [h9]}, contradiction, }, have h16 : ∃a' as', (b' + c') = (a' :: as') ∧ associated a' p ∧ rel_multiset associated as' d', from rel_multiset.cons_right h14, rcases h16 with ⟨e', es', h17, h18, h19⟩, have h20 : e' ∈ b' + c', {simp [h17]}, simp at h20, cases h20, { left, apply associated.dvd_of_associated h18.symm, apply dvd_of_mem_prod h9.1 h20, }, { right, apply associated.dvd_of_associated h18.symm, apply dvd_of_mem_prod h10.1 h20, } } } } } } } } end section ufd variables [unique_factorization_domain α] {a b c : α} --Instead of writing inf everywhere, could we use the symbols for the meet and the join? --Or do we want to keep inf and sup because they generalize to sets? instance unique_factorization_domain.has_gcd : has_gcd α := { gcd := assume a b : α, quot.out (inf (mk a) (mk b)), gcd_right := by simp [dvd_iff_mk_le_mk, inf_le_right], gcd_left := by simp [dvd_iff_mk_le_mk, inf_le_left], gcd_min := by simp [dvd_iff_mk_le_mk, le_inf] {contextual := tt} } @[simp] lemma mk_gcd_eq_inf : associated.mk (gcd a b) = (mk a) ⊓ (mk b) := associated.mk_quot_out lemma mul_gcd : a * gcd b c ~ᵤ gcd (a * b) (a * c) := complete $ show mk a * mk (gcd b c) = _, by simp; exact associated.mul_inf --Is in isa lib lemma gcd_mul_cancel (h1 : coprime c b) : (gcd (c * a) b ~ᵤ gcd a b) := begin rw [coprime,←mk_eq_one_iff_is_unit] at h1, apply complete, simp [mul_mk] at *, exact mul_inf_eq_inf_of_inf_eq_one h1, end lemma coprime_mul_of_coprime_of_coprime_of_coprime (h1 : coprime a c) (h2 : coprime b c ) : coprime (a * b) c := begin rw [coprime,←mk_eq_one_iff_is_unit] at *, --duplicate line with gcd_mul_cancel simp [mul_mk] at *, rw mul_inf_eq_inf_of_inf_eq_one; assumption end /- a ⊓ b = 1 b ⊓ c = 1 c ⊓ a = 1 (a * b) ⊓ c = 1 a ⊓ b = 1 (a * b) ⊓ c = (a ⊓ c) * (b ⊓ c) (a ⊔ b) ⊓ c = (a ⊓ c) ⊔ (b ⊓ c) [ (Ma + Mb) ∩ Mc ] = [ Ma ∩ Mc + Mb ∩ Mc ] a ⊓ b = 1 gcd (a * b) c = (gcd a c) * (gcd b c) -/ --open associated --lemma asso /- lemma mk_eq_zero_iff_eq_zero {a : α} : mk a = 0 ↔ a = 0:= begin split, { intro h, rw [zero_def, ←mk_def] at h, have : (a ~ᵤ 0), from complete h, rw associated_zero_iff_eq_zero at this ; assumption, }, { intro h, simp * at *, } end -/ lemma to_multiset_eq_singleton_of_irred {a : quot α} (h : irred a) : to_multiset a = a::0 := begin apply uniqueness, exact to_multiset_irred _, { intros x h1, simp [mem_singleton, *] at *, }, rw [to_multiset_prod_eq a (ne_zero_of_irred h)], simp, end lemma inf_eq_one_iff_ne_eq_of_irred_of_irred {a b : quot α} (ha : irred a) (hb : irred b) : a ⊓ b = 1 ↔ a ≠ b := begin split, { intro h, by_contradiction, simp * at *, }, { intro h, by_cases h1 : a = 0, { have h2 : a ≠ 0, from ne_zero_of_irred ha, contradiction, }, by_cases h2 : b = 0, { have h3 : b ≠ 0, from ne_zero_of_irred hb, contradiction, }, { simp [inf_def, *], rw [to_multiset_eq_singleton_of_irred ha, to_multiset_eq_singleton_of_irred hb], --Need to proof the to_multiset of a single irreducible element. have h3 : (a :: 0) ∩ (b :: 0) = 0, { apply eq_zero_of_forall_not_mem, intros x h3, simp at h3, rw [←h3.1, ←h3.2] at h, contradiction, }, simp *, } } end lemma coprime_iff_mk_inf_mk_eq_one {a b : α} : coprime a b ↔ (mk a) ⊓ (mk b) = 1 := begin split, { intro h, simp [coprime, gcd, has_gcd.gcd] at h, have h1 : is_unit_quot (inf (mk a) (mk b)), { rw ←quot.out_eq (inf (mk a) (mk b)), exact h, }, rw is_unit_quot_iff_eq_one at h1, exact h1, }, { intro h, simp [coprime, gcd, has_gcd.gcd], have h1 : inf (mk a) (mk b) = 1, --anoying, that this step needs to be made. from h, rw h1, apply is_unit_of_associated is_unit_one, apply complete, simp [one_def] } end lemma mul_dvd_of_dvd_of_dvd_of_coprime {α : Type u}{a b c: α} [unique_factorization_domain α] (h1 : coprime a b)(h2 : a ∣ c)(h3 : b ∣ c) : (a * b) ∣ c:= begin rw dvd_iff_mk_le_mk at *, rw [mul_mk], rw coprime_iff_mk_inf_mk_eq_one at h1, exact mul_le_of_le_of_le_of_coprime h1 h2 h3, end @[symm] protected lemma coprime.symm {γ : Type u} [unique_factorization_domain γ] {a b : γ} (h1: coprime a b ): coprime b a := begin rw coprime at *, apply is_unit_of_associated h1 gcd_comm end def facs_to_pow [monoid α] (p : α →₀ ℕ ) : finset α:= p.support.image (λ a, a^(p a)) --Was not consistant everywhere --I think the left should refer to the variable @[simp] lemma gcd_one_left (a : α) : (gcd 1 a ~ᵤ 1) := begin apply complete, simp [one_def'], exact lattice.bot_inf_eq, end @[simp] lemma gcd_one_right (a : α) : (gcd a 1 ~ᵤ 1) := begin apply complete, simp [one_def'], exact lattice.inf_bot_eq, end @[simp] lemma is_unit_gcd_one_left {a : α } : is_unit (gcd 1 a) := begin apply is_unit_of_associated, apply is_unit_one, apply (gcd_one_left a).symm, end @[simp] lemma is_unit_gcd_one_right {a : α } : is_unit (gcd a 1) := begin apply is_unit_of_associated is_unit_one (gcd_one_right a).symm, end lemma coprime_mul_iff_coprime_and_coprime {a b c : α} : coprime a (b * c) ↔ coprime a b ∧ coprime a c := begin repeat {rw [coprime_iff_mk_inf_mk_eq_one]}, rw mul_mk, exact inf_mul_eq_one_iff_inf_eq_one_and_inf_eq_one, end lemma coprime_pow {x y : α } {n : ℕ} (h : n ≠ 0) : coprime x (y ^ n) ↔ coprime x y := begin induction n with n ih, { contradiction, }, { by_cases hn : n = 0, simp [hn], --clear? simp only [pow_succ] at *, split, { intro h, rw coprime_mul_iff_coprime_and_coprime at h, exact h.1, }, { intro h1, rw coprime_mul_iff_coprime_and_coprime, split, exact h1, { exact (ih hn).2 h1, } } } end @[simp] lemma coprime_one_left {x : α} : coprime x 1 := begin simp [coprime], end @[simp] lemma coprime_one_right{x : α} : coprime 1 x := begin simp [coprime], end lemma coprime_pow_pow_of_coprime {x y : α}{n m : ℕ}(h : coprime x y) : coprime (x ^ n) (y ^ m) := begin by_cases h1 : n = 0, {simp [h1]}, by_cases h2 : m = 0, {simp [h2]}, { rw [coprime_pow h2], apply coprime.symm, rw [coprime_pow h1], exact h.symm, } end lemma coprime_of_irreducible_of_irreducible_of_not_associated {x y : α} (hx : irreducible x) (hy : irreducible y) (h : ¬ (x ~ᵤ y)) : coprime x y := begin rw associated_iff_mk_eq_mk at h, rw [coprime_iff_mk_inf_mk_eq_one], rw inf_eq_one_iff_ne_eq_of_irred_of_irred; assumption, end --Could have been proven using the defintion irreducible, since than gcd x y ≠ 1 would imply x ~ᵤ y which is a contradiction lemma coprime_iff_not_associated_of_irreducible_of_irreducible {x y : α} (hx : irreducible x) (hy : irreducible y) : coprime x y ↔ ¬ (x ~ᵤ y) := begin rw [coprime_iff_mk_inf_mk_eq_one, inf_eq_one_iff_ne_eq_of_irred_of_irred, associated_iff_mk_eq_mk], exact hx, exact hy, end lemma pow_mul_pow_dvd [unique_factorization_domain α] {x y z : α} {n m : ℕ} (hx : irreducible x) (hy : irreducible y) (hxz: x ^ n ∣ z) (hyz : y ^ m ∣ z) (h : ¬ (x ~ᵤ y)) : (x ^ n * y ^ m) ∣ z := begin apply @mul_dvd_of_dvd_of_dvd_of_coprime _ (x ^ n) (y ^ m) z, apply coprime_pow_pow_of_coprime, rw coprime_iff_not_associated_of_irreducible_of_irreducible, repeat {assumption}, end lemma to_multiset_prod_of_zero_not_mem {s : multiset (quot α)} (h0 : (0 : quot α) ∉ s) : to_multiset (s.prod) = (multiset.map to_multiset s).sum := begin --We need some non_zero constraint here by_cases hs : s = 0, {simp * at *}, { by_cases hs1 : s.prod = 1, { simp * at *, apply eq.symm, rw sum_map_eq_zero_iff_forall_eq_zero, intros x h1, rw to_multiset_eq_zero_iff_eq_zero_or_eq_one, rcases (exists_cons_of_mem h1) with ⟨t, ht⟩, subst ht, simp * at *, have : is_unit_quot x, from is_unit_quot_of_mul_eq_one_left hs1, rw is_unit_quot_iff_eq_one at this, simp * at *, }, { by_cases hs2 : prod s = 0, { rw prod_eq_zero_iff_zero_mem at hs2, contradiction, }, { revert hs1 hs2 hs h0, apply multiset.induction_on s, { simp * at *, }, { intros a s h1 h2 h3 h4 h5, simp * at *, rw not_or_distrib at h5, have h6 : ¬prod s = 0, { by_contradiction h6, simp * at *, }, rw to_multiset_mul (ne.symm h5.1) h6, simp, by_cases hs1 : prod s = 1, { simp * at *, --Complete duplication! apply eq.symm, rw sum_map_eq_zero_iff_forall_eq_zero, intros x h1, rw to_multiset_eq_zero_iff_eq_zero_or_eq_one, rcases (exists_cons_of_mem h1) with ⟨t, ht⟩, subst ht, simp * at *, have : is_unit_quot x, from is_unit_quot_of_mul_eq_one_left hs1, rw is_unit_quot_iff_eq_one at this, simp * at *, }, { apply h1 hs1 h6, { by_contradiction h7, simp * at *, }, exact h5.2 } } } } } end --Maybe we need a general lemma for to multiset prod? lemma to_multiset_prod_eq_of_irred {s : multiset (quot α)} (h : ∀x, x ∈ s → irred x) : (to_multiset (s.prod)) = s := begin rw to_multiset_prod_of_zero_not_mem, rw [←@sum_map_singleton _ s] {occs := occurrences.pos [2]}, apply congr_arg, apply map_congr, { intros x h1, exact to_multiset_eq_singleton_of_irred (h x h1), }, { by_contradiction h1, have : irred 0, from h _ h1, have : (0 : quot α) ≠ 0, from ne_zero_of_irred this, contradiction, } end lemma inf_prod_eq_one_iff_forall_inf_eq_one {y: quot α} {s : multiset (quot α)} : y ⊓ s.prod = 1 ↔ ∀x ∈ s, y ⊓ x = 1 := begin split, { apply multiset.induction_on s, { intros h x h1, simp * at *, }, { intros a s h1 h2 x h3, simp * at *, rw inf_mul_eq_one_iff_inf_eq_one_and_inf_eq_one at h2, cases h3, { subst h3, exact h2.1, }, { exact h1 h2.2 x h3, } } }, { apply multiset.induction_on s, { intros x, simp * at *, exact lattice.inf_bot_eq, }, { intros a t h1 h2, simp * at *, rw inf_mul_eq_one_iff_inf_eq_one_and_inf_eq_one, split, { apply h2 a, simp, }, { apply h1, intros x h, apply h2, simp *, } } } end lemma prod_inf_prod_eq_one_iff_forall_forall_inf_eq_one {t s : multiset (quot α)} : t.prod ⊓ s.prod = 1 ↔ (∀y ∈ t, (∀x ∈ s, y ⊓ x = (1 : quot α))) := begin split, { intros h y hy x hx, rw inf_prod_eq_one_iff_forall_inf_eq_one at h, have : prod t ⊓ x = 1, from h x hx, rw lattice.inf_comm at this, rw inf_prod_eq_one_iff_forall_inf_eq_one at this, have : x ⊓ y = 1, from this y hy, rw lattice.inf_comm at this, exact this, }, { intros h, rw inf_prod_eq_one_iff_forall_inf_eq_one, intros x hx, rw lattice.inf_comm, rw inf_prod_eq_one_iff_forall_inf_eq_one, intros y hy, have : y ⊓ x = 1, from h y hy x hx, rw lattice.inf_comm at this, exact this, } end --Why do we need irreucible here?? (h : ∀x ∈ s, irreducible x) lemma coprime_prod_iff_forall_coprime {y: α} {s : multiset α}: coprime y s.prod ↔ ∀x ∈ s, coprime y x := begin rw coprime_iff_mk_inf_mk_eq_one, rw [mk_def, mk_def], rw [←prod_mk], --have h4 : ∀ x, x ∈ map mk s → irred x, --from forall_map_mk_irred_of_forall_irreducible h, rw inf_prod_eq_one_iff_forall_inf_eq_one, -- h4, split, { intros h1 z h3, rw coprime_iff_mk_inf_mk_eq_one, apply h1 (mk z), rw mem_map, exact ⟨z, h3, rfl⟩, }, { intros h1 x, apply quot.induction_on x, intros a h2, rw mem_map at h2, rcases h2 with ⟨b, hb⟩, rw ←hb.2, have h2: coprime y b, from h1 b hb.1, rw coprime_iff_mk_inf_mk_eq_one at h2, exact h2, } end lemma le_of_mem_to_multiset {y : quot α} : ∀x ∈ to_multiset y, x ≤ y := begin intros x h1, by_cases h2 : y = 0, { simp * at *, }, { rw ←to_multiset_prod_eq y h2, rcases (exists_cons_of_mem h1) with ⟨t, ht⟩, rw ht, simp * at *, exact le_mul_right, } end --Problem? could be that I need it for intergral domain?? [integral_domain α] lemma facs_to_pow_prod_dvd {f : α →₀ ℕ} {z : α} (h1 : ∀x∈f.support, irreducible x ∧ (x^(f x)) ∣ z ∧ ∀y∈f.support, x ≠ y → ¬ (x ~ᵤ y)) : f.prod (λx y, x^y) ∣ z := begin revert h1, rw finsupp.prod, apply @finset.induction_on _ _ (λ b, (∀ (x : α), x ∈ b → irreducible x ∧ x ^ f x ∣ z ∧ ∀ (y : α), y ∈ b → x ≠ y → ¬(x~ᵤ y)) → finset.prod (b) (λ (a : α), a ^ f a) ∣ z) (finsupp.support f), { simp * at *, }, { intros a s h2 h3 h4, simp [finset.prod_insert h2], apply mul_dvd_of_dvd_of_dvd_of_coprime, { rw finset_prod_eq_map_prod, rw coprime_prod_iff_forall_coprime, { intros y h5, rw mem_map at h5, rcases h5 with ⟨b, hb⟩, rw ←hb.2, apply coprime_pow_pow_of_coprime, have h5 : a ∈ insert a s, {simp}, have h6 : b ∈ s, from hb.1, have h7 : b ∈ insert a s, {simp *}, have h8 : (¬(a ~ᵤ b)), { apply (h4 a h5).2.2 b h7, by_contradiction h9, simp at h9, subst h9, exact h2 h6, }, rwa coprime_iff_not_associated_of_irreducible_of_irreducible (h4 a h5).1 (h4 b h7).1, }, --admit, --separate induction prove? }, { have h5 : a ∈ insert a s, { rw finset.mem_insert, simp, }, exact (h4 a h5).2.1, }, { apply h3, intros x h5, have h6 : x ∈ insert a s, { rw finset.mem_insert, simp *, }, have h5 : irreducible x ∧ x ^ f x ∣ z ∧ ∀ (y : α), y ∈ insert a s → x ≠ y → ¬(x~ᵤ y), from h4 x h6, { split, exact h5.1, split, exact h5.2.1, intros q h6, have : q ∈ insert a s, --duplicate { rw finset.mem_insert, simp *, }, apply h5.2.2 q this, } } } end --Problem? could be that I need it for intergral domain?? [integral_domain α] lemma facs_to_pow_prod_dvd_multiset {s : multiset α} {z : α} (h1 : ∀x∈s, irreducible x ∧ (x^(count x s)) ∣ z ∧ ∀y∈s, x ≠ y → ¬ (x ~ᵤ y)) : s.prod∣ z := begin revert h1, apply multiset.induction_on s, { simp * at *, }, { intros a t h1 h2, simp * at *, have : repeat a (count a t) ≤ t, { rw ←multiset.le_count_iff_repeat_le, }, have h3 : t - repeat a (count a t) + repeat a (count a t) = t, from multiset.sub_add_cancel this, rw [←h3, ←prod_mul_prod_eq_add_prod, mul_comm a, mul_assoc], apply mul_dvd_of_dvd_of_dvd_of_coprime, { apply coprime.symm, rw [coprime_prod_iff_forall_coprime], intros x h, have : x ≠ a, { by_contradiction hc, simp at hc, subst hc, rw ←count_pos at h, have : count x (t - repeat x (count x t)) = 0, { simp [nat.sub_self], }, rw this at h, exact nat.not_lt_zero 0 h, }, rw [prod_repeat, mul_comm, ←pow_succ, ←pow_one x], apply coprime_pow_pow_of_coprime, have ht : x ∈ t, { refine mem_of_le _ h, apply multiset.sub_le_self, }, refine (coprime_iff_not_associated_of_irreducible_of_irreducible _ _).2 _, { refine (h2 a _).1, simp, }, { refine (h2 x _).1, simp *, }, { refine (h2 a _).2.2 x _ _, simp *, simp *, simp [ne.symm, *], } }, { have : prod (t - repeat a (count a t)) ∣ prod t, from prod_sub_dvd_prod _, apply dvd_trans this, apply h1, intros x h, split, { refine (h2 x _).1, simp *, }, split, { have : x ^ count x (a :: t) ∣ z, { refine (h2 x _).2.1, simp *, }, { by_cases ha : x = a, --Could be done nicer { subst ha, rw [count_cons_self, pow_succ] at this, have ha2: x ^ count x t ∣ x * x ^ count x t, from dvd.intro_left x (rfl), exact dvd_trans ha2 this, }, { rw [count_cons_of_ne ha] at this, exact this, } }, }, { intros y hy, refine (h2 x _).2.2 y _, simp *, simp *, } }, { rw [prod_repeat, mul_comm, ←pow_succ], have : a ^ count a (a :: t) ∣ z, { refine (h2 a _).2.1, simp *, }, simp at this, exact this, } } end lemma dvd_of_dvd_mul_of_coprime {a b c : α} (h1 : a ∣ b * c) (h2 : coprime a b) : a ∣ c := begin rw coprime_iff_mk_inf_mk_eq_one at h2, rw dvd_iff_mk_le_mk at *, rw [mul_mk] at h1, apply le_of_le_mul_of_le_of_inf_eq_one h2, have h3 : mk c ≤ mk b * mk c, from le_mul_left, cc, end def composite (a : α) : Prop := a ≠ 0 ∧ (∃ b c : α, (a = b * c ∧ ¬is_unit b ∧ ¬is_unit c)) --naming? --Is this needed? lemma eq_zero_or_is_unit_or_irreducible_or_composite (b : α) : b = 0 ∨ is_unit b ∨ irreducible b ∨ composite b := begin rw [or_iff_not_imp_left, or_iff_not_imp_left, or_iff_not_imp_left], intros h1 h2 h3, rw composite, rw [irreducible_iff_irreducible', irreducible'] at h3, simp at h3, simp *, have h4 : (¬∀ (a b_1 : α), b = a * b_1 → is_unit a ∨ is_unit b_1), from h3 h1 h2, rw _root_.not_forall at h4, rcases h4 with ⟨x, hx⟩, rw _root_.not_forall at hx, fapply exists.intro, exact x, rcases hx with ⟨y, hy⟩, fapply exists.intro, exact y, simp [not_or_distrib] at hy, exact hy, end /- lemma classification (a : α) : a = 0 ∨ is_unit a ∨ irreducible a ∨ composite a := begin rw [or_iff_not_imp_left, or_iff_not_imp_left, or_iff_not_imp_left], intros h1 h2 h3, by_contradiction h4, rw composite at h4, simp at h4, have h5: ∀ (x y : α), a = x * y → ¬is_unit a → is_unit x -- https://github.com/leanprover/lean/issues/1822 -/ lemma coprime_of_coprime_of_associated_left {a a' b : α} (h1 : coprime a b) (h2 : a' ~ᵤ a) : coprime a' b := begin rw coprime_iff_mk_inf_mk_eq_one at *, have : mk a' = mk a, from quot.sound h2, simp * at *, end lemma coprime_of_coprime_of_associated_right {a b b': α} (h1 : coprime a b) (h2 : b' ~ᵤ b) : coprime a b' := begin have h3 : coprime b a, from h1.symm, apply coprime.symm, exact coprime_of_coprime_of_associated_left h3 h2, end end ufd
dadd820c126499ee0684820287717c75d9b3554e
d436468d80b739ba7e06843c4d0d2070e43448e5
/src/topology/uniform_space/abstract_completion.lean
19a2150891cba34aa88c44277582b28484b030b3
[ "Apache-2.0" ]
permissive
roro47/mathlib
761fdc002aef92f77818f3fef06bf6ec6fc1a28e
80aa7d52537571a2ca62a3fdf71c9533a09422cf
refs/heads/master
1,599,656,410,625
1,573,649,488,000
1,573,649,488,000
221,452,951
0
0
Apache-2.0
1,573,647,693,000
1,573,647,692,000
null
UTF-8
Lean
false
false
11,251
lean
/- Copyright (c) 2019 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot -/ import topology.uniform_space.cauchy import topology.uniform_space.uniform_embedding /-! # Abstract theory of Hausdorff completions of uniform spaces This file characterizes Hausdorff completions of a uniform space α as complete Hausdorff spaces equipped with a map from α which has dense image and induce the original uniform structure on α. Assuming these properties we "extend" uniformly continuous maps from α to complete Hausdorff spaces to the completions of α. This is the universal property expected from a completion. It is then used to extend uniformly continuous maps from α to α' to maps between completions of α and α'. This file does not construct any such completion, it only study consequences of their existence. The first advantage is that formal properties are clearly highlighted without interference from construction details. The second advantage is that this framework can then be used to compare different completion constructions. See `topology/uniform_space/compare_reals` for an example. Of course the comparison comes from the universal property as usual. A general explicit construction of completions is done in `uniform_space/completion`, leading to a functor from uniform spaces to complete Hausdorff uniform spaces that is left adjoint to the inclusion, see `uniform_space/UniformSpace` for the category packaging. ## Implementation notes A tiny technical advantage of using a characteristic predicate such as the properties listed in `abstract_completion` instead of stating the universal property is that the universal property derived from the predicate is more universe polymorphic. ## References We don't know any traditional text discussing this. Real world mathematics simply silently identify the results of any two constructions that lead to something one could reasonnably call a completion. ## Tags uniform spaces, completion, universal property -/ noncomputable theory local attribute [instance, priority 10] classical.prop_decidable open filter set function universes u /-- A completion of `α` is the data of a complete separated uniform space (from the same universe) and a map from `α` with dense range and inducing the original uniform structure on `α`. -/ structure abstract_completion (α : Type u) [uniform_space α] := (space : Type u) (coe : α → space) (uniform_struct : uniform_space space) (complete : complete_space space) (separation : separated space) (uniform_inducing : uniform_inducing coe) (dense : dense_range coe) local attribute [instance] abstract_completion.uniform_struct abstract_completion.complete abstract_completion.separation namespace abstract_completion variables {α : Type*} [uniform_space α] (pkg : abstract_completion α) local notation `hatα` := pkg.space local notation `ι` := pkg.coe lemma dense' : closure (range ι) = univ := (dense_range_iff_closure_eq _).1 pkg.dense lemma dense_inducing : dense_inducing ι := ⟨pkg.uniform_inducing.inducing, pkg.dense⟩ lemma uniform_continuous_coe : uniform_continuous ι := uniform_inducing.uniform_continuous pkg.uniform_inducing lemma continuous_coe : continuous ι := pkg.uniform_continuous_coe.continuous @[elab_as_eliminator] lemma induction_on {p : hatα → Prop} (a : hatα) (hp : is_closed {a | p a}) (ih : ∀ a, p (ι a)) : p a := is_closed_property pkg.dense' hp ih a variables {β : Type*} [uniform_space β] protected lemma funext [t2_space β] {f g : hatα → β} (hf : continuous f) (hg : continuous g) (h : ∀ a, f (ι a) = g (ι a)) : f = g := funext $ assume a, pkg.induction_on a (is_closed_eq hf hg) h section extend /-- Extension of maps to completions -/ protected def extend (f : α → β) : hatα → β := if uniform_continuous f then pkg.dense_inducing.extend f else λ x, f (classical.inhabited_of_nonempty $ pkg.dense.nonempty.2 ⟨x⟩).default variables {f : α → β} lemma extend_def (hf : uniform_continuous f) : pkg.extend f = pkg.dense_inducing.extend f := if_pos hf lemma extend_coe [t2_space β] (hf : uniform_continuous f) (a : α) : (pkg.extend f) (ι a) = f a := begin rw pkg.extend_def hf, exact pkg.dense_inducing.extend_eq_of_cont hf.continuous a end variables [complete_space β] [separated β] lemma uniform_continuous_extend : uniform_continuous (pkg.extend f) := begin by_cases hf : uniform_continuous f, { rw pkg.extend_def hf, exact uniform_continuous_uniformly_extend (pkg.uniform_inducing) (pkg.dense) hf }, { change uniform_continuous (ite _ _ _), rw if_neg hf, exact uniform_continuous_of_const (assume a b, by congr) } end lemma continuous_extend : continuous (pkg.extend f) := pkg.uniform_continuous_extend.continuous lemma extend_unique (hf : uniform_continuous f) {g : hatα → β} (hg : uniform_continuous g) (h : ∀ a : α, f a = g (ι a)) : pkg.extend f = g := begin apply pkg.funext pkg.continuous_extend hg.continuous, simpa only [pkg.extend_coe hf] using h end @[simp] lemma extend_comp_coe {f : hatα → β} (hf : uniform_continuous f) : pkg.extend (f ∘ ι) = f := funext $ λ x, pkg.induction_on x (is_closed_eq pkg.continuous_extend hf.continuous) (λ y, pkg.extend_coe (hf.comp $ pkg.uniform_continuous_coe) y) end extend section map_sec variables (pkg' : abstract_completion β) local notation `hatβ` := pkg'.space local notation `ι'` := pkg'.coe /-- Lifting maps to completions -/ protected def map (f : α → β) : hatα → hatβ := pkg.extend (ι' ∘ f) local notation `map` := pkg.map pkg' variables (f : α → β) lemma uniform_continuous_map : uniform_continuous (map f) := pkg.uniform_continuous_extend lemma continuous_map : continuous (map f) := pkg.continuous_extend variables {f} @[simp] lemma map_coe (hf : uniform_continuous f) (a : α) : map f (ι a) = ι' (f a) := pkg.extend_coe (pkg'.uniform_continuous_coe.comp hf) a lemma map_unique {f : α → β} {g : hatα → hatβ} (hg : uniform_continuous g) (h : ∀ a, ι' (f a) = g (ι a)) : map f = g := pkg.funext (pkg.continuous_map _ _) hg.continuous $ begin intro a, change pkg.extend (ι' ∘ f) _ = _, simp only [(∘), h], rw [pkg.extend_coe (hg.comp pkg.uniform_continuous_coe)] end @[simp] lemma map_id : pkg.map pkg id = id := pkg.map_unique pkg uniform_continuous_id (assume a, rfl) variables {γ : Type*} [uniform_space γ] lemma extend_map [complete_space γ] [separated γ] {f : β → γ} {g : α → β} (hf : uniform_continuous f) (hg : uniform_continuous g) : pkg'.extend f ∘ map g = pkg.extend (f ∘ g) := pkg.funext (pkg'.continuous_extend.comp (pkg.continuous_map pkg' _)) pkg.continuous_extend $ λ a, by rw [pkg.extend_coe (hf.comp hg), comp_app, pkg.map_coe pkg' hg, pkg'.extend_coe hf] variables (pkg'' : abstract_completion γ) lemma map_comp {g : β → γ} {f : α → β} (hg : uniform_continuous g) (hf : uniform_continuous f) : (pkg'.map pkg'' g) ∘ (pkg.map pkg' f) = pkg.map pkg'' (g ∘ f) := pkg.extend_map pkg' (pkg''.uniform_continuous_coe.comp hg) hf end map_sec section compare -- We can now compare two completion packages for the same uniform space variables (pkg' : abstract_completion α) /-- The comparison map between two completions of the same uniform space. -/ def compare : pkg.space → pkg'.space := pkg.extend pkg'.coe lemma uniform_continuous_compare : uniform_continuous (pkg.compare pkg') := pkg.uniform_continuous_extend lemma compare_coe (a : α) : pkg.compare pkg' (pkg.coe a) = pkg'.coe a := pkg.extend_coe pkg'.uniform_continuous_coe a lemma inverse_compare : (pkg.compare pkg') ∘ (pkg'.compare pkg) = id := begin have uc := pkg.uniform_continuous_compare pkg', have uc' := pkg'.uniform_continuous_compare pkg, apply pkg'.funext (uc.comp uc').continuous continuous_id, intro a, rw [comp_app, pkg'.compare_coe pkg, pkg.compare_coe pkg'], refl end /-- The bijection between two completions of the same uniform space. -/ def compare_equiv : pkg.space ≃ pkg'.space := { to_fun := pkg.compare pkg', inv_fun := pkg'.compare pkg, left_inv := congr_fun (pkg'.inverse_compare pkg), right_inv := congr_fun (pkg.inverse_compare pkg') } lemma uniform_continuous_compare_equiv : uniform_continuous (pkg.compare_equiv pkg') := pkg.uniform_continuous_compare pkg' lemma uniform_continuous_compare_equiv_symm : uniform_continuous (pkg.compare_equiv pkg').symm := pkg'.uniform_continuous_compare pkg end compare section prod variables (pkg' : abstract_completion β) local notation `hatβ` := pkg'.space local notation `ι'` := pkg'.coe /-- Products of completions -/ protected def prod : abstract_completion (α × β) := { space := hatα × hatβ, coe := λ p, ⟨ι p.1, ι' p.2⟩, uniform_struct := prod.uniform_space, complete := by apply_instance, separation := by apply_instance, uniform_inducing := uniform_inducing.prod pkg.uniform_inducing pkg'.uniform_inducing, dense := dense_range_prod pkg.dense pkg'.dense } end prod section extension₂ variables (pkg' : abstract_completion β) local notation `hatβ` := pkg'.space local notation `ι'` := pkg'.coe variables {γ : Type*} [uniform_space γ] open function /-- Extend two variable map to completions. -/ protected def extend₂ (f : α → β → γ) : hatα → hatβ → γ := curry $ (pkg.prod pkg').extend (uncurry' f) variables [separated γ] {f : α → β → γ} lemma extension₂_coe_coe (hf : uniform_continuous $ uncurry' f) (a : α) (b : β) : pkg.extend₂ pkg' f (ι a) (ι' b) = f a b := show (pkg.prod pkg').extend (uncurry' f) ((pkg.prod pkg').coe (a, b)) = uncurry' f (a, b), from (pkg.prod pkg').extend_coe hf _ variables [complete_space γ] (f) lemma uniform_continuous_extension₂ : uniform_continuous₂ (pkg.extend₂ pkg' f) := begin rw [uniform_continuous₂_def, abstract_completion.extend₂, uncurry'_curry], apply uniform_continuous_extend end end extension₂ section map₂ variables (pkg' : abstract_completion β) local notation `hatβ` := pkg'.space local notation `ι'` := pkg'.coe variables {γ : Type*} [uniform_space γ] (pkg'' : abstract_completion γ) local notation `hatγ` := pkg''.space local notation `ι''` := pkg''.coe local notation f `∘₂` g := bicompr f g /-- Lift two variable maps to completions. -/ protected def map₂ (f : α → β → γ) : hatα → hatβ → hatγ := pkg.extend₂ pkg' (pkg''.coe ∘₂ f) lemma uniform_continuous_map₂ (f : α → β → γ) : uniform_continuous (uncurry' $ pkg.map₂ pkg' pkg'' f) := pkg.uniform_continuous_extension₂ pkg' _ lemma continuous_map₂ {δ} [topological_space δ] {f : α → β → γ} {a : δ → hatα} {b : δ → hatβ} (ha : continuous a) (hb : continuous b) : continuous (λd:δ, pkg.map₂ pkg' pkg'' f (a d) (b d)) := ((pkg.uniform_continuous_map₂ pkg' pkg'' f).continuous.comp (continuous.prod_mk ha hb) : _) lemma map₂_coe_coe (a : α) (b : β) (f : α → β → γ) (hf : uniform_continuous₂ f) : pkg.map₂ pkg' pkg'' f (ι a) (ι' b) = ι'' (f a b) := pkg.extension₂_coe_coe pkg' (pkg''.uniform_continuous_coe.comp hf) a b end map₂ end abstract_completion
00a79ff2423dc7776bff03e03784fb267d8e167d
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/examples/reverse-ffi/lib/RFFI.lean
b04ce923a41338d34f33622d63a1e94f3bf31104
[ "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
78
lean
@[export my_length] def myLength (s : String) : UInt64 := s.length.toUInt64
ffca2c7cad06d06aab367249729f61356798bb4a
64874bd1010548c7f5a6e3e8902efa63baaff785
/tests/lean/run/eq10.lean
2bd4bf7689262b6cde17578ee432b8be9a7be815
[ "Apache-2.0" ]
permissive
tjiaqi/lean
4634d729795c164664d10d093f3545287c76628f
d0ce4cf62f4246b0600c07e074d86e51f2195e30
refs/heads/master
1,622,323,796,480
1,422,643,069,000
1,422,643,069,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,359
lean
inductive formula := eqf : nat → nat → formula, andf : formula → formula → formula, impf : formula → formula → formula, notf : formula → formula, orf : formula → formula → formula, allf : (nat → formula) → formula namespace formula definition implies (a b : Prop) : Prop := a → b definition denote : formula → Prop, denote (eqf n1 n2) := n1 = n2, denote (andf f1 f2) := denote f1 ∧ denote f2, denote (impf f1 f2) := implies (denote f1) (denote f2), denote (orf f1 f2) := denote f1 ∨ denote f2, denote (notf f) := ¬ denote f, denote (allf f) := ∀ n : nat, denote (f n) theorem denote_eqf (n1 n2 : nat) : denote (eqf n1 n2) = (n1 = n2) := rfl theorem denote_andf (f1 f2 : formula) : denote (andf f1 f2) = (denote f1 ∧ denote f2) := rfl theorem denote_impf (f1 f2 : formula) : denote (impf f1 f2) = (denote f1 → denote f2) := rfl theorem denote_orf (f1 f2 : formula) : denote (orf f1 f2) = (denote f1 ∨ denote f2) := rfl theorem denote_notf (f : formula) : denote (notf f) = ¬ denote f := rfl theorem denote_allf (f : nat → formula) : denote (allf f) = (∀ n, denote (f n)) := rfl example : denote (allf (λ n₁, allf (λ n₂, impf (eqf n₁ n₂) (eqf n₂ n₁)))) = (∀ n₁ n₂ : nat, n₁ = n₂ → n₂ = n₁) := rfl end formula
8689c02fd998b6b28ebe3ec93e41f70871720c17
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/polynomial/content.lean
f41c140b3cd8c8d4a26ca16583a798905e44702a
[ "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
17,503
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.gcd_monoid.finset import data.polynomial.field_division import data.polynomial.erase_lead import data.polynomial.cancel_leads /-! # GCD structures on polynomials Definitions and basic results about polynomials over GCD domains, particularly their contents and primitive polynomials. ## Main Definitions Let `p : polynomial R`. - `p.content` is the `gcd` of the coefficients of `p`. - `p.is_primitive` indicates that `p.content = 1`. ## Main Results - `polynomial.content_mul`: If `p q : polynomial R`, then `(p * q).content = p.content * q.content`. - `polynomial.normalized_gcd_monoid`: The polynomial ring of a GCD domain is itself a GCD domain. -/ namespace polynomial section primitive variables {R : Type*} [comm_semiring R] /-- A polynomial is primitive when the only constant polynomials dividing it are units -/ def is_primitive (p : polynomial R) : Prop := ∀ (r : R), C r ∣ p → is_unit r lemma is_primitive_iff_is_unit_of_C_dvd {p : polynomial R} : p.is_primitive ↔ ∀ (r : R), C r ∣ p → is_unit r := iff.rfl @[simp] lemma is_primitive_one : is_primitive (1 : polynomial R) := λ r h, is_unit_C.mp (is_unit_of_dvd_one (C r) h) lemma monic.is_primitive {p : polynomial R} (hp : p.monic) : p.is_primitive := begin rintros r ⟨q, h⟩, exact is_unit_of_mul_eq_one r (q.coeff p.nat_degree) (by rwa [←coeff_C_mul, ←h]), end lemma is_primitive.ne_zero [nontrivial R] {p : polynomial R} (hp : p.is_primitive) : p ≠ 0 := begin rintro rfl, exact (hp 0 (dvd_zero (C 0))).ne_zero rfl, end end primitive variables {R : Type*} [comm_ring R] [is_domain R] section normalized_gcd_monoid variable [normalized_gcd_monoid R] /-- `p.content` is the `gcd` of the coefficients of `p`. -/ def content (p : polynomial R) : R := (p.support).gcd p.coeff lemma content_dvd_coeff {p : polynomial R} (n : ℕ) : p.content ∣ p.coeff n := begin by_cases h : n ∈ p.support, { apply finset.gcd_dvd h }, rw [mem_support_iff, not_not] at h, rw h, apply dvd_zero, end @[simp] lemma content_C {r : R} : (C r).content = normalize r := begin rw content, by_cases h0 : r = 0, { simp [h0] }, have h : (C r).support = {0} := support_monomial _ _ h0, simp [h], end @[simp] lemma content_zero : content (0 : polynomial R) = 0 := by rw [← C_0, content_C, normalize_zero] @[simp] lemma content_one : content (1 : polynomial R) = 1 := by rw [← C_1, content_C, normalize_one] lemma content_X_mul {p : polynomial R} : content (X * p) = content p := begin rw [content, content, finset.gcd_def, finset.gcd_def], refine congr rfl _, have h : (X * p).support = p.support.map ⟨nat.succ, nat.succ_injective⟩, { ext a, simp only [exists_prop, finset.mem_map, function.embedding.coe_fn_mk, ne.def, mem_support_iff], cases a, { simp [coeff_X_mul_zero, nat.succ_ne_zero] }, rw [mul_comm, coeff_mul_X], split, { intro h, use a, simp [h] }, { rintros ⟨b, ⟨h1, h2⟩⟩, rw ← nat.succ_injective h2, apply h1 } }, rw h, simp only [finset.map_val, function.comp_app, function.embedding.coe_fn_mk, multiset.map_map], refine congr (congr rfl _) rfl, ext a, rw mul_comm, simp [coeff_mul_X], end @[simp] lemma content_X_pow {k : ℕ} : content ((X : polynomial R) ^ k) = 1 := begin induction k with k hi, { simp }, rw [pow_succ, content_X_mul, hi] end @[simp] lemma content_X : content (X : polynomial R) = 1 := by { rw [← mul_one X, content_X_mul, content_one] } lemma content_C_mul (r : R) (p : polynomial R) : (C r * p).content = normalize r * p.content := begin by_cases h0 : r = 0, { simp [h0] }, rw content, rw content, rw ← finset.gcd_mul_left, refine congr (congr rfl _) _; ext; simp [h0, mem_support_iff] end @[simp] lemma content_monomial {r : R} {k : ℕ} : content (monomial k r) = normalize r := by { rw [monomial_eq_C_mul_X, content_C_mul, content_X_pow, mul_one] } lemma content_eq_zero_iff {p : polynomial R} : content p = 0 ↔ p = 0 := begin rw [content, finset.gcd_eq_zero_iff], split; intro h, { ext n, by_cases h0 : n ∈ p.support, { rw [h n h0, coeff_zero], }, { rw mem_support_iff at h0, push_neg at h0, simp [h0] } }, { intros x h0, simp [h] } end @[simp] lemma normalize_content {p : polynomial R} : normalize p.content = p.content := finset.normalize_gcd lemma content_eq_gcd_range_of_lt (p : polynomial R) (n : ℕ) (h : p.nat_degree < n) : p.content = (finset.range n).gcd p.coeff := begin apply dvd_antisymm_of_normalize_eq normalize_content finset.normalize_gcd, { rw finset.dvd_gcd_iff, intros i hi, apply content_dvd_coeff _ }, { apply finset.gcd_mono, intro i, simp only [nat.lt_succ_iff, mem_support_iff, ne.def, finset.mem_range], contrapose!, intro h1, apply coeff_eq_zero_of_nat_degree_lt (lt_of_lt_of_le h h1), } end lemma content_eq_gcd_range_succ (p : polynomial R) : p.content = (finset.range p.nat_degree.succ).gcd p.coeff := content_eq_gcd_range_of_lt _ _ (nat.lt_succ_self _) lemma content_eq_gcd_leading_coeff_content_erase_lead (p : polynomial R) : p.content = gcd_monoid.gcd p.leading_coeff (erase_lead p).content := begin by_cases h : p = 0, { simp [h] }, rw [← leading_coeff_eq_zero, leading_coeff, ← ne.def, ← mem_support_iff] at h, rw [content, ← finset.insert_erase h, finset.gcd_insert, leading_coeff, content, erase_lead_support], refine congr rfl (finset.gcd_congr rfl (λ i hi, _)), rw finset.mem_erase at hi, rw [erase_lead_coeff, if_neg hi.1], end lemma dvd_content_iff_C_dvd {p : polynomial R} {r : R} : r ∣ p.content ↔ C r ∣ p := begin rw C_dvd_iff_dvd_coeff, split, { intros h i, apply h.trans (content_dvd_coeff _) }, { intro h, rw [content, finset.dvd_gcd_iff], intros i hi, apply h i } end lemma C_content_dvd (p : polynomial R) : C p.content ∣ p := dvd_content_iff_C_dvd.1 dvd_rfl lemma is_primitive_iff_content_eq_one {p : polynomial R} : p.is_primitive ↔ p.content = 1 := begin rw [←normalize_content, normalize_eq_one, is_primitive], simp_rw [←dvd_content_iff_C_dvd], exact ⟨λ h, h p.content (dvd_refl p.content), λ h r hdvd, is_unit_of_dvd_unit hdvd h⟩, end lemma is_primitive.content_eq_one {p : polynomial R} (hp : p.is_primitive) : p.content = 1 := is_primitive_iff_content_eq_one.mp hp open_locale classical noncomputable theory section prim_part /-- The primitive part of a polynomial `p` is the primitive polynomial gained by dividing `p` by `p.content`. If `p = 0`, then `p.prim_part = 1`. -/ def prim_part (p : polynomial R) : polynomial R := if p = 0 then 1 else classical.some (C_content_dvd p) lemma eq_C_content_mul_prim_part (p : polynomial R) : p = C p.content * p.prim_part := begin by_cases h : p = 0, { simp [h] }, rw [prim_part, if_neg h, ← classical.some_spec (C_content_dvd p)], end @[simp] lemma prim_part_zero : prim_part (0 : polynomial R) = 1 := if_pos rfl lemma is_primitive_prim_part (p : polynomial R) : p.prim_part.is_primitive := begin by_cases h : p = 0, { simp [h] }, rw ← content_eq_zero_iff at h, rw is_primitive_iff_content_eq_one, apply mul_left_cancel₀ h, conv_rhs { rw [p.eq_C_content_mul_prim_part, mul_one, content_C_mul, normalize_content] } end lemma content_prim_part (p : polynomial R) : p.prim_part.content = 1 := p.is_primitive_prim_part.content_eq_one lemma prim_part_ne_zero (p : polynomial R) : p.prim_part ≠ 0 := p.is_primitive_prim_part.ne_zero lemma nat_degree_prim_part (p : polynomial R) : p.prim_part.nat_degree = p.nat_degree := begin by_cases h : C p.content = 0, { rw [C_eq_zero, content_eq_zero_iff] at h, simp [h] }, conv_rhs { rw [p.eq_C_content_mul_prim_part, nat_degree_mul h p.prim_part_ne_zero, nat_degree_C, zero_add] }, end @[simp] lemma is_primitive.prim_part_eq {p : polynomial R} (hp : p.is_primitive) : p.prim_part = p := by rw [← one_mul p.prim_part, ← C_1, ← hp.content_eq_one, ← p.eq_C_content_mul_prim_part] lemma is_unit_prim_part_C (r : R) : is_unit (C r).prim_part := begin by_cases h0 : r = 0, { simp [h0] }, unfold is_unit, refine ⟨⟨C ↑(norm_unit r)⁻¹, C ↑(norm_unit r), by rw [← ring_hom.map_mul, units.inv_mul, C_1], by rw [← ring_hom.map_mul, units.mul_inv, C_1]⟩, _⟩, rw [← normalize_eq_zero, ← C_eq_zero] at h0, apply mul_left_cancel₀ h0, conv_rhs { rw [← content_C, ← (C r).eq_C_content_mul_prim_part], }, simp only [units.coe_mk, normalize_apply, ring_hom.map_mul], rw [mul_assoc, ← ring_hom.map_mul, units.mul_inv, C_1, mul_one], end lemma prim_part_dvd (p : polynomial R) : p.prim_part ∣ p := dvd.intro_left (C p.content) p.eq_C_content_mul_prim_part.symm end prim_part lemma gcd_content_eq_of_dvd_sub {a : R} {p q : polynomial R} (h : C a ∣ p - q) : gcd_monoid.gcd a p.content = gcd_monoid.gcd a q.content := begin rw content_eq_gcd_range_of_lt p (max p.nat_degree q.nat_degree).succ (lt_of_le_of_lt (le_max_left _ _) (nat.lt_succ_self _)), rw content_eq_gcd_range_of_lt q (max p.nat_degree q.nat_degree).succ (lt_of_le_of_lt (le_max_right _ _) (nat.lt_succ_self _)), apply finset.gcd_eq_of_dvd_sub, intros x hx, cases h with w hw, use w.coeff x, rw [← coeff_sub, hw, coeff_C_mul] end lemma content_mul_aux {p q : polynomial R} : gcd_monoid.gcd (p * q).erase_lead.content p.leading_coeff = gcd_monoid.gcd (p.erase_lead * q).content p.leading_coeff := begin rw [gcd_comm (content _) _, gcd_comm (content _) _], apply gcd_content_eq_of_dvd_sub, rw [← self_sub_C_mul_X_pow, ← self_sub_C_mul_X_pow, sub_mul, sub_sub, add_comm, sub_add, sub_sub_cancel, leading_coeff_mul, ring_hom.map_mul, mul_assoc, mul_assoc], apply dvd_sub (dvd.intro _ rfl) (dvd.intro _ rfl), end @[simp] theorem content_mul {p q : polynomial R} : (p * q).content = p.content * q.content := begin classical, suffices h : ∀ (n : ℕ) (p q : polynomial R), ((p * q).degree < n) → (p * q).content = p.content * q.content, { apply h, apply (lt_of_le_of_lt degree_le_nat_degree (with_bot.coe_lt_coe.2 (nat.lt_succ_self _))) }, intro n, induction n with n ih, { intros p q hpq, rw [with_bot.coe_zero, nat.with_bot.lt_zero_iff, degree_eq_bot, mul_eq_zero] at hpq, rcases hpq with rfl | rfl; simp }, intros p q hpq, by_cases p0 : p = 0, { simp [p0] }, by_cases q0 : q = 0, { simp [q0] }, rw [degree_eq_nat_degree (mul_ne_zero p0 q0), with_bot.coe_lt_coe, nat.lt_succ_iff_lt_or_eq, ← with_bot.coe_lt_coe, ← degree_eq_nat_degree (mul_ne_zero p0 q0), nat_degree_mul p0 q0] at hpq, rcases hpq with hlt | heq, { apply ih _ _ hlt }, rw [← p.nat_degree_prim_part, ← q.nat_degree_prim_part, ← with_bot.coe_eq_coe, with_bot.coe_add, ← degree_eq_nat_degree p.prim_part_ne_zero, ← degree_eq_nat_degree q.prim_part_ne_zero] at heq, rw [p.eq_C_content_mul_prim_part, q.eq_C_content_mul_prim_part], suffices h : (q.prim_part * p.prim_part).content = 1, { rw [mul_assoc, content_C_mul, content_C_mul, mul_comm p.prim_part, mul_assoc, content_C_mul, content_C_mul, h, mul_one, content_prim_part, content_prim_part, mul_one, mul_one] }, rw [← normalize_content, normalize_eq_one, is_unit_iff_dvd_one, content_eq_gcd_leading_coeff_content_erase_lead, leading_coeff_mul, gcd_comm], apply (gcd_mul_dvd_mul_gcd _ _ _).trans, rw [content_mul_aux, ih, content_prim_part, mul_one, gcd_comm, ← content_eq_gcd_leading_coeff_content_erase_lead, content_prim_part, one_mul, mul_comm q.prim_part, content_mul_aux, ih, content_prim_part, mul_one, gcd_comm, ← content_eq_gcd_leading_coeff_content_erase_lead, content_prim_part], { rw [← heq, degree_mul, with_bot.add_lt_add_iff_right], { apply degree_erase_lt p.prim_part_ne_zero }, { rw [ne.def, degree_eq_bot], apply q.prim_part_ne_zero } }, { rw [mul_comm, ← heq, degree_mul, with_bot.add_lt_add_iff_left], { apply degree_erase_lt q.prim_part_ne_zero }, { rw [ne.def, degree_eq_bot], apply p.prim_part_ne_zero } } end theorem is_primitive.mul {p q : polynomial R} (hp : p.is_primitive) (hq : q.is_primitive) : (p * q).is_primitive := by rw [is_primitive_iff_content_eq_one, content_mul, hp.content_eq_one, hq.content_eq_one, mul_one] @[simp] theorem prim_part_mul {p q : polynomial R} (h0 : p * q ≠ 0) : (p * q).prim_part = p.prim_part * q.prim_part := begin rw [ne.def, ← content_eq_zero_iff, ← C_eq_zero] at h0, apply mul_left_cancel₀ h0, conv_lhs { rw [← (p * q).eq_C_content_mul_prim_part, p.eq_C_content_mul_prim_part, q.eq_C_content_mul_prim_part] }, rw [content_mul, ring_hom.map_mul], ring, end lemma is_primitive.is_primitive_of_dvd {p q : polynomial R} (hp : p.is_primitive) (hdvd : q ∣ p) : q.is_primitive := begin rcases hdvd with ⟨r, rfl⟩, rw [is_primitive_iff_content_eq_one, ← normalize_content, normalize_eq_one, is_unit_iff_dvd_one], apply dvd.intro r.content, rwa [is_primitive_iff_content_eq_one, content_mul] at hp, end lemma is_primitive.dvd_prim_part_iff_dvd {p q : polynomial R} (hp : p.is_primitive) (hq : q ≠ 0) : p ∣ q.prim_part ↔ p ∣ q := begin refine ⟨λ h, h.trans (dvd.intro_left _ q.eq_C_content_mul_prim_part.symm), λ h, _⟩, rcases h with ⟨r, rfl⟩, apply dvd.intro _, rw [prim_part_mul hq, hp.prim_part_eq], end theorem exists_primitive_lcm_of_is_primitive {p q : polynomial R} (hp : p.is_primitive) (hq : q.is_primitive) : ∃ r : polynomial R, r.is_primitive ∧ (∀ s : polynomial R, p ∣ s ∧ q ∣ s ↔ r ∣ s) := begin classical, have h : ∃ (n : ℕ) (r : polynomial R), r.nat_degree = n ∧ r.is_primitive ∧ p ∣ r ∧ q ∣ r := ⟨(p * q).nat_degree, p * q, rfl, hp.mul hq, dvd_mul_right _ _, dvd_mul_left _ _⟩, rcases nat.find_spec h with ⟨r, rdeg, rprim, pr, qr⟩, refine ⟨r, rprim, λ s, ⟨_, λ rs, ⟨pr.trans rs, qr.trans rs⟩⟩⟩, suffices hs : ∀ (n : ℕ) (s : polynomial R), s.nat_degree = n → (p ∣ s ∧ q ∣ s → r ∣ s), { apply hs s.nat_degree s rfl }, clear s, by_contra' con, rcases nat.find_spec con with ⟨s, sdeg, ⟨ps, qs⟩, rs⟩, have s0 : s ≠ 0, { contrapose! rs, simp [rs] }, have hs := nat.find_min' h ⟨_, s.nat_degree_prim_part, s.is_primitive_prim_part, (hp.dvd_prim_part_iff_dvd s0).2 ps, (hq.dvd_prim_part_iff_dvd s0).2 qs⟩, rw ← rdeg at hs, by_cases sC : s.nat_degree ≤ 0, { rw [eq_C_of_nat_degree_le_zero (le_trans hs sC), is_primitive_iff_content_eq_one, content_C, normalize_eq_one] at rprim, rw [eq_C_of_nat_degree_le_zero (le_trans hs sC), ← dvd_content_iff_C_dvd] at rs, apply rs rprim.dvd }, have hcancel := nat_degree_cancel_leads_lt_of_nat_degree_le_nat_degree hs (lt_of_not_ge sC), rw sdeg at hcancel, apply nat.find_min con hcancel, refine ⟨_, rfl, ⟨dvd_cancel_leads_of_dvd_of_dvd pr ps, dvd_cancel_leads_of_dvd_of_dvd qr qs⟩, λ rcs, rs _⟩, rw ← rprim.dvd_prim_part_iff_dvd s0, rw [cancel_leads, tsub_eq_zero_iff_le.mpr hs, pow_zero, mul_one] at rcs, have h := dvd_add rcs (dvd.intro_left _ rfl), have hC0 := rprim.ne_zero, rw [ne.def, ← leading_coeff_eq_zero, ← C_eq_zero] at hC0, rw [sub_add_cancel, ← rprim.dvd_prim_part_iff_dvd (mul_ne_zero hC0 s0)] at h, rcases is_unit_prim_part_C r.leading_coeff with ⟨u, hu⟩, apply h.trans (associated.symm ⟨u, _⟩).dvd, rw [prim_part_mul (mul_ne_zero hC0 s0), hu, mul_comm], end lemma dvd_iff_content_dvd_content_and_prim_part_dvd_prim_part {p q : polynomial R} (hq : q ≠ 0) : p ∣ q ↔ p.content ∣ q.content ∧ p.prim_part ∣ q.prim_part := begin split; intro h, { rcases h with ⟨r, rfl⟩, rw [content_mul, p.is_primitive_prim_part.dvd_prim_part_iff_dvd hq], exact ⟨dvd.intro _ rfl, p.prim_part_dvd.trans (dvd.intro _ rfl)⟩ }, { rw [p.eq_C_content_mul_prim_part, q.eq_C_content_mul_prim_part], exact mul_dvd_mul (ring_hom.map_dvd C h.1) h.2 } end @[priority 100] instance normalized_gcd_monoid : normalized_gcd_monoid (polynomial R) := normalized_gcd_monoid_of_exists_lcm $ λ p q, begin rcases exists_primitive_lcm_of_is_primitive p.is_primitive_prim_part q.is_primitive_prim_part with ⟨r, rprim, hr⟩, refine ⟨C (lcm p.content q.content) * r, λ s, _⟩, by_cases hs : s = 0, { simp [hs] }, by_cases hpq : C (lcm p.content q.content) = 0, { rw [C_eq_zero, lcm_eq_zero_iff, content_eq_zero_iff, content_eq_zero_iff] at hpq, rcases hpq with hpq | hpq; simp [hpq, hs] }, iterate 3 { rw dvd_iff_content_dvd_content_and_prim_part_dvd_prim_part hs }, rw [content_mul, rprim.content_eq_one, mul_one, content_C, normalize_lcm, lcm_dvd_iff, prim_part_mul (mul_ne_zero hpq rprim.ne_zero), rprim.prim_part_eq, is_unit.mul_left_dvd _ _ _ (is_unit_prim_part_C (lcm p.content q.content)), ← hr s.prim_part], tauto, end lemma degree_gcd_le_left {p : polynomial R} (hp : p ≠ 0) (q) : (gcd p q).degree ≤ p.degree := begin have := nat_degree_le_iff_degree_le.mp (nat_degree_le_of_dvd (gcd_dvd_left p q) hp), rwa degree_eq_nat_degree hp end lemma degree_gcd_le_right (p) {q : polynomial R} (hq : q ≠ 0) : (gcd p q).degree ≤ q.degree := by { rw [gcd_comm], exact degree_gcd_le_left hq p } end normalized_gcd_monoid end polynomial
955f63e7b58835af4e775986b281a3421f3c7e41
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/simpDisch.lean
6acd918764e7b3e1cc0e5d418370fe53cf3aa880
[ "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
805
lean
opaque f : Nat → Nat @[simp] axiom fEq (x : Nat) (h : x ≠ 0) : f x = x example (x : Nat) (h : x ≠ 0) : f x = x + 0 := by simp (discharger := trace_state; exact (fun h' => h') h) example (x y : Nat) (h1 : x ≠ 0) (h2 : y ≠ 0) (h3 : x = y) : f x = f y + 0 := by simp (discharger := trace_state; assumption) assumption example (x y : Nat) (h1 : x ≠ 0) (h2 : y ≠ 0) (h3 : x = y) : f x = f y + 0 := by simp (discharger := assumption) assumption example (x y : Nat) (h1 : x ≠ 0) (h2 : y ≠ 0) (h3 : x = y) : f x = f y + 0 := by simp (disch := assumption) assumption example (x y : Nat) (h1 : x ≠ 0) (h2 : y ≠ 0) (h3 : x = y) : f x = f y + 0 := by conv => lhs; simp (disch := assumption) trace_state conv => rhs; simp (disch := assumption) trace_state assumption
4c0887275f303bd4a7651cee4a991902aeabab37
fecda8e6b848337561d6467a1e30cf23176d6ad0
/src/data/mv_polynomial/rename.lean
e13c7395b668f958ecfce35a3e8d0e59b332d304
[ "Apache-2.0" ]
permissive
spolu/mathlib
bacf18c3d2a561d00ecdc9413187729dd1f705ed
480c92cdfe1cf3c2d083abded87e82162e8814f4
refs/heads/master
1,671,684,094,325
1,600,736,045,000
1,600,736,045,000
297,564,749
1
0
null
1,600,758,368,000
1,600,758,367,000
null
UTF-8
Lean
false
false
7,109
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Johan Commelin, Mario Carneiro -/ import data.mv_polynomial.variables /-! # Renaming variables of polynomials This file establishes the `rename` operation on multivariate polynomials, which modifies the set of variables. ## Main declarations * `mv_polynomial.rename` ## Notation As in other polynomial files we typically use the notation: + `σ : Type*` (indexing the variables) + `α : Type*` `[comm_semiring α]` (the coefficients) + `s : σ →₀ ℕ`, a function from `σ` to `ℕ` which is zero away from a finite set. This will give rise to a monomial in `mv_polynomial σ R` which mathematicians might call `X^s` + `a : α` + `i : σ`, with corresponding monomial `X i`, often denoted `X_i` by mathematicians + `p : mv_polynomial σ α` -/ noncomputable theory open_locale classical big_operators open set function finsupp add_monoid_algebra open_locale big_operators universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} namespace mv_polynomial variables {σ : Type*} {a a' a₁ a₂ : α} {e : ℕ} {n m : σ} {s : σ →₀ ℕ} section rename variables {α} [comm_semiring α] /-- Rename all the variables in a multivariable polynomial. -/ def rename (f : β → γ) : mv_polynomial β α →ₐ[α] mv_polynomial γ α := aeval (X ∘ f) @[simp] lemma rename_C (f : β → γ) (a : α) : rename f (C a) = C a := eval₂_C _ _ _ @[simp] lemma rename_X (f : β → γ) (b : β) : rename f (X b : mv_polynomial β α) = X (f b) := eval₂_X _ _ _ lemma map_rename [comm_semiring β] (f : α →+* β) (g : γ → δ) (p : mv_polynomial γ α) : map f (rename g p) = rename g (map f p) := mv_polynomial.induction_on p (λ a, by simp) (λ p q hp hq, by simp [hp, hq]) (λ p n hp, by simp [hp]) @[simp] lemma rename_rename (f : β → γ) (g : γ → δ) (p : mv_polynomial β α) : rename g (rename f p) = rename (g ∘ f) p := show rename g (eval₂ C (X ∘ f) p) = _, begin simp only [rename, aeval_eq_eval₂_hom], simp [eval₂_comp_left _ C (X ∘ f) p, (∘), eval₂_C, eval_X], apply eval₂_hom_congr _ rfl rfl, ext1, simp only [comp_app, ring_hom.coe_comp, eval₂_hom_C], end @[simp] lemma rename_id (p : mv_polynomial β α) : rename id p = p := eval₂_eta p lemma rename_monomial (f : β → γ) (p : β →₀ ℕ) (a : α) : rename f (monomial p a) = monomial (p.map_domain f) a := begin rw [rename, aeval_monomial, monomial_eq, finsupp.prod_map_domain_index], { refl }, { exact assume n, pow_zero _ }, { exact assume n i₁ i₂, pow_add _ _ _ } end lemma rename_eq (f : β → γ) (p : mv_polynomial β α) : rename f p = finsupp.map_domain (finsupp.map_domain f) p := begin simp only [rename, aeval_def, eval₂, finsupp.map_domain, ring_hom.coe_of], congr' with s a : 2, rw [← monomial, monomial_eq, finsupp.prod_sum_index], congr' with n i : 2, rw [finsupp.prod_single_index], exact pow_zero _, exact assume a, pow_zero _, exact assume a b c, pow_add _ _ _ end lemma rename_injective (f : β → γ) (hf : function.injective f) : function.injective (rename f : mv_polynomial β α → mv_polynomial γ α) := have (rename f : mv_polynomial β α → mv_polynomial γ α) = finsupp.map_domain (finsupp.map_domain f) := funext (rename_eq f), begin rw this, exact finsupp.map_domain_injective (finsupp.map_domain_injective hf) end lemma total_degree_rename_le (f : β → γ) (p : mv_polynomial β α) : (rename f p).total_degree ≤ p.total_degree := finset.sup_le $ assume b, begin assume h, rw rename_eq at h, have h' := finsupp.map_domain_support h, rw finset.mem_image at h', rcases h' with ⟨s, hs, rfl⟩, rw finsupp.sum_map_domain_index, exact le_trans (le_refl _) (finset.le_sup hs), exact assume _, rfl, exact assume _ _ _, rfl end section variables [comm_semiring β] (f : α →+* β) variables (k : γ → δ) (g : δ → β) (p : mv_polynomial γ α) lemma eval₂_rename : (rename k p).eval₂ f g = p.eval₂ f (g ∘ k) := by apply mv_polynomial.induction_on p; { intros, simp [*] } lemma eval₂_hom_rename : eval₂_hom f g (rename k p) = eval₂_hom f (g ∘ k) p := eval₂_rename _ _ _ _ lemma rename_eval₂ (g : δ → mv_polynomial γ α) : rename k (p.eval₂ C (g ∘ k)) = (rename k p).eval₂ C (rename k ∘ g) := by apply mv_polynomial.induction_on p; { intros, simp [*] } lemma rename_prodmk_eval₂ (d : δ) (g : γ → mv_polynomial γ α) : rename (prod.mk d) (p.eval₂ C g) = p.eval₂ C (λ x, rename (prod.mk d) (g x)) := by apply mv_polynomial.induction_on p; { intros, simp [*] } lemma eval₂_rename_prodmk (g : δ × γ → β) (d : δ) : (rename (prod.mk d) p).eval₂ f g = eval₂ f (λ i, g (d, i)) p := by apply mv_polynomial.induction_on p; { intros, simp [*] } lemma eval_rename_prodmk (g : δ × γ → α) (d : δ) : eval g (rename (prod.mk d) p) = eval (λ i, g (d, i)) p := eval₂_rename_prodmk (ring_hom.id _) _ _ _ end /-- Every polynomial is a polynomial in finitely many variables. -/ theorem exists_finset_rename (p : mv_polynomial γ α) : ∃ (s : finset γ) (q : mv_polynomial {x // x ∈ s} α), p = rename coe q := begin apply induction_on p, { intro r, exact ⟨∅, C r, by rw rename_C⟩ }, { rintro p q ⟨s, p, rfl⟩ ⟨t, q, rfl⟩, refine ⟨s ∪ t, ⟨_, _⟩⟩, { refine rename (subtype.map id _) p + rename (subtype.map id _) q; simp only [id.def, true_or, or_true, finset.mem_union, forall_true_iff] {contextual := tt}, }, { simp only [rename_rename, alg_hom.map_add], refl, }, }, { rintro p n ⟨s, p, rfl⟩, refine ⟨insert n s, ⟨_, _⟩⟩, { refine rename (subtype.map id _) p * X ⟨n, s.mem_insert_self n⟩, simp only [id.def, or_true, finset.mem_insert, forall_true_iff] {contextual := tt}, }, { simp only [rename_rename, rename_X, subtype.coe_mk, alg_hom.map_mul], refl, }, }, end /-- Every polynomial is a polynomial in finitely many variables. -/ theorem exists_fin_rename (p : mv_polynomial γ α) : ∃ (n : ℕ) (f : fin n → γ) (hf : injective f) (q : mv_polynomial (fin n) α), p = rename f q := begin obtain ⟨s, q, rfl⟩ := exists_finset_rename p, obtain ⟨n, ⟨e⟩⟩ := fintype.exists_equiv_fin {x // x ∈ s}, refine ⟨n, coe ∘ e.symm, subtype.val_injective.comp e.symm.injective, rename e q, _⟩, rw [← rename_rename, rename_rename e], simp only [function.comp, equiv.symm_apply_apply, rename_rename] end end rename lemma eval₂_cast_comp {β : Type u} {γ : Type v} (f : γ → β) {α : Type w} [comm_ring α] (c : ℤ →+* α) (g : β → α) (x : mv_polynomial γ ℤ) : eval₂ c (g ∘ f) x = eval₂ c g (rename f x) := mv_polynomial.induction_on x (λ n, by simp only [eval₂_C, rename_C]) (λ p q hp hq, by simp only [hp, hq, rename, eval₂_add, alg_hom.map_add]) (λ p n hp, by simp only [hp, rename, aeval_def, eval₂_X, eval₂_mul]) end mv_polynomial
f89c0b53566b6349e8ba45716b5a146c1348f472
8e31b9e0d8cec76b5aa1e60a240bbd557d01047c
/scratch/feasible_tableau.lean
57baa5afb48b8e2dd3599d73a6005c5400e91fc1
[]
no_license
ChrisHughes24/LP
7bdd62cb648461c67246457f3ddcb9518226dd49
e3ed64c2d1f642696104584e74ae7226d8e916de
refs/heads/master
1,685,642,642,858
1,578,070,602,000
1,578,070,602,000
195,268,102
4
3
null
1,569,229,518,000
1,562,255,287,000
Lean
UTF-8
Lean
false
false
82,831
lean
import data.matrix.pequiv data.rat.basic tactic.fin_cases data.list.min_max .partition2 import order.lexicographic open matrix fintype finset function pequiv local notation `rvec`:2000 n := matrix (fin 1) (fin n) ℚ local notation `cvec`:2000 m := matrix (fin m) (fin 1) ℚ local infix ` ⬝ `:70 := matrix.mul local postfix `ᵀ` : 1500 := transpose section universes u v variables {l m n o : Type u} [fintype l] [fintype m] [fintype n] [fintype o] {R : Type v} /- Belongs in mathlib -/ lemma mul_right_eq_of_mul_eq [semiring R] {M : matrix l m R} {N : matrix m n R} {O : matrix l n R} {P : matrix n o R} (h : M ⬝ N = O) : M ⬝ (N ⬝ P) = O ⬝ P := by rw [← matrix.mul_assoc, h] end variables {m n : ℕ} /-- The tableau consists of a matrix and a kant `const` column. `to_partition` stores the indices of the current row and column variables. `restricted` is the set of variables that are restricted to be nonnegative -/ structure tableau (m n : ℕ) extends partition m n := (to_matrix : matrix (fin m) (fin n) ℚ) (const : cvec m) --(to_partition : partition m n) (restricted : finset (fin (m + n))) namespace tableau open partition section predicates variable (T : tableau m n) /-- The affine subspace represented by the tableau ignoring nonnegativity restrictiions -/ def flat : set (cvec (m + n)) := { x | T.to_partition.rowp.to_matrix ⬝ x = T.to_matrix ⬝ T.to_partition.colp.to_matrix ⬝ x + T.const } /-- The sol_set is the subset of ℚ^(m+n) that satisifies the tableau -/ def sol_set : set (cvec (m + n)) := flat T ∩ { x | ∀ i, i ∈ T.restricted → 0 ≤ x i 0 } /-- Predicate for a variable being unbounded above in the `sol_set` -/ def is_unbounded_above (i : fin (m + n)) : Prop := ∀ q : ℚ, ∃ x : cvec (m + n), x ∈ sol_set T ∧ q ≤ x i 0 /-- Predicate for a variable being unbounded below in the `sol_set` -/ def is_unbounded_below (i : fin (m + n)) : Prop := ∀ q : ℚ, ∃ x : cvec (m + n), x ∈ sol_set T ∧ x i 0 ≤ q def is_optimal (x : cvec (m + n)) (i : fin (m + n)) : Prop := x ∈ T.sol_set ∧ ∀ y : cvec (m + n), y ∈ sol_set T → y i 0 ≤ x i 0 /-- Is this equivalent to `∀ (x : cvec (m + n)), x ∈ sol_set T → x i 0 = x j 0`? No -/ def equal_in_flat (i j : fin (m + n)) : Prop := ∀ (x : cvec (m + n)), x ∈ flat T → x i 0 = x j 0 /-- Returns an element of the `flat` after assigning values to the column variables -/ def of_col (T : tableau m n) (x : cvec n) : cvec (m + n) := T.to_partition.colp.to_matrixᵀ ⬝ x + T.to_partition.rowp.to_matrixᵀ ⬝ (T.to_matrix ⬝ x + T.const) /-- A `tableau` is feasible if its `const` column is nonnegative in restricted rows -/ def feasible : Prop := ∀ i, T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.const i 0 structure feasible_tableau (m n : ℕ) extends tableau m n := (feasible : to_tableau.feasible) instance : has_coe (feasible_tableau m n) (tableau m n) := ⟨feasible_tableau.to_tableau⟩ @[simp] lemma coe_mk (T : tableau m n) (hT : feasible T) : (feasible_tableau.mk T hT : tableau m n) = T := rfl instance : decidable_pred (@feasible m n) := λ _, by dunfold feasible; apply_instance /-- Given a row index `r` and a column index `s` it returns a tableau with `r` and `s` switched, but with the same `sol_set` -/ def pivot (r : fin m) (c : fin n) : tableau m n := let p := (T.to_matrix r c)⁻¹ in { to_matrix := λ i j, if i = r then if j = c then p else -T.to_matrix r j * p else if j = c then T.to_matrix i c * p else T.to_matrix i j - T.to_matrix i c * T.to_matrix r j * p, to_partition := T.to_partition.swap r c, const := λ i k, if i = r then -T.const r k * p else T.const i k - T.to_matrix i c * T.const r k * p, restricted := T.restricted } end predicates section predicate_lemmas variable {T : tableau m n} lemma mem_flat_iff {x : cvec (m + n)} : x ∈ T.flat ↔ ∀ r, x (T.to_partition.rowg r) 0 = univ.sum (λ c : fin n, T.to_matrix r c * x (T.to_partition.colg c) 0) + T.const r 0 := have hx : x ∈ T.flat ↔ ∀ i, (T.to_partition.rowp.to_matrix ⬝ x) i 0 = (T.to_matrix ⬝ T.to_partition.colp.to_matrix ⬝ x + T.const) i 0, by rw [flat, set.mem_set_of_eq, matrix.ext_iff.symm, forall_swap, unique.forall_iff]; refl, begin rw hx, refine forall_congr (λ i, _), rw [mul_matrix_apply, add_val, rowp_eq_some_rowg, matrix.mul_assoc, matrix.mul], conv in (T.to_matrix _ _ * (T.to_partition.colp.to_matrix ⬝ x) _ _) { rw [mul_matrix_apply, colp_eq_some_colg] }, end variable (T) @[simp] lemma colp_mul_of_col (x : cvec n) : T.to_partition.colp.to_matrix ⬝ of_col T x = x := by simp [matrix.mul_assoc, matrix.mul_add, of_col, flat, mul_right_eq_of_mul_eq (rowp_mul_colp_transpose _), mul_right_eq_of_mul_eq (rowp_mul_rowp_transpose _), mul_right_eq_of_mul_eq (colp_mul_colp_transpose _), mul_right_eq_of_mul_eq (colp_mul_rowp_transpose _)] @[simp] lemma rowp_mul_of_col (x : cvec n) : T.to_partition.rowp.to_matrix ⬝ of_col T x = T.to_matrix ⬝ x + T.const := by simp [matrix.mul_assoc, matrix.mul_add, of_col, flat, mul_right_eq_of_mul_eq (rowp_mul_colp_transpose _), mul_right_eq_of_mul_eq (rowp_mul_rowp_transpose _), mul_right_eq_of_mul_eq (colp_mul_colp_transpose _), mul_right_eq_of_mul_eq (colp_mul_rowp_transpose _)] lemma of_col_mem_flat (x : cvec n) : T.of_col x ∈ T.flat := by simp [matrix.mul_assoc, matrix.mul_add, flat] @[simp] lemma of_col_colg (x : cvec n) (c : fin n) : of_col T x (T.to_partition.colg c) = x c := funext $ λ v, calc of_col T x (T.to_partition.colg c) v = (T.to_partition.colp.to_matrix ⬝ of_col T x) c v : by rw [mul_matrix_apply, colp_eq_some_colg] ... = x c v : by rw [colp_mul_of_col] lemma of_col_rowg (c : cvec n) (r : fin m) : of_col T c (T.to_partition.rowg r) = (T.to_matrix ⬝ c + T.const) r := funext $ λ v, calc of_col T c (T.to_partition.rowg r) v = (T.to_partition.rowp.to_matrix ⬝ of_col T c) r v : by rw [mul_matrix_apply, rowp_eq_some_rowg] ... = (T.to_matrix ⬝ c + T.const) r v : by rw [rowp_mul_of_col] variable {T} lemma of_col_single_rowg {q : ℚ} {r c} {k} : T.of_col (q • (single c 0).to_matrix) (T.to_partition.rowg r) k = q * T.to_matrix r c + T.const r k:= begin fin_cases k, erw [of_col_rowg, matrix.mul_smul, matrix.add_val, matrix.smul_val, matrix_mul_apply, pequiv.symm_single_apply] end /-- Condition for the solution given by setting column index `j` to `q` and all other columns to zero being in the `sol_set` -/ lemma of_col_single_mem_sol_set {q : ℚ} {c : fin n} (hT : T.feasible) (hi : ∀ i, T.to_partition.rowg i ∈ T.restricted → 0 ≤ q * T.to_matrix i c) (hj : T.to_partition.colg c ∉ T.restricted ∨ 0 ≤ q) : T.of_col (q • (single c 0).to_matrix) ∈ T.sol_set := ⟨of_col_mem_flat _ _, λ v, (T.to_partition.eq_rowg_or_colg v).elim begin rintros ⟨r, hr⟩ hres, subst hr, rw [of_col_single_rowg], exact add_nonneg (hi _ hres) (hT _ hres) end begin rintros ⟨j, hj⟩ hres, subst hj, simp [of_col_colg, smul_val, pequiv.single, pequiv.to_matrix], by_cases hjc : j = c; simp [*, le_refl] at * end⟩ @[simp] lemma of_col_zero_mem_sol_set_iff : T.of_col 0 ∈ T.sol_set ↔ T.feasible := suffices (∀ v : fin (m + n), v ∈ T.restricted → (0 : ℚ) ≤ T.of_col 0 v 0) ↔ (∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.const i 0), by simpa [sol_set, feasible, of_col_mem_flat], ⟨λ h i hi, by simpa [of_col_rowg] using h _ hi, λ h v hv, (T.to_partition.eq_rowg_or_colg v).elim (by rintros ⟨i, hi⟩; subst hi; simp [of_col_rowg]; tauto) (by rintros ⟨j, hj⟩; subst hj; simp)⟩ lemma is_unbounded_above_colg_aux {c : fin n} (hT : T.feasible) (h : ∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.to_matrix i c) (q : ℚ): of_col T (max q 0 • (single c 0).to_matrix) ∈ sol_set T ∧ q ≤ of_col T (max q 0 • (single c 0).to_matrix) (T.to_partition.colg c) 0 := ⟨of_col_single_mem_sol_set hT (λ i hi, mul_nonneg (le_max_right _ _) (h _ hi)) (or.inr (le_max_right _ _)), by simp [of_col_colg, smul_val, pequiv.single, pequiv.to_matrix, le_refl q]⟩ /-- A column variable is unbounded above if it is in a column where every negative entry is in a row owned by an unrestricted variable -/ lemma is_unbounded_above_colg {c : fin n} (hT : T.feasible) (h : ∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.to_matrix i c) : T.is_unbounded_above (T.to_partition.colg c) := λ q, ⟨_, is_unbounded_above_colg_aux hT h q⟩ lemma is_unbounded_below_colg_aux {c : fin n} (hT : T.feasible) (hres : T.to_partition.colg c ∉ T.restricted) (h : ∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → T.to_matrix i c ≤ 0) (q : ℚ) : of_col T (min q 0 • (single c 0).to_matrix) ∈ sol_set T ∧ of_col T (min q 0 • (single c 0).to_matrix) (T.to_partition.colg c) 0 ≤ q := ⟨of_col_single_mem_sol_set hT (λ i hi, mul_nonneg_of_nonpos_of_nonpos (min_le_right _ _) (h _ hi)) (or.inl hres), by simp [of_col_colg, smul_val, pequiv.single, pequiv.to_matrix, le_refl q]⟩ /-- A column variable is unbounded below if it is unrestricted and it is in a column where every positive entry is in a row owned by an unrestricted variable -/ lemma is_unbounded_below_colg {c : fin n} (hT : T.feasible) (hres : T.to_partition.colg c ∉ T.restricted) (h : ∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → T.to_matrix i c ≤ 0) : T.is_unbounded_below (T.to_partition.colg c) := λ q, ⟨_, is_unbounded_below_colg_aux hT hres h q⟩ /-- A row variable `r` is unbounded above if it is unrestricted and there is a column `s` where every restricted row variable has a nonpositive entry in that column, and `r` has a negative entry in that column. -/ lemma is_unbounded_above_rowg_of_nonpos {r : fin m} (hT : T.feasible) (s : fin n) (hres : T.to_partition.colg s ∉ T.restricted) (h : ∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → T.to_matrix i s ≤ 0) (his : T.to_matrix r s < 0) : is_unbounded_above T (T.to_partition.rowg r) := λ q, ⟨T.of_col (min ((q - T.const r 0) / T.to_matrix r s) 0 • (single s 0).to_matrix), of_col_single_mem_sol_set hT (λ i' hi', mul_nonneg_of_nonpos_of_nonpos (min_le_right _ _) (h _ hi')) (or.inl hres), begin rw [of_col_rowg, add_val, matrix.mul_smul, smul_val, matrix_mul_apply, symm_single_apply], cases le_total 0 ((q - T.const r 0) / T.to_matrix r s) with hq hq, { rw [min_eq_right hq], rw [le_div_iff_of_neg his, zero_mul, sub_nonpos] at hq, simpa }, { rw [min_eq_left hq, div_mul_cancel _ (ne_of_lt his)], simp } end⟩ /-- A row variable `r` is unbounded above if there is a column `s` where every restricted row variable has a nonpositive entry in that column, and `r` has a positive entry in that column. -/ lemma is_unbounded_above_rowg_of_nonneg {r : fin m} (hT : T.feasible) (s : fin n) (hs : ∀ i : fin m, T.to_partition.rowg i ∈ T.restricted → 0 ≤ T.to_matrix i s) (his : 0 < T.to_matrix r s) : is_unbounded_above T (T.to_partition.rowg r) := λ q, ⟨T.of_col (max ((q - T.const r 0) / T.to_matrix r s) 0 • (single s 0).to_matrix), of_col_single_mem_sol_set hT (λ i hi, mul_nonneg (le_max_right _ _) (hs i hi)) (or.inr (le_max_right _ _)), begin rw [of_col_rowg, add_val, matrix.mul_smul, smul_val, matrix_mul_apply, symm_single_apply], cases le_total ((q - T.const r 0) / T.to_matrix r s) 0 with hq hq, { rw [max_eq_right hq], rw [div_le_iff his, zero_mul, sub_nonpos] at hq, simpa }, { rw [max_eq_left hq, div_mul_cancel _ (ne_of_gt his)], simp } end⟩ /-- The sample solution of a feasible tableau maximises the variable in row `r`, if every entry in that row is nonpositive and every entry in that row owned by a restricted variable is `0` -/ lemma is_optimal_of_col_zero {r : fin m} (hf : T.feasible) (h : ∀ j, T.to_matrix r j ≤ 0 ∧ (T.to_partition.colg j ∉ T.restricted → T.to_matrix r j = 0)) : T.is_optimal (T.of_col 0) (T.to_partition.rowg r) := ⟨of_col_zero_mem_sol_set_iff.2 hf, λ x hx, begin rw [of_col_rowg, matrix.mul_zero, zero_add, mem_flat_iff.1 hx.1], refine add_le_of_nonpos_of_le _ (le_refl _), refine sum_nonpos (λ j _, _), by_cases hj : (T.to_partition.colg j) ∈ T.restricted, { refine mul_nonpos_of_nonpos_of_nonneg (h _).1 (hx.2 _ hj) }, { rw [(h _).2 hj, _root_.zero_mul] } end⟩ lemma not_optimal_of_unbounded_above {v : fin (m + n)} {x : cvec (m + n)} (hu : is_unbounded_above T v) : ¬is_optimal T x v := λ hm, let ⟨y, hy⟩ := hu (x v 0 + 1) in not_le_of_gt (lt_add_one (x v 0)) (le_trans hy.2 (hm.2 y hy.1)) /-- Expression for the sum of all but one entries in the a row of a tableau. -/ lemma row_sum_erase_eq {x : cvec (m + n)} (hx : x ∈ T.flat) {r : fin m} {s : fin n} : (univ.erase s).sum (λ j : fin n, T.to_matrix r j * x (T.to_partition.colg j) 0) = x (T.to_partition.rowg r) 0 - T.const r 0 - T.to_matrix r s * x (T.to_partition.colg s) 0 := begin rw [mem_flat_iff] at hx, conv_rhs { rw [hx r, ← insert_erase (mem_univ s), sum_insert (not_mem_erase _ _)] }, simp end /-- An expression for a column variable in terms of row variables. -/ lemma colg_eq {x : cvec (m + n)} (hx : x ∈ T.flat) {r : fin m} {s : fin n} (hrs : T.to_matrix r s ≠ 0) : x (T.to_partition.colg s) 0 = (x (T.to_partition.rowg r) 0 -(univ.erase s).sum (λ j : fin n, T.to_matrix r j * x (T.to_partition.colg j) 0) - T.const r 0) * (T.to_matrix r s)⁻¹ := by simp [row_sum_erase_eq hx, mul_left_comm (T.to_matrix r s)⁻¹, mul_assoc, mul_left_comm (T.to_matrix r s), mul_inv_cancel hrs] /-- Another expression for a column variable in terms of row variables. -/ lemma colg_eq' {x : cvec (m + n)} (hx : x ∈ T.flat) {r : fin m} {s : fin n} (hrs : T.to_matrix r s ≠ 0) : x (T.to_partition.colg s) 0 = univ.sum (λ (j : fin n), (if j = s then (T.to_matrix r s)⁻¹ else (-(T.to_matrix r j * (T.to_matrix r s)⁻¹))) * x (colg (swap (T.to_partition) r s) j) 0) - (T.const r 0) * (T.to_matrix r s)⁻¹ := have (univ.erase s).sum (λ j : fin n, ite (j = s) (T.to_matrix r s)⁻¹ (-(T.to_matrix r j * (T.to_matrix r s)⁻¹)) * x (colg (swap (T.to_partition) r s) j) 0) = (univ.erase s).sum (λ j : fin n, -T.to_matrix r j * x (T.to_partition.colg j) 0 * (T.to_matrix r s)⁻¹), from finset.sum_congr rfl $ λ j hj, by simp [if_neg (mem_erase.1 hj).1, colg_swap_of_ne _ (mem_erase.1 hj).1, mul_comm, mul_assoc, mul_left_comm], by rw [← finset.insert_erase (mem_univ s), finset.sum_insert (not_mem_erase _ _), if_pos rfl, colg_swap, colg_eq hx hrs, this, ← finset.sum_mul]; simp [_root_.add_mul, mul_comm, _root_.mul_add] /-- Pivoting twice in the same place does nothing -/ @[simp] lemma pivot_pivot {r : fin m} {s : fin n} (hrs : T.to_matrix r s ≠ 0) : (T.pivot r s).pivot r s = T := begin cases T, simp [pivot, function.funext_iff], split; intros; split_ifs; simp [*, mul_assoc, mul_left_comm (T_to_matrix r s), mul_left_comm (T_to_matrix r s)⁻¹, mul_comm (T_to_matrix r s), inv_mul_cancel hrs] end /- These two sets are equal_in_flat, the stronger lemma is `flat_pivot` -/ private lemma subset_flat_pivot {r : fin m} {s : fin n} (h : T.to_matrix r s ≠ 0) : T.flat ⊆ (T.pivot r s).flat := λ x hx, have ∀ i : fin m, (univ.erase s).sum (λ j : fin n, ite (j = s) (T.to_matrix i s * (T.to_matrix r s)⁻¹) (T.to_matrix i j + -(T.to_matrix i s * T.to_matrix r j * (T.to_matrix r s)⁻¹)) * x ((T.to_partition.swap r s).colg j) 0) = (univ.erase s).sum (λ j : fin n, T.to_matrix i j * x (T.to_partition.colg j) 0 - T.to_matrix r j * x (T.to_partition.colg j) 0 * T.to_matrix i s * (T.to_matrix r s)⁻¹), from λ i, finset.sum_congr rfl (λ j hj, by rw [if_neg (mem_erase.1 hj).1, colg_swap_of_ne _ (mem_erase.1 hj).1]; simp [mul_add, add_mul, mul_comm, mul_assoc, mul_left_comm]), begin rw mem_flat_iff, assume i, by_cases hir : i = r, { rw eq_comm at hir, subst hir, dsimp [pivot], simp [mul_inv_cancel h, neg_mul_eq_neg_mul_symm, if_true, add_comm, mul_inv_cancel, rowg_swap, eq_self_iff_true, colg_eq' hx h], congr, funext, congr }, { dsimp [pivot], simp only [if_neg hir], rw [← insert_erase (mem_univ s), sum_insert (not_mem_erase _ _), if_pos rfl, colg_swap, this, sum_sub_distrib, ← sum_mul, ← sum_mul, row_sum_erase_eq hx, rowg_swap_of_ne _ hir], simp [row_sum_erase_eq hx, mul_add, add_mul, mul_comm, mul_left_comm, mul_assoc], simp [mul_assoc, mul_left_comm (T.to_matrix r s), mul_left_comm (T.to_matrix r s)⁻¹, mul_comm (T.to_matrix r s), inv_mul_cancel h] } end variable (T) @[simp] lemma pivot_pivot_element (r : fin m) (s : fin n) : (T.pivot r s).to_matrix r s = (T.to_matrix r s)⁻¹ := by simp [pivot, if_pos rfl] @[simp] lemma pivot_pivot_row {r : fin m} {j s : fin n} (h : j ≠ s) : (T.pivot r s).to_matrix r j = -T.to_matrix r j / T.to_matrix r s := by dsimp [pivot]; rw [if_pos rfl, if_neg h, div_eq_mul_inv] @[simp] lemma pivot_pivot_column {i r : fin m} {s : fin n} (h : i ≠ r) : (T.pivot r s).to_matrix i s = T.to_matrix i s / T.to_matrix r s := by dsimp [pivot]; rw [if_neg h, if_pos rfl, div_eq_mul_inv] @[simp] lemma pivot_of_ne_of_ne {i r : fin m} {j s : fin n} (hir : i ≠ r) (hjs : j ≠ s) : (T.pivot r s).to_matrix i j = T.to_matrix i j - T.to_matrix i s * T.to_matrix r j / T.to_matrix r s := by dsimp [pivot]; rw [if_neg hir, if_neg hjs, div_eq_mul_inv] @[simp] lemma const_pivot_row {r : fin m} {s : fin n} : (T.pivot r s).const r 0 = -T.const r 0 / T.to_matrix r s := by simp [pivot, if_pos rfl, div_eq_mul_inv] @[simp] lemma const_pivot_of_ne {i r : fin m} {s : fin n} (hir : i ≠ r) : (T.pivot r s).const i 0 = T.const i 0 - T.to_matrix i s * T.const r 0 / T.to_matrix r s := by dsimp [pivot]; rw [if_neg hir, div_eq_mul_inv] @[simp] lemma restricted_pivot (r s) : (T.pivot r s).restricted = T.restricted := rfl @[simp] lemma to_partition_pivot (r s) : (T.pivot r s).to_partition = T.to_partition.swap r s := rfl variable {T} @[simp] lemma flat_pivot {r : fin m} {s : fin n} (hrs : T.to_matrix r s ≠ 0) : (T.pivot r s).flat = T.flat := set.subset.antisymm (by conv_rhs { rw ← pivot_pivot hrs }; exact subset_flat_pivot (by simp [hrs])) (subset_flat_pivot hrs) @[simp] lemma sol_set_pivot {r : fin m} {s : fin n} (hrs : T.to_matrix r s ≠ 0) : (T.pivot r s).sol_set = T.sol_set := by rw [sol_set, flat_pivot hrs]; refl /-- Two row variables are `equal_in_flat` iff the corresponding rows of the tableau are equal -/ lemma equal_in_flat_row_row {i i' : fin m} : T.equal_in_flat (T.to_partition.rowg i) (T.to_partition.rowg i') ↔ (T.const i 0 = T.const i' 0 ∧ ∀ j : fin n, T.to_matrix i j = T.to_matrix i' j) := ⟨λ h, have Hconst : T.const i 0 = T.const i' 0, by simpa [of_col_rowg] using h (T.of_col 0) (of_col_mem_flat _ _), ⟨Hconst, λ j, begin have := h (T.of_col (single j (0 : fin 1)).to_matrix) (of_col_mem_flat _ _), rwa [of_col_rowg, of_col_rowg, add_val, add_val, matrix_mul_apply, matrix_mul_apply, symm_single_apply, Hconst, add_right_cancel_iff] at this, end⟩, λ h x hx, by simp [mem_flat_iff.1 hx, h.1, h.2]⟩ /-- A row variable is equal_in_flat to a column variable iff its row has zeros, and a single one in that column. -/ lemma equal_in_flat_row_col {i : fin m} {j : fin n} : T.equal_in_flat (T.to_partition.rowg i) (T.to_partition.colg j) ↔ (∀ j', j' ≠ j → T.to_matrix i j' = 0) ∧ T.const i 0 = 0 ∧ T.to_matrix i j = 1 := ⟨λ h, have Hconst : T.const i 0 = 0, by simpa [of_col_rowg] using h (T.of_col 0) (of_col_mem_flat _ _), ⟨assume j' hj', begin have := h (T.of_col (single j' (0 : fin 1)).to_matrix) (of_col_mem_flat _ _), rwa [of_col_rowg, of_col_colg, add_val, Hconst, add_zero, matrix_mul_apply, symm_single_apply, pequiv.to_matrix, single_apply_of_ne hj', if_neg (option.not_mem_none _)] at this end, Hconst, begin have := h (T.of_col (single j (0 : fin 1)).to_matrix) (of_col_mem_flat _ _), rwa [of_col_rowg, of_col_colg, add_val, Hconst, add_zero, matrix_mul_apply, symm_single_apply, pequiv.to_matrix, single_apply] at this end⟩, by rintros ⟨h₁, h₂, h₃⟩ x hx; rw [mem_flat_iff.1 hx, h₂, sum_eq_single j]; simp *; tauto⟩ lemma mul_single_ext {R : Type*} {m n : ℕ} [semiring R] {A B : matrix (fin m) (fin n) R} (h : ∀ j : fin n, A ⬝ (single j (0 : fin 1)).to_matrix = B ⬝ (single j (0 : fin 1)).to_matrix) : A = B := by ext i j; simpa [matrix_mul_apply] using congr_fun (congr_fun (h j) i) 0 lemma single_mul_ext {R : Type*} {m n : ℕ} [semiring R] {A B : matrix (fin m) (fin n) R} (h : ∀ i, (single (0 : fin 1) i).to_matrix ⬝ A = (single (0 : fin 1) i).to_matrix ⬝ B) : A = B := by ext i j; simpa [mul_matrix_apply] using congr_fun (congr_fun (h i) 0) j lemma ext {T₁ T₂ : tableau m n} (hflat : T₁.flat = T₂.flat) (hpartition : T₁.to_partition = T₂.to_partition) (hres : T₁.restricted = T₂.restricted) : T₁ = T₂ := have hconst : T₁.const = T₂.const, by rw [set.ext_iff] at hflat; simpa [of_col, flat, hpartition, matrix.mul_assoc, mul_right_eq_of_mul_eq (rowp_mul_rowp_transpose _), mul_right_eq_of_mul_eq (colp_mul_rowp_transpose _)] using (hflat (T₁.of_col 0)).1 (of_col_mem_flat _ _), have hmatrix : T₁.to_matrix = T₂.to_matrix, from mul_single_ext $ λ j, begin rw [set.ext_iff] at hflat, have := (hflat (T₁.of_col (single j 0).to_matrix)).1 (of_col_mem_flat _ _), simpa [of_col, hconst, hpartition, flat, matrix.mul_add, matrix.mul_assoc, mul_right_eq_of_mul_eq (rowp_mul_rowp_transpose _), mul_right_eq_of_mul_eq (colp_mul_rowp_transpose _), mul_right_eq_of_mul_eq (colp_mul_colp_transpose _), mul_right_eq_of_mul_eq (rowp_mul_colp_transpose _)] using (hflat (T₁.of_col (single j 0).to_matrix)).1 (of_col_mem_flat _ _) end, by cases T₁; cases T₂; simp * at * end predicate_lemmas /-- Conditions for unboundedness based on reading the tableau. The conditions are equivalent to the simplex pivot rule failing to find a pivot row. -/ lemma unbounded_of_tableau {T : tableau m n} {obj : fin m} {c : fin n} (hT : T.feasible) (hrow : ∀ r, obj ≠ r → T.to_partition.rowg r ∈ T.restricted → 0 ≤ T.to_matrix obj c / T.to_matrix r c) (hc : (T.to_matrix obj c ≠ 0 ∧ T.to_partition.colg c ∉ T.restricted) ∨ (0 < T.to_matrix obj c ∧ T.to_partition.colg c ∈ T.restricted)) : T.is_unbounded_above (T.to_partition.rowg obj) := have hToc : T.to_matrix obj c ≠ 0, from λ h, by simpa [h, lt_irrefl] using hc, (lt_or_gt_of_ne hToc).elim (λ hToc : T.to_matrix obj c < 0, is_unbounded_above_rowg_of_nonpos hT c (hc.elim and.right (λ h, (not_lt_of_gt hToc h.1).elim)) (λ i hi, classical.by_cases (λ hoi : obj = i, le_of_lt (hoi ▸ hToc)) (λ hoi : obj ≠ i, inv_nonpos.1 $ nonpos_of_mul_nonneg_right (hrow _ hoi hi) hToc)) hToc) (λ hToc : 0 < T.to_matrix obj c, is_unbounded_above_rowg_of_nonneg hT c (λ i hi, classical.by_cases (λ hoi : obj = i, le_of_lt (hoi ▸ hToc)) (λ hoi : obj ≠ i, inv_nonneg.1 $ nonneg_of_mul_nonneg_left (hrow _ hoi hi) hToc)) hToc) /-- Conditions for the tableau being feasible, that must be satisified by a simplex pivot rule -/ lemma feasible_pivot {T : tableau m n} (hT : T.feasible) {r c} (hres : T.to_partition.rowg r ∈ T.restricted) (hpos : T.to_partition.colg c ∈ T.restricted → T.to_matrix r c < 0) (hrmin : ∀ (i : fin m), T.to_partition.rowg i ∈ T.restricted → 0 < T.to_matrix i c / T.to_matrix r c → abs (T.const r 0 / T.to_matrix r c) ≤ abs (T.const i 0 / T.to_matrix i c)) : (T.pivot r c).feasible := begin assume i hi, dsimp only [pivot], by_cases hir : i = r, { subst i, rw [if_pos rfl, neg_mul_eq_neg_mul_symm, neg_nonneg], exact mul_nonpos_of_nonneg_of_nonpos (hT _ hres) (inv_nonpos.2 $ le_of_lt (by simp * at *)) }, { rw if_neg hir, rw [to_partition_pivot, rowg_swap_of_ne _ hir, restricted_pivot] at hi, by_cases hTir : 0 < T.to_matrix i c / T.to_matrix r c, { have hTic0 : T.to_matrix i c ≠ 0, from λ h, by simpa [h, lt_irrefl] using hTir, have hTrc0 : T.to_matrix r c ≠ 0, from λ h, by simpa [h, lt_irrefl] using hTir, have := hrmin _ hi hTir, rwa [abs_div, abs_div, abs_of_nonneg (hT _ hres), abs_of_nonneg (hT _ hi), le_div_iff (abs_pos_iff.2 hTic0), div_eq_mul_inv, mul_right_comm, ← abs_inv, mul_assoc, ← abs_mul, ← div_eq_mul_inv, abs_of_nonneg (le_of_lt hTir), ← sub_nonneg, ← mul_div_assoc, div_eq_mul_inv, mul_comm (T.const r 0)] at this }, { refine add_nonneg (hT _ hi) (neg_nonneg.2 _), rw [mul_assoc, mul_left_comm], exact mul_nonpos_of_nonneg_of_nonpos (hT _ hres) (le_of_not_gt hTir) } } end lemma feasible_simplex_pivot {T : tableau m n} {obj : fin m} (hT : T.feasible) {r c} (hres : T.to_partition.rowg r ∈ T.restricted) (hrneg : T.to_matrix obj c / T.to_matrix r c < 0) (hrmin : ∀ (r' : fin m), obj ≠ r' → T.to_partition.rowg r' ∈ T.restricted → T.to_matrix obj c / T.to_matrix r' c < 0 → abs (T.const r 0 / T.to_matrix r c) ≤ abs (T.const r' 0 / T.to_matrix r' c)) (hc : T.to_partition.colg c ∈ T.restricted → 0 < T.to_matrix obj c) : (T.pivot r c).feasible := feasible_pivot hT hres (λ hcres, inv_neg'.1 (neg_of_mul_neg_left hrneg (le_of_lt (hc hcres)))) (λ i hires hir, have hobji : obj ≠ i, from λ hobji, not_lt_of_gt hir (hobji ▸ hrneg), (hrmin _ hobji hires $ have hTrc0 : T.to_matrix r c ≠ 0, from λ _, by simp [*, lt_irrefl] at *, suffices (T.to_matrix obj c / T.to_matrix r c) / (T.to_matrix i c / T.to_matrix r c) < 0, by rwa [div_div_div_cancel_right _ _ hTrc0] at this, div_neg_of_neg_of_pos hrneg hir)) lemma simplex_const_obj_le {T : tableau m n} {obj : fin m} (hT : T.feasible) {r c} (hres : T.to_partition.rowg r ∈ T.restricted) (hrneg : T.to_matrix obj c / T.to_matrix r c < 0) : T.const obj 0 ≤ (T.pivot r c).const obj 0 := have obj ≠ r, from λ hor, begin subst hor, by_cases h0 : T.to_matrix obj c = 0, { simp [lt_irrefl, *] at * }, { simp [div_self h0, not_lt_of_le zero_le_one, *] at * } end, by simp only [le_add_iff_nonneg_right, sub_eq_add_neg, neg_nonneg, mul_assoc, div_eq_mul_inv, mul_left_comm (T.to_matrix obj c), const_pivot_of_ne _ this]; exact mul_nonpos_of_nonneg_of_nonpos (hT _ hres) (le_of_lt hrneg) lemma const_eq_zero_of_const_obj_eq {T : tableau m n} {obj : fin m} (hT : T.feasible) {r c} (hc : T.to_matrix obj c ≠ 0) (hrc : T.to_matrix r c ≠ 0) (hobjr : obj ≠ r) (hobj : (T.pivot r c).const obj 0 = T.const obj 0) : T.const r 0 = 0 := by rw [const_pivot_of_ne _ hobjr, sub_eq_iff_eq_add, ← sub_eq_iff_eq_add', sub_self, eq_comm, div_eq_mul_inv, mul_eq_zero, mul_eq_zero, inv_eq_zero] at hobj; tauto namespace simplex def pivot_linear_order (T : tableau m n) : decidable_linear_order (fin n) := decidable_linear_order.lift T.to_partition.colg (injective_colg _) (by apply_instance) def find_pivot_column (T : tableau m n) (obj : fin m) : option (fin n) := option.cases_on (fin.find (λ c : fin n, T.to_matrix obj c ≠ 0 ∧ T.to_partition.colg c ∉ T.restricted)) (((list.fin_range n).filter (λ c : fin n, 0 < T.to_matrix obj c)).argmin T.to_partition.colg) some def pivot_row_linear_order (T : tableau m n) (c : fin n) : decidable_linear_order (fin m) := decidable_linear_order.lift (show fin m → lex ℚ (fin (m + n)), from λ r', (abs (T.const r' 0 / T.to_matrix r' c), T.to_partition.rowg r')) (λ x y, by simp [T.to_partition.injective_rowg.eq_iff]) (by apply_instance) section local attribute [instance, priority 0] fin.has_le fin.decidable_linear_order lemma pivot_row_linear_order_le_def (T : tableau m n) (c : fin n) : @has_le.le (fin m) (by haveI := pivot_row_linear_order T c; apply_instance) = (λ i i', abs (T.const i 0 / T.to_matrix i c) < abs (T.const i' 0 / T.to_matrix i' c) ∨ (abs (T.const i 0 / T.to_matrix i c) = abs (T.const i' 0 / T.to_matrix i' c) ∧ T.to_partition.rowg i ≤ T.to_partition.rowg i')) := funext $ λ i, funext $ λ i', propext $ prod.lex_def _ _ end -- @[simp] lemma pivot_row_linear_order_le_def (T : tableau m n) (c : fin n) (i i' : fin m) : -- pivot_row_le T c i i' ↔ -- abs (T.const i 0 / T.to_matrix i c) < abs (T.const i' 0 / T.to_matrix i' c) ∨ -- (abs (T.const i 0 / T.to_matrix i c) = abs (T.const i' 0 / T.to_matrix i' c) ∧ -- T.to_partition.rowg i ≤ T.to_partition.rowg i') := -- prod.lex_def _ _ def find_pivot_row (T : tableau m n) (obj: fin m) (c : fin n) : option (fin m) := let l := (list.fin_range m).filter (λ r : fin m, obj ≠ r ∧ T.to_partition.rowg r ∈ T.restricted ∧ T.to_matrix obj c / T.to_matrix r c < 0) in @list.minimum _ (pivot_row_linear_order T c) l lemma find_pivot_column_spec {T : tableau m n} {obj : fin m} {c : fin n} : c ∈ find_pivot_column T obj → (T.to_matrix obj c ≠ 0 ∧ T.to_partition.colg c ∉ T.restricted) ∨ (0 < T.to_matrix obj c ∧ T.to_partition.colg c ∈ T.restricted) := begin simp [find_pivot_column], cases h : fin.find (λ c : fin n, T.to_matrix obj c ≠ 0 ∧ T.to_partition.colg c ∉ T.restricted), { finish [h, fin.find_eq_some_iff, fin.find_eq_none_iff, lt_irrefl (0 : ℚ), list.argmin_eq_some_iff] }, { finish [fin.find_eq_some_iff] } end lemma nonpos_of_lt_find_pivot_column {T : tableau m n} {obj : fin m} {c j : fin n} (hc : c ∈ find_pivot_column T obj) (hcres : T.to_partition.colg c ∈ T.restricted) (hjc : T.to_partition.colg j < T.to_partition.colg c) : T.to_matrix obj j ≤ 0 := begin rw [find_pivot_column] at hc, cases h : fin.find (λ c, T.to_matrix obj c ≠ 0 ∧ colg (T.to_partition) c ∉ T.restricted), { rw h at hc, refine le_of_not_lt (λ hj0, _), exact not_le_of_gt hjc ((list.mem_argmin_iff.1 hc).2.1 j (list.mem_filter.2 (by simp [hj0]))) }, { rw h at hc, simp [*, fin.find_eq_some_iff] at * } end lemma find_pivot_column_eq_none {T : tableau m n} {obj : fin m} (hT : T.feasible) (h : find_pivot_column T obj = none) : T.is_optimal (T.of_col 0) (T.to_partition.rowg obj) := is_optimal_of_col_zero hT begin revert h, simp [find_pivot_column], cases h : fin.find (λ c : fin n, T.to_matrix obj c ≠ 0 ∧ T.to_partition.colg c ∉ T.restricted), { finish [fin.find_eq_none_iff, list.argmin_eq_some_iff, list.filter_eq_nil] }, { simp [h] } end lemma find_pivot_row_spec {T : tableau m n} {obj r : fin m} {c : fin n} : r ∈ find_pivot_row T obj c → obj ≠ r ∧ T.to_partition.rowg r ∈ T.restricted ∧ T.to_matrix obj c / T.to_matrix r c < 0 ∧ (∀ r' : fin m, obj ≠ r' → T.to_partition.rowg r' ∈ T.restricted → T.to_matrix obj c / T.to_matrix r' c < 0 → abs (T.const r 0 / T.to_matrix r c) ≤ abs (T.const r' 0 / T.to_matrix r' c)) := begin simp only [list.mem_filter, find_pivot_row, option.mem_def, with_bot.some_eq_coe, list.minimum_eq_coe_iff, list.mem_fin_range, true_and, and_imp], rw [pivot_row_linear_order_le_def], intros hor hres hr0 h, simp only [*, true_and, ne.def, not_false_iff], intros r' hor' hres' hr0', cases h r' hor' hres' hr0', { exact le_of_lt (by assumption) }, { exact le_of_eq (by tauto) } end lemma nonneg_of_lt_find_pivot_row {T : tableau m n} {obj : fin m} {r i : fin m} {c : fin n} (hc0 : 0 < T.to_matrix obj c) (hres : T.to_partition.rowg i ∈ T.restricted) (hc : c ∈ find_pivot_column T obj) (hr : r ∈ find_pivot_row T obj c) (hconst : T.const i 0 = 0) (hjc : T.to_partition.rowg i < T.to_partition.rowg r) : 0 ≤ T.to_matrix i c := if hobj : obj = i then le_of_lt $ hobj ▸ hc0 else le_of_not_gt $ λ hic, not_le_of_lt hjc begin have := ((@list.minimum_eq_coe_iff _ (id _) _ _).1 hr).2 i (list.mem_filter.2 ⟨list.mem_fin_range _, hobj, hres, div_neg_of_pos_of_neg hc0 hic⟩), rw [pivot_row_linear_order_le_def] at this, simp [hconst, not_lt_of_ge (abs_nonneg _), *] at * end lemma ne_zero_of_mem_find_pivot_row {T : tableau m n} {obj r : fin m} {c : fin n} (hr : r ∈ find_pivot_row T obj c) : T.to_matrix r c ≠ 0 := assume hrc, by simpa [lt_irrefl, hrc] using find_pivot_row_spec hr lemma ne_zero_of_mem_find_pivot_column {T : tableau m n} {obj : fin m} {c : fin n} (hc : c ∈ find_pivot_column T obj) : T.to_matrix obj c ≠ 0 := λ h, by simpa [h, lt_irrefl] using find_pivot_column_spec hc lemma find_pivot_row_eq_none_aux {T : tableau m n} {obj : fin m} {c : fin n} (hrow : find_pivot_row T obj c = none) (hs : c ∈ find_pivot_column T obj) : ∀ r, obj ≠ r → T.to_partition.rowg r ∈ T.restricted → 0 ≤ T.to_matrix obj c / T.to_matrix r c := by simpa [find_pivot_row, list.filter_eq_nil] using hrow lemma find_pivot_row_eq_none {T : tableau m n} {obj : fin m} {c : fin n} (hT : T.feasible) (hrow : find_pivot_row T obj c = none) (hs : c ∈ find_pivot_column T obj) : T.is_unbounded_above (T.to_partition.rowg obj) := have hrow : ∀ r, obj ≠ r → T.to_partition.rowg r ∈ T.restricted → 0 ≤ T.to_matrix obj c / T.to_matrix r c, from find_pivot_row_eq_none_aux hrow hs, have hc : (T.to_matrix obj c ≠ 0 ∧ T.to_partition.colg c ∉ T.restricted) ∨ (0 < T.to_matrix obj c ∧ T.to_partition.colg c ∈ T.restricted), from find_pivot_column_spec hs, have hToc : T.to_matrix obj c ≠ 0, from λ h, by simpa [h, lt_irrefl] using hc, (lt_or_gt_of_ne hToc).elim (λ hToc : T.to_matrix obj c < 0, is_unbounded_above_rowg_of_nonpos hT c (hc.elim and.right (λ h, (not_lt_of_gt hToc h.1).elim)) (λ i hi, classical.by_cases (λ hoi : obj = i, le_of_lt (hoi ▸ hToc)) (λ hoi : obj ≠ i, inv_nonpos.1 $ nonpos_of_mul_nonneg_right (hrow _ hoi hi) hToc)) hToc) (λ hToc : 0 < T.to_matrix obj c, is_unbounded_above_rowg_of_nonneg hT c (λ i hi, classical.by_cases (λ hoi : obj = i, le_of_lt (hoi ▸ hToc)) (λ hoi : obj ≠ i, inv_nonneg.1 $ nonneg_of_mul_nonneg_left (hrow _ hoi hi) hToc)) hToc) def feasible_of_mem_pivot_row_and_column {T : tableau m n} {obj : fin m} (hT : T.feasible) {c} (hc : c ∈ find_pivot_column T obj) {r} (hr : r ∈ find_pivot_row T obj c) : feasible (T.pivot r c) := begin have := find_pivot_column_spec hc, have := find_pivot_row_spec hr, have := @feasible_simplex_pivot _ _ _ obj hT r c, tauto end section blands_rule local attribute [instance, priority 0] classical.dec variable (obj : fin m) lemma not_unique_row_and_unique_col {T T' : tableau m n} {r c c'} (hcobj0 : 0 < T.to_matrix obj c) (hc'obj0 : 0 < T'.to_matrix obj c') (hrc0 : T.to_matrix r c < 0) (hflat : T.flat = T'.flat) (hs : T.to_partition.rowg r = T'.to_partition.colg c') (hrobj : T.to_partition.rowg obj = T'.to_partition.rowg obj) (hfickle : ∀ i, T.to_partition.rowg i ≠ T'.to_partition.rowg i → T.const i 0 = 0) (hobj : T.const obj 0 = T'.const obj 0) (nonpos_of_colg_ne : ∀ j, T'.to_partition.colg j ≠ T.to_partition.colg j → j ≠ c' → T'.to_matrix obj j ≤ 0) (nonpos_of_colg_eq : ∀ j, j ≠ c' → T'.to_partition.colg j = T.to_partition.colg c → T'.to_matrix obj j ≤ 0) (unique_row : ∀ i ≠ r, T.const i 0 = 0 → T.to_partition.rowg i ≠ T'.to_partition.rowg i → 0 ≤ T.to_matrix i c) : false := let objr := T.to_partition.rowg obj in let x := λ y : ℚ, T.of_col (y • (single c 0).to_matrix) in have hxflatT' : ∀ {y}, x y ∈ flat T', from hflat ▸ λ _, of_col_mem_flat _ _, have hxrow : ∀ y i, x y (T.to_partition.rowg i) 0 = T.const i 0 + y * T.to_matrix i c, by simp [x, of_col_single_rowg], have hxcol : ∀ {y j}, j ≠ c → x y (T.to_partition.colg j) 0 = 0, from λ y j hjc, by simp [x, of_col_colg, pequiv.to_matrix, single_apply_of_ne hjc.symm], have hxcolc : ∀ {y}, x y (T.to_partition.colg c) 0 = y, by simp [x, of_col_colg, pequiv.to_matrix], let c_star : fin (m + n) → ℚ := λ v, option.cases_on (T'.to_partition.colp.symm v) 0 (T'.to_matrix obj) in have hxobj : ∀ y, x y objr 0 = T.const obj 0 + y * T.to_matrix obj c, from λ y, hxrow _ _, have hgetr : ∀ {y v}, c_star v * x y v 0 ≠ 0 → (T'.to_partition.colp.symm v).is_some, from λ y v, by cases h : T'.to_partition.colp.symm v; dsimp [c_star]; rw h; simp, have c_star_eq_get : ∀ {v} (hv : (T'.to_partition.colp.symm v).is_some), c_star v = T'.to_matrix obj (option.get hv), from λ v hv, by dsimp only [c_star]; conv_lhs{rw [← option.some_get hv]}; refl, have hsummmn : ∀ {y}, sum univ (λ j, T'.to_matrix obj j * x y (T'.to_partition.colg j) 0) = sum univ (λ v, c_star v * x y v 0), from λ y, sum_bij_ne_zero (λ j _ _, T'.to_partition.colg j) (λ _ _ _, mem_univ _) (λ _ _ _ _ _ _ h, T'.to_partition.injective_colg h) (λ v _ h0, ⟨option.get (hgetr h0), mem_univ _, by rw [← c_star_eq_get (hgetr h0)]; simpa using h0, by simp⟩) (λ _ _ h0, by dsimp [c_star]; rw [colp_colg]), have hgetc : ∀ {y v}, c_star v * x y v 0 ≠ 0 → v ≠ T.to_partition.colg c → (T.to_partition.rowp.symm v).is_some, from λ y v, (eq_rowg_or_colg T.to_partition v).elim (λ ⟨i, hi⟩, by rw [hi, rowp_rowg]; simp) (λ ⟨j, hj⟩ h0 hvc, by rw [hj, hxcol (mt (congr_arg T.to_partition.colg) (hvc ∘ hj.trans)), mul_zero] at h0; exact (h0 rfl).elim), have hsummmnn : ∀ {y}, (univ.erase (T.to_partition.colg c)).sum (λ v, c_star v * x y v 0) = univ.sum (λ i, c_star (T.to_partition.rowg i) * x y (T.to_partition.rowg i) 0), from λ y, eq.symm $ sum_bij_ne_zero (λ i _ _, T.to_partition.rowg i) (by simp) (λ _ _ _ _ _ _ h, T.to_partition.injective_rowg h) (λ v hvc h0, ⟨option.get (hgetc h0 (mem_erase.1 hvc).1), mem_univ _, by simpa using h0⟩) (by intros; refl), have hsumm : ∀ {y}, univ.sum (λ i, c_star (T.to_partition.rowg i) * x y (T.to_partition.rowg i) 0) = univ.sum (λ i, c_star (T.to_partition.rowg i) * T.const i 0) + y * univ.sum (λ i, c_star (T.to_partition.rowg i) * T.to_matrix i c), from λ y, by simp only [hxrow, mul_add, add_mul, sum_add_distrib, mul_assoc, mul_left_comm _ y, mul_sum.symm], have hxobj' : ∀ y, x y objr 0 = univ.sum (λ v, c_star v * x y v 0) + T'.const obj 0, from λ y, by dsimp [objr]; rw [hrobj, mem_flat_iff.1 hxflatT', hsummmn], have hy : ∀ {y}, y * T.to_matrix obj c = c_star (T.to_partition.colg c) * y + univ.sum (λ i, c_star (T.to_partition.rowg i) * T.const i 0) + y * univ.sum (λ i, c_star (T.to_partition.rowg i) * T.to_matrix i c), from λ y, by rw [← add_left_inj (T.const obj 0), ← hxobj, hxobj', ← insert_erase (mem_univ (T.to_partition.colg c)), sum_insert (not_mem_erase _ _), hsummmnn, hobj, hsumm, hxcolc]; simp, have hy' : ∀ (y), y * (T.to_matrix obj c - c_star (T.to_partition.colg c) - univ.sum (λ i, c_star (T.to_partition.rowg i) * T.to_matrix i c)) = univ.sum (λ i, c_star (T.to_partition.rowg i) * T.const i 0), from λ y, by rw [mul_sub, mul_sub, hy]; simp [mul_comm, mul_assoc, mul_left_comm], have h0 : T.to_matrix obj c - c_star (T.to_partition.colg c) - univ.sum (λ i, c_star (T.to_partition.rowg i) * T.to_matrix i c) = 0, by rw [← (domain.mul_left_inj (@one_ne_zero ℚ _)), hy', ← hy' 0, zero_mul, mul_zero], have hcolnec' : T'.to_partition.colp.symm (T.to_partition.colg c) ≠ some c', from λ h, by simpa [hs.symm] using congr_arg T'.to_partition.colg (option.eq_some_iff_get_eq.1 h).snd, have eq_of_roweqc' : ∀ {i}, T'.to_partition.colp.symm (T.to_partition.rowg i) = some c' → i = r, from λ i h, by simpa [hs.symm, T.to_partition.injective_rowg.eq_iff] using congr_arg T'.to_partition.colg (option.eq_some_iff_get_eq.1 h).snd, have sumpos : 0 < univ.sum (λ i, c_star (T.to_partition.rowg i) * T.to_matrix i c), by rw [← sub_eq_zero.1 h0]; exact add_pos_of_pos_of_nonneg hcobj0 (begin simp only [c_star, neg_nonneg], cases h : T'.to_partition.colp.symm (T.to_partition.colg c) with j, { refl }, { exact nonpos_of_colg_eq j (mt (congr_arg some) (h ▸ hcolnec')) (by rw [← (option.eq_some_iff_get_eq.1 h).snd]; simp) } end), have hexi : ∃ i, 0 < c_star (T.to_partition.rowg i) * T.to_matrix i c, from imp_of_not_imp_not _ _ (by simpa using @sum_nonpos _ _ (@univ (fin m) _) (λ i, c_star (T.to_partition.rowg i) * T.to_matrix i c) _ _) sumpos, let ⟨i, hi⟩ := hexi in have hi0 : T.const i 0 = 0, from hfickle i (λ h, by dsimp [c_star] at hi; rw [h, colp_rowg_eq_none] at hi; simpa [lt_irrefl] using hi), have hi_some : (T'.to_partition.colp.symm (T.to_partition.rowg i)).is_some, from option.ne_none_iff_is_some.1 (λ h, by dsimp only [c_star] at hi; rw h at hi; simpa [lt_irrefl] using hi), have hi' : 0 < T'.to_matrix obj (option.get hi_some) * T.to_matrix i c, by dsimp only [c_star] at hi; rwa [← option.some_get hi_some] at hi, have hir : i ≠ r, from λ hir, begin have : option.get hi_some = c', from T'.to_partition.injective_colg (by rw [colg_get_colp_symm, ← hs, hir]), rw [this, hir] at hi', exact not_lt_of_gt hi' (mul_neg_of_pos_of_neg hc'obj0 hrc0) end, have hnec' : option.get hi_some ≠ c', from λ eq_c', hir $ @eq_of_roweqc' i (eq_c' ▸ by simp), have hic0 : T.to_matrix i c < 0, from neg_of_mul_pos_right hi' (nonpos_of_colg_ne _ (by simp) hnec'), not_le_of_gt hic0 (unique_row _ hir hi0 (by rw [← colg_get_colp_symm _ _ hi_some]; exact colg_ne_rowg _ _ _)) inductive rel : tableau m n → tableau m n → Prop | pivot : ∀ {T}, feasible T → ∀ {r c}, c ∈ find_pivot_column T obj → r ∈ find_pivot_row T obj c → rel (T.pivot r c) T | trans_pivot : ∀ {T₁ T₂ r c}, rel T₁ T₂ → c ∈ find_pivot_column T₁ obj → r ∈ find_pivot_row T₁ obj c → rel (T₁.pivot r c) T₂ lemma feasible_of_rel_right {T T' : tableau m n} (h : rel obj T' T) : T.feasible := rel.rec_on h (by tauto) (by tauto) lemma feasible_of_rel_left {T T' : tableau m n} (h : rel obj T' T) : T'.feasible := rel.rec_on h (λ _ hT _ _ hc hr, feasible_of_mem_pivot_row_and_column hT hc hr) (λ _ _ _ _ _ hc hr hT, feasible_of_mem_pivot_row_and_column hT hc hr) /-- Slightly stronger recursor than the default recursor -/ @[elab_as_eliminator] lemma rel.rec_on' {obj : fin m} {C : tableau m n → tableau m n → Prop} {T T' : tableau m n} (hrel : rel obj T T') (hpivot : ∀ {T : tableau m n} {r : fin m} {c : fin n}, feasible T → c ∈ find_pivot_column T obj → r ∈ find_pivot_row T obj c → C (pivot T r c) T) (hpivot_trans : ∀ {T₁ T₂ : tableau m n} {r : fin m} {c : fin n}, rel obj (T₁.pivot r c) T₁ → rel obj T₁ T₂ → c ∈ find_pivot_column T₁ obj → r ∈ find_pivot_row T₁ obj c → C (T₁.pivot r c) T₁ → C T₁ T₂ → C (pivot T₁ r c) T₂) : C T T' := rel.rec_on hrel (λ T hT r c hc hr, hpivot hT hc hr) (λ T₁ T₂ r c hrelT₁₂ hc hr ih, hpivot_trans (rel.pivot (feasible_of_rel_left obj hrelT₁₂) hc hr) hrelT₁₂ hc hr (hpivot (feasible_of_rel_left obj hrelT₁₂) hc hr) ih) lemma rel.trans {obj : fin m} {T₁ T₂ T₃ : tableau m n} (h₁₂ : rel obj T₁ T₂) : rel obj T₂ T₃ → rel obj T₁ T₃ := rel.rec_on h₁₂ (λ T r c hT hc hr hrelT, rel.trans_pivot hrelT hc hr) (λ T₁ T₂ r c hrelT₁₂ hc hr ih hrelT₂₃, rel.trans_pivot (ih hrelT₂₃) hc hr) instance : is_trans (tableau m n) (rel obj) := ⟨@rel.trans _ _ obj⟩ lemma flat_eq_of_rel {T T' : tableau m n} (h : rel obj T' T) : flat T' = flat T := rel.rec_on' h (λ _ _ _ _ _ hr, flat_pivot (ne_zero_of_mem_find_pivot_row hr)) (λ _ _ _ _ _ _ _ _, eq.trans) lemma rowg_obj_eq_of_rel {T T' : tableau m n} (h : rel obj T T') : T.to_partition.rowg obj = T'.to_partition.rowg obj := rel.rec_on' h (λ T r c hfT hc hr, by simp [rowg_swap_of_ne _ (find_pivot_row_spec hr).1]) (λ _ _ _ _ _ _ _ _, eq.trans) lemma restricted_eq_of_rel {T T' : tableau m n} (h : rel obj T T') : T.restricted = T'.restricted := rel.rec_on' h (λ _ _ _ _ _ _, rfl) (λ _ _ _ _ _ _ _ _, eq.trans) lemma exists_mem_pivot_row_column_of_rel {T T' : tableau m n} (h : rel obj T' T) : ∃ r c, c ∈ find_pivot_column T obj ∧ r ∈ find_pivot_row T obj c := rel.rec_on' h (λ _ r c _ hc hr, ⟨r, c, hc, hr⟩) (λ _ _ _ _ _ _ _ _ _, id) lemma exists_mem_pivot_row_of_rel {T T' : tableau m n} (h : rel obj T' T) {c : fin n} (hc : c ∈ find_pivot_column T obj) : ∃ r, r ∈ find_pivot_row T obj c := let ⟨r, c', hc', hr⟩ := exists_mem_pivot_row_column_of_rel obj h in ⟨r, by simp * at *⟩ lemma colg_eq_or_exists_mem_pivot_column {T₁ T₂ : tableau m n} (h : rel obj T₂ T₁) {c : fin n} : T₁.to_partition.colg c = T₂.to_partition.colg c ∨ ∃ T₃, (T₃ = T₁ ∨ rel obj T₃ T₁) ∧ (rel obj T₂ T₃) ∧ T₃.to_partition.colg c = T₁.to_partition.colg c ∧ c ∈ find_pivot_column T₃ obj := rel.rec_on' h begin assume T r c' hT hc' hr, by_cases hcc : c = c', { subst hcc, exact or.inr ⟨T, or.inl rfl, rel.pivot hT hc' hr, rfl, hc'⟩ }, { simp [colg_swap_of_ne _ hcc] } end (λ T₁ T₂ r c hrelp₁ hrel₁₂ hc hr ihp₁ ih₁₂, ih₁₂.elim (λ ih₁₂, ihp₁.elim (λ ihp₁, or.inl (ih₁₂.trans ihp₁)) (λ ⟨T₃, hT₃⟩, or.inr ⟨T₃, hT₃.1.elim (λ h, h.symm ▸ or.inr hrel₁₂) (λ h, or.inr $ h.trans hrel₁₂), hT₃.2.1, hT₃.2.2.1.trans ih₁₂.symm, hT₃.2.2.2⟩)) (λ ⟨T₃, hT₃⟩, or.inr ⟨T₃, hT₃.1, hrelp₁.trans hT₃.2.1, hT₃.2.2⟩)) lemma rowg_eq_or_exists_mem_pivot_row {T₁ T₂ : tableau m n} (h : rel obj T₂ T₁) (r : fin m) : T₁.to_partition.rowg r = T₂.to_partition.rowg r ∨ ∃ (T₃ : tableau m n) c, (T₃ = T₁ ∨ rel obj T₃ T₁) ∧ (rel obj T₂ T₃) ∧ T₃.to_partition.rowg r = T₁.to_partition.rowg r ∧ c ∈ find_pivot_column T₃ obj ∧ r ∈ find_pivot_row T₃ obj c := rel.rec_on' h begin assume T r' c hT hc hr', by_cases hrr : r = r', { subst hrr, exact or.inr ⟨T, c, or.inl rfl, rel.pivot hT hc hr', rfl, hc, hr'⟩ }, { simp [rowg_swap_of_ne _ hrr] } end (λ T₁ T₂ r c hrelp₁ hrel₁₂ hc hr ihp₁ ih₁₂, ih₁₂.elim (λ ih₁₂, ihp₁.elim (λ ihp₁, or.inl $ ih₁₂.trans ihp₁) (λ ⟨T₃, c', hT₃⟩, or.inr ⟨T₃, c', hT₃.1.elim (λ h, h.symm ▸ or.inr hrel₁₂) (λ h, or.inr $ h.trans hrel₁₂), hT₃.2.1, ih₁₂.symm ▸ hT₃.2.2.1, hT₃.2.2.2⟩)) (λ ⟨T₃, c', hT₃⟩, or.inr ⟨T₃, c', hT₃.1, (rel.pivot (feasible_of_rel_left _ hrel₁₂) hc hr).trans hT₃.2.1, hT₃.2.2⟩)) lemma eq_or_rel_pivot_of_rel {T₁ T₂ : tableau m n} (h : rel obj T₁ T₂) : ∀ {r c} (hc : c ∈ find_pivot_column T₂ obj) (hr : r ∈ find_pivot_row T₂ obj c), T₁ = T₂.pivot r c ∨ rel obj T₁ (T₂.pivot r c) := rel.rec_on' h (λ T r c hT hc hr r' c' hc' hr', by simp * at *) (λ T₁ T₂ r c hrelp₁ hrel₁₂ hc hr ihp₁ ih₁₂ r' c' hc' hr', (ih₁₂ hc' hr').elim (λ ih₁₂, or.inr $ ih₁₂ ▸ rel.pivot (feasible_of_rel_left _ hrel₁₂) hc hr) (λ ih₁₂, or.inr $ (rel.pivot (feasible_of_rel_left _ hrel₁₂) hc hr).trans ih₁₂)) lemma exists_mem_pivot_column_of_mem_pivot_row {T : tableau m n} (hrelTT : rel obj T T) {r c} (hc : c ∈ find_pivot_column T obj) (hr : r ∈ find_pivot_row T obj c) : ∃ (T' : tableau m n), c ∈ find_pivot_column T' obj ∧ T'.to_partition.colg c = T.to_partition.rowg r ∧ rel obj T' T ∧ rel obj T T' := have hrelTTp : rel obj T (T.pivot r c), from (eq_or_rel_pivot_of_rel _ hrelTT hc hr).elim (λ h, h ▸ hrelTT ) id, let ⟨T', hT'⟩ := (colg_eq_or_exists_mem_pivot_column obj hrelTTp).resolve_left (show (T.pivot r c).to_partition.colg c ≠ T.to_partition.colg c, by simp) in ⟨T', hT'.2.2.2, by simp [hT'.2.2.1], hT'.1.elim (λ h, h.symm ▸ rel.pivot (feasible_of_rel_left _ hrelTT) hc hr) (λ h, h.trans $ rel.pivot (feasible_of_rel_left _ hrelTT) hc hr), hT'.2.1⟩ lemma exists_mem_pivot_column_of_rowg_ne {T T' : tableau m n} (hrelTT' : rel obj T T') {r : fin m} (hrelT'T : rel obj T' T) (hrow : T.to_partition.rowg r ≠ T'.to_partition.rowg r) : ∃ (T₃ : tableau m n) c, c ∈ find_pivot_column T₃ obj ∧ T₃.to_partition.colg c = T.to_partition.rowg r ∧ rel obj T₃ T ∧ rel obj T T₃ := let ⟨T₃, c, hT₃, hrelT₃T, hrow₃, hc, hr⟩ := (rowg_eq_or_exists_mem_pivot_row obj hrelT'T _).resolve_left hrow in let ⟨T₄, hT₄⟩ := exists_mem_pivot_column_of_mem_pivot_row obj (show rel obj T₃ T₃, from hT₃.elim (λ h, h.symm ▸ hrelTT'.trans hrelT'T) (λ h, h.trans $ hrelTT'.trans hrelT₃T)) hc hr in ⟨T₄, c, hT₄.1, hT₄.2.1.trans hrow₃, hT₄.2.2.1.trans $ hT₃.elim (λ h, h.symm ▸ hrelTT'.trans hrelT'T) (λ h, h.trans $ hrelTT'.trans hrelT'T), hrelTT'.trans (hrelT₃T.trans hT₄.2.2.2)⟩ lemma const_obj_le_of_rel {T₁ T₂ : tableau m n} (h : rel obj T₁ T₂) : T₂.const obj 0 ≤ T₁.const obj 0 := rel.rec_on' h (λ T r c hT hc hr, have hr' : _ := find_pivot_row_spec hr, simplex_const_obj_le hT (by tauto) (by tauto)) (λ _ _ _ _ _ _ _ _ h₁ h₂, le_trans h₂ h₁) lemma const_obj_eq_of_rel_of_rel {T₁ T₂ : tableau m n} (h₁₂ : rel obj T₁ T₂) (h₂₁ : rel obj T₂ T₁) : T₁.const obj 0 = T₂.const obj 0 := le_antisymm (const_obj_le_of_rel _ h₂₁) (const_obj_le_of_rel _ h₁₂) lemma const_eq_const_of_const_obj_eq {T₁ T₂ : tableau m n} (h₁₂ : rel obj T₁ T₂) : ∀ (hobj : T₁.const obj 0 = T₂.const obj 0) (i : fin m), T₁.const i 0 = T₂.const i 0 := rel.rec_on' h₁₂ (λ T r c hfT hc hr hobj i, have hr0 : T.const r 0 = 0, from const_eq_zero_of_const_obj_eq hfT (ne_zero_of_mem_find_pivot_column hc) (ne_zero_of_mem_find_pivot_row hr) (find_pivot_row_spec hr).1 hobj, if hir : i = r then by simp [hir, hr0] else by simp [const_pivot_of_ne _ hir, hr0]) (λ T₁ T₂ r c hrelp₁ hrel₁₂ hc hr ihp₁ ih₁₂ hobj i, have hobjp : (pivot T₁ r c).const obj 0 = T₁.const obj 0, from le_antisymm (hobj.symm ▸ const_obj_le_of_rel _ hrel₁₂) (const_obj_le_of_rel _ hrelp₁), by rw [ihp₁ hobjp, ih₁₂ (hobjp.symm.trans hobj)]) lemma const_eq_zero_of_rowg_ne_of_rel_self {T T' : tableau m n} (hrelTT' : rel obj T T') (hrelT'T : rel obj T' T) (i : fin m) (hrow : T.to_partition.rowg i ≠ T'.to_partition.rowg i) : T.const i 0 = 0 := let ⟨T₃, c, hT₃₁, hT'₃, hrow₃, hc, hi⟩ := (rowg_eq_or_exists_mem_pivot_row obj hrelT'T _).resolve_left hrow in have T₃.const i 0 = 0, from const_eq_zero_of_const_obj_eq (feasible_of_rel_right _ hT'₃) (ne_zero_of_mem_find_pivot_column hc) (ne_zero_of_mem_find_pivot_row hi) (find_pivot_row_spec hi).1 (const_obj_eq_of_rel_of_rel _ (rel.pivot (feasible_of_rel_right _ hT'₃) hc hi) ((eq_or_rel_pivot_of_rel _ hT'₃ hc hi).elim (λ h, h ▸ hT₃₁.elim (λ h, h.symm ▸ hrelTT') (λ h, h.trans hrelTT')) (λ hrelT'p, hT₃₁.elim (λ h, h.symm ▸ hrelTT'.trans (h ▸ hrelT'p)) (λ h, h.trans $ hrelTT'.trans hrelT'p)))), have hobj : T₃.const obj 0 = T.const obj 0, from hT₃₁.elim (λ h, h ▸ rfl) (λ h, const_obj_eq_of_rel_of_rel _ h (hrelTT'.trans hT'₃)), hT₃₁.elim (λ h, h ▸ this) (λ h, const_eq_const_of_const_obj_eq obj h hobj i ▸ this) lemma colg_mem_restricted_of_rel_self {T : tableau m n} (hrelTT : rel obj T T) {c} (hc : c ∈ find_pivot_column T obj) : T.to_partition.colg c ∈ T.restricted := let ⟨r, hr⟩ := exists_mem_pivot_row_of_rel obj hrelTT hc in let ⟨T', c', hT', hrelTT', hrowcol, _, hr'⟩ := (rowg_eq_or_exists_mem_pivot_row obj ((eq_or_rel_pivot_of_rel _ hrelTT hc hr).elim (λ h, show rel obj T (T.pivot r c), from h ▸ hrelTT) id) _).resolve_left (show (T.pivot r c).to_partition.rowg r ≠ T.to_partition.rowg r, by simp) in (restricted_eq_of_rel _ hrelTT').symm ▸ by convert (find_pivot_row_spec hr').2.1; simp [hrowcol] lemma eq_zero_of_not_mem_restricted_of_rel_self {T : tableau m n} (hrelTT : rel obj T T) {j} (hjres : T.to_partition.colg j ∉ T.restricted) : T.to_matrix obj j = 0 := let ⟨r, c, hc, hr⟩ := exists_mem_pivot_row_column_of_rel obj hrelTT in have hcres : T.to_partition.colg c ∈ T.restricted, from colg_mem_restricted_of_rel_self obj hrelTT hc, by_contradiction $ λ h0, begin simp [find_pivot_column] at hc, cases h : fin.find (λ c, T.to_matrix obj c ≠ 0 ∧ colg (T.to_partition) c ∉ T.restricted), { simp [*, fin.find_eq_none_iff] at * }, { rw h at hc, clear_aux_decl, have := (fin.find_eq_some_iff.1 h).1, simp * at * } end lemma rel.irrefl {obj : fin m} : ∀ (T : tableau m n), ¬ rel obj T T := λ T1 hrelT1, let ⟨rT1 , cT1, hrT1, hcT1⟩ := exists_mem_pivot_row_column_of_rel obj hrelT1 in let ⟨t, ht⟩ := finset.max_of_mem (show T1.to_partition.colg cT1 ∈ univ.filter (λ v, ∃ (T' : tableau m n) (c : fin n), rel obj T' T' ∧ c ∈ find_pivot_column T' obj ∧ T'.to_partition.colg c = v), by simp only [true_and, mem_filter, mem_univ, exists_and_distrib_left]; exact ⟨T1, hrelT1, cT1, hrT1, rfl⟩) in let ⟨_, T', c', hrelTT'', hcT', hct⟩ := finset.mem_filter.1 (finset.mem_of_max ht) in have htmax : ∀ (s : fin (m + n)) (T : tableau m n), rel obj T T → ∀ (j : fin n), find_pivot_column T obj = some j → T.to_partition.colg j = s → s ≤ t, by simpa using λ s (h : s ∈ _), finset.le_max_of_mem h ht, let ⟨r, hrT'⟩ := exists_mem_pivot_row_of_rel obj hrelTT'' hcT' in have hrelTT''p : rel obj T' (T'.pivot r c'), from (eq_or_rel_pivot_of_rel obj hrelTT'' hcT' hrT').elim (λ h, h ▸ hrelTT'') id, let ⟨T, c, hTT', hrelT'T, hT'Tr, hc, hr⟩ := (rowg_eq_or_exists_mem_pivot_row obj hrelTT''p r).resolve_left (by simp) in have hfT' : feasible T', from feasible_of_rel_left _ hrelTT'', have hfT : feasible T, from feasible_of_rel_right _ hrelT'T, have hrelT'pT' : rel obj (T'.pivot r c') T', from rel.pivot hfT' hcT' hrT', have hrelTT' : rel obj T T', from hTT'.elim (λ h, h.symm ▸ hrelT'pT') (λ h, h.trans hrelT'pT'), have hrelTT : rel obj T T, from hrelTT'.trans hrelT'T, have hc't : T.to_partition.colg c ≤ t, from htmax _ T hrelTT _ hc rfl, have hoT'T : T'.const obj 0 = T.const obj 0, from const_obj_eq_of_rel_of_rel _ hrelT'T hrelTT', have hfickle : ∀ i, T.to_partition.rowg i ≠ T'.to_partition.rowg i → T.const i 0 = 0, from const_eq_zero_of_rowg_ne_of_rel_self obj hrelTT' hrelT'T, have hobj : T.const obj 0 = T'.const obj 0, from const_obj_eq_of_rel_of_rel _ hrelTT' hrelT'T, have hflat : T.flat = T'.flat, from flat_eq_of_rel obj hrelTT', have hrobj : T.to_partition.rowg obj = T'.to_partition.rowg obj, from rowg_obj_eq_of_rel _ hrelTT', have hs : T.to_partition.rowg r = T'.to_partition.colg c', by simpa using hT'Tr, have hc'res : T'.to_partition.colg c' ∈ T'.restricted, from hs ▸ restricted_eq_of_rel _ hrelTT' ▸ (find_pivot_row_spec hr).2.1, have hc'obj0 : 0 < T'.to_matrix obj c', by simpa [hc'res] using find_pivot_column_spec hcT', have hcres : T.to_partition.colg c ∈ T.restricted, from colg_mem_restricted_of_rel_self obj hrelTT hc, have hcobj0 : 0 < to_matrix T obj c, by simpa [hcres] using find_pivot_column_spec hc, have hrc0 : T.to_matrix r c < 0, from inv_neg'.1 $ neg_of_mul_neg_left (find_pivot_row_spec hr).2.2.1 (le_of_lt hcobj0), have nonpos_of_colg_ne : ∀ j, T'.to_partition.colg j ≠ T.to_partition.colg j → j ≠ c' → T'.to_matrix obj j ≤ 0, from λ j hj hjc', let ⟨T₃, hT₃⟩ := (colg_eq_or_exists_mem_pivot_column obj hrelTT').resolve_left hj in nonpos_of_lt_find_pivot_column hcT' hc'res (lt_of_le_of_ne (hct.symm ▸ hT₃.2.2.1 ▸ htmax _ T₃ (hT₃.1.elim (λ h, h.symm ▸ hrelTT'') (λ h, h.trans (hrelT'T.trans hT₃.2.1))) _ hT₃.2.2.2 rfl) (by rwa [ne.def, T'.to_partition.injective_colg.eq_iff])), have nonpos_of_colg_eq : ∀ j, j ≠ c' → T'.to_partition.colg j = T.to_partition.colg c → T'.to_matrix obj j ≤ 0, from λ j hjc' hj, if hjc : j = c then by clear_aux_decl; subst j; exact nonpos_of_lt_find_pivot_column hcT' hc'res (lt_of_le_of_ne (hj.symm ▸ hct.symm ▸ htmax _ _ hrelTT _ hc rfl) (hs ▸ hj.symm ▸ colg_ne_rowg _ _ _)) else let ⟨T₃, hT₃⟩ := (colg_eq_or_exists_mem_pivot_column obj hrelTT').resolve_left (show T'.to_partition.colg j ≠ T.to_partition.colg j, by simpa [hj, T.to_partition.injective_colg.eq_iff, eq_comm] using hjc) in nonpos_of_lt_find_pivot_column hcT' hc'res (lt_of_le_of_ne (hct.symm ▸ hT₃.2.2.1 ▸ htmax _ T₃ (hT₃.1.elim (λ h, h.symm ▸ hrelTT'') (λ h, h.trans (hrelT'T.trans hT₃.2.1))) _ hT₃.2.2.2 rfl) (by rwa [ne.def, T'.to_partition.injective_colg.eq_iff])), have unique_row : ∀ i ≠ r, T.const i 0 = 0 → T.to_partition.rowg i ≠ T'.to_partition.rowg i → 0 ≤ T.to_matrix i c, from λ i hir hi0 hrow, let ⟨T₃, c₃, hc₃, hrow₃, hrelT₃T, hrelTT₃⟩ := exists_mem_pivot_column_of_rowg_ne _ hrelTT' hrelT'T hrow in have hrelT₃T₃ : rel obj T₃ T₃, from hrelT₃T.trans hrelTT₃, nonneg_of_lt_find_pivot_row (by exact hcobj0) (by rw [← hrow₃, ← restricted_eq_of_rel _ hrelT₃T]; exact colg_mem_restricted_of_rel_self _ hrelT₃T₃ hc₃) hc hr hi0 (lt_of_le_of_ne (by rw [hs, hct, ← hrow₃]; exact htmax _ _ hrelT₃T₃ _ hc₃ rfl) (by simpa [T.to_partition.injective_rowg.eq_iff])), not_unique_row_and_unique_col obj hcobj0 hc'obj0 hrc0 hflat hs hrobj hfickle hobj nonpos_of_colg_ne nonpos_of_colg_eq unique_row noncomputable instance fintype_rel (T : tableau m n) : fintype {T' | rel obj T' T} := fintype.of_injective (λ T', T'.val.to_partition) (λ T₁ T₂ h, subtype.eq $ tableau.ext (by rw [flat_eq_of_rel _ T₁.2, flat_eq_of_rel _ T₂.2]) h (by rw [restricted_eq_of_rel _ T₁.2, restricted_eq_of_rel _ T₂.2])) lemma rel_wf (m n : ℕ) (obj : fin m): well_founded (@rel m n obj) := subrelation.wf (show subrelation (@rel m n obj) (measure (λ T, fintype.card {T' | rel obj T' T})), from assume T₁ T₂ h, set.card_lt_card (set.ssubset_iff_subset_not_subset.2 ⟨λ T' hT', hT'.trans h, classical.not_forall.2 ⟨T₁, λ h', rel.irrefl _ (h' h)⟩⟩)) (measure_wf (λ T, fintype.card {T' | rel obj T' T})) end blands_rule @[derive _root_.decidable_eq] inductive termination : Type | while : termination | unbounded : termination | optimal : termination open termination instance : has_repr termination := ⟨λ t, termination.cases_on t "while" "unbounded" "optimal"⟩ instance : fintype termination := ⟨⟨quotient.mk [while, unbounded, optimal], dec_trivial⟩, λ x, by cases x; exact dec_trivial⟩ end simplex open simplex simplex.termination /-- The simplex algorithm -/ def simplex (w : feasible_tableau m n → bool) (obj : fin m) : Π (T : feasible_tableau m n), feasible_tableau m n × termination | T := cond (w T) (match find_pivot_column T.1 obj, @feasible_of_mem_pivot_row_and_column _ _ _ obj T.2, @rel.pivot m n obj _ T.2 with | none, hc, hrel := (T, optimal) | some c, hc, hrel := match find_pivot_row T.1 obj c, @hc _ rfl, (λ r, @hrel r c rfl) with | none, hr, hrel := (T, unbounded) | some r, hr, hrel := have wf : rel obj (pivot T.1 r c) T, from hrel _ rfl, simplex ⟨T.1.pivot r c, hr rfl⟩ end end) (T, while) using_well_founded {rel_tac := λ _ _, `[exact ⟨_, inv_image.wf feasible_tableau.to_tableau (rel_wf m n obj)⟩], dec_tac := tactic.assumption} namespace simplex lemma simplex_pivot {w : feasible_tableau m n → bool} {T : feasible_tableau m n} (hw : w T = tt) {obj : fin m} {r : fin m} {c : fin n} (hc : c ∈ find_pivot_column T.1 obj) (hr : r ∈ find_pivot_row T.1 obj c) : simplex w obj ⟨T.1.pivot r c, feasible_of_mem_pivot_row_and_column T.2 hc hr⟩ = simplex w obj T := by conv_rhs { rw simplex }; simp [hw, show _ = _, from hr, show _ = _, from hc, _match_1, _match_2] lemma simplex_spec_aux (w : feasible_tableau m n → bool) (obj : fin m) : Π (T : feasible_tableau m n), ((simplex w obj T).2 = while ∧ w (simplex w obj T).1 = ff) ∨ ((simplex w obj T).2 = optimal ∧ w (simplex w obj T).1 = tt ∧ find_pivot_column (simplex w obj T).1.1 obj = none) ∨ ((simplex w obj T).2 = unbounded ∧ w (simplex w obj T).1 = tt ∧ ∃ c, c ∈ find_pivot_column (simplex w obj T).1.1 obj ∧ find_pivot_row (simplex w obj T).1.1 obj c = none) | T := begin cases hw : w T, { rw simplex, simp [hw] }, { cases hc : find_pivot_column T.1 obj with c, { rw simplex, simp [hc, hw, _match_1] }, { cases hr : find_pivot_row T.1 obj c with r, { rw simplex, simp [hr, hc, hw, _match_1, _match_2] }, { rw [← simplex_pivot hw hc hr], exact have wf : rel obj (T.1.pivot r c) T, from rel.pivot T.2 hc hr, simplex_spec_aux _ } } } end using_well_founded {rel_tac := λ _ _, `[exact ⟨_, inv_image.wf feasible_tableau.to_tableau (rel_wf m n obj)⟩], dec_tac := tactic.assumption} lemma simplex_while_eq_ff {w : feasible_tableau m n → bool} {T : feasible_tableau m n} {obj : fin m} (hw : w T = ff) : simplex w obj T = (T, while) := by rw [simplex, hw]; refl lemma simplex_find_pivot_column_eq_none {w : feasible_tableau m n → bool} {T : feasible_tableau m n} (hw : w T = tt) {obj : fin m} (hc : find_pivot_column T.1 obj = none) : simplex w obj T = (T, optimal) := by rw simplex; simp [hc, hw, _match_1] lemma simplex_find_pivot_row_eq_none {w : feasible_tableau m n → bool} {T : feasible_tableau m n} {obj : fin m} (hw : w T = tt) {c} (hc : c ∈ find_pivot_column T.1 obj) (hr : find_pivot_row T.1 obj c = none) : simplex w obj T = (T, unbounded) := by rw simplex; simp [hw, show _ = _, from hc, hr, _match_1, _match_2] lemma simplex_induction (P : feasible_tableau m n → Prop) (w : feasible_tableau m n → bool) (obj : fin m): Π {T : feasible_tableau m n} (h0 : P T) (hpivot : ∀ {T' r c} (hw : w T' = tt) (hc : c ∈ find_pivot_column T'.1 obj) (hr : r ∈ find_pivot_row T'.1 obj c), P T' → P ⟨(↑T' : tableau m n).pivot r c, feasible_of_mem_pivot_row_and_column T'.2 hc hr⟩), P (simplex w obj T).1 | T := λ h0 hpivot, begin cases hw : w T, { rwa [simplex_while_eq_ff hw] }, { cases hc : find_pivot_column T.1 obj with c, { rwa [simplex_find_pivot_column_eq_none hw hc] }, { cases hr : find_pivot_row T.1 obj c with r, { rwa simplex_find_pivot_row_eq_none hw hc hr }, { rw [← simplex_pivot hw hc hr], exact have wf : rel obj (pivot T.1 r c) T, from rel.pivot T.2 hc hr, simplex_induction (hpivot hw hc hr h0) @hpivot } } } end using_well_founded {rel_tac := λ _ _, `[exact ⟨_, inv_image.wf feasible_tableau.to_tableau (rel_wf m n obj)⟩], dec_tac := tactic.assumption} @[simp] lemma simplex_simplex {w : feasible_tableau m n → bool} {T : feasible_tableau m n} {obj : fin m} : simplex w obj (simplex w obj T).1 = simplex w obj T := simplex_induction (λ T', simplex w obj T' = simplex w obj T) _ _ rfl (λ T' r c hw hc hr (ih : _ = _), by rw ← ih; exact simplex_pivot hw hc hr) /-- `simplex` does not move the row variable it is trying to maximise. -/ @[simp] lemma rowg_simplex (T : feasible_tableau m n) (w : feasible_tableau m n → bool) (obj : fin m) : ((simplex w obj T).1 : tableau m n).to_partition.rowg obj = T.to_partition.rowg obj := simplex_induction (λ T', T'.to_partition.rowg obj = T.to_partition.rowg obj) w obj rfl (λ T' r c hw hc hr, by simp [rowg_swap_of_ne _ (find_pivot_row_spec hr).1]; exact id) @[simp] lemma flat_simplex (T : feasible_tableau m n) (w : feasible_tableau m n → bool) (obj : fin m) : ((simplex w obj T).1 : tableau m n).flat = flat T := simplex_induction (λ T', flat (↑T' : tableau m n) = flat ↑T) w obj rfl (λ T' r c hw hc hr ih, have T'.to_matrix r c ≠ 0, from λ h, by simpa [h, lt_irrefl] using find_pivot_row_spec hr, begin rw [coe_mk (pivot (T'.to_tableau) r c), flat_pivot this, ih], end) @[simp] lemma restricted_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n → bool) (obj : fin m) : (T.simplex w obj hT).1.restricted = T.restricted := simplex_induction (λ T', T'.restricted = T.restricted) _ _ _ rfl (by simp { contextual := tt }) @[simp] lemma sol_set_simplex (T : tableau m n) (hT : feasible T) (w : tableau m n → bool) (obj : fin m) : (T.simplex w obj hT).1.sol_set = T.sol_set := by simp [sol_set] @[simp] lemma of_col_simplex_zero_mem_sol_set {w : tableau m n → bool} {T : tableau m n} {hT : feasible T} {obj : fin m} : (T.simplex w obj hT).1.of_col 0 ∈ sol_set T := by rw [← sol_set_simplex, of_col_zero_mem_sol_set_iff]; exact feasible_simplex @[simp] lemma of_col_simplex_rowg {w : tableau m n → bool} {T : tableau m n} {hT : feasible T} {obj : fin m} (x : cvec n) : (T.simplex w obj hT).1.of_col x (T.to_partition.rowg obj) = ((T.simplex w obj hT).1.to_matrix ⬝ x + (T.simplex w obj hT).1.const) obj := by rw [← of_col_rowg (T.simplex w obj hT).1 x obj, rowg_simplex] @[simp] lemma is_unbounded_above_simplex {T : tableau m n} {hT : feasible T} {w : tableau m n → bool} {obj : fin m} {v : fin (m + n)} : is_unbounded_above (T.simplex w obj hT).1 v ↔ is_unbounded_above T v := by simp [is_unbounded_above] @[simp] lemma is_optimal_simplex {T : tableau m n} {hT : feasible T} {w : tableau m n → bool} {obj : fin m} {x : cvec (m + n)} {v : fin (m + n)} : is_optimal (T.simplex w obj hT).1 x v ↔ is_optimal T x v := by simp [is_optimal] lemma termination_eq_while_iff {T : tableau m n} {hT : feasible T} {w : tableau m n → bool} {obj : fin m} : (T.simplex w obj hT).2 = while ↔ w (T.simplex w obj hT).1 = ff := by have := simplex_spec_aux w obj T hT; finish lemma termination_eq_optimal_iff_find_pivot_column_eq_none {T : tableau m n} {hT : feasible T} {w : tableau m n → bool} {obj : fin m} : (T.simplex w obj hT).2 = optimal ↔ w (T.simplex w obj hT).1 = tt ∧ find_pivot_column (T.simplex w obj hT).1 obj = none := by have := simplex_spec_aux w obj T hT; finish lemma termination_eq_unbounded_iff_find_pivot_row_eq_none {T : tableau m n} {hT : feasible T} {w : tableau m n → bool} {obj : fin m} : (T.simplex w obj hT).2 = unbounded ↔ w (T.simplex w obj hT).1 = tt ∧ ∃ c, c ∈ find_pivot_column (T.simplex w obj hT).1 obj ∧ find_pivot_row (T.simplex w obj hT).1 obj c = none := by have := simplex_spec_aux w obj T hT; finish lemma termination_eq_unbounded_iff_aux {T : tableau m n} {hT : feasible T} {w : tableau m n → bool} {obj : fin m} : (T.simplex w obj hT).2 = unbounded → w (T.simplex w obj hT).1 = tt ∧ is_unbounded_above T (T.to_partition.rowg obj) := begin rw termination_eq_unbounded_iff_find_pivot_row_eq_none, rintros ⟨_, c, hc⟩, simpa * using find_pivot_row_eq_none feasible_simplex hc.2 hc.1 end lemma termination_eq_optimal_iff {T : tableau m n} {hT : feasible T} {w : tableau m n → bool} {obj : fin m} : (T.simplex w obj hT).2 = optimal ↔ w (T.simplex w obj hT).1 = tt ∧ is_optimal T ((T.simplex w obj hT).1.of_col 0) (T.to_partition.rowg obj) := begin rw [termination_eq_optimal_iff_find_pivot_column_eq_none], split, { rintros ⟨_, hc⟩, simpa * using find_pivot_column_eq_none feasible_simplex hc }, { cases ht : (T.simplex w obj hT).2, { simp [*, termination_eq_while_iff] at * }, { cases termination_eq_unbounded_iff_aux ht, simp [*, not_optimal_of_unbounded_above right] }, { simp [*, termination_eq_optimal_iff_find_pivot_column_eq_none] at * } } end lemma termination_eq_unbounded_iff {T : tableau m n} {hT : feasible T} {w : tableau m n → bool} {obj : fin m} : (T.simplex w obj hT).2 = unbounded ↔ w (T.simplex w obj hT).1 = tt ∧ is_unbounded_above T (T.to_partition.rowg obj) := ⟨termination_eq_unbounded_iff_aux, begin have := @not_optimal_of_unbounded_above m n (T.simplex w obj hT).1 (T.to_partition.rowg obj) ((T.simplex w obj hT).1.of_col 0), cases ht : (T.simplex w obj hT).2; simp [termination_eq_optimal_iff, termination_eq_while_iff, *] at * end⟩ end simplex section add_row /-- adds a new row without making it a restricted variable. -/ def add_row (T : tableau m n) (fac : rvec (m + n)) (k : ℚ) : tableau (m + 1) n := { to_matrix := λ i j, if hm : i.1 < m then T.to_matrix (fin.cast_lt i hm) j else fac 0 (T.to_partition.colg j) + univ.sum (λ i' : fin m, fac 0 (T.to_partition.rowg i') * T.to_matrix i' j), const := λ i j, if hm : i.1 < m then T.const (fin.cast_lt i hm) j else k + univ.sum (λ i' : fin m, fac 0 (T.to_partition.rowg i') * T.const i' 0), to_partition := T.to_partition.add_row, restricted := T.restricted.map ⟨fin.castp, λ ⟨_, _⟩ ⟨_, _⟩ h, fin.eq_of_veq (fin.veq_of_eq h : _)⟩ } @[simp] lemma add_row_to_partition (T : tableau m n) (fac : rvec (m + n)) (k : ℚ) : (T.add_row fac k).to_partition = T.to_partition.add_row := rfl lemma add_row_to_matrix (T : tableau m n) (fac : rvec (m + n)) (k : ℚ) : (T.add_row fac k).to_matrix = λ i j, if hm : i.1 < m then T.to_matrix (fin.cast_lt i hm) j else fac 0 (T.to_partition.colg j) + univ.sum (λ i' : fin m, fac 0 (T.to_partition.rowg i') * T.to_matrix i' j) := rfl lemma add_row_const (T : tableau m n) (fac : rvec (m + n)) (k : ℚ) : (T.add_row fac k).const = λ i j, if hm : i.1 < m then T.const (fin.cast_lt i hm) j else k + univ.sum (λ i' : fin m, fac 0 (T.to_partition.rowg i') * T.const i' 0) := rfl lemma add_row_restricted (T : tableau m n) (fac : rvec (m + n)) (k : ℚ) : (T.add_row fac k).restricted = T.restricted.image fin.castp := by simp [add_row, map_eq_image] -- @[simp] lemma fin.cast_lt_cast_succ {n : ℕ} (a : fin n) (h : a.1 < n) : -- a.cast_succ.cast_lt h = a := by cases a; refl lemma minor_mem_flat_of_mem_add_row_flat {T : tableau m n} {fac : rvec (m + n)} {k : ℚ} {x : cvec (m + 1 + n)} : x ∈ (T.add_row fac k).flat → minor x fin.castp id ∈ T.flat := begin rw [mem_flat_iff, mem_flat_iff], intros h r, have := h (fin.cast_succ r), simp [add_row_rowg_cast_succ, add_row_const, add_row_to_matrix, (show (fin.cast_succ r).val < m, from r.2), add_row_colg] at this, simpa end lemma minor_mem_sol_set_of_mem_add_row_sol_set {T : tableau m n} {fac : rvec (m + n)} {k : ℚ} {x : cvec (m + 1 + n)} : x ∈ (T.add_row fac k).sol_set → minor x fin.castp id ∈ T.sol_set := and_implies minor_mem_flat_of_mem_add_row_flat begin assume h v, simp only [set.mem_set_of_eq, add_row_restricted, mem_image, exists_imp_distrib] at h, simpa [add_row_restricted, matrix.minor, id.def] using h (fin.castp v) v end lemma add_row_new_eq_sum_fac (T : tableau m n) (fac : rvec (m + n)) (k : ℚ) (x : cvec (m + 1 + n)) (hx : x ∈ (T.add_row fac k).flat) : x fin.lastp 0 = univ.sum (λ v : fin (m + n), fac 0 v * x (fin.castp v) 0) + k := calc x fin.lastp 0 = x ((T.add_row fac k).to_partition.rowg (fin.last _)) 0 : by simp [add_row_rowg_last] ... = univ.sum (λ j : fin n, _) + (T.add_row fac k).const _ _ : mem_flat_iff.1 hx _ ... = k + univ.sum (λ j, (fac 0 (T.to_partition.colg j) * x (T.to_partition.add_row.colg j) 0)) + (univ.sum (λ j, univ.sum (λ i, fac 0 (T.to_partition.rowg i) * T.to_matrix i j * x (T.to_partition.add_row.colg j) 0)) + univ.sum (λ i, fac 0 (T.to_partition.rowg i) * T.const i 0)) : by simp [add_row_to_matrix, add_row_const, fin.last, add_mul, sum_add_distrib, sum_mul] ... = k + univ.sum (λ j, (fac 0 (T.to_partition.colg j) * x (T.to_partition.add_row.colg j) 0)) + (univ.sum (λ i, univ.sum (λ j, fac 0 (T.to_partition.rowg i) * T.to_matrix i j * x (T.to_partition.add_row.colg j) 0)) + univ.sum (λ i, fac 0 (T.to_partition.rowg i) * T.const i 0)) : by rw [sum_comm] ... = k + univ.sum (λ j, (fac 0 (T.to_partition.colg j) * x (T.to_partition.add_row.colg j) 0)) + univ.sum (λ i : fin m, (fac 0 (T.to_partition.rowg i) * x (fin.castp (T.to_partition.rowg i)) 0)) : begin rw [← sum_add_distrib], have : ∀ r : fin m, x (fin.castp (T.to_partition.rowg r)) 0 = sum univ (λ (c : fin n), T.to_matrix r c * x (fin.castp (T.to_partition.colg c)) 0) + T.const r 0, from mem_flat_iff.1 (minor_mem_flat_of_mem_add_row_flat hx), simp [this, mul_add, add_row_colg, mul_sum, mul_assoc] end ... = ((univ.image T.to_partition.colg).sum (λ v, (fac 0 v * x (fin.castp v) 0)) + (univ.image T.to_partition.rowg).sum (λ v, (fac 0 v * x (fin.castp v) 0))) + k : by rw [sum_image, sum_image]; simp [add_row_rowg_cast_succ, add_row_colg, T.to_partition.injective_rowg.eq_iff, T.to_partition.injective_colg.eq_iff] ... = _ : begin rw [← sum_union], congr, simpa [finset.ext, eq_comm] using T.to_partition.eq_rowg_or_colg, { simp [finset.ext, eq_comm, T.to_partition.rowg_ne_colg] {contextual := tt} } end end add_row open tableau.simplex tableau.simplex.termination -- /-- Boolean returning whether or not it is consistent to make `obj` nonnegative. -- Only makes sense for feasible tableaux. -/ -- def max_nonneg (T : tableau m n) (hT : feasible T) (obj : fin m) : bool := -- let T' := T.simplex (λ T', T'.const obj 0 < 0) hT obj in -- match T'.2 with -- | while := tt -- | unbounded := tt -- | optimal := ff -- end -- lemma max_nonneg_iff {T : tableau m n} {hT : T.feasible} {obj : fin m} : -- max_nonneg T hT obj ↔ ∃ x : cvec (m + n), x ∈ T.sol_set ∧ 0 ≤ x (T.to_partition.rowg obj) 0 := -- let T' := T.simplex (λ T', T'.const obj 0 < 0) hT obj in -- begin -- cases h : T'.2, -- { simp only [max_nonneg, h, bool.coe_sort_tt, coe_tt, true_iff], -- rw [termination_eq_while_iff] at h, -- use T'.1.of_col 0, -- simpa [T'] using h }, -- { simp only [max_nonneg, h, bool.coe_sort_tt, coe_tt, true_iff], -- rw [termination_eq_unbounded_iff, is_unbounded_above] at h, -- tauto }, -- { simp only [max_nonneg, h, not_exists, false_iff, not_and, bool.coe_sort_ff, not_le], -- rw [termination_eq_optimal_iff, is_optimal, to_bool_iff] at h, -- assume x hx, -- refine lt_of_le_of_lt _ h.1, -- simpa using h.2 x hx } -- end section sign_of_max_row def sign_of_max_row (T : tableau m n) (hT : feasible T) (obj : fin m) : ℤ := let T' := T.simplex (λ T', T'.const obj 0 ≤ 0) obj hT in match T'.2 with | while := 1 | unbounded := 1 | optimal := if T'.1.const obj 0 = 0 then 0 else -1 end lemma sign_of_max_row_eq_zero {T : tableau m n} {hT : feasible T} {obj : fin m} : sign_of_max_row T hT obj = 0 ↔ ∃ x : cvec (m + n), x (T.to_partition.rowg obj) 0 = 0 ∧ is_optimal T x (T.to_partition.rowg obj) := let T' := T.simplex (λ T', T'.const obj 0 ≤ 0) obj hT in begin cases h : T'.2, { simp only [sign_of_max_row, *, termination_eq_while_iff, is_optimal, classical.not_forall, not_exists, exists_prop, false_iff, not_and, not_le, to_bool_ff_iff, one_ne_zero] at *, assume x hx0 hxs, use [T'.1.of_col 0], simpa [T', hx0] }, { simp only [sign_of_max_row, *, termination_eq_unbounded_iff, is_unbounded_above, classical.not_forall, not_exists, exists_prop, false_iff, not_and, not_le, to_bool_iff, one_ne_zero, is_optimal] at * {contextual := tt}, cases h.2 1 with y hy, assume x hxs hx, use [y, hy.1], exact lt_of_lt_of_le zero_lt_one hy.2 }, { simp only [sign_of_max_row, *, termination_eq_optimal_iff, is_unbounded_above, classical.not_forall, not_exists, exists_prop, false_iff, not_and, not_le, to_bool_iff, one_ne_zero] at * {contextual := tt}, split_ifs with h0, { simp only [eq_self_iff_true, true_iff], refine ⟨_, _, _, h.2.2⟩; simp [h0] }, { simp only [is_optimal, not_exists, neg_eq_zero, one_ne_zero, false_iff, not_and], assume x hx0 hsx , exact absurd (le_antisymm h.1 (by simpa [hx0] using h.2.2 x hsx)) h0 } } end lemma sign_of_max_row_eq_one {T : tableau m n} {hT : feasible T} {obj : fin m} : sign_of_max_row T hT obj = 1 ↔ ∃ x : cvec (m + n), x ∈ sol_set T ∧ 0 < x (T.to_partition.rowg obj) 0 := let T' := T.simplex (λ T', T'.const obj 0 ≤ 0) obj hT in begin cases h : T'.2, { simp only [sign_of_max_row, *, termination_eq_while_iff, eq_self_iff_true, true_iff, to_bool_ff_iff, not_le] at *, exact ⟨T'.1.of_col 0, by simp *⟩ }, { simp only [sign_of_max_row, *, termination_eq_unbounded_iff, eq_self_iff_true, true_iff, to_bool_iff] at *, cases h.2 1 with y hy, use [y, hy.1], exact lt_of_lt_of_le zero_lt_one hy.2 }, { simp only [sign_of_max_row, *, termination_eq_optimal_iff, to_bool_iff] at *, suffices : ∀ (x : matrix (fin (m + n)) (fin 1) ℚ), x ∈ sol_set T → x (T.to_partition.rowg obj) 0 ≤ 0, { split_ifs; simpa [show ¬(-1 : ℤ) = 1, from dec_trivial] }, assume x hx, exact le_trans (h.2.2 x hx) (by simpa using h.1) } end lemma sign_of_max_row_eq_neg_one {T : tableau m n} {hT : feasible T} {obj : fin m} : sign_of_max_row T hT obj = -1 ↔ ∀ x : cvec (m + n), x ∈ sol_set T → x (T.to_partition.rowg obj) 0 < 0 := let T' := T.simplex (λ T', T'.const obj 0 ≤ 0) obj hT in begin cases h : T'.2, { simp only [sign_of_max_row, *, termination_eq_while_iff, false_iff, classical.not_forall, not_lt, show (1 : ℤ) ≠ -1, from dec_trivial, to_bool_ff_iff, not_le] at *, use T'.1.of_col 0, simp [le_of_lt h] }, { simp only [sign_of_max_row, *, termination_eq_unbounded_iff, false_iff, classical.not_forall, show (1 : ℤ) ≠ -1, from dec_trivial, to_bool_iff, not_lt, not_le] at *, cases h.2 1 with y hy, use [y, hy.1], exact le_trans zero_le_one hy.2 }, { simp only [sign_of_max_row, *, termination_eq_optimal_iff, to_bool_iff] at *, split_ifs, { simp [show (0 : ℤ) ≠ -1, from dec_trivial, classical.not_forall], use T'.1.of_col 0, simp * }, { simp only [eq_self_iff_true, true_iff], assume x hx, exact lt_of_le_of_lt (h.2.2 x hx) (by apply lt_of_le_of_ne; simp; tauto) } } end end sign_of_max_row section to_row def to_row_pivot_row (T : tableau m n) (c : fin n) : option (fin m) := ((list.fin_range m).filter (λ r, (T.to_partition.rowg r ∈ T.restricted ∧ T.to_matrix r c < 0))).argmax (λ r, T.const r 0 / T.to_matrix r c) lemma feasible_to_row_pivot_row {T : tableau m n} (hT : feasible T) {r} (c : fin n) (hr : r ∈ to_row_pivot_row T c) : feasible (T.pivot r c) := begin simp only [to_row_pivot_row, list.mem_argmax_iff, list.mem_filter] at hr, refine feasible_pivot hT (by tauto) (by tauto) _, assume i hir hir0, have hic0 : T.to_matrix i c < 0, from neg_of_mul_pos_left hir0 (inv_nonpos.2 $ le_of_lt $ by tauto), rw [abs_of_nonpos (div_nonpos_of_nonneg_of_neg (hT _ hir) hic0), abs_of_nonpos (div_nonpos_of_nonneg_of_neg (hT r (by tauto)) hr.1.2.2), neg_le_neg_iff], apply hr.2.1, simp, tauto end def to_row (T : tableau m n) (hT : feasible T) (c : fin n) : option (tableau m n × fin m) := to_row_pivot_row T c >>= λ r, (T.pivot r c, r) end to_row section sign_of_max def sign_of_max (T : tableau m n) (hT : feasible T) (v : fin (m + n)) : ℤ := row_col_cases_on T.to_partition v (sign_of_max_row T hT) (λ c, match to_row T hT c with | some (T, r) := sign_of_max_row T hT r end sign_of_max section assertge end assertge end tableau section test open tableau tableau.simplex def list.to_matrix (m :ℕ) (n : ℕ) (l : list (list ℚ)) : matrix (fin m) (fin n) ℚ := λ i j, (l.nth_le i sorry).nth_le j sorry instance has_repr_fin_fun {n : ℕ} {α : Type*} [has_repr α] : has_repr (fin n → α) := ⟨λ f, repr (vector.of_fn f).to_list⟩ instance {m n} : has_repr (matrix (fin m) (fin n) ℚ) := has_repr_fin_fun -- def T : tableau 4 5 := -- { to_matrix := list.to_matrix 4 5 [[-1, -3/4, 20, -1/2, 6], [0, 1/4, -8, -1, 9], -- [0, 1/2, -12, -1/2, 3], [0,0,0,1,0]], -- const := (list.to_matrix 1 4 [[0,0,0,1]])ᵀ, -- to_partition := default _, -- restricted := univ } -- def T : tableau 4 5 := -- { to_matrix := list.to_matrix 4 5 [[1, 3/5, 20, 1/2, -6], [19, 1, -8, -1, 9], -- [5, 1/2, -12, 1/2, 3], [13,0.1,11,21,0]], -- const := (list.to_matrix 1 4 [[3,1,51,1]])ᵀ, -- to_partition := default _, -- restricted := univ } -- set_option profiler true -- #print tactic.eval_expr def T : tableau 25 10 := { to_matrix := list.to_matrix 25 10 [[0, 0, 0, 0, 1, 0, 1, 0, 1, -1], [-1, 1, 0, -1, 1, 0, 1, -1, 0, 0], [0, -1, 1, 1, 1, 0, 0, 0, 1, 0], [1, 1, 1, 0, 1, -1, 1, -1, 1, -1], [0, 1, 1, -1, -1, 1, -1, 1, -1, 1], [0, -1, 1, -1, 1, 1, 0, 1, 0, -1], [-1, 0, 0, -1, -1, 1, 1, 0, -1, -1], [-1, 0, 0, -1, 0, -1, 0, 0, -1, 1], [-1, 0, 0, 1, -1, 1, -1, -1, 1, 0], [1, 0, 0, 0, 1, -1, 1, 0, -1, 1], [0, -1, 1, 0, 0, 1, 0, -1, 0, 0], [-1, 1, -1, 1, 1, 0, 1, 0, 1, 0], [1, 1, 1, 1, -1, 0, 0, 0, -1, 0], [-1, -1, 0, 0, 1, 0, 1, 1, -1, 0], [0, 0, -1, 1, -1, 0, 0, 1, 0, -1], [-1, 0, -1, 1, 1, 1, 0, 0, 0, 0], [1, 0, -1, 1, 0, -1, -1, 1, -1, 1], [-1, 1, -1, 1, -1, -1, -1, 1, -1, 1], [-1, 0, 0, 0, 1, -1, 1, -1, -1, 1], [-1, -1, -1, 1, 0, 1, -1, 1, 0, 0], [-1, 0, 0, 0, -1, -1, 1, -1, 0, 1], [-1, 0, 0, -1, 1, 1, 1, -1, 1, 0], [0, -1, 0, 0, 0, -1, 0, 1, 0, -1], [1, -1, 1, 0, 0, 1, 0, 1, 0, -1], [0, -1, -1, 0, 0, 0, -1, 0, 1, 0]], const := λ i _, if i.1 < 8 then 0 else 1, to_partition := default _, restricted := univ } --(λ x, x.1 < 25) } -- #eval tableau.sizeof _ _ T -- #print tc.rec -- #eval 1000 * 1000 -- run_cmd do tactic.is_def_eq `(1000000) `(1000 * 1000) --#reduce let s := T.simplex (λ _, tt) dec_trivial 0 in s.2 #eval let s := T.simplex (λ _, tt) 0 dec_trivial in (s.2, s.1.to_partition.row_indices.1, s.1.const) -- (s.2, s.1.const 0 0, s.1.to_partition.row_indices.1) end test
87a95aa54d83176c3748c6b91d478fef28eafe1c
9dd3f3912f7321eb58ee9aa8f21778ad6221f87c
/library/init/data/nat/div.lean
89855becd06e0bdf96dc3cc56bd2a133d8a27d7c
[ "Apache-2.0" ]
permissive
bre7k30/lean
de893411bcfa7b3c5572e61b9e1c52951b310aa4
5a924699d076dab1bd5af23a8f910b433e598d7a
refs/heads/master
1,610,900,145,817
1,488,006,845,000
1,488,006,845,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
1,168
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.wf init.data.nat.basic namespace nat private def div_rec_lemma {x y : nat} : 0 < y ∧ y ≤ x → x - y < x := λ h, and.rec (λ ypos ylex, sub_lt (nat.lt_of_lt_of_le ypos ylex) ypos) h private def div.F (x : nat) (f : Π x₁, x₁ < x → nat → nat) (y : nat) : nat := if h : 0 < y ∧ y ≤ x then f (x - y) (div_rec_lemma h) y + 1 else zero protected def div := well_founded.fix lt_wf div.F instance : has_div nat := ⟨nat.div⟩ lemma div_def (x y : nat) : div x y = if h : 0 < y ∧ y ≤ x then div (x - y) y + 1 else 0 := congr_fun (well_founded.fix_eq lt_wf div.F x) y private def mod.F (x : nat) (f : Π x₁, x₁ < x → nat → nat) (y : nat) : nat := if h : 0 < y ∧ y ≤ x then f (x - y) (div_rec_lemma h) y else x protected def mod := well_founded.fix lt_wf mod.F instance : has_mod nat := ⟨nat.mod⟩ lemma mod_def (x y : nat) : mod x y = if h : 0 < y ∧ y ≤ x then mod (x - y) y else x := congr_fun (well_founded.fix_eq lt_wf mod.F x) y end nat
9eed7c1c389d4395b400007c18c8e80f5f5022aa
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/differential_object.lean
9fecf2aa77e80da48315d9d62cc6878a3f556d9c
[]
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
5,759
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.shift import Mathlib.category_theory.concrete_category.default import Mathlib.PostPort universes v u l u_1 namespace Mathlib /-! # Differential objects in a category. A differential object in a category with zero morphisms and a shift is an object `X` equipped with a morphism `d : X ⟶ X⟦1⟧`, such that `d^2 = 0`. We build the category of differential objects, and some basic constructions such as the forgetful functor, and zero morphisms and zero objects. -/ namespace category_theory /-- A differential object in a category with zero morphisms and a shift is an object `X` equipped with a morphism `d : X ⟶ X⟦1⟧`, such that `d^2 = 0`. -/ structure differential_object (C : Type u) [category C] [limits.has_zero_morphisms C] [has_shift C] where X : C d : X ⟶ functor.obj (equivalence.functor (shift C ^ 1)) X d_squared' : autoParam (d ≫ functor.map (equivalence.functor (shift C ^ 1)) d = 0) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) @[simp] theorem differential_object.d_squared {C : Type u} [category C] [limits.has_zero_morphisms C] [has_shift C] (c : differential_object C) : differential_object.d c ≫ functor.map (equivalence.functor (shift C)) (differential_object.d c) = 0 := sorry namespace differential_object /-- A morphism of differential objects is a morphism commuting with the differentials. -/ structure hom {C : Type u} [category C] [limits.has_zero_morphisms C] [has_shift C] (X : differential_object C) (Y : differential_object C) where f : X X ⟶ X Y comm' : autoParam (d X ≫ functor.map (equivalence.functor (shift C ^ 1)) f = f ≫ d Y) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) @[simp] theorem hom.comm {C : Type u} [category C] [limits.has_zero_morphisms C] [has_shift C] {X : differential_object C} {Y : differential_object C} (c : hom X Y) : d X ≫ functor.map (equivalence.functor (shift C)) (hom.f c) = hom.f c ≫ d Y := sorry @[simp] theorem hom.comm_assoc {C : Type u} [category C] [limits.has_zero_morphisms C] [has_shift C] {X : differential_object C} {Y : differential_object C} (c : hom X Y) {X' : C} (f' : functor.obj (equivalence.functor (shift C)) (X Y) ⟶ X') : d X ≫ functor.map (equivalence.functor (shift C)) (hom.f c) ≫ f' = hom.f c ≫ d Y ≫ f' := sorry namespace hom /-- The identity morphism of a differential object. -/ @[simp] theorem id_f {C : Type u} [category C] [limits.has_zero_morphisms C] [has_shift C] (X : differential_object C) : f (id X) = 𝟙 := Eq.refl (f (id X)) /-- The composition of morphisms of differential objects. -/ @[simp] theorem comp_f {C : Type u} [category C] [limits.has_zero_morphisms C] [has_shift C] {X : differential_object C} {Y : differential_object C} {Z : differential_object C} (f : hom X Y) (g : hom Y Z) : f (comp f g) = f f ≫ f g := Eq.refl (f (comp f g)) end hom protected instance category_of_differential_objects {C : Type u} [category C] [limits.has_zero_morphisms C] [has_shift C] : category (differential_object C) := category.mk @[simp] theorem id_f {C : Type u} [category C] [limits.has_zero_morphisms C] [has_shift C] (X : differential_object C) : hom.f 𝟙 = 𝟙 := rfl @[simp] theorem comp_f {C : Type u} [category C] [limits.has_zero_morphisms C] [has_shift C] {X : differential_object C} {Y : differential_object C} {Z : differential_object C} (f : X ⟶ Y) (g : Y ⟶ Z) : hom.f (f ≫ g) = hom.f f ≫ hom.f g := rfl /-- The forgetful functor taking a differential object to its underlying object. -/ def forget (C : Type u) [category C] [limits.has_zero_morphisms C] [has_shift C] : differential_object C ⥤ C := functor.mk (fun (X : differential_object C) => X X) fun (X Y : differential_object C) (f : X ⟶ Y) => hom.f f protected instance forget_faithful (C : Type u) [category C] [limits.has_zero_morphisms C] [has_shift C] : faithful (forget C) := faithful.mk protected instance has_zero_morphisms (C : Type u) [category C] [limits.has_zero_morphisms C] [has_shift C] : limits.has_zero_morphisms (differential_object C) := limits.has_zero_morphisms.mk @[simp] theorem zero_f {C : Type u} [category C] [limits.has_zero_morphisms C] [has_shift C] (P : differential_object C) (Q : differential_object C) : hom.f 0 = 0 := rfl end differential_object end category_theory namespace category_theory namespace differential_object protected instance has_zero_object (C : Type u) [category C] [limits.has_zero_object C] [limits.has_zero_morphisms C] [has_shift C] : limits.has_zero_object (differential_object C) := limits.has_zero_object.mk (mk 0 0) (fun (X : differential_object C) => unique.mk { default := hom.mk 0 } sorry) fun (X : differential_object C) => unique.mk { default := hom.mk 0 } sorry end differential_object namespace differential_object protected instance concrete_category_of_differential_objects (C : Type (u + 1)) [large_category C] [concrete_category C] [limits.has_zero_morphisms C] [has_shift C] : concrete_category (differential_object C) := concrete_category.mk (forget C ⋙ forget C) protected instance category_theory.has_forget₂ (C : Type (u + 1)) [large_category C] [concrete_category C] [limits.has_zero_morphisms C] [has_shift C] : has_forget₂ (differential_object C) C := has_forget₂.mk (forget C)
634ea73524da543b99cd72b8c501b4268350820e
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/notation_priority.lean
ddbc34bb8bed2948024254c2e42ddb6cf8b5f294
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
419
lean
constant f : nat → nat → nat constant g : nat → nat → nat infix [priority 10] + := f infix [priority 20] + := g variables a b : nat infix [priority std.priority.default+1] + := f infix + := g example : a + b = f a b := rfl infix [priority std.priority.default+2] + := g example : a + b = g a b := rfl infix + := f infix + := g infix [priority std.priority.default+1] + := g example : a + b = g a b := rfl
653c4a88e457fe129808dcd45baeeeb29db9dfe1
94637389e03c919023691dcd05bd4411b1034aa5
/src/inClassNotes/predicate_logic/exists.lean
25aa888caad405b5dfd6a15ded7c1cbe4dac9464
[]
no_license
kevinsullivan/complogic-s21
7c4eef2105abad899e46502270d9829d913e8afc
99039501b770248c8ceb39890be5dfe129dc1082
refs/heads/master
1,682,985,669,944
1,621,126,241,000
1,621,126,241,000
335,706,272
0
38
null
1,618,325,669,000
1,612,374,118,000
Lean
UTF-8
Lean
false
false
2,845
lean
/- Exists introduction. To prove ∃ (p : P), Q -/ /- A proof of ∃ (p : P), Q is a *dependent* pair, ⟨ p, q ⟩, where (p : P) is a "witness" to the existential proposition, and q is a proof of Q. Very often, Q will be *about* p, e.g., that p is an "odd prime", or a "nice person". Q will be the result of aplying a predicate Q' to P. Q is short for Q' p, with Q' : Person → Prop being a property of a person, such as the property of being nice. ∃ (p : Person), Q' p thus asserts that there is *some* person with property Q'. So a proof of this proposition will be a dependent pair, ⟨ (p : P), (q : Q' p) ⟩, with Q' a predicate on values, p, of type P. -/ example : ∃ (n : nat), n = 0 := ⟨ 0, eq.refl 0 ⟩ /- There exists a natural number that is the square of another natural number. -/ example : ∃ (n : nat), ∃ (m : nat), n = m*m := ⟨4, ⟨2, rfl⟩ ⟩ example : ∃ (n : nat), ∃ (m : nat), n = m*m := begin end /- If everyone likes Mary then someone likes Mary. -/ axiom Person : Type axiom Mary : Person axiom Likes : Person → Person → Prop example : (∀ (p : Person), Likes p Mary) → (∃ (q : Person), Likes q Mary) := begin assume h, refine ⟨Mary, _⟩, apply h Mary, end /- Exercise: ∃ elimination. -/ /- Practice -/ -- Proof of transitivity of → example : ∀ (P Q R : Prop), (P → Q) → (Q → R) → (P → R) := begin assume P Q R pq qr p, apply qr (pq p), end example : ∀ (P Q R : Prop), (P → Q) → (Q → R) → (P → R) := λ P Q R pq qr p, qr (pq p ) example : ∀ (P : Prop), P ∧ ¬ P → false := begin assume (P : Prop), assume (pnp : P ∧ ¬ P), cases pnp with p np, apply np p, end example : ∀ (n : nat), n = 0 ∨ n ≠ 0 := begin assume n, cases n, apply or.inl rfl, apply or.inr _, assume ns, cases ns, end example : ∀ (n : nat), n = 0 ∨ n ≠ 0 := λ (n : nat), match n with | nat.zero := or.inl (rfl) | (nat.succ n') := or.inr (λ sn, match sn with end ) end /- Prove, ∀ (n : nat), n = 0 ∨ n ≠ 0. Proof. To begin, we'll assume that n is an arbitrary natural number (forall introduction) and in this context what remains to be proved is n = 0 ∨ n ≠ 0. Proof: By case analysis on the possible forms of n. Case 1, base case: n = 0. In this case the disjuction is 0 = 0 ∨ ) ≠ 0 is true because the left disjuct is trivially true (by reflexivity of equality). Case 2: n = succ n'. What remains to be proved is succ n' = 0 ∨ succ n' ≠ 0. We will prove this is true by proving that the right hand side is true: succ n' ≠ 0. Proof: This is true by Peano's axioms of arithmetic. Zero is axomatically not equal to any other natural number. -/ example : ∀ (n : nat), ∃ m, m = n + 2 := λ n, begin apply exists.intro (n+2), apply rfl, end
9057c9abade40b5155a24ddad84ea98a94f6d110
08bd4ba4ca87dba1f09d2c96a26f5d65da81f4b4
/src/Lean/Linter/Builtin.lean
cb5a4b7bc0f28d1bf3f64d8f2e904d72dc8cdd71
[ "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "Apache-2.0", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
gebner/lean4
d51c4922640a52a6f7426536ea669ef18a1d9af5
8cd9ce06843c9d42d6d6dc43d3e81e3b49dfc20f
refs/heads/master
1,685,732,780,391
1,672,962,627,000
1,673,459,398,000
373,307,283
0
0
Apache-2.0
1,691,316,730,000
1,622,669,271,000
Lean
UTF-8
Lean
false
false
1,232
lean
import Lean.Linter.Util import Lean.Elab.Command namespace Lean.Linter register_builtin_option linter.suspiciousUnexpanderPatterns : Bool := { defValue := true, descr := "enable the 'suspicious unexpander patterns' linter" } def getLinterSuspiciousUnexpanderPatterns (o : Options) : Bool := getLinterValue linter.suspiciousUnexpanderPatterns o def suspiciousUnexpanderPatterns : Linter := fun cmdStx => do unless getLinterSuspiciousUnexpanderPatterns (← getOptions) do return -- check `[app_unexpander _]` defs defined by pattern matching let `($[$_:docComment]? @[$[$attrs:attr],*] $(_vis)? def $_ : $_ $[| $pats => $_]*) := cmdStx | return unless attrs.any (· matches `(attr| app_unexpander $_)) do return for pat in pats do let patHead ← match pat with | `(`($patHead:ident $_args*)) => pure patHead | `(`($patHead:ident)) => pure patHead | _ => continue logLint linter.suspiciousUnexpanderPatterns patHead "Unexpanders should match the function name against an antiquotation `$_` so as to be independent of the specific pretty printing of the name." builtin_initialize addLinter suspiciousUnexpanderPatterns end Lean.Linter
4dec453f1c12e7494e1a2bd22d7d3d23756b262f
5d166a16ae129621cb54ca9dde86c275d7d2b483
/library/init/meta/environment.lean
c959105a2145f06016dd33d2ffbd33c679ef3bc1
[ "Apache-2.0" ]
permissive
jcarlson23/lean
b00098763291397e0ac76b37a2dd96bc013bd247
8de88701247f54d325edd46c0eed57aeacb64baf
refs/heads/master
1,611,571,813,719
1,497,020,963,000
1,497,021,515,000
93,882,536
1
0
null
1,497,029,896,000
1,497,029,896,000
null
UTF-8
Lean
false
false
6,023
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.meta.declaration init.meta.exceptional init.data.option.basic import init.meta.rb_map meta constant environment : Type namespace environment /-- Information for a projection declaration - `cname` is the name of the constructor associated with the projection. - `nparams` is the number of constructor parameters - `idx` is the parameter being projected by this projection - `is_class` is tt iff this is a class projection. -/ structure projection_info := (cname : name) (nparams : nat) (idx : nat) (is_class : bool) /- Create a standard environment using the given trust level -/ meta constant mk_std : nat → environment /- Return the trust level of the given environment -/ meta constant trust_lvl : environment → nat /- Add a new declaration to the environment -/ meta constant add : environment → declaration → exceptional environment /- Retrieve a declaration from the environment -/ meta constant get : environment → name → exceptional declaration meta def contains (env : environment) (d : name) : bool := match env.get d with | exceptional.success _ := tt | exceptional.exception ._ _ := ff end /- Return tt iff the given name is a namespace -/ meta constant is_namespace : environment → name → bool /- Add a new inductive datatype to the environment name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/ meta constant add_inductive : environment → name → list name → nat → expr → list (name × expr) → bool → exceptional environment /- Return tt iff the given name is an inductive datatype -/ meta constant is_inductive : environment → name → bool /- Return tt iff the given name is a constructor -/ meta constant is_constructor : environment → name → bool /- Return tt iff the given name is a recursor -/ meta constant is_recursor : environment → name → bool /- Return tt iff the given name is a recursive inductive datatype -/ meta constant is_recursive : environment → name → bool /- Return the name of the inductive datatype of the given constructor. -/ meta constant inductive_type_of : environment → name → option name /- Return the constructors of the inductive datatype with the given name -/ meta constant constructors_of : environment → name → list name /- Return the recursor of the given inductive datatype -/ meta constant recursor_of : environment → name → option name /- Return the number of parameters of the inductive datatype -/ meta constant inductive_num_params : environment → name → nat /- Return the number of indices of the inductive datatype -/ meta constant inductive_num_indices : environment → name → nat /- Return tt iff the inductive datatype recursor supports dependent elimination -/ meta constant inductive_dep_elim : environment → name → bool /- Return tt iff the given name is a generalized inductive datatype -/ meta constant is_ginductive : environment → name → bool meta constant is_projection : environment → name → option projection_info /- Fold over declarations in the environment -/ meta constant fold {α :Type} : environment → α → (declaration → α → α) → α /- (relation_info env n) returns some value if n is marked as a relation in the given environment. the tuple contains: total number of arguments of the relation, lhs position and rhs position. -/ meta constant relation_info : environment → name → option (nat × nat × nat) /- (refl_for env R) returns the name of the reflexivity theorem for the relation R -/ meta constant refl_for : environment → name → option name /- (symm_for env R) returns the name of the symmetry theorem for the relation R -/ meta constant symm_for : environment → name → option name /- (trans_for env R) returns the name of the transitivity theorem for the relation R -/ meta constant trans_for : environment → name → option name /- (decl_olean env d) returns the name of the .olean file where d was defined. The result is none if d was not defined in an imported file. -/ meta constant decl_olean : environment → name → option string /- (decl_pos env d) returns the source location of d if available. -/ meta constant decl_pos : environment → name → option pos /- Return the fields of the structure with the given name, or `none` if it is not a structure -/ meta constant structure_fields : environment → name → option (list name) /- (get_class_attribute_symbols env attr_name) return symbols occurring in instances of type classes tagged with the attribute `attr_name`. Example: [algebra] -/ meta constant get_class_attribute_symbols : environment → name → name_set meta constant fingerprint : environment → nat open expr meta constant unfold_untrusted_macros : environment → expr → expr meta def is_constructor_app (env : environment) (e : expr) : bool := is_constant (get_app_fn e) && is_constructor env (const_name (get_app_fn e)) meta def is_refl_app (env : environment) (e : expr) : option (name × expr × expr) := match (refl_for env (const_name (get_app_fn e))) with | (some n) := if get_app_num_args e ≥ 2 then some (n, app_arg (app_fn e), app_arg e) else none | none := none end /-- Return true if 'n' has been declared in the current file -/ meta def in_current_file (env : environment) (n : name) : bool := (env.decl_olean n).is_none && env.contains n meta def is_definition (env : environment) (n : name) : bool := match env.get n with | exceptional.success (declaration.defn _ _ _ _ _ _) := tt | _ := ff end end environment meta instance : has_to_string environment := ⟨λ e, "[environment]"⟩ meta instance : inhabited environment := ⟨environment.mk_std 0⟩
f9cbd2de5b1b2d88979950d2f2903d49c925ceba
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/number_theory/modular.lean
5f213bf57bb3fa2d87ce821f51e63392dda1c8c4
[ "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
16,553
lean
/- Copyright (c) 2021 Alex Kontorovich and Heather Macbeth and Marc Masdeu. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alex Kontorovich, Heather Macbeth, Marc Masdeu -/ import analysis.complex.upper_half_plane import linear_algebra.general_linear_group /-! # The action of the modular group SL(2, ℤ) on the upper half-plane We define the action of `SL(2,ℤ)` on `ℍ` (via restriction of the `SL(2,ℝ)` action in `analysis.complex.upper_half_plane`). We then define the standard fundamental domain (`modular_group.fundamental_domain`, `𝒟`) for this action and show (`modular_group.exists_smul_mem_fundamental_domain`) that any point in `ℍ` can be moved inside `𝒟`. Standard proofs make use of the identity `g • z = a / c - 1 / (c (cz + d))` for `g = [[a, b], [c, d]]` in `SL(2)`, but this requires separate handling of whether `c = 0`. Instead, our proof makes use of the following perhaps novel identity (see `modular_group.smul_eq_lc_row0_add`): `g • z = (a c + b d) / (c^2 + d^2) + (d z - c) / ((c^2 + d^2) (c z + d))` where there is no issue of division by zero. Another feature is that we delay until the very end the consideration of special matrices `T=[[1,1],[0,1]]` (see `modular_group.T`) and `S=[[0,-1],[1,0]]` (see `modular_group.S`), by instead using abstract theory on the properness of certain maps (phrased in terms of the filters `filter.cocompact`, `filter.cofinite`, etc) to deduce existence theorems, first to prove the existence of `g` maximizing `(g•z).im` (see `modular_group.exists_max_im`), and then among those, to minimize `|(g•z).re|` (see `modular_group.exists_row_one_eq_and_min_re`). -/ open complex matrix matrix.special_linear_group upper_half_plane noncomputable theory local notation `SL(` n `, ` R `)`:= special_linear_group (fin n) R local prefix `↑ₘ`:1024 := @coe _ (matrix (fin 2) (fin 2) ℤ) _ open_locale upper_half_plane complex_conjugate local attribute [instance] fintype.card_fin_even namespace modular_group section upper_half_plane_action /-- For a subring `R` of `ℝ`, the action of `SL(2, R)` on the upper half-plane, as a restriction of the `SL(2, ℝ)`-action defined by `upper_half_plane.mul_action`. -/ instance {R : Type*} [comm_ring R] [algebra R ℝ] : mul_action SL(2, R) ℍ := mul_action.comp_hom ℍ (map (algebra_map R ℝ)) lemma coe_smul (g : SL(2, ℤ)) (z : ℍ) : ↑(g • z) = num g z / denom g z := rfl lemma re_smul (g : SL(2, ℤ)) (z : ℍ) : (g • z).re = (num g z / denom g z).re := rfl @[simp] lemma smul_coe (g : SL(2, ℤ)) (z : ℍ) : (g : SL(2,ℝ)) • z = g • z := rfl @[simp] lemma neg_smul (g : SL(2, ℤ)) (z : ℍ) : -g • z = g • z := show ↑(-g) • _ = _, by simp [neg_smul g z] lemma im_smul (g : SL(2, ℤ)) (z : ℍ) : (g • z).im = (num g z / denom g z).im := rfl lemma im_smul_eq_div_norm_sq (g : SL(2, ℤ)) (z : ℍ) : (g • z).im = z.im / (complex.norm_sq (denom g z)) := im_smul_eq_div_norm_sq g z @[simp] lemma denom_apply (g : SL(2, ℤ)) (z : ℍ) : denom g z = ↑ₘg 1 0 * z + ↑ₘg 1 1 := by simp end upper_half_plane_action section bottom_row /-- The two numbers `c`, `d` in the "bottom_row" of `g=[[*,*],[c,d]]` in `SL(2, ℤ)` are coprime. -/ lemma bottom_row_coprime {R : Type*} [comm_ring R] (g : SL(2, R)) : is_coprime ((↑g : matrix (fin 2) (fin 2) R) 1 0) ((↑g : matrix (fin 2) (fin 2) R) 1 1) := begin use [- (↑g : matrix (fin 2) (fin 2) R) 0 1, (↑g : matrix (fin 2) (fin 2) R) 0 0], rw [add_comm, ←neg_mul_eq_neg_mul, ←sub_eq_add_neg, ←det_fin_two], exact g.det_coe, end /-- Every pair `![c, d]` of coprime integers is the "bottom_row" of some element `g=[[*,*],[c,d]]` of `SL(2,ℤ)`. -/ lemma bottom_row_surj {R : Type*} [comm_ring R] : set.surj_on (λ g : SL(2, R), @coe _ (matrix (fin 2) (fin 2) R) _ g 1) set.univ {cd | is_coprime (cd 0) (cd 1)} := begin rintros cd ⟨b₀, a, gcd_eqn⟩, let A := ![![a, -b₀], cd], have det_A_1 : det A = 1, { convert gcd_eqn, simp [A, det_fin_two, (by ring : a * (cd 1) + b₀ * (cd 0) = b₀ * (cd 0) + a * (cd 1))] }, refine ⟨⟨A, det_A_1⟩, set.mem_univ _, _⟩, ext; simp [A] end end bottom_row section tendsto_lemmas open filter continuous_linear_map local attribute [instance] matrix.normed_group matrix.normed_space local attribute [simp] coe_smul /-- The function `(c,d) → |cz+d|^2` is proper, that is, preimages of bounded-above sets are finite. -/ lemma tendsto_norm_sq_coprime_pair (z : ℍ) : filter.tendsto (λ p : fin 2 → ℤ, ((p 0 : ℂ) * z + p 1).norm_sq) cofinite at_top := begin let π₀ : (fin 2 → ℝ) →ₗ[ℝ] ℝ := linear_map.proj 0, let π₁ : (fin 2 → ℝ) →ₗ[ℝ] ℝ := linear_map.proj 1, let f : (fin 2 → ℝ) →ₗ[ℝ] ℂ := π₀.smul_right (z:ℂ) + π₁.smul_right 1, have f_def : ⇑f = λ (p : fin 2 → ℝ), (p 0 : ℂ) * ↑z + p 1, { ext1, dsimp only [linear_map.coe_proj, real_smul, linear_map.coe_smul_right, linear_map.add_apply], rw mul_one, }, have : (λ (p : fin 2 → ℤ), norm_sq ((p 0 : ℂ) * ↑z + ↑(p 1))) = norm_sq ∘ f ∘ (λ p : fin 2 → ℤ, (coe : ℤ → ℝ) ∘ p), { ext1, rw f_def, dsimp only [function.comp], rw [of_real_int_cast, of_real_int_cast], }, rw this, have hf : f.ker = ⊥, { let g : ℂ →ₗ[ℝ] (fin 2 → ℝ) := linear_map.pi ![im_lm, im_lm.comp ((z:ℂ) • (conj_ae : ℂ →ₗ[ℝ] ℂ))], suffices : ((z:ℂ).im⁻¹ • g).comp f = linear_map.id, { exact linear_map.ker_eq_bot_of_inverse this }, apply linear_map.ext, intros c, have hz : (z:ℂ).im ≠ 0 := z.2.ne', rw [linear_map.comp_apply, linear_map.smul_apply, linear_map.id_apply], ext i, dsimp only [g, pi.smul_apply, linear_map.pi_apply, smul_eq_mul], fin_cases i, { show ((z : ℂ).im)⁻¹ * (f c).im = c 0, rw [f_def, add_im, of_real_mul_im, of_real_im, add_zero, mul_left_comm, inv_mul_cancel hz, mul_one], }, { show ((z : ℂ).im)⁻¹ * ((z : ℂ) * conj (f c)).im = c 1, rw [f_def, ring_hom.map_add, ring_hom.map_mul, mul_add, mul_left_comm, mul_conj, conj_of_real, conj_of_real, ← of_real_mul, add_im, of_real_im, zero_add, inv_mul_eq_iff_eq_mul₀ hz], simp only [of_real_im, of_real_re, mul_im, zero_add, mul_zero] } }, have h₁ := (linear_equiv.closed_embedding_of_injective hf).tendsto_cocompact, have h₂ : tendsto (λ p : fin 2 → ℤ, (coe : ℤ → ℝ) ∘ p) cofinite (cocompact _), { convert tendsto.pi_map_Coprod (λ i, int.tendsto_coe_cofinite), { rw Coprod_cofinite }, { rw Coprod_cocompact } }, exact tendsto_norm_sq_cocompact_at_top.comp (h₁.comp h₂) end /-- Given `coprime_pair` `p=(c,d)`, the matrix `[[a,b],[*,*]]` is sent to `a*c+b*d`. This is the linear map version of this operation. -/ def lc_row0 (p : fin 2 → ℤ) : (matrix (fin 2) (fin 2) ℝ) →ₗ[ℝ] ℝ := ((p 0:ℝ) • linear_map.proj 0 + (p 1:ℝ) • linear_map.proj 1 : (fin 2 → ℝ) →ₗ[ℝ] ℝ).comp (linear_map.proj 0) @[simp] lemma lc_row0_apply (p : fin 2 → ℤ) (g : matrix (fin 2) (fin 2) ℝ) : lc_row0 p g = p 0 * g 0 0 + p 1 * g 0 1 := rfl lemma lc_row0_apply' (a b : ℝ) (c d : ℤ) (v : fin 2 → ℝ) : lc_row0 ![c, d] ![![a, b], v] = c * a + d * b := by simp /-- Linear map sending the matrix [a, b; c, d] to the matrix [ac₀ + bd₀, - ad₀ + bc₀; c, d], for some fixed `(c₀, d₀)`. -/ @[simps] def lc_row0_extend {cd : fin 2 → ℤ} (hcd : is_coprime (cd 0) (cd 1)) : (matrix (fin 2) (fin 2) ℝ) ≃ₗ[ℝ] matrix (fin 2) (fin 2) ℝ := linear_equiv.Pi_congr_right ![begin refine linear_map.general_linear_group.general_linear_equiv ℝ (fin 2 → ℝ) (general_linear_group.to_linear (plane_conformal_matrix (cd 0 : ℝ) (-(cd 1 : ℝ)) _)), norm_cast, rw neg_sq, exact hcd.sq_add_sq_ne_zero end, linear_equiv.refl ℝ (fin 2 → ℝ)] /-- The map `lc_row0` is proper, that is, preimages of cocompact sets are finite in `[[* , *], [c, d]]`.-/ theorem tendsto_lc_row0 {cd : fin 2 → ℤ} (hcd : is_coprime (cd 0) (cd 1)) : tendsto (λ g : {g : SL(2, ℤ) // g 1 = cd}, lc_row0 cd ↑(↑g : SL(2, ℝ))) cofinite (cocompact ℝ) := begin let mB : ℝ → (matrix (fin 2) (fin 2) ℝ) := λ t, ![![t, (-(1:ℤ):ℝ)], coe ∘ cd], have hmB : continuous mB, { simp only [continuous_pi_iff, fin.forall_fin_two], have : ∀ c : ℝ, continuous (λ x : ℝ, c) := λ c, continuous_const, exact ⟨⟨continuous_id, @this (-1 : ℤ)⟩, ⟨this (cd 0), this (cd 1)⟩⟩ }, refine filter.tendsto.of_tendsto_comp _ (comap_cocompact hmB), let f₁ : SL(2, ℤ) → matrix (fin 2) (fin 2) ℝ := λ g, matrix.map (↑g : matrix _ _ ℤ) (coe : ℤ → ℝ), have cocompact_ℝ_to_cofinite_ℤ_matrix : tendsto (λ m : matrix (fin 2) (fin 2) ℤ, matrix.map m (coe : ℤ → ℝ)) cofinite (cocompact _), { simpa only [Coprod_cofinite, Coprod_cocompact] using tendsto.pi_map_Coprod (λ i : fin 2, tendsto.pi_map_Coprod (λ j : fin 2, int.tendsto_coe_cofinite)) }, have hf₁ : tendsto f₁ cofinite (cocompact _) := cocompact_ℝ_to_cofinite_ℤ_matrix.comp subtype.coe_injective.tendsto_cofinite, have hf₂ : closed_embedding (lc_row0_extend hcd) := (lc_row0_extend hcd).to_continuous_linear_equiv.to_homeomorph.closed_embedding, convert hf₂.tendsto_cocompact.comp (hf₁.comp subtype.coe_injective.tendsto_cofinite) using 1, ext ⟨g, rfl⟩ i j : 3, fin_cases i; [fin_cases j, skip], { simp [mB, f₁, mul_vec, dot_product, fin.sum_univ_two] }, { convert congr_arg (λ n : ℤ, (-n:ℝ)) g.det_coe.symm using 1, simp [f₁, mul_vec, dot_product, mB, fin.sum_univ_two, matrix.det_fin_two], ring }, { refl } end /-- This replaces `(g•z).re = a/c + *` in the standard theory with the following novel identity: `g • z = (a c + b d) / (c^2 + d^2) + (d z - c) / ((c^2 + d^2) (c z + d))` which does not need to be decomposed depending on whether `c = 0`. -/ lemma smul_eq_lc_row0_add {p : fin 2 → ℤ} (hp : is_coprime (p 0) (p 1)) (z : ℍ) {g : SL(2,ℤ)} (hg : ↑ₘg 1 = p) : ↑(g • z) = ((lc_row0 p ↑(g : SL(2, ℝ))) : ℂ) / (p 0 ^ 2 + p 1 ^ 2) + ((p 1 : ℂ) * z - p 0) / ((p 0 ^ 2 + p 1 ^ 2) * (p 0 * z + p 1)) := begin have nonZ1 : (p 0 : ℂ) ^ 2 + (p 1) ^ 2 ≠ 0 := by exact_mod_cast hp.sq_add_sq_ne_zero, have : (coe : ℤ → ℝ) ∘ p ≠ 0 := λ h, hp.ne_zero ((@int.cast_injective ℝ _ _ _).comp_left h), have nonZ2 : (p 0 : ℂ) * z + p 1 ≠ 0 := by simpa using linear_ne_zero _ z this, field_simp [nonZ1, nonZ2, denom_ne_zero, -upper_half_plane.denom, -denom_apply], rw (by simp : (p 1 : ℂ) * z - p 0 = ((p 1) * z - p 0) * ↑(det (↑g : matrix (fin 2) (fin 2) ℤ))), rw [←hg, det_fin_two], simp only [int.coe_cast_ring_hom, coe_matrix_coe, coe_fn_eq_coe, int.cast_mul, of_real_int_cast, map_apply, denom, int.cast_sub], ring, end lemma tendsto_abs_re_smul (z:ℍ) {p : fin 2 → ℤ} (hp : is_coprime (p 0) (p 1)) : tendsto (λ g : {g : SL(2, ℤ) // g 1 = p}, |((g : SL(2, ℤ)) • z).re|) cofinite at_top := begin suffices : tendsto (λ g : (λ g : SL(2, ℤ), g 1) ⁻¹' {p}, (((g : SL(2, ℤ)) • z).re)) cofinite (cocompact ℝ), { exact tendsto_norm_cocompact_at_top.comp this }, have : ((p 0 : ℝ) ^ 2 + p 1 ^ 2)⁻¹ ≠ 0, { apply inv_ne_zero, exact_mod_cast hp.sq_add_sq_ne_zero }, let f := homeomorph.mul_right₀ _ this, let ff := homeomorph.add_right (((p 1:ℂ)* z - p 0) / ((p 0 ^ 2 + p 1 ^ 2) * (p 0 * z + p 1))).re, convert ((f.trans ff).closed_embedding.tendsto_cocompact).comp (tendsto_lc_row0 hp), ext g, change ((g : SL(2, ℤ)) • z).re = (lc_row0 p ↑(↑g : SL(2, ℝ))) / (p 0 ^ 2 + p 1 ^ 2) + (((p 1:ℂ )* z - p 0) / ((p 0 ^ 2 + p 1 ^ 2) * (p 0 * z + p 1))).re, exact_mod_cast (congr_arg complex.re (smul_eq_lc_row0_add hp z g.2)) end end tendsto_lemmas section fundamental_domain local attribute [simp] coe_smul re_smul /-- For `z : ℍ`, there is a `g : SL(2,ℤ)` maximizing `(g•z).im` -/ lemma exists_max_im (z : ℍ) : ∃ g : SL(2, ℤ), ∀ g' : SL(2, ℤ), (g' • z).im ≤ (g • z).im := begin classical, let s : set (fin 2 → ℤ) := {cd | is_coprime (cd 0) (cd 1)}, have hs : s.nonempty := ⟨![1, 1], is_coprime_one_left⟩, obtain ⟨p, hp_coprime, hp⟩ := filter.tendsto.exists_within_forall_le hs (tendsto_norm_sq_coprime_pair z), obtain ⟨g, -, hg⟩ := bottom_row_surj hp_coprime, refine ⟨g, λ g', _⟩, rw [im_smul_eq_div_norm_sq, im_smul_eq_div_norm_sq, div_le_div_left], { simpa [← hg] using hp (g' 1) (bottom_row_coprime g') }, { exact z.im_pos }, { exact norm_sq_denom_pos g' z }, { exact norm_sq_denom_pos g z }, end /-- Given `z : ℍ` and a bottom row `(c,d)`, among the `g : SL(2,ℤ)` with this bottom row, minimize `|(g•z).re|`. -/ lemma exists_row_one_eq_and_min_re (z:ℍ) {cd : fin 2 → ℤ} (hcd : is_coprime (cd 0) (cd 1)) : ∃ g : SL(2,ℤ), ↑ₘg 1 = cd ∧ (∀ g' : SL(2,ℤ), ↑ₘg 1 = ↑ₘg' 1 → |(g • z).re| ≤ |(g' • z).re|) := begin haveI : nonempty {g : SL(2, ℤ) // g 1 = cd} := let ⟨x, hx⟩ := bottom_row_surj hcd in ⟨⟨x, hx.2⟩⟩, obtain ⟨g, hg⟩ := filter.tendsto.exists_forall_le (tendsto_abs_re_smul z hcd), refine ⟨g, g.2, _⟩, { intros g1 hg1, have : g1 ∈ ((λ g : SL(2, ℤ), g 1) ⁻¹' {cd}), { rw [set.mem_preimage, set.mem_singleton_iff], exact eq.trans hg1.symm (set.mem_singleton_iff.mp (set.mem_preimage.mp g.2)) }, exact hg ⟨g1, this⟩ }, end /-- The matrix `T = [[1,1],[0,1]]` as an element of `SL(2,ℤ)` -/ def T : SL(2,ℤ) := ⟨![![1, 1], ![0, 1]], by norm_num [matrix.det_fin_two]⟩ /-- The matrix `T' (= T⁻¹) = [[1,-1],[0,1]]` as an element of `SL(2,ℤ)` -/ def T' : SL(2,ℤ) := ⟨![![1, -1], ![0, 1]], by norm_num [matrix.det_fin_two]⟩ /-- The matrix `S = [[0,-1],[1,0]]` as an element of `SL(2,ℤ)` -/ def S : SL(2,ℤ) := ⟨![![0, -1], ![1, 0]], by norm_num [matrix.det_fin_two]⟩ /-- The standard (closed) fundamental domain of the action of `SL(2,ℤ)` on `ℍ` -/ def fundamental_domain : set ℍ := {z | 1 ≤ (complex.norm_sq z) ∧ |z.re| ≤ (1 : ℝ) / 2} localized "notation `𝒟` := modular_group.fundamental_domain" in modular /-- If `|z|<1`, then applying `S` strictly decreases `im` -/ lemma im_lt_im_S_smul {z : ℍ} (h: norm_sq z < 1) : z.im < (S • z).im := begin have : z.im < z.im / norm_sq (z:ℂ), { have imz : 0 < z.im := im_pos z, apply (lt_div_iff z.norm_sq_pos).mpr, nlinarith }, convert this, simp only [im_smul_eq_div_norm_sq], field_simp [norm_sq_denom_ne_zero, norm_sq_ne_zero, S] end /-- Any `z : ℍ` can be moved to `𝒟` by an element of `SL(2,ℤ)` -/ lemma exists_smul_mem_fundamental_domain (z : ℍ) : ∃ g : SL(2,ℤ), g • z ∈ 𝒟 := begin -- obtain a g₀ which maximizes im (g • z), obtain ⟨g₀, hg₀⟩ := exists_max_im z, -- then among those, minimize re obtain ⟨g, hg, hg'⟩ := exists_row_one_eq_and_min_re z (bottom_row_coprime g₀), refine ⟨g, _⟩, -- `g` has same max im property as `g₀` have hg₀' : ∀ (g' : SL(2,ℤ)), (g' • z).im ≤ (g • z).im, { have hg'' : (g • z).im = (g₀ • z).im, { rw [im_smul_eq_div_norm_sq, im_smul_eq_div_norm_sq, denom_apply, denom_apply, hg] }, simpa only [hg''] using hg₀ }, split, { -- Claim: `1 ≤ ⇑norm_sq ↑(g • z)`. If not, then `S•g•z` has larger imaginary part contrapose! hg₀', refine ⟨S * g, _⟩, rw mul_action.mul_smul, exact im_lt_im_S_smul hg₀' }, { show |(g • z).re| ≤ 1 / 2, -- if not, then either `T` or `T'` decrease |Re|. rw abs_le, split, { contrapose! hg', refine ⟨T * g, by simp [T, matrix.mul, matrix.dot_product, fin.sum_univ_succ], _⟩, rw mul_action.mul_smul, have : |(g • z).re + 1| < |(g • z).re| := by cases abs_cases ((g • z).re + 1); cases abs_cases (g • z).re; linarith, convert this, simp [T] }, { contrapose! hg', refine ⟨T' * g, by simp [T', matrix.mul, matrix.dot_product, fin.sum_univ_succ], _⟩, rw mul_action.mul_smul, have : |(g • z).re - 1| < |(g • z).re| := by cases abs_cases ((g • z).re - 1); cases abs_cases (g • z).re; linarith, convert this, simp [T', sub_eq_add_neg] } } end end fundamental_domain end modular_group
6145ec58e0ddba848dd9faff3282fe7e66d5d126
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_unit_dep.lean
9a4f323015a6dd4688747daaca71fceebf31c3f0
[ "Apache-2.0" ]
permissive
soonhokong/lean
cb8aa01055ffe2af0fb99a16b4cda8463b882cd1
38607e3eb57f57f77c0ac114ad169e9e4262e24f
refs/heads/master
1,611,187,284,081
1,450,766,737,000
1,476,122,547,000
11,513,992
2
0
null
1,401,763,102,000
1,374,182,235,000
C++
UTF-8
Lean
false
false
826
lean
constant p : nat → Prop constant q : Π a, p a → Prop set_option blast.strategy "unit" example (a : nat) (h₁ : p a) (h₂ : ∀ h : p a, q a h) : q a h₁ := by blast example (a : nat) (h₂ : ∀ h : p a, q a h) (h₁ : p a) : q a h₁ := by blast example (a b : nat) (H : ∀ (p₁ : p a) (p₂ : p b), q b p₂ → q a p₁) (h₁ : p a) (h₂ : p b) : q b h₂ → q a h₁ := by blast example (a b : nat) (h₂ : p b) (H : ∀ (p₁ : p a) (p₂ : p b), q b p₂ → q a p₁) (h₁ : p a) : q b h₂ → q a h₁ := by blast example (a b : nat) (h₂ : p b) (h₁ : p a) (H : ∀ (p₁ : p a) (p₂ : p b), q b p₂ → q a p₁) : q b h₂ → q a h₁ := by blast example (a b : nat) (h₁ : p a) (H : ∀ (p₁ : p a) (p₂ : p b), q b p₂ → q a p₁) (h₂ : p b) : q b h₂ → q a h₁ := by blast
76a629af76719a7a532b4215a684d69cacb86dd8
4727251e0cd73359b15b664c3170e5d754078599
/src/group_theory/group_action/sub_mul_action.lean
cc8224d09a9434085a44f85627f77f2de93e447d
[ "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,188
lean
/- Copyright (c) 2020 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.hom.group_action import algebra.module.basic import data.set_like.basic import group_theory.group_action.basic /-! # Sets invariant to a `mul_action` In this file we define `sub_mul_action R M`; a subset of a `mul_action R M` which is closed with respect to scalar multiplication. For most uses, typically `submodule R M` is more powerful. ## Main definitions * `sub_mul_action.mul_action` - the `mul_action R M` transferred to the subtype. * `sub_mul_action.mul_action'` - the `mul_action S M` transferred to the subtype when `is_scalar_tower S R M`. * `sub_mul_action.is_scalar_tower` - the `is_scalar_tower S R M` transferred to the subtype. ## Tags submodule, mul_action -/ open function universes u u' u'' v variables {S : Type u'} {T : Type u''} {R : Type u} {M : Type v} set_option old_structure_cmd true /-- A sub_mul_action is a set which is closed under scalar multiplication. -/ structure sub_mul_action (R : Type u) (M : Type v) [has_scalar R M] : Type v := (carrier : set M) (smul_mem' : ∀ (c : R) {x : M}, x ∈ carrier → c • x ∈ carrier) namespace sub_mul_action variables [has_scalar R M] instance : set_like (sub_mul_action R M) M := ⟨sub_mul_action.carrier, λ p q h, by cases p; cases q; congr'⟩ @[simp] lemma mem_carrier {p : sub_mul_action R M} {x : M} : x ∈ p.carrier ↔ x ∈ (p : set M) := iff.rfl @[ext] theorem ext {p q : sub_mul_action R M} (h : ∀ x, x ∈ p ↔ x ∈ q) : p = q := set_like.ext h /-- Copy of a sub_mul_action with a new `carrier` equal to the old one. Useful to fix definitional equalities.-/ protected def copy (p : sub_mul_action R M) (s : set M) (hs : s = ↑p) : sub_mul_action R M := { carrier := s, smul_mem' := hs.symm ▸ p.smul_mem' } @[simp] lemma coe_copy (p : sub_mul_action R M) (s : set M) (hs : s = ↑p) : (p.copy s hs : set M) = s := rfl lemma copy_eq (p : sub_mul_action R M) (s : set M) (hs : s = ↑p) : p.copy s hs = p := set_like.coe_injective hs instance : has_bot (sub_mul_action R M) := ⟨{ carrier := ∅, smul_mem' := λ c, set.not_mem_empty}⟩ instance : inhabited (sub_mul_action R M) := ⟨⊥⟩ end sub_mul_action namespace sub_mul_action section has_scalar variables [has_scalar R M] variables (p : sub_mul_action R M) variables {r : R} {x : M} lemma smul_mem (r : R) (h : x ∈ p) : r • x ∈ p := p.smul_mem' r h instance : has_scalar R p := { smul := λ c x, ⟨c • x.1, smul_mem _ c x.2⟩ } variables {p} @[simp, norm_cast] lemma coe_smul (r : R) (x : p) : ((r • x : p) : M) = r • ↑x := rfl @[simp, norm_cast] lemma coe_mk (x : M) (hx : x ∈ p) : ((⟨x, hx⟩ : p) : M) = x := rfl variables (p) /-- Embedding of a submodule `p` to the ambient space `M`. -/ protected def subtype : p →[R] M := by refine {to_fun := coe, ..}; simp [coe_smul] @[simp] theorem subtype_apply (x : p) : p.subtype x = x := rfl lemma subtype_eq_val : ((sub_mul_action.subtype p) : p → M) = subtype.val := rfl end has_scalar section mul_action_monoid variables [monoid R] [mul_action R M] section variables [has_scalar S R] [has_scalar S M] [is_scalar_tower S R M] variables (p : sub_mul_action R M) lemma smul_of_tower_mem (s : S) {x : M} (h : x ∈ p) : s • x ∈ p := by { rw [←one_smul R x, ←smul_assoc], exact p.smul_mem _ h } instance has_scalar' : has_scalar S p := { smul := λ c x, ⟨c • x.1, smul_of_tower_mem _ c x.2⟩ } instance : is_scalar_tower S R p := { smul_assoc := λ s r x, subtype.ext $ smul_assoc s r ↑x } @[simp, norm_cast] lemma coe_smul_of_tower (s : S) (x : p) : ((s • x : p) : M) = s • ↑x := rfl @[simp] lemma smul_mem_iff' {G} [group G] [has_scalar G R] [mul_action G M] [is_scalar_tower G R M] (g : G) {x : M} : g • x ∈ p ↔ x ∈ p := ⟨λ h, inv_smul_smul g x ▸ p.smul_of_tower_mem g⁻¹ h, p.smul_of_tower_mem g⟩ instance [has_scalar Sᵐᵒᵖ R] [has_scalar Sᵐᵒᵖ M] [is_scalar_tower Sᵐᵒᵖ R M] [is_central_scalar S M] : is_central_scalar S p := { op_smul_eq_smul := λ r x, subtype.ext $ op_smul_eq_smul r x } end section variables [monoid S] [has_scalar S R] [mul_action S M] [is_scalar_tower S R M] variables (p : sub_mul_action R M) /-- If the scalar product forms a `mul_action`, then the subset inherits this action -/ instance mul_action' : mul_action S p := { smul := (•), one_smul := λ x, subtype.ext $ one_smul _ x, mul_smul := λ c₁ c₂ x, subtype.ext $ mul_smul c₁ c₂ x } instance : mul_action R p := p.mul_action' end /-- Orbits in a `sub_mul_action` coincide with orbits in the ambient space. -/ lemma coe_image_orbit {p : sub_mul_action R M} (m : p) : coe '' mul_action.orbit R m = mul_action.orbit R (m : M) := (set.range_comp _ _).symm /- -- Previously, the relatively useless : lemma orbit_of_sub_mul {p : sub_mul_action R M} (m : p) : (mul_action.orbit R m : set M) = mul_action.orbit R (m : M) := rfl -/ /-- Stabilizers in monoid sub_mul_action coincide with stabilizers in the ambient space -/ lemma stabilizer_of_sub_mul.submonoid {p : sub_mul_action R M} (m : p) : mul_action.stabilizer.submonoid R m = mul_action.stabilizer.submonoid R (m : M) := begin ext, simp only [mul_action.mem_stabilizer_submonoid_iff, ← sub_mul_action.coe_smul, set_like.coe_eq_coe] end end mul_action_monoid section mul_action_group variables [group R] [mul_action R M] /-- Stabilizers in group sub_mul_action coincide with stabilizers in the ambient space -/ lemma stabilizer_of_sub_mul {p : sub_mul_action R M} (m : p) : mul_action.stabilizer R m = mul_action.stabilizer R (m : M) := begin rw ← subgroup.to_submonoid_eq, exact stabilizer_of_sub_mul.submonoid m, end end mul_action_group section module variables [semiring R] [add_comm_monoid M] variables [module R M] variables (p : sub_mul_action R M) lemma zero_mem (h : (p : set M).nonempty) : (0 : M) ∈ p := let ⟨x, hx⟩ := h in zero_smul R (x : M) ▸ p.smul_mem 0 hx /-- If the scalar product forms a `module`, and the `sub_mul_action` is not `⊥`, then the subset inherits the zero. -/ instance [n_empty : nonempty p] : has_zero p := { zero := ⟨0, n_empty.elim $ λ x, p.zero_mem ⟨x, x.prop⟩⟩ } end module section add_comm_group variables [ring R] [add_comm_group M] variables [module R M] variables (p p' : sub_mul_action R M) variables {r : R} {x y : M} lemma neg_mem (hx : x ∈ p) : -x ∈ p := by { rw ← neg_one_smul R, exact p.smul_mem _ hx } @[simp] lemma neg_mem_iff : -x ∈ p ↔ x ∈ p := ⟨λ h, by { rw ←neg_neg x, exact neg_mem _ h}, neg_mem _⟩ instance : has_neg p := ⟨λx, ⟨-x.1, neg_mem _ x.2⟩⟩ @[simp, norm_cast] lemma coe_neg (x : p) : ((-x : p) : M) = -x := rfl end add_comm_group end sub_mul_action namespace sub_mul_action variables [group_with_zero S] [monoid R] [mul_action R M] variables [has_scalar S R] [mul_action S M] [is_scalar_tower S R M] variables (p : sub_mul_action R M) {s : S} {x y : M} theorem smul_mem_iff (s0 : s ≠ 0) : s • x ∈ p ↔ x ∈ p := p.smul_mem_iff' (units.mk0 s s0) end sub_mul_action
e2f04200c159bb36aee30f9fb10cdee008d3b56f
cc060cf567f81c404a13ee79bf21f2e720fa6db0
/lean/20170706-simp.lean
8b68b31b969c9cefffb495b1e2c0f7e26364eecc
[ "Apache-2.0" ]
permissive
semorrison/proof
cf0a8c6957153bdb206fd5d5a762a75958a82bca
5ee398aa239a379a431190edbb6022b1a0aa2c70
refs/heads/master
1,610,414,502,842
1,518,696,851,000
1,518,696,851,000
78,375,937
2
1
null
null
null
null
UTF-8
Lean
false
false
1,286
lean
structure Category := ( Obj : Type ) ( Hom : Obj → Obj → Type ) ( identity : Π X : Obj, Hom X X ) ( compose : Π { X Y Z : Obj }, Hom X Y → Hom Y Z → Hom X Z ) structure Functor (C : Category) (D : Category) := (onObjects : C.Obj → D.Obj) (onMorphisms : Π { X Y : C.Obj }, C.Hom X Y → D.Hom (onObjects X) (onObjects Y)) definition ProductCategory (C D : Category) : Category := { Obj := C.Obj × D.Obj, Hom := (λ X Y : C.Obj × D.Obj, C.Hom (X.fst) (Y.fst) × D.Hom (X.snd) (Y.snd)), identity := λ X, ⟨ C.identity (X.fst), D.identity (X.snd) ⟩, compose := λ _ _ _ f g, (C.compose (f.fst) (g.fst), D.compose (f.snd) (g.snd)) } lemma Bifunctor_diagonal_identities_1 { C : Category } ( F : Functor (ProductCategory C C) C ) ( X : C.Obj ) ( f g : C.Hom X X ) : C.compose (@Functor.onMorphisms _ _ F (X, X) (X, X) (C.identity X, g)) (@Functor.onMorphisms _ _ F (X, X) (X, X) (f, C.identity X)) = @Functor.onMorphisms _ _ F (X, X) (X, X) (f, g) := begin -- simp {single_pass := tt}, -- fails with 'simplify tactic failed to simplify' simp {max_steps := 20}, -- fails with 'simplify failed, maximum number of steps exceeded' -- neither should not suffice to finish the proof! end
c62aad53bc99ebda4fa7eaba97039c5e0effb1fd
798dd332c1ad790518589a09bc82459fb12e5156
/category_theory/natural_isomorphism.lean
c20ceeefee57ebe4cbbc1195eff8ef58d07b6e37
[ "Apache-2.0" ]
permissive
tobiasgrosser/mathlib
b040b7eb42d5942206149371cf92c61404de3c31
120635628368ec261e031cefc6d30e0304088b03
refs/heads/master
1,644,803,442,937
1,536,663,752,000
1,536,663,907,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,069
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Tim Baumann, Stephen Morgan, Scott Morrison import category_theory.isomorphism import category_theory.functor_category open category_theory namespace category_theory.nat_iso universes u₁ u₂ v₁ v₂ variables {C : Type u₁} [𝒞 : category.{u₁ v₁} C] {D : Type u₂} [𝒟 : category.{u₂ v₂} D] include 𝒞 𝒟 def app {F G : C ⥤ D} (α : F ≅ G) (X : C) : F X ≅ G X := { hom := (α : F ⟶ G) X, inv := (α.symm : G ⟶ F) X, hom_inv_id' := begin rw [← functor.category.comp_app, iso.hom_inv_id], refl, end, inv_hom_id' := begin rw [← functor.category.comp_app, iso.inv_hom_id], refl, end } instance {F G : C ⥤ D} : has_coe_to_fun (F ≅ G) := { F := λ α, Π X : C, (F X) ≅ (G X), coe := λ α, app α } @[simp] lemma comp_app {F G H : C ⥤ D} (α : F ≅ G) (β : G ≅ H) (X : C) : ((α ≪≫ β) : F ⟹ H) X = α X ≪≫ β X := rfl @[simp] lemma hom_eq_coe {F G : C ⥤ D} (α : F ≅ G) (X : C) : α.hom X = (α : F ⟶ G) X := rfl @[simp] lemma inv_eq_symm_coe {F G : C ⥤ D} (α : F ≅ G) (X : C) : α.inv X = (α.symm : G ⟶ F) X := rfl variables {F G : C ⥤ D} instance hom_app_is_iso (α : F ≅ G) (X : C) : is_iso ((α : F ⟶ G) X) := { inv := α.inv X, hom_inv_id' := begin dsimp at *, erw [←functor.category.comp_app, iso.hom_inv_id, ←functor.category.id_app] end, inv_hom_id' := begin dsimp at *, erw [←functor.category.comp_app, iso.inv_hom_id, ←functor.category.id_app] end } instance inv_app_is_iso (α : F ≅ G) (X : C) : is_iso ((α.symm : G ⟶ F) X) := { inv := α.hom X, hom_inv_id' := begin dsimp at *, erw [is_iso.hom_inv_id] end, inv_hom_id' := begin dsimp at *, erw [is_iso.hom_inv_id] end } variables {X Y : C} @[simp] lemma naturality_1 (α : F ≅ G) (f : X ⟶ Y) : ((α.symm : G ⟶ F) X) ≫ (F.map f) ≫ ((α : F ⟶ G) Y) = G.map f := begin erw [nat_trans.naturality, ←category.assoc, is_iso.hom_inv_id, category.id_comp] end @[simp] lemma naturality_2 (α : F ≅ G) (f : X ⟶ Y) : ((α : F ⟶ G) X) ≫ (G.map f) ≫ ((α.symm : G ⟶ F) Y) = F.map f := begin erw [nat_trans.naturality, ←category.assoc, is_iso.hom_inv_id, category.id_comp] end def of_components (app : ∀ X : C, (F X) ≅ (G X)) (naturality : ∀ {X Y : C} (f : X ⟶ Y), (F.map f) ≫ ((app Y) : F Y ⟶ G Y) = ((app X) : F X ⟶ G X) ≫ (G.map f)) : F ≅ G := { hom := { app := λ X, ((app X) : F X ⟶ G X), }, inv := { app := λ X, ((app X).symm : G X ⟶ F X), naturality' := λ X Y f, begin let p := congr_arg (λ f, (app X).inv ≫ (f ≫ (app Y).inv)) (eq.symm (naturality f)), dsimp at *, simp at *, erw [←p, ←category.assoc, is_iso.hom_inv_id, category.id_comp], end } } end category_theory.nat_iso
84e1552236e0df633c8ed9c339dad08ce20320ef
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/measure_theory/integral/peak_function.lean
0436fb4cce815567d9302a728cfefb2c9a417527
[ "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
19,631
lean
/- Copyright (c) 2023 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import measure_theory.integral.set_integral import measure_theory.function.locally_integrable /-! # Integrals against peak functions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. A sequence of peak functions is a sequence of functions with average one concentrating around a point `x₀`. Given such a sequence `φₙ`, then `∫ φₙ g` tends to `g x₀` in many situations, with a whole zoo of possible assumptions on `φₙ` and `g`. This file is devoted to such results. ## Main results * `tendsto_set_integral_peak_smul_of_integrable_on_of_continuous_within_at`: If a sequence of peak functions `φᵢ` converges uniformly to zero away from a point `x₀`, and `g` is integrable and continuous at `x₀`, then `∫ φᵢ • g` converges to `g x₀`. * `tendsto_set_integral_pow_smul_of_unique_maximum_of_is_compact_of_continuous_on`: If a continuous function `c` realizes its maximum at a unique point `x₀` in a compact set `s`, then the sequence of functions `(c x) ^ n / ∫ (c x) ^ n` is a sequence of peak functions concentrating around `x₀`. Therefore, `∫ (c x) ^ n * g / ∫ (c x) ^ n` converges to `g x₀` if `g` is continuous on `s`. Note that there are related results about convolution with respect to peak functions in the file `analysis.convolution`, such as `convolution_tendsto_right` there. -/ open set filter measure_theory measure_theory.measure topological_space metric open_locale topology ennreal /-- This lemma exists for finsets, but not for sets currently. porting note: move to data.set.basic after the port. -/ lemma set.disjoint_sdiff_inter {α : Type*} (s t : set α) : disjoint (s \ t) (s ∩ t) := disjoint_of_subset_right (inter_subset_right _ _) disjoint_sdiff_left open set variables {α E ι : Type*} {hm : measurable_space α} {μ : measure α} [topological_space α] [borel_space α] [normed_add_comm_group E] [normed_space ℝ E] {g : α → E} {l : filter ι} {x₀ : α} {s : set α} {φ : ι → α → ℝ} /-- If a sequence of peak functions `φᵢ` converges uniformly to zero away from a point `x₀`, and `g` is integrable and continuous at `x₀`, then `φᵢ • g` is eventually integrable. -/ lemma integrable_on_peak_smul_of_integrable_on_of_continuous_within_at (hs : measurable_set s) (hlφ : ∀ (u : set α), is_open u → x₀ ∈ u → tendsto_uniformly_on φ 0 l (s \ u)) (hiφ : ∀ᶠ i in l, ∫ x in s, φ i x ∂μ = 1) (hmg : integrable_on g s μ) (hcg : continuous_within_at g s x₀) : ∀ᶠ i in l, integrable_on (λ x, φ i x • g x) s μ := begin obtain ⟨u, u_open, x₀u, hu⟩ : ∃ u, is_open u ∧ x₀ ∈ u ∧ ∀ x ∈ u ∩ s, g x ∈ ball (g x₀) 1, from mem_nhds_within.1 (hcg (ball_mem_nhds _ zero_lt_one)), filter_upwards [tendsto_uniformly_on_iff.1 (hlφ u u_open x₀u) 1 zero_lt_one, hiφ] with i hi h'i, have A : integrable_on (λ x, φ i x • g x) (s \ u) μ, { refine integrable.smul_of_top_right (hmg.mono (diff_subset _ _) le_rfl) _, apply mem_ℒp_top_of_bound ((integrable_of_integral_eq_one h'i).ae_strongly_measurable.mono_set ((diff_subset _ _))) 1, filter_upwards [self_mem_ae_restrict (hs.diff u_open.measurable_set)] with x hx, simpa only [pi.zero_apply, dist_zero_left] using (hi x hx).le }, have B : integrable_on (λ x, φ i x • g x) (s ∩ u) μ, { apply integrable.smul_of_top_left, { exact integrable_on.mono_set (integrable_of_integral_eq_one h'i) (inter_subset_left _ _) }, { apply mem_ℒp_top_of_bound (hmg.mono_set (inter_subset_left _ _)).ae_strongly_measurable (‖g x₀‖ + 1), filter_upwards [self_mem_ae_restrict (hs.inter u_open.measurable_set)] with x hx, rw inter_comm at hx, exact (norm_lt_of_mem_ball (hu x hx)).le } }, convert A.union B, simp only [diff_union_inter], end variables [complete_space E] /-- If a sequence of peak functions `φᵢ` converges uniformly to zero away from a point `x₀`, and `g` is integrable and continuous at `x₀`, then `∫ φᵢ • g` converges to `x₀`. Auxiliary lemma where one assumes additionally `g x₀ = 0`. -/ lemma tendsto_set_integral_peak_smul_of_integrable_on_of_continuous_within_at_aux (hs : measurable_set s) (hnφ : ∀ᶠ i in l, ∀ x ∈ s, 0 ≤ φ i x) (hlφ : ∀ (u : set α), is_open u → x₀ ∈ u → tendsto_uniformly_on φ 0 l (s \ u)) (hiφ : ∀ᶠ i in l, ∫ x in s, φ i x ∂μ = 1) (hmg : integrable_on g s μ) (h'g : g x₀ = 0) (hcg : continuous_within_at g s x₀) : tendsto (λ i : ι, ∫ x in s, φ i x • g x ∂μ) l (𝓝 0) := begin refine metric.tendsto_nhds.2 (λ ε εpos, _), obtain ⟨δ, hδ, δpos⟩ : ∃ δ, δ * ∫ x in s, ‖g x‖ ∂μ + δ < ε ∧ 0 < δ, { have A : tendsto (λ δ, δ * ∫ x in s, ‖g x‖ ∂μ + δ) (𝓝[>] 0) (𝓝 (0 * ∫ x in s, ‖g x‖ ∂μ + 0)), { apply tendsto.mono_left _ nhds_within_le_nhds, exact (tendsto_id.mul tendsto_const_nhds).add tendsto_id }, rw [zero_mul, zero_add] at A, exact (((tendsto_order.1 A).2 ε εpos).and self_mem_nhds_within).exists }, suffices : ∀ᶠ i in l, ‖∫ x in s, φ i x • g x ∂μ‖ ≤ δ * ∫ x in s, ‖g x‖ ∂μ + δ, { filter_upwards [this] with i hi, simp only [dist_zero_right], exact hi.trans_lt hδ }, obtain ⟨u, u_open, x₀u, hu⟩ : ∃ u, is_open u ∧ x₀ ∈ u ∧ ∀ x ∈ u ∩ s, g x ∈ ball (g x₀) δ, from mem_nhds_within.1 (hcg (ball_mem_nhds _ δpos)), filter_upwards [tendsto_uniformly_on_iff.1 (hlφ u u_open x₀u) δ δpos, hiφ, hnφ, integrable_on_peak_smul_of_integrable_on_of_continuous_within_at hs hlφ hiφ hmg hcg] with i hi h'i hφpos h''i, have B : ‖∫ x in s ∩ u, φ i x • g x ∂μ‖ ≤ δ, from calc ‖∫ x in s ∩ u, φ i x • g x ∂μ‖ ≤ ∫ x in s ∩ u, ‖φ i x • g x‖ ∂μ : norm_integral_le_integral_norm _ ... ≤ ∫ x in s ∩ u, ‖φ i x‖ * δ ∂μ : begin refine set_integral_mono_on _ _ (hs.inter u_open.measurable_set) (λ x hx, _), { exact integrable_on.mono_set h''i.norm (inter_subset_left _ _) }, { exact integrable_on.mono_set ((integrable_of_integral_eq_one h'i).norm.mul_const _) (inter_subset_left _ _) }, rw norm_smul, apply mul_le_mul_of_nonneg_left _ (norm_nonneg _), rw [inter_comm, h'g] at hu, exact (mem_ball_zero_iff.1 (hu x hx)).le, end ... ≤ ∫ x in s, ‖φ i x‖ * δ ∂μ : begin apply set_integral_mono_set, { exact ((integrable_of_integral_eq_one h'i).norm.mul_const _) }, { exact eventually_of_forall (λ x, mul_nonneg (norm_nonneg _) δpos.le) }, { apply eventually_of_forall, exact inter_subset_left s u } end ... = ∫ x in s, φ i x * δ ∂μ : begin apply set_integral_congr hs (λ x hx, _), rw real.norm_of_nonneg (hφpos _ hx), end ... = δ : by rw [integral_mul_right, h'i, one_mul], have C : ‖∫ x in s \ u, φ i x • g x ∂μ‖ ≤ δ * ∫ x in s, ‖g x‖ ∂μ, from calc ‖∫ x in s \ u, φ i x • g x ∂μ‖ ≤ ∫ x in s \ u, ‖φ i x • g x‖ ∂μ : norm_integral_le_integral_norm _ ... ≤ ∫ x in s \ u, δ * ‖g x‖ ∂μ : begin refine set_integral_mono_on _ _ (hs.diff u_open.measurable_set) (λ x hx, _), { exact integrable_on.mono_set h''i.norm (diff_subset _ _) }, { exact integrable_on.mono_set (hmg.norm.const_mul _) (diff_subset _ _) }, rw norm_smul, apply mul_le_mul_of_nonneg_right _ (norm_nonneg _), simpa only [pi.zero_apply, dist_zero_left] using (hi x hx).le, end ... ≤ δ * ∫ x in s, ‖g x‖ ∂μ : begin rw integral_mul_left, apply mul_le_mul_of_nonneg_left (set_integral_mono_set hmg.norm _ _) δpos.le, { exact eventually_of_forall (λ x, norm_nonneg _) }, { apply eventually_of_forall, exact diff_subset s u } end, calc ‖∫ x in s, φ i x • g x ∂μ‖ = ‖∫ x in s \ u, φ i x • g x ∂μ + ∫ x in s ∩ u, φ i x • g x ∂μ‖ : begin conv_lhs { rw ← diff_union_inter s u }, rw integral_union (disjoint_sdiff_inter _ _) (hs.inter u_open.measurable_set) (h''i.mono_set (diff_subset _ _)) (h''i.mono_set (inter_subset_left _ _)) end ... ≤ ‖∫ x in s \ u, φ i x • g x ∂μ‖ + ‖∫ x in s ∩ u, φ i x • g x ∂μ‖ : norm_add_le _ _ ... ≤ δ * ∫ x in s, ‖g x‖ ∂μ + δ : add_le_add C B end /- If a sequence of peak functions `φᵢ` converges uniformly to zero away from a point `x₀`, and `g` is integrable and continuous at `x₀`, then `∫ φᵢ • g` converges to `x₀`. -/ lemma tendsto_set_integral_peak_smul_of_integrable_on_of_continuous_within_at (hs : measurable_set s) (h's : μ s ≠ ∞) (hnφ : ∀ᶠ i in l, ∀ x ∈ s, 0 ≤ φ i x) (hlφ : ∀ (u : set α), is_open u → x₀ ∈ u → tendsto_uniformly_on φ 0 l (s \ u)) (hiφ : (λ i, ∫ x in s, φ i x ∂μ) =ᶠ[l] 1) (hmg : integrable_on g s μ) (hcg : continuous_within_at g s x₀) : tendsto (λ i : ι, ∫ x in s, φ i x • g x ∂μ) l (𝓝 (g x₀)) := begin let h := g - (λ y, g x₀), have A : tendsto (λ i : ι, ∫ x in s, φ i x • h x ∂μ + (∫ x in s, φ i x ∂μ) • g x₀) l (𝓝 (0 + (1 : ℝ) • g x₀)), { refine tendsto.add _ (tendsto.smul (tendsto_const_nhds.congr' hiφ.symm) tendsto_const_nhds), apply tendsto_set_integral_peak_smul_of_integrable_on_of_continuous_within_at_aux hs hnφ hlφ hiφ, { apply integrable.sub hmg, apply integrable_on_const.2, simp only [h's.lt_top, or_true] }, { simp only [h, pi.sub_apply, sub_self] }, { exact hcg.sub continuous_within_at_const } }, simp only [one_smul, zero_add] at A, refine tendsto.congr' _ A, filter_upwards [integrable_on_peak_smul_of_integrable_on_of_continuous_within_at hs hlφ hiφ hmg hcg, hiφ] with i hi h'i, simp only [h, pi.sub_apply, smul_sub], rw [integral_sub hi, integral_smul_const, sub_add_cancel], exact integrable.smul_const (integrable_of_integral_eq_one h'i) _, end /-- If a continuous function `c` realizes its maximum at a unique point `x₀` in a compact set `s`, then the sequence of functions `(c x) ^ n / ∫ (c x) ^ n` is a sequence of peak functions concentrating around `x₀`. Therefore, `∫ (c x) ^ n * g / ∫ (c x) ^ n` converges to `g x₀` if `g` is integrable on `s` and continuous at `x₀`. Version assuming that `μ` gives positive mass to all neighborhoods of `x₀` within `s`. For a less precise but more usable version, see `tendsto_set_integral_pow_smul_of_unique_maximum_of_is_compact_of_continuous_on`. -/ lemma tendsto_set_integral_pow_smul_of_unique_maximum_of_is_compact_of_measure_nhds_within_pos [metrizable_space α] [is_locally_finite_measure μ] (hs : is_compact s) (hμ : ∀ u, is_open u → x₀ ∈ u → 0 < μ (u ∩ s)) {c : α → ℝ} (hc : continuous_on c s) (h'c : ∀ y ∈ s, y ≠ x₀ → c y < c x₀) (hnc : ∀ x ∈ s, 0 ≤ c x) (hnc₀ : 0 < c x₀) (h₀ : x₀ ∈ s) (hmg : integrable_on g s μ) (hcg : continuous_within_at g s x₀) : tendsto (λ (n : ℕ), (∫ x in s, (c x) ^ n ∂μ)⁻¹ • (∫ x in s, (c x) ^ n • g x ∂μ)) at_top (𝓝 (g x₀)) := begin /- We apply the general result `tendsto_set_integral_peak_smul_of_integrable_on_of_continuous_within_at` to the sequence of peak functions `φₙ = (c x) ^ n / ∫ (c x) ^ n`. The only nontrivial bit is to check that this sequence converges uniformly to zero on any set `s \ u` away from `x₀`. By compactness, the function `c` is bounded by `t < c x₀` there. Consider `t' ∈ (t, c x₀)`, and a neighborhood `v` of `x₀` where `c x ≥ t'`, by continuity. Then `∫ (c x) ^ n` is bounded below by `t' ^ n μ v`. It follows that, on `s \ u`, then `φₙ x ≤ t ^ n / (t' ^ n μ v)`, which tends (exponentially fast) to zero with `n`. -/ let φ : ℕ → α → ℝ := λ n x, (∫ x in s, (c x) ^ n ∂μ)⁻¹ * (c x) ^ n, have hnφ : ∀ n, ∀ x ∈ s, 0 ≤ φ n x, { assume n x hx, apply mul_nonneg (inv_nonneg.2 _) (pow_nonneg (hnc x hx) _), exact set_integral_nonneg hs.measurable_set (λ x hx, pow_nonneg (hnc x hx) _) }, have I : ∀ n, integrable_on (λ x, (c x)^n) s μ := λ n, continuous_on.integrable_on_compact hs (hc.pow n), have J : ∀ n, 0 ≤ᵐ[μ.restrict s] λ (x : α), c x ^ n, { assume n, filter_upwards [ae_restrict_mem hs.measurable_set] with x hx, exact pow_nonneg (hnc x hx) n }, have P : ∀ n, 0 < ∫ x in s, (c x) ^ n ∂μ, { assume n, refine (set_integral_pos_iff_support_of_nonneg_ae (J n) (I n)).2 _, obtain ⟨u, u_open, x₀_u, hu⟩ : ∃ (u : set α), is_open u ∧ x₀ ∈ u ∧ u ∩ s ⊆ c ⁻¹' Ioi 0 := _root_.continuous_on_iff.1 hc x₀ h₀ (Ioi (0 : ℝ)) is_open_Ioi hnc₀, apply (hμ u u_open x₀_u).trans_le, exact measure_mono (λ x hx, ⟨ne_of_gt (pow_pos (hu hx) _), hx.2⟩) }, have hiφ : ∀ n, ∫ x in s, φ n x ∂μ = 1 := λ n, by rw [integral_mul_left, inv_mul_cancel (P n).ne'], have A : ∀ (u : set α), is_open u → x₀ ∈ u → tendsto_uniformly_on φ 0 at_top (s \ u), { assume u u_open x₀u, obtain ⟨t, t_pos, tx₀, ht⟩ : ∃ t, 0 ≤ t ∧ t < c x₀ ∧ (∀ x ∈ s \ u, c x ≤ t), { rcases eq_empty_or_nonempty (s \ u) with h|h, { exact ⟨0, le_rfl, hnc₀, by simp only [h, mem_empty_iff_false, is_empty.forall_iff, implies_true_iff]⟩ }, obtain ⟨x, hx, h'x⟩ : ∃ x ∈ s \ u, ∀ y ∈ s \ u, c y ≤ c x := is_compact.exists_forall_ge (hs.diff u_open) h (hc.mono (diff_subset _ _)), refine ⟨c x, hnc x hx.1, h'c x hx.1 _, h'x⟩, rintros rfl, exact hx.2 x₀u }, obtain ⟨t', tt', t'x₀⟩ : ∃ t', t < t' ∧ t' < c x₀ := exists_between tx₀, have t'_pos : 0 < t' := t_pos.trans_lt tt', obtain ⟨v, v_open, x₀_v, hv⟩ : ∃ (v : set α), is_open v ∧ x₀ ∈ v ∧ v ∩ s ⊆ c ⁻¹' Ioi t' := _root_.continuous_on_iff.1 hc x₀ h₀ (Ioi t') is_open_Ioi t'x₀, have M : ∀ n, ∀ x ∈ s \ u, φ n x ≤ (μ (v ∩ s)).to_real ⁻¹ * (t / t') ^ n, { assume n x hx, have B : t' ^ n * (μ (v ∩ s)).to_real ≤ ∫ y in s, (c y) ^ n ∂μ, from calc t' ^ n * (μ (v ∩ s)).to_real = ∫ y in v ∩ s, t' ^ n ∂μ : by simp only [integral_const, measure.restrict_apply, measurable_set.univ, univ_inter, algebra.id.smul_eq_mul, mul_comm] ... ≤ ∫ y in v ∩ s, (c y) ^ n ∂μ : begin apply set_integral_mono_on _ _ (v_open.measurable_set.inter hs.measurable_set) _, { apply integrable_on_const.2 (or.inr _), exact lt_of_le_of_lt (measure_mono (inter_subset_right _ _)) hs.measure_lt_top }, { exact (I n).mono (inter_subset_right _ _) le_rfl }, { assume x hx, exact pow_le_pow_of_le_left t'_pos.le (le_of_lt (hv hx)) _ } end ... ≤ ∫ y in s, (c y) ^ n ∂μ : set_integral_mono_set (I n) (J n) (eventually_of_forall (inter_subset_right _ _)), simp_rw [φ, ← div_eq_inv_mul, div_pow, div_div], apply div_le_div (pow_nonneg t_pos n) _ _ B, { exact pow_le_pow_of_le_left (hnc _ hx.1) (ht x hx) _ }, { apply mul_pos (pow_pos (t_pos.trans_lt tt') _) (ennreal.to_real_pos (hμ v v_open x₀_v).ne' _), have : μ (v ∩ s) ≤ μ s := measure_mono (inter_subset_right _ _), exact ne_of_lt (lt_of_le_of_lt this hs.measure_lt_top) } }, have N : tendsto (λ n, (μ (v ∩ s)).to_real ⁻¹ * (t / t') ^ n) at_top (𝓝 ((μ (v ∩ s)).to_real ⁻¹ * 0)), { apply tendsto.mul tendsto_const_nhds _, { apply_instance }, apply tendsto_pow_at_top_nhds_0_of_lt_1 (div_nonneg t_pos t'_pos.le), exact (div_lt_one t'_pos).2 tt' }, rw mul_zero at N, refine tendsto_uniformly_on_iff.2 (λ ε εpos, _), filter_upwards [(tendsto_order.1 N).2 ε εpos] with n hn x hx, simp only [pi.zero_apply, dist_zero_left, real.norm_of_nonneg (hnφ n x hx.1)], exact (M n x hx).trans_lt hn }, have : tendsto (λ (i : ℕ), ∫ (x : α) in s, φ i x • g x ∂μ) at_top (𝓝 (g x₀)) := tendsto_set_integral_peak_smul_of_integrable_on_of_continuous_within_at hs.measurable_set hs.measure_lt_top.ne (eventually_of_forall hnφ) A (eventually_of_forall hiφ) hmg hcg, convert this, simp_rw [← smul_smul, integral_smul], end /-- If a continuous function `c` realizes its maximum at a unique point `x₀` in a compact set `s`, then the sequence of functions `(c x) ^ n / ∫ (c x) ^ n` is a sequence of peak functions concentrating around `x₀`. Therefore, `∫ (c x) ^ n * g / ∫ (c x) ^ n` converges to `g x₀` if `g` is integrable on `s` and continuous at `x₀`. Version assuming that `μ` gives positive mass to all open sets. For a less precise but more usable version, see `tendsto_set_integral_pow_smul_of_unique_maximum_of_is_compact_of_continuous_on`. -/ lemma tendsto_set_integral_pow_smul_of_unique_maximum_of_is_compact_of_integrable_on [metrizable_space α] [is_locally_finite_measure μ] [is_open_pos_measure μ] (hs : is_compact s) {c : α → ℝ} (hc : continuous_on c s) (h'c : ∀ y ∈ s, y ≠ x₀ → c y < c x₀) (hnc : ∀ x ∈ s, 0 ≤ c x) (hnc₀ : 0 < c x₀) (h₀ : x₀ ∈ closure (interior s)) (hmg : integrable_on g s μ) (hcg : continuous_within_at g s x₀) : tendsto (λ (n : ℕ), (∫ x in s, (c x) ^ n ∂μ)⁻¹ • (∫ x in s, (c x) ^ n • g x ∂μ)) at_top (𝓝 (g x₀)) := begin have : x₀ ∈ s, { rw ← hs.is_closed.closure_eq, exact closure_mono interior_subset h₀ }, apply tendsto_set_integral_pow_smul_of_unique_maximum_of_is_compact_of_measure_nhds_within_pos hs _ hc h'c hnc hnc₀ this hmg hcg, assume u u_open x₀_u, calc 0 < μ (u ∩ interior s) : (u_open.inter is_open_interior).measure_pos μ (_root_.mem_closure_iff.1 h₀ u u_open x₀_u) ... ≤ μ (u ∩ s) : measure_mono (inter_subset_inter_right _ interior_subset) end /-- If a continuous function `c` realizes its maximum at a unique point `x₀` in a compact set `s`, then the sequence of functions `(c x) ^ n / ∫ (c x) ^ n` is a sequence of peak functions concentrating around `x₀`. Therefore, `∫ (c x) ^ n * g / ∫ (c x) ^ n` converges to `g x₀` if `g` is continuous on `s`. -/ lemma tendsto_set_integral_pow_smul_of_unique_maximum_of_is_compact_of_continuous_on [metrizable_space α] [is_locally_finite_measure μ] [is_open_pos_measure μ] (hs : is_compact s) {c : α → ℝ} (hc : continuous_on c s) (h'c : ∀ y ∈ s, y ≠ x₀ → c y < c x₀) (hnc : ∀ x ∈ s, 0 ≤ c x) (hnc₀ : 0 < c x₀) (h₀ : x₀ ∈ closure (interior s)) (hmg : continuous_on g s) : tendsto (λ (n : ℕ), (∫ x in s, (c x) ^ n ∂μ)⁻¹ • (∫ x in s, (c x) ^ n • g x ∂μ)) at_top (𝓝 (g x₀)) := begin have : x₀ ∈ s, { rw ← hs.is_closed.closure_eq, exact closure_mono interior_subset h₀ }, exact tendsto_set_integral_pow_smul_of_unique_maximum_of_is_compact_of_integrable_on hs hc h'c hnc hnc₀ h₀ (hmg.integrable_on_compact hs) (hmg x₀ this) end
3533689da3357171e200e268b27b595e4f92b49b
367134ba5a65885e863bdc4507601606690974c1
/src/tactic/cache.lean
184e5a2d82df9669d4e0038ff6f778ae781b7eb9
[ "Apache-2.0" ]
permissive
kodyvajjha/mathlib
9bead00e90f68269a313f45f5561766cfd8d5cad
b98af5dd79e13a38d84438b850a2e8858ec21284
refs/heads/master
1,624,350,366,310
1,615,563,062,000
1,615,563,062,000
162,666,963
0
0
Apache-2.0
1,545,367,651,000
1,545,367,651,000
null
UTF-8
Lean
false
false
5,552
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import tactic.doc_commands /-! # Instance cache tactics For performance reasons, Lean does not automatically update its database of class instances during a proof. The group of tactics in this file helps to force such updates. -/ open lean.parser local postfix `?`:9001 := optional local postfix *:9001 := many namespace tactic /-- Reset the instance cache for the main goal. -/ meta def reset_instance_cache : tactic unit := do unfreeze_local_instances, freeze_local_instances /-- Unfreeze the local instances while executing `tac` on the main goal. -/ meta def unfreezing {α} (tac : tactic α) : tactic α := focus1 $ unfreeze_local_instances *> tac <* all_goals freeze_local_instances /-- Unfreeze local instances while executing `tac`, if the passed expression is amongst the frozen instances. -/ meta def unfreezing_hyp (h : expr) (tac : tactic unit) : tactic unit := do frozen ← frozen_local_instances, if h ∈ frozen.get_or_else [] then unfreezing tac else tac namespace interactive open interactive interactive.types /-- `unfreezingI { tac }` executes tac while temporarily unfreezing the instance cache. -/ meta def unfreezingI (tac : itactic) := unfreezing tac /-- Reset the instance cache. This allows any new instances added to the context to be used in typeclass inference. -/ meta def resetI := reset_instance_cache /-- Like `subst`, but can also substitute in instance arguments. -/ meta def substI (q : parse texpr) : tactic unit := unfreezingI (subst q) /-- Like `cases`, but can also be used with instance arguments. -/ meta def casesI (p : parse cases_arg_p) (q : parse with_ident_list) : tactic unit := unfreezingI (cases p q) /-- Like `intro`, but uses the introduced variable in typeclass inference. -/ meta def introI (p : parse ident_?) : tactic unit := intro p >> reset_instance_cache /-- Like `intros`, but uses the introduced variable(s) in typeclass inference. -/ meta def introsI (p : parse ident_*) : tactic unit := intros p >> reset_instance_cache /-- Used to add typeclasses to the context so that they can be used in typeclass inference. The syntax is the same as `have`, but the proof-omitted version is not supported. For this one must write `have : t, { <proof> }, resetI, <proof>`. -/ meta def haveI (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse (tk ":=" *> texpr)) : tactic unit := do h ← match h with | none := get_unused_name "_inst" | some a := return a end, «have» (some h) q₁ (some q₂), match q₁ with | none := swap >> reset_instance_cache >> swap | some p₂ := reset_instance_cache end /-- Used to add typeclasses to the context so that they can be used in typeclass inference. The syntax is the same as `let`. -/ meta def letI (h : parse ident?) (q₁ : parse (tk ":" *> texpr)?) (q₂ : parse $ (tk ":=" *> texpr)?) : tactic unit := do h ← match h with | none := get_unused_name "_inst" | some a := return a end, «let» (some h) q₁ q₂, match q₂ with | none := swap >> reset_instance_cache >> swap | some p₂ := reset_instance_cache end /-- Like `exact`, but uses all variables in the context for typeclass inference. -/ meta def exactI (q : parse texpr) : tactic unit := reset_instance_cache >> exact q /-- For performance reasons, Lean does not automatically update its database of class instances during a proof. The group of tactics described below helps to force such updates. For a simple (but very artificial) example, consider the function `default` from the core library. It has type `Π (α : Sort u) [inhabited α], α`, so one can use `default α` only if Lean can find a registered instance of `inhabited α`. Because the database of such instance is not automatically updated during a proof, the following attempt won't work (Lean will not pick up the instance from the local context): ```lean def my_id (α : Type) : α → α := begin intro x, have : inhabited α := ⟨x⟩, exact default α, -- Won't work! end ``` However, it will work, producing the identity function, if one replaces `have` by its variant `haveI` described below. * `resetI`: Reset the instance cache. This allows any instances currently in the context to be used in typeclass inference. * `unfreezingI { tac }`: Unfreeze local instances while executing the tactic `tac`. * `introI`/`introsI`: `intro`/`intros` followed by `resetI`. Like `intro`/`intros`, but uses the introduced variable in typeclass inference. * `casesI`: like `cases`, but can also be used with instance arguments. * `substI`: like `subst`, but can also substitute in type-class arguments * `haveI`/`letI`: `have`/`let` followed by `resetI`. Used to add typeclasses to the context so that they can be used in typeclass inference. The syntax `haveI := <proof>` and `haveI : t := <proof>` is supported, but `haveI : t, from _` and `haveI : t, { <proof> }` are not; in these cases use `have : t, { <proof> }, resetI` directly. * `exactI`: `resetI` followed by `exact`. Like `exact`, but uses all variables in the context for typeclass inference. -/ add_tactic_doc { name := "Instance cache tactics", category := doc_category.tactic, decl_names := [``resetI, ``unfreezingI, ``casesI, ``substI, ``introI, ``introsI, ``haveI, ``letI, ``exactI], tags := ["type class", "context management"] } end interactive end tactic
6c1d17e91fa4336b72844e69f8b9fca680bff5f2
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/data/rat/cast.lean
d32a5f2f556731af69123784d56324e7fbf57a33
[ "Apache-2.0" ]
permissive
dupuisf/mathlib
62de4ec6544bf3b79086afd27b6529acfaf2c1bb
8582b06b0a5d06c33ee07d0bdf7c646cae22cf36
refs/heads/master
1,669,494,854,016
1,595,692,409,000
1,595,692,409,000
272,046,630
0
0
Apache-2.0
1,592,066,143,000
1,592,066,142,000
null
UTF-8
Lean
false
false
11,950
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, Mario Carneiro -/ import data.rat.order import data.int.char_zero /-! # Casts for Rational Numbers ## Summary We define the canonical injection from ℚ into an arbitrary division ring and prove various casting lemmas showing the well-behavedness of this injection. ## Notations - `/.` is infix notation for `rat.mk`. ## Tags rat, rationals, field, ℚ, numerator, denominator, num, denom, cast, coercion, casting -/ namespace rat variable {α : Type*} open_locale rat section with_div_ring variable [division_ring α] /-- Construct the canonical injection from `ℚ` into an arbitrary division ring. If the field has positive characteristic `p`, we define `1 / p = 1 / 0 = 0` for consistency with our division by zero convention. -/ -- see Note [coercion into rings] @[priority 900] instance cast_coe : has_coe_t ℚ α := ⟨λ r, r.1 / r.2⟩ @[simp] theorem cast_of_int (n : ℤ) : (of_int n : α) = n := show (n / (1:ℕ) : α) = n, by rw [nat.cast_one, div_one] @[simp, norm_cast] theorem cast_coe_int (n : ℤ) : ((n : ℚ) : α) = n := by rw [coe_int_eq_of_int, cast_of_int] @[simp, norm_cast] theorem cast_coe_nat (n : ℕ) : ((n : ℚ) : α) = n := cast_coe_int n @[simp, norm_cast] theorem cast_zero : ((0 : ℚ) : α) = 0 := (cast_of_int _).trans int.cast_zero @[simp, norm_cast] theorem cast_one : ((1 : ℚ) : α) = 1 := (cast_of_int _).trans int.cast_one theorem cast_commute (r : ℚ) (a : α) : commute ↑r a := (r.1.cast_commute a).div_left (r.2.cast_commute a) theorem commute_cast (a : α) (r : ℚ) : commute a r := (r.cast_commute a).symm @[norm_cast] theorem cast_mk_of_ne_zero (a b : ℤ) (b0 : (b:α) ≠ 0) : (a /. b : α) = a / b := begin have b0' : b ≠ 0, { refine mt _ b0, simp {contextual := tt} }, cases e : a /. b with n d h c, have d0 : (d:α) ≠ 0, { intro d0, have dd := denom_dvd a b, cases (show (d:ℤ) ∣ b, by rwa e at dd) with k ke, have : (b:α) = (d:α) * (k:α), {rw [ke, int.cast_mul], refl}, rw [d0, zero_mul] at this, contradiction }, rw [num_denom'] at e, have := congr_arg (coe : ℤ → α) ((mk_eq b0' $ ne_of_gt $ int.coe_nat_pos.2 h).1 e), rw [int.cast_mul, int.cast_mul, int.cast_coe_nat] at this, symmetry, change (a * b⁻¹ : α) = n / d, rw [eq_div_iff_mul_eq d0, mul_assoc, (d.commute_cast _).eq, ← mul_assoc, this, mul_assoc, mul_inv_cancel b0, mul_one] end @[norm_cast] theorem cast_add_of_ne_zero : ∀ {m n : ℚ}, (m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m + n : ℚ) : α) = m + n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl), have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl), rw [num_denom', num_denom', add_def d₁0' d₂0'], suffices : (n₁ * (d₂ * (d₂⁻¹ * d₁⁻¹)) + n₂ * (d₁ * d₂⁻¹) * d₁⁻¹ : α) = n₁ * d₁⁻¹ + n₂ * d₂⁻¹, { rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero], { simpa [division_def, left_distrib, right_distrib, mul_inv_rev', d₁0, d₂0, mul_assoc] }, all_goals {simp [d₁0, d₂0]} }, rw [← mul_assoc (d₂:α), mul_inv_cancel d₂0, one_mul, (nat.cast_commute _ _).eq], simp [d₁0, mul_assoc] end @[simp, norm_cast] theorem cast_neg : ∀ n, ((-n : ℚ) : α) = -n | ⟨n, d, h, c⟩ := show (↑-n * d⁻¹ : α) = -(n * d⁻¹), by rw [int.cast_neg, neg_mul_eq_neg_mul] @[norm_cast] theorem cast_sub_of_ne_zero {m n : ℚ} (m0 : (m.denom : α) ≠ 0) (n0 : (n.denom : α) ≠ 0) : ((m - n : ℚ) : α) = m - n := have ((-n).denom : α) ≠ 0, by cases n; exact n0, by simp [sub_eq_add_neg, (cast_add_of_ne_zero m0 this)] @[norm_cast] theorem cast_mul_of_ne_zero : ∀ {m n : ℚ}, (m.denom : α) ≠ 0 → (n.denom : α) ≠ 0 → ((m * n : ℚ) : α) = m * n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := λ (d₁0 : (d₁:α) ≠ 0) (d₂0 : (d₂:α) ≠ 0), begin have d₁0' : (d₁:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₁0; exact d₁0 rfl), have d₂0' : (d₂:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d₂0; exact d₂0 rfl), rw [num_denom', num_denom', mul_def d₁0' d₂0'], suffices : (n₁ * ((n₂ * d₂⁻¹) * d₁⁻¹) : α) = n₁ * (d₁⁻¹ * (n₂ * d₂⁻¹)), { rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, cast_mk_of_ne_zero], { simpa [division_def, mul_inv_rev', d₁0, d₂0, mul_assoc] }, all_goals {simp [d₁0, d₂0]} }, rw [(d₁.commute_cast (_:α)).inv_right'.eq] end @[norm_cast] theorem cast_inv_of_ne_zero : ∀ {n : ℚ}, (n.num : α) ≠ 0 → (n.denom : α) ≠ 0 → ((n⁻¹ : ℚ) : α) = n⁻¹ | ⟨n, d, h, c⟩ := λ (n0 : (n:α) ≠ 0) (d0 : (d:α) ≠ 0), begin have n0' : (n:ℤ) ≠ 0 := λ e, by rw e at n0; exact n0 rfl, have d0' : (d:ℤ) ≠ 0 := int.coe_nat_ne_zero.2 (λ e, by rw e at d0; exact d0 rfl), rw [num_denom', inv_def], rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero, inv_div]; simp [n0, d0] end @[norm_cast] theorem cast_div_of_ne_zero {m n : ℚ} (md : (m.denom : α) ≠ 0) (nn : (n.num : α) ≠ 0) (nd : (n.denom : α) ≠ 0) : ((m / n : ℚ) : α) = m / n := have (n⁻¹.denom : ℤ) ∣ n.num, by conv in n⁻¹.denom { rw [←(@num_denom n), inv_def] }; apply denom_dvd, have (n⁻¹.denom : α) = 0 → (n.num : α) = 0, from λ h, let ⟨k, e⟩ := this in by have := congr_arg (coe : ℤ → α) e; rwa [int.cast_mul, int.cast_coe_nat, h, zero_mul] at this, by rw [division_def, cast_mul_of_ne_zero md (mt this nn), cast_inv_of_ne_zero nn nd, division_def] @[simp, norm_cast] theorem cast_inj [char_zero α] : ∀ {m n : ℚ}, (m : α) = n ↔ m = n | ⟨n₁, d₁, h₁, c₁⟩ ⟨n₂, d₂, h₂, c₂⟩ := begin refine ⟨λ h, _, congr_arg _⟩, have d₁0 : d₁ ≠ 0 := ne_of_gt h₁, have d₂0 : d₂ ≠ 0 := ne_of_gt h₂, have d₁a : (d₁:α) ≠ 0 := nat.cast_ne_zero.2 d₁0, have d₂a : (d₂:α) ≠ 0 := nat.cast_ne_zero.2 d₂0, rw [num_denom', num_denom'] at h ⊢, rw [cast_mk_of_ne_zero, cast_mk_of_ne_zero] at h; simp [d₁0, d₂0] at h ⊢, rwa [eq_div_iff_mul_eq d₂a, division_def, mul_assoc, (d₁.cast_commute (d₂:α)).inv_left'.eq, ← mul_assoc, ← division_def, eq_comm, eq_div_iff_mul_eq d₁a, eq_comm, ← int.cast_coe_nat, ← int.cast_mul, ← int.cast_coe_nat, ← int.cast_mul, int.cast_inj, ← mk_eq (int.coe_nat_ne_zero.2 d₁0) (int.coe_nat_ne_zero.2 d₂0)] at h end theorem cast_injective [char_zero α] : function.injective (coe : ℚ → α) | m n := cast_inj.1 @[simp] theorem cast_eq_zero [char_zero α] {n : ℚ} : (n : α) = 0 ↔ n = 0 := by rw [← cast_zero, cast_inj] theorem cast_ne_zero [char_zero α] {n : ℚ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero @[simp, norm_cast] theorem cast_add [char_zero α] (m n) : ((m + n : ℚ) : α) = m + n := cast_add_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, norm_cast] theorem cast_sub [char_zero α] (m n) : ((m - n : ℚ) : α) = m - n := cast_sub_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, norm_cast] theorem cast_mul [char_zero α] (m n) : ((m * n : ℚ) : α) = m * n := cast_mul_of_ne_zero (nat.cast_ne_zero.2 $ ne_of_gt m.pos) (nat.cast_ne_zero.2 $ ne_of_gt n.pos) @[simp, norm_cast] theorem cast_bit0 [char_zero α] (n : ℚ) : ((bit0 n : ℚ) : α) = bit0 n := cast_add _ _ @[simp, norm_cast] theorem cast_bit1 [char_zero α] (n : ℚ) : ((bit1 n : ℚ) : α) = bit1 n := by rw [bit1, cast_add, cast_one, cast_bit0]; refl variable (α) /-- Coercion `ℚ → α` as a `ring_hom`. -/ def cast_hom [char_zero α] : ℚ →+* α := ⟨coe, cast_one, cast_mul, cast_zero, cast_add⟩ variable {α} @[simp] lemma coe_cast_hom [char_zero α] : ⇑(cast_hom α) = coe := rfl @[simp, norm_cast] theorem cast_inv [char_zero α] (n) : ((n⁻¹ : ℚ) : α) = n⁻¹ := (cast_hom α).map_inv _ @[simp, norm_cast] theorem cast_div [char_zero α] (m n) : ((m / n : ℚ) : α) = m / n := (cast_hom α).map_div _ _ @[norm_cast] theorem cast_mk [char_zero α] (a b : ℤ) : ((a /. b) : α) = a / b := by simp only [mk_eq_div, cast_div, cast_coe_int] @[simp, norm_cast] theorem cast_pow [char_zero α] (q) (k : ℕ) : ((q ^ k : ℚ) : α) = q ^ k := (cast_hom α).map_pow q k end with_div_ring @[simp, norm_cast] theorem cast_nonneg [linear_ordered_field α] : ∀ {n : ℚ}, 0 ≤ (n : α) ↔ 0 ≤ n | ⟨n, d, h, c⟩ := show 0 ≤ (n * d⁻¹ : α) ↔ 0 ≤ (⟨n, d, h, c⟩ : ℚ), by rw [num_denom', ← nonneg_iff_zero_le, mk_nonneg _ (int.coe_nat_pos.2 h), mul_nonneg_iff_right_nonneg_of_pos ((@inv_pos α _ _).2 (nat.cast_pos.2 h)), int.cast_nonneg] @[simp, norm_cast] theorem cast_le [linear_ordered_field α] {m n : ℚ} : (m : α) ≤ n ↔ m ≤ n := by rw [← sub_nonneg, ← cast_sub, cast_nonneg, sub_nonneg] @[simp, norm_cast] theorem cast_lt [linear_ordered_field α] {m n : ℚ} : (m : α) < n ↔ m < n := by simpa [-cast_le] using not_congr (@cast_le α _ n m) @[simp] theorem cast_nonpos [linear_ordered_field α] {n : ℚ} : (n : α) ≤ 0 ↔ n ≤ 0 := by rw [← cast_zero, cast_le] @[simp] theorem cast_pos [linear_ordered_field α] {n : ℚ} : (0 : α) < n ↔ 0 < n := by rw [← cast_zero, cast_lt] @[simp] theorem cast_lt_zero [linear_ordered_field α] {n : ℚ} : (n : α) < 0 ↔ n < 0 := by rw [← cast_zero, cast_lt] @[simp, norm_cast] theorem cast_id : ∀ n : ℚ, ↑n = n | ⟨n, d, h, c⟩ := show (n / (d : ℤ) : ℚ) = _, by rw [num_denom', mk_eq_div] @[simp, norm_cast] theorem cast_min [discrete_linear_ordered_field α] {a b : ℚ} : (↑(min a b) : α) = min a b := by by_cases a ≤ b; simp [h, min] @[simp, norm_cast] theorem cast_max [discrete_linear_ordered_field α] {a b : ℚ} : (↑(max a b) : α) = max a b := by by_cases a ≤ b; simp [h, max] @[simp, norm_cast] theorem cast_abs [discrete_linear_ordered_field α] {q : ℚ} : ((abs q : ℚ) : α) = abs q := by simp [abs] end rat open rat ring_hom lemma ring_hom.eq_rat_cast {k} [division_ring k] (f : ℚ →+* k) (r : ℚ) : f r = r := calc f r = f (r.1 / r.2) : by rw [← int.cast_coe_nat, ← mk_eq_div, num_denom] ... = f r.1 / f r.2 : f.map_div _ _ ... = r.1 / r.2 : by rw [map_nat_cast, map_int_cast] -- This seems to be true for a `[char_p k]` too because `k'` must have the same characteristic -- but the proof would be much longer lemma ring_hom.map_rat_cast {k k'} [division_ring k] [char_zero k] [division_ring k'] (f : k →+* k') (r : ℚ) : f r = r := (f.comp (cast_hom k)).eq_rat_cast r lemma ring_hom.ext_rat {R : Type*} [semiring R] (f g : ℚ →+* R) : f = g := begin ext r, refine rat.num_denom_cases_on' r _, intros a b b0, let φ : ℤ →+* R := f.comp (int.cast_ring_hom ℚ), let ψ : ℤ →+* R := g.comp (int.cast_ring_hom ℚ), rw [rat.mk_eq_div, int.cast_coe_nat], have b0' : (b:ℚ) ≠ 0 := nat.cast_ne_zero.2 b0, have : ∀ n : ℤ, f n = g n := λ n, show φ n = ψ n, by rw [φ.ext_int ψ], calc f (a * b⁻¹) = f a * f b⁻¹ * (g (b:ℤ) * g b⁻¹) : by rw [int.cast_coe_nat, ← g.map_mul, mul_inv_cancel b0', g.map_one, mul_one, f.map_mul] ... = g a * f b⁻¹ * (f (b:ℤ) * g b⁻¹) : by rw [this a, ← this b] ... = g (a * b⁻¹) : by rw [int.cast_coe_nat, mul_assoc, ← mul_assoc (f b⁻¹), ← f.map_mul, inv_mul_cancel b0', f.map_one, one_mul, g.map_mul] end instance rat.subsingleton_ring_hom {R : Type*} [semiring R] : subsingleton (ℚ →+* R) := ⟨ring_hom.ext_rat⟩
77b387b2373b6b5ed72b392188263adbe27c004f
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/Lean/Elab/Tactic/Conv/Unfold.lean
9c12e9991d845db44c99fb3d7afad16ce86c3084
[ "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
568
lean
/- Copyright (c) 2022 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Tactic.Unfold import Lean.Elab.Tactic.Conv.Simp namespace Lean.Elab.Tactic.Conv open Meta @[builtin_tactic Lean.Parser.Tactic.Conv.unfold] def evalUnfold : Tactic := fun stx => withMainContext do for declNameId in stx[1].getArgs do let declName ← resolveGlobalConstNoOverloadWithInfo declNameId applySimpResult (← unfold (← getLhs) declName) end Lean.Elab.Tactic.Conv
fcaad581a85573e721da50aa011a48401ff7f1bd
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/data/fp/basic.lean
80fabd7e9685937ed0bc31f2ed01517520813dcd
[ "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
6,215
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Implementation of floating-point numbers (experimental). -/ import data.rat data.semiquot def int.shift2 (a b : ℕ) : ℤ → ℕ × ℕ | (int.of_nat e) := (a.shiftl e, b) | -[1+ e] := (a, b.shiftl e.succ) namespace fp inductive rmode | NE -- round to nearest even class float_cfg := (prec emax : ℕ) (prec_pos : prec > 0) (prec_max : prec ≤ emax) variable [C : float_cfg] include C def prec := C.prec def emax := C.emax def emin : ℤ := 1 - C.emax def valid_finite (e : ℤ) (m : ℕ) : Prop := emin ≤ e + prec - 1 ∧ e + prec - 1 ≤ emax ∧ e = max (e + m.size - prec) emin instance dec_valid_finite (e m) : decidable (valid_finite e m) := by unfold valid_finite; apply_instance inductive float | inf : bool → float | nan : float | finite : bool → Π e m, valid_finite e m → float def float.is_finite : float → bool | (float.finite s e m f) := tt | _ := ff def to_rat : Π (f : float), f.is_finite → ℚ | (float.finite s e m f) _ := let (n, d) := int.shift2 m 1 e, r := rat.mk_nat n d in if s then -r else r theorem float.zero.valid : valid_finite emin 0 := ⟨begin rw add_sub_assoc, apply le_add_of_nonneg_right, apply sub_nonneg_of_le, apply int.coe_nat_le_coe_nat_of_le, exact C.prec_pos end, by simpa [emin] using show (prec : ℤ) ≤ emax + float_cfg.emax, from le_trans (int.coe_nat_le.2 C.prec_max) (le_add_of_nonneg_left (int.coe_zero_le _)), by rw max_eq_right; simp⟩ def float.zero (s : bool) : float := float.finite s emin 0 float.zero.valid protected def float.sign' : float → semiquot bool | (float.inf s) := pure s | float.nan := ⊤ | (float.finite s e m f) := pure s protected def float.sign : float → bool | (float.inf s) := s | float.nan := ff | (float.finite s e m f) := s protected def float.is_zero : float → bool | (float.finite s e 0 f) := tt | _ := ff protected def float.neg : float → float | (float.inf s) := float.inf (bnot s) | float.nan := float.nan | (float.finite s e m f) := float.finite (bnot s) e m f def div_nat_lt_two_pow (n d : ℕ) : ℤ → bool | (int.of_nat e) := n < d.shiftl e | -[1+ e] := n.shiftl e.succ < d -- TODO(Mario): Prove these and drop 'meta' meta def of_pos_rat_dn (n : ℕ+) (d : ℕ+) : float × bool := begin let e₁ : ℤ := n.1.size - d.1.size - prec, cases h₁ : int.shift2 d.1 n.1 (e₁ + prec) with d₁ n₁, let e₂ := if n₁ < d₁ then e₁ - 1 else e₁, let e₃ := max e₂ emin, cases h₂ : int.shift2 d.1 n.1 (e₃ + prec) with d₂ n₂, let r := rat.mk_nat n₂ d₂, let m := r.floor, refine (float.finite ff e₃ (int.to_nat m) _, r.denom = 1), { exact undefined } end meta def next_up_pos (e m) (v : valid_finite e m) : float := let m' := m.succ in if ss : m'.size = m.size then float.finite ff e m' (by unfold valid_finite at *; rw ss; exact v) else if h : e = emax then float.inf ff else float.finite ff e.succ (nat.div2 m') undefined meta def next_dn_pos (e m) (v : valid_finite e m) : float := match m with | 0 := next_up_pos _ _ float.zero.valid | nat.succ m' := if ss : m'.size = m.size then float.finite ff e m' (by unfold valid_finite at *; rw ss; exact v) else if h : e = emin then float.finite ff emin m' undefined else float.finite ff e.pred (bit1 m') undefined end meta def next_up : float → float | (float.finite ff e m f) := next_up_pos e m f | (float.finite tt e m f) := float.neg $ next_dn_pos e m f | f := f meta def next_dn : float → float | (float.finite ff e m f) := next_dn_pos e m f | (float.finite tt e m f) := float.neg $ next_up_pos e m f | f := f meta def of_rat_up : ℚ → float | ⟨0, _, _, _⟩ := float.zero ff | ⟨nat.succ n, d, h, _⟩ := let (f, exact) := of_pos_rat_dn n.succ_pnat ⟨d, h⟩ in if exact then f else next_up f | ⟨-[1+n], d, h, _⟩ := float.neg (of_pos_rat_dn n.succ_pnat ⟨d, h⟩).1 meta def of_rat_dn (r : ℚ) : float := float.neg $ of_rat_up (-r) meta def of_rat : rmode → ℚ → float | rmode.NE r := let low := of_rat_dn r, high := of_rat_up r in if hf : high.is_finite then if r = to_rat _ hf then high else if lf : low.is_finite then if r - to_rat _ lf > to_rat _ hf - r then high else if r - to_rat _ lf < to_rat _ hf - r then low else match low, lf with float.finite s e m f, _ := if 2 ∣ m then low else high end else float.inf tt else float.inf ff namespace float instance : has_neg float := ⟨float.neg⟩ meta def add (mode : rmode) : float → float → float | nan _ := nan | _ nan := nan | (inf tt) (inf ff) := nan | (inf ff) (inf tt) := nan | (inf s₁) _ := inf s₁ | _ (inf s₂) := inf s₂ | (finite s₁ e₁ m₁ v₁) (finite s₂ e₂ m₂ v₂) := let f₁ := finite s₁ e₁ m₁ v₁, f₂ := finite s₂ e₂ m₂ v₂ in of_rat mode (to_rat f₁ rfl + to_rat f₂ rfl) meta instance : has_add float := ⟨float.add rmode.NE⟩ meta def sub (mode : rmode) (f1 f2 : float) : float := add mode f1 (-f2) meta instance : has_sub float := ⟨float.sub rmode.NE⟩ meta def mul (mode : rmode) : float → float → float | nan _ := nan | _ nan := nan | (inf s₁) f₂ := if f₂.is_zero then nan else inf (bxor s₁ f₂.sign) | f₁ (inf s₂) := if f₁.is_zero then nan else inf (bxor f₁.sign s₂) | (finite s₁ e₁ m₁ v₁) (finite s₂ e₂ m₂ v₂) := let f₁ := finite s₁ e₁ m₁ v₁, f₂ := finite s₂ e₂ m₂ v₂ in of_rat mode (to_rat f₁ rfl * to_rat f₂ rfl) meta def div (mode : rmode) : float → float → float | nan _ := nan | _ nan := nan | (inf s₁) (inf s₂) := nan | (inf s₁) f₂ := inf (bxor s₁ f₂.sign) | f₁ (inf s₂) := zero (bxor f₁.sign s₂) | (finite s₁ e₁ m₁ v₁) (finite s₂ e₂ m₂ v₂) := let f₁ := finite s₁ e₁ m₁ v₁, f₂ := finite s₂ e₂ m₂ v₂ in if f₂.is_zero then inf (bxor s₁ s₂) else of_rat mode (to_rat f₁ rfl / to_rat f₂ rfl) end float end fp
822830f4414461745bbce6ef0d0fbe99556ce259
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/strictImplicit.lean
1cc86a68550e1b6710fec14131bca951c0ff3e70
[ "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
109
lean
def g {α : Type} (a : α) := a def f {{α : Type}} (a : α) := a #check g #check f #check g 1 #check f 1
b285043c9405564d6e580c3aae3256e15e657caa
4f643cce24b2d005aeeb5004c2316a8d6cc7f3b1
/omin/def_choice/choice4.lean
16fbb32b7b1cc351f1de63b1b511e5bfae607bd6
[]
no_license
rwbarton/lean-omin
da209ed061d64db65a8f7f71f198064986f30eb9
fd733c6d95ef6f4743aae97de5e15df79877c00e
refs/heads/master
1,674,408,673,325
1,607,343,535,000
1,607,343,535,000
285,150,399
9
0
null
null
null
null
UTF-8
Lean
false
false
3,893
lean
import o_minimal.examples.simple import .choice3 import ..tame import ..ultra -- TODO: for lean core library: modify binder type of dif_pos etc.: -- lemma {u} dif_pos' {c : Prop} {h : decidable c} (hc : c) {α : Sort u} {t : c → α} {e : ¬c → α} : dite c t e = t hc := dif_pos hc -- Avoids the need (unexplained) for `open_locale classical` below. -- The comments above are obsolete, but this still seems like a good idea. open o_minimal variables {R : Type*} [OQM R] variables {X : set R} local notation `½` := (1/2 : ℚ) lemma lt_of_self_add_lt {a b : R} (h : a + a < b + b) : a < b := begin contrapose! h, exact add_le_add h h end lemma average_between {a b : R} (hab : a < b) : ½ • (a + b) ∈ set.Ioo a b := begin split, { apply lt_of_self_add_lt, rw half_add_half, apply add_lt_add_left hab }, { apply lt_of_self_add_lt, rw half_add_half, apply add_lt_add_right hab } end local attribute [instance] one lemma one_pos : (0 : R) < 1 := classical.some_spec _ lemma chosen_one_mem (nX : X.nonempty) (tX : tame X) : (chosen_one X) ∈ X := begin -- Administrative nonsense; also handle the trivial "has least" case. dsimp [chosen_one, roption.map, roption.orelse_pure, function.comp], split_ifs with hleast hinf hsup hsup hsup; try { dsimp [the_least, the_inf, the_sup] at * }, { obtain ⟨e, he⟩ := hleast, rw get_pfun_of_rel_eq_of_rel he, exact he.1 }, any_goals { obtain ⟨a, ha⟩ := hinf, simp only [get_pfun_of_rel_eq_of_rel ha] at ⊢ hsup }, any_goals { obtain ⟨b, hb⟩ := hsup, rw get_pfun_of_rel_eq_of_rel hb, try { clear hsup } }, -- Now handle the remaining cases, respectively those yielding -- (a+b)/2, b-1, a+1, 0 -- where a = inf X, b = sup Y, Y = {b | a < b ∧ (a, b) ⊆ X}. { have hab : a < b, { obtain ⟨b', hb'⟩ := hb.nonempty, exact lt_of_lt_of_le hb'.1 (hb.1 hb') }, have mid : ½ • (a + b) ∈ set.Ioo a b := average_between hab, obtain ⟨c, hc, hmc⟩ := (lt_is_lub_iff hb).mp mid.2, apply hc.2, exact ⟨mid.1, hmc⟩ }, { let Y := {b | a < b ∧ set.Ioo a b ⊆ X}, change ¬ ∃ b, is_lub Y b at hsup, have nY : Y.nonempty, { have := above_inf tX ha (λ H, hleast ⟨a, H, ha.1⟩), -- TODO: for_mathlib: ^ is_glb ∧ mem → is_least rw mem_above_iff at this, obtain ⟨b, hab, hb⟩ := this, exact ⟨b, hab, hb⟩ }, have tY : tame Y, { refine tame_of_def simple_struc _, apply def_set.and, { exact definable_lt def_fun_const def_fun.id }, { apply def_set.forall, apply def_set.imp, { apply def_set.and, { exact definable_lt def_fun_const def_fun.snd }, { exact definable_lt def_fun.snd def_fun.fst } }, { exact def_fun.snd.preimage tX.def_set } } }, have := mt (exists_tSup tY nY) hsup, rw not_bdd_above_iff at this, obtain ⟨b, hb₁, hb₂⟩ := this (a + 1), apply hb₁.2 ⟨lt_add_of_pos_right _ one_pos, hb₂⟩ }, { obtain ⟨c, hc₁, hc₂⟩ := (lt_is_lub_iff hb).mp (sub_lt_self b one_pos), exact hc₁ hc₂ }, { let Y := {b | set.Iio b ⊆ X}, change ¬ ∃ b, is_lub Y b at hsup, have nY : Y.nonempty, { have := mt (exists_tInf tX nX) hinf, exact (contains_Iio_or_bdd_below tX).resolve_right this }, have tY : tame Y, { refine tame_of_def simple_struc _, apply def_set.forall, apply def_set.imp, { exact definable_lt def_fun.snd def_fun.fst }, { exact def_fun.snd.preimage tX.def_set } }, have := mt (exists_tSup tY nY) hsup, rw not_bdd_above_iff at this, obtain ⟨b, hb₁, hb₂⟩ := this 0, apply hb₁ hb₂ } end lemma chosen_one'_mem (nX : X.nonempty) : (chosen_one' X) ∈ X := begin unfold chosen_one', split_ifs with h, { exact chosen_one_mem nX h }, { exact classical.some_spec nX } end
e0dd013021cc1125a6002aec4fbb41fc6f138eb2
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/nat/modeq.lean
30407ca709d0e9927a1e81dee629b4f2f4a26539
[ "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
12,834
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import data.int.gcd import tactic.abel import data.list.rotate /- # Congruences modulo a natural number This file defines the equivalence relation `a ≡ b [MOD n]` on the natural numbers, and proves basic properties about it such as the Chinese Remainder Theorem `modeq_and_modeq_iff_modeq_mul`. ## Notations `a ≡ b [MOD n]` is notation for `modeq n a b`, which is defined to mean `a % n = b % n`. ## Tags modeq, congruence, mod, MOD, modulo -/ namespace nat /-- Modular equality. `modeq n a b`, or `a ≡ b [MOD n]`, means that `a - b` is a multiple of `n`. -/ @[derive decidable] def modeq (n a b : ℕ) := a % n = b % n notation a ` ≡ `:50 b ` [MOD `:50 n `]`:0 := modeq n a b namespace modeq variables {n m a b c d : ℕ} @[refl] protected theorem refl (a : ℕ) : a ≡ a [MOD n] := @rfl _ _ @[symm] protected theorem symm : a ≡ b [MOD n] → b ≡ a [MOD n] := eq.symm @[trans] protected theorem trans : a ≡ b [MOD n] → b ≡ c [MOD n] → a ≡ c [MOD n] := eq.trans theorem modeq_zero_iff : a ≡ 0 [MOD n] ↔ n ∣ a := by rw [modeq, zero_mod, dvd_iff_mod_eq_zero] theorem modeq_iff_dvd : a ≡ b [MOD n] ↔ (n:ℤ) ∣ b - a := by rw [modeq, eq_comm, ← int.coe_nat_inj', int.coe_nat_mod, int.coe_nat_mod, int.mod_eq_mod_iff_mod_sub_eq_zero, int.dvd_iff_mod_eq_zero] theorem modeq_of_dvd : (n:ℤ) ∣ b - a → a ≡ b [MOD n] := modeq_iff_dvd.2 theorem dvd_of_modeq : a ≡ b [MOD n] → (n:ℤ) ∣ b - a := modeq_iff_dvd.1 /-- A variant of `modeq_iff_dvd` with `nat` divisibility -/ theorem modeq_iff_dvd' (h : a ≤ b) : a ≡ b [MOD n] ↔ n ∣ b - a := by rw [modeq_iff_dvd, ←int.coe_nat_dvd, int.coe_nat_sub h] theorem mod_modeq (a n) : a % n ≡ a [MOD n] := nat.mod_mod _ _ theorem modeq_of_dvd_of_modeq (d : m ∣ n) (h : a ≡ b [MOD n]) : a ≡ b [MOD m] := modeq_of_dvd $ dvd_trans (int.coe_nat_dvd.2 d) (dvd_of_modeq h) theorem modeq_mul_left' (c : ℕ) (h : a ≡ b [MOD n]) : c * a ≡ c * b [MOD (c * n)] := by unfold modeq at *; rw [mul_mod_mul_left, mul_mod_mul_left, h] theorem modeq_mul_left (c : ℕ) (h : a ≡ b [MOD n]) : c * a ≡ c * b [MOD n] := modeq_of_dvd_of_modeq (dvd_mul_left _ _) $ modeq_mul_left' _ h theorem modeq_mul_right' (c : ℕ) (h : a ≡ b [MOD n]) : a * c ≡ b * c [MOD (n * c)] := by rw [mul_comm a, mul_comm b, mul_comm n]; exact modeq_mul_left' c h theorem modeq_mul_right (c : ℕ) (h : a ≡ b [MOD n]) : a * c ≡ b * c [MOD n] := by rw [mul_comm a, mul_comm b]; exact modeq_mul_left c h theorem modeq_mul (h₁ : a ≡ b [MOD n]) (h₂ : c ≡ d [MOD n]) : a * c ≡ b * d [MOD n] := (modeq_mul_left _ h₂).trans (modeq_mul_right _ h₁) theorem modeq_add (h₁ : a ≡ b [MOD n]) (h₂ : c ≡ d [MOD n]) : a + c ≡ b + d [MOD n] := modeq_of_dvd begin convert dvd_add (dvd_of_modeq h₁) (dvd_of_modeq h₂) using 1, simp [sub_eq_add_neg, add_left_comm, add_comm], end theorem modeq_add_cancel_left (h₁ : a ≡ b [MOD n]) (h₂ : a + c ≡ b + d [MOD n]) : c ≡ d [MOD n] := begin simp only [modeq_iff_dvd] at *, convert _root_.dvd_sub h₂ h₁ using 1, simp [sub_eq_add_neg], abel end theorem modeq_add_cancel_right (h₁ : c ≡ d [MOD n]) (h₂ : a + c ≡ b + d [MOD n]) : a ≡ b [MOD n] := by rw [add_comm a, add_comm b] at h₂; exact modeq_add_cancel_left h₁ h₂ theorem modeq_of_modeq_mul_left (m : ℕ) (h : a ≡ b [MOD m * n]) : a ≡ b [MOD n] := by rw [modeq_iff_dvd] at *; exact dvd.trans (dvd_mul_left (n : ℤ) (m : ℤ)) h theorem modeq_of_modeq_mul_right (m : ℕ) : a ≡ b [MOD n * m] → a ≡ b [MOD n] := mul_comm m n ▸ modeq_of_modeq_mul_left _ local attribute [semireducible] int.nonneg /-- The natural number less than `n*m` congruent to `a` mod `n` and `b` mod `m` -/ def chinese_remainder (co : coprime n m) (a b : ℕ) : {k // k ≡ a [MOD n] ∧ k ≡ b [MOD m]} := ⟨let (c, d) := xgcd n m in int.to_nat ((b * c * n + a * d * m) % (n * m)), begin rw xgcd_val, dsimp [chinese_remainder._match_1], rw [modeq_iff_dvd, modeq_iff_dvd], rw [int.to_nat_of_nonneg], swap, { by_cases h₁ : n = 0, {simp [coprime, h₁] at co, substs m n, simp}, by_cases h₂ : m = 0, {simp [coprime, h₂] at co, substs m n, simp}, exact int.mod_nonneg _ (mul_ne_zero (int.coe_nat_ne_zero.2 h₁) (int.coe_nat_ne_zero.2 h₂)) }, have := gcd_eq_gcd_ab n m, simp [co.gcd_eq_one, mul_comm] at this, rw [int.mod_def, ← sub_add, ← sub_add]; split, { refine dvd_add _ (dvd_trans (dvd_mul_right _ _) (dvd_mul_right _ _)), rw [add_comm, ← sub_sub], refine _root_.dvd_sub _ (dvd_mul_left _ _), have := congr_arg ((*) ↑a) this, exact ⟨_, by rwa [mul_add, ← mul_assoc, ← mul_assoc, mul_one, mul_comm, ← sub_eq_iff_eq_add] at this⟩ }, { refine dvd_add _ (dvd_trans (dvd_mul_left _ _) (dvd_mul_right _ _)), rw [← sub_sub], refine _root_.dvd_sub _ (dvd_mul_left _ _), have := congr_arg ((*) ↑b) this, exact ⟨_, by rwa [mul_add, ← mul_assoc, ← mul_assoc, mul_one, mul_comm _ ↑m, ← sub_eq_iff_eq_add'] at this⟩ } end⟩ lemma modeq_and_modeq_iff_modeq_mul {a b m n : ℕ} (hmn : coprime m n) : a ≡ b [MOD m] ∧ a ≡ b [MOD n] ↔ (a ≡ b [MOD m * n]) := ⟨λ h, begin rw [nat.modeq.modeq_iff_dvd, nat.modeq.modeq_iff_dvd, ← int.dvd_nat_abs, int.coe_nat_dvd, ← int.dvd_nat_abs, int.coe_nat_dvd] at h, rw [nat.modeq.modeq_iff_dvd, ← int.dvd_nat_abs, int.coe_nat_dvd], exact hmn.mul_dvd_of_dvd_of_dvd h.1 h.2 end, λ h, ⟨nat.modeq.modeq_of_modeq_mul_right _ h, nat.modeq.modeq_of_modeq_mul_left _ h⟩⟩ lemma coprime_of_mul_modeq_one (b : ℕ) {a n : ℕ} (h : a * b ≡ 1 [MOD n]) : coprime a n := nat.coprime_of_dvd' (λ k kp ⟨ka, hka⟩ ⟨kb, hkb⟩, int.coe_nat_dvd.1 begin rw [hka, hkb, modeq_iff_dvd] at h, cases h with z hz, rw [sub_eq_iff_eq_add] at hz, rw [hz, int.coe_nat_mul, mul_assoc, mul_assoc, int.coe_nat_mul, ← mul_add], exact dvd_mul_right _ _, end) end modeq @[simp] lemma mod_mul_right_mod (a b c : ℕ) : a % (b * c) % b = a % b := modeq.modeq_of_modeq_mul_right _ (modeq.mod_modeq _ _) @[simp] lemma mod_mul_left_mod (a b c : ℕ) : a % (b * c) % c = a % c := modeq.modeq_of_modeq_mul_left _ (modeq.mod_modeq _ _) lemma div_mod_eq_mod_mul_div (a b c : ℕ) : a / b % c = a % (b * c) / b := if hb0 : b = 0 then by simp [hb0] else by rw [← @add_right_cancel_iff _ _ (c * (a / b / c)), mod_add_div, nat.div_div_eq_div_mul, ← nat.mul_right_inj (nat.pos_of_ne_zero hb0),← @add_left_cancel_iff _ _ (a % b), mod_add_div, mul_add, ← @add_left_cancel_iff _ _ (a % (b * c) % b), add_left_comm, ← add_assoc (a % (b * c) % b), mod_add_div, ← mul_assoc, mod_add_div, mod_mul_right_mod] lemma add_mod_add_ite (a b c : ℕ) : (a + b) % c + (if c ≤ a % c + b % c then c else 0) = a % c + b % c := have (a + b) % c = (a % c + b % c) % c, from nat.modeq.modeq_add (nat.modeq.mod_modeq _ _).symm (nat.modeq.mod_modeq _ _).symm, if hc0 : c = 0 then by simp [hc0] else begin rw this, split_ifs, { have h2 : (a % c + b % c) / c < 2, from nat.div_lt_of_lt_mul (by rw mul_two; exact add_lt_add (nat.mod_lt _ (nat.pos_of_ne_zero hc0)) (nat.mod_lt _ (nat.pos_of_ne_zero hc0))), have h0 : 0 < (a % c + b % c) / c, from nat.div_pos h (nat.pos_of_ne_zero hc0), rw [← @add_right_cancel_iff _ _ (c * ((a % c + b % c) / c)), add_comm _ c, add_assoc, mod_add_div, le_antisymm (le_of_lt_succ h2) h0, mul_one, add_comm] }, { rw [nat.mod_eq_of_lt (lt_of_not_ge h), add_zero] } end lemma add_mod_of_add_mod_lt {a b c : ℕ} (hc : a % c + b % c < c) : (a + b) % c = a % c + b % c := by rw [← add_mod_add_ite, if_neg (not_le_of_lt hc), add_zero] lemma add_mod_add_of_le_add_mod {a b c : ℕ} (hc : c ≤ a % c + b % c) : (a + b) % c + c = a % c + b % c := by rw [← add_mod_add_ite, if_pos hc] lemma add_div {a b c : ℕ} (hc0 : 0 < c) : (a + b) / c = a / c + b / c + if c ≤ a % c + b % c then 1 else 0 := begin rw [← nat.mul_right_inj hc0, ← @add_left_cancel_iff _ _ ((a + b) % c + a % c + b % c)], suffices : (a + b) % c + c * ((a + b) / c) + a % c + b % c = a % c + c * (a / c) + (b % c + c * (b / c)) + c * (if c ≤ a % c + b % c then 1 else 0) + (a + b) % c, { simpa only [mul_add, add_comm, add_left_comm, add_assoc] }, rw [mod_add_div, mod_add_div, mod_add_div, mul_ite, add_assoc, add_assoc], conv_lhs { rw ← add_mod_add_ite }, simp, ac_refl end lemma add_div_eq_of_add_mod_lt {a b c : ℕ} (hc : a % c + b % c < c) : (a + b) / c = a / c + b / c := if hc0 : c = 0 then by simp [hc0] else by rw [add_div (nat.pos_of_ne_zero hc0), if_neg (not_le_of_lt hc), add_zero] lemma add_div_eq_of_le_mod_add_mod {a b c : ℕ} (hc : c ≤ a % c + b % c) (hc0 : 0 < c) : (a + b) / c = a / c + b / c + 1 := by rw [add_div hc0, if_pos hc] lemma add_div_le_add_div (a b c : ℕ) : a / c + b / c ≤ (a + b) / c := if hc0 : c = 0 then by simp [hc0] else by rw [nat.add_div (nat.pos_of_ne_zero hc0)]; exact le_add_right _ _ lemma le_mod_add_mod_of_dvd_add_of_not_dvd {a b c : ℕ} (h : c ∣ a + b) (ha : ¬ c ∣ a) : c ≤ a % c + b % c := by_contradiction $ λ hc, have (a + b) % c = a % c + b % c, from add_mod_of_add_mod_lt (lt_of_not_ge hc), by simp [dvd_iff_mod_eq_zero, *] at * lemma odd_mul_odd {n m : ℕ} (hn1 : n % 2 = 1) (hm1 : m % 2 = 1) : (n * m) % 2 = 1 := show (n * m) % 2 = (1 * 1) % 2, from nat.modeq.modeq_mul hn1 hm1 lemma odd_mul_odd_div_two {m n : ℕ} (hm1 : m % 2 = 1) (hn1 : n % 2 = 1) : (m * n) / 2 = m * (n / 2) + m / 2 := have hm0 : 0 < m := nat.pos_of_ne_zero (λ h, by simp * at *), have hn0 : 0 < n := nat.pos_of_ne_zero (λ h, by simp * at *), (nat.mul_right_inj (show 0 < 2, from dec_trivial)).1 $ by rw [mul_add, two_mul_odd_div_two hm1, mul_left_comm, two_mul_odd_div_two hn1, two_mul_odd_div_two (nat.odd_mul_odd hm1 hn1), nat.mul_sub_left_distrib, mul_one, ← nat.add_sub_assoc hm0, nat.sub_add_cancel (le_mul_of_one_le_right (nat.zero_le _) hn0)] lemma odd_of_mod_four_eq_one {n : ℕ} (h : n % 4 = 1) : n % 2 = 1 := @modeq.modeq_of_modeq_mul_left 2 n 1 2 h lemma odd_of_mod_four_eq_three {n : ℕ} (h : n % 4 = 3) : n % 2 = 1 := @modeq.modeq_of_modeq_mul_left 2 n 3 2 h end nat namespace list variable {α : Type*} lemma nth_rotate : ∀ {l : list α} {n m : ℕ} (hml : m < l.length), (l.rotate n).nth m = l.nth ((m + n) % l.length) | [] n m hml := (nat.not_lt_zero _ hml).elim | l 0 m hml := by simp [nat.mod_eq_of_lt hml] | (a::l) (n+1) m hml := have h₃ : m < list.length (l ++ [a]), by simpa using hml, (lt_or_eq_of_le (nat.le_of_lt_succ $ nat.mod_lt (m + n) (lt_of_le_of_lt (nat.zero_le _) hml))).elim (λ hml', have h₁ : (m + (n + 1)) % ((a :: l : list α).length) = (m + n) % ((a :: l : list α).length) + 1, from calc (m + (n + 1)) % (l.length + 1) = ((m + n) % (l.length + 1) + 1) % (l.length + 1) : add_assoc m n 1 ▸ nat.modeq.modeq_add (nat.mod_mod _ _).symm rfl ... = (m + n) % (l.length + 1) + 1 : nat.mod_eq_of_lt (nat.succ_lt_succ hml'), have h₂ : (m + n) % (l ++ [a]).length < l.length, by simpa [nat.add_one] using hml', by rw [list.rotate_cons_succ, nth_rotate h₃, list.nth_append h₂, h₁, list.nth]; simp) (λ hml', have h₁ : (m + (n + 1)) % (l.length + 1) = 0, from calc (m + (n + 1)) % (l.length + 1) = (l.length + 1) % (l.length + 1) : add_assoc m n 1 ▸ nat.modeq.modeq_add (hml'.trans (nat.mod_eq_of_lt (nat.lt_succ_self _)).symm) rfl ... = 0 : by simp, have h₂ : l.length < (l ++ [a]).length, by simp [nat.lt_succ_self], by rw [list.length, list.rotate_cons_succ, nth_rotate h₃, list.length_append, list.length_cons, list.length, zero_add, hml', h₁, list.nth_concat_length]; refl) lemma rotate_eq_self_iff_eq_repeat [hα : nonempty α] : ∀ {l : list α}, (∀ n, l.rotate n = l) ↔ ∃ a, l = list.repeat a l.length | [] := ⟨λ h, nonempty.elim hα (λ a, ⟨a, by simp⟩), by simp⟩ | (a::l) := ⟨λ h, ⟨a, list.ext_le (by simp) $ λ n hn h₁, begin rw [← option.some_inj, ← list.nth_le_nth], conv {to_lhs, rw ← h ((list.length (a :: l)) - n)}, rw [nth_rotate hn, nat.add_sub_cancel' (le_of_lt hn), nat.mod_self, nth_le_repeat], refl end⟩, λ ⟨a, ha⟩ n, ha.symm ▸ list.ext_le (by simp) (λ m hm h, have hm' : (m + n) % (list.repeat a (list.length (a :: l))).length < list.length (a :: l), by rw list.length_repeat; exact nat.mod_lt _ (nat.succ_pos _), by rw [nth_le_repeat, ← option.some_inj, ← list.nth_le_nth, nth_rotate h, list.nth_le_nth, nth_le_repeat]; simp * at *)⟩ end list
e6f6ee163aa15cd2ce1c98424eeb6cb02f27f6e3
e898bfefd5cb60a60220830c5eba68cab8d02c79
/uexp/src/uexp/rules/pushJoinThroughUnionOnLeft.lean
24829acfd9b51d124c3f9ce2e0d2f7017562a850
[ "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
1,828
lean
import ..sql import ..tactics import ..u_semiring import ..extra_constants import ..UDP set_option profiler true open Expr open Proj open Pred open SQL open tree notation `int` := datatypes.int theorem rule: forall ( Γ scm_t scm_account scm_bonus scm_dept scm_emp: Schema) (rel_t: relation scm_t) (rel_account: relation scm_account) (rel_bonus: relation scm_bonus) (rel_dept: relation scm_dept) (rel_emp: relation scm_emp) (t_k0 : Column int scm_t) (t_c1 : Column int scm_t) (t_f1_a0 : Column int scm_t) (t_f2_a0 : Column int scm_t) (t_f0_c0 : Column int scm_t) (t_f1_c0 : Column int scm_t) (t_f0_c1 : Column int scm_t) (t_f1_c2 : Column int scm_t) (t_f2_c3 : Column int scm_t) (account_acctno : Column int scm_account) (account_type : Column int scm_account) (account_balance : Column int scm_account) (bonus_ename : Column int scm_bonus) (bonus_job : Column int scm_bonus) (bonus_sal : Column int scm_bonus) (bonus_comm : Column int scm_bonus) (dept_deptno : Column int scm_dept) (dept_name : Column int scm_dept) (emp_empno : Column int scm_emp) (emp_ename : Column int scm_emp) (emp_job : Column int scm_emp) (emp_mgr : Column int scm_emp) (emp_hiredate : Column int scm_emp) (emp_comm : Column int scm_emp) (emp_sal : Column int scm_emp) (emp_deptno : Column int scm_emp) (emp_slacker : Column int scm_emp), denoteSQL ((SELECT1 (right⋅left⋅emp_sal) FROM1 (product (((SELECT * FROM1 (table rel_emp) )) UNION ALL ((SELECT * FROM1 (table rel_emp) ))) (table rel_emp)) ) : SQL Γ _ ) = denoteSQL ((SELECT1 (right⋅right⋅emp_sal) FROM1 (((SELECT * FROM1 (product (table rel_emp) (table rel_emp)) )) UNION ALL ((SELECT * FROM1 (product (table rel_emp) (table rel_emp)) ))) ) : SQL Γ _) := begin intros, unfold_all_denotations, funext, print_size, simp, print_size, UDP, end
fb50b978a12e1a05f87366648947411fc6cf4b34
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/category_theory/preadditive/opposite.lean
9cb7e4e48d28600f6d296c9f002b7f956de51a31
[ "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
1,817
lean
/- Copyright (c) 2021 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Adam Topaz -/ import category_theory.preadditive import category_theory.preadditive.additive_functor import data.equiv.transfer_instance /-! # If `C` is preadditive, `Cᵒᵖ` has a natural preadditive structure. -/ open opposite namespace category_theory variables (C : Type*) [category C] [preadditive C] instance : preadditive Cᵒᵖ := { hom_group := λ X Y, equiv.add_comm_group (op_equiv X Y), add_comp' := λ X Y Z f f' g, congr_arg quiver.hom.op (preadditive.comp_add _ _ _ g.unop f.unop f'.unop), comp_add' := λ X Y Z f g g', congr_arg quiver.hom.op (preadditive.add_comp _ _ _ g.unop g'.unop f.unop), } instance module_End_left {X : Cᵒᵖ} {Y : C} : module (End X) (unop X ⟶ Y) := { smul_add := λ r f g, preadditive.comp_add _ _ _ _ _ _, smul_zero := λ r, limits.comp_zero, add_smul := λ r s f, preadditive.add_comp _ _ _ _ _ _, zero_smul := λ f, limits.zero_comp } @[simp] lemma unop_zero (X Y : Cᵒᵖ) : (0 : X ⟶ Y).unop = 0 := rfl @[simp] lemma unop_add {X Y : Cᵒᵖ} (f g : X ⟶ Y) : (f + g).unop = f.unop + g.unop := rfl @[simp] lemma op_zero (X Y : C) : (0 : X ⟶ Y).op = 0 := rfl @[simp] lemma op_add {X Y : C} (f g : X ⟶ Y) : (f + g).op = f.op + g.op := rfl variables {C} {D : Type*} [category D] [preadditive D] instance functor.op_additive (F : C ⥤ D) [F.additive] : F.op.additive := {} instance functor.right_op_additive (F : Cᵒᵖ ⥤ D) [F.additive] : F.right_op.additive := {} instance functor.left_op_additive (F : C ⥤ Dᵒᵖ) [F.additive] : F.left_op.additive := {} instance functor.unop_additive (F : Cᵒᵖ ⥤ Dᵒᵖ) [F.additive] : F.unop.additive := {} end category_theory
1fa02afc8bb5abab9166b8442bd0549d143b8586
80cc5bf14c8ea85ff340d1d747a127dcadeb966f
/src/measure_theory/integration.lean
333765a12cb5f94ba648e5f7a526195ecd5eaa7a
[ "Apache-2.0" ]
permissive
lacker/mathlib
f2439c743c4f8eb413ec589430c82d0f73b2d539
ddf7563ac69d42cfa4a1bfe41db1fed521bd795f
refs/heads/master
1,671,948,326,773
1,601,479,268,000
1,601,479,268,000
298,686,743
0
0
Apache-2.0
1,601,070,794,000
1,601,070,794,000
null
UTF-8
Lean
false
false
68,004
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Johannes Hölzl -/ import measure_theory.measure_space import measure_theory.borel_space import data.indicator_function import data.support /-! # Lebesgue integral for `ennreal`-valued functions We define simple functions and show that each Borel measurable function on `ennreal` can be approximated by a sequence of simple functions. To prove something for an arbitrary measurable function into `ennreal`, the theorem `measurable.ennreal_induction` shows that is it sufficient to show that the property holds for (multiples of) characteristic functions and is closed under addition and supremum of increasing sequences of functions. ## Notation We introduce the following notation for the lower Lebesgue integral of a function `f : α → ennreal`. * `∫⁻ x, f x ∂μ`: integral of a function `f : α → ennreal` with respect to a measure `μ`; * `∫⁻ x, f x`: integral of a function `f : α → ennreal` with respect to the canonical measure `volume` on `α`; * `∫⁻ x in s, f x ∂μ`: integral of a function `f : α → ennreal` over a set `s` with respect to a measure `μ`, defined as `∫⁻ x, f x ∂(μ.restrict s)`; * `∫⁻ x in s, f x`: integral of a function `f : α → ennreal` over a set `s` with respect to the canonical measure `volume`, defined as `∫⁻ x, f x ∂(volume.restrict s)`. -/ noncomputable theory open set (hiding restrict restrict_apply) filter ennreal open_locale classical topological_space big_operators nnreal namespace measure_theory variables {α β γ δ : Type*} /-- A function `f` from a measurable space to any type is called *simple*, if every preimage `f ⁻¹' {x}` is measurable, and the range is finite. This structure bundles a function with these properties. -/ structure {u v} simple_func (α : Type u) [measurable_space α] (β : Type v) := (to_fun : α → β) (is_measurable_fiber' : ∀ x, is_measurable (to_fun ⁻¹' {x})) (finite_range' : (set.range to_fun).finite) local infixr ` →ₛ `:25 := simple_func namespace simple_func section measurable variables [measurable_space α] instance has_coe_to_fun : has_coe_to_fun (α →ₛ β) := ⟨_, to_fun⟩ lemma coe_injective ⦃f g : α →ₛ β⦄ (H : ⇑f = g) : f = g := by cases f; cases g; congr; exact H @[ext] theorem ext {f g : α →ₛ β} (H : ∀ a, f a = g a) : f = g := coe_injective $ funext H lemma finite_range (f : α →ₛ β) : (set.range f).finite := f.finite_range' lemma is_measurable_fiber (f : α →ₛ β) (x : β) : is_measurable (f ⁻¹' {x}) := f.is_measurable_fiber' x /-- Range of a simple function `α →ₛ β` as a `finset β`. -/ protected def range (f : α →ₛ β) : finset β := f.finite_range.to_finset @[simp] theorem mem_range {f : α →ₛ β} {b} : b ∈ f.range ↔ b ∈ range f := finite.mem_to_finset theorem mem_range_self (f : α →ₛ β) (x : α) : f x ∈ f.range := mem_range.2 ⟨x, rfl⟩ @[simp] lemma coe_range (f : α →ₛ β) : (↑f.range : set β) = set.range f := f.finite_range.coe_to_finset theorem mem_range_of_measure_ne_zero {f : α →ₛ β} {x : β} {μ : measure α} (H : μ (f ⁻¹' {x}) ≠ 0) : x ∈ f.range := let ⟨a, ha⟩ := nonempty_of_measure_ne_zero H in mem_range.2 ⟨a, ha⟩ lemma forall_range_iff {f : α →ₛ β} {p : β → Prop} : (∀ y ∈ f.range, p y) ↔ ∀ x, p (f x) := by simp only [mem_range, set.forall_range_iff] lemma exists_range_iff {f : α →ₛ β} {p : β → Prop} : (∃ y ∈ f.range, p y) ↔ ∃ x, p (f x) := by simpa only [mem_range, exists_prop] using set.exists_range_iff lemma preimage_eq_empty_iff (f : α →ₛ β) (b : β) : f ⁻¹' {b} = ∅ ↔ b ∉ f.range := preimage_singleton_eq_empty.trans $ not_congr mem_range.symm /-- Constant function as a `simple_func`. -/ def const (α) {β} [measurable_space α] (b : β) : α →ₛ β := ⟨λ a, b, λ x, is_measurable.const _, finite_range_const⟩ instance [inhabited β] : inhabited (α →ₛ β) := ⟨const _ (default _)⟩ theorem const_apply (a : α) (b : β) : (const α b) a = b := rfl @[simp] theorem coe_const (b : β) : ⇑(const α b) = function.const α b := rfl @[simp] lemma range_const (α) [measurable_space α] [nonempty α] (b : β) : (const α b).range = {b} := finset.coe_injective $ by simp lemma is_measurable_cut (r : α → β → Prop) (f : α →ₛ β) (h : ∀b, is_measurable {a | r a b}) : is_measurable {a | r a (f a)} := begin have : {a | r a (f a)} = ⋃ b ∈ range f, {a | r a b} ∩ f ⁻¹' {b}, { ext a, suffices : r a (f a) ↔ ∃ i, r a (f i) ∧ f a = f i, by simpa, exact ⟨λ h, ⟨a, ⟨h, rfl⟩⟩, λ ⟨a', ⟨h', e⟩⟩, e.symm ▸ h'⟩ }, rw this, exact is_measurable.bUnion f.finite_range.countable (λ b _, is_measurable.inter (h b) (f.is_measurable_fiber _)) end theorem is_measurable_preimage (f : α →ₛ β) (s) : is_measurable (f ⁻¹' s) := is_measurable_cut (λ _ b, b ∈ s) f (λ b, is_measurable.const (b ∈ s)) /-- A simple function is measurable -/ protected theorem measurable [measurable_space β] (f : α →ₛ β) : measurable f := λ s _, is_measurable_preimage f s /-- If-then-else as a `simple_func`. -/ def piecewise (s : set α) (hs : is_measurable s) (f g : α →ₛ β) : α →ₛ β := ⟨s.piecewise f g, λ x, by letI : measurable_space β := ⊤; exact f.measurable.piecewise hs g.measurable trivial, (f.finite_range.union g.finite_range).subset range_ite_subset⟩ @[simp] theorem coe_piecewise {s : set α} (hs : is_measurable s) (f g : α →ₛ β) : ⇑(piecewise s hs f g) = s.piecewise f g := rfl theorem piecewise_apply {s : set α} (hs : is_measurable s) (f g : α →ₛ β) (a) : piecewise s hs f g a = if a ∈ s then f a else g a := rfl @[simp] lemma piecewise_compl {s : set α} (hs : is_measurable sᶜ) (f g : α →ₛ β) : piecewise sᶜ hs f g = piecewise s hs.of_compl g f := coe_injective $ by simp [hs] @[simp] lemma piecewise_univ (f g : α →ₛ β) : piecewise univ is_measurable.univ f g = f := coe_injective $ by simp @[simp] lemma piecewise_empty (f g : α →ₛ β) : piecewise ∅ is_measurable.empty f g = g := coe_injective $ by simp lemma measurable_bind [measurable_space γ] (f : α →ₛ β) (g : β → α → γ) (hg : ∀ b, measurable (g b)) : measurable (λ a, g (f a) a) := λ s hs, f.is_measurable_cut (λ a b, g b a ∈ s) $ λ b, hg b hs /-- If `f : α →ₛ β` is a simple function and `g : β → α →ₛ γ` is a family of simple functions, then `f.bind g` binds the first argument of `g` to `f`. In other words, `f.bind g a = g (f a) a`. -/ def bind (f : α →ₛ β) (g : β → α →ₛ γ) : α →ₛ γ := ⟨λa, g (f a) a, λ c, f.is_measurable_cut (λ a b, g b a = c) $ λ b, (g b).is_measurable_preimage {c}, (f.finite_range.bUnion (λ b _, (g b).finite_range)).subset $ by rintro _ ⟨a, rfl⟩; simp; exact ⟨a, a, rfl⟩⟩ @[simp] theorem bind_apply (f : α →ₛ β) (g : β → α →ₛ γ) (a) : f.bind g a = g (f a) a := rfl /-- Given a function `g : β → γ` and a simple function `f : α →ₛ β`, `f.map g` return the simple function `g ∘ f : α →ₛ γ` -/ def map (g : β → γ) (f : α →ₛ β) : α →ₛ γ := bind f (const α ∘ g) theorem map_apply (g : β → γ) (f : α →ₛ β) (a) : f.map g a = g (f a) := rfl theorem map_map (g : β → γ) (h: γ → δ) (f : α →ₛ β) : (f.map g).map h = f.map (h ∘ g) := rfl @[simp] theorem coe_map (g : β → γ) (f : α →ₛ β) : (f.map g : α → γ) = g ∘ f := rfl @[simp] theorem range_map [decidable_eq γ] (g : β → γ) (f : α →ₛ β) : (f.map g).range = f.range.image g := finset.coe_injective $ by simp [range_comp] @[simp] theorem map_const (g : β → γ) (b : β) : (const α b).map g = const α (g b) := rfl lemma map_preimage (f : α →ₛ β) (g : β → γ) (s : set γ) : (f.map g) ⁻¹' s = f ⁻¹' ↑(f.range.filter (λb, g b ∈ s)) := by { simp only [coe_range, sep_mem_eq, set.mem_range, function.comp_app, coe_map, finset.coe_filter, ← mem_preimage, inter_comm, preimage_inter_range], apply preimage_comp } lemma map_preimage_singleton (f : α →ₛ β) (g : β → γ) (c : γ) : (f.map g) ⁻¹' {c} = f ⁻¹' ↑(f.range.filter (λ b, g b = c)) := map_preimage _ _ _ /-- Composition of a `simple_fun` and a measurable function is a `simple_func`. -/ def comp [measurable_space β] (f : β →ₛ γ) (g : α → β) (hgm : measurable g) : α →ₛ γ := { to_fun := f ∘ g, finite_range' := f.finite_range.subset $ set.range_comp_subset_range _ _, is_measurable_fiber' := λ z, hgm (f.is_measurable_fiber z) } @[simp] lemma coe_comp [measurable_space β] (f : β →ₛ γ) {g : α → β} (hgm : measurable g) : ⇑(f.comp g hgm) = f ∘ g := rfl lemma range_comp_subset_range [measurable_space β] (f : β →ₛ γ) {g : α → β} (hgm : measurable g) : (f.comp g hgm).range ⊆ f.range := finset.coe_subset.1 $ by simp only [coe_range, coe_comp, set.range_comp_subset_range] /-- If `f` is a simple function taking values in `β → γ` and `g` is another simple function with the same domain and codomain `β`, then `f.seq g = f a (g a)`. -/ def seq (f : α →ₛ (β → γ)) (g : α →ₛ β) : α →ₛ γ := f.bind (λf, g.map f) @[simp] lemma seq_apply (f : α →ₛ (β → γ)) (g : α →ₛ β) (a : α) : f.seq g a = f a (g a) := rfl /-- Combine two simple functions `f : α →ₛ β` and `g : α →ₛ β` into `λ a, (f a, g a)`. -/ def pair (f : α →ₛ β) (g : α →ₛ γ) : α →ₛ (β × γ) := (f.map prod.mk).seq g @[simp] lemma pair_apply (f : α →ₛ β) (g : α →ₛ γ) (a) : pair f g a = (f a, g a) := rfl lemma pair_preimage (f : α →ₛ β) (g : α →ₛ γ) (s : set β) (t : set γ) : (pair f g) ⁻¹' (set.prod s t) = (f ⁻¹' s) ∩ (g ⁻¹' t) := rfl /- A special form of `pair_preimage` -/ lemma pair_preimage_singleton (f : α →ₛ β) (g : α →ₛ γ) (b : β) (c : γ) : (pair f g) ⁻¹' {(b, c)} = (f ⁻¹' {b}) ∩ (g ⁻¹' {c}) := by { rw ← singleton_prod_singleton, exact pair_preimage _ _ _ _ } theorem bind_const (f : α →ₛ β) : f.bind (const α) = f := by ext; simp instance [has_zero β] : has_zero (α →ₛ β) := ⟨const α 0⟩ instance [has_add β] : has_add (α →ₛ β) := ⟨λf g, (f.map (+)).seq g⟩ instance [has_mul β] : has_mul (α →ₛ β) := ⟨λf g, (f.map (*)).seq g⟩ instance [has_sup β] : has_sup (α →ₛ β) := ⟨λf g, (f.map (⊔)).seq g⟩ instance [has_inf β] : has_inf (α →ₛ β) := ⟨λf g, (f.map (⊓)).seq g⟩ instance [has_le β] : has_le (α →ₛ β) := ⟨λf g, ∀a, f a ≤ g a⟩ @[simp, norm_cast] lemma coe_zero [has_zero β] : ⇑(0 : α →ₛ β) = 0 := rfl @[simp] lemma const_zero [has_zero β] : const α (0:β) = 0 := rfl @[simp, norm_cast] lemma coe_add [has_add β] (f g : α →ₛ β) : ⇑(f + g) = f + g := rfl @[simp, norm_cast] lemma coe_mul [has_mul β] (f g : α →ₛ β) : ⇑(f * g) = f * g := rfl @[simp, norm_cast] lemma coe_le [preorder β] {f g : α →ₛ β} : (f : α → β) ≤ g ↔ f ≤ g := iff.rfl @[simp] lemma range_zero [nonempty α] [has_zero β] : (0 : α →ₛ β).range = {0} := finset.ext $ λ x, by simp [eq_comm] lemma eq_zero_of_mem_range_zero [has_zero β] : ∀ {y : β}, y ∈ (0 : α →ₛ β).range → y = 0 := forall_range_iff.2 $ λ x, rfl lemma sup_apply [has_sup β] (f g : α →ₛ β) (a : α) : (f ⊔ g) a = f a ⊔ g a := rfl lemma mul_apply [has_mul β] (f g : α →ₛ β) (a : α) : (f * g) a = f a * g a := rfl lemma add_apply [has_add β] (f g : α →ₛ β) (a : α) : (f + g) a = f a + g a := rfl lemma add_eq_map₂ [has_add β] (f g : α →ₛ β) : f + g = (pair f g).map (λp:β×β, p.1 + p.2) := rfl lemma mul_eq_map₂ [has_mul β] (f g : α →ₛ β) : f * g = (pair f g).map (λp:β×β, p.1 * p.2) := rfl lemma sup_eq_map₂ [has_sup β] (f g : α →ₛ β) : f ⊔ g = (pair f g).map (λp:β×β, p.1 ⊔ p.2) := rfl lemma const_mul_eq_map [has_mul β] (f : α →ₛ β) (b : β) : const α b * f = f.map (λa, b * a) := rfl instance [add_monoid β] : add_monoid (α →ₛ β) := function.injective.add_monoid (λ f, show α → β, from f) coe_injective coe_zero coe_add instance add_comm_monoid [add_comm_monoid β] : add_comm_monoid (α →ₛ β) := function.injective.add_comm_monoid (λ f, show α → β, from f) coe_injective coe_zero coe_add instance [has_neg β] : has_neg (α →ₛ β) := ⟨λf, f.map (has_neg.neg)⟩ @[simp, norm_cast] lemma coe_neg [has_neg β] (f : α →ₛ β) : ⇑(-f) = -f := rfl instance [add_group β] : add_group (α →ₛ β) := function.injective.add_group (λ f, show α → β, from f) coe_injective coe_zero coe_add coe_neg @[simp, norm_cast] lemma coe_sub [add_group β] (f g : α →ₛ β) : ⇑(f - g) = f - g := rfl instance [add_comm_group β] : add_comm_group (α →ₛ β) := function.injective.add_comm_group (λ f, show α → β, from f) coe_injective coe_zero coe_add coe_neg variables {K : Type*} instance [has_scalar K β] : has_scalar K (α →ₛ β) := ⟨λk f, f.map ((•) k)⟩ @[simp] lemma coe_smul [has_scalar K β] (c : K) (f : α →ₛ β) : ⇑(c • f) = c • f := rfl lemma smul_apply [has_scalar K β] (k : K) (f : α →ₛ β) (a : α) : (k • f) a = k • f a := rfl instance [semiring K] [add_comm_monoid β] [semimodule K β] : semimodule K (α →ₛ β) := function.injective.semimodule K ⟨λ f, show α → β, from f, coe_zero, coe_add⟩ coe_injective coe_smul lemma smul_eq_map [has_scalar K β] (k : K) (f : α →ₛ β) : k • f = f.map ((•) k) := rfl instance [preorder β] : preorder (α →ₛ β) := { le_refl := λf a, le_refl _, le_trans := λf g h hfg hgh a, le_trans (hfg _) (hgh a), .. simple_func.has_le } instance [partial_order β] : partial_order (α →ₛ β) := { le_antisymm := assume f g hfg hgf, ext $ assume a, le_antisymm (hfg a) (hgf a), .. simple_func.preorder } instance [order_bot β] : order_bot (α →ₛ β) := { bot := const α ⊥, bot_le := λf a, bot_le, .. simple_func.partial_order } instance [order_top β] : order_top (α →ₛ β) := { top := const α ⊤, le_top := λf a, le_top, .. simple_func.partial_order } instance [semilattice_inf β] : semilattice_inf (α →ₛ β) := { inf := (⊓), inf_le_left := assume f g a, inf_le_left, inf_le_right := assume f g a, inf_le_right, le_inf := assume f g h hfh hgh a, le_inf (hfh a) (hgh a), .. simple_func.partial_order } instance [semilattice_sup β] : semilattice_sup (α →ₛ β) := { sup := (⊔), le_sup_left := assume f g a, le_sup_left, le_sup_right := assume f g a, le_sup_right, sup_le := assume f g h hfh hgh a, sup_le (hfh a) (hgh a), .. simple_func.partial_order } instance [semilattice_sup_bot β] : semilattice_sup_bot (α →ₛ β) := { .. simple_func.semilattice_sup,.. simple_func.order_bot } instance [lattice β] : lattice (α →ₛ β) := { .. simple_func.semilattice_sup,.. simple_func.semilattice_inf } instance [bounded_lattice β] : bounded_lattice (α →ₛ β) := { .. simple_func.lattice, .. simple_func.order_bot, .. simple_func.order_top } lemma finset_sup_apply [semilattice_sup_bot β] {f : γ → α →ₛ β} (s : finset γ) (a : α) : s.sup f a = s.sup (λc, f c a) := begin refine finset.induction_on s rfl _, assume a s hs ih, rw [finset.sup_insert, finset.sup_insert, sup_apply, ih] end section restrict variables [has_zero β] /-- Restrict a simple function `f : α →ₛ β` to a set `s`. If `s` is measurable, then `f.restrict s a = if a ∈ s then f a else 0`, otherwise `f.restrict s = const α 0`. -/ def restrict (f : α →ₛ β) (s : set α) : α →ₛ β := if hs : is_measurable s then piecewise s hs f 0 else 0 theorem restrict_of_not_measurable {f : α →ₛ β} {s : set α} (hs : ¬is_measurable s) : restrict f s = 0 := dif_neg hs @[simp] theorem coe_restrict (f : α →ₛ β) {s : set α} (hs : is_measurable s) : ⇑(restrict f s) = indicator s f := by { rw [restrict, dif_pos hs], refl } @[simp] theorem restrict_univ (f : α →ₛ β) : restrict f univ = f := by simp [restrict] @[simp] theorem restrict_empty (f : α →ₛ β) : restrict f ∅ = 0 := by simp [restrict] theorem map_restrict_of_zero [has_zero γ] {g : β → γ} (hg : g 0 = 0) (f : α →ₛ β) (s : set α) : (f.restrict s).map g = (f.map g).restrict s := ext $ λ x, if hs : is_measurable s then by simp [hs, set.indicator_comp_of_zero hg] else by simp [restrict_of_not_measurable hs, hg] theorem map_coe_ennreal_restrict (f : α →ₛ nnreal) (s : set α) : (f.restrict s).map (coe : nnreal → ennreal) = (f.map coe).restrict s := map_restrict_of_zero ennreal.coe_zero _ _ theorem map_coe_nnreal_restrict (f : α →ₛ nnreal) (s : set α) : (f.restrict s).map (coe : nnreal → ℝ) = (f.map coe).restrict s := map_restrict_of_zero nnreal.coe_zero _ _ theorem restrict_apply (f : α →ₛ β) {s : set α} (hs : is_measurable s) (a) : restrict f s a = if a ∈ s then f a else 0 := by simp only [hs, coe_restrict] theorem restrict_preimage (f : α →ₛ β) {s : set α} (hs : is_measurable s) {t : set β} (ht : (0:β) ∉ t) : restrict f s ⁻¹' t = s ∩ f ⁻¹' t := by simp [hs, indicator_preimage_of_not_mem _ _ ht] theorem restrict_preimage_singleton (f : α →ₛ β) {s : set α} (hs : is_measurable s) {r : β} (hr : r ≠ 0) : restrict f s ⁻¹' {r} = s ∩ f ⁻¹' {r} := f.restrict_preimage hs hr.symm lemma mem_restrict_range {r : β} {s : set α} {f : α →ₛ β} (hs : is_measurable s) : r ∈ (restrict f s).range ↔ (r = 0 ∧ s ≠ univ) ∨ (r ∈ f '' s) := by rw [← finset.mem_coe, coe_range, coe_restrict _ hs, mem_range_indicator] lemma mem_image_of_mem_range_restrict {r : β} {s : set α} {f : α →ₛ β} (hr : r ∈ (restrict f s).range) (h0 : r ≠ 0) : r ∈ f '' s := if hs : is_measurable s then by simpa [mem_restrict_range hs, h0] using hr else by { rw [restrict_of_not_measurable hs] at hr, exact (h0 $ eq_zero_of_mem_range_zero hr).elim } @[mono] lemma restrict_mono [preorder β] (s : set α) {f g : α →ₛ β} (H : f ≤ g) : f.restrict s ≤ g.restrict s := if hs : is_measurable s then λ x, by simp only [coe_restrict _ hs, indicator_le_indicator (H x)] else by simp only [restrict_of_not_measurable hs, le_refl] end restrict section approx section variables [semilattice_sup_bot β] [has_zero β] /-- Fix a sequence `i : ℕ → β`. Given a function `α → β`, its `n`-th approximation by simple functions is defined so that in case `β = ennreal` it sends each `a` to the supremum of the set `{i k | k ≤ n ∧ i k ≤ f a}`, see `approx_apply` and `supr_approx_apply` for details. -/ def approx (i : ℕ → β) (f : α → β) (n : ℕ) : α →ₛ β := (finset.range n).sup (λk, restrict (const α (i k)) {a:α | i k ≤ f a}) lemma approx_apply [topological_space β] [order_closed_topology β] [measurable_space β] [opens_measurable_space β] {i : ℕ → β} {f : α → β} {n : ℕ} (a : α) (hf : measurable f) : (approx i f n : α →ₛ β) a = (finset.range n).sup (λk, if i k ≤ f a then i k else 0) := begin dsimp only [approx], rw [finset_sup_apply], congr, funext k, rw [restrict_apply], refl, exact (hf is_measurable_Ici) end lemma monotone_approx (i : ℕ → β) (f : α → β) : monotone (approx i f) := assume n m h, finset.sup_mono $ finset.range_subset.2 h lemma approx_comp [topological_space β] [order_closed_topology β] [measurable_space β] [opens_measurable_space β] [measurable_space γ] {i : ℕ → β} {f : γ → β} {g : α → γ} {n : ℕ} (a : α) (hf : measurable f) (hg : measurable g) : (approx i (f ∘ g) n : α →ₛ β) a = (approx i f n : γ →ₛ β) (g a) := by rw [approx_apply _ hf, approx_apply _ (hf.comp hg)] end lemma supr_approx_apply [topological_space β] [complete_lattice β] [order_closed_topology β] [has_zero β] [measurable_space β] [opens_measurable_space β] (i : ℕ → β) (f : α → β) (a : α) (hf : measurable f) (h_zero : (0 : β) = ⊥) : (⨆n, (approx i f n : α →ₛ β) a) = (⨆k (h : i k ≤ f a), i k) := begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume k, supr_le $ assume hk, _), { rw [approx_apply a hf, h_zero], refine finset.sup_le (assume k hk, _), split_ifs, exact le_supr_of_le k (le_supr _ h), exact bot_le }, { refine le_supr_of_le (k+1) _, rw [approx_apply a hf], have : k ∈ finset.range (k+1) := finset.mem_range.2 (nat.lt_succ_self _), refine le_trans (le_of_eq _) (finset.le_sup this), rw [if_pos hk] } end end approx section eapprox /-- A sequence of `ennreal`s such that its range is the set of non-negative rational numbers. -/ def ennreal_rat_embed (n : ℕ) : ennreal := ennreal.of_real ((encodable.decode ℚ n).get_or_else (0 : ℚ)) lemma ennreal_rat_embed_encode (q : ℚ) : ennreal_rat_embed (encodable.encode q) = nnreal.of_real q := by rw [ennreal_rat_embed, encodable.encodek]; refl /-- Approximate a function `α → ennreal` by a sequence of simple functions. -/ def eapprox : (α → ennreal) → ℕ → α →ₛ ennreal := approx ennreal_rat_embed lemma monotone_eapprox (f : α → ennreal) : monotone (eapprox f) := monotone_approx _ f lemma supr_eapprox_apply (f : α → ennreal) (hf : measurable f) (a : α) : (⨆n, (eapprox f n : α →ₛ ennreal) a) = f a := begin rw [eapprox, supr_approx_apply ennreal_rat_embed f a hf rfl], refine le_antisymm (supr_le $ assume i, supr_le $ assume hi, hi) (le_of_not_gt _), assume h, rcases ennreal.lt_iff_exists_rat_btwn.1 h with ⟨q, hq, lt_q, q_lt⟩, have : (nnreal.of_real q : ennreal) ≤ (⨆ (k : ℕ) (h : ennreal_rat_embed k ≤ f a), ennreal_rat_embed k), { refine le_supr_of_le (encodable.encode q) _, rw [ennreal_rat_embed_encode q], refine le_supr_of_le (le_of_lt q_lt) _, exact le_refl _ }, exact lt_irrefl _ (lt_of_le_of_lt this lt_q) end lemma eapprox_comp [measurable_space γ] {f : γ → ennreal} {g : α → γ} {n : ℕ} (hf : measurable f) (hg : measurable g) : (eapprox (f ∘ g) n : α → ennreal) = (eapprox f n : γ →ₛ ennreal) ∘ g := funext $ assume a, approx_comp a hf hg end eapprox end measurable section measure variables [measurable_space α] {μ : measure α} /-- Integral of a simple function whose codomain is `ennreal`. -/ def lintegral (f : α →ₛ ennreal) (μ : measure α) : ennreal := ∑ x in f.range, x * μ (f ⁻¹' {x}) lemma lintegral_eq_of_subset (f : α →ₛ ennreal) {s : finset ennreal} (hs : ∀ x, f x ≠ 0 → μ (f ⁻¹' {f x}) ≠ 0 → f x ∈ s) : f.lintegral μ = ∑ x in s, x * μ (f ⁻¹' {x}) := begin refine finset.sum_bij_ne_zero (λr _ _, r) _ _ _ _, { simpa only [forall_range_iff, mul_ne_zero_iff, and_imp] }, { intros, assumption }, { intros b _ hb, refine ⟨b, _, hb, rfl⟩, rw [mem_range, ← preimage_singleton_nonempty], exact nonempty_of_measure_ne_zero (mul_ne_zero_iff.1 hb).2 }, { intros, refl } end /-- Calculate the integral of `(g ∘ f)`, where `g : β → ennreal` and `f : α →ₛ β`. -/ lemma map_lintegral (g : β → ennreal) (f : α →ₛ β) : (f.map g).lintegral μ = ∑ x in f.range, g x * μ (f ⁻¹' {x}) := begin simp only [lintegral, range_map], refine finset.sum_image' _ (assume b hb, _), rcases mem_range.1 hb with ⟨a, rfl⟩, rw [map_preimage_singleton, ← sum_measure_preimage_singleton _ (λ _ _, f.is_measurable_preimage _), finset.mul_sum], refine finset.sum_congr _ _, { congr }, { assume x, simp only [finset.mem_filter], rintro ⟨_, h⟩, rw h }, end lemma add_lintegral (f g : α →ₛ ennreal) : (f + g).lintegral μ = f.lintegral μ + g.lintegral μ := calc (f + g).lintegral μ = ∑ x in (pair f g).range, (x.1 * μ (pair f g ⁻¹' {x}) + x.2 * μ (pair f g ⁻¹' {x})) : by rw [add_eq_map₂, map_lintegral]; exact finset.sum_congr rfl (assume a ha, add_mul _ _ _) ... = ∑ x in (pair f g).range, x.1 * μ (pair f g ⁻¹' {x}) + ∑ x in (pair f g).range, x.2 * μ (pair f g ⁻¹' {x}) : by rw [finset.sum_add_distrib] ... = ((pair f g).map prod.fst).lintegral μ + ((pair f g).map prod.snd).lintegral μ : by rw [map_lintegral, map_lintegral] ... = lintegral f μ + lintegral g μ : rfl lemma const_mul_lintegral (f : α →ₛ ennreal) (x : ennreal) : (const α x * f).lintegral μ = x * f.lintegral μ := calc (f.map (λa, x * a)).lintegral μ = ∑ r in f.range, x * r * μ (f ⁻¹' {r}) : map_lintegral _ _ ... = ∑ r in f.range, x * (r * μ (f ⁻¹' {r})) : finset.sum_congr rfl (assume a ha, mul_assoc _ _ _) ... = x * f.lintegral μ : finset.mul_sum.symm /-- Integral of a simple function `α →ₛ ennreal` as a bilinear map. -/ def lintegralₗ : (α →ₛ ennreal) →ₗ[ennreal] measure α →ₗ[ennreal] ennreal := { to_fun := λ f, { to_fun := lintegral f, map_add' := by simp [lintegral, mul_add, finset.sum_add_distrib], map_smul' := λ c μ, by simp [lintegral, mul_left_comm _ c, finset.mul_sum] }, map_add' := λ f g, linear_map.ext (λ μ, add_lintegral f g), map_smul' := λ c f, linear_map.ext (λ μ, const_mul_lintegral f c) } @[simp] lemma zero_lintegral : (0 : α →ₛ ennreal).lintegral μ = 0 := linear_map.ext_iff.1 lintegralₗ.map_zero μ lemma lintegral_add {ν} (f : α →ₛ ennreal) : f.lintegral (μ + ν) = f.lintegral μ + f.lintegral ν := (lintegralₗ f).map_add μ ν lemma lintegral_smul (f : α →ₛ ennreal) (c : ennreal) : f.lintegral (c • μ) = c • f.lintegral μ := (lintegralₗ f).map_smul c μ @[simp] lemma lintegral_zero (f : α →ₛ ennreal) : f.lintegral 0 = 0 := (lintegralₗ f).map_zero lemma lintegral_sum {ι} (f : α →ₛ ennreal) (μ : ι → measure α) : f.lintegral (measure.sum μ) = ∑' i, f.lintegral (μ i) := begin simp only [lintegral, measure.sum_apply, f.is_measurable_preimage, ← finset.tsum_subtype, ← ennreal.tsum_mul_left], apply ennreal.tsum_comm end lemma restrict_lintegral (f : α →ₛ ennreal) {s : set α} (hs : is_measurable s) : (restrict f s).lintegral μ = ∑ r in f.range, r * μ (f ⁻¹' {r} ∩ s) := calc (restrict f s).lintegral μ = ∑ r in f.range, r * μ (restrict f s ⁻¹' {r}) : lintegral_eq_of_subset _ $ λ x hx, if hxs : x ∈ s then by simp [f.restrict_apply hs, if_pos hxs, mem_range_self] else false.elim $ hx $ by simp [*] ... = ∑ r in f.range, r * μ (f ⁻¹' {r} ∩ s) : finset.sum_congr rfl $ forall_range_iff.2 $ λ b, if hb : f b = 0 then by simp only [hb, zero_mul] else by rw [restrict_preimage_singleton _ hs hb, inter_comm] lemma lintegral_restrict (f : α →ₛ ennreal) (s : set α) (μ : measure α) : f.lintegral (μ.restrict s) = ∑ y in f.range, y * μ (f ⁻¹' {y} ∩ s) := by simp only [lintegral, measure.restrict_apply, f.is_measurable_preimage] lemma restrict_lintegral_eq_lintegral_restrict (f : α →ₛ ennreal) {s : set α} (hs : is_measurable s) : (restrict f s).lintegral μ = f.lintegral (μ.restrict s) := by rw [f.restrict_lintegral hs, lintegral_restrict] lemma const_lintegral (c : ennreal) : (const α c).lintegral μ = c * μ univ := begin rw [lintegral], by_cases ha : nonempty α, { resetI, simp [preimage_const_of_mem] }, { simp [μ.eq_zero_of_not_nonempty ha] } end lemma const_lintegral_restrict (c : ennreal) (s : set α) : (const α c).lintegral (μ.restrict s) = c * μ s := by rw [const_lintegral, measure.restrict_apply is_measurable.univ, univ_inter] lemma restrict_const_lintegral (c : ennreal) {s : set α} (hs : is_measurable s) : ((const α c).restrict s).lintegral μ = c * μ s := by rw [restrict_lintegral_eq_lintegral_restrict _ hs, const_lintegral_restrict] lemma le_sup_lintegral (f g : α →ₛ ennreal) : f.lintegral μ ⊔ g.lintegral μ ≤ (f ⊔ g).lintegral μ := calc f.lintegral μ ⊔ g.lintegral μ = ((pair f g).map prod.fst).lintegral μ ⊔ ((pair f g).map prod.snd).lintegral μ : rfl ... ≤ ∑ x in (pair f g).range, (x.1 ⊔ x.2) * μ (pair f g ⁻¹' {x}) : begin rw [map_lintegral, map_lintegral], refine sup_le _ _; refine finset.sum_le_sum (λ a _, canonically_ordered_semiring.mul_le_mul _ (le_refl _)), exact le_sup_left, exact le_sup_right end ... = (f ⊔ g).lintegral μ : by rw [sup_eq_map₂, map_lintegral] /-- `simple_func.lintegral` is monotone both in function and in measure. -/ @[mono] lemma lintegral_mono {f g : α →ₛ ennreal} (hfg : f ≤ g) {μ ν : measure α} (hμν : μ ≤ ν) : f.lintegral μ ≤ g.lintegral ν := calc f.lintegral μ ≤ f.lintegral μ ⊔ g.lintegral μ : le_sup_left ... ≤ (f ⊔ g).lintegral μ : le_sup_lintegral _ _ ... = g.lintegral μ : by rw [sup_of_le_right hfg] ... ≤ g.lintegral ν : finset.sum_le_sum $ λ y hy, ennreal.mul_left_mono $ hμν _ (g.is_measurable_preimage _) /-- `simple_func.lintegral` depends only on the measures of `f ⁻¹' {y}`. -/ lemma lintegral_eq_of_measure_preimage [measurable_space β] {f : α →ₛ ennreal} {g : β →ₛ ennreal} {ν : measure β} (H : ∀ y, μ (f ⁻¹' {y}) = ν (g ⁻¹' {y})) : f.lintegral μ = g.lintegral ν := begin simp only [lintegral, ← H], apply lintegral_eq_of_subset, simp only [H], intros, exact mem_range_of_measure_ne_zero ‹_› end /-- If two simple functions are equal a.e., then their `lintegral`s are equal. -/ lemma lintegral_congr {f g : α →ₛ ennreal} (h : f =ᵐ[μ] g) : f.lintegral μ = g.lintegral μ := lintegral_eq_of_measure_preimage $ λ y, measure_congr $ eventually.set_eq $ h.mono $ λ x hx, by simp [hx] lemma lintegral_map {β} [measurable_space β] {μ' : measure β} (f : α →ₛ ennreal) (g : β →ₛ ennreal) (m : α → β) (eq : ∀a:α, f a = g (m a)) (h : ∀s:set β, is_measurable s → μ' s = μ (m ⁻¹' s)) : f.lintegral μ = g.lintegral μ' := lintegral_eq_of_measure_preimage $ λ y, by { simp only [preimage, eq], exact (h (g ⁻¹' {y}) (g.is_measurable_preimage _)).symm } end measure section fin_meas_supp variables [measurable_space α] [has_zero β] [has_zero γ] {μ : measure α} open finset ennreal function lemma support_eq (f : α →ₛ β) : support f = ⋃ y ∈ f.range.filter (λ y, y ≠ 0), f ⁻¹' {y} := set.ext $ λ x, by simp only [finset.bUnion_preimage_singleton, mem_support, set.mem_preimage, finset.mem_coe, mem_filter, mem_range_self, true_and] /-- A `simple_func` has finite measure support if it is equal to `0` outside of a set of finite measure. -/ protected def fin_meas_supp (f : α →ₛ β) (μ : measure α) : Prop := f =ᶠ[μ.cofinite] 0 lemma fin_meas_supp_iff_support {f : α →ₛ β} {μ : measure α} : f.fin_meas_supp μ ↔ μ (support f) < ⊤ := iff.rfl lemma fin_meas_supp_iff {f : α →ₛ β} {μ : measure α} : f.fin_meas_supp μ ↔ ∀ y ≠ 0, μ (f ⁻¹' {y}) < ⊤ := begin split, { refine λ h y hy, lt_of_le_of_lt (measure_mono _) h, exact λ x hx (H : f x = 0), hy $ H ▸ eq.symm hx }, { intro H, rw [fin_meas_supp_iff_support, support_eq], refine lt_of_le_of_lt (measure_bUnion_finset_le _ _) (sum_lt_top _), exact λ y hy, H y (finset.mem_filter.1 hy).2 } end namespace fin_meas_supp lemma meas_preimage_singleton_ne_zero {f : α →ₛ β} (h : f.fin_meas_supp μ) {y : β} (hy : y ≠ 0) : μ (f ⁻¹' {y}) < ⊤ := fin_meas_supp_iff.1 h y hy protected lemma map {f : α →ₛ β} {g : β → γ} (hf : f.fin_meas_supp μ) (hg : g 0 = 0) : (f.map g).fin_meas_supp μ := flip lt_of_le_of_lt hf (measure_mono $ support_comp_subset hg f) lemma of_map {f : α →ₛ β} {g : β → γ} (h : (f.map g).fin_meas_supp μ) (hg : ∀b, g b = 0 → b = 0) : f.fin_meas_supp μ := flip lt_of_le_of_lt h $ measure_mono $ support_subset_comp hg _ lemma map_iff {f : α →ₛ β} {g : β → γ} (hg : ∀ {b}, g b = 0 ↔ b = 0) : (f.map g).fin_meas_supp μ ↔ f.fin_meas_supp μ := ⟨λ h, h.of_map $ λ b, hg.1, λ h, h.map $ hg.2 rfl⟩ protected lemma pair {f : α →ₛ β} {g : α →ₛ γ} (hf : f.fin_meas_supp μ) (hg : g.fin_meas_supp μ) : (pair f g).fin_meas_supp μ := calc μ (support $ pair f g) = μ (support f ∪ support g) : congr_arg μ $ support_prod_mk f g ... ≤ μ (support f) + μ (support g) : measure_union_le _ _ ... < _ : add_lt_top.2 ⟨hf, hg⟩ protected lemma map₂ [has_zero δ] {μ : measure α} {f : α →ₛ β} (hf : f.fin_meas_supp μ) {g : α →ₛ γ} (hg : g.fin_meas_supp μ) {op : β → γ → δ} (H : op 0 0 = 0) : ((pair f g).map (function.uncurry op)).fin_meas_supp μ := (hf.pair hg).map H protected lemma add {β} [add_monoid β] {f g : α →ₛ β} (hf : f.fin_meas_supp μ) (hg : g.fin_meas_supp μ) : (f + g).fin_meas_supp μ := by { rw [add_eq_map₂], exact hf.map₂ hg (zero_add 0) } protected lemma mul {β} [monoid_with_zero β] {f g : α →ₛ β} (hf : f.fin_meas_supp μ) (hg : g.fin_meas_supp μ) : (f * g).fin_meas_supp μ := by { rw [mul_eq_map₂], exact hf.map₂ hg (zero_mul 0) } lemma lintegral_lt_top {f : α →ₛ ennreal} (hm : f.fin_meas_supp μ) (hf : ∀ᵐ a ∂μ, f a < ⊤) : f.lintegral μ < ⊤ := begin refine sum_lt_top (λ a ha, _), rcases eq_or_lt_of_le (le_top : a ≤ ⊤) with rfl|ha, { simp only [ae_iff, lt_top_iff_ne_top, ne.def, not_not] at hf, simp [set.preimage, hf] }, { by_cases ha0 : a = 0, { subst a, rwa [zero_mul] }, { exact mul_lt_top ha (fin_meas_supp_iff.1 hm _ ha0) } } end lemma of_lintegral_lt_top {f : α →ₛ ennreal} (h : f.lintegral μ < ⊤) : f.fin_meas_supp μ := begin refine fin_meas_supp_iff.2 (λ b hb, _), rw [lintegral, sum_lt_top_iff] at h, by_cases b_mem : b ∈ f.range, { rw ennreal.lt_top_iff_ne_top, have h : ¬ _ = ⊤ := ennreal.lt_top_iff_ne_top.1 (h b b_mem), simp only [mul_eq_top, not_or_distrib, not_and_distrib] at h, rcases h with ⟨h, h'⟩, refine or.elim h (λh, by contradiction) (λh, h) }, { rw ← preimage_eq_empty_iff at b_mem, rw [b_mem, measure_empty], exact with_top.zero_lt_top } end lemma iff_lintegral_lt_top {f : α →ₛ ennreal} (hf : ∀ᵐ a ∂μ, f a < ⊤) : f.fin_meas_supp μ ↔ f.lintegral μ < ⊤ := ⟨λ h, h.lintegral_lt_top hf, λ h, of_lintegral_lt_top h⟩ end fin_meas_supp end fin_meas_supp /-- To prove something for an arbitrary simple function, it suffices to show that the property holds for (multiples of) characteristic functions and is closed under addition (of functions with disjoint support). It is possible to make the hypotheses in `h_sum` a bit stronger, and such conditions can be added once we need them (for example it is only necessary to consider the case where `g` is a multiple of a characteristic function, and that this multiple doesn't appear in the image of `f`) -/ @[elab_as_eliminator] protected lemma induction {α γ} [measurable_space α] [add_monoid γ] {P : simple_func α γ → Prop} (h_ind : ∀ c {s} (hs : is_measurable s), P (simple_func.piecewise s hs (simple_func.const _ c) (simple_func.const _ 0))) (h_sum : ∀ ⦃f g : simple_func α γ⦄, set.univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0} → P f → P g → P (f + g)) (f : simple_func α γ) : P f := begin generalize' h : f.range \ {0} = s, rw [← finset.coe_inj, finset.coe_sdiff, finset.coe_singleton, simple_func.coe_range] at h, revert s f h, refine finset.induction _ _, { intros f hf, rw [finset.coe_empty, diff_eq_empty, range_subset_singleton] at hf, convert h_ind 0 is_measurable.univ, ext x, simp [hf] }, { intros x s hxs ih f hf, have mx := f.is_measurable_preimage {x}, let g := simple_func.piecewise (f ⁻¹' {x}) mx 0 f, have Pg : P g, { apply ih, simp only [g, simple_func.coe_piecewise, range_piecewise], rw [image_compl_preimage, union_diff_distrib, diff_diff_comm, hf, finset.coe_insert, insert_diff_self_of_not_mem, diff_eq_empty.mpr, set.empty_union], { rw [set.image_subset_iff], convert set.subset_univ _, exact preimage_const_of_mem (mem_singleton _) }, { rwa [finset.mem_coe] }}, convert h_sum _ Pg (h_ind x mx), { ext1 y, by_cases hy : y ∈ f ⁻¹' {x}; [simpa [hy], simp [hy]] }, { rintro y -, by_cases hy : y ∈ f ⁻¹' {x}; simp [hy] } } end end simple_func section lintegral open simple_func variables [measurable_space α] {μ : measure α} /-- The lower Lebesgue integral of a function `f` with respect to a measure `μ`. -/ def lintegral (μ : measure α) (f : α → ennreal) : ennreal := ⨆ (g : α →ₛ ennreal) (hf : ⇑g ≤ f), g.lintegral μ notation `∫⁻` binders `, ` r:(scoped:60 f, f) ` ∂` μ:70 := lintegral μ r notation `∫⁻` binders `, ` r:(scoped:60 f, lintegral volume f) := r notation `∫⁻` binders ` in ` s `, ` r:(scoped:60 f, f) ` ∂` μ:70 := lintegral (measure.restrict μ s) r notation `∫⁻` binders ` in ` s `, ` r:(scoped:60 f, lintegral (measure.restrict volume s) f) := r theorem simple_func.lintegral_eq_lintegral (f : α →ₛ ennreal) (μ : measure α) : ∫⁻ a, f a ∂ μ = f.lintegral μ := le_antisymm (bsupr_le $ λ g hg, lintegral_mono hg $ le_refl _) (le_supr_of_le f $ le_supr_of_le (le_refl _) (le_refl _)) @[mono] lemma lintegral_mono' ⦃μ ν : measure α⦄ (hμν : μ ≤ ν) ⦃f g : α → ennreal⦄ (hfg : f ≤ g) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂ν := supr_le_supr $ λ φ, supr_le_supr2 $ λ hφ, ⟨le_trans hφ hfg, lintegral_mono (le_refl φ) hμν⟩ lemma lintegral_mono ⦃f g : α → ennreal⦄ (hfg : f ≤ g) : ∫⁻ a, f a ∂μ ≤ ∫⁻ a, g a ∂μ := lintegral_mono' (le_refl μ) hfg lemma monotone_lintegral (μ : measure α) : monotone (lintegral μ) := lintegral_mono @[simp] lemma lintegral_const (c : ennreal) : ∫⁻ a, c ∂μ = c * μ univ := by rw [← simple_func.const_lintegral, ← simple_func.lintegral_eq_lintegral, simple_func.coe_const] lemma set_lintegral_one (s) : ∫⁻ a in s, 1 ∂μ = μ s := by rw [lintegral_const, one_mul, measure.restrict_apply_univ] /-- `∫⁻ a in s, f a ∂μ` is defined as the supremum of integrals of simple functions `φ : α →ₛ ennreal` such that `φ ≤ f`. This lemma says that it suffices to take functions `φ : α →ₛ ℝ≥0`. -/ lemma lintegral_eq_nnreal (f : α → ennreal) (μ : measure α) : (∫⁻ a, f a ∂μ) = (⨆ (φ : α →ₛ ℝ≥0) (hf : ∀ x, ↑(φ x) ≤ f x), (φ.map (coe : nnreal → ennreal)).lintegral μ) := begin refine le_antisymm (bsupr_le $ assume φ hφ, _) (supr_le_supr2 $ λ φ, ⟨φ.map (coe : ℝ≥0 → ennreal), le_refl _⟩), by_cases h : ∀ᵐ a ∂μ, φ a ≠ ⊤, { let ψ := φ.map ennreal.to_nnreal, replace h : ψ.map (coe : ℝ≥0 → ennreal) =ᵐ[μ] φ := h.mono (λ a, ennreal.coe_to_nnreal), have : ∀ x, ↑(ψ x) ≤ f x := λ x, le_trans ennreal.coe_to_nnreal_le_self (hφ x), exact le_supr_of_le (φ.map ennreal.to_nnreal) (le_supr_of_le this (ge_of_eq $ lintegral_congr h)) }, { have h_meas : μ (φ ⁻¹' {⊤}) ≠ 0, from mt measure_zero_iff_ae_nmem.1 h, refine le_trans le_top (ge_of_eq $ (supr_eq_top _).2 $ λ b hb, _), obtain ⟨n, hn⟩ : ∃ n : ℕ, b < n * μ (φ ⁻¹' {⊤}), from exists_nat_mul_gt h_meas (ne_of_lt hb), use (const α (n : ℝ≥0)).restrict (φ ⁻¹' {⊤}), simp only [lt_supr_iff, exists_prop, coe_restrict, φ.is_measurable_preimage, coe_const, ennreal.coe_indicator, map_coe_ennreal_restrict, map_const, ennreal.coe_nat, restrict_const_lintegral], refine ⟨indicator_le (λ x hx, le_trans _ (hφ _)), hn⟩, simp only [mem_preimage, mem_singleton_iff] at hx, simp only [hx, le_top] } end theorem supr_lintegral_le {ι : Sort*} (f : ι → α → ennreal) : (⨆i, ∫⁻ a, f i a ∂μ) ≤ (∫⁻ a, ⨆i, f i a ∂μ) := begin simp only [← supr_apply], exact (monotone_lintegral μ).le_map_supr end theorem supr2_lintegral_le {ι : Sort*} {ι' : ι → Sort*} (f : Π i, ι' i → α → ennreal) : (⨆i (h : ι' i), ∫⁻ a, f i h a ∂μ) ≤ (∫⁻ a, ⨆i (h : ι' i), f i h a ∂μ) := by { convert (monotone_lintegral μ).le_map_supr2 f, ext1 a, simp only [supr_apply] } theorem le_infi_lintegral {ι : Sort*} (f : ι → α → ennreal) : (∫⁻ a, ⨅i, f i a ∂μ) ≤ (⨅i, ∫⁻ a, f i a ∂μ) := by { simp only [← infi_apply], exact (monotone_lintegral μ).map_infi_le } theorem le_infi2_lintegral {ι : Sort*} {ι' : ι → Sort*} (f : Π i, ι' i → α → ennreal) : (∫⁻ a, ⨅ i (h : ι' i), f i h a ∂μ) ≤ (⨅ i (h : ι' i), ∫⁻ a, f i h a ∂μ) := by { convert (monotone_lintegral μ).map_infi2_le f, ext1 a, simp only [infi_apply] } /-- Monotone convergence theorem -- sometimes called Beppo-Levi convergence. See `lintegral_supr_directed` for a more general form. -/ theorem lintegral_supr {f : ℕ → α → ennreal} (hf : ∀n, measurable (f n)) (h_mono : monotone f) : (∫⁻ a, ⨆n, f n a ∂μ) = (⨆n, ∫⁻ a, f n a ∂μ) := begin set c : nnreal → ennreal := coe, set F := λ a:α, ⨆n, f n a, have hF : measurable F := measurable_supr hf, refine le_antisymm _ (supr_lintegral_le _), rw [lintegral_eq_nnreal], refine supr_le (assume s, supr_le (assume hsf, _)), refine ennreal.le_of_forall_lt_one_mul_lt (assume a ha, _), rcases ennreal.lt_iff_exists_coe.1 ha with ⟨r, rfl, ha⟩, have ha : r < 1 := ennreal.coe_lt_coe.1 ha, let rs := s.map (λa, r * a), have eq_rs : (const α r : α →ₛ ennreal) * map c s = rs.map c, { ext1 a, exact ennreal.coe_mul.symm }, have eq : ∀p, (rs.map c) ⁻¹' {p} = (⋃n, (rs.map c) ⁻¹' {p} ∩ {a | p ≤ f n a}), { assume p, rw [← inter_Union, ← inter_univ ((map c rs) ⁻¹' {p})] {occs := occurrences.pos [1]}, refine set.ext (assume x, and_congr_right $ assume hx, (true_iff _).2 _), by_cases p_eq : p = 0, { simp [p_eq] }, simp at hx, subst hx, have : r * s x ≠ 0, { rwa [(≠), ← ennreal.coe_eq_zero] }, have : s x ≠ 0, { refine mt _ this, assume h, rw [h, mul_zero] }, have : (rs.map c) x < ⨆ (n : ℕ), f n x, { refine lt_of_lt_of_le (ennreal.coe_lt_coe.2 (_)) (hsf x), suffices : r * s x < 1 * s x, simpa [rs], exact mul_lt_mul_of_pos_right ha (zero_lt_iff_ne_zero.2 this) }, rcases lt_supr_iff.1 this with ⟨i, hi⟩, exact mem_Union.2 ⟨i, le_of_lt hi⟩ }, have mono : ∀r:ennreal, monotone (λn, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}), { assume r i j h, refine inter_subset_inter (subset.refl _) _, assume x hx, exact le_trans hx (h_mono h x) }, have h_meas : ∀n, is_measurable {a : α | ⇑(map c rs) a ≤ f n a} := assume n, is_measurable_le (simple_func.measurable _) (hf n), calc (r:ennreal) * (s.map c).lintegral μ = ∑ r in (rs.map c).range, r * μ ((rs.map c) ⁻¹' {r}) : by rw [← const_mul_lintegral, eq_rs, simple_func.lintegral] ... ≤ ∑ r in (rs.map c).range, r * μ (⋃n, (rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}) : le_of_eq (finset.sum_congr rfl $ assume x hx, by rw ← eq) ... ≤ ∑ r in (rs.map c).range, (⨆n, r * μ ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a})) : le_of_eq (finset.sum_congr rfl $ assume x hx, begin rw [measure_Union_eq_supr _ (directed_of_sup $ mono x), ennreal.mul_supr], { assume i, refine ((rs.map c).is_measurable_preimage _).inter _, exact hf i is_measurable_Ici } end) ... ≤ ⨆n, ∑ r in (rs.map c).range, r * μ ((rs.map c) ⁻¹' {r} ∩ {a | r ≤ f n a}) : begin refine le_of_eq _, rw [ennreal.finset_sum_supr_nat], assume p i j h, exact canonically_ordered_semiring.mul_le_mul (le_refl _) (measure_mono $ mono p h) end ... ≤ (⨆n:ℕ, ((rs.map c).restrict {a | (rs.map c) a ≤ f n a}).lintegral μ) : begin refine supr_le_supr (assume n, _), rw [restrict_lintegral _ (h_meas n)], { refine le_of_eq (finset.sum_congr rfl $ assume r hr, _), congr' 2 with a, refine and_congr_right _, simp {contextual := tt} } end ... ≤ (⨆n, ∫⁻ a, f n a ∂μ) : begin refine supr_le_supr (assume n, _), rw [← simple_func.lintegral_eq_lintegral], refine lintegral_mono (assume a, _), dsimp, rw [restrict_apply], split_ifs; simp, simpa using h, exact h_meas n end end lemma lintegral_eq_supr_eapprox_lintegral {f : α → ennreal} (hf : measurable f) : (∫⁻ a, f a ∂μ) = (⨆n, (eapprox f n).lintegral μ) := calc (∫⁻ a, f a ∂μ) = (∫⁻ a, ⨆n, (eapprox f n : α → ennreal) a ∂μ) : by congr; ext a; rw [supr_eapprox_apply f hf] ... = (⨆n, ∫⁻ a, (eapprox f n : α → ennreal) a ∂μ) : begin rw [lintegral_supr], { assume n, exact (eapprox f n).measurable }, { assume i j h, exact (monotone_eapprox f h) } end ... = (⨆n, (eapprox f n).lintegral μ) : by congr; ext n; rw [(eapprox f n).lintegral_eq_lintegral] lemma lintegral_add {f g : α → ennreal} (hf : measurable f) (hg : measurable g) : (∫⁻ a, f a + g a ∂μ) = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) := calc (∫⁻ a, f a + g a ∂μ) = (∫⁻ a, (⨆n, (eapprox f n : α → ennreal) a) + (⨆n, (eapprox g n : α → ennreal) a) ∂μ) : by congr; funext a; rw [supr_eapprox_apply f hf, supr_eapprox_apply g hg] ... = (∫⁻ a, (⨆n, (eapprox f n + eapprox g n : α → ennreal) a) ∂μ) : begin congr, funext a, rw [ennreal.supr_add_supr_of_monotone], { refl }, { assume i j h, exact monotone_eapprox _ h a }, { assume i j h, exact monotone_eapprox _ h a }, end ... = (⨆n, (eapprox f n).lintegral μ + (eapprox g n).lintegral μ) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.add_lintegral, ← simple_func.lintegral_eq_lintegral], refl }, { assume n, exact measurable.add (eapprox f n).measurable (eapprox g n).measurable }, { assume i j h a, exact add_le_add (monotone_eapprox _ h _) (monotone_eapprox _ h _) } end ... = (⨆n, (eapprox f n).lintegral μ) + (⨆n, (eapprox g n).lintegral μ) : by refine (ennreal.supr_add_supr_of_monotone _ _).symm; { assume i j h, exact simple_func.lintegral_mono (monotone_eapprox _ h) (le_refl μ) } ... = (∫⁻ a, f a ∂μ) + (∫⁻ a, g a ∂μ) : by rw [lintegral_eq_supr_eapprox_lintegral hf, lintegral_eq_supr_eapprox_lintegral hg] lemma lintegral_zero : (∫⁻ a:α, 0 ∂μ) = 0 := by simp lemma lintegral_smul_measure (c : ennreal) (f : α → ennreal) : ∫⁻ a, f a ∂ (c • μ) = c * ∫⁻ a, f a ∂μ := by simp only [lintegral, supr_subtype', simple_func.lintegral_smul, ennreal.mul_supr, smul_eq_mul] lemma lintegral_sum_measure {ι} (f : α → ennreal) (μ : ι → measure α) : ∫⁻ a, f a ∂(measure.sum μ) = ∑' i, ∫⁻ a, f a ∂(μ i) := begin simp only [lintegral, supr_subtype', simple_func.lintegral_sum, ennreal.tsum_eq_supr_sum], rw [supr_comm], congr, funext s, induction s using finset.induction_on with i s hi hs, { apply bot_unique, simp }, simp only [finset.sum_insert hi, ← hs], refine (ennreal.supr_add_supr _).symm, intros φ ψ, exact ⟨⟨φ ⊔ ψ, λ x, sup_le (φ.2 x) (ψ.2 x)⟩, add_le_add (simple_func.lintegral_mono le_sup_left (le_refl _)) (finset.sum_le_sum $ λ j hj, simple_func.lintegral_mono le_sup_right (le_refl _))⟩ end lemma lintegral_add_measure (f : α → ennreal) (μ ν : measure α) : ∫⁻ a, f a ∂ (μ + ν) = ∫⁻ a, f a ∂μ + ∫⁻ a, f a ∂ν := by simpa [tsum_fintype] using lintegral_sum_measure f (λ b, cond b μ ν) @[simp] lemma lintegral_zero_measure (f : α → ennreal) : ∫⁻ a, f a ∂0 = 0 := bot_unique $ by simp [lintegral] lemma lintegral_finset_sum (s : finset β) {f : β → α → ennreal} (hf : ∀b, measurable (f b)) : (∫⁻ a, ∑ b in s, f b a ∂μ) = ∑ b in s, ∫⁻ a, f b a ∂μ := begin refine finset.induction_on s _ _, { simp }, { assume a s has ih, simp only [finset.sum_insert has], rw [lintegral_add (hf _) (s.measurable_sum hf), ih] } end lemma lintegral_const_mul (r : ennreal) {f : α → ennreal} (hf : measurable f) : (∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) := calc (∫⁻ a, r * f a ∂μ) = (∫⁻ a, (⨆n, (const α r * eapprox f n) a) ∂μ) : by { congr, funext a, rw [← supr_eapprox_apply f hf, ennreal.mul_supr], refl } ... = (⨆n, r * (eapprox f n).lintegral μ) : begin rw [lintegral_supr], { congr, funext n, rw [← simple_func.const_mul_lintegral, ← simple_func.lintegral_eq_lintegral] }, { assume n, exact simple_func.measurable _ }, { assume i j h a, exact canonically_ordered_semiring.mul_le_mul (le_refl _) (monotone_eapprox _ h _) } end ... = r * (∫⁻ a, f a ∂μ) : by rw [← ennreal.mul_supr, lintegral_eq_supr_eapprox_lintegral hf] lemma lintegral_const_mul_le (r : ennreal) (f : α → ennreal) : r * (∫⁻ a, f a ∂μ) ≤ (∫⁻ a, r * f a ∂μ) := begin rw [lintegral, ennreal.mul_supr], refine supr_le (λs, _), rw [ennreal.mul_supr], simp only [supr_le_iff, ge_iff_le], assume hs, rw ← simple_func.const_mul_lintegral, refine le_supr_of_le (const α r * s) (le_supr_of_le (λx, _) (le_refl _)), exact canonically_ordered_semiring.mul_le_mul (le_refl _) (hs x) end lemma lintegral_const_mul' (r : ennreal) (f : α → ennreal) (hr : r ≠ ⊤) : (∫⁻ a, r * f a ∂μ) = r * (∫⁻ a, f a ∂μ) := begin by_cases h : r = 0, { simp [h] }, apply le_antisymm _ (lintegral_const_mul_le r f), have rinv : r * r⁻¹ = 1 := ennreal.mul_inv_cancel h hr, have rinv' : r ⁻¹ * r = 1, by { rw mul_comm, exact rinv }, have := lintegral_const_mul_le (r⁻¹) (λx, r * f x), simp [(mul_assoc _ _ _).symm, rinv'] at this, simpa [(mul_assoc _ _ _).symm, rinv] using canonically_ordered_semiring.mul_le_mul (le_refl r) this end lemma lintegral_mono_ae {f g : α → ennreal} (h : ∀ᵐ a ∂μ, f a ≤ g a) : (∫⁻ a, f a ∂μ) ≤ (∫⁻ a, g a ∂μ) := begin rcases exists_is_measurable_superset_of_measure_eq_zero h with ⟨t, hts, ht, ht0⟩, have : ∀ᵐ x ∂μ, x ∉ t := measure_zero_iff_ae_nmem.1 ht0, refine (supr_le $ assume s, supr_le $ assume hfs, le_supr_of_le (s.restrict tᶜ) $ le_supr_of_le _ _), { assume a, by_cases a ∈ t; simp [h, restrict_apply, ht.compl], exact le_trans (hfs a) (by_contradiction $ assume hnfg, h (hts hnfg)) }, { refine le_of_eq (simple_func.lintegral_congr $ this.mono $ λ a hnt, _), by_cases hat : a ∈ t; simp [hat, ht.compl], exact (hnt hat).elim } end lemma lintegral_congr_ae {f g : α → ennreal} (h : f =ᵐ[μ] g) : (∫⁻ a, f a ∂μ) = (∫⁻ a, g a ∂μ) := le_antisymm (lintegral_mono_ae $ h.le) (lintegral_mono_ae $ h.symm.le) lemma lintegral_congr {f g : α → ennreal} (h : ∀ a, f a = g a) : (∫⁻ a, f a ∂μ) = (∫⁻ a, g a ∂μ) := by simp only [h] lemma set_lintegral_congr {f : α → ennreal} {s t : set α} (h : s =ᵐ[μ] t) : ∫⁻ x in s, f x ∂μ = ∫⁻ x in t, f x ∂μ := by rw [restrict_congr_set h] -- TODO: Need a better way of rewriting inside of a integral lemma lintegral_rw₁ {f f' : α → β} (h : f =ᵐ[μ] f') (g : β → ennreal) : (∫⁻ a, g (f a) ∂μ) = (∫⁻ a, g (f' a) ∂μ) := lintegral_congr_ae $ h.mono $ λ a h, by rw h -- TODO: Need a better way of rewriting inside of a integral lemma lintegral_rw₂ {f₁ f₁' : α → β} {f₂ f₂' : α → γ} (h₁ : f₁ =ᵐ[μ] f₁') (h₂ : f₂ =ᵐ[μ] f₂') (g : β → γ → ennreal) : (∫⁻ a, g (f₁ a) (f₂ a) ∂μ) = (∫⁻ a, g (f₁' a) (f₂' a) ∂μ) := lintegral_congr_ae $ h₁.mp $ h₂.mono $ λ _ h₂ h₁, by rw [h₁, h₂] @[simp] lemma lintegral_indicator (f : α → ennreal) {s : set α} (hs : is_measurable s) : ∫⁻ a, s.indicator f a ∂μ = ∫⁻ a in s, f a ∂μ := begin simp only [lintegral, ← restrict_lintegral_eq_lintegral_restrict _ hs, supr_subtype'], apply le_antisymm; refine supr_le_supr2 (subtype.forall.2 $ λ φ hφ, _), { refine ⟨⟨φ, le_trans hφ (indicator_le_self _ _)⟩, _⟩, refine simple_func.lintegral_mono (λ x, _) (le_refl _), by_cases hx : x ∈ s, { simp [hx, hs, le_refl] }, { apply le_trans (hφ x), simp [hx, hs, le_refl] } }, { refine ⟨⟨φ.restrict s, λ x, _⟩, le_refl _⟩, simp [hφ x, hs, indicator_le_indicator] } end /-- Chebyshev's inequality -/ lemma mul_meas_ge_le_lintegral {f : α → ennreal} (hf : measurable f) (ε : ennreal) : ε * μ {x | ε ≤ f x} ≤ ∫⁻ a, f a ∂μ := begin have : is_measurable {a : α | ε ≤ f a }, from hf is_measurable_Ici, rw [← simple_func.restrict_const_lintegral _ this, ← simple_func.lintegral_eq_lintegral], refine lintegral_mono (λ a, _), simp only [restrict_apply _ this], split_ifs; [assumption, exact zero_le _] end lemma meas_ge_le_lintegral_div {f : α → ennreal} (hf : measurable f) {ε : ennreal} (hε : ε ≠ 0) (hε' : ε ≠ ⊤) : μ {x | ε ≤ f x} ≤ (∫⁻ a, f a ∂μ) / ε := (ennreal.le_div_iff_mul_le (or.inl hε) (or.inl hε')).2 $ by { rw [mul_comm], exact mul_meas_ge_le_lintegral hf ε } lemma lintegral_eq_zero_iff {f : α → ennreal} (hf : measurable f) : ∫⁻ a, f a ∂μ = 0 ↔ (f =ᵐ[μ] 0) := begin refine iff.intro (assume h, _) (assume h, _), { have : ∀n:ℕ, ∀ᵐ a ∂μ, f a < n⁻¹, { assume n, rw [ae_iff, ← le_zero_iff_eq, ← @ennreal.zero_div n⁻¹, ennreal.le_div_iff_mul_le, mul_comm], simp only [not_lt], -- TODO: why `rw ← h` fails with "not an equality or an iff"? exacts [h ▸ mul_meas_ge_le_lintegral hf n⁻¹, or.inl (ennreal.inv_ne_zero.2 ennreal.coe_nat_ne_top), or.inr ennreal.zero_ne_top] }, refine (ae_all_iff.2 this).mono (λ a ha, _), by_contradiction h, rcases ennreal.exists_inv_nat_lt h with ⟨n, hn⟩, exact (lt_irrefl _ $ lt_trans hn $ ha n).elim }, { calc ∫⁻ a, f a ∂μ = ∫⁻ a, 0 ∂μ : lintegral_congr_ae h ... = 0 : lintegral_zero } end /-- Weaker version of the monotone convergence theorem-/ lemma lintegral_supr_ae {f : ℕ → α → ennreal} (hf : ∀n, measurable (f n)) (h_mono : ∀n, ∀ᵐ a ∂μ, f n a ≤ f n.succ a) : (∫⁻ a, ⨆n, f n a ∂μ) = (⨆n, ∫⁻ a, f n a ∂μ) := let ⟨s, hs⟩ := exists_is_measurable_superset_of_measure_eq_zero (ae_iff.1 (ae_all_iff.2 h_mono)) in let g := λ n a, if a ∈ s then 0 else f n a in have g_eq_f : ∀ᵐ a ∂μ, ∀n, g n a = f n a, from (measure_zero_iff_ae_nmem.1 hs.2.2).mono (assume a ha n, if_neg ha), calc ∫⁻ a, ⨆n, f n a ∂μ = ∫⁻ a, ⨆n, g n a ∂μ : lintegral_congr_ae $ g_eq_f.mono $ λ a ha, by simp only [ha] ... = ⨆n, (∫⁻ a, g n a ∂μ) : lintegral_supr (assume n, measurable_const.piecewise hs.2.1 (hf n)) (monotone_of_monotone_nat $ assume n a, classical.by_cases (assume h : a ∈ s, by simp [g, if_pos h]) (assume h : a ∉ s, begin simp only [g, if_neg h], have := hs.1, rw subset_def at this, have := mt (this a) h, simp only [not_not, mem_set_of_eq] at this, exact this n end)) ... = ⨆n, (∫⁻ a, f n a ∂μ) : by simp only [lintegral_congr_ae (g_eq_f.mono $ λ a ha, ha _)] lemma lintegral_sub {f g : α → ennreal} (hf : measurable f) (hg : measurable g) (hg_fin : ∫⁻ a, g a ∂μ < ⊤) (h_le : g ≤ᵐ[μ] f) : ∫⁻ a, f a - g a ∂μ = ∫⁻ a, f a ∂μ - ∫⁻ a, g a ∂μ := begin rw [← ennreal.add_left_inj hg_fin, ennreal.sub_add_cancel_of_le (lintegral_mono_ae h_le), ← lintegral_add (hf.ennreal_sub hg) hg], refine lintegral_congr_ae (h_le.mono $ λ x hx, _), exact ennreal.sub_add_cancel_of_le hx end /-- Monotone convergence theorem for nonincreasing sequences of functions -/ lemma lintegral_infi_ae {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) (h_mono : ∀n:ℕ, f n.succ ≤ᵐ[μ] f n) (h_fin : ∫⁻ a, f 0 a ∂μ < ⊤) : ∫⁻ a, ⨅n, f n a ∂μ = ⨅n, ∫⁻ a, f n a ∂μ := have fn_le_f0 : ∫⁻ a, ⨅n, f n a ∂μ ≤ ∫⁻ a, f 0 a ∂μ, from lintegral_mono (assume a, infi_le_of_le 0 (le_refl _)), have fn_le_f0' : (⨅n, ∫⁻ a, f n a ∂μ) ≤ ∫⁻ a, f 0 a ∂μ, from infi_le_of_le 0 (le_refl _), (ennreal.sub_right_inj h_fin fn_le_f0 fn_le_f0').1 $ show ∫⁻ a, f 0 a ∂μ - ∫⁻ a, ⨅n, f n a ∂μ = ∫⁻ a, f 0 a ∂μ - (⨅n, ∫⁻ a, f n a ∂μ), from calc ∫⁻ a, f 0 a ∂μ - (∫⁻ a, ⨅n, f n a ∂μ) = ∫⁻ a, f 0 a - ⨅n, f n a ∂μ: (lintegral_sub (h_meas 0) (measurable_infi h_meas) (calc (∫⁻ a, ⨅n, f n a ∂μ) ≤ ∫⁻ a, f 0 a ∂μ : lintegral_mono (assume a, infi_le _ _) ... < ⊤ : h_fin ) (ae_of_all _ $ assume a, infi_le _ _)).symm ... = ∫⁻ a, ⨆n, f 0 a - f n a ∂μ : congr rfl (funext (assume a, ennreal.sub_infi)) ... = ⨆n, ∫⁻ a, f 0 a - f n a ∂μ : lintegral_supr_ae (assume n, (h_meas 0).ennreal_sub (h_meas n)) (assume n, (h_mono n).mono $ assume a ha, ennreal.sub_le_sub (le_refl _) ha) ... = ⨆n, ∫⁻ a, f 0 a ∂μ - ∫⁻ a, f n a ∂μ : have h_mono : ∀ᵐ a ∂μ, ∀n:ℕ, f n.succ a ≤ f n a := ae_all_iff.2 h_mono, have h_mono : ∀n, ∀ᵐ a ∂μ, f n a ≤ f 0 a := assume n, h_mono.mono $ assume a h, begin induction n with n ih, {exact le_refl _}, {exact le_trans (h n) ih} end, congr rfl (funext $ assume n, lintegral_sub (h_meas _) (h_meas _) (calc ∫⁻ a, f n a ∂μ ≤ ∫⁻ a, f 0 a ∂μ : lintegral_mono_ae $ h_mono n ... < ⊤ : h_fin) (h_mono n)) ... = ∫⁻ a, f 0 a ∂μ - ⨅n, ∫⁻ a, f n a ∂μ : ennreal.sub_infi.symm /-- Monotone convergence theorem for nonincreasing sequences of functions -/ lemma lintegral_infi {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) (h_mono : ∀ ⦃m n⦄, m ≤ n → f n ≤ f m) (h_fin : ∫⁻ a, f 0 a ∂μ < ⊤) : ∫⁻ a, ⨅n, f n a ∂μ = ⨅n, ∫⁻ a, f n a ∂μ := lintegral_infi_ae h_meas (λ n, ae_of_all _ $ h_mono $ le_of_lt n.lt_succ_self) h_fin /-- Known as Fatou's lemma -/ lemma lintegral_liminf_le {f : ℕ → α → ennreal} (h_meas : ∀n, measurable (f n)) : ∫⁻ a, liminf at_top (λ n, f n a) ∂μ ≤ liminf at_top (λ n, ∫⁻ a, f n a ∂μ) := calc ∫⁻ a, liminf at_top (λ n, f n a) ∂μ = ∫⁻ a, ⨆n:ℕ, ⨅i≥n, f i a ∂μ : by simp only [liminf_eq_supr_infi_of_nat] ... = ⨆n:ℕ, ∫⁻ a, ⨅i≥n, f i a ∂μ : lintegral_supr (assume n, measurable_binfi _ h_meas) (assume n m hnm a, infi_le_infi_of_subset $ λ i hi, le_trans hnm hi) ... ≤ ⨆n:ℕ, ⨅i≥n, ∫⁻ a, f i a ∂μ : supr_le_supr $ λ n, le_infi2_lintegral _ ... = liminf at_top (λ n, ∫⁻ a, f n a ∂μ) : liminf_eq_supr_infi_of_nat.symm lemma limsup_lintegral_le {f : ℕ → α → ennreal} {g : α → ennreal} (hf_meas : ∀ n, measurable (f n)) (h_bound : ∀n, f n ≤ᵐ[μ] g) (h_fin : ∫⁻ a, g a ∂μ < ⊤) : limsup at_top (λn, ∫⁻ a, f n a ∂μ) ≤ ∫⁻ a, limsup at_top (λn, f n a) ∂μ := calc limsup at_top (λn, ∫⁻ a, f n a ∂μ) = ⨅n:ℕ, ⨆i≥n, ∫⁻ a, f i a ∂μ : limsup_eq_infi_supr_of_nat ... ≤ ⨅n:ℕ, ∫⁻ a, ⨆i≥n, f i a ∂μ : infi_le_infi $ assume n, supr2_lintegral_le _ ... = ∫⁻ a, ⨅n:ℕ, ⨆i≥n, f i a ∂μ : begin refine (lintegral_infi _ _ _).symm, { assume n, exact measurable_bsupr _ hf_meas }, { assume n m hnm a, exact (supr_le_supr_of_subset $ λ i hi, le_trans hnm hi) }, { refine lt_of_le_of_lt (lintegral_mono_ae _) h_fin, refine (ae_all_iff.2 h_bound).mono (λ n hn, _), exact supr_le (λ i, supr_le $ λ hi, hn i) } end ... = ∫⁻ a, limsup at_top (λn, f n a) ∂μ : by simp only [limsup_eq_infi_supr_of_nat] /-- Dominated convergence theorem for nonnegative functions -/ lemma tendsto_lintegral_of_dominated_convergence {F : ℕ → α → ennreal} {f : α → ennreal} (bound : α → ennreal) (hF_meas : ∀n, measurable (F n)) (h_bound : ∀n, F n ≤ᵐ[μ] bound) (h_fin : ∫⁻ a, bound a ∂μ < ⊤) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) at_top (𝓝 (f a))) : tendsto (λn, ∫⁻ a, F n a ∂μ) at_top (𝓝 (∫⁻ a, f a ∂μ)) := tendsto_of_le_liminf_of_limsup_le (calc ∫⁻ a, f a ∂μ = ∫⁻ a, liminf at_top (λ (n : ℕ), F n a) ∂μ : lintegral_congr_ae $ h_lim.mono $ assume a h, h.liminf_eq.symm ... ≤ liminf at_top (λ n, ∫⁻ a, F n a ∂μ) : lintegral_liminf_le hF_meas) (calc limsup at_top (λ (n : ℕ), ∫⁻ a, F n a ∂μ) ≤ ∫⁻ a, limsup at_top (λn, F n a) ∂μ : limsup_lintegral_le hF_meas h_bound h_fin ... = ∫⁻ a, f a ∂μ : lintegral_congr_ae $ h_lim.mono $ λ a h, h.limsup_eq) /-- Dominated convergence theorem for filters with a countable basis -/ lemma tendsto_lintegral_filter_of_dominated_convergence {ι} {l : filter ι} {F : ι → α → ennreal} {f : α → ennreal} (bound : α → ennreal) (hl_cb : l.is_countably_generated) (hF_meas : ∀ᶠ n in l, measurable (F n)) (h_bound : ∀ᶠ n in l, ∀ᵐ a ∂μ, F n a ≤ bound a) (h_fin : ∫⁻ a, bound a ∂μ < ⊤) (h_lim : ∀ᵐ a ∂μ, tendsto (λ n, F n a) l (𝓝 (f a))) : tendsto (λn, ∫⁻ a, F n a ∂μ) l (𝓝 $ ∫⁻ a, f a ∂μ) := begin rw hl_cb.tendsto_iff_seq_tendsto, { intros x xl, have hxl, { rw tendsto_at_top' at xl, exact xl }, have h := inter_mem_sets hF_meas h_bound, replace h := hxl _ h, rcases h with ⟨k, h⟩, rw ← tendsto_add_at_top_iff_nat k, refine tendsto_lintegral_of_dominated_convergence _ _ _ _ _, { exact bound }, { intro, refine (h _ _).1, exact nat.le_add_left _ _ }, { intro, refine (h _ _).2, exact nat.le_add_left _ _ }, { assumption }, { refine h_lim.mono (λ a h_lim, _), apply @tendsto.comp _ _ _ (λn, x (n + k)) (λn, F n a), { assumption }, rw tendsto_add_at_top_iff_nat, assumption } }, end section open encodable /-- Monotone convergence for a suprema over a directed family and indexed by an encodable type -/ theorem lintegral_supr_directed [encodable β] {f : β → α → ennreal} (hf : ∀b, measurable (f b)) (h_directed : directed (≤) f) : ∫⁻ a, ⨆b, f b a ∂μ = ⨆b, ∫⁻ a, f b a ∂μ := begin by_cases hβ : nonempty β, swap, { simp [supr_of_empty hβ] }, resetI, inhabit β, have : ∀a, (⨆ b, f b a) = (⨆ n, f (h_directed.sequence f n) a), { assume a, refine le_antisymm (supr_le $ assume b, _) (supr_le $ assume n, le_supr (λn, f n a) _), exact le_supr_of_le (encode b + 1) (h_directed.le_sequence b a) }, calc ∫⁻ a, ⨆ b, f b a ∂μ = ∫⁻ a, ⨆ n, f (h_directed.sequence f n) a ∂μ : by simp only [this] ... = ⨆ n, ∫⁻ a, f (h_directed.sequence f n) a ∂μ : lintegral_supr (assume n, hf _) h_directed.sequence_mono ... = ⨆ b, ∫⁻ a, f b a ∂μ : begin refine le_antisymm (supr_le $ assume n, _) (supr_le $ assume b, _), { exact le_supr (λb, ∫⁻ a, f b a ∂μ) _ }, { exact le_supr_of_le (encode b + 1) (lintegral_mono $ h_directed.le_sequence b) } end end end lemma lintegral_tsum [encodable β] {f : β → α → ennreal} (hf : ∀i, measurable (f i)) : ∫⁻ a, ∑' i, f i a ∂μ = ∑' i, ∫⁻ a, f i a ∂μ := begin simp only [ennreal.tsum_eq_supr_sum], rw [lintegral_supr_directed], { simp [lintegral_finset_sum _ hf] }, { assume b, exact finset.measurable_sum _ hf }, { assume s t, use [s ∪ t], split, exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_left _ _), exact assume a, finset.sum_le_sum_of_subset (finset.subset_union_right _ _) } end open measure lemma lintegral_Union [encodable β] {s : β → set α} (hm : ∀ i, is_measurable (s i)) (hd : pairwise (disjoint on s)) (f : α → ennreal) : ∫⁻ a in ⋃ i, s i, f a ∂μ = ∑' i, ∫⁻ a in s i, f a ∂μ := by simp only [measure.restrict_Union hd hm, lintegral_sum_measure] lemma lintegral_Union_le [encodable β] (s : β → set α) (f : α → ennreal) : ∫⁻ a in ⋃ i, s i, f a ∂μ ≤ ∑' i, ∫⁻ a in s i, f a ∂μ := begin rw [← lintegral_sum_measure], exact lintegral_mono' restrict_Union_le (le_refl _) end lemma lintegral_map [measurable_space β] {f : β → ennreal} {g : α → β} (hf : measurable f) (hg : measurable g) : ∫⁻ a, f a ∂(map g μ) = ∫⁻ a, f (g a) ∂μ := begin simp only [lintegral_eq_supr_eapprox_lintegral, hf, hf.comp hg], { congr, funext n, symmetry, apply simple_func.lintegral_map, { assume a, exact congr_fun (simple_func.eapprox_comp hf hg) a }, { assume s hs, exact map_apply hg hs } }, end lemma set_lintegral_map [measurable_space β] {f : β → ennreal} {g : α → β} {s : set β} (hs : is_measurable s) (hf : measurable f) (hg : measurable g) : ∫⁻ y in s, f y ∂(map g μ) = ∫⁻ x in g ⁻¹' s, f (g x) ∂μ := by rw [restrict_map hg hs, lintegral_map hf hg] lemma lintegral_dirac (a : α) {f : α → ennreal} (hf : measurable f) : ∫⁻ a, f a ∂(dirac a) = f a := by simp [lintegral_congr_ae (eventually_eq_dirac hf)] /-- Given a measure `μ : measure α` and a function `f : α → ennreal`, `μ.with_density f` is the measure such that for a measurable set `s` we have `μ.with_density f s = ∫⁻ a in s, f a ∂μ`. -/ def measure.with_density (μ : measure α) (f : α → ennreal) : measure α := measure.of_measurable (λs hs, ∫⁻ a in s, f a ∂μ) (by simp) (λ s hs hd, lintegral_Union hs hd _) lemma with_density_apply (f : α → ennreal) {s : set α} (hs : is_measurable s) : μ.with_density f s = ∫⁻ a in s, f a ∂μ := measure.of_measurable_apply s hs end lintegral end measure_theory open measure_theory measure_theory.simple_func /-- To prove something for an arbitrary measurable function into `ennreal`, it suffices to show that the property holds for (multiples of) characteristic functions and is closed under addition and supremum of increasing sequences of functions. It is possible to make the hypotheses in the induction steps a bit stronger, and such conditions can be added once we need them (for example in `h_sum` it is only necessary to consider the sum of a simple function with a multiple of a characteristic function and that the intersection of their images is a subset of `{0}`. -/ @[elab_as_eliminator] theorem measurable.ennreal_induction {α} [measurable_space α] {P : (α → ennreal) → Prop} (h_ind : ∀ (c : ennreal) ⦃s⦄, is_measurable s → P (indicator s (λ _, c))) (h_sum : ∀ ⦃f g : α → ennreal⦄, set.univ ⊆ f ⁻¹' {0} ∪ g ⁻¹' {0} → measurable f → measurable g → P f → P g → P (f + g)) (h_supr : ∀ ⦃f : ℕ → α → ennreal⦄ (hf : ∀n, measurable (f n)) (h_mono : monotone f) (hP : ∀ n, P (f n)), P (λ x, ⨆ n, f n x)) ⦃f : α → ennreal⦄ (hf : measurable f) : P f := begin convert h_supr (λ n, (eapprox f n).measurable) (monotone_eapprox f) _, { ext1 x, rw [supr_eapprox_apply f hf] }, { exact λ n, simple_func.induction (λ c s hs, h_ind c hs) (λ f g hfg hf hg, h_sum hfg f.measurable g.measurable hf hg) (eapprox f n) } end
c0f600c93fc41c88004565e183bbaa5befbba67a
2102833783742d9cd20d98b382ecb3af427d8071
/library/init/meta/attribute.lean
bcc2128eded62f79c60d84c97510dfaa715f000d
[ "Apache-2.0" ]
permissive
bryangingechen/lean
b63dd2b7d2ed46c13c6226148691b7d88282e9b2
ec76117504723667bdc0dda4b93aa1b31536147d
refs/heads/master
1,592,587,806,769
1,568,328,715,000
1,568,328,715,000
196,801,202
0
0
Apache-2.0
1,563,085,022,000
1,563,085,022,000
null
UTF-8
Lean
false
false
5,912
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ prelude import init.meta.tactic init.meta.rb_map init.meta.has_reflect init.meta.lean.parser /-- Get all of the declaration names that have the given attribute. Eg. ``get_instances `simp`` returns a list with the names of all of the lemmas in the environment tagged with the `@[simp]` attribute. -/ meta constant attribute.get_instances : name → tactic (list name) /-- Returns a hash of `get_instances`. You can use this to tell if your attribute instances have changed. -/ meta constant attribute.fingerprint : name → tactic nat /-- Configuration for a user attribute cache. For example, the `simp` attribute has a cache of type simp_lemmas. - `mk_cache` is a function where you are given all of the declarations tagged with your attribute and you return the new value for the cache. That is, `mk_cache` makes the object you want to be cached. - `dependencies` [TODO] is a list of other attributes whose caches need to be computed first. -/ meta structure user_attribute_cache_cfg (cache_ty : Type) := (mk_cache : list name → tactic cache_ty) (dependencies : list name) /-- Close the current goal by filling it with the trivial `user_attribute_cache_cfg unit`. -/ meta def user_attribute.dflt_cache_cfg : tactic unit := tactic.exact `(⟨λ _, pure (), []⟩ : user_attribute_cache_cfg unit) meta def user_attribute.dflt_parser : tactic unit := tactic.exact `(pure () : lean.parser unit) /-- A __user attribute__ is an attribute defined by the user (ie, not built in to Lean). ### Type parameters - `cache_ty` is the type of a cached VM object that is computed from all of the declarations in the environment tagged with this attribute. - `param_ty` is an argument for the attribute when it is used. For instance with `param_ty` being `ℕ` you could write `@[my_attribute 4]`. ### Data A `user_attribute` consists of the following pieces of data: - `name` is the name of the attribute, eg ```simp``` - `descr` is a plaintext description of the attribute for humans. - `after_set` is an optional handler that will be called after the attribute has been applied to a declaration. Failing the tactic will fail the entire `attribute/def/...` command, i.e. the attribute will not be applied after all. Declaring an `after_set` handler without a `before_unset` handler will make the attribute non-removable. - `before_unset` Optional handler that will be called before the attribute is removed from a declaration. - `cache_cfg` describes how to construct the user attribute's cache. See docstring for `user_attribute_cache_cfg` - `reflect_param` demands that `param_ty` can be reflected. This means we have a function from `param_ty` to an expr. See the docstring for `has_reflect`. - `parser` Parser that will be invoked after parsing the attribute's name. The parse result will be reflected and stored and can be retrieved with `user_attribute.get_param`. -/ meta structure user_attribute (cache_ty : Type := unit) (param_ty : Type := unit) := (name : name) (descr : string) (after_set : option (Π (decl : _root_.name) (prio : nat) (persistent : bool), command) := none) (before_unset : option (Π (decl : _root_.name) (persistent : bool), command) := none) (cache_cfg : user_attribute_cache_cfg cache_ty . user_attribute.dflt_cache_cfg) [reflect_param : has_reflect param_ty] (parser : lean.parser param_ty . user_attribute.dflt_parser) /-- Registers a new user-defined attribute. The argument must be the name of a definition of type `user_attribute α β`. Once registered, you may tag declarations with this attribute. -/ meta def attribute.register (decl : name) : command := tactic.set_basic_attribute ``user_attribute decl tt /-- Returns the attribute cache for the given user attribute. -/ meta constant user_attribute.get_cache {α β : Type} (attr : user_attribute α β) : tactic α meta def user_attribute.parse_reflect {α β : Type} (attr : user_attribute α β) : lean.parser expr := (λ a, attr.reflect_param a) <$> attr.parser meta constant user_attribute.get_param_untyped {α β : Type} (attr : user_attribute α β) (decl : name) : tactic expr meta constant user_attribute.set_untyped {α β : Type} [reflected β] (attr : user_attribute α β) (decl : name) (val : expr) (persistent : bool) (prio : option nat := none) : tactic unit /-- Get the value of the parameter for the attribute on a given declatation. Will fail if the attribute does not exist.-/ meta def user_attribute.get_param {α β : Type} [reflected β] (attr : user_attribute α β) (n : name) : tactic β := attr.get_param_untyped n >>= tactic.eval_expr β meta def user_attribute.set {α β : Type} [reflected β] (attr : user_attribute α β) (n : name) (val : β) (persistent : bool) (prio : option nat := none) : tactic unit := attr.set_untyped n (attr.reflect_param val) persistent prio open tactic /-- Alias for attribute.register -/ meta def register_attribute := attribute.register meta def get_attribute_cache_dyn {α : Type} [reflected α] (attr_decl_name : name) : tactic α := let attr : pexpr := expr.const attr_decl_name [] in do e ← to_expr ``(user_attribute.get_cache %%attr), t ← eval_expr (tactic α) e, t meta def mk_name_set_attr (attr_name : name) : command := do let t := `(user_attribute name_set), let v := `({name := attr_name, descr := "name_set attribute", cache_cfg := { mk_cache := λ ns, return (name_set.of_list ns), dependencies := []}} : user_attribute name_set), add_meta_definition attr_name [] t v, register_attribute attr_name meta def get_name_set_for_attr (name : name) : tactic name_set := get_attribute_cache_dyn name
adabe4bc0e312aff6a450a45157fa6a5718dbd43
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/bornology/hom.lean
f9b4a24cc1a80fcb7ac3a0006e7cc4c207d96dbd
[ "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
5,248
lean
/- Copyright (c) 2022 Yaël Dillies. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies -/ import topology.bornology.basic /-! # Locally bounded maps This file defines locally bounded maps between bornologies. 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. ## Types of morphisms * `locally_bounded_map`: Locally bounded maps. Maps which preserve boundedness. ## Typeclasses * `locally_bounded_map_class` -/ open bornology filter function set variables {F α β γ δ : Type*} /-- The type of bounded maps from `α` to `β`, the maps which send a bounded set to a bounded set. -/ structure locally_bounded_map (α β : Type*) [bornology α] [bornology β] := (to_fun : α → β) (comap_cobounded_le' : (cobounded β).comap to_fun ≤ cobounded α) section set_option old_structure_cmd true /-- `locally_bounded_map_class F α β` states that `F` is a type of bounded maps. You should extend this class when you extend `locally_bounded_map`. -/ class locally_bounded_map_class (F : Type*) (α β : out_param $ Type*) [bornology α] [bornology β] extends fun_like F α (λ _, β) := (comap_cobounded_le (f : F) : (cobounded β).comap f ≤ cobounded α) end export locally_bounded_map_class (comap_cobounded_le) lemma is_bounded.image [bornology α] [bornology β] [locally_bounded_map_class F α β] {f : F} {s : set α} (hs : is_bounded s) : is_bounded (f '' s) := comap_cobounded_le_iff.1 (comap_cobounded_le f) hs instance [bornology α] [bornology β] [locally_bounded_map_class F α β] : has_coe_t F (locally_bounded_map α β) := ⟨λ f, ⟨f, comap_cobounded_le f⟩⟩ namespace locally_bounded_map variables [bornology α] [bornology β] [bornology γ] [bornology δ] instance : locally_bounded_map_class (locally_bounded_map α β) α β := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by { cases f, cases g, congr' }, comap_cobounded_le := λ f, f.comap_cobounded_le' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun` directly. -/ instance : has_coe_to_fun (locally_bounded_map α β) (λ _, α → β) := fun_like.has_coe_to_fun @[simp] lemma to_fun_eq_coe {f : locally_bounded_map α β} : f.to_fun = (f : α → β) := rfl @[ext] lemma ext {f g : locally_bounded_map α β} (h : ∀ a, f a = g a) : f = g := fun_like.ext f g h /-- Copy of a `locally_bounded_map` with a new `to_fun` equal to the old one. Useful to fix definitional equalities. -/ protected def copy (f : locally_bounded_map α β) (f' : α → β) (h : f' = f) : locally_bounded_map α β := ⟨f', h.symm ▸ f.comap_cobounded_le'⟩ @[simp] lemma coe_copy (f : locally_bounded_map α β) (f' : α → β) (h : f' = f) : ⇑(f.copy f' h) = f' := rfl lemma copy_eq (f : locally_bounded_map α β) (f' : α → β) (h : f' = f) : f.copy f' h = f := fun_like.ext' h /-- Construct a `locally_bounded_map` from the fact that the function maps bounded sets to bounded sets. -/ def of_map_bounded (f : α → β) (h) : locally_bounded_map α β := ⟨f, comap_cobounded_le_iff.2 h⟩ @[simp] lemma coe_of_map_bounded (f : α → β) {h} : ⇑(of_map_bounded f h) = f := rfl @[simp] lemma of_map_bounded_apply (f : α → β) {h} (a : α) : of_map_bounded f h a = f a := rfl variables (α) /-- `id` as a `locally_bounded_map`. -/ protected def id : locally_bounded_map α α := ⟨id, comap_id.le⟩ instance : inhabited (locally_bounded_map α α) := ⟨locally_bounded_map.id α⟩ @[simp] lemma coe_id : ⇑(locally_bounded_map.id α) = id := rfl variables {α} @[simp] lemma id_apply (a : α) : locally_bounded_map.id α a = a := rfl /-- Composition of `locally_bounded_map`s as a `locally_bounded_map`. -/ def comp (f : locally_bounded_map β γ) (g : locally_bounded_map α β) : locally_bounded_map α γ := { to_fun := f ∘ g, comap_cobounded_le' := comap_comap.ge.trans $ (comap_mono f.comap_cobounded_le').trans g.comap_cobounded_le' } @[simp] lemma coe_comp (f : locally_bounded_map β γ) (g : locally_bounded_map α β) : ⇑(f.comp g) = f ∘ g := rfl @[simp] lemma comp_apply (f : locally_bounded_map β γ) (g : locally_bounded_map α β) (a : α) : f.comp g a = f (g a) := rfl @[simp] lemma comp_assoc (f : locally_bounded_map γ δ) (g : locally_bounded_map β γ) (h : locally_bounded_map α β) : (f.comp g).comp h = f.comp (g.comp h) := rfl @[simp] lemma comp_id (f : locally_bounded_map α β) : f.comp (locally_bounded_map.id α) = f := ext $ λ a, rfl @[simp] lemma id_comp (f : locally_bounded_map α β) : (locally_bounded_map.id β).comp f = f := ext $ λ a, rfl lemma cancel_right {g₁ g₂ : locally_bounded_map β γ} {f : locally_bounded_map α β} (hf : surjective f) : g₁.comp f = g₂.comp f ↔ g₁ = g₂ := ⟨λ h, ext $ hf.forall.2 $ fun_like.ext_iff.1 h, congr_arg _⟩ lemma cancel_left {g : locally_bounded_map β γ} {f₁ f₂ : locally_bounded_map α β} (hg : injective g) : g.comp f₁ = g.comp f₂ ↔ f₁ = f₂ := ⟨λ h, ext $ λ a, hg $ by rw [←comp_apply, h, comp_apply], congr_arg _⟩ end locally_bounded_map
98bf6fdc28240553e884fd7d077603c5efd79c83
31f556cdeb9239ffc2fad8f905e33987ff4feab9
/src/Init/Util.lean
df7bbee40f365e70ba9403465a92d860ff59d750
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
tobiasgrosser/lean4
ce0fd9cca0feba1100656679bf41f0bffdbabb71
ebdbdc10436a4d9d6b66acf78aae7a23f5bd073f
refs/heads/master
1,673,103,412,948
1,664,930,501,000
1,664,930,501,000
186,870,185
0
0
Apache-2.0
1,665,129,237,000
1,557,939,901,000
Lean
UTF-8
Lean
false
false
3,806
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 -/ prelude import Init.Data.String.Basic import Init.Data.ToString.Basic universe u v /-! # Debugging helper functions -/ set_option linter.unusedVariables.funArgs false in @[neverExtract, extern "lean_dbg_trace"] def dbgTrace {α : Type u} (s : String) (f : Unit → α) : α := f () def dbgTraceVal {α : Type u} [ToString α] (a : α) : α := dbgTrace (toString a) (fun _ => a) set_option linter.unusedVariables.funArgs false in /-- Display the given message if `a` is shared, that is, RC(a) > 1 -/ @[neverExtract, extern "lean_dbg_trace_if_shared"] def dbgTraceIfShared {α : Type u} (s : String) (a : α) : α := a /-- Print stack trace to stderr before evaluating given closure. Currently supported on Linux only. -/ @[neverExtract, extern "lean_dbg_stack_trace"] def dbgStackTrace {α : Type u} (f : Unit → α) : α := f () @[extern "lean_dbg_sleep"] def dbgSleep {α : Type u} (ms : UInt32) (f : Unit → α) : α := f () @[noinline] private def mkPanicMessage (modName : String) (line col : Nat) (msg : String) : String := "PANIC at " ++ modName ++ ":" ++ toString line ++ ":" ++ toString col ++ ": " ++ msg @[neverExtract, inline] def panicWithPos {α : Type u} [Inhabited α] (modName : String) (line col : Nat) (msg : String) : α := panic (mkPanicMessage modName line col msg) @[noinline] private def mkPanicMessageWithDecl (modName : String) (declName : String) (line col : Nat) (msg : String) : String := "PANIC at " ++ declName ++ " " ++ modName ++ ":" ++ toString line ++ ":" ++ toString col ++ ": " ++ msg @[neverExtract, inline] def panicWithPosWithDecl {α : Type u} [Inhabited α] (modName : String) (declName : String) (line col : Nat) (msg : String) : α := panic (mkPanicMessageWithDecl modName declName line col msg) @[extern "lean_ptr_addr"] unsafe opaque ptrAddrUnsafe {α : Type u} (a : @& α) : USize set_option linter.unusedVariables.funArgs false in @[inline] unsafe def withPtrAddrUnsafe {α : Type u} {β : Type v} (a : α) (k : USize → β) (h : ∀ u₁ u₂, k u₁ = k u₂) : β := k (ptrAddrUnsafe a) @[inline] unsafe def ptrEq (a b : α) : Bool := ptrAddrUnsafe a == ptrAddrUnsafe b unsafe def ptrEqList : (as bs : List α) → Bool | [], [] => true | a::as, b::bs => if ptrEq a b then ptrEqList as bs else false | _, _ => false set_option linter.unusedVariables.funArgs false in @[inline] unsafe def withPtrEqUnsafe {α : Type u} (a b : α) (k : Unit → Bool) (h : a = b → k () = true) : Bool := if ptrEq a b then true else k () @[implementedBy withPtrEqUnsafe] def withPtrEq {α : Type u} (a b : α) (k : Unit → Bool) (h : a = b → k () = true) : Bool := k () /-- `withPtrEq` for `DecidableEq` -/ @[inline] def withPtrEqDecEq {α : Type u} (a b : α) (k : Unit → Decidable (a = b)) : Decidable (a = b) := let b := withPtrEq a b (fun _ => toBoolUsing (k ())) (toBoolUsing_eq_true (k ())); match h:b with | true => isTrue (ofBoolUsing_eq_true h) | false => isFalse (ofBoolUsing_eq_false h) @[implementedBy withPtrAddrUnsafe] def withPtrAddr {α : Type u} {β : Type v} (a : α) (k : USize → β) (h : ∀ u₁ u₂, k u₁ = k u₂) : β := k 0 @[inline] def getElem! [GetElem cont idx elem dom] [Inhabited elem] (xs : cont) (i : idx) [Decidable (dom xs i)] : elem := if h : _ then getElem xs i h else panic! "index out of bounds" @[inline] def getElem? [GetElem cont idx elem dom] (xs : cont) (i : idx) [Decidable (dom xs i)] : Option elem := if h : _ then some (getElem xs i h) else none macro:max x:term noWs "[" i:term "]" noWs "?" : term => `(getElem? $x $i) macro:max x:term noWs "[" i:term "]" noWs "!" : term => `(getElem! $x $i)
ca9b913f7d8c827e1471b9179e6c50264dd9e7e3
d0664585e88edfefe384f2b01de54487029040bb
/src/uniform_structure/entourages.lean
38c6cf27c5fe2c0a9178af4237b6f234b9a1d754
[]
no_license
ImperialCollegeLondon/uniform-structures
acf0a092d764925564595c59e7347e066d2a78ab
a41a170ef125b36bdac1e2201f54affa958d0349
refs/heads/master
1,668,088,958,039
1,592,495,127,000
1,592,495,127,000
269,964,470
2
0
null
null
null
null
UTF-8
Lean
false
false
1,263
lean
import tactic /-! # The entourage definition of a uniform space We start with a little section on `U ∘ V` (see axiom 4 of the wikipedia entourage definition of a uniform space) We then give the entourage definition of a uniform space -/ -- We first define U ∘ V. First the function itself (called `comp_ent`) /-- composition `∘` of two subsets of X × X -/ def comp_ent {X : Type} (U V : set (X×X)) := {p : X × X | ∃z : X, (p.1, z) ∈ U ∧ (z, p.2) ∈ V} -- and now the notation notation U ` ∘ ` V := comp_ent U V variables {X : Type} {U V : set (X × X)} {x y : X} /-- This is the theorem which gives the defining property of U ∘ V -/ @[simp] theorem mem_comp_ent : (x, y) ∈ U ∘ V ↔ ∃ z, (x, z) ∈ U ∧ (z, y) ∈ V := iff.rfl -- true by definition structure uniform_space_entourage (X : Type) := (entourages : set (set (X × X))) -- now go through the five axioms in Wikipedia (refl : ∀ U ∈ entourages, ∀ x : X, (x,x) ∈ U) (bigger : ∀ U V : set (X × X), U ∈ entourages → U ⊆ V → V ∈ entourages) (inter : ∀ U V ∈ entourages, U ∩ V ∈ entourages) (comp : ∀ U ∈ entourages, ∃ V ∈ entourages, V ∘ V ⊆ U) (symm : ∀ U ∈ entourages, {z : X × X | (z.2, z.1) ∈ U} ∈ entourages)
1b3c01beeb5543be89f5e39ff4bf49843d1d2db9
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/stage0/src/Lean/Elab/SetOption.lean
4bcfab4cfb6a77a074f3fbdf27e6fa3b95fbddd5
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
1,353
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.Log import Lean.Elab.InfoTree namespace Lean.Elab variable [Monad m] [MonadOptions m] [MonadExceptOf Exception m] [MonadRef m] variable [AddErrorMessageContext m] [MonadLiftT (EIO Exception) m] [MonadInfoTree m] def elabSetOption (id : Syntax) (val : Syntax) : m Options := do let optionName := id.getId.eraseMacroScopes match val.isStrLit? with | some str => setOption optionName (DataValue.ofString str) | none => match val.isNatLit? with | some num => setOption optionName (DataValue.ofNat num) | none => match val with | Syntax.atom _ "true" => setOption optionName (DataValue.ofBool true) | Syntax.atom _ "false" => setOption optionName (DataValue.ofBool false) | _ => addCompletionInfo <| CompletionInfo.option (← getRef) throwError "unexpected set_option value {val}" where setOption (optionName : Name) (val : DataValue) : m Options := do let ref ← getRef let decl ← IO.toEIO (fun (ex : IO.Error) => Exception.error ref ex.toString) (getOptionDecl optionName) unless decl.defValue.sameCtor val do throwError "type mismatch at set_option" return (← getOptions).insert optionName val end Lean.Elab
9625866e9a42cbfd80f60ee65b0f4b005583b5d8
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/number_theory/number_field/canonical_embedding.lean
d3b00666835051dfb6ebb2245cee98096c9b6430
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
7,289
lean
/- Copyright (c) 2022 Xavier Roblot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Xavier Roblot -/ import number_theory.number_field.embeddings /-! # Canonical embedding of a number field > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. The canonical embedding of a number field `K` of signature `(r₁, r₂)` is the ring homomorphism `K →+* ℝ^r₁ × ℂ^r₂` that sends `x ∈ K` to `(φ_₁(x),...,φ_r₁(x)) × (ψ_₁(x),..., ψ_r₂(x))` where `φ_₁,...,φ_r₁` are its real embeddings and `ψ_₁,..., ψ_r₂` are its complex embeddings (up to complex conjugation). ## Main definitions and results * `number_field.canonical_embedding.ring_of_integers.inter_ball_finite`: the intersection of the image of the ring of integers by the canonical embedding and any ball centered at `0` of finite radius is finite. ## Tags number field, infinite places -/ noncomputable theory open function finite_dimensional finset fintype number_field number_field.infinite_place metric module open_locale classical number_field variables (K : Type*) [field K] namespace number_field.canonical_embedding -- The ambient space `ℝ^r₁ × ℂ^r₂` with `(r₁, r₂)` the signature of `K`. localized "notation `E` := ({w : infinite_place K // is_real w} → ℝ) × ({w : infinite_place K // is_complex w} → ℂ)" in canonical_embedding lemma space_rank [number_field K] : finrank ℝ E = finrank ℚ K := begin haveI : module.free ℝ ℂ := infer_instance, rw [finrank_prod, finrank_pi, finrank_pi_fintype, complex.finrank_real_complex, finset.sum_const, finset.card_univ, ← card_real_embeddings, algebra.id.smul_eq_mul, mul_comm, ← card_complex_embeddings, ← number_field.embeddings.card K ℂ, fintype.card_subtype_compl, nat.add_sub_of_le (fintype.card_subtype_le _)], end lemma non_trivial_space [number_field K] : nontrivial E := begin obtain ⟨w⟩ := infinite_place.nonempty K, obtain hw | hw := w.is_real_or_is_complex, { haveI : nonempty {w : infinite_place K // is_real w} := ⟨⟨w, hw⟩⟩, exact nontrivial_prod_left }, { haveI : nonempty {w : infinite_place K // is_complex w} := ⟨⟨w, hw⟩⟩, exact nontrivial_prod_right } end /-- The canonical embedding of a number field `K` of signature `(r₁, r₂)` into `ℝ^r₁ × ℂ^r₂`. -/ def _root_.number_field.canonical_embedding : K →+* E := ring_hom.prod (pi.ring_hom (λ w, w.prop.embedding)) (pi.ring_hom (λ w, w.val.embedding)) lemma _root_.number_field.canonical_embedding_injective [number_field K] : injective (number_field.canonical_embedding K) := @ring_hom.injective _ _ _ _ (non_trivial_space K) _ open number_field variable {K} @[simp] lemma apply_at_real_infinite_place (w : {w : infinite_place K // is_real w}) (x : K) : (number_field.canonical_embedding K x).1 w = w.prop.embedding x := by simp only [canonical_embedding, ring_hom.prod_apply, pi.ring_hom_apply] @[simp] lemma apply_at_complex_infinite_place (w : { w : infinite_place K // is_complex w}) (x : K) : (number_field.canonical_embedding K x).2 w = embedding w.val x := by simp only [canonical_embedding, ring_hom.prod_apply, pi.ring_hom_apply] lemma nnnorm_eq [number_field K] (x : K) : ‖canonical_embedding K x‖₊ = finset.univ.sup (λ w : infinite_place K, ⟨w x, map_nonneg w x⟩) := begin rw [prod.nnnorm_def', pi.nnnorm_def, pi.nnnorm_def], rw ( _ : finset.univ = {w : infinite_place K | is_real w}.to_finset ∪ {w : infinite_place K | is_complex w}.to_finset), { rw [finset.sup_union, sup_eq_max], refine congr_arg2 _ _ _, { convert (finset.univ.sup_map (function.embedding.subtype (λ w : infinite_place K, is_real w)) (λ w, (⟨w x, map_nonneg w x⟩ : nnreal))).symm using 2, ext w, simp only [apply_at_real_infinite_place, coe_nnnorm, real.norm_eq_abs, function.embedding.coe_subtype, subtype.coe_mk, is_real.abs_embedding_apply], }, { convert (finset.univ.sup_map (function.embedding.subtype (λ w : infinite_place K, is_complex w)) (λ w, (⟨w x, map_nonneg w x⟩ : nnreal))).symm using 2, ext w, simp only [apply_at_complex_infinite_place, subtype.val_eq_coe, coe_nnnorm, complex.norm_eq_abs, function.embedding.coe_subtype, subtype.coe_mk, abs_embedding], }}, { ext w, simp only [w.is_real_or_is_complex, set.mem_set_of_eq, finset.mem_union, set.mem_to_finset, finset.mem_univ], }, end lemma norm_le_iff [number_field K] (x : K) (r : ℝ) : ‖canonical_embedding K x‖ ≤ r ↔ ∀ w : infinite_place K, w x ≤ r := begin obtain hr | hr := lt_or_le r 0, { obtain ⟨w⟩ := infinite_place.nonempty K, exact iff_of_false (hr.trans_le $ norm_nonneg _).not_le (λ h, hr.not_le $ (map_nonneg w _).trans $ h _) }, { lift r to nnreal using hr, simp_rw [← coe_nnnorm, nnnorm_eq, nnreal.coe_le_coe, finset.sup_le_iff, finset.mem_univ, forall_true_left, ←nnreal.coe_le_coe, subtype.coe_mk] } end variables (K) /-- The image of `𝓞 K` as a subring of `ℝ^r₁ × ℂ^r₂`. -/ def integer_lattice : subring E := (ring_hom.range (algebra_map (𝓞 K) K)).map (canonical_embedding K) /-- The linear equiv between `𝓞 K` and the integer lattice. -/ def equiv_integer_lattice [number_field K] : 𝓞 K ≃ₗ[ℤ] integer_lattice K := linear_equiv.of_bijective { to_fun := λ x, ⟨canonical_embedding K (algebra_map (𝓞 K) K x), algebra_map (𝓞 K) K x, by simp only [subring.mem_carrier, ring_hom.mem_range, exists_apply_eq_apply], rfl⟩, map_add' := λ x y, by simpa only [map_add], map_smul' := λ c x, by simpa only [zsmul_eq_mul, map_mul, map_int_cast] } begin refine ⟨λ _ _ h, _, λ ⟨_, _, ⟨a, rfl⟩, rfl⟩, ⟨a, rfl⟩⟩, rw [linear_map.coe_mk, subtype.mk_eq_mk] at h, exact is_fraction_ring.injective (𝓞 K) K (canonical_embedding_injective K h), end lemma integer_lattice.inter_ball_finite [number_field K] (r : ℝ) : ((integer_lattice K : set E) ∩ (closed_ball 0 r)).finite := begin obtain hr | hr := lt_or_le r 0, { simp [closed_ball_eq_empty.2 hr] }, have heq : ∀ x, canonical_embedding K x ∈ closed_ball (0 : E) r ↔ ∀ φ : K →+* ℂ, ‖φ x‖ ≤ r, { simp only [← place_apply, ← infinite_place.coe_mk, mem_closed_ball_zero_iff, norm_le_iff], exact λ x, le_iff_le x r, }, convert (embeddings.finite_of_norm_le K ℂ r).image (canonical_embedding K), ext, split, { rintro ⟨⟨_, ⟨x, rfl⟩, rfl⟩, hx2⟩, exact ⟨x, ⟨set_like.coe_mem x, (heq x).mp hx2⟩, rfl⟩, }, { rintro ⟨x, ⟨hx1, hx2⟩, rfl⟩, exact ⟨⟨x, ⟨⟨x, hx1⟩, rfl⟩, rfl⟩, (heq x).mpr hx2⟩, } end instance [number_field K] : countable (integer_lattice K) := begin have : (⋃ n : ℕ, ((integer_lattice K : set E) ∩ (closed_ball 0 n))).countable, { exact set.countable_Union (λ n, (integer_lattice.inter_ball_finite K n).countable) }, refine (this.mono _).to_subtype, rintro _ ⟨x, hx, rfl⟩, rw set.mem_Union, exact ⟨⌈‖canonical_embedding K x‖⌉₊, ⟨x, hx, rfl⟩, mem_closed_ball_zero_iff.2 (nat.le_ceil _)⟩, end end number_field.canonical_embedding
53a9228adb8122ccb21b3887cf0bfebb1b8d7177
618003631150032a5676f229d13a079ac875ff77
/src/measure_theory/borel_space.lean
ef177c8af7921050449e05b45d29585ac4beb285
[ "Apache-2.0" ]
permissive
awainverse/mathlib
939b68c8486df66cfda64d327ad3d9165248c777
ea76bd8f3ca0a8bf0a166a06a475b10663dec44a
refs/heads/master
1,659,592,962,036
1,590,987,592,000
1,590,987,592,000
268,436,019
1
0
Apache-2.0
1,590,990,500,000
1,590,990,500,000
null
UTF-8
Lean
false
false
29,406
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, Yury Kudryashov -/ import measure_theory.measurable_space import topology.instances.ennreal import analysis.normed_space.basic /-! # Borel (measurable) space ## Main definitions * `borel α` : the least `σ`-algebra that contains all open sets; * `class borel_space` : a space with `topological_space` and `measurable_space` structures such that `‹measurable_space α› = borel α`; * `class opens_measurable_space` : a space with `topological_space` and `measurable_space` structures such that all open sets are measurable; equivalently, `borel α ≤ ‹measurable_space α›`. * `borel_space` instances on `empty`, `unit`, `bool`, `nat`, `int`, `rat`; * `measurable` and `borel_space` instances on `ℝ`, `ℝ≥0`, `ennreal`. ## Main statements * `is_open.is_measurable`, `is_closed.is_measurable`: open and closed sets are measurable; * `continuous.measurable` : a continuous function is measurable; * `continuous.measurable2` : if `f : α → β` and `g : α → γ` are measurable and `op : β × γ → δ` is continuous, then `λ x, op (f x, g y)` is measurable; * `measurable.add` etc : dot notation for arithmetic operations on `measurable` predicates, and similarly for `dist` and `edist`; * `measurable.ennreal*` : special cases for arithmetic operations on `ennreal`s. -/ noncomputable theory open classical set open_locale classical universes u v w x y variables {α : Type u} {β : Type v} {γ : Type w} {δ : Type x} {ι : Sort y} {s t u : set α} open measurable_space topological_space /-- `measurable_space` structure generated by `topological_space`. -/ def borel (α : Type u) [topological_space α] : measurable_space α := generate_from {s : set α | is_open s} lemma borel_eq_top_of_discrete [topological_space α] [discrete_topology α] : borel α = ⊤ := top_le_iff.1 $ λ s hs, generate_measurable.basic s (is_open_discrete s) lemma borel_eq_top_of_encodable [topological_space α] [t1_space α] [encodable α] : borel α = ⊤ := begin refine (top_le_iff.1 $ λ s hs, bUnion_of_singleton s ▸ _), apply is_measurable.bUnion s.countable_encodable, intros x hx, apply is_measurable.of_compl, apply generate_measurable.basic, exact is_closed_singleton end lemma borel_eq_generate_from_of_subbasis {s : set (set α)} [t : topological_space α] [second_countable_topology α] (hs : t = generate_from s) : borel α = generate_from s := le_antisymm (generate_from_le $ assume u (hu : t.is_open u), begin rw [hs] at hu, induction hu, case generate_open.basic : u hu { exact generate_measurable.basic u hu }, case generate_open.univ { exact @is_measurable.univ α (generate_from s) }, case generate_open.inter : s₁ s₂ _ _ hs₁ hs₂ { exact @is_measurable.inter α (generate_from s) _ _ hs₁ hs₂ }, case generate_open.sUnion : f hf ih { rcases is_open_sUnion_countable f (by rwa hs) with ⟨v, hv, vf, vu⟩, rw ← vu, exact @is_measurable.sUnion α (generate_from s) _ hv (λ x xv, ih _ (vf xv)) } end) (generate_from_le $ assume u hu, generate_measurable.basic _ $ show t.is_open u, by rw [hs]; exact generate_open.basic _ hu) lemma borel_eq_generate_Iio (α) [topological_space α] [second_countable_topology α] [linear_order α] [order_topology α] : borel α = generate_from (range Iio) := begin refine le_antisymm _ (generate_from_le _), { rw borel_eq_generate_from_of_subbasis (@order_topology.topology_eq_generate_intervals α _ _ _), have H : ∀ a:α, is_measurable (measurable_space.generate_from (range Iio)) (Iio a) := λ a, generate_measurable.basic _ ⟨_, rfl⟩, refine generate_from_le _, rintro _ ⟨a, rfl | rfl⟩; [skip, apply H], by_cases h : ∃ a', ∀ b, a < b ↔ a' ≤ b, { rcases h with ⟨a', ha'⟩, rw (_ : Ioi a = -Iio a'), {exact (H _).compl _}, simp [set.ext_iff, ha'] }, { rcases is_open_Union_countable (λ a' : {a' : α // a < a'}, {b | a'.1 < b}) (λ a', is_open_lt' _) with ⟨v, ⟨hv⟩, vu⟩, simp [set.ext_iff] at vu, have : Ioi a = ⋃ x : v, -Iio x.1.1, { simp [set.ext_iff], refine λ x, ⟨λ ax, _, λ ⟨a', ⟨h, av⟩, ax⟩, lt_of_lt_of_le h ax⟩, rcases (vu x).2 _ with ⟨a', h₁, h₂⟩, { exact ⟨a', h₁, le_of_lt h₂⟩ }, refine not_imp_comm.1 (λ h, _) h, exact ⟨x, λ b, ⟨λ ab, le_of_not_lt (λ h', h ⟨b, ab, h'⟩), lt_of_lt_of_le ax⟩⟩ }, rw this, resetI, apply is_measurable.Union, exact λ _, (H _).compl _ } }, { simp, rintro _ a rfl, exact generate_measurable.basic _ is_open_Iio } end lemma borel_eq_generate_Ioi (α) [topological_space α] [second_countable_topology α] [linear_order α] [order_topology α] : borel α = generate_from (range Ioi) := begin refine le_antisymm _ (generate_from_le _), { rw borel_eq_generate_from_of_subbasis (@order_topology.topology_eq_generate_intervals α _ _ _), have H : ∀ a:α, is_measurable (measurable_space.generate_from (range (λ a, {x | a < x}))) {x | a < x} := λ a, generate_measurable.basic _ ⟨_, rfl⟩, refine generate_from_le _, rintro _ ⟨a, rfl | rfl⟩, {apply H}, by_cases h : ∃ a', ∀ b, b < a ↔ b ≤ a', { rcases h with ⟨a', ha'⟩, rw (_ : Iio a = -Ioi a'), {exact (H _).compl _}, simp [set.ext_iff, ha'] }, { rcases is_open_Union_countable (λ a' : {a' : α // a' < a}, {b | b < a'.1}) (λ a', is_open_gt' _) with ⟨v, ⟨hv⟩, vu⟩, simp [set.ext_iff] at vu, have : Iio a = ⋃ x : v, -Ioi x.1.1, { simp [set.ext_iff], refine λ x, ⟨λ ax, _, λ ⟨a', ⟨h, av⟩, ax⟩, lt_of_le_of_lt ax h⟩, rcases (vu x).2 _ with ⟨a', h₁, h₂⟩, { exact ⟨a', h₁, le_of_lt h₂⟩ }, refine not_imp_comm.1 (λ h, _) h, exact ⟨x, λ b, ⟨λ ab, le_of_not_lt (λ h', h ⟨b, ab, h'⟩), λ h, lt_of_le_of_lt h ax⟩⟩ }, rw this, resetI, apply is_measurable.Union, exact λ _, (H _).compl _ } }, { simp, rintro _ a rfl, exact generate_measurable.basic _ (is_open_lt' _) } end lemma borel_comap {f : α → β} {t : topological_space β} : @borel α (t.induced f) = (@borel β t).comap f := comap_generate_from.symm lemma continuous.borel_measurable [topological_space α] [topological_space β] {f : α → β} (hf : continuous f) : @measurable α β (borel α) (borel β) f := generate_from_le $ λ s hs, generate_measurable.basic (f ⁻¹' s) (hf s hs) /-- A space with `measurable_space` and `topological_space` structures such that all open sets are measurable. -/ class opens_measurable_space (α : Type*) [topological_space α] [h : measurable_space α] : Prop := (borel_le : borel α ≤ h) /-- A space with `measurable_space` and `topological_space` structures such that the `σ`-algebra of measurable sets is exactly the `σ`-algebra generated by open sets. -/ class borel_space (α : Type*) [topological_space α] [measurable_space α] : Prop := (measurable_eq : ‹measurable_space α› = borel α) /-- In a `borel_space` all open sets are measurable. -/ @[priority 100] instance borel_space.opens_measurable {α : Type*} [topological_space α] [measurable_space α] [borel_space α] : opens_measurable_space α := ⟨ge_of_eq $ borel_space.measurable_eq⟩ instance subtype.borel_space {α : Type*} [topological_space α] [measurable_space α] [hα : borel_space α] (s : set α) : borel_space s := ⟨by { rw [hα.1, subtype.measurable_space, ← borel_comap], refl }⟩ instance subtype.opens_measurable_space {α : Type*} [topological_space α] [measurable_space α] [h : opens_measurable_space α] (s : set α) : opens_measurable_space s := ⟨by { rw [borel_comap], exact comap_mono h.1 }⟩ section variables [topological_space α] [measurable_space α] [opens_measurable_space α] [topological_space β] [measurable_space β] [opens_measurable_space β] [topological_space γ] [measurable_space γ] [borel_space γ] [measurable_space δ] lemma is_open.is_measurable (h : is_open s) : is_measurable s := opens_measurable_space.borel_le _ $ generate_measurable.basic _ h lemma is_measurable_interior : is_measurable (interior s) := is_open_interior.is_measurable lemma is_closed.is_measurable (h : is_closed s) : is_measurable s := is_measurable.compl_iff.1 $ h.is_measurable lemma is_measurable_singleton [t1_space α] {x : α} : is_measurable ({x} : set α) := is_closed_singleton.is_measurable lemma is_measurable_eq [t1_space α] {a : α} : is_measurable {x | x = a} := is_measurable_singleton lemma is_measurable_closure : is_measurable (closure s) := is_closed_closure.is_measurable section order_closed_topology variables [preorder α] [order_closed_topology α] {a b : α} lemma is_measurable_Ici : is_measurable (Ici a) := is_closed_Ici.is_measurable lemma is_measurable_Iic : is_measurable (Iic a) := is_closed_Iic.is_measurable lemma is_measurable_Icc : is_measurable (Icc a b) := is_closed_Icc.is_measurable end order_closed_topology section order_closed_topology variables [linear_order α] [order_closed_topology α] {a b : α} lemma is_measurable_Iio : is_measurable (Iio a) := is_open_Iio.is_measurable lemma is_measurable_Ioi : is_measurable (Ioi a) := is_open_Ioi.is_measurable lemma is_measurable_Ioo : is_measurable (Ioo a b) := is_open_Ioo.is_measurable lemma is_measurable_Ioc : is_measurable (Ioc a b) := is_measurable_Ioi.inter is_measurable_Iic lemma is_measurable_Ico : is_measurable (Ico a b) := is_measurable_Ici.inter is_measurable_Iio end order_closed_topology lemma is_measurable_interval [decidable_linear_order α] [order_closed_topology α] {a b : α} : is_measurable (interval a b) := is_measurable_Icc instance prod.opens_measurable_space [second_countable_topology α] [second_countable_topology β] : opens_measurable_space (α × β) := begin refine ⟨_⟩, rcases is_open_generated_countable_inter α with ⟨a, ha₁, ha₂, ha₃, ha₄, ha₅⟩, rcases is_open_generated_countable_inter β with ⟨b, hb₁, hb₂, hb₃, hb₄, hb₅⟩, have : prod.topological_space = generate_from {g | ∃u∈a, ∃v∈b, g = set.prod u v}, { rw [ha₅, hb₅], exact prod_generate_from_generate_from_eq ha₄ hb₄ }, rw [borel_eq_generate_from_of_subbasis this], apply generate_from_le, rintros _ ⟨u, hu, v, hv, rfl⟩, have hu : is_open u, by { rw [ha₅], exact generate_open.basic _ hu }, have hv : is_open v, by { rw [hb₅], exact generate_open.basic _ hv }, exact hu.is_measurable.prod hv.is_measurable end /-- A continuous function from an `opens_measurable_space` to a `borel_space` is measurable. -/ lemma continuous.measurable {f : α → γ} (hf : continuous f) : measurable f := hf.borel_measurable.mono opens_measurable_space.borel_le (le_of_eq $ borel_space.measurable_eq) /-- A homeomorphism between two Borel spaces is a measurable equivalence.-/ def homeomorph.to_measurable_equiv {α : Type*} {β : Type*} [topological_space α] [measurable_space α] [borel_space α] [topological_space β] [measurable_space β] [borel_space β] (h : α ≃ₜ β) : measurable_equiv α β := { measurable_to_fun := h.continuous_to_fun.measurable, measurable_inv_fun := h.continuous_inv_fun.measurable, .. h } lemma measurable_of_continuous_on_compl_singleton [t1_space α] {f : α → γ} (a : α) (hf : continuous_on f {x | x ≠ a}) : measurable f := measurable_of_measurable_on_compl_singleton a is_measurable_singleton (continuous_on_iff_continuous_restrict.1 hf).measurable lemma continuous.measurable2 [second_countable_topology α] [second_countable_topology β] {f : δ → α} {g : δ → β} {c : α → β → γ} (h : continuous (λp:α×β, c p.1 p.2)) (hf : measurable f) (hg : measurable g) : measurable (λa, c (f a) (g a)) := h.measurable.comp (hf.prod_mk hg) lemma measurable.smul [semiring α] [second_countable_topology α] [add_comm_monoid γ] [second_countable_topology γ] [semimodule α γ] [topological_semimodule α γ] {f : δ → α} {g : δ → γ} (hf : measurable f) (hg : measurable g) : measurable (λ c, f c • g c) := continuous_smul.measurable2 hf hg lemma measurable.const_smul {α : Type*} [topological_space α] [semiring α] [add_comm_monoid γ] [semimodule α γ] [topological_semimodule α γ] {f : δ → γ} (hf : measurable f) (c : α) : measurable (λ x, c • f x) := (continuous_const.smul continuous_id).measurable.comp hf lemma measurable_const_smul_iff {α : Type*} [topological_space α] [division_ring α] [add_comm_monoid γ] [semimodule α γ] [topological_semimodule α γ] {f : δ → γ} {c : α} (hc : c ≠ 0) : measurable (λ x, c • f x) ↔ measurable f := ⟨λ h, by simpa only [smul_smul, inv_mul_cancel hc, one_smul] using h.const_smul c⁻¹, λ h, h.const_smul c⟩ lemma is_measurable_le' [partial_order α] [order_closed_topology α] [second_countable_topology α] : is_measurable {p : α × α | p.1 ≤ p.2} := order_closed_topology.is_closed_le'.is_measurable lemma is_measurable_le [partial_order α] [order_closed_topology α] [second_countable_topology α] {f g : δ → α} (hf : measurable f) (hg : measurable g) : is_measurable {a | f a ≤ g a} := (hf.prod_mk hg).preimage is_measurable_le' lemma measurable.max [decidable_linear_order α] [order_closed_topology α] [second_countable_topology α] {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λa, max (f a) (g a)) := measurable.if (is_measurable_le hf hg) hg hf lemma measurable.min [decidable_linear_order α] [order_closed_topology α] [second_countable_topology α] {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λa, min (f a) (g a)) := measurable.if (is_measurable_le hf hg) hf hg end section borel_space variables [topological_space α] [measurable_space α] [borel_space α] [topological_space β] [measurable_space β] [borel_space β] [topological_space γ] [measurable_space γ] [borel_space γ] [measurable_space δ] lemma prod_le_borel_prod : prod.measurable_space ≤ borel (α × β) := begin rw [‹borel_space α›.measurable_eq, ‹borel_space β›.measurable_eq], refine sup_le _ _, { exact comap_le_iff_le_map.mpr continuous_fst.borel_measurable }, { exact comap_le_iff_le_map.mpr continuous_snd.borel_measurable } end instance prod.borel_space [second_countable_topology α] [second_countable_topology β] : borel_space (α × β) := ⟨le_antisymm prod_le_borel_prod opens_measurable_space.borel_le⟩ @[to_additive] lemma measurable_mul [monoid α] [topological_monoid α] [second_countable_topology α] : measurable (λ p : α × α, p.1 * p.2) := continuous_mul.measurable @[to_additive] lemma measurable.mul [monoid α] [topological_monoid α] [second_countable_topology α] {f : δ → α} {g : δ → α} : measurable f → measurable g → measurable (λa, f a * g a) := continuous_mul.measurable2 @[to_additive] lemma finset.measurable_prod {ι : Type*} [comm_monoid α] [topological_monoid α] [second_countable_topology α] {f : ι → δ → α} (s : finset ι) (hf : ∀i, measurable (f i)) : measurable (λa, s.prod (λi, f i a)) := finset.induction_on s (by simp only [finset.prod_empty, measurable_const]) (assume i s his ih, by simpa [his] using (hf i).mul ih) @[to_additive] lemma measurable_inv [group α] [topological_group α] : measurable (has_inv.inv : α → α) := continuous_inv.measurable @[to_additive] lemma measurable.inv [group α] [topological_group α] {f : δ → α} (hf : measurable f) : measurable (λa, (f a)⁻¹) := measurable_inv.comp hf lemma measurable_inv' {α : Type*} [normed_field α] [measurable_space α] [borel_space α] : measurable (has_inv.inv : α → α) := measurable_of_continuous_on_compl_singleton 0 normed_field.continuous_on_inv lemma measurable.inv' {α : Type*} [normed_field α] [measurable_space α] [borel_space α] {f : δ → α} (hf : measurable f) : measurable (λa, (f a)⁻¹) := measurable_inv'.comp hf @[to_additive] lemma measurable.of_inv [group α] [topological_group α] {f : δ → α} (hf : measurable (λ a, (f a)⁻¹)) : measurable f := by simpa only [inv_inv] using hf.inv @[to_additive] lemma measurable_inv_iff [group α] [topological_group α] {f : δ → α} : measurable (λ a, (f a)⁻¹) ↔ measurable f := ⟨measurable.of_inv, measurable.inv⟩ lemma measurable.sub [add_group α] [topological_add_group α] [second_countable_topology α] {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λ x, f x - g x) := hf.add hg.neg lemma measurable.is_lub [linear_order α] [order_topology α] [second_countable_topology α] {ι} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_lub {a | ∃ i, f i b = a} (g b)) : measurable g := begin change ∀ b, is_lub (range $ λ i, f i b) (g b) at hg, rw [‹borel_space α›.measurable_eq, borel_eq_generate_Ioi α], apply measurable_generate_from, rintro _ ⟨a, rfl⟩, simp only [set.preimage, mem_Ioi, lt_is_lub_iff (hg _), exists_range_iff, set_of_exists], exact is_measurable.Union (λ i, hf i _ (is_open_lt' _).is_measurable) end lemma measurable.is_glb [linear_order α] [order_topology α] [second_countable_topology α] {ι} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_glb {a | ∃ i, f i b = a} (g b)) : measurable g := begin change ∀ b, is_glb (range $ λ i, f i b) (g b) at hg, rw [‹borel_space α›.measurable_eq, borel_eq_generate_Iio α], apply measurable_generate_from, rintro _ ⟨a, rfl⟩, simp only [set.preimage, mem_Iio, is_glb_lt_iff (hg _), exists_range_iff, set_of_exists], exact is_measurable.Union (λ i, hf i _ (is_open_gt' _).is_measurable) end lemma measurable_supr [complete_linear_order α] [order_topology α] [second_countable_topology α] {ι} [encodable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i, f i b) := measurable.is_lub hf $ λ b, is_lub_supr lemma measurable_infi [complete_linear_order α] [order_topology α] [second_countable_topology α] {ι} [encodable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i, f i b) := measurable.is_glb hf $ λ b, is_glb_infi lemma measurable.supr_Prop {α} [measurable_space α] [complete_lattice α] (p : Prop) {f : δ → α} (hf : measurable f) : measurable (λ b, ⨆ h : p, f b) := classical.by_cases (assume h : p, begin convert hf, funext, exact supr_pos h end) (assume h : ¬p, begin convert measurable_const, funext, exact supr_neg h end) lemma measurable.infi_Prop {α} [measurable_space α] [complete_lattice α] (p : Prop) {f : δ → α} (hf : measurable f) : measurable (λ b, ⨅ h : p, f b) := classical.by_cases (assume h : p, begin convert hf, funext, exact infi_pos h end ) (assume h : ¬p, begin convert measurable_const, funext, exact infi_neg h end) lemma measurable_bsupr [complete_linear_order α] [order_topology α] [second_countable_topology α] {ι} [encodable ι] (p : ι → Prop) {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i (hi : p i), f i b) := measurable_supr $ λ i, (hf i).supr_Prop (p i) lemma measurable_binfi [complete_linear_order α] [order_topology α] [second_countable_topology α] {ι} [encodable ι] (p : ι → Prop) {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i (hi : p i), f i b) := measurable_infi $ λ i, (hf i).infi_Prop (p i) /-- Convert a `homeomorph` to a `measurable_equiv`. -/ def homemorph.to_measurable_equiv (h : α ≃ₜ β) : measurable_equiv α β := { to_equiv := h.to_equiv, measurable_to_fun := h.continuous_to_fun.measurable, measurable_inv_fun := h.continuous_inv_fun.measurable } end borel_space instance empty.borel_space : borel_space empty := ⟨borel_eq_top_of_discrete.symm⟩ instance unit.borel_space : borel_space unit := ⟨borel_eq_top_of_discrete.symm⟩ instance bool.borel_space : borel_space bool := ⟨borel_eq_top_of_discrete.symm⟩ instance nat.borel_space : borel_space ℕ := ⟨borel_eq_top_of_discrete.symm⟩ instance int.borel_space : borel_space ℤ := ⟨borel_eq_top_of_discrete.symm⟩ instance rat.borel_space : borel_space ℚ := ⟨borel_eq_top_of_encodable.symm⟩ instance real.measurable_space : measurable_space ℝ := borel ℝ instance real.borel_space : borel_space ℝ := ⟨rfl⟩ instance nnreal.measurable_space : measurable_space nnreal := borel nnreal instance nnreal.borel_space : borel_space nnreal := ⟨rfl⟩ instance ennreal.measurable_space : measurable_space ennreal := borel ennreal instance ennreal.borel_space : borel_space ennreal := ⟨rfl⟩ section metric_space variables [metric_space α] [measurable_space α] [opens_measurable_space α] {x : α} {ε : ℝ} lemma is_measurable_ball : is_measurable (metric.ball x ε) := metric.is_open_ball.is_measurable lemma is_measurable_closed_ball : is_measurable (metric.closed_ball x ε) := metric.is_closed_ball.is_measurable lemma measurable_dist [second_countable_topology α] : measurable (λp:α×α, dist p.1 p.2) := continuous_dist.measurable lemma measurable.dist [second_countable_topology α] [measurable_space β] {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, dist (f b) (g b)) := continuous_dist.measurable2 hf hg lemma measurable_nndist [second_countable_topology α] : measurable (λp:α×α, nndist p.1 p.2) := continuous_nndist.measurable lemma measurable.nndist [second_countable_topology α] [measurable_space β] {f g : β → α} : measurable f → measurable g → measurable (λ b, nndist (f b) (g b)) := continuous_nndist.measurable2 end metric_space section emetric_space variables [emetric_space α] [measurable_space α] [opens_measurable_space α] {x : α} {ε : ennreal} lemma is_measurable_eball : is_measurable (emetric.ball x ε) := emetric.is_open_ball.is_measurable lemma measurable_edist [second_countable_topology α] : measurable (λp:α×α, edist p.1 p.2) := continuous_edist.measurable lemma measurable.edist [second_countable_topology α] [measurable_space β] {f g : β → α} : measurable f → measurable g → measurable (λ b, edist (f b) (g b)) := continuous_edist.measurable2 end emetric_space namespace real open measurable_space lemma borel_eq_generate_from_Ioo_rat : borel ℝ = generate_from (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := borel_eq_generate_from_of_subbasis is_topological_basis_Ioo_rat.2.2 lemma borel_eq_generate_from_Iio_rat : borel ℝ = generate_from (⋃a:ℚ, {Iio a}) := begin let g, swap, apply le_antisymm (_ : _ ≤ g) (measurable_space.generate_from_le (λ t, _)), { rw borel_eq_generate_from_Ioo_rat, refine generate_from_le (λ t, _), simp only [mem_Union], rintro ⟨a, b, h, H⟩, rw [mem_singleton_iff.1 H], rw (set.ext (λ x, _) : Ioo (a:ℝ) b = (⋃c>a, - Iio c) ∩ Iio b), { have hg : ∀q:ℚ, g.is_measurable (Iio q) := λ q, generate_measurable.basic _ (by simp; exact ⟨_, rfl⟩), refine @is_measurable.inter _ g _ _ _ (hg _), refine @is_measurable.bUnion _ _ g _ _ (countable_encodable _) (λ c h, _), exact @is_measurable.compl _ _ g (hg _) }, { simp [Ioo, Iio], refine and_congr _ iff.rfl, exact ⟨λ h, let ⟨c, ac, cx⟩ := exists_rat_btwn h in ⟨c, rat.cast_lt.1 ac, le_of_lt cx⟩, λ ⟨c, ac, cx⟩, lt_of_lt_of_le (rat.cast_lt.2 ac) cx⟩ } }, { simp, rintro r rfl, exact is_open_Iio.is_measurable } end end real lemma measurable.sub_nnreal [measurable_space α] {f g : α → nnreal} : measurable f → measurable g → measurable (λ a, f a - g a) := nnreal.continuous_sub.measurable2 lemma measurable.nnreal_of_real [measurable_space α] {f : α → ℝ} (hf : measurable f) : measurable (λ x, nnreal.of_real (f x)) := nnreal.continuous_of_real.measurable.comp hf lemma measurable.nnreal_coe [measurable_space α] {f : α → nnreal} (hf : measurable f) : measurable (λ x, (f x : ℝ)) := nnreal.continuous_coe.measurable.comp hf lemma measurable.ennreal_coe [measurable_space α] {f : α → nnreal} (hf : measurable f) : measurable (λ x, (f x : ennreal)) := (ennreal.continuous_coe.2 continuous_id).measurable.comp hf lemma measurable.ennreal_of_real [measurable_space α] {f : α → ℝ} (hf : measurable f) : measurable (λ x, ennreal.of_real (f x)) := ennreal.continuous_of_real.measurable.comp hf /-- The set of finite `ennreal` numbers is `measurable_equiv` to `nnreal`. -/ def measurable_equiv.ennreal_equiv_nnreal : measurable_equiv {r : ennreal | r ≠ ⊤} nnreal := ennreal.ne_top_homeomorph_nnreal.to_measurable_equiv namespace ennreal open filter lemma measurable_coe : measurable (coe : nnreal → ennreal) := measurable_id.ennreal_coe lemma measurable_of_measurable_nnreal [measurable_space α] {f : ennreal → α} (h : measurable (λp:nnreal, f p)) : measurable f := measurable_of_measurable_on_compl_singleton ⊤ is_measurable_singleton (measurable_equiv.ennreal_equiv_nnreal.symm.measurable_coe_iff.1 h) /-- `ennreal` is `measurable_equiv` to `nnreal ⊕ unit`. -/ def ennreal_equiv_sum : measurable_equiv ennreal (nnreal ⊕ unit) := { measurable_to_fun := measurable_of_measurable_nnreal measurable_inl, measurable_inv_fun := measurable_sum measurable_coe (@measurable_const ennreal unit _ _ ⊤), .. equiv.option_equiv_sum_punit nnreal } lemma measurable_of_measurable_nnreal_nnreal [measurable_space α] [measurable_space β] (f : ennreal → ennreal → β) {g : α → ennreal} {h : α → ennreal} (h₁ : measurable (λp:nnreal × nnreal, f p.1 p.2)) (h₂ : measurable (λr:nnreal, f ⊤ r)) (h₃ : measurable (λr:nnreal, f r ⊤)) (hg : measurable g) (hh : measurable h) : measurable (λa, f (g a) (h a)) := let e : measurable_equiv (ennreal × ennreal) (((nnreal × nnreal) ⊕ (nnreal × unit)) ⊕ ((unit × nnreal) ⊕ (unit × unit))) := (measurable_equiv.prod_congr ennreal_equiv_sum ennreal_equiv_sum).trans (measurable_equiv.sum_prod_sum _ _ _ _) in have measurable (λp:ennreal×ennreal, f p.1 p.2), begin refine e.symm.measurable_coe_iff.1 (measurable_sum (measurable_sum _ _) (measurable_sum _ _)), { show measurable (λp:nnreal × nnreal, f p.1 p.2), exact h₁ }, { show measurable (λp:nnreal × unit, f p.1 ⊤), exact h₃.comp (measurable.fst measurable_id) }, { show measurable ((λp:nnreal, f ⊤ p) ∘ (λp:unit × nnreal, p.2)), exact h₂.comp (measurable.snd measurable_id) }, { show measurable (λp:unit × unit, f ⊤ ⊤), exact measurable_const } end, this.comp (measurable.prod_mk hg hh) lemma measurable_of_real : measurable ennreal.of_real := ennreal.continuous_of_real.measurable end ennreal lemma measurable.ennreal_mul {α : Type*} [measurable_space α] {f g : α → ennreal} : measurable f → measurable g → measurable (λa, f a * g a) := begin refine ennreal.measurable_of_measurable_nnreal_nnreal (*) _ _ _, { simp only [ennreal.coe_mul.symm], exact ennreal.measurable_coe.comp measurable_mul }, { simp [ennreal.top_mul], exact measurable.if (is_closed_eq continuous_id continuous_const).is_measurable measurable_const measurable_const }, { simp [ennreal.mul_top], exact measurable.if (is_closed_eq continuous_id continuous_const).is_measurable measurable_const measurable_const } end lemma measurable.ennreal_add {α : Type*} [measurable_space α] {f g : α → ennreal} : measurable f → measurable g → measurable (λa, f a + g a) := begin refine ennreal.measurable_of_measurable_nnreal_nnreal (+) _ _ _, { simp only [ennreal.coe_add.symm], exact ennreal.measurable_coe.comp measurable_add }, { simp [measurable_const] }, { simp [measurable_const] } end lemma measurable.ennreal_sub {α : Type*} [measurable_space α] {f g : α → ennreal} : measurable f → measurable g → measurable (λa, f a - g a) := begin refine ennreal.measurable_of_measurable_nnreal_nnreal (has_sub.sub) _ _ _, { simp only [ennreal.coe_sub.symm], exact ennreal.measurable_coe.comp nnreal.continuous_sub.measurable }, { simp [measurable_const] }, { simp [measurable_const] } end section normed_group variables [measurable_space α] [normed_group α] [opens_measurable_space α] [measurable_space β] lemma measurable_norm : measurable (norm : α → ℝ) := continuous_norm.measurable lemma measurable.norm {f : β → α} (hf : measurable f) : measurable (λa, norm (f a)) := measurable_norm.comp hf lemma measurable_nnnorm : measurable (nnnorm : α → nnreal) := continuous_nnnorm.measurable lemma measurable.nnnorm {f : β → α} (hf : measurable f) : measurable (λa, nnnorm (f a)) := measurable_nnnorm.comp hf lemma measurable.ennnorm {f : β → α} (hf : measurable f) : measurable (λa, (nnnorm (f a) : ennreal)) := hf.nnnorm.ennreal_coe end normed_group
7769a981c2f9655dd9ed32a30b4216fbbae4a9cd
f5a711bc61b4fe426425fc39edfb9aa84b06f644
/library/init/meta/tactic.lean
81fb6720285397b71d6aa74c8f5e1398bd541173
[ "Apache-2.0" ]
permissive
ChrisHughes24/lean
89697c262783aa4fc1e3cc9bd7adf16d049e2be0
8ba2c1a8b4b9edd11c96482356b47df8322b3785
refs/heads/master
1,610,100,259,751
1,582,175,143,000
1,582,175,143,000
241,995,683
0
0
Apache-2.0
1,582,234,740,000
1,582,234,739,000
null
UTF-8
Lean
false
false
62,093
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.function init.data.option.basic init.util import init.category.combinators init.category.monad init.category.alternative init.category.monad_fail import init.data.nat.div init.meta.exceptional init.meta.format init.meta.environment import init.meta.pexpr init.data.repr init.data.string.basic init.meta.interaction_monad meta constant tactic_state : Type universes u v namespace tactic_state meta constant env : tactic_state → environment /-- Format the given tactic state. If `target_lhs_only` is true and the target is of the form `lhs ~ rhs`, where `~` is a simplification relation, then only the `lhs` is displayed. Remark: the parameter `target_lhs_only` is a temporary hack used to implement the `conv` monad. It will be removed in the future. -/ meta constant to_format (s : tactic_state) (target_lhs_only : bool := ff) : format /-- Format expression with respect to the main goal in the tactic state. If the tactic state does not contain any goals, then format expression using an empty local context. -/ meta constant format_expr : tactic_state → expr → format meta constant get_options : tactic_state → options meta constant set_options : tactic_state → options → tactic_state end tactic_state meta instance : has_to_format tactic_state := ⟨tactic_state.to_format⟩ meta instance : has_to_string tactic_state := ⟨λ s, (to_fmt s).to_string s.get_options⟩ /-- `tactic` is the monad for building tactics. You use this to: - View and modify the local goals and hypotheses in the prover's state. - Invoke type checking and elaboration of terms. - View and modify the environment. - Build new tactics out of existing ones such as `simp` and `rewrite`. -/ @[reducible] meta def tactic := interaction_monad tactic_state @[reducible] meta def tactic_result := interaction_monad.result tactic_state namespace tactic export interaction_monad (hiding failed fail) /-- Cause the tactic to fail with no error message. -/ meta def failed {α : Type} : tactic α := interaction_monad.failed meta def fail {α : Type u} {β : Type v} [has_to_format β] (msg : β) : tactic α := interaction_monad.fail msg end tactic namespace tactic_result export interaction_monad.result end tactic_result open tactic open tactic_result infixl ` >>=[tactic] `:2 := interaction_monad_bind infixl ` >>[tactic] `:2 := interaction_monad_seq meta instance : alternative tactic := { failure := @interaction_monad.failed _, orelse := @interaction_monad_orelse _, ..interaction_monad.monad } meta def {u₁ u₂} tactic.up {α : Type u₂} (t : tactic α) : tactic (ulift.{u₁} α) := λ s, match t s with | success a s' := success (ulift.up a) s' | exception t ref s := exception t ref s end meta def {u₁ u₂} tactic.down {α : Type u₂} (t : tactic (ulift.{u₁} α)) : tactic α := λ s, match t s with | success (ulift.up a) s' := success a s' | exception t ref s := exception t ref s end namespace interactive /-- Typeclass for custom interaction monads, which provides the information required to convert an interactive-mode construction to a `tactic` which can actually be executed. Given a `[monad m]`, `execute_with` explains how to turn a `begin ... end` block, or a `by ...` statement into a `tactic α` which can actually be executed. The `inhabited` first argument facilitates the passing of an optional configuration parameter `config`, using the syntax: ``` begin [custom_monad] with config, ... end ``` -/ meta class executor (m : Type → Type u) [monad m] := (config_type : Type) [inhabited : inhabited config_type] (execute_with : config_type → m unit → tactic unit) attribute [inline] executor.execute_with @[inline] meta def executor.execute_explicit (m : Type → Type u) [monad m] [e : executor m] : m unit → tactic unit := executor.execute_with e.inhabited.default @[inline] meta def executor.execute_with_explicit (m : Type → Type u) [monad m] [executor m] : executor.config_type m → m unit → tactic unit := executor.execute_with /-- Default `executor` instance for `tactic`s themselves -/ meta instance : executor tactic := { config_type := unit, inhabited := ⟨()⟩, execute_with := λ _, id } end interactive namespace tactic variables {α : Type u} meta def try_core (t : tactic α) : tactic (option α) := λ s, result.cases_on (t s) (λ a, success (some a)) (λ e ref s', success none s) /-- Does nothing. -/ meta def skip : tactic unit := success () meta def try (t : tactic α) : tactic unit := try_core t >>[tactic] skip meta def try_lst : list (tactic unit) → tactic unit | [] := failed | (tac :: tacs) := λ s, match tac s with | result.success _ s' := try (try_lst tacs) s' | result.exception e p s' := match try_lst tacs s' with | result.exception _ _ _ := result.exception e p s' | r := r end end meta def fail_if_success {α : Type u} (t : tactic α) : tactic unit := λ s, result.cases_on (t s) (λ a s, mk_exception "fail_if_success combinator failed, given tactic succeeded" none s) (λ e ref s', success () s) meta def success_if_fail {α : Type u} (t : tactic α) : tactic unit := λ s, match t s with | (interaction_monad.result.exception _ _ s') := success () s | (interaction_monad.result.success a s) := mk_exception "success_if_fail combinator failed, given tactic succeeded" none s end open nat /-- (iterate_at_most n t): repeat the given tactic at most n times or until t fails -/ meta def iterate_at_most : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := (do t, iterate_at_most n t) <|> skip /-- (iterate_exactly n t) : execute t n times -/ meta def iterate_exactly : nat → tactic unit → tactic unit | 0 t := skip | (succ n) t := do t, iterate_exactly n t /-- Repeat the given tactic forever. -/ meta def iterate : tactic unit → tactic unit := iterate_at_most 100000 meta def returnopt (e : option α) : tactic α := λ s, match e with | (some a) := success a s | none := mk_exception "failed" none s end meta instance opt_to_tac : has_coe (option α) (tactic α) := ⟨returnopt⟩ /-- Decorate t's exceptions with msg. -/ meta def decorate_ex (msg : format) (t : tactic α) : tactic α := λ s, result.cases_on (t s) success (λ opt_thunk, match opt_thunk with | some e := exception (some (λ u, msg ++ format.nest 2 (format.line ++ e u))) | none := exception none end) /-- Set the tactic_state. -/ @[inline] meta def write (s' : tactic_state) : tactic unit := λ s, success () s' /-- Get the tactic_state. -/ @[inline] meta def read : tactic tactic_state := λ s, success s s meta def get_options : tactic options := do s ← read, return s.get_options meta def set_options (o : options) : tactic unit := do s ← read, write (s.set_options o) meta def save_options {α : Type} (t : tactic α) : tactic α := do o ← get_options, a ← t, set_options o, return a meta def returnex {α : Type} (e : exceptional α) : tactic α := λ s, match e with | exceptional.success a := success a s | exceptional.exception ._ f := match get_options s with | success opt _ := exception (some (λ u, f opt)) none s | exception _ _ _ := exception (some (λ u, f options.mk)) none s end end meta instance ex_to_tac {α : Type} : has_coe (exceptional α) (tactic α) := ⟨returnex⟩ end tactic meta def tactic_format_expr (e : expr) : tactic format := do s ← tactic.read, return (tactic_state.format_expr s e) meta class has_to_tactic_format (α : Type u) := (to_tactic_format : α → tactic format) meta instance : has_to_tactic_format expr := ⟨tactic_format_expr⟩ meta def tactic.pp {α : Type u} [has_to_tactic_format α] : α → tactic format := has_to_tactic_format.to_tactic_format open tactic format meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (list α) := ⟨λ l, to_fmt <$> l.mmap pp⟩ meta instance (α : Type u) (β : Type v) [has_to_tactic_format α] [has_to_tactic_format β] : has_to_tactic_format (α × β) := ⟨λ ⟨a, b⟩, to_fmt <$> (prod.mk <$> pp a <*> pp b)⟩ meta def option_to_tactic_format {α : Type u} [has_to_tactic_format α] : option α → tactic format | (some a) := do fa ← pp a, return (to_fmt "(some " ++ fa ++ ")") | none := return "none" meta instance {α : Type u} [has_to_tactic_format α] : has_to_tactic_format (option α) := ⟨option_to_tactic_format⟩ meta instance {α} (a : α) : has_to_tactic_format (reflected a) := ⟨λ h, pp h.to_expr⟩ @[priority 10] meta instance has_to_format_to_has_to_tactic_format (α : Type) [has_to_format α] : has_to_tactic_format α := ⟨(λ x, return x) ∘ to_fmt⟩ namespace tactic open tactic_state meta def get_env : tactic environment := do s ← read, return $ env s meta def get_decl (n : name) : tactic declaration := do s ← read, (env s).get n meta def trace {α : Type u} [has_to_tactic_format α] (a : α) : tactic unit := do fmt ← pp a, return $ _root_.trace_fmt fmt (λ u, ()) meta def trace_call_stack : tactic unit := assume state, _root_.trace_call_stack (success () state) meta def timetac {α : Type u} (desc : string) (t : thunk (tactic α)) : tactic α := λ s, timeit desc (t () s) meta def trace_state : tactic unit := do s ← read, trace $ to_fmt s /-- A parameter representing how aggressively definitions should be unfolded when trying to decide if two terms match, unify or are definitionally equal. By default, theorem declarations are never unfolded. - `all` will unfold everything, including macros and theorems. Except projection macros. - `semireducible` will unfold everything except theorems and definitions tagged as irreducible. - `instances` will unfold all class instance definitions and definitions tagged with reducible. - `reducible` will only unfold definitions tagged with the `reducible` attribute. - `none` will never unfold anything. [NOTE] You are not allowed to tag a definition with more than one of `reducible`, `irreducible`, `semireducible` attributes. [NOTE] there is a config flag `m_unfold_lemmas`that will make it unfold theorems. -/ inductive transparency | all | semireducible | instances | reducible | none export transparency (reducible semireducible) /-- (eval_expr α e) evaluates 'e' IF 'e' has type 'α'. -/ meta constant eval_expr (α : Type u) [reflected α] : expr → tactic α /-- Return the partial term/proof constructed so far. Note that the resultant expression may contain variables that are not declarate in the current main goal. -/ meta constant result : tactic expr /-- Display the partial term/proof constructed so far. This tactic is *not* equivalent to `do { r ← result, s ← read, return (format_expr s r) }` because this one will format the result with respect to the current goal, and trace_result will do it with respect to the initial goal. -/ meta constant format_result : tactic format /-- Return target type of the main goal. Fail if tactic_state does not have any goal left. -/ meta constant target : tactic expr meta constant intro_core : name → tactic expr meta constant intron : nat → tactic unit /-- Clear the given local constant. The tactic fails if the given expression is not a local constant. -/ meta constant clear : expr → tactic unit /-- `revert_lst : list expr → tactic nat` is the reverse of `intron`. It takes a local constant `c` and puts it back as bound by a `pi` or `elet` of the main target. If there are other local constants that depend on `c`, these are also reverted. Because of this, the `nat` that is returned is the actual number of reverted local constants. Example: with `x : ℕ, h : P(x) ⊢ T(x)`, `revert_lst [x]` returns `2` and produces the state ` ⊢ Π x, P(x) → T(x)`. -/ meta constant revert_lst : list expr → tactic nat /-- Return `e` in weak head normal form with respect to the given transparency setting. If `unfold_ginductive` is `tt`, then nested and/or mutually recursive inductive datatype constructors and types are unfolded. Recall that nested and mutually recursive inductive datatype declarations are compiled into primitive datatypes accepted by the Kernel. -/ meta constant whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic expr /-- (head) eta expand the given expression. `f : α → β` head-eta-expands to `λ a, f a`. If `f` isn't a function then it just returns `f`. -/ meta constant head_eta_expand : expr → tactic expr /-- (head) beta reduction. `(λ x, B) c` reduces to `B[x/c]`. -/ meta constant head_beta : expr → tactic expr /-- (head) zeta reduction. Reduction of let bindings at the head of the expression. `let x : a := b in c` reduces to `c[x/b]`. -/ meta constant head_zeta : expr → tactic expr /-- Zeta reduction. Reduction of let bindings. `let x : a := b in c` reduces to `c[x/b]`. -/ meta constant zeta : expr → tactic expr /-- (head) eta reduction. `(λ x, f x)` reduces to `f`. -/ meta constant head_eta : expr → tactic expr /-- Succeeds if `t` and `s` can be unified using the given transparency setting. -/ meta constant unify (t s : expr) (md := semireducible) (approx := ff) : tactic unit /-- Similar to `unify`, but it treats metavariables as constants. -/ meta constant is_def_eq (t s : expr) (md := semireducible) (approx := ff) : tactic unit /-- Infer the type of the given expression. Remark: transparency does not affect type inference -/ meta constant infer_type : expr → tactic expr /-- Get the `local_const` expr for the given `name`. -/ meta constant get_local : name → tactic expr /-- Resolve a name using the current local context, environment, aliases, etc. -/ meta constant resolve_name : name → tactic pexpr /-- Return the hypothesis in the main goal. Fail if tactic_state does not have any goal left. -/ meta constant local_context : tactic (list expr) /-- Get a fresh name that is guaranteed to not be in use in the local context. If `n` is provided and `n` is not in use, then `n` is returned. Otherwise a number `i` is appended to give `"n_i"`. -/ meta constant get_unused_name (n : name := `_x) (i : option nat := none) : tactic name /-- Helper tactic for creating simple applications where some arguments are inferred using type inference. Example, given ``` rel.{l_1 l_2} : Pi (α : Type.{l_1}) (β : α -> Type.{l_2}), (Pi x : α, β x) -> (Pi x : α, β x) -> , Prop nat : Type real : Type vec.{l} : Pi (α : Type l) (n : nat), Type.{l1} f g : Pi (n : nat), vec real n ``` then ``` mk_app_core semireducible "rel" [f, g] ``` returns the application ``` rel.{1 2} nat (fun n : nat, vec real n) f g ``` The unification constraints due to type inference are solved using the transparency `md`. -/ meta constant mk_app (fn : name) (args : list expr) (md := semireducible) : tactic expr /-- Similar to `mk_app`, but allows to specify which arguments are explicit/implicit. Example, given `(a b : nat)` then ``` mk_mapp "ite" [some (a > b), none, none, some a, some b] ``` returns the application ``` @ite.{1} (a > b) (nat.decidable_gt a b) nat a b ``` -/ meta constant mk_mapp (fn : name) (args : list (option expr)) (md := semireducible) : tactic expr /-- (mk_congr_arg h₁ h₂) is a more efficient version of (mk_app `congr_arg [h₁, h₂]) -/ meta constant mk_congr_arg : expr → expr → tactic expr /-- (mk_congr_fun h₁ h₂) is a more efficient version of (mk_app `congr_fun [h₁, h₂]) -/ meta constant mk_congr_fun : expr → expr → tactic expr /-- (mk_congr h₁ h₂) is a more efficient version of (mk_app `congr [h₁, h₂]) -/ meta constant mk_congr : expr → expr → tactic expr /-- (mk_eq_refl h) is a more efficient version of (mk_app `eq.refl [h]) -/ meta constant mk_eq_refl : expr → tactic expr /-- (mk_eq_symm h) is a more efficient version of (mk_app `eq.symm [h]) -/ meta constant mk_eq_symm : expr → tactic expr /-- (mk_eq_trans h₁ h₂) is a more efficient version of (mk_app `eq.trans [h₁, h₂]) -/ meta constant mk_eq_trans : expr → expr → tactic expr /-- (mk_eq_mp h₁ h₂) is a more efficient version of (mk_app `eq.mp [h₁, h₂]) -/ meta constant mk_eq_mp : expr → expr → tactic expr /-- (mk_eq_mpr h₁ h₂) is a more efficient version of (mk_app `eq.mpr [h₁, h₂]) -/ meta constant mk_eq_mpr : expr → expr → tactic expr /- Given a local constant t, if t has type (lhs = rhs) apply substitution. Otherwise, try to find a local constant that has type of the form (t = t') or (t' = t). The tactic fails if the given expression is not a local constant. -/ meta constant subst_core : expr → tactic unit /-- Close the current goal using `e`. Fail is the type of `e` is not definitionally equal to the target type. -/ meta constant exact (e : expr) (md := semireducible) : tactic unit /-- Elaborate the given quoted expression with respect to the current main goal. Note that this means that any implicit arguments for the given `pexpr` will be applied with fresh metavariables. If `allow_mvars` is tt, then metavariables are tolerated and become new goals if `subgoals` is tt. -/ meta constant to_expr (q : pexpr) (allow_mvars := tt) (subgoals := tt) : tactic expr /-- Return true if the given expression is a type class. -/ meta constant is_class : expr → tactic bool /-- Try to create an instance of the given type class. -/ meta constant mk_instance : expr → tactic expr /-- Change the target of the main goal. The input expression must be definitionally equal to the current target. If `check` is `ff`, then the tactic does not check whether `e` is definitionally equal to the current target. If it is not, then the error will only be detected by the kernel type checker. -/ meta constant change (e : expr) (check : bool := tt): tactic unit /-- `assert_core H T`, adds a new goal for T, and change target to `T -> target`. -/ meta constant assert_core : name → expr → tactic unit /-- `assertv_core H T P`, change target to (T -> target) if P has type T. -/ meta constant assertv_core : name → expr → expr → tactic unit /-- `define_core H T`, adds a new goal for T, and change target to `let H : T := ?M in target` in the current goal. -/ meta constant define_core : name → expr → tactic unit /-- `definev_core H T P`, change target to `let H : T := P in target` if P has type T. -/ meta constant definev_core : name → expr → expr → tactic unit /-- Rotate goals to the left. That is, `rotate_left 1` takes the main goal and puts it to the back of the subgoal list. -/ meta constant rotate_left : nat → tactic unit /-- Gets a list of metavariables, one for each goal. -/ meta constant get_goals : tactic (list expr) /-- Replace the current list of goals with the given one. Each expr in the list should be a metavariable. Any assigned metavariables will be ignored.-/ meta constant set_goals : list expr → tactic unit /-- How to order the new goals made from an `apply` tactic. Supposing we were applying `e : ∀ (a:α) (p : P(a)), Q` - `non_dep_first` would produce goals `⊢ P(?m)`, `⊢ α`. It puts the P goal at the front because none of the arguments after `p` in `e` depend on `p`. It doesn't matter what the result `Q` depends on. - `non_dep_only` would produce goal `⊢ P(?m)`. - `all` would produce goals `⊢ α`, `⊢ P(?m)`. -/ inductive new_goals | non_dep_first | non_dep_only | all /-- Configuration options for the `apply` tactic. - `md` sets how aggressively definitions are unfolded. - `new_goals` is the strategy for ordering new goals. - `instances` if `tt`, then `apply` tries to synthesize unresolved `[...]` arguments using type class resolution. - `auto_param` if `tt`, then `apply` tries to synthesize unresolved `(h : p . tac_id)` arguments using tactic `tac_id`. - `opt_param` if `tt`, then `apply` tries to synthesize unresolved `(a : t := v)` arguments by setting them to `v`. - `unify` if `tt`, then `apply` is free to assign existing metavariables in the goal when solving unification constraints. For example, in the goal `|- ?x < succ 0`, the tactic `apply succ_lt_succ` succeeds with the default configuration, but `apply_with succ_lt_succ {unify := ff}` doesn't since it would require Lean to assign `?x` to `succ ?y` where `?y` is a fresh metavariable. -/ structure apply_cfg := (md := semireducible) (approx := tt) (new_goals := new_goals.non_dep_first) (instances := tt) (auto_param := tt) (opt_param := tt) (unify := tt) /-- Apply the expression `e` to the main goal, the unification is performed using the transparency mode in `cfg`. Supposing `e : Π (a₁:α₁) ... (aₙ:αₙ), P(a₁,...,aₙ)` and the target is `Q`, `apply` will attempt to unify `Q` with `P(?a₁,...?aₙ)`. All of the metavariables that are not assigned are added as new metavariables. If `cfg.approx` is `tt`, then fallback to first-order unification, and approximate context during unification. `cfg.new_goals` specifies which unassigned metavariables become new goals, and their order. If `cfg.instances` is `tt`, then use type class resolution to instantiate unassigned meta-variables. The fields `cfg.auto_param` and `cfg.opt_param` are ignored by this tactic (See `tactic.apply`). It returns a list of all introduced meta variables and the parameter name associated with them, even the assigned ones. -/ meta constant apply_core (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) /- Create a fresh meta universe variable. -/ meta constant mk_meta_univ : tactic level /- Create a fresh meta-variable with the given type. The scope of the new meta-variable is the local context of the main goal. -/ meta constant mk_meta_var : expr → tactic expr /-- Return the value assigned to the given universe meta-variable. Fail if argument is not an universe meta-variable or if it is not assigned. -/ meta constant get_univ_assignment : level → tactic level /-- Return the value assigned to the given meta-variable. Fail if argument is not a meta-variable or if it is not assigned. -/ meta constant get_assignment : expr → tactic expr /-- Return true if the given meta-variable is assigned. Fail if argument is not a meta-variable. -/ meta constant is_assigned : expr → tactic bool /-- Make a name that is guaranteed to be unique. Eg `_fresh.1001.4667`. These will be different for each run of the tactic. -/ meta constant mk_fresh_name : tactic name /-- Induction on `h` using recursor `rec`, names for the new hypotheses are retrieved from `ns`. If `ns` does not have sufficient names, then use the internal binder names in the recursor. It returns for each new goal the name of the constructor (if `rec_name` is a builtin recursor), a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The substitutions map internal names to their replacement terms. If the replacement is again a hypothesis the user name stays the same. The internal names are only valid in the original goal, not in the type context of the new goal. Remark: if `rec_name` is not a builtin recursor, we use parameter names of `rec_name` instead of constructor names. If `rec` is none, then the type of `h` is inferred, if it is of the form `C ...`, tactic uses `C.rec` -/ meta constant induction (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic (list (name × list expr × list (name × expr))) /-- Apply `cases_on` recursor, names for the new hypotheses are retrieved from `ns`. `h` must be a local constant. It returns for each new goal the name of the constructor, a list of new hypotheses, and a list of substitutions for hypotheses depending on `h`. The number of new goals may be smaller than the number of constructors. Some goals may be discarded when the indices to not match. See `induction` for information on the list of substitutions. The `cases` tactic is implemented using this one, and it relaxes the restriction of `h`. -/ meta constant cases_core (h : expr) (ns : list name := []) (md := semireducible) : tactic (list (name × list expr × list (name × expr))) /-- Similar to cases tactic, but does not revert/intro/clear hypotheses. -/ meta constant destruct (e : expr) (md := semireducible) : tactic unit /-- Generalizes the target with respect to `e`. -/ meta constant generalize (e : expr) (n : name := `_x) (md := semireducible) : tactic unit /-- instantiate assigned metavariables in the given expression -/ meta constant instantiate_mvars : expr → tactic expr /-- Add the given declaration to the environment -/ meta constant add_decl : declaration → tactic unit /-- Changes the environment to the `new_env`. The new environment does not need to be a descendant of the old one. Use with care. -/ meta constant set_env_core : environment → tactic unit /-- Changes the environment to the `new_env`. `new_env` needs to be a descendant from the current environment. -/ meta constant set_env : environment → tactic unit /-- `doc_string env d k` returns the doc string for `d` (if available) -/ meta constant doc_string : name → tactic string /-- Set the docstring for the given declaration. -/ meta constant add_doc_string : name → string → tactic unit /-- Create an auxiliary definition with name `c` where `type` and `value` may contain local constants and meta-variables. This function collects all dependencies (universe parameters, universe metavariables, local constants (aka hypotheses) and metavariables). It updates the environment in the tactic_state, and returns an expression of the form (c.{l_1 ... l_n} a_1 ... a_m) where l_i's and a_j's are the collected dependencies. -/ meta constant add_aux_decl (c : name) (type : expr) (val : expr) (is_lemma : bool) : tactic expr /-- Returns a list of all top-level (`/-! ... -/`) docstrings in the active module and imported ones. The returned object is a list of modules, indexed by `(some filename)` for imported modules and `none` for the active one, where each module in the list is paired with a list of `(position_in_file, docstring)` pairs. -/ meta constant olean_doc_strings : tactic (list (option string × (list (pos × string)))) /-- Returns a list of docstrings in the active module. An entry in the list can be either: - a top-level (`/-! ... -/`) docstring, represented as `(none, docstring)` - a declaration-specific (`/-- ... -/`) docstring, represented as `(some decl_name, docstring)` -/ meta def module_doc_strings : tactic (list (option name × string)) := do /- Obtain a list of top-level docs in current module. -/ mod_docs ← olean_doc_strings, let mod_docs: list (list (option name × string)) := mod_docs.filter_map (λ d, if d.1.is_none then some (d.2.map (λ pos_doc, ⟨none, pos_doc.2⟩)) else none), let mod_docs := mod_docs.join, /- Obtain list of declarations in current module. -/ e ← get_env, let decls := environment.fold e ([]: list name) (λ d acc, let n := d.to_name in if (environment.decl_olean e n).is_none then n::acc else acc), /- Map declarations to those which have docstrings. -/ decls ← decls.mfoldl (λa n, (doc_string n >>= λ doc, pure $ (some n, doc) :: a) <|> pure a) [], pure (mod_docs ++ decls) /-- Set attribute `attr_name` for constant `c_name` with the given priority. If the priority is none, then use default -/ meta constant set_basic_attribute (attr_name : name) (c_name : name) (persistent := ff) (prio : option nat := none) : tactic unit /-- `unset_attribute attr_name c_name` -/ meta constant unset_attribute : name → name → tactic unit /-- `has_attribute attr_name c_name` succeeds if the declaration `decl_name` has the attribute `attr_name`. The result is the priority. -/ meta constant has_attribute : name → name → tactic nat /-- `copy_attribute attr_name c_name d_name` copy attribute `attr_name` from `src` to `tgt` if it is defined for `src` -/ meta def copy_attribute (attr_name : name) (src : name) (p : bool) (tgt : name) : tactic unit := try $ do prio ← has_attribute attr_name src, set_basic_attribute attr_name tgt p (some prio) /-- Name of the declaration currently being elaborated. -/ meta constant decl_name : tactic name /-- `save_type_info e ref` save (typeof e) at position associated with ref -/ meta constant save_type_info {elab : bool} : expr → expr elab → tactic unit meta constant save_info_thunk : pos → (unit → format) → tactic unit /-- Return list of currently open namespaces -/ meta constant open_namespaces : tactic (list name) /-- Return tt iff `t` "occurs" in `e`. The occurrence checking is performed using keyed matching with the given transparency setting. We say `t` occurs in `e` by keyed matching iff there is a subterm `s` s.t. `t` and `s` have the same head, and `is_def_eq t s md` The main idea is to minimize the number of `is_def_eq` checks performed. -/ meta constant kdepends_on (e t : expr) (md := reducible) : tactic bool /-- Abstracts all occurrences of the term `t` in `e` using keyed matching. If `unify` is `ff`, then matching is used instead of unification. That is, metavariables occurring in `e` are not assigned. -/ meta constant kabstract (e t : expr) (md := reducible) (unify := tt) : tactic expr /-- Blocks the execution of the current thread for at least `msecs` milliseconds. This tactic is used mainly for debugging purposes. -/ meta constant sleep (msecs : nat) : tactic unit /-- Type check `e` with respect to the current goal. Fails if `e` is not type correct. -/ meta constant type_check (e : expr) (md := semireducible) : tactic unit open list nat /-- A `tag` is a list of `names`. These are attached to goals to help tactics track them.-/ def tag : Type := list name /-- Enable/disable goal tagging. -/ meta constant enable_tags (b : bool) : tactic unit /-- Return tt iff goal tagging is enabled. -/ meta constant tags_enabled : tactic bool /-- Tag goal `g` with tag `t`. It does nothing if goal tagging is disabled. Remark: `set_goal g []` removes the tag -/ meta constant set_tag (g : expr) (t : tag) : tactic unit /-- Return tag associated with `g`. Return `[]` if there is no tag. -/ meta constant get_tag (g : expr) : tactic tag /-- By default, Lean only considers local instances in the header of declarations. This has two main benefits. 1- Results produced by the type class resolution procedure can be easily cached. 2- The set of local instances does not have to be recomputed. This approach has the following disadvantages: 1- Frozen local instances cannot be reverted. 2- Local instances defined inside of a declaration are not considered during type class resolution. This tactic resets the set of local instances. After executing this tactic, the set of local instances will be recomputed and the cache will be frequently reset. Note that, the cache is still used when executing a single tactic that may generate many type class resolution problems (e.g., `simp`). -/ meta constant unfreeze_local_instances : tactic unit /- Return the list of frozen local instances. Return `none` if local instances were not frozen. -/ meta constant frozen_local_instances : tactic (option (list expr)) meta def induction' (h : expr) (ns : list name := []) (rec : option name := none) (md := semireducible) : tactic unit := induction h ns rec md >> return () /-- Remark: set_goals will erase any solved goal -/ meta def cleanup : tactic unit := get_goals >>= set_goals /-- Auxiliary definition used to implement begin ... end blocks -/ meta def step {α : Type u} (t : tactic α) : tactic unit := t >>[tactic] cleanup meta def istep {α : Type u} (line0 col0 : ℕ) (line col : ℕ) (t : tactic α) : tactic unit := λ s, (@scope_trace _ line col (λ _, step t s)).clamp_pos line0 line col meta def is_prop (e : expr) : tactic bool := do t ← infer_type e, return (t = `(Prop)) /-- Return true iff n is the name of declaration that is a proposition. -/ meta def is_prop_decl (n : name) : tactic bool := do env ← get_env, d ← env.get n, t ← return $ d.type, is_prop t meta def is_proof (e : expr) : tactic bool := infer_type e >>= is_prop meta def whnf_no_delta (e : expr) : tactic expr := whnf e transparency.none /-- Return `e` in weak head normal form with respect to the given transparency setting, or `e` head is a generalized constructor or inductive datatype. -/ meta def whnf_ginductive (e : expr) (md := semireducible) : tactic expr := whnf e md ff meta def whnf_target : tactic unit := target >>= whnf >>= change /-- Change the target of the main goal. The input expression must be definitionally equal to the current target. The tactic does not check whether `e` is definitionally equal to the current target. The error will only be detected by the kernel type checker. -/ meta def unsafe_change (e : expr) : tactic unit := change e ff /-- Pi or elet introduction. Given the tactic state `⊢ Π x : α, Y`, ``intro `hello`` will produce the state `hello : α ⊢ Y[x/hello]`. Returns the new local constant. Similarly for `elet` expressions. If the target is not a Pi or elet it will try to put it in WHNF. -/ meta def intro (n : name) : tactic expr := do t ← target, if expr.is_pi t ∨ expr.is_let t then intro_core n else whnf_target >> intro_core n /-- Like `intro` except the name is derived from the bound name in the Π. -/ meta def intro1 : tactic expr := intro `_ /-- Repeatedly apply `intro1` and return the list of new local constants in order of introduction.-/ meta def intros : tactic (list expr) := do t ← target, match t with | expr.pi _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | expr.elet _ _ _ _ := do H ← intro1, Hs ← intros, return (H :: Hs) | _ := return [] end /-- Same as `intros`, except with the given names for the new hypotheses. Use the name ```_``` to instead use the binder's name.-/ meta def intro_lst : list name → tactic (list expr) | [] := return [] | (n::ns) := do H ← intro n, Hs ← intro_lst ns, return (H :: Hs) /-- Introduces new hypotheses with forward dependencies. -/ meta def intros_dep : tactic (list expr) := do t ← target, let proc (b : expr) := if b.has_var_idx 0 then do h ← intro1, hs ← intros_dep, return (h::hs) else -- body doesn't depend on new hypothesis return [], match t with | expr.pi _ _ _ b := proc b | expr.elet _ _ _ b := proc b | _ := return [] end meta def introv : list name → tactic (list expr) | [] := intros_dep | (n::ns) := do hs ← intros_dep, h ← intro n, hs' ← introv ns, return (hs ++ h :: hs') /-- Returns n fully qualified if it refers to a constant, or else fails. -/ meta def resolve_constant (n : name) : tactic name := do (expr.const n _) ← resolve_name n, pure n meta def to_expr_strict (q : pexpr) : tactic expr := to_expr q /-- Example: with `x : ℕ, h : P(x) ⊢ T(x)`, `revert x` returns `2` and produces the state ` ⊢ Π x, P(x) → T(x)`. -/ meta def revert (l : expr) : tactic nat := revert_lst [l] /- Revert "all" hypotheses. Actually, the tactic only reverts hypotheses occurring after the last frozen local instance. Recall that frozen local instances cannot be reverted. We can use `unfreeze_local_instances` to workaround this limitation. -/ meta def revert_all : tactic nat := do lctx ← local_context, lis ← frozen_local_instances, match lis with | none := revert_lst lctx | some [] := revert_lst lctx /- `hi` is the last local instance. We shoul truncate `lctx` at `hi`. -/ | some (hi::his) := revert_lst $ lctx.foldl (λ r h, if h.local_uniq_name = hi.local_uniq_name then [] else h :: r) [] end meta def clear_lst : list name → tactic unit | [] := skip | (n::ns) := do H ← get_local n, clear H, clear_lst ns meta def match_not (e : expr) : tactic expr := match (expr.is_not e) with | (some a) := return a | none := fail "expression is not a negation" end meta def match_and (e : expr) : tactic (expr × expr) := match (expr.is_and e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a conjunction" end meta def match_or (e : expr) : tactic (expr × expr) := match (expr.is_or e) with | (some (α, β)) := return (α, β) | none := fail "expression is not a disjunction" end meta def match_iff (e : expr) : tactic (expr × expr) := match (expr.is_iff e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an iff" end meta def match_eq (e : expr) : tactic (expr × expr) := match (expr.is_eq e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not an equality" end meta def match_ne (e : expr) : tactic (expr × expr) := match (expr.is_ne e) with | (some (lhs, rhs)) := return (lhs, rhs) | none := fail "expression is not a disequality" end meta def match_heq (e : expr) : tactic (expr × expr × expr × expr) := do match (expr.is_heq e) with | (some (α, lhs, β, rhs)) := return (α, lhs, β, rhs) | none := fail "expression is not a heterogeneous equality" end meta def match_refl_app (e : expr) : tactic (name × expr × expr) := do env ← get_env, match (environment.is_refl_app env e) with | (some (R, lhs, rhs)) := return (R, lhs, rhs) | none := fail "expression is not an application of a reflexive relation" end meta def match_app_of (e : expr) (n : name) : tactic (list expr) := guard (expr.is_app_of e n) >> return e.get_app_args meta def get_local_type (n : name) : tactic expr := get_local n >>= infer_type meta def trace_result : tactic unit := format_result >>= trace meta def rexact (e : expr) : tactic unit := exact e reducible meta def any_hyp_aux {α : Type} (f : expr → tactic α) : list expr → tactic α | [] := failed | (h :: hs) := f h <|> any_hyp_aux hs meta def any_hyp {α : Type} (f : expr → tactic α) : tactic α := local_context >>= any_hyp_aux f /-- `find_same_type t es` tries to find in es an expression with type definitionally equal to t -/ meta def find_same_type : expr → list expr → tactic expr | e [] := failed | e (H :: Hs) := do t ← infer_type H, (unify e t >> return H) <|> find_same_type e Hs meta def find_assumption (e : expr) : tactic expr := do ctx ← local_context, find_same_type e ctx meta def assumption : tactic unit := do { ctx ← local_context, t ← target, H ← find_same_type t ctx, exact H } <|> fail "assumption tactic failed" meta def save_info (p : pos) : tactic unit := do s ← read, tactic.save_info_thunk p (λ _, tactic_state.to_format s) notation `‹` p `›` := (by assumption : p) /-- Swap first two goals, do nothing if tactic state does not have at least two goals. -/ meta def swap : tactic unit := do gs ← get_goals, match gs with | (g₁ :: g₂ :: rs) := set_goals (g₂ :: g₁ :: rs) | e := skip end /-- `assert h t`, adds a new goal for t, and the hypothesis `h : t` in the current goal. -/ meta def assert (h : name) (t : expr) : tactic expr := do assert_core h t, swap, e ← intro h, swap, return e /-- `assertv h t v`, adds the hypothesis `h : t` in the current goal if v has type t. -/ meta def assertv (h : name) (t : expr) (v : expr) : tactic expr := assertv_core h t v >> intro h /-- `define h t`, adds a new goal for t, and the hypothesis `h : t := ?M` in the current goal. -/ meta def define (h : name) (t : expr) : tactic expr := do define_core h t, swap, e ← intro h, swap, return e /-- `definev h t v`, adds the hypothesis (h : t := v) in the current goal if v has type t. -/ meta def definev (h : name) (t : expr) (v : expr) : tactic expr := definev_core h t v >> intro h /-- Add `h : t := pr` to the current goal -/ meta def pose (h : name) (t : option expr := none) (pr : expr) : tactic expr := let dv := λt, definev h t pr in option.cases_on t (infer_type pr >>= dv) dv /-- Add `h : t` to the current goal, given a proof `pr : t` -/ meta def note (h : name) (t : option expr := none) (pr : expr) : tactic expr := let dv := λt, assertv h t pr in option.cases_on t (infer_type pr >>= dv) dv /-- Return the number of goals that need to be solved -/ meta def num_goals : tactic nat := do gs ← get_goals, return (length gs) /-- Rotate the goals to the right by `n`. That is, take the goal at the back and push it to the front `n` times. [NOTE] We have to provide the instance argument `[has_mod nat]` because mod for nat was not defined yet -/ meta def rotate_right (n : nat) [has_mod nat] : tactic unit := do ng ← num_goals, if ng = 0 then skip else rotate_left (ng - n % ng) /-- Rotate the goals to the left by `n`. That is, put the main goal to the back `n` times. -/ meta def rotate : nat → tactic unit := rotate_left private meta def repeat_aux (t : tactic unit) : list expr → list expr → tactic unit | [] r := set_goals r.reverse | (g::gs) r := do ok ← try_core (set_goals [g] >> t), match ok with | none := repeat_aux gs (g::r) | _ := do gs' ← get_goals, repeat_aux (gs' ++ gs) r end /-- This tactic is applied to each goal. If the application succeeds, the tactic is applied recursively to all the generated subgoals until it eventually fails. The recursion stops in a subgoal when the tactic has failed to make progress. The tactic `repeat` never fails. -/ meta def repeat (t : tactic unit) : tactic unit := do gs ← get_goals, repeat_aux t gs [] /-- `first [t_1, ..., t_n]` applies the first tactic that doesn't fail. The tactic fails if all t_i's fail. -/ meta def first {α : Type u} : list (tactic α) → tactic α | [] := fail "first tactic failed, no more alternatives" | (t::ts) := t <|> first ts /-- Applies the given tactic to the main goal and fails if it is not solved. -/ meta def solve1 (tac : tactic unit) : tactic unit := do gs ← get_goals, match gs with | [] := fail "solve1 tactic failed, there isn't any goal left to focus" | (g::rs) := do set_goals [g], tac, gs' ← get_goals, match gs' with | [] := set_goals rs | gs := fail "solve1 tactic failed, focused goal has not been solved" end end /-- `solve [t_1, ... t_n]` applies the first tactic that solves the main goal. -/ meta def solve (ts : list (tactic unit)) : tactic unit := first $ map solve1 ts private meta def focus_aux : list (tactic unit) → list expr → list expr → tactic unit | [] [] rs := set_goals rs | (t::ts) [] rs := fail "focus tactic failed, insufficient number of goals" | tts (g::gs) rs := mcond (is_assigned g) (focus_aux tts gs rs) $ do set_goals [g], t::ts ← pure tts | fail "focus tactic failed, insufficient number of tactics", t, rs' ← get_goals, focus_aux ts gs (rs ++ rs') /-- `focus [t_1, ..., t_n]` applies t_i to the i-th goal. Fails if the number of goals is not n. -/ meta def focus (ts : list (tactic unit)) : tactic unit := do gs ← get_goals, focus_aux ts gs [] meta def focus1 {α} (tac : tactic α) : tactic α := do g::gs ← get_goals, match gs with | [] := tac | _ := do set_goals [g], a ← tac, gs' ← get_goals, set_goals (gs' ++ gs), return a end private meta def all_goals_core (tac : tactic unit) : list expr → list expr → tactic unit | [] ac := set_goals ac | (g :: gs) ac := mcond (is_assigned g) (all_goals_core gs ac) $ do set_goals [g], tac, new_gs ← get_goals, all_goals_core gs (ac ++ new_gs) /-- Apply the given tactic to all goals. -/ meta def all_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, all_goals_core tac gs [] private meta def any_goals_core (tac : tactic unit) : list expr → list expr → bool → tactic unit | [] ac progress := guard progress >> set_goals ac | (g :: gs) ac progress := mcond (is_assigned g) (any_goals_core gs ac progress) $ do set_goals [g], succeeded ← try_core tac, new_gs ← get_goals, any_goals_core gs (ac ++ new_gs) (succeeded.is_some || progress) /-- Apply the given tactic to any goal where it succeeds. The tactic succeeds only if tac succeeds for at least one goal. -/ meta def any_goals (tac : tactic unit) : tactic unit := do gs ← get_goals, any_goals_core tac gs [] ff /-- LCF-style AND_THEN tactic. It applies tac1, and if succeed applies tac2 to each subgoal produced by tac1 -/ meta def seq (tac1 : tactic unit) (tac2 : tactic unit) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, all_goals tac2, gs' ← get_goals, set_goals (gs' ++ gs) meta def seq_focus (tac1 : tactic unit) (tacs2 : list (tactic unit)) : tactic unit := do g::gs ← get_goals, set_goals [g], tac1, focus tacs2, gs' ← get_goals, set_goals (gs' ++ gs) meta instance andthen_seq : has_andthen (tactic unit) (tactic unit) (tactic unit) := ⟨seq⟩ meta instance andthen_seq_focus : has_andthen (tactic unit) (list (tactic unit)) (tactic unit) := ⟨seq_focus⟩ meta constant is_trace_enabled_for : name → bool /-- Execute tac only if option trace.n is set to true. -/ meta def when_tracing (n : name) (tac : tactic unit) : tactic unit := when (is_trace_enabled_for n = tt) tac /-- Fail if there are no remaining goals. -/ meta def fail_if_no_goals : tactic unit := do n ← num_goals, when (n = 0) (fail "tactic failed, there are no goals to be solved") /-- Fail if there are unsolved goals. -/ meta def done : tactic unit := do n ← num_goals, when (n ≠ 0) (fail "done tactic failed, there are unsolved goals") meta def apply_opt_param : tactic unit := do `(opt_param %%t %%v) ← target, exact v meta def apply_auto_param : tactic unit := do `(auto_param %%type %%tac_name_expr) ← target, change type, tac_name ← eval_expr name tac_name_expr, tac ← eval_expr (tactic unit) (expr.const tac_name []), tac meta def has_opt_auto_param (ms : list expr) : tactic bool := ms.mfoldl (λ r m, do type ← infer_type m, return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2) ff meta def try_apply_opt_auto_param (cfg : apply_cfg) (ms : list expr) : tactic unit := when (cfg.auto_param || cfg.opt_param) $ mwhen (has_opt_auto_param ms) $ do gs ← get_goals, ms.mmap' (λ m, mwhen (bnot <$> is_assigned m) $ set_goals [m] >> when cfg.opt_param (try apply_opt_param) >> when cfg.auto_param (try apply_auto_param)), set_goals gs meta def has_opt_auto_param_for_apply (ms : list (name × expr)) : tactic bool := ms.mfoldl (λ r m, do type ← infer_type m.2, return $ r || type.is_napp_of `opt_param 2 || type.is_napp_of `auto_param 2) ff meta def try_apply_opt_auto_param_for_apply (cfg : apply_cfg) (ms : list (name × expr)) : tactic unit := mwhen (has_opt_auto_param_for_apply ms) $ do gs ← get_goals, ms.mmap' (λ m, mwhen (bnot <$> (is_assigned m.2)) $ set_goals [m.2] >> when cfg.opt_param (try apply_opt_param) >> when cfg.auto_param (try apply_auto_param)), set_goals gs meta def apply (e : expr) (cfg : apply_cfg := {}) : tactic (list (name × expr)) := do r ← apply_core e cfg, try_apply_opt_auto_param_for_apply cfg r, return r /-- Same as `apply` but __all__ arguments that weren't inferred are added to goal list. -/ meta def fapply (e : expr) : tactic (list (name × expr)) := apply e {new_goals := new_goals.all} /-- Same as `apply` but only goals that don't depend on other goals are added to goal list. -/ meta def eapply (e : expr) : tactic (list (name × expr)) := apply e {new_goals := new_goals.non_dep_only} /-- Try to solve the main goal using type class resolution. -/ meta def apply_instance : tactic unit := do tgt ← target >>= instantiate_mvars, b ← is_class tgt, if b then mk_instance tgt >>= exact else fail "apply_instance tactic fail, target is not a type class" /-- Create a list of universe meta-variables of the given size. -/ meta def mk_num_meta_univs : nat → tactic (list level) | 0 := return [] | (succ n) := do l ← mk_meta_univ, ls ← mk_num_meta_univs n, return (l::ls) /-- Return `expr.const c [l_1, ..., l_n]` where l_i's are fresh universe meta-variables. -/ meta def mk_const (c : name) : tactic expr := do env ← get_env, decl ← env.get c, let num := decl.univ_params.length, ls ← mk_num_meta_univs num, return (expr.const c ls) /-- Apply the constant `c` -/ meta def applyc (c : name) (cfg : apply_cfg := {}) : tactic unit := do c ← mk_const c, apply c cfg, skip meta def eapplyc (c : name) : tactic unit := do c ← mk_const c, eapply c, skip meta def save_const_type_info (n : name) {elab : bool} (ref : expr elab) : tactic unit := try (do c ← mk_const n, save_type_info c ref) /-- Create a fresh universe `?u`, a metavariable `?T : Type.{?u}`, and return metavariable `?M : ?T`. This action can be used to create a meta-variable when we don't know its type at creation time -/ meta def mk_mvar : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), mk_meta_var t /-- Makes a sorry macro with a meta-variable as its type. -/ meta def mk_sorry : tactic expr := do u ← mk_meta_univ, t ← mk_meta_var (expr.sort u), return $ expr.mk_sorry t /-- Closes the main goal using sorry. -/ meta def admit : tactic unit := target >>= exact ∘ expr.mk_sorry meta def mk_local' (pp_name : name) (bi : binder_info) (type : expr) : tactic expr := do uniq_name ← mk_fresh_name, return $ expr.local_const uniq_name pp_name bi type meta def mk_local_def (pp_name : name) (type : expr) : tactic expr := mk_local' pp_name binder_info.default type meta def mk_local_pis : expr → tactic (list expr × expr) | (expr.pi n bi d b) := do p ← mk_local' n bi d, (ps, r) ← mk_local_pis (expr.instantiate_var b p), return ((p :: ps), r) | e := return ([], e) private meta def get_pi_arity_aux : expr → tactic nat | (expr.pi n bi d b) := do m ← mk_fresh_name, let l := expr.local_const m n bi d, new_b ← whnf (expr.instantiate_var b l), r ← get_pi_arity_aux new_b, return (r + 1) | e := return 0 /-- Compute the arity of the given (Pi-)type -/ meta def get_pi_arity (type : expr) : tactic nat := whnf type >>= get_pi_arity_aux /-- Compute the arity of the given function -/ meta def get_arity (fn : expr) : tactic nat := infer_type fn >>= get_pi_arity meta def triv : tactic unit := mk_const `trivial >>= exact notation `dec_trivial` := of_as_true (by tactic.triv) meta def by_contradiction (H : option name := none) : tactic expr := do tgt : expr ← target, (match_not tgt >> return ()) <|> (mk_mapp `decidable.by_contradiction [some tgt, none] >>= eapply >> skip) <|> fail "tactic by_contradiction failed, target is not a negation nor a decidable proposition (remark: when 'local attribute classical.prop_decidable [instance]' is used all propositions are decidable)", match H with | some n := intro n | none := intro1 end private meta def generalizes_aux (md : transparency) : list expr → tactic unit | [] := skip | (e::es) := generalize e `x md >> generalizes_aux es meta def generalizes (es : list expr) (md := semireducible) : tactic unit := generalizes_aux md es private meta def kdependencies_core (e : expr) (md : transparency) : list expr → list expr → tactic (list expr) | [] r := return r | (h::hs) r := do type ← infer_type h, d ← kdepends_on type e md, if d then kdependencies_core hs (h::r) else kdependencies_core hs r /-- Return all hypotheses that depends on `e` The dependency test is performed using `kdepends_on` with the given transparency setting. -/ meta def kdependencies (e : expr) (md := reducible) : tactic (list expr) := do ctx ← local_context, kdependencies_core e md ctx [] /-- Revert all hypotheses that depend on `e` -/ meta def revert_kdependencies (e : expr) (md := reducible) : tactic nat := kdependencies e md >>= revert_lst meta def revert_kdeps (e : expr) (md := reducible) := revert_kdependencies e md /-- Similar to `cases_core`, but `e` doesn't need to be a hypothesis. Remark, it reverts dependencies using `revert_kdeps`. Two different transparency modes are used `md` and `dmd`. The mode `md` is used with `cases_core` and `dmd` with `generalize` and `revert_kdeps`. It returns the constructor names associated with each new goal. -/ meta def cases (e : expr) (ids : list name := []) (md := semireducible) (dmd := semireducible) : tactic (list name) := if e.is_local_constant then do r ← cases_core e ids md, return $ r.map (λ t, t.1) else do n ← revert_kdependencies e dmd, x ← get_unused_name, (tactic.generalize e x dmd) <|> (do t ← infer_type e, tactic.assertv x t e, get_local x >>= tactic.revert, return ()), h ← tactic.intro1, focus1 (do r ← cases_core h ids md, all_goals (intron n), return $ r.map (λ t, t.1)) /-- The same as `exact` except you can add proof holes. -/ meta def refine (e : pexpr) : tactic unit := do tgt : expr ← target, to_expr ``(%%e : %%tgt) tt >>= exact meta def by_cases (e : expr) (h : name) : tactic unit := do dec_e ← (mk_app `decidable [e] <|> fail "by_cases tactic failed, type is not a proposition"), inst ← (mk_instance dec_e <|> fail "by_cases tactic failed, type of given expression is not decidable"), t ← target, tm ← mk_mapp `dite [some e, some inst, some t], seq (apply tm >> skip) (intro h >> skip) meta def funext_core : list name → bool → tactic unit | [] tt := return () | ids only_ids := try $ do some (lhs, rhs) ← expr.is_eq <$> (target >>= whnf), applyc `funext, id ← if ids.empty ∨ ids.head = `_ then do (expr.lam n _ _ _) ← whnf lhs | pure `_, return n else return ids.head, intro id, funext_core ids.tail only_ids meta def funext : tactic unit := funext_core [] ff meta def funext_lst (ids : list name) : tactic unit := funext_core ids tt private meta def get_undeclared_const (env : environment) (base : name) : ℕ → name | i := let n := base <.> ("_aux_" ++ repr i) in if ¬env.contains n then n else get_undeclared_const (i+1) meta def new_aux_decl_name : tactic name := do env ← get_env, n ← decl_name, return $ get_undeclared_const env n 1 private meta def mk_aux_decl_name : option name → tactic name | none := new_aux_decl_name | (some suffix) := do p ← decl_name, return $ p ++ suffix meta def abstract (tac : tactic unit) (suffix : option name := none) (zeta_reduce := tt) : tactic unit := do fail_if_no_goals, gs ← get_goals, type ← if zeta_reduce then target >>= zeta else target, is_lemma ← is_prop type, m ← mk_meta_var type, set_goals [m], tac, n ← num_goals, when (n ≠ 0) (fail "abstract tactic failed, there are unsolved goals"), set_goals gs, val ← instantiate_mvars m, val ← if zeta_reduce then zeta val else return val, c ← mk_aux_decl_name suffix, e ← add_aux_decl c type val is_lemma, exact e /-- `solve_aux type tac` synthesize an element of 'type' using tactic 'tac' -/ meta def solve_aux {α : Type} (type : expr) (tac : tactic α) : tactic (α × expr) := do m ← mk_meta_var type, gs ← get_goals, set_goals [m], a ← tac, set_goals gs, return (a, m) /-- Return tt iff 'd' is a declaration in one of the current open namespaces -/ meta def in_open_namespaces (d : name) : tactic bool := do ns ← open_namespaces, env ← get_env, return $ ns.any (λ n, n.is_prefix_of d) && env.contains d /-- Execute tac for 'max' "heartbeats". The heartbeat is approx. the maximum number of memory allocations (in thousands) performed by 'tac'. This is a deterministic way of interrupting long running tactics. -/ meta def try_for {α} (max : nat) (tac : tactic α) : tactic α := λ s, match _root_.try_for max (tac s) with | some r := r | none := mk_exception "try_for tactic failed, timeout" none s end meta def updateex_env (f : environment → exceptional environment) : tactic unit := do env ← get_env, env ← returnex $ f env, set_env env /- Add a new inductive datatype to the environment name, universe parameters, number of parameters, type, constructors (name and type), is_meta -/ meta def add_inductive (n : name) (ls : list name) (p : nat) (ty : expr) (is : list (name × expr)) (is_meta : bool := ff) : tactic unit := updateex_env $ λe, e.add_inductive n ls p ty is is_meta meta def add_meta_definition (n : name) (lvls : list name) (type value : expr) : tactic unit := add_decl (declaration.defn n lvls type value reducibility_hints.abbrev ff) /-- `add_defn_equations` adds a definition specified by a list of equations. The arguments: * `lp`: list of universe parameters * `params`: list of parameters (binders before the colon); * `fn`: a local constant giving the name and type of the declaration (with `params` in the local context); * `eqns`: a list of equations, each of which is a list of patterns (constructors applied to new local constants) and the branch expression; * `is_meta`: is the definition meta? `add_defn_equations` can be used as: do my_add ← mk_local_def `my_add `(ℕ → ℕ), a ← mk_local_def `a ℕ, b ← mk_local_def `b ℕ, add_defn_equations [a] my_add [ ([``(nat.zero)], a), ([``(nat.succ %%b)], my_add b) ]) ff -- non-meta to create the following definition: def my_add (a : ℕ) : ℕ → ℕ | nat.zero := a | (nat.succ b) := my_add b -/ meta def add_defn_equations (lp : list name) (params : list expr) (fn : expr) (eqns : list (list pexpr × expr)) (is_meta : bool) : tactic unit := do opt ← get_options, updateex_env $ λ e, e.add_defn_eqns opt lp params fn eqns is_meta meta def rename (curr : name) (new : name) : tactic unit := do h ← get_local curr, n ← revert h, intro new, intron (n - 1) /-- "Replace" hypothesis `h : type` with `h : new_type` where `eq_pr` is a proof that (type = new_type). The tactic actually creates a new hypothesis with the same user facing name, and (tries to) clear `h`. The `clear` step fails if `h` has forward dependencies. In this case, the old `h` will remain in the local context. The tactic returns the new hypothesis. -/ meta def replace_hyp (h : expr) (new_type : expr) (eq_pr : expr) : tactic expr := do h_type ← infer_type h, new_h ← assert h.local_pp_name new_type, mk_eq_mp eq_pr h >>= exact, try $ clear h, return new_h meta def main_goal : tactic expr := do g::gs ← get_goals, return g /- Goal tagging support -/ meta def with_enable_tags {α : Type} (t : tactic α) (b := tt) : tactic α := do old ← tags_enabled, enable_tags b, r ← t, enable_tags old, return r meta def get_main_tag : tactic tag := main_goal >>= get_tag meta def set_main_tag (t : tag) : tactic unit := do g ← main_goal, set_tag g t meta def subst (h : expr) : tactic unit := (do guard h.is_local_constant, some (α, lhs, β, rhs) ← expr.is_heq <$> infer_type h, is_def_eq α β, new_h_type ← mk_app `eq [lhs, rhs], new_h_pr ← mk_app `eq_of_heq [h], new_h ← assertv h.local_pp_name new_h_type new_h_pr, try (clear h), subst_core new_h) <|> subst_core h end tactic notation [parsing_only] `command`:max := tactic unit open tactic namespace list meta def for_each {α} : list α → (α → tactic unit) → tactic unit | [] fn := skip | (e::es) fn := do fn e, for_each es fn meta def any_of {α β} : list α → (α → tactic β) → tactic β | [] fn := failed | (e::es) fn := do opt_b ← try_core (fn e), match opt_b with | some b := return b | none := any_of es fn end end list /- Install monad laws tactic and use it to prove some instances. -/ /-- Try to prove with `iff.refl`.-/ meta def order_laws_tac := whnf_target >> intros >> to_expr ``(iff.refl _) >>= exact meta def monad_from_pure_bind {m : Type u → Type v} (pure : Π {α : Type u}, α → m α) (bind : Π {α β : Type u}, m α → (α → m β) → m β) : monad m := {pure := @pure, bind := @bind} meta instance : monad task := {map := @task.map, bind := @task.bind, pure := @task.pure} namespace tactic meta def mk_id_proof (prop : expr) (pr : expr) : expr := expr.app (expr.app (expr.const ``id [level.zero]) prop) pr meta def mk_id_eq (lhs : expr) (rhs : expr) (pr : expr) : tactic expr := do prop ← mk_app `eq [lhs, rhs], return $ mk_id_proof prop pr meta def replace_target (new_target : expr) (pr : expr) : tactic unit := do t ← target, assert `htarget new_target, swap, ht ← get_local `htarget, locked_pr ← mk_id_eq t new_target pr, mk_eq_mpr locked_pr ht >>= exact end tactic
d55de4d011efc21346fab039969d4cd38363ee40
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Leanpkg/Toml.lean
31d910a63e7c110b5faf25639094d176da62b5cb
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
cipher1024/lean4
6e1f98bb58e7a92b28f5364eb38a14c8d0aae393
69114d3b50806264ef35b57394391c3e738a9822
refs/heads/master
1,642,227,983,603
1,642,011,696,000
1,642,011,696,000
228,607,691
0
0
Apache-2.0
1,576,584,269,000
1,576,584,268,000
null
UTF-8
Lean
false
false
2,466
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Sebastian Ullrich -/ import Lean.Parser namespace Toml inductive Value : Type where | str : String → Value | nat : Nat → Value | bool : Bool → Value | table : List (String × Value) → Value deriving Inhabited def Value.lookup : Value → String → Option Value | Value.table cs, k => cs.lookup k | _, _ => none -- TODO: custom whitespace and other inaccuracies declare_syntax_cat val syntax "True" : val syntax "False" : val syntax str : val syntax num : val syntax bareKey := ident -- TODO syntax key := bareKey <|> str declare_syntax_cat keyCat @[keyCatParser] def key' := key -- HACK: for the antiquotation syntax keyVal := key " = " val syntax table := "[" key "]" keyVal* syntax inlineTable := "{" keyVal,* "}" syntax inlineTable : val syntax file := table* declare_syntax_cat fileCat @[fileCatParser] def file' := file -- HACK: for the antiquotation open Lean partial def ofSyntax : Syntax → Value | `(val|True) => Value.bool true | `(val|False) => Value.bool false | `(val|$s:strLit) => Value.str <| s.isStrLit?.get! | `(val|$n:numLit) => Value.nat <| n.isNatLit?.get! | `(val|{$[$keys:key = $values],*}) => toTable keys (values.map ofSyntax) | `(fileCat|$[[$keys] $kvss*]*) => toTable keys <| kvss.map fun kvs => ofSyntax <| Lean.Unhygienic.run `(val|{$kvs,*}) | stx => unreachable! where toKey : Syntax → String | `(keyCat|$key:ident) => key.getId.toString | `(keyCat|$key:strLit) => key.isStrLit?.get! | _ => unreachable! toTable (keys : Array Syntax) (vals : Array Value) : Value := Value.table <| Array.toList <| keys.zipWith vals fun k v => (toKey k, v) open Lean.Parser def parse (input : String) : IO Value := do -- HACKHACKHACK let env ← importModules [{ module := `Leanpkg.Toml }] {} let fileParser ← compileParserDescr (parserExtension.getState env).categories file { env := env, opts := {} } let c := mkParserContext (mkInputContext input "") { env := env, options := {} } let s := mkParserState input let s := whitespace c s let s := fileParser.fn c s if s.hasError then throw <| IO.userError (s.toErrorMsg c) else if input.atEnd s.pos then ofSyntax s.stxStack.back else throw <| IO.userError ((s.mkError "end of input").toErrorMsg c) end Toml
30cc8c2a95eae7f8316d9320834d5604413d16de
3dc4623269159d02a444fe898d33e8c7e7e9461b
/.github/workflows/project_1_a_decrire/lean-scheme-submission/src/sheaves/covering/covering_on_standard_basis.lean
f306e9aa4cb8f94d5b0e316867c63fc970f710e4
[]
no_license
Or7ando/lean
cc003e6c41048eae7c34aa6bada51c9e9add9e66
d41169cf4e416a0d42092fb6bdc14131cee9dd15
refs/heads/master
1,650,600,589,722
1,587,262,906,000
1,587,262,906,000
255,387,160
0
0
null
null
null
null
UTF-8
Lean
false
false
497
lean
/- Same as covering bu thte Ui's are required to be on the basis. -/ import topology.basic import to_mathlib.opens import sheaves.covering.covering universes u open topological_space section covering_on_standard_basis parameters {α : Type u} [topological_space α] parameters (B : set (opens α)) [HB : opens.is_basis B] -- Open cover for standard basis. structure covering_standard_basis (U : opens α) extends covering U := (BUis : ∀ i, Uis i ∈ B) end covering_on_standard_basis
6a25773a91e78c637498eadea19b0140d0701632
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/diamond3.lean
24bd9cee0ff8a8714388eccd896b6777fed63363
[ "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
255
lean
structure A where x : Nat := 0 y : Nat := 0 f : Nat → Nat := (· + 10) structure B extends A where z : Nat structure C extends A where w : Nat set_option structureDiamondWarning false structure D extends B, C where a : Nat #print D.toC
75af09b076eb2f9f8969afd27fe9f5ce6e7bc743
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/analysis/schwartz_space.lean
b0ff178f015e6088b6ef65801ae7e3a49e808dfe
[ "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
19,342
lean
/- Copyright (c) 2022 Moritz Doll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Moritz Doll -/ import analysis.calculus.cont_diff import analysis.locally_convex.with_seminorms import topology.algebra.uniform_filter_basis import topology.continuous_function.bounded import tactic.positivity /-! # Schwartz space This file defines the Schwartz space. Usually, the Schwartz space is defined as the set of smooth functions $f : ℝ^n → ℂ$ such that there exists $C_{αβ} > 0$ with $$|x^α ∂^β f(x)| < C_{αβ}$$ for all $x ∈ ℝ^n$ and for all multiindices $α, β$. In mathlib, we use a slightly different approach and define define the Schwartz space as all smooth functions `f : E → F`, where `E` and `F` are real normed vector spaces such that for all natural numbers `k` and `n` we have uniform bounds `‖x‖^k * ‖iterated_fderiv ℝ n f x‖ < C`. This approach completely avoids using partial derivatives as well as polynomials. We construct the topology on the Schwartz space by a family of seminorms, which are the best constants in the above estimates, which is by abstract theory from `seminorm_family.module_filter_basis` and `with_seminorms.to_locally_convex_space` turns the Schwartz space into a locally convex topological vector space. ## Main definitions * `schwartz_map`: The Schwartz space is the space of smooth functions such that all derivatives decay faster than any power of `‖x‖`. * `schwartz_map.seminorm`: The family of seminorms as described above * `schwartz_map.fderiv_clm`: The differential as a continuous linear map `𝓢(E, F) →L[𝕜] 𝓢(E, E →L[ℝ] F)` ## Main statements * `schwartz_map.uniform_add_group` and `schwartz_map.locally_convex`: The Schwartz space is a locally convex topological vector space. ## Implementation details The implementation of the seminorms is taken almost literally from `continuous_linear_map.op_norm`. ## Notation * `𝓢(E, F)`: The Schwartz space `schwartz_map E F` localized in `schwartz_space` ## Tags Schwartz space, tempered distributions -/ noncomputable theory variables {𝕜 𝕜' E F : Type*} variables [normed_add_comm_group E] [normed_space ℝ E] variables [normed_add_comm_group F] [normed_space ℝ F] variables (E F) /-- A function is a Schwartz function if it is smooth and all derivatives decay faster than any power of `‖x‖`. -/ structure schwartz_map := (to_fun : E → F) (smooth' : cont_diff ℝ ⊤ to_fun) (decay' : ∀ (k n : ℕ), ∃ (C : ℝ), ∀ x, ‖x‖^k * ‖iterated_fderiv ℝ n to_fun x‖ ≤ C) localized "notation `𝓢(` E `, ` F `)` := schwartz_map E F" in schwartz_space variables {E F} namespace schwartz_map instance : has_coe 𝓢(E, F) (E → F) := ⟨to_fun⟩ instance fun_like : fun_like 𝓢(E, F) E (λ _, F) := { coe := λ f, f.to_fun, coe_injective' := λ f g h, by cases f; cases g; congr' } /-- Helper instance for when there's too many metavariables to apply `fun_like.has_coe_to_fun`. -/ instance : has_coe_to_fun 𝓢(E, F) (λ _, E → F) := ⟨λ p, p.to_fun⟩ /-- All derivatives of a Schwartz function are rapidly decaying. -/ lemma decay (f : 𝓢(E, F)) (k n : ℕ) : ∃ (C : ℝ) (hC : 0 < C), ∀ x, ‖x‖^k * ‖iterated_fderiv ℝ n f x‖ ≤ C := begin rcases f.decay' k n with ⟨C, hC⟩, exact ⟨max C 1, by positivity, λ x, (hC x).trans (le_max_left _ _)⟩, end /-- Every Schwartz function is smooth. -/ lemma smooth (f : 𝓢(E, F)) (n : ℕ∞) : cont_diff ℝ n f := f.smooth'.of_le le_top /-- Every Schwartz function is continuous. -/ @[continuity, protected] lemma continuous (f : 𝓢(E, F)) : continuous f := (f.smooth 0).continuous /-- Every Schwartz function is differentiable. -/ @[protected] lemma differentiable (f : 𝓢(E, F)) : differentiable ℝ f := (f.smooth 1).differentiable rfl.le @[ext] lemma ext {f g : 𝓢(E, F)} (h : ∀ x, (f : E → F) x = g x) : f = g := fun_like.ext f g h section aux lemma bounds_nonempty (k n : ℕ) (f : 𝓢(E, F)) : ∃ (c : ℝ), c ∈ {c : ℝ | 0 ≤ c ∧ ∀ (x : E), ‖x‖^k * ‖iterated_fderiv ℝ n f x‖ ≤ c} := let ⟨M, hMp, hMb⟩ := f.decay k n in ⟨M, le_of_lt hMp, hMb⟩ lemma bounds_bdd_below (k n : ℕ) (f : 𝓢(E, F)) : bdd_below {c | 0 ≤ c ∧ ∀ x, ‖x‖^k * ‖iterated_fderiv ℝ n f x‖ ≤ c} := ⟨0, λ _ ⟨hn, _⟩, hn⟩ lemma decay_add_le_aux (k n : ℕ) (f g : 𝓢(E, F)) (x : E) : ‖x‖^k * ‖iterated_fderiv ℝ n (f+g) x‖ ≤ ‖x‖^k * ‖iterated_fderiv ℝ n f x‖ + ‖x‖^k * ‖iterated_fderiv ℝ n g x‖ := begin rw ←mul_add, refine mul_le_mul_of_nonneg_left _ (by positivity), convert norm_add_le _ _, exact iterated_fderiv_add_apply (f.smooth _) (g.smooth _), end lemma decay_neg_aux (k n : ℕ) (f : 𝓢(E, F)) (x : E) : ‖x‖ ^ k * ‖iterated_fderiv ℝ n (-f) x‖ = ‖x‖ ^ k * ‖iterated_fderiv ℝ n f x‖ := begin nth_rewrite 3 ←norm_neg, congr, exact iterated_fderiv_neg_apply, end variables [normed_field 𝕜] [normed_space 𝕜 F] [smul_comm_class ℝ 𝕜 F] lemma decay_smul_aux (k n : ℕ) (f : 𝓢(E, F)) (c : 𝕜) (x : E) : ‖x‖ ^ k * ‖iterated_fderiv ℝ n (c • f) x‖ = ‖c‖ * ‖x‖ ^ k * ‖iterated_fderiv ℝ n f x‖ := by rw [mul_comm (‖c‖), mul_assoc, iterated_fderiv_const_smul_apply (f.smooth _), norm_smul] end aux section seminorm_aux /-- Helper definition for the seminorms of the Schwartz space. -/ @[protected] def seminorm_aux (k n : ℕ) (f : 𝓢(E, F)) : ℝ := Inf {c | 0 ≤ c ∧ ∀ x, ‖x‖^k * ‖iterated_fderiv ℝ n f x‖ ≤ c} lemma seminorm_aux_nonneg (k n : ℕ) (f : 𝓢(E, F)) : 0 ≤ f.seminorm_aux k n := le_cInf (bounds_nonempty k n f) (λ _ ⟨hx, _⟩, hx) lemma le_seminorm_aux (k n : ℕ) (f : 𝓢(E, F)) (x : E) : ‖x‖ ^ k * ‖iterated_fderiv ℝ n ⇑f x‖ ≤ f.seminorm_aux k n := le_cInf (bounds_nonempty k n f) (λ y ⟨_, h⟩, h x) /-- If one controls the norm of every `A x`, then one controls the norm of `A`. -/ lemma seminorm_aux_le_bound (k n : ℕ) (f : 𝓢(E, F)) {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ x, ‖x‖^k * ‖iterated_fderiv ℝ n f x‖ ≤ M) : f.seminorm_aux k n ≤ M := cInf_le (bounds_bdd_below k n f) ⟨hMp, hM⟩ end seminorm_aux /-! ### Algebraic properties -/ section smul variables [normed_field 𝕜] [normed_space 𝕜 F] [smul_comm_class ℝ 𝕜 F] [normed_field 𝕜'] [normed_space 𝕜' F] [smul_comm_class ℝ 𝕜' F] instance : has_smul 𝕜 𝓢(E, F) := ⟨λ c f, { to_fun := c • f, smooth' := (f.smooth _).const_smul c, decay' := λ k n, begin refine ⟨f.seminorm_aux k n * (‖c‖+1), λ x, _⟩, have hc : 0 ≤ ‖c‖ := by positivity, refine le_trans _ ((mul_le_mul_of_nonneg_right (f.le_seminorm_aux k n x) hc).trans _), { apply eq.le, rw [mul_comm _ (‖c‖), ← mul_assoc], exact decay_smul_aux k n f c x }, { apply mul_le_mul_of_nonneg_left _ (f.seminorm_aux_nonneg k n), linarith } end}⟩ @[simp] lemma smul_apply {f : 𝓢(E, F)} {c : 𝕜} {x : E} : (c • f) x = c • (f x) := rfl instance [has_smul 𝕜 𝕜'] [is_scalar_tower 𝕜 𝕜' F] : is_scalar_tower 𝕜 𝕜' 𝓢(E, F) := ⟨λ a b f, ext $ λ x, smul_assoc a b (f x)⟩ instance [smul_comm_class 𝕜 𝕜' F] : smul_comm_class 𝕜 𝕜' 𝓢(E, F) := ⟨λ a b f, ext $ λ x, smul_comm a b (f x)⟩ lemma seminorm_aux_smul_le (k n : ℕ) (c : 𝕜) (f : 𝓢(E, F)) : (c • f).seminorm_aux k n ≤ ‖c‖ * f.seminorm_aux k n := begin refine (c • f).seminorm_aux_le_bound k n (mul_nonneg (norm_nonneg _) (seminorm_aux_nonneg _ _ _)) (λ x, (decay_smul_aux k n f c x).le.trans _), rw mul_assoc, exact mul_le_mul_of_nonneg_left (f.le_seminorm_aux k n x) (norm_nonneg _), end instance has_nsmul : has_smul ℕ 𝓢(E, F) := ⟨λ c f, { to_fun := c • f, smooth' := (f.smooth _).const_smul c, decay' := begin have : c • (f : E → F) = (c : ℝ) • f, { ext x, simp only [pi.smul_apply, ← nsmul_eq_smul_cast] }, simp only [this], exact ((c : ℝ) • f).decay', end}⟩ instance has_zsmul : has_smul ℤ 𝓢(E, F) := ⟨λ c f, { to_fun := c • f, smooth' := (f.smooth _).const_smul c, decay' := begin have : c • (f : E → F) = (c : ℝ) • f, { ext x, simp only [pi.smul_apply, ← zsmul_eq_smul_cast] }, simp only [this], exact ((c : ℝ) • f).decay', end}⟩ end smul section zero instance : has_zero 𝓢(E, F) := ⟨{ to_fun := λ _, 0, smooth' := cont_diff_const, decay' := λ _ _, ⟨1, λ _, by simp⟩ }⟩ instance : inhabited 𝓢(E, F) := ⟨0⟩ lemma coe_zero : ↑(0 : 𝓢(E, F)) = (0 : E → F) := rfl @[simp] lemma coe_fn_zero : coe_fn (0 : 𝓢(E, F)) = (0 : E → F) := rfl @[simp] lemma zero_apply {x : E} : (0 : 𝓢(E, F)) x = 0 := rfl lemma seminorm_aux_zero (k n : ℕ) : (0 : 𝓢(E, F)).seminorm_aux k n = 0 := le_antisymm (seminorm_aux_le_bound k n _ rfl.le (λ _, by simp [pi.zero_def])) (seminorm_aux_nonneg _ _ _) end zero section neg instance : has_neg 𝓢(E, F) := ⟨λ f, ⟨-f, (f.smooth _).neg, λ k n, ⟨f.seminorm_aux k n, λ x, (decay_neg_aux k n f x).le.trans (f.le_seminorm_aux k n x)⟩⟩⟩ end neg section add instance : has_add 𝓢(E, F) := ⟨λ f g, ⟨f + g, (f.smooth _).add (g.smooth _), λ k n, ⟨f.seminorm_aux k n + g.seminorm_aux k n, λ x, (decay_add_le_aux k n f g x).trans (add_le_add (f.le_seminorm_aux k n x) (g.le_seminorm_aux k n x))⟩⟩⟩ @[simp] lemma add_apply {f g : 𝓢(E, F)} {x : E} : (f + g) x = f x + g x := rfl lemma seminorm_aux_add_le (k n : ℕ) (f g : 𝓢(E, F)) : (f + g).seminorm_aux k n ≤ f.seminorm_aux k n + g.seminorm_aux k n := (f + g).seminorm_aux_le_bound k n (add_nonneg (seminorm_aux_nonneg _ _ _) (seminorm_aux_nonneg _ _ _)) $ λ x, (decay_add_le_aux k n f g x).trans $ add_le_add (f.le_seminorm_aux k n x) (g.le_seminorm_aux k n x) end add section sub instance : has_sub 𝓢(E, F) := ⟨λ f g, ⟨f - g, (f.smooth _).sub (g.smooth _), begin intros k n, refine ⟨f.seminorm_aux k n + g.seminorm_aux k n, λ x, _⟩, refine le_trans _ (add_le_add (f.le_seminorm_aux k n x) (g.le_seminorm_aux k n x)), rw sub_eq_add_neg, rw ←decay_neg_aux k n g x, convert decay_add_le_aux k n f (-g) x, -- exact fails with deterministic timeout end⟩ ⟩ @[simp] lemma sub_apply {f g : 𝓢(E, F)} {x : E} : (f - g) x = f x - g x := rfl end sub section add_comm_group instance : add_comm_group 𝓢(E, F) := fun_like.coe_injective.add_comm_group _ rfl (λ _ _, rfl) (λ _, rfl) (λ _ _, rfl) (λ _ _, rfl) (λ _ _, rfl) variables (E F) /-- Coercion as an additive homomorphism. -/ def coe_hom : 𝓢(E, F) →+ (E → F) := { to_fun := λ f, f, map_zero' := coe_zero, map_add' := λ _ _, rfl } variables {E F} lemma coe_coe_hom : (coe_hom E F : 𝓢(E, F) → (E → F)) = coe_fn := rfl lemma coe_hom_injective : function.injective (coe_hom E F) := by { rw coe_coe_hom, exact fun_like.coe_injective } end add_comm_group section module variables [normed_field 𝕜] [normed_space 𝕜 F] [smul_comm_class ℝ 𝕜 F] instance : module 𝕜 𝓢(E, F) := coe_hom_injective.module 𝕜 (coe_hom E F) (λ _ _, rfl) end module section seminorms /-! ### Seminorms on Schwartz space-/ variables [normed_field 𝕜] [normed_space 𝕜 F] [smul_comm_class ℝ 𝕜 F] variable (𝕜) /-- The seminorms of the Schwartz space given by the best constants in the definition of `𝓢(E, F)`. -/ @[protected] def seminorm (k n : ℕ) : seminorm 𝕜 𝓢(E, F) := seminorm.of_smul_le (seminorm_aux k n) (seminorm_aux_zero k n) (seminorm_aux_add_le k n) (seminorm_aux_smul_le k n) /-- If one controls the seminorm for every `x`, then one controls the seminorm. -/ lemma seminorm_le_bound (k n : ℕ) (f : 𝓢(E, F)) {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ x, ‖x‖^k * ‖iterated_fderiv ℝ n f x‖ ≤ M) : seminorm 𝕜 k n f ≤ M := f.seminorm_aux_le_bound k n hMp hM /-- The seminorm controls the Schwartz estimate for any fixed `x`. -/ lemma le_seminorm (k n : ℕ) (f : 𝓢(E, F)) (x : E) : ‖x‖ ^ k * ‖iterated_fderiv ℝ n f x‖ ≤ seminorm 𝕜 k n f := f.le_seminorm_aux k n x lemma norm_iterated_fderiv_le_seminorm (f : 𝓢(E, F)) (n : ℕ) (x₀ : E) : ‖iterated_fderiv ℝ n f x₀‖ ≤ (schwartz_map.seminorm 𝕜 0 n) f := begin have := schwartz_map.le_seminorm 𝕜 0 n f x₀, rwa [pow_zero, one_mul] at this, end lemma norm_pow_mul_le_seminorm (f : 𝓢(E, F)) (k : ℕ) (x₀ : E) : ‖x₀‖^k * ‖f x₀‖ ≤ (schwartz_map.seminorm 𝕜 k 0) f := begin have := schwartz_map.le_seminorm 𝕜 k 0 f x₀, rwa norm_iterated_fderiv_zero at this, end lemma norm_le_seminorm (f : 𝓢(E, F)) (x₀ : E) : ‖f x₀‖ ≤ (schwartz_map.seminorm 𝕜 0 0) f := begin have := norm_pow_mul_le_seminorm 𝕜 f 0 x₀, rwa [pow_zero, one_mul] at this, end end seminorms section topology /-! ### The topology on the Schwartz space-/ variables [normed_field 𝕜] [normed_space 𝕜 F] [smul_comm_class ℝ 𝕜 F] variables (𝕜 E F) /-- The family of Schwartz seminorms. -/ def _root_.schwartz_seminorm_family : seminorm_family 𝕜 𝓢(E, F) (ℕ × ℕ) := λ n, seminorm 𝕜 n.1 n.2 @[simp] lemma schwartz_seminorm_family_apply (n k : ℕ) : schwartz_seminorm_family 𝕜 E F (n,k) = schwartz_map.seminorm 𝕜 n k := rfl @[simp] lemma schwartz_seminorm_family_apply_zero : schwartz_seminorm_family 𝕜 E F 0 = schwartz_map.seminorm 𝕜 0 0 := rfl instance : topological_space 𝓢(E, F) := (schwartz_seminorm_family ℝ E F).module_filter_basis.topology' lemma _root_.schwartz_with_seminorms : with_seminorms (schwartz_seminorm_family 𝕜 E F) := begin have A : with_seminorms (schwartz_seminorm_family ℝ E F) := ⟨rfl⟩, rw seminorm_family.with_seminorms_iff_nhds_eq_infi at ⊢ A, rw A, refl end variables {𝕜 E F} instance : has_continuous_smul 𝕜 𝓢(E, F) := begin rw (schwartz_with_seminorms 𝕜 E F).with_seminorms_eq, exact (schwartz_seminorm_family 𝕜 E F).module_filter_basis.has_continuous_smul, end instance : topological_add_group 𝓢(E, F) := (schwartz_seminorm_family ℝ E F).add_group_filter_basis.is_topological_add_group instance : uniform_space 𝓢(E, F) := (schwartz_seminorm_family ℝ E F).add_group_filter_basis.uniform_space instance : uniform_add_group 𝓢(E, F) := (schwartz_seminorm_family ℝ E F).add_group_filter_basis.uniform_add_group instance : locally_convex_space ℝ 𝓢(E, F) := (schwartz_with_seminorms ℝ E F).to_locally_convex_space instance : topological_space.first_countable_topology (𝓢(E, F)) := (schwartz_with_seminorms ℝ E F).first_countable end topology section fderiv /-! ### Derivatives of Schwartz functions -/ variables {E F} /-- The derivative of a Schwartz function as a Schwartz function with values in the continuous linear maps `E→L[ℝ] F`. -/ @[protected] def fderiv (f : 𝓢(E, F)) : 𝓢(E, E →L[ℝ] F) := { to_fun := fderiv ℝ f, smooth' := (cont_diff_top_iff_fderiv.mp f.smooth').2, decay' := begin intros k n, cases f.decay' k (n+1) with C hC, use C, intros x, rw norm_iterated_fderiv_fderiv, exact hC x, end } @[simp, norm_cast] lemma coe_fderiv (f : 𝓢(E, F)) : ⇑f.fderiv = fderiv ℝ f := rfl @[simp] lemma fderiv_apply (f : 𝓢(E, F)) (x : E) : f.fderiv x = fderiv ℝ f x := rfl variables (𝕜) variables [is_R_or_C 𝕜] [normed_space 𝕜 F] [smul_comm_class ℝ 𝕜 F] /-- The derivative on Schwartz space as a linear map. -/ def fderiv_lm : 𝓢(E, F) →ₗ[𝕜] 𝓢(E, E →L[ℝ] F) := { to_fun := schwartz_map.fderiv, map_add' := λ f g, ext $ λ _, fderiv_add f.differentiable.differentiable_at g.differentiable.differentiable_at, map_smul' := λ a f, ext $ λ _, fderiv_const_smul f.differentiable.differentiable_at a } @[simp, norm_cast] lemma fderiv_lm_apply (f : 𝓢(E, F)) : fderiv_lm 𝕜 f = schwartz_map.fderiv f := rfl /-- The derivative on Schwartz space as a continuous linear map. -/ def fderiv_clm : 𝓢(E, F) →L[𝕜] 𝓢(E, E →L[ℝ] F) := { cont := begin change continuous (fderiv_lm 𝕜 : 𝓢(E, F) →ₗ[𝕜] 𝓢(E, E →L[ℝ] F)), refine seminorm.continuous_from_bounded (schwartz_with_seminorms 𝕜 E F) (schwartz_with_seminorms 𝕜 E (E →L[ℝ] F)) _ _, rintros ⟨k, n⟩, use [{⟨k, n+1⟩}, 1, one_ne_zero], intros f, simp only [schwartz_seminorm_family_apply, seminorm.comp_apply, finset.sup_singleton, one_smul], refine (fderiv_lm 𝕜 f).seminorm_le_bound 𝕜 k n (by positivity) _, intros x, rw [fderiv_lm_apply, coe_fderiv, norm_iterated_fderiv_fderiv], exact f.le_seminorm 𝕜 k (n+1) x, end, to_linear_map := fderiv_lm 𝕜 } @[simp, norm_cast] lemma fderiv_clm_apply (f : 𝓢(E, F)) : fderiv_clm 𝕜 f = schwartz_map.fderiv f := rfl end fderiv section bounded_continuous_function /-! ### Inclusion into the space of bounded continuous functions -/ open_locale bounded_continuous_function /-- Schwartz functions as bounded continuous functions-/ def to_bounded_continuous_function (f : 𝓢(E, F)) : E →ᵇ F := bounded_continuous_function.of_normed_add_comm_group f (schwartz_map.continuous f) (schwartz_map.seminorm ℝ 0 0 f) (norm_le_seminorm ℝ f) @[simp] lemma to_bounded_continuous_function_apply (f : 𝓢(E, F)) (x : E) : f.to_bounded_continuous_function x = f x := rfl variables (𝕜 E F) variables [is_R_or_C 𝕜] [normed_space 𝕜 F] [smul_comm_class ℝ 𝕜 F] /-- The inclusion map from Schwartz functions to bounded continuous functions as a linear map. -/ def to_bounded_continuous_function_lm : 𝓢(E, F) →ₗ[𝕜] E →ᵇ F := { to_fun := λ f, f.to_bounded_continuous_function, map_add' := λ f g, by { ext, exact add_apply }, map_smul' := λ a f, by { ext, exact smul_apply } } @[simp] lemma to_bounded_continuous_function_lm_apply (f : 𝓢(E, F)) (x : E) : to_bounded_continuous_function_lm 𝕜 E F f x = f x := rfl /-- The inclusion map from Schwartz functions to bounded continuous functions as a continuous linear map. -/ def to_bounded_continuous_function_clm : 𝓢(E, F) →L[𝕜] E →ᵇ F := { cont := begin change continuous (to_bounded_continuous_function_lm 𝕜 E F), refine seminorm.continuous_from_bounded (schwartz_with_seminorms 𝕜 E F) (norm_with_seminorms 𝕜 (E →ᵇ F)) _ (λ i, ⟨{0}, 1, one_ne_zero, λ f, _⟩), rw [finset.sup_singleton, one_smul , seminorm.comp_apply, coe_norm_seminorm, schwartz_seminorm_family_apply_zero, bounded_continuous_function.norm_le (map_nonneg _ _)], intros x, exact norm_le_seminorm 𝕜 _ _, end, .. to_bounded_continuous_function_lm 𝕜 E F} @[simp] lemma to_bounded_continuous_function_clm_apply (f : 𝓢(E, F)) (x : E) : to_bounded_continuous_function_clm 𝕜 E F f x = f x := rfl variables {E} /-- The Dirac delta distribution -/ def delta (x : E) : 𝓢(E, F) →L[𝕜] F := (bounded_continuous_function.eval_clm 𝕜 x).comp (to_bounded_continuous_function_clm 𝕜 E F) @[simp] lemma delta_apply (x₀ : E) (f : 𝓢(E, F)) : delta 𝕜 F x₀ f = f x₀ := rfl end bounded_continuous_function end schwartz_map
f4fc00f56ed5be5bd2e7f8b049227a3d58e2b8a0
36938939954e91f23dec66a02728db08a7acfcf9
/lean4/deps/galois_stdlib/src/Galois/Data/Bitvec.lean
a79c53d4cdea23a1411d61344716e261efa83cc4
[]
no_license
pnwamk/reopt-vcg
f8b56dd0279392a5e1c6aee721be8138e6b558d3
c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d
refs/heads/master
1,631,145,017,772
1,593,549,019,000
1,593,549,143,000
254,191,418
0
0
null
1,586,377,077,000
1,586,377,077,000
null
UTF-8
Lean
false
false
14,306
lean
/- Copyright (c) 2015 Joe Hendrix. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joe Hendrix, Sebastian Ullrich, Jason Dagit Basic operations on bitvectors. This is a work-in-progress, and contains additions to other theories. -/ -- import galois.data.nat.basic -- import data.vector -- A `bitvec n` is a subtype of natural numbers such that the value of -- the bitvec is strictly less than 2^n. -- structure bitvec (sz:ℕ) := -- (to_nat : ℕ) -- (property : to_nat < (2 ^ sz)) import Galois.Init.Nat import Galois.Init.Int -- FIXME: obviously this needs to be replaced by actual proofs axiom power_hack (n : Nat) (e : Nat) : n < 2 ^ e def bitvec (sz : Nat) := { x // x < 2 ^ sz } instance bitvec_DecidableEq {n : Nat}: DecidableEq (bitvec n) := Subtype.DecidableEq namespace bitvec -- open galois def to_nat {w : Nat} (b : bitvec w) : Nat := b.val -- instance (w:Nat) : DecidableEq (bitvec w) := -- { decEq := (λx y, @decEq _ (@Subtype.DecidableEq Nat (λn, n < 2 ^ w) _) x y) } -- By default just show a bitvector as a nat. instance (w:Nat) : HasRepr (bitvec w) := ⟨fun v => repr (v.to_nat)⟩ section to_hex --- Print word as hex def pp_hex {n : Nat} (v : bitvec n) : String := Nat.ppHex v.to_nat end to_hex axiom zero_lt_pow (n : Nat) : 0 < 2 ^ n section zero -- Create a zero bitvector protected def zero (n : Nat) : bitvec n := ⟨0, zero_lt_pow n⟩ -- bitvectors have a zero, at every length instance {n:Nat} : HasZero (bitvec n) := ⟨bitvec.zero n⟩ -- @[simp] -- lemma bitvec_zero_zero (x : bitvec 0) : x.to_Nat = 0 := -- begin -- cases x with x_val x_prop, -- { simp [Nat.pow_zero, Nat.lt_one_is_zero] at x_prop, -- simp, assumption -- } -- end end zero axiom one_le_pow_2 {n: Nat} (h : n > 0) : 1 < 2^n axiom Nat.zero_lt_succ (n : Nat) : 0 < Nat.succ n section one -- lemma one_le_pow_2 {n: Nat} (h : n > 0) : 1 < 2^n := -- calc 1 < 2^1 : by exact (of_as_true trivial) -- ... ≤ 2^n : Nat.pow_le_pow_of_le_right (of_as_true trivial) h -- In pratice, it's more useful to allow 0 length bitvectors to have 1 -- as well. This leads to a special case where the 0-length bitvector -- 1 is really just 0. This turns out to simplify things. protected def one : ∀(n:Nat), bitvec n | 0 => 0 | (Nat.succ _) => ⟨1, one_le_pow_2 (Nat.zero_lt_succ _)⟩ instance {n:Nat} : HasOne (bitvec n) := ⟨bitvec.one n⟩ end one protected def cong {a b : Nat} (h : a = b) : bitvec a → bitvec b | ⟨x, p⟩ => ⟨x, h ▸ p⟩ -- lemma cong_val {n m : Nat} {H : n = m} (x : bitvec n) -- : (bitvec.cong H x).to_Nat = x.to_Nat := -- begin -- cases x, simp [bitvec.cong] -- end -- protected -- lemma intro {n:Nat} : Π(x y : bitvec n), x.to_Nat = y.to_Nat → x = y -- | ⟨x, h1⟩ ⟨.(_), h2⟩ rfl => rfl -- FIXME: more efficient implementation of of_Nat -- protected def of_nat (n : Nat) (x:Nat) : bitvec n := ⟨ x % (Nat.shiftl 1 n), power_hack _ _⟩ protected def of_nat (n : Nat) (x:Nat) : bitvec n := ⟨ x % 2^n, Nat.modLt _ (Nat.posPowOfPos n (zero_lt_pow 1))⟩ instance Nat_to_bitvec_coe {w : Nat} : HasCoe Nat (bitvec w) := ⟨bitvec.of_nat w⟩ -- theorem of_Nat_to_Nat {n : Nat} (x : bitvec n) -- : bitvec.of_Nat n (bitvec.to_Nat x) = x := -- begin -- cases x, -- simp [bitvec.to_Nat, bitvec.of_Nat], -- apply Nat.mod_eq_of_lt x_property, -- end -- theorem to_Nat_of_Nat (k n : Nat) -- : bitvec.to_Nat (bitvec.of_Nat k n) = n % 2^k := -- begin -- simp [bitvec.of_Nat, bitvec.to_Nat] -- end --- Most significant bit def msb {n:Nat} (x: bitvec n) : Bool := (Nat.shiftr x.to_nat (n-1)) = 1 --- Least significant bit. def lsb {n:Nat} (x: bitvec n) : Bool := Nat.bodd x.to_nat section conversion -- Operations For converting to/from bitvectors protected def to_int {n:Nat} (x: bitvec n) : Int := match msb x with | false => Int.ofNat x.to_nat | true => Int.negOfNat (2^n - x.to_nat) --- Convert an int to two's complement bitvector. protected def of_int : ∀(n : Nat), Int → bitvec n | n, (Int.ofNat x) => bitvec.of_nat n x | n, (Int.negSucc x) => bitvec.of_nat n (Nat.ldiff (2^n-1) x) end conversion section bitwise -- bitwise negation def not {w:Nat} (x: bitvec w) : bitvec w := ⟨2^w - x.to_nat - 1, power_hack _ _ -- begin -- have xval_pos : 0 < x.to_nat + 1, -- { apply (Nat.succ_pos x.to_nat) }, -- apply (Nat.sub_lt _ xval_pos), -- apply Nat.pos_pow_of_pos, -- apply (Nat.succ_pos 1) -- end ⟩ -- logical bitwise and def and {w:Nat} (x y : bitvec w) : bitvec w := bitvec.of_nat w (Nat.land x.to_nat y.to_nat) -- diff x y = x & not y def diff {w:Nat} (x y : bitvec w) : bitvec w := bitvec.of_nat w (Nat.ldiff x.to_nat y.to_nat) -- logical bitwise or def or {w:Nat} (x y : bitvec w) : bitvec w := bitvec.of_nat w (Nat.lor x.to_nat y.to_nat) -- logical bitwise xor def xor {w:Nat} (x y : bitvec w) : bitvec w := bitvec.of_nat w (Nat.lxor x.to_nat y.to_nat) infix `.&&.`:70 := and infix `.||.`:65 := or end bitwise section arith -- Arithmetic operations on bitvectors variable {n : Nat} protected def add (x y : bitvec n) : bitvec n := bitvec.of_nat n (x.to_nat + y.to_nat) def adc (x y : bitvec n) : bitvec n × Bool := ⟨ bitvec.add x y , x.to_nat + y.to_nat ≥ 2^n ⟩ -- Usual arithmetic subtraction protected def sub (x y : bitvec n) : bitvec n := bitvec.of_int n (x.to_int - y.to_int) -- 2s complement negation protected def neg {n:Nat} (x : bitvec n) : bitvec n := ⟨if x.to_nat = 0 then 0 else 2^n - x.to_nat, power_hack _ _ -- begin -- by_cases (x.to_nat = 0), -- { simp [h], exact Nat.pos_pow_of_pos _ (of_as_true trivial), }, -- { simp [h], -- --x.to_nat (2^n) x_to_nat_pos, -- have pos : 0 < 2^n - x.to_nat, { apply Nat.sub_pos_of_lt x.property }, -- have x_to_nat_pos: 0 < x.to_nat, { apply Nat.pos_of_ne_zero h }, -- apply Nat.sub_lt_of_pos_le x.to_nat (2^n) x_to_nat_pos, -- apply le_of_lt x.property, -- } -- end ⟩ instance : HasAdd (bitvec n) := ⟨bitvec.add⟩ instance : HasSub (bitvec n) := ⟨bitvec.sub⟩ instance : HasNeg (bitvec n) := ⟨bitvec.neg⟩ protected def mul (x y : bitvec n) : bitvec n := bitvec.of_nat n (x.to_nat * y.to_nat) instance : HasMul (bitvec n) := ⟨bitvec.mul⟩ def bitvec_pow (x: bitvec n) (k:Nat) : bitvec n := bitvec.of_nat n (x.to_nat^k) instance bitvec_has_pow : HasPow (bitvec n) Nat := ⟨bitvec_pow⟩ end arith section shift -- Shift related operations, including signed and unsigned shift. variable {n : Nat} -- shift left def shl (x : bitvec n) (i : Nat) : bitvec n := bitvec.of_nat n (Nat.shiftl x.to_nat i) -- unsigned shift right def ushr (x : bitvec n) (i : Nat) : bitvec n := bitvec.of_nat n (Nat.shiftr x.to_nat i) -- signed shift right def sshr (x: bitvec n) (i:Nat) : bitvec n := bitvec.of_int n (Int.shiftr (bitvec.to_int x) i) end shift section listlike -- Operations that treat bitvectors as a list of bits. --- Test if a specific bit with given index is set. def nth {w:Nat} (x : bitvec w) (idx : Nat) : Bool := Nat.test_bit x.to_nat idx -- Change number of bits result while preserving unsigned value modulo output width. def uresize {m:Nat} (x: bitvec m) (n:Nat) : bitvec n := bitvec.of_nat _ x.to_nat -- Change number of bits result while preserving signed value modulo output width. def sresize {m:Nat} (x: bitvec m) (n:Nat) : bitvec n := bitvec.of_int _ x.to_int open Nat -- bitvec specific version of vector.append def append {m n} (x: bitvec m) (y: bitvec n) : bitvec (m + n) := ⟨ x.to_nat * 2^n + y.to_nat, power_hack _ _ /- Nat.mul_pow_add_lt_pow x.property y.property -/ ⟩ protected def bsf' : ∀(n:Nat), Nat → Nat → Option Nat | 0, idx, _ => none | (succ m), idx, x => if Nat.test_bit x idx then some idx else bsf' m (idx+1) x --- index of least-significant bit that is 1. def bsf : ∀{n:Nat}, bitvec n → Option Nat | n, x => bitvec.bsf' n 0 x.to_nat protected def bsr' : Nat → Nat → Option Nat | x, zero => none | x, (succ idx) => if Nat.test_bit x idx then some idx else bsr' x idx --- index of the most-significant bit that is 1. def bsr : ∀{n:Nat}, bitvec n → Option Nat | n, x => bitvec.bsr' x.to_nat n -- example : bsf (bitvec.of_nat 3 0) = none := of_as_true trivial -- example : bsr (bitvec.of_nat 3 0) = none := of_as_true trivial -- example : bsf (bitvec.of_nat 3 5) = some 0 := of_as_true trivial -- example : bsr (bitvec.of_nat 3 5) = some 2 := of_as_true trivial def slice {w: Nat} (u l k:Nat) (H: w = k + (u + 1 - l)) (x: bitvec w) : bitvec (u + 1 - l) := bitvec.of_nat _ (Nat.shiftr x.to_nat l) protected def foldl' {α : Sort _} (f : α -> Bool → α) (x : Nat) (init : α) : Nat → α | zero => init | (succ idx) => f (foldl' idx) (x.test_bit idx) -- foldl follows nth's behaviour, so -- foldl f i b = f (f (f i b!0) b!1) b!2 etc. def foldl {α : Sort _} {n : Nat} (f : α → Bool → α) (init : α) (b : bitvec n) : α := bitvec.foldl' f b.to_nat init n protected def foldr' {α : Sort _} (f : Bool → α → α) (x : Nat) (init : α) (n : Nat) : Nat → α | zero => init | (succ idx) => f (x.test_bit (n - succ idx)) (foldr' idx) -- foldr follows nth's behaviour, so -- foldr f i b = f b!0 (f b!1 ... (f b!(n-1) i)) def foldr {α : Sort _} {n : Nat} (f : Bool → α → α) (init : α) (b : bitvec n) : α := bitvec.foldr' f b.to_nat init n n end listlike section comparison -- Comparison operations, including signed and unsigned versions variable {n : Nat} def ult (x y : bitvec n) : Prop := x.to_nat < y.to_nat def ugt (x y : bitvec n) : Prop := ult y x def ule (x y : bitvec n) : Prop := ¬ (ult y x) def uge (x y : bitvec n) : Prop := ule y x def slt (x y : bitvec n) : Prop := x.to_int < y.to_int def sgt (x y : bitvec n) : Prop := slt y x def sle (x y : bitvec n) : Prop := ¬ (slt y x) def sge (x y : bitvec n) : Prop := sle y x -- local attribute [reducible] ult -- local attribute [reducible] ugt -- local attribute [reducible] ule -- local attribute [reducible] uge attribute [reducible] ult attribute [reducible] ugt attribute [reducible] ule attribute [reducible] uge instance decidable_ult {n} {x y : bitvec n} : Decidable (bitvec.ult x y) := inferInstance -- by apply_instance instance decidable_ugt {n} {x y : bitvec n} : Decidable (bitvec.ugt x y) := inferInstance -- by apply_instance instance decidable_ule {n} {x y : bitvec n} : Decidable (bitvec.ule x y) := inferInstance -- by apply_instance instance decidable_uge {n} {x y : bitvec n} : Decidable (bitvec.uge x y) := inferInstance -- by apply_instance -- local attribute [reducible] slt -- local attribute [reducible] sgt -- local attribute [reducible] sle -- local attribute [reducible] sge attribute [reducible] slt attribute [reducible] sgt attribute [reducible] sle attribute [reducible] sge instance decidable_slt {n} {x y : bitvec n} : Decidable (bitvec.slt x y) := inferInstance -- by apply_instance instance decidable_sgt {n} {x y : bitvec n} : Decidable (bitvec.sgt x y) := inferInstance -- by apply_instance instance decidable_sle {n} {x y : bitvec n} : Decidable (bitvec.sle x y) := inferInstance -- by apply_instance instance decidable_sge {n} {x y : bitvec n} : Decidable (bitvec.sge x y) := inferInstance -- by apply_instance end comparison def concat' {n:Nat} (input: List (bitvec n)): Nat := List.foldl (fun v (a:bitvec n) => Nat.shiftl v n + a.to_nat) 0 input --- ConcateNation all bitvectors in the List together and return a new bitvector. -- -- The most significant bits of are returned first. def concat_list {m:Nat}(input: List (bitvec m)) (n:Nat) : bitvec n := bitvec.of_nat _ (concat' input) --- ConcateNation all bitvectors in the vector together and return a new bitvector. -- -- The most significant bits of are returned first. -- -- To minimize the need for proofs, we intentionally do not force that the output -- has a specific length. -- def concat_vec {w m : Nat}(input: vector (bitvec w) m) (n:Nat) : bitvec n := -- bitvec.of_nat _ (concat' input.to_list) -- example : concat_list [(1 : bitvec 4), 0] 8 = (16 : bitvec 8) := by exact (of_as_true trivial) --- Forms a List of bitvectors by taking a specific number of bits from parts of the -- first argument. -- -- The head of the List has the most-significant bits. def split_to_list (x:Nat) (w:Nat) : Nat → List (bitvec w) | Nat.zero => [] | (Nat.succ n) => bitvec.of_nat w (Nat.shiftr x (n*w)) :: split_to_list n -- theorem length_split_to_list (x:Nat) (w : Nat) (m:Nat) : List.length (split_to_list x w m) = m := -- begin -- induction m, -- case Nat.zero { simp [split_to_list], }, -- case Nat.succ : m ind { simp [split_to_list, ind, Nat.succ_add], }, -- end /- Split a single bitvector into a List of bitvectors with most-significant bits first. -/ def split_list {n:Nat} (x:bitvec n) (w:Nat) : List (bitvec w) := split_to_list x.to_nat w (Nat.div n w) /- Split a single bitvector into a vector of bitvectors with most-significant bits first. -/ -- def split_vec {n:Nat} (x:bitvec n) (w m:Nat) : vector (bitvec w) m := -- ⟨split_to_list x.to_nat w m, length_split_to_list _ _ _⟩ -- example : split_list (16 : bitvec 8) 4 = [(1 : bitvec 4), 0] := by exact (of_as_true trivial) --- Git bits [i..i+m] out of n. def get_bits {n} (x:bitvec n) (i m : Nat) (p:i+m ≤ n) : bitvec m := bitvec.of_nat m (Nat.shiftr x.to_nat i) --#eval ((get_bits (0x01234567 : bitvec 32) 8 16 (of_as_true trivial) = 0x2345) : Bool) --- Set bits at given index. def set_bits {n} (x:bitvec n) (i:Nat) {m} (y:bitvec m) (p:i+m ≤ n) : bitvec n := let mask := bitvec.of_nat n (Nat.shiftl ((2^m)-1) i); or (diff x mask) (bitvec.of_nat n (Nat.shiftl y.to_nat i)) --#eval ((set_bits (0x01234567 : bitvec 32) 8 (0x5432 : bitvec 16) (of_as_true trivial) = 0x01543267) : Bool) end bitvec
a44efb28e7c1109ec3bce5df5517386d4b654325
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/polynomial/chebyshev/basic.lean
bdaeb9a112c064e71397790515dd1800abf5f586
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
3,292
lean
/- Copyright (c) 2020 Johan Commelin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johan Commelin -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.ring_theory.polynomial.chebyshev.defs import Mathlib.analysis.special_functions.trigonometric import Mathlib.ring_theory.localization import Mathlib.data.zmod.basic import Mathlib.algebra.invertible import Mathlib.PostPort universes u_1 namespace Mathlib /-! # Chebyshev polynomials The Chebyshev polynomials are two families of polynomials indexed by `ℕ`, with integral coefficients. In this file, we only consider Chebyshev polynomials of the first kind. ## Main declarations * `polynomial.chebyshev₁_mul`, the `(m * n)`-th Chebyshev polynomial is the composition of the `m`-th and `n`-th Chebyshev polynomials. * `polynomial.lambdashev_mul`, the `(m * n)`-th lambdashev polynomial is the composition of the `m`-th and `n`-th lambdashev polynomials. * `polynomial.lambdashev_char_p`, for a prime number `p`, the `p`-th lambdashev polynomial is congruent to `X ^ p` modulo `p`. ## Implementation details Since Chebyshev polynomials have interesting behaviour over the complex numbers and modulo `p`, we define them to have coefficients in an arbitrary commutative ring, even though technically `ℤ` would suffice. The benefit of allowing arbitrary coefficient rings, is that the statements afterwards are clean, and do not have `map (int.cast_ring_hom R)` interfering all the time. -/ namespace polynomial /-- The `(m * n)`-th Chebyshev polynomial is the composition of the `m`-th and `n`-th -/ theorem chebyshev₁_mul (R : Type u_1) [comm_ring R] (m : ℕ) (n : ℕ) : chebyshev₁ R (m * n) = comp (chebyshev₁ R m) (chebyshev₁ R n) := sorry /-! ### A Lambda structure on `polynomial ℤ` Mathlib doesn't currently know what a Lambda ring is. But once it does, we can endow `polynomial ℤ` with a Lambda structure in terms of the `lambdashev` polynomials defined below. There is exactly one other Lambda structure on `polynomial ℤ` in terms of binomial polynomials. -/ theorem lambdashev_eval_add_inv {R : Type u_1} [comm_ring R] (x : R) (y : R) (h : x * y = 1) (n : ℕ) : eval (x + y) (lambdashev R n) = x ^ n + y ^ n := sorry theorem lambdashev_eq_chebyshev₁ (R : Type u_1) [comm_ring R] [invertible (bit0 1)] (n : ℕ) : lambdashev R n = bit0 1 * comp (chebyshev₁ R n) (coe_fn C ⅟ * X) := sorry theorem chebyshev₁_eq_lambdashev (R : Type u_1) [comm_ring R] [invertible (bit0 1)] (n : ℕ) : chebyshev₁ R n = coe_fn C ⅟ * comp (lambdashev R n) (bit0 1 * X) := sorry /-- the `(m * n)`-th lambdashev polynomial is the composition of the `m`-th and `n`-th -/ theorem lambdashev_mul (R : Type u_1) [comm_ring R] (m : ℕ) (n : ℕ) : lambdashev R (m * n) = comp (lambdashev R m) (lambdashev R n) := sorry theorem lambdashev_comp_comm (R : Type u_1) [comm_ring R] (m : ℕ) (n : ℕ) : comp (lambdashev R m) (lambdashev R n) = comp (lambdashev R n) (lambdashev R m) := sorry theorem lambdashev_zmod_p (p : ℕ) [fact (nat.prime p)] : lambdashev (zmod p) p = X ^ p := sorry theorem lambdashev_char_p (R : Type u_1) [comm_ring R] (p : ℕ) [fact (nat.prime p)] [char_p R p] : lambdashev R p = X ^ p := sorry
5b00712905b1a3ba7d75833f7720446a3c3b3d1c
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/tropical/lattice.lean
544bba5582e4a094d7ef5c8de116b665cfffec0a
[ "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,510
lean
/- Copyright (c) 2021 Yakov Pechersky. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yakov Pechersky -/ import algebra.tropical.basic import order.conditionally_complete_lattice.basic /-! # Order on tropical algebraic structure > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines the orders induced on tropical algebraic structures by the underlying type. ## Main declarations * `conditionally_complete_lattice (tropical R)` * `conditionally_complete_linear_order (tropical R)` ## Implementation notes The order induced is the definitionally equal underlying order, which makes the proofs and constructions quicker to implement. -/ variables {R S : Type*} open tropical instance [has_sup R] : has_sup (tropical R) := { sup := λ x y, trop (untrop x ⊔ untrop y) } instance [has_inf R] : has_inf (tropical R) := { inf := λ x y, trop (untrop x ⊓ untrop y) } instance [semilattice_inf R] : semilattice_inf (tropical R) := { le_inf := λ _ _ _, le_inf, inf_le_left := λ _ _, inf_le_left, inf_le_right := λ _ _, inf_le_right, ..tropical.has_inf, ..tropical.partial_order } instance [semilattice_sup R] : semilattice_sup (tropical R) := { sup_le := λ _ _ _, sup_le, le_sup_left := λ _ _, le_sup_left, le_sup_right := λ _ _, le_sup_right, ..tropical.has_sup, ..tropical.partial_order } instance [lattice R] : lattice (tropical R) := { ..tropical.semilattice_inf, ..tropical.semilattice_sup } instance [has_Sup R] : has_Sup (tropical R) := { Sup := λ s, trop (Sup (untrop '' s)) } instance [has_Inf R] : has_Inf (tropical R) := { Inf := λ s, trop (Inf (untrop '' s)) } instance [conditionally_complete_lattice R] : conditionally_complete_lattice (tropical R) := { le_cSup := λ s x hs hx, le_cSup (untrop_monotone.map_bdd_above hs) (set.mem_image_of_mem untrop hx), cSup_le := λ s x hs hx, cSup_le (hs.image untrop) (untrop_monotone.mem_upper_bounds_image hx), le_cInf := λ s x hs hx, le_cInf (hs.image untrop) (untrop_monotone.mem_lower_bounds_image hx), cInf_le := λ s x hs hx, cInf_le (untrop_monotone.map_bdd_below hs) (set.mem_image_of_mem untrop hx), ..tropical.has_Sup, ..tropical.has_Inf, ..tropical.lattice } instance [conditionally_complete_linear_order R] : conditionally_complete_linear_order (tropical R) := { ..tropical.conditionally_complete_lattice, ..tropical.linear_order }
74a753722a0101155f16806eafd8e5c256e0ba40
25adb3ce35902d6e9c57e494fe055c47c9881db4
/metrology/scalar.lean
9e43795a3d0a1132245cfebb8362b6c1c51729aa
[]
no_license
rohanrajnair/phys
fefb5e430f8e4b61c2acbaecb9d1c6702495ef87
0172c81b24bc94e2df5e32904c9f6904d8f24da7
refs/heads/master
1,673,021,045,568
1,603,474,638,000
1,603,474,638,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,173
lean
--import .....math.affine.aff_coord_space import data.real.basic namespace scalar /- Algebraic types of scalars for different physical dimensions. Deprecated. Use basicDimScalarType. TODO: Rethink use of abbreviation -/ abbreviation length := ℝ abbreviation time := ℝ abbreviation mass := { r : ℝ // r >= 0} abbreviation current := ℝ abbreviation temperature := { r : ℝ // r >= 0} -- how/where to say can't be equivalent to negative in Kelvin? abbreviation quantity := ℕ abbreviation intensity := {r : ℝ // r >= 0} -- is this right? -- Need proof that result isn't negative. Currently sorry. Turns into runtime check? def add_mass : mass → mass → mass | m1 m2 := ⟨m1.1 + m2.1, sorry ⟩ -- Need proof that result isn't negative. Currently sorry. Turns into runtime check? def add_intensity : intensity → intensity → intensity | i1 i2 := ⟨i1.1 + i2.1, sorry ⟩ -- Need proof that result isn't negative. Currently sorry. Turns into runtime check? def add_temperature : temperature → temperature → temperature | i1 i2 := ⟨i1.1 + i2.1, sorry ⟩ -- Need proof that result isn't negative. Currently sorry. Turns into runtime check? def sub_mass : mass → mass → mass | m1 m2 := ⟨m1.1 - m2.1, sorry ⟩ -- Need proof that result isn't negative. Currently sorry. Turns into runtime check? def sub_intensity : intensity → intensity → intensity | i1 i2 := ⟨i1.1 - i2.1, sorry ⟩ -- Need proof that result isn't negative. Currently sorry. Turns into runtime check? def sub_temperature : temperature → temperature → temperature | i1 i2 := ⟨i1.1 - i2.1, sorry ⟩ -- Need proof that result isn't negative. Currently sorry. Turns into runtime check? def mul_mass : mass → mass → mass | m1 m2 := ⟨m1.1 * m2.1, sorry ⟩ -- Need proof that result isn't negative. Currently sorry. Turns into runtime check? def mul_intensity : intensity → intensity → intensity | i1 i2 := ⟨i1.1 * i2.1, sorry ⟩ -- Need proof that result isn't negative. Currently sorry. Turns into runtime check? def mul_temperature : temperature → temperature → temperature | i1 i2 := ⟨i1.1 * i2.1, sorry ⟩ end scalar
c4e122bf4b1109d62aea6277ff4f7a8e7d0a85b5
ba4ad8a778c69640c9cca8e5dcaeb40d4a10fa10
/lean4/hello/lakefile.lean
6b4c87e614a66f8796b763aee1817186e90be031
[]
no_license
tangentstorm/tangentlabs
390ac60618bd913b567d20933dab70b84aac7151
137adbba6e7c35f8bb54b0786ada6c8c2ff6bc72
refs/heads/master
1,693,514,213,127
1,692,322,210,000
1,692,322,210,000
7,815,356
33
22
null
1,433,592,935,000
1,359,097,381,000
Visual Basic
UTF-8
Lean
false
false
87
lean
import Lake open Lake DSL package hello { -- add configuration options here }
3f31c0ff33e3e9a98523199d98c87a910193f50f
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/combinatorics/configuration.lean
d5768f9c69eadc5628ab9ef76ccd0ecb912594b5
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
23,316
lean
/- Copyright (c) 2021 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import algebra.big_operators.order import combinatorics.hall.basic import data.fintype.card import set_theory.fincard /-! # Configurations of Points and lines This file introduces abstract configurations of points and lines, and proves some basic properties. ## Main definitions * `configuration.nondegenerate`: Excludes certain degenerate configurations, and imposes uniqueness of intersection points. * `configuration.has_points`: A nondegenerate configuration in which every pair of lines has an intersection point. * `configuration.has_lines`: A nondegenerate configuration in which every pair of points has a line through them. * `configuration.line_count`: The number of lines through a given point. * `configuration.point_count`: The number of lines through a given line. ## Main statements * `configuration.has_lines.card_le`: `has_lines` implies `|P| ≤ |L|`. * `configuration.has_points.card_le`: `has_points` implies `|L| ≤ |P|`. * `configuration.has_lines.has_points`: `has_lines` and `|P| = |L|` implies `has_points`. * `configuration.has_points.has_lines`: `has_points` and `|P| = |L|` implies `has_lines`. Together, these four statements say that any two of the following properties imply the third: (a) `has_lines`, (b) `has_points`, (c) `|P| = |L|`. -/ open_locale big_operators namespace configuration universe u variables (P L : Type u) [has_mem P L] /-- A type synonym. -/ def dual := P instance [this : inhabited P] : inhabited (dual P) := this instance [this : fintype P] : fintype (dual P) := this instance : has_mem (dual L) (dual P) := ⟨function.swap (has_mem.mem : P → L → Prop)⟩ /-- A configuration is nondegenerate if: 1) there does not exist a line that passes through all of the points, 2) there does not exist a point that is on all of the lines, 3) there is at most one line through any two points, 4) any two lines have at most one intersection point. Conditions 3 and 4 are equivalent. -/ class nondegenerate : Prop := (exists_point : ∀ l : L, ∃ p, p ∉ l) (exists_line : ∀ p, ∃ l : L, p ∉ l) (eq_or_eq : ∀ {p₁ p₂ : P} {l₁ l₂ : L}, p₁ ∈ l₁ → p₂ ∈ l₁ → p₁ ∈ l₂ → p₂ ∈ l₂ → p₁ = p₂ ∨ l₁ = l₂) /-- A nondegenerate configuration in which every pair of lines has an intersection point. -/ class has_points extends nondegenerate P L : Type u := (mk_point : ∀ {l₁ l₂ : L} (h : l₁ ≠ l₂), P) (mk_point_ax : ∀ {l₁ l₂ : L} (h : l₁ ≠ l₂), mk_point h ∈ l₁ ∧ mk_point h ∈ l₂) /-- A nondegenerate configuration in which every pair of points has a line through them. -/ class has_lines extends nondegenerate P L : Type u := (mk_line : ∀ {p₁ p₂ : P} (h : p₁ ≠ p₂), L) (mk_line_ax : ∀ {p₁ p₂ : P} (h : p₁ ≠ p₂), p₁ ∈ mk_line h ∧ p₂ ∈ mk_line h) open nondegenerate has_points has_lines instance [nondegenerate P L] : nondegenerate (dual L) (dual P) := { exists_point := @exists_line P L _ _, exists_line := @exists_point P L _ _, eq_or_eq := λ l₁ l₂ p₁ p₂ h₁ h₂ h₃ h₄, (@eq_or_eq P L _ _ p₁ p₂ l₁ l₂ h₁ h₃ h₂ h₄).symm } instance [has_points P L] : has_lines (dual L) (dual P) := { mk_line := @mk_point P L _ _, mk_line_ax := λ _ _, mk_point_ax } instance [has_lines P L] : has_points (dual L) (dual P) := { mk_point := @mk_line P L _ _, mk_point_ax := λ _ _, mk_line_ax } lemma has_points.exists_unique_point [has_points P L] (l₁ l₂ : L) (hl : l₁ ≠ l₂) : ∃! p, p ∈ l₁ ∧ p ∈ l₂ := ⟨mk_point hl, mk_point_ax hl, λ p hp, (eq_or_eq hp.1 (mk_point_ax hl).1 hp.2 (mk_point_ax hl).2).resolve_right hl⟩ lemma has_lines.exists_unique_line [has_lines P L] (p₁ p₂ : P) (hp : p₁ ≠ p₂) : ∃! l : L, p₁ ∈ l ∧ p₂ ∈ l := has_points.exists_unique_point (dual L) (dual P) p₁ p₂ hp variables {P L} /-- If a nondegenerate configuration has at least as many points as lines, then there exists an injective function `f` from lines to points, such that `f l` does not lie on `l`. -/ lemma nondegenerate.exists_injective_of_card_le [nondegenerate P L] [fintype P] [fintype L] (h : fintype.card L ≤ fintype.card P) : ∃ f : L → P, function.injective f ∧ ∀ l, (f l) ∉ l := begin classical, let t : L → finset P := λ l, (set.to_finset {p | p ∉ l}), suffices : ∀ s : finset L, s.card ≤ (s.bUnion t).card, -- Hall's marriage theorem { obtain ⟨f, hf1, hf2⟩ := (finset.all_card_le_bUnion_card_iff_exists_injective t).mp this, exact ⟨f, hf1, λ l, set.mem_to_finset.mp (hf2 l)⟩ }, intro s, by_cases hs₀ : s.card = 0, -- If `s = ∅`, then `s.card = 0 ≤ (s.bUnion t).card` { simp_rw [hs₀, zero_le] }, by_cases hs₁ : s.card = 1, -- If `s = {l}`, then pick a point `p ∉ l` { obtain ⟨l, rfl⟩ := finset.card_eq_one.mp hs₁, obtain ⟨p, hl⟩ := exists_point l, rw [finset.card_singleton, finset.singleton_bUnion, nat.one_le_iff_ne_zero], exact finset.card_ne_zero_of_mem (set.mem_to_finset.mpr hl) }, suffices : (s.bUnion t)ᶜ.card ≤ sᶜ.card, -- Rephrase in terms of complements (uses `h`) { rw [finset.card_compl, finset.card_compl, tsub_le_iff_left] at this, replace := h.trans this, rwa [←add_tsub_assoc_of_le s.card_le_univ, le_tsub_iff_left (le_add_left s.card_le_univ), add_le_add_iff_right] at this }, have hs₂ : (s.bUnion t)ᶜ.card ≤ 1, -- At most one line through two points of `s` { refine finset.card_le_one_iff.mpr (λ p₁ p₂ hp₁ hp₂, _), simp_rw [finset.mem_compl, finset.mem_bUnion, exists_prop, not_exists, not_and, set.mem_to_finset, set.mem_set_of_eq, not_not] at hp₁ hp₂, obtain ⟨l₁, l₂, hl₁, hl₂, hl₃⟩ := finset.one_lt_card_iff.mp (nat.one_lt_iff_ne_zero_and_ne_one.mpr ⟨hs₀, hs₁⟩), exact (eq_or_eq (hp₁ l₁ hl₁) (hp₂ l₁ hl₁) (hp₁ l₂ hl₂) (hp₂ l₂ hl₂)).resolve_right hl₃ }, by_cases hs₃ : sᶜ.card = 0, { rw [hs₃, nat.le_zero_iff], rw [finset.card_compl, tsub_eq_zero_iff_le, has_le.le.le_iff_eq (finset.card_le_univ _), eq_comm, finset.card_eq_iff_eq_univ, hs₃, finset.eq_univ_iff_forall] at hs₃ ⊢, exact λ p, exists.elim (exists_line p) -- If `s = univ`, then show `s.bUnion t = univ` (λ l hl, finset.mem_bUnion.mpr ⟨l, finset.mem_univ l, set.mem_to_finset.mpr hl⟩) }, { exact hs₂.trans (nat.one_le_iff_ne_zero.mpr hs₃) }, -- If `s < univ`, then consequence of `hs₂` end variables {P} (L) /-- Number of points on a given line. -/ noncomputable def line_count (p : P) : ℕ := nat.card {l : L // p ∈ l} variables (P) {L} /-- Number of lines through a given point. -/ noncomputable def point_count (l : L) : ℕ := nat.card {p : P // p ∈ l} variables (P L) lemma sum_line_count_eq_sum_point_count [fintype P] [fintype L] : ∑ p : P, line_count L p = ∑ l : L, point_count P l := begin classical, simp only [line_count, point_count, nat.card_eq_fintype_card, ←fintype.card_sigma], apply fintype.card_congr, calc (Σ p, {l : L // p ∈ l}) ≃ {x : P × L // x.1 ∈ x.2} : (equiv.subtype_prod_equiv_sigma_subtype (∈)).symm ... ≃ {x : L × P // x.2 ∈ x.1} : (equiv.prod_comm P L).subtype_equiv (λ x, iff.rfl) ... ≃ (Σ l, {p // p ∈ l}) : equiv.subtype_prod_equiv_sigma_subtype (λ (l : L) (p : P), p ∈ l), end variables {P L} lemma has_lines.point_count_le_line_count [has_lines P L] {p : P} {l : L} (h : p ∉ l) [fintype {l : L // p ∈ l}] : point_count P l ≤ line_count L p := begin by_cases hf : infinite {p : P // p ∈ l}, { exactI (le_of_eq nat.card_eq_zero_of_infinite).trans (zero_le (line_count L p)) }, haveI := fintype_of_not_infinite hf, rw [line_count, point_count, nat.card_eq_fintype_card, nat.card_eq_fintype_card], have : ∀ p' : {p // p ∈ l}, p ≠ p' := λ p' hp', h ((congr_arg (∈ l) hp').mpr p'.2), exact fintype.card_le_of_injective (λ p', ⟨mk_line (this p'), (mk_line_ax (this p')).1⟩) (λ p₁ p₂ hp, subtype.ext ((eq_or_eq p₁.2 p₂.2 (mk_line_ax (this p₁)).2 ((congr_arg _ (subtype.ext_iff.mp hp)).mpr (mk_line_ax (this p₂)).2)).resolve_right (λ h', (congr_arg _ h').mp h (mk_line_ax (this p₁)).1))), end lemma has_points.line_count_le_point_count [has_points P L] {p : P} {l : L} (h : p ∉ l) [hf : fintype {p : P // p ∈ l}] : line_count L p ≤ point_count P l := @has_lines.point_count_le_line_count (dual L) (dual P) _ _ l p h hf variables (P L) /-- If a nondegenerate configuration has a unique line through any two points, then `|P| ≤ |L|`. -/ lemma has_lines.card_le [has_lines P L] [fintype P] [fintype L] : fintype.card P ≤ fintype.card L := begin classical, by_contradiction hc₂, obtain ⟨f, hf₁, hf₂⟩ := nondegenerate.exists_injective_of_card_le (le_of_not_le hc₂), have := calc ∑ p, line_count L p = ∑ l, point_count P l : sum_line_count_eq_sum_point_count P L ... ≤ ∑ l, line_count L (f l) : finset.sum_le_sum (λ l hl, has_lines.point_count_le_line_count (hf₂ l)) ... = ∑ p in finset.univ.image f, line_count L p : finset.sum_bij (λ l hl, f l) (λ l hl, finset.mem_image_of_mem f hl) (λ l hl, rfl) (λ l₁ l₂ hl₁ hl₂ hl₃, hf₁ hl₃) (λ p, by simp_rw [finset.mem_image, eq_comm, imp_self]) ... < ∑ p, line_count L p : _, { exact lt_irrefl _ this }, { obtain ⟨p, hp⟩ := not_forall.mp (mt (fintype.card_le_of_surjective f) hc₂), refine finset.sum_lt_sum_of_subset ((finset.univ.image f).subset_univ) (finset.mem_univ p) _ _ (λ p hp₁ hp₂, zero_le (line_count L p)), { simpa only [finset.mem_image, exists_prop, finset.mem_univ, true_and] }, { rw [line_count, nat.card_eq_fintype_card, fintype.card_pos_iff], obtain ⟨l, hl⟩ := @exists_line P L _ _ p, exact let this := not_exists.mp hp l in ⟨⟨mk_line this, (mk_line_ax this).2⟩⟩ } }, end /-- If a nondegenerate configuration has a unique point on any two lines, then `|L| ≤ |P|`. -/ lemma has_points.card_le [has_points P L] [fintype P] [fintype L] : fintype.card L ≤ fintype.card P := @has_lines.card_le (dual L) (dual P) _ _ _ _ variables {P L} lemma has_lines.exists_bijective_of_card_eq [has_lines P L] [fintype P] [fintype L] (h : fintype.card P = fintype.card L) : ∃ f : L → P, function.bijective f ∧ ∀ l, point_count P l = line_count L (f l) := begin classical, obtain ⟨f, hf1, hf2⟩ := nondegenerate.exists_injective_of_card_le (ge_of_eq h), have hf3 := (fintype.bijective_iff_injective_and_card f).mpr ⟨hf1, h.symm⟩, refine ⟨f, hf3, λ l, (finset.sum_eq_sum_iff_of_le (by exact λ l hl, has_lines.point_count_le_line_count (hf2 l))).mp ((sum_line_count_eq_sum_point_count P L).symm.trans ((finset.sum_bij (λ l hl, f l) (λ l hl, finset.mem_univ (f l)) (λ l hl, refl (line_count L (f l))) (λ l₁ l₂ hl₁ hl₂ hl, hf1 hl) (λ p hp, _)).symm)) l (finset.mem_univ l)⟩, obtain ⟨l, rfl⟩ := hf3.2 p, exact ⟨l, finset.mem_univ l, rfl⟩, end lemma has_lines.line_count_eq_point_count [has_lines P L] [fintype P] [fintype L] (hPL : fintype.card P = fintype.card L) {p : P} {l : L} (hpl : p ∉ l) : line_count L p = point_count P l := begin classical, obtain ⟨f, hf1, hf2⟩ := has_lines.exists_bijective_of_card_eq hPL, let s : finset (P × L) := set.to_finset {i | i.1 ∈ i.2}, have step1 : ∑ i : P × L, line_count L i.1 = ∑ i : P × L, point_count P i.2, { rw [←finset.univ_product_univ, finset.sum_product_right, finset.sum_product], simp_rw [finset.sum_const, finset.card_univ, hPL, sum_line_count_eq_sum_point_count] }, have step2 : ∑ i in s, line_count L i.1 = ∑ i in s, point_count P i.2, { rw [s.sum_finset_product finset.univ (λ p, set.to_finset {l | p ∈ l})], rw [s.sum_finset_product_right finset.univ (λ l, set.to_finset {p | p ∈ l})], refine (finset.sum_bij (λ l hl, f l) (λ l hl, finset.mem_univ (f l)) (λ l hl, _) (λ _ _ _ _ h, hf1.1 h) (λ p hp, _)).symm, { simp_rw [finset.sum_const, set.to_finset_card, ←nat.card_eq_fintype_card], change (point_count P l) • (point_count P l) = (line_count L (f l)) • (line_count L (f l)), rw hf2 }, { obtain ⟨l, hl⟩ := hf1.2 p, exact ⟨l, finset.mem_univ l, hl.symm⟩ }, all_goals { simp_rw [finset.mem_univ, true_and, set.mem_to_finset], exact λ p, iff.rfl } }, have step3 : ∑ i in sᶜ, line_count L i.1 = ∑ i in sᶜ, point_count P i.2, { rwa [←s.sum_add_sum_compl, ←s.sum_add_sum_compl, step2, add_left_cancel_iff] at step1 }, rw ← set.to_finset_compl at step3, exact ((finset.sum_eq_sum_iff_of_le (by exact λ i hi, has_lines.point_count_le_line_count (set.mem_to_finset.mp hi))).mp step3.symm (p, l) (set.mem_to_finset.mpr hpl)).symm, end lemma has_points.line_count_eq_point_count [has_points P L] [fintype P] [fintype L] (hPL : fintype.card P = fintype.card L) {p : P} {l : L} (hpl : p ∉ l) : line_count L p = point_count P l := (@has_lines.line_count_eq_point_count (dual L) (dual P) _ _ _ _ hPL.symm l p hpl).symm /-- If a nondegenerate configuration has a unique line through any two points, and if `|P| = |L|`, then there is a unique point on any two lines. -/ noncomputable def has_lines.has_points [has_lines P L] [fintype P] [fintype L] (h : fintype.card P = fintype.card L) : has_points P L := let this : ∀ l₁ l₂ : L, l₁ ≠ l₂ → ∃ p : P, p ∈ l₁ ∧ p ∈ l₂ := λ l₁ l₂ hl, begin classical, obtain ⟨f, hf1, hf2⟩ := has_lines.exists_bijective_of_card_eq h, haveI : nontrivial L := ⟨⟨l₁, l₂, hl⟩⟩, haveI := fintype.one_lt_card_iff_nontrivial.mp ((congr_arg _ h).mpr fintype.one_lt_card), have h₁ : ∀ p : P, 0 < line_count L p := λ p, exists.elim (exists_ne p) (λ q hq, (congr_arg _ nat.card_eq_fintype_card).mpr (fintype.card_pos_iff.mpr ⟨⟨mk_line hq, (mk_line_ax hq).2⟩⟩)), have h₂ : ∀ l : L, 0 < point_count P l := λ l, (congr_arg _ (hf2 l)).mpr (h₁ (f l)), obtain ⟨p, hl₁⟩ := fintype.card_pos_iff.mp ((congr_arg _ nat.card_eq_fintype_card).mp (h₂ l₁)), by_cases hl₂ : p ∈ l₂, exact ⟨p, hl₁, hl₂⟩, have key' : fintype.card {q : P // q ∈ l₂} = fintype.card {l : L // p ∈ l}, { exact ((has_lines.line_count_eq_point_count h hl₂).trans nat.card_eq_fintype_card).symm.trans nat.card_eq_fintype_card, }, have : ∀ q : {q // q ∈ l₂}, p ≠ q := λ q hq, hl₂ ((congr_arg (∈ l₂) hq).mpr q.2), let f : {q : P // q ∈ l₂} → {l : L // p ∈ l} := λ q, ⟨mk_line (this q), (mk_line_ax (this q)).1⟩, have hf : function.injective f := λ q₁ q₂ hq, subtype.ext ((eq_or_eq q₁.2 q₂.2 (mk_line_ax (this q₁)).2 ((congr_arg _ (subtype.ext_iff.mp hq)).mpr (mk_line_ax (this q₂)).2)).resolve_right (λ h, (congr_arg _ h).mp hl₂ (mk_line_ax (this q₁)).1)), have key' := ((fintype.bijective_iff_injective_and_card f).mpr ⟨hf, key'⟩).2, obtain ⟨q, hq⟩ := key' ⟨l₁, hl₁⟩, exact ⟨q, (congr_arg _ (subtype.ext_iff.mp hq)).mp (mk_line_ax (this q)).2, q.2⟩, end in { mk_point := λ l₁ l₂ hl, classical.some (this l₁ l₂ hl), mk_point_ax := λ l₁ l₂ hl, classical.some_spec (this l₁ l₂ hl) } /-- If a nondegenerate configuration has a unique point on any two lines, and if `|P| = |L|`, then there is a unique line through any two points. -/ noncomputable def has_points.has_lines [has_points P L] [fintype P] [fintype L] (h : fintype.card P = fintype.card L) : has_lines P L := let this := @has_lines.has_points (dual L) (dual P) _ _ _ _ h.symm in { mk_line := this.mk_point, mk_line_ax := this.mk_point_ax } variables (P L) /-- A projective plane is a nondegenerate configuration in which every pair of lines has an intersection point, every pair of points has a line through them, and which has three points in general position. -/ class projective_plane extends nondegenerate P L : Type u := (mk_point : ∀ {l₁ l₂ : L} (h : l₁ ≠ l₂), P) (mk_point_ax : ∀ {l₁ l₂ : L} (h : l₁ ≠ l₂), mk_point h ∈ l₁ ∧ mk_point h ∈ l₂) (mk_line : ∀ {p₁ p₂ : P} (h : p₁ ≠ p₂), L) (mk_line_ax : ∀ {p₁ p₂ : P} (h : p₁ ≠ p₂), p₁ ∈ mk_line h ∧ p₂ ∈ mk_line h) (exists_config : ∃ (p₁ p₂ p₃ : P) (l₁ l₂ l₃ : L), p₁ ∉ l₂ ∧ p₁ ∉ l₃ ∧ p₂ ∉ l₁ ∧ p₂ ∈ l₂ ∧ p₂ ∈ l₃ ∧ p₃ ∉ l₁ ∧ p₃ ∈ l₂ ∧ p₃ ∉ l₃) namespace projective_plane @[priority 100] -- see Note [lower instance priority] instance has_points [h : projective_plane P L] : has_points P L := { .. h } @[priority 100] -- see Note [lower instance priority] instance has_lines [h : projective_plane P L] : has_lines P L := { .. h } instance [projective_plane P L] : projective_plane (dual L) (dual P) := { mk_line := @mk_point P L _ _, mk_line_ax := λ _ _, mk_point_ax, mk_point := @mk_line P L _ _, mk_point_ax := λ _ _, mk_line_ax, exists_config := by { obtain ⟨p₁, p₂, p₃, l₁, l₂, l₃, h₁₂, h₁₃, h₂₁, h₂₂, h₂₃, h₃₁, h₃₂, h₃₃⟩ := @exists_config P L _ _, exact ⟨l₁, l₂, l₃, p₁, p₂, p₃, h₂₁, h₃₁, h₁₂, h₂₂, h₃₂, h₁₃, h₂₃, h₃₃⟩ }, .. dual.nondegenerate P L } /-- The order of a projective plane is one less than the number of lines through an arbitrary point. Equivalently, it is one less than the number of points on an arbitrary line. -/ noncomputable def order [projective_plane P L] : ℕ := line_count L (classical.some (@exists_config P L _ _)) - 1 variables [fintype P] [fintype L] lemma card_points_eq_card_lines [projective_plane P L] : fintype.card P = fintype.card L := le_antisymm (has_lines.card_le P L) (has_points.card_le P L) variables {P} (L) lemma line_count_eq_line_count [projective_plane P L] (p q : P) : line_count L p = line_count L q := begin obtain ⟨p₁, p₂, p₃, l₁, l₂, l₃, h₁₂, h₁₃, h₂₁, h₂₂, h₂₃, h₃₁, h₃₂, h₃₃⟩ := exists_config, have h := card_points_eq_card_lines P L, let n := line_count L p₂, have hp₂ : line_count L p₂ = n := rfl, have hl₁ : point_count P l₁ = n := (has_lines.line_count_eq_point_count h h₂₁).symm.trans hp₂, have hp₃ : line_count L p₃ = n := (has_lines.line_count_eq_point_count h h₃₁).trans hl₁, have hl₃ : point_count P l₃ = n := (has_lines.line_count_eq_point_count h h₃₃).symm.trans hp₃, have hp₁ : line_count L p₁ = n := (has_lines.line_count_eq_point_count h h₁₃).trans hl₃, have hl₂ : point_count P l₂ = n := (has_lines.line_count_eq_point_count h h₁₂).symm.trans hp₁, suffices : ∀ p : P, line_count L p = n, { exact (this p).trans (this q).symm }, refine λ p, or_not.elim (λ h₂, _) (λ h₂, (has_lines.line_count_eq_point_count h h₂).trans hl₂), refine or_not.elim (λ h₃, _) (λ h₃, (has_lines.line_count_eq_point_count h h₃).trans hl₃), rwa (eq_or_eq h₂ h₂₂ h₃ h₂₃).resolve_right (λ h, h₃₃ ((congr_arg (has_mem.mem p₃) h).mp h₃₂)), end variables (P) {L} lemma point_count_eq_point_count [projective_plane P L] (l m : L) : point_count P l = point_count P m := line_count_eq_line_count (dual P) l m variables {P L} lemma line_count_eq_point_count [projective_plane P L] (p : P) (l : L) : line_count L p = point_count P l := exists.elim (exists_point l) (λ q hq, (line_count_eq_line_count L p q).trans (has_lines.line_count_eq_point_count (card_points_eq_card_lines P L) hq)) variables (P L) lemma dual.order [projective_plane P L] : order (dual L) (dual P) = order P L := congr_arg (λ n, n - 1) (line_count_eq_point_count _ _) variables {P} (L) lemma line_count_eq [projective_plane P L] (p : P) : line_count L p = order P L + 1 := begin classical, obtain ⟨q, -, -, l, -, -, -, -, h, -⟩ := classical.some_spec (@exists_config P L _ _), rw [order, line_count_eq_line_count L p q, line_count_eq_line_count L (classical.some _) q, line_count, nat.card_eq_fintype_card, nat.sub_add_cancel], exact fintype.card_pos_iff.mpr ⟨⟨l, h⟩⟩, end variables (P) {L} lemma point_count_eq [projective_plane P L] (l : L) : point_count P l = order P L + 1 := (line_count_eq (dual P) l).trans (congr_arg (λ n, n + 1) (dual.order P L)) variables (P L) lemma one_lt_order [projective_plane P L] : 1 < order P L := begin obtain ⟨p₁, p₂, p₃, l₁, l₂, l₃, -, -, h₂₁, h₂₂, h₂₃, h₃₁, h₃₂, h₃₃⟩ := @exists_config P L _ _, classical, rw [←add_lt_add_iff_right, ←point_count_eq, point_count, nat.card_eq_fintype_card], simp_rw [fintype.two_lt_card_iff, ne, subtype.ext_iff], have h := mk_point_ax (λ h, h₂₁ ((congr_arg _ h).mpr h₂₂)), exact ⟨⟨mk_point _, h.2⟩, ⟨p₂, h₂₂⟩, ⟨p₃, h₃₂⟩, ne_of_mem_of_not_mem h.1 h₂₁, ne_of_mem_of_not_mem h.1 h₃₁, ne_of_mem_of_not_mem h₂₃ h₃₃⟩, end variables {P} (L) lemma two_lt_line_count [projective_plane P L] (p : P) : 2 < line_count L p := by simpa only [line_count_eq L p, nat.succ_lt_succ_iff] using one_lt_order P L variables (P) {L} lemma two_lt_point_count [projective_plane P L] (l : L) : 2 < point_count P l := by simpa only [point_count_eq P l, nat.succ_lt_succ_iff] using one_lt_order P L variables (P) (L) lemma card_points [projective_plane P L] : fintype.card P = order P L ^ 2 + order P L + 1 := begin let p : P := (classical.some (@exists_config P L _ _)), let ϕ : {q // q ≠ p} ≃ Σ (l : {l : L // p ∈ l}), {q // q ∈ l.1 ∧ q ≠ p} := { to_fun := λ q, ⟨⟨mk_line q.2, (mk_line_ax q.2).2⟩, q, (mk_line_ax q.2).1, q.2⟩, inv_fun := λ lq, ⟨lq.2, lq.2.2.2⟩, left_inv := λ q, subtype.ext rfl, right_inv := λ lq, sigma.subtype_ext (subtype.ext ((eq_or_eq (mk_line_ax lq.2.2.2).1 (mk_line_ax lq.2.2.2).2 lq.2.2.1 lq.1.2).resolve_left lq.2.2.2)) rfl }, classical, have h1 : fintype.card {q // q ≠ p} + 1 = fintype.card P, { apply (eq_tsub_iff_add_eq_of_le (nat.succ_le_of_lt (fintype.card_pos_iff.mpr ⟨p⟩))).mp, convert (fintype.card_subtype_compl).trans (congr_arg _ (fintype.card_subtype_eq p)) }, have h2 : ∀ l : {l : L // p ∈ l}, fintype.card {q // q ∈ l.1 ∧ q ≠ p} = order P L, { intro l, rw [←fintype.card_congr (equiv.subtype_subtype_equiv_subtype_inter _ _), fintype.card_subtype_compl, ←nat.card_eq_fintype_card], refine tsub_eq_of_eq_add ((point_count_eq P l.1).trans _), rw ← fintype.card_subtype_eq (⟨p, l.2⟩ : {q : P // q ∈ l.1}), simp_rw subtype.ext_iff_val }, simp_rw [←h1, fintype.card_congr ϕ, fintype.card_sigma, h2, finset.sum_const, finset.card_univ], rw [←nat.card_eq_fintype_card, ←line_count, line_count_eq, smul_eq_mul, nat.succ_mul, sq], end lemma card_lines [projective_plane P L] : fintype.card L = order P L ^ 2 + order P L + 1 := (card_points (dual L) (dual P)).trans (congr_arg (λ n, n ^ 2 + n + 1) (dual.order P L)) end projective_plane end configuration
938700247c3733017e1eb607c066104656ca77cd
2fbe653e4bc441efde5e5d250566e65538709888
/src/analysis/normed_space/banach.lean
634534c9db9b8c5554d43f3309f2d7717fb29900
[ "Apache-2.0" ]
permissive
aceg00/mathlib
5e15e79a8af87ff7eb8c17e2629c442ef24e746b
8786ea6d6d46d6969ac9a869eb818bf100802882
refs/heads/master
1,649,202,698,930
1,580,924,783,000
1,580,924,783,000
149,197,272
0
0
Apache-2.0
1,537,224,208,000
1,537,224,207,000
null
UTF-8
Lean
false
false
11,019
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 Banach spaces, i.e., complete vector spaces. This file contains the Banach open mapping theorem, i.e., the fact that a bijective bounded linear map between Banach spaces has a bounded inverse. -/ import topology.metric_space.baire analysis.normed_space.bounded_linear_maps open function metric set filter finset open_locale classical topological_space variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [complete_space E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [complete_space F] [normed_space 𝕜 F] {f : E → F} include 𝕜 set_option class.instance_max_depth 70 /-- The Banach open mapping theorem: if a bounded linear map between Banach spaces is onto, then any point has a preimage with controlled norm. -/ theorem exists_preimage_norm_le (hf : is_bounded_linear_map 𝕜 f) (surj : surjective f) : ∃C, 0 < C ∧ ∀y, ∃x, f x = y ∧ ∥x∥ ≤ C * ∥y∥ := begin have lin := hf.to_is_linear_map, haveI : nonempty F := ⟨0⟩, /- First step of the proof (using completeness of `F`): by Baire's theorem, there exists a ball in E whose image closure has nonempty interior. Rescaling everything, it follows that any `y ∈ F` is arbitrarily well approached by images of elements of norm at most `C * ∥y∥`. For further use, we will only need such an element whose image is within distance ∥y∥/2 of y, to apply an iterative process. -/ have A : (⋃n:ℕ, closure (f '' (ball 0 n))) = univ, { refine subset.antisymm (subset_univ _) (λy hy, _), rcases surj y with ⟨x, hx⟩, rcases exists_nat_gt (∥x∥) with ⟨n, hn⟩, refine mem_Union.2 ⟨n, subset_closure _⟩, refine (mem_image _ _ _).2 ⟨x, ⟨_, hx⟩⟩, rwa [mem_ball, dist_eq_norm, sub_zero] }, have : ∃(n:ℕ) y ε, 0 < ε ∧ ball y ε ⊆ closure (f '' (ball 0 n)) := nonempty_interior_of_Union_of_closed (λn, is_closed_closure) A, have : ∃C, 0 ≤ C ∧ ∀y, ∃x, dist (f x) y ≤ (1/2) * ∥y∥ ∧ ∥x∥ ≤ C * ∥y∥, { rcases this with ⟨n, a, ε, ⟨εpos, H⟩⟩, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine ⟨(ε/2)⁻¹ * ∥c∥ * 2 * n, _, λy, _⟩, { refine mul_nonneg (mul_nonneg (mul_nonneg _ (norm_nonneg _)) (by norm_num)) _, refine inv_nonneg.2 (div_nonneg' (le_of_lt εpos) (by norm_num)), exact nat.cast_nonneg n }, { by_cases hy : y = 0, { use 0, simp [hy, lin.map_zero] }, { rcases rescale_to_shell hc (half_pos εpos) hy with ⟨d, hd, ydle, leyd, dinv⟩, let δ := ∥d∥ * ∥y∥/4, have δpos : 0 < δ := div_pos (mul_pos ((norm_pos_iff _).2 hd) ((norm_pos_iff _).2 hy)) (by norm_num), have : a + d • y ∈ ball a ε, by simp [dist_eq_norm, lt_of_le_of_lt ydle (half_lt_self εpos)], rcases mem_closure_iff'.1 (H this) _ δpos with ⟨z₁, z₁im, h₁⟩, rcases (mem_image _ _ _).1 z₁im with ⟨x₁, hx₁, xz₁⟩, rw ← xz₁ at h₁, rw [mem_ball, dist_eq_norm, sub_zero] at hx₁, have : a ∈ ball a ε, by { simp, exact εpos }, rcases mem_closure_iff'.1 (H this) _ δpos with ⟨z₂, z₂im, h₂⟩, rcases (mem_image _ _ _).1 z₂im with ⟨x₂, hx₂, xz₂⟩, rw ← xz₂ at h₂, rw [mem_ball, dist_eq_norm, sub_zero] at hx₂, let x := x₁ - x₂, have I : ∥f x - d • y∥ ≤ 2 * δ := calc ∥f x - d • y∥ = ∥f x₁ - (a + d • y) - (f x₂ - a)∥ : by { congr' 1, simp only [x, lin.map_sub], abel } ... ≤ ∥f x₁ - (a + d • y)∥ + ∥f x₂ - a∥ : norm_sub_le _ _ ... ≤ δ + δ : begin apply add_le_add, { rw [← dist_eq_norm, dist_comm], exact le_of_lt h₁ }, { rw [← dist_eq_norm, dist_comm], exact le_of_lt h₂ } end ... = 2 * δ : (two_mul _).symm, have J : ∥f (d⁻¹ • x) - y∥ ≤ 1/2 * ∥y∥ := calc ∥f (d⁻¹ • x) - y∥ = ∥d⁻¹ • f x - (d⁻¹ * d) • y∥ : by rwa [lin.smul, inv_mul_cancel, one_smul] ... = ∥d⁻¹ • (f x - d • y)∥ : by rw [mul_smul, smul_sub] ... = ∥d∥⁻¹ * ∥f x - d • y∥ : by rw [norm_smul, normed_field.norm_inv] ... ≤ ∥d∥⁻¹ * (2 * δ) : begin apply mul_le_mul_of_nonneg_left I, rw inv_nonneg, exact norm_nonneg _ end ... = (∥d∥⁻¹ * ∥d∥) * ∥y∥ /2 : by { simp only [δ], ring } ... = ∥y∥/2 : by { rw [inv_mul_cancel, one_mul], simp [norm_eq_zero, hd] } ... = (1/2) * ∥y∥ : by ring, rw ← dist_eq_norm at J, have 𝕜 : ∥d⁻¹ • x∥ ≤ (ε / 2)⁻¹ * ∥c∥ * 2 * ↑n * ∥y∥ := calc ∥d⁻¹ • x∥ = ∥d∥⁻¹ * ∥x₁ - x₂∥ : by rw [norm_smul, normed_field.norm_inv] ... ≤ ((ε / 2)⁻¹ * ∥c∥ * ∥y∥) * (n + n) : begin refine mul_le_mul dinv _ (norm_nonneg _) _, { exact le_trans (norm_sub_le _ _) (add_le_add (le_of_lt hx₁) (le_of_lt hx₂)) }, { apply mul_nonneg (mul_nonneg _ (norm_nonneg _)) (norm_nonneg _), exact inv_nonneg.2 (le_of_lt (half_pos εpos)) } end ... = (ε / 2)⁻¹ * ∥c∥ * 2 * ↑n * ∥y∥ : by ring, exact ⟨d⁻¹ • x, J, 𝕜⟩ } } }, rcases this with ⟨C, C0, hC⟩, /- Second step of the proof: starting from `y`, we want an exact preimage of `y`. Let `g y` be the approximate preimage of `y` given by the first step, and `h y = y - f(g y)` the part that has no preimage yet. We will iterate this process, taking the approximate preimage of `h y`, leaving only `h^2 y` without preimage yet, and so on. Let `u n` be the approximate preimage of `h^n y`. Then `u` is a converging series, and by design the sum of the series is a preimage of `y`. This uses completeness of `E`. -/ choose g hg using hC, let h := λy, y - f (g y), have hle : ∀y, ∥h y∥ ≤ (1/2) * ∥y∥, { assume y, rw [← dist_eq_norm, dist_comm], exact (hg y).1 }, refine ⟨2 * C + 1, by linarith, λy, _⟩, have hnle : ∀n:ℕ, ∥(h^[n]) y∥ ≤ (1/2)^n * ∥y∥, { assume n, induction n with n IH, { simp only [one_div_eq_inv, nat.nat_zero_eq_zero, one_mul, nat.iterate_zero, pow_zero] }, { rw [nat.iterate_succ'], apply le_trans (hle _) _, rw [pow_succ, mul_assoc], apply mul_le_mul_of_nonneg_left IH, norm_num } }, let u := λn, g((h^[n]) y), have ule : ∀n, ∥u n∥ ≤ (1/2)^n * (C * ∥y∥), { assume n, apply le_trans (hg _).2 _, calc C * ∥(h^[n]) y∥ ≤ C * ((1/2)^n * ∥y∥) : mul_le_mul_of_nonneg_left (hnle n) C0 ... = (1 / 2) ^ n * (C * ∥y∥) : by ring }, have sNu : summable (λn, ∥u n∥), { refine summable_of_nonneg_of_le (λn, norm_nonneg _) ule _, exact summable_mul_right _ (summable_geometric (by norm_num) (by norm_num)) }, have su : summable u := summable_of_summable_norm sNu, let x := tsum u, have x_ineq : ∥x∥ ≤ (2 * C + 1) * ∥y∥ := calc ∥x∥ ≤ (∑n, ∥u n∥) : norm_tsum_le_tsum_norm sNu ... ≤ (∑n, (1/2)^n * (C * ∥y∥)) : tsum_le_tsum ule sNu (summable_mul_right _ summable_geometric_two) ... = (∑n, (1/2)^n) * (C * ∥y∥) : by { rw tsum_mul_right, exact summable_geometric_two } ... = 2 * (C * ∥y∥) : by rw tsum_geometric_two ... = 2 * C * ∥y∥ + 0 : by rw [add_zero, mul_assoc] ... ≤ 2 * C * ∥y∥ + ∥y∥ : add_le_add (le_refl _) (norm_nonneg _) ... = (2 * C + 1) * ∥y∥ : by ring, have fsumeq : ∀n:ℕ, f((range n).sum u) = y - (h^[n]) y, { assume n, induction n with n IH, { simp [lin.map_zero] }, { rw [sum_range_succ, lin.add, IH, nat.iterate_succ'], simp [u, h] } }, have : tendsto (λn, (range n).sum u) at_top (𝓝 x) := tendsto_sum_nat_of_has_sum (has_sum_tsum su), have L₁ : tendsto (λn, f((range n).sum u)) at_top (𝓝 (f x)) := tendsto.comp (hf.continuous.tendsto _) this, simp only [fsumeq] at L₁, have L₂ : tendsto (λn, y - (h^[n]) y) at_top (𝓝 (y - 0)), { refine tendsto_const_nhds.sub _, rw tendsto_iff_norm_tendsto_zero, simp only [sub_zero], refine squeeze_zero (λ_, norm_nonneg _) hnle _, have : 0 = 0 * ∥y∥, by rw zero_mul, rw this, refine tendsto.mul _ tendsto_const_nhds, exact tendsto_pow_at_top_nhds_0_of_lt_1 (by norm_num) (by norm_num) }, have feq : f x = y - 0, { apply tendsto_nhds_unique _ L₁ L₂, simp }, rw sub_zero at feq, exact ⟨x, feq, x_ineq⟩ end /-- The Banach open mapping theorem: a surjective bounded linear map between Banach spaces is open. -/ theorem open_mapping (hf : is_bounded_linear_map 𝕜 f) (surj : surjective f) : is_open_map f := begin assume s hs, have lin := hf.to_is_linear_map, rcases exists_preimage_norm_le hf surj with ⟨C, Cpos, hC⟩, refine is_open_iff.2 (λy yfs, _), rcases mem_image_iff_bex.1 yfs with ⟨x, xs, fxy⟩, rcases is_open_iff.1 hs x xs with ⟨ε, εpos, hε⟩, refine ⟨ε/C, div_pos εpos Cpos, λz hz, _⟩, rcases hC (z-y) with ⟨w, wim, wnorm⟩, have : f (x + w) = z, by { rw [lin.add, wim, fxy], abel }, rw ← this, have : x + w ∈ ball x ε := calc dist (x+w) x = ∥w∥ : by { rw dist_eq_norm, simp } ... ≤ C * ∥z - y∥ : wnorm ... < C * (ε/C) : begin apply mul_lt_mul_of_pos_left _ Cpos, rwa [mem_ball, dist_eq_norm] at hz, end ... = ε : mul_div_cancel' _ (ne_of_gt Cpos), exact set.mem_image_of_mem _ (hε this) end /-- If a bounded linear map is a bijection, then its inverse is also a bounded linear map. -/ theorem linear_equiv.is_bounded_inv (e : E ≃ₗ[𝕜] F) (h : is_bounded_linear_map 𝕜 e.to_fun) : is_bounded_linear_map 𝕜 e.inv_fun := { bound := begin have : surjective e.to_fun := (equiv.bijective e.to_equiv).2, rcases exists_preimage_norm_le h this with ⟨M, Mpos, hM⟩, refine ⟨M, Mpos, λy, _⟩, rcases hM y with ⟨x, hx, xnorm⟩, have : x = e.inv_fun y, by { rw ← hx, exact (e.symm_apply_apply _).symm }, rwa ← this end, ..e.symm } /-- Associating to a linear equivalence between Banach spaces a continuous linear equivalence when the direct map is continuous, thanks to the Banach open mapping theorem that ensures that the inverse map is also continuous. -/ def linear_equiv.to_continuous_linear_equiv_of_continuous (e : E ≃ₗ[𝕜] F) (h : continuous e) : E ≃L[𝕜] F := { continuous_to_fun := h, continuous_inv_fun := let f : E →L[𝕜] F := { cont := h, ..e} in (e.is_bounded_inv f.is_bounded_linear_map).continuous, ..e }
3d08d2ee0262ecd610d8dd0831701f681aac5086
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/group_theory/group_action/basic.lean
c9dfe90ea91b90dfa3bfe7ad4383dddfd0e0b9a4
[ "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
14,366
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes -/ import data.fintype.card import group_theory.group_action.defs import group_theory.group_action.group import data.setoid.basic import data.set.pointwise.smul import group_theory.subgroup.basic /-! # Basic properties of group actions > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file primarily concerns itself with orbits, stabilizers, and other objects defined in terms of actions. Despite this file being called `basic`, low-level helper lemmas for algebraic manipulation of `•` belong elsewhere. ## Main definitions * `mul_action.orbit` * `mul_action.fixed_points` * `mul_action.fixed_by` * `mul_action.stabilizer` -/ universes u v w variables {α : Type u} {β : Type v} {γ : Type w} open_locale pointwise open function namespace mul_action variables (α) [monoid α] [mul_action α β] /-- The orbit of an element under an action. -/ @[to_additive "The orbit of an element under an action."] def orbit (b : β) := set.range (λ x : α, x • b) variable {α} @[to_additive] lemma mem_orbit_iff {b₁ b₂ : β} : b₂ ∈ orbit α b₁ ↔ ∃ x : α, x • b₁ = b₂ := iff.rfl @[simp, to_additive] lemma mem_orbit (b : β) (x : α) : x • b ∈ orbit α b := ⟨x, rfl⟩ @[simp, to_additive] lemma mem_orbit_self (b : β) : b ∈ orbit α b := ⟨1, by simp [mul_action.one_smul]⟩ @[to_additive] lemma orbit_nonempty (b : β) : set.nonempty (orbit α b) := set.range_nonempty _ @[to_additive] lemma maps_to_smul_orbit (a : α) (b : β) : set.maps_to ((•) a) (orbit α b) (orbit α b) := set.range_subset_iff.2 $ λ a', ⟨a * a', mul_smul _ _ _⟩ @[to_additive] lemma smul_orbit_subset (a : α) (b : β) : a • orbit α b ⊆ orbit α b := (maps_to_smul_orbit a b).image_subset @[to_additive] lemma orbit_smul_subset (a : α) (b : β) : orbit α (a • b) ⊆ orbit α b := set.range_subset_iff.2 $ λ a', mul_smul a' a b ▸ mem_orbit _ _ @[to_additive] instance {b : β} : mul_action α (orbit α b) := { smul := λ a, (maps_to_smul_orbit a b).restrict _ _ _, one_smul := λ a, subtype.ext (one_smul α a), mul_smul := λ a a' b', subtype.ext (mul_smul a a' b') } @[simp, to_additive] lemma orbit.coe_smul {b : β} {a : α} {b' : orbit α b} : ↑(a • b') = a • (b' : β) := rfl variables (α) (β) /-- The set of elements fixed under the whole action. -/ @[to_additive "The set of elements fixed under the whole action."] def fixed_points : set β := {b : β | ∀ x : α, x • b = b} /-- `fixed_by g` is the subfield of elements fixed by `g`. -/ @[to_additive "`fixed_by g` is the subfield of elements fixed by `g`."] def fixed_by (g : α) : set β := { x | g • x = x } @[to_additive] theorem fixed_eq_Inter_fixed_by : fixed_points α β = ⋂ g : α, fixed_by α β g := set.ext $ λ x, ⟨λ hx, set.mem_Inter.2 $ λ g, hx g, λ hx g, by exact (set.mem_Inter.1 hx g : _)⟩ variables {α} (β) @[simp, to_additive] lemma mem_fixed_points {b : β} : b ∈ fixed_points α β ↔ ∀ x : α, x • b = b := iff.rfl @[simp, to_additive] lemma mem_fixed_by {g : α} {b : β} : b ∈ fixed_by α β g ↔ g • b = b := iff.rfl @[to_additive] lemma mem_fixed_points' {b : β} : b ∈ fixed_points α β ↔ (∀ b', b' ∈ orbit α b → b' = b) := ⟨λ h b h₁, let ⟨x, hx⟩ := mem_orbit_iff.1 h₁ in hx ▸ h x, λ h b, h _ (mem_orbit _ _)⟩ variables (α) {β} /-- The stabilizer of a point `b` as a submonoid of `α`. -/ @[to_additive "The stabilizer of a point `b` as an additive submonoid of `α`."] def stabilizer.submonoid (b : β) : submonoid α := { carrier := { a | a • b = b }, one_mem' := one_smul _ b, mul_mem' := λ a a' (ha : a • b = b) (hb : a' • b = b), show (a * a') • b = b, by rw [←smul_smul, hb, ha] } @[simp, to_additive] lemma mem_stabilizer_submonoid_iff {b : β} {a : α} : a ∈ stabilizer.submonoid α b ↔ a • b = b := iff.rfl @[to_additive] lemma orbit_eq_univ [is_pretransitive α β] (x : β) : orbit α x = set.univ := (surjective_smul α x).range_eq variables {α} {β} @[to_additive] lemma mem_fixed_points_iff_card_orbit_eq_one {a : β} [fintype (orbit α a)] : a ∈ fixed_points α β ↔ fintype.card (orbit α a) = 1 := begin rw [fintype.card_eq_one_iff, mem_fixed_points], split, { exact λ h, ⟨⟨a, mem_orbit_self _⟩, λ ⟨b, ⟨x, hx⟩⟩, subtype.eq $ by simp [h x, hx.symm]⟩ }, { assume h x, rcases h with ⟨⟨z, hz⟩, hz₁⟩, calc x • a = z : subtype.mk.inj (hz₁ ⟨x • a, mem_orbit _ _⟩) ... = a : (subtype.mk.inj (hz₁ ⟨a, mem_orbit_self _⟩)).symm } end end mul_action namespace mul_action variable (α) variables [group α] [mul_action α β] /-- The stabilizer of an element under an action, i.e. what sends the element to itself. A subgroup. -/ @[to_additive "The stabilizer of an element under an action, i.e. what sends the element to itself. An additive subgroup."] def stabilizer (b : β) : subgroup α := { inv_mem' := λ a (ha : a • b = b), show a⁻¹ • b = b, by rw [inv_smul_eq_iff, ha] ..stabilizer.submonoid α b } variables {α} {β} @[simp, to_additive] lemma mem_stabilizer_iff {b : β} {a : α} : a ∈ stabilizer α b ↔ a • b = b := iff.rfl @[simp, to_additive] lemma smul_orbit (a : α) (b : β) : a • orbit α b = orbit α b := (smul_orbit_subset a b).antisymm $ calc orbit α b = a • a⁻¹ • orbit α b : (smul_inv_smul _ _).symm ... ⊆ a • orbit α b : set.image_subset _ (smul_orbit_subset _ _) @[simp, to_additive] lemma orbit_smul (a : α) (b : β) : orbit α (a • b) = orbit α b := (orbit_smul_subset a b).antisymm $ calc orbit α b = orbit α (a⁻¹ • a • b) : by rw inv_smul_smul ... ⊆ orbit α (a • b) : orbit_smul_subset _ _ /-- The action of a group on an orbit is transitive. -/ @[to_additive "The action of an additive group on an orbit is transitive."] instance (x : β) : is_pretransitive α (orbit α x) := ⟨by { rintro ⟨_, a, rfl⟩ ⟨_, b, rfl⟩, use b * a⁻¹, ext1, simp [mul_smul] }⟩ @[to_additive] lemma orbit_eq_iff {a b : β} : orbit α a = orbit α b ↔ a ∈ orbit α b:= ⟨λ h, h ▸ mem_orbit_self _, λ ⟨c, hc⟩, hc ▸ orbit_smul _ _⟩ variables (α) {β} @[to_additive] lemma mem_orbit_smul (g : α) (a : β) : a ∈ orbit α (g • a) := by simp only [orbit_smul, mem_orbit_self] @[to_additive] lemma smul_mem_orbit_smul (g h : α) (a : β) : g • a ∈ orbit α (h • a) := by simp only [orbit_smul, mem_orbit] variables (α) (β) /-- The relation 'in the same orbit'. -/ @[to_additive "The relation 'in the same orbit'."] def orbit_rel : setoid β := { r := λ a b, a ∈ orbit α b, iseqv := ⟨mem_orbit_self, λ a b, by simp [orbit_eq_iff.symm, eq_comm], λ a b, by simp [orbit_eq_iff.symm, eq_comm] {contextual := tt}⟩ } local attribute [instance] orbit_rel variables {α} {β} @[to_additive] lemma orbit_rel_apply {x y : β} : (orbit_rel α β).rel x y ↔ x ∈ orbit α y := iff.rfl /-- When you take a set `U` in `β`, push it down to the quotient, and pull back, you get the union of the orbit of `U` under `α`. -/ @[to_additive "When you take a set `U` in `β`, push it down to the quotient, and pull back, you get the union of the orbit of `U` under `α`."] lemma quotient_preimage_image_eq_union_mul (U : set β) : quotient.mk ⁻¹' (quotient.mk '' U) = ⋃ a : α, ((•) a) '' U := begin set f : β → quotient (mul_action.orbit_rel α β) := quotient.mk, ext, split, { rintros ⟨y , hy, hxy⟩, obtain ⟨a, rfl⟩ := quotient.exact hxy, rw set.mem_Union, exact ⟨a⁻¹, a • x, hy, inv_smul_smul a x⟩ }, { intros hx, rw set.mem_Union at hx, obtain ⟨a, u, hu₁, hu₂⟩ := hx, rw [set.mem_preimage, set.mem_image_iff_bex], refine ⟨a⁻¹ • x, _, by simp only [quotient.eq]; use a⁻¹⟩, rw ← hu₂, convert hu₁, simp only [inv_smul_smul], }, end @[to_additive] lemma disjoint_image_image_iff {U V : set β} : disjoint (quotient.mk '' U) (quotient.mk '' V) ↔ ∀ x ∈ U, ∀ a : α, a • x ∉ V := begin set f : β → quotient (mul_action.orbit_rel α β) := quotient.mk, refine ⟨λ h x x_in_U a a_in_V, h.le_bot ⟨⟨x, x_in_U, quotient.sound ⟨a⁻¹, _⟩⟩, ⟨a • x, a_in_V, rfl⟩⟩, _⟩, { simp }, { intro h, rw set.disjoint_left, rintro x ⟨y, hy₁, hy₂⟩ ⟨z, hz₁, hz₂⟩, obtain ⟨a, rfl⟩ := quotient.exact (hz₂.trans hy₂.symm), exact h y hy₁ a hz₁ } end @[to_additive] lemma image_inter_image_iff (U V : set β) : (quotient.mk '' U) ∩ (quotient.mk '' V) = ∅ ↔ ∀ x ∈ U, ∀ a : α, a • x ∉ V := set.disjoint_iff_inter_eq_empty.symm.trans disjoint_image_image_iff variables (α β) /-- The quotient by `mul_action.orbit_rel`, given a name to enable dot notation. -/ @[reducible, to_additive "The quotient by `add_action.orbit_rel`, given a name to enable dot notation."] def orbit_rel.quotient : Type* := quotient $ orbit_rel α β variables {α β} /-- The orbit corresponding to an element of the quotient by `mul_action.orbit_rel` -/ @[to_additive "The orbit corresponding to an element of the quotient by `add_action.orbit_rel`"] def orbit_rel.quotient.orbit (x : orbit_rel.quotient α β) : set β := quotient.lift_on' x (orbit α) $ λ _ _, mul_action.orbit_eq_iff.2 @[simp, to_additive] lemma orbit_rel.quotient.orbit_mk (b : β) : orbit_rel.quotient.orbit (quotient.mk' b : orbit_rel.quotient α β) = orbit α b := rfl @[to_additive] lemma orbit_rel.quotient.mem_orbit {b : β} {x : orbit_rel.quotient α β} : b ∈ x.orbit ↔ quotient.mk' b = x := by { induction x using quotient.induction_on', rw quotient.eq', refl } /-- Note that `hφ = quotient.out_eq'` is a useful choice here. -/ @[to_additive "Note that `hφ = quotient.out_eq'` is a useful choice here."] lemma orbit_rel.quotient.orbit_eq_orbit_out (x : orbit_rel.quotient α β) {φ : orbit_rel.quotient α β → β} (hφ : right_inverse φ quotient.mk') : orbit_rel.quotient.orbit x = orbit α (φ x) := begin conv_lhs { rw ←hφ x }, induction x using quotient.induction_on', refl, end variables (α) (β) local notation `Ω` := orbit_rel.quotient α β /-- Decomposition of a type `X` as a disjoint union of its orbits under a group action. This version is expressed in terms of `mul_action.orbit_rel.quotient.orbit` instead of `mul_action.orbit`, to avoid mentioning `quotient.out'`. -/ @[to_additive "Decomposition of a type `X` as a disjoint union of its orbits under an additive group action. This version is expressed in terms of `add_action.orbit_rel.quotient.orbit` instead of `add_action.orbit`, to avoid mentioning `quotient.out'`. "] def self_equiv_sigma_orbits' : β ≃ Σ ω : Ω, ω.orbit := calc β ≃ Σ (ω : Ω), {b // quotient.mk' b = ω} : (equiv.sigma_fiber_equiv quotient.mk').symm ... ≃ Σ (ω : Ω), ω.orbit : equiv.sigma_congr_right $ λ ω, equiv.subtype_equiv_right $ λ x, orbit_rel.quotient.mem_orbit.symm /-- Decomposition of a type `X` as a disjoint union of its orbits under a group action. -/ @[to_additive "Decomposition of a type `X` as a disjoint union of its orbits under an additive group action."] def self_equiv_sigma_orbits : β ≃ Σ (ω : Ω), orbit α ω.out' := (self_equiv_sigma_orbits' α β).trans $ equiv.sigma_congr_right $ λ i, equiv.set.of_eq $ orbit_rel.quotient.orbit_eq_orbit_out _ quotient.out_eq' variables {α β} /-- If the stabilizer of `x` is `S`, then the stabilizer of `g • x` is `gSg⁻¹`. -/ lemma stabilizer_smul_eq_stabilizer_map_conj (g : α) (x : β) : (stabilizer α (g • x) = (stabilizer α x).map (mul_aut.conj g).to_monoid_hom) := begin ext h, rw [mem_stabilizer_iff, ← smul_left_cancel_iff g⁻¹, smul_smul, smul_smul, smul_smul, mul_left_inv, one_smul, ← mem_stabilizer_iff, subgroup.mem_map_equiv, mul_aut.conj_symm_apply] end /-- A bijection between the stabilizers of two elements in the same orbit. -/ noncomputable def stabilizer_equiv_stabilizer_of_orbit_rel {x y : β} (h : (orbit_rel α β).rel x y) : stabilizer α x ≃* stabilizer α y := let g : α := classical.some h in have hg : g • y = x := classical.some_spec h, have this : stabilizer α x = (stabilizer α y).map (mul_aut.conj g).to_monoid_hom, by rw [← hg, stabilizer_smul_eq_stabilizer_map_conj], (mul_equiv.subgroup_congr this).trans ((mul_aut.conj g).subgroup_map $ stabilizer α y).symm end mul_action namespace add_action variables [add_group α] [add_action α β] /-- If the stabilizer of `x` is `S`, then the stabilizer of `g +ᵥ x` is `g + S + (-g)`. -/ lemma stabilizer_vadd_eq_stabilizer_map_conj (g : α) (x : β) : (stabilizer α (g +ᵥ x) = (stabilizer α x).map (add_aut.conj g).to_add_monoid_hom) := begin ext h, rw [mem_stabilizer_iff, ← vadd_left_cancel_iff (-g) , vadd_vadd, vadd_vadd, vadd_vadd, add_left_neg, zero_vadd, ← mem_stabilizer_iff, add_subgroup.mem_map_equiv, add_aut.conj_symm_apply] end /-- A bijection between the stabilizers of two elements in the same orbit. -/ noncomputable def stabilizer_equiv_stabilizer_of_orbit_rel {x y : β} (h : (orbit_rel α β).rel x y) : stabilizer α x ≃+ stabilizer α y := let g : α := classical.some h in have hg : g +ᵥ y = x := classical.some_spec h, have this : stabilizer α x = (stabilizer α y).map (add_aut.conj g).to_add_monoid_hom, by rw [← hg, stabilizer_vadd_eq_stabilizer_map_conj], (add_equiv.add_subgroup_congr this).trans ((add_aut.conj g).add_subgroup_map $ stabilizer α y).symm end add_action /-- `smul` by a `k : M` over a ring is injective, if `k` is not a zero divisor. The general theory of such `k` is elaborated by `is_smul_regular`. The typeclass that restricts all terms of `M` to have this property is `no_zero_smul_divisors`. -/ lemma smul_cancel_of_non_zero_divisor {M R : Type*} [monoid M] [non_unital_non_assoc_ring R] [distrib_mul_action M R] (k : M) (h : ∀ (x : R), k • x = 0 → x = 0) {a b : R} (h' : k • a = k • b) : a = b := begin rw ←sub_eq_zero, refine h _ _, rw [smul_sub, h', sub_self] end