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
65a2bffe56caa11ea3f12a3ef09871c774924963
94e33a31faa76775069b071adea97e86e218a8ee
/src/geometry/manifold/derivation_bundle.lean
373ca53b0918751a815ed36bcc60b8d1546c044c
[ "Apache-2.0" ]
permissive
urkud/mathlib
eab80095e1b9f1513bfb7f25b4fa82fa4fd02989
6379d39e6b5b279df9715f8011369a301b634e41
refs/heads/master
1,658,425,342,662
1,658,078,703,000
1,658,078,703,000
186,910,338
0
0
Apache-2.0
1,568,512,083,000
1,557,958,709,000
Lean
UTF-8
Lean
false
false
6,336
lean
/- Copyright © 2020 Nicolò Cavalleri. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Nicolò Cavalleri -/ import geometry.manifold.algebra.smooth_functions import ring_theory.derivation /-! # Derivation bundle In this file we define the derivations at a point of a manifold on the algebra of smooth fuctions. Moreover, we define the differential of a function in terms of derivations. The content of this file is not meant to be regarded as an alternative definition to the current tangent bundle but rather as a purely algebraic theory that provides a purely algebraic definition of the Lie algebra for a Lie group. -/ variables (𝕜 : Type*) [nondiscrete_normed_field 𝕜] {E : Type*} [normed_group E] [normed_space 𝕜 E] {H : Type*} [topological_space H] (I : model_with_corners 𝕜 E H) (M : Type*) [topological_space M] [charted_space H M] (n : with_top ℕ) open_locale manifold -- the following two instances prevent poorly understood type class inference timeout problems instance smooth_functions_algebra : algebra 𝕜 C^∞⟮I, M; 𝕜⟯ := by apply_instance instance smooth_functions_tower : is_scalar_tower 𝕜 C^∞⟮I, M; 𝕜⟯ C^∞⟮I, M; 𝕜⟯ := by apply_instance /-- Type synonym, introduced to put a different `has_smul` action on `C^n⟮I, M; 𝕜⟯` which is defined as `f • r = f(x) * r`. -/ @[nolint unused_arguments] def pointed_smooth_map (x : M) := C^n⟮I, M; 𝕜⟯ localized "notation `C^` n `⟮` I `,` M `;` 𝕜 `⟯⟨` x `⟩` := pointed_smooth_map 𝕜 I M n x" in derivation variables {𝕜 M} namespace pointed_smooth_map instance {x : M} : has_coe_to_fun C^∞⟮I, M; 𝕜⟯⟨x⟩ (λ _, M → 𝕜) := cont_mdiff_map.has_coe_to_fun instance {x : M} : comm_ring C^∞⟮I, M; 𝕜⟯⟨x⟩ := smooth_map.comm_ring instance {x : M} : algebra 𝕜 C^∞⟮I, M; 𝕜⟯⟨x⟩ := smooth_map.algebra instance {x : M} : inhabited C^∞⟮I, M; 𝕜⟯⟨x⟩ := ⟨0⟩ instance {x : M} : algebra C^∞⟮I, M; 𝕜⟯⟨x⟩ C^∞⟮I, M; 𝕜⟯ := algebra.id C^∞⟮I, M; 𝕜⟯ instance {x : M} : is_scalar_tower 𝕜 C^∞⟮I, M; 𝕜⟯⟨x⟩ C^∞⟮I, M; 𝕜⟯ := is_scalar_tower.right variable {I} /-- `smooth_map.eval_ring_hom` gives rise to an algebra structure of `C^∞⟮I, M; 𝕜⟯` on `𝕜`. -/ instance eval_algebra {x : M} : algebra C^∞⟮I, M; 𝕜⟯⟨x⟩ 𝕜 := (smooth_map.eval_ring_hom x : C^∞⟮I, M; 𝕜⟯⟨x⟩ →+* 𝕜).to_algebra /-- With the `eval_algebra` algebra structure evaluation is actually an algebra morphism. -/ def eval (x : M) : C^∞⟮I, M; 𝕜⟯ →ₐ[C^∞⟮I, M; 𝕜⟯⟨x⟩] 𝕜 := algebra.of_id C^∞⟮I, M; 𝕜⟯⟨x⟩ 𝕜 lemma smul_def (x : M) (f : C^∞⟮I, M; 𝕜⟯⟨x⟩) (k : 𝕜) : f • k = f x * k := rfl instance (x : M) : is_scalar_tower 𝕜 C^∞⟮I, M; 𝕜⟯⟨x⟩ 𝕜 := { smul_assoc := λ k f h, by { simp only [smul_def, algebra.id.smul_eq_mul, smooth_map.coe_smul, pi.smul_apply, mul_assoc]} } end pointed_smooth_map open_locale derivation /-- The derivations at a point of a manifold. Some regard this as a possible definition of the tangent space -/ @[reducible] def point_derivation (x : M) := derivation 𝕜 (C^∞⟮I, M; 𝕜⟯⟨x⟩) 𝕜 section variables (I) {M} (X Y : derivation 𝕜 C^∞⟮I, M; 𝕜⟯ C^∞⟮I, M; 𝕜⟯) (f g : C^∞⟮I, M; 𝕜⟯) (r : 𝕜) /-- Evaluation at a point gives rise to a `C^∞⟮I, M; 𝕜⟯`-linear map between `C^∞⟮I, M; 𝕜⟯` and `𝕜`. -/ def smooth_function.eval_at (x : M) : C^∞⟮I, M; 𝕜⟯ →ₗ[C^∞⟮I, M; 𝕜⟯⟨x⟩] 𝕜 := (pointed_smooth_map.eval x).to_linear_map namespace derivation variable {I} /-- The evaluation at a point as a linear map. -/ def eval_at (x : M) : (derivation 𝕜 C^∞⟮I, M; 𝕜⟯ C^∞⟮I, M; 𝕜⟯) →ₗ[𝕜] point_derivation I x := (smooth_function.eval_at I x).comp_der lemma eval_at_apply (x : M) : eval_at x X f = (X f) x := rfl end derivation variables {I} {E' : Type*} [normed_group E'] [normed_space 𝕜 E'] {H' : Type*} [topological_space H'] {I' : model_with_corners 𝕜 E' H'} {M' : Type*} [topological_space M'] [charted_space H' M'] /-- The heterogeneous differential as a linear map. Instead of taking a function as an argument this differential takes `h : f x = y`. It is particularly handy to deal with situations where the points on where it has to be evaluated are equal but not definitionally equal. -/ def hfdifferential {f : C^∞⟮I, M; I', M'⟯} {x : M} {y : M'} (h : f x = y) : point_derivation I x →ₗ[𝕜] point_derivation I' y := { to_fun := λ v, derivation.mk' { to_fun := λ g, v (g.comp f), map_add' := λ g g', by rw [smooth_map.add_comp, derivation.map_add], map_smul' := λ k g, by simp only [smooth_map.smul_comp, derivation.map_smul, ring_hom.id_apply], } (λ g g', by simp only [derivation.leibniz, smooth_map.mul_comp, linear_map.coe_mk, pointed_smooth_map.smul_def, cont_mdiff_map.comp_apply, h]), map_smul' := λ k v, rfl, map_add' := λ v w, rfl } /-- The homogeneous differential as a linear map. -/ def fdifferential (f : C^∞⟮I, M; I', M'⟯) (x : M) : point_derivation I x →ₗ[𝕜] point_derivation I' (f x) := hfdifferential (rfl : f x = f x) /- Standard notation for the differential. The abbreviation is `MId`. -/ localized "notation `𝒅` := fdifferential" in manifold /- Standard notation for the differential. The abbreviation is `MId`. -/ localized "notation `𝒅ₕ` := hfdifferential" in manifold @[simp] lemma apply_fdifferential (f : C^∞⟮I, M; I', M'⟯) {x : M} (v : point_derivation I x) (g : C^∞⟮I', M'; 𝕜⟯) : 𝒅f x v g = v (g.comp f) := rfl @[simp] lemma apply_hfdifferential {f : C^∞⟮I, M; I', M'⟯} {x : M} {y : M'} (h : f x = y) (v : point_derivation I x) (g : C^∞⟮I', M'; 𝕜⟯) : 𝒅ₕh v g = 𝒅f x v g := rfl variables {E'' : Type*} [normed_group E''] [normed_space 𝕜 E''] {H'' : Type*} [topological_space H''] {I'' : model_with_corners 𝕜 E'' H''} {M'' : Type*} [topological_space M''] [charted_space H'' M''] @[simp] lemma fdifferential_comp (g : C^∞⟮I', M'; I'', M''⟯) (f : C^∞⟮I, M; I', M'⟯) (x : M) : 𝒅(g.comp f) x = (𝒅g (f x)).comp (𝒅f x) := rfl end
2cc0c2f9256d4296ebfc9b6720539062d2591c60
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/algebra/ring_quot.lean
f654bddd1904f067ea3d41b7ca358fcae0367198
[ "Apache-2.0" ]
permissive
ilitzroth/mathlib
ea647e67f1fdfd19a0f7bdc5504e8acec6180011
5254ef14e3465f6504306132fe3ba9cec9ffff16
refs/heads/master
1,680,086,661,182
1,617,715,647,000
1,617,715,647,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,875
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import algebra.algebra.basic import ring_theory.ideal.basic /-! # Quotients of non-commutative rings Unfortunately, ideals have only been developed in the commutative case as `ideal`, and it's not immediately clear how one should formalise ideals in the non-commutative case. In this file, we directly define the quotient of a semiring by any relation, by building a bigger relation that represents the ideal generated by that relation. We prove the universal properties of the quotient, and recommend avoiding relying on the actual definition! Since everything runs in parallel for quotients of `R`-algebras, we do that case at the same time. -/ universes u₁ u₂ u₃ u₄ variables {R : Type u₁} [semiring R] variables {S : Type u₂} [comm_semiring S] variables {A : Type u₃} [semiring A] [algebra S A] namespace ring_quot /-- Given an arbitrary relation `r` on a ring, we strengthen it to a relation `rel r`, such that the equivalence relation generated by `rel r` has `x ~ y` if and only if `x - y` is in the ideal generated by elements `a - b` such that `r a b`. -/ inductive rel (r : R → R → Prop) : R → R → Prop | of ⦃x y : R⦄ (h : r x y) : rel x y | add_left ⦃a b c⦄ : rel a b → rel (a + c) (b + c) | mul_left ⦃a b c⦄ : rel a b → rel (a * c) (b * c) | mul_right ⦃a b c⦄ : rel b c → rel (a * b) (a * c) theorem rel.add_right {r : R → R → Prop} ⦃a b c : R⦄ (h : rel r b c) : rel r (a + b) (a + c) := by { rw [add_comm a b, add_comm a c], exact rel.add_left h } theorem rel.neg {R : Type u₁} [ring R] {r : R → R → Prop} ⦃a b : R⦄ (h : rel r a b) : rel r (-a) (-b) := by simp only [neg_eq_neg_one_mul a, neg_eq_neg_one_mul b, rel.mul_right h] theorem rel.smul {r : A → A → Prop} (k : S) ⦃a b : A⦄ (h : rel r a b) : rel r (k • a) (k • b) := by simp only [algebra.smul_def, rel.mul_right h] end ring_quot /-- The quotient of a ring by an arbitrary relation. -/ def ring_quot (r : R → R → Prop) := quot (ring_quot.rel r) namespace ring_quot instance (r : R → R → Prop) : semiring (ring_quot r) := { add := quot.map₂ (+) rel.add_right rel.add_left, add_assoc := by { rintros ⟨⟩ ⟨⟩ ⟨⟩, exact congr_arg (quot.mk _) (add_assoc _ _ _), }, zero := quot.mk _ 0, zero_add := by { rintros ⟨⟩, exact congr_arg (quot.mk _) (zero_add _), }, add_zero := by { rintros ⟨⟩, exact congr_arg (quot.mk _) (add_zero _), }, zero_mul := by { rintros ⟨⟩, exact congr_arg (quot.mk _) (zero_mul _), }, mul_zero := by { rintros ⟨⟩, exact congr_arg (quot.mk _) (mul_zero _), }, add_comm := by { rintros ⟨⟩ ⟨⟩, exact congr_arg (quot.mk _) (add_comm _ _), }, mul := quot.map₂ (*) rel.mul_right rel.mul_left, mul_assoc := by { rintros ⟨⟩ ⟨⟩ ⟨⟩, exact congr_arg (quot.mk _) (mul_assoc _ _ _), }, one := quot.mk _ 1, one_mul := by { rintros ⟨⟩, exact congr_arg (quot.mk _) (one_mul _), }, mul_one := by { rintros ⟨⟩, exact congr_arg (quot.mk _) (mul_one _), }, left_distrib := by { rintros ⟨⟩ ⟨⟩ ⟨⟩, exact congr_arg (quot.mk _) (left_distrib _ _ _), }, right_distrib := by { rintros ⟨⟩ ⟨⟩ ⟨⟩, exact congr_arg (quot.mk _) (right_distrib _ _ _), }, } instance {R : Type u₁} [ring R] (r : R → R → Prop) : ring (ring_quot r) := { neg := quot.map (λ a, -a) rel.neg, add_left_neg := by { rintros ⟨⟩, exact congr_arg (quot.mk _) (add_left_neg _), }, .. (ring_quot.semiring r) } instance {R : Type u₁} [comm_semiring R] (r : R → R → Prop) : comm_semiring (ring_quot r) := { mul_comm := by { rintros ⟨⟩ ⟨⟩, exact congr_arg (quot.mk _) (mul_comm _ _), } .. (ring_quot.semiring r) } instance {R : Type u₁} [comm_ring R] (r : R → R → Prop) : comm_ring (ring_quot r) := { .. (ring_quot.comm_semiring r), .. (ring_quot.ring r) } instance (s : A → A → Prop) : algebra S (ring_quot s) := { smul := λ r, quot.map ((•) r) (rel.smul r), to_fun := λ r, quot.mk _ (algebra_map S A r), map_one' := congr_arg (quot.mk _) (ring_hom.map_one _), map_mul' := λ r s, congr_arg (quot.mk _) (ring_hom.map_mul _ _ _), map_zero' := congr_arg (quot.mk _) (ring_hom.map_zero _), map_add' := λ r s, congr_arg (quot.mk _) (ring_hom.map_add _ _ _), commutes' := λ r, by { rintro ⟨a⟩, exact congr_arg (quot.mk _) (algebra.commutes _ _) }, smul_def' := λ r, by { rintro ⟨a⟩, exact congr_arg (quot.mk _) (algebra.smul_def _ _) }, } instance (r : R → R → Prop) : inhabited (ring_quot r) := ⟨0⟩ /-- The quotient map from a ring to its quotient, as a homomorphism of rings. -/ def mk_ring_hom (r : R → R → Prop) : R →+* ring_quot r := { to_fun := quot.mk _, map_one' := rfl, map_mul' := λ a b, rfl, map_zero' := rfl, map_add' := λ a b, rfl, } lemma mk_ring_hom_rel {r : R → R → Prop} {x y : R} (w : r x y) : mk_ring_hom r x = mk_ring_hom r y := quot.sound (rel.of w) lemma mk_ring_hom_surjective (r : R → R → Prop) : function.surjective (mk_ring_hom r) := by { dsimp [mk_ring_hom], rintro ⟨⟩, simp, } @[ext] lemma ring_quot_ext {T : Type u₄} [semiring T] {r : R → R → Prop} (f g : ring_quot r →+* T) (w : f.comp (mk_ring_hom r) = g.comp (mk_ring_hom r)) : f = g := begin ext, rcases mk_ring_hom_surjective r x with ⟨x, rfl⟩, exact (ring_hom.congr_fun w x : _), end variables {T : Type u₄} [semiring T] /-- Any ring homomorphism `f : R →+* T` which respects a relation `r : R → R → Prop` factors uniquely through a morphism `ring_quot r →+* T`. -/ def lift {r : R → R → Prop} : {f : R →+* T // ∀ ⦃x y⦄, r x y → f x = f y} ≃ (ring_quot r →+* T) := { to_fun := λ f', let f := (f' : R →+* T) in { to_fun := quot.lift f begin rintros _ _ r, induction r, case of : _ _ r { exact f'.prop r, }, case add_left : _ _ _ _ r' { simp [r'], }, case mul_left : _ _ _ _ r' { simp [r'], }, case mul_right : _ _ _ _ r' { simp [r'], }, end, map_zero' := f.map_zero, map_add' := by { rintros ⟨x⟩ ⟨y⟩, exact f.map_add x y, }, map_one' := f.map_one, map_mul' := by { rintros ⟨x⟩ ⟨y⟩, exact f.map_mul x y, }, }, inv_fun := λ F, ⟨F.comp (mk_ring_hom r), λ x y h, by { dsimp, rw mk_ring_hom_rel h, }⟩, left_inv := λ f, by { ext, simp, refl }, right_inv := λ F, by { ext, simp, refl } } @[simp] lemma lift_mk_ring_hom_apply (f : R →+* T) {r : R → R → Prop} (w : ∀ ⦃x y⦄, r x y → f x = f y) (x) : lift ⟨f, w⟩ (mk_ring_hom r x) = f x := rfl -- note this is essentially `lift.symm_apply_eq.mp h` lemma lift_unique (f : R →+* T) {r : R → R → Prop} (w : ∀ ⦃x y⦄, r x y → f x = f y) (g : ring_quot r →+* T) (h : g.comp (mk_ring_hom r) = f) : g = lift ⟨f, w⟩ := by { ext, simp [h], } lemma eq_lift_comp_mk_ring_hom {r : R → R → Prop} (f : ring_quot r →+* T) : f = lift ⟨f.comp (mk_ring_hom r), λ x y h, by { dsimp, rw mk_ring_hom_rel h, }⟩ := (lift.apply_symm_apply f).symm section comm_ring /-! We now verify that in the case of a commutative ring, the `ring_quot` construction agrees with the quotient by the appropriate ideal. -/ variables {B : Type u₁} [comm_ring B] /-- The universal ring homomorphism from `ring_quot r` to `(ideal.of_rel r).quotient`. -/ def ring_quot_to_ideal_quotient (r : B → B → Prop) : ring_quot r →+* (ideal.of_rel r).quotient := lift ⟨ideal.quotient.mk (ideal.of_rel r), λ x y h, quot.sound (submodule.mem_Inf.mpr (λ p w, w ⟨x, y, h, sub_add_cancel x y⟩))⟩ @[simp] lemma ring_quot_to_ideal_quotient_apply (r : B → B → Prop) (x : B) : ring_quot_to_ideal_quotient r (mk_ring_hom r x) = ideal.quotient.mk _ x := rfl /-- The universal ring homomorphism from `(ideal.of_rel r).quotient` to `ring_quot r`. -/ def ideal_quotient_to_ring_quot (r : B → B → Prop) : (ideal.of_rel r).quotient →+* ring_quot r := ideal.quotient.lift (ideal.of_rel r) (mk_ring_hom r) begin refine λ x h, submodule.span_induction h _ _ _ _, { rintro y ⟨a, b, h, su⟩, symmetry' at su, rw ←sub_eq_iff_eq_add at su, rw [ ← su, ring_hom.map_sub, mk_ring_hom_rel h, sub_self], }, { simp, }, { intros a b ha hb, simp [ha, hb], }, { intros a x hx, simp [hx], }, end @[simp] lemma ideal_quotient_to_ring_quot_apply (r : B → B → Prop) (x : B) : ideal_quotient_to_ring_quot r (ideal.quotient.mk _ x) = mk_ring_hom r x := rfl /-- The ring equivalence between `ring_quot r` and `(ideal.of_rel r).quotient` -/ def ring_quot_equiv_ideal_quotient (r : B → B → Prop) : ring_quot r ≃+* (ideal.of_rel r).quotient := ring_equiv.of_hom_inv (ring_quot_to_ideal_quotient r) (ideal_quotient_to_ring_quot r) (by { ext, simp, }) (by { ext ⟨x⟩, simp, }) end comm_ring /-- Transfer a star_ring instance through a quotient, if the quotient is invariant to `star` -/ def star_ring {R : Type u₁} [semiring R] [star_ring R] (r : R → R → Prop) (hr : ∀ {a b}, r a b → r (star a) (star b)) : star_ring (ring_quot r) := { star := quot.map star $ λ a b h, begin induction h, { exact rel.of (hr h_h) }, { rw [star_add, star_add], exact rel.add_left h_ih, }, { rw [star_mul, star_mul], exact rel.mul_right h_ih, }, { rw [star_mul, star_mul], exact rel.mul_left h_ih, }, end, star_involutive := by { rintros ⟨⟩, exact congr_arg (quot.mk _) (star_star _), }, star_mul := by { rintros ⟨⟩ ⟨⟩, exact congr_arg (quot.mk _) (star_mul _ _), }, star_add := by { rintros ⟨⟩ ⟨⟩, exact congr_arg (quot.mk _) (star_add _ _), } } section algebra variables (S) /-- The quotient map from an `S`-algebra to its quotient, as a homomorphism of `S`-algebras. -/ def mk_alg_hom (s : A → A → Prop) : A →ₐ[S] ring_quot s := { commutes' := λ r, rfl, ..mk_ring_hom s } @[simp] lemma mk_alg_hom_coe (s : A → A → Prop) : (mk_alg_hom S s : A →+* ring_quot s) = mk_ring_hom s := rfl lemma mk_alg_hom_rel {s : A → A → Prop} {x y : A} (w : s x y) : mk_alg_hom S s x = mk_alg_hom S s y := quot.sound (rel.of w) lemma mk_alg_hom_surjective (s : A → A → Prop) : function.surjective (mk_alg_hom S s) := by { dsimp [mk_alg_hom], rintro ⟨a⟩, use a, refl, } variables {B : Type u₄} [semiring B] [algebra S B] @[ext] lemma ring_quot_ext' {s : A → A → Prop} (f g : ring_quot s →ₐ[S] B) (w : f.comp (mk_alg_hom S s) = g.comp (mk_alg_hom S s)) : f = g := begin ext, rcases mk_alg_hom_surjective S s x with ⟨x, rfl⟩, exact (alg_hom.congr_fun w x : _), end /-- Any `S`-algebra homomorphism `f : A →ₐ[S] B` which respects a relation `s : A → A → Prop` factors uniquely through a morphism `ring_quot s →ₐ[S] B`. -/ def lift_alg_hom {s : A → A → Prop} : { f : A →ₐ[S] B // ∀ ⦃x y⦄, s x y → f x = f y} ≃ (ring_quot s →ₐ[S] B) := { to_fun := λ f', let f := (f' : A →ₐ[S] B) in { to_fun := quot.lift f begin rintros _ _ r, induction r, case of : _ _ r { exact f'.prop r, }, case add_left : _ _ _ _ r' { simp [r'], }, case mul_left : _ _ _ _ r' { simp [r'], }, case mul_right : _ _ _ _ r' { simp [r'], }, end, map_zero' := f.map_zero, map_add' := by { rintros ⟨x⟩ ⟨y⟩, exact f.map_add x y, }, map_one' := f.map_one, map_mul' := by { rintros ⟨x⟩ ⟨y⟩, exact f.map_mul x y, }, commutes' := begin rintros x, conv_rhs { rw [algebra.algebra_map_eq_smul_one, ←f.map_one, ←f.map_smul], }, rw algebra.algebra_map_eq_smul_one, exact quot.lift_mk f f'.prop (x • 1), end, }, inv_fun := λ F, ⟨F.comp (mk_alg_hom S s), λ _ _ h, by { dsimp, erw mk_alg_hom_rel S h }⟩, left_inv := λ f, by { ext, simp, refl }, right_inv := λ F, by { ext, simp, refl } } @[simp] lemma lift_alg_hom_mk_alg_hom_apply (f : A →ₐ[S] B) {s : A → A → Prop} (w : ∀ ⦃x y⦄, s x y → f x = f y) (x) : (lift_alg_hom S ⟨f, w⟩) ((mk_alg_hom S s) x) = f x := rfl -- note this is essentially `(lift_alg_hom S).symm_apply_eq.mp h` lemma lift_alg_hom_unique (f : A →ₐ[S] B) {s : A → A → Prop} (w : ∀ ⦃x y⦄, s x y → f x = f y) (g : ring_quot s →ₐ[S] B) (h : g.comp (mk_alg_hom S s) = f) : g = lift_alg_hom S ⟨f, w⟩ := by { ext, simp [h], } lemma eq_lift_alg_hom_comp_mk_alg_hom {s : A → A → Prop} (f : ring_quot s →ₐ[S] B) : f = lift_alg_hom S ⟨f.comp (mk_alg_hom S s), λ x y h, by { dsimp, erw mk_alg_hom_rel S h, }⟩ := ((lift_alg_hom S).apply_symm_apply f).symm end algebra attribute [irreducible] mk_ring_hom mk_alg_hom lift lift_alg_hom end ring_quot
cb62a7493e2aa6a446c0e38407a15a034340f463
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/group/conj.lean
ba988ce048bf51bc2f204da0ace4de62829577dd
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
10,175
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Chris Hughes, Michael Howes -/ import algebra.group.semiconj import algebra.group_with_zero.basic import algebra.hom.aut import algebra.hom.group /-! # Conjugacy of group elements > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. See also `mul_aut.conj` and `quandle.conj`. -/ universes u v variables {α : Type u} {β : Type v} section monoid variables [monoid α] [monoid β] /-- We say that `a` is conjugate to `b` if for some unit `c` we have `c * a * c⁻¹ = b`. -/ def is_conj (a b : α) := ∃ c : αˣ, semiconj_by ↑c a b @[refl] lemma is_conj.refl (a : α) : is_conj a a := ⟨1, semiconj_by.one_left a⟩ @[symm] lemma is_conj.symm {a b : α} : is_conj a b → is_conj b a | ⟨c, hc⟩ := ⟨c⁻¹, hc.units_inv_symm_left⟩ lemma is_conj_comm {g h : α} : is_conj g h ↔ is_conj h g := ⟨is_conj.symm, is_conj.symm⟩ @[trans] lemma is_conj.trans {a b c : α} : is_conj a b → is_conj b c → is_conj a c | ⟨c₁, hc₁⟩ ⟨c₂, hc₂⟩ := ⟨c₂ * c₁, hc₂.mul_left hc₁⟩ @[simp] lemma is_conj_iff_eq {α : Type*} [comm_monoid α] {a b : α} : is_conj a b ↔ a = b := ⟨λ ⟨c, hc⟩, begin rw [semiconj_by, mul_comm, ← units.mul_inv_eq_iff_eq_mul, mul_assoc, c.mul_inv, mul_one] at hc, exact hc, end, λ h, by rw h⟩ protected lemma monoid_hom.map_is_conj (f : α →* β) {a b : α} : is_conj a b → is_conj (f a) (f b) | ⟨c, hc⟩ := ⟨units.map f c, by rw [units.coe_map, semiconj_by, ← f.map_mul, hc.eq, f.map_mul]⟩ end monoid section cancel_monoid variables [cancel_monoid α] -- These lemmas hold for `right_cancel_monoid` with the current proofs, but for the sake of -- not duplicating code (these lemmas also hold for `left_cancel_monoids`) we leave these -- not generalised. @[simp] lemma is_conj_one_right {a : α} : is_conj 1 a ↔ a = 1 := ⟨λ ⟨c, hc⟩, mul_right_cancel (hc.symm.trans ((mul_one _).trans (one_mul _).symm)), λ h, by rw [h]⟩ @[simp] lemma is_conj_one_left {a : α} : is_conj a 1 ↔ a = 1 := calc is_conj a 1 ↔ is_conj 1 a : ⟨is_conj.symm, is_conj.symm⟩ ... ↔ a = 1 : is_conj_one_right end cancel_monoid section group variables [group α] @[simp] lemma is_conj_iff {a b : α} : is_conj a b ↔ ∃ c : α, c * a * c⁻¹ = b := ⟨λ ⟨c, hc⟩, ⟨c, mul_inv_eq_iff_eq_mul.2 hc⟩, λ ⟨c, hc⟩, ⟨⟨c, c⁻¹, mul_inv_self c, inv_mul_self c⟩, mul_inv_eq_iff_eq_mul.1 hc⟩⟩ @[simp] lemma conj_inv {a b : α} : (b * a * b⁻¹)⁻¹ = b * a⁻¹ * b⁻¹ := ((mul_aut.conj b).map_inv a).symm @[simp] lemma conj_mul {a b c : α} : (b * a * b⁻¹) * (b * c * b⁻¹) = b * (a * c) * b⁻¹ := ((mul_aut.conj b).map_mul a c).symm @[simp] lemma conj_pow {i : ℕ} {a b : α} : (a * b * a⁻¹) ^ i = a * (b ^ i) * a⁻¹ := begin induction i with i hi, { simp }, { simp [pow_succ, hi] } end @[simp] lemma conj_zpow {i : ℤ} {a b : α} : (a * b * a⁻¹) ^ i = a * (b ^ i) * a⁻¹ := begin induction i, { simp }, { simp [zpow_neg_succ_of_nat, conj_pow] } end lemma conj_injective {x : α} : function.injective (λ (g : α), x * g * x⁻¹) := (mul_aut.conj x).injective end group @[simp] lemma is_conj_iff₀ [group_with_zero α] {a b : α} : is_conj a b ↔ ∃ c : α, c ≠ 0 ∧ c * a * c⁻¹ = b := ⟨λ ⟨c, hc⟩, ⟨c, begin rw [← units.coe_inv, units.mul_inv_eq_iff_eq_mul], exact ⟨c.ne_zero, hc⟩, end⟩, λ ⟨c, c0, hc⟩, ⟨units.mk0 c c0, begin rw [semiconj_by, ← units.mul_inv_eq_iff_eq_mul, units.coe_inv, units.coe_mk0], exact hc end⟩⟩ namespace is_conj /- This small quotient API is largely copied from the API of `associates`; where possible, try to keep them in sync -/ /-- The setoid of the relation `is_conj` iff there is a unit `u` such that `u * x = y * u` -/ protected def setoid (α : Type*) [monoid α] : setoid α := { r := is_conj, iseqv := ⟨is_conj.refl, λa b, is_conj.symm, λa b c, is_conj.trans⟩ } end is_conj local attribute [instance, priority 100] is_conj.setoid /-- The quotient type of conjugacy classes of a group. -/ def conj_classes (α : Type*) [monoid α] : Type* := quotient (is_conj.setoid α) namespace conj_classes section monoid variables [monoid α] [monoid β] /-- The canonical quotient map from a monoid `α` into the `conj_classes` of `α` -/ protected def mk {α : Type*} [monoid α] (a : α) : conj_classes α := ⟦a⟧ instance : inhabited (conj_classes α) := ⟨⟦1⟧⟩ theorem mk_eq_mk_iff_is_conj {a b : α} : conj_classes.mk a = conj_classes.mk b ↔ is_conj a b := iff.intro quotient.exact quot.sound theorem quotient_mk_eq_mk (a : α) : ⟦ a ⟧ = conj_classes.mk a := rfl theorem quot_mk_eq_mk (a : α) : quot.mk setoid.r a = conj_classes.mk a := rfl theorem forall_is_conj {p : conj_classes α → Prop} : (∀a, p a) ↔ (∀a, p (conj_classes.mk a)) := iff.intro (assume h a, h _) (assume h a, quotient.induction_on a h) theorem mk_surjective : function.surjective (@conj_classes.mk α _) := forall_is_conj.2 (λ a, ⟨a, rfl⟩) instance : has_one (conj_classes α) := ⟨⟦ 1 ⟧⟩ theorem one_eq_mk_one : (1 : conj_classes α) = conj_classes.mk 1 := rfl lemma exists_rep (a : conj_classes α) : ∃ a0 : α, conj_classes.mk a0 = a := quot.exists_rep a /-- A `monoid_hom` maps conjugacy classes of one group to conjugacy classes of another. -/ def map (f : α →* β) : conj_classes α → conj_classes β := quotient.lift (conj_classes.mk ∘ f) (λ a b ab, mk_eq_mk_iff_is_conj.2 (f.map_is_conj ab)) lemma map_surjective {f : α →* β} (hf : function.surjective f) : function.surjective (conj_classes.map f) := begin intros b, obtain ⟨b, rfl⟩ := conj_classes.mk_surjective b, obtain ⟨a, rfl⟩ := hf b, exact ⟨conj_classes.mk a, rfl⟩, end /-- Certain instances trigger further searches when they are considered as candidate instances; these instances should be assigned a priority lower than the default of 1000 (for example, 900). The conditions for this rule are as follows: * a class `C` has instances `instT : C T` and `instT' : C T'` * types `T` and `T'` are both specializations of another type `S` * the parameters supplied to `S` to produce `T` are not (fully) determined by `instT`, instead they have to be found by instance search If those conditions hold, the instance `instT` should be assigned lower priority. For example, suppose the search for an instance of `decidable_eq (multiset α)` tries the candidate instance `con.quotient.decidable_eq (c : con M) : decidable_eq c.quotient`. Since `multiset` and `con.quotient` are both quotient types, unification will check that the relations `list.perm` and `c.to_setoid.r` unify. However, `c.to_setoid` depends on a `has_mul M` instance, so this unification triggers a search for `has_mul (list α)`; this will traverse all subclasses of `has_mul` before failing. On the other hand, the search for an instance of `decidable_eq (con.quotient c)` for `c : con M` can quickly reject the candidate instance `multiset.has_decidable_eq` because the type of `list.perm : list ?m_1 → list ?m_1 → Prop` does not unify with `M → M → Prop`. Therefore, we should assign `con.quotient.decidable_eq` a lower priority because it fails slowly. (In terms of the rules above, `C := decidable_eq`, `T := con.quotient`, `instT := con.quotient.decidable_eq`, `T' := multiset`, `instT' := multiset.has_decidable_eq`, and `S := quot`.) If the type involved is a free variable (rather than an instantiation of some type `S`), the instance priority should be even lower, see Note [lower instance priority]. -/ library_note "slow-failing instance priority" @[priority 900] -- see Note [slow-failing instance priority] instance [decidable_rel (is_conj : α → α → Prop)] : decidable_eq (conj_classes α) := quotient.decidable_eq end monoid section comm_monoid variable [comm_monoid α] lemma mk_injective : function.injective (@conj_classes.mk α _) := λ _ _, (mk_eq_mk_iff_is_conj.trans is_conj_iff_eq).1 lemma mk_bijective : function.bijective (@conj_classes.mk α _) := ⟨mk_injective, mk_surjective⟩ /-- The bijection between a `comm_group` and its `conj_classes`. -/ def mk_equiv : α ≃ conj_classes α := ⟨conj_classes.mk, quotient.lift id (λ (a : α) b, is_conj_iff_eq.1), quotient.lift_mk _ _, begin rw [function.right_inverse, function.left_inverse, forall_is_conj], intro x, rw [← quotient_mk_eq_mk, ← quotient_mk_eq_mk, quotient.lift_mk, id.def], end⟩ end comm_monoid end conj_classes section monoid variables [monoid α] /-- Given an element `a`, `conjugates a` is the set of conjugates. -/ def conjugates_of (a : α) : set α := {b | is_conj a b} lemma mem_conjugates_of_self {a : α} : a ∈ conjugates_of a := is_conj.refl _ lemma is_conj.conjugates_of_eq {a b : α} (ab : is_conj a b) : conjugates_of a = conjugates_of b := set.ext (λ g, ⟨λ ag, (ab.symm).trans ag, λ bg, ab.trans bg⟩) lemma is_conj_iff_conjugates_of_eq {a b : α} : is_conj a b ↔ conjugates_of a = conjugates_of b := ⟨is_conj.conjugates_of_eq, λ h, begin have ha := mem_conjugates_of_self, rwa ← h at ha, end⟩ end monoid namespace conj_classes variables [monoid α] local attribute [instance] is_conj.setoid /-- Given a conjugacy class `a`, `carrier a` is the set it represents. -/ def carrier : conj_classes α → set α := quotient.lift conjugates_of (λ (a : α) b ab, is_conj.conjugates_of_eq ab) lemma mem_carrier_mk {a : α} : a ∈ carrier (conj_classes.mk a) := is_conj.refl _ lemma mem_carrier_iff_mk_eq {a : α} {b : conj_classes α} : a ∈ carrier b ↔ conj_classes.mk a = b := begin revert b, rw forall_is_conj, intro b, rw [carrier, eq_comm, mk_eq_mk_iff_is_conj, ← quotient_mk_eq_mk, quotient.lift_mk], refl, end lemma carrier_eq_preimage_mk {a : conj_classes α} : a.carrier = conj_classes.mk ⁻¹' {a} := set.ext (λ x, mem_carrier_iff_mk_eq) end conj_classes assert_not_exists multiset
0fe149c1c5e8ca949c897c808e19c0f595203800
f57749ca63d6416f807b770f67559503fdb21001
/hott/init/trunc.hlean
68fcd3a1bf77f29035736cf8e67c4cccdbaadede
[ "Apache-2.0" ]
permissive
aliassaf/lean
bd54e85bed07b1ff6f01396551867b2677cbc6ac
f9b069b6a50756588b309b3d716c447004203152
refs/heads/master
1,610,982,152,948
1,438,916,029,000
1,438,916,029,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,753
hlean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Floris van Doorn Definition of is_trunc (n-truncatedness) Ported from Coq HoTT. -/ --TODO: can we replace some definitions with a hprop as codomain by theorems? prelude import .logic .equiv .types .pathover open eq nat sigma unit namespace is_trunc /- Truncation levels -/ inductive trunc_index : Type₀ := | minus_two : trunc_index | succ : trunc_index → trunc_index /- notation for trunc_index is -2, -1, 0, 1, ... from 0 and up this comes from a coercion from num to trunc_index (via nat) -/ postfix `.+1`:(max+1) := trunc_index.succ postfix `.+2`:(max+1) := λn, (n .+1 .+1) notation `-2` := trunc_index.minus_two notation `-1` := -2.+1 -- ISSUE: -1 gets printed as -2.+1 export [coercions] nat namespace trunc_index definition add (n m : trunc_index) : trunc_index := trunc_index.rec_on m n (λ k l, l .+1) definition leq (n m : trunc_index) : Type₀ := trunc_index.rec_on n (λm, unit) (λ n p m, trunc_index.rec_on m (λ p, empty) (λ m q p, p m) p) m infix <= := trunc_index.leq infix ≤ := trunc_index.leq end trunc_index infix `+2+`:65 := trunc_index.add namespace trunc_index definition succ_le_succ {n m : trunc_index} (H : n ≤ m) : n.+1 ≤ m.+1 := H definition le_of_succ_le_succ {n m : trunc_index} (H : n.+1 ≤ m.+1) : n ≤ m := H definition minus_two_le (n : trunc_index) : -2 ≤ n := star definition empty_of_succ_le_minus_two {n : trunc_index} (H : n .+1 ≤ -2) : empty := H end trunc_index definition trunc_index.of_nat [coercion] [reducible] (n : nat) : trunc_index := (nat.rec_on n -2 (λ n k, k.+1)).+2 definition sub_two [reducible] (n : nat) : trunc_index := nat.rec_on n -2 (λ n k, k.+1) postfix `.-2`:(max+1) := sub_two /- truncated types -/ /- Just as in Coq HoTT we define an internal version of contractibility and is_trunc, but we only use `is_trunc` and `is_contr` -/ structure contr_internal (A : Type) := (center : A) (center_eq : Π(a : A), center = a) definition is_trunc_internal (n : trunc_index) : Type → Type := trunc_index.rec_on n (λA, contr_internal A) (λn trunc_n A, (Π(x y : A), trunc_n (x = y))) end is_trunc open is_trunc structure is_trunc [class] (n : trunc_index) (A : Type) := (to_internal : is_trunc_internal n A) open nat num is_trunc.trunc_index namespace is_trunc abbreviation is_contr := is_trunc -2 abbreviation is_hprop := is_trunc -1 abbreviation is_hset := is_trunc 0 variables {A B : Type} definition is_trunc_succ_intro (A : Type) (n : trunc_index) [H : ∀x y : A, is_trunc n (x = y)] : is_trunc n.+1 A := is_trunc.mk (λ x y, !is_trunc.to_internal) definition is_trunc_eq [instance] [priority 1200] (n : trunc_index) [H : is_trunc (n.+1) A] (x y : A) : is_trunc n (x = y) := is_trunc.mk (is_trunc.to_internal (n.+1) A x y) /- contractibility -/ definition is_contr.mk (center : A) (center_eq : Π(a : A), center = a) : is_contr A := is_trunc.mk (contr_internal.mk center center_eq) definition center (A : Type) [H : is_contr A] : A := contr_internal.center (is_trunc.to_internal -2 A) definition center_eq [H : is_contr A] (a : A) : !center = a := contr_internal.center_eq (is_trunc.to_internal -2 A) a definition eq_of_is_contr [H : is_contr A] (x y : A) : x = y := (center_eq x)⁻¹ ⬝ (center_eq y) definition hprop_eq_of_is_contr {A : Type} [H : is_contr A] {x y : A} (p q : x = y) : p = q := have K : ∀ (r : x = y), eq_of_is_contr x y = r, from (λ r, eq.rec_on r !con.left_inv), (K p)⁻¹ ⬝ K q theorem is_contr_eq {A : Type} [H : is_contr A] (x y : A) : is_contr (x = y) := is_contr.mk !eq_of_is_contr (λ p, !hprop_eq_of_is_contr) local attribute is_contr_eq [instance] /- truncation is upward close -/ -- n-types are also (n+1)-types theorem is_trunc_succ [instance] [priority 900] (A : Type) (n : trunc_index) [H : is_trunc n A] : is_trunc (n.+1) A := trunc_index.rec_on n (λ A (H : is_contr A), !is_trunc_succ_intro) (λ n IH A (H : is_trunc (n.+1) A), @is_trunc_succ_intro _ _ (λ x y, IH _ _)) A H --in the proof the type of H is given explicitly to make it available for class inference theorem is_trunc_of_leq.{l} (A : Type.{l}) {n m : trunc_index} (Hnm : n ≤ m) [Hn : is_trunc n A] : is_trunc m A := have base : ∀k A, k ≤ -2 → is_trunc k A → (is_trunc -2 A), from λ k A, trunc_index.cases_on k (λh1 h2, h2) (λk h1 h2, empty.elim (trunc_index.empty_of_succ_le_minus_two h1)), have step : Π (m : trunc_index) (IHm : Π (n : trunc_index) (A : Type), n ≤ m → is_trunc n A → is_trunc m A) (n : trunc_index) (A : Type) (Hnm : n ≤ m .+1) (Hn : is_trunc n A), is_trunc m .+1 A, from λm IHm n, trunc_index.rec_on n (λA Hnm Hn, @is_trunc_succ A m (IHm -2 A star Hn)) (λn IHn A Hnm (Hn : is_trunc n.+1 A), @is_trunc_succ_intro A m (λx y, IHm n (x = y) (trunc_index.le_of_succ_le_succ Hnm) _)), trunc_index.rec_on m base step n A Hnm Hn -- the following cannot be instances in their current form, because they are looping theorem is_trunc_of_is_contr (A : Type) (n : trunc_index) [H : is_contr A] : is_trunc n A := trunc_index.rec_on n H _ theorem is_trunc_succ_of_is_hprop (A : Type) (n : trunc_index) [H : is_hprop A] : is_trunc (n.+1) A := is_trunc_of_leq A (show -1 ≤ n.+1, from star) theorem is_trunc_succ_succ_of_is_hset (A : Type) (n : trunc_index) [H : is_hset A] : is_trunc (n.+2) A := is_trunc_of_leq A (show 0 ≤ n.+2, from star) /- hprops -/ definition is_hprop.elim [H : is_hprop A] (x y : A) : x = y := !center definition is_contr_of_inhabited_hprop {A : Type} [H : is_hprop A] (x : A) : is_contr A := is_contr.mk x (λy, !is_hprop.elim) theorem is_hprop_of_imp_is_contr {A : Type} (H : A → is_contr A) : is_hprop A := @is_trunc_succ_intro A -2 (λx y, have H2 [visible] : is_contr A, from H x, !is_contr_eq) theorem is_hprop.mk {A : Type} (H : ∀x y : A, x = y) : is_hprop A := is_hprop_of_imp_is_contr (λ x, is_contr.mk x (H x)) theorem is_hprop_elim_self {A : Type} {H : is_hprop A} (x : A) : is_hprop.elim x x = idp := !is_hprop.elim /- hsets -/ theorem is_hset.mk (A : Type) (H : ∀(x y : A) (p q : x = y), p = q) : is_hset A := @is_trunc_succ_intro _ _ (λ x y, is_hprop.mk (H x y)) definition is_hset.elim [H : is_hset A] ⦃x y : A⦄ (p q : x = y) : p = q := !is_hprop.elim /- instances -/ definition is_contr_sigma_eq [instance] [priority 800] {A : Type} (a : A) : is_contr (Σ(x : A), a = x) := is_contr.mk (sigma.mk a idp) (λp, sigma.rec_on p (λ b q, eq.rec_on q idp)) definition is_contr_unit [instance] : is_contr unit := is_contr.mk star (λp, unit.rec_on p idp) definition is_hprop_empty [instance] : is_hprop empty := is_hprop.mk (λx, !empty.elim x) /- truncated universe -/ -- TODO: move to root namespace? structure trunctype (n : trunc_index) := (carrier : Type) (struct : is_trunc n carrier) attribute trunctype.carrier [coercion] attribute trunctype.struct [instance] notation n `-Type` := trunctype n abbreviation hprop := -1-Type abbreviation hset := 0-Type protected abbreviation hprop.mk := @trunctype.mk -1 protected abbreviation hset.mk := @trunctype.mk (-1.+1) protected abbreviation trunctype.mk' [parsing-only] (n : trunc_index) (A : Type) [H : is_trunc n A] : n-Type := trunctype.mk A H /- interaction with equivalences -/ section open is_equiv equiv --should we remove the following two theorems as they are special cases of --"is_trunc_is_equiv_closed" definition is_contr_is_equiv_closed (f : A → B) [Hf : is_equiv f] [HA: is_contr A] : (is_contr B) := is_contr.mk (f (center A)) (λp, eq_of_eq_inv !center_eq) definition is_contr_equiv_closed (H : A ≃ B) [HA: is_contr A] : is_contr B := is_contr_is_equiv_closed (to_fun H) definition equiv_of_is_contr_of_is_contr [HA : is_contr A] [HB : is_contr B] : A ≃ B := equiv.mk (λa, center B) (is_equiv.adjointify (λa, center B) (λb, center A) center_eq center_eq) theorem is_trunc_is_equiv_closed (n : trunc_index) (f : A → B) [H : is_equiv f] [HA : is_trunc n A] : is_trunc n B := trunc_index.rec_on n (λA (HA : is_contr A) B f (H : is_equiv f), is_contr_is_equiv_closed f) (λn IH A (HA : is_trunc n.+1 A) B f (H : is_equiv f), @is_trunc_succ_intro _ _ (λ x y : B, IH (f⁻¹ x = f⁻¹ y) _ (x = y) (ap f⁻¹)⁻¹ !is_equiv_inv)) A HA B f H definition is_trunc_is_equiv_closed_rev (n : trunc_index) (f : A → B) [H : is_equiv f] [HA : is_trunc n B] : is_trunc n A := is_trunc_is_equiv_closed n f⁻¹ definition is_trunc_equiv_closed (n : trunc_index) (f : A ≃ B) [HA : is_trunc n A] : is_trunc n B := is_trunc_is_equiv_closed n (to_fun f) definition is_trunc_equiv_closed_rev (n : trunc_index) (f : A ≃ B) [HA : is_trunc n B] : is_trunc n A := is_trunc_is_equiv_closed n (to_inv f) definition is_equiv_of_is_hprop [constructor] [HA : is_hprop A] [HB : is_hprop B] (f : A → B) (g : B → A) : is_equiv f := is_equiv.mk f g (λb, !is_hprop.elim) (λa, !is_hprop.elim) (λa, !is_hset.elim) definition equiv_of_is_hprop [constructor] [HA : is_hprop A] [HB : is_hprop B] (f : A → B) (g : B → A) : A ≃ B := equiv.mk f (is_equiv_of_is_hprop f g) definition equiv_of_iff_of_is_hprop [unfold 5] [HA : is_hprop A] [HB : is_hprop B] (H : A ↔ B) : A ≃ B := equiv_of_is_hprop (iff.elim_left H) (iff.elim_right H) end /- interaction with the Unit type -/ open equiv -- A contractible type is equivalent to [Unit]. *) definition equiv_unit_of_is_contr [H : is_contr A] : A ≃ unit := equiv.MK (λ (x : A), ⋆) (λ (u : unit), center A) (λ (u : unit), unit.rec_on u idp) (λ (x : A), center_eq x) /- interaction with pathovers -/ variables {C : A → Type} {a a₂ : A} (p : a = a₂) (c : C a) (c₂ : C a₂) definition is_hprop.elimo [H : is_hprop (C a)] : c =[p] c₂ := pathover_of_eq_tr !is_hprop.elim definition is_trunc_pathover [instance] (n : trunc_index) [H : is_trunc (n.+1) (C a)] : is_trunc n (c =[p] c₂) := is_trunc_equiv_closed_rev n !pathover_equiv_eq_tr variables {p c c₂} theorem is_hset.elimo (q q' : c =[p] c₂) [H : is_hset (C a)] : q = q' := !is_hprop.elim -- TODO: port "Truncated morphisms" end is_trunc
34afdb43214d52d2b0ab496a9e6225c757447d1b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/1436.lean
5f5265bf6f60a7c803639486beac4abe4029920a
[ "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
548
lean
import Lean open List Lean example (l : List α) (h : length l = length l) : length (a::l) = length (a::l) := congrArg (·+1) h elab:max "(" tm:term ":)" : term => Elab.Term.elabTerm tm none example (l : List α) (h : length l = length l) : length (a::l) = length (a::l) := (congrArg (·+1) h :) example (l : List α) (h : length l = length l) : length (a::l) = length (a::l) := have := congrArg (·+1) h; this example (l : List α) (h : length l = length l) : length (a::l) = length (a::l) := by have := congrArg (·+1) h; exact this
2ca5f5f6c23de94d15c8fc84be66d377589f615e
55c7fc2bf55d496ace18cd6f3376e12bb14c8cc5
/src/order/filter/at_top_bot.lean
94818b1b455a3ddb2551a36e681f2f6d4504403e
[ "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
29,256
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad, Yury Kudryashov, Patrick Massot -/ import order.filter.bases /-! # `at_top` and `at_bot` filters on preorded sets, monoids and groups. In this file we define the filters * `at_top`: corresponds to `n → +∞`; * `at_bot`: corresponds to `n → -∞`. Then we prove many lemmas like “if `f → +∞`, then `f ± c → +∞`”. -/ variables {ι ι' α β γ : Type*} open set open_locale classical filter big_operators namespace filter /-- `at_top` is the filter representing the limit `→ ∞` on an ordered set. It is generated by the collection of up-sets `{b | a ≤ b}`. (The preorder need not have a top element for this to be well defined, and indeed is trivial when a top element exists.) -/ def at_top [preorder α] : filter α := ⨅ a, 𝓟 {b | a ≤ b} /-- `at_bot` is the filter representing the limit `→ -∞` on an ordered set. It is generated by the collection of down-sets `{b | b ≤ a}`. (The preorder need not have a bottom element for this to be well defined, and indeed is trivial when a bottom element exists.) -/ def at_bot [preorder α] : filter α := ⨅ a, 𝓟 {b | b ≤ a} lemma mem_at_top [preorder α] (a : α) : {b : α | a ≤ b} ∈ @at_top α _ := mem_infi_sets a $ subset.refl _ lemma Ioi_mem_at_top [preorder α] [no_top_order α] (x : α) : Ioi x ∈ (at_top : filter α) := let ⟨z, hz⟩ := no_top x in mem_sets_of_superset (mem_at_top z) $ λ y h, lt_of_lt_of_le hz h lemma mem_at_bot [preorder α] (a : α) : {b : α | b ≤ a} ∈ @at_bot α _ := mem_infi_sets a $ subset.refl _ lemma Iio_mem_at_bot [preorder α] [no_bot_order α] (x : α) : Iio x ∈ (at_bot : filter α) := let ⟨z, hz⟩ := no_bot x in mem_sets_of_superset (mem_at_bot z) $ λ y h, lt_of_le_of_lt h hz lemma at_top_basis [nonempty α] [semilattice_sup α] : (@at_top α _).has_basis (λ _, true) Ici := has_basis_infi_principal (directed_of_sup $ λ a b, Ici_subset_Ici.2) lemma at_top_basis' [semilattice_sup α] (a : α) : (@at_top α _).has_basis (λ x, a ≤ x) Ici := ⟨λ t, (@at_top_basis α ⟨a⟩ _).mem_iff.trans ⟨λ ⟨x, _, hx⟩, ⟨x ⊔ a, le_sup_right, λ y hy, hx (le_trans le_sup_left hy)⟩, λ ⟨x, _, hx⟩, ⟨x, trivial, hx⟩⟩⟩ @[instance] lemma at_top_ne_bot [nonempty α] [semilattice_sup α] : ne_bot (at_top : filter α) := at_top_basis.forall_nonempty_iff_ne_bot.1 $ λ a _, nonempty_Ici @[simp, nolint ge_or_gt] lemma mem_at_top_sets [nonempty α] [semilattice_sup α] {s : set α} : s ∈ (at_top : filter α) ↔ ∃a:α, ∀b≥a, b ∈ s := at_top_basis.mem_iff.trans $ exists_congr $ λ _, exists_const _ @[simp, nolint ge_or_gt] lemma eventually_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} : (∀ᶠ x in at_top, p x) ↔ (∃ a, ∀ b ≥ a, p b) := mem_at_top_sets lemma eventually_ge_at_top [preorder α] (a : α) : ∀ᶠ x in at_top, a ≤ x := mem_at_top a lemma at_top_countable_basis [nonempty α] [semilattice_sup α] [encodable α] : has_countable_basis (at_top : filter α) (λ _, true) Ici := { countable := countable_encodable _, .. at_top_basis } lemma order_top.at_top_eq (α) [order_top α] : (at_top : filter α) = pure ⊤ := le_antisymm (le_pure_iff.2 $ (eventually_ge_at_top ⊤).mono $ λ b, top_unique) (le_infi $ λ b, le_principal_iff.2 le_top) lemma tendsto_at_top_pure [order_top α] (f : α → β) : tendsto f at_top (pure $ f ⊤) := (order_top.at_top_eq α).symm ▸ tendsto_pure_pure _ _ @[nolint ge_or_gt] lemma eventually.exists_forall_of_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} (h : ∀ᶠ x in at_top, p x) : ∃ a, ∀ b ≥ a, p b := eventually_at_top.mp h @[nolint ge_or_gt] lemma frequently_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} : (∃ᶠ x in at_top, p x) ↔ (∀ a, ∃ b ≥ a, p b) := by simp only [filter.frequently, eventually_at_top, not_exists, not_forall, not_not] @[nolint ge_or_gt] lemma frequently_at_top' [semilattice_sup α] [nonempty α] [no_top_order α] {p : α → Prop} : (∃ᶠ x in at_top, p x) ↔ (∀ a, ∃ b > a, p b) := begin rw frequently_at_top, split ; intros h a, { cases no_top a with a' ha', rcases h a' with ⟨b, hb, hb'⟩, exact ⟨b, lt_of_lt_of_le ha' hb, hb'⟩ }, { rcases h a with ⟨b, hb, hb'⟩, exact ⟨b, le_of_lt hb, hb'⟩ }, end @[nolint ge_or_gt] lemma frequently.forall_exists_of_at_top [semilattice_sup α] [nonempty α] {p : α → Prop} (h : ∃ᶠ x in at_top, p x) : ∀ a, ∃ b ≥ a, p b := frequently_at_top.mp h lemma map_at_top_eq [nonempty α] [semilattice_sup α] {f : α → β} : at_top.map f = (⨅a, 𝓟 $ f '' {a' | a ≤ a'}) := (at_top_basis.map _).eq_infi lemma tendsto_at_top [preorder β] (m : α → β) (f : filter α) : tendsto m f at_top ↔ (∀b, ∀ᶠ a in f, b ≤ m a) := by simp only [at_top, tendsto_infi, tendsto_principal, mem_set_of_eq] lemma tendsto_at_bot [preorder β] (m : α → β) (f : filter α) : tendsto m f at_bot ↔ (∀b, ∀ᶠ a in f, m a ≤ b) := @tendsto_at_top α (order_dual β) _ m f lemma tendsto_at_top_mono' [preorder β] (l : filter α) ⦃f₁ f₂ : α → β⦄ (h : f₁ ≤ᶠ[l] f₂) : tendsto f₁ l at_top → tendsto f₂ l at_top := assume h₁, (tendsto_at_top _ _).2 $ λ b, mp_sets ((tendsto_at_top _ _).1 h₁ b) (monotone_mem_sets (λ a ha ha₁, le_trans ha₁ ha) h) lemma tendsto_at_top_mono [preorder β] {l : filter α} {f g : α → β} (h : ∀ n, f n ≤ g n) : tendsto f l at_top → tendsto g l at_top := tendsto_at_top_mono' l $ eventually_of_forall h /-! ### Sequences -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma inf_map_at_top_ne_bot_iff [semilattice_sup α] [nonempty α] {F : filter β} {u : α → β} : ne_bot (F ⊓ (map u at_top)) ↔ ∀ U ∈ F, ∀ N, ∃ n ≥ N, u n ∈ U := by simp_rw [inf_ne_bot_iff_frequently_left, frequently_map, frequently_at_top]; refl lemma extraction_of_frequently_at_top' {P : ℕ → Prop} (h : ∀ N, ∃ n > N, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := begin choose u hu using h, cases forall_and_distrib.mp hu with hu hu', exact ⟨u ∘ (nat.rec 0 (λ n v, u v)), strict_mono.nat (λ n, hu _), λ n, hu' _⟩, end lemma extraction_of_frequently_at_top {P : ℕ → Prop} (h : ∃ᶠ n in at_top, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := begin rw frequently_at_top' at h, exact extraction_of_frequently_at_top' h, end lemma extraction_of_eventually_at_top {P : ℕ → Prop} (h : ∀ᶠ n in at_top, P n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ ∀ n, P (φ n) := extraction_of_frequently_at_top h.frequently @[nolint ge_or_gt] -- see Note [nolint_ge] lemma exists_le_of_tendsto_at_top [semilattice_sup α] [preorder β] {u : α → β} (h : tendsto u at_top at_top) : ∀ a b, ∃ a' ≥ a, b ≤ u a' := begin intros a b, have : ∀ᶠ x in at_top, a ≤ x ∧ b ≤ u x := (eventually_ge_at_top a).and (h.eventually $ eventually_ge_at_top b), haveI : nonempty α := ⟨a⟩, rcases this.exists with ⟨a', ha, hb⟩, exact ⟨a', ha, hb⟩ end @[nolint ge_or_gt] -- see Note [nolint_ge] lemma exists_lt_of_tendsto_at_top [semilattice_sup α] [preorder β] [no_top_order β] {u : α → β} (h : tendsto u at_top at_top) : ∀ a b, ∃ a' ≥ a, b < u a' := begin intros a b, cases no_top b with b' hb', rcases exists_le_of_tendsto_at_top h a b' with ⟨a', ha', ha''⟩, exact ⟨a', ha', lt_of_lt_of_le hb' ha''⟩ end /-- If `u` is a sequence which is unbounded above, then after any point, it reaches a value strictly greater than all previous values. -/ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma high_scores [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∀ N, ∃ n ≥ N, ∀ k < n, u k < u n := begin letI := classical.DLO β, intros N, let A := finset.image u (finset.range $ N+1), -- A = {u 0, ..., u N} have Ane : A.nonempty, from ⟨u 0, finset.mem_image_of_mem _ (finset.mem_range.mpr $ nat.zero_lt_succ _)⟩, let M := finset.max' A Ane, have ex : ∃ n ≥ N, M < u n, from exists_lt_of_tendsto_at_top hu _ _, obtain ⟨n, hnN, hnM, hn_min⟩ : ∃ n, N ≤ n ∧ M < u n ∧ ∀ k, N ≤ k → k < n → u k ≤ M, { use nat.find ex, rw ← and_assoc, split, { simpa using nat.find_spec ex }, { intros k hk hk', simpa [hk] using nat.find_min ex hk' } }, use [n, hnN], intros k hk, by_cases H : k ≤ N, { have : u k ∈ A, from finset.mem_image_of_mem _ (finset.mem_range.mpr $ nat.lt_succ_of_le H), have : u k ≤ M, from finset.le_max' A Ane (u k) this, exact lt_of_le_of_lt this hnM }, { push_neg at H, calc u k ≤ M : hn_min k (le_of_lt H) hk ... < u n : hnM }, end /-- If `u` is a sequence which is unbounded above, then it `frequently` reaches a value strictly greater than all previous values. -/ lemma frequently_high_scores [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∃ᶠ n in at_top, ∀ k < n, u k < u n := by simpa [frequently_at_top] using high_scores hu lemma strict_mono_subseq_of_tendsto_at_top {β : Type*} [linear_order β] [no_top_order β] {u : ℕ → β} (hu : tendsto u at_top at_top) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ strict_mono (u ∘ φ) := let ⟨φ, h, h'⟩ := extraction_of_frequently_at_top (frequently_high_scores hu) in ⟨φ, h, λ n m hnm, h' m _ (h hnm)⟩ lemma strict_mono_subseq_of_id_le {u : ℕ → ℕ} (hu : ∀ n, n ≤ u n) : ∃ φ : ℕ → ℕ, strict_mono φ ∧ strict_mono (u ∘ φ) := strict_mono_subseq_of_tendsto_at_top (tendsto_at_top_mono hu tendsto_id) lemma strict_mono_tendsto_at_top {φ : ℕ → ℕ} (h : strict_mono φ) : tendsto φ at_top at_top := tendsto_at_top_mono h.id_le tendsto_id section ordered_add_comm_monoid variables [ordered_add_comm_monoid β] {l : filter α} {f g : α → β} lemma tendsto_at_top_add_nonneg_left' (hf : ∀ᶠ x in l, 0 ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (hf.mono (λ x, le_add_of_nonneg_left)) hg lemma tendsto_at_top_add_nonneg_left (hf : ∀ x, 0 ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_left' (eventually_of_forall hf) hg lemma tendsto_at_top_add_nonneg_right' (hf : tendsto f l at_top) (hg : ∀ᶠ x in l, 0 ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_mono' l (monotone_mem_sets (λ x, le_add_of_nonneg_right) hg) hf lemma tendsto_at_top_add_nonneg_right (hf : tendsto f l at_top) (hg : ∀ x, 0 ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_nonneg_right' hf (eventually_of_forall hg) end ordered_add_comm_monoid section ordered_cancel_add_comm_monoid variables [ordered_cancel_add_comm_monoid β] {l : filter α} {f g : α → β} lemma tendsto_at_top_of_add_const_left (C : β) (hf : tendsto (λ x, C + f x) l at_top) : tendsto f l at_top := (tendsto_at_top _ l).2 $ assume b, ((tendsto_at_top _ _).1 hf (C + b)).mono (λ x, le_of_add_le_add_left) lemma tendsto_at_top_of_add_const_right (C : β) (hf : tendsto (λ x, f x + C) l at_top) : tendsto f l at_top := (tendsto_at_top _ l).2 $ assume b, ((tendsto_at_top _ _).1 hf (b + C)).mono (λ x, le_of_add_le_add_right) lemma tendsto_at_top_of_add_bdd_above_left' (C) (hC : ∀ᶠ x in l, f x ≤ C) (h : tendsto (λ x, f x + g x) l at_top) : tendsto g l at_top := tendsto_at_top_of_add_const_left C (tendsto_at_top_mono' l (hC.mono (λ x hx, add_le_add_right hx (g x))) h) lemma tendsto_at_top_of_add_bdd_above_left (C) (hC : ∀ x, f x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto g l at_top := tendsto_at_top_of_add_bdd_above_left' C (univ_mem_sets' hC) lemma tendsto_at_top_of_add_bdd_above_right' (C) (hC : ∀ᶠ x in l, g x ≤ C) (h : tendsto (λ x, f x + g x) l at_top) : tendsto f l at_top := tendsto_at_top_of_add_const_right C (tendsto_at_top_mono' l (hC.mono (λ x hx, add_le_add_left hx (f x))) h) lemma tendsto_at_top_of_add_bdd_above_right (C) (hC : ∀ x, g x ≤ C) : tendsto (λ x, f x + g x) l at_top → tendsto f l at_top := tendsto_at_top_of_add_bdd_above_right' C (univ_mem_sets' hC) end ordered_cancel_add_comm_monoid section ordered_group variables [ordered_add_comm_group β] (l : filter α) {f g : α → β} lemma tendsto_at_top_add_left_of_le' (C : β) (hf : ∀ᶠ x in l, C ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_left' _ _ _ l (λ x, -(f x)) (λ x, f x + g x) (-C) (by simpa) (by simpa) lemma tendsto_at_top_add_left_of_le (C : β) (hf : ∀ x, C ≤ f x) (hg : tendsto g l at_top) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' hf) hg lemma tendsto_at_top_add_right_of_le' (C : β) (hf : tendsto f l at_top) (hg : ∀ᶠ x in l, C ≤ g x) : tendsto (λ x, f x + g x) l at_top := @tendsto_at_top_of_add_bdd_above_right' _ _ _ l (λ x, f x + g x) (λ x, -(g x)) (-C) (by simp [hg]) (by simp [hf]) lemma tendsto_at_top_add_right_of_le (C : β) (hf : tendsto f l at_top) (hg : ∀ x, C ≤ g x) : tendsto (λ x, f x + g x) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' hg) lemma tendsto_at_top_add_const_left (C : β) (hf : tendsto f l at_top) : tendsto (λ x, C + f x) l at_top := tendsto_at_top_add_left_of_le' l C (univ_mem_sets' $ λ _, le_refl C) hf lemma tendsto_at_top_add_const_right (C : β) (hf : tendsto f l at_top) : tendsto (λ x, f x + C) l at_top := tendsto_at_top_add_right_of_le' l C hf (univ_mem_sets' $ λ _, le_refl C) end ordered_group open_locale filter @[nolint ge_or_gt] lemma tendsto_at_top' [nonempty α] [semilattice_sup α] (f : α → β) (l : filter β) : tendsto f at_top l ↔ (∀s ∈ l, ∃a, ∀b≥a, f b ∈ s) := by simp only [tendsto_def, mem_at_top_sets]; refl lemma tendsto_at_bot' [nonempty α] [semilattice_inf α] (f : α → β) (l : filter β) : tendsto f at_bot l ↔ (∀s ∈ l, ∃a, ∀b≤a, f b ∈ s) := @tendsto_at_top' (order_dual α) _ _ _ _ _ @[nolint ge_or_gt] theorem tendsto_at_top_principal [nonempty β] [semilattice_sup β] {f : β → α} {s : set α} : tendsto f at_top (𝓟 s) ↔ ∃N, ∀n≥N, f n ∈ s := by rw [tendsto_iff_comap, comap_principal, le_principal_iff, mem_at_top_sets]; refl /-- A function `f` grows to infinity independent of an order-preserving embedding `e`. -/ lemma tendsto_at_top_embedding [preorder β] [preorder γ] {f : α → β} {e : β → γ} {l : filter α} (hm : ∀b₁ b₂, e b₁ ≤ e b₂ ↔ b₁ ≤ b₂) (hu : ∀c, ∃b, c ≤ e b) : tendsto (e ∘ f) l at_top ↔ tendsto f l at_top := begin rw [tendsto_at_top, tendsto_at_top], split, { assume hc b, filter_upwards [hc (e b)] assume a, (hm b (f a)).1 }, { assume hb c, rcases hu c with ⟨b, hc⟩, filter_upwards [hb b] assume a ha, le_trans hc ((hm b (f a)).2 ha) } end lemma tendsto_at_top_at_top [nonempty α] [semilattice_sup α] [preorder β] (f : α → β) : tendsto f at_top at_top ↔ ∀ b : β, ∃ i : α, ∀ a : α, i ≤ a → b ≤ f a := iff.trans tendsto_infi $ forall_congr $ assume b, tendsto_at_top_principal lemma tendsto_at_top_at_bot [nonempty α] [semilattice_sup α] [preorder β] (f : α → β) : tendsto f at_top at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), i ≤ a → f a ≤ b := @tendsto_at_top_at_top α (order_dual β) _ _ _ f lemma tendsto_at_bot_at_top [nonempty α] [semilattice_inf α] [preorder β] (f : α → β) : tendsto f at_bot at_top ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → b ≤ f a := @tendsto_at_top_at_top (order_dual α) β _ _ _ f lemma tendsto_at_bot_at_bot [nonempty α] [semilattice_inf α] [preorder β] (f : α → β) : tendsto f at_bot at_bot ↔ ∀ (b : β), ∃ (i : α), ∀ (a : α), a ≤ i → f a ≤ b := @tendsto_at_top_at_top (order_dual α) (order_dual β) _ _ _ f lemma tendsto_at_top_at_top_of_monotone [preorder α] [preorder β] {f : α → β} (hf : monotone f) (h : ∀ b, ∃ a, b ≤ f a) : tendsto f at_top at_top := tendsto_infi.2 $ λ b, tendsto_principal.2 $ let ⟨a, ha⟩ := h b in mem_sets_of_superset (mem_at_top a) $ λ a' ha', le_trans ha (hf ha') lemma tendsto_at_top_at_top_iff_of_monotone [nonempty α] [semilattice_sup α] [preorder β] {f : α → β} (hf : monotone f) : tendsto f at_top at_top ↔ ∀ b : β, ∃ a : α, b ≤ f a := (tendsto_at_top_at_top f).trans $ forall_congr $ λ b, exists_congr $ λ a, ⟨λ h, h a (le_refl a), λ h a' ha', le_trans h $ hf ha'⟩ alias tendsto_at_top_at_top_of_monotone ← monotone.tendsto_at_top_at_top alias tendsto_at_top_at_top_iff_of_monotone ← monotone.tendsto_at_top_at_top_iff lemma tendsto_finset_range : tendsto finset.range at_top at_top := finset.range_mono.tendsto_at_top_at_top finset.exists_nat_subset_range /-- If `f` is a monotone sequence of `finset`s and each `x` belongs to one of `f n`, then `tendsto f at_top at_top`. -/ lemma monotone.tendsto_at_top_finset [semilattice_sup β] {f : β → finset α} (h : monotone f) (h' : ∀ x : α, ∃ n, x ∈ f n) : tendsto f at_top at_top := begin by_cases ne : nonempty β, { resetI, apply h.tendsto_at_top_at_top, choose N hN using h', assume b, rcases (b.image N).bdd_above with ⟨n, hn⟩, refine ⟨n, λ i ib, _⟩, have : N i ∈ b.image N := finset.mem_image_of_mem _ ib, exact h (hn $ finset.mem_coe.2 this) (hN i) }, { exact tendsto_of_not_nonempty ne } end lemma tendsto_finset_image_at_top_at_top {i : β → γ} {j : γ → β} (h : function.left_inverse j i) : tendsto (finset.image j) at_top at_top := (finset.image_mono j).tendsto_at_top_at_top $ assume s, ⟨s.image i, by simp only [finset.image_image, h.comp_eq_id, finset.image_id, le_refl]⟩ lemma prod_at_top_at_top_eq {β₁ β₂ : Type*} [semilattice_sup β₁] [semilattice_sup β₂] : (at_top : filter β₁) ×ᶠ (at_top : filter β₂) = (at_top : filter (β₁ × β₂)) := begin by_cases ne : nonempty β₁ ∧ nonempty β₂, { cases ne, resetI, inhabit β₁, inhabit β₂, simp [at_top, prod_infi_left (default β₁), prod_infi_right (default β₂), infi_prod], exact infi_comm }, { rw not_and_distrib at ne, cases ne; { have : ¬ (nonempty (β₁ × β₂)), by simp [ne], rw [at_top.filter_eq_bot_of_not_nonempty ne, at_top.filter_eq_bot_of_not_nonempty this], simp only [bot_prod, prod_bot] } } end lemma prod_map_at_top_eq {α₁ α₂ β₁ β₂ : Type*} [semilattice_sup β₁] [semilattice_sup β₂] (u₁ : β₁ → α₁) (u₂ : β₂ → α₂) : (map u₁ at_top) ×ᶠ (map u₂ at_top) = map (prod.map u₁ u₂) at_top := by rw [prod_map_map_eq, prod_at_top_at_top_eq, prod.map_def] /-- A function `f` maps upwards closed sets (at_top sets) to upwards closed sets when it is a Galois insertion. The Galois "insertion" and "connection" is weakened to only require it to be an insertion and a connetion above `b'`. -/ lemma map_at_top_eq_of_gc [semilattice_sup α] [semilattice_sup β] {f : α → β} (g : β → α) (b' : β) (hf : monotone f) (gc : ∀a, ∀b≥b', f a ≤ b ↔ a ≤ g b) (hgi : ∀b≥b', b ≤ f (g b)) : map f at_top = at_top := begin rw [@map_at_top_eq α _ ⟨g b'⟩], refine le_antisymm (le_infi $ assume b, infi_le_of_le (g (b ⊔ b')) $ principal_mono.2 $ image_subset_iff.2 _) (le_infi $ assume a, infi_le_of_le (f a ⊔ b') $ principal_mono.2 _), { assume a ha, exact (le_trans le_sup_left $ le_trans (hgi _ le_sup_right) $ hf ha) }, { assume b hb, have hb' : b' ≤ b := le_trans le_sup_right hb, exact ⟨g b, (gc _ _ hb').1 (le_trans le_sup_left hb), le_antisymm ((gc _ _ hb').2 (le_refl _)) (hgi _ hb')⟩ } end lemma map_add_at_top_eq_nat (k : ℕ) : map (λa, a + k) at_top = at_top := map_at_top_eq_of_gc (λa, a - k) k (assume a b h, add_le_add_right h k) (assume a b h, (nat.le_sub_right_iff_add_le h).symm) (assume a h, by rw [nat.sub_add_cancel h]) lemma map_sub_at_top_eq_nat (k : ℕ) : map (λa, a - k) at_top = at_top := map_at_top_eq_of_gc (λa, a + k) 0 (assume a b h, nat.sub_le_sub_right h _) (assume a b _, nat.sub_le_right_iff_le_add) (assume b _, by rw [nat.add_sub_cancel]) lemma tendsto_add_at_top_nat (k : ℕ) : tendsto (λa, a + k) at_top at_top := le_of_eq (map_add_at_top_eq_nat k) lemma tendsto_sub_at_top_nat (k : ℕ) : tendsto (λa, a - k) at_top at_top := le_of_eq (map_sub_at_top_eq_nat k) lemma tendsto_add_at_top_iff_nat {f : ℕ → α} {l : filter α} (k : ℕ) : tendsto (λn, f (n + k)) at_top l ↔ tendsto f at_top l := show tendsto (f ∘ (λn, n + k)) at_top l ↔ tendsto f at_top l, by rw [← tendsto_map'_iff, map_add_at_top_eq_nat] lemma map_div_at_top_eq_nat (k : ℕ) (hk : k > 0) : map (λa, a / k) at_top = at_top := map_at_top_eq_of_gc (λb, b * k + (k - 1)) 1 (assume a b h, nat.div_le_div_right h) (assume a b _, calc a / k ≤ b ↔ a / k < b + 1 : by rw [← nat.succ_eq_add_one, nat.lt_succ_iff] ... ↔ a < (b + 1) * k : nat.div_lt_iff_lt_mul _ _ hk ... ↔ _ : begin cases k, exact (lt_irrefl _ hk).elim, simp [mul_add, add_mul, nat.succ_add, nat.lt_succ_iff] end) (assume b _, calc b = (b * k) / k : by rw [nat.mul_div_cancel b hk] ... ≤ (b * k + (k - 1)) / k : nat.div_le_div_right $ nat.le_add_right _ _) /-- If `u` is a monotone function with linear ordered codomain and the range of `u` is not bounded above, then `tendsto u at_top at_top`. -/ lemma tendsto_at_top_at_top_of_monotone' [preorder ι] [linear_order α] {u : ι → α} (h : monotone u) (H : ¬bdd_above (range u)) : tendsto u at_top at_top := begin apply h.tendsto_at_top_at_top, intro b, rcases not_bdd_above_iff.1 H b with ⟨_, ⟨N, rfl⟩, hN⟩, exact ⟨N, le_of_lt hN⟩, end lemma unbounded_of_tendsto_at_top [nonempty α] [semilattice_sup α] [preorder β] [no_top_order β] {f : α → β} (h : tendsto f at_top at_top) : ¬ bdd_above (range f) := begin rintros ⟨M, hM⟩, cases mem_at_top_sets.mp (h $ Ioi_mem_at_top M) with a ha, apply lt_irrefl M, calc M < f a : ha a (le_refl _) ... ≤ M : hM (set.mem_range_self a) end /-- If a monotone function `u : ι → α` tends to `at_top` along *some* non-trivial filter `l`, then it tends to `at_top` along `at_top`. -/ lemma tendsto_at_top_of_monotone_of_filter [preorder ι] [preorder α] {l : filter ι} {u : ι → α} (h : monotone u) [ne_bot l] (hu : tendsto u l at_top) : tendsto u at_top at_top := h.tendsto_at_top_at_top $ λ b, (hu.eventually (mem_at_top b)).exists lemma tendsto_at_top_of_monotone_of_subseq [preorder ι] [preorder α] {u : ι → α} {φ : ι' → ι} (h : monotone u) {l : filter ι'} [ne_bot l] (H : tendsto (u ∘ φ) l at_top) : tendsto u at_top at_top := tendsto_at_top_of_monotone_of_filter h (tendsto_map' H) lemma tendsto_neg_at_top_at_bot [ordered_add_comm_group α] : tendsto (has_neg.neg : α → α) at_top at_bot := begin simp only [tendsto_at_bot, neg_le], exact λ b, eventually_ge_at_top _ end lemma tendsto_neg_at_bot_at_top [ordered_add_comm_group α] : tendsto (has_neg.neg : α → α) at_bot at_top := @tendsto_neg_at_top_at_bot (order_dual α) _ /-- Let `f` and `g` be two maps to the same commutative monoid. This lemma gives a sufficient condition for comparison of the filter `at_top.map (λ s, ∏ b in s, f b)` with `at_top.map (λ s, ∏ b in s, g b)`. This is useful to compare the set of limit points of `Π b in s, f b` as `s → at_top` with the similar set for `g`. -/ @[to_additive] lemma map_at_top_finset_prod_le_of_prod_eq [comm_monoid α] {f : β → α} {g : γ → α} (h_eq : ∀u:finset γ, ∃v:finset β, ∀v', v ⊆ v' → ∃u', u ⊆ u' ∧ ∏ x in u', g x = ∏ b in v', f b) : at_top.map (λs:finset β, ∏ b in s, f b) ≤ at_top.map (λs:finset γ, ∏ x in s, g x) := by rw [map_at_top_eq, map_at_top_eq]; from (le_infi $ assume b, let ⟨v, hv⟩ := h_eq b in infi_le_of_le v $ by simp [set.image_subset_iff]; exact hv) lemma has_antimono_basis.tendsto [semilattice_sup ι] [nonempty ι] {l : filter α} {p : ι → Prop} {s : ι → set α} (hl : l.has_antimono_basis p s) {φ : ι → α} (h : ∀ i : ι, φ i ∈ s i) : tendsto φ at_top l := begin rw hl.to_has_basis.tendsto_right_iff, intros i hi, rw eventually_at_top, exact ⟨i, λ j hij, hl.decreasing hi (hl.mono hij hi) hij (h j)⟩, end namespace is_countably_generated /-- An abstract version of continuity of sequentially continuous functions on metric spaces: if a filter `k` is countably generated then `tendsto f k l` iff for every sequence `u` converging to `k`, `f ∘ u` tends to `l`. -/ lemma tendsto_iff_seq_tendsto {f : α → β} {k : filter α} {l : filter β} (hcb : k.is_countably_generated) : tendsto f k l ↔ (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) := suffices (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l, from ⟨by intros; apply tendsto.comp; assumption, by assumption⟩, begin rcases hcb.exists_antimono_seq with ⟨g, gmon, gbasis⟩, have gbasis : ∀ A, A ∈ k ↔ ∃ i, g i ⊆ A, { intro A, subst gbasis, rw mem_infi, { simp only [set.mem_Union, iff_self, filter.mem_principal_sets] }, { exact directed_of_sup (λ i j h, principal_mono.mpr $ gmon h) } }, contrapose, simp only [not_forall, not_imp, not_exists, subset_def, @tendsto_def _ _ f, gbasis], rintro ⟨B, hBl, hfBk⟩, choose x h using hfBk, use x, split, { simp only [tendsto_at_top', gbasis], rintros A ⟨i, hgiA⟩, use i, refine (λ j hj, hgiA $ gmon hj _), simp only [h] }, { simp only [tendsto_at_top', (∘), not_forall, not_exists], use [B, hBl], intro i, use [i, (le_refl _)], apply (h i).right }, end lemma tendsto_of_seq_tendsto {f : α → β} {k : filter α} {l : filter β} (hcb : k.is_countably_generated) : (∀ x : ℕ → α, tendsto x at_top k → tendsto (f ∘ x) at_top l) → tendsto f k l := hcb.tendsto_iff_seq_tendsto.2 lemma subseq_tendsto {f : filter α} (hf : is_countably_generated f) {u : ℕ → α} (hx : ne_bot (f ⊓ map u at_top)) : ∃ (θ : ℕ → ℕ), (strict_mono θ) ∧ (tendsto (u ∘ θ) at_top f) := begin rcases hf.has_antimono_basis with ⟨B, h⟩, have : ∀ N, ∃ n ≥ N, u n ∈ B N, from λ N, filter.inf_map_at_top_ne_bot_iff.mp hx _ (h.to_has_basis.mem_of_mem trivial) N, choose φ hφ using this, cases forall_and_distrib.mp hφ with φ_ge φ_in, have lim_uφ : tendsto (u ∘ φ) at_top f, from h.tendsto φ_in, have lim_φ : tendsto φ at_top at_top, from (tendsto_at_top_mono φ_ge tendsto_id), obtain ⟨ψ, hψ, hψφ⟩ : ∃ ψ : ℕ → ℕ, strict_mono ψ ∧ strict_mono (φ ∘ ψ), from strict_mono_subseq_of_tendsto_at_top lim_φ, exact ⟨φ ∘ ψ, hψφ, lim_uφ.comp $ strict_mono_tendsto_at_top hψ⟩, end end is_countably_generated end filter open filter finset /-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g` to a commutative monoid. Suppose that `f x = 1` outside of the range of `g`. Then the filters `at_top.map (λ s, ∏ i in s, f (g i))` and `at_top.map (λ s, ∏ i in s, f i)` coincide. The additive version of this lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under the same assumptions.-/ @[to_additive] lemma function.injective.map_at_top_finset_prod_eq [comm_monoid α] {g : γ → β} (hg : function.injective g) {f : β → α} (hf : ∀ x ∉ set.range g, f x = 1) : map (λ s, ∏ i in s, f (g i)) at_top = map (λ s, ∏ i in s, f i) at_top := begin apply le_antisymm; refine map_at_top_finset_prod_le_of_prod_eq (λ s, _), { refine ⟨s.preimage (hg.inj_on _), λ t ht, _⟩, refine ⟨t.image g ∪ s, finset.subset_union_right _ _, _⟩, rw [← finset.prod_image (hg.inj_on _)], refine (prod_subset (subset_union_left _ _) _).symm, simp only [finset.mem_union, finset.mem_image], refine λ y hy hyt, hf y (mt _ hyt), rintros ⟨x, rfl⟩, exact ⟨x, ht (finset.mem_preimage.2 $ hy.resolve_left hyt), rfl⟩ }, { refine ⟨s.image g, λ t ht, _⟩, simp only [← prod_preimage _ _ (hg.inj_on _) _ (λ x _, hf x)], exact ⟨_, (image_subset_iff_subset_preimage _).1 ht, rfl⟩ } end /-- Let `g : γ → β` be an injective function and `f : β → α` be a function from the codomain of `g` to an additive commutative monoid. Suppose that `f x = 0` outside of the range of `g`. Then the filters `at_top.map (λ s, ∑ i in s, f (g i))` and `at_top.map (λ s, ∑ i in s, f i)` coincide. This lemma is used to prove the equality `∑' x, f (g x) = ∑' y, f y` under the same assumptions.-/ add_decl_doc function.injective.map_at_top_finset_sum_eq
d1a777e81485fb5e23a15acbffc4af38594e0fbf
82e44445c70db0f03e30d7be725775f122d72f3e
/src/order/filter/basic.lean
af744ac95dbc3614547323753175499fcec57b51
[ "Apache-2.0" ]
permissive
stjordanis/mathlib
51e286d19140e3788ef2c470bc7b953e4991f0c9
2568d41bca08f5d6bf39d915434c8447e21f42ee
refs/heads/master
1,631,748,053,501
1,627,938,886,000
1,627,938,886,000
228,728,358
0
0
Apache-2.0
1,576,630,588,000
1,576,630,587,000
null
UTF-8
Lean
false
false
112,400
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Jeremy Avigad -/ import order.zorn import order.copy import data.set.finite import tactic.monotonicity /-! # Theory of filters on sets ## Main definitions * `filter` : filters on a set; * `at_top`, `at_bot`, `cofinite`, `principal` : specific filters; * `map`, `comap`, `prod` : operations on filters; * `tendsto` : limit with respect to filters; * `eventually` : `f.eventually p` means `{x | p x} ∈ f`; * `frequently` : `f.frequently p` means `{x | ¬p x} ∉ f`; * `filter_upwards [h₁, ..., hₙ]` : takes a list of proofs `hᵢ : sᵢ ∈ f`, and replaces a goal `s ∈ f` with `∀ x, x ∈ s₁ → ... → x ∈ sₙ → x ∈ s`; * `ne_bot f` : an utility class stating that `f` is a non-trivial filter. Filters on a type `X` are sets of sets of `X` satisfying three conditions. They are mostly used to abstract two related kinds of ideas: * *limits*, including finite or infinite limits of sequences, finite or infinite limits of functions at a point or at infinity, etc... * *things happening eventually*, including things happening for large enough `n : ℕ`, or near enough a point `x`, or for close enough pairs of points, or things happening almost everywhere in the sense of measure theory. Dually, filters can also express the idea of *things happening often*: for arbitrarily large `n`, or at a point in any neighborhood of given a point etc... In this file, we define the type `filter X` of filters on `X`, and endow it with a complete lattice structure. This structure is lifted from the lattice structure on `set (set X)` using the Galois insertion which maps a filter to its elements in one direction, and an arbitrary set of sets to the smallest filter containing it in the other direction. We also prove `filter` is a monadic functor, with a push-forward operation `filter.map` and a pull-back operation `filter.comap` that form a Galois connections for the order on filters. Finally we describe a product operation `filter X → filter Y → filter (X × Y)`. The examples of filters appearing in the description of the two motivating ideas are: * `(at_top : filter ℕ)` : made of sets of `ℕ` containing `{n | n ≥ N}` for some `N` * `𝓝 x` : made of neighborhoods of `x` in a topological space (defined in topology.basic) * `𝓤 X` : made of entourages of a uniform space (those space are generalizations of metric spaces defined in topology.uniform_space.basic) * `μ.ae` : made of sets whose complement has zero measure with respect to `μ` (defined in `measure_theory.measure_space`) The general notion of limit of a map with respect to filters on the source and target types is `filter.tendsto`. It is defined in terms of the order and the push-forward operation. The predicate "happening eventually" is `filter.eventually`, and "happening often" is `filter.frequently`, whose definitions are immediate after `filter` is defined (but they come rather late in this file in order to immediately relate them to the lattice structure). For instance, anticipating on topology.basic, the statement: "if a sequence `u` converges to some `x` and `u n` belongs to a set `M` for `n` large enough then `x` is in the closure of `M`" is formalized as: `tendsto u at_top (𝓝 x) → (∀ᶠ n in at_top, u n ∈ M) → x ∈ closure M`, which is a special case of `mem_closure_of_tendsto` from topology.basic. ## Notations * `∀ᶠ x in f, p x` : `f.eventually p`; * `∃ᶠ x in f, p x` : `f.frequently p`; * `f =ᶠ[l] g` : `∀ᶠ x in l, f x = g x`; * `f ≤ᶠ[l] g` : `∀ᶠ x in l, f x ≤ g x`; * `f ×ᶠ g` : `filter.prod f g`, localized in `filter`; * `𝓟 s` : `principal s`, localized in `filter`. ## References * [N. Bourbaki, *General Topology*][bourbaki1966] Important note: Bourbaki requires that a filter on `X` cannot contain all sets of `X`, which we do *not* require. This gives `filter X` better formal properties, in particular a bottom element `⊥` for its lattice structure, at the cost of including the assumption `[ne_bot f]` in a number of lemmas and definitions. -/ open set universes u v w x y open_locale classical /-- A filter `F` on a type `α` is a collection of sets of `α` which contains the whole `α`, is upwards-closed, and is stable under intersection. We do not forbid this collection to be all sets of `α`. -/ structure filter (α : Type*) := (sets : set (set α)) (univ_sets : set.univ ∈ sets) (sets_of_superset {x y} : x ∈ sets → x ⊆ y → y ∈ sets) (inter_sets {x y} : x ∈ sets → y ∈ sets → x ∩ y ∈ sets) /-- If `F` is a filter on `α`, and `U` a subset of `α` then we can write `U ∈ F` as on paper. -/ instance {α : Type*}: has_mem (set α) (filter α) := ⟨λ U F, U ∈ F.sets⟩ namespace filter variables {α : Type u} {f g : filter α} {s t : set α} @[simp] protected lemma mem_mk {t : set (set α)} {h₁ h₂ h₃} : s ∈ mk t h₁ h₂ h₃ ↔ s ∈ t := iff.rfl @[simp] protected lemma mem_sets : s ∈ f.sets ↔ s ∈ f := iff.rfl instance inhabited_mem : inhabited {s : set α // s ∈ f} := ⟨⟨univ, f.univ_sets⟩⟩ lemma filter_eq : ∀{f g : filter α}, f.sets = g.sets → f = g | ⟨a, _, _, _⟩ ⟨._, _, _, _⟩ rfl := rfl lemma filter_eq_iff : f = g ↔ f.sets = g.sets := ⟨congr_arg _, filter_eq⟩ protected lemma ext_iff : f = g ↔ ∀ s, s ∈ f ↔ s ∈ g := by simp only [filter_eq_iff, ext_iff, filter.mem_sets] @[ext] protected lemma ext : (∀ s, s ∈ f ↔ s ∈ g) → f = g := filter.ext_iff.2 @[simp] lemma univ_mem_sets : univ ∈ f := f.univ_sets lemma mem_sets_of_superset : ∀{x y : set α}, x ∈ f → x ⊆ y → y ∈ f := f.sets_of_superset lemma inter_mem_sets : ∀{s t}, s ∈ f → t ∈ f → s ∩ t ∈ f := f.inter_sets @[simp] lemma inter_mem_sets_iff {s t} : s ∩ t ∈ f ↔ s ∈ f ∧ t ∈ f := ⟨λ h, ⟨mem_sets_of_superset h (inter_subset_left s t), mem_sets_of_superset h (inter_subset_right s t)⟩, and_imp.2 inter_mem_sets⟩ lemma univ_mem_sets' (h : ∀ a, a ∈ s) : s ∈ f := mem_sets_of_superset univ_mem_sets (assume x _, h x) lemma mp_sets (hs : s ∈ f) (h : {x | x ∈ s → x ∈ t} ∈ f) : t ∈ f := mem_sets_of_superset (inter_mem_sets hs h) $ assume x ⟨h₁, h₂⟩, h₂ h₁ lemma congr_sets (h : {x | x ∈ s ↔ x ∈ t} ∈ f) : s ∈ f ↔ t ∈ f := ⟨λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mp)), λ hs, mp_sets hs (mem_sets_of_superset h (λ x, iff.mpr))⟩ @[simp] lemma bInter_mem_sets {β : Type v} {s : β → set α} {is : set β} (hf : finite is) : (⋂ i ∈ is, s i) ∈ f ↔ ∀ i ∈ is, s i ∈ f := finite.induction_on hf (by simp) (λ i s hi _ hs, by simp [hs]) @[simp] lemma bInter_finset_mem_sets {β : Type v} {s : β → set α} (is : finset β) : (⋂ i ∈ is, s i) ∈ f ↔ ∀ i ∈ is, s i ∈ f := bInter_mem_sets is.finite_to_set alias bInter_finset_mem_sets ← finset.Inter_mem_sets attribute [protected] finset.Inter_mem_sets @[simp] lemma sInter_mem_sets {s : set (set α)} (hfin : finite s) : ⋂₀ s ∈ f ↔ ∀ U ∈ s, U ∈ f := by rw [sInter_eq_bInter, bInter_mem_sets hfin] @[simp] lemma Inter_mem_sets {β : Type v} {s : β → set α} [fintype β] : (⋂ i, s i) ∈ f ↔ ∀ i, s i ∈ f := by simpa using bInter_mem_sets finite_univ lemma exists_sets_subset_iff : (∃t ∈ f, t ⊆ s) ↔ s ∈ f := ⟨assume ⟨t, ht, ts⟩, mem_sets_of_superset ht ts, assume hs, ⟨s, hs, subset.refl _⟩⟩ lemma monotone_mem_sets {f : filter α} : monotone (λs, s ∈ f) := assume s t hst h, mem_sets_of_superset h hst end filter namespace tactic.interactive open tactic interactive /-- `filter_upwards [h1, ⋯, hn]` replaces a goal of the form `s ∈ f` and terms `h1 : t1 ∈ f, ⋯, hn : tn ∈ f` with `∀x, x ∈ t1 → ⋯ → x ∈ tn → x ∈ s`. `filter_upwards [h1, ⋯, hn] e` is a short form for `{ filter_upwards [h1, ⋯, hn], exact e }`. -/ meta def filter_upwards (s : parse types.pexpr_list) (e' : parse $ optional types.texpr) : tactic unit := do s.reverse.mmap (λ e, eapplyc `filter.mp_sets >> eapply e), eapplyc `filter.univ_mem_sets', `[dsimp only [set.mem_set_of_eq]], match e' with | some e := interactive.exact e | none := skip end add_tactic_doc { name := "filter_upwards", category := doc_category.tactic, decl_names := [`tactic.interactive.filter_upwards], tags := ["goal management", "lemma application"] } end tactic.interactive namespace filter variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} section principal /-- The principal filter of `s` is the collection of all supersets of `s`. -/ def principal (s : set α) : filter α := { sets := {t | s ⊆ t}, univ_sets := subset_univ s, sets_of_superset := assume x y hx hy, subset.trans hx hy, inter_sets := assume x y, subset_inter } localized "notation `𝓟` := filter.principal" in filter instance : inhabited (filter α) := ⟨𝓟 ∅⟩ @[simp] lemma mem_principal_sets {s t : set α} : s ∈ 𝓟 t ↔ t ⊆ s := iff.rfl lemma mem_principal_self (s : set α) : s ∈ 𝓟 s := subset.refl _ end principal open_locale filter section join /-- The join of a filter of filters is defined by the relation `s ∈ join f ↔ {t | s ∈ t} ∈ f`. -/ def join (f : filter (filter α)) : filter α := { sets := {s | {t : filter α | s ∈ t} ∈ f}, univ_sets := by simp only [mem_set_of_eq, univ_sets, ← filter.mem_sets, set_of_true], sets_of_superset := assume x y hx xy, mem_sets_of_superset hx $ assume f h, mem_sets_of_superset h xy, inter_sets := assume x y hx hy, mem_sets_of_superset (inter_mem_sets hx hy) $ assume f ⟨h₁, h₂⟩, inter_mem_sets h₁ h₂ } @[simp] lemma mem_join_sets {s : set α} {f : filter (filter α)} : s ∈ join f ↔ {t | s ∈ t} ∈ f := iff.rfl end join section lattice instance : partial_order (filter α) := { le := λf g, ∀ ⦃U : set α⦄, U ∈ g → U ∈ f, le_antisymm := assume a b h₁ h₂, filter_eq $ subset.antisymm h₂ h₁, le_refl := assume a, subset.refl _, le_trans := assume a b c h₁ h₂, subset.trans h₂ h₁ } theorem le_def {f g : filter α} : f ≤ g ↔ ∀ x ∈ g, x ∈ f := iff.rfl /-- `generate_sets g s`: `s` is in the filter closure of `g`. -/ inductive generate_sets (g : set (set α)) : set α → Prop | basic {s : set α} : s ∈ g → generate_sets s | univ : generate_sets univ | superset {s t : set α} : generate_sets s → s ⊆ t → generate_sets t | inter {s t : set α} : generate_sets s → generate_sets t → generate_sets (s ∩ t) /-- `generate g` is the smallest filter containing the sets `g`. -/ def generate (g : set (set α)) : filter α := { sets := generate_sets g, univ_sets := generate_sets.univ, sets_of_superset := assume x y, generate_sets.superset, inter_sets := assume s t, generate_sets.inter } lemma sets_iff_generate {s : set (set α)} {f : filter α} : f ≤ filter.generate s ↔ s ⊆ f.sets := iff.intro (assume h u hu, h $ generate_sets.basic $ hu) (assume h u hu, hu.rec_on h univ_mem_sets (assume x y _ hxy hx, mem_sets_of_superset hx hxy) (assume x y _ _ hx hy, inter_mem_sets hx hy)) lemma mem_generate_iff {s : set $ set α} {U : set α} : U ∈ generate s ↔ ∃ t ⊆ s, finite t ∧ ⋂₀ t ⊆ U := begin split ; intro h, { induction h with V V_in V W V_in hVW hV V W V_in W_in hV hW, { use {V}, simp [V_in] }, { use ∅, simp [subset.refl, univ] }, { rcases hV with ⟨t, hts, htfin, hinter⟩, exact ⟨t, hts, htfin, subset.trans hinter hVW⟩ }, { rcases hV with ⟨t, hts, htfin, htinter⟩, rcases hW with ⟨z, hzs, hzfin, hzinter⟩, refine ⟨t ∪ z, union_subset hts hzs, htfin.union hzfin, _⟩, rw sInter_union, exact inter_subset_inter htinter hzinter } }, { rcases h with ⟨t, ts, tfin, h⟩, apply generate_sets.superset _ h, revert ts, apply finite.induction_on tfin, { intro h, rw sInter_empty, exact generate_sets.univ }, { intros V r hV rfin hinter h, cases insert_subset.mp h with V_in r_sub, rw [insert_eq V r, sInter_union], apply generate_sets.inter _ (hinter r_sub), rw sInter_singleton, exact generate_sets.basic V_in } }, end /-- `mk_of_closure s hs` constructs a filter on `α` whose elements set is exactly `s : set (set α)`, provided one gives the assumption `hs : (generate s).sets = s`. -/ protected def mk_of_closure (s : set (set α)) (hs : (generate s).sets = s) : filter α := { sets := s, univ_sets := hs ▸ (univ_mem_sets : univ ∈ generate s), sets_of_superset := λ x y, hs ▸ (mem_sets_of_superset : x ∈ generate s → x ⊆ y → y ∈ generate s), inter_sets := λ x y, hs ▸ (inter_mem_sets : x ∈ generate s → y ∈ generate s → x ∩ y ∈ generate s) } lemma mk_of_closure_sets {s : set (set α)} {hs : (generate s).sets = s} : filter.mk_of_closure s hs = generate s := filter.ext $ assume u, show u ∈ (filter.mk_of_closure s hs).sets ↔ u ∈ (generate s).sets, from hs.symm ▸ iff.rfl /-- Galois insertion from sets of sets into filters. -/ def gi_generate (α : Type*) : @galois_insertion (set (set α)) (order_dual (filter α)) _ _ filter.generate filter.sets := { gc := assume s f, sets_iff_generate, le_l_u := assume f u h, generate_sets.basic h, choice := λs hs, filter.mk_of_closure s (le_antisymm hs $ sets_iff_generate.1 $ le_refl _), choice_eq := assume s hs, mk_of_closure_sets } /-- The infimum of filters is the filter generated by intersections of elements of the two filters. -/ instance : has_inf (filter α) := ⟨λf g : filter α, { sets := {s | ∃ (a ∈ f) (b ∈ g), a ∩ b ⊆ s }, univ_sets := ⟨_, univ_mem_sets, _, univ_mem_sets, inter_subset_left _ _⟩, sets_of_superset := assume x y ⟨a, ha, b, hb, h⟩ xy, ⟨a, ha, b, hb, subset.trans h xy⟩, inter_sets := assume x y ⟨a, ha, b, hb, hx⟩ ⟨c, hc, d, hd, hy⟩, ⟨_, inter_mem_sets ha hc, _, inter_mem_sets hb hd, calc a ∩ c ∩ (b ∩ d) = (a ∩ b) ∩ (c ∩ d) : by ac_refl ... ⊆ x ∩ y : inter_subset_inter hx hy⟩ }⟩ @[simp] lemma mem_inf_sets {f g : filter α} {s : set α} : s ∈ f ⊓ g ↔ ∃t₁∈f, ∃t₂∈g, t₁ ∩ t₂ ⊆ s := iff.rfl lemma mem_inf_sets_of_left {f g : filter α} {s : set α} (h : s ∈ f) : s ∈ f ⊓ g := ⟨s, h, univ, univ_mem_sets, inter_subset_left _ _⟩ lemma mem_inf_sets_of_right {f g : filter α} {s : set α} (h : s ∈ g) : s ∈ f ⊓ g := ⟨univ, univ_mem_sets, s, h, inter_subset_right _ _⟩ lemma inter_mem_inf_sets {α : Type u} {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s ∩ t ∈ f ⊓ g := inter_mem_sets (mem_inf_sets_of_left hs) (mem_inf_sets_of_right ht) instance : has_top (filter α) := ⟨{ sets := {s | ∀x, x ∈ s}, univ_sets := assume x, mem_univ x, sets_of_superset := assume x y hx hxy a, hxy (hx a), inter_sets := assume x y hx hy a, mem_inter (hx _) (hy _) }⟩ lemma mem_top_sets_iff_forall {s : set α} : s ∈ (⊤ : filter α) ↔ (∀x, x ∈ s) := iff.rfl @[simp] lemma mem_top_sets {s : set α} : s ∈ (⊤ : filter α) ↔ s = univ := by rw [mem_top_sets_iff_forall, eq_univ_iff_forall] section complete_lattice /- We lift the complete lattice along the Galois connection `generate` / `sets`. Unfortunately, we want to have different definitional equalities for the lattice operations. So we define them upfront and change the lattice operations for the complete lattice instance. -/ private def original_complete_lattice : complete_lattice (filter α) := @order_dual.complete_lattice _ (gi_generate α).lift_complete_lattice local attribute [instance] original_complete_lattice instance : complete_lattice (filter α) := original_complete_lattice.copy /- le -/ filter.partial_order.le rfl /- top -/ (filter.has_top).1 (top_unique $ assume s hs, by simp [mem_top_sets.1 hs]) /- bot -/ _ rfl /- sup -/ _ rfl /- inf -/ (filter.has_inf).1 begin ext f g : 2, exact le_antisymm (le_inf (assume s, mem_inf_sets_of_left) (assume s, mem_inf_sets_of_right)) (assume s ⟨a, ha, b, hb, hs⟩, show s ∈ complete_lattice.inf f g, from mem_sets_of_superset (inter_mem_sets (@inf_le_left (filter α) _ _ _ _ ha) (@inf_le_right (filter α) _ _ _ _ hb)) hs) end /- Sup -/ (join ∘ 𝓟) (by ext s x; exact (@mem_bInter_iff _ _ s filter.sets x).symm) /- Inf -/ _ rfl end complete_lattice /-- A filter is `ne_bot` if it is not equal to `⊥`, or equivalently the empty set does not belong to the filter. Bourbaki include this assumption in the definition of a filter but we prefer to have a `complete_lattice` structure on filter, so we use a typeclass argument in lemmas instead. -/ class ne_bot (f : filter α) : Prop := (ne' : f ≠ ⊥) lemma ne_bot_iff {f : filter α} : ne_bot f ↔ f ≠ ⊥ := ⟨λ h, h.1, λ h, ⟨h⟩⟩ lemma ne_bot.ne {f : filter α} (hf : ne_bot f) : f ≠ ⊥ := ne_bot.ne' @[simp] lemma not_ne_bot {α : Type*} {f : filter α} : ¬ f.ne_bot ↔ f = ⊥ := not_iff_comm.1 ne_bot_iff.symm lemma ne_bot.mono {f g : filter α} (hf : ne_bot f) (hg : f ≤ g) : ne_bot g := ⟨ne_bot_of_le_ne_bot hf.1 hg⟩ lemma ne_bot_of_le {f g : filter α} [hf : ne_bot f] (hg : f ≤ g) : ne_bot g := hf.mono hg lemma bot_sets_eq : (⊥ : filter α).sets = univ := rfl lemma sup_sets_eq {f g : filter α} : (f ⊔ g).sets = f.sets ∩ g.sets := (gi_generate α).gc.u_inf lemma Sup_sets_eq {s : set (filter α)} : (Sup s).sets = (⋂f∈s, (f:filter α).sets) := (gi_generate α).gc.u_Inf lemma supr_sets_eq {f : ι → filter α} : (supr f).sets = (⋂i, (f i).sets) := (gi_generate α).gc.u_infi lemma generate_empty : filter.generate ∅ = (⊤ : filter α) := (gi_generate α).gc.l_bot lemma generate_univ : filter.generate univ = (⊥ : filter α) := mk_of_closure_sets.symm lemma generate_union {s t : set (set α)} : filter.generate (s ∪ t) = filter.generate s ⊓ filter.generate t := (gi_generate α).gc.l_sup lemma generate_Union {s : ι → set (set α)} : filter.generate (⋃ i, s i) = (⨅ i, filter.generate (s i)) := (gi_generate α).gc.l_supr @[simp] lemma mem_bot_sets {s : set α} : s ∈ (⊥ : filter α) := trivial @[simp] lemma mem_sup_sets {f g : filter α} {s : set α} : s ∈ f ⊔ g ↔ s ∈ f ∧ s ∈ g := iff.rfl lemma union_mem_sup {f g : filter α} {s t : set α} (hs : s ∈ f) (ht : t ∈ g) : s ∪ t ∈ f ⊔ g := ⟨mem_sets_of_superset hs (subset_union_left s t), mem_sets_of_superset ht (subset_union_right s t)⟩ @[simp] lemma mem_Sup_sets {x : set α} {s : set (filter α)} : x ∈ Sup s ↔ (∀f∈s, x ∈ (f:filter α)) := iff.rfl @[simp] lemma mem_supr_sets {x : set α} {f : ι → filter α} : x ∈ supr f ↔ (∀i, x ∈ f i) := by simp only [← filter.mem_sets, supr_sets_eq, iff_self, mem_Inter] lemma infi_eq_generate (s : ι → filter α) : infi s = generate (⋃ i, (s i).sets) := show generate _ = generate _, from congr_arg _ supr_range lemma mem_infi_iff {ι} {s : ι → filter α} {U : set α} : (U ∈ ⨅ i, s i) ↔ ∃ I : set ι, finite I ∧ ∃ V : I → set α, (∀ i, V i ∈ s i) ∧ (⋂ i, V i) ⊆ U := begin rw [infi_eq_generate, mem_generate_iff], split, { rintro ⟨t, tsub, tfin, tinter⟩, rcases eq_finite_Union_of_finite_subset_Union tfin tsub with ⟨I, Ifin, σ, σfin, σsub, rfl⟩, rw sInter_Union at tinter, let V := λ i, ⋂₀ σ i, have V_in : ∀ i, V i ∈ s i, { rintro ⟨i, i_in⟩, rw sInter_mem_sets (σfin _), apply σsub }, exact ⟨I, Ifin, V, V_in, tinter⟩ }, { rintro ⟨I, Ifin, V, V_in, h⟩, refine ⟨range V, _, _, h⟩, { rintro _ ⟨i, rfl⟩, rw mem_Union, use [i, V_in i] }, { haveI : fintype I := finite.fintype Ifin, exact finite_range _ } }, end lemma mem_infi_iff' {ι} {s : ι → filter α} {U : set α} : (U ∈ ⨅ i, s i) ↔ ∃ I : set ι, finite I ∧ ∃ V : ι → set α, (∀ i ∈ I, V i ∈ s i) ∧ (⋂ i ∈ I, V i) ⊆ U := begin simp only [mem_infi_iff, set_coe.forall', bInter_eq_Inter], refine ⟨_, λ ⟨I, If, V, hV⟩, ⟨I, If, λ i, V i, hV⟩⟩, rintro ⟨I, If, V, hV⟩, lift V to ι → set α using trivial, exact ⟨I, If, V, hV⟩ end @[simp] lemma le_principal_iff {s : set α} {f : filter α} : f ≤ 𝓟 s ↔ s ∈ f := show (∀{t}, s ⊆ t → t ∈ f) ↔ s ∈ f, from ⟨assume h, h (subset.refl s), assume hs t ht, mem_sets_of_superset hs ht⟩ lemma principal_mono {s t : set α} : 𝓟 s ≤ 𝓟 t ↔ s ⊆ t := by simp only [le_principal_iff, iff_self, mem_principal_sets] @[mono] lemma monotone_principal : monotone (𝓟 : set α → filter α) := λ _ _, principal_mono.2 @[simp] lemma principal_eq_iff_eq {s t : set α} : 𝓟 s = 𝓟 t ↔ s = t := by simp only [le_antisymm_iff, le_principal_iff, mem_principal_sets]; refl @[simp] lemma join_principal_eq_Sup {s : set (filter α)} : join (𝓟 s) = Sup s := rfl @[simp] lemma principal_univ : 𝓟 (univ : set α) = ⊤ := top_unique $ by simp only [le_principal_iff, mem_top_sets, eq_self_iff_true] @[simp] lemma principal_empty : 𝓟 (∅ : set α) = ⊥ := bot_unique $ assume s _, empty_subset _ /-! ### Lattice equations -/ lemma empty_in_sets_eq_bot {f : filter α} : ∅ ∈ f ↔ f = ⊥ := ⟨assume h, bot_unique $ assume s _, mem_sets_of_superset h (empty_subset s), assume : f = ⊥, this.symm ▸ mem_bot_sets⟩ lemma nonempty_of_mem_sets {f : filter α} [hf : ne_bot f] {s : set α} (hs : s ∈ f) : s.nonempty := s.eq_empty_or_nonempty.elim (λ h, absurd hs (h.symm ▸ mt empty_in_sets_eq_bot.mp hf.1)) id lemma ne_bot.nonempty_of_mem {f : filter α} (hf : ne_bot f) {s : set α} (hs : s ∈ f) : s.nonempty := @nonempty_of_mem_sets α f hf s hs @[simp] lemma empty_nmem_sets (f : filter α) [ne_bot f] : ¬(∅ ∈ f) := λ h, (nonempty_of_mem_sets h).ne_empty rfl lemma nonempty_of_ne_bot (f : filter α) [ne_bot f] : nonempty α := nonempty_of_exists $ nonempty_of_mem_sets (univ_mem_sets : univ ∈ f) lemma compl_not_mem_sets {f : filter α} {s : set α} [ne_bot f] (h : s ∈ f) : sᶜ ∉ f := λ hsc, (nonempty_of_mem_sets (inter_mem_sets h hsc)).ne_empty $ inter_compl_self s lemma filter_eq_bot_of_is_empty [is_empty α] (f : filter α) : f = ⊥ := empty_in_sets_eq_bot.mp $ univ_mem_sets' is_empty_elim lemma filter_eq_bot_of_not_nonempty (f : filter α) (ne : ¬ nonempty α) : f = ⊥ := empty_in_sets_eq_bot.mp $ univ_mem_sets' $ assume x, false.elim (ne ⟨x⟩) /-- There is exactly one filter on an empty type. --/ -- TODO[gh-6025]: make this globally an instance once safe to do so local attribute [instance] protected def unique [is_empty α] : unique (filter α) := { default := ⊥, uniq := filter_eq_bot_of_is_empty } lemma forall_sets_nonempty_iff_ne_bot {f : filter α} : (∀ (s : set α), s ∈ f → s.nonempty) ↔ ne_bot f := ⟨λ h, ⟨λ hf, empty_not_nonempty (h ∅ $ hf.symm ▸ mem_bot_sets)⟩, @nonempty_of_mem_sets _ _⟩ lemma nontrivial_iff_nonempty : nontrivial (filter α) ↔ nonempty α := ⟨λ ⟨⟨f, g, hfg⟩⟩, by_contra $ λ h, hfg $ by haveI : is_empty α := not_nonempty_iff.1 h; exact subsingleton.elim _ _, λ ⟨x⟩, ⟨⟨⊤, ⊥, ne_bot.ne $ forall_sets_nonempty_iff_ne_bot.1 $ λ s hs, by rwa [mem_top_sets.1 hs, ← nonempty_iff_univ_nonempty]⟩⟩⟩ lemma mem_sets_of_eq_bot {f : filter α} {s : set α} (h : f ⊓ 𝓟 sᶜ = ⊥) : s ∈ f := have ∅ ∈ f ⊓ 𝓟 sᶜ, from h.symm ▸ mem_bot_sets, let ⟨s₁, hs₁, s₂, (hs₂ : sᶜ ⊆ s₂), (hs : s₁ ∩ s₂ ⊆ ∅)⟩ := this in by filter_upwards [hs₁] assume a ha, classical.by_contradiction $ assume ha', hs ⟨ha, hs₂ ha'⟩ lemma eq_Inf_of_mem_sets_iff_exists_mem {S : set (filter α)} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ f ∈ S, s ∈ f) : l = Inf S := le_antisymm (le_Inf $ λ f hf s hs, h.2 ⟨f, hf, hs⟩) (λ s hs, let ⟨f, hf, hs⟩ := h.1 hs in (Inf_le hf : Inf S ≤ f) hs) lemma eq_infi_of_mem_sets_iff_exists_mem {f : ι → filter α} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i, s ∈ f i) : l = infi f := eq_Inf_of_mem_sets_iff_exists_mem $ λ s, h.trans exists_range_iff.symm lemma eq_binfi_of_mem_sets_iff_exists_mem {f : ι → filter α} {p : ι → Prop} {l : filter α} (h : ∀ {s}, s ∈ l ↔ ∃ i (_ : p i), s ∈ f i) : l = ⨅ i (_ : p i), f i := begin rw [infi_subtype'], apply eq_infi_of_mem_sets_iff_exists_mem, intro s, exact h.trans ⟨λ ⟨i, pi, si⟩, ⟨⟨i, pi⟩, si⟩, λ ⟨⟨i, pi⟩, si⟩, ⟨i, pi, si⟩⟩ end lemma infi_sets_eq {f : ι → filter α} (h : directed (≥) f) [ne : nonempty ι] : (infi f).sets = (⋃ i, (f i).sets) := let ⟨i⟩ := ne, u := { filter . sets := (⋃ i, (f i).sets), univ_sets := by simp only [mem_Union]; exact ⟨i, univ_mem_sets⟩, sets_of_superset := by simp only [mem_Union, exists_imp_distrib]; intros x y i hx hxy; exact ⟨i, mem_sets_of_superset hx hxy⟩, inter_sets := begin simp only [mem_Union, exists_imp_distrib], assume x y a hx b hy, rcases h a b with ⟨c, ha, hb⟩, exact ⟨c, inter_mem_sets (ha hx) (hb hy)⟩ end } in have u = infi f, from eq_infi_of_mem_sets_iff_exists_mem (λ s, by simp only [filter.mem_mk, mem_Union, filter.mem_sets]), congr_arg filter.sets this.symm lemma mem_infi {f : ι → filter α} (h : directed (≥) f) [nonempty ι] (s) : s ∈ infi f ↔ ∃ i, s ∈ f i := by simp only [← filter.mem_sets, infi_sets_eq h, mem_Union] lemma mem_binfi {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) {t : set α} : t ∈ (⨅ i∈s, f i) ↔ ∃ i ∈ s, t ∈ f i := by haveI : nonempty {x // x ∈ s} := ne.to_subtype; erw [infi_subtype', mem_infi h.directed_coe, subtype.exists]; refl lemma binfi_sets_eq {f : β → filter α} {s : set β} (h : directed_on (f ⁻¹'o (≥)) s) (ne : s.nonempty) : (⨅ i∈s, f i).sets = (⋃ i ∈ s, (f i).sets) := ext $ λ t, by simp [mem_binfi h ne] lemma infi_sets_eq_finite {ι : Type*} (f : ι → filter α) : (⨅i, f i).sets = (⋃t:finset ι, (⨅i∈t, f i).sets) := begin rw [infi_eq_infi_finset, infi_sets_eq], exact (directed_of_sup $ λs₁ s₂ hs, infi_le_infi $ λi, infi_le_infi_const $ λh, hs h), end lemma infi_sets_eq_finite' (f : ι → filter α) : (⨅i, f i).sets = (⋃t:finset (plift ι), (⨅i∈t, f (plift.down i)).sets) := by rw [← infi_sets_eq_finite, ← equiv.plift.surjective.infi_comp]; refl lemma mem_infi_finite {ι : Type*} {f : ι → filter α} (s) : s ∈ infi f ↔ ∃ t:finset ι, s ∈ ⨅i∈t, f i := (set.ext_iff.1 (infi_sets_eq_finite f) s).trans mem_Union lemma mem_infi_finite' {f : ι → filter α} (s) : s ∈ infi f ↔ ∃ t:finset (plift ι), s ∈ ⨅i∈t, f (plift.down i) := (set.ext_iff.1 (infi_sets_eq_finite' f) s).trans mem_Union @[simp] lemma sup_join {f₁ f₂ : filter (filter α)} : (join f₁ ⊔ join f₂) = join (f₁ ⊔ f₂) := filter.ext $ λ x, by simp only [mem_sup_sets, mem_join_sets] @[simp] lemma supr_join {ι : Sort w} {f : ι → filter (filter α)} : (⨆x, join (f x)) = join (⨆x, f x) := filter.ext $ assume x, by simp only [mem_supr_sets, mem_join_sets] instance : bounded_distrib_lattice (filter α) := { le_sup_inf := begin assume x y z s, simp only [and_assoc, mem_inf_sets, mem_sup_sets, exists_prop, exists_imp_distrib, and_imp], intros hs t₁ ht₁ t₂ ht₂ hts, exact ⟨s ∪ t₁, x.sets_of_superset hs $ subset_union_left _ _, y.sets_of_superset ht₁ $ subset_union_right _ _, s ∪ t₂, x.sets_of_superset hs $ subset_union_left _ _, z.sets_of_superset ht₂ $ subset_union_right _ _, subset.trans (@le_sup_inf (set α) _ _ _ _) (union_subset (subset.refl _) hts)⟩ end, ..filter.complete_lattice } /- the complementary version with ⨆i, f ⊓ g i does not hold! -/ lemma infi_sup_left {f : filter α} {g : ι → filter α} : (⨅ x, f ⊔ g x) = f ⊔ infi g := begin refine le_antisymm _ (le_infi $ assume i, sup_le_sup_left (infi_le _ _) _), rintros t ⟨h₁, h₂⟩, rw [infi_sets_eq_finite'] at h₂, simp only [mem_Union, (finset.inf_eq_infi _ _).symm] at h₂, rcases h₂ with ⟨s, hs⟩, suffices : (⨅i, f ⊔ g i) ≤ f ⊔ s.inf (λi, g i.down), { exact this ⟨h₁, hs⟩ }, refine finset.induction_on s _ _, { exact le_sup_of_le_right le_top }, { rintros ⟨i⟩ s his ih, rw [finset.inf_insert, sup_inf_left], exact le_inf (infi_le _ _) ih } end lemma infi_sup_right {f : filter α} {g : ι → filter α} : (⨅ x, g x ⊔ f) = infi g ⊔ f := by simp [sup_comm, ← infi_sup_left] lemma binfi_sup_right (p : ι → Prop) (f : ι → filter α) (g : filter α) : (⨅ i (h : p i), (f i ⊔ g)) = (⨅ i (h : p i), f i) ⊔ g := by rw [infi_subtype', infi_sup_right, infi_subtype'] lemma binfi_sup_left (p : ι → Prop) (f : ι → filter α) (g : filter α) : (⨅ i (h : p i), (g ⊔ f i)) = g ⊔ (⨅ i (h : p i), f i) := by rw [infi_subtype', infi_sup_left, infi_subtype'] lemma mem_infi_sets_finset {s : finset α} {f : α → filter β} : ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⋂a∈s, p a) ⊆ t) := show ∀t, t ∈ (⨅a∈s, f a) ↔ (∃p:α → set β, (∀a∈s, p a ∈ f a) ∧ (⨅a∈s, p a) ≤ t), begin simp only [(finset.inf_eq_infi _ _).symm], refine finset.induction_on s _ _, { simp only [finset.not_mem_empty, false_implies_iff, finset.inf_empty, top_le_iff, imp_true_iff, mem_top_sets, true_and, exists_const], intros; refl }, { intros a s has ih t, simp only [ih, finset.forall_mem_insert, finset.inf_insert, mem_inf_sets, exists_prop, iff_iff_implies_and_implies, exists_imp_distrib, and_imp, and_assoc] {contextual := tt}, split, { intros t₁ ht₁ t₂ p hp ht₂ ht, existsi function.update p a t₁, have : ∀a'∈s, function.update p a t₁ a' = p a', from assume a' ha', have a' ≠ a, from assume h, has $ h ▸ ha', function.update_noteq this _ _, have eq : s.inf (λj, function.update p a t₁ j) = s.inf (λj, p j) := finset.inf_congr rfl this, simp only [this, ht₁, hp, function.update_same, true_and, imp_true_iff, eq] {contextual := tt}, exact subset.trans (inter_subset_inter (subset.refl _) ht₂) ht }, assume p hpa hp ht, exact ⟨p a, hpa, (s.inf p), ⟨⟨p, hp, le_refl _⟩, ht⟩⟩ } end /-- If `f : ι → filter α` is directed, `ι` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed` for a version assuming `nonempty α` instead of `nonempty ι`. -/ lemma infi_ne_bot_of_directed' {f : ι → filter α} [nonempty ι] (hd : directed (≥) f) (hb : ∀i, ne_bot (f i)) : ne_bot (infi f) := ⟨begin intro h, have he: ∅ ∈ (infi f), from h.symm ▸ (mem_bot_sets : ∅ ∈ (⊥ : filter α)), obtain ⟨i, hi⟩ : ∃i, ∅ ∈ f i, from (mem_infi hd ∅).1 he, exact (hb i).ne (empty_in_sets_eq_bot.1 hi) end⟩ /-- If `f : ι → filter α` is directed, `α` is not empty, and `∀ i, f i ≠ ⊥`, then `infi f ≠ ⊥`. See also `infi_ne_bot_of_directed'` for a version assuming `nonempty ι` instead of `nonempty α`. -/ lemma infi_ne_bot_of_directed {f : ι → filter α} [hn : nonempty α] (hd : directed (≥) f) (hb : ∀i, ne_bot (f i)) : ne_bot (infi f) := if hι : nonempty ι then @infi_ne_bot_of_directed' _ _ _ hι hd hb else ⟨λ h : infi f = ⊥, have univ ⊆ (∅ : set α), begin rw [←principal_mono, principal_univ, principal_empty, ←h], exact (le_infi $ assume i, false.elim $ hι ⟨i⟩) end, let ⟨x⟩ := hn in this (mem_univ x)⟩ lemma infi_ne_bot_iff_of_directed' {f : ι → filter α} [nonempty ι] (hd : directed (≥) f) : ne_bot (infi f) ↔ ∀i, ne_bot (f i) := ⟨assume H i, H.mono (infi_le _ i), infi_ne_bot_of_directed' hd⟩ lemma infi_ne_bot_iff_of_directed {f : ι → filter α} [nonempty α] (hd : directed (≥) f) : ne_bot (infi f) ↔ (∀i, ne_bot (f i)) := ⟨assume H i, H.mono (infi_le _ i), infi_ne_bot_of_directed hd⟩ lemma mem_infi_sets {f : ι → filter α} (i : ι) : ∀{s}, s ∈ f i → s ∈ ⨅i, f i := show (⨅i, f i) ≤ f i, from infi_le _ _ @[elab_as_eliminator] lemma infi_sets_induct {f : ι → filter α} {s : set α} (hs : s ∈ infi f) {p : set α → Prop} (uni : p univ) (ins : ∀{i s₁ s₂}, s₁ ∈ f i → p s₂ → p (s₁ ∩ s₂)) (upw : ∀{s₁ s₂}, s₁ ⊆ s₂ → p s₁ → p s₂) : p s := begin rw [mem_infi_finite'] at hs, simp only [← finset.inf_eq_infi] at hs, rcases hs with ⟨is, his⟩, revert s, refine finset.induction_on is _ _, { assume s hs, rwa [mem_top_sets.1 hs] }, { rintros ⟨i⟩ js his ih s hs, rw [finset.inf_insert, mem_inf_sets] at hs, rcases hs with ⟨s₁, hs₁, s₂, hs₂, hs⟩, exact upw hs (ins hs₁ (ih hs₂)) } end /- principal equations -/ @[simp] lemma inf_principal {s t : set α} : 𝓟 s ⊓ 𝓟 t = 𝓟 (s ∩ t) := le_antisymm (by simp; exact ⟨s, subset.refl s, t, subset.refl t, by simp⟩) (by simp [le_inf_iff, inter_subset_left, inter_subset_right]) @[simp] lemma sup_principal {s t : set α} : 𝓟 s ⊔ 𝓟 t = 𝓟 (s ∪ t) := filter.ext $ λ u, by simp only [union_subset_iff, mem_sup_sets, mem_principal_sets] @[simp] lemma supr_principal {ι : Sort w} {s : ι → set α} : (⨆x, 𝓟 (s x)) = 𝓟 (⋃i, s i) := filter.ext $ assume x, by simp only [mem_supr_sets, mem_principal_sets, Union_subset_iff] @[simp] lemma principal_eq_bot_iff {s : set α} : 𝓟 s = ⊥ ↔ s = ∅ := empty_in_sets_eq_bot.symm.trans $ mem_principal_sets.trans subset_empty_iff @[simp] lemma principal_ne_bot_iff {s : set α} : ne_bot (𝓟 s) ↔ s.nonempty := ne_bot_iff.trans $ (not_congr principal_eq_bot_iff).trans ne_empty_iff_nonempty lemma is_compl_principal (s : set α) : is_compl (𝓟 s) (𝓟 sᶜ) := ⟨by simp only [inf_principal, inter_compl_self, principal_empty, le_refl], by simp only [sup_principal, union_compl_self, principal_univ, le_refl]⟩ theorem mem_inf_principal {f : filter α} {s t : set α} : s ∈ f ⊓ 𝓟 t ↔ {x | x ∈ t → x ∈ s} ∈ f := begin simp only [← le_principal_iff, (is_compl_principal s).le_left_iff, disjoint, inf_assoc, inf_principal, imp_iff_not_or], rw [← disjoint, ← (is_compl_principal (t ∩ sᶜ)).le_right_iff, compl_inter, compl_compl], refl end lemma inf_principal_eq_bot {f : filter α} {s : set α} : f ⊓ 𝓟 s = ⊥ ↔ sᶜ ∈ f := by { rw [← empty_in_sets_eq_bot, mem_inf_principal], refl } lemma diff_mem_inf_principal_compl {f : filter α} {s : set α} (hs : s ∈ f) (t : set α) : s \ t ∈ f ⊓ 𝓟 tᶜ := begin rw mem_inf_principal, filter_upwards [hs], intros a has hat, exact ⟨has, hat⟩ end lemma principal_le_iff {s : set α} {f : filter α} : 𝓟 s ≤ f ↔ ∀ V ∈ f, s ⊆ V := begin change (∀ V, V ∈ f → V ∈ _) ↔ _, simp_rw mem_principal_sets, end @[simp] lemma infi_principal_finset {ι : Type w} (s : finset ι) (f : ι → set α) : (⨅i∈s, 𝓟 (f i)) = 𝓟 (⋂i∈s, f i) := begin ext t, simp [mem_infi_sets_finset], split, { rintros ⟨p, hp, ht⟩, calc (⋂ (i : ι) (H : i ∈ s), f i) ≤ (⋂ (i : ι) (H : i ∈ s), p i) : infi_le_infi (λi, infi_le_infi (λhi, mem_principal_sets.1 (hp i hi))) ... ≤ t : ht }, { assume h, exact ⟨f, λi hi, subset.refl _, h⟩ } end @[simp] lemma infi_principal_fintype {ι : Type w} [fintype ι] (f : ι → set α) : (⨅i, 𝓟 (f i)) = 𝓟 (⋂i, f i) := by simpa using infi_principal_finset finset.univ f lemma infi_principal_finite {ι : Type w} {s : set ι} (hs : finite s) (f : ι → set α) : (⨅i∈s, 𝓟 (f i)) = 𝓟 (⋂i∈s, f i) := begin unfreezingI { lift s to finset ι using hs }, -- TODO: why `unfreezingI` is needed? exact_mod_cast infi_principal_finset s f end end lattice @[mono] lemma join_mono {f₁ f₂ : filter (filter α)} (h : f₁ ≤ f₂) : join f₁ ≤ join f₂ := λ s hs, h hs /-! ### Eventually -/ /-- `f.eventually p` or `∀ᶠ x in f, p x` mean that `{x | p x} ∈ f`. E.g., `∀ᶠ x in at_top, p x` means that `p` holds true for sufficiently large `x`. -/ protected def eventually (p : α → Prop) (f : filter α) : Prop := {x | p x} ∈ f notation `∀ᶠ` binders ` in ` f `, ` r:(scoped p, filter.eventually p f) := r lemma eventually_iff {f : filter α} {P : α → Prop} : (∀ᶠ x in f, P x) ↔ {x | P x} ∈ f := iff.rfl protected lemma ext' {f₁ f₂ : filter α} (h : ∀ p : α → Prop, (∀ᶠ x in f₁, p x) ↔ (∀ᶠ x in f₂, p x)) : f₁ = f₂ := filter.ext h lemma eventually.filter_mono {f₁ f₂ : filter α} (h : f₁ ≤ f₂) {p : α → Prop} (hp : ∀ᶠ x in f₂, p x) : ∀ᶠ x in f₁, p x := h hp lemma eventually_of_mem {f : filter α} {P : α → Prop} {U : set α} (hU : U ∈ f) (h : ∀ x ∈ U, P x) : ∀ᶠ x in f, P x := mem_sets_of_superset hU h protected lemma eventually.and {p q : α → Prop} {f : filter α} : f.eventually p → f.eventually q → ∀ᶠ x in f, p x ∧ q x := inter_mem_sets @[simp] lemma eventually_true (f : filter α) : ∀ᶠ x in f, true := univ_mem_sets lemma eventually_of_forall {p : α → Prop} {f : filter α} (hp : ∀ x, p x) : ∀ᶠ x in f, p x := univ_mem_sets' hp @[simp] lemma eventually_false_iff_eq_bot {f : filter α} : (∀ᶠ x in f, false) ↔ f = ⊥ := empty_in_sets_eq_bot @[simp] lemma eventually_const {f : filter α} [t : ne_bot f] {p : Prop} : (∀ᶠ x in f, p) ↔ p := classical.by_cases (λ h : p, by simp [h]) (λ h, by simpa [h] using t.ne) lemma eventually_iff_exists_mem {p : α → Prop} {f : filter α} : (∀ᶠ x in f, p x) ↔ ∃ v ∈ f, ∀ y ∈ v, p y := exists_sets_subset_iff.symm lemma eventually.exists_mem {p : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) : ∃ v ∈ f, ∀ y ∈ v, p y := eventually_iff_exists_mem.1 hp lemma eventually.mp {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ᶠ x in f, p x → q x) : ∀ᶠ x in f, q x := mp_sets hp hq lemma eventually.mono {p q : α → Prop} {f : filter α} (hp : ∀ᶠ x in f, p x) (hq : ∀ x, p x → q x) : ∀ᶠ x in f, q x := hp.mp (eventually_of_forall hq) @[simp] lemma eventually_and {p q : α → Prop} {f : filter α} : (∀ᶠ x in f, p x ∧ q x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in f, q x) := inter_mem_sets_iff lemma eventually.congr {f : filter α} {p q : α → Prop} (h' : ∀ᶠ x in f, p x) (h : ∀ᶠ x in f, p x ↔ q x) : ∀ᶠ x in f, q x := h'.mp (h.mono $ λ x hx, hx.mp) lemma eventually_congr {f : filter α} {p q : α → Prop} (h : ∀ᶠ x in f, p x ↔ q x) : (∀ᶠ x in f, p x) ↔ (∀ᶠ x in f, q x) := ⟨λ hp, hp.congr h, λ hq, hq.congr $ by simpa only [iff.comm] using h⟩ @[simp] lemma eventually_all {ι} [fintype ι] {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i, p i x) ↔ ∀ i, ∀ᶠ x in l, p i x := by simpa only [filter.eventually, set_of_forall] using Inter_mem_sets @[simp] lemma eventually_all_finite {ι} {I : set ι} (hI : I.finite) {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i ∈ I, p i x) ↔ (∀ i ∈ I, ∀ᶠ x in l, p i x) := by simpa only [filter.eventually, set_of_forall] using bInter_mem_sets hI alias eventually_all_finite ← set.finite.eventually_all attribute [protected] set.finite.eventually_all @[simp] lemma eventually_all_finset {ι} (I : finset ι) {l} {p : ι → α → Prop} : (∀ᶠ x in l, ∀ i ∈ I, p i x) ↔ ∀ i ∈ I, ∀ᶠ x in l, p i x := I.finite_to_set.eventually_all alias eventually_all_finset ← finset.eventually_all attribute [protected] finset.eventually_all @[simp] lemma eventually_or_distrib_left {f : filter α} {p : Prop} {q : α → Prop} : (∀ᶠ x in f, p ∨ q x) ↔ (p ∨ ∀ᶠ x in f, q x) := classical.by_cases (λ h : p, by simp [h]) (λ h, by simp [h]) @[simp] lemma eventually_or_distrib_right {f : filter α} {p : α → Prop} {q : Prop} : (∀ᶠ x in f, p x ∨ q) ↔ ((∀ᶠ x in f, p x) ∨ q) := by simp only [or_comm _ q, eventually_or_distrib_left] @[simp] lemma eventually_imp_distrib_left {f : filter α} {p : Prop} {q : α → Prop} : (∀ᶠ x in f, p → q x) ↔ (p → ∀ᶠ x in f, q x) := by simp only [imp_iff_not_or, eventually_or_distrib_left] @[simp] lemma eventually_bot {p : α → Prop} : ∀ᶠ x in ⊥, p x := ⟨⟩ @[simp] lemma eventually_top {p : α → Prop} : (∀ᶠ x in ⊤, p x) ↔ (∀ x, p x) := iff.rfl @[simp] lemma eventually_sup {p : α → Prop} {f g : filter α} : (∀ᶠ x in f ⊔ g, p x) ↔ (∀ᶠ x in f, p x) ∧ (∀ᶠ x in g, p x) := iff.rfl @[simp] lemma eventually_Sup {p : α → Prop} {fs : set (filter α)} : (∀ᶠ x in Sup fs, p x) ↔ (∀ f ∈ fs, ∀ᶠ x in f, p x) := iff.rfl @[simp] lemma eventually_supr {p : α → Prop} {fs : β → filter α} : (∀ᶠ x in (⨆ b, fs b), p x) ↔ (∀ b, ∀ᶠ x in fs b, p x) := mem_supr_sets @[simp] lemma eventually_principal {a : set α} {p : α → Prop} : (∀ᶠ x in 𝓟 a, p x) ↔ (∀ x ∈ a, p x) := iff.rfl theorem eventually_inf_principal {f : filter α} {p : α → Prop} {s : set α} : (∀ᶠ x in f ⊓ 𝓟 s, p x) ↔ ∀ᶠ x in f, x ∈ s → p x := mem_inf_principal /-! ### Frequently -/ /-- `f.frequently p` or `∃ᶠ x in f, p x` mean that `{x | ¬p x} ∉ f`. E.g., `∃ᶠ x in at_top, p x` means that there exist arbitrarily large `x` for which `p` holds true. -/ protected def frequently (p : α → Prop) (f : filter α) : Prop := ¬∀ᶠ x in f, ¬p x notation `∃ᶠ` binders ` in ` f `, ` r:(scoped p, filter.frequently p f) := r lemma eventually.frequently {f : filter α} [ne_bot f] {p : α → Prop} (h : ∀ᶠ x in f, p x) : ∃ᶠ x in f, p x := compl_not_mem_sets h lemma frequently_of_forall {f : filter α} [ne_bot f] {p : α → Prop} (h : ∀ x, p x) : ∃ᶠ x in f, p x := eventually.frequently (eventually_of_forall h) lemma frequently.mp {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ᶠ x in f, p x → q x) : ∃ᶠ x in f, q x := mt (λ hq, hq.mp $ hpq.mono $ λ x, mt) h lemma frequently.filter_mono {p : α → Prop} {f g : filter α} (h : ∃ᶠ x in f, p x) (hle : f ≤ g) : ∃ᶠ x in g, p x := mt (λ h', h'.filter_mono hle) h lemma frequently.mono {p q : α → Prop} {f : filter α} (h : ∃ᶠ x in f, p x) (hpq : ∀ x, p x → q x) : ∃ᶠ x in f, q x := h.mp (eventually_of_forall hpq) lemma frequently.and_eventually {p q : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) (hq : ∀ᶠ x in f, q x) : ∃ᶠ x in f, p x ∧ q x := begin refine mt (λ h, hq.mp $ h.mono _) hp, assume x hpq hq hp, exact hpq ⟨hp, hq⟩ end lemma frequently.exists {p : α → Prop} {f : filter α} (hp : ∃ᶠ x in f, p x) : ∃ x, p x := begin by_contradiction H, replace H : ∀ᶠ x in f, ¬ p x, from eventually_of_forall (not_exists.1 H), exact hp H end lemma eventually.exists {p : α → Prop} {f : filter α} [ne_bot f] (hp : ∀ᶠ x in f, p x) : ∃ x, p x := hp.frequently.exists lemma frequently_iff_forall_eventually_exists_and {p : α → Prop} {f : filter α} : (∃ᶠ x in f, p x) ↔ ∀ {q : α → Prop}, (∀ᶠ x in f, q x) → ∃ x, p x ∧ q x := ⟨assume hp q hq, (hp.and_eventually hq).exists, assume H hp, by simpa only [and_not_self, exists_false] using H hp⟩ lemma frequently_iff {f : filter α} {P : α → Prop} : (∃ᶠ x in f, P x) ↔ ∀ {U}, U ∈ f → ∃ x ∈ U, P x := begin rw frequently_iff_forall_eventually_exists_and, split ; intro h, { intros U U_in, simpa [exists_prop, and_comm] using h U_in }, { intros H H', simpa [and_comm] using h H' }, end @[simp] lemma not_eventually {p : α → Prop} {f : filter α} : (¬ ∀ᶠ x in f, p x) ↔ (∃ᶠ x in f, ¬ p x) := by simp [filter.frequently] @[simp] lemma not_frequently {p : α → Prop} {f : filter α} : (¬ ∃ᶠ x in f, p x) ↔ (∀ᶠ x in f, ¬ p x) := by simp only [filter.frequently, not_not] @[simp] lemma frequently_true_iff_ne_bot (f : filter α) : (∃ᶠ x in f, true) ↔ ne_bot f := by simp [filter.frequently, -not_eventually, eventually_false_iff_eq_bot, ne_bot_iff] @[simp] lemma frequently_false (f : filter α) : ¬ ∃ᶠ x in f, false := by simp @[simp] lemma frequently_const {f : filter α} [ne_bot f] {p : Prop} : (∃ᶠ x in f, p) ↔ p := classical.by_cases (λ h : p, by simpa [h]) (λ h, by simp [h]) @[simp] lemma frequently_or_distrib {f : filter α} {p q : α → Prop} : (∃ᶠ x in f, p x ∨ q x) ↔ (∃ᶠ x in f, p x) ∨ (∃ᶠ x in f, q x) := by simp only [filter.frequently, ← not_and_distrib, not_or_distrib, eventually_and] lemma frequently_or_distrib_left {f : filter α} [ne_bot f] {p : Prop} {q : α → Prop} : (∃ᶠ x in f, p ∨ q x) ↔ (p ∨ ∃ᶠ x in f, q x) := by simp lemma frequently_or_distrib_right {f : filter α} [ne_bot f] {p : α → Prop} {q : Prop} : (∃ᶠ x in f, p x ∨ q) ↔ (∃ᶠ x in f, p x) ∨ q := by simp @[simp] lemma frequently_imp_distrib {f : filter α} {p q : α → Prop} : (∃ᶠ x in f, p x → q x) ↔ ((∀ᶠ x in f, p x) → ∃ᶠ x in f, q x) := by simp [imp_iff_not_or, not_eventually, frequently_or_distrib] lemma frequently_imp_distrib_left {f : filter α} [ne_bot f] {p : Prop} {q : α → Prop} : (∃ᶠ x in f, p → q x) ↔ (p → ∃ᶠ x in f, q x) := by simp lemma frequently_imp_distrib_right {f : filter α} [ne_bot f] {p : α → Prop} {q : Prop} : (∃ᶠ x in f, p x → q) ↔ ((∀ᶠ x in f, p x) → q) := by simp @[simp] lemma eventually_imp_distrib_right {f : filter α} {p : α → Prop} {q : Prop} : (∀ᶠ x in f, p x → q) ↔ ((∃ᶠ x in f, p x) → q) := by simp only [imp_iff_not_or, eventually_or_distrib_right, not_frequently] @[simp] lemma frequently_bot {p : α → Prop} : ¬ ∃ᶠ x in ⊥, p x := by simp @[simp] lemma frequently_top {p : α → Prop} : (∃ᶠ x in ⊤, p x) ↔ (∃ x, p x) := by simp [filter.frequently] @[simp] lemma frequently_principal {a : set α} {p : α → Prop} : (∃ᶠ x in 𝓟 a, p x) ↔ (∃ x ∈ a, p x) := by simp [filter.frequently, not_forall] lemma frequently_sup {p : α → Prop} {f g : filter α} : (∃ᶠ x in f ⊔ g, p x) ↔ (∃ᶠ x in f, p x) ∨ (∃ᶠ x in g, p x) := by simp only [filter.frequently, eventually_sup, not_and_distrib] @[simp] lemma frequently_Sup {p : α → Prop} {fs : set (filter α)} : (∃ᶠ x in Sup fs, p x) ↔ (∃ f ∈ fs, ∃ᶠ x in f, p x) := by simp [filter.frequently, -not_eventually, not_forall] @[simp] lemma frequently_supr {p : α → Prop} {fs : β → filter α} : (∃ᶠ x in (⨆ b, fs b), p x) ↔ (∃ b, ∃ᶠ x in fs b, p x) := by simp [filter.frequently, -not_eventually, not_forall] /-! ### Relation “eventually equal” -/ /-- Two functions `f` and `g` are *eventually equal* along a filter `l` if the set of `x` such that `f x = g x` belongs to `l`. -/ def eventually_eq (l : filter α) (f g : α → β) : Prop := ∀ᶠ x in l, f x = g x notation f ` =ᶠ[`:50 l:50 `] `:0 g:50 := eventually_eq l f g lemma eventually_eq.eventually {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) : ∀ᶠ x in l, f x = g x := h lemma eventually_eq.rw {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) (p : α → β → Prop) (hf : ∀ᶠ x in l, p x (f x)) : ∀ᶠ x in l, p x (g x) := hf.congr $ h.mono $ λ x hx, hx ▸ iff.rfl lemma eventually_eq_set {s t : set α} {l : filter α} : s =ᶠ[l] t ↔ ∀ᶠ x in l, x ∈ s ↔ x ∈ t := eventually_congr $ eventually_of_forall $ λ x, ⟨eq.to_iff, iff.to_eq⟩ alias eventually_eq_set ↔ filter.eventually_eq.mem_iff filter.eventually.set_eq lemma eventually_eq.exists_mem {l : filter α} {f g : α → β} (h : f =ᶠ[l] g) : ∃ s ∈ l, eq_on f g s := h.exists_mem lemma eventually_eq_of_mem {l : filter α} {f g : α → β} {s : set α} (hs : s ∈ l) (h : eq_on f g s) : f =ᶠ[l] g := eventually_of_mem hs h lemma eventually_eq_iff_exists_mem {l : filter α} {f g : α → β} : (f =ᶠ[l] g) ↔ ∃ s ∈ l, eq_on f g s := eventually_iff_exists_mem lemma eventually_eq.filter_mono {l l' : filter α} {f g : α → β} (h₁ : f =ᶠ[l] g) (h₂ : l' ≤ l) : f =ᶠ[l'] g := h₂ h₁ @[refl] lemma eventually_eq.refl (l : filter α) (f : α → β) : f =ᶠ[l] f := eventually_of_forall $ λ x, rfl lemma eventually_eq.rfl {l : filter α} {f : α → β} : f =ᶠ[l] f := eventually_eq.refl l f @[symm] lemma eventually_eq.symm {f g : α → β} {l : filter α} (H : f =ᶠ[l] g) : g =ᶠ[l] f := H.mono $ λ _, eq.symm @[trans] lemma eventually_eq.trans {f g h : α → β} {l : filter α} (H₁ : f =ᶠ[l] g) (H₂ : g =ᶠ[l] h) : f =ᶠ[l] h := H₂.rw (λ x y, f x = y) H₁ lemma eventually_eq.prod_mk {l} {f f' : α → β} (hf : f =ᶠ[l] f') {g g' : α → γ} (hg : g =ᶠ[l] g') : (λ x, (f x, g x)) =ᶠ[l] (λ x, (f' x, g' x)) := hf.mp $ hg.mono $ by { intros, simp only * } lemma eventually_eq.fun_comp {f g : α → β} {l : filter α} (H : f =ᶠ[l] g) (h : β → γ) : (h ∘ f) =ᶠ[l] (h ∘ g) := H.mono $ λ x hx, congr_arg h hx lemma eventually_eq.comp₂ {δ} {f f' : α → β} {g g' : α → γ} {l} (Hf : f =ᶠ[l] f') (h : β → γ → δ) (Hg : g =ᶠ[l] g') : (λ x, h (f x) (g x)) =ᶠ[l] (λ x, h (f' x) (g' x)) := (Hf.prod_mk Hg).fun_comp (function.uncurry h) @[to_additive] lemma eventually_eq.mul [has_mul β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x * f' x) =ᶠ[l] (λ x, g x * g' x)) := h.comp₂ (*) h' @[to_additive] lemma eventually_eq.inv [has_inv β] {f g : α → β} {l : filter α} (h : f =ᶠ[l] g) : ((λ x, (f x)⁻¹) =ᶠ[l] (λ x, (g x)⁻¹)) := h.fun_comp has_inv.inv lemma eventually_eq.div [group_with_zero β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x / f' x) =ᶠ[l] (λ x, g x / g' x)) := by simpa only [div_eq_mul_inv] using h.mul h'.inv lemma eventually_eq.div' [group β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x / f' x) =ᶠ[l] (λ x, g x / g' x)) := by simpa only [div_eq_mul_inv] using h.mul h'.inv lemma eventually_eq.sub [add_group β] {f f' g g' : α → β} {l : filter α} (h : f =ᶠ[l] g) (h' : f' =ᶠ[l] g') : ((λ x, f x - f' x) =ᶠ[l] (λ x, g x - g' x)) := by simpa only [sub_eq_add_neg] using h.add h'.neg lemma eventually_eq.inter {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s ∩ s' : set α) =ᶠ[l] (t ∩ t' : set α) := h.comp₂ (∧) h' lemma eventually_eq.union {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s ∪ s' : set α) =ᶠ[l] (t ∪ t' : set α) := h.comp₂ (∨) h' lemma eventually_eq.compl {s t : set α} {l : filter α} (h : s =ᶠ[l] t) : (sᶜ : set α) =ᶠ[l] (tᶜ : set α) := h.fun_comp not lemma eventually_eq.diff {s t s' t' : set α} {l : filter α} (h : s =ᶠ[l] t) (h' : s' =ᶠ[l] t') : (s \ s' : set α) =ᶠ[l] (t \ t' : set α) := h.inter h'.compl lemma eventually_eq_empty {s : set α} {l : filter α} : s =ᶠ[l] (∅ : set α) ↔ ∀ᶠ x in l, x ∉ s := eventually_eq_set.trans $ by simp lemma inter_eventually_eq_left {s t : set α} {l : filter α} : (s ∩ t : set α) =ᶠ[l] s ↔ ∀ᶠ x in l, x ∈ s → x ∈ t := by simp only [eventually_eq_set, mem_inter_eq, and_iff_left_iff_imp] lemma inter_eventually_eq_right {s t : set α} {l : filter α} : (s ∩ t : set α) =ᶠ[l] t ↔ ∀ᶠ x in l, x ∈ t → x ∈ s := by rw [inter_comm, inter_eventually_eq_left] @[simp] lemma eventually_eq_principal {s : set α} {f g : α → β} : f =ᶠ[𝓟 s] g ↔ eq_on f g s := iff.rfl lemma eventually_eq_inf_principal_iff {F : filter α} {s : set α} {f g : α → β} : (f =ᶠ[F ⊓ 𝓟 s] g) ↔ ∀ᶠ x in F, x ∈ s → f x = g x := eventually_inf_principal lemma eventually_eq.sub_eq [add_group β] {f g : α → β} {l : filter α} (h : f =ᶠ[l] g) : f - g =ᶠ[l] 0 := by simpa using (eventually_eq.sub (eventually_eq.refl l f) h).symm lemma eventually_eq_iff_sub [add_group β] {f g : α → β} {l : filter α} : f =ᶠ[l] g ↔ f - g =ᶠ[l] 0 := ⟨λ h, h.sub_eq, λ h, by simpa using h.add (eventually_eq.refl l g)⟩ section has_le variables [has_le β] {l : filter α} /-- A function `f` is eventually less than or equal to a function `g` at a filter `l`. -/ def eventually_le (l : filter α) (f g : α → β) : Prop := ∀ᶠ x in l, f x ≤ g x notation f ` ≤ᶠ[`:50 l:50 `] `:0 g:50 := eventually_le l f g lemma eventually_le.congr {f f' g g' : α → β} (H : f ≤ᶠ[l] g) (hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') : f' ≤ᶠ[l] g' := H.mp $ hg.mp $ hf.mono $ λ x hf hg H, by rwa [hf, hg] at H lemma eventually_le_congr {f f' g g' : α → β} (hf : f =ᶠ[l] f') (hg : g =ᶠ[l] g') : f ≤ᶠ[l] g ↔ f' ≤ᶠ[l] g' := ⟨λ H, H.congr hf hg, λ H, H.congr hf.symm hg.symm⟩ end has_le section preorder variables [preorder β] {l : filter α} {f g h : α → β} lemma eventually_eq.le (h : f =ᶠ[l] g) : f ≤ᶠ[l] g := h.mono $ λ x, le_of_eq @[refl] lemma eventually_le.refl (l : filter α) (f : α → β) : f ≤ᶠ[l] f := eventually_eq.rfl.le lemma eventually_le.rfl : f ≤ᶠ[l] f := eventually_le.refl l f @[trans] lemma eventually_le.trans (H₁ : f ≤ᶠ[l] g) (H₂ : g ≤ᶠ[l] h) : f ≤ᶠ[l] h := H₂.mp $ H₁.mono $ λ x, le_trans @[trans] lemma eventually_eq.trans_le (H₁ : f =ᶠ[l] g) (H₂ : g ≤ᶠ[l] h) : f ≤ᶠ[l] h := H₁.le.trans H₂ @[trans] lemma eventually_le.trans_eq (H₁ : f ≤ᶠ[l] g) (H₂ : g =ᶠ[l] h) : f ≤ᶠ[l] h := H₁.trans H₂.le end preorder lemma eventually_le.antisymm [partial_order β] {l : filter α} {f g : α → β} (h₁ : f ≤ᶠ[l] g) (h₂ : g ≤ᶠ[l] f) : f =ᶠ[l] g := h₂.mp $ h₁.mono $ λ x, le_antisymm lemma eventually_le_antisymm_iff [partial_order β] {l : filter α} {f g : α → β} : f =ᶠ[l] g ↔ f ≤ᶠ[l] g ∧ g ≤ᶠ[l] f := by simp only [eventually_eq, eventually_le, le_antisymm_iff, eventually_and] lemma eventually_le.le_iff_eq [partial_order β] {l : filter α} {f g : α → β} (h : f ≤ᶠ[l] g) : g ≤ᶠ[l] f ↔ g =ᶠ[l] f := ⟨λ h', h'.antisymm h, eventually_eq.le⟩ @[mono] lemma eventually_le.inter {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : s' ≤ᶠ[l] t') : (s ∩ s' : set α) ≤ᶠ[l] (t ∩ t' : set α) := h'.mp $ h.mono $ λ x, and.imp @[mono] lemma eventually_le.union {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : s' ≤ᶠ[l] t') : (s ∪ s' : set α) ≤ᶠ[l] (t ∪ t' : set α) := h'.mp $ h.mono $ λ x, or.imp @[mono] lemma eventually_le.compl {s t : set α} {l : filter α} (h : s ≤ᶠ[l] t) : (tᶜ : set α) ≤ᶠ[l] (sᶜ : set α) := h.mono $ λ x, mt @[mono] lemma eventually_le.diff {s t s' t' : set α} {l : filter α} (h : s ≤ᶠ[l] t) (h' : t' ≤ᶠ[l] s') : (s \ s' : set α) ≤ᶠ[l] (t \ t' : set α) := h.inter h'.compl lemma join_le {f : filter (filter α)} {l : filter α} (h : ∀ᶠ m in f, m ≤ l) : join f ≤ l := λ s hs, h.mono $ λ m hm, hm hs /-! ### Push-forwards, pull-backs, and the monad structure -/ section map /-- The forward map of a filter -/ def map (m : α → β) (f : filter α) : filter β := { sets := preimage m ⁻¹' f.sets, univ_sets := univ_mem_sets, sets_of_superset := assume s t hs st, mem_sets_of_superset hs $ preimage_mono st, inter_sets := assume s t hs ht, inter_mem_sets hs ht } @[simp] lemma map_principal {s : set α} {f : α → β} : map f (𝓟 s) = 𝓟 (set.image f s) := filter_eq $ set.ext $ assume a, image_subset_iff.symm variables {f : filter α} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] lemma eventually_map {P : β → Prop} : (∀ᶠ b in map m f, P b) ↔ ∀ᶠ a in f, P (m a) := iff.rfl @[simp] lemma frequently_map {P : β → Prop} : (∃ᶠ b in map m f, P b) ↔ ∃ᶠ a in f, P (m a) := iff.rfl @[simp] lemma mem_map : t ∈ map m f ↔ {x | m x ∈ t} ∈ f := iff.rfl lemma image_mem_map (hs : s ∈ f) : m '' s ∈ map m f := f.sets_of_superset hs $ subset_preimage_image m s lemma image_mem_map_iff (hf : function.injective m) : m '' s ∈ map m f ↔ s ∈ f := ⟨λ h, by rwa [← preimage_image_eq s hf], image_mem_map⟩ lemma range_mem_map : range m ∈ map m f := by rw ←image_univ; exact image_mem_map univ_mem_sets lemma mem_map_sets_iff : t ∈ map m f ↔ (∃s∈f, m '' s ⊆ t) := iff.intro (assume ht, ⟨m ⁻¹' t, ht, image_preimage_subset _ _⟩) (assume ⟨s, hs, ht⟩, mem_sets_of_superset (image_mem_map hs) ht) @[simp] lemma map_id : filter.map id f = f := filter_eq $ rfl @[simp] lemma map_id' : filter.map (λ x, x) f = f := map_id @[simp] lemma map_compose : filter.map m' ∘ filter.map m = filter.map (m' ∘ m) := funext $ assume _, filter_eq $ rfl @[simp] lemma map_map : filter.map m' (filter.map m f) = filter.map (m' ∘ m) f := congr_fun (@@filter.map_compose m m') f /-- If functions `m₁` and `m₂` are eventually equal at a filter `f`, then they map this filter to the same filter. -/ lemma map_congr {m₁ m₂ : α → β} {f : filter α} (h : m₁ =ᶠ[f] m₂) : map m₁ f = map m₂ f := filter.ext' $ λ p, by { simp only [eventually_map], exact eventually_congr (h.mono $ λ x hx, hx ▸ iff.rfl) } end map section comap /-- The inverse map of a filter -/ def comap (m : α → β) (f : filter β) : filter α := { sets := { s | ∃t∈ f, m ⁻¹' t ⊆ s }, univ_sets := ⟨univ, univ_mem_sets, by simp only [subset_univ, preimage_univ]⟩, sets_of_superset := assume a b ⟨a', ha', ma'a⟩ ab, ⟨a', ha', subset.trans ma'a ab⟩, inter_sets := assume a b ⟨a', ha₁, ha₂⟩ ⟨b', hb₁, hb₂⟩, ⟨a' ∩ b', inter_mem_sets ha₁ hb₁, inter_subset_inter ha₂ hb₂⟩ } lemma eventually_comap' {f : filter β} {φ : α → β} {p : β → Prop} (hf : ∀ᶠ b in f, p b) : ∀ᶠ a in comap φ f, p (φ a) := ⟨_, hf, (λ a h, h)⟩ @[simp] lemma eventually_comap {f : filter β} {φ : α → β} {P : α → Prop} : (∀ᶠ a in comap φ f, P a) ↔ ∀ᶠ b in f, ∀ a, φ a = b → P a := begin split ; intro h, { rcases h with ⟨t, t_in, ht⟩, apply mem_sets_of_superset t_in, rintros y y_in _ rfl, apply ht y_in }, { exact ⟨_, h, λ _ x_in, x_in _ rfl⟩ } end @[simp] lemma frequently_comap {f : filter β} {φ : α → β} {P : α → Prop} : (∃ᶠ a in comap φ f, P a) ↔ ∃ᶠ b in f, ∃ a, φ a = b ∧ P a := begin classical, erw [← not_iff_not, not_not, not_not, filter.eventually_comap], simp only [not_exists, not_and], end end comap /-- The monadic bind operation on filter is defined the usual way in terms of `map` and `join`. Unfortunately, this `bind` does not result in the expected applicative. See `filter.seq` for the applicative instance. -/ def bind (f : filter α) (m : α → filter β) : filter β := join (map m f) /-- The applicative sequentiation operation. This is not induced by the bind operation. -/ def seq (f : filter (α → β)) (g : filter α) : filter β := ⟨{ s | ∃u∈ f, ∃t∈ g, (∀m∈u, ∀x∈t, (m : α → β) x ∈ s) }, ⟨univ, univ_mem_sets, univ, univ_mem_sets, by simp only [forall_prop_of_true, mem_univ, forall_true_iff]⟩, assume s₀ s₁ ⟨t₀, t₁, h₀, h₁, h⟩ hst, ⟨t₀, t₁, h₀, h₁, assume x hx y hy, hst $ h _ hx _ hy⟩, assume s₀ s₁ ⟨t₀, ht₀, t₁, ht₁, ht⟩ ⟨u₀, hu₀, u₁, hu₁, hu⟩, ⟨t₀ ∩ u₀, inter_mem_sets ht₀ hu₀, t₁ ∩ u₁, inter_mem_sets ht₁ hu₁, assume x ⟨hx₀, hx₁⟩ x ⟨hy₀, hy₁⟩, ⟨ht _ hx₀ _ hy₀, hu _ hx₁ _ hy₁⟩⟩⟩ /-- `pure x` is the set of sets that contain `x`. It is equal to `𝓟 {x}` but with this definition we have `s ∈ pure a` defeq `a ∈ s`. -/ instance : has_pure filter := ⟨λ (α : Type u) x, { sets := {s | x ∈ s}, inter_sets := λ s t, and.intro, sets_of_superset := λ s t hs hst, hst hs, univ_sets := trivial }⟩ instance : has_bind filter := ⟨@filter.bind⟩ instance : has_seq filter := ⟨@filter.seq⟩ instance : functor filter := { map := @filter.map } lemma pure_sets (a : α) : (pure a : filter α).sets = {s | a ∈ s} := rfl @[simp] lemma mem_pure_sets {a : α} {s : set α} : s ∈ (pure a : filter α) ↔ a ∈ s := iff.rfl @[simp] lemma eventually_pure {a : α} {p : α → Prop} : (∀ᶠ x in pure a, p x) ↔ p a := iff.rfl @[simp] lemma principal_singleton (a : α) : 𝓟 {a} = pure a := filter.ext $ λ s, by simp only [mem_pure_sets, mem_principal_sets, singleton_subset_iff] @[simp] lemma map_pure (f : α → β) (a : α) : map f (pure a) = pure (f a) := rfl @[simp] lemma join_pure (f : filter α) : join (pure f) = f := filter.ext $ λ s, iff.rfl @[simp] lemma pure_bind (a : α) (m : α → filter β) : bind (pure a) m = m a := by simp only [has_bind.bind, bind, map_pure, join_pure] section -- this section needs to be before applicative, otherwise the wrong instance will be chosen /-- The monad structure on filters. -/ protected def monad : monad filter := { map := @filter.map } local attribute [instance] filter.monad protected lemma is_lawful_monad : is_lawful_monad filter := { id_map := assume α f, filter_eq rfl, pure_bind := assume α β, pure_bind, bind_assoc := assume α β γ f m₁ m₂, filter_eq rfl, bind_pure_comp_eq_map := assume α β f x, filter.ext $ λ s, by simp only [has_bind.bind, bind, functor.map, mem_map, mem_join_sets, mem_set_of_eq, function.comp, mem_pure_sets] } end instance : applicative filter := { map := @filter.map, seq := @filter.seq } instance : alternative filter := { failure := λα, ⊥, orelse := λα x y, x ⊔ y } @[simp] lemma map_def {α β} (m : α → β) (f : filter α) : m <$> f = map m f := rfl @[simp] lemma bind_def {α β} (f : filter α) (m : α → filter β) : f >>= m = bind f m := rfl /- map and comap equations -/ section map variables {f f₁ f₂ : filter α} {g g₁ g₂ : filter β} {m : α → β} {m' : β → γ} {s : set α} {t : set β} @[simp] theorem mem_comap_sets : s ∈ comap m g ↔ ∃t∈ g, m ⁻¹' t ⊆ s := iff.rfl theorem preimage_mem_comap (ht : t ∈ g) : m ⁻¹' t ∈ comap m g := ⟨t, ht, subset.refl _⟩ lemma comap_id : comap id f = f := le_antisymm (assume s, preimage_mem_comap) (assume s ⟨t, ht, hst⟩, mem_sets_of_superset ht hst) lemma comap_const_of_not_mem {x : α} {f : filter α} {V : set α} (hV : V ∈ f) (hx : x ∉ V) : comap (λ y : α, x) f = ⊥ := begin ext W, suffices : ∃ t ∈ f, (λ (y : α), x) ⁻¹' t ⊆ W, by simpa, use [V, hV], simp [preimage_const_of_not_mem hx], end lemma comap_const_of_mem {x : α} {f : filter α} (h : ∀ V ∈ f, x ∈ V) : comap (λ y : α, x) f = ⊤ := begin ext W, suffices : (∃ (t : set α), t ∈ f.sets ∧ (λ (y : α), x) ⁻¹' t ⊆ W) ↔ W = univ, by simpa, split, { rintros ⟨V, V_in, hW⟩, simpa [preimage_const_of_mem (h V V_in), univ_subset_iff] using hW }, { rintro rfl, use univ, simp [univ_mem_sets] }, end lemma comap_comap {m : γ → β} {n : β → α} : comap m (comap n f) = comap (n ∘ m) f := le_antisymm (assume c ⟨b, hb, (h : preimage (n ∘ m) b ⊆ c)⟩, ⟨preimage n b, preimage_mem_comap hb, h⟩) (assume c ⟨b, ⟨a, ha, (h₁ : preimage n a ⊆ b)⟩, (h₂ : preimage m b ⊆ c)⟩, ⟨a, ha, show preimage m (preimage n a) ⊆ c, from subset.trans (preimage_mono h₁) h₂⟩) section comm variables {δ : Type*} /-! The variables in the following lemmas are used as in this diagram: ``` φ α → β θ ↓ ↓ ψ γ → δ ρ ``` -/ variables {φ : α → β} {θ : α → γ} {ψ : β → δ} {ρ : γ → δ} (H : ψ ∘ φ = ρ ∘ θ) include H lemma map_comm (F : filter α) : map ψ (map φ F) = map ρ (map θ F) := by rw [filter.map_map, H, ← filter.map_map] lemma comap_comm (G : filter δ) : comap φ (comap ψ G) = comap θ (comap ρ G) := by rw [filter.comap_comap, H, ← filter.comap_comap] end comm @[simp] theorem comap_principal {t : set β} : comap m (𝓟 t) = 𝓟 (m ⁻¹' t) := filter_eq $ set.ext $ assume s, ⟨assume ⟨u, (hu : t ⊆ u), (b : preimage m u ⊆ s)⟩, subset.trans (preimage_mono hu) b, assume : preimage m t ⊆ s, ⟨t, subset.refl t, this⟩⟩ @[simp] theorem comap_pure {b : β} : comap m (pure b) = 𝓟 (m ⁻¹' {b}) := by rw [← principal_singleton, comap_principal] lemma map_le_iff_le_comap : map m f ≤ g ↔ f ≤ comap m g := ⟨assume h s ⟨t, ht, hts⟩, mem_sets_of_superset (h ht) hts, assume h s ht, h ⟨_, ht, subset.refl _⟩⟩ lemma gc_map_comap (m : α → β) : galois_connection (map m) (comap m) := assume f g, map_le_iff_le_comap @[mono] lemma map_mono : monotone (map m) := (gc_map_comap m).monotone_l @[mono] lemma comap_mono : monotone (comap m) := (gc_map_comap m).monotone_u @[simp] lemma map_bot : map m ⊥ = ⊥ := (gc_map_comap m).l_bot @[simp] lemma map_sup : map m (f₁ ⊔ f₂) = map m f₁ ⊔ map m f₂ := (gc_map_comap m).l_sup @[simp] lemma map_supr {f : ι → filter α} : map m (⨆i, f i) = (⨆i, map m (f i)) := (gc_map_comap m).l_supr @[simp] lemma comap_top : comap m ⊤ = ⊤ := (gc_map_comap m).u_top @[simp] lemma comap_inf : comap m (g₁ ⊓ g₂) = comap m g₁ ⊓ comap m g₂ := (gc_map_comap m).u_inf @[simp] lemma comap_infi {f : ι → filter β} : comap m (⨅i, f i) = (⨅i, comap m (f i)) := (gc_map_comap m).u_infi lemma le_comap_top (f : α → β) (l : filter α) : l ≤ comap f ⊤ := by rw [comap_top]; exact le_top lemma map_comap_le : map m (comap m g) ≤ g := (gc_map_comap m).l_u_le _ lemma le_comap_map : f ≤ comap m (map m f) := (gc_map_comap m).le_u_l _ @[simp] lemma comap_bot : comap m ⊥ = ⊥ := bot_unique $ λ s _, ⟨∅, by simp only [mem_bot_sets], by simp only [empty_subset, preimage_empty]⟩ lemma comap_supr {ι} {f : ι → filter β} {m : α → β} : comap m (supr f) = (⨆i, comap m (f i)) := le_antisymm (assume s hs, have ∀i, ∃t, t ∈ f i ∧ m ⁻¹' t ⊆ s, by simpa only [mem_comap_sets, exists_prop, mem_supr_sets] using mem_supr_sets.1 hs, let ⟨t, ht⟩ := classical.axiom_of_choice this in ⟨⋃i, t i, mem_supr_sets.2 $ assume i, (f i).sets_of_superset (ht i).1 (subset_Union _ _), begin rw [preimage_Union, Union_subset_iff], assume i, exact (ht i).2 end⟩) (supr_le $ assume i, comap_mono $ le_supr _ _) lemma comap_Sup {s : set (filter β)} {m : α → β} : comap m (Sup s) = (⨆f∈s, comap m f) := by simp only [Sup_eq_supr, comap_supr, eq_self_iff_true] lemma comap_sup : comap m (g₁ ⊔ g₂) = comap m g₁ ⊔ comap m g₂ := le_antisymm (assume s ⟨⟨t₁, ht₁, hs₁⟩, ⟨t₂, ht₂, hs₂⟩⟩, ⟨t₁ ∪ t₂, ⟨mem_sets_of_superset ht₁ (subset_union_left _ _), mem_sets_of_superset ht₂ (subset_union_right _ _)⟩, union_subset hs₁ hs₂⟩) ((@comap_mono _ _ m).le_map_sup _ _) lemma map_comap (f : filter β) (m : α → β) : (f.comap m).map m = f ⊓ 𝓟 (range m) := begin refine le_antisymm (le_inf map_comap_le $ le_principal_iff.2 range_mem_map) _, rintro t' ⟨t, ht, sub⟩, refine mem_inf_principal.2 (mem_sets_of_superset ht _), rintro _ hxt ⟨x, rfl⟩, exact sub hxt end lemma map_comap_of_mem {f : filter β} {m : α → β} (hf : range m ∈ f) : (f.comap m).map m = f := by rw [map_comap, inf_eq_left.2 (le_principal_iff.2 hf)] lemma comap_le_comap_iff {f g : filter β} {m : α → β} (hf : range m ∈ f) : comap m f ≤ comap m g ↔ f ≤ g := ⟨λ h, map_comap_of_mem hf ▸ (map_mono h).trans map_comap_le, λ h, comap_mono h⟩ theorem map_comap_of_surjective {f : α → β} (hf : function.surjective f) (l : filter β) : map f (comap f l) = l := map_comap_of_mem $ by simp only [hf.range_eq, univ_mem_sets] lemma subtype_coe_map_comap (s : set α) (f : filter α) : map (coe : s → α) (comap (coe : s → α) f) = f ⊓ 𝓟 s := by rw [map_comap, subtype.range_coe] lemma subtype_coe_map_comap_prod (s : set α) (f : filter (α × α)) : map (coe : s × s → α × α) (comap (coe : s × s → α × α) f) = f ⊓ 𝓟 (s.prod s) := have (coe : s × s → α × α) = (λ x, (x.1, x.2)), by ext ⟨x, y⟩; refl, by simp [this, map_comap, ← prod_range_range_eq] lemma image_mem_sets {f : filter α} {c : β → α} (h : range c ∈ f) {W : set β} (W_in : W ∈ comap c f) : c '' W ∈ f := begin rw ← map_comap_of_mem h, exact image_mem_map W_in end lemma image_coe_mem_sets {f : filter α} {U : set α} (h : U ∈ f) {W : set U} (W_in : W ∈ comap (coe : U → α) f) : coe '' W ∈ f := image_mem_sets (by simp [h]) W_in lemma comap_map {f : filter α} {m : α → β} (h : function.injective m) : comap m (map m f) = f := le_antisymm (assume s hs, mem_sets_of_superset (preimage_mem_comap $ image_mem_map hs) $ by simp only [preimage_image_eq s h]) le_comap_map lemma mem_comap_iff {f : filter β} {m : α → β} (inj : function.injective m) (large : set.range m ∈ f) {S : set α} : S ∈ comap m f ↔ m '' S ∈ f := by rw [← image_mem_map_iff inj, map_comap_of_mem large] lemma le_of_map_le_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) (h : map m f ≤ map m g) : f ≤ g := assume t ht, by filter_upwards [hsf, h $ image_mem_map (inter_mem_sets hsg ht)] assume a has ⟨b, ⟨hbs, hb⟩, h⟩, have b = a, from hm _ hbs _ has h, this ▸ hb lemma le_of_map_le_map_inj_iff {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) : map m f ≤ map m g ↔ f ≤ g := iff.intro (le_of_map_le_map_inj' hsf hsg hm) (λ h, map_mono h) lemma eq_of_map_eq_map_inj' {f g : filter α} {m : α → β} {s : set α} (hsf : s ∈ f) (hsg : s ∈ g) (hm : ∀x∈s, ∀y∈s, m x = m y → x = y) (h : map m f = map m g) : f = g := le_antisymm (le_of_map_le_map_inj' hsf hsg hm $ le_of_eq h) (le_of_map_le_map_inj' hsg hsf hm $ le_of_eq h.symm) lemma map_inj {f g : filter α} {m : α → β} (hm : function.injective m) (h : map m f = map m g) : f = g := have comap m (map m f) = comap m (map m g), by rw h, by rwa [comap_map hm, comap_map hm] at this lemma comap_ne_bot_iff {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ ∀ t ∈ f, ∃ a, m a ∈ t := begin rw ← forall_sets_nonempty_iff_ne_bot, exact ⟨λ h t t_in, h (m ⁻¹' t) ⟨t, t_in, subset.refl _⟩, λ h s ⟨u, u_in, hu⟩, let ⟨x, hx⟩ := h u u_in in ⟨x, hu hx⟩⟩, end lemma comap_ne_bot {f : filter β} {m : α → β} (hm : ∀t∈ f, ∃a, m a ∈ t) : ne_bot (comap m f) := comap_ne_bot_iff.mpr hm lemma comap_ne_bot_iff_frequently {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ ∃ᶠ y in f, y ∈ range m := by simp [comap_ne_bot_iff, frequently_iff, ← exists_and_distrib_left, and.comm] lemma comap_ne_bot_iff_compl_range {f : filter β} {m : α → β} : ne_bot (comap m f) ↔ (range m)ᶜ ∉ f := comap_ne_bot_iff_frequently lemma ne_bot.comap_of_range_mem {f : filter β} {m : α → β} (hf : ne_bot f) (hm : range m ∈ f) : ne_bot (comap m f) := comap_ne_bot_iff_frequently.2 $ eventually.frequently hm lemma comap_inf_principal_ne_bot_of_image_mem {f : filter β} {m : α → β} (hf : ne_bot f) {s : set α} (hs : m '' s ∈ f) : ne_bot (comap m f ⊓ 𝓟 s) := begin refine ⟨compl_compl s ▸ mt mem_sets_of_eq_bot _⟩, rintros ⟨t, ht, hts⟩, rcases hf.nonempty_of_mem (inter_mem_sets hs ht) with ⟨_, ⟨x, hxs, rfl⟩, hxt⟩, exact absurd hxs (hts hxt) end lemma comap_coe_ne_bot_of_le_principal {s : set γ} {l : filter γ} [h : ne_bot l] (h' : l ≤ 𝓟 s) : ne_bot (comap (coe : s → γ) l) := h.comap_of_range_mem $ (@subtype.range_coe γ s).symm ▸ h' (mem_principal_self s) lemma ne_bot.comap_of_surj {f : filter β} {m : α → β} (hf : ne_bot f) (hm : function.surjective m) : ne_bot (comap m f) := hf.comap_of_range_mem $ univ_mem_sets' hm lemma ne_bot.comap_of_image_mem {f : filter β} {m : α → β} (hf : ne_bot f) {s : set α} (hs : m '' s ∈ f) : ne_bot (comap m f) := hf.comap_of_range_mem $ mem_sets_of_superset hs (image_subset_range _ _) @[simp] lemma map_eq_bot_iff : map m f = ⊥ ↔ f = ⊥ := ⟨by rw [←empty_in_sets_eq_bot, ←empty_in_sets_eq_bot]; exact id, assume h, by simp only [h, eq_self_iff_true, map_bot]⟩ lemma map_ne_bot_iff (f : α → β) {F : filter α} : ne_bot (map f F) ↔ ne_bot F := by simp only [ne_bot_iff, ne, map_eq_bot_iff] lemma ne_bot.map (hf : ne_bot f) (m : α → β) : ne_bot (map m f) := (map_ne_bot_iff m).2 hf instance map_ne_bot [hf : ne_bot f] : ne_bot (f.map m) := hf.map m lemma sInter_comap_sets (f : α → β) (F : filter β) : ⋂₀ (comap f F).sets = ⋂ U ∈ F, f ⁻¹' U := begin ext x, suffices : (∀ (A : set α) (B : set β), B ∈ F → f ⁻¹' B ⊆ A → x ∈ A) ↔ ∀ (B : set β), B ∈ F → f x ∈ B, by simp only [mem_sInter, mem_Inter, filter.mem_sets, mem_comap_sets, this, and_imp, mem_comap_sets, exists_prop, mem_sInter, mem_Inter, mem_preimage, exists_imp_distrib], split, { intros h U U_in, simpa only [set.subset.refl, forall_prop_of_true, mem_preimage] using h (f ⁻¹' U) U U_in }, { intros h V U U_in f_U_V, exact f_U_V (h U U_in) }, end end map -- this is a generic rule for monotone functions: lemma map_infi_le {f : ι → filter α} {m : α → β} : map m (infi f) ≤ (⨅ i, map m (f i)) := le_infi $ assume i, map_mono $ infi_le _ _ lemma map_infi_eq {f : ι → filter α} {m : α → β} (hf : directed (≥) f) [nonempty ι] : map m (infi f) = (⨅ i, map m (f i)) := le_antisymm map_infi_le (assume s (hs : preimage m s ∈ infi f), have ∃i, preimage m s ∈ f i, by simp only [mem_infi hf, mem_Union] at hs; assumption, let ⟨i, hi⟩ := this in have (⨅ i, map m (f i)) ≤ 𝓟 s, from infi_le_of_le i $ by simp only [le_principal_iff, mem_map]; assumption, by simp only [filter.le_principal_iff] at this; assumption) lemma map_binfi_eq {ι : Type w} {f : ι → filter α} {m : α → β} {p : ι → Prop} (h : directed_on (f ⁻¹'o (≥)) {x | p x}) (ne : ∃i, p i) : map m (⨅i (h : p i), f i) = (⨅i (h: p i), map m (f i)) := begin haveI := nonempty_subtype.2 ne, simp only [infi_subtype'], exact map_infi_eq h.directed_coe end lemma map_inf_le {f g : filter α} {m : α → β} : map m (f ⊓ g) ≤ map m f ⊓ map m g := (@map_mono _ _ m).map_inf_le f g lemma map_inf' {f g : filter α} {m : α → β} {t : set α} (htf : t ∈ f) (htg : t ∈ g) (h : ∀x∈t, ∀y∈t, m x = m y → x = y) : map m (f ⊓ g) = map m f ⊓ map m g := begin refine le_antisymm map_inf_le (assume s hs, _), simp only [mem_inf_sets, exists_prop, mem_map, mem_preimage, mem_inf_sets] at hs ⊢, rcases hs with ⟨t₁, h₁, t₂, h₂, hs⟩, refine ⟨m '' (t₁ ∩ t), _, m '' (t₂ ∩ t), _, _⟩, { filter_upwards [h₁, htf] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ }, { filter_upwards [h₂, htg] assume a h₁ h₂, mem_image_of_mem _ ⟨h₁, h₂⟩ }, { rw [image_inter_on], { refine image_subset_iff.2 _, exact λ x ⟨⟨h₁, _⟩, h₂, _⟩, hs ⟨h₁, h₂⟩ }, { exact λ x ⟨_, hx⟩ y ⟨_, hy⟩, h x hx y hy } } end lemma map_inf {f g : filter α} {m : α → β} (h : function.injective m) : map m (f ⊓ g) = map m f ⊓ map m g := map_inf' univ_mem_sets univ_mem_sets (assume x _ y _ hxy, h hxy) lemma map_eq_comap_of_inverse {f : filter α} {m : α → β} {n : β → α} (h₁ : m ∘ n = id) (h₂ : n ∘ m = id) : map m f = comap n f := le_antisymm (assume b ⟨a, ha, (h : preimage n a ⊆ b)⟩, f.sets_of_superset ha $ calc a = preimage (n ∘ m) a : by simp only [h₂, preimage_id, eq_self_iff_true] ... ⊆ preimage m b : preimage_mono h) (assume b (hb : preimage m b ∈ f), ⟨preimage m b, hb, show preimage (m ∘ n) b ⊆ b, by simp only [h₁]; apply subset.refl⟩) lemma map_swap_eq_comap_swap {f : filter (α × β)} : prod.swap <$> f = comap prod.swap f := map_eq_comap_of_inverse prod.swap_swap_eq prod.swap_swap_eq lemma le_map {f : filter α} {m : α → β} {g : filter β} (h : ∀ s ∈ f, m '' s ∈ g) : g ≤ f.map m := assume s hs, mem_sets_of_superset (h _ hs) $ image_preimage_subset _ _ protected lemma push_pull (f : α → β) (F : filter α) (G : filter β) : map f (F ⊓ comap f G) = map f F ⊓ G := begin apply le_antisymm, { calc map f (F ⊓ comap f G) ≤ map f F ⊓ (map f $ comap f G) : map_inf_le ... ≤ map f F ⊓ G : inf_le_inf_left (map f F) map_comap_le }, { rintros U ⟨V, V_in, W, ⟨Z, Z_in, hZ⟩, h⟩, rw ← image_subset_iff at h, use [f '' V, image_mem_map V_in, Z, Z_in], refine subset.trans _ h, have : f '' (V ∩ f ⁻¹' Z) ⊆ f '' (V ∩ W), from image_subset _ (inter_subset_inter_right _ ‹_›), rwa image_inter_preimage at this } end protected lemma push_pull' (f : α → β) (F : filter α) (G : filter β) : map f (comap f G ⊓ F) = G ⊓ map f F := by simp only [filter.push_pull, inf_comm] section applicative lemma singleton_mem_pure_sets {a : α} : {a} ∈ (pure a : filter α) := mem_singleton a lemma pure_injective : function.injective (pure : α → filter α) := assume a b hab, (filter.ext_iff.1 hab {x | a = x}).1 rfl instance pure_ne_bot {α : Type u} {a : α} : ne_bot (pure a) := ⟨mt empty_in_sets_eq_bot.2 $ not_mem_empty a⟩ @[simp] lemma le_pure_iff {f : filter α} {a : α} : f ≤ pure a ↔ {a} ∈ f := ⟨λ h, h singleton_mem_pure_sets, λ h s hs, mem_sets_of_superset h $ singleton_subset_iff.2 hs⟩ lemma mem_seq_sets_def {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, ∀x∈u, ∀y∈t, (x : α → β) y ∈ s) := iff.rfl lemma mem_seq_sets_iff {f : filter (α → β)} {g : filter α} {s : set β} : s ∈ f.seq g ↔ (∃u ∈ f, ∃t ∈ g, set.seq u t ⊆ s) := by simp only [mem_seq_sets_def, seq_subset, exists_prop, iff_self] lemma mem_map_seq_iff {f : filter α} {g : filter β} {m : α → β → γ} {s : set γ} : s ∈ (f.map m).seq g ↔ (∃t u, t ∈ g ∧ u ∈ f ∧ ∀x∈u, ∀y∈t, m x y ∈ s) := iff.intro (λ ⟨t, ht, s, hs, hts⟩, ⟨s, m ⁻¹' t, hs, ht, λ a, hts _⟩) (λ ⟨t, s, ht, hs, hts⟩, ⟨m '' s, image_mem_map hs, t, ht, λ f ⟨a, has, eq⟩, eq ▸ hts _ has⟩) lemma seq_mem_seq_sets {f : filter (α → β)} {g : filter α} {s : set (α → β)} {t : set α} (hs : s ∈ f) (ht : t ∈ g) : s.seq t ∈ f.seq g := ⟨s, hs, t, ht, assume f hf a ha, ⟨f, hf, a, ha, rfl⟩⟩ lemma le_seq {f : filter (α → β)} {g : filter α} {h : filter β} (hh : ∀t ∈ f, ∀u ∈ g, set.seq t u ∈ h) : h ≤ seq f g := assume s ⟨t, ht, u, hu, hs⟩, mem_sets_of_superset (hh _ ht _ hu) $ assume b ⟨m, hm, a, ha, eq⟩, eq ▸ hs _ hm _ ha @[mono] lemma seq_mono {f₁ f₂ : filter (α → β)} {g₁ g₂ : filter α} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.seq g₁ ≤ f₂.seq g₂ := le_seq $ assume s hs t ht, seq_mem_seq_sets (hf hs) (hg ht) @[simp] lemma pure_seq_eq_map (g : α → β) (f : filter α) : seq (pure g) f = f.map g := begin refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _), { rw ← singleton_seq, apply seq_mem_seq_sets _ hs, exact singleton_mem_pure_sets }, { refine sets_of_superset (map g f) (image_mem_map ht) _, rintros b ⟨a, ha, rfl⟩, exact ⟨g, hs, a, ha, rfl⟩ } end @[simp] lemma seq_pure (f : filter (α → β)) (a : α) : seq f (pure a) = map (λg:α → β, g a) f := begin refine le_antisymm (le_map $ assume s hs, _) (le_seq $ assume s hs t ht, _), { rw ← seq_singleton, exact seq_mem_seq_sets hs singleton_mem_pure_sets }, { refine sets_of_superset (map (λg:α→β, g a) f) (image_mem_map hs) _, rintros b ⟨g, hg, rfl⟩, exact ⟨g, hg, a, ht, rfl⟩ } end @[simp] lemma seq_assoc (x : filter α) (g : filter (α → β)) (h : filter (β → γ)) : seq h (seq g x) = seq (seq (map (∘) h) g) x := begin refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _), { rcases mem_seq_sets_iff.1 hs with ⟨u, hu, v, hv, hs⟩, rcases mem_map_sets_iff.1 hu with ⟨w, hw, hu⟩, refine mem_sets_of_superset _ (set.seq_mono (subset.trans (set.seq_mono hu (subset.refl _)) hs) (subset.refl _)), rw ← set.seq_seq, exact seq_mem_seq_sets hw (seq_mem_seq_sets hv ht) }, { rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩, refine mem_sets_of_superset _ (set.seq_mono (subset.refl _) ht), rw set.seq_seq, exact seq_mem_seq_sets (seq_mem_seq_sets (image_mem_map hs) hu) hv } end lemma prod_map_seq_comm (f : filter α) (g : filter β) : (map prod.mk f).seq g = seq (map (λb a, (a, b)) g) f := begin refine le_antisymm (le_seq $ assume s hs t ht, _) (le_seq $ assume s hs t ht, _), { rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩, refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)), rw ← set.prod_image_seq_comm, exact seq_mem_seq_sets (image_mem_map ht) hu }, { rcases mem_map_sets_iff.1 hs with ⟨u, hu, hs⟩, refine mem_sets_of_superset _ (set.seq_mono hs (subset.refl _)), rw set.prod_image_seq_comm, exact seq_mem_seq_sets (image_mem_map ht) hu } end instance : is_lawful_functor (filter : Type u → Type u) := { id_map := assume α f, map_id, comp_map := assume α β γ f g a, map_map.symm } instance : is_lawful_applicative (filter : Type u → Type u) := { pure_seq_eq_map := assume α β, pure_seq_eq_map, map_pure := assume α β, map_pure, seq_pure := assume α β, seq_pure, seq_assoc := assume α β γ, seq_assoc } instance : is_comm_applicative (filter : Type u → Type u) := ⟨assume α β f g, prod_map_seq_comm f g⟩ lemma {l} seq_eq_filter_seq {α β : Type l} (f : filter (α → β)) (g : filter α) : f <*> g = seq f g := rfl end applicative /- bind equations -/ section bind @[simp] lemma eventually_bind {f : filter α} {m : α → filter β} {p : β → Prop} : (∀ᶠ y in bind f m, p y) ↔ ∀ᶠ x in f, ∀ᶠ y in m x, p y := iff.rfl @[simp] lemma eventually_eq_bind {f : filter α} {m : α → filter β} {g₁ g₂ : β → γ} : (g₁ =ᶠ[bind f m] g₂) ↔ ∀ᶠ x in f, g₁ =ᶠ[m x] g₂ := iff.rfl @[simp] lemma eventually_le_bind [has_le γ] {f : filter α} {m : α → filter β} {g₁ g₂ : β → γ} : (g₁ ≤ᶠ[bind f m] g₂) ↔ ∀ᶠ x in f, g₁ ≤ᶠ[m x] g₂ := iff.rfl lemma mem_bind_sets' {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ {a | s ∈ m a} ∈ f := iff.rfl @[simp] lemma mem_bind_sets {s : set β} {f : filter α} {m : α → filter β} : s ∈ bind f m ↔ ∃t ∈ f, ∀x ∈ t, s ∈ m x := calc s ∈ bind f m ↔ {a | s ∈ m a} ∈ f : iff.rfl ... ↔ (∃t ∈ f, t ⊆ {a | s ∈ m a}) : exists_sets_subset_iff.symm ... ↔ (∃t ∈ f, ∀x ∈ t, s ∈ m x) : iff.rfl lemma bind_le {f : filter α} {g : α → filter β} {l : filter β} (h : ∀ᶠ x in f, g x ≤ l) : f.bind g ≤ l := join_le $ eventually_map.2 h @[mono] lemma bind_mono {f₁ f₂ : filter α} {g₁ g₂ : α → filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ᶠ[f₁] g₂) : bind f₁ g₁ ≤ bind f₂ g₂ := begin refine le_trans (λ s hs, _) (join_mono $ map_mono hf), simp only [mem_join_sets, mem_bind_sets', mem_map] at hs ⊢, filter_upwards [hg, hs], exact λ x hx hs, hx hs end lemma bind_inf_principal {f : filter α} {g : α → filter β} {s : set β} : f.bind (λ x, g x ⊓ 𝓟 s) = (f.bind g) ⊓ 𝓟 s := filter.ext $ λ s, by simp only [mem_bind_sets, mem_inf_principal] lemma sup_bind {f g : filter α} {h : α → filter β} : bind (f ⊔ g) h = bind f h ⊔ bind g h := by simp only [bind, sup_join, map_sup, eq_self_iff_true] lemma principal_bind {s : set α} {f : α → filter β} : (bind (𝓟 s) f) = (⨆x ∈ s, f x) := show join (map f (𝓟 s)) = (⨆x ∈ s, f x), by simp only [Sup_image, join_principal_eq_Sup, map_principal, eq_self_iff_true] end bind section list_traverse /- This is a separate section in order to open `list`, but mostly because of universe equality requirements in `traverse` -/ open list lemma sequence_mono : ∀(as bs : list (filter α)), forall₂ (≤) as bs → sequence as ≤ sequence bs | [] [] forall₂.nil := le_refl _ | (a::as) (b::bs) (forall₂.cons h hs) := seq_mono (map_mono h) (sequence_mono as bs hs) variables {α' β' γ' : Type u} {f : β' → filter α'} {s : γ' → set α'} lemma mem_traverse_sets : ∀(fs : list β') (us : list γ'), forall₂ (λb c, s c ∈ f b) fs us → traverse s us ∈ traverse f fs | [] [] forall₂.nil := mem_pure_sets.2 $ mem_singleton _ | (f::fs) (u::us) (forall₂.cons h hs) := seq_mem_seq_sets (image_mem_map h) (mem_traverse_sets fs us hs) lemma mem_traverse_sets_iff (fs : list β') (t : set (list α')) : t ∈ traverse f fs ↔ (∃us:list (set α'), forall₂ (λb (s : set α'), s ∈ f b) fs us ∧ sequence us ⊆ t) := begin split, { induction fs generalizing t, case nil { simp only [sequence, mem_pure_sets, imp_self, forall₂_nil_left_iff, exists_eq_left, set.pure_def, singleton_subset_iff, traverse_nil] }, case cons : b fs ih t { assume ht, rcases mem_seq_sets_iff.1 ht with ⟨u, hu, v, hv, ht⟩, rcases mem_map_sets_iff.1 hu with ⟨w, hw, hwu⟩, rcases ih v hv with ⟨us, hus, hu⟩, exact ⟨w :: us, forall₂.cons hw hus, subset.trans (set.seq_mono hwu hu) ht⟩ } }, { rintros ⟨us, hus, hs⟩, exact mem_sets_of_superset (mem_traverse_sets _ _ hus) hs } end end list_traverse /-! ### Limits -/ /-- `tendsto` is the generic "limit of a function" predicate. `tendsto f l₁ l₂` asserts that for every `l₂` neighborhood `a`, the `f`-preimage of `a` is an `l₁` neighborhood. -/ def tendsto (f : α → β) (l₁ : filter α) (l₂ : filter β) := l₁.map f ≤ l₂ lemma tendsto_def {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ s ∈ l₂, f ⁻¹' s ∈ l₁ := iff.rfl lemma tendsto_iff_eventually {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ ∀ ⦃p : β → Prop⦄, (∀ᶠ y in l₂, p y) → ∀ᶠ x in l₁, p (f x) := iff.rfl lemma tendsto.eventually {f : α → β} {l₁ : filter α} {l₂ : filter β} {p : β → Prop} (hf : tendsto f l₁ l₂) (h : ∀ᶠ y in l₂, p y) : ∀ᶠ x in l₁, p (f x) := hf h lemma tendsto.frequently {f : α → β} {l₁ : filter α} {l₂ : filter β} {p : β → Prop} (hf : tendsto f l₁ l₂) (h : ∃ᶠ x in l₁, p (f x)) : ∃ᶠ y in l₂, p y := mt hf.eventually h lemma tendsto.frequently_map {l₁ : filter α} {l₂ : filter β} {p : α → Prop} {q : β → Prop} (f : α → β) (c : filter.tendsto f l₁ l₂) (w : ∀ x, p x → q (f x)) (h : ∃ᶠ x in l₁, p x) : ∃ᶠ y in l₂, q y := c.frequently (h.mono w) @[simp] lemma tendsto_bot {f : α → β} {l : filter β} : tendsto f ⊥ l := by simp [tendsto] @[simp] lemma tendsto_top {f : α → β} {l : filter α} : tendsto f l ⊤ := le_top lemma le_map_of_right_inverse {mab : α → β} {mba : β → α} {f : filter α} {g : filter β} (h₁ : mab ∘ mba =ᶠ[g] id) (h₂ : tendsto mba g f) : g ≤ map mab f := by { rw [← @map_id _ g, ← map_congr h₁, ← map_map], exact map_mono h₂ } lemma tendsto_of_not_nonempty {f : α → β} {la : filter α} {lb : filter β} (h : ¬nonempty α) : tendsto f la lb := by simp only [filter_eq_bot_of_not_nonempty la h, tendsto_bot] lemma eventually_eq_of_left_inv_of_right_inv {f : α → β} {g₁ g₂ : β → α} {fa : filter α} {fb : filter β} (hleft : ∀ᶠ x in fa, g₁ (f x) = x) (hright : ∀ᶠ y in fb, f (g₂ y) = y) (htendsto : tendsto g₂ fb fa) : g₁ =ᶠ[fb] g₂ := (htendsto.eventually hleft).mp $ hright.mono $ λ y hr hl, (congr_arg g₁ hr.symm).trans hl lemma tendsto_iff_comap {f : α → β} {l₁ : filter α} {l₂ : filter β} : tendsto f l₁ l₂ ↔ l₁ ≤ l₂.comap f := map_le_iff_le_comap alias tendsto_iff_comap ↔ filter.tendsto.le_comap _ lemma tendsto_congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : f₁ =ᶠ[l₁] f₂) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := by rw [tendsto, tendsto, map_congr hl] lemma tendsto.congr' {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (hl : f₁ =ᶠ[l₁] f₂) (h : tendsto f₁ l₁ l₂) : tendsto f₂ l₁ l₂ := (tendsto_congr' hl).1 h theorem tendsto_congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ ↔ tendsto f₂ l₁ l₂ := tendsto_congr' (univ_mem_sets' h) theorem tendsto.congr {f₁ f₂ : α → β} {l₁ : filter α} {l₂ : filter β} (h : ∀ x, f₁ x = f₂ x) : tendsto f₁ l₁ l₂ → tendsto f₂ l₁ l₂ := (tendsto_congr h).1 lemma tendsto_id' {x y : filter α} : x ≤ y → tendsto id x y := by simp only [tendsto, map_id, forall_true_iff] {contextual := tt} lemma tendsto_id {x : filter α} : tendsto id x x := tendsto_id' $ le_refl x lemma tendsto.comp {f : α → β} {g : β → γ} {x : filter α} {y : filter β} {z : filter γ} (hg : tendsto g y z) (hf : tendsto f x y) : tendsto (g ∘ f) x z := calc map (g ∘ f) x = map g (map f x) : by rw [map_map] ... ≤ map g y : map_mono hf ... ≤ z : hg lemma tendsto.mono_left {f : α → β} {x y : filter α} {z : filter β} (hx : tendsto f x z) (h : y ≤ x) : tendsto f y z := le_trans (map_mono h) hx lemma tendsto.mono_right {f : α → β} {x : filter α} {y z : filter β} (hy : tendsto f x y) (hz : y ≤ z) : tendsto f x z := le_trans hy hz lemma tendsto.ne_bot {f : α → β} {x : filter α} {y : filter β} (h : tendsto f x y) [hx : ne_bot x] : ne_bot y := (hx.map _).mono h lemma tendsto_map {f : α → β} {x : filter α} : tendsto f x (map f x) := le_refl (map f x) lemma tendsto_map' {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} (h : tendsto (f ∘ g) x y) : tendsto f (map g x) y := by rwa [tendsto, map_map] lemma tendsto_map'_iff {f : β → γ} {g : α → β} {x : filter α} {y : filter γ} : tendsto f (map g x) y ↔ tendsto (f ∘ g) x y := by rw [tendsto, map_map]; refl lemma tendsto_comap {f : α → β} {x : filter β} : tendsto f (comap f x) x := map_comap_le lemma tendsto_comap_iff {f : α → β} {g : β → γ} {a : filter α} {c : filter γ} : tendsto f a (c.comap g) ↔ tendsto (g ∘ f) a c := ⟨assume h, tendsto_comap.comp h, assume h, map_le_iff_le_comap.mp $ by rwa [map_map]⟩ lemma tendsto_comap'_iff {m : α → β} {f : filter α} {g : filter β} {i : γ → α} (h : range i ∈ f) : tendsto (m ∘ i) (comap i f) g ↔ tendsto m f g := by rw [tendsto, ← map_compose]; simp only [(∘), map_comap_of_mem h, tendsto] lemma comap_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : ψ ∘ φ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : comap φ g = f := begin refine le_antisymm (le_trans (comap_mono $ map_le_iff_le_comap.1 hψ) _) (map_le_iff_le_comap.1 hφ), rw [comap_comap, eq, comap_id], exact le_refl _ end lemma map_eq_of_inverse {f : filter α} {g : filter β} {φ : α → β} (ψ : β → α) (eq : φ ∘ ψ = id) (hφ : tendsto φ f g) (hψ : tendsto ψ g f) : map φ f = g := begin refine le_antisymm hφ (le_trans _ (map_mono hψ)), rw [map_map, eq, map_id], exact le_refl _ end lemma tendsto_inf {f : α → β} {x : filter α} {y₁ y₂ : filter β} : tendsto f x (y₁ ⊓ y₂) ↔ tendsto f x y₁ ∧ tendsto f x y₂ := by simp only [tendsto, le_inf_iff, iff_self] lemma tendsto_inf_left {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₁ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_left) h lemma tendsto_inf_right {f : α → β} {x₁ x₂ : filter α} {y : filter β} (h : tendsto f x₂ y) : tendsto f (x₁ ⊓ x₂) y := le_trans (map_mono inf_le_right) h lemma tendsto.inf {f : α → β} {x₁ x₂ : filter α} {y₁ y₂ : filter β} (h₁ : tendsto f x₁ y₁) (h₂ : tendsto f x₂ y₂) : tendsto f (x₁ ⊓ x₂) (y₁ ⊓ y₂) := tendsto_inf.2 ⟨tendsto_inf_left h₁, tendsto_inf_right h₂⟩ @[simp] lemma tendsto_infi {f : α → β} {x : filter α} {y : ι → filter β} : tendsto f x (⨅i, y i) ↔ ∀i, tendsto f x (y i) := by simp only [tendsto, iff_self, le_infi_iff] lemma tendsto_infi' {f : α → β} {x : ι → filter α} {y : filter β} (i : ι) (hi : tendsto f (x i) y) : tendsto f (⨅i, x i) y := hi.mono_left $ infi_le _ _ lemma tendsto_sup {f : α → β} {x₁ x₂ : filter α} {y : filter β} : tendsto f (x₁ ⊔ x₂) y ↔ tendsto f x₁ y ∧ tendsto f x₂ y := by simp only [tendsto, map_sup, sup_le_iff] lemma tendsto.sup {f : α → β} {x₁ x₂ : filter α} {y : filter β} : tendsto f x₁ y → tendsto f x₂ y → tendsto f (x₁ ⊔ x₂) y := λ h₁ h₂, tendsto_sup.mpr ⟨ h₁, h₂ ⟩ @[simp] lemma tendsto_principal {f : α → β} {l : filter α} {s : set β} : tendsto f l (𝓟 s) ↔ ∀ᶠ a in l, f a ∈ s := by simp only [tendsto, le_principal_iff, mem_map, filter.eventually] @[simp] lemma tendsto_principal_principal {f : α → β} {s : set α} {t : set β} : tendsto f (𝓟 s) (𝓟 t) ↔ ∀a∈s, f a ∈ t := by simp only [tendsto_principal, eventually_principal] @[simp] lemma tendsto_pure {f : α → β} {a : filter α} {b : β} : tendsto f a (pure b) ↔ ∀ᶠ x in a, f x = b := by simp only [tendsto, le_pure_iff, mem_map, mem_singleton_iff, filter.eventually] lemma tendsto_pure_pure (f : α → β) (a : α) : tendsto f (pure a) (pure (f a)) := tendsto_pure.2 rfl lemma tendsto_const_pure {a : filter α} {b : β} : tendsto (λx, b) a (pure b) := tendsto_pure.2 $ univ_mem_sets' $ λ _, rfl lemma pure_le_iff {a : α} {l : filter α} : pure a ≤ l ↔ ∀ s ∈ l, a ∈ s := iff.rfl lemma tendsto_pure_left {f : α → β} {a : α} {l : filter β} : tendsto f (pure a) l ↔ ∀ s ∈ l, f a ∈ s := iff.rfl @[simp] lemma map_inf_principal_preimage {f : α → β} {s : set β} {l : filter α} : map f (l ⊓ 𝓟 (f ⁻¹' s)) = map f l ⊓ 𝓟 s := filter.ext $ λ t, by simp only [mem_map, mem_inf_principal, mem_set_of_eq, mem_preimage] /-- If two filters are disjoint, then a function cannot tend to both of them along a non-trivial filter. -/ lemma tendsto.not_tendsto {f : α → β} {a : filter α} {b₁ b₂ : filter β} (hf : tendsto f a b₁) [ne_bot a] (hb : disjoint b₁ b₂) : ¬ tendsto f a b₂ := λ hf', (tendsto_inf.2 ⟨hf, hf'⟩).ne_bot.ne hb.eq_bot lemma tendsto.if {l₁ : filter α} {l₂ : filter β} {f g : α → β} {p : α → Prop} [∀ x, decidable (p x)] (h₀ : tendsto f (l₁ ⊓ 𝓟 {x | p x}) l₂) (h₁ : tendsto g (l₁ ⊓ 𝓟 { x | ¬ p x }) l₂) : tendsto (λ x, if p x then f x else g x) l₁ l₂ := begin simp only [tendsto_def, mem_inf_principal] at *, intros s hs, filter_upwards [h₀ s hs, h₁ s hs], simp only [mem_preimage], intros x hp₀ hp₁, split_ifs, exacts [hp₀ h, hp₁ h] end lemma tendsto.piecewise {l₁ : filter α} {l₂ : filter β} {f g : α → β} {s : set α} [∀ x, decidable (x ∈ s)] (h₀ : tendsto f (l₁ ⊓ 𝓟 s) l₂) (h₁ : tendsto g (l₁ ⊓ 𝓟 sᶜ) l₂) : tendsto (piecewise s f g) l₁ l₂ := h₀.if h₁ /-! ### Products of filters -/ section prod variables {s : set α} {t : set β} {f : filter α} {g : filter β} /- The product filter cannot be defined using the monad structure on filters. For example: F := do {x ← seq, y ← top, return (x, y)} hence: s ∈ F ↔ ∃n, [n..∞] × univ ⊆ s G := do {y ← top, x ← seq, return (x, y)} hence: s ∈ G ↔ ∀i:ℕ, ∃n, [n..∞] × {i} ⊆ s Now ⋃i, [i..∞] × {i} is in G but not in F. As product filter we want to have F as result. -/ /-- Product of filters. This is the filter generated by cartesian products of elements of the component filters. -/ protected def prod (f : filter α) (g : filter β) : filter (α × β) := f.comap prod.fst ⊓ g.comap prod.snd localized "infix ` ×ᶠ `:60 := filter.prod" in filter lemma prod_mem_prod {s : set α} {t : set β} {f : filter α} {g : filter β} (hs : s ∈ f) (ht : t ∈ g) : set.prod s t ∈ f ×ᶠ g := inter_mem_inf_sets (preimage_mem_comap hs) (preimage_mem_comap ht) lemma mem_prod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ f ×ᶠ g ↔ (∃ t₁ ∈ f, ∃ t₂ ∈ g, set.prod t₁ t₂ ⊆ s) := begin simp only [filter.prod], split, exact assume ⟨t₁, ⟨s₁, hs₁, hts₁⟩, t₂, ⟨s₂, hs₂, hts₂⟩, h⟩, ⟨s₁, hs₁, s₂, hs₂, subset.trans (inter_subset_inter hts₁ hts₂) h⟩, exact assume ⟨t₁, ht₁, t₂, ht₂, h⟩, ⟨prod.fst ⁻¹' t₁, ⟨t₁, ht₁, subset.refl _⟩, prod.snd ⁻¹' t₂, ⟨t₂, ht₂, subset.refl _⟩, h⟩ end @[simp] lemma prod_mem_prod_iff {s : set α} {t : set β} {f : filter α} {g : filter β} [f.ne_bot] [g.ne_bot] : s.prod t ∈ f ×ᶠ g ↔ s ∈ f ∧ t ∈ g := ⟨λ h, let ⟨s', hs', t', ht', H⟩ := mem_prod_iff.1 h in (prod_subset_prod_iff.1 H).elim (λ ⟨hs's, ht't⟩, ⟨mem_sets_of_superset hs' hs's, mem_sets_of_superset ht' ht't⟩) (λ h, h.elim (λ hs'e, absurd hs'e (nonempty_of_mem_sets hs').ne_empty) (λ ht'e, absurd ht'e (nonempty_of_mem_sets ht').ne_empty)), λ h, prod_mem_prod h.1 h.2⟩ lemma comap_prod (f : α → β × γ) (b : filter β) (c : filter γ) : comap f (b ×ᶠ c) = (comap (prod.fst ∘ f) b) ⊓ (comap (prod.snd ∘ f) c) := by erw [comap_inf, filter.comap_comap, filter.comap_comap] lemma eventually_prod_iff {p : α × β → Prop} {f : filter α} {g : filter β} : (∀ᶠ x in f ×ᶠ g, p x) ↔ ∃ (pa : α → Prop) (ha : ∀ᶠ x in f, pa x) (pb : β → Prop) (hb : ∀ᶠ y in g, pb y), ∀ {x}, pa x → ∀ {y}, pb y → p (x, y) := by simpa only [set.prod_subset_iff] using @mem_prod_iff α β p f g lemma tendsto_fst {f : filter α} {g : filter β} : tendsto prod.fst (f ×ᶠ g) f := tendsto_inf_left tendsto_comap lemma tendsto_snd {f : filter α} {g : filter β} : tendsto prod.snd (f ×ᶠ g) g := tendsto_inf_right tendsto_comap lemma tendsto.prod_mk {f : filter α} {g : filter β} {h : filter γ} {m₁ : α → β} {m₂ : α → γ} (h₁ : tendsto m₁ f g) (h₂ : tendsto m₂ f h) : tendsto (λx, (m₁ x, m₂ x)) f (g ×ᶠ h) := tendsto_inf.2 ⟨tendsto_comap_iff.2 h₁, tendsto_comap_iff.2 h₂⟩ lemma eventually.prod_inl {la : filter α} {p : α → Prop} (h : ∀ᶠ x in la, p x) (lb : filter β) : ∀ᶠ x in la ×ᶠ lb, p (x : α × β).1 := tendsto_fst.eventually h lemma eventually.prod_inr {lb : filter β} {p : β → Prop} (h : ∀ᶠ x in lb, p x) (la : filter α) : ∀ᶠ x in la ×ᶠ lb, p (x : α × β).2 := tendsto_snd.eventually h lemma eventually.prod_mk {la : filter α} {pa : α → Prop} (ha : ∀ᶠ x in la, pa x) {lb : filter β} {pb : β → Prop} (hb : ∀ᶠ y in lb, pb y) : ∀ᶠ p in la ×ᶠ lb, pa (p : α × β).1 ∧ pb p.2 := (ha.prod_inl lb).and (hb.prod_inr la) lemma eventually.curry {la : filter α} {lb : filter β} {p : α × β → Prop} (h : ∀ᶠ x in la ×ᶠ lb, p x) : ∀ᶠ x in la, ∀ᶠ y in lb, p (x, y) := begin rcases eventually_prod_iff.1 h with ⟨pa, ha, pb, hb, h⟩, exact ha.mono (λ a ha, hb.mono $ λ b hb, h ha hb) end lemma prod_infi_left [nonempty ι] {f : ι → filter α} {g : filter β}: (⨅i, f i) ×ᶠ g = (⨅i, (f i) ×ᶠ g) := by rw [filter.prod, comap_infi, infi_inf]; simp only [filter.prod, eq_self_iff_true] lemma prod_infi_right [nonempty ι] {f : filter α} {g : ι → filter β} : f ×ᶠ (⨅i, g i) = (⨅i, f ×ᶠ (g i)) := by rw [filter.prod, comap_infi, inf_infi]; simp only [filter.prod, eq_self_iff_true] @[mono] lemma prod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁ ×ᶠ g₁ ≤ f₂ ×ᶠ g₂ := inf_le_inf (comap_mono hf) (comap_mono hg) lemma prod_comap_comap_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : β₁ → α₁} {m₂ : β₂ → α₂} : (comap m₁ f₁) ×ᶠ (comap m₂ f₂) = comap (λp:β₁×β₂, (m₁ p.1, m₂ p.2)) (f₁ ×ᶠ f₂) := by simp only [filter.prod, comap_comap, eq_self_iff_true, comap_inf] lemma prod_comm' : f ×ᶠ g = comap (prod.swap) (g ×ᶠ f) := by simp only [filter.prod, comap_comap, (∘), inf_comm, prod.fst_swap, eq_self_iff_true, prod.snd_swap, comap_inf] lemma prod_comm : f ×ᶠ g = map (λp:β×α, (p.2, p.1)) (g ×ᶠ f) := by rw [prod_comm', ← map_swap_eq_comap_swap]; refl lemma prod_map_map_eq {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} : (map m₁ f₁) ×ᶠ (map m₂ f₂) = map (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) (f₁ ×ᶠ f₂) := le_antisymm (assume s hs, let ⟨s₁, hs₁, s₂, hs₂, h⟩ := mem_prod_iff.mp hs in filter.sets_of_superset _ (prod_mem_prod (image_mem_map hs₁) (image_mem_map hs₂)) $ calc set.prod (m₁ '' s₁) (m₂ '' s₂) = (λp:α₁×α₂, (m₁ p.1, m₂ p.2)) '' set.prod s₁ s₂ : set.prod_image_image_eq ... ⊆ _ : by rwa [image_subset_iff]) ((tendsto.comp (le_refl _) tendsto_fst).prod_mk (tendsto.comp (le_refl _) tendsto_snd)) lemma prod_map_map_eq' {α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*} (f : α₁ → α₂) (g : β₁ → β₂) (F : filter α₁) (G : filter β₁) : (map f F) ×ᶠ (map g G) = map (prod.map f g) (F ×ᶠ G) := by { rw filter.prod_map_map_eq, refl } lemma tendsto.prod_map {δ : Type*} {f : α → γ} {g : β → δ} {a : filter α} {b : filter β} {c : filter γ} {d : filter δ} (hf : tendsto f a c) (hg : tendsto g b d) : tendsto (prod.map f g) (a ×ᶠ b) (c ×ᶠ d) := begin erw [tendsto, ← prod_map_map_eq], exact filter.prod_mono hf hg, end lemma map_prod (m : α × β → γ) (f : filter α) (g : filter β) : map m (f ×ᶠ g) = (f.map (λa b, m (a, b))).seq g := begin simp [filter.ext_iff, mem_prod_iff, mem_map_seq_iff], assume s, split, exact assume ⟨t, ht, s, hs, h⟩, ⟨s, hs, t, ht, assume x hx y hy, @h ⟨x, y⟩ ⟨hx, hy⟩⟩, exact assume ⟨s, hs, t, ht, h⟩, ⟨t, ht, s, hs, assume ⟨x, y⟩ ⟨hx, hy⟩, h x hx y hy⟩ end lemma prod_eq {f : filter α} {g : filter β} : f ×ᶠ g = (f.map prod.mk).seq g := have h : _ := map_prod id f g, by rwa [map_id] at h lemma prod_inf_prod {f₁ f₂ : filter α} {g₁ g₂ : filter β} : (f₁ ×ᶠ g₁) ⊓ (f₂ ×ᶠ g₂) = (f₁ ⊓ f₂) ×ᶠ (g₁ ⊓ g₂) := by simp only [filter.prod, comap_inf, inf_comm, inf_assoc, inf_left_comm] @[simp] lemma prod_bot {f : filter α} : f ×ᶠ (⊥ : filter β) = ⊥ := by simp [filter.prod] @[simp] lemma bot_prod {g : filter β} : (⊥ : filter α) ×ᶠ g = ⊥ := by simp [filter.prod] @[simp] lemma prod_principal_principal {s : set α} {t : set β} : (𝓟 s) ×ᶠ (𝓟 t) = 𝓟 (set.prod s t) := by simp only [filter.prod, comap_principal, principal_eq_iff_eq, comap_principal, inf_principal]; refl @[simp] lemma pure_prod {a : α} {f : filter β} : pure a ×ᶠ f = map (prod.mk a) f := by rw [prod_eq, map_pure, pure_seq_eq_map] @[simp] lemma prod_pure {f : filter α} {b : β} : f ×ᶠ pure b = map (λ a, (a, b)) f := by rw [prod_eq, seq_pure, map_map] lemma prod_pure_pure {a : α} {b : β} : (pure a) ×ᶠ (pure b) = pure (a, b) := by simp lemma prod_eq_bot {f : filter α} {g : filter β} : f ×ᶠ g = ⊥ ↔ (f = ⊥ ∨ g = ⊥) := begin split, { assume h, rcases mem_prod_iff.1 (empty_in_sets_eq_bot.2 h) with ⟨s, hs, t, ht, hst⟩, rw [subset_empty_iff, set.prod_eq_empty_iff] at hst, cases hst with s_eq t_eq, { left, exact empty_in_sets_eq_bot.1 (s_eq ▸ hs) }, { right, exact empty_in_sets_eq_bot.1 (t_eq ▸ ht) } }, { rintros (rfl | rfl), exact bot_prod, exact prod_bot } end lemma prod_ne_bot {f : filter α} {g : filter β} : ne_bot (f ×ᶠ g) ↔ (ne_bot f ∧ ne_bot g) := by simp only [ne_bot_iff, ne, prod_eq_bot, not_or_distrib] lemma ne_bot.prod {f : filter α} {g : filter β} (hf : ne_bot f) (hg : ne_bot g) : ne_bot (f ×ᶠ g) := prod_ne_bot.2 ⟨hf, hg⟩ instance prod_ne_bot' {f : filter α} {g : filter β} [hf : ne_bot f] [hg : ne_bot g] : ne_bot (f ×ᶠ g) := hf.prod hg lemma tendsto_prod_iff {f : α × β → γ} {x : filter α} {y : filter β} {z : filter γ} : filter.tendsto f (x ×ᶠ y) z ↔ ∀ W ∈ z, ∃ U ∈ x, ∃ V ∈ y, ∀ x y, x ∈ U → y ∈ V → f (x, y) ∈ W := by simp only [tendsto_def, mem_prod_iff, prod_sub_preimage_iff, exists_prop, iff_self] end prod /-! ### Coproducts of filters -/ section coprod variables {s : set α} {t : set β} {f : filter α} {g : filter β} /-- Coproduct of filters. -/ protected def coprod (f : filter α) (g : filter β) : filter (α × β) := f.comap prod.fst ⊔ g.comap prod.snd lemma mem_coprod_iff {s : set (α×β)} {f : filter α} {g : filter β} : s ∈ f.coprod g ↔ ((∃ t₁ ∈ f, prod.fst ⁻¹' t₁ ⊆ s) ∧ (∃ t₂ ∈ g, prod.snd ⁻¹' t₂ ⊆ s)) := by simp [filter.coprod] @[mono] lemma coprod_mono {f₁ f₂ : filter α} {g₁ g₂ : filter β} (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.coprod g₁ ≤ f₂.coprod g₂ := sup_le_sup (comap_mono hf) (comap_mono hg) lemma principal_coprod_principal (s : set α) (t : set β) : (𝓟 s).coprod (𝓟 t) = 𝓟 (sᶜ.prod tᶜ)ᶜ := begin rw [filter.coprod, comap_principal, comap_principal, sup_principal], congr, ext x, simp ; tauto, end -- this inequality can be strict; see `map_const_principal_coprod_map_id_principal` and -- `map_prod_map_const_id_principal_coprod_principal` below. lemma map_prod_map_coprod_le {α₁ : Type u} {α₂ : Type v} {β₁ : Type w} {β₂ : Type x} {f₁ : filter α₁} {f₂ : filter α₂} {m₁ : α₁ → β₁} {m₂ : α₂ → β₂} : map (prod.map m₁ m₂) (f₁.coprod f₂) ≤ (map m₁ f₁).coprod (map m₂ f₂) := begin intros s, simp only [mem_map, mem_coprod_iff], rintros ⟨⟨u₁, hu₁, h₁⟩, ⟨u₂, hu₂, h₂⟩⟩, refine ⟨⟨m₁ ⁻¹' u₁, hu₁, λ _ hx, h₁ _⟩, ⟨m₂ ⁻¹' u₂, hu₂, λ _ hx, h₂ _⟩⟩; convert hx end /-- Characterization of the coproduct of the `filter.map`s of two principal filters `𝓟 {a}` and `𝓟 {i}`, the first under the constant function `λ a, b` and the second under the identity function. Together with the next lemma, `map_prod_map_const_id_principal_coprod_principal`, this provides an example showing that the inequality in the lemma `map_prod_map_coprod_le` can be strict. -/ lemma map_const_principal_coprod_map_id_principal {α β ι : Type*} (a : α) (b : β) (i : ι) : (map (λ _ : α, b) (𝓟 {a})).coprod (map id (𝓟 {i})) = 𝓟 (({b} : set β).prod (univ : set ι) ∪ (univ : set β).prod {i}) := begin rw [map_principal, map_principal, principal_coprod_principal], congr, ext ⟨b', i'⟩, simp, tauto, end /-- Characterization of the `filter.map` of the coproduct of two principal filters `𝓟 {a}` and `𝓟 {i}`, under the `prod.map` of two functions, respectively the constant function `λ a, b` and the identity function. Together with the previous lemma, `map_const_principal_coprod_map_id_principal`, this provides an example showing that the inequality in the lemma `map_prod_map_coprod_le` can be strict. -/ lemma map_prod_map_const_id_principal_coprod_principal {α β ι : Type*} (a : α) (b : β) (i : ι) : map (prod.map (λ _ : α, b) id) ((𝓟 {a}).coprod (𝓟 {i})) = 𝓟 (({b} : set β).prod (univ : set ι)) := begin rw [principal_coprod_principal, map_principal], congr, ext ⟨b', i'⟩, split, { rintros ⟨⟨a'', i''⟩, h₁, ⟨h₂, h₃⟩⟩, simp }, { rintros ⟨h₁, h₂⟩, use (a, i'), simpa using h₁.symm } end lemma tendsto.prod_map_coprod {δ : Type*} {f : α → γ} {g : β → δ} {a : filter α} {b : filter β} {c : filter γ} {d : filter δ} (hf : tendsto f a c) (hg : tendsto g b d) : tendsto (prod.map f g) (a.coprod b) (c.coprod d) := map_prod_map_coprod_le.trans (coprod_mono hf hg) end coprod /-! ### `n`-ary coproducts of filters -/ section Coprod variables {δ : Type*} {κ : δ → Type*} -- {f : Π d, filter (κ d)} /-- Coproduct of filters. -/ protected def Coprod (f : Π d, filter (κ d)) : filter (Π d, κ d) := ⨆ d : δ, (f d).comap (λ k, k d) lemma mem_Coprod_iff {s : set (Π d, κ d)} {f : Π d, filter (κ d)} : (s ∈ (filter.Coprod f)) ↔ (∀ d : δ, (∃ t₁ ∈ f d, (λ k : (Π d, κ d), k d) ⁻¹' t₁ ⊆ s)) := by simp [filter.Coprod] @[mono] lemma Coprod_mono {f₁ f₂ : Π d, filter (κ d)} (hf : ∀ d, f₁ d ≤ f₂ d) : filter.Coprod f₁ ≤ filter.Coprod f₂ := supr_le_supr $ λ d, comap_mono (hf d) lemma map_pi_map_Coprod_le {μ : δ → Type*} {f : Π d, filter (κ d)} {m : Π d, κ d → μ d} : map (λ (k : Π d, κ d), λ d, m d (k d)) (filter.Coprod f) ≤ filter.Coprod (λ d, map (m d) (f d)) := begin intros s h, rw [mem_map, mem_Coprod_iff], intros d, rw mem_Coprod_iff at h, obtain ⟨t, H, hH⟩ := h d, rw mem_map at H, refine ⟨{x : κ d | m d x ∈ t}, H, _⟩, intros x hx, simp only [mem_set_of_eq, preimage_set_of_eq] at hx, rw mem_set_of_eq, exact set.mem_of_subset_of_mem hH (mem_preimage.mpr hx), end lemma tendsto.pi_map_Coprod {μ : δ → Type*} {f : Π d, filter (κ d)} {m : Π d, κ d → μ d} {g : Π d, filter (μ d)} (hf : ∀ d, tendsto (m d) (f d) (g d)) : tendsto (λ (k : Π d, κ d), λ d, m d (k d)) (filter.Coprod f) (filter.Coprod g) := map_pi_map_Coprod_le.trans (Coprod_mono hf) end Coprod end filter open_locale filter lemma set.eq_on.eventually_eq {α β} {s : set α} {f g : α → β} (h : eq_on f g s) : f =ᶠ[𝓟 s] g := h lemma set.eq_on.eventually_eq_of_mem {α β} {s : set α} {l : filter α} {f g : α → β} (h : eq_on f g s) (hl : s ∈ l) : f =ᶠ[l] g := h.eventually_eq.filter_mono $ filter.le_principal_iff.2 hl lemma set.subset.eventually_le {α} {l : filter α} {s t : set α} (h : s ⊆ t) : s ≤ᶠ[l] t := filter.eventually_of_forall h lemma set.maps_to.tendsto {α β} {s : set α} {t : set β} {f : α → β} (h : maps_to f s t) : filter.tendsto f (𝓟 s) (𝓟 t) := filter.tendsto_principal_principal.2 h
db9d46f499ff9420ed8319ad7d8d5ef17fab1e3e
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/category_theory/triangulated/rotate.lean
18ece83b4b95ebfe7fe809a282d8fc62116bcfde
[ "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
7,747
lean
/- Copyright (c) 2021 Luke Kershaw. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Luke Kershaw -/ import category_theory.additive.basic import category_theory.shift import category_theory.preadditive.additive_functor import category_theory.natural_isomorphism import category_theory.triangulated.basic /-! # Rotate This file adds the ability to rotate triangles and triangle morphisms. It also shows that rotation gives an equivalence on the category of triangles. -/ noncomputable theory open category_theory open category_theory.preadditive open category_theory.limits universes v v₀ v₁ v₂ u u₀ u₁ u₂ namespace category_theory.triangulated open category_theory.category /-- We work in an preadditive category `C` equipped with an additive shift. -/ variables {C : Type u} [category.{v} C] [has_shift C] [preadditive C] variables (X : C) /-- If you rotate a triangle, you get another triangle. Given a triangle of the form: ``` f g h X ───> Y ───> Z ───> X⟦1⟧ ``` applying `rotate` gives a triangle of the form: ``` g h -f⟦1⟧' Y ───> Z ───> X⟦1⟧ ───> Y⟦1⟧ ``` -/ @[simps] def triangle.rotate (T : triangle C) : triangle C := triangle.mk _ T.mor₂ T.mor₃ (-T.mor₁⟦1⟧') /-- Given a triangle of the form: ``` f g h X ───> Y ───> Z ───> X⟦1⟧ ``` applying `inv_rotate` gives a triangle that can be thought of as: ``` -h⟦-1⟧' f g Z⟦-1⟧ ───> X ───> Y ───> Z ``` (note that this diagram doesn't technically fit the definition of triangle, as `Z⟦-1⟧⟦1⟧` is not necessarily equal to `Z`, but it is isomorphic, by the `counit_iso` of `shift C`) -/ @[simps] def triangle.inv_rotate (T : triangle C) : triangle C := triangle.mk _ (-T.mor₃⟦-1⟧' ≫ (shift C).unit_iso.inv.app T.obj₁) T.mor₁ (T.mor₂ ≫ (shift C).counit_iso.inv.app T.obj₃) namespace triangle_morphism variables {T₁ T₂ T₃ T₄: triangle C} open triangle /-- You can also rotate a triangle morphism to get a morphism between the two rotated triangles. Given a triangle morphism of the form: ``` f g h X ───> Y ───> Z ───> X⟦1⟧ │ │ │ │ │a │b │c │a⟦1⟧ V V V V X' ───> Y' ───> Z' ───> X'⟦1⟧ f' g' h' ``` applying `rotate` gives a triangle morphism of the form: ⟦⟧ ``` g h -f⟦1⟧ Y ───> Z ───> X⟦1⟧ ───> Y⟦1⟧ │ │ │ │ │b │c │a⟦1⟧ │b⟦1⟧' V V V V Y' ───> Z' ───> X'⟦1⟧ ───> Y'⟦1⟧ g' h' -f'⟦1⟧ ``` -/ @[simps] def rotate (f : triangle_morphism T₁ T₂) : triangle_morphism (T₁.rotate) (T₂.rotate):= { hom₁ := f.hom₂, hom₂ := f.hom₃, hom₃ := f.hom₁⟦1⟧', comm₃' := begin dsimp, simp only [rotate_mor₃, comp_neg, neg_comp, ← functor.map_comp, f.comm₁] end} /-- Given a triangle morphism of the form: ``` f g h X ───> Y ───> Z ───> X⟦1⟧ │ │ │ │ │a │b │c │a⟦1⟧ V V V V X' ───> Y' ───> Z' ───> X'⟦1⟧ f' g' h' ``` applying `inv_rotate` gives a triangle morphism that can be thought of as: ``` -h⟦-1⟧ f g Z⟦-1⟧ ───> X ───> Y ───> Z │ │ │ │ │c⟦-1⟧' │a │b │c V V V V Z'⟦-1⟧ ───> X' ───> Y' ───> Z' -h'⟦-1⟧ f' g' ``` (note that this diagram doesn't technically fit the definition of triangle morphism, as `Z⟦-1⟧⟦1⟧` is not necessarily equal to `Z`, and `Z'⟦-1⟧⟦1⟧` is not necessarily equal to `Z'`, but they are isomorphic, by the `counit_iso` of `shift C`) -/ @[simps] def inv_rotate (f : triangle_morphism T₁ T₂) : triangle_morphism (T₁.inv_rotate) (T₂.inv_rotate) := { hom₁ := f.hom₃⟦-1⟧', hom₂ := f.hom₁, hom₃ := f.hom₂, comm₁' := begin dsimp [inv_rotate_mor₁], simp_rw [comp_neg, neg_comp, ← assoc, ← functor.map_comp (shift C ).inverse, ← f.comm₃, functor.map_comp, assoc, equivalence.inv_fun_map, assoc, iso.hom_inv_id_app], dsimp, simp only [comp_id], end } end triangle_morphism /-- Rotating triangles gives an endofunctor on the category of triangles in `C`. -/ @[simps] def rotate : (triangle C) ⥤ (triangle C) := { obj := triangle.rotate, map := λ _ _ f, f.rotate } /-- The inverse rotation of triangles gives an endofunctor on the category of triangles in `C`. -/ @[simps] def inv_rotate : (triangle C) ⥤ (triangle C) := { obj := triangle.inv_rotate, map := λ _ _ f, f.inv_rotate } variables [functor.additive (shift C).functor] /-- There is a natural transformation between the identity functor on triangles in `C`, and the composition of a rotation with an inverse rotation. -/ @[simps] def rot_comp_inv_rot_hom : 𝟭 (triangle C) ⟶ rotate ⋙ inv_rotate := { app := λ T, { hom₁ := (shift C).unit.app T.obj₁, hom₂ := 𝟙 T.obj₂, hom₃ := 𝟙 T.obj₃, comm₃' := begin dsimp, rw [id_comp, equivalence.counit_inv_app_functor], end } } /-- There is a natural transformation between the composition of a rotation with an inverse rotation on triangles in `C`, and the identity functor. -/ @[simps] def rot_comp_inv_rot_inv : rotate ⋙ inv_rotate ⟶ 𝟭 (triangle C) := { app := λ T, { hom₁ := (shift C).unit_inv.app T.obj₁, hom₂ := 𝟙 T.obj₂, hom₃ := 𝟙 T.obj₃ } } /-- The natural transformations between the identity functor on triangles in `C` and the composition of a rotation with an inverse rotation are natural isomorphisms (they are isomorphisms in the category of functors). -/ @[simps] def rot_comp_inv_rot : 𝟭 (triangle C) ≅ rotate ⋙ inv_rotate := { hom := rot_comp_inv_rot_hom, inv := rot_comp_inv_rot_inv } /-- There is a natural transformation between the composition of an inverse rotation with a rotation on triangles in `C`, and the identity functor. -/ @[simps] def inv_rot_comp_rot_hom : inv_rotate ⋙ rotate ⟶ 𝟭 (triangle C) := { app := λ T, { hom₁ := 𝟙 T.obj₁, hom₂ := 𝟙 T.obj₂, hom₃ := (shift C).counit.app T.obj₃ } } /-- There is a natural transformation between the identity functor on triangles in `C`, and the composition of an inverse rotation with a rotation. -/ @[simps] def inv_rot_comp_rot_inv : 𝟭 (triangle C) ⟶ inv_rotate ⋙ rotate := { app := λ T, { hom₁ := 𝟙 T.obj₁, hom₂ := 𝟙 T.obj₂, hom₃ := (shift C).counit_inv.app T.obj₃ } } /-- The natural transformations between the composition of a rotation with an inverse rotation on triangles in `C`, and the identity functor on triangles are natural isomorphisms (they are isomorphisms in the category of functors). -/ @[simps] def inv_rot_comp_rot : inv_rotate ⋙ rotate ≅ 𝟭 (triangle C) := { hom := inv_rot_comp_rot_hom, inv := inv_rot_comp_rot_inv } /-- Rotating triangles gives an auto-equivalence on the category of triangles in `C`. -/ @[simps] def triangle_rotation : equivalence (triangle C) (triangle C) := { functor := rotate, inverse := inv_rotate, unit_iso := rot_comp_inv_rot, counit_iso := inv_rot_comp_rot } end category_theory.triangulated
2e46825c9d29b722d62f422f7a74696cb7b00e17
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/set/countable.lean
3882fc93f9cfedc9eff2139fa596482a07c03520
[ "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
9,899
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.set.finite import data.countable.basic import logic.equiv.list /-! # Countable sets -/ noncomputable theory open function set encodable open classical (hiding some) open_locale classical universes u v w x variables {α : Type u} {β : Type v} {γ : Type w} {ι : Sort x} namespace set /-- A set is countable if there exists an encoding of the set into the natural numbers. An encoding is an injection with a partial inverse, which can be viewed as a constructive analogue of countability. (For the most part, theorems about `countable` will be classical and `encodable` will be constructive.) -/ protected def countable (s : set α) : Prop := nonempty (encodable s) @[simp] lemma countable_coe_iff {s : set α} : countable s ↔ s.countable := encodable.nonempty_encodable.symm /-- Prove `set.countable` from a `countable` instance on the subtype. -/ lemma to_countable (s : set α) [countable s] : s.countable := countable_coe_iff.mp ‹_› /-- Restate `set.countable` as a `countable` instance. -/ alias countable_coe_iff ↔ _root_.countable.to_set countable.to_subtype protected lemma countable_iff_exists_injective {s : set α} : s.countable ↔ ∃ f : s → ℕ, injective f := countable_coe_iff.symm.trans (countable_iff_exists_injective s) /-- A set `s : set α` is countable if and only if there exists a function `α → ℕ` injective on `s`. -/ lemma countable_iff_exists_inj_on {s : set α} : s.countable ↔ ∃ f : α → ℕ, inj_on f s := set.countable_iff_exists_injective.trans exists_inj_on_iff_injective.symm /-- Convert `set.countable s` to `encodable s` (noncomputable). -/ protected def countable.to_encodable {s : set α} : s.countable → encodable s := classical.choice section enumerate /-- Noncomputably enumerate elements in a set. The `default` value is used to extend the domain to all of `ℕ`. -/ def enumerate_countable {s : set α} (h : s.countable) (default : α) : ℕ → α := assume n, match @encodable.decode s h.to_encodable n with | (some y) := y | (none) := default end lemma subset_range_enumerate {s : set α} (h : s.countable) (default : α) : s ⊆ range (enumerate_countable h default) := assume x hx, ⟨@encodable.encode s h.to_encodable ⟨x, hx⟩, by simp [enumerate_countable, encodable.encodek]⟩ end enumerate lemma countable.mono {s₁ s₂ : set α} (h : s₁ ⊆ s₂) : s₂.countable → s₁.countable | ⟨H⟩ := ⟨@of_inj _ _ H _ (embedding_of_subset _ _ h).2⟩ lemma countable_range [countable ι] (f : ι → β) : (range f).countable := surjective_onto_range.countable.to_set lemma countable_iff_exists_subset_range [nonempty α] {s : set α} : s.countable ↔ ∃ f : ℕ → α, s ⊆ range f := ⟨λ h, by { inhabit α, exact ⟨enumerate_countable h default, subset_range_enumerate _ _⟩ }, λ ⟨f, hsf⟩, (countable_range f).mono hsf⟩ /-- A non-empty set is countable iff there exists a surjection from the natural numbers onto the subtype induced by the set. -/ protected lemma countable_iff_exists_surjective {s : set α} (hs : s.nonempty) : s.countable ↔ ∃ f : ℕ → s, surjective f := countable_coe_iff.symm.trans $ @countable_iff_exists_surjective s hs.to_subtype alias set.countable_iff_exists_surjective ↔ countable.exists_surjective _ lemma countable_univ [countable α] : (univ : set α).countable := to_countable univ /-- If `s : set α` is a nonempty countable set, then there exists a map `f : ℕ → α` such that `s = range f`. -/ lemma countable.exists_eq_range {s : set α} (hc : s.countable) (hs : s.nonempty) : ∃ f : ℕ → α, s = range f := begin rcases hc.exists_surjective hs with ⟨f, hf⟩, refine ⟨coe ∘ f, _⟩, rw [hf.range_comp, subtype.range_coe] end @[simp] lemma countable_empty : (∅ : set α).countable := to_countable _ @[simp] lemma countable_singleton (a : α) : ({a} : set α).countable := ⟨of_equiv _ (equiv.set.singleton a)⟩ lemma countable.image {s : set α} (hs : s.countable) (f : α → β) : (f '' s).countable := by { rw [image_eq_range], haveI := hs.to_subtype, apply countable_range } lemma maps_to.countable_of_inj_on {s : set α} {t : set β} {f : α → β} (hf : maps_to f s t) (hf' : inj_on f s) (ht : t.countable) : s.countable := have injective (hf.restrict f s t), from (inj_on_iff_injective.1 hf').cod_restrict _, ⟨@encodable.of_inj _ _ ht.to_encodable _ this⟩ lemma countable.preimage_of_inj_on {s : set β} (hs : s.countable) {f : α → β} (hf : inj_on f (f ⁻¹' s)) : (f ⁻¹' s).countable := (maps_to_preimage f s).countable_of_inj_on hf hs protected lemma countable.preimage {s : set β} (hs : s.countable) {f : α → β} (hf : injective f) : (f ⁻¹' s).countable := hs.preimage_of_inj_on (hf.inj_on _) lemma exists_seq_supr_eq_top_iff_countable [complete_lattice α] {p : α → Prop} (h : ∃ x, p x) : (∃ s : ℕ → α, (∀ n, p (s n)) ∧ (⨆ n, s n) = ⊤) ↔ ∃ S : set α, S.countable ∧ (∀ s ∈ S, p s) ∧ Sup S = ⊤ := begin split, { rintro ⟨s, hps, hs⟩, refine ⟨range s, countable_range s, forall_range_iff.2 hps, _⟩, rwa Sup_range }, { rintro ⟨S, hSc, hps, hS⟩, rcases eq_empty_or_nonempty S with rfl|hne, { rw [Sup_empty] at hS, haveI := subsingleton_of_bot_eq_top hS, rcases h with ⟨x, hx⟩, exact ⟨λ n, x, λ n, hx, subsingleton.elim _ _⟩ }, { rcases (set.countable_iff_exists_surjective hne).1 hSc with ⟨s, hs⟩, refine ⟨λ n, s n, λ n, hps _ (s n).coe_prop, _⟩, rwa [hs.supr_comp, ← Sup_eq_supr'] } } end lemma exists_seq_cover_iff_countable {p : set α → Prop} (h : ∃ s, p s) : (∃ s : ℕ → set α, (∀ n, p (s n)) ∧ (⋃ n, s n) = univ) ↔ ∃ S : set (set α), S.countable ∧ (∀ s ∈ S, p s) ∧ ⋃₀ S = univ := exists_seq_supr_eq_top_iff_countable h lemma countable_of_injective_of_countable_image {s : set α} {f : α → β} (hf : inj_on f s) (hs : (f '' s).countable) : s.countable := let ⟨g, hg⟩ := countable_iff_exists_inj_on.1 hs in countable_iff_exists_inj_on.2 ⟨g ∘ f, hg.comp hf (maps_to_image _ _)⟩ lemma countable_Union {t : ι → set α} [countable ι] (ht : ∀ i, (t i).countable) : (⋃ i, t i).countable := by { haveI := λ a, (ht a).to_subtype, rw Union_eq_range_psigma, apply countable_range } @[simp] lemma countable_Union_iff [countable ι] {t : ι → set α} : (⋃ i, t i).countable ↔ ∀ i, (t i).countable := ⟨λ h i, h.mono $ subset_Union _ _, countable_Union⟩ lemma countable.bUnion_iff {s : set α} {t : Π a ∈ s, set β} (hs : s.countable) : (⋃ a ∈ s, t a ‹_›).countable ↔ ∀ a ∈ s, (t a ‹_›).countable := by { haveI := hs.to_subtype, rw [bUnion_eq_Union, countable_Union_iff, set_coe.forall'] } lemma countable.sUnion_iff {s : set (set α)} (hs : s.countable) : (⋃₀ s).countable ↔ ∀ a ∈ s, (a : _).countable := by rw [sUnion_eq_bUnion, hs.bUnion_iff] alias countable.bUnion_iff ↔ _ countable.bUnion alias countable.sUnion_iff ↔ _ countable.sUnion @[simp] lemma countable_union {s t : set α} : (s ∪ t).countable ↔ s.countable ∧ t.countable := by simp [union_eq_Union, and.comm] lemma countable.union {s t : set α} (hs : s.countable) (ht : t.countable) : (s ∪ t).countable := countable_union.2 ⟨hs, ht⟩ @[simp] lemma countable_insert {s : set α} {a : α} : (insert a s).countable ↔ s.countable := by simp only [insert_eq, countable_union, countable_singleton, true_and] lemma countable.insert {s : set α} (a : α) (h : s.countable) : (insert a s).countable := countable_insert.2 h lemma finite.countable {s : set α} : s.finite → s.countable | ⟨h⟩ := trunc.nonempty (by exactI fintype.trunc_encodable s) @[nontriviality] lemma countable.of_subsingleton [subsingleton α] (s : set α) : s.countable := (finite.of_subsingleton s).countable lemma subsingleton.countable {s : set α} (hs : s.subsingleton) : s.countable := hs.finite.countable lemma countable_is_top (α : Type*) [partial_order α] : {x : α | is_top x}.countable := (finite_is_top α).countable lemma countable_is_bot (α : Type*) [partial_order α] : {x : α | is_bot x}.countable := (finite_is_bot α).countable /-- The set of finite subsets of a countable set is countable. -/ lemma countable_set_of_finite_subset {s : set α} : s.countable → {t | set.finite t ∧ t ⊆ s}.countable | ⟨h⟩ := begin resetI, refine countable.mono _ (countable_range (λ t : finset s, {a | ∃ h:a ∈ s, subtype.mk a h ∈ t})), rintro t ⟨⟨ht⟩, ts⟩, resetI, refine ⟨finset.univ.map (embedding_of_subset _ _ ts), set.ext $ λ a, _⟩, simpa using @ts a end lemma countable_univ_pi {π : α → Type*} [finite α] {s : Π a, set (π a)} (hs : ∀ a, (s a).countable) : (pi univ s).countable := begin haveI := λ a, (hs a).to_subtype, exact (countable.of_equiv _ (equiv.set.univ_pi s).symm).to_set end lemma countable_pi {π : α → Type*} [finite α] {s : Πa, set (π a)} (hs : ∀a, (s a).countable) : {f : Πa, π a | ∀a, f a ∈ s a}.countable := by simpa only [← mem_univ_pi] using countable_univ_pi hs protected lemma countable.prod {s : set α} {t : set β} (hs : s.countable) (ht : t.countable) : set.countable (s ×ˢ t) := begin haveI : countable s := hs.to_subtype, haveI : countable t := ht.to_subtype, exact (countable.of_equiv _ $ (equiv.set.prod _ _).symm).to_set end lemma countable.image2 {s : set α} {t : set β} (hs : s.countable) (ht : t.countable) (f : α → β → γ) : (image2 f s t).countable := by { rw ← image_prod, exact (hs.prod ht).image _ } end set lemma finset.countable_to_set (s : finset α) : set.countable (↑s : set α) := s.finite_to_set.countable
a8018dc2791ddae066d20ce889584ff8ecca95cb
9d2e3d5a2e2342a283affd97eead310c3b528a24
/src/exercises_sources/friday/manifolds.lean
df6e4b453dd2fd2a6364d5ac5d3c89808583db50
[]
permissive
Vtec234/lftcm2020
ad2610ab614beefe44acc5622bb4a7fff9a5ea46
bbbd4c8162f8c2ef602300ab8fdeca231886375d
refs/heads/master
1,668,808,098,623
1,594,989,081,000
1,594,990,079,000
280,423,039
0
0
MIT
1,594,990,209,000
1,594,990,209,000
null
UTF-8
Lean
false
false
32,147
lean
import for_mathlib.manifolds noncomputable theory open_locale manifold classical big_operators open set universe u /-! ## Reminder on updating the exercises These instructions are now available at: https://leanprover-community.github.io/lftcm2020/exercises.html To get a new copy of the exercises, run the following commands in your terminal: ``` leanproject get lftcm2020 cp -r lftcm2020/src/exercises_sources/ lftcm2020/src/my_exercises code lftcm2020 ``` To update your exercise files, run the following commands: ``` cd /path/to/lftcm2020 git pull leanproject get-mathlib-cache ``` Don’t forget to copy the updated files to `src/my_exercises`. -/ /-! ## An overview of manifolds in Lean, discussing design decisions Warning: there are sorries in this section, they are not supposed to be filled! The exercises section start later, and there you will have plenty of sorries to fill. What is a manifold? 1) allow field other than `ℝ` or `ℂ`? 2) allow infinite dimension? 3) allow boundary? 4) allow model space depending on the point of the manifold? Bourbaki: 2, 4 (and just definitions and statements, no proofs!) Lean: 1, 2, 3 Perelman geometrization theorem : any compact connected irreducible 3-manifold can be cut along tori into finitely many pieces, each of which has a _geometric structure_ of finite volume, i.e., it is locally like a model space, with changes of coordinates given locally by the action of a Lie group Typical dynamics theorem : let `M` be a compact manifold, and `f : M → M` a map with property such and such. Then ... Or : Consider a hyperbolic surface of genus `g`, and a random geodesic of length `T`. How many times does it typically self-intersect? Manifold in Lean: * charted space structure, i.e., set of local homeos to a model space. This is data, fixed once and for all (and a typeclass) * compatibility condition, i.e., the change of coordinates should belong to some subgroup of the group of local homeos of the model space. This is Prop (and a typeclass). The same manifold can be at the same time an analytic manifold, a smooth manifold and a topological manifold (with the same fixed atlas). * A charted space is a smooth manifold (with corners) if it is compatible with the smooth groupoid on the model space. To cover uniformly both situations with and without boundary, the smooth groupoid is with respect to a map `I : H → E` (think of `H` as the half-space and `E` the full space), which is the identity in the boundaryless situation, the inclusion in the half-space situation. This map `I` is called a _model with corners_. The most standard ones (identity in `ℝ^n` and inclusion of half-space in `ℝ^n`) have dedicated notations: `𝓡 n` and `𝓡∂ n`. -/ #check charted_space (euclidean_half_space 1) (Icc (0 : ℝ) 1) #check has_groupoid (Icc (0 : ℝ) 1) (times_cont_diff_groupoid ∞ (𝓡∂ 1)) #check smooth_manifold_with_corners (𝓡∂ 1) (Icc (0 : ℝ) 1) -- atlases are not maximal in general #check (times_cont_diff_groupoid ∞ (𝓡∂ 1)).maximal_atlas (Icc (0 : ℝ) 1) -- let's try to put a smooth manifold structure on the sphere -- (we don't have submanifolds yet, but it's coming in the near future) @[derive topological_space] definition sphere (n : ℕ) : Type := metric.sphere (0 : euclidean_space (fin (n+1))) 1 instance (n : ℕ) : has_coe (sphere n) (euclidean_space (fin (n+1))) := ⟨subtype.val⟩ instance (n : ℕ) : charted_space (euclidean_space (fin n)) (sphere n) := { atlas := begin sorry end, chart_at := begin sorry end, mem_chart_source := begin sorry end, chart_mem_atlas := begin sorry end } instance (n : ℕ) : smooth_manifold_with_corners (𝓡 n) (sphere n) := { compatible := begin assume e e' he he', sorry end } -- smooth functions def inc (n : ℕ) : sphere n → euclidean_space (fin (n+1)) := λ p : sphere n, (p : euclidean_space (fin (n+1))) lemma inc_smooth (n : ℕ) : times_cont_mdiff (𝓡 n) (𝓡 (n+1)) ∞ (inc n) := begin rw times_cont_mdiff_iff, split, { exact continuous_subtype_coe, }, { assume x y, sorry } end lemma inc_continuous (n : ℕ) : continuous (inc n) := (inc_smooth n).continuous lemma inc_mdifferentiable (n : ℕ) : mdifferentiable (𝓡 n) (𝓡 (n+1)) (inc n) := (inc_smooth n).mdifferentiable le_top -- tangent space and tangent bundles example (n : ℕ) (p : sphere n) (v : tangent_space (𝓡 n) p) : tangent_bundle (𝓡 n) (sphere n) := ⟨p, v⟩ -- tangent map, derivatives example (n : ℕ) : times_cont_mdiff ((𝓡 n).prod (𝓡 n)) ((𝓡 (n+1)).prod (𝓡 (n+1))) ∞ (tangent_map (𝓡 n) (𝓡 (n+1)) (inc n)) := (inc_smooth n).times_cont_mdiff_tangent_map le_top example (n : ℕ) (f : sphere n → sphere (n^2)) (p : sphere n) (v : tangent_space (𝓡 n) p) : mfderiv (𝓡 n) (𝓡 (n^2)) f p v = (tangent_map (𝓡 n) (𝓡 (n^2)) f ⟨p, v⟩).2 := rfl /- Can you express the sphere eversion theorem, i.e., the fact that there is a smooth isotopy of immersions between the canonical embedding of the sphere `S^2` and `ℝ^3`, and the antipodal embedding? Note that we haven't defined immersions in mathlib, but you can jut require that the fiber derivative is injective everywhere, which is easy to express if you know that the derivative of a function `f` from a manifold of dimension `2` to a manifold of dimension `3` at a point `x` is `mfderiv (𝓡 2) (𝓡 3) f x`. Don't forget to require the global smoothness of the map! You may need to know that the interval `[0,1]`, called `Icc (0 : ℝ) 1` in Lean, already has a manifold (with boundary!) structure, where the corresponding model with corners is called `𝓡∂ 1`. -/ theorem sphere_eversion : ∃ f : (Icc (0 : ℝ) 1) × sphere 2 → euclidean_space (fin 3), times_cont_mdiff ((𝓡∂ 1).prod (𝓡 2)) (𝓡 3) ∞ f ∧ ∀ (t : (Icc (0 : ℝ) 1)), ∀ (p : sphere 2), function.injective (mfderiv (𝓡 2) (𝓡 3) (f ∘ λ y, (t, y)) p) ∧ ∀ (p : sphere 2), f (0, p) = p ∧ ∀ (p : sphere 2), f (1, p) = - p := sorry /- Dicussing three (controversial?) design decisions #### Local homeos What is a local homeo `f` between an open subset of `E` and an open subset of `F`? 1) a map defined on a subtype: `f x` only makes sense for `x : f.source` 2) a map defined on the whole space `E`, but taking values in `option F = F ∪ {junk}`, with `f x = junk` when `x ∉ f.source` 3) a map defined on the whole space `E`, taking values in `F`, and we don't care about its values outside of `f.source`. Just like division by zero! But worse: * issue with 1): you keep intersecting chart domains. But the subtype `u ∩ v` is not the same as the subtype `v ∩ u`, so you keep adding casts everywhere * issue with 2): if you want to say that a chart is smooth, then you define to define smooth functions between `option E` and `option F` when `E` and `F` are vector spaces. All notions need to be redefined with `option`. * issue with 3): it works perfectly well, but it makes mathematicians unhappy/uneasy (and it is *not* equivalent to 1) or 2) when one of the spaces is empty) I picked 3) #### Tangent vectors What is a tangent vector (for a manifold `M` modelled on a vector space `E`)? 1) An equivalence class of germs of curves 2) A derivation 3) Physicist point of view: I don't know what a tangent vector is, but I know in charts. Mathematician's interpretation: equivalence class of `(e, v)` where `e` is a chart at `x`, `v` a vector in the vector space, and `(e, v) ∼ (e', v')` if `D(e' ∘ e ⁻¹) v = v'` 4) ... Issues: 1) Pictures are pretty, but this doesn't bring anything compared to 3) when you go down to details. And what about boundaries, where you can only have a half-curve 2) Need partitions of unity to show that this is local and coincides with the usual point of view. Doesn't work well in finite smoothness, nor in complex manifolds 3) Fine, works in all situations, but requires a lot of work to define the equivalence classes, the topology, check that the topology is compatible with the vector space structure, and so on. In a vector space, the tangent space is not defeq to the vector space itself 4) Pick one favorite chart at `x`, say `e_x`, and *define* the tangent space at `x` to be `E`, but "seen" in the chart `e_x` (this will show up in the definition of the derivative : the derivative of `f : M → M'` at `x` is defined to be the derivative of the map `e_{f x} ∘ f ∘ e_x⁻¹`). Works perfectly fine, but makes mathematicians unhappy/uneasy. (Axiom of choice? In fact we put the choice of `e_x` in the *definition* of charted spaces, so not further choice) I picked 4) #### Smooth functions in manifolds with boundary Usual definition of smooth functions in a half space: extend to a smooth function a little bit beyond the boundary, so one only really needs to speak of smooth functions in open subsets of vector spaces. When you define the derivative, you will need to check that it does not depend on the choice of the extension. Even worse when you want to define the tangent bundle: choose an open extension of your manifold with boundary, and then check that the restriction of the tangent bundle does not depend on the choice of the extension. Very easy when handwaving, nightmare to formalize. (What is the extension of the manifold with boundary? Another type?) Instead, if you define derivatives in (non-open) domains, you can talk of smooth functions in domains, and do everything without extending. Need to know this early enough: when starting to define derivatives, you should already think of manifolds with boundaries! That's what we did in mathlib. Difficulty: if a domain `s` is too small (think `s = ℝ ⊆ ℝ^2`), the values of `f` on `s` do not prescribe uniquely a derivative, so `fderiv_within_at ℝ f s x` may behave badly: derivative of a sum might be different from sum of derivatives, as there is an arbitrary choice to be made. This does not happen with the half-space, as it is large enough: derivatives within domains only work well if the tangent directions span the whole space. Predicate `unique_diff_on` for sets in vector spaces. You won't find this in books! -/ /-! ## Exercises -/ /-! ### Local homeomorphisms Local homeomorphisms are globally defined maps with a globally defined "inverse", but the only relevant set is the *source*, which should be mapped homeomorphically to the *target*. -/ /- Define a local homeomorphism from `ℝ` to `ℝ` which is just `x ↦ -x`, but on `(-1, 1)`. In Lean, the interval `(-1, 1)` is denoted by `Ioo (-1 : ℝ) 1` (where `o` stands for _open_). -/ -- set up a simple helper simp lemma to simplify our life later. @[simp] lemma neg_mem_Ioo_minus_one_one (x : ℝ) : -x ∈ Ioo (-1 : ℝ) 1 ↔ x ∈ Ioo (-1 : ℝ) 1 := begin sorry end def my_first_local_homeo : local_homeomorph ℝ ℝ := { to_fun := λ x, -x, inv_fun := λ x, -x, source := Ioo (-1) 1, target := sorry, map_source' := begin sorry end, map_target' := begin sorry end, left_inv' := begin sorry end, right_inv' := begin sorry end, open_source := sorry, open_target := sorry, continuous_to_fun := sorry, continuous_inv_fun := sorry } /- Two simple lemmas that will prove useful below. You can leave them sorried if you like. -/ lemma ne_3_of_mem_Ioo {x : ℝ} (h : x ∈ Ioo (-1 : ℝ) 1) : x ≠ 3 := begin sorry end lemma neg_ne_3_of_mem_Ioo {x : ℝ} (h : x ∈ Ioo (-1 : ℝ) 1) : -x ≠ 3 := begin sorry end /- Now, define a second local homeomorphism which is almost like the previous one. You may find the following lemma useful for `continuous_to_fun`: -/ #check continuous_on.congr def my_second_local_homeo : local_homeomorph ℝ ℝ := { to_fun := λ x, if x = 3 then 0 else - x, inv_fun := λ x, -x, source := Ioo (-1) 1, target := sorry, map_source' := sorry, map_target' := sorry, left_inv' := sorry, right_inv' := sorry, open_source := sorry, open_target := sorry, continuous_to_fun := begin sorry end, continuous_inv_fun := sorry } /- Although the two above local homeos are the same for all practical purposes as they coincide where relevant, they are not *equal*: -/ lemma my_first_local_homeo_ne_my_second_local_homeo : my_first_local_homeo ≠ my_second_local_homeo := begin sorry end /- The right equivalence relation for local homeos is not equality, but `eq_on_source`. Indeed, the two local homeos we have defined above coincide from this point of view. -/ #check local_homeomorph.eq_on_source lemma eq_on_source_my_first_local_homeo_my_second_local_homeo : local_homeomorph.eq_on_source my_first_local_homeo my_second_local_homeo := begin sorry end /-! ### An example of a charted space structure on `ℝ` A charted space is a topological space together with a set of local homeomorphisms to a model space, whose sources cover the whole space. For instance, `ℝ` is already endowed with a charted space structure with model space `ℝ`, where the unique chart is the identity: -/ #check charted_space_self ℝ /- For educational purposes only, we will put another charted space structure on `ℝ` using the local homeomorphisms we have constructed above. To avoid using too much structure of `ℝ` (and to avoid confusing Lean), we will work with a copy of `ℝ`, on which we will only register the topology. -/ @[derive topological_space] def myℝ : Type := ℝ instance : charted_space ℝ myℝ := { atlas := { local_homeomorph.refl ℝ, my_first_local_homeo }, chart_at := λ x, if x ∈ Ioo (-1 : ℝ) 1 then my_first_local_homeo else local_homeomorph.refl ℝ, mem_chart_source := begin sorry end, chart_mem_atlas := begin sorry end } /- Now come more interesting bits. We have endowed `myℝ` with a charted space structure, with charts taking values in `ℝ`. We want to say that this is a smooth structure, i.e., the changes of coordinates are smooth. In Lean, this is written with `has_groupoid`. A groupoid is a set of local homeomorphisms of the model space (for example, local homeos that are smooth on their domain). A charted space admits the groupoid as a structure groupoid if all the changes of coordinates belong to the groupoid. There is a difficulty that the definitions are set up to be able to also speak of smooth manifolds with boundary or with corners, so the name of the smooth groupoid on `ℝ` has the slightly strange name `times_cont_diff_groupoid ∞ (model_with_corners_self ℝ ℝ)`. To avoid typing again and again `model_with_corners_self ℝ ℝ`, let us introduce a shortcut -/ abbreviation 𝓡1 := model_with_corners_self ℝ ℝ /- In the library, there are such shortcuts for manifolds modelled on `ℝ^n`, denoted with `𝓡 n`, but for `n = 1` this does not coincide with the above one, as `ℝ^1` (a.k.a. `fin 1 → ℝ`) is not the same as `ℝ`! Still, since they are of the same nature, the notation we have just introduced is very close, compare `𝓡1` with `𝓡 1` (and try not to get confused): -/ instance : has_groupoid myℝ (times_cont_diff_groupoid ∞ 𝓡1) := begin -- in theory, we should prove that all compositions of charts are diffeos, i.e., they are smooth -- and their inverse are smooth. For symmetry reasons, it suffices to check one direction apply has_groupoid_of_pregroupoid, -- take two charts `e` and `e'` assume e e' he he', -- if next line is a little bit slow for your taste, you can replace `simp` with `squeeze_simp` -- and then follow the advice simp [atlas] at he he', dsimp, -- to continue, some hints: -- (1) don't hesitate to use the fact that the restriction of a smooth function to a -- subset is still smooth there (`times_cont_diff.times_cont_diff_on`) -- (2) hopefully, there is a theorem saying that the negation function is smooth. -- you can either try to guess its name, or hope that `suggest` will help you there. sorry end /- The statement of the previous instance is not very readable. There is a shortcut notation: -/ instance : smooth_manifold_with_corners 𝓡1 myℝ := {} /- We will now study a very simple map from `myℝ` to `ℝ`, the identity. -/ def my_map : myℝ → ℝ := λ x, x /- The map `my_map` is a map going from the type `myℝ` to the type `ℝ`. From the point of view of the kernel of Lean, it is just the identity, but from the point of view of structures on `myℝ` and `ℝ` it might not be trivial, as we have registered different instances on these two types. -/ /- The continuity should be trivial, as the topologies on `myℝ` and `ℝ` are definitionally the same. So `continuous_id` might help. -/ lemma continuous_my_map : continuous my_map := sorry /- Smoothness should not be obvious, though, as the manifold structures are not the same: the atlas on `myℝ` has two elements, while the atlas on `ℝ` has one single element. Note that `myℝ` is not a vector space, nor a normed space, so one can not ask whether `my_map` is smooth in the usual sense (as a map between vector spaces): -/ -- lemma times_cont_diff_my_map : times_cont_diff ℝ ∞ my_map := sorry /- does not make sense (try uncommenting it!) However, we can ask whether `my_map` is a smooth map between manifolds, i.e., whether it is smooth when read in the charts. When we mention the smoothness of a map, we should always specify explicitly the model with corners we are using, because there might be several around (think of a complex manifold that you may want to consider as a real manifold, to talk about functions which are real-smooth but not holomorphic) -/ lemma times_cont_mdiff_my_map : times_cont_mdiff 𝓡1 𝓡1 ∞ my_map := begin -- put things in a nicer form. The simpset `mfld_simps` registers many simplification rules for -- manifolds. `simp` is used heavily in manifold files to bring everything into manageable form. rw times_cont_mdiff_iff, simp only [continuous_my_map] with mfld_simps, -- simp has erased the chart in the target, as it knows that the only chart in the manifold `ℝ` -- is the identity. assume x y, sorry end /- Now, let's go to tangent bundles. We have a smooth manifold, so its tangent bundle should also be a smooth manifold. -/ -- the type `tangent_bundle I myℝ` makes sense #check tangent_bundle 𝓡1 myℝ /- The tangent space above a point of `myℝ` is just a one-dimensional vector space (identified with `ℝ`). So, one can prescribe an element of the tangent bundle as a pair (more on this below) -/ example : tangent_bundle 𝓡1 myℝ := ((4 : ℝ), 0) /- Construct the smooth manifold structure on the tangent bundle. Hint: the answer is a one-liner, and this instance is not really needed. -/ instance tangent_bundle_myℝ : smooth_manifold_with_corners (𝓡1.prod 𝓡1) (tangent_bundle 𝓡1 myℝ) := sorry /- NB: the model space for the tangent bundle to a product manifold or a tangent space is not `ℝ × ℝ`, but a copy called `model_prod ℝ ℝ`. Otherwise, `ℝ × ℝ` would have two charted space structures with model `ℝ × ℝ`, the identity one and the product one, which are not definitionally equal. And this would be bad. -/ #check tangent_bundle.charted_space 𝓡1 myℝ /- A smooth map between manifolds induces a map between their tangent bundles. In `mathlib` this is called the `tangent_map` (you might instead know it as the "differential" or "pushforward" of the map). Let us check that the `tangent_map` of `my_map` is smooth. -/ lemma times_cont_mdiff_tangent_map_my_map : times_cont_mdiff (𝓡1.prod 𝓡1) (𝓡1.prod 𝓡1) ∞ (tangent_map 𝓡1 𝓡1 my_map) := begin -- hopefully, there is a theorem providing the general result, i.e. the tangent map to a smooth -- map is smooth. -- you can either try to guess its name, or hope that `suggest` will help you there. sorry end /- (Harder question) Can you show that this tangent bundle is homeomorphic to `ℝ × ℝ`? You could try to build the homeomorphism by hand, using `tangent_map I I my_map` in one direction and a similar map in the other direction, but it is probably more efficient to use one of the charts of the tangent bundle. Remember, the model space for `tangent_bundle I myℝ` is `model_prod ℝ ℝ`, not `ℝ × ℝ`. But the topologies on `model_prod ℝ ℝ` and `ℝ × ℝ` are the same, so it is by definition good enough to construct a homeomorphism with `model_prod ℝ ℝ`. -/ def my_homeo : tangent_bundle 𝓡1 myℝ ≃ₜ (ℝ × ℝ) := begin sorry end /- Up to now, we have never used the definition of the tangent bundle, and this corresponds to the usual mathematical practice: one doesn't care if the tangent space is defined using germs of curves, or spaces of derivations, or whatever equivalent definition. Instead, one relies all the time on functoriality (i.e., a smooth map has a well defined derivative, and they compose well, together with the fact that the tangent bundle to a vector space is the product). If you want to know more about the internals of the tangent bundle in mathlib, you can browse through the next section, but it is maybe wiser to skip it on first reading, as it is not needed to use the library -/ section you_should_probably_skip_this /- If `M` is a manifold modelled on a vector space `E`, then the underlying type for the tangent bundle is just `M × E` -/ lemma tangent_bundle_myℝ_is_prod : tangent_bundle 𝓡1 myℝ = (myℝ × ℝ) := sorry /- This means that you can specify a point in the tangent bundle as a pair `(x, y)`. However, in general, a tangent bundle is not trivial: the topology on `tangent_bundle I myℝ` is *not* the product topology. Instead, the tangent space at a point `x` is identified with `ℝ` through some preferred chart at `x`, called `chart_at ℝ x`, but the way they are glued together depends on the manifold and the charts. In vector spaces, the tangent space is canonically the product space, with the same topology, as there is only one chart so there is no strange gluing at play. The equality of the topologies is given in `tangent_bundle_model_space_topology_eq_prod`, but they are not definitionally equal so one can get strange behavior if abusing identifications. Let us register the identification explicitly, as a homeomorphism: -/ def tangent_bundle_vector_space_triv (E : Type u) [normed_group E] [normed_space ℝ E] : tangent_bundle (model_with_corners_self ℝ E) E ≃ₜ E × E := { to_fun := id, inv_fun := id, left_inv := sorry, right_inv := sorry, continuous_to_fun := begin -- if you think that `continuous_id` should work but `exact continuous_id` fails, you -- can try `convert continuous_id`: it might show you what doesn't match and let you -- fix it afterwards. sorry end, continuous_inv_fun := begin sorry end } /- Even though the tangent bundle to `myℝ` is trivial abstractly, with this construction the tangent bundle is *not* the product space with the product topology, as we have used various charts so the gluing is not trivial. The following exercise unfolds the definition to see what is going on. It is not a reasonable exercise, in the sense that one should never ever do this when working with a manifold! -/ lemma crazy_formula_after_identifications (x : ℝ) (v : ℝ) : let p : tangent_bundle 𝓡1 myℝ := ((3 : ℝ), 0) in chart_at (model_prod ℝ ℝ) p (x, v) = if x ∈ Ioo (-1 : ℝ) 1 then (x, -v) else (x, v) := begin -- this exercise is not easy (and shouldn't be: you are not supposed to use the library like this!) -- if you really want to do this, you should unfold as much as you can using simp and dsimp, until you -- are left with a statement speaking of derivatives of real functions, without any manifold code left. sorry end end you_should_probably_skip_this /-! ### The language of manifolds In this paragraph, we will try to write down interesting statements of theorems, without proving them. The goal here is that Lean should not complain on the statement, but the proof should be sorried. -/ /- Here is a first example, already filled up, to show you how diffeomorphisms are currently named (we will probably introduce an abbreviation, but this hasn't been done yet). Don't try to fill the sorried proof! -/ /-- Two zero-dimensional connected manifolds are diffeomorphic. -/ theorem diffeomorph_of_zero_dim_connected (M M' : Type*) [topological_space M] [topological_space M'] [charted_space (euclidean_space (fin 0)) M] [charted_space (euclidean_space (fin 0)) M'] [connected_space M] [connected_space M'] : nonempty (structomorph (times_cont_diff_groupoid ∞ (𝓡 0)) M M') := sorry /- Do you think that this statement is correct? (note that we have not assumed that our manifolds are smooth, nor that they are separated, but this is maybe automatic in zero dimension). Now, write down a version of this theorem in dimension 1, replacing the first sorry with meaningful content (and adding what is needed before the colon). Don't try to fill the sorried proof! -/ /-- Two one-dimensional smooth compact connected manifolds are diffeomorphic. -/ theorem diffeomorph_of_one_dim_compact_connected : sorry := sorry /- You will definitely need to require smoothness and separation in this case, as it is wrong otherwise. Note that Lean won't complain if you don't put these assumptions, as the theorem would still make sense, but it would just turn out to be wrong. The previous statement is not really satisfactory: we would instead like to express that any such manifold is diffeomorphic to the circle. The trouble is that we don't have the circle as a smooth manifold yet. Since we have cheated and introduced it (with sorries) at the beginning of the tutorial, let's cheat again and use it to reformulate the previous statement. -/ -- the next result is not trivial, leave it sorried (but you can work on it if you don't like -- manifolds and prefer topology -- then please PR it to mathlib!). instance connected_sphere (n : ℕ) : connected_space (sphere (n+1)) := sorry /- The next two instances are easier to prove, you can prove them or leave them sorried as you like. For the second one, you may need to use facts of the library such as -/ #check compact_iff_compact_space #check metric.compact_iff_closed_bounded instance (n : ℕ) : t2_space (sphere n) := begin sorry end instance (n : ℕ) : compact_space (sphere n) := begin sorry end /- Now, you can prove that any one-dimensional compact connected manifold is diffeomorphic to the circle. Here, you should fill the `sorry` (but luckily you may use `diffeomorph_of_one_dim_compact_connected`). -/ theorem diffeomorph_circle_of_one_dim_compact_connected (M : Type*) [topological_space M] [charted_space (euclidean_space (fin 1)) M] [connected_space M] [compact_space M] [t2_space M] [smooth_manifold_with_corners (𝓡 1) M] : nonempty (structomorph (times_cont_diff_groupoid ∞ (𝓡 1)) M (sphere 1)) := sorry /- What about trying to say that there are uncountably many different smooth structures on `ℝ⁴`? (see https://en.wikipedia.org/wiki/Exotic_R4). The library is not really designed with this in mind, as in general we only work with one differentiable structure on a space, but it is perfectly capable of expressing this fact if one uses the `@` version of some definitions. Don't try to fill the sorried proof! -/ theorem exotic_ℝ4 : sorry := sorry /-! ### Smooth functions on `[0, 1]` In this paragraph, you will prove several (math-trivial but Lean-nontrivial) statements on the smooth structure of `[0,1]`. These facts should be Lean-trivial, but they are not (yet) since there is essentially nothing in this direction for now in the library. The goal is as much to be able to write the statements as to prove them. Most of the necessary vocabulary has been introduced above, so don't hesitate to browse the file if you are stuck. Additionally, you will need the notion of a smooth function on a subset: it is `times_cont_diff_on` for functions between vector spaces and `times_cont_mdiff_on` for functions between manifolds. Lemma times_cont_mdiff_g : the inclusion `g` of `[0, 1]` in `ℝ` is smooth. Lemma msmooth_of_smooth : Consider a function `f : ℝ → [0, 1]`, which is smooth in the usual sense as a function from `ℝ` to `ℝ` on a set `s`. Then it is manifold-smooth on `s`. Definition : construct a function `f` from `ℝ` to `[0,1]` which is the identity on `[0, 1]`. Theorem : the tangent bundle to `[0, 1]` is homeomorphic to `[0, 1] × ℝ` Hint for Theorem 4: don't try to unfold the definition of the tangent bundle, it will only get you into trouble. Instead, use the derivatives of the maps `f` and `g`, and rely on functoriality to check that they are inverse to each other. (This advice is slightly misleading as these derivatives do not go between the right spaces, so you will need to massage them a little bit). A global advice: don't hesitate to use and abuse `simp`, it is the main workhorse in this area of mathlib. -/ /- After doing the exercise myself, I realized it was (way!) too hard. So I will give at least the statements of the lemmas, to guide you a little bit more. To let you try the original version if you want, I have left a big blank space to avoid spoilers. -/ def g : Icc (0 : ℝ) 1 → ℝ := subtype.val -- smoothness results for `euclidean_space` are expressed for general `L^p` spaces -- (as `euclidean_space` has the `L^2` norm), in: #check pi_Lp.times_cont_diff_coord #check pi_Lp.times_cont_diff_on_iff_coord lemma times_cont_mdiff_g : times_cont_mdiff (𝓡∂ 1) 𝓡1 ∞ g := begin sorry end lemma msmooth_of_smooth {f : ℝ → Icc (0 : ℝ) 1} {s : set ℝ} (h : times_cont_diff_on ℝ ∞ (λ x, (f x : ℝ)) s) : times_cont_mdiff_on 𝓡1 (𝓡∂ 1) ∞ f s := begin sorry end /- A function from `ℝ` to `[0,1]` which is the identity on `[0,1]`. -/ def f : ℝ → Icc (0 : ℝ) 1 := λ x, ⟨max (min x 1) 0, by simp [le_refl, zero_le_one]⟩ lemma times_cont_mdiff_on_f : times_cont_mdiff_on 𝓡1 (𝓡∂ 1) ∞ f (Icc 0 1) := begin sorry end lemma fog : f ∘ g = id := begin sorry end lemma gof : ∀ x ∈ Icc (0 : ℝ) 1, g (f x) = x := begin sorry end def G : tangent_bundle (𝓡∂ 1) (Icc (0 : ℝ) 1) → (Icc (0 : ℝ) 1) × ℝ := λ p, (p.1, (tangent_map (𝓡∂ 1) 𝓡1 g p).2) lemma continuous_G : continuous G := begin sorry end /- in the definition of `F`, we use the map `tangent_bundle_vector_space_triv` (which is just the identity pointwise) to make sure that Lean is not lost between the different topologies. -/ def F : (Icc (0 : ℝ) 1) × ℝ → tangent_bundle (𝓡∂ 1) (Icc (0 : ℝ) 1) := λ p, tangent_map_within 𝓡1 (𝓡∂ 1) f (Icc 0 1) ((tangent_bundle_vector_space_triv ℝ).symm (p.1, p.2)) lemma continuous_F : continuous F := begin sorry end lemma FoG : F ∘ G = id := begin sorry end lemma GoF : G ∘ F = id := begin sorry end def my_tangent_homeo : tangent_bundle (𝓡∂ 1) (Icc (0 : ℝ) 1) ≃ₜ (Icc (0 : ℝ) 1) × ℝ := sorry /-! ### Further things to do 1) can you prove `diffeomorph_of_zero_dim_connected` or `connected_sphere`? 2) Try to express and then prove the local inverse theorem in real manifolds: if a map between real manifolds (without boundary, modelled on a complete vector space) is smooth, then it is a local homeomorphism around each point. We already have versions of this statement in mathlib for functions between vector spaces, but this is very much a work in progress. 3) What about trying to prove `diffeomorph_of_one_dim_compact_connected`? (I am not sure mathlib is ready for this, as the proofs I am thinking of are currently a little bit too high-powered. If you manage to do it, you should absolutely PR it!) 4) Why not contribute to the proof of `sphere_eversion`? You can have a look at https://leanprover-community.github.io/sphere-eversion/ to learn more about this project by Patrick Massot. -/
1ac334bee581869c7a0275d358d0282df5095aa7
aa2345b30d710f7e75f13157a35845ee6d48c017
/data/nat/basic.lean
0287ab3e36f8d1ce69260911dd3221ccf6e0364e
[ "Apache-2.0" ]
permissive
CohenCyril/mathlib
5241b20a3fd0ac0133e48e618a5fb7761ca7dcbe
a12d5a192f5923016752f638d19fc1a51610f163
refs/heads/master
1,586,031,957,957
1,541,432,824,000
1,541,432,824,000
156,246,337
0
0
Apache-2.0
1,541,434,514,000
1,541,434,513,000
null
UTF-8
Lean
false
false
31,081
lean
/- Copyright (c) 2014 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Leonardo de Moura, Jeremy Avigad, Mario Carneiro Basic operations on the natural numbers. -/ import logic.basic algebra.ordered_ring data.option universe u namespace nat variables {m n k : ℕ} theorem succ_inj' {n m : ℕ} : succ n = succ m ↔ n = m := ⟨succ_inj, congr_arg _⟩ theorem succ_le_succ_iff {m n : ℕ} : succ m ≤ succ n ↔ m ≤ n := ⟨le_of_succ_le_succ, succ_le_succ⟩ theorem lt_succ_iff {m n : ℕ} : m < succ n ↔ m ≤ n := succ_le_succ_iff lemma succ_le_iff {m n : ℕ} : succ m ≤ n ↔ m < n := ⟨lt_of_succ_le, succ_le_of_lt⟩ theorem pred_eq_of_eq_succ {m n : ℕ} (H : m = n.succ) : m.pred = n := by simp [H] theorem pred_sub (n m : ℕ) : pred n - m = pred (n - m) := by rw [← sub_one, nat.sub_sub, one_add]; refl lemma pred_eq_sub_one (n : ℕ) : pred n = n - 1 := rfl theorem pos_iff_ne_zero : n > 0 ↔ n ≠ 0 := ⟨ne_of_gt, nat.pos_of_ne_zero⟩ theorem pos_iff_ne_zero' : 0 < n ↔ n ≠ 0 := pos_iff_ne_zero theorem eq_of_lt_succ_of_not_lt {a b : ℕ} (h1 : a < b + 1) (h2 : ¬ a < b) : a = b := have h3 : a ≤ b, from le_of_lt_succ h1, or.elim (eq_or_lt_of_not_lt h2) (λ h, h) (λ h, absurd h (not_lt_of_ge h3)) protected theorem le_sub_add (n m : ℕ) : n ≤ n - m + m := or.elim (le_total n m) (assume : n ≤ m, begin rw [sub_eq_zero_of_le this, zero_add], exact this end) (assume : m ≤ n, begin rw (nat.sub_add_cancel this) end) theorem sub_add_eq_max (n m : ℕ) : n - m + m = max n m := eq_max (nat.le_sub_add _ _) (le_add_left _ _) $ λ k h₁ h₂, by rw ← nat.sub_add_cancel h₂; exact add_le_add_right (nat.sub_le_sub_right h₁ _) _ theorem sub_add_min (n m : ℕ) : n - m + min n m = n := (le_total n m).elim (λ h, by rw [min_eq_left h, sub_eq_zero_of_le h, zero_add]) (λ h, by rw [min_eq_right h, nat.sub_add_cancel h]) protected theorem add_sub_cancel' {n m : ℕ} (h : n ≥ m) : m + (n - m) = n := by rw [add_comm, nat.sub_add_cancel h] protected theorem sub_eq_of_eq_add (h : k = m + n) : k - m = n := begin rw [h, nat.add_sub_cancel_left] end theorem sub_min (n m : ℕ) : n - min n m = n - m := nat.sub_eq_of_eq_add $ by rw [add_comm, sub_add_min] protected theorem lt_of_sub_pos (h : n - m > 0) : m < n := lt_of_not_ge (assume : m ≥ n, have n - m = 0, from sub_eq_zero_of_le this, begin rw this at h, exact lt_irrefl _ h end) protected theorem lt_of_sub_lt_sub_right : m - k < n - k → m < n := lt_imp_lt_of_le_imp_le (λ h, nat.sub_le_sub_right h _) protected theorem lt_of_sub_lt_sub_left : m - n < m - k → k < n := lt_imp_lt_of_le_imp_le (nat.sub_le_sub_left _) protected theorem sub_lt_self (h₁ : m > 0) (h₂ : n > 0) : m - n < m := calc m - n = succ (pred m) - succ (pred n) : by rw [succ_pred_eq_of_pos h₁, succ_pred_eq_of_pos h₂] ... = pred m - pred n : by rw succ_sub_succ ... ≤ pred m : sub_le _ _ ... < succ (pred m) : lt_succ_self _ ... = m : succ_pred_eq_of_pos h₁ protected theorem le_sub_right_of_add_le (h : m + k ≤ n) : m ≤ n - k := by rw ← nat.add_sub_cancel m k; exact nat.sub_le_sub_right h k protected theorem le_sub_left_of_add_le (h : k + m ≤ n) : m ≤ n - k := nat.le_sub_right_of_add_le (by rwa add_comm at h) protected theorem lt_sub_right_of_add_lt (h : m + k < n) : m < n - k := lt_of_succ_le $ nat.le_sub_right_of_add_le $ by rw succ_add; exact succ_le_of_lt h protected theorem lt_sub_left_of_add_lt (h : k + m < n) : m < n - k := nat.lt_sub_right_of_add_lt (by rwa add_comm at h) protected theorem add_lt_of_lt_sub_right (h : m < n - k) : m + k < n := @nat.lt_of_sub_lt_sub_right _ _ k (by rwa nat.add_sub_cancel) protected theorem add_lt_of_lt_sub_left (h : m < n - k) : k + m < n := by rw add_comm; exact nat.add_lt_of_lt_sub_right h protected theorem le_add_of_sub_le_right : n - k ≤ m → n ≤ m + k := le_imp_le_of_lt_imp_lt nat.lt_sub_right_of_add_lt protected theorem le_add_of_sub_le_left : n - k ≤ m → n ≤ k + m := le_imp_le_of_lt_imp_lt nat.lt_sub_left_of_add_lt protected theorem lt_add_of_sub_lt_right : n - k < m → n < m + k := lt_imp_lt_of_le_imp_le nat.le_sub_right_of_add_le protected theorem lt_add_of_sub_lt_left : n - k < m → n < k + m := lt_imp_lt_of_le_imp_le nat.le_sub_left_of_add_le protected theorem sub_le_left_of_le_add : n ≤ k + m → n - k ≤ m := le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_left protected theorem sub_le_right_of_le_add : n ≤ m + k → n - k ≤ m := le_imp_le_of_lt_imp_lt nat.add_lt_of_lt_sub_right protected theorem sub_lt_left_iff_lt_add (H : n ≤ k) : k - n < m ↔ k < n + m := ⟨nat.lt_add_of_sub_lt_left, λ h₁, have succ k ≤ n + m, from succ_le_of_lt h₁, have succ (k - n) ≤ m, from calc succ (k - n) = succ k - n : by rw (succ_sub H) ... ≤ n + m - n : nat.sub_le_sub_right this n ... = m : by rw nat.add_sub_cancel_left, lt_of_succ_le this⟩ protected theorem le_sub_left_iff_add_le (H : m ≤ k) : n ≤ k - m ↔ m + n ≤ k := le_iff_le_iff_lt_iff_lt.2 (nat.sub_lt_left_iff_lt_add H) protected theorem le_sub_right_iff_add_le (H : n ≤ k) : m ≤ k - n ↔ m + n ≤ k := by rw [nat.le_sub_left_iff_add_le H, add_comm] protected theorem lt_sub_left_iff_add_lt : n < k - m ↔ m + n < k := ⟨nat.add_lt_of_lt_sub_left, nat.lt_sub_left_of_add_lt⟩ protected theorem lt_sub_right_iff_add_lt : m < k - n ↔ m + n < k := by rw [nat.lt_sub_left_iff_add_lt, add_comm] theorem sub_le_left_iff_le_add : m - n ≤ k ↔ m ≤ n + k := le_iff_le_iff_lt_iff_lt.2 nat.lt_sub_left_iff_add_lt theorem sub_le_right_iff_le_add : m - k ≤ n ↔ m ≤ n + k := by rw [nat.sub_le_left_iff_le_add, add_comm] protected theorem sub_lt_right_iff_lt_add (H : k ≤ m) : m - k < n ↔ m < n + k := by rw [nat.sub_lt_left_iff_lt_add H, add_comm] protected theorem sub_le_sub_left_iff (H : k ≤ m) : m - n ≤ m - k ↔ k ≤ n := ⟨λ h, have k + (m - k) - n ≤ m - k, by rwa nat.add_sub_cancel' H, nat.le_of_add_le_add_right (nat.le_add_of_sub_le_left this), nat.sub_le_sub_left _⟩ protected theorem sub_lt_sub_right_iff (H : k ≤ m) : m - k < n - k ↔ m < n := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_right_iff _ _ _ H) protected theorem sub_lt_sub_left_iff (H : n ≤ m) : m - n < m - k ↔ k < n := lt_iff_lt_of_le_iff_le (nat.sub_le_sub_left_iff H) protected theorem sub_le_iff : m - n ≤ k ↔ m - k ≤ n := nat.sub_le_left_iff_le_add.trans nat.sub_le_right_iff_le_add.symm protected lemma sub_le_self (n m : ℕ) : n - m ≤ n := nat.sub_le_left_of_le_add (nat.le_add_left _ _) protected theorem sub_lt_iff (h₁ : n ≤ m) (h₂ : k ≤ m) : m - n < k ↔ m - k < n := (nat.sub_lt_left_iff_lt_add h₁).trans (nat.sub_lt_right_iff_lt_add h₂).symm lemma pred_le_iff {n m : ℕ} : pred n ≤ m ↔ n ≤ succ m := @nat.sub_le_right_iff_le_add n m 1 lemma lt_pred_iff {n m : ℕ} : n < pred m ↔ succ n < m := @nat.lt_sub_right_iff_add_lt n 1 m protected theorem mul_ne_zero {n m : ℕ} (n0 : n ≠ 0) (m0 : m ≠ 0) : n * m ≠ 0 | nm := (eq_zero_of_mul_eq_zero nm).elim n0 m0 @[simp] protected theorem mul_eq_zero {a b : ℕ} : a * b = 0 ↔ a = 0 ∨ b = 0 := iff.intro eq_zero_of_mul_eq_zero (by simp [or_imp_distrib] {contextual := tt}) @[simp] protected theorem zero_eq_mul {a b : ℕ} : 0 = a * b ↔ a = 0 ∨ b = 0 := by rw [eq_comm, nat.mul_eq_zero] @[elab_as_eliminator] protected def strong_rec' {p : ℕ → Sort u} (H : ∀ n, (∀ m, m < n → p m) → p n) : ∀ (n : ℕ), p n | n := H n (λ m hm, strong_rec' m) attribute [simp] nat.div_self protected lemma div_le_of_le_mul' {m n : ℕ} {k} (h : m ≤ k * n) : m / k ≤ n := (eq_zero_or_pos k).elim (λ k0, by rw [k0, nat.div_zero]; apply zero_le) (λ k0, (decidable.mul_le_mul_left k0).1 $ calc k * (m / k) ≤ m % k + k * (m / k) : le_add_left _ _ ... = m : mod_add_div _ _ ... ≤ k * n : h) protected lemma div_le_self' (m n : ℕ) : m / n ≤ m := (eq_zero_or_pos n).elim (λ n0, by rw [n0, nat.div_zero]; apply zero_le) (λ n0, nat.div_le_of_le_mul' $ calc m = 1 * m : (one_mul _).symm ... ≤ n * m : mul_le_mul_right _ n0) theorem le_div_iff_mul_le' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x ≤ y / k ↔ x * k ≤ y := begin revert x, refine nat.strong_rec' _ y, clear y, intros y IH x, cases decidable.lt_or_le y k with h h, { rw [div_eq_of_lt h], cases x with x, { simp [zero_mul, zero_le] }, { rw succ_mul, exact iff_of_false (not_succ_le_zero _) (not_le_of_lt $ lt_of_lt_of_le h (le_add_left _ _)) } }, { rw [div_eq_sub_div k0 h], cases x with x, { simp [zero_mul, zero_le] }, { rw [← add_one, nat.add_le_add_iff_le_right, succ_mul, IH _ (sub_lt_of_pos_le _ _ k0 h), add_le_to_le_sub _ h] } } end theorem div_mul_le_self' (m n : ℕ) : m / n * n ≤ m := (nat.eq_zero_or_pos n).elim (λ n0, by simp [n0, zero_le]) $ λ n0, (le_div_iff_mul_le' n0).1 (le_refl _) theorem div_lt_iff_lt_mul' {x y : ℕ} {k : ℕ} (k0 : 0 < k) : x / k < y ↔ x < y * k := lt_iff_lt_of_le_iff_le $ le_div_iff_mul_le' k0 protected theorem div_le_div_right {n m : ℕ} (h : n ≤ m) {k : ℕ} : n / k ≤ m / k := (nat.eq_zero_or_pos k).elim (λ k0, by simp [k0]) $ λ hk, (le_div_iff_mul_le' hk).2 $ le_trans (nat.div_mul_le_self' _ _) h protected theorem eq_mul_of_div_eq_right {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = b * c := by rw [← H2, nat.mul_div_cancel' H1] protected theorem div_eq_iff_eq_mul_right {a b c : ℕ} (H : b > 0) (H' : b ∣ a) : a / b = c ↔ a = b * c := ⟨nat.eq_mul_of_div_eq_right H', nat.div_eq_of_eq_mul_right H⟩ protected theorem div_eq_iff_eq_mul_left {a b c : ℕ} (H : b > 0) (H' : b ∣ a) : a / b = c ↔ a = c * b := by rw mul_comm; exact nat.div_eq_iff_eq_mul_right H H' protected theorem eq_mul_of_div_eq_left {a b c : ℕ} (H1 : b ∣ a) (H2 : a / b = c) : a = c * b := by rw [mul_comm, nat.eq_mul_of_div_eq_right H1 H2] protected theorem mul_div_cancel_left' {a b : ℕ} (Hd : a ∣ b) : a * (b / a) = b := by rw [mul_comm,nat.div_mul_cancel Hd] protected theorem div_mod_unique {n k m d : ℕ} (h : 0 < k) : n / k = d ∧ n % k = m ↔ m + k * d = n ∧ m < k := ⟨λ ⟨e₁, e₂⟩, e₁ ▸ e₂ ▸ ⟨mod_add_div _ _, mod_lt _ h⟩, λ ⟨h₁, h₂⟩, h₁ ▸ by rw [add_mul_div_left _ _ h, add_mul_mod_self_left]; simp [div_eq_of_lt, mod_eq_of_lt, h₂]⟩ lemma two_mul_odd_div_two {n : ℕ} (hn : n % 2 = 1) : 2 * (n / 2) = n - 1 := by conv {to_rhs, rw [← nat.mod_add_div n 2, hn, nat.add_sub_cancel_left]} lemma div_dvd_of_dvd {a b : ℕ} (h : b ∣ a) : (a / b) ∣ a := ⟨b, (nat.div_mul_cancel h).symm⟩ protected lemma div_pos {a b : ℕ} (hba : b ≤ a) (hb : 0 < b) : 0 < a / b := nat.pos_of_ne_zero (λ h, lt_irrefl a (calc a = a % b : by simpa [h] using (mod_add_div a b).symm ... < b : nat.mod_lt a hb ... ≤ a : hba)) protected theorem mul_right_inj {a b c : ℕ} (ha : a > 0) : b * a = c * a ↔ b = c := ⟨nat.eq_of_mul_eq_mul_right ha, λ e, e ▸ rfl⟩ protected theorem mul_left_inj {a b c : ℕ} (ha : a > 0) : a * b = a * c ↔ b = c := ⟨nat.eq_of_mul_eq_mul_left ha, λ e, e ▸ rfl⟩ protected lemma div_div_self : ∀ {a b : ℕ}, b ∣ a → 0 < a → a / (a / b) = b | a 0 h₁ h₂ := by rw eq_zero_of_zero_dvd h₁; refl | 0 b h₁ h₂ := absurd h₂ dec_trivial | (a+1) (b+1) h₁ h₂ := (nat.mul_right_inj (nat.div_pos (le_of_dvd (succ_pos a) h₁) (succ_pos b))).1 $ by rw [nat.div_mul_cancel (div_dvd_of_dvd h₁), nat.mul_div_cancel' h₁] protected lemma div_lt_of_lt_mul {m n k : ℕ} (h : m < n * k) : m / n < k := lt_of_mul_lt_mul_left (calc n * (m / n) ≤ m % n + n * (m / n) : nat.le_add_left _ _ ... = m : mod_add_div _ _ ... < n * k : h) (nat.zero_le n) protected lemma div_eq_zero_iff {a b : ℕ} (hb : 0 < b) : a / b = 0 ↔ a < b := ⟨λ h, by rw [← mod_add_div a b, h, mul_zero, add_zero]; exact mod_lt _ hb, λ h, by rw [← nat.mul_left_inj hb, ← @add_left_cancel_iff _ _ (a % b), mod_add_div, mod_eq_of_lt h, mul_zero, add_zero]⟩ lemma mod_mul_right_div_self (a b c : ℕ) : a % (b * c) / b = (a / b) % c := if hb : b = 0 then by simp [hb] else if hc : c = 0 then by simp [hc] else by conv {to_rhs, rw ← mod_add_div a (b * c)}; rw [mul_assoc, nat.add_mul_div_left _ _ (nat.pos_of_ne_zero hb), add_mul_mod_self_left, mod_eq_of_lt (nat.div_lt_of_lt_mul (mod_lt _ (mul_pos (nat.pos_of_ne_zero hb) (nat.pos_of_ne_zero hc))))] lemma mod_mul_left_div_self (a b c : ℕ) : a % (c * b) / b = (a / b) % c := by rw [mul_comm c, mod_mul_right_div_self] @[simp] protected theorem dvd_one {n : ℕ} : n ∣ 1 ↔ n = 1 := ⟨eq_one_of_dvd_one, λ e, e.symm ▸ dvd_refl _⟩ protected theorem dvd_add_left {k m n : ℕ} (h : k ∣ n) : k ∣ m + n ↔ k ∣ m := (nat.dvd_add_iff_left h).symm protected theorem dvd_add_right {k m n : ℕ} (h : k ∣ m) : k ∣ m + n ↔ k ∣ n := (nat.dvd_add_iff_right h).symm protected 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, nat.mul_left_inj ha] protected 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, nat.mul_right_inj hc] @[simp] theorem mod_mod (a n : ℕ) : (a % n) % n = a % n := (eq_zero_or_pos n).elim (λ n0, by simp [n0]) (λ npos, mod_eq_of_lt (mod_lt _ npos)) theorem add_pos_left {m : ℕ} (h : m > 0) (n : ℕ) : m + n > 0 := calc m + n > 0 + n : nat.add_lt_add_right h n ... = n : nat.zero_add n ... ≥ 0 : zero_le n theorem add_pos_right (m : ℕ) {n : ℕ} (h : n > 0) : m + n > 0 := begin rw add_comm, exact add_pos_left h m end theorem add_pos_iff_pos_or_pos (m n : ℕ) : m + n > 0 ↔ m > 0 ∨ n > 0 := iff.intro begin intro h, cases m with m, {simp [zero_add] at h, exact or.inr h}, exact or.inl (succ_pos _) end begin intro h, cases h with mpos npos, { apply add_pos_left mpos }, apply add_pos_right _ npos end lemma lt_succ_iff_lt_or_eq {n i : ℕ} : n < i.succ ↔ (n < i ∨ n = i) := lt_succ_iff.trans le_iff_lt_or_eq theorem le_zero_iff {i : ℕ} : i ≤ 0 ↔ i = 0 := ⟨nat.eq_zero_of_le_zero, assume h, h ▸ le_refl i⟩ theorem le_add_one_iff {i j : ℕ} : i ≤ j + 1 ↔ (i ≤ j ∨ i = j + 1) := ⟨assume h, match nat.eq_or_lt_of_le h with | or.inl h := or.inr h | or.inr h := or.inl $ nat.le_of_succ_le_succ h end, or.rec (assume h, le_trans h $ nat.le_add_right _ _) le_of_eq⟩ theorem mul_self_inj {n m : ℕ} : n * n = m * m ↔ n = m := le_antisymm_iff.trans (le_antisymm_iff.trans (and_congr mul_self_le_mul_self_iff mul_self_le_mul_self_iff)).symm instance decidable_ball_lt (n : nat) (P : Π k < n, Prop) : ∀ [H : ∀ n h, decidable (P n h)], decidable (∀ n h, P n h) := begin induction n with n IH; intro; resetI, { exact is_true (λ n, dec_trivial) }, cases IH (λ k h, P k (lt_succ_of_lt h)) with h, { refine is_false (mt _ h), intros hn k h, apply hn }, by_cases p : P n (lt_succ_self n), { exact is_true (λ k h', (lt_or_eq_of_le $ le_of_lt_succ h').elim (h _) (λ e, match k, e, h' with _, rfl, h := p end)) }, { exact is_false (mt (λ hn, hn _ _) p) } end instance decidable_forall_fin {n : ℕ} (P : fin n → Prop) [H : decidable_pred P] : decidable (∀ i, P i) := decidable_of_iff (∀ k h, P ⟨k, h⟩) ⟨λ a ⟨k, h⟩, a k h, λ a k h, a ⟨k, h⟩⟩ instance decidable_ball_le (n : ℕ) (P : Π k ≤ n, Prop) [H : ∀ n h, decidable (P n h)] : decidable (∀ n h, P n h) := decidable_of_iff (∀ k (h : k < succ n), P k (le_of_lt_succ h)) ⟨λ a k h, a k (lt_succ_of_le h), λ a k h, a k _⟩ instance decidable_lo_hi (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x < hi → P x) := decidable_of_iff (∀ x < hi - lo, P (lo + x)) ⟨λal x hl hh, by have := al (x - lo) (lt_of_not_ge $ (not_congr (nat.sub_le_sub_right_iff _ _ _ hl)).2 $ not_le_of_gt hh); rwa [nat.add_sub_of_le hl] at this, λal x h, al _ (nat.le_add_right _ _) (nat.add_lt_of_lt_sub_left h)⟩ instance decidable_lo_hi_le (lo hi : ℕ) (P : ℕ → Prop) [H : decidable_pred P] : decidable (∀x, lo ≤ x → x ≤ hi → P x) := decidable_of_iff (∀x, lo ≤ x → x < hi + 1 → P x) $ ball_congr $ λ x hl, imp_congr lt_succ_iff iff.rfl protected theorem bit0_le {n m : ℕ} (h : n ≤ m) : bit0 n ≤ bit0 m := add_le_add h h protected theorem bit1_le {n m : ℕ} (h : n ≤ m) : bit1 n ≤ bit1 m := succ_le_succ (add_le_add h h) theorem bit_le : ∀ (b : bool) {n m : ℕ}, n ≤ m → bit b n ≤ bit b m | tt n m h := nat.bit1_le h | ff n m h := nat.bit0_le h theorem bit_ne_zero (b) {n} (h : n ≠ 0) : bit b n ≠ 0 := by cases b; [exact nat.bit0_ne_zero h, exact nat.bit1_ne_zero _] theorem bit0_le_bit : ∀ (b) {m n : ℕ}, m ≤ n → bit0 m ≤ bit b n | tt m n h := le_of_lt $ nat.bit0_lt_bit1 h | ff m n h := nat.bit0_le h theorem bit_le_bit1 : ∀ (b) {m n : ℕ}, m ≤ n → bit b m ≤ bit1 n | ff m n h := le_of_lt $ nat.bit0_lt_bit1 h | tt m n h := nat.bit1_le h theorem bit_lt_bit0 : ∀ (b) {n m : ℕ}, n < m → bit b n < bit0 m | tt n m h := nat.bit1_lt_bit0 h | ff n m h := nat.bit0_lt h theorem bit_lt_bit (a b) {n m : ℕ} (h : n < m) : bit a n < bit b m := lt_of_lt_of_le (bit_lt_bit0 _ h) (bit0_le_bit _ (le_refl _)) /- partial subtraction -/ /-- Partial predecessor operation. Returns `ppred n = some m` if `n = m + 1`, otherwise `none`. -/ @[simp] def ppred : ℕ → option ℕ | 0 := none | (n+1) := some n /-- Partial subtraction operation. Returns `psub m n = some k` if `m = n + k`, otherwise `none`. -/ @[simp] def psub (m : ℕ) : ℕ → option ℕ | 0 := some m | (n+1) := psub n >>= ppred theorem pred_eq_ppred (n : ℕ) : pred n = (ppred n).get_or_else 0 := by cases n; refl theorem sub_eq_psub (m : ℕ) : ∀ n, m - n = (psub m n).get_or_else 0 | 0 := rfl | (n+1) := (pred_eq_ppred (m-n)).trans $ by rw [sub_eq_psub, psub]; cases psub m n; refl @[simp] theorem ppred_eq_some {m : ℕ} : ∀ {n}, ppred n = some m ↔ succ m = n | 0 := by split; intro h; contradiction | (n+1) := by dsimp; split; intro h; injection h; subst n @[simp] theorem ppred_eq_none : ∀ {n : ℕ}, ppred n = none ↔ n = 0 | 0 := by simp | (n+1) := by dsimp; split; contradiction theorem psub_eq_some {m : ℕ} : ∀ {n k}, psub m n = some k ↔ k + n = m | 0 k := by simp [eq_comm] | (n+1) k := by dsimp; apply option.bind_eq_some.trans; simp [psub_eq_some] theorem psub_eq_none (m n : ℕ) : psub m n = none ↔ m < n := begin cases s : psub m n; simp [eq_comm], { show m < n, refine lt_of_not_ge (λ h, _), cases le.dest h with k e, injection s.symm.trans (psub_eq_some.2 $ (add_comm _ _).trans e) }, { show n ≤ m, rw ← psub_eq_some.1 s, apply le_add_left } end theorem ppred_eq_pred {n} (h : 0 < n) : ppred n = some (pred n) := ppred_eq_some.2 $ succ_pred_eq_of_pos h theorem psub_eq_sub {m n} (h : n ≤ m) : psub m n = some (m - n) := psub_eq_some.2 $ nat.sub_add_cancel h theorem psub_add (m n k) : psub m (n + k) = do x ← psub m n, psub x k := by induction k; simp [*, add_succ, bind_assoc] /- pow -/ attribute [simp] nat.pow_zero nat.pow_one @[simp] lemma one_pow : ∀ n : ℕ, 1 ^ n = 1 | 0 := rfl | (k+1) := show 1^k * 1 = 1, by rw [mul_one, one_pow] theorem pow_add (a m n : ℕ) : a^(m + n) = a^m * a^n := by induction n; simp [*, pow_succ, mul_assoc] theorem pow_two (a : ℕ) : a ^ 2 = a * a := show (1 * a) * a = _, by rw one_mul theorem pow_dvd_pow (a : ℕ) {m n : ℕ} (h : m ≤ n) : a^m ∣ a^n := by rw [← nat.add_sub_cancel' h, pow_add]; apply dvd_mul_right theorem pow_dvd_pow_of_dvd {a b : ℕ} (h : a ∣ b) : ∀ n:ℕ, a^n ∣ b^n | 0 := dvd_refl _ | (n+1) := mul_dvd_mul (pow_dvd_pow_of_dvd n) h theorem mul_pow (a b n : ℕ) : (a * b) ^ n = a ^ n * b ^ n := by induction n; simp [*, nat.pow_succ, mul_comm, mul_assoc, mul_left_comm] protected theorem pow_mul (a b n : ℕ) : n ^ (a * b) = (n ^ a) ^ b := by induction b; simp [*, nat.succ_eq_add_one, nat.pow_add, mul_add, mul_comm] theorem pow_pos {p : ℕ} (hp : p > 0) : ∀ n : ℕ, p ^ n > 0 | 0 := by simpa using zero_lt_one | (k+1) := mul_pos (pow_pos _) hp lemma pow_eq_mul_pow_sub (p : ℕ) {m n : ℕ} (h : m ≤ n) : p ^ m * p ^ (n - m) = p ^ n := by rw [←nat.pow_add, nat.add_sub_cancel' h] lemma pow_lt_pow_succ {p : ℕ} (h : p > 1) (n : ℕ) : p^n < p^(n+1) := suffices p^n*1 < p^n*p, by simpa, nat.mul_lt_mul_of_pos_left h (nat.pow_pos (lt_of_succ_lt h) n) lemma lt_pow_self {p : ℕ} (h : p > 1) : ∀ n : ℕ, n < p ^ n | 0 := by simp [zero_lt_one] | (n+1) := calc n + 1 < p^n + 1 : nat.add_lt_add_right (lt_pow_self _) _ ... ≤ p ^ (n+1) : pow_lt_pow_succ h _ lemma not_pos_pow_dvd : ∀ {p k : ℕ} (hp : p > 1) (hk : k > 1), ¬ p^k ∣ p | (succ p) (succ k) hp hk h := have (succ p)^k * succ p ∣ 1 * succ p, by simpa, have (succ p) ^ k ∣ 1, from dvd_of_mul_dvd_mul_right (succ_pos _) this, have he : (succ p) ^ k = 1, from eq_one_of_dvd_one this, have k < (succ p) ^ k, from lt_pow_self hp k, have k < 1, by rwa [he] at this, have k = 0, from eq_zero_of_le_zero $ le_of_lt_succ this, have 1 > 1, by rwa [this] at hk, absurd this dec_trivial @[simp] theorem bodd_div2_eq (n : ℕ) : bodd_div2 n = (bodd n, div2 n) := by unfold bodd div2; cases bodd_div2 n; refl @[simp] lemma bodd_bit0 (n) : bodd (bit0 n) = ff := bodd_bit ff n @[simp] lemma bodd_bit1 (n) : bodd (bit1 n) = tt := bodd_bit tt n @[simp] lemma div2_bit0 (n) : div2 (bit0 n) = n := div2_bit ff n @[simp] lemma div2_bit1 (n) : div2 (bit1 n) = n := div2_bit tt n /- iterate -/ section variables {α : Sort*} (op : α → α) @[simp] theorem iterate_zero (a : α) : op^[0] a = a := rfl @[simp] theorem iterate_succ (n : ℕ) (a : α) : op^[succ n] a = (op^[n]) (op a) := rfl theorem iterate_add : ∀ (m n : ℕ) (a : α), op^[m + n] a = (op^[m]) (op^[n] a) | m 0 a := rfl | m (succ n) a := iterate_add m n _ theorem iterate_succ' (n : ℕ) (a : α) : op^[succ n] a = op (op^[n] a) := by rw [← one_add, iterate_add]; refl end /- size and shift -/ theorem shiftl'_ne_zero_left (b) {m} (h : m ≠ 0) (n) : shiftl' b m n ≠ 0 := by induction n; simp [shiftl', bit_ne_zero, *] theorem shiftl'_tt_ne_zero (m) : ∀ {n} (h : n ≠ 0), shiftl' tt m n ≠ 0 | 0 h := absurd rfl h | (succ n) _ := nat.bit1_ne_zero _ @[simp] theorem size_zero : size 0 = 0 := rfl @[simp] theorem size_bit {b n} (h : bit b n ≠ 0) : size (bit b n) = succ (size n) := begin rw size, conv { to_lhs, rw [binary_rec], simp [h] }, rw div2_bit, refl end @[simp] theorem size_bit0 {n} (h : n ≠ 0) : size (bit0 n) = succ (size n) := @size_bit ff n (nat.bit0_ne_zero h) @[simp] theorem size_bit1 (n) : size (bit1 n) = succ (size n) := @size_bit tt n (nat.bit1_ne_zero n) @[simp] theorem size_one : size 1 = 1 := by apply size_bit1 0 @[simp] theorem size_shiftl' {b m n} (h : shiftl' b m n ≠ 0) : size (shiftl' b m n) = size m + n := begin induction n with n IH; simp [shiftl'] at h ⊢, rw [size_bit h, nat.add_succ], by_cases s0 : shiftl' b m n = 0; [skip, rw [IH s0]], rw s0 at h ⊢, cases b, {exact absurd rfl h}, have : shiftl' tt m n + 1 = 1 := congr_arg (+1) s0, rw [shiftl'_tt_eq_mul_pow] at this, have m0 := succ_inj (eq_one_of_dvd_one ⟨_, this.symm⟩), subst m0, simp at this, have : n = 0 := eq_zero_of_le_zero (le_of_not_gt $ λ hn, ne_of_gt (pow_lt_pow_of_lt_right dec_trivial hn) this), subst n, refl end @[simp] theorem size_shiftl {m} (h : m ≠ 0) (n) : size (shiftl m n) = size m + n := size_shiftl' (shiftl'_ne_zero_left _ h _) theorem lt_size_self (n : ℕ) : n < 2^size n := begin rw [← one_shiftl], have : ∀ {n}, n = 0 → n < shiftl 1 (size n) := λ n e, by subst e; exact dec_trivial, apply binary_rec _ _ n, {apply this rfl}, intros b n IH, by_cases bit b n = 0, {apply this h}, rw [size_bit h, shiftl_succ], exact bit_lt_bit0 _ IH end theorem size_le {m n : ℕ} : size m ≤ n ↔ m < 2^n := ⟨λ h, lt_of_lt_of_le (lt_size_self _) (pow_le_pow_of_le_right dec_trivial h), begin rw [← one_shiftl], revert n, apply binary_rec _ _ m, { intros n h, apply zero_le }, { intros b m IH n h, by_cases e : bit b m = 0, { rw e, apply zero_le }, rw [size_bit e], cases n with n, { exact e.elim (eq_zero_of_le_zero (le_of_lt_succ h)) }, { apply succ_le_succ (IH _), apply lt_imp_lt_of_le_imp_le (λ h', bit0_le_bit _ h') h } } end⟩ theorem lt_size {m n : ℕ} : m < size n ↔ 2^m ≤ n := by rw [← not_lt, iff_not_comm, not_lt, size_le] theorem size_pos {n : ℕ} : 0 < size n ↔ 0 < n := by rw lt_size; refl theorem size_eq_zero {n : ℕ} : size n = 0 ↔ n = 0 := by have := @size_pos n; simp [pos_iff_ne_zero'] at this; exact not_iff_not.1 this theorem size_pow {n : ℕ} : size (2^n) = n+1 := le_antisymm (size_le.2 $ pow_lt_pow_of_lt_right dec_trivial (lt_succ_self _)) (lt_size.2 $ le_refl _) theorem size_le_size {m n : ℕ} (h : m ≤ n) : size m ≤ size n := size_le.2 $ lt_of_le_of_lt h (lt_size_self _) /- factorial -/ /-- `fact n` is the factorial of `n`. -/ @[simp] def fact : nat → nat | 0 := 1 | (succ n) := succ n * fact n @[simp] theorem fact_zero : fact 0 = 1 := rfl @[simp] theorem fact_one : fact 1 = 1 := rfl @[simp] theorem fact_succ (n) : fact (succ n) = succ n * fact n := rfl theorem fact_pos : ∀ n, fact n > 0 | 0 := zero_lt_one | (succ n) := mul_pos (succ_pos _) (fact_pos n) theorem fact_ne_zero (n : ℕ) : fact n ≠ 0 := ne_of_gt (fact_pos _) theorem fact_dvd_fact {m n} (h : m ≤ n) : fact m ∣ fact n := begin induction n with n IH; simp, { have := eq_zero_of_le_zero h, subst m, simp }, { cases eq_or_lt_of_le h with he hl, { subst m, simp }, { apply dvd_mul_of_dvd_right (IH (le_of_lt_succ hl)) } } end theorem dvd_fact : ∀ {m n}, m > 0 → m ≤ n → m ∣ fact n | (succ m) n _ h := dvd_of_mul_right_dvd (fact_dvd_fact h) theorem fact_le {m n} (h : m ≤ n) : fact m ≤ fact n := le_of_dvd (fact_pos _) (fact_dvd_fact h) lemma fact_mul_pow_le_fact : ∀ {m n : ℕ}, m.fact * m.succ ^ n ≤ (m + n).fact | m 0 := by simp | m (n+1) := by rw [← add_assoc, nat.fact_succ, mul_comm (nat.succ _), nat.pow_succ, ← mul_assoc]; exact mul_le_mul fact_mul_pow_le_fact (nat.succ_le_succ (nat.le_add_right _ _)) (nat.zero_le _) (nat.zero_le _) section find_greatest /-- `find_greatest P b` is the largest `i ≤ bound` such that `P i` holds, or `0` if no such `i` exists -/ protected def find_greatest (P : ℕ → Prop) [decidable_pred P] : ℕ → ℕ | 0 := 0 | (n + 1) := if P (n + 1) then n + 1 else find_greatest n variables {P : ℕ → Prop} [decidable_pred P] @[simp] lemma find_greatest_zero : nat.find_greatest P 0 = 0 := rfl @[simp] lemma find_greatest_eq : ∀{b}, P b → nat.find_greatest P b = b | 0 h := rfl | (n + 1) h := by simp [nat.find_greatest, h] @[simp] lemma find_greatest_of_not {b} (h : ¬ P (b + 1)) : nat.find_greatest P (b + 1) = nat.find_greatest P b := by simp [nat.find_greatest, h] lemma find_greatest_spec_and_le : ∀{b m}, m ≤ b → P m → P (nat.find_greatest P b) ∧ m ≤ nat.find_greatest P b | 0 m hm hP := have m = 0, from le_antisymm hm (nat.zero_le _), show P 0 ∧ m ≤ 0, from this ▸ ⟨hP, le_refl _⟩ | (b + 1) m hm hP := begin by_cases h : P (b + 1), { simp [h, hm] }, { have : m ≠ b + 1 := assume this, h $ this ▸ hP, have : m ≤ b := (le_of_not_gt $ assume h : b + 1 ≤ m, this $ le_antisymm hm h), have : P (nat.find_greatest P b) ∧ m ≤ nat.find_greatest P b := find_greatest_spec_and_le this hP, simp [h, this] } end lemma find_greatest_spec {b} : (∃m, m ≤ b ∧ P m) → P (nat.find_greatest P b) | ⟨m, hmb, hm⟩ := (find_greatest_spec_and_le hmb hm).1 lemma find_greatest_le : ∀ {b}, nat.find_greatest P b ≤ b | 0 := le_refl _ | (b + 1) := have nat.find_greatest P b ≤ b + 1, from le_trans find_greatest_le (nat.le_succ b), by by_cases P (b + 1); simp [h, this] lemma le_find_greatest {b m} (hmb : m ≤ b) (hm : P m) : m ≤ nat.find_greatest P b := (find_greatest_spec_and_le hmb hm).2 lemma find_greatest_is_greatest {P : ℕ → Prop} [decidable_pred P] {b} : (∃ m, m ≤ b ∧ P m) → ∀ k, nat.find_greatest P b < k ∧ k ≤ b → ¬ P k | ⟨m, hmb, hP⟩ k ⟨hk, hkb⟩ hPk := lt_irrefl k $ lt_of_le_of_lt (le_find_greatest hkb hPk) hk end find_greatest section div lemma dvd_div_of_mul_dvd {a b c : ℕ} (h : a * b ∣ c) : b ∣ c / a := if ha : a = 0 then by simp [ha] else have ha : a > 0, from nat.pos_of_ne_zero ha, have h1 : ∃ d, c = a * b * d, from h, let ⟨d, hd⟩ := h1 in have hac : a ∣ c, from dvd_of_mul_right_dvd h, have h2 : c / a = b * d, from nat.div_eq_of_eq_mul_right ha (by simpa [mul_assoc] using hd), show ∃ d, c / a = b * d, from ⟨d, h2⟩ lemma mul_dvd_of_dvd_div {a b c : ℕ} (hab : c ∣ b) (h : a ∣ b / c) : c * a ∣ b := have h1 : ∃ d, b / c = a * d, from h, have h2 : ∃ e, b = c * e, from hab, let ⟨d, hd⟩ := h1, ⟨e, he⟩ := h2 in have h3 : b = a * d * c, from nat.eq_mul_of_div_eq_left hab hd, show ∃ d, b = c * a * d, from ⟨d, by cc⟩ lemma div_mul_div {a b c d : ℕ} (hab : b ∣ a) (hcd : d ∣ c) : (a / b) * (c / d) = (a * c) / (b * d) := have exi1 : ∃ x, a = b * x, from hab, have exi2 : ∃ y, c = d * y, from hcd, if hb : b = 0 then by simp [hb] else have b > 0, from nat.pos_of_ne_zero hb, if hd : d = 0 then by simp [hd] else have d > 0, from nat.pos_of_ne_zero hd, begin cases exi1 with x hx, cases exi2 with y hy, rw [hx, hy, nat.mul_div_cancel_left, nat.mul_div_cancel_left], symmetry, apply nat.div_eq_of_eq_mul_left, apply mul_pos, repeat {assumption}, cc end lemma pow_dvd_of_le_of_pow_dvd {p m n k : ℕ} (hmn : m ≤ n) (hdiv : p ^ n ∣ k) : p ^ m ∣ k := have p ^ m ∣ p ^ n, from pow_dvd_pow _ hmn, dvd_trans this hdiv lemma dvd_of_pow_dvd {p k m : ℕ} (hk : 1 ≤ k) (hpk : p^k ∣ m) : p ∣ m := by rw ←nat.pow_one p; exact pow_dvd_of_le_of_pow_dvd hk hpk end div lemma exists_eq_add_of_le : ∀ {m n : ℕ}, m ≤ n → ∃ k : ℕ, n = m + k | 0 0 h := ⟨0, by simp⟩ | 0 (n+1) h := ⟨n+1, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk]⟩ lemma exists_eq_add_of_lt : ∀ {m n : ℕ}, m < n → ∃ k : ℕ, n = m + k + 1 | 0 0 h := false.elim $ lt_irrefl _ h | 0 (n+1) h := ⟨n, by simp⟩ | (m+1) (n+1) h := let ⟨k, hk⟩ := exists_eq_add_of_le (nat.le_of_succ_le_succ h) in ⟨k, by simp [hk]⟩ end nat
2fe7bf437cfc395efb0c8df7a3ef5409719c0661
d1a52c3f208fa42c41df8278c3d280f075eb020c
/src/Lean/Compiler/IR/EmitUtil.lean
c9155bd5912a8b073017bbdba1539cee0135d9b5
[ "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
3,249
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.InitAttr import Lean.Compiler.IR.CompilerM /- Helper functions for backend code generators -/ namespace Lean.IR /- Return true iff `b` is of the form `let x := g ys; ret x` -/ def isTailCallTo (g : Name) (b : FnBody) : Bool := match b with | FnBody.vdecl x _ (Expr.fap f _) (FnBody.ret (Arg.var y)) => x == y && f == g | _ => false def usesModuleFrom (env : Environment) (modulePrefix : Name) : Bool := env.allImportedModuleNames.toList.any $ fun modName => modulePrefix.isPrefixOf modName namespace CollectUsedDecls abbrev M := ReaderT Environment (StateM NameSet) @[inline] def collect (f : FunId) : M Unit := modify fun s => s.insert f partial def collectFnBody : FnBody → M Unit | FnBody.vdecl _ _ v b => match v with | Expr.fap f _ => collect f *> collectFnBody b | Expr.pap f _ => collect f *> collectFnBody b | other => collectFnBody b | FnBody.jdecl _ _ v b => collectFnBody v *> collectFnBody b | FnBody.case _ _ _ alts => alts.forM $ fun alt => collectFnBody alt.body | e => do unless e.isTerminal do collectFnBody e.body def collectInitDecl (fn : Name) : M Unit := do let env ← read match getInitFnNameFor? env fn with | some initFn => collect initFn | _ => pure () def collectDecl : Decl → M NameSet | Decl.fdecl (f := f) (body := b) .. => collectInitDecl f *> CollectUsedDecls.collectFnBody b *> get | Decl.extern (f := f) .. => collectInitDecl f *> get end CollectUsedDecls def collectUsedDecls (env : Environment) (decl : Decl) (used : NameSet := {}) : NameSet := (CollectUsedDecls.collectDecl decl env).run' used abbrev VarTypeMap := Std.HashMap VarId IRType abbrev JPParamsMap := Std.HashMap JoinPointId (Array Param) namespace CollectMaps abbrev Collector := (VarTypeMap × JPParamsMap) → (VarTypeMap × JPParamsMap) @[inline] def collectVar (x : VarId) (t : IRType) : Collector | (vs, js) => (vs.insert x t, js) def collectParams (ps : Array Param) : Collector := fun s => ps.foldl (fun s p => collectVar p.x p.ty s) s @[inline] def collectJP (j : JoinPointId) (xs : Array Param) : Collector | (vs, js) => (vs, js.insert j xs) /- `collectFnBody` assumes the variables in -/ partial def collectFnBody : FnBody → Collector | FnBody.vdecl x t _ b => collectVar x t ∘ collectFnBody b | FnBody.jdecl j xs v b => collectJP j xs ∘ collectParams xs ∘ collectFnBody v ∘ collectFnBody b | FnBody.case _ _ _ alts => fun s => alts.foldl (fun s alt => collectFnBody alt.body s) s | e => if e.isTerminal then id else collectFnBody e.body def collectDecl : Decl → Collector | Decl.fdecl (xs := xs) (body := b) .. => collectParams xs ∘ collectFnBody b | _ => id end CollectMaps /- Return a pair `(v, j)`, where `v` is a mapping from variable/parameter to type, and `j` is a mapping from join point to parameters. This function assumes `d` has normalized indexes (see `normids.lean`). -/ def mkVarJPMaps (d : Decl) : VarTypeMap × JPParamsMap := CollectMaps.collectDecl d ({}, {}) end IR end Lean
c02ccff7d88578ee9af1274410ac825b34ba8bb2
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/num/bitwise.lean
3366040ca5a5b9dd553947014e859cc10e39fbf3
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
6,072
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.num.basic import Mathlib.data.bitvec.core import Mathlib.PostPort universes l u_1 namespace Mathlib /-! # Bitwise operations using binary representation of integers ## Definitions * bitwise operations for `pos_num` and `num`, * `snum`, a type that represents integers as a bit string with a sign bit at the end, * arithmetic operations for `snum`. -/ namespace pos_num def lor : pos_num → pos_num → pos_num := sorry def land : pos_num → pos_num → num := sorry def ldiff : pos_num → pos_num → num := sorry def lxor : pos_num → pos_num → num := sorry def test_bit : pos_num → ℕ → Bool := sorry def one_bits : pos_num → ℕ → List ℕ := sorry def shiftl (p : pos_num) : ℕ → pos_num := sorry def shiftr : pos_num → ℕ → num := sorry end pos_num namespace num def lor : num → num → num := sorry def land : num → num → num := sorry def ldiff : num → num → num := sorry def lxor : num → num → num := sorry def shiftl : num → ℕ → num := sorry def shiftr : num → ℕ → num := sorry def test_bit : num → ℕ → Bool := sorry def one_bits : num → List ℕ := sorry end num /-- This is a nonzero (and "non minus one") version of `snum`. See the documentation of `snum` for more details. -/ inductive nzsnum where | msb : Bool → nzsnum | bit : Bool → nzsnum → nzsnum /-- Alternative representation of integers using a sign bit at the end. The convention on sign here is to have the argument to `msb` denote the sign of the MSB itself, with all higher bits set to the negation of this sign. The result is interpreted in two's complement. 13 = ..0001101(base 2) = nz (bit1 (bit0 (bit1 (msb tt)))) -13 = ..1110011(base 2) = nz (bit1 (bit1 (bit0 (msb ff)))) As with `num`, a special case must be added for zero, which has no msb, but by two's complement symmetry there is a second special case for -1. Here the `bool` field indicates the sign of the number. 0 = ..0000000(base 2) = zero ff -1 = ..1111111(base 2) = zero tt -/ inductive snum where | zero : Bool → snum | nz : nzsnum → snum protected instance snum.has_coe : has_coe nzsnum snum := has_coe.mk snum.nz protected instance snum.has_zero : HasZero snum := { zero := snum.zero false } protected instance nzsnum.has_one : HasOne nzsnum := { one := nzsnum.msb tt } protected instance snum.has_one : HasOne snum := { one := snum.nz 1 } protected instance nzsnum.inhabited : Inhabited nzsnum := { default := 1 } protected instance snum.inhabited : Inhabited snum := { default := 0 } infixr:67 " :: " => Mathlib.nzsnum.bit /-! The `snum` representation uses a bit string, essentially a list of 0 (`ff`) and 1 (`tt`) bits, and the negation of the MSB is sign-extended to all higher bits. -/ namespace nzsnum def sign : nzsnum → Bool := sorry def not : nzsnum → nzsnum := sorry prefix:40 "~" => Mathlib.nzsnum.not def bit0 : nzsnum → nzsnum := bit false def bit1 : nzsnum → nzsnum := bit tt def head : nzsnum → Bool := sorry def tail : nzsnum → snum := sorry end nzsnum namespace snum def sign : snum → Bool := sorry def not : snum → snum := sorry prefix:40 "~" => Mathlib.snum.not def bit : Bool → snum → snum := sorry infixr:67 " :: " => Mathlib.snum.bit def bit0 : snum → snum := bit false def bit1 : snum → snum := bit tt theorem bit_zero (b : Bool) : b :: zero b = zero b := bool.cases_on b (Eq.refl (false :: zero false)) (Eq.refl (tt :: zero tt)) theorem bit_one (b : Bool) : b :: zero (!b) = ↑(nzsnum.msb b) := bool.cases_on b (Eq.refl (false :: zero (!false))) (Eq.refl (tt :: zero (!tt))) end snum namespace nzsnum def drec' {C : snum → Sort u_1} (z : (b : Bool) → C (snum.zero b)) (s : (b : Bool) → (p : snum) → C p → C (b :: p)) (p : nzsnum) : C ↑p := sorry end nzsnum namespace snum def head : snum → Bool := sorry def tail : snum → snum := sorry def drec' {C : snum → Sort u_1} (z : (b : Bool) → C (zero b)) (s : (b : Bool) → (p : snum) → C p → C (b :: p)) (p : snum) : C p := sorry def rec' {α : Sort u_1} (z : Bool → α) (s : Bool → snum → α → α) : snum → α := drec' z s def test_bit : ℕ → snum → Bool := sorry def succ : snum → snum := rec' (fun (b : Bool) => cond b 0 1) fun (b : Bool) (p succp : snum) => cond b (false :: succp) (tt :: p) def pred : snum → snum := rec' (fun (b : Bool) => cond b (~1) (~0)) fun (b : Bool) (p predp : snum) => cond b (false :: p) (tt :: predp) protected def neg (n : snum) : snum := succ (~n) protected instance has_neg : Neg snum := { neg := snum.neg } def czadd : Bool → Bool → snum → snum := sorry end snum namespace snum /-- `a.bits n` is the vector of the `n` first bits of `a` (starting from the LSB). -/ def bits : snum → (n : ℕ) → vector Bool n := sorry def cadd : snum → snum → Bool → snum := rec' (fun (a : Bool) (p : snum) (c : Bool) => czadd c a p) fun (a : Bool) (p : snum) (IH : snum → Bool → snum) => rec' (fun (b c : Bool) => czadd c b (a :: p)) fun (b : Bool) (q : snum) (_x : Bool → snum) (c : Bool) => bitvec.xor3 a b c :: IH q (bitvec.carry a b c) /-- Add two `snum`s. -/ protected def add (a : snum) (b : snum) : snum := cadd a b false protected instance has_add : Add snum := { add := snum.add } /-- Substract two `snum`s. -/ protected def sub (a : snum) (b : snum) : snum := a + -b protected instance has_sub : Sub snum := { sub := snum.sub } /-- Multiply two `snum`s. -/ protected def mul (a : snum) : snum → snum := rec' (fun (b : Bool) => cond b (-a) 0) fun (b : Bool) (q IH : snum) => cond b (bit0 IH + a) (bit0 IH) protected instance has_mul : Mul snum := { mul := snum.mul }
444f3b8e3307f71173f8f9ef76f2f355c8d9ef83
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/test/coinductive.lean
212ddca52df48efed3a6115e2aa2a049585662ee
[ "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
5,081
lean
/- test cases for coinductive predicates -/ import data.stream.init import meta.coinductive_predicates universe u coinductive all_stream {α : Type u} (s : set α) : stream α → Prop | step : ∀{a : α} {ω : stream α}, a ∈ s → all_stream ω → all_stream (a :: ω) example : Π {α : Type u}, set α → stream α → Prop := @all_stream example : ∀ {α : Type u} {s : set α} {a : α} {ω : stream α}, a ∈ s → all_stream s ω → all_stream s (a :: ω) := @all_stream.step example : ∀ {α : Type u} (s : set α) {a : stream α}, all_stream s a → all_stream.functional s (all_stream s) a := @all_stream.destruct example : ∀ {α : Type u} (s : set α) (C : stream α → Prop) {a : stream α}, C a → (∀ (a : stream α), C a → (∃ {a_1 : α} {ω : stream α}, a_1 ∈ s ∧ C ω ∧ a_1 :: ω = a)) → all_stream s a := @all_stream.corec_on example : ∀ {α : Type u} (s : set α) (C : stream α → Prop), (∀ (a : stream α), C a → all_stream.functional s C a) → ∀ (a : stream α), C a → all_stream s a := @all_stream.corec_functional coinductive all_stream' {α : Type u} (s : set α) : stream α → Prop | step : ∀{ω : stream α}, stream.head ω ∈ s → all_stream' (stream.tail ω) → all_stream' ω coinductive alt_stream : stream bool → Prop | tt_step : ∀{ω : stream bool}, alt_stream (ff :: ω) → alt_stream (tt :: ff :: ω) | ff_step : ∀{ω : stream bool}, alt_stream (tt :: ω) → alt_stream (ff :: tt :: ω) example : stream bool → Prop := @alt_stream example : ∀ {ω : stream bool}, alt_stream (ff :: ω) → alt_stream (tt :: ff :: ω) := @alt_stream.tt_step example : ∀ {ω : stream bool}, alt_stream (tt :: ω) → alt_stream (ff :: tt :: ω) := @alt_stream.ff_step example : ∀ (C : stream bool → Prop), (∀ (a : stream bool), C a → alt_stream.functional C a) → ∀ (a : stream bool), C a → alt_stream a := @alt_stream.corec_functional mutual coinductive tt_stream, ff_stream with tt_stream : stream bool → Prop | step : ∀{ω : stream bool}, ff_stream ω → tt_stream (stream.cons tt ω) with ff_stream : stream bool → Prop | step : ∀{ω : stream bool}, tt_stream ω → ff_stream (stream.cons ff ω) example : stream bool → Prop := @tt_stream example : stream bool → Prop := @ff_stream example : ∀ (C_tt_stream C_ff_stream : stream bool → Prop), (∀ (a : stream bool), C_tt_stream a → tt_stream.functional C_tt_stream C_ff_stream a) → (∀ (a : stream bool), C_ff_stream a → ff_stream.functional C_tt_stream C_ff_stream a) → ∀ (a : stream bool), C_tt_stream a → tt_stream a := @tt_stream.corec_functional example : ∀ (C_tt_stream C_ff_stream : stream bool → Prop), (∀ (a : stream bool), C_tt_stream a → tt_stream.functional C_tt_stream C_ff_stream a) → (∀ (a : stream bool), C_ff_stream a → ff_stream.functional C_tt_stream C_ff_stream a) → ∀ (a : stream bool), C_ff_stream a → ff_stream a := @ff_stream.corec_functional mutual coinductive tt_ff_stream, ff_tt_stream with tt_ff_stream : stream bool → Prop | step : ∀{ω : stream bool}, tt_ff_stream ω ∨ ff_tt_stream ω → tt_ff_stream (stream.cons tt ω) with ff_tt_stream : stream bool → Prop | step : ∀{ω : stream bool}, ff_tt_stream ω ∨ tt_ff_stream ω → ff_tt_stream (stream.cons ff ω) inductive all_list {α : Type} (p : α → Prop) : list α → Prop | nil : all_list [] | cons : ∀a xs, p a → all_list xs → all_list (a :: xs) @[monotonicity] lemma monotonicity.all_list {α : Type} {p q : α → Prop} (h : ∀a, implies (p a) (q a)) : ∀xs, implies (all_list p xs) (all_list q xs) | _ (all_list.nil) := all_list.nil | _ (all_list.cons a xs ha hxs) := all_list.cons _ _ (h a ha) (monotonicity.all_list _ hxs) mutual coinductive walk_a, walk_b {α β : Type} (f : α → list β) (g : β → α) (p : α → Prop) (t : α → Prop) with walk_a : α → Prop | step : ∀a, all_list walk_b (f a) → p a → walk_a a | term : ∀a, t a → walk_a a with walk_b : β → Prop | step : ∀b, walk_a (g b) → walk_b b example : ∀ {α β : Type} (f : α → list β) (g : β → α) (p t C_walk_a : α → Prop) (C_walk_b : β → Prop) {a : α}, C_walk_a a → (∀ (a : α), C_walk_a a → all_list C_walk_b (f a) ∧ p a ∨ t a) → (∀ (a : β), C_walk_b a → C_walk_a (g a)) → walk_a f g p t a := @walk_a.corec_on coinductive walk_list {α : Type} (f : α → list α) (p : α → Prop) : ℕ → α → Prop | step : ∀n a, all_list (walk_list n) (f a) → p a → walk_list (n + 1) a example {f : ℕ → list ℕ} {a' : ℕ} {n : ℕ} {a : fin n} : true := begin suffices : walk_list f (λ a'', a'' = a') (n + 1) a', {trivial}, coinduction walk_list.corec_on generalizing a n, show ∃ (n : ℕ), all_list (λ (a : ℕ), ∃ {n_1 : ℕ} {a_1 : fin n_1}, n_1 + 1 = n ∧ a' = a) (f a') ∧ a' = a' ∧ n + 1 = w + 1, admit end coinductive coind_foo : list ℕ → Prop | mk : ∀ xs, (∀ k l m, coind_foo (k::l::m::xs)) → coind_foo xs
a57382c63724475c15a9e7302df91ac8bb64745e
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/data/unsigned/ops.lean
02c67e4f99b2037697bdd251806ef2f20b78efb6
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
725
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import init.data.unsigned.basic init.data.fin.ops namespace unsigned def of_nat (n : nat) : unsigned := fin.of_nat n instance : has_zero unsigned := ⟨fin.of_nat 0⟩ instance : has_one unsigned := ⟨fin.of_nat 1⟩ instance : has_add unsigned := ⟨fin.add⟩ instance : has_sub unsigned := ⟨fin.sub⟩ instance : has_mul unsigned := ⟨fin.mul⟩ instance : has_mod unsigned := ⟨fin.mod⟩ instance : has_div unsigned := ⟨fin.div⟩ instance : has_lt unsigned := ⟨fin.lt⟩ instance : has_le unsigned := ⟨fin.le⟩ end unsigned
8b4e1d47f4ddb3ca70d54fda5a1e82e55dd13800
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/archive/imo/imo2013_q1.lean
3febeb3069c659ced4fc21a4acf761dbddd89518
[ "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
4,240
lean
/- Copyright (c) 2021 David Renshaw. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: David Renshaw -/ import data.pnat.basic import data.nat.parity import algebra.big_operators.pi import tactic.ring import tactic.field_simp /-! # IMO 2013 Q1 Prove that for any pair of positive integers k and n, there exist k positive integers m₁, m₂, ..., mₖ (not necessarily different) such that 1 + (2ᵏ - 1)/ n = (1 + 1/m₁) * (1 + 1/m₂) * ... * (1 + 1/mₖ). # Solution Adaptation of the solution found in https://www.imo-official.org/problems/IMO2013SL.pdf We prove a slightly more general version where k does not need to be strictly positive. -/ open_locale big_operators lemma arith_lemma (k n : ℕ) : 0 < 2 * n + 2^k.succ := calc 0 < 2 : zero_lt_two ... = 2^1 : (pow_one 2).symm ... ≤ 2^k.succ : nat.pow_le_pow_of_le_right zero_lt_two (nat.le_add_left 1 k) ... ≤ 2 * n + 2^k.succ : nat.le_add_left _ _ lemma prod_lemma (m : ℕ → ℕ+) (k : ℕ) (nm : ℕ+): ∏ (i : ℕ) in finset.range k, ((1 : ℚ) + 1 / ↑(if i < k then m i else nm)) = ∏ (i : ℕ) in finset.range k, (1 + 1 / m i) := begin suffices : ∀ i, i ∈ finset.range k → (1 : ℚ) + 1 / ↑(if i < k then m i else nm) = 1 + 1 / m i, from finset.prod_congr rfl this, intros i hi, simp [finset.mem_range.mp hi] end theorem imo2013_q1 (n : ℕ+) (k : ℕ) : (∃ m : ℕ → ℕ+, (1 : ℚ) + (2^k - 1) / n = (∏ i in finset.range k, (1 + 1 / m i))) := begin revert n, induction k with pk hpk, { intro n, use (λ_, 1), simp }, -- For the base case, any m works. intro n, obtain ⟨t, ht : ↑n = 2 * t⟩ | ⟨t, ht : ↑n = 2 * t + 1⟩ := (n : ℕ).even_or_odd, { -- even case cases t, -- Eliminate the zero case to simplify later calculations. { exfalso, rw mul_zero at ht, exact pnat.ne_zero n ht }, -- Now we have ht : ↑n = 2 * (t + 1). let t_succ : ℕ+ := ⟨t + 1, t.succ_pos⟩, obtain ⟨pm, hpm⟩ := hpk t_succ, let m := λi, if i < pk then pm i else ⟨2 * t + 2^pk.succ, arith_lemma pk t⟩, use m, have hmpk : (m pk : ℚ) = 2 * t + 2^pk.succ, { have : m pk = ⟨2 * t + 2^pk.succ, _⟩ := if_neg (irrefl pk), simp [this] }, have denom_ne_zero : (2 * (t:ℚ) + 2^pk.succ) ≠ 0, { norm_cast, exact (ne_of_gt $ arith_lemma pk t) }, calc (1 : ℚ) + (2 ^ pk.succ - 1) / ↑n = 1 + (2 * 2 ^ pk - 1) / (2 * (t + 1) : ℕ) : by rw [coe_coe n, ht, pow_succ] ... = (1 + 1 / (2 * t + 2 * 2^pk)) * (1 + (2 ^ pk - 1) / (↑t + 1)) : by { field_simp [t.cast_add_one_ne_zero], ring } ... = (1 + 1 / (2 * t + 2^pk.succ)) * (1 + (2 ^ pk - 1) / t_succ) : by norm_cast ... = (∏ i in finset.range pk, (1 + 1 / m i)) * (1 + 1 / (m pk)) : by rw [prod_lemma, hpm, ←hmpk, mul_comm] ... = ∏ i in finset.range pk.succ, (1 + 1 / m i) : by rw ← finset.prod_range_succ _ pk }, { -- odd case let t_succ : ℕ+ := ⟨t + 1, t.succ_pos⟩, obtain ⟨pm, hpm⟩ := hpk t_succ, let m := λi, if i < pk then pm i else ⟨2 * t + 1, nat.succ_pos _⟩, use m, have hmpk : (m pk : ℚ) = 2 * t + 1, { have : m pk = ⟨2 * t + 1, _⟩ := if_neg (irrefl pk), simp [this] }, have denom_ne_zero : (2 * (t : ℚ) + 1) ≠ 0 := by { norm_cast, apply (2 * t).succ_ne_zero }, calc (1 : ℚ) + (2 ^ pk.succ - 1) / ↑n = 1 + (2 * 2^pk - 1) / (2 * t + 1 : ℕ) : by rw [coe_coe n, ht, pow_succ] ... = (1 + 1 / (2 * t + 1)) * (1 + (2^pk - 1) / (t + 1)) : by { field_simp [t.cast_add_one_ne_zero], ring } ... = (1 + 1 / (2 * t + 1)) * (1 + (2^pk - 1) / t_succ) : by norm_cast ... = (∏ i in finset.range pk, (1 + 1 / m i)) * (1 + 1 / ↑(m pk)) : by rw [prod_lemma, hpm, ←hmpk, mul_comm] ... = ∏ i in finset.range pk.succ, (1 + 1 / m i) : by rw ← finset.prod_range_succ _ pk } end
f566e66f0083950f4b58a55db49d7c765f9670dd
f3a5af2927397cf346ec0e24312bfff077f00425
/experiments/evenodd.lean
d22c7beb8ec79506beea859f97d3ce18219ada1e
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
2,051
lean
import tactic.interactive tactic.ring inductive is_even : ℕ → Prop | zero : is_even 0 | step {n} : is_even n → is_even (n + 2) example : is_even 4 := begin repeat { apply is_even.step }, apply is_even.zero, end example : ¬ is_even 5 := begin intro even_five, cases even_five with _ even_three, cases even_three with _ even_one, cases even_one, end lemma even_if_double {n} : is_even (2*n) := begin induction n with d hd, { exact is_even.zero }, { show is_even (2 * (d + 1)), rw mul_add, apply is_even.step, assumption, }, end lemma double_if_even {n} : is_even n → ∃ m, n = 2*m := begin intro h, induction h with d Hd ih, { use 0, refl }, { cases ih with n Hn, use (n + 1), rw Hn, refl, } end lemma even_iff_double {n} : is_even n ↔ ∃ m, n = 2*m := begin split, apply double_if_even, intro h, cases h with d Hd, rw Hd, apply even_if_double end inductive is_odd : ℕ → Prop | one : is_odd 1 | step {n} : is_odd n → is_odd (n + 2) lemma odd_iff_double_add_one {n} : is_odd n ↔ ∃ m, n = 2*m + 1 := sorry lemma even_of_not_odd : ∀ n, ¬ is_odd n → is_even n | 0 h := is_even.zero | 1 h := begin exfalso, apply h, constructor end | (n+2) h := have ih : _, from even_of_not_odd n, begin constructor, apply ih, intro hn, apply h, constructor, assumption, end #print even_of_not_odd lemma not_odd_of_even : ∀ n, is_even n → ¬ is_odd n := begin intros n h, induction h with m m hm, {intro h, cases h}, {intro h, apply hm, cases h, assumption}, end lemma even_iff_not_odd : ∀ n, is_even n ↔ ¬ is_odd n := begin intro n, split, apply not_odd_of_even, apply even_of_not_odd end lemma odd_square (n : ℕ) : is_odd n → is_odd (n*n) := begin simp [odd_iff_double_add_one], intro m, intros h, use 2*m + 2*m*m, subst h, ring, end lemma even_square (n : ℕ) : is_even (n*n) → is_even n := begin conv in (is_even (n*n)) { simp [even_iff_not_odd] }, simp [even_iff_not_odd], intros h1 h2, apply h1, apply odd_square, assumption end --set_option pp.all true #check (7 : ℤ)
06f867ce4fd5e3abb53242bc15856ab4dbf26a01
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/category_theory/category/default.lean
eeacb45b2ce50eb3e988eacbf0b354687015968d
[ "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
7,570
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Stephen Morgan, Scott Morrison, Johannes Hölzl, Reid Barton -/ import tactic.basic import tactic.tidy /-! # Categories Defines a category, as a type class parametrised by the type of objects. ## Notations Introduces notations * `X ⟶ Y` for the morphism spaces, * `f ≫ g` for composition in the 'arrows' convention. Users may like to add `f ⊚ g` for composition in the standard convention, using ```lean local notation f ` ⊚ `:80 g:80 := category.comp g f -- type as \oo ``` -/ universes v u -- The order in this declaration matters: v often needs to be explicitly specified while u often can be omitted namespace category_theory /- The propositional fields of `category` are annotated with the auto_param `obviously`, which is defined here as a [`replacer` tactic](https://leanprover-community.github.io/mathlib_docs/commands.html#def_replacer). We then immediately set up `obviously` to call `tidy`. Later, this can be replaced with more powerful tactics. -/ def_replacer obviously @[obviously] meta def obviously' := tactic.tidy class has_hom (obj : Type u) : Type (max u (v+1)) := (hom : obj → obj → Type v) infixr ` ⟶ `:10 := has_hom.hom -- type as \h section prio set_option default_priority 100 -- see Note [default priority] class category_struct (obj : Type u) extends has_hom.{v} obj : Type (max u (v+1)) := (id : Π X : obj, hom X X) (comp : Π {X Y Z : obj}, (X ⟶ Y) → (Y ⟶ Z) → (X ⟶ Z)) notation `𝟙` := category_struct.id -- type as \b1 infixr ` ≫ `:80 := category_struct.comp -- type as \gg /-- The typeclass `category C` describes morphisms associated to objects of type `C`. The universe levels of the objects and morphisms are unconstrained, and will often need to be specified explicitly, as `category.{v} C`. (See also `large_category` and `small_category`.) -/ class category (obj : Type u) extends category_struct.{v} obj : Type (max u (v+1)) := (id_comp' : ∀ {X Y : obj} (f : hom X Y), 𝟙 X ≫ f = f . obviously) (comp_id' : ∀ {X Y : obj} (f : hom X Y), f ≫ 𝟙 Y = f . obviously) (assoc' : ∀ {W X Y Z : obj} (f : hom W X) (g : hom X Y) (h : hom Y Z), (f ≫ g) ≫ h = f ≫ (g ≫ h) . obviously) end prio -- `restate_axiom` is a command that creates a lemma from a structure field, -- discarding any auto_param wrappers from the type. -- (It removes a backtick from the name, if it finds one, and otherwise adds "_lemma".) restate_axiom category.id_comp' restate_axiom category.comp_id' restate_axiom category.assoc' attribute [simp] category.id_comp category.comp_id category.assoc attribute [trans] category_struct.comp /-- A `large_category` has objects in one universe level higher than the universe level of the morphisms. It is useful for examples such as the category of types, or the category of groups, etc. -/ abbreviation large_category (C : Type (u+1)) : Type (u+1) := category.{u} C /-- A `small_category` has objects and morphisms in the same universe level. -/ abbreviation small_category (C : Type u) : Type (u+1) := category.{u} C section variables {C : Type u} [category.{v} C] {X Y Z : C} /-- postcompose an equation between morphisms by another morphism -/ lemma eq_whisker {f g : X ⟶ Y} (w : f = g) (h : Y ⟶ Z) : f ≫ h = g ≫ h := by rw w /-- precompose an equation between morphisms by another morphism -/ lemma whisker_eq (f : X ⟶ Y) {g h : Y ⟶ Z} (w : g = h) : f ≫ g = f ≫ h := by rw w infixr ` =≫ `:80 := eq_whisker infixr ` ≫= `:80 := whisker_eq lemma eq_of_comp_left_eq {f g : X ⟶ Y} (w : ∀ {Z : C} (h : Y ⟶ Z), f ≫ h = g ≫ h) : f = g := by { convert w (𝟙 Y), tidy } lemma eq_of_comp_right_eq {f g : Y ⟶ Z} (w : ∀ {X : C} (h : X ⟶ Y), h ≫ f = h ≫ g) : f = g := by { convert w (𝟙 Y), tidy } lemma eq_of_comp_left_eq' (f g : X ⟶ Y) (w : (λ {Z : C} (h : Y ⟶ Z), f ≫ h) = (λ {Z : C} (h : Y ⟶ Z), g ≫ h)) : f = g := eq_of_comp_left_eq (λ Z h, by convert congr_fun (congr_fun w Z) h) lemma eq_of_comp_right_eq' (f g : Y ⟶ Z) (w : (λ {X : C} (h : X ⟶ Y), h ≫ f) = (λ {X : C} (h : X ⟶ Y), h ≫ g)) : f = g := eq_of_comp_right_eq (λ X h, by convert congr_fun (congr_fun w X) h) lemma id_of_comp_left_id (f : X ⟶ X) (w : ∀ {Y : C} (g : X ⟶ Y), f ≫ g = g) : f = 𝟙 X := by { convert w (𝟙 X), tidy } lemma id_of_comp_right_id (f : X ⟶ X) (w : ∀ {Y : C} (g : Y ⟶ X), g ≫ f = g) : f = 𝟙 X := by { convert w (𝟙 X), tidy } class epi (f : X ⟶ Y) : Prop := (left_cancellation : Π {Z : C} (g h : Y ⟶ Z) (w : f ≫ g = f ≫ h), g = h) class mono (f : X ⟶ Y) : Prop := (right_cancellation : Π {Z : C} (g h : Z ⟶ X) (w : g ≫ f = h ≫ f), g = h) instance (X : C) : epi.{v} (𝟙 X) := ⟨λ Z g h w, by simpa using w⟩ instance (X : C) : mono.{v} (𝟙 X) := ⟨λ Z g h w, by simpa using w⟩ lemma cancel_epi (f : X ⟶ Y) [epi f] {g h : Y ⟶ Z} : (f ≫ g = f ≫ h) ↔ g = h := ⟨ λ p, epi.left_cancellation g h p, begin intro a, subst a end ⟩ lemma cancel_mono (f : X ⟶ Y) [mono f] {g h : Z ⟶ X} : (g ≫ f = h ≫ f) ↔ g = h := ⟨ λ p, mono.right_cancellation g h p, begin intro a, subst a end ⟩ lemma cancel_epi_id (f : X ⟶ Y) [epi f] {h : Y ⟶ Y} : (f ≫ h = f) ↔ h = 𝟙 Y := by { convert cancel_epi f, simp, } lemma cancel_mono_id (f : X ⟶ Y) [mono f] {g : X ⟶ X} : (g ≫ f = f) ↔ g = 𝟙 X := by { convert cancel_mono f, simp, } lemma epi_comp {X Y Z : C} (f : X ⟶ Y) [epi f] (g : Y ⟶ Z) [epi g] : epi (f ≫ g) := begin split, intros Z a b w, apply (cancel_epi g).1, apply (cancel_epi f).1, simpa using w, end lemma mono_comp {X Y Z : C} (f : X ⟶ Y) [mono f] (g : Y ⟶ Z) [mono g] : mono (f ≫ g) := begin split, intros Z a b w, apply (cancel_mono f).1, apply (cancel_mono g).1, simpa using w, end lemma mono_of_mono {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [mono (f ≫ g)] : mono f := begin split, intros Z a b w, replace w := congr_arg (λ k, k ≫ g) w, dsimp at w, rw [category.assoc, category.assoc] at w, exact (cancel_mono _).1 w, end lemma mono_of_mono_fac {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} {h : X ⟶ Z} [mono h] (w : f ≫ g = h) : mono f := by { resetI, subst h, exact mono_of_mono f g, } lemma epi_of_epi {X Y Z : C} (f : X ⟶ Y) (g : Y ⟶ Z) [epi (f ≫ g)] : epi g := begin split, intros Z a b w, replace w := congr_arg (λ k, f ≫ k) w, dsimp at w, rw [←category.assoc, ←category.assoc] at w, exact (cancel_epi _).1 w, end lemma epi_of_epi_fac {X Y Z : C} {f : X ⟶ Y} {g : Y ⟶ Z} {h : X ⟶ Z} [epi h] (w : f ≫ g = h) : epi g := by { resetI, subst h, exact epi_of_epi f g, } end section variable (C : Type u) variable [category.{v} C] universe u' instance ulift_category : category.{v} (ulift.{u'} C) := { hom := λ X Y, (X.down ⟶ Y.down), id := λ X, 𝟙 X.down, comp := λ _ _ _ f g, f ≫ g } -- We verify that this previous instance can lift small categories to large categories. example (D : Type u) [small_category D] : large_category (ulift.{u+1} D) := by apply_instance end end category_theory open category_theory namespace preorder variables (α : Type u) @[priority 100] -- see Note [lower instance priority] instance small_category [preorder α] : small_category α := { hom := λ U V, ulift (plift (U ≤ V)), id := λ X, ⟨ ⟨ le_refl X ⟩ ⟩, comp := λ X Y Z f g, ⟨ ⟨ le_trans _ _ _ f.down.down g.down.down ⟩ ⟩ } end preorder
33dff2da020befad4409e4af4f2123146b0c17de
9dc8cecdf3c4634764a18254e94d43da07142918
/src/data/complex/exponential.lean
45b60b8ae7c96a93813bfb3b74c4c5a7fea48ec2
[ "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
67,002
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir -/ import algebra.geom_sum import data.complex.basic import data.nat.choose.sum /-! # Exponential, trigonometric and hyperbolic trigonometric functions This file contains the definitions of the real and complex exponential, sine, cosine, tangent, hyperbolic sine, hyperbolic cosine, and hyperbolic tangent functions. -/ local notation `abs'` := has_abs.abs open is_absolute_value open_locale classical big_operators nat complex_conjugate section open real is_absolute_value finset section variables {α : Type*} {β : Type*} [ring β] [linear_ordered_field α] [archimedean α] {abv : β → α} [is_absolute_value abv] lemma is_cau_of_decreasing_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, |f n| ≤ a) (hnm : ∀ n ≥ m, f n.succ ≤ f n) : is_cau_seq abs f := λ ε ε0, let ⟨k, hk⟩ := archimedean.arch a ε0 in have h : ∃ l, ∀ n ≥ m, a - l • ε < f n := ⟨k + k + 1, λ n hnm, lt_of_lt_of_le (show a - (k + (k + 1)) • ε < -|f n|, from lt_neg.1 $ lt_of_le_of_lt (ham n hnm) (begin rw [neg_sub, lt_sub_iff_add_lt, add_nsmul, add_nsmul, one_nsmul], exact add_lt_add_of_le_of_lt hk (lt_of_le_of_lt hk (lt_add_of_pos_right _ ε0)), end)) (neg_le.2 $ (abs_neg (f n)) ▸ le_abs_self _)⟩, let l := nat.find h in have hl : ∀ (n : ℕ), n ≥ m → f n > a - l • ε := nat.find_spec h, have hl0 : l ≠ 0 := λ hl0, not_lt_of_ge (ham m le_rfl) (lt_of_lt_of_le (by have := hl m (le_refl m); simpa [hl0] using this) (le_abs_self (f m))), begin cases not_forall.1 (nat.find_min h (nat.pred_lt hl0)) with i hi, rw [not_imp, not_lt] at hi, existsi i, assume j hj, have hfij : f j ≤ f i := (nat.rel_of_forall_rel_succ_of_le_of_le (≥) hnm hi.1 hj).le, rw [abs_of_nonpos (sub_nonpos.2 hfij), neg_sub, sub_lt_iff_lt_add'], calc f i ≤ a - (nat.pred l) • ε : hi.2 ... = a - l • ε + ε : by conv {to_rhs, rw [← nat.succ_pred_eq_of_pos (nat.pos_of_ne_zero hl0), succ_nsmul', sub_add, add_sub_cancel] } ... < f j + ε : add_lt_add_right (hl j (le_trans hi.1 hj)) _ end lemma is_cau_of_mono_bounded (f : ℕ → α) {a : α} {m : ℕ} (ham : ∀ n ≥ m, |f n| ≤ a) (hnm : ∀ n ≥ m, f n ≤ f n.succ) : is_cau_seq abs f := begin refine @eq.rec_on (ℕ → α) _ (is_cau_seq abs) _ _ (-⟨_, @is_cau_of_decreasing_bounded _ _ _ (λ n, -f n) a m (by simpa) (by simpa)⟩ : cau_seq α abs).2, ext, exact neg_neg _ end end section no_archimedean variables {α : Type*} {β : Type*} [ring β] [linear_ordered_field α] {abv : β → α} [is_absolute_value abv] lemma is_cau_series_of_abv_le_cau {f : ℕ → β} {g : ℕ → α} (n : ℕ) : (∀ m, n ≤ m → abv (f m) ≤ g m) → is_cau_seq abs (λ n, ∑ i in range n, g i) → is_cau_seq abv (λ n, ∑ i in range n, f i) := begin assume hm hg ε ε0, cases hg (ε / 2) (div_pos ε0 (by norm_num)) with i hi, existsi max n i, assume j ji, have hi₁ := hi j (le_trans (le_max_right n i) ji), have hi₂ := hi (max n i) (le_max_right n i), have sub_le := abs_sub_le (∑ k in range j, g k) (∑ k in range i, g k) (∑ k in range (max n i), g k), have := add_lt_add hi₁ hi₂, rw [abs_sub_comm (∑ k in range (max n i), g k), add_halves ε] at this, refine lt_of_le_of_lt (le_trans (le_trans _ (le_abs_self _)) sub_le) this, generalize hk : j - max n i = k, clear this hi₂ hi₁ hi ε0 ε hg sub_le, rw tsub_eq_iff_eq_add_of_le ji at hk, rw hk, clear hk ji j, induction k with k' hi, { simp [abv_zero abv] }, { simp only [nat.succ_add, sum_range_succ_comm, sub_eq_add_neg, add_assoc], refine le_trans (abv_add _ _ _) _, simp only [sub_eq_add_neg] at hi, exact add_le_add (hm _ (le_add_of_nonneg_of_le (nat.zero_le _) (le_max_left _ _))) hi }, end lemma is_cau_series_of_abv_cau {f : ℕ → β} : is_cau_seq abs (λ m, ∑ n in range m, abv (f n)) → is_cau_seq abv (λ m, ∑ n in range m, f n) := is_cau_series_of_abv_le_cau 0 (λ n h, le_rfl) end no_archimedean section variables {α : Type*} [linear_ordered_field α] [archimedean α] lemma is_cau_geo_series {β : Type*} [ring β] [nontrivial β] {abv : β → α} [is_absolute_value abv] (x : β) (hx1 : abv x < 1) : is_cau_seq abv (λ n, ∑ m in range n, x ^ m) := have hx1' : abv x ≠ 1 := λ h, by simpa [h, lt_irrefl] using hx1, is_cau_series_of_abv_cau begin simp only [abv_pow abv, geom_sum_eq hx1'], conv in (_ / _) { rw [← neg_div_neg_eq, neg_sub, neg_sub] }, refine @is_cau_of_mono_bounded _ _ _ _ ((1 : α) / (1 - abv x)) 0 _ _, { assume n hn, rw abs_of_nonneg, refine div_le_div_of_le (le_of_lt $ sub_pos.2 hx1) (sub_le_self _ (abv_pow abv x n ▸ abv_nonneg _ _)), refine div_nonneg (sub_nonneg.2 _) (sub_nonneg.2 $ le_of_lt hx1), clear hn, induction n with n ih, { simp }, { rw [pow_succ, ← one_mul (1 : α)], refine mul_le_mul (le_of_lt hx1) ih (abv_pow abv x n ▸ abv_nonneg _ _) (by norm_num) } }, { assume n hn, refine div_le_div_of_le (le_of_lt $ sub_pos.2 hx1) (sub_le_sub_left _ _), rw [← one_mul (_ ^ n), pow_succ], exact mul_le_mul_of_nonneg_right (le_of_lt hx1) (pow_nonneg (abv_nonneg _ _) _) } end lemma is_cau_geo_series_const (a : α) {x : α} (hx1 : |x| < 1) : is_cau_seq abs (λ m, ∑ n in range m, a * x ^ n) := have is_cau_seq abs (λ m, a * ∑ n in range m, x ^ n) := (cau_seq.const abs a * ⟨_, is_cau_geo_series x hx1⟩).2, by simpa only [mul_sum] variables {β : Type*} [ring β] {abv : β → α} [is_absolute_value abv] lemma series_ratio_test {f : ℕ → β} (n : ℕ) (r : α) (hr0 : 0 ≤ r) (hr1 : r < 1) (h : ∀ m, n ≤ m → abv (f m.succ) ≤ r * abv (f m)) : is_cau_seq abv (λ m, ∑ n in range m, f n) := have har1 : |r| < 1, by rwa abs_of_nonneg hr0, begin refine is_cau_series_of_abv_le_cau n.succ _ (is_cau_geo_series_const (abv (f n.succ) * r⁻¹ ^ n.succ) har1), assume m hmn, cases classical.em (r = 0) with r_zero r_ne_zero, { have m_pos := lt_of_lt_of_le (nat.succ_pos n) hmn, have := h m.pred (nat.le_of_succ_le_succ (by rwa [nat.succ_pred_eq_of_pos m_pos])), simpa [r_zero, nat.succ_pred_eq_of_pos m_pos, pow_succ] }, generalize hk : m - n.succ = k, have r_pos : 0 < r := lt_of_le_of_ne hr0 (ne.symm r_ne_zero), replace hk : m = k + n.succ := (tsub_eq_iff_eq_add_of_le hmn).1 hk, induction k with k ih generalizing m n, { rw [hk, zero_add, mul_right_comm, inv_pow _ _, ← div_eq_mul_inv, mul_div_cancel], exact (ne_of_lt (pow_pos r_pos _)).symm }, { have kn : k + n.succ ≥ n.succ, by rw ← zero_add n.succ; exact add_le_add (zero_le _) (by simp), rw [hk, nat.succ_add, pow_succ' r, ← mul_assoc], exact le_trans (by rw mul_comm; exact h _ (nat.le_of_succ_le kn)) (mul_le_mul_of_nonneg_right (ih (k + n.succ) n h kn rfl) hr0) } end lemma sum_range_diag_flip {α : Type*} [add_comm_monoid α] (n : ℕ) (f : ℕ → ℕ → α) : ∑ m in range n, ∑ k in range (m + 1), f k (m - k) = ∑ m in range n, ∑ k in range (n - m), f m k := by rw [sum_sigma', sum_sigma']; exact sum_bij (λ a _, ⟨a.2, a.1 - a.2⟩) (λ a ha, have h₁ : a.1 < n := mem_range.1 (mem_sigma.1 ha).1, have h₂ : a.2 < nat.succ a.1 := mem_range.1 (mem_sigma.1 ha).2, mem_sigma.2 ⟨mem_range.2 (lt_of_lt_of_le h₂ h₁), mem_range.2 ((tsub_lt_tsub_iff_right (nat.le_of_lt_succ h₂)).2 h₁)⟩) (λ _ _, rfl) (λ ⟨a₁, a₂⟩ ⟨b₁, b₂⟩ ha hb h, have ha : a₁ < n ∧ a₂ ≤ a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 ha).2)⟩, have hb : b₁ < n ∧ b₂ ≤ b₁ := ⟨mem_range.1 (mem_sigma.1 hb).1, nat.le_of_lt_succ (mem_range.1 (mem_sigma.1 hb).2)⟩, have h : a₂ = b₂ ∧ _ := sigma.mk.inj h, have h' : a₁ = b₁ - b₂ + a₂ := (tsub_eq_iff_eq_add_of_le ha.2).1 (eq_of_heq h.2), sigma.mk.inj_iff.2 ⟨tsub_add_cancel_of_le hb.2 ▸ h'.symm ▸ h.1 ▸ rfl, (heq_of_eq h.1)⟩) (λ ⟨a₁, a₂⟩ ha, have ha : a₁ < n ∧ a₂ < n - a₁ := ⟨mem_range.1 (mem_sigma.1 ha).1, (mem_range.1 (mem_sigma.1 ha).2)⟩, ⟨⟨a₂ + a₁, a₁⟩, ⟨mem_sigma.2 ⟨mem_range.2 (lt_tsub_iff_right.1 ha.2), mem_range.2 (nat.lt_succ_of_le (nat.le_add_left _ _))⟩, sigma.mk.inj_iff.2 ⟨rfl, heq_of_eq (add_tsub_cancel_right _ _).symm⟩⟩⟩) end section no_archimedean variables {α : Type*} {β : Type*} [linear_ordered_field α] {abv : β → α} section variables [semiring β] [is_absolute_value abv] lemma abv_sum_le_sum_abv {γ : Type*} (f : γ → β) (s : finset γ) : abv (∑ k in s, f k) ≤ ∑ k in s, abv (f k) := by haveI := classical.dec_eq γ; exact finset.induction_on s (by simp [abv_zero abv]) (λ a s has ih, by rw [sum_insert has, sum_insert has]; exact le_trans (abv_add abv _ _) (add_le_add_left ih _)) end section variables [ring β] [is_absolute_value abv] lemma cauchy_product {a b : ℕ → β} (ha : is_cau_seq abs (λ m, ∑ n in range m, abv (a n))) (hb : is_cau_seq abv (λ m, ∑ n in range m, b n)) (ε : α) (ε0 : 0 < ε) : ∃ i : ℕ, ∀ j ≥ i, abv ((∑ k in range j, a k) * (∑ k in range j, b k) - ∑ n in range j, ∑ m in range (n + 1), a m * b (n - m)) < ε := let ⟨Q, hQ⟩ := cau_seq.bounded ⟨_, hb⟩ in let ⟨P, hP⟩ := cau_seq.bounded ⟨_, ha⟩ in have hP0 : 0 < P, from lt_of_le_of_lt (abs_nonneg _) (hP 0), have hPε0 : 0 < ε / (2 * P), from div_pos ε0 (mul_pos (show (2 : α) > 0, from by norm_num) hP0), let ⟨N, hN⟩ := cau_seq.cauchy₂ ⟨_, hb⟩ hPε0 in have hQε0 : 0 < ε / (4 * Q), from div_pos ε0 (mul_pos (show (0 : α) < 4, by norm_num) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))), let ⟨M, hM⟩ := cau_seq.cauchy₂ ⟨_, ha⟩ hQε0 in ⟨2 * (max N M + 1), λ K hK, have h₁ : ∑ m in range K, ∑ k in range (m + 1), a k * b (m - k) = ∑ m in range K, ∑ n in range (K - m), a m * b n, by simpa using sum_range_diag_flip K (λ m n, a m * b n), have h₂ : (λ i, ∑ k in range (K - i), a i * b k) = (λ i, a i * ∑ k in range (K - i), b k), by simp [finset.mul_sum], have h₃ : ∑ i in range K, a i * ∑ k in range (K - i), b k = ∑ i in range K, a i * (∑ k in range (K - i), b k - ∑ k in range K, b k) + ∑ i in range K, a i * ∑ k in range K, b k, by rw ← sum_add_distrib; simp [(mul_add _ _ _).symm], have two_mul_two : (4 : α) = 2 * 2, by norm_num, have hQ0 : Q ≠ 0, from λ h, by simpa [h, lt_irrefl] using hQε0, have h2Q0 : 2 * Q ≠ 0, from mul_ne_zero two_ne_zero hQ0, have hε : ε / (2 * P) * P + ε / (4 * Q) * (2 * Q) = ε, by rw [← div_div, div_mul_cancel _ (ne.symm (ne_of_lt hP0)), two_mul_two, mul_assoc, ← div_div, div_mul_cancel _ h2Q0, add_halves], have hNMK : max N M + 1 < K, from lt_of_lt_of_le (by rw two_mul; exact lt_add_of_pos_left _ (nat.succ_pos _)) hK, have hKN : N < K, from calc N ≤ max N M : le_max_left _ _ ... < max N M + 1 : nat.lt_succ_self _ ... < K : hNMK, have hsumlesum : ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) ≤ ∑ i in range (max N M + 1), abv (a i) * (ε / (2 * P)), from sum_le_sum (λ m hmJ, mul_le_mul_of_nonneg_left (le_of_lt (hN (K - m) (le_tsub_of_add_le_left (le_trans (by rw two_mul; exact add_le_add (le_of_lt (mem_range.1 hmJ)) (le_trans (le_max_left _ _) (le_of_lt (lt_add_one _)))) hK)) K (le_of_lt hKN))) (abv_nonneg abv _)), have hsumltP : ∑ n in range (max N M + 1), abv (a n) < P := calc ∑ n in range (max N M + 1), abv (a n) = |∑ n in range (max N M + 1), abv (a n)| : eq.symm (abs_of_nonneg (sum_nonneg (λ x h, abv_nonneg abv (a x)))) ... < P : hP (max N M + 1), begin rw [h₁, h₂, h₃, sum_mul, ← sub_sub, sub_right_comm, sub_self, zero_sub, abv_neg abv], refine lt_of_le_of_lt (abv_sum_le_sum_abv _ _) _, suffices : ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) + (∑ i in range K, abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) - ∑ i in range (max N M + 1), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k)) < ε / (2 * P) * P + ε / (4 * Q) * (2 * Q), { rw hε at this, simpa [abv_mul abv] }, refine add_lt_add (lt_of_le_of_lt hsumlesum (by rw [← sum_mul, mul_comm]; exact (mul_lt_mul_left hPε0).mpr hsumltP)) _, rw sum_range_sub_sum_range (le_of_lt hNMK), calc ∑ i in (range K).filter (λ k, max N M + 1 ≤ k), abv (a i) * abv (∑ k in range (K - i), b k - ∑ k in range K, b k) ≤ ∑ i in (range K).filter (λ k, max N M + 1 ≤ k), abv (a i) * (2 * Q) : sum_le_sum (λ n hn, begin refine mul_le_mul_of_nonneg_left _ (abv_nonneg _ _), rw sub_eq_add_neg, refine le_trans (abv_add _ _ _) _, rw [two_mul, abv_neg abv], exact add_le_add (le_of_lt (hQ _)) (le_of_lt (hQ _)), end) ... < ε / (4 * Q) * (2 * Q) : by rw [← sum_mul, ← sum_range_sub_sum_range (le_of_lt hNMK)]; refine (mul_lt_mul_right $ by rw two_mul; exact add_pos (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0)) (lt_of_le_of_lt (abv_nonneg _ _) (hQ 0))).2 (lt_of_le_of_lt (le_abs_self _) (hM _ (le_trans (nat.le_succ_of_le (le_max_right _ _)) (le_of_lt hNMK)) _ (nat.le_succ_of_le (le_max_right _ _)))) end⟩ end end no_archimedean end open finset open cau_seq namespace complex lemma is_cau_abs_exp (z : ℂ) : is_cau_seq has_abs.abs (λ n, ∑ m in range n, abs (z ^ m / m!)) := let ⟨n, hn⟩ := exists_nat_gt (abs z) in have hn0 : (0 : ℝ) < n, from lt_of_le_of_lt (abs_nonneg _) hn, series_ratio_test n (complex.abs z / n) (div_nonneg (complex.abs_nonneg _) (le_of_lt hn0)) (by rwa [div_lt_iff hn0, one_mul]) (λ m hm, by rw [abs_abs, abs_abs, nat.factorial_succ, pow_succ, mul_comm m.succ, nat.cast_mul, ← div_div, mul_div_assoc, mul_div_right_comm, abs_mul, abs_div, abs_cast_nat]; exact mul_le_mul_of_nonneg_right (div_le_div_of_le_left (abs_nonneg _) hn0 (nat.cast_le.2 (le_trans hm (nat.le_succ _)))) (abs_nonneg _)) noncomputable theory lemma is_cau_exp (z : ℂ) : is_cau_seq abs (λ n, ∑ m in range n, z ^ m / m!) := is_cau_series_of_abv_cau (is_cau_abs_exp z) /-- The Cauchy sequence consisting of partial sums of the Taylor series of the complex exponential function -/ @[pp_nodot] def exp' (z : ℂ) : cau_seq ℂ complex.abs := ⟨λ n, ∑ m in range n, z ^ m / m!, is_cau_exp z⟩ /-- The complex exponential function, defined via its Taylor series -/ @[pp_nodot] def exp (z : ℂ) : ℂ := lim (exp' z) /-- The complex sine function, defined via `exp` -/ @[pp_nodot] def sin (z : ℂ) : ℂ := ((exp (-z * I) - exp (z * I)) * I) / 2 /-- The complex cosine function, defined via `exp` -/ @[pp_nodot] def cos (z : ℂ) : ℂ := (exp (z * I) + exp (-z * I)) / 2 /-- The complex tangent function, defined as `sin z / cos z` -/ @[pp_nodot] def tan (z : ℂ) : ℂ := sin z / cos z /-- The complex hyperbolic sine function, defined via `exp` -/ @[pp_nodot] def sinh (z : ℂ) : ℂ := (exp z - exp (-z)) / 2 /-- The complex hyperbolic cosine function, defined via `exp` -/ @[pp_nodot] def cosh (z : ℂ) : ℂ := (exp z + exp (-z)) / 2 /-- The complex hyperbolic tangent function, defined as `sinh z / cosh z` -/ @[pp_nodot] def tanh (z : ℂ) : ℂ := sinh z / cosh z end complex namespace real open complex /-- The real exponential function, defined as the real part of the complex exponential -/ @[pp_nodot] def exp (x : ℝ) : ℝ := (exp x).re /-- The real sine function, defined as the real part of the complex sine -/ @[pp_nodot] def sin (x : ℝ) : ℝ := (sin x).re /-- The real cosine function, defined as the real part of the complex cosine -/ @[pp_nodot] def cos (x : ℝ) : ℝ := (cos x).re /-- The real tangent function, defined as the real part of the complex tangent -/ @[pp_nodot] def tan (x : ℝ) : ℝ := (tan x).re /-- The real hypebolic sine function, defined as the real part of the complex hyperbolic sine -/ @[pp_nodot] def sinh (x : ℝ) : ℝ := (sinh x).re /-- The real hypebolic cosine function, defined as the real part of the complex hyperbolic cosine -/ @[pp_nodot] def cosh (x : ℝ) : ℝ := (cosh x).re /-- The real hypebolic tangent function, defined as the real part of the complex hyperbolic tangent -/ @[pp_nodot] def tanh (x : ℝ) : ℝ := (tanh x).re end real namespace complex variables (x y : ℂ) @[simp] lemma exp_zero : exp 0 = 1 := lim_eq_of_equiv_const $ λ ε ε0, ⟨1, λ j hj, begin convert ε0, cases j, { exact absurd hj (not_le_of_gt zero_lt_one) }, { dsimp [exp'], induction j with j ih, { dsimp [exp']; simp }, { rw ← ih dec_trivial, simp only [sum_range_succ, pow_succ], simp } } end⟩ lemma exp_add : exp (x + y) = exp x * exp y := show lim (⟨_, is_cau_exp (x + y)⟩ : cau_seq ℂ abs) = lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp x⟩) * lim (show cau_seq ℂ abs, from ⟨_, is_cau_exp y⟩), from have hj : ∀ j : ℕ, ∑ m in range j, (x + y) ^ m / m! = ∑ i in range j, ∑ k in range (i + 1), x ^ k / k! * (y ^ (i - k) / (i - k)!), from assume j, finset.sum_congr rfl (λ m hm, begin rw [add_pow, div_eq_mul_inv, sum_mul], refine finset.sum_congr rfl (λ i hi, _), have h₁ : (m.choose i : ℂ) ≠ 0 := nat.cast_ne_zero.2 (pos_iff_ne_zero.1 (nat.choose_pos (nat.le_of_lt_succ (mem_range.1 hi)))), have h₂ := nat.choose_mul_factorial_mul_factorial (nat.le_of_lt_succ $ finset.mem_range.1 hi), rw [← h₂, nat.cast_mul, nat.cast_mul, mul_inv, mul_inv], simp only [mul_left_comm (m.choose i : ℂ), mul_assoc, mul_left_comm (m.choose i : ℂ)⁻¹, mul_comm (m.choose i : ℂ)], rw inv_mul_cancel h₁, simp [div_eq_mul_inv, mul_comm, mul_assoc, mul_left_comm] end), by rw lim_mul_lim; exact eq.symm (lim_eq_lim_of_equiv (by dsimp; simp only [hj]; exact cauchy_product (is_cau_abs_exp x) (is_cau_exp y))) attribute [irreducible] complex.exp lemma exp_list_sum (l : list ℂ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℂ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℂ) ℂ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℂ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) := @monoid_hom.map_prod (multiplicative ℂ) α ℂ _ _ ⟨exp, exp_zero, exp_add⟩ f s lemma exp_nat_mul (x : ℂ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, zero_ne_one $ by rw [← exp_zero, ← add_neg_self x, exp_add, h]; simp lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← mul_right_inj' (exp_ne_zero x), ← exp_add]; simp [mul_inv_cancel (exp_ne_zero x)] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] lemma exp_int_mul (z : ℂ) (n : ℤ) : complex.exp (n * z) = (complex.exp z) ^ n := begin cases n, { apply complex.exp_nat_mul }, { simpa [complex.exp_neg, add_comm, ← neg_mul] using complex.exp_nat_mul (-z) (1 + n) }, end @[simp] lemma exp_conj : exp (conj x) = conj (exp x) := begin dsimp [exp], rw [← lim_conj], refine congr_arg lim (cau_seq.ext (λ _, _)), dsimp [exp', function.comp, cau_seq_conj], rw (star_ring_end _).map_sum, refine sum_congr rfl (λ n hn, _), rw [map_div₀, map_pow, ← of_real_nat_cast, conj_of_real] end @[simp] lemma of_real_exp_of_real_re (x : ℝ) : ((exp x).re : ℂ) = exp x := eq_conj_iff_re.1 $ by rw [← exp_conj, conj_of_real] @[simp, norm_cast] lemma of_real_exp (x : ℝ) : (real.exp x : ℂ) = exp x := of_real_exp_of_real_re _ @[simp] lemma exp_of_real_im (x : ℝ) : (exp x).im = 0 := by rw [← of_real_exp_of_real_re, of_real_im] lemma exp_of_real_re (x : ℝ) : (exp x).re = real.exp x := rfl lemma two_sinh : 2 * sinh x = exp x - exp (-x) := mul_div_cancel' _ two_ne_zero' lemma two_cosh : 2 * cosh x = exp x + exp (-x) := mul_div_cancel' _ two_ne_zero' @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] private lemma sinh_add_aux {a b c d : ℂ} : (a - b) * (c + d) + (a + b) * (c - d) = 2 * (a * c - b * d) := by ring lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := begin rw [← mul_right_inj' (@two_ne_zero' ℂ _ _), two_sinh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_sinh, mul_left_comm, two_sinh, ← mul_right_inj' (@two_ne_zero' ℂ _ _), mul_add, mul_left_comm, two_cosh, ← mul_assoc, two_cosh], exact sinh_add_aux end @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := by simp [add_comm, cosh, exp_neg] private lemma cosh_add_aux {a b c d : ℂ} : (a + b) * (c + d) + (a - b) * (c - d) = 2 * (a * c + b * d) := by ring lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := begin rw [← mul_right_inj' (@two_ne_zero' ℂ _ _), two_cosh, exp_add, neg_add, exp_add, eq_comm, mul_add, ← mul_assoc, two_cosh, ← mul_assoc, two_sinh, ← mul_right_inj' (@two_ne_zero' ℂ _ _), mul_add, mul_left_comm, two_cosh, mul_left_comm, two_sinh], exact cosh_add_aux end lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg] lemma sinh_conj : sinh (conj x) = conj (sinh x) := by rw [sinh, ← ring_hom.map_neg, exp_conj, exp_conj, ← ring_hom.map_sub, sinh, map_div₀, conj_bit0, ring_hom.map_one] @[simp] lemma of_real_sinh_of_real_re (x : ℝ) : ((sinh x).re : ℂ) = sinh x := eq_conj_iff_re.1 $ by rw [← sinh_conj, conj_of_real] @[simp, norm_cast] lemma of_real_sinh (x : ℝ) : (real.sinh x : ℂ) = sinh x := of_real_sinh_of_real_re _ @[simp] lemma sinh_of_real_im (x : ℝ) : (sinh x).im = 0 := by rw [← of_real_sinh_of_real_re, of_real_im] lemma sinh_of_real_re (x : ℝ) : (sinh x).re = real.sinh x := rfl lemma cosh_conj : cosh (conj x) = conj (cosh x) := begin rw [cosh, ← ring_hom.map_neg, exp_conj, exp_conj, ← ring_hom.map_add, cosh, map_div₀, conj_bit0, ring_hom.map_one] end lemma of_real_cosh_of_real_re (x : ℝ) : ((cosh x).re : ℂ) = cosh x := eq_conj_iff_re.1 $ by rw [← cosh_conj, conj_of_real] @[simp, norm_cast] lemma of_real_cosh (x : ℝ) : (real.cosh x : ℂ) = cosh x := of_real_cosh_of_real_re _ @[simp] lemma cosh_of_real_im (x : ℝ) : (cosh x).im = 0 := by rw [← of_real_cosh_of_real_re, of_real_im] @[simp] lemma cosh_of_real_re (x : ℝ) : (cosh x).re = real.cosh x := rfl lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := rfl @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] lemma tanh_conj : tanh (conj x) = conj (tanh x) := by rw [tanh, sinh_conj, cosh_conj, ← map_div₀, tanh] @[simp] lemma of_real_tanh_of_real_re (x : ℝ) : ((tanh x).re : ℂ) = tanh x := eq_conj_iff_re.1 $ by rw [← tanh_conj, conj_of_real] @[simp, norm_cast] lemma of_real_tanh (x : ℝ) : (real.tanh x : ℂ) = tanh x := of_real_tanh_of_real_re _ @[simp] lemma tanh_of_real_im (x : ℝ) : (tanh x).im = 0 := by rw [← of_real_tanh_of_real_re, of_real_im] lemma tanh_of_real_re (x : ℝ) : (tanh x).re = real.tanh x := rfl @[simp] lemma cosh_add_sinh : cosh x + sinh x = exp x := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _), mul_add, two_cosh, two_sinh, add_add_sub_cancel, two_mul] @[simp] lemma sinh_add_cosh : sinh x + cosh x = exp x := by rw [add_comm, cosh_add_sinh] @[simp] lemma exp_sub_cosh : exp x - cosh x = sinh x := sub_eq_iff_eq_add.2 (sinh_add_cosh x).symm @[simp] lemma exp_sub_sinh : exp x - sinh x = cosh x := sub_eq_iff_eq_add.2 (cosh_add_sinh x).symm @[simp] lemma cosh_sub_sinh : cosh x - sinh x = exp (-x) := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _), mul_sub, two_cosh, two_sinh, add_sub_sub_cancel, two_mul] @[simp] lemma sinh_sub_cosh : sinh x - cosh x = -exp (-x) := by rw [← neg_sub, cosh_sub_sinh] @[simp] lemma cosh_sq_sub_sinh_sq : cosh x ^ 2 - sinh x ^ 2 = 1 := by rw [sq_sub_sq, cosh_add_sinh, cosh_sub_sinh, ← exp_add, add_neg_self, exp_zero] lemma cosh_sq : cosh x ^ 2 = sinh x ^ 2 + 1 := begin rw ← cosh_sq_sub_sinh_sq x, ring end lemma sinh_sq : sinh x ^ 2 = cosh x ^ 2 - 1 := begin rw ← cosh_sq_sub_sinh_sq x, ring end lemma cosh_two_mul : cosh (2 * x) = cosh x ^ 2 + sinh x ^ 2 := by rw [two_mul, cosh_add, sq, sq] lemma sinh_two_mul : sinh (2 * x) = 2 * sinh x * cosh x := begin rw [two_mul, sinh_add], ring end lemma cosh_three_mul : cosh (3 * x) = 4 * cosh x ^ 3 - 3 * cosh x := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, cosh_add x (2 * x)], simp only [cosh_two_mul, sinh_two_mul], have h2 : sinh x * (2 * sinh x * cosh x) = 2 * cosh x * sinh x ^ 2, by ring, rw [h2, sinh_sq], ring end lemma sinh_three_mul : sinh (3 * x) = 4 * sinh x ^ 3 + 3 * sinh x := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, sinh_add x (2 * x)], simp only [cosh_two_mul, sinh_two_mul], have h2 : cosh x * (2 * sinh x * cosh x) = 2 * sinh x * cosh x ^ 2, by ring, rw [h2, cosh_sq], ring, end @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, sub_eq_add_neg, exp_neg, (neg_div _ _).symm, add_mul] lemma two_sin : 2 * sin x = (exp (-x * I) - exp (x * I)) * I := mul_div_cancel' _ two_ne_zero' lemma two_cos : 2 * cos x = exp (x * I) + exp (-x * I) := mul_div_cancel' _ two_ne_zero' lemma sinh_mul_I : sinh (x * I) = sin x * I := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _), two_sinh, ← mul_assoc, two_sin, mul_assoc, I_mul_I, mul_neg_one, neg_sub, neg_mul_eq_neg_mul] lemma cosh_mul_I : cosh (x * I) = cos x := by rw [← mul_right_inj' (@two_ne_zero' ℂ _ _), two_cosh, two_cos, neg_mul_eq_neg_mul] lemma tanh_mul_I : tanh (x * I) = tan x * I := by rw [tanh_eq_sinh_div_cosh, cosh_mul_I, sinh_mul_I, mul_div_right_comm, tan] lemma cos_mul_I : cos (x * I) = cosh x := by rw ← cosh_mul_I; ring_nf; simp lemma sin_mul_I : sin (x * I) = sinh x * I := have h : I * sin (x * I) = -sinh x := by { rw [mul_comm, ← sinh_mul_I], ring_nf, simp }, by simpa only [neg_mul, div_I, neg_neg] using cancel_factors.cancel_factors_eq_div h I_ne_zero lemma tan_mul_I : tan (x * I) = tanh x * I := by rw [tan, sin_mul_I, cos_mul_I, mul_div_right_comm, tanh_eq_sinh_div_cosh] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← mul_left_inj' I_ne_zero, ← sinh_mul_I, add_mul, add_mul, mul_right_comm, ← sinh_mul_I, mul_assoc, ← sinh_mul_I, ← cosh_mul_I, ← cosh_mul_I, sinh_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, sub_eq_add_neg, exp_neg, add_comm] private lemma cos_add_aux {a b c d : ℂ} : (a + b) * (c + d) - (b - a) * (d - c) * (-1) = 2 * (a * c + b * d) := by ring lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw [← cosh_mul_I, add_mul, cosh_add, cosh_mul_I, cosh_mul_I, sinh_mul_I, sinh_mul_I, mul_mul_mul_comm, I_mul_I, mul_neg_one, sub_eq_add_neg] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] lemma sin_add_mul_I (x y : ℂ) : sin (x + y*I) = sin x * cosh y + cos x * sinh y * I := by rw [sin_add, cos_mul_I, sin_mul_I, mul_assoc] lemma sin_eq (z : ℂ) : sin z = sin z.re * cosh z.im + cos z.re * sinh z.im * I := by convert sin_add_mul_I z.re z.im; exact (re_add_im z).symm lemma cos_add_mul_I (x y : ℂ) : cos (x + y*I) = cos x * cosh y - sin x * sinh y * I := by rw [cos_add, cos_mul_I, sin_mul_I, mul_assoc] lemma cos_eq (z : ℂ) : cos z = cos z.re * cosh z.im - sin z.re * sinh z.im * I := by convert cos_add_mul_I z.re z.im; exact (re_add_im z).symm theorem sin_sub_sin : sin x - sin y = 2 * sin((x - y)/2) * cos((x + y)/2) := begin have s1 := sin_add ((x + y) / 2) ((x - y) / 2), have s2 := sin_sub ((x + y) / 2) ((x - y) / 2), rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, half_add_self] at s1, rw [div_sub_div_same, ←sub_add, add_sub_cancel', half_add_self] at s2, rw [s1, s2], ring end theorem cos_sub_cos : cos x - cos y = -2 * sin((x + y)/2) * sin((x - y)/2) := begin have s1 := cos_add ((x + y) / 2) ((x - y) / 2), have s2 := cos_sub ((x + y) / 2) ((x - y) / 2), rw [div_add_div_same, add_sub, add_right_comm, add_sub_cancel, half_add_self] at s1, rw [div_sub_div_same, ←sub_add, add_sub_cancel', half_add_self] at s2, rw [s1, s2], ring, end lemma cos_add_cos : cos x + cos y = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) := begin have h2 : (2:ℂ) ≠ 0 := by norm_num, calc cos x + cos y = cos ((x + y) / 2 + (x - y) / 2) + cos ((x + y) / 2 - (x - y) / 2) : _ ... = (cos ((x + y) / 2) * cos ((x - y) / 2) - sin ((x + y) / 2) * sin ((x - y) / 2)) + (cos ((x + y) / 2) * cos ((x - y) / 2) + sin ((x + y) / 2) * sin ((x - y) / 2)) : _ ... = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) : _, { congr; field_simp [h2]; ring }, { rw [cos_add, cos_sub] }, ring, end lemma sin_conj : sin (conj x) = conj (sin x) := by rw [← mul_left_inj' I_ne_zero, ← sinh_mul_I, ← conj_neg_I, ← ring_hom.map_mul, ← ring_hom.map_mul, sinh_conj, mul_neg, sinh_neg, sinh_mul_I, mul_neg] @[simp] lemma of_real_sin_of_real_re (x : ℝ) : ((sin x).re : ℂ) = sin x := eq_conj_iff_re.1 $ by rw [← sin_conj, conj_of_real] @[simp, norm_cast] lemma of_real_sin (x : ℝ) : (real.sin x : ℂ) = sin x := of_real_sin_of_real_re _ @[simp] lemma sin_of_real_im (x : ℝ) : (sin x).im = 0 := by rw [← of_real_sin_of_real_re, of_real_im] lemma sin_of_real_re (x : ℝ) : (sin x).re = real.sin x := rfl lemma cos_conj : cos (conj x) = conj (cos x) := by rw [← cosh_mul_I, ← conj_neg_I, ← ring_hom.map_mul, ← cosh_mul_I, cosh_conj, mul_neg, cosh_neg] @[simp] lemma of_real_cos_of_real_re (x : ℝ) : ((cos x).re : ℂ) = cos x := eq_conj_iff_re.1 $ by rw [← cos_conj, conj_of_real] @[simp, norm_cast] lemma of_real_cos (x : ℝ) : (real.cos x : ℂ) = cos x := of_real_cos_of_real_re _ @[simp] lemma cos_of_real_im (x : ℝ) : (cos x).im = 0 := by rw [← of_real_cos_of_real_re, of_real_im] lemma cos_of_real_re (x : ℝ) : (cos x).re = real.cos x := rfl @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] lemma tan_eq_sin_div_cos : tan x = sin x / cos x := rfl lemma tan_mul_cos {x : ℂ} (hx : cos x ≠ 0) : tan x * cos x = sin x := by rw [tan_eq_sin_div_cos, div_mul_cancel _ hx] @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] lemma tan_conj : tan (conj x) = conj (tan x) := by rw [tan, sin_conj, cos_conj, ← map_div₀, tan] @[simp] lemma of_real_tan_of_real_re (x : ℝ) : ((tan x).re : ℂ) = tan x := eq_conj_iff_re.1 $ by rw [← tan_conj, conj_of_real] @[simp, norm_cast] lemma of_real_tan (x : ℝ) : (real.tan x : ℂ) = tan x := of_real_tan_of_real_re _ @[simp] lemma tan_of_real_im (x : ℝ) : (tan x).im = 0 := by rw [← of_real_tan_of_real_re, of_real_im] lemma tan_of_real_re (x : ℝ) : (tan x).re = real.tan x := rfl lemma cos_add_sin_I : cos x + sin x * I = exp (x * I) := by rw [← cosh_add_sinh, sinh_mul_I, cosh_mul_I] lemma cos_sub_sin_I : cos x - sin x * I = exp (-x * I) := by rw [neg_mul, ← cosh_sub_sinh, sinh_mul_I, cosh_mul_I] @[simp] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := eq.trans (by rw [cosh_mul_I, sinh_mul_I, mul_pow, I_sq, mul_neg_one, sub_neg_eq_add, add_comm]) (cosh_sq_sub_sinh_sq (x * I)) @[simp] lemma cos_sq_add_sin_sq : cos x ^ 2 + sin x ^ 2 = 1 := by rw [add_comm, sin_sq_add_cos_sq] lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 := by rw [two_mul, cos_add, ← sq, ← sq] lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw [cos_two_mul', eq_sub_iff_add_eq.2 (sin_sq_add_cos_sq x), ← sub_add, sub_add_eq_add_sub, two_mul] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw [two_mul, sin_add, two_mul, add_mul, mul_comm] lemma cos_sq : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := by simp [cos_two_mul, div_add_div_same, mul_div_cancel_left, two_ne_zero', -one_div] lemma cos_sq' : cos x ^ 2 = 1 - sin x ^ 2 := by rw [←sin_sq_add_cos_sq x, add_sub_cancel'] lemma sin_sq : sin x ^ 2 = 1 - cos x ^ 2 := by rw [←sin_sq_add_cos_sq x, add_sub_cancel] lemma inv_one_add_tan_sq {x : ℂ} (hx : cos x ≠ 0) : (1 + tan x ^ 2)⁻¹ = cos x ^ 2 := have cos x ^ 2 ≠ 0, from pow_ne_zero 2 hx, by { rw [tan_eq_sin_div_cos, div_pow], field_simp [this] } lemma tan_sq_div_one_add_tan_sq {x : ℂ} (hx : cos x ≠ 0) : tan x ^ 2 / (1 + tan x ^ 2) = sin x ^ 2 := by simp only [← tan_mul_cos hx, mul_pow, ← inv_one_add_tan_sq hx, div_eq_mul_inv, one_mul] lemma cos_three_mul : cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, cos_add x (2 * x)], simp only [cos_two_mul, sin_two_mul, mul_add, mul_sub, mul_one, sq], have h2 : 4 * cos x ^ 3 = 2 * cos x * cos x * cos x + 2 * cos x * cos x ^ 2, by ring, rw [h2, cos_sq'], ring end lemma sin_three_mul : sin (3 * x) = 3 * sin x - 4 * sin x ^ 3 := begin have h1 : x + 2 * x = 3 * x, by ring, rw [← h1, sin_add x (2 * x)], simp only [cos_two_mul, sin_two_mul, cos_sq'], have h2 : cos x * (2 * sin x * cos x) = 2 * sin x * cos x ^ 2, by ring, rw [h2, cos_sq'], ring end lemma exp_mul_I : exp (x * I) = cos x + sin x * I := (cos_add_sin_I _).symm lemma exp_add_mul_I : exp (x + y * I) = exp x * (cos y + sin y * I) := by rw [exp_add, exp_mul_I] lemma exp_eq_exp_re_mul_sin_add_cos : exp x = exp x.re * (cos x.im + sin x.im * I) := by rw [← exp_add_mul_I, re_add_im] lemma exp_re : (exp x).re = real.exp x.re * real.cos x.im := by { rw [exp_eq_exp_re_mul_sin_add_cos], simp [exp_of_real_re, cos_of_real_re] } lemma exp_im : (exp x).im = real.exp x.re * real.sin x.im := by { rw [exp_eq_exp_re_mul_sin_add_cos], simp [exp_of_real_re, sin_of_real_re] } @[simp] lemma exp_of_real_mul_I_re (x : ℝ) : (exp (x * I)).re = real.cos x := by simp [exp_mul_I, cos_of_real_re] @[simp] lemma exp_of_real_mul_I_im (x : ℝ) : (exp (x * I)).im = real.sin x := by simp [exp_mul_I, sin_of_real_re] /-- **De Moivre's formula** -/ theorem cos_add_sin_mul_I_pow (n : ℕ) (z : ℂ) : (cos z + sin z * I) ^ n = cos (↑n * z) + sin (↑n * z) * I := begin rw [← exp_mul_I, ← exp_mul_I], induction n with n ih, { rw [pow_zero, nat.cast_zero, zero_mul, zero_mul, exp_zero] }, { rw [pow_succ', ih, nat.cast_succ, add_mul, add_mul, one_mul, exp_add] } end end complex namespace real open complex variables (x y : ℝ) @[simp] lemma exp_zero : exp 0 = 1 := by simp [real.exp] lemma exp_add : exp (x + y) = exp x * exp y := by simp [exp_add, exp] lemma exp_list_sum (l : list ℝ) : exp l.sum = (l.map exp).prod := @monoid_hom.map_list_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ l lemma exp_multiset_sum (s : multiset ℝ) : exp s.sum = (s.map exp).prod := @monoid_hom.map_multiset_prod (multiplicative ℝ) ℝ _ _ ⟨exp, exp_zero, exp_add⟩ s lemma exp_sum {α : Type*} (s : finset α) (f : α → ℝ) : exp (∑ x in s, f x) = ∏ x in s, exp (f x) := @monoid_hom.map_prod (multiplicative ℝ) α ℝ _ _ ⟨exp, exp_zero, exp_add⟩ f s lemma exp_nat_mul (x : ℝ) : ∀ n : ℕ, exp(n*x) = (exp x)^n | 0 := by rw [nat.cast_zero, zero_mul, exp_zero, pow_zero] | (nat.succ n) := by rw [pow_succ', nat.cast_add_one, add_mul, exp_add, ←exp_nat_mul, one_mul] lemma exp_ne_zero : exp x ≠ 0 := λ h, exp_ne_zero x $ by rw [exp, ← of_real_inj] at h; simp * at * lemma exp_neg : exp (-x) = (exp x)⁻¹ := by rw [← of_real_inj, exp, of_real_exp_of_real_re, of_real_neg, exp_neg, of_real_inv, of_real_exp] lemma exp_sub : exp (x - y) = exp x / exp y := by simp [sub_eq_add_neg, exp_add, exp_neg, div_eq_mul_inv] @[simp] lemma sin_zero : sin 0 = 0 := by simp [sin] @[simp] lemma sin_neg : sin (-x) = -sin x := by simp [sin, exp_neg, (neg_div _ _).symm, add_mul] lemma sin_add : sin (x + y) = sin x * cos y + cos x * sin y := by rw [← of_real_inj]; simp [sin, sin_add] @[simp] lemma cos_zero : cos 0 = 1 := by simp [cos] @[simp] lemma cos_neg : cos (-x) = cos x := by simp [cos, exp_neg] @[simp] lemma cos_abs : cos (|x|) = cos x := by cases le_total x 0; simp only [*, _root_.abs_of_nonneg, abs_of_nonpos, cos_neg] lemma cos_add : cos (x + y) = cos x * cos y - sin x * sin y := by rw ← of_real_inj; simp [cos, cos_add] lemma sin_sub : sin (x - y) = sin x * cos y - cos x * sin y := by simp [sub_eq_add_neg, sin_add, sin_neg, cos_neg] lemma cos_sub : cos (x - y) = cos x * cos y + sin x * sin y := by simp [sub_eq_add_neg, cos_add, sin_neg, cos_neg] lemma sin_sub_sin : sin x - sin y = 2 * sin((x - y)/2) * cos((x + y)/2) := begin rw ← of_real_inj, simp only [sin, cos, of_real_sin_of_real_re, of_real_sub, of_real_add, of_real_div, of_real_mul, of_real_one, of_real_bit0], convert sin_sub_sin _ _; norm_cast end theorem cos_sub_cos : cos x - cos y = -2 * sin((x + y)/2) * sin((x - y)/2) := begin rw ← of_real_inj, simp only [cos, neg_mul, of_real_sin, of_real_sub, of_real_add, of_real_cos_of_real_re, of_real_div, of_real_mul, of_real_one, of_real_neg, of_real_bit0], convert cos_sub_cos _ _, ring, end lemma cos_add_cos : cos x + cos y = 2 * cos ((x + y) / 2) * cos ((x - y) / 2) := begin rw ← of_real_inj, simp only [cos, of_real_sub, of_real_add, of_real_cos_of_real_re, of_real_div, of_real_mul, of_real_one, of_real_bit0], convert cos_add_cos _ _; norm_cast, end lemma tan_eq_sin_div_cos : tan x = sin x / cos x := by rw [← of_real_inj, of_real_tan, tan_eq_sin_div_cos, of_real_div, of_real_sin, of_real_cos] lemma tan_mul_cos {x : ℝ} (hx : cos x ≠ 0) : tan x * cos x = sin x := by rw [tan_eq_sin_div_cos, div_mul_cancel _ hx] @[simp] lemma tan_zero : tan 0 = 0 := by simp [tan] @[simp] lemma tan_neg : tan (-x) = -tan x := by simp [tan, neg_div] @[simp] lemma sin_sq_add_cos_sq : sin x ^ 2 + cos x ^ 2 = 1 := of_real_inj.1 $ by simp @[simp] lemma cos_sq_add_sin_sq : cos x ^ 2 + sin x ^ 2 = 1 := by rw [add_comm, sin_sq_add_cos_sq] lemma sin_sq_le_one : sin x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_right (sq_nonneg _) lemma cos_sq_le_one : cos x ^ 2 ≤ 1 := by rw ← sin_sq_add_cos_sq x; exact le_add_of_nonneg_left (sq_nonneg _) lemma abs_sin_le_one : |sin x| ≤ 1 := abs_le_one_iff_mul_self_le_one.2 $ by simp only [← sq, sin_sq_le_one] lemma abs_cos_le_one : |cos x| ≤ 1 := abs_le_one_iff_mul_self_le_one.2 $ by simp only [← sq, cos_sq_le_one] lemma sin_le_one : sin x ≤ 1 := (abs_le.1 (abs_sin_le_one _)).2 lemma cos_le_one : cos x ≤ 1 := (abs_le.1 (abs_cos_le_one _)).2 lemma neg_one_le_sin : -1 ≤ sin x := (abs_le.1 (abs_sin_le_one _)).1 lemma neg_one_le_cos : -1 ≤ cos x := (abs_le.1 (abs_cos_le_one _)).1 lemma cos_two_mul : cos (2 * x) = 2 * cos x ^ 2 - 1 := by rw ← of_real_inj; simp [cos_two_mul] lemma cos_two_mul' : cos (2 * x) = cos x ^ 2 - sin x ^ 2 := by rw ← of_real_inj; simp [cos_two_mul'] lemma sin_two_mul : sin (2 * x) = 2 * sin x * cos x := by rw ← of_real_inj; simp [sin_two_mul] lemma cos_sq : cos x ^ 2 = 1 / 2 + cos (2 * x) / 2 := of_real_inj.1 $ by simpa using cos_sq x lemma cos_sq' : cos x ^ 2 = 1 - sin x ^ 2 := by rw [←sin_sq_add_cos_sq x, add_sub_cancel'] lemma sin_sq : sin x ^ 2 = 1 - cos x ^ 2 := eq_sub_iff_add_eq.2 $ sin_sq_add_cos_sq _ lemma abs_sin_eq_sqrt_one_sub_cos_sq (x : ℝ) : |sin x| = sqrt (1 - cos x ^ 2) := by rw [← sin_sq, sqrt_sq_eq_abs] lemma abs_cos_eq_sqrt_one_sub_sin_sq (x : ℝ) : |cos x| = sqrt (1 - sin x ^ 2) := by rw [← cos_sq', sqrt_sq_eq_abs] lemma inv_one_add_tan_sq {x : ℝ} (hx : cos x ≠ 0) : (1 + tan x ^ 2)⁻¹ = cos x ^ 2 := have complex.cos x ≠ 0, from mt (congr_arg re) hx, of_real_inj.1 $ by simpa using complex.inv_one_add_tan_sq this lemma tan_sq_div_one_add_tan_sq {x : ℝ} (hx : cos x ≠ 0) : tan x ^ 2 / (1 + tan x ^ 2) = sin x ^ 2 := by simp only [← tan_mul_cos hx, mul_pow, ← inv_one_add_tan_sq hx, div_eq_mul_inv, one_mul] lemma inv_sqrt_one_add_tan_sq {x : ℝ} (hx : 0 < cos x) : (sqrt (1 + tan x ^ 2))⁻¹ = cos x := by rw [← sqrt_sq hx.le, ← sqrt_inv, inv_one_add_tan_sq hx.ne'] lemma tan_div_sqrt_one_add_tan_sq {x : ℝ} (hx : 0 < cos x) : tan x / sqrt (1 + tan x ^ 2) = sin x := by rw [← tan_mul_cos hx.ne', ← inv_sqrt_one_add_tan_sq hx, div_eq_mul_inv] lemma cos_three_mul : cos (3 * x) = 4 * cos x ^ 3 - 3 * cos x := by rw ← of_real_inj; simp [cos_three_mul] lemma sin_three_mul : sin (3 * x) = 3 * sin x - 4 * sin x ^ 3 := by rw ← of_real_inj; simp [sin_three_mul] /-- The definition of `sinh` in terms of `exp`. -/ lemma sinh_eq (x : ℝ) : sinh x = (exp x - exp (-x)) / 2 := eq_div_of_mul_eq two_ne_zero $ by rw [sinh, exp, exp, complex.of_real_neg, complex.sinh, mul_two, ← complex.add_re, ← mul_two, div_mul_cancel _ (two_ne_zero' : (2 : ℂ) ≠ 0), complex.sub_re] @[simp] lemma sinh_zero : sinh 0 = 0 := by simp [sinh] @[simp] lemma sinh_neg : sinh (-x) = -sinh x := by simp [sinh, exp_neg, (neg_div _ _).symm, add_mul] lemma sinh_add : sinh (x + y) = sinh x * cosh y + cosh x * sinh y := by rw ← of_real_inj; simp [sinh_add] /-- The definition of `cosh` in terms of `exp`. -/ lemma cosh_eq (x : ℝ) : cosh x = (exp x + exp (-x)) / 2 := eq_div_of_mul_eq two_ne_zero $ by rw [cosh, exp, exp, complex.of_real_neg, complex.cosh, mul_two, ← complex.add_re, ← mul_two, div_mul_cancel _ (two_ne_zero' : (2 : ℂ) ≠ 0), complex.add_re] @[simp] lemma cosh_zero : cosh 0 = 1 := by simp [cosh] @[simp] lemma cosh_neg : cosh (-x) = cosh x := of_real_inj.1 $ by simp @[simp] lemma cosh_abs : cosh (|x|) = cosh x := by cases le_total x 0; simp [*, _root_.abs_of_nonneg, abs_of_nonpos] lemma cosh_add : cosh (x + y) = cosh x * cosh y + sinh x * sinh y := by rw ← of_real_inj; simp [cosh_add] lemma sinh_sub : sinh (x - y) = sinh x * cosh y - cosh x * sinh y := by simp [sub_eq_add_neg, sinh_add, sinh_neg, cosh_neg] lemma cosh_sub : cosh (x - y) = cosh x * cosh y - sinh x * sinh y := by simp [sub_eq_add_neg, cosh_add, sinh_neg, cosh_neg] lemma tanh_eq_sinh_div_cosh : tanh x = sinh x / cosh x := of_real_inj.1 $ by simp [tanh_eq_sinh_div_cosh] @[simp] lemma tanh_zero : tanh 0 = 0 := by simp [tanh] @[simp] lemma tanh_neg : tanh (-x) = -tanh x := by simp [tanh, neg_div] @[simp] lemma cosh_add_sinh : cosh x + sinh x = exp x := by rw ← of_real_inj; simp @[simp] lemma sinh_add_cosh : sinh x + cosh x = exp x := by rw [add_comm, cosh_add_sinh] @[simp] lemma exp_sub_cosh : exp x - cosh x = sinh x := sub_eq_iff_eq_add.2 (sinh_add_cosh x).symm @[simp] lemma exp_sub_sinh : exp x - sinh x = cosh x := sub_eq_iff_eq_add.2 (cosh_add_sinh x).symm @[simp] lemma cosh_sub_sinh : cosh x - sinh x = exp (-x) := by { rw [← of_real_inj], simp } @[simp] lemma sinh_sub_cosh : sinh x - cosh x = -exp (-x) := by rw [← neg_sub, cosh_sub_sinh] @[simp] lemma cosh_sq_sub_sinh_sq (x : ℝ) : cosh x ^ 2 - sinh x ^ 2 = 1 := by rw ← of_real_inj; simp lemma cosh_sq : cosh x ^ 2 = sinh x ^ 2 + 1 := by rw ← of_real_inj; simp [cosh_sq] lemma cosh_sq' : cosh x ^ 2 = 1 + sinh x ^ 2 := (cosh_sq x).trans (add_comm _ _) lemma sinh_sq : sinh x ^ 2 = cosh x ^ 2 - 1 := by rw ← of_real_inj; simp [sinh_sq] lemma cosh_two_mul : cosh (2 * x) = cosh x ^ 2 + sinh x ^ 2 := by rw ← of_real_inj; simp [cosh_two_mul] lemma sinh_two_mul : sinh (2 * x) = 2 * sinh x * cosh x := by rw ← of_real_inj; simp [sinh_two_mul] lemma cosh_three_mul : cosh (3 * x) = 4 * cosh x ^ 3 - 3 * cosh x := by rw ← of_real_inj; simp [cosh_three_mul] lemma sinh_three_mul : sinh (3 * x) = 4 * sinh x ^ 3 + 3 * sinh x := by rw ← of_real_inj; simp [sinh_three_mul] open is_absolute_value /-- This is an intermediate result that is later replaced by `real.add_one_le_exp`; use that lemma instead. -/ lemma add_one_le_exp_of_nonneg {x : ℝ} (hx : 0 ≤ x) : x + 1 ≤ exp x := calc x + 1 ≤ lim (⟨(λ n : ℕ, ((exp' x) n).re), is_cau_seq_re (exp' x)⟩ : cau_seq ℝ has_abs.abs) : le_lim (cau_seq.le_of_exists ⟨2, λ j hj, show x + (1 : ℝ) ≤ (∑ m in range j, (x ^ m / m! : ℂ)).re, from have h₁ : (((λ m : ℕ, (x ^ m / m! : ℂ)) ∘ nat.succ) 0).re = x, by simp, have h₂ : ((x : ℂ) ^ 0 / 0!).re = 1, by simp, begin rw [← tsub_add_cancel_of_le hj, sum_range_succ', sum_range_succ', add_re, add_re, h₁, h₂, add_assoc, ← coe_re_add_group_hom, (re_add_group_hom).map_sum, coe_re_add_group_hom ], refine le_add_of_nonneg_of_le (sum_nonneg (λ m hm, _)) le_rfl, rw [← of_real_pow, ← of_real_nat_cast, ← of_real_div, of_real_re], exact div_nonneg (pow_nonneg hx _) (nat.cast_nonneg _), end⟩) ... = exp x : by rw [exp, complex.exp, ← cau_seq_re, lim_re] lemma one_le_exp {x : ℝ} (hx : 0 ≤ x) : 1 ≤ exp x := by linarith [add_one_le_exp_of_nonneg hx] lemma exp_pos (x : ℝ) : 0 < exp x := (le_total 0 x).elim (lt_of_lt_of_le zero_lt_one ∘ one_le_exp) (λ h, by rw [← neg_neg x, real.exp_neg]; exact inv_pos.2 (lt_of_lt_of_le zero_lt_one (one_le_exp (neg_nonneg.2 h)))) @[simp] lemma abs_exp (x : ℝ) : |exp x| = exp x := abs_of_pos (exp_pos _) @[mono] lemma exp_strict_mono : strict_mono exp := λ x y h, by rw [← sub_add_cancel y x, real.exp_add]; exact (lt_mul_iff_one_lt_left (exp_pos _)).2 (lt_of_lt_of_le (by linarith) (add_one_le_exp_of_nonneg (by linarith))) @[mono] lemma exp_monotone : monotone exp := exp_strict_mono.monotone @[simp] lemma exp_lt_exp {x y : ℝ} : exp x < exp y ↔ x < y := exp_strict_mono.lt_iff_lt @[simp] lemma exp_le_exp {x y : ℝ} : exp x ≤ exp y ↔ x ≤ y := exp_strict_mono.le_iff_le lemma exp_injective : function.injective exp := exp_strict_mono.injective @[simp] lemma exp_eq_exp {x y : ℝ} : exp x = exp y ↔ x = y := exp_injective.eq_iff @[simp] lemma exp_eq_one_iff : exp x = 1 ↔ x = 0 := exp_injective.eq_iff' exp_zero @[simp] lemma one_lt_exp_iff {x : ℝ} : 1 < exp x ↔ 0 < x := by rw [← exp_zero, exp_lt_exp] @[simp] lemma exp_lt_one_iff {x : ℝ} : exp x < 1 ↔ x < 0 := by rw [← exp_zero, exp_lt_exp] @[simp] lemma exp_le_one_iff {x : ℝ} : exp x ≤ 1 ↔ x ≤ 0 := exp_zero ▸ exp_le_exp @[simp] lemma one_le_exp_iff {x : ℝ} : 1 ≤ exp x ↔ 0 ≤ x := exp_zero ▸ exp_le_exp /-- `real.cosh` is always positive -/ lemma cosh_pos (x : ℝ) : 0 < real.cosh x := (cosh_eq x).symm ▸ half_pos (add_pos (exp_pos x) (exp_pos (-x))) lemma sinh_lt_cosh : sinh x < cosh x := lt_of_pow_lt_pow 2 (cosh_pos _).le $ (cosh_sq x).symm ▸ lt_add_one _ end real namespace complex lemma sum_div_factorial_le {α : Type*} [linear_ordered_field α] (n j : ℕ) (hn : 0 < n) : ∑ m in filter (λ k, n ≤ k) (range j), (1 / m! : α) ≤ n.succ / (n! * n) := calc ∑ m in filter (λ k, n ≤ k) (range j), (1 / m! : α) = ∑ m in range (j - n), 1 / (m + n)! : sum_bij (λ m _, m - n) (λ m hm, mem_range.2 $ (tsub_lt_tsub_iff_right (by simp at hm; tauto)).2 (by simp at hm; tauto)) (λ m hm, by rw tsub_add_cancel_of_le; simp at *; tauto) (λ a₁ a₂ ha₁ ha₂ h, by rwa [tsub_eq_iff_eq_add_of_le, tsub_add_eq_add_tsub, eq_comm, tsub_eq_iff_eq_add_of_le, add_left_inj, eq_comm] at h; simp at *; tauto) (λ b hb, ⟨b + n, mem_filter.2 ⟨mem_range.2 $ lt_tsub_iff_right.mp (mem_range.1 hb), nat.le_add_left _ _⟩, by rw add_tsub_cancel_right⟩) ... ≤ ∑ m in range (j - n), (n! * n.succ ^ m)⁻¹ : begin refine sum_le_sum (assume m n, _), rw [one_div, inv_le_inv], { rw [← nat.cast_pow, ← nat.cast_mul, nat.cast_le, add_comm], exact nat.factorial_mul_pow_le_factorial }, { exact nat.cast_pos.2 (nat.factorial_pos _) }, { exact mul_pos (nat.cast_pos.2 (nat.factorial_pos _)) (pow_pos (nat.cast_pos.2 (nat.succ_pos _)) _) }, end ... = n!⁻¹ * ∑ m in range (j - n), n.succ⁻¹ ^ m : by simp [mul_inv, mul_sum.symm, sum_mul.symm, -nat.factorial_succ, mul_comm, inv_pow] ... = (n.succ - n.succ * n.succ⁻¹ ^ (j - n)) / (n! * n) : have h₁ : (n.succ : α) ≠ 1, from @nat.cast_one α _ ▸ mt nat.cast_inj.1 (mt nat.succ.inj (pos_iff_ne_zero.1 hn)), have h₂ : (n.succ : α) ≠ 0, from nat.cast_ne_zero.2 (nat.succ_ne_zero _), have h₃ : (n! * n : α) ≠ 0, from mul_ne_zero (nat.cast_ne_zero.2 (pos_iff_ne_zero.1 (nat.factorial_pos _))) (nat.cast_ne_zero.2 (pos_iff_ne_zero.1 hn)), have h₄ : (n.succ - 1 : α) = n, by simp, by rw [geom_sum_inv h₁ h₂, eq_div_iff_mul_eq h₃, mul_comm _ (n! * n : α), ← mul_assoc (n!⁻¹ : α), ← mul_inv_rev, h₄, ← mul_assoc (n! * n : α), mul_comm (n : α) n!, mul_inv_cancel h₃]; simp [mul_add, add_mul, mul_assoc, mul_comm] ... ≤ n.succ / (n! * n) : begin refine iff.mpr (div_le_div_right (mul_pos _ _)) _, exact nat.cast_pos.2 (nat.factorial_pos _), exact nat.cast_pos.2 hn, exact sub_le_self _ (mul_nonneg (nat.cast_nonneg _) (pow_nonneg (inv_nonneg.2 (nat.cast_nonneg _)) _)) end lemma exp_bound {x : ℂ} (hx : abs x ≤ 1) {n : ℕ} (hn : 0 < n) : abs (exp x - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n * (n.succ * (n! * n)⁻¹) := begin rw [← lim_const (∑ m in range n, _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs], refine lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩), simp_rw ← sub_eq_add_neg, show abs (∑ m in range j, x ^ m / m! - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n * (n.succ * (n! * n)⁻¹), rw sum_range_sub_sum_range hj, calc abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ m / m! : ℂ)) = abs (∑ m in (range j).filter (λ k, n ≤ k), (x ^ n * (x ^ (m - n) / m!) : ℂ)) : begin refine congr_arg abs (sum_congr rfl (λ m hm, _)), rw [mem_filter, mem_range] at hm, rw [← mul_div_assoc, ← pow_add, add_tsub_cancel_of_le hm.2] end ... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs (x ^ n * (_ / m!)) : abv_sum_le_sum_abv _ _ ... ≤ ∑ m in filter (λ k, n ≤ k) (range j), abs x ^ n * (1 / m!) : begin refine sum_le_sum (λ m hm, _), rw [abs_mul, abv_pow abs, abs_div, abs_cast_nat], refine mul_le_mul_of_nonneg_left ((div_le_div_right _).2 _) _, { exact nat.cast_pos.2 (nat.factorial_pos _), }, { rw abv_pow abs, exact (pow_le_one _ (abs_nonneg _) hx), }, { exact pow_nonneg (abs_nonneg _) _ }, end ... = abs x ^ n * (∑ m in (range j).filter (λ k, n ≤ k), (1 / m! : ℝ)) : by simp [abs_mul, abv_pow abs, abs_div, mul_sum.symm] ... ≤ abs x ^ n * (n.succ * (n! * n)⁻¹) : mul_le_mul_of_nonneg_left (sum_div_factorial_le _ _ hn) (pow_nonneg (abs_nonneg _) _) end lemma exp_bound' {x : ℂ} {n : ℕ} (hx : abs x / (n.succ) ≤ 1 / 2) : abs (exp x - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n / (n!) * 2 := begin rw [← lim_const (∑ m in range n, _), exp, sub_eq_add_neg, ← lim_neg, lim_add, ← lim_abs], refine lim_le (cau_seq.le_of_exists ⟨n, λ j hj, _⟩), simp_rw [←sub_eq_add_neg], show abs (∑ m in range j, x ^ m / m! - ∑ m in range n, x ^ m / m!) ≤ abs x ^ n / (n!) * 2, let k := j - n, have hj : j = n + k := (add_tsub_cancel_of_le hj).symm, rw [hj, sum_range_add_sub_sum_range], calc abs (∑ (i : ℕ) in range k, x ^ (n + i) / ((n + i)! : ℂ)) ≤ ∑ (i : ℕ) in range k, abs (x ^ (n + i) / ((n + i)! : ℂ)) : abv_sum_le_sum_abv _ _ ... ≤ ∑ (i : ℕ) in range k, (abs x) ^ (n + i) / (n + i)! : by simp only [complex.abs_cast_nat, complex.abs_div, abv_pow abs] ... ≤ ∑ (i : ℕ) in range k, (abs x) ^ (n + i) / (n! * n.succ ^ i) : _ ... = ∑ (i : ℕ) in range k, (abs x) ^ (n) / (n!) * ((abs x)^i / n.succ ^ i) : _ ... ≤ abs x ^ n / (↑n!) * 2 : _, { refine sum_le_sum (λ m hm, div_le_div (pow_nonneg (abs_nonneg x) (n + m)) le_rfl _ _), { exact_mod_cast mul_pos n.factorial_pos (pow_pos n.succ_pos _), }, { exact_mod_cast (nat.factorial_mul_pow_le_factorial), }, }, { refine finset.sum_congr rfl (λ _ _, _), simp only [pow_add, div_eq_inv_mul, mul_inv, mul_left_comm, mul_assoc], }, { rw [←mul_sum], apply mul_le_mul_of_nonneg_left, { simp_rw [←div_pow], rw [geom_sum_eq, div_le_iff_of_neg], { transitivity (-1 : ℝ), { linarith }, { simp only [neg_le_sub_iff_le_add, div_pow, nat.cast_succ, le_add_iff_nonneg_left], exact div_nonneg (pow_nonneg (abs_nonneg x) k) (pow_nonneg (add_nonneg n.cast_nonneg zero_le_one) k) } }, { linarith }, { linarith }, }, { exact div_nonneg (pow_nonneg (abs_nonneg x) n) (nat.cast_nonneg (n!)), }, }, end lemma abs_exp_sub_one_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1) ≤ 2 * abs x := calc abs (exp x - 1) = abs (exp x - ∑ m in range 1, x ^ m / m!) : by simp [sum_range_succ] ... ≤ abs x ^ 1 * ((nat.succ 1) * (1! * (1 : ℕ))⁻¹) : exp_bound hx dec_trivial ... = 2 * abs x : by simp [two_mul, mul_two, mul_add, mul_comm] lemma abs_exp_sub_one_sub_id_le {x : ℂ} (hx : abs x ≤ 1) : abs (exp x - 1 - x) ≤ (abs x)^2 := calc abs (exp x - 1 - x) = abs (exp x - ∑ m in range 2, x ^ m / m!) : by simp [sub_eq_add_neg, sum_range_succ_comm, add_assoc] ... ≤ (abs x)^2 * (nat.succ 2 * (2! * (2 : ℕ))⁻¹) : exp_bound hx dec_trivial ... ≤ (abs x)^2 * 1 : mul_le_mul_of_nonneg_left (by norm_num) (sq_nonneg (abs x)) ... = (abs x)^2 : by rw [mul_one] end complex namespace real open complex finset lemma exp_bound {x : ℝ} (hx : |x| ≤ 1) {n : ℕ} (hn : 0 < n) : |exp x - ∑ m in range n, x ^ m / m!|≤ |x| ^ n * (n.succ / (n! * n)) := begin have hxc : complex.abs x ≤ 1, by exact_mod_cast hx, convert exp_bound hxc hn; norm_cast end lemma exp_bound' {x : ℝ} (h1 : 0 ≤ x) (h2 : x ≤ 1) {n : ℕ} (hn : 0 < n) : real.exp x ≤ ∑ m in finset.range n, x ^ m / m! + x ^ n * (n + 1) / (n! * n) := begin have h3 : |x| = x := by simpa, have h4 : |x| ≤ 1 := by rwa h3, have h' := real.exp_bound h4 hn, rw h3 at h', have h'' := (abs_sub_le_iff.1 h').1, have t := sub_le_iff_le_add'.1 h'', simpa [mul_div_assoc] using t end lemma abs_exp_sub_one_le {x : ℝ} (hx : |x| ≤ 1) : |exp x - 1| ≤ 2 * |x| := begin have : complex.abs x ≤ 1 := by exact_mod_cast hx, exact_mod_cast complex.abs_exp_sub_one_le this, end lemma abs_exp_sub_one_sub_id_le {x : ℝ} (hx : |x| ≤ 1) : |exp x - 1 - x| ≤ x ^ 2 := begin rw ←_root_.sq_abs, have : complex.abs x ≤ 1 := by exact_mod_cast hx, exact_mod_cast complex.abs_exp_sub_one_sub_id_le this, end /-- A finite initial segment of the exponential series, followed by an arbitrary tail. For fixed `n` this is just a linear map wrt `r`, and each map is a simple linear function of the previous (see `exp_near_succ`), with `exp_near n x r ⟶ exp x` as `n ⟶ ∞`, for any `r`. -/ def exp_near (n : ℕ) (x r : ℝ) : ℝ := ∑ m in range n, x ^ m / m! + x ^ n / n! * r @[simp] theorem exp_near_zero (x r) : exp_near 0 x r = r := by simp [exp_near] @[simp] theorem exp_near_succ (n x r) : exp_near (n + 1) x r = exp_near n x (1 + x / (n+1) * r) := by simp [exp_near, range_succ, mul_add, add_left_comm, add_assoc, pow_succ, div_eq_mul_inv, mul_inv]; ac_refl theorem exp_near_sub (n x r₁ r₂) : exp_near n x r₁ - exp_near n x r₂ = x ^ n / n! * (r₁ - r₂) := by simp [exp_near, mul_sub] lemma exp_approx_end (n m : ℕ) (x : ℝ) (e₁ : n + 1 = m) (h : |x| ≤ 1) : |exp x - exp_near m x 0| ≤ |x| ^ m / m! * ((m+1)/m) := by { simp [exp_near], convert exp_bound h _ using 1, field_simp [mul_comm], linarith } lemma exp_approx_succ {n} {x a₁ b₁ : ℝ} (m : ℕ) (e₁ : n + 1 = m) (a₂ b₂ : ℝ) (e : |1 + x / m * a₂ - a₁| ≤ b₁ - |x| / m * b₂) (h : |exp x - exp_near m x a₂| ≤ |x| ^ m / m! * b₂) : |exp x - exp_near n x a₁| ≤ |x| ^ n / n! * b₁ := begin refine (_root_.abs_sub_le _ _ _).trans ((add_le_add_right h _).trans _), subst e₁, rw [exp_near_succ, exp_near_sub, _root_.abs_mul], convert mul_le_mul_of_nonneg_left (le_sub_iff_add_le'.1 e) _, { simp [mul_add, pow_succ', div_eq_mul_inv, _root_.abs_mul, _root_.abs_inv, ← pow_abs, mul_inv], ac_refl }, { simp [_root_.div_nonneg, _root_.abs_nonneg] } end lemma exp_approx_end' {n} {x a b : ℝ} (m : ℕ) (e₁ : n + 1 = m) (rm : ℝ) (er : ↑m = rm) (h : |x| ≤ 1) (e : |1 - a| ≤ b - |x| / rm * ((rm+1)/rm)) : |exp x - exp_near n x a| ≤ |x| ^ n / n! * b := by subst er; exact exp_approx_succ _ e₁ _ _ (by simpa using e) (exp_approx_end _ _ _ e₁ h) lemma exp_1_approx_succ_eq {n} {a₁ b₁ : ℝ} {m : ℕ} (en : n + 1 = m) {rm : ℝ} (er : ↑m = rm) (h : |exp 1 - exp_near m 1 ((a₁ - 1) * rm)| ≤ |1| ^ m / m! * (b₁ * rm)) : |exp 1 - exp_near n 1 a₁| ≤ |1| ^ n / n! * b₁ := begin subst er, refine exp_approx_succ _ en _ _ _ h, field_simp [show (m : ℝ) ≠ 0, by norm_cast; linarith], end lemma exp_approx_start (x a b : ℝ) (h : |exp x - exp_near 0 x a| ≤ |x| ^ 0 / 0! * b) : |exp x - a| ≤ b := by simpa using h lemma cos_bound {x : ℝ} (hx : |x| ≤ 1) : |cos x - (1 - x ^ 2 / 2)| ≤ |x| ^ 4 * (5 / 96) := calc |cos x - (1 - x ^ 2 / 2)| = abs (complex.cos x - (1 - x ^ 2 / 2)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs ((complex.exp (x * I) + complex.exp (-x * I) - (2 - x ^ 2)) / 2) : by simp [complex.cos, sub_div, add_div, neg_div, div_self (@two_ne_zero' ℂ _ _)] ... = abs (((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) + ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!))) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) / 2) + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) / 2) : by rw add_div; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) / 2 + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!)) / 2) : by simp [complex.abs_div] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ... ≤ |x| ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma sin_bound {x : ℝ} (hx : |x| ≤ 1) : |sin x - (x - x ^ 3 / 6)| ≤ |x| ^ 4 * (5 / 96) := calc |sin x - (x - x ^ 3 / 6)| = abs (complex.sin x - (x - x ^ 3 / 6)) : by rw ← abs_of_real; simp [of_real_bit0, of_real_one, of_real_inv] ... = abs (((complex.exp (-x * I) - complex.exp (x * I)) * I - (2 * x - x ^ 3 / 3)) / 2) : by simp [complex.sin, sub_div, add_div, neg_div, mul_div_cancel_left _ (@two_ne_zero' ℂ _ _), div_div, show (3 : ℂ) * 2 = 6, by norm_num] ... = abs ((((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) - (complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) * I) / 2) : congr_arg abs (congr_arg (λ x : ℂ, x / 2) begin simp only [sum_range_succ], simp [pow_succ], apply complex.ext; simp [div_eq_mul_inv, norm_sq]; ring end) ... ≤ abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!) * I / 2) + abs (-((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!) * I) / 2) : by rw [sub_mul, sub_eq_add_neg, add_div]; exact abs_add _ _ ... = (abs ((complex.exp (x * I) - ∑ m in range 4, (x * I) ^ m / m!)) / 2 + abs ((complex.exp (-x * I) - ∑ m in range 4, (-x * I) ^ m / m!)) / 2) : by simp [add_comm, complex.abs_div, complex.abs_mul] ... ≤ ((complex.abs (x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2 + (complex.abs (-x * I) ^ 4 * (nat.succ 4 * (4! * (4 : ℕ))⁻¹)) / 2) : add_le_add ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ((div_le_div_right (by norm_num)).2 (complex.exp_bound (by simpa) dec_trivial)) ... ≤ |x| ^ 4 * (5 / 96) : by norm_num; simp [mul_assoc, mul_comm, mul_left_comm, mul_div_assoc] lemma cos_pos_of_le_one {x : ℝ} (hx : |x| ≤ 1) : 0 < cos x := calc 0 < (1 - x ^ 2 / 2) - |x| ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc |x| ^ 4 * (5 / 96) + x ^ 2 / 2 ≤ 1 * (5 / 96) + 1 / 2 : add_le_add (mul_le_mul_of_nonneg_right (pow_le_one _ (abs_nonneg _) hx) (by norm_num)) ((div_le_div_right (by norm_num)).2 (by rw [sq, ← abs_mul_self, _root_.abs_mul]; exact mul_le_one hx (abs_nonneg _) hx)) ... < 1 : by norm_num) ... ≤ cos x : sub_le.1 (abs_sub_le_iff.1 (cos_bound hx)).2 lemma sin_pos_of_pos_of_le_one {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 1) : 0 < sin x := calc 0 < x - x ^ 3 / 6 - |x| ^ 4 * (5 / 96) : sub_pos.2 $ lt_sub_iff_add_lt.2 (calc |x| ^ 4 * (5 / 96) + x ^ 3 / 6 ≤ x * (5 / 96) + x / 6 : add_le_add (mul_le_mul_of_nonneg_right (calc |x| ^ 4 ≤ |x| ^ 1 : pow_le_pow_of_le_one (abs_nonneg _) (by rwa _root_.abs_of_nonneg (le_of_lt hx0)) dec_trivial ... = x : by simp [_root_.abs_of_nonneg (le_of_lt (hx0))]) (by norm_num)) ((div_le_div_right (by norm_num)).2 (calc x ^ 3 ≤ x ^ 1 : pow_le_pow_of_le_one (le_of_lt hx0) hx dec_trivial ... = x : pow_one _)) ... < x : by linarith) ... ≤ sin x : sub_le.1 (abs_sub_le_iff.1 (sin_bound (by rwa [_root_.abs_of_nonneg (le_of_lt hx0)]))).2 lemma sin_pos_of_pos_of_le_two {x : ℝ} (hx0 : 0 < x) (hx : x ≤ 2) : 0 < sin x := have x / 2 ≤ 1, from (div_le_iff (by norm_num)).mpr (by simpa), calc 0 < 2 * sin (x / 2) * cos (x / 2) : mul_pos (mul_pos (by norm_num) (sin_pos_of_pos_of_le_one (half_pos hx0) this)) (cos_pos_of_le_one (by rwa [_root_.abs_of_nonneg (le_of_lt (half_pos hx0))])) ... = sin x : by rw [← sin_two_mul, two_mul, add_halves] lemma cos_one_le : cos 1 ≤ 2 / 3 := calc cos 1 ≤ |(1 : ℝ)| ^ 4 * (5 / 96) + (1 - 1 ^ 2 / 2) : sub_le_iff_le_add.1 (abs_sub_le_iff.1 (cos_bound (by simp))).1 ... ≤ 2 / 3 : by norm_num lemma cos_one_pos : 0 < cos 1 := cos_pos_of_le_one (le_of_eq abs_one) lemma cos_two_neg : cos 2 < 0 := calc cos 2 = cos (2 * 1) : congr_arg cos (mul_one _).symm ... = _ : real.cos_two_mul 1 ... ≤ 2 * (2 / 3) ^ 2 - 1 : sub_le_sub_right (mul_le_mul_of_nonneg_left (by { rw [sq, sq], exact mul_self_le_mul_self (le_of_lt cos_one_pos) cos_one_le }) zero_le_two) _ ... < 0 : by norm_num lemma exp_bound_div_one_sub_of_interval_approx {x : ℝ} (h1 : 0 ≤ x) (h2 : x ≤ 1) : ∑ (j : ℕ) in finset.range 3, x ^ j / (j.factorial) + x ^ 3 * ((3 : ℕ) + 1) / ((3 : ℕ).factorial * (3 : ℕ)) ≤ ∑ j in (finset.range 3), x ^ j := begin norm_num [finset.sum], rw [add_assoc, add_comm (x + 1) (x ^ 3 * 4 / 18), ← add_assoc, add_le_add_iff_right, ← add_le_add_iff_left (-(x ^ 2 / 2)), ← add_assoc, comm_ring.add_left_neg (x ^ 2 / 2), zero_add, neg_add_eq_sub, sub_half, sq, pow_succ, sq], have i1 : x * 4 / 18 ≤ 1 / 2 := by linarith, have i2 : 0 ≤ x * 4 / 18 := by linarith, have i3 := mul_le_mul h1 h1 le_rfl h1, rw zero_mul at i3, have t := mul_le_mul le_rfl i1 i2 i3, rw ← mul_assoc, rwa [mul_one_div, ← mul_div_assoc, ← mul_assoc] at t, end lemma exp_bound_div_one_sub_of_interval {x : ℝ} (h1 : 0 ≤ x) (h2 : x < 1) : real.exp x ≤ 1 / (1 - x) := begin have h : ∑ j in (finset.range 3), x ^ j ≤ 1 / (1 - x), { norm_num [finset.sum], have h1x : 0 < 1 - x := by simpa, rw le_div_iff h1x, norm_num [← add_assoc, mul_sub_left_distrib, mul_one, add_mul, sub_add_eq_sub_sub, pow_succ' x 2], have hx3 : 0 ≤ x ^ 3, { norm_num, exact h1 }, linarith }, exact (exp_bound' h1 h2.le $ by linarith).trans ((exp_bound_div_one_sub_of_interval_approx h1 h2.le).trans h), end lemma one_sub_le_exp_minus_of_pos {y : ℝ} (h : 0 ≤ y) : 1 - y ≤ real.exp (-y) := begin rw real.exp_neg, have r1 : (1 - y) * (real.exp y) ≤ 1, { cases le_or_lt (1 - y) 0, { have h'' : (1 - y) * y.exp ≤ 0, { rw mul_nonpos_iff, right, exact ⟨h_1, y.exp_pos.le⟩ }, linarith }, have hy1 : y < 1 := by linarith, rw ← le_div_iff' h_1, exact exp_bound_div_one_sub_of_interval h hy1 }, rw inv_eq_one_div, rw le_div_iff' y.exp_pos, rwa mul_comm at r1, end lemma add_one_le_exp_of_nonpos {x : ℝ} (h : x ≤ 0) : x + 1 ≤ real.exp x := begin rw add_comm, have h1 : 0 ≤ -x := by linarith, simpa using one_sub_le_exp_minus_of_pos h1 end lemma add_one_le_exp (x : ℝ) : x + 1 ≤ real.exp x := begin cases le_or_lt 0 x, { exact real.add_one_le_exp_of_nonneg h }, exact add_one_le_exp_of_nonpos h.le, end end real namespace complex @[simp] lemma abs_cos_add_sin_mul_I (x : ℝ) : abs (cos x + sin x * I) = 1 := have _ := real.sin_sq_add_cos_sq x, by simp [add_comm, abs, norm_sq, sq, *, sin_of_real_re, cos_of_real_re, mul_re] at * @[simp] lemma abs_exp_of_real (x : ℝ) : abs (exp x) = real.exp x := by rw [← of_real_exp]; exact abs_of_nonneg (le_of_lt (real.exp_pos _)) @[simp] lemma abs_exp_of_real_mul_I (x : ℝ) : abs (exp (x * I)) = 1 := by rw [exp_mul_I, abs_cos_add_sin_mul_I] lemma abs_exp (z : ℂ) : abs (exp z) = real.exp z.re := by rw [exp_eq_exp_re_mul_sin_add_cos, abs_mul, abs_exp_of_real, abs_cos_add_sin_mul_I, mul_one] lemma abs_exp_eq_iff_re_eq {x y : ℂ} : abs (exp x) = abs (exp y) ↔ x.re = y.re := by rw [abs_exp, abs_exp, real.exp_eq_exp] end complex
69efdc2058b577d690508c82726c12f60d6a512a
618003631150032a5676f229d13a079ac875ff77
/src/init_/data/int/order.lean
6de3f348ce2a79140d787dfe53a5c2d64a64a56d
[ "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
1,029
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The order relation on the integers. -/ import init_.data.int.basic import algebra.ordered_ring /- Results copied from the core library to mathlib by Johan Commelin -/ namespace int instance : decidable_linear_ordered_comm_ring int := { add_le_add_left := @int.add_le_add_left, zero_ne_one := int.zero_ne_one, mul_pos := @int.mul_pos, zero_lt_one := int.zero_lt_one, ..int.comm_ring, ..int.decidable_linear_order } instance : decidable_linear_ordered_add_comm_group int := by apply_instance theorem abs_eq_nat_abs : ∀ a : ℤ, abs a = nat_abs a | (n : ℕ) := abs_of_nonneg $ coe_zero_le _ | -[1+ n] := abs_of_nonpos $ le_of_lt $ neg_succ_lt_zero _ theorem nat_abs_abs (a : ℤ) : nat_abs (abs a) = nat_abs a := by rw [abs_eq_nat_abs]; refl theorem sign_mul_abs (a : ℤ) : sign a * abs a = a := by rw [abs_eq_nat_abs, sign_mul_nat_abs] end int
d70e363e862248ade864378691330bed22e7a84f
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/data/polynomial/iterated_deriv.lean
e37409a00a7aa3df7acdd970a651702b24ac8059
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
8,015
lean
/- Copyright (c) 2020 Jujian Zhang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jujian Zhang -/ import data.finset.intervals import data.polynomial.derivative import tactic.linarith /-! # Theory of iterated derivative We define and prove some lemmas about iterated (formal) derivative for polynomials over a semiring. -/ noncomputable theory open finset nat polynomial open_locale big_operators namespace polynomial universes u variable {R : Type u} section semiring variables [semiring R] (r : R) (f p q : polynomial R) (n k : ℕ) /-- `iterated_deriv f n` is the `n`-th formal derivative of the polynomial `f` -/ def iterated_deriv : polynomial R := derivative ^[n] f @[simp] lemma iterated_deriv_zero_right : iterated_deriv f 0 = f := rfl lemma iterated_deriv_succ : iterated_deriv f (n + 1) = (iterated_deriv f n).derivative := by rw [iterated_deriv, iterated_deriv, function.iterate_succ'] @[simp] lemma iterated_deriv_zero_left : iterated_deriv (0 : polynomial R) n = 0 := begin induction n with n hn, { exact iterated_deriv_zero_right _ }, { rw [iterated_deriv_succ, hn, derivative_zero] }, end @[simp] lemma iterated_deriv_add : iterated_deriv (p + q) n = iterated_deriv p n + iterated_deriv q n := begin induction n with n ih, { simp only [iterated_deriv_zero_right], }, { simp only [iterated_deriv_succ, ih, derivative_add] } end @[simp] lemma iterated_deriv_smul : iterated_deriv (r • p) n = r • iterated_deriv p n := begin induction n with n ih, { simp only [iterated_deriv_zero_right] }, { simp only [iterated_deriv_succ, ih, derivative_smul] } end @[simp] lemma iterated_deriv_X_zero : iterated_deriv (X : polynomial R) 0 = X := by simp only [iterated_deriv_zero_right] @[simp] lemma iterated_deriv_X_one : iterated_deriv (X : polynomial R) 1 = 1 := by simp only [iterated_deriv, derivative_X, function.iterate_one] @[simp] lemma iterated_deriv_X (h : 1 < n) : iterated_deriv (X : polynomial R) n = 0 := begin induction n with n ih, { exfalso, exact nat.not_lt_zero 1 h}, { simp only [iterated_deriv_succ], by_cases H : n = 1, { rw H, simp only [iterated_deriv_X_one, derivative_one] }, { replace h : 1 < n := array.push_back_idx h (ne.symm H), rw ih h, simp only [derivative_zero] } } end @[simp] lemma iterated_deriv_C_zero : iterated_deriv (C r) 0 = C r := by simp only [iterated_deriv_zero_right] @[simp] lemma iterated_deriv_C (h : 0 < n) : iterated_deriv (C r) n = 0 := begin induction n with n ih, { exfalso, exact nat.lt_asymm h h }, { by_cases H : n = 0, { rw [iterated_deriv_succ, H], simp only [iterated_deriv_C_zero, derivative_C] }, { replace h : 0 < n := nat.pos_of_ne_zero H, rw [iterated_deriv_succ, ih h], simp only [derivative_zero] } } end @[simp] lemma iterated_deriv_one_zero : iterated_deriv (1 : polynomial R) 0 = 1 := by simp only [iterated_deriv_zero_right] @[simp] lemma iterated_deriv_one : 0 < n → iterated_deriv (1 : polynomial R) n = 0 := λ h, begin have eq1 : (1 : polynomial R) = C 1 := by simp only [ring_hom.map_one], rw eq1, exact iterated_deriv_C _ _ h, end end semiring section ring variables [ring R] (p q : polynomial R) (n : ℕ) @[simp] lemma iterated_deriv_neg : iterated_deriv (-p) n = - iterated_deriv p n := begin induction n with n ih, { simp only [iterated_deriv_zero_right] }, { simp only [iterated_deriv_succ, ih, derivative_neg] } end @[simp] lemma iterated_deriv_sub : iterated_deriv (p - q) n = iterated_deriv p n - iterated_deriv q n := by rw [sub_eq_add_neg, iterated_deriv_add, iterated_deriv_neg, ←sub_eq_add_neg] end ring section comm_semiring variable [comm_semiring R] variables (f p q : polynomial R) (n k : ℕ) lemma coeff_iterated_deriv_as_prod_Ico : ∀ m : ℕ, (iterated_deriv f k).coeff m = (∏ i in Ico m.succ (m + k.succ), i) * (f.coeff (m+k)) := begin induction k with k ih, { simp only [add_zero, forall_const, one_mul, Ico.self_eq_empty, eq_self_iff_true, iterated_deriv_zero_right, prod_empty] }, { intro m, rw [iterated_deriv_succ, coeff_derivative, ih (m+1), mul_right_comm], apply congr_arg2, { have set_eq : (Ico m.succ (m + k.succ.succ)) = (Ico (m + 1).succ (m + 1 + k.succ)) ∪ {m+1}, { rw [union_comm, ←insert_eq, Ico.insert_succ_bot, add_succ, add_succ, add_succ _ k, ←succ_eq_add_one, succ_add], rw succ_eq_add_one, linarith }, rw [set_eq, prod_union], apply congr_arg2, { refl }, { simp only [prod_singleton], norm_cast }, { simp only [succ_pos', disjoint_singleton, and_true, lt_add_iff_pos_right, not_le, Ico.mem], exact lt_add_one (m + 1) } }, { exact congr_arg _ (succ_add m k) } }, end lemma coeff_iterated_deriv_as_prod_range : ∀ m : ℕ, (iterated_deriv f k).coeff m = f.coeff (m + k) * (∏ i in range k, ↑(m + k - i)) := begin induction k with k ih, { simp }, intro m, calc (f.iterated_deriv k.succ).coeff m = f.coeff (m + k.succ) * (∏ i in range k, ↑(m + k.succ - i)) * (m + 1) : by rw [iterated_deriv_succ, coeff_derivative, ih m.succ, succ_add, add_succ] ... = f.coeff (m + k.succ) * (∏ i in range k, ↑(m + k.succ - i)) * ↑(m + 1) : by push_cast ... = f.coeff (m + k.succ) * (∏ i in range k.succ, ↑(m + k.succ - i)) : by rw [prod_range_succ, nat.add_sub_assoc k.le_succ, succ_sub le_rfl, nat.sub_self, mul_assoc] end lemma iterated_deriv_eq_zero_of_nat_degree_lt (h : f.nat_degree < n) : iterated_deriv f n = 0 := begin ext m, rw [coeff_iterated_deriv_as_prod_range, coeff_zero, coeff_eq_zero_of_nat_degree_lt, zero_mul], linarith end lemma iterated_deriv_mul : iterated_deriv (p * q) n = ∑ k in range n.succ, (C (n.choose k : R)) * iterated_deriv p (n - k) * iterated_deriv q k := begin induction n with n IH, { simp }, calc (p * q).iterated_deriv n.succ = (∑ (k : ℕ) in range n.succ, C ↑(n.choose k) * p.iterated_deriv (n - k) * q.iterated_deriv k).derivative : by rw [iterated_deriv_succ, IH] ... = ∑ (k : ℕ) in range n.succ, C ↑(n.choose k) * p.iterated_deriv (n - k + 1) * q.iterated_deriv k + ∑ (k : ℕ) in range n.succ, C ↑(n.choose k) * p.iterated_deriv (n - k) * q.iterated_deriv (k + 1) : by simp_rw [derivative_sum, derivative_mul, derivative_C, zero_mul, zero_add, iterated_deriv_succ, sum_add_distrib] ... = (∑ (k : ℕ) in range n.succ, C ↑(n.choose k.succ) * p.iterated_deriv (n - k) * q.iterated_deriv (k + 1) + C ↑1 * p.iterated_deriv n.succ * q.iterated_deriv 0) + ∑ (k : ℕ) in range n.succ, C ↑(n.choose k) * p.iterated_deriv (n - k) * q.iterated_deriv (k + 1) : _ ... = ∑ (k : ℕ) in range n.succ, C ↑(n.choose k) * p.iterated_deriv (n - k) * q.iterated_deriv (k + 1) + ∑ (k : ℕ) in range n.succ, C ↑(n.choose k.succ) * p.iterated_deriv (n - k) * q.iterated_deriv (k + 1) + C ↑1 * p.iterated_deriv n.succ * q.iterated_deriv 0 : by ring ... = ∑ (i : ℕ) in range n.succ, C ↑((n+1).choose (i+1)) * p.iterated_deriv (n + 1 - (i+1)) * q.iterated_deriv (i+1) + C ↑1 * p.iterated_deriv n.succ * q.iterated_deriv 0 : by simp_rw [choose_succ_succ, succ_sub_succ, cast_add, C.map_add, add_mul, sum_add_distrib] ... = ∑ (k : ℕ) in range n.succ.succ, C ↑(n.succ.choose k) * p.iterated_deriv (n.succ - k) * q.iterated_deriv k : by rw [sum_range_succ' _ n.succ, choose_zero_right, nat.sub_zero], congr, refine (sum_range_succ' _ _).trans (congr_arg2 (+) _ _), { rw [sum_range_succ, nat.choose_succ_self, cast_zero, C.map_zero, zero_mul, zero_mul, add_zero], refine sum_congr rfl (λ k hk, _), rw mem_range at hk, congr, rw [← nat.sub_add_comm (nat.succ_le_of_lt hk), nat.succ_sub_succ] }, { rw [choose_zero_right, nat.sub_zero] }, end end comm_semiring end polynomial
7566fa14576f96bfd345a226e7f4f2c72ec21822
da3a76c514d38801bae19e8a9e496dc31f8e5866
/tests/lean/run/decl_olean.lean
60ee7f6a1e4083df684b1694b285a81c5fa7731d
[ "Apache-2.0" ]
permissive
cipher1024/lean
270c1ac5781e6aee12f5c8d720d267563a164beb
f5cbdff8932dd30c6dd8eec68f3059393b4f8b3a
refs/heads/master
1,611,223,459,029
1,487,566,573,000
1,487,566,573,000
83,356,543
0
0
null
1,488,229,336,000
1,488,229,336,000
null
UTF-8
Lean
false
false
529
lean
open tactic def g : nat → nat := λ n, 0 meta def show_pos (n : name) : command := do env ← get_env, pos ← returnopt (env^.decl_pos_info n), olean ← returnopt (env^.decl_olean n) <|> return "current file", trace $ to_string n ++ " was defined at " ++ olean ++ " : " ++ to_string pos run_command show_pos `add run_command show_pos `nat.succ run_command show_pos `subsingleton.intro run_command show_pos `subsingleton.rec run_command show_pos `nat.add run_command show_pos `quotient run_command show_pos `g
7ff4034ad66c611e840413478e1840d7e78cd414
d0f9af2b0ace5ce352570d61b09019c8ef4a3b96
/notes/2020.02.04-product_types.lean
ce393b9ce3f6fe5be41a7daf9f5de20495a69288
[]
no_license
jngo13/Discrete-Mathematics
8671540ef2da7c75915d32332dd20c02f001474e
bf674a866e61f60e6e6d128df85fa73819091787
refs/heads/master
1,675,615,657,924
1,609,142,011,000
1,609,142,011,000
267,190,341
0
0
null
null
null
null
UTF-8
Lean
false
false
2,037
lean
/- some type variant type ordered pair type, prod -/ namespace hidden inductive prod_nat_nat :Type | mk : nat → nat → prod_nat_nat --parametric polymorphism -- similar to generics inductive prod_S_T (S T :Type) : Type | mk : S → T → prod_S_T def p1:= prod_nat_nat.mk 5 0 def p2 := prod_nat_nat.mk 3 2 --polymorphic --def p03 := prod_S_T.mk "yo" "kaitlin" def p3:= prod_S_T.mk 3 0 def p4:= prod_S_T.mk tt ff def p5:= prod_S_T.mk "hello" 3 #reduce p1 --first def first: prod_nat_nat → nat:= λ (p: prod_nat_nat), match p with |(prod_nat_nat.mk x _) := x end #eval first p1 #eval first p2 def p_first (S T: Type): (prod_S_T S T) → S:= λ (p : prod_S_T S T), match p with |(prod_S_T.mk x _) := x end --sideways t = turnstile in logic, return type /-we constructed p, now we have to destruct p -> cracking it open so you can see and use the pairs-/ --swap def swap: prod_nat_nat → prod_nat_nat:= λ (p: prod_nat_nat), match p with |(prod_nat_nat.mk x y) := (prod_nat_nat.mk y x) end #eval swap p1 #eval swap p2 --second def second: prod_nat_nat → nat:= λ (p: prod_nat_nat), match p with |(prod_nat_nat.mk _ y) := y end #eval second p1 #eval second p2 def p_second (S T: Type): (prod_S_T S T) → T:= λ (p : prod_S_T S T), match p with |(prod_S_T.mk _ y) := y end #check p_second string nat p5 --set first def set_first: prod_nat_nat → nat → prod_nat_nat:= λ (p: prod_nat_nat) (n: nat), match p with |(prod_nat_nat.mk x y) := (prod_nat_nat.mk n y) end #eval set_first p1 #eval set_first p2 --set second def set_second: prod_nat_nat → nat → prod_nat_nat:= λ (p: prod_nat_nat) (n: nat), match p with |(prod_nat_nat.mk x y) := (prod_nat_nat.mk x n) end #eval set_first p1 #eval set_second p2 --diff --def diff: prod_nat_nat → prod_nat_nat → prod_nat_nat := _ -- check to see if elements are equal or not pair → bool end hidden
0fde9732ee32ebef2aa4a259a36026b4968d9a50
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/sheaves/presheaf.lean
92779fa4ea9cb7e9c860cba33386ac1d5922846c
[ "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
8,663
lean
/- Copyright (c) 2018 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison, Mario Carneiro, Reid Barton, Andrew Yang -/ import topology.category.Top.opens import category_theory.limits.kan_extension import category_theory.adjunction.opposites /-! # Presheaves on a topological space We define `presheaf C X` simply as `(opens X)ᵒᵖ ⥤ C`, and inherit the category structure with natural transformations as morphisms. We define * `pushforward_obj {X Y : Top.{v}} (f : X ⟶ Y) (ℱ : X.presheaf C) : Y.presheaf C` with notation `f _* ℱ` and for `ℱ : X.presheaf C` provide the natural isomorphisms * `pushforward.id : (𝟙 X) _* ℱ ≅ ℱ` * `pushforward.comp : (f ≫ g) _* ℱ ≅ g _* (f _* ℱ)` along with their `@[simp]` lemmas. We also define the functors `pushforward` and `pullback` between the categories `X.presheaf C` and `Y.presheaf C`, and provide their adjunction at `pushforward_pullback_adjunction`. -/ universes v u open category_theory open topological_space open opposite variables (C : Type u) [category.{v} C] namespace Top /-- The category of `C`-valued presheaves on a (bundled) topological space `X`. -/ @[derive category, nolint has_inhabited_instance] def presheaf (X : Top.{v}) := (opens X)ᵒᵖ ⥤ C variables {C} namespace presheaf /-- Pushforward a presheaf on `X` along a continuous map `f : X ⟶ Y`, obtaining a presheaf on `Y`. -/ def pushforward_obj {X Y : Top.{v}} (f : X ⟶ Y) (ℱ : X.presheaf C) : Y.presheaf C := (opens.map f).op ⋙ ℱ infix ` _* `: 80 := pushforward_obj @[simp] lemma pushforward_obj_obj {X Y : Top.{v}} (f : X ⟶ Y) (ℱ : X.presheaf C) (U : (opens Y)ᵒᵖ) : (f _* ℱ).obj U = ℱ.obj ((opens.map f).op.obj U) := rfl @[simp] lemma pushforward_obj_map {X Y : Top.{v}} (f : X ⟶ Y) (ℱ : X.presheaf C) {U V : (opens Y)ᵒᵖ} (i : U ⟶ V) : (f _* ℱ).map i = ℱ.map ((opens.map f).op.map i) := rfl /-- An equality of continuous maps induces a natural isomorphism between the pushforwards of a presheaf along those maps. -/ def pushforward_eq {X Y : Top.{v}} {f g : X ⟶ Y} (h : f = g) (ℱ : X.presheaf C) : f _* ℱ ≅ g _* ℱ := iso_whisker_right (nat_iso.op (opens.map_iso f g h).symm) ℱ lemma pushforward_eq' {X Y : Top.{v}} {f g : X ⟶ Y} (h : f = g) (ℱ : X.presheaf C) : f _* ℱ = g _* ℱ := by rw h @[simp] lemma pushforward_eq_hom_app {X Y : Top.{v}} {f g : X ⟶ Y} (h : f = g) (ℱ : X.presheaf C) (U) : (pushforward_eq h ℱ).hom.app U = ℱ.map (begin dsimp [functor.op], apply quiver.hom.op, apply eq_to_hom, rw h, end) := by simp [pushforward_eq] @[simp] lemma pushforward_eq_rfl {X Y : Top.{v}} (f : X ⟶ Y) (ℱ : X.presheaf C) (U) : (pushforward_eq (rfl : f = f) ℱ).hom.app (op U) = 𝟙 _ := begin dsimp [pushforward_eq], simp, end lemma pushforward_eq_eq {X Y : Top.{v}} {f g : X ⟶ Y} (h₁ h₂ : f = g) (ℱ : X.presheaf C) : ℱ.pushforward_eq h₁ = ℱ.pushforward_eq h₂ := rfl namespace pushforward variables {X : Top.{v}} (ℱ : X.presheaf C) /-- The natural isomorphism between the pushforward of a presheaf along the identity continuous map and the original presheaf. -/ def id : (𝟙 X) _* ℱ ≅ ℱ := (iso_whisker_right (nat_iso.op (opens.map_id X).symm) ℱ) ≪≫ functor.left_unitor _ lemma id_eq : (𝟙 X) _* ℱ = ℱ := by { unfold pushforward_obj, rw opens.map_id_eq, erw functor.id_comp } @[simp] lemma id_hom_app' (U) (p) : (id ℱ).hom.app (op ⟨U, p⟩) = ℱ.map (𝟙 (op ⟨U, p⟩)) := by { dsimp [id], simp, } local attribute [tidy] tactic.op_induction' @[simp, priority 990] lemma id_hom_app (U) : (id ℱ).hom.app U = ℱ.map (eq_to_hom (opens.op_map_id_obj U)) := by tidy @[simp] lemma id_inv_app' (U) (p) : (id ℱ).inv.app (op ⟨U, p⟩) = ℱ.map (𝟙 (op ⟨U, p⟩)) := by { dsimp [id], simp, } /-- The natural isomorphism between the pushforward of a presheaf along the composition of two continuous maps and the corresponding pushforward of a pushforward. -/ def comp {Y Z : Top.{v}} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g) _* ℱ ≅ g _* (f _* ℱ) := iso_whisker_right (nat_iso.op (opens.map_comp f g).symm) ℱ lemma comp_eq {Y Z : Top.{v}} (f : X ⟶ Y) (g : Y ⟶ Z) : (f ≫ g) _* ℱ = g _* (f _* ℱ) := rfl @[simp] lemma comp_hom_app {Y Z : Top.{v}} (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (comp ℱ f g).hom.app U = 𝟙 _ := by { dsimp [comp], tidy, } @[simp] lemma comp_inv_app {Y Z : Top.{v}} (f : X ⟶ Y) (g : Y ⟶ Z) (U) : (comp ℱ f g).inv.app U = 𝟙 _ := by { dsimp [comp], tidy, } end pushforward /-- A morphism of presheaves gives rise to a morphisms of the pushforwards of those presheaves. -/ @[simps] def pushforward_map {X Y : Top.{v}} (f : X ⟶ Y) {ℱ 𝒢 : X.presheaf C} (α : ℱ ⟶ 𝒢) : f _* ℱ ⟶ f _* 𝒢 := { app := λ U, α.app _, naturality' := λ U V i, by { erw α.naturality, refl, } } open category_theory.limits section pullback variable [has_colimits C] noncomputable theory /-- Pullback a presheaf on `Y` along a continuous map `f : X ⟶ Y`, obtaining a presheaf on `X`. This is defined in terms of left Kan extensions, which is just a fancy way of saying "take the colimits over the open sets whose preimage contains U". -/ @[simps] def pullback_obj {X Y : Top.{v}} (f : X ⟶ Y) (ℱ : Y.presheaf C) : X.presheaf C := (Lan (opens.map f).op).obj ℱ /-- Pulling back along continuous maps is functorial. -/ def pullback_map {X Y : Top.{v}} (f : X ⟶ Y) {ℱ 𝒢 : Y.presheaf C} (α : ℱ ⟶ 𝒢) : pullback_obj f ℱ ⟶ pullback_obj f 𝒢 := (Lan (opens.map f).op).map α /-- If `f '' U` is open, then `f⁻¹ℱ U ≅ ℱ (f '' U)`. -/ @[simps] def pullback_obj_obj_of_image_open {X Y : Top.{v}} (f : X ⟶ Y) (ℱ : Y.presheaf C) (U : opens X) (H : is_open (f '' U)) : (pullback_obj f ℱ).obj (op U) ≅ ℱ.obj (op ⟨_, H⟩) := begin let x : costructured_arrow (opens.map f).op (op U) := { left := op ⟨f '' U, H⟩, hom := ((@hom_of_le _ _ _ ((opens.map f).obj ⟨_, H⟩) (set.image_preimage.le_u_l _)).op : op ((opens.map f).obj (⟨⇑f '' ↑U, H⟩)) ⟶ op U) }, have hx : is_terminal x := { lift := λ s, begin fapply costructured_arrow.hom_mk, change op (unop _) ⟶ op (⟨_, H⟩ : opens _), refine (hom_of_le _).op, exact (set.image_subset f s.X.hom.unop.le).trans (set.image_preimage.l_u_le ↑(unop s.X.left)), simp end }, exact is_colimit.cocone_point_unique_up_to_iso (colimit.is_colimit _) (colimit_of_diagram_terminal hx _), end namespace pullback variables {X Y : Top.{v}} (ℱ : Y.presheaf C) local attribute [reassoc] colimit.pre_desc /-- The pullback along the identity is isomorphic to the original presheaf. -/ def id : pullback_obj (𝟙 _) ℱ ≅ ℱ := nat_iso.of_components (λ U, pullback_obj_obj_of_image_open (𝟙 _) ℱ (unop U) (by simpa using U.unop.2) ≪≫ ℱ.map_iso (eq_to_iso (by simp))) (λ U V i, begin ext, simp[-eq_to_hom_map,-eq_to_iso_map], erw category_theory.limits.colimit.pre_desc_assoc, erw colimit.ι_desc_assoc, erw colimit.ι_desc_assoc, dsimp, simp only [←ℱ.map_comp], congr end) lemma id_inv_app (U : opens Y) : (id ℱ).inv.app (op U) = colimit.ι (Lan.diagram (opens.map (𝟙 Y)).op ℱ (op U)) (@costructured_arrow.mk _ _ _ _ _ (op U) _ (eq_to_hom (by simp))) := begin dsimp[id], simp[-eq_to_hom_map,-eq_to_iso_map],dsimp[colimit_of_diagram_terminal], delta Lan.diagram, refine eq.trans _ (category.id_comp _), rw ← ℱ.map_id, congr, any_goals { apply subsingleton.helim }, all_goals { simp } end end pullback end pullback variable (C) /-- The pushforward functor. -/ def pushforward {X Y : Top.{v}} (f : X ⟶ Y) : X.presheaf C ⥤ Y.presheaf C := { obj := pushforward_obj f, map := @pushforward_map _ _ X Y f } lemma id_pushforward {X : Top.{v}} : pushforward C (𝟙 X) = 𝟭 (X.presheaf C) := begin apply category_theory.functor.ext, { intros, ext U, have h := f.congr, erw h (opens.op_map_id_obj U), simpa }, { intros, apply pushforward.id_eq }, end variables [has_colimits C] /-- Pullback a presheaf on `Y` along a continuous map `f : X ⟶ Y`, obtaining a presheaf on `X`. -/ @[simps] def pullback {X Y : Top.{v}} (f : X ⟶ Y) : Y.presheaf C ⥤ X.presheaf C := Lan (opens.map f).op /-- The pullback and pushforward along a continuous map are adjoint to each other. -/ @[simps unit_app_app counit_app_app] def pushforward_pullback_adjunction {X Y : Top.{v}} (f : X ⟶ Y) : pullback C f ⊣ pushforward C f := Lan.adjunction _ _ end presheaf end Top
d44569bcb8f790b5a43a9452df23b816cf800328
dd4e652c749fea9ac77e404005cb3470e5f75469
/src/alex_playground/test3.lean
5e135017689d54d3730590e89e187196a78296d3
[]
no_license
skbaek/cvx
e32822ad5943541539966a37dee162b0a5495f55
c50c790c9116f9fac8dfe742903a62bdd7292c15
refs/heads/master
1,623,803,010,339
1,618,058,958,000
1,618,058,958,000
176,293,135
3
2
null
null
null
null
UTF-8
Lean
false
false
150
lean
universe variables u v w def foo : Type 1 := sorry def bar : Type 2 := sorry def x : foo := sorry set_option pp.universes true #check lift.{2 9} x
4fcaeeeaa5ca45f2c70c71876ad39ff1dafd815f
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/1859.lean
8214454980e1c00f0f335aad3e7e706ed554265d
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
290
lean
prelude class T1 (α : Type) := (O : Type) class T2 (α : Type) extends T1 α class T3 (α : Type) extends T1 α class A (α : Type) [T1 α] := (x : T1.O α) class B (α : Type) [T3 α] extends A α def X {α : Type} [T2 α] : A α := sorry example {α : Type} [T3 α] : B α := { X with }
4ea780dcb3cf55cbca7280124eca4cfd2d14ff48
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/finsupp/to_dfinsupp.lean
17e7ff470fb9b7e35d99f1e4d4e5acac18470c34
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
11,449
lean
/- Copyright (c) 2021 Eric Wieser. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Eric Wieser -/ import algebra.module.equiv import data.dfinsupp.basic import data.finsupp.basic /-! # Conversion between `finsupp` and homogenous `dfinsupp` This module provides conversions between `finsupp` and `dfinsupp`. It is in its own file since neither `finsupp` or `dfinsupp` depend on each other. ## Main definitions * "identity" maps between `finsupp` and `dfinsupp`: * `finsupp.to_dfinsupp : (ι →₀ M) → (Π₀ i : ι, M)` * `dfinsupp.to_finsupp : (Π₀ i : ι, M) → (ι →₀ M)` * Bundled equiv versions of the above: * `finsupp_equiv_dfinsupp : (ι →₀ M) ≃ (Π₀ i : ι, M)` * `finsupp_add_equiv_dfinsupp : (ι →₀ M) ≃+ (Π₀ i : ι, M)` * `finsupp_lequiv_dfinsupp R : (ι →₀ M) ≃ₗ[R] (Π₀ i : ι, M)` * stronger versions of `finsupp.split`: * `sigma_finsupp_equiv_dfinsupp : ((Σ i, η i) →₀ N) ≃ (Π₀ i, (η i →₀ N))` * `sigma_finsupp_add_equiv_dfinsupp : ((Σ i, η i) →₀ N) ≃+ (Π₀ i, (η i →₀ N))` * `sigma_finsupp_lequiv_dfinsupp : ((Σ i, η i) →₀ N) ≃ₗ[R] (Π₀ i, (η i →₀ N))` ## Theorems The defining features of these operations is that they preserve the function and support: * `finsupp.to_dfinsupp_coe` * `finsupp.to_dfinsupp_support` * `dfinsupp.to_finsupp_coe` * `dfinsupp.to_finsupp_support` and therefore map `finsupp.single` to `dfinsupp.single` and vice versa: * `finsupp.to_dfinsupp_single` * `dfinsupp.to_finsupp_single` as well as preserving arithmetic operations. For the bundled equivalences, we provide lemmas that they reduce to `finsupp.to_dfinsupp`: * `finsupp_add_equiv_dfinsupp_apply` * `finsupp_lequiv_dfinsupp_apply` * `finsupp_add_equiv_dfinsupp_symm_apply` * `finsupp_lequiv_dfinsupp_symm_apply` ## Implementation notes We provide `dfinsupp.to_finsupp` and `finsupp_equiv_dfinsupp` computably by adding `[decidable_eq ι]` and `[Π m : M, decidable (m ≠ 0)]` arguments. To aid with definitional unfolding, these arguments are also present on the `noncomputable` equivs. -/ variables {ι : Type*} {R : Type*} {M : Type*} /-! ### Basic definitions and lemmas -/ section defs /-- Interpret a `finsupp` as a homogenous `dfinsupp`. -/ def finsupp.to_dfinsupp [has_zero M] (f : ι →₀ M) : Π₀ i : ι, M := { to_fun := f, support' := trunc.mk ⟨f.support.1, λ i, (classical.em (f i = 0)).symm.imp_left (finsupp.mem_support_iff.mpr)⟩ } @[simp] lemma finsupp.to_dfinsupp_coe [has_zero M] (f : ι →₀ M) : ⇑f.to_dfinsupp = f := rfl section variables [decidable_eq ι] [has_zero M] @[simp] lemma finsupp.to_dfinsupp_single (i : ι) (m : M) : (finsupp.single i m).to_dfinsupp = dfinsupp.single i m := by { ext, simp [finsupp.single_apply, dfinsupp.single_apply] } variables [Π m : M, decidable (m ≠ 0)] @[simp] lemma to_dfinsupp_support (f : ι →₀ M) : f.to_dfinsupp.support = f.support := by { ext, simp, } /-- Interpret a homogenous `dfinsupp` as a `finsupp`. Note that the elaborator has a lot of trouble with this definition - it is often necessary to write `(dfinsupp.to_finsupp f : ι →₀ M)` instead of `f.to_finsupp`, as for some unknown reason using dot notation or omitting the type ascription prevents the type being resolved correctly. -/ def dfinsupp.to_finsupp (f : Π₀ i : ι, M) : ι →₀ M := ⟨f.support, f, λ i, by simp only [dfinsupp.mem_support_iff]⟩ @[simp] lemma dfinsupp.to_finsupp_coe (f : Π₀ i : ι, M) : ⇑f.to_finsupp = f := rfl @[simp] lemma dfinsupp.to_finsupp_support (f : Π₀ i : ι, M) : f.to_finsupp.support = f.support := by { ext, simp, } @[simp] lemma dfinsupp.to_finsupp_single (i : ι) (m : M) : (dfinsupp.single i m : Π₀ i : ι, M).to_finsupp = finsupp.single i m := by { ext, simp [finsupp.single_apply, dfinsupp.single_apply] } @[simp] lemma finsupp.to_dfinsupp_to_finsupp (f : ι →₀ M) : f.to_dfinsupp.to_finsupp = f := finsupp.coe_fn_injective rfl @[simp] lemma dfinsupp.to_finsupp_to_dfinsupp (f : Π₀ i : ι, M) : f.to_finsupp.to_dfinsupp = f := dfinsupp.coe_fn_injective rfl end end defs /-! ### Lemmas about arithmetic operations -/ section lemmas namespace finsupp @[simp] lemma to_dfinsupp_zero [has_zero M] : (0 : ι →₀ M).to_dfinsupp = 0 := dfinsupp.coe_fn_injective rfl @[simp] lemma to_dfinsupp_add [add_zero_class M] (f g : ι →₀ M) : (f + g).to_dfinsupp = f.to_dfinsupp + g.to_dfinsupp := dfinsupp.coe_fn_injective rfl @[simp] lemma to_dfinsupp_neg [add_group M] (f : ι →₀ M) : (-f).to_dfinsupp = -f.to_dfinsupp := dfinsupp.coe_fn_injective rfl @[simp] lemma to_dfinsupp_sub [add_group M] (f g : ι →₀ M) : (f - g).to_dfinsupp = f.to_dfinsupp - g.to_dfinsupp := dfinsupp.coe_fn_injective rfl @[simp] lemma to_dfinsupp_smul [monoid R] [add_monoid M] [distrib_mul_action R M] (r : R) (f : ι →₀ M) : (r • f).to_dfinsupp = r • f.to_dfinsupp := dfinsupp.coe_fn_injective rfl end finsupp namespace dfinsupp variables [decidable_eq ι] @[simp] lemma to_finsupp_zero [has_zero M] [Π m : M, decidable (m ≠ 0)] : to_finsupp 0 = (0 : ι →₀ M) := finsupp.coe_fn_injective rfl @[simp] lemma to_finsupp_add [add_zero_class M] [Π m : M, decidable (m ≠ 0)] (f g : Π₀ i : ι, M) : (to_finsupp (f + g) : ι →₀ M) = (to_finsupp f + to_finsupp g) := finsupp.coe_fn_injective $ dfinsupp.coe_add _ _ @[simp] lemma to_finsupp_neg [add_group M] [Π m : M, decidable (m ≠ 0)] (f : Π₀ i : ι, M) : (to_finsupp (-f) : ι →₀ M) = -to_finsupp f := finsupp.coe_fn_injective $ dfinsupp.coe_neg _ @[simp] lemma to_finsupp_sub [add_group M] [Π m : M, decidable (m ≠ 0)] (f g : Π₀ i : ι, M) : (to_finsupp (f - g) : ι →₀ M) = to_finsupp f - to_finsupp g := finsupp.coe_fn_injective $ dfinsupp.coe_sub _ _ @[simp] lemma to_finsupp_smul [monoid R] [add_monoid M] [distrib_mul_action R M] [Π m : M, decidable (m ≠ 0)] (r : R) (f : Π₀ i : ι, M) : (to_finsupp (r • f) : ι →₀ M) = r • to_finsupp f := finsupp.coe_fn_injective $ dfinsupp.coe_smul _ _ end dfinsupp end lemmas /-! ### Bundled `equiv`s -/ section equivs /-- `finsupp.to_dfinsupp` and `dfinsupp.to_finsupp` together form an equiv. -/ @[simps {fully_applied := ff}] def finsupp_equiv_dfinsupp [decidable_eq ι] [has_zero M] [Π m : M, decidable (m ≠ 0)] : (ι →₀ M) ≃ (Π₀ i : ι, M) := { to_fun := finsupp.to_dfinsupp, inv_fun := dfinsupp.to_finsupp, left_inv := finsupp.to_dfinsupp_to_finsupp, right_inv := dfinsupp.to_finsupp_to_dfinsupp } /-- The additive version of `finsupp.to_finsupp`. Note that this is `noncomputable` because `finsupp.has_add` is noncomputable. -/ @[simps {fully_applied := ff}] def finsupp_add_equiv_dfinsupp [decidable_eq ι] [add_zero_class M] [Π m : M, decidable (m ≠ 0)] : (ι →₀ M) ≃+ (Π₀ i : ι, M) := { to_fun := finsupp.to_dfinsupp, inv_fun := dfinsupp.to_finsupp, map_add' := finsupp.to_dfinsupp_add, .. finsupp_equiv_dfinsupp} variables (R) /-- The additive version of `finsupp.to_finsupp`. Note that this is `noncomputable` because `finsupp.has_add` is noncomputable. -/ @[simps {fully_applied := ff}] def finsupp_lequiv_dfinsupp [decidable_eq ι] [semiring R] [add_comm_monoid M] [Π m : M, decidable (m ≠ 0)] [module R M] : (ι →₀ M) ≃ₗ[R] (Π₀ i : ι, M) := { to_fun := finsupp.to_dfinsupp, inv_fun := dfinsupp.to_finsupp, map_smul' := finsupp.to_dfinsupp_smul, map_add' := finsupp.to_dfinsupp_add, .. finsupp_equiv_dfinsupp} section sigma /-- ### Stronger versions of `finsupp.split` -/ noncomputable theory open_locale classical variables {η : ι → Type*} {N : Type*} [semiring R] open finsupp /-- `finsupp.split` is an equivalence between `(Σ i, η i) →₀ N` and `Π₀ i, (η i →₀ N)`. -/ def sigma_finsupp_equiv_dfinsupp [has_zero N] : ((Σ i, η i) →₀ N) ≃ (Π₀ i, (η i →₀ N)) := { to_fun := λ f, ⟨split f, trunc.mk ⟨(split_support f : finset ι).val, λ i, begin rw [← finset.mem_def, mem_split_support_iff_nonzero], exact (decidable.em _).symm end⟩⟩, inv_fun := λ f, begin refine on_finset (finset.sigma f.support (λ j, (f j).support)) (λ ji, f ji.1 ji.2) (λ g hg, finset.mem_sigma.mpr ⟨_, mem_support_iff.mpr hg⟩), simp only [ne.def, dfinsupp.mem_support_to_fun], intro h, rw h at hg, simpa using hg end, left_inv := λ f, by { ext, simp [split] }, right_inv := λ f, by { ext, simp [split] } } @[simp] lemma sigma_finsupp_equiv_dfinsupp_apply [has_zero N] (f : (Σ i, η i) →₀ N) : (sigma_finsupp_equiv_dfinsupp f : Π i, (η i →₀ N)) = finsupp.split f := rfl @[simp] lemma sigma_finsupp_equiv_dfinsupp_symm_apply [has_zero N] (f : Π₀ i, (η i →₀ N)) (s : Σ i, η i) : (sigma_finsupp_equiv_dfinsupp.symm f : (Σ i, η i) →₀ N) s = f s.1 s.2 := rfl @[simp] lemma sigma_finsupp_equiv_dfinsupp_support [has_zero N] (f : (Σ i, η i) →₀ N) : (sigma_finsupp_equiv_dfinsupp f).support = finsupp.split_support f := begin ext, rw dfinsupp.mem_support_to_fun, exact (finsupp.mem_split_support_iff_nonzero _ _).symm, end @[simp] lemma sigma_finsupp_equiv_dfinsupp_single [has_zero N] (a : Σ i, η i) (n : N) : sigma_finsupp_equiv_dfinsupp (finsupp.single a n) = @dfinsupp.single _ (λ i, η i →₀ N) _ _ a.1 (finsupp.single a.2 n) := begin obtain ⟨i, a⟩ := a, ext j b, by_cases h : i = j, { subst h, simp [split_apply, finsupp.single_apply] }, suffices : finsupp.single (⟨i, a⟩ : Σ i, η i) n ⟨j, b⟩ = 0, { simp [split_apply, dif_neg h, this] }, have H : (⟨i, a⟩ : Σ i, η i) ≠ ⟨j, b⟩ := by simp [h], rw [finsupp.single_apply, if_neg H] end -- Without this Lean fails to find the `add_zero_class` instance on `Π₀ i, (η i →₀ N)`. local attribute [-instance] finsupp.has_zero @[simp] lemma sigma_finsupp_equiv_dfinsupp_add [add_zero_class N] (f g : (Σ i, η i) →₀ N) : sigma_finsupp_equiv_dfinsupp (f + g) = (sigma_finsupp_equiv_dfinsupp f + (sigma_finsupp_equiv_dfinsupp g) : (Π₀ (i : ι), η i →₀ N)) := by {ext, refl} /-- `finsupp.split` is an additive equivalence between `(Σ i, η i) →₀ N` and `Π₀ i, (η i →₀ N)`. -/ @[simps] def sigma_finsupp_add_equiv_dfinsupp [add_zero_class N] : ((Σ i, η i) →₀ N) ≃+ (Π₀ i, (η i →₀ N)) := { to_fun := sigma_finsupp_equiv_dfinsupp, inv_fun := sigma_finsupp_equiv_dfinsupp.symm, map_add' := sigma_finsupp_equiv_dfinsupp_add, .. sigma_finsupp_equiv_dfinsupp } local attribute [-instance] finsupp.add_zero_class --tofix: r • (sigma_finsupp_equiv_dfinsupp f) doesn't work. @[simp] lemma sigma_finsupp_equiv_dfinsupp_smul {R} [monoid R] [add_monoid N] [distrib_mul_action R N] (r : R) (f : (Σ i, η i) →₀ N) : sigma_finsupp_equiv_dfinsupp (r • f) = @has_smul.smul R (Π₀ i, η i →₀ N) mul_action.to_has_smul r (sigma_finsupp_equiv_dfinsupp f) := by { ext, refl } local attribute [-instance] finsupp.add_monoid /-- `finsupp.split` is a linear equivalence between `(Σ i, η i) →₀ N` and `Π₀ i, (η i →₀ N)`. -/ @[simps] def sigma_finsupp_lequiv_dfinsupp [add_comm_monoid N] [module R N] : ((Σ i, η i) →₀ N) ≃ₗ[R] (Π₀ i, (η i →₀ N)) := { map_smul' := sigma_finsupp_equiv_dfinsupp_smul, .. sigma_finsupp_add_equiv_dfinsupp } end sigma end equivs
d68d1dc59bb228691f7996d7485ce9f9891833b4
07c6143268cfb72beccd1cc35735d424ebcb187b
/src/analysis/calculus/deriv.lean
5a5486ee217f94a2768046854401a63e4491b02b
[ "Apache-2.0" ]
permissive
khoek/mathlib
bc49a842910af13a3c372748310e86467d1dc766
aa55f8b50354b3e11ba64792dcb06cccb2d8ee28
refs/heads/master
1,588,232,063,837
1,587,304,803,000
1,587,304,803,000
176,688,517
0
0
Apache-2.0
1,553,070,585,000
1,553,070,585,000
null
UTF-8
Lean
false
false
60,786
lean
/- Copyright (c) 2019 Gabriel Ebner. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Gabriel Ebner, Sébastien Gouëzel -/ import analysis.calculus.fderiv data.polynomial /-! # One-dimensional derivatives This file defines the derivative of a function `f : 𝕜 → F` where `𝕜` is a normed field and `F` is a normed space over this field. The derivative of such a function `f` at a point `x` is given by an element `f' : F`. The theory is developed analogously to the [Fréchet derivatives](./fderiv.lean). We first introduce predicates defined in terms of the corresponding predicates for Fréchet derivatives: - `has_deriv_at_filter f f' x L` states that the function `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. - `has_deriv_within_at f f' s x` states that the function `f` has the derivative `f'` at the point `x` within the subset `s`. - `has_deriv_at f f' x` states that the function `f` has the derivative `f'` at the point `x`. For the last two notions we also define a functional version: - `deriv_within f s x` is a derivative of `f` at `x` within `s`. If the derivative does not exist, then `deriv_within f s x` equals zero. - `deriv f x` is a derivative of `f` at `x`. If the derivative does not exist, then `deriv f x` equals zero. The theorems `fderiv_within_deriv_within` and `fderiv_deriv` show that the one-dimensional derivatives coincide with the general Fréchet derivatives. We also show the existence and compute the derivatives of: - constants - the identity function - linear maps - addition - negation - subtraction - multiplication - inverse `x → x⁻¹` - multiplication of two functions in `𝕜 → 𝕜` - multiplication of a function in `𝕜 → 𝕜` and of a function in `𝕜 → E` - composition of a function in `𝕜 → F` with a function in `𝕜 → 𝕜` - composition of a function in `F → E` with a function in `𝕜 → F` - division - polynomials For most binary operations we also define `const_op` and `op_const` theorems for the cases when the first or second argument is a constant. This makes writing chains of `has_deriv_at`'s easier, and they more frequently lead to the desired result. We set up the simplifier so that it can compute the derivative of simple functions. For instance, ```lean example (x : ℝ) : deriv (λ x, cos (sin x) * exp x) x = (cos(sin(x))-sin(sin(x))*cos(x))*exp(x) := by { simp, ring } ``` ## Implementation notes Most of the theorems are direct restatements of the corresponding theorems for Fréchet derivatives. The strategy to construct simp lemmas that give the simplifier the possibility to compute derivatives is the same as the one for differentiability statements, as explained in `fderiv.lean`. See the explanations there. -/ universes u v w noncomputable theory open_locale classical topological_space open filter asymptotics set open continuous_linear_map (smul_right smul_right_one_eq_iff) set_option class.instance_max_depth 100 variables {𝕜 : Type u} [nondiscrete_normed_field 𝕜] section variables {F : Type v} [normed_group F] [normed_space 𝕜 F] variables {E : Type w} [normed_group E] [normed_space 𝕜 E] /-- `f` has the derivative `f'` at the point `x` as `x` goes along the filter `L`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges along the filter `L`. -/ def has_deriv_at_filter (f : 𝕜 → F) (f' : F) (x : 𝕜) (L : filter 𝕜) := has_fderiv_at_filter f (smul_right 1 f' : 𝕜 →L[𝕜] F) x L /-- `f` has the derivative `f'` at the point `x` within the subset `s`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def has_deriv_within_at (f : 𝕜 → F) (f' : F) (s : set 𝕜) (x : 𝕜) := has_deriv_at_filter f f' x (nhds_within x s) /-- `f` has the derivative `f'` at the point `x`. That is, `f x' = f x + (x' - x) • f' + o(x' - x)` where `x'` converges to `x`. -/ def has_deriv_at (f : 𝕜 → F) (f' : F) (x : 𝕜) := has_deriv_at_filter f f' x (𝓝 x) /-- Derivative of `f` at the point `x` within the set `s`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_within_at f f' s x`), then `f x' = f x + (x' - x) • deriv_within f s x + o(x' - x)` where `x'` converges to `x` inside `s`. -/ def deriv_within (f : 𝕜 → F) (s : set 𝕜) (x : 𝕜) := (fderiv_within 𝕜 f s x : 𝕜 →L[𝕜] F) 1 /-- Derivative of `f` at the point `x`, if it exists. Zero otherwise. If the derivative exists (i.e., `∃ f', has_deriv_at f f' x`), then `f x' = f x + (x' - x) • deriv f x + o(x' - x)` where `x'` converges to `x`. -/ def deriv (f : 𝕜 → F) (x : 𝕜) := (fderiv 𝕜 f x : 𝕜 →L[𝕜] F) 1 variables {f f₀ f₁ g : 𝕜 → F} variables {f' f₀' f₁' g' : F} variables {x : 𝕜} variables {s t : set 𝕜} variables {L L₁ L₂ : filter 𝕜} /-- Expressing `has_fderiv_at_filter f f' x L` in terms of `has_deriv_at_filter` -/ lemma has_fderiv_at_filter_iff_has_deriv_at_filter {f' : 𝕜 →L[𝕜] F} : has_fderiv_at_filter f f' x L ↔ has_deriv_at_filter f (f' 1) x L := by simp [has_deriv_at_filter] /-- Expressing `has_fderiv_within_at f f' s x` in terms of `has_deriv_within_at` -/ lemma has_fderiv_within_at_iff_has_deriv_within_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_within_at f f' s x ↔ has_deriv_within_at f (f' 1) s x := by simp [has_deriv_within_at, has_deriv_at_filter, has_fderiv_within_at] /-- Expressing `has_deriv_within_at f f' s x` in terms of `has_fderiv_within_at` -/ lemma has_deriv_within_at_iff_has_fderiv_within_at {f' : F} : has_deriv_within_at f f' s x ↔ has_fderiv_within_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) s x := iff.rfl /-- Expressing `has_fderiv_at f f' x` in terms of `has_deriv_at` -/ lemma has_fderiv_at_iff_has_deriv_at {f' : 𝕜 →L[𝕜] F} : has_fderiv_at f f' x ↔ has_deriv_at f (f' 1) x := by simp [has_deriv_at, has_deriv_at_filter, has_fderiv_at] /-- Expressing `has_deriv_at f f' x` in terms of `has_fderiv_at` -/ lemma has_deriv_at_iff_has_fderiv_at {f' : F} : has_deriv_at f f' x ↔ has_fderiv_at f (smul_right 1 f' : 𝕜 →L[𝕜] F) x := iff.rfl lemma deriv_within_zero_of_not_differentiable_within_at (h : ¬ differentiable_within_at 𝕜 f s x) : deriv_within f s x = 0 := by { unfold deriv_within, rw fderiv_within_zero_of_not_differentiable_within_at, simp, assumption } lemma deriv_zero_of_not_differentiable_at (h : ¬ differentiable_at 𝕜 f x) : deriv f x = 0 := by { unfold deriv, rw fderiv_zero_of_not_differentiable_at, simp, assumption } theorem unique_diff_within_at.eq_deriv (s : set 𝕜) (H : unique_diff_within_at 𝕜 s x) (h : has_deriv_within_at f f' s x) (h₁ : has_deriv_within_at f f₁' s x) : f' = f₁' := smul_right_one_eq_iff.mp $ unique_diff_within_at.eq H h h₁ theorem has_deriv_at_filter_iff_tendsto : has_deriv_at_filter f f' x L ↔ tendsto (λ x' : 𝕜, ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) L (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_within_at_iff_tendsto : has_deriv_within_at f f' s x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (nhds_within x s) (𝓝 0) := has_fderiv_at_filter_iff_tendsto theorem has_deriv_at_iff_tendsto : has_deriv_at f f' x ↔ tendsto (λ x', ∥x' - x∥⁻¹ * ∥f x' - f x - (x' - x) • f'∥) (𝓝 x) (𝓝 0) := has_fderiv_at_filter_iff_tendsto /-- If the domain has dimension one, then Fréchet derivative is equivalent to the classical definition with a limit. In this version we have to take the limit along the subset `-{x}`, because for `y=x` the slope equals zero due to the convention `0⁻¹=0`. -/ lemma has_deriv_at_filter_iff_tendsto_slope {x : 𝕜} {L : filter 𝕜} : has_deriv_at_filter f f' x L ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (L ⊓ principal (-{x})) (𝓝 f') := begin conv_lhs { simp only [has_deriv_at_filter_iff_tendsto, (normed_field.norm_inv _).symm, (norm_smul _ _).symm, tendsto_zero_iff_norm_tendsto_zero.symm] }, conv_rhs { rw [← nhds_translation f', tendsto_comap_iff] }, refine (tendsto_inf_principal_nhds_iff_of_forall_eq $ by simp).symm.trans (tendsto_congr' _), rw mem_inf_principal, refine univ_mem_sets' (λ z hz, _), have : z ≠ x, by simpa [function.comp] using hz, simp only [mem_set_of_eq], rw [smul_sub, ← mul_smul, inv_mul_cancel (sub_ne_zero.2 this), one_smul] end lemma has_deriv_within_at_iff_tendsto_slope {x : 𝕜} {s : set 𝕜} : has_deriv_within_at f f' s x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (nhds_within x (s \ {x})) (𝓝 f') := begin simp only [has_deriv_within_at, nhds_within, diff_eq, inf_assoc.symm, inf_principal.symm], exact has_deriv_at_filter_iff_tendsto_slope end lemma has_deriv_within_at_iff_tendsto_slope' {x : 𝕜} {s : set 𝕜} (hs : x ∉ s) : has_deriv_within_at f f' s x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (nhds_within x s) (𝓝 f') := begin convert ← has_deriv_within_at_iff_tendsto_slope, exact diff_singleton_eq_self hs end lemma has_deriv_at_iff_tendsto_slope {x : 𝕜} : has_deriv_at f f' x ↔ tendsto (λ y, (y - x)⁻¹ • (f y - f x)) (nhds_within x (-{x})) (𝓝 f') := has_deriv_at_filter_iff_tendsto_slope theorem has_deriv_at_iff_is_o_nhds_zero : has_deriv_at f f' x ↔ is_o (λh, f (x + h) - f x - h • f') (λh, h) (𝓝 0) := has_fderiv_at_iff_is_o_nhds_zero theorem has_deriv_at_filter.mono (h : has_deriv_at_filter f f' x L₂) (hst : L₁ ≤ L₂) : has_deriv_at_filter f f' x L₁ := has_fderiv_at_filter.mono h hst theorem has_deriv_within_at.mono (h : has_deriv_within_at f f' t x) (hst : s ⊆ t) : has_deriv_within_at f f' s x := has_fderiv_within_at.mono h hst theorem has_deriv_at.has_deriv_at_filter (h : has_deriv_at f f' x) (hL : L ≤ 𝓝 x) : has_deriv_at_filter f f' x L := has_fderiv_at.has_fderiv_at_filter h hL theorem has_deriv_at.has_deriv_within_at (h : has_deriv_at f f' x) : has_deriv_within_at f f' s x := has_fderiv_at.has_fderiv_within_at h lemma has_deriv_within_at.differentiable_within_at (h : has_deriv_within_at f f' s x) : differentiable_within_at 𝕜 f s x := has_fderiv_within_at.differentiable_within_at h lemma has_deriv_at.differentiable_at (h : has_deriv_at f f' x) : differentiable_at 𝕜 f x := has_fderiv_at.differentiable_at h @[simp] lemma has_deriv_within_at_univ : has_deriv_within_at f f' univ x ↔ has_deriv_at f f' x := has_fderiv_within_at_univ theorem has_deriv_at_unique (h₀ : has_deriv_at f f₀' x) (h₁ : has_deriv_at f f₁' x) : f₀' = f₁' := smul_right_one_eq_iff.mp $ has_fderiv_at_unique h₀ h₁ lemma has_deriv_within_at_inter' (h : t ∈ nhds_within x s) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter' h lemma has_deriv_within_at_inter (h : t ∈ 𝓝 x) : has_deriv_within_at f f' (s ∩ t) x ↔ has_deriv_within_at f f' s x := has_fderiv_within_at_inter h lemma has_deriv_within_at.union (hs : has_deriv_within_at f f' s x) (ht : has_deriv_within_at f f' t x) : has_deriv_within_at f f' (s ∪ t) x := begin simp only [has_deriv_within_at, nhds_within_union], exact hs.join ht, end lemma has_deriv_within_at.nhds_within (h : has_deriv_within_at f f' s x) (ht : s ∈ nhds_within x t) : has_deriv_within_at f f' t x := (has_deriv_within_at_inter' ht).1 (h.mono (inter_subset_right _ _)) lemma has_deriv_within_at.has_deriv_at (h : has_deriv_within_at f f' s x) (hs : s ∈ 𝓝 x) : has_deriv_at f f' x := has_fderiv_within_at.has_fderiv_at h hs lemma differentiable_within_at.has_deriv_within_at (h : differentiable_within_at 𝕜 f s x) : has_deriv_within_at f (deriv_within f s x) s x := show has_fderiv_within_at _ _ _ _, by { convert h.has_fderiv_within_at, simp [deriv_within] } lemma differentiable_at.has_deriv_at (h : differentiable_at 𝕜 f x) : has_deriv_at f (deriv f x) x := show has_fderiv_at _ _ _, by { convert h.has_fderiv_at, simp [deriv] } lemma has_deriv_at.deriv (h : has_deriv_at f f' x) : deriv f x = f' := has_deriv_at_unique h.differentiable_at.has_deriv_at h lemma has_deriv_within_at.deriv_within (h : has_deriv_within_at f f' s x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = f' := hxs.eq_deriv _ h.differentiable_within_at.has_deriv_within_at h lemma fderiv_within_deriv_within : (fderiv_within 𝕜 f s x : 𝕜 → F) 1 = deriv_within f s x := rfl lemma deriv_within_fderiv_within : smul_right 1 (deriv_within f s x) = fderiv_within 𝕜 f s x := by simp [deriv_within] lemma fderiv_deriv : (fderiv 𝕜 f x : 𝕜 → F) 1 = deriv f x := rfl lemma deriv_fderiv : smul_right 1 (deriv f x) = fderiv 𝕜 f x := by simp [deriv] lemma differentiable_at.deriv_within (h : differentiable_at 𝕜 f x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = deriv f x := by { unfold deriv_within deriv, rw h.fderiv_within hxs } lemma deriv_within_subset (st : s ⊆ t) (ht : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f t x) : deriv_within f s x = deriv_within f t x := ((differentiable_within_at.has_deriv_within_at h).mono st).deriv_within ht @[simp] lemma deriv_within_univ : deriv_within f univ = deriv f := by { ext, unfold deriv_within deriv, rw fderiv_within_univ } lemma deriv_within_inter (ht : t ∈ 𝓝 x) (hs : unique_diff_within_at 𝕜 s x) : deriv_within f (s ∩ t) x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_inter ht hs } section congr /-! ### Congruence properties of derivatives -/ theorem has_deriv_at_filter_congr_of_mem_sets (hx : f₀ x = f₁ x) (h₀ : ∀ᶠ x in L, f₀ x = f₁ x) (h₁ : f₀' = f₁') : has_deriv_at_filter f₀ f₀' x L ↔ has_deriv_at_filter f₁ f₁' x L := has_fderiv_at_filter_congr_of_mem_sets hx h₀ (by simp [h₁]) lemma has_deriv_at_filter.congr_of_mem_sets (h : has_deriv_at_filter f f' x L) (hL : ∀ᶠ x in L, f₁ x = f x) (hx : f₁ x = f x) : has_deriv_at_filter f₁ f' x L := by rwa has_deriv_at_filter_congr_of_mem_sets hx hL rfl lemma has_deriv_within_at.congr_mono (h : has_deriv_within_at f f' s x) (ht : ∀x ∈ t, f₁ x = f x) (hx : f₁ x = f x) (h₁ : t ⊆ s) : has_deriv_within_at f₁ f' t x := has_fderiv_within_at.congr_mono h ht hx h₁ lemma has_deriv_within_at.congr (h : has_deriv_within_at f f' s x) (hs : ∀x ∈ s, f₁ x = f x) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := h.congr_mono hs hx (subset.refl _) lemma has_deriv_within_at.congr_of_mem_nhds_within (h : has_deriv_within_at f f' s x) (h₁ : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : has_deriv_within_at f₁ f' s x := has_deriv_at_filter.congr_of_mem_sets h h₁ hx lemma has_deriv_at.congr_of_mem_nhds (h : has_deriv_at f f' x) (h₁ : ∀ᶠ y in 𝓝 x, f₁ y = f y) : has_deriv_at f₁ f' x := has_deriv_at_filter.congr_of_mem_sets h h₁ (mem_of_nhds h₁ : _) lemma deriv_within_congr_of_mem_nhds_within (hs : unique_diff_within_at 𝕜 s x) (hL : ∀ᶠ y in nhds_within x s, f₁ y = f y) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_congr_of_mem_nhds_within hs hL hx } lemma deriv_within_congr (hs : unique_diff_within_at 𝕜 s x) (hL : ∀y∈s, f₁ y = f y) (hx : f₁ x = f x) : deriv_within f₁ s x = deriv_within f s x := by { unfold deriv_within, rw fderiv_within_congr hs hL hx } lemma deriv_congr_of_mem_nhds (hL : ∀ᶠ y in 𝓝 x, f₁ y = f y) : deriv f₁ x = deriv f x := by { unfold deriv, rwa fderiv_congr_of_mem_nhds } end congr section id /-! ### Derivative of the identity -/ variables (s x L) theorem has_deriv_at_filter_id : has_deriv_at_filter id 1 x L := (is_o_zero _ _).congr_left $ by simp theorem has_deriv_within_at_id : has_deriv_within_at id 1 s x := has_deriv_at_filter_id _ _ theorem has_deriv_at_id : has_deriv_at id 1 x := has_deriv_at_filter_id _ _ theorem has_deriv_at_id' : has_deriv_at (λ (x : 𝕜), x) 1 x := has_deriv_at_filter_id _ _ lemma deriv_id : deriv id x = 1 := has_deriv_at.deriv (has_deriv_at_id x) @[simp] lemma deriv_id' : deriv (@id 𝕜) = λ _, 1 := funext deriv_id @[simp] lemma deriv_id'' : deriv (λ x : 𝕜, x) x = 1 := deriv_id x lemma deriv_within_id (hxs : unique_diff_within_at 𝕜 s x) : deriv_within id s x = 1 := by { unfold deriv_within, rw fderiv_within_id, simp, assumption } end id section const /-! ### Derivative of constant functions -/ variables (c : F) (s x L) theorem has_deriv_at_filter_const : has_deriv_at_filter (λ x, c) 0 x L := (is_o_zero _ _).congr_left $ λ _, by simp [continuous_linear_map.zero_apply, sub_self] theorem has_deriv_within_at_const : has_deriv_within_at (λ x, c) 0 s x := has_deriv_at_filter_const _ _ _ theorem has_deriv_at_const : has_deriv_at (λ x, c) 0 x := has_deriv_at_filter_const _ _ _ lemma deriv_const : deriv (λ x, c) x = 0 := has_deriv_at.deriv (has_deriv_at_const x c) @[simp] lemma deriv_const' : deriv (λ x:𝕜, c) = λ x, 0 := funext (λ x, deriv_const x c) lemma deriv_within_const (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λ x, c) s x = 0 := by { rw (differentiable_at_const _).deriv_within hxs, apply deriv_const } end const section is_linear_map /-! ### Derivative of linear maps -/ variables (s x L) [is_linear_map 𝕜 f] lemma is_linear_map.has_deriv_at_filter : has_deriv_at_filter f (f 1) x L := (is_o_zero _ _).congr_left begin intro y, simp only [sub_smul, continuous_linear_map.one_apply, continuous_linear_map.smul_right_apply], rw ← is_linear_map.smul f x, rw ← is_linear_map.smul f y, simp end lemma is_linear_map.has_deriv_within_at : has_deriv_within_at f (f 1) s x := is_linear_map.has_deriv_at_filter _ _ lemma is_linear_map.has_deriv_at : has_deriv_at f (f 1) x := is_linear_map.has_deriv_at_filter _ _ lemma is_linear_map.differentiable_at : differentiable_at 𝕜 f x := (is_linear_map.has_deriv_at _).differentiable_at lemma is_linear_map.differentiable_within_at : differentiable_within_at 𝕜 f s x := (is_linear_map.differentiable_at _).differentiable_within_at @[simp] lemma is_linear_map.deriv : deriv f x = f 1 := has_deriv_at.deriv (is_linear_map.has_deriv_at _) lemma is_linear_map.deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within f s x = f 1 := begin rw differentiable_at.deriv_within (is_linear_map.differentiable_at _) hxs, apply is_linear_map.deriv, assumption end lemma is_linear_map.differentiable : differentiable 𝕜 f := λ x, is_linear_map.differentiable_at _ lemma is_linear_map.differentiable_on : differentiable_on 𝕜 f s := is_linear_map.differentiable.differentiable_on end is_linear_map section add /-! ### Derivative of the sum of two functions -/ theorem has_deriv_at_filter.add (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ y, f y + g y) (f' + g') x L := (hf.add hg).congr_left $ by simp [add_smul, smul_add] theorem has_deriv_within_at.add (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ y, f y + g y) (f' + g') s x := hf.add hg theorem has_deriv_at.add (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x + g x) (f' + g') x := hf.add hg lemma deriv_within_add (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y + g y) s x = deriv_within f s x + deriv_within g s x := (hf.has_deriv_within_at.add hg.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_add (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λy, f y + g y) x = deriv f x + deriv g x := (hf.has_deriv_at.add hg.has_deriv_at).deriv theorem has_deriv_at_filter.add_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ y, f y + c) f' x L := add_zero f' ▸ hf.add (has_deriv_at_filter_const x L c) theorem has_deriv_within_at.add_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ y, f y + c) f' s x := hf.add_const c theorem has_deriv_at.add_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x + c) f' x := hf.add_const c lemma deriv_within_add_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : deriv_within (λy, f y + c) s x = deriv_within f s x := (hf.has_deriv_within_at.add_const c).deriv_within hxs lemma deriv_add_const (hf : differentiable_at 𝕜 f x) (c : F) : deriv (λy, f y + c) x = deriv f x := (hf.has_deriv_at.add_const c).deriv theorem has_deriv_at_filter.const_add (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ y, c + f y) f' x L := zero_add f' ▸ (has_deriv_at_filter_const x L c).add hf theorem has_deriv_within_at.const_add (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c + f y) f' s x := hf.const_add c theorem has_deriv_at.const_add (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c + f x) f' x := hf.const_add c lemma deriv_within_const_add (hxs : unique_diff_within_at 𝕜 s x) (c : F) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λy, c + f y) s x = deriv_within f s x := (hf.has_deriv_within_at.const_add c).deriv_within hxs lemma deriv_const_add (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λy, c + f y) x = deriv f x := (hf.has_deriv_at.const_add c).deriv end add section mul_vector /-! ### Derivative of the multiplication of a scalar function and a vector function -/ variables {c : 𝕜 → 𝕜} {c' : 𝕜} theorem has_deriv_within_at.smul (hc : has_deriv_within_at c c' s x) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c y • f y) (c x • f' + c' • f x) s x := begin show has_fderiv_within_at _ _ _ _, convert has_fderiv_within_at.smul hc hf, ext, simp [smul_add, (mul_smul _ _ _).symm, mul_comm] end theorem has_deriv_at.smul (hc : has_deriv_at c c' x) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c y • f y) (c x • f' + c' • f x) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul hf end lemma deriv_within_smul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c y • f y) s x = c x • deriv_within f s x + (deriv_within c s x) • f x := (hc.has_deriv_within_at.smul hf.has_deriv_within_at).deriv_within hxs lemma deriv_smul (hc : differentiable_at 𝕜 c x) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c y • f y) x = c x • deriv f x + (deriv c x) • f x := (hc.has_deriv_at.smul hf.has_deriv_at).deriv theorem has_deriv_within_at.smul_const (hc : has_deriv_within_at c c' s x) (f : F) : has_deriv_within_at (λ y, c y • f) (c' • f) s x := begin have := hc.smul (has_deriv_within_at_const x s f), rwa [smul_zero, zero_add] at this end theorem has_deriv_at.smul_const (hc : has_deriv_at c c' x) (f : F) : has_deriv_at (λ y, c y • f) (c' • f) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.smul_const f end lemma deriv_within_smul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (f : F) : deriv_within (λ y, c y • f) s x = (deriv_within c s x) • f := (hc.has_deriv_within_at.smul_const f).deriv_within hxs lemma deriv_smul_const (hc : differentiable_at 𝕜 c x) (f : F) : deriv (λ y, c y • f) x = (deriv c x) • f := (hc.has_deriv_at.smul_const f).deriv theorem has_deriv_within_at.const_smul (c : 𝕜) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ y, c • f y) (c • f') s x := begin convert (has_deriv_within_at_const x s c).smul hf, rw [zero_smul, add_zero] end theorem has_deriv_at.const_smul (c : 𝕜) (hf : has_deriv_at f f' x) : has_deriv_at (λ y, c • f y) (c • f') x := begin rw [← has_deriv_within_at_univ] at *, exact hf.const_smul c end lemma deriv_within_const_smul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝕜) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λ y, c • f y) s x = c • deriv_within f s x := (hf.has_deriv_within_at.const_smul c).deriv_within hxs lemma deriv_const_smul (c : 𝕜) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c • f y) x = c • deriv f x := (hf.has_deriv_at.const_smul c).deriv end mul_vector section neg /-! ### Derivative of the negative of a function -/ theorem has_deriv_at_filter.neg (h : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, -f x) (-f') x L := h.neg.congr (by simp) (by simp) theorem has_deriv_within_at.neg (h : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, -f x) (-f') s x := h.neg theorem has_deriv_at.neg (h : has_deriv_at f f' x) : has_deriv_at (λ x, -f x) (-f') x := h.neg lemma deriv_within_neg (hxs : unique_diff_within_at 𝕜 s x) (h : differentiable_within_at 𝕜 f s x) : deriv_within (λy, -f y) s x = - deriv_within f s x := h.has_deriv_within_at.neg.deriv_within hxs lemma deriv_neg : deriv (λy, -f y) x = - deriv f x := if h : differentiable_at 𝕜 f x then h.has_deriv_at.neg.deriv else have ¬differentiable_at 𝕜 (λ y, -f y) x, from λ h', by simpa only [neg_neg] using h'.neg, by simp only [deriv_zero_of_not_differentiable_at h, deriv_zero_of_not_differentiable_at this, neg_zero] @[simp] lemma deriv_neg' : deriv (λy, -f y) = (λ x, - deriv f x) := funext $ λ x, deriv_neg end neg section sub /-! ### Derivative of the difference of two functions -/ theorem has_deriv_at_filter.sub (hf : has_deriv_at_filter f f' x L) (hg : has_deriv_at_filter g g' x L) : has_deriv_at_filter (λ x, f x - g x) (f' - g') x L := hf.add hg.neg theorem has_deriv_within_at.sub (hf : has_deriv_within_at f f' s x) (hg : has_deriv_within_at g g' s x) : has_deriv_within_at (λ x, f x - g x) (f' - g') s x := hf.sub hg theorem has_deriv_at.sub (hf : has_deriv_at f f' x) (hg : has_deriv_at g g' x) : has_deriv_at (λ x, f x - g x) (f' - g') x := hf.sub hg lemma deriv_within_sub (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (hg : differentiable_within_at 𝕜 g s x) : deriv_within (λy, f y - g y) s x = deriv_within f s x - deriv_within g s x := (hf.has_deriv_within_at.sub hg.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_sub (hf : differentiable_at 𝕜 f x) (hg : differentiable_at 𝕜 g x) : deriv (λ y, f y - g y) x = deriv f x - deriv g x := (hf.has_deriv_at.sub hg.has_deriv_at).deriv theorem has_deriv_at_filter.is_O_sub (h : has_deriv_at_filter f f' x L) : is_O (λ x', f x' - f x) (λ x', x' - x) L := has_fderiv_at_filter.is_O_sub h theorem has_deriv_at_filter.sub_const (hf : has_deriv_at_filter f f' x L) (c : F) : has_deriv_at_filter (λ x, f x - c) f' x L := hf.add_const (-c) theorem has_deriv_within_at.sub_const (hf : has_deriv_within_at f f' s x) (c : F) : has_deriv_within_at (λ x, f x - c) f' s x := hf.sub_const c theorem has_deriv_at.sub_const (hf : has_deriv_at f f' x) (c : F) : has_deriv_at (λ x, f x - c) f' x := hf.sub_const c lemma deriv_within_sub_const (hxs : unique_diff_within_at 𝕜 s x) (hf : differentiable_within_at 𝕜 f s x) (c : F) : deriv_within (λy, f y - c) s x = deriv_within f s x := (hf.has_deriv_within_at.sub_const c).deriv_within hxs lemma deriv_sub_const (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λ y, f y - c) x = deriv f x := (hf.has_deriv_at.sub_const c).deriv theorem has_deriv_at_filter.const_sub (c : F) (hf : has_deriv_at_filter f f' x L) : has_deriv_at_filter (λ x, c - f x) (-f') x L := hf.neg.const_add c theorem has_deriv_within_at.const_sub (c : F) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (λ x, c - f x) (-f') s x := hf.const_sub c theorem has_deriv_at.const_sub (c : F) (hf : has_deriv_at f f' x) : has_deriv_at (λ x, c - f x) (-f') x := hf.const_sub c lemma deriv_within_const_sub (hxs : unique_diff_within_at 𝕜 s x) (c : F) (hf : differentiable_within_at 𝕜 f s x) : deriv_within (λy, c - f y) s x = -deriv_within f s x := (hf.has_deriv_within_at.const_sub c).deriv_within hxs lemma deriv_const_sub (c : F) (hf : differentiable_at 𝕜 f x) : deriv (λ y, c - f y) x = -deriv f x := (hf.has_deriv_at.const_sub c).deriv end sub section continuous /-! ### Continuity of a function admitting a derivative -/ theorem has_deriv_at_filter.tendsto_nhds (hL : L ≤ 𝓝 x) (h : has_deriv_at_filter f f' x L) : tendsto f L (𝓝 (f x)) := has_fderiv_at_filter.tendsto_nhds hL h theorem has_deriv_within_at.continuous_within_at (h : has_deriv_within_at f f' s x) : continuous_within_at f s x := has_deriv_at_filter.tendsto_nhds inf_le_left h theorem has_deriv_at.continuous_at (h : has_deriv_at f f' x) : continuous_at f x := has_deriv_at_filter.tendsto_nhds (le_refl _) h end continuous section cartesian_product /-! ### Derivative of the cartesian product of two functions -/ variables {G : Type w} [normed_group G] [normed_space 𝕜 G] variables {f₂ : 𝕜 → G} {f₂' : G} lemma has_deriv_at_filter.prod (hf₁ : has_deriv_at_filter f₁ f₁' x L) (hf₂ : has_deriv_at_filter f₂ f₂' x L) : has_deriv_at_filter (λ x, (f₁ x, f₂ x)) (f₁', f₂') x L := show has_fderiv_at_filter _ _ _ _, by convert has_fderiv_at_filter.prod hf₁ hf₂ lemma has_deriv_within_at.prod (hf₁ : has_deriv_within_at f₁ f₁' s x) (hf₂ : has_deriv_within_at f₂ f₂' s x) : has_deriv_within_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') s x := hf₁.prod hf₂ lemma has_deriv_at.prod (hf₁ : has_deriv_at f₁ f₁' x) (hf₂ : has_deriv_at f₂ f₂' x) : has_deriv_at (λ x, (f₁ x, f₂ x)) (f₁', f₂') x := hf₁.prod hf₂ end cartesian_product section composition /-! ### Derivative of the composition of a vector function and a scalar function We use `scomp` in lemmas on composition of vector valued and scalar valued functions, and `comp` in lemmas on composition of scalar valued functions, in analogy for `smul` and `mul` (and also because the `comp` version with the shorter name will show up much more often in applications). The formula for the derivative involves `smul` in `scomp` lemmas, which can be reduced to usual multiplication in `comp` lemmas. -/ variables {h h₁ h₂ : 𝕜 → 𝕜} {h' h₁' h₂' : 𝕜} /- For composition lemmas, we put x explicit to help the elaborator, as otherwise Lean tends to get confused since there are too many possibilities for composition -/ variable (x) theorem has_deriv_at_filter.scomp (hg : has_deriv_at_filter g g' (h x) (L.map h)) (hh : has_deriv_at_filter h h' x L) : has_deriv_at_filter (g ∘ h) (h' • g') x L := have (smul_right 1 g' : 𝕜 →L[𝕜] _).comp (smul_right 1 h' : 𝕜 →L[𝕜] _) = smul_right 1 (h' • g'), by { ext, simp [mul_smul] }, begin unfold has_deriv_at_filter, rw ← this, exact has_fderiv_at_filter.comp x hg hh, end theorem has_deriv_within_at.scomp {t : set 𝕜} (hg : has_deriv_within_at g g' t (h x)) (hh : has_deriv_within_at h h' s x) (hst : s ⊆ h ⁻¹' t) : has_deriv_within_at (g ∘ h) (h' • g') s x := begin apply has_deriv_at_filter.scomp _ (has_deriv_at_filter.mono hg _) hh, calc map h (nhds_within x s) ≤ nhds_within (h x) (h '' s) : hh.continuous_within_at.tendsto_nhds_within_image ... ≤ nhds_within (h x) t : nhds_within_mono _ (image_subset_iff.mpr hst) end /-- The chain rule. -/ theorem has_deriv_at.scomp (hg : has_deriv_at g g' (h x)) (hh : has_deriv_at h h' x) : has_deriv_at (g ∘ h) (h' • g') x := (hg.mono hh.continuous_at).scomp x hh theorem has_deriv_at.scomp_has_deriv_within_at (hg : has_deriv_at g g' (h x)) (hh : has_deriv_within_at h h' s x) : has_deriv_within_at (g ∘ h) (h' • g') s x := begin rw ← has_deriv_within_at_univ at hg, exact has_deriv_within_at.scomp x hg hh subset_preimage_univ end lemma deriv_within.scomp (hg : differentiable_within_at 𝕜 g t (h x)) (hh : differentiable_within_at 𝕜 h s x) (hs : s ⊆ h ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (g ∘ h) s x = deriv_within h s x • deriv_within g t (h x) := begin apply has_deriv_within_at.deriv_within _ hxs, exact has_deriv_within_at.scomp x (hg.has_deriv_within_at) (hh.has_deriv_within_at) hs end lemma deriv.scomp (hg : differentiable_at 𝕜 g (h x)) (hh : differentiable_at 𝕜 h x) : deriv (g ∘ h) x = deriv h x • deriv g (h x) := begin apply has_deriv_at.deriv, exact has_deriv_at.scomp x hg.has_deriv_at hh.has_deriv_at end /-! ### Derivative of the composition of two scalar functions -/ theorem has_deriv_at_filter.comp (hh₁ : has_deriv_at_filter h₁ h₁' (h₂ x) (L.map h₂)) (hh₂ : has_deriv_at_filter h₂ h₂' x L) : has_deriv_at_filter (h₁ ∘ h₂) (h₁' * h₂') x L := by { rw mul_comm, exact hh₁.scomp x hh₂ } theorem has_deriv_within_at.comp {t : set 𝕜} (hh₁ : has_deriv_within_at h₁ h₁' t (h₂ x)) (hh₂ : has_deriv_within_at h₂ h₂' s x) (hst : s ⊆ h₂ ⁻¹' t) : has_deriv_within_at (h₁ ∘ h₂) (h₁' * h₂') s x := by { rw mul_comm, exact hh₁.scomp x hh₂ hst, } /-- The chain rule. -/ theorem has_deriv_at.comp (hh₁ : has_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_deriv_at h₂ h₂' x) : has_deriv_at (h₁ ∘ h₂) (h₁' * h₂') x := (hh₁.mono hh₂.continuous_at).comp x hh₂ theorem has_deriv_at.comp_has_deriv_within_at (hh₁ : has_deriv_at h₁ h₁' (h₂ x)) (hh₂ : has_deriv_within_at h₂ h₂' s x) : has_deriv_within_at (h₁ ∘ h₂) (h₁' * h₂') s x := begin rw ← has_deriv_within_at_univ at hh₁, exact has_deriv_within_at.comp x hh₁ hh₂ subset_preimage_univ end lemma deriv_within.comp (hh₁ : differentiable_within_at 𝕜 h₁ t (h₂ x)) (hh₂ : differentiable_within_at 𝕜 h₂ s x) (hs : s ⊆ h₂ ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (h₁ ∘ h₂) s x = deriv_within h₁ t (h₂ x) * deriv_within h₂ s x := begin apply has_deriv_within_at.deriv_within _ hxs, exact has_deriv_within_at.comp x (hh₁.has_deriv_within_at) (hh₂.has_deriv_within_at) hs end lemma deriv.comp (hh₁ : differentiable_at 𝕜 h₁ (h₂ x)) (hh₂ : differentiable_at 𝕜 h₂ x) : deriv (h₁ ∘ h₂) x = deriv h₁ (h₂ x) * deriv h₂ x := begin apply has_deriv_at.deriv, exact has_deriv_at.comp x hh₁.has_deriv_at hh₂.has_deriv_at end end composition section composition_vector /-! ### Derivative of the composition of a function between vector spaces and of a function defined on `𝕜` -/ variables {l : F → E} {l' : F →L[𝕜] E} variable (x) /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative within a set equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_within_at.comp_has_deriv_within_at {t : set F} (hl : has_fderiv_within_at l l' t (f x)) (hf : has_deriv_within_at f f' s x) (hst : s ⊆ f ⁻¹' t) : has_deriv_within_at (l ∘ f) (l' (f')) s x := begin rw has_deriv_within_at_iff_has_fderiv_within_at, convert has_fderiv_within_at.comp x hl hf hst, ext, simp end /-- The composition `l ∘ f` where `l : F → E` and `f : 𝕜 → F`, has a derivative equal to the Fréchet derivative of `l` applied to the derivative of `f`. -/ theorem has_fderiv_at.comp_has_deriv_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_at f f' x) : has_deriv_at (l ∘ f) (l' (f')) x := begin rw has_deriv_at_iff_has_fderiv_at, convert has_fderiv_at.comp x hl hf, ext, simp end theorem has_fderiv_at.comp_has_deriv_within_at (hl : has_fderiv_at l l' (f x)) (hf : has_deriv_within_at f f' s x) : has_deriv_within_at (l ∘ f) (l' (f')) s x := begin rw ← has_fderiv_within_at_univ at hl, exact has_fderiv_within_at.comp_has_deriv_within_at x hl hf subset_preimage_univ end lemma fderiv_within.comp_deriv_within {t : set F} (hl : differentiable_within_at 𝕜 l t (f x)) (hf : differentiable_within_at 𝕜 f s x) (hs : s ⊆ f ⁻¹' t) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (l ∘ f) s x = (fderiv_within 𝕜 l t (f x) : F → E) (deriv_within f s x) := begin apply has_deriv_within_at.deriv_within _ hxs, exact (hl.has_fderiv_within_at).comp_has_deriv_within_at x (hf.has_deriv_within_at) hs end lemma fderiv.comp_deriv (hl : differentiable_at 𝕜 l (f x)) (hf : differentiable_at 𝕜 f x) : deriv (l ∘ f) x = (fderiv 𝕜 l (f x) : F → E) (deriv f x) := begin apply has_deriv_at.deriv _, exact (hl.has_fderiv_at).comp_has_deriv_at x (hf.has_deriv_at) end end composition_vector section mul /-! ### Derivative of the multiplication of two scalar functions -/ variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜} theorem has_deriv_within_at.mul (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c y * d y) (c' * d x + c x * d') s x := begin convert hc.smul hd using 1, rw [smul_eq_mul, smul_eq_mul, add_comm] end theorem has_deriv_at.mul (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c y * d y) (c' * d x + c x * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul hd end lemma deriv_within_mul (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c y * d y) s x = deriv_within c s x * d x + c x * deriv_within d s x := (hc.has_deriv_within_at.mul hd.has_deriv_within_at).deriv_within hxs @[simp] lemma deriv_mul (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c y * d y) x = deriv c x * d x + c x * deriv d x := (hc.has_deriv_at.mul hd.has_deriv_at).deriv theorem has_deriv_within_at.mul_const (hc : has_deriv_within_at c c' s x) (d : 𝕜) : has_deriv_within_at (λ y, c y * d) (c' * d) s x := begin convert hc.mul (has_deriv_within_at_const x s d), rw [mul_zero, add_zero] end theorem has_deriv_at.mul_const (hc : has_deriv_at c c' x) (d : 𝕜) : has_deriv_at (λ y, c y * d) (c' * d) x := begin rw [← has_deriv_within_at_univ] at *, exact hc.mul_const d end lemma deriv_within_mul_const (hxs : unique_diff_within_at 𝕜 s x) (hc : differentiable_within_at 𝕜 c s x) (d : 𝕜) : deriv_within (λ y, c y * d) s x = deriv_within c s x * d := (hc.has_deriv_within_at.mul_const d).deriv_within hxs lemma deriv_mul_const (hc : differentiable_at 𝕜 c x) (d : 𝕜) : deriv (λ y, c y * d) x = deriv c x * d := (hc.has_deriv_at.mul_const d).deriv theorem has_deriv_within_at.const_mul (c : 𝕜) (hd : has_deriv_within_at d d' s x) : has_deriv_within_at (λ y, c * d y) (c * d') s x := begin convert (has_deriv_within_at_const x s c).mul hd, rw [zero_mul, zero_add] end theorem has_deriv_at.const_mul (c : 𝕜) (hd : has_deriv_at d d' x) : has_deriv_at (λ y, c * d y) (c * d') x := begin rw [← has_deriv_within_at_univ] at *, exact hd.const_mul c end lemma deriv_within_const_mul (hxs : unique_diff_within_at 𝕜 s x) (c : 𝕜) (hd : differentiable_within_at 𝕜 d s x) : deriv_within (λ y, c * d y) s x = c * deriv_within d s x := (hd.has_deriv_within_at.const_mul c).deriv_within hxs lemma deriv_const_mul (c : 𝕜) (hd : differentiable_at 𝕜 d x) : deriv (λ y, c * d y) x = c * deriv d x := (hd.has_deriv_at.const_mul c).deriv end mul section inverse /-! ### Derivative of `x ↦ x⁻¹` -/ lemma has_deriv_at_inv_one : has_deriv_at (λx, x⁻¹) (-1) (1 : 𝕜) := begin rw has_deriv_at_iff_is_o_nhds_zero, have : is_o (λ (h : 𝕜), h^2 * (1 + h)⁻¹) (λ (h : 𝕜), h * 1) (𝓝 0), { have : tendsto (λ (h : 𝕜), (1 + h)⁻¹) (𝓝 0) (𝓝 (1 + 0)⁻¹) := ((tendsto_const_nhds).add tendsto_id).inv' (by norm_num), exact is_o.mul_is_O (is_o_pow_id one_lt_two) (is_O_one_of_tendsto _ this) }, apply this.congr' _ _, { have : metric.ball (0 : 𝕜) 1 ∈ 𝓝 (0 : 𝕜), from metric.ball_mem_nhds 0 zero_lt_one, filter_upwards [this], assume h hx, have : 0 < ∥1 + h∥ := calc 0 < ∥(1:𝕜)∥ - ∥-h∥ : by rwa [norm_neg, sub_pos, ← dist_zero_right h, normed_field.norm_one] ... ≤ ∥1 - -h∥ : norm_sub_norm_le _ _ ... = ∥1 + h∥ : by simp, have : 1 + h ≠ 0 := norm_pos_iff.mp this, simp, rw ← eq_div_iff_mul_eq _ _ (inv_ne_zero this), field_simp, simp [right_distrib, sub_mul, (show (1 + h)⁻¹ * (1 + h) = 1, by rw mul_comm; exact field.mul_inv_cancel this)], ring }, { exact univ_mem_sets' mul_one } end theorem has_deriv_at_inv (x_ne_zero : x ≠ 0) : has_deriv_at (λy, y⁻¹) (-(x^2)⁻¹) x := begin have A : has_deriv_at (λy, y⁻¹) (-1) (x⁻¹ * x : 𝕜), by { simp only [inv_mul_cancel x_ne_zero, has_deriv_at_inv_one] }, have B : has_deriv_at (λy, x⁻¹ * y) (x⁻¹) x, by simpa only [mul_one] using (has_deriv_at_id x).const_mul x⁻¹, convert (A.comp x B : _).const_mul x⁻¹, { ext y, rw [function.comp_apply, mul_inv', inv_inv', mul_comm, mul_assoc, mul_inv_cancel x_ne_zero, mul_one] }, { field_simp [pow_two] } end theorem has_deriv_within_at_inv (x_ne_zero : x ≠ 0) (s : set 𝕜) : has_deriv_within_at (λx, x⁻¹) (-(x^2)⁻¹) s x := (has_deriv_at_inv x_ne_zero).has_deriv_within_at lemma differentiable_at_inv (x_ne_zero : x ≠ 0) : differentiable_at 𝕜 (λx, x⁻¹) x := (has_deriv_at_inv x_ne_zero).differentiable_at lemma differentiable_within_at_inv (x_ne_zero : x ≠ 0) : differentiable_within_at 𝕜 (λx, x⁻¹) s x := (differentiable_at_inv x_ne_zero).differentiable_within_at lemma differentiable_on_inv : differentiable_on 𝕜 (λx:𝕜, x⁻¹) {x | x ≠ 0} := λx hx, differentiable_within_at_inv hx lemma deriv_inv (x_ne_zero : x ≠ 0) : deriv (λx, x⁻¹) x = -(x^2)⁻¹ := (has_deriv_at_inv x_ne_zero).deriv lemma deriv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x⁻¹) s x = -(x^2)⁻¹ := begin rw differentiable_at.deriv_within (differentiable_at_inv x_ne_zero) hxs, exact deriv_inv x_ne_zero end lemma has_fderiv_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_at (λx, x⁻¹) (smul_right 1 (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) x := has_deriv_at_inv x_ne_zero lemma has_fderiv_within_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_within_at (λx, x⁻¹) (smul_right 1 (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) s x := (has_fderiv_at_inv x_ne_zero).has_fderiv_within_at lemma fderiv_inv (x_ne_zero : x ≠ 0) : fderiv 𝕜 (λx, x⁻¹) x = smul_right 1 (-(x^2)⁻¹) := (has_fderiv_at_inv x_ne_zero).fderiv lemma fderiv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, x⁻¹) s x = smul_right 1 (-(x^2)⁻¹) := begin rw differentiable_at.fderiv_within (differentiable_at_inv x_ne_zero) hxs, exact fderiv_inv x_ne_zero end variables {c : 𝕜 → 𝕜} {c' : 𝕜} lemma has_deriv_within_at.inv (hc : has_deriv_within_at c c' s x) (hx : c x ≠ 0) : has_deriv_within_at (λ y, (c y)⁻¹) (- c' / (c x)^2) s x := begin convert (has_deriv_at_inv hx).comp_has_deriv_within_at x hc, field_simp end lemma has_deriv_at.inv (hc : has_deriv_at c c' x) (hx : c x ≠ 0) : has_deriv_at (λ y, (c y)⁻¹) (- c' / (c x)^2) x := begin rw ← has_deriv_within_at_univ at *, exact hc.inv hx end lemma differentiable_within_at.inv (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0) : differentiable_within_at 𝕜 (λx, (c x)⁻¹) s x := (hc.has_deriv_within_at.inv hx).differentiable_within_at @[simp] lemma differentiable_at.inv (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) : differentiable_at 𝕜 (λx, (c x)⁻¹) x := (hc.has_deriv_at.inv hx).differentiable_at lemma differentiable_on.inv (hc : differentiable_on 𝕜 c s) (hx : ∀ x ∈ s, c x ≠ 0) : differentiable_on 𝕜 (λx, (c x)⁻¹) s := λx h, (hc x h).inv (hx x h) @[simp] lemma differentiable.inv (hc : differentiable 𝕜 c) (hx : ∀ x, c x ≠ 0) : differentiable 𝕜 (λx, (c x)⁻¹) := λx, (hc x).inv (hx x) lemma deriv_within_inv' (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, (c x)⁻¹) s x = - (deriv_within c s x) / (c x)^2 := (hc.has_deriv_within_at.inv hx).deriv_within hxs @[simp] lemma deriv_inv' (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) : deriv (λx, (c x)⁻¹) x = - (deriv c x) / (c x)^2 := (hc.has_deriv_at.inv hx).deriv end inverse section division /-! ### Derivative of `x ↦ c x / d x` -/ variables {c d : 𝕜 → 𝕜} {c' d' : 𝕜} lemma has_deriv_within_at.div (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) (hx : d x ≠ 0) : has_deriv_within_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) s x := begin have A : (d x)⁻¹ * (d x)⁻¹ * (c' * d x) = (d x)⁻¹ * c', by rw [← mul_assoc, mul_comm, ← mul_assoc, ← mul_assoc, mul_inv_cancel hx, one_mul], convert hc.mul ((has_deriv_at_inv hx).comp_has_deriv_within_at x hd), simp [div_eq_inv_mul', pow_two, mul_inv', mul_add, A, sub_eq_add_neg], ring end lemma has_deriv_at.div (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) (hx : d x ≠ 0) : has_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x := begin rw ← has_deriv_within_at_univ at *, exact hc.div hd hx end lemma differentiable_within_at.div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) : differentiable_within_at 𝕜 (λx, c x / d x) s x := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).differentiable_within_at @[simp] lemma differentiable_at.div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : differentiable_at 𝕜 (λx, c x / d x) x := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).differentiable_at lemma differentiable_on.div (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) (hx : ∀ x ∈ s, d x ≠ 0) : differentiable_on 𝕜 (λx, c x / d x) s := λx h, (hc x h).div (hd x h) (hx x h) @[simp] lemma differentiable.div (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) (hx : ∀ x, d x ≠ 0) : differentiable 𝕜 (λx, c x / d x) := λx, (hc x).div (hd x) (hx x) lemma deriv_within_div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, c x / d x) s x = ((deriv_within c s x) * d x - c x * (deriv_within d s x)) / (d x)^2 := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).deriv_within hxs @[simp] lemma deriv_div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : deriv (λx, c x / d x) x = ((deriv c x) * d x - c x * (deriv d x)) / (d x)^2 := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).deriv end division end namespace polynomial /-! ### Derivative of a polynomial -/ variables {x : 𝕜} {s : set 𝕜} variable (p : polynomial 𝕜) /-- The derivative (in the analysis sense) of a polynomial `p` is given by `p.derivative`. -/ protected lemma has_deriv_at (x : 𝕜) : has_deriv_at (λx, p.eval x) (p.derivative.eval x) x := begin apply p.induction_on, { simp [has_deriv_at_const] }, { assume p q hp hq, convert hp.add hq; simp }, { assume n a h, convert h.mul (has_deriv_at_id x), { ext y, simp [pow_add, mul_assoc] }, { simp [pow_add], ring } } end protected theorem has_deriv_within_at (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, p.eval x) (p.derivative.eval x) s x := (p.has_deriv_at x).has_deriv_within_at protected lemma differentiable_at : differentiable_at 𝕜 (λx, p.eval x) x := (p.has_deriv_at x).differentiable_at protected lemma differentiable_within_at : differentiable_within_at 𝕜 (λx, p.eval x) s x := p.differentiable_at.differentiable_within_at protected lemma differentiable : differentiable 𝕜 (λx, p.eval x) := λx, p.differentiable_at protected lemma differentiable_on : differentiable_on 𝕜 (λx, p.eval x) s := p.differentiable.differentiable_on @[simp] protected lemma deriv : deriv (λx, p.eval x) x = p.derivative.eval x := (p.has_deriv_at x).deriv protected lemma deriv_within (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, p.eval x) s x = p.derivative.eval x := begin rw differentiable_at.deriv_within p.differentiable_at hxs, exact p.deriv end protected lemma continuous : continuous (λx, p.eval x) := p.differentiable.continuous protected lemma continuous_on : continuous_on (λx, p.eval x) s := p.continuous.continuous_on protected lemma continuous_at : continuous_at (λx, p.eval x) x := p.continuous.continuous_at protected lemma continuous_within_at : continuous_within_at (λx, p.eval x) s x := p.continuous_at.continuous_within_at protected lemma has_fderiv_at (x : 𝕜) : has_fderiv_at (λx, p.eval x) (smul_right 1 (p.derivative.eval x) : 𝕜 →L[𝕜] 𝕜) x := by simpa [has_deriv_at_iff_has_fderiv_at] using p.has_deriv_at x protected lemma has_fderiv_within_at (x : 𝕜) : has_fderiv_within_at (λx, p.eval x) (smul_right 1 (p.derivative.eval x) : 𝕜 →L[𝕜] 𝕜) s x := (p.has_fderiv_at x).has_fderiv_within_at @[simp] protected lemma fderiv : fderiv 𝕜 (λx, p.eval x) x = smul_right 1 (p.derivative.eval x) := (p.has_fderiv_at x).fderiv protected lemma fderiv_within (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, p.eval x) s x = smul_right 1 (p.derivative.eval x) := begin rw differentiable_at.fderiv_within p.differentiable_at hxs, exact p.fderiv end end polynomial section pow /-! ### Derivative of `x ↦ x^n` for `n : ℕ` -/ variables {x : 𝕜} {s : set 𝕜} {c : 𝕜 → 𝕜} {c' : 𝕜} variable {n : ℕ } lemma has_deriv_at_pow (n : ℕ) (x : 𝕜) : has_deriv_at (λx, x^n) ((n : 𝕜) * x^(n-1)) x := begin convert (polynomial.C 1 * (polynomial.X)^n).has_deriv_at x, { simp }, { rw [polynomial.derivative_monomial], simp } end theorem has_deriv_within_at_pow (n : ℕ) (x : 𝕜) (s : set 𝕜) : has_deriv_within_at (λx, x^n) ((n : 𝕜) * x^(n-1)) s x := (has_deriv_at_pow n x).has_deriv_within_at lemma differentiable_at_pow : differentiable_at 𝕜 (λx, x^n) x := (has_deriv_at_pow n x).differentiable_at lemma differentiable_within_at_pow : differentiable_within_at 𝕜 (λx, x^n) s x := differentiable_at_pow.differentiable_within_at lemma differentiable_pow : differentiable 𝕜 (λx:𝕜, x^n) := λx, differentiable_at_pow lemma differentiable_on_pow : differentiable_on 𝕜 (λx, x^n) s := differentiable_pow.differentiable_on lemma deriv_pow : deriv (λx, x^n) x = (n : 𝕜) * x^(n-1) := (has_deriv_at_pow n x).deriv @[simp] lemma deriv_pow' : deriv (λx, x^n) = λ x, (n : 𝕜) * x^(n-1) := funext $ λ x, deriv_pow lemma deriv_within_pow (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x^n) s x = (n : 𝕜) * x^(n-1) := (has_deriv_within_at_pow n x s).deriv_within hxs lemma iter_deriv_pow' {k : ℕ} : deriv^[k] (λx:𝕜, x^n) = λ x, ((finset.range k).prod (λ i, n - i):ℕ) * x^(n-k) := begin induction k with k ihk, { simp only [one_mul, finset.prod_range_zero, nat.iterate_zero, nat.sub_zero, nat.cast_one] }, { simp only [nat.iterate_succ', ihk, finset.prod_range_succ], ext x, rw [((has_deriv_at_pow (n - k) x).const_mul _).deriv, nat.cast_mul, mul_left_comm, mul_assoc, nat.succ_eq_add_one, nat.sub_sub] } end lemma iter_deriv_pow {k : ℕ} : deriv^[k] (λx:𝕜, x^n) x = ((finset.range k).prod (λ i, n - i):ℕ) * x^(n-k) := congr_fun iter_deriv_pow' x lemma has_deriv_within_at.pow (hc : has_deriv_within_at c c' s x) : has_deriv_within_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') s x := (has_deriv_at_pow n (c x)).comp_has_deriv_within_at x hc lemma has_deriv_at.pow (hc : has_deriv_at c c' x) : has_deriv_at (λ y, (c y)^n) ((n : 𝕜) * (c x)^(n-1) * c') x := by { rw ← has_deriv_within_at_univ at *, exact hc.pow } lemma differentiable_within_at.pow (hc : differentiable_within_at 𝕜 c s x) : differentiable_within_at 𝕜 (λx, (c x)^n) s x := hc.has_deriv_within_at.pow.differentiable_within_at @[simp] lemma differentiable_at.pow (hc : differentiable_at 𝕜 c x) : differentiable_at 𝕜 (λx, (c x)^n) x := hc.has_deriv_at.pow.differentiable_at lemma differentiable_on.pow (hc : differentiable_on 𝕜 c s) : differentiable_on 𝕜 (λx, (c x)^n) s := λx h, (hc x h).pow @[simp] lemma differentiable.pow (hc : differentiable 𝕜 c) : differentiable 𝕜 (λx, (c x)^n) := λx, (hc x).pow lemma deriv_within_pow' (hc : differentiable_within_at 𝕜 c s x) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, (c x)^n) s x = (n : 𝕜) * (c x)^(n-1) * (deriv_within c s x) := hc.has_deriv_within_at.pow.deriv_within hxs @[simp] lemma deriv_pow'' (hc : differentiable_at 𝕜 c x) : deriv (λx, (c x)^n) x = (n : 𝕜) * (c x)^(n-1) * (deriv c x) := hc.has_deriv_at.pow.deriv end pow section fpow /-! ### Derivative of `x ↦ x^m` for `m : ℤ` -/ variables {x : 𝕜} {s : set 𝕜} variable {m : ℤ} lemma has_deriv_at_fpow (m : ℤ) (hx : x ≠ 0) : has_deriv_at (λx, x^m) ((m : 𝕜) * x^(m-1)) x := begin have : ∀ m : ℤ, 0 < m → has_deriv_at (λx, x^m) ((m:𝕜) * x^(m-1)) x, { assume m hm, lift m to ℕ using (le_of_lt hm), simp only [fpow_of_nat, int.cast_coe_nat], convert has_deriv_at_pow _ _ using 2, rw [← int.coe_nat_one, ← int.coe_nat_sub, fpow_coe_nat], norm_cast at hm, exact nat.succ_le_of_lt hm }, rcases lt_trichotomy m 0 with hm|hm|hm, { have := (has_deriv_at_inv _).scomp _ (this (-m) (neg_pos.2 hm)); [skip, exact fpow_ne_zero_of_ne_zero hx _], simp only [(∘), fpow_neg, one_div_eq_inv, inv_inv', smul_eq_mul] at this, convert this using 1, rw [pow_two, mul_inv', inv_inv', int.cast_neg, ← neg_mul_eq_neg_mul, neg_mul_neg, ← fpow_add hx, mul_assoc, ← fpow_add hx], congr, abel }, { simp only [hm, fpow_zero, int.cast_zero, zero_mul, has_deriv_at_const] }, { exact this m hm } end theorem has_deriv_within_at_fpow (m : ℤ) (hx : x ≠ 0) (s : set 𝕜) : has_deriv_within_at (λx, x^m) ((m : 𝕜) * x^(m-1)) s x := (has_deriv_at_fpow m hx).has_deriv_within_at lemma differentiable_at_fpow (hx : x ≠ 0) : differentiable_at 𝕜 (λx, x^m) x := (has_deriv_at_fpow m hx).differentiable_at lemma differentiable_within_at_fpow (hx : x ≠ 0) : differentiable_within_at 𝕜 (λx, x^m) s x := (differentiable_at_fpow hx).differentiable_within_at lemma differentiable_on_fpow (hs : (0:𝕜) ∉ s) : differentiable_on 𝕜 (λx, x^m) s := λ x hxs, differentiable_within_at_fpow (λ hx, hs $ hx ▸ hxs) -- TODO : this is true at `x=0` as well lemma deriv_fpow (hx : x ≠ 0) : deriv (λx, x^m) x = (m : 𝕜) * x^(m-1) := (has_deriv_at_fpow m hx).deriv lemma deriv_within_fpow (hxs : unique_diff_within_at 𝕜 s x) (hx : x ≠ 0) : deriv_within (λx, x^m) s x = (m : 𝕜) * x^(m-1) := (has_deriv_within_at_fpow m hx s).deriv_within hxs lemma iter_deriv_fpow {k : ℕ} (hx : x ≠ 0) : deriv^[k] (λx:𝕜, x^m) x = ((finset.range k).prod (λ i, m - i):ℤ) * x^(m-k) := begin induction k with k ihk generalizing x hx, { simp only [one_mul, finset.prod_range_zero, nat.iterate_zero, int.coe_nat_zero, sub_zero, int.cast_one] }, { rw [nat.iterate_succ', finset.prod_range_succ, int.cast_mul, mul_assoc, mul_left_comm, int.coe_nat_succ, ← sub_sub, ← ((has_deriv_at_fpow _ hx).const_mul _).deriv], apply deriv_congr_of_mem_nhds, apply eventually.mono _ @ihk, exact mem_nhds_sets (is_open_neg $ is_closed_eq continuous_id continuous_const) hx } end end fpow /-! ### Upper estimates on liminf and limsup -/ section real variables {f : ℝ → ℝ} {f' : ℝ} {s : set ℝ} {x : ℝ} {r : ℝ} lemma has_deriv_within_at.limsup_slope_le (hf : has_deriv_within_at f f' s x) (hr : f' < r) : ∀ᶠ z in nhds_within x (s \ {x}), (z - x)⁻¹ * (f z - f x) < r := has_deriv_within_at_iff_tendsto_slope.1 hf (mem_nhds_sets is_open_Iio hr) lemma has_deriv_within_at.limsup_slope_le' (hf : has_deriv_within_at f f' s x) (hs : x ∉ s) (hr : f' < r) : ∀ᶠ z in nhds_within x s, (z - x)⁻¹ * (f z - f x) < r := (has_deriv_within_at_iff_tendsto_slope' hs).1 hf (mem_nhds_sets is_open_Iio hr) lemma has_deriv_within_at.liminf_right_slope_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : f' < r) : ∃ᶠ z in nhds_within x (Ioi x), (z - x)⁻¹ * (f z - f x) < r := (hf.limsup_slope_le' (lt_irrefl x) hr).frequently (nhds_within_Ioi_self_ne_bot x) end real section real_space open metric variables {E : Type u} [normed_group E] [normed_space ℝ E] {f : ℝ → E} {f' : E} {s : set ℝ} {x r : ℝ} /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. -/ lemma has_deriv_within_at.limsup_norm_slope_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in nhds_within x s, ∥z - x∥⁻¹ * ∥f z - f x∥ < r := begin have hr₀ : 0 < r, from lt_of_le_of_lt (norm_nonneg f') hr, have A : ∀ᶠ z in nhds_within x (s \ {x}), ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from (has_deriv_within_at_iff_tendsto_slope.1 hf).norm (mem_nhds_sets is_open_Iio hr), have B : ∀ᶠ z in nhds_within x {x}, ∥(z - x)⁻¹ • (f z - f x)∥ ∈ Iio r, from mem_sets_of_superset self_mem_nhds_within (singleton_subset_iff.2 $ by simp [hr₀]), have C := mem_sup_sets.2 ⟨A, B⟩, rw [← nhds_within_union, diff_union_self, nhds_within_union, mem_sup_sets] at C, filter_upwards [C.1], simp only [mem_set_of_eq, norm_smul, mem_Iio, normed_field.norm_inv], exact λ _, id end /-- If `f` has derivative `f'` within `s` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / ∥z - x∥` is less than `r` in some neighborhood of `x` within `s`. In other words, the limit superior of this ratio as `z` tends to `x` along `s` is less than or equal to `∥f'∥`. This lemma is a weaker version of `has_deriv_within_at.limsup_norm_slope_le` where `∥f z∥ - ∥f x∥` is replaced by `∥f z - f x∥`. -/ lemma has_deriv_within_at.limsup_slope_norm_le (hf : has_deriv_within_at f f' s x) (hr : ∥f'∥ < r) : ∀ᶠ z in nhds_within x s, ∥z - x∥⁻¹ * (∥f z∥ - ∥f x∥) < r := begin apply (hf.limsup_norm_slope_le hr).mono, assume z hz, refine lt_of_le_of_lt (mul_le_mul_of_nonneg_left (norm_sub_norm_le _ _) _) hz, exact inv_nonneg.2 (norm_nonneg _) end /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `∥f z - f x∥ / ∥z - x∥` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`. -/ lemma has_deriv_within_at.liminf_right_norm_slope_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in nhds_within x (Ioi x), ∥z - x∥⁻¹ * ∥f z - f x∥ < r := (hf.limsup_norm_slope_le hr).frequently (nhds_within_Ioi_self_ne_bot x) /-- If `f` has derivative `f'` within `(x, +∞)` at `x`, then for any `r > ∥f'∥` the ratio `(∥f z∥ - ∥f x∥) / (z - x)` is frequently less than `r` as `z → x+0`. In other words, the limit inferior of this ratio as `z` tends to `x+0` is less than or equal to `∥f'∥`. See also * `has_deriv_within_at.limsup_norm_slope_le` for a stronger version using limit superior and any set `s`; * `has_deriv_within_at.liminf_right_norm_slope_le` for a stronger version using `∥f z - f x∥` instead of `∥f z∥ - ∥f x∥`. -/ lemma has_deriv_within_at.liminf_right_slope_norm_le (hf : has_deriv_within_at f f' (Ioi x) x) (hr : ∥f'∥ < r) : ∃ᶠ z in nhds_within x (Ioi x), (z - x)⁻¹ * (∥f z∥ - ∥f x∥) < r := begin have := (hf.limsup_slope_norm_le hr).frequently (nhds_within_Ioi_self_ne_bot x), refine this.mp (eventually.mono self_mem_nhds_within _), assume z hxz hz, rwa [real.norm_eq_abs, abs_of_pos (sub_pos_of_lt hxz)] at hz end end real_space
e6e6e2d1ee25b7e0a057e76974a3c417b8d4e4ea
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/calculus/conformal/normed_space.lean
ed631ac4bab84f325d30d6a158f25dcb2f652aeb
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
4,681
lean
/- Copyright (c) 2021 Yourong Zang. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yourong Zang -/ import analysis.normed_space.conformal_linear_map import analysis.calculus.fderiv /-! # Conformal Maps A continuous linear map between real normed spaces `X` and `Y` is `conformal_at` some point `x` if it is real differentiable at that point and its differential `is_conformal_linear_map`. ## Main definitions * `conformal_at`: the main definition of conformal maps * `conformal`: maps that are conformal at every point * `conformal_factor_at`: the conformal factor of a conformal map at some point ## Main results * The conformality of the composition of two conformal maps, the identity map and multiplications by nonzero constants * `conformal_at_iff_is_conformal_map_fderiv`: an equivalent definition of the conformality of a map In `analysis.calculus.conformal.inner_product`: * `conformal_at_iff`: an equivalent definition of the conformality of a map In `geometry.euclidean.basic`: * `conformal_at.preserves_angle`: if a map is conformal at `x`, then its differential preserves all angles at `x` ## Tags conformal ## Warning The definition of conformality in this file does NOT require the maps to be orientation-preserving. Maps such as the complex conjugate are considered to be conformal. -/ noncomputable theory variables {X Y Z : Type*} [normed_group X] [normed_group Y] [normed_group Z] [normed_space ℝ X] [normed_space ℝ Y] [normed_space ℝ Z] section loc_conformality open linear_isometry continuous_linear_map /-- A map `f` is said to be conformal if it has a conformal differential `f'`. -/ def conformal_at (f : X → Y) (x : X) := ∃ (f' : X →L[ℝ] Y), has_fderiv_at f f' x ∧ is_conformal_map f' lemma conformal_at_id (x : X) : conformal_at id x := ⟨id ℝ X, has_fderiv_at_id _, is_conformal_map_id⟩ lemma conformal_at_const_smul {c : ℝ} (h : c ≠ 0) (x : X) : conformal_at (λ (x': X), c • x') x := ⟨c • continuous_linear_map.id ℝ X, (has_fderiv_at_id x).const_smul c, is_conformal_map_const_smul h⟩ @[nontriviality] lemma subsingleton.conformal_at [subsingleton X] (f : X → Y) (x : X) : conformal_at f x := ⟨0, has_fderiv_at_of_subsingleton _ _, is_conformal_map_of_subsingleton _⟩ /-- A function is a conformal map if and only if its differential is a conformal linear map-/ lemma conformal_at_iff_is_conformal_map_fderiv {f : X → Y} {x : X} : conformal_at f x ↔ is_conformal_map (fderiv ℝ f x) := begin split, { rintros ⟨f', hf, hf'⟩, rwa hf.fderiv }, { intros H, by_cases h : differentiable_at ℝ f x, { exact ⟨fderiv ℝ f x, h.has_fderiv_at, H⟩, }, { nontriviality X, exact absurd (fderiv_zero_of_not_differentiable_at h) H.ne_zero } }, end namespace conformal_at lemma differentiable_at {f : X → Y} {x : X} (h : conformal_at f x) : differentiable_at ℝ f x := let ⟨_, h₁, _⟩ := h in h₁.differentiable_at lemma congr {f g : X → Y} {x : X} {u : set X} (hx : x ∈ u) (hu : is_open u) (hf : conformal_at f x) (h : ∀ (x : X), x ∈ u → g x = f x) : conformal_at g x := let ⟨f', hfderiv, hf'⟩ := hf in ⟨f', hfderiv.congr_of_eventually_eq ((hu.eventually_mem hx).mono h), hf'⟩ lemma comp {f : X → Y} {g : Y → Z} (x : X) (hg : conformal_at g (f x)) (hf : conformal_at f x) : conformal_at (g ∘ f) x := begin rcases hf with ⟨f', hf₁, cf⟩, rcases hg with ⟨g', hg₁, cg⟩, exact ⟨g'.comp f', hg₁.comp x hf₁, cg.comp cf⟩, end lemma const_smul {f : X → Y} {x : X} {c : ℝ} (hc : c ≠ 0) (hf : conformal_at f x) : conformal_at (c • f) x := (conformal_at_const_smul hc $ f x).comp x hf end conformal_at end loc_conformality section global_conformality /-- A map `f` is conformal if it's conformal at every point. -/ def conformal (f : X → Y) := ∀ (x : X), conformal_at f x lemma conformal_id : conformal (id : X → X) := λ x, conformal_at_id x lemma conformal_const_smul {c : ℝ} (h : c ≠ 0) : conformal (λ (x : X), c • x) := λ x, conformal_at_const_smul h x namespace conformal lemma conformal_at {f : X → Y} (h : conformal f) (x : X) : conformal_at f x := h x lemma differentiable {f : X → Y} (h : conformal f) : differentiable ℝ f := λ x, (h x).differentiable_at lemma comp {f : X → Y} {g : Y → Z} (hf : conformal f) (hg : conformal g) : conformal (g ∘ f) := λ x, (hg $ f x).comp x (hf x) lemma const_smul {f : X → Y} (hf : conformal f) {c : ℝ} (hc : c ≠ 0) : conformal (c • f) := λ x, (hf x).const_smul hc end conformal end global_conformality
39d1abeadaa9c186d0b9719ba351144cd840e487
fc086f79b20cf002d6f34b023749998408e94fbf
/src/tidy/some_goal.lean
ff271dee985116e1ebd3b2246e60ef2cfc9b1f13
[]
no_license
semorrison/lean-tidy
f039460136b898fb282f75efedd92f2d5c5d90f8
6c1d46de6cff05e1c2c4c9692af812bca3e13b6c
refs/heads/master
1,624,461,332,392
1,559,655,744,000
1,559,655,744,000
96,569,994
9
4
null
1,538,287,895,000
1,499,455,306,000
Lean
UTF-8
Lean
false
false
1,128
lean
-- Copyright (c) 2018 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison open tactic variable {α : Type} meta def prepend_goal (g : expr) : tactic unit := do goals ← get_goals, set_goals (g :: goals) meta def append_goals (gs : list expr) : tactic unit := do goals ← get_goals, set_goals (goals ++ gs) meta def some_goal_aux (t : tactic α) : ℕ → list expr → tactic (ℕ × α) | n (g :: gs) := do set_goals [g], o ← try_core t, match o with | none := do r ← some_goal_aux (n+1) gs, prepend_goal g, return r | (some r) := do append_goals gs, return (n, r) end | _ [] := fail "some_goal did not find a goal the tactic could succeed on" /- Finds a goal on which the tactic `t` succeeds. If there is one, returns the index of the goal, along with the result of the tactic. Otherwise, fails. -/ meta def some_goal (t : tactic α) : tactic (ℕ × α) := do goals ← get_goals, some_goal_aux t 0 goals
de2153b0423c648120df5789a8ac642842eaeb67
dd4e652c749fea9ac77e404005cb3470e5f75469
/src/alex_playground/sup.lean
e443a6c471339431aee260083ad554d3ec116cd8
[]
no_license
skbaek/cvx
e32822ad5943541539966a37dee162b0a5495f55
c50c790c9116f9fac8dfe742903a62bdd7292c15
refs/heads/master
1,623,803,010,339
1,618,058,958,000
1,618,058,958,000
176,293,135
3
2
null
null
null
null
UTF-8
Lean
false
false
4,552
lean
import data.real.basic import data.matrix.basic import order.lattice import tactic.interactive noncomputable theory section curried universe variables u v w x variables {α : Sort u} {β : Type w} class curried (α : Sort u) (β : Type w) := (uncurried_arg_type : Sort x) (uncurry (f : α): uncurried_arg_type → β) notation `↿`:max x:max := curried.uncurry x instance curried_base : curried (α → β) β := ⟨α, id⟩ instance curried_induction {α' : α → Type v} [∀ a, curried (α' a) β] : curried (Π (a : α), α' a) β := ⟨Σ' (a : α), curried.uncurried_arg_type (α' a) β, λ f p, ↿(f p.1) p.2⟩ def range [curried α β] (f : α) := set.range (@curried.uncurry α β _ f) end curried def optimal_value {α : Type*} [curried α ℝ] (f : α) : ℝ := Sup (range f) def optimal_point {α : Type*} [curried α ℝ] (f : α) := {x : curried.uncurried_arg_type α ℝ // ∀ y, ↿f x ≥ ↿f y} def optimal_point' {α : Type*} [curried α ℝ] (f : α) := {x : curried.uncurried_arg_type α ℝ // ↿f x = optimal_value f} notation `subject_to ` binders ` maximize ` f:(scoped Q, Q) := optimal_point f def transform {α β : Type*} [curried α ℝ] [curried β ℝ] (f : α) (g : β) (t : curried.uncurried_arg_type α ℝ → curried.uncurried_arg_type β ℝ) (t' : curried.uncurried_arg_type β ℝ → curried.uncurried_arg_type α ℝ) (ht : ∀ x, ↿f x = ↿g (t x)) (ht' : ∀ x, ↿f (t' x) = ↿g x) (p : optimal_point f) : optimal_point g := ⟨t p.val, λ y, begin rw [←ht, ←ht'], apply p.property (t' y) end⟩ open tactic open expr setup_tactic_parser meta def get_obj_fun : expr → tactic expr | `(optimal_point %%a) := return a | _ := fail "no optimization problem" meta def get_vars : expr → list (name × expr) | (lam var_name bi var_type body) := (var_name, var_type) :: get_vars body | _ := [] meta def curry_local : list (name × expr) → name → list expr → tactic unit | [] nm locals := fail "nothing to curry" | [(v, t)] nm locals := do l <- get_local nm, change_core (t.instantiate_vars locals) (some l), rename nm v | ((v, t) :: vars') nm locals := do lnm <- get_local nm, cases_core lnm [v, nm], lv <- get_local v, curry_local vars' nm (lv :: locals) meta def curry_goal : list (name × expr) → list expr → tactic unit | [] goals := fail "nothing to curry" | [(v, t)] goals := do change (t.instantiate_vars goals), enable_tags true, set_main_tag [v.to_string] | ((v, t) :: vars') goals := focus1 (do applyc `psigma.mk, swap, gs <- get_goals, focus' [curry_goal [(v, t)] goals, curry_goal vars' (gs.head :: goals)]) meta def curry1 (vars1: list (name × expr)) (vars2: list (name × expr)) : tactic unit := do nm <- get_unused_name, intro nm, curry_local vars1 nm [], curry_goal vars2 [] meta def curry2 (vars: list (name × expr)) : tactic unit := do nm <- get_unused_name, intro nm, curry_local vars nm [], `[dsimp [curried.uncurry, id]], skip meta def transformtac (new : pexpr) : tactic unit := do old_obj_fun <- target >>= get_obj_fun, new_obj_fun <- to_expr new >>= get_obj_fun, old_obj_fun_type <- infer_type old_obj_fun, new_obj_fun_type <- infer_type new_obj_fun, focus1 (do refine ``(@transform %%new_obj_fun_type %%old_obj_fun_type _ _ %%new_obj_fun %%old_obj_fun _ --(λ x, ⟨_, _, _⟩ : ℝ → Σ' (x y : ℝ), x = 5) _ --(λ x : Σ' (x y : ℝ), x = 5, (x.cases_on (λ x yh, _) : ℝ)) _ _ _), focus' [ curry1 (get_vars new_obj_fun) (get_vars old_obj_fun), curry1 (get_vars old_obj_fun) (get_vars new_obj_fun), curry2 (get_vars new_obj_fun), curry2 (get_vars old_obj_fun), skip]) -- intro `x, -- to_expr ```(x) >>= cases_core,) meta def tactic.interactive.transformtac (new : parse texpr) : tactic unit := transformtac new -- Eliminate a fixed variable def my_optimal_point5 : subject_to (x y : ℝ) (h : x = 5) maximize x + y := begin transformtac (subject_to (y : ℝ) maximize 5 + y), { exact 5 }, { exact y }, { refl }, { exact y }, { refl }, { rw h }, sorry end -- Introduce a slack variable def my_optimal_point6 : subject_to (x y : ℝ) (h : x + y ≥ 5) maximize x / y := begin transformtac (subject_to (x y z : ℝ) (h : z = x + y) (hz : z ≥ 5) maximize x / y), { exact x }, { exact y }, { linarith }, { exact x }, { exact y }, { exact x + y }, { refl }, { exact h }, { refl }, { refl }, sorry end #check nat
3a4961c101349dfaf8437a994e813cec6fc995d2
8e2026ac8a0660b5a490dfb895599fb445bb77a0
/library/init/data/set.lean
307012a28a1fb5d4cb590fcf4038b18298c6ef79
[ "Apache-2.0" ]
permissive
pcmoritz/lean
6a8575115a724af933678d829b4f791a0cb55beb
35eba0107e4cc8a52778259bb5392300267bfc29
refs/heads/master
1,607,896,326,092
1,490,752,175,000
1,490,752,175,000
86,612,290
0
0
null
1,490,809,641,000
1,490,809,641,000
null
UTF-8
Lean
false
false
2,146
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.interactive universes u v def set (α : Type u) := α → Prop def set_of {α : Type u} (p : α → Prop) : set α := p namespace set variables {α : Type u} {β : Type v} protected def mem (a : α) (s : set α) := s a instance : has_mem α (set α) := ⟨set.mem⟩ protected def subset (s₁ s₂ : set α) := ∀ ⦃a⦄, a ∈ s₁ → a ∈ s₂ instance : has_subset (set α) := ⟨set.subset⟩ protected def sep (p : α → Prop) (s : set α) : set α := {a | a ∈ s ∧ p a} instance : has_sep α (set α) := ⟨set.sep⟩ instance : has_emptyc (set α) := ⟨λ a, false⟩ protected def insert (a : α) (s : set α) : set α := {b | b = a ∨ b ∈ s} instance : has_insert α (set α) := ⟨set.insert⟩ protected def union (s₁ s₂ : set α) : set α := {a | a ∈ s₁ ∨ a ∈ s₂} instance : has_union (set α) := ⟨set.union⟩ protected def inter (s₁ s₂ : set α) : set α := {a | a ∈ s₁ ∧ a ∈ s₂} instance : has_inter (set α) := ⟨set.inter⟩ def compl (s : set α) : set α := {a | a ∉ s} instance : has_neg (set α) := ⟨compl⟩ protected def diff (s t : set α) : set α := {a ∈ s | a ∉ t} instance : has_sdiff (set α) := ⟨set.diff⟩ def powerset (s : set α) : set (set α) := {t | t ⊆ s} prefix `𝒫`:100 := powerset def image (f : α → β) (s : set α) : set β := {b | ∃ a, a ∈ s ∧ f a = b} instance : functor set := {map := @set.image, id_map := begin intros _ s, apply funext, intro b, dsimp [image, set_of], exact propext ⟨λ ⟨b', ⟨_, _⟩⟩, ‹b' = b› ▸ ‹s b'›, λ _, ⟨b, ⟨‹s b›, rfl⟩⟩⟩, end, map_comp := begin intros, apply funext, intro c, dsimp [image, set_of], exact propext ⟨λ ⟨a, ⟨h₁, h₂⟩⟩, ⟨g a, ⟨⟨a, ⟨h₁, rfl⟩⟩, h₂⟩⟩, λ ⟨b, ⟨⟨a, ⟨h₁, h₂⟩⟩, h₃⟩⟩, ⟨a, ⟨h₁, h₂.symm ▸ h₃⟩⟩⟩ end} end set
1d7a888c05e4cec4f8e5d3899d58ad1523180f3e
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/625.lean
40cc37780e75b3542aa9d5ab58f9e6b18eba2438
[ "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
565
lean
import Lean open Lean Lean.PrettyPrinter def foo : PUnit → PUnit := id def x : PUnit := () @[app_unexpander foo] def unexpandFoo : Unexpander := fun _ => `(sorry) #eval do let e : Expr := mkApp (mkMData {} $ mkConst `foo [levelOne]) (mkConst `x) formatTerm (← delab e) #eval do let opts := ({}: Options).setBool `pp.universes true -- the MData annotation should make it not a regular application, -- so the unexpander should not be called. let e : Expr := mkApp (mkMData opts $ mkConst `foo [levelOne]) (mkConst `x) formatTerm (← delab e)
c1cfe325822433cea7d4899800c453afe655c46f
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast_cc_heq6.lean
94e7d6c7418701b19a38b92d17b239ceeef80d3f
[ "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
420
lean
import data.unit open unit set_option blast.strategy "cc" set_option blast.cc.subsingleton true set_option blast.cc.heq true example (a b : unit) : a = b := by blast example (a b : nat) (h₁ : a = 0) (h₂ : b = 0) : a = b → h₁ == h₂ := by blast definition inv' : ∀ (a : nat), a ≠ 0 → nat := sorry example (a b : nat) (h₁ : a ≠ 0) (h₂ : b ≠ 0) : a = b → inv' a h₁ = inv' b h₂ := by blast
0df3e5d103c83933514fbb15af6540c5b1fb6511
4fa118f6209450d4e8d058790e2967337811b2b5
/src/sheaves/sheaf.lean
8be514e35e4a920d916a3eb3993bbc693c52ee49
[ "Apache-2.0" ]
permissive
leanprover-community/lean-perfectoid-spaces
16ab697a220ed3669bf76311daa8c466382207f7
95a6520ce578b30a80b4c36e36ab2d559a842690
refs/heads/master
1,639,557,829,139
1,638,797,866,000
1,638,797,866,000
135,769,296
96
10
Apache-2.0
1,638,797,866,000
1,527,892,754,000
Lean
UTF-8
Lean
false
false
1,537
lean
/- Sheaf (of types). https://stacks.math.columbia.edu/tag/006S Author: Ramon Fernandez Mir -/ import sheaves.covering import sheaves.presheaf universes u v open topological_space lattice section sheaf_condition variables {α : Type u} [topological_space α] -- Restriction map from U to U ∩ V. def res_to_inter_left (F : presheaf α) (U V : opens α) : (F U) → (F (U ∩ V)) := F.res U (U ∩ V) (set.inter_subset_left U V) -- Restriction map from V to U ∩ V. def res_to_inter_right (F : presheaf α) (U V : opens α) : (F V) → (F (U ∩ V)) := F.res V (U ∩ V) (set.inter_subset_right U V) -- Sheaf condition. def locality (F : presheaf α) := ∀ {U} (OC : covering U) (s t : F U), (∀ i, F.res U (OC.Uis i) (subset_covering i) s = F.res U (OC.Uis i) (subset_covering i) t) → s = t def gluing (F : presheaf α) := ∀ {U} (OC : covering U), ∀ (s : Π i, F (OC.Uis i)), (∀ j k, res_to_inter_left F (OC.Uis j) (OC.Uis k) (s j) = res_to_inter_right F (OC.Uis j) (OC.Uis k) (s k)) → ∃ S, ∀ i, F.res U (OC.Uis i) (subset_covering i) S = s i end sheaf_condition -- Definition of a sheaf of types. structure sheaf (α : Type u) [T : topological_space α] := (F : presheaf α) (locality : locality F) (gluing : gluing F) section sheaf_of_types variables {α : Type u} [T : topological_space α] include T instance sheaf.to_presheaf : has_coe (sheaf α) (presheaf α) := ⟨λ S, S.F⟩ def is_sheaf (F : presheaf α) := locality F ∧ gluing F end sheaf_of_types
c45af93621f913497afe91a0dc18133d97bcaad6
cb43248ccd028db2c147695d2c68772d583ed390
/code/dnf.lean
0bf792c87edf90264a9d07e1e7b5cd34757b76a4
[]
no_license
codyroux/ny-haskell
812d872a74be7c68d3dac5c69507214bad2c660e
463e730c5ff1e50c43415714aa27ea4ebf4f64b6
refs/heads/master
1,610,284,527,025
1,448,464,569,000
1,448,464,569,000
46,724,063
4
0
null
null
null
null
UTF-8
Lean
false
false
9,267
lean
import data.bool logic logic.connectives section dnf -- The type of syntactic formulae with "A"s at the leaves inductive Formula (A : Type) : Type := | Var : A → Formula A | Not : Formula A → Formula A | And : Formula A → Formula A → Formula A | Or : Formula A → Formula A → Formula A -- | Implies : Formula A → Formula A → Formula A print bool open Formula bool -- This function distributes a (simple) formula over disjunctions on the right definition right_conj {A : Type} : Formula A → Formula A → Formula A | right_conj a (Or b c) := Or (right_conj a b) (right_conj a c) | right_conj a d := And a d -- This function distributes a formula over disjunctions on the left definition conjunct {A : Type} : Formula A → Formula A → Formula A | conjunct (Or a b) c := Or (conjunct a c) (conjunct b c) | conjunct d c := right_conj d c -- This function simultaneously computes the Disjunctive Normal Form (DNF) of a formula -- and the DNF of its negation depending on the flag. -- Both are required simultaneously in order for the function to work. definition dnf_aux {A : Type} : bool → Formula A → Formula A | dnf_aux tt (Var v) := Var v | dnf_aux ff (Var v) := Not (Var v) | dnf_aux tt (Not a) := dnf_aux ff a | dnf_aux ff (Not a) := dnf_aux tt a | dnf_aux tt (And a b) := conjunct (dnf_aux tt a) (dnf_aux tt b) | dnf_aux ff (And a b) := Or (dnf_aux ff a) (dnf_aux ff b) | dnf_aux tt (Or a b) := Or (dnf_aux tt a) (dnf_aux tt b) | dnf_aux ff (Or a b) := conjunct (dnf_aux ff a) (dnf_aux ff b) definition dnf {A : Type} := @dnf_aux A tt -- Let's test our function, to see if it works as expected section test_eval variable A : Type variables f g h i : A eval dnf (Or (And (Var f) (Or (Var g) (Var h))) (Var i)) theorem test : dnf (Or (And (Var f) (Or (Var g) (Var h))) (Var i)) = Or (Or (And (Var f) (Var g)) (And (Var f) (Var h))) (Var i) := by apply eq.refl end test_eval definition interp : Formula Prop → Prop | interp (Var p) := p | interp (Not a) := ¬ (interp a) | interp (And a b) := (interp a) ∧ (interp b) | interp (Or a b) := (interp a) ∨ (interp b) notation `⟦` φ `⟧` := interp φ print prefix Formula open eq.ops check and.left_distrib lemma right_conj_correct1 {P Q} : ⟦right_conj P Q⟧ → ⟦P⟧ ∧ ⟦Q⟧ := Formula.induction_on Q (assume a H, H) (assume a H1 H2, H2) (assume a b H1 H2 H3, H3) proof assume a b H1 H2 H3, show ⟦P⟧ ∧ (⟦a⟧ ∨ ⟦b⟧), from iff.elim_right (and.left_distrib _ _ _) begin apply (or.imp H1 H2), apply H3 end qed -- more of the above lemma conjunct_correct1 {P Q} : ⟦conjunct P Q⟧ → ⟦P⟧ ∧ ⟦Q⟧ := Formula.induction_on P (assume a, right_conj_correct1) (assume a H, right_conj_correct1) (assume a b H1 H2, right_conj_correct1) proof assume a b H1 H2 H3, iff.elim_right (and.right_distrib _ _ _) begin apply (or.imp H1 H2), apply H3 end qed check non_contradictory_intro check and_of_and_of_imp_of_imp lemma or_not_not_and {a b : Prop} : (¬ a) ∨ (¬ b) → ¬ (a ∧ b) := proof assume (H1 : ¬ a ∨ ¬ b)(H2 : a ∧ b), show false, from or.cases_on H1 (begin intros H3; apply H3; cases H2; assumption end) (begin intros H3; apply H3; cases H2; assumption end) qed lemma and_not_not_or {a b : Prop} : (¬ a) ∧ (¬ b) → ¬ (a ∨ b) := begin intros H1 H2, cases H1 with L R, cases H2 with H2' H2', {apply L, assumption}, {apply R, assumption} end -- This lemma is tougher! We need to prove the positive and negative cases for dnf_aux simultaneously lemma dnf_aux_correct1 {P} : (⟦dnf_aux tt P⟧ → ⟦P⟧) ∧ (⟦dnf_aux ff P⟧ → ¬ ⟦P⟧) := proof Formula.induction_on P (begin intros a, constructor, all_goals (intro H; exact H) end) (proof assume a H, obtain (H1 : ⟦dnf_aux tt a⟧ → ⟦a⟧) (H2 : ⟦dnf_aux ff a⟧ → ¬⟦a⟧), from H, and.intro (show ⟦dnf_aux tt (Not a)⟧ → ⟦Not a⟧, from H2) (assume H3 : ⟦dnf_aux ff (Not a)⟧, assert H4 : ⟦a⟧, from H1 H3, show ¬(¬⟦a⟧), from non_contradictory_intro H4) qed) (proof assume a b H1 H2, assert L : ⟦dnf_aux tt (And a b)⟧ → ⟦And a b⟧, from (proof assume H3 : ⟦dnf_aux tt (And a b)⟧, assert H3' : ⟦dnf_aux tt a⟧ ∧ ⟦dnf_aux tt b⟧, from conjunct_correct1 H3, show ⟦a⟧ ∧ ⟦b⟧, from assert H1' : ⟦dnf_aux tt a⟧ → ⟦a⟧, from and.left H1, assert H2' : ⟦dnf_aux tt b⟧ → ⟦b⟧, from and.left H2, and_of_and_of_imp_of_imp H3' H1' H2' qed), assert R : ⟦dnf_aux ff (And a b)⟧ → ¬⟦And a b⟧, from proof assume H3 : ⟦dnf_aux ff (And a b)⟧, show ¬ (⟦a⟧ ∧ ⟦b⟧), from assert D : ¬⟦a⟧ ∨ ¬⟦b⟧, from proof show ¬⟦a⟧ ∨ ¬⟦b⟧, from assert H1' : ⟦dnf_aux ff a⟧ → ¬⟦a⟧, from and.right H1, assert H2' : ⟦dnf_aux ff b⟧ → ¬⟦b⟧, from and.right H2, or.imp H1' H2' H3 qed, or_not_not_and D qed, and.intro L R qed) begin intros a b H1 H2, split, intro H, esimp [interp], esimp [interp, dnf_aux] at H, cases H with H' H', { clear H2, left, cases H1 with L R, apply L, assumption }, { clear H1, right, cases H2 with L R, apply L, assumption }, intro H, esimp [interp], apply (@and_not_not_or ⟦a⟧ ⟦b⟧), split, { cases H1 with L R, apply R, esimp [dnf_aux] at H, apply and.left, apply conjunct_correct1, exact H }, { cases H2 with L R, apply R, esimp [dnf_aux] at H, apply and.right, apply conjunct_correct1, exact H } end qed lemma dnf_correct1 {P} : ⟦dnf P⟧ → ⟦P⟧ := by exact (and.left dnf_aux_correct1) -- this actually needs EM lemma dnf_correct2 {P} : ⟦P⟧ → ⟦dnf P⟧ := sorry print prefix iff theorem dnf_correct {P} : ⟦dnf P⟧ ↔ ⟦P⟧ := proof have H1 : ⟦dnf P⟧ → ⟦P⟧, from dnf_correct1, have H2 : ⟦P⟧ → ⟦dnf P⟧, from dnf_correct2, iff.intro H1 H2 qed -- The reifiable class captures the propositions which have a -- representation in syntax, which is witnessed by the "is_reification" -- field. structure reifiable [class] (P : Prop) := (phi : Formula Prop)(is_reification : P = ⟦phi⟧) -- we could have chosen P ↔ ⟦phi⟧ alternatively open reifiable -- We define class instances for reifiable for all the formulae that -- we want to be able to reify definition atom_reifiable [instance] {A : Type} {x y : A} : reifiable (x = y) := reifiable.mk (Var (x = y)) (eq.refl _) definition neg_reifiable [instance] {P : Prop} [h : reifiable P] : reifiable (¬ P) := reifiable.mk (Not (phi P)) ( calc (¬ P) = (¬ ⟦phi P⟧) : {is_reification P} ... = ⟦Not (phi P)⟧ : eq.refl ) definition neg_atom_reifiable [instance] {A : Type} {x y : A} : reifiable (x ≠ y) := neg_reifiable definition conjunct_reifiable [instance] {P Q : Prop} [h : reifiable P] [i : reifiable Q] : reifiable (P ∧ Q) := reifiable.mk (And (phi P) (phi Q)) ( calc (P ∧ Q) = (⟦phi P⟧ ∧ Q) : {is_reification P} ... = (⟦phi P⟧ ∧ ⟦phi Q⟧) : {is_reification Q} ... = ⟦And (phi P) (phi Q)⟧ : eq.refl ) definition disjunct_reifiable [instance] {P Q : Prop} [h : reifiable P] [i : reifiable Q] : reifiable (P ∨ Q) := reifiable.mk (Or (phi P) (phi Q)) ( calc (P ∨ Q) = (⟦phi P⟧ ∨ Q) : {is_reification P} ... = (⟦phi P⟧ ∨ ⟦phi Q⟧) : {is_reification Q} ... = ⟦Or (phi P) (phi Q)⟧ : eq.refl ) print prefix iff lemma normalize {P : Prop} [h : reifiable P] : ⟦dnf (phi P)⟧ ↔ P := calc ⟦dnf (phi P)⟧ ↔ ⟦phi P⟧ : dnf_correct ... ↔ P : by rewrite- is_reification variable A : Type variables x y z : A definition pdnf (P : Prop) [h : reifiable P] : Prop := ⟦dnf (phi P)⟧ lemma test' : reifiable (¬ (x = y ∧ y = z) ∨ x = z) := _ lemma test'' : reifiable ((¬ (x = y) ∨ ¬ (y = z)) ∨ x = z) := _ eval (pdnf (¬ (x = y ∧ y = z))) lemma compute_dnf : pdnf (¬ (x = y ∧ y = z)) = ((x = y → false) ∨ (y = z → false)) := eq.refl _ help options set_option pp.implicit true lemma test_normalize : ((x ≠ y ∨ y ≠ z) ∨ x = z) ↔ (¬ (x = y ∧ y = z) ∨ x = z) := proof normalize qed end dnf
535fd2f120ef789156a58eb011f9b8dbca601d52
8b9f17008684d796c8022dab552e42f0cb6fb347
/library/algebra/relation.lean
3582439c839ae80b390229e58c0fc0ff660bc71b
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,451
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: algebra.relation 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
9f27aa3c95d942244c7faf0f9f81cfd005491b3b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/Lake/Build/Monad.lean
ab335aece21d2abfb43fc792eb7e244691889afb
[ "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
3,720
lean
/- Copyright (c) 2021 Mac Malone. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mac Malone, Gabriel Ebner, Sebastian Ullrich -/ import Lake.Config.Monad import Lake.Build.Context import Lake.Util.EStateT open System namespace Lake def mkBuildContext (ws : Workspace) (oldMode : Bool) : IO BuildContext := do let lean := ws.lakeEnv.lean let leanTrace := Hash.ofString lean.githash return { opaqueWs := ws, leanTrace, oldMode startedBuilds := ← IO.mkRef 0 finishedBuilds := ← IO.mkRef 0 } @[inline] def getLeanTrace : BuildM BuildTrace := (·.leanTrace) <$> readThe BuildContext @[inline] def getIsOldMode : BuildM Bool := (·.oldMode) <$> readThe BuildContext def failOnBuildCycle [ToString k] : Except (List k) α → BuildM α | Except.ok a => pure a | Except.error cycle => do let cycle := cycle.map (s!" {·}") error s!"build cycle detected:\n{"\n".intercalate cycle}" /-- Run the recursive build in the given build store. If a cycle is encountered, log it and then fail. -/ @[inline] def RecBuildM.runIn (store : BuildStore) (build : RecBuildM α) : BuildM (α × BuildStore) := do let (res, store) ← EStateT.run store <| ReaderT.run build [] return (← failOnBuildCycle res, store) /-- Run the recursive build in a fresh build store. If a cycle is encountered, log it and then fail. -/ @[inline] def RecBuildM.run (build : RecBuildM α) : BuildM α := do (·.1) <$> build.runIn {} /-- Busy waits to acquire the lock represented by the `lockFile`. Prints a warning if on the first time it has to wait. -/ @[inline] partial def busyAcquireLockFile (lockFile : FilePath) : IO PUnit := do busyLoop true where busyLoop firstTime := try -- Remark: fail if already exists -- (not part of POSIX, but supported on all our platforms) createParentDirs lockFile let h ← IO.FS.Handle.mk lockFile .writeNew h.putStrLn <| toString <| ← IO.Process.getPID catch | .alreadyExists .. => do if firstTime then let stderr ← IO.getStderr stderr.putStrLn s!"warning: waiting for prior `lake build` invocation to finish... (remove '{lockFile}' if stuck)" stderr.flush IO.sleep (ms := 300) busyLoop false | e => throw e /-- Busy wait to acquire the lock of `lockFile`, run `act`, and then release the lock. -/ @[inline] def withLockFile [Monad m] [MonadFinally m] [MonadLiftT IO m] (lockFile : FilePath) (act : m α) : m α := do try busyAcquireLockFile lockFile; act finally show IO _ from do try IO.FS.removeFile lockFile catch | .noFileOrDirectory .. => IO.eprintln <| s!"warning: `{lockFile}` was deleted before the lock was released" | e => throw e /-- The name of the Lake build lock file name (i.e., `lake.lock`). -/ @[noinline] def lockFileName : String := "lake.lock" /-- The workspace's build lock file. -/ @[inline] def Workspace.lockFile (self : Workspace) : FilePath := self.root.buildDir / lockFileName /-- Run the given build function in the Workspace's context. -/ @[inline] def Workspace.runBuild (ws : Workspace) (build : BuildM α) (oldMode := false) : LogIO α := do let ctx ← mkBuildContext ws oldMode /- TODO: The lock file has been temporarily disabled (by lean4#2445) until we have an API for catching `Ctrl-C` during a build. Absent this, the lock file was too disruptive for users. -/ -- withLockFile ws.lockFile do build.run ctx /-- Run the given build function in the Lake monad's workspace. -/ @[inline] def runBuild (build : BuildM α) (oldMode := false) : LakeT LogIO α := do (← getWorkspace).runBuild build oldMode
92ce58eaa87a92671f3ad1113db866327469068c
853df553b1d6ca524e3f0a79aedd32dde5d27ec3
/src/order/boolean_algebra.lean
4858e0463cb0f67f9a8def1a8c477d990bd2679b
[ "Apache-2.0" ]
permissive
DanielFabian/mathlib
efc3a50b5dde303c59eeb6353ef4c35a345d7112
f520d07eba0c852e96fe26da71d85bf6d40fcc2a
refs/heads/master
1,668,739,922,971
1,595,201,756,000
1,595,201,756,000
279,469,476
0
0
null
1,594,696,604,000
1,594,696,604,000
null
UTF-8
Lean
false
false
3,878
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 Type class hierarchy for Boolean algebras. -/ import order.bounded_lattice import logic.function.basic set_option old_structure_cmd true universes u v variables {α : Type u} {w x y z : α} /-- Set / lattice complement -/ class has_compl (α : Type*) := (compl : α → α) export has_compl (compl) postfix `ᶜ`:(max+1) := compl section prio set_option default_priority 100 -- see Note [default priority] /-- A boolean algebra is a bounded distributive lattice with a complementation operation `-` such that `x ⊓ - x = ⊥` and `x ⊔ - x = ⊤`. This is a generalization of (classical) logic of propositions, or the powerset lattice. -/ class boolean_algebra α extends bounded_distrib_lattice α, has_compl α, has_sdiff α := (inf_compl_le_bot : ∀x:α, x ⊓ xᶜ ≤ ⊥) (top_le_sup_compl : ∀x:α, ⊤ ≤ x ⊔ xᶜ) (sdiff_eq : ∀x y:α, x \ y = x ⊓ yᶜ) end prio section boolean_algebra variables [boolean_algebra α] @[simp] theorem inf_compl_eq_bot : x ⊓ xᶜ = ⊥ := bot_unique $ boolean_algebra.inf_compl_le_bot x @[simp] theorem compl_inf_eq_bot : xᶜ ⊓ x = ⊥ := eq.trans inf_comm inf_compl_eq_bot @[simp] theorem sup_compl_eq_top : x ⊔ xᶜ = ⊤ := top_unique $ boolean_algebra.top_le_sup_compl x @[simp] theorem compl_sup_eq_top : xᶜ ⊔ x = ⊤ := eq.trans sup_comm sup_compl_eq_top theorem is_compl_compl : is_compl x xᶜ := is_compl.of_eq inf_compl_eq_bot sup_compl_eq_top theorem is_compl.compl_eq (h : is_compl x y) : xᶜ = y := (h.right_unique is_compl_compl).symm theorem sdiff_eq : x \ y = x ⊓ yᶜ := boolean_algebra.sdiff_eq x y theorem compl_unique (i : x ⊓ y = ⊥) (s : x ⊔ y = ⊤) : xᶜ = y := (is_compl.of_eq i s).compl_eq @[simp] theorem compl_top : ⊤ᶜ = (⊥:α) := is_compl_top_bot.compl_eq @[simp] theorem compl_bot : ⊥ᶜ = (⊤:α) := is_compl_bot_top.compl_eq @[simp] theorem compl_compl' : xᶜᶜ = x := is_compl_compl.symm.compl_eq theorem compl_injective : function.injective (compl : α → α) := function.involutive.injective $ λ x, compl_compl' @[simp] theorem compl_inj_iff : xᶜ = yᶜ ↔ x = y := compl_injective.eq_iff @[simp] theorem compl_inf : (x ⊓ y)ᶜ = xᶜ ⊔ yᶜ := (is_compl_compl.inf_sup is_compl_compl).compl_eq @[simp] theorem compl_sup : (x ⊔ y)ᶜ = xᶜ ⊓ yᶜ := (is_compl_compl.sup_inf is_compl_compl).compl_eq theorem compl_le_compl (h : y ≤ x) : xᶜ ≤ yᶜ := is_compl_compl.antimono is_compl_compl h theorem compl_le_compl_iff_le : yᶜ ≤ xᶜ ↔ x ≤ y := ⟨assume h, by have h := compl_le_compl h; simp at h; assumption, compl_le_compl⟩ theorem le_compl_of_le_compl (h : y ≤ xᶜ) : x ≤ yᶜ := by simpa only [compl_compl'] using compl_le_compl h theorem compl_le_of_compl_le (h : yᶜ ≤ x) : xᶜ ≤ y := by simpa only [compl_compl'] using compl_le_compl h theorem compl_le_iff_compl_le : y ≤ xᶜ ↔ x ≤ yᶜ := ⟨le_compl_of_le_compl, le_compl_of_le_compl⟩ theorem sup_sdiff_same : x ⊔ (y \ x) = x ⊔ y := by simp [sdiff_eq, sup_inf_left] theorem sdiff_eq_left (h : x ⊓ y = ⊥) : x \ y = x := by rwa [sdiff_eq, inf_eq_left, is_compl_compl.le_right_iff, disjoint_iff] theorem sdiff_le_sdiff (h₁ : w ≤ y) (h₂ : z ≤ x) : w \ x ≤ y \ z := by rw [sdiff_eq, sdiff_eq]; from inf_le_inf h₁ (compl_le_compl h₂) end boolean_algebra instance boolean_algebra_Prop : boolean_algebra Prop := { compl := not, sdiff := λ p q, p ∧ ¬ q, sdiff_eq := λ _ _, rfl, inf_compl_le_bot := λ p ⟨Hp, Hpc⟩, Hpc Hp, top_le_sup_compl := λ p H, classical.em p, .. bounded_distrib_lattice_Prop } instance pi.boolean_algebra {α : Type u} {β : Type v} [boolean_algebra β] : boolean_algebra (α → β) := by pi_instance
24354c8920b9b3184be80c4285667ba59882a043
2c096fdfecf64e46ea7bc6ce5521f142b5926864
/src/Lean/Meta/DiscrTreeTypes.lean
f100a857bf18683b6db8383713c60c6b0b9b77a2
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
Kha/lean4
1005785d2c8797ae266a303968848e5f6ce2fe87
b99e11346948023cd6c29d248cd8f3e3fb3474cf
refs/heads/master
1,693,355,498,027
1,669,080,461,000
1,669,113,138,000
184,748,176
0
0
Apache-2.0
1,665,995,520,000
1,556,884,930,000
Lean
UTF-8
Lean
false
false
2,647
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Expr namespace Lean.Meta /-! See file `DiscrTree.lean` for the actual implementation and documentation. -/ namespace DiscrTree /-- Discrimination tree key. See `DiscrTree` -/ inductive Key (simpleReduce : Bool) where | const : Name → Nat → Key simpleReduce | fvar : FVarId → Nat → Key simpleReduce | lit : Literal → Key simpleReduce | star : Key simpleReduce | other : Key simpleReduce | arrow : Key simpleReduce | proj : Name → Nat → Key simpleReduce deriving Inhabited, BEq, Repr protected def Key.hash : Key s → UInt64 | Key.const n a => mixHash 5237 $ mixHash (hash n) (hash a) | Key.fvar n a => mixHash 3541 $ mixHash (hash n) (hash a) | Key.lit v => mixHash 1879 $ hash v | Key.star => 7883 | Key.other => 2411 | Key.arrow => 17 | Key.proj s i => mixHash 11 $ mixHash (hash s) (hash i) instance : Hashable (Key s) := ⟨Key.hash⟩ /-- Discrimination tree trie. See `DiscrTree`. -/ inductive Trie (α : Type) (simpleReduce : Bool) where | node (vs : Array α) (children : Array (Key simpleReduce × Trie α simpleReduce)) : Trie α simpleReduce end DiscrTree open DiscrTree /-- Discrimination trees. It is an index from terms to values of type `α`. If `simpleReduce := true`, then only simple reduction are performed while indexing/retrieving terms. For example, `iota` reduction is not performed. We use `simpleReduce := false` in the type class resolution module, and `simpleReduce := true` in `simp`. Motivations: - In `simp`, we want to have `simp` theorem such as ``` @[simp] theorem liftOn_mk (a : α) (f : α → γ) (h : ∀ a₁ a₂, r a₁ a₂ → f a₁ = f a₂) : Quot.liftOn (Quot.mk r a) f h = f a := rfl ``` If we enable `iota`, then the lhs is reduced to `f a`. - During type class resolution, we often want to reduce types using even `iota`. Example: ``` inductive Ty where | int | bool @[reducible] def Ty.interp (ty : Ty) : Type := Ty.casesOn (motive := fun _ => Type) ty Int Bool def test {a b c : Ty} (f : a.interp → b.interp → c.interp) (x : a.interp) (y : b.interp) : c.interp := f x y def f (a b : Ty.bool.interp) : Ty.bool.interp := -- We want to synthesize `BEq Ty.bool.interp` here, and it will fail -- if we do not reduce `Ty.bool.interp` to `Bool`. test (.==.) a b ``` -/ structure DiscrTree (α : Type) (simpleReduce : Bool) where root : PersistentHashMap (Key simpleReduce) (Trie α simpleReduce) := {} end Lean.Meta
3939de589d22b6ba948325b03604a7aa1daeaf97
97f752b44fd85ec3f635078a2dd125ddae7a82b6
/library/data/complex.lean
8acf0147af0789ae6d101a5ada141ef99612104c
[ "Apache-2.0" ]
permissive
tectronics/lean
ab977ba6be0fcd46047ddbb3c8e16e7c26710701
f38af35e0616f89c6e9d7e3eb1d48e47ee666efe
refs/heads/master
1,532,358,526,384
1,456,276,623,000
1,456,276,623,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
12,477
lean
/- Copyright (c) 2015 Jacob Gross. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jacob Gross, Jeremy Avigad The complex numbers. -/ import data.real open real eq.ops record complex : Type := (re : ℝ) (im : ℝ) notation `ℂ` := complex namespace complex variables (u w z : ℂ) variable n : ℕ protected proposition eq {z w : ℂ} (H1 : complex.re z = complex.re w) (H2 : complex.im z = complex.im w) : z = w := begin induction z, induction w, rewrite [H1, H2] end protected proposition eta (z : ℂ) : complex.mk (complex.re z) (complex.im z) = z := by cases z; exact rfl definition of_real [coercion] (x : ℝ) : ℂ := complex.mk x 0 definition of_rat [coercion] (q : ℚ) : ℂ := q definition of_int [coercion] (i : ℤ) : ℂ := i definition of_nat [coercion] (n : ℕ) : ℂ := n definition of_num [coercion] [reducible] (n : num) : ℂ := n protected definition prio : num := num.pred real.prio definition complex_has_zero [reducible] [instance] [priority complex.prio] : has_zero ℂ := has_zero.mk (of_nat 0) definition complex_has_one [reducible] [instance] [priority complex.prio] : has_one ℂ := has_one.mk (of_nat 1) theorem re_of_real (x : ℝ) : re (of_real x) = x := rfl theorem im_of_real (x : ℝ) : im (of_real x) = 0 := rfl protected definition add (z w : ℂ) : ℂ := complex.mk (complex.re z + complex.re w) (complex.im z + complex.im w) protected definition neg (z : ℂ) : ℂ := complex.mk (-(re z)) (-(im z)) protected definition mul (z w : ℂ) : ℂ := complex.mk (complex.re w * complex.re z - complex.im w * complex.im z) (complex.re w * complex.im z + complex.im w * complex.re z) /- notation -/ definition complex_has_add [reducible] [instance] [priority complex.prio] : has_add complex := has_add.mk complex.add definition complex_has_neg [reducible] [instance] [priority complex.prio] : has_neg complex := has_neg.mk complex.neg definition complex_has_mul [reducible] [instance] [priority complex.prio] : has_mul complex := has_mul.mk complex.mul protected theorem add_def (z w : ℂ) : z + w = complex.mk (complex.re z + complex.re w) (complex.im z + complex.im w) := rfl protected theorem neg_def (z : ℂ) : -z = complex.mk (-(re z)) (-(im z)) := rfl protected theorem mul_def (z w : ℂ) : z * w = complex.mk (complex.re w * complex.re z - complex.im w * complex.im z) (complex.re w * complex.im z + complex.im w * complex.re z) := rfl -- TODO: what notation should we use for i? definition ii := complex.mk 0 1 theorem i_mul_i : ii * ii = -1 := rfl /- basic properties -/ protected theorem add_comm (w z : ℂ) : w + z = z + w := complex.eq !add.comm !add.comm protected theorem add_assoc (w z u : ℂ) : (w + z) + u = w + (z + u) := complex.eq !add.assoc !add.assoc protected theorem add_zero (z : ℂ) : z + 0 = z := complex.eq !add_zero !add_zero protected theorem zero_add (z : ℂ) : 0 + z = z := !complex.add_comm ▸ !complex.add_zero definition smul (x : ℝ) (z : ℂ) : ℂ := complex.mk (x*re z) (x*im z) protected theorem add_right_inv : z + - z = 0 := complex.eq !add.right_inv !add.right_inv protected theorem add_left_inv : - z + z = 0 := !complex.add_comm ▸ !complex.add_right_inv protected theorem mul_comm : w * z = z * w := by rewrite [*complex.mul_def, *mul.comm (re w), *mul.comm (im w), add.comm] protected theorem one_mul : 1 * z = z := by krewrite [complex.mul_def, *mul_one, *mul_zero, sub_zero, zero_add, complex.eta] protected theorem mul_one : z * 1 = z := !complex.mul_comm ▸ !complex.one_mul protected theorem left_distrib : u * (w + z) = u * w + u * z := begin rewrite [*complex.mul_def, *complex.add_def, ▸*, *right_distrib, -sub_sub, *sub_eq_add_neg], rewrite [*add.assoc, add.left_comm (re z * im u), add.left_comm (-_)] end protected theorem right_distrib : (u + w) * z = u * z + w * z := by rewrite [*complex.mul_comm _ z, complex.left_distrib] protected theorem mul_assoc : (u * w) * z = u * (w * z) := begin rewrite [*complex.mul_def, ▸*, *sub_eq_add_neg, *left_distrib, *right_distrib, *neg_add], rewrite [-*neg_mul_eq_neg_mul, -*neg_mul_eq_mul_neg, *add.assoc, *mul.assoc], rewrite [add.comm (-(im z * (im w * _))), add.comm (-(im z * (im w * _))), *add.assoc] end theorem re_add (z w : ℂ) : re (z + w) = re z + re w := rfl theorem im_add (z w : ℂ) : im (z + w) = im z + im w := rfl /- coercions -/ theorem of_real_add (a b : ℝ) : of_real (a + b) = of_real a + of_real b := rfl theorem of_real_mul (a b : ℝ) : of_real (a * b) = (of_real a) * (of_real b) := by rewrite [complex.mul_def, *re_of_real, *im_of_real, *mul_zero, *zero_mul, sub_zero, add_zero, mul.comm] theorem of_real_neg (a : ℝ) : of_real (-a) = -(of_real a) := rfl theorem of_real.inj {a b : ℝ} (H : of_real a = of_real b) : a = b := show re (of_real a) = re (of_real b), from congr_arg re H theorem eq_of_of_real_eq_of_real {a b : ℝ} (H : of_real a = of_real b) : a = b := of_real.inj H theorem of_real_eq_of_real_iff (a b : ℝ) : of_real a = of_real b ↔ a = b := iff.intro eq_of_of_real_eq_of_real !congr_arg /- make complex an instance of ring -/ protected definition comm_ring [reducible] : comm_ring complex := begin fapply comm_ring.mk, exact complex.add, exact complex.add_assoc, exact 0, exact complex.zero_add, exact complex.add_zero, exact complex.neg, exact complex.add_left_inv, exact complex.add_comm, exact complex.mul, exact complex.mul_assoc, exact 1, apply complex.one_mul, apply complex.mul_one, apply complex.left_distrib, apply complex.right_distrib, apply complex.mul_comm end local attribute complex.comm_ring [instance] definition complex_has_sub [reducible] [instance] [priority complex.prio] : has_sub complex := has_sub.mk has_sub.sub theorem of_real_sub (x y : ℝ) : of_real (x - y) = of_real x - of_real y := rfl /- complex modulus and conjugate-/ definition cmod (z : ℂ) : ℝ := (complex.re z) * (complex.re z) + (complex.im z) * (complex.im z) theorem cmod_zero : cmod 0 = 0 := rfl theorem cmod_of_real (x : ℝ) : cmod x = x * x := by rewrite [↑cmod, re_of_real, im_of_real, mul_zero, add_zero] theorem eq_zero_of_cmod_eq_zero {z : ℂ} (H : cmod z = 0) : z = 0 := have H1 : (complex.re z) * (complex.re z) + (complex.im z) * (complex.im z) = 0, from H, have H2 : complex.re z = 0, from eq_zero_of_mul_self_add_mul_self_eq_zero H1, have H3 : complex.im z = 0, from eq_zero_of_mul_self_add_mul_self_eq_zero (!add.comm ▸ H1), show z = 0, from complex.eq H2 H3 definition conj (z : ℂ) : ℂ := complex.mk (complex.re z) (-(complex.im z)) theorem conj_of_real {x : ℝ} : conj (of_real x) = of_real x := rfl theorem conj_add (z w : ℂ) : conj (z + w) = conj z + conj w := by rewrite [↑conj, *complex.add_def, ▸*, neg_add] theorem conj_mul (z w : ℂ) : conj (z * w) = conj z * conj w := by rewrite [↑conj, *complex.mul_def, ▸*, neg_mul_neg, neg_add, -neg_mul_eq_mul_neg, -neg_mul_eq_neg_mul] theorem conj_conj (z : ℂ) : conj (conj z) = z := by rewrite [↑conj, neg_neg, complex.eta] theorem mul_conj_eq_of_real_cmod (z : ℂ) : z * conj z = of_real (cmod z) := by rewrite [↑conj, ↑cmod, ↑of_real, complex.mul_def, ▸*, -*neg_mul_eq_neg_mul, sub_neg_eq_add, mul.comm (re z) (im z), add.right_inv] theorem cmod_conj (z : ℂ) : cmod (conj z) = cmod z := begin apply eq_of_of_real_eq_of_real, rewrite [-*mul_conj_eq_of_real_cmod, conj_conj, mul.comm] end theorem cmod_mul (z w : ℂ) : cmod (z * w) = cmod z * cmod w := begin apply eq_of_of_real_eq_of_real, rewrite [of_real_mul, -*mul_conj_eq_of_real_cmod, conj_mul, *mul.assoc, mul.left_comm w] end protected noncomputable definition inv (z : ℂ) : complex := conj z * of_real (cmod z)⁻¹ protected noncomputable definition complex_has_inv [reducible] [instance] [priority complex.prio] : has_inv complex := has_inv.mk complex.inv protected theorem inv_def (z : ℂ) : z⁻¹ = conj z * of_real (cmod z)⁻¹ := rfl protected theorem inv_zero : 0⁻¹ = (0 : ℂ) := by krewrite [complex.inv_def, conj_of_real, zero_mul] theorem of_real_inv (x : ℝ) : of_real x⁻¹ = (of_real x)⁻¹ := classical.by_cases (assume H : x = 0, by krewrite [H, inv_zero, complex.inv_zero]) (assume H : x ≠ 0, by rewrite [complex.inv_def, cmod_of_real, conj_of_real, mul_inv_eq H H, -of_real_mul, -mul.assoc, mul_inv_cancel H, one_mul]) noncomputable protected definition div (z w : ℂ) : ℂ := z * w⁻¹ noncomputable definition complex_has_div [instance] [reducible] [priority complex.prio] : has_div complex := has_div.mk complex.div protected theorem div_def (z w : ℂ) : z / w = z * w⁻¹ := rfl theorem of_real_div (x y : ℝ) : of_real (x / y) = of_real x / of_real y := have H : x / y = x * y⁻¹, from rfl, by+ rewrite [H, complex.div_def, of_real_mul, of_real_inv] theorem conj_inv (z : ℂ) : (conj z)⁻¹ = conj (z⁻¹) := by rewrite [*complex.inv_def, conj_mul, *conj_conj, conj_of_real, cmod_conj] protected theorem mul_inv_cancel {z : ℂ} (H : z ≠ 0) : z * z⁻¹ = 1 := by rewrite [complex.inv_def, -mul.assoc, mul_conj_eq_of_real_cmod, -of_real_mul, mul_inv_cancel (assume H', H (eq_zero_of_cmod_eq_zero H'))] protected theorem inv_mul_cancel {z : ℂ} (H : z ≠ 0) : z⁻¹ * z = 1 := !mul.comm ▸ complex.mul_inv_cancel H protected noncomputable definition has_decidable_eq : decidable_eq ℂ := take z w, classical.prop_decidable (z = w) protected theorem zero_ne_one : (0 : ℂ) ≠ 1 := assume H, zero_ne_one (eq_of_of_real_eq_of_real H) protected noncomputable definition discrete_field [reducible][trans_instance] : discrete_field ℂ := ⦃ discrete_field, complex.comm_ring, mul_inv_cancel := @complex.mul_inv_cancel, inv_mul_cancel := @complex.inv_mul_cancel, zero_ne_one := complex.zero_ne_one, inv_zero := complex.inv_zero, has_decidable_eq := complex.has_decidable_eq ⦄ -- TODO : we still need the whole family of coercion properties, for nat, int, rat -- coercions theorem of_rat_eq (a : ℚ) : of_rat a = of_real (real.of_rat a) := rfl theorem of_int_eq (a : ℤ) : of_int a = of_real (real.of_int a) := rfl theorem of_nat_eq (a : ℕ) : of_nat a = of_real (real.of_nat a) := rfl theorem of_rat.inj {x y : ℚ} (H : of_rat x = of_rat y) : x = y := real.of_rat.inj (of_real.inj H) theorem eq_of_of_rat_eq_of_rat {x y : ℚ} (H : of_rat x = of_rat y) : x = y := of_rat.inj H theorem of_rat_eq_of_rat_iff (x y : ℚ) : of_rat x = of_rat y ↔ x = y := iff.intro eq_of_of_rat_eq_of_rat !congr_arg theorem of_int.inj {a b : ℤ} (H : of_int a = of_int b) : a = b := rat.of_int.inj (of_rat.inj H) theorem eq_of_of_int_eq_of_int {a b : ℤ} (H : of_int a = of_int b) : a = b := of_int.inj H theorem of_int_eq_of_int_iff (a b : ℤ) : of_int a = of_int b ↔ a = b := iff.intro of_int.inj !congr_arg theorem of_nat.inj {a b : ℕ} (H : of_nat a = of_nat b) : a = b := int.of_nat.inj (of_int.inj H) theorem eq_of_of_nat_eq_of_nat {a b : ℕ} (H : of_nat a = of_nat b) : a = b := of_nat.inj H theorem of_nat_eq_of_nat_iff (a b : ℕ) : of_nat a = of_nat b ↔ a = b := iff.intro of_nat.inj !congr_arg open rat theorem of_rat_add (a b : ℚ) : of_rat (a + b) = of_rat a + of_rat b := by rewrite [of_rat_eq] theorem of_rat_neg (a : ℚ) : of_rat (-a) = -of_rat a := by rewrite [of_rat_eq] -- these show why we have to use krewrite in the next theorem: there are -- two different instances of "has_mul". -- set_option pp.notation false -- set_option pp.coercions true -- set_option pp.implicit true theorem of_rat_mul (a b : ℚ) : of_rat (a * b) = of_rat a * of_rat b := by krewrite [of_rat_eq, real.of_rat_mul, of_real_mul] open int theorem of_int_add (a b : ℤ) : of_int (a + b) = of_int a + of_int b := by krewrite [of_int_eq, real.of_int_add, of_real_add] theorem of_int_neg (a : ℤ) : of_int (-a) = -of_int a := by krewrite [of_int_eq, real.of_int_neg, of_real_neg] theorem of_int_mul (a b : ℤ) : of_int (a * b) = of_int a * of_int b := by krewrite [of_int_eq, real.of_int_mul, of_real_mul] open nat theorem of_nat_add (a b : ℕ) : of_nat (a + b) = of_nat a + of_nat b := by krewrite [of_nat_eq, real.of_nat_add, of_real_add] theorem of_nat_mul (a b : ℕ) : of_nat (a * b) = of_nat a * of_nat b := by krewrite [of_nat_eq, real.of_nat_mul, of_real_mul] end complex
2c21648951722546c827b0ef79eb429fbbabd603
958488bc7f3c2044206e0358e56d7690b6ae696c
/lean/decidable.lean
1262c717d31dd92543029b844fb7ce8355a74a7b
[]
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
1,135
lean
namespace hidden class inductive decidable (p : Prop) : Type | is_false : ¬p → decidable | is_true : p → decidable -- if-then-else def ite (p : Prop) [d : decidable p] {α : Type} (t e : α) : α := decidable.rec_on d (λ _, e) (λ _, t) -- dependent version def dite (p : Prop) [d : decidable p] {α : Type} (t : p → α) (e : ¬p → α) : α := decidable.rec_on d e t end hidden --#check @and.decidable --#check @or.decidable --#check @not.decidable --#check @implies.decidable open nat def step (a b x : ℕ) : ℕ := if x < a ∨ x > b then 0 else 1 set_option pp.implicit true --#print definition step -- Every proposition is decidable -- priority 0 use prop_decidable as a last resort open classical local attribute [instance, priority 0] prop_decidable def as_true2 (c:Prop) [decidable c] : Prop := if c then true else false def of_as_true2 {c : Prop} [H1 : decidable c] (H2 : as_true c) : c := match H1, H2 with | (is_true H), H2 := H | (is_false H), H2 := false.elim H2 end notation `dec_trivial2` := of_as_true2 (by tactic.triv) example : 0 ≠ 1 ∧ (5 < 2 ∨ 3 < 7) := dec_trivial2
ef0eca8898aa0d2d5d6f353b3e1589256d487564
63abd62053d479eae5abf4951554e1064a4c45b4
/src/data/bitvec/core.lean
157df836ea5b970e70bd4867a40d8a091b267abb
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
8,767
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 -/ import data.vector2 import data.nat.basic /-! # Basic operations on bitvectors This is a work-in-progress, and contains additions to other theories. This file was moved to mathlib from core Lean in the switch to Lean 3.20.0c. It is not fully in compliance with mathlib style standards. -/ /-- `bitvec n` is a `vector` of `bool` with length `n`. -/ @[reducible] def bitvec (n : ℕ) := vector bool n namespace bitvec open nat open vector local infix `++ₜ`:65 := vector.append /-- Create a zero bitvector -/ @[reducible] protected def zero (n : ℕ) : bitvec n := repeat ff n /-- Create a bitvector of length `n` whose `n-1`st entry is 1 and other entries are 0. -/ @[reducible] protected def one : Π (n : ℕ), bitvec n | 0 := nil | (succ n) := repeat ff n ++ₜ tt::ᵥnil /-- Create a bitvector from another with a provably equal length. -/ protected def cong {a b : ℕ} (h : a = b) : bitvec a → bitvec b | ⟨x, p⟩ := ⟨x, h ▸ p⟩ /-- `bitvec` specific version of `vector.append` -/ def append {m n} : bitvec m → bitvec n → bitvec (m + n) := vector.append /-! ### Shift operations -/ section shift variable {n : ℕ} /-- `shl x i` is the bitvector obtained by left-shifting `x` `i` times and padding with `ff`. If `x.length < i` then this will return the all-`ff`s bitvector. -/ def shl (x : bitvec n) (i : ℕ) : bitvec n := bitvec.cong (by simp) $ drop i x ++ₜ repeat ff (min n i) /-- `fill_shr x i fill` is the bitvector obtained by right-shifting `x` `i` times and then padding with `fill : bool`. If `x.length < i` then this will return the constant `fill` bitvector. -/ def fill_shr (x : bitvec n) (i : ℕ) (fill : bool) : bitvec n := bitvec.cong begin by_cases (i ≤ n), { have h₁ := sub_le n i, rw [min_eq_right h], rw [min_eq_left h₁, ← nat.add_sub_assoc h, nat.add_comm, nat.add_sub_cancel] }, { have h₁ := le_of_not_ge h, rw [min_eq_left h₁, sub_eq_zero_of_le h₁, zero_min, nat.add_zero] } end $ repeat fill (min n i) ++ₜ take (n-i) x /-- unsigned shift right -/ def ushr (x : bitvec n) (i : ℕ) : bitvec n := fill_shr x i ff /-- signed shift right -/ def sshr : Π {m : ℕ}, bitvec m → ℕ → bitvec m | 0 _ _ := nil | (succ m) x i := head x ::ᵥ fill_shr (tail x) i (head x) end shift /-! ### Bitwise operations -/ section bitwise variable {n : ℕ} /-- bitwise not -/ def not : bitvec n → bitvec n := map bnot /-- bitwise and -/ def and : bitvec n → bitvec n → bitvec n := map₂ band /-- bitwise or -/ def or : bitvec n → bitvec n → bitvec n := map₂ bor /-- bitwise xor -/ def xor : bitvec n → bitvec n → bitvec n := map₂ bxor end bitwise /-! ### Arithmetic operators -/ section arith variable {n : ℕ} /-- `xor3 x y c` is `((x XOR y) XOR c)`. -/ protected def xor3 (x y c : bool) := bxor (bxor x y) c /-- `carry x y c` is `x && y || x && c || y && c`. -/ protected def carry (x y c : bool) := x && y || x && c || y && c /-- `neg x` is the two's complement of `x`. -/ protected def neg (x : bitvec n) : bitvec n := let f := λ y c, (y || c, bxor y c) in prod.snd (map_accumr f x ff) /-- Add with carry (no overflow) -/ def adc (x y : bitvec n) (c : bool) : bitvec (n+1) := let f := λ x y c, (bitvec.carry x y c, bitvec.xor3 x y c) in let ⟨c, z⟩ := vector.map_accumr₂ f x y c in c ::ᵥ z /-- The sum of two bitvectors -/ protected def add (x y : bitvec n) : bitvec n := tail (adc x y ff) /-- Subtract with borrow -/ def sbb (x y : bitvec n) (b : bool) : bool × bitvec n := let f := λ x y c, (bitvec.carry (bnot x) y c, bitvec.xor3 x y c) in vector.map_accumr₂ f x y b /-- The difference of two bitvectors -/ protected def sub (x y : bitvec n) : bitvec n := prod.snd (sbb x y ff) instance : has_zero (bitvec n) := ⟨bitvec.zero n⟩ instance : has_one (bitvec n) := ⟨bitvec.one n⟩ instance : has_add (bitvec n) := ⟨bitvec.add⟩ instance : has_sub (bitvec n) := ⟨bitvec.sub⟩ instance : has_neg (bitvec n) := ⟨bitvec.neg⟩ /-- The product of two bitvectors -/ protected def mul (x y : bitvec n) : bitvec n := let f := λ r b, cond b (r + r + y) (r + r) in (to_list x).foldl f 0 instance : has_mul (bitvec n) := ⟨bitvec.mul⟩ end arith /-! ### Comparison operators -/ section comparison variable {n : ℕ} /-- `uborrow x y` returns `tt` iff the "subtract with borrow" operation on `x`, `y` and `ff` required a borrow. -/ def uborrow (x y : bitvec n) : bool := prod.fst (sbb x y ff) /-- unsigned less-than proposition -/ def ult (x y : bitvec n) : Prop := uborrow x y /-- unsigned greater-than proposition -/ def ugt (x y : bitvec n) : Prop := ult y x /-- unsigned less-than-or-equal-to proposition -/ def ule (x y : bitvec n) : Prop := ¬ (ult y x) /-- unsigned greater-than-or-equal-to proposition -/ def uge (x y : bitvec n) : Prop := ule y x /-- `sborrow x y` returns `tt` iff `x < y` as two's complement integers -/ def sborrow : Π {n : ℕ}, bitvec n → bitvec n → bool | 0 _ _ := ff | (succ n) x y := match (head x, head y) with | (tt, ff) := tt | (ff, tt) := ff | _ := uborrow (tail x) (tail y) end /-- signed less-than proposition -/ def slt (x y : bitvec n) : Prop := sborrow x y /-- signed greater-than proposition -/ def sgt (x y : bitvec n) : Prop := slt y x /-- signed less-than-or-equal-to proposition -/ def sle (x y : bitvec n) : Prop := ¬ (slt y x) /-- signed greater-than-or-equal-to proposition -/ def sge (x y : bitvec n) : Prop := sle y x end comparison /-! ### Conversion to `nat` and `int` -/ section conversion variable {α : Type} /-- Create a bitvector from a `nat` -/ protected def of_nat : Π (n : ℕ), nat → bitvec n | 0 x := nil | (succ n) x := of_nat n (x / 2) ++ₜ to_bool (x % 2 = 1) ::ᵥ nil /-- Create a bitvector in the two's complement representation from an `int` -/ protected def of_int : Π (n : ℕ), int → bitvec (succ n) | n (int.of_nat m) := ff ::ᵥ bitvec.of_nat n m | n (int.neg_succ_of_nat m) := tt ::ᵥ not (bitvec.of_nat n m) /-- `add_lsb r b` is `r + r + 1` if `b` is `tt` and `r + r` otherwise. -/ def add_lsb (r : ℕ) (b : bool) := r + r + cond b 1 0 /-- Given a `list` of `bool`s, return the `nat` they represent as a list of binary digits. -/ def bits_to_nat (v : list bool) : nat := v.foldl add_lsb 0 /-- Return the natural number encoded by the input bitvector -/ protected def to_nat {n : nat} (v : bitvec n) : nat := bits_to_nat (to_list v) theorem bits_to_nat_to_list {n : ℕ} (x : bitvec n) : bitvec.to_nat x = bits_to_nat (vector.to_list x) := rfl local attribute [simp] nat.add_comm nat.add_assoc nat.add_left_comm nat.mul_comm nat.mul_assoc local attribute [simp] nat.zero_add nat.add_zero nat.one_mul nat.mul_one nat.zero_mul nat.mul_zero -- mul_left_comm theorem to_nat_append {m : ℕ} (xs : bitvec m) (b : bool) : bitvec.to_nat (xs ++ₜ b::ᵥnil) = bitvec.to_nat xs * 2 + bitvec.to_nat (b::ᵥnil) := begin cases xs with xs P, simp [bits_to_nat_to_list], clear P, unfold bits_to_nat list.foldl, -- generalize the accumulator of foldl generalize h : 0 = x, conv in (add_lsb x b) { rw ←h }, clear h, simp, induction xs with x xs generalizing x, { simp, unfold list.foldl add_lsb, simp [nat.mul_succ] }, { simp, apply xs_ih } end theorem bits_to_nat_to_bool (n : ℕ) : bitvec.to_nat (to_bool (n % 2 = 1) ::ᵥ nil) = n % 2 := begin simp [bits_to_nat_to_list], unfold bits_to_nat add_lsb list.foldl cond, simp [cond_to_bool_mod_two], end theorem of_nat_succ {k n : ℕ} : bitvec.of_nat (succ k) n = bitvec.of_nat k (n / 2) ++ₜ to_bool (n % 2 = 1) ::ᵥ nil := rfl theorem to_nat_of_nat {k n : ℕ} : bitvec.to_nat (bitvec.of_nat k n) = n % 2 ^ k := begin induction k with k ih generalizing n, { simp [nat.mod_one], refl }, { have h : 0 < 2, { apply le_succ }, rw [of_nat_succ, to_nat_append, ih, bits_to_nat_to_bool, mod_pow_succ h, nat.mul_comm] } end /-- Return the integer encoded by the input bitvector -/ protected def to_int : Π {n : nat}, bitvec n → int | 0 _ := 0 | (succ n) v := cond (head v) (int.neg_succ_of_nat $ bitvec.to_nat $ not $ tail v) (int.of_nat $ bitvec.to_nat $ tail v) end conversion /-! ### Miscellaneous instances -/ private def repr {n : nat} : bitvec n → string | ⟨bs, p⟩ := "0b" ++ (bs.map (λ b : bool, if b then '1' else '0')).as_string instance (n : nat) : has_repr (bitvec n) := ⟨repr⟩ end bitvec instance {n} {x y : bitvec n} : decidable (bitvec.ult x y) := bool.decidable_eq _ _ instance {n} {x y : bitvec n} : decidable (bitvec.ugt x y) := bool.decidable_eq _ _
40ae72da6c29e8a8b60338196af1edb80fe2b45c
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/library/init/tactic.lean
1ac506c8d6d085cf29af68bd4e7eb807021d2096
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,136
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 This is just a trick to embed the 'tactic language' as a Lean expression. We should view 'tactic' as automation that when execute produces a term. tactic.builtin is just a "dummy" for creating the definitions that are actually implemented in C++ -/ prelude import init.datatypes init.reserved_notation init.num inductive tactic : Type := builtin : tactic namespace tactic -- Remark the following names are not arbitrary, the tactic module -- uses them when converting Lean expressions into actual tactic objects. -- The bultin 'by' construct triggers the process of converting a -- a term of type 'tactic' into a tactic that sythesizes a term definition and_then (t1 t2 : tactic) : tactic := builtin definition or_else (t1 t2 : tactic) : tactic := builtin definition append (t1 t2 : tactic) : tactic := builtin definition interleave (t1 t2 : tactic) : tactic := builtin definition par (t1 t2 : tactic) : tactic := builtin definition fixpoint (f : tactic → tactic) : tactic := builtin definition repeat (t : tactic) : tactic := builtin definition at_most (t : tactic) (k : num) : tactic := builtin definition discard (t : tactic) (k : num) : tactic := builtin definition focus_at (t : tactic) (i : num) : tactic := builtin definition try_for (t : tactic) (ms : num) : tactic := builtin definition all_goals (t : tactic) : tactic := builtin definition now : tactic := builtin definition assumption : tactic := builtin definition eassumption : tactic := builtin definition state : tactic := builtin definition fail : tactic := builtin definition id : tactic := builtin definition beta : tactic := builtin definition info : tactic := builtin definition whnf : tactic := builtin definition contradiction : tactic := builtin definition exfalso : tactic := builtin definition congruence : tactic := builtin definition rotate_left (k : num) := builtin definition rotate_right (k : num) := builtin definition rotate (k : num) := rotate_left k definition norm_num : tactic := builtin -- This is just a trick to embed expressions into tactics. -- The nested expressions are "raw". They tactic should -- elaborate them when it is executed. inductive expr : Type := builtin : expr inductive expr_list : Type := | nil : expr_list | cons : expr → expr_list → expr_list -- auxiliary type used to mark optional list of arguments definition opt_expr_list := expr_list -- auxiliary types used to mark that the expression is suppose to be an identifier, optional, or a list. definition identifier := expr definition identifier_list := expr_list definition opt_identifier_list := expr_list -- Marker for instructing the parser to parse it as '?(using <expr>)' definition using_expr := expr -- Constant used to denote the case were no expression was provided definition none_expr : expr := expr.builtin definition apply (e : expr) : tactic := builtin definition eapply (e : expr) : tactic := builtin definition fapply (e : expr) : tactic := builtin definition rename (a b : identifier) : tactic := builtin definition intro (e : identifier_list) : tactic := builtin definition generalize_tac (e : expr) (id : identifier) : tactic := builtin definition clear (e : identifier_list) : tactic := builtin definition revert (e : identifier_list) : tactic := builtin definition refine (e : expr) : tactic := builtin definition exact (e : expr) : tactic := builtin -- Relaxed version of exact that does not enforce goal type definition rexact (e : expr) : tactic := builtin definition check_expr (e : expr) : tactic := builtin definition trace (s : string) : tactic := builtin -- rewrite_tac is just a marker for the builtin 'rewrite' notation -- used to create instances of this tactic. definition rewrite_tac (e : expr_list) : tactic := builtin definition xrewrite_tac (e : expr_list) : tactic := builtin definition krewrite_tac (e : expr_list) : tactic := builtin -- simp_tac is just a marker for the builtin 'simp' notation -- used to create instances of this tactic. -- Arguments: -- - e : additional rewrites to be considered -- - n : add rewrites from the give namespaces -- - x : exclude the give global rewrites -- - t : tactic for discharging conditions -- - l : location definition simp_tac (e : expr_list) (n : identifier_list) (x : identifier_list) (t : option tactic) (l : expr) : tactic := builtin -- Arguments: -- - ls : lemmas to be used (if not provided, then blast will choose them) -- - ds : definitions that can be unfolded (if not provided, then blast will choose them) definition blast (ls : opt_identifier_list) (ds : opt_identifier_list) : tactic := builtin -- with_options_tac is just a marker for the builtin 'with_options' notation definition with_options_tac (o : expr) (t : tactic) : tactic := builtin definition cases (h : expr) (ids : opt_identifier_list) : tactic := builtin definition induction (h : expr) (rec : using_expr) (ids : opt_identifier_list) : tactic := builtin definition intros (ids : opt_identifier_list) : tactic := builtin definition generalizes (es : expr_list) : tactic := builtin definition clears (ids : identifier_list) : tactic := builtin definition reverts (ids : identifier_list) : tactic := builtin definition change (e : expr) : tactic := builtin definition assert_hypothesis (id : identifier) (e : expr) : tactic := builtin definition lettac (id : identifier) (e : expr) : tactic := builtin definition constructor (k : option num) : tactic := builtin definition fconstructor (k : option num) : tactic := builtin definition existsi (e : expr) : tactic := builtin definition split : tactic := builtin definition left : tactic := builtin definition right : tactic := builtin definition injection (e : expr) (ids : opt_identifier_list) : tactic := builtin definition subst (ids : identifier_list) : tactic := builtin definition substvars : tactic := builtin definition reflexivity : tactic := builtin definition symmetry : tactic := builtin definition transitivity (e : expr) : tactic := builtin definition try (t : tactic) : tactic := or_else t id definition repeat1 (t : tactic) : tactic := and_then t (repeat t) definition focus (t : tactic) : tactic := focus_at t 0 definition determ (t : tactic) : tactic := at_most t 1 definition trivial : tactic := or_else (or_else (apply eq.refl) (apply true.intro)) assumption definition do (n : num) (t : tactic) : tactic := nat.rec id (λn t', and_then t t') (nat.of_num n) end tactic tactic_infixl `;`:15 := tactic.and_then tactic_notation T1 `:`:15 T2 := tactic.focus (tactic.and_then T1 (tactic.all_goals T2)) tactic_notation `(` h `|` r:(foldl `|` (e r, tactic.or_else r e) h) `)` := r
7afed354d40b1c8654e09a5e041f6fa6c78236e3
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/calculus/deriv/inv.lean
5895b4209ab95664c9c7d08c17cd21d8d3a99a1e
[ "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,669
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, Yury Kudryashov -/ import analysis.calculus.deriv.mul import analysis.calculus.deriv.comp /-! # Derivatives of `x ↦ x⁻¹` and `f x / g x` > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. In this file we prove `(x⁻¹)' = -1 / x ^ 2`, `((f x)⁻¹)' = -f' x / (f x) ^ 2`, and `(f x / g x)' = (f' x * g x - f x * g' x) / (g x) ^ 2` for different notions of derivative. For a more detailed overview of one-dimensional derivatives in mathlib, see the module docstring of `analysis/calculus/deriv/basic`. ## Keywords derivative -/ universes u v w open_locale classical topology big_operators filter ennreal open filter asymptotics set open continuous_linear_map (smul_right smul_right_one_eq_iff) variables {𝕜 : Type u} [nontrivially_normed_field 𝕜] variables {F : Type v} [normed_add_comm_group F] [normed_space 𝕜 F] variables {E : Type w} [normed_add_comm_group E] [normed_space 𝕜 E] variables {f f₀ f₁ g : 𝕜 → F} variables {f' f₀' f₁' g' : F} variables {x : 𝕜} variables {s t : set 𝕜} variables {L : filter 𝕜} section inverse /-! ### Derivative of `x ↦ x⁻¹` -/ theorem has_strict_deriv_at_inv (hx : x ≠ 0) : has_strict_deriv_at has_inv.inv (-(x^2)⁻¹) x := begin suffices : (λ p : 𝕜 × 𝕜, (p.1 - p.2) * ((x * x)⁻¹ - (p.1 * p.2)⁻¹)) =o[𝓝 (x, x)] (λ p, (p.1 - p.2) * 1), { refine this.congr' _ (eventually_of_forall $ λ _, mul_one _), refine eventually.mono ((is_open_ne.prod is_open_ne).mem_nhds ⟨hx, hx⟩) _, rintro ⟨y, z⟩ ⟨hy, hz⟩, simp only [mem_set_of_eq] at hy hz, -- hy : y ≠ 0, hz : z ≠ 0 field_simp [hx, hy, hz], ring, }, refine (is_O_refl (λ p : 𝕜 × 𝕜, p.1 - p.2) _).mul_is_o ((is_o_one_iff _).2 _), rw [← sub_self (x * x)⁻¹], exact tendsto_const_nhds.sub ((continuous_mul.tendsto (x, x)).inv₀ $ mul_ne_zero hx hx) end theorem has_deriv_at_inv (x_ne_zero : x ≠ 0) : has_deriv_at (λy, y⁻¹) (-(x^2)⁻¹) x := (has_strict_deriv_at_inv x_ne_zero).has_deriv_at theorem has_deriv_within_at_inv (x_ne_zero : x ≠ 0) (s : set 𝕜) : has_deriv_within_at (λx, x⁻¹) (-(x^2)⁻¹) s x := (has_deriv_at_inv x_ne_zero).has_deriv_within_at lemma differentiable_at_inv : differentiable_at 𝕜 (λx, x⁻¹) x ↔ x ≠ 0:= ⟨λ H, normed_field.continuous_at_inv.1 H.continuous_at, λ H, (has_deriv_at_inv H).differentiable_at⟩ lemma differentiable_within_at_inv (x_ne_zero : x ≠ 0) : differentiable_within_at 𝕜 (λx, x⁻¹) s x := (differentiable_at_inv.2 x_ne_zero).differentiable_within_at lemma differentiable_on_inv : differentiable_on 𝕜 (λx:𝕜, x⁻¹) {x | x ≠ 0} := λx hx, differentiable_within_at_inv hx lemma deriv_inv : deriv (λx, x⁻¹) x = -(x^2)⁻¹ := begin rcases eq_or_ne x 0 with rfl|hne, { simp [deriv_zero_of_not_differentiable_at (mt differentiable_at_inv.1 (not_not.2 rfl))] }, { exact (has_deriv_at_inv hne).deriv } end @[simp] lemma deriv_inv' : deriv (λ x : 𝕜, x⁻¹) = λ x, -(x ^ 2)⁻¹ := funext (λ x, deriv_inv) lemma deriv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, x⁻¹) s x = -(x^2)⁻¹ := begin rw differentiable_at.deriv_within (differentiable_at_inv.2 x_ne_zero) hxs, exact deriv_inv end lemma has_fderiv_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_at (λx, x⁻¹) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) x := has_deriv_at_inv x_ne_zero lemma has_fderiv_within_at_inv (x_ne_zero : x ≠ 0) : has_fderiv_within_at (λx, x⁻¹) (smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) : 𝕜 →L[𝕜] 𝕜) s x := (has_fderiv_at_inv x_ne_zero).has_fderiv_within_at lemma fderiv_inv : fderiv 𝕜 (λx, x⁻¹) x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) := by rw [← deriv_fderiv, deriv_inv] lemma fderiv_within_inv (x_ne_zero : x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : fderiv_within 𝕜 (λx, x⁻¹) s x = smul_right (1 : 𝕜 →L[𝕜] 𝕜) (-(x^2)⁻¹) := begin rw differentiable_at.fderiv_within (differentiable_at_inv.2 x_ne_zero) hxs, exact fderiv_inv end variables {c : 𝕜 → 𝕜} {h : E → 𝕜} {c' : 𝕜} {z : E} {S : set E} lemma has_deriv_within_at.inv (hc : has_deriv_within_at c c' s x) (hx : c x ≠ 0) : has_deriv_within_at (λ y, (c y)⁻¹) (- c' / (c x)^2) s x := begin convert (has_deriv_at_inv hx).comp_has_deriv_within_at x hc, field_simp end lemma has_deriv_at.inv (hc : has_deriv_at c c' x) (hx : c x ≠ 0) : has_deriv_at (λ y, (c y)⁻¹) (- c' / (c x)^2) x := begin rw ← has_deriv_within_at_univ at *, exact hc.inv hx end lemma differentiable_within_at.inv (hf : differentiable_within_at 𝕜 h S z) (hz : h z ≠ 0) : differentiable_within_at 𝕜 (λx, (h x)⁻¹) S z := (differentiable_at_inv.mpr hz).comp_differentiable_within_at z hf @[simp] lemma differentiable_at.inv (hf : differentiable_at 𝕜 h z) (hz : h z ≠ 0) : differentiable_at 𝕜 (λx, (h x)⁻¹) z := (differentiable_at_inv.mpr hz).comp z hf lemma differentiable_on.inv (hf : differentiable_on 𝕜 h S) (hz : ∀ x ∈ S, h x ≠ 0) : differentiable_on 𝕜 (λx, (h x)⁻¹) S := λx h, (hf x h).inv (hz x h) @[simp] lemma differentiable.inv (hf : differentiable 𝕜 h) (hz : ∀ x, h x ≠ 0) : differentiable 𝕜 (λx, (h x)⁻¹) := λx, (hf x).inv (hz x) lemma deriv_within_inv' (hc : differentiable_within_at 𝕜 c s x) (hx : c x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, (c x)⁻¹) s x = - (deriv_within c s x) / (c x)^2 := (hc.has_deriv_within_at.inv hx).deriv_within hxs @[simp] lemma deriv_inv'' (hc : differentiable_at 𝕜 c x) (hx : c x ≠ 0) : deriv (λx, (c x)⁻¹) x = - (deriv c x) / (c x)^2 := (hc.has_deriv_at.inv hx).deriv end inverse section division /-! ### Derivative of `x ↦ c x / d x` -/ variables {𝕜' : Type*} [nontrivially_normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] {c d : 𝕜 → 𝕜'} {c' d' : 𝕜'} lemma has_deriv_within_at.div (hc : has_deriv_within_at c c' s x) (hd : has_deriv_within_at d d' s x) (hx : d x ≠ 0) : has_deriv_within_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) s x := begin convert hc.mul ((has_deriv_at_inv hx).comp_has_deriv_within_at x hd), { simp only [div_eq_mul_inv] }, { field_simp, ring } end lemma has_strict_deriv_at.div (hc : has_strict_deriv_at c c' x) (hd : has_strict_deriv_at d d' x) (hx : d x ≠ 0) : has_strict_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x := begin convert hc.mul ((has_strict_deriv_at_inv hx).comp x hd), { simp only [div_eq_mul_inv] }, { field_simp, ring } end lemma has_deriv_at.div (hc : has_deriv_at c c' x) (hd : has_deriv_at d d' x) (hx : d x ≠ 0) : has_deriv_at (λ y, c y / d y) ((c' * d x - c x * d') / (d x)^2) x := begin rw ← has_deriv_within_at_univ at *, exact hc.div hd hx end lemma differentiable_within_at.div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) : differentiable_within_at 𝕜 (λx, c x / d x) s x := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).differentiable_within_at @[simp] lemma differentiable_at.div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : differentiable_at 𝕜 (λx, c x / d x) x := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).differentiable_at lemma differentiable_on.div (hc : differentiable_on 𝕜 c s) (hd : differentiable_on 𝕜 d s) (hx : ∀ x ∈ s, d x ≠ 0) : differentiable_on 𝕜 (λx, c x / d x) s := λx h, (hc x h).div (hd x h) (hx x h) @[simp] lemma differentiable.div (hc : differentiable 𝕜 c) (hd : differentiable 𝕜 d) (hx : ∀ x, d x ≠ 0) : differentiable 𝕜 (λx, c x / d x) := λx, (hc x).div (hd x) (hx x) lemma deriv_within_div (hc : differentiable_within_at 𝕜 c s x) (hd : differentiable_within_at 𝕜 d s x) (hx : d x ≠ 0) (hxs : unique_diff_within_at 𝕜 s x) : deriv_within (λx, c x / d x) s x = ((deriv_within c s x) * d x - c x * (deriv_within d s x)) / (d x)^2 := ((hc.has_deriv_within_at).div (hd.has_deriv_within_at) hx).deriv_within hxs @[simp] lemma deriv_div (hc : differentiable_at 𝕜 c x) (hd : differentiable_at 𝕜 d x) (hx : d x ≠ 0) : deriv (λx, c x / d x) x = ((deriv c x) * d x - c x * (deriv d x)) / (d x)^2 := ((hc.has_deriv_at).div (hd.has_deriv_at) hx).deriv end division
c8e2ce1d54c8f78b3e1e7f80560e22d053e58d2c
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/topology/bases.lean
d1d7eff584a0b324f4be45c58baa20b894f00f2b
[ "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
31,294
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 topology.constructions import topology.continuous_on /-! # Bases of topologies. Countability axioms. A topological basis on a topological space `t` is a collection of sets, such that all open sets can be generated as unions of these sets, without the need to take finite intersections of them. This file introduces a framework for dealing with these collections, and also what more we can say under certain countability conditions on bases, which are referred to as first- and second-countable. We also briefly cover the theory of separable spaces, which are those with a countable, dense subset. If a space is second-countable, and also has a countably generated uniformity filter (for example, if `t` is a metric space), it will automatically be separable (and indeed, these conditions are equivalent in this case). ## Main definitions * `is_topological_basis s`: The topological space `t` has basis `s`. * `separable_space α`: The topological space `t` has a countable, dense subset. * `first_countable_topology α`: A topology in which `𝓝 x` is countably generated for every `x`. * `second_countable_topology α`: A topology which has a topological basis which is countable. ## Main results * `first_countable_topology.tendsto_subseq`: In a first-countable space, cluster points are limits of subsequences. * `second_countable_topology.is_open_Union_countable`: In a second-countable space, the union of arbitrarily-many open sets is equal to a sub-union of only countably many of these sets. * `second_countable_topology.countable_cover_nhds`: Consider `f : α → set α` with the property that `f x ∈ 𝓝 x` for all `x`. Then there is some countable set `s` whose image covers the space. ## Implementation Notes For our applications we are interested that there exists a countable basis, but we do not need the concrete basis itself. This allows us to declare these type classes as `Prop` to use them as mixins. ### TODO: More fine grained instances for `first_countable_topology`, `separable_space`, `t2_space`, and more (see the comment below `subtype.second_countable_topology`.) -/ open set filter classical open_locale topological_space filter noncomputable theory namespace topological_space universe u variables {α : Type u} [t : topological_space α] include t /-- A topological basis is one that satisfies the necessary conditions so that it suffices to take unions of the basis sets to get a topology (without taking finite intersections as well). -/ structure is_topological_basis (s : set (set α)) : Prop := (exists_subset_inter : ∀t₁∈s, ∀t₂∈s, ∀ x ∈ t₁ ∩ t₂, ∃ t₃∈s, x ∈ t₃ ∧ t₃ ⊆ t₁ ∩ t₂) (sUnion_eq : (⋃₀ s) = univ) (eq_generate_from : t = generate_from s) /-- If a family of sets `s` generates the topology, then nonempty intersections of finite subcollections of `s` form a topological basis. -/ lemma is_topological_basis_of_subbasis {s : set (set α)} (hs : t = generate_from s) : is_topological_basis ((λ f, ⋂₀ f) '' {f : set (set α) | finite f ∧ f ⊆ s ∧ (⋂₀ f).nonempty}) := begin refine ⟨_, _, _⟩, { rintro _ ⟨t₁, ⟨hft₁, ht₁b, ht₁⟩, rfl⟩ _ ⟨t₂, ⟨hft₂, ht₂b, ht₂⟩, rfl⟩ x h, have : ⋂₀ (t₁ ∪ t₂) = ⋂₀ t₁ ∩ ⋂₀ t₂ := sInter_union t₁ t₂, exact ⟨_, ⟨t₁ ∪ t₂, ⟨hft₁.union hft₂, union_subset ht₁b ht₂b, this.symm ▸ ⟨x, h⟩⟩, this⟩, h, subset.rfl⟩ }, { rw [sUnion_image, Union₂_eq_univ_iff], intro x, have : x ∈ ⋂₀ ∅, { rw sInter_empty, exact mem_univ x }, exact ⟨∅, ⟨finite_empty, empty_subset _, x, this⟩, this⟩ }, { rw hs, apply le_antisymm; apply le_generate_from, { rintro _ ⟨t, ⟨hft, htb, ht⟩, rfl⟩, exact @is_open_sInter _ (generate_from s) _ hft (λ s hs, generate_open.basic _ $ htb hs) }, { intros t ht, rcases t.eq_empty_or_nonempty with rfl|hne, { apply @is_open_empty _ _ }, rw ← sInter_singleton t at hne ⊢, exact generate_open.basic _ ⟨{t}, ⟨finite_singleton t, singleton_subset_iff.2 ht, hne⟩, rfl⟩ } } end /-- If a family of open sets `s` is such that every open neighbourhood contains some member of `s`, then `s` is a topological basis. -/ lemma is_topological_basis_of_open_of_nhds {s : set (set α)} (h_open : ∀ u ∈ s, is_open u) (h_nhds : ∀(a:α) (u : set α), a ∈ u → is_open u → ∃v ∈ s, a ∈ v ∧ v ⊆ u) : is_topological_basis s := begin refine ⟨λ t₁ ht₁ t₂ ht₂ x hx, h_nhds _ _ hx (is_open.inter (h_open _ ht₁) (h_open _ ht₂)), _, _⟩, { refine sUnion_eq_univ_iff.2 (λ a, _), rcases h_nhds a univ trivial is_open_univ with ⟨u, h₁, h₂, -⟩, exact ⟨u, h₁, h₂⟩ }, { refine (le_generate_from h_open).antisymm (λ u hu, _), refine (@is_open_iff_nhds α (generate_from s) u).mpr (λ a ha, _), rcases h_nhds a u ha hu with ⟨v, hvs, hav, hvu⟩, rw nhds_generate_from, exact binfi_le_of_le v ⟨hav, hvs⟩ (le_principal_iff.2 hvu) } end /-- A set `s` is in the neighbourhood of `a` iff there is some basis set `t`, which contains `a` and is itself contained in `s`. -/ lemma is_topological_basis.mem_nhds_iff {a : α} {s : set α} {b : set (set α)} (hb : is_topological_basis b) : s ∈ 𝓝 a ↔ ∃t∈b, a ∈ t ∧ t ⊆ s := begin change s ∈ (𝓝 a).sets ↔ ∃t∈b, a ∈ t ∧ t ⊆ s, rw [hb.eq_generate_from, nhds_generate_from, binfi_sets_eq], { simp [and_assoc, and.left_comm] }, { exact assume s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩, have a ∈ s ∩ t, from ⟨hs₁, ht₁⟩, let ⟨u, hu₁, hu₂, hu₃⟩ := hb.1 _ hs₂ _ ht₂ _ this in ⟨u, ⟨hu₂, hu₁⟩, le_principal_iff.2 (subset.trans hu₃ (inter_subset_left _ _)), le_principal_iff.2 (subset.trans hu₃ (inter_subset_right _ _))⟩ }, { rcases eq_univ_iff_forall.1 hb.sUnion_eq a with ⟨i, h1, h2⟩, exact ⟨i, h2, h1⟩ } end lemma is_topological_basis.nhds_has_basis {b : set (set α)} (hb : is_topological_basis b) {a : α} : (𝓝 a).has_basis (λ t : set α, t ∈ b ∧ a ∈ t) (λ t, t) := ⟨λ s, hb.mem_nhds_iff.trans $ by simp only [exists_prop, and_assoc]⟩ protected lemma is_topological_basis.is_open {s : set α} {b : set (set α)} (hb : is_topological_basis b) (hs : s ∈ b) : is_open s := by { rw hb.eq_generate_from, exact generate_open.basic s hs } protected lemma is_topological_basis.mem_nhds {a : α} {s : set α} {b : set (set α)} (hb : is_topological_basis b) (hs : s ∈ b) (ha : a ∈ s) : s ∈ 𝓝 a := (hb.is_open hs).mem_nhds ha lemma is_topological_basis.exists_subset_of_mem_open {b : set (set α)} (hb : is_topological_basis b) {a:α} {u : set α} (au : a ∈ u) (ou : is_open u) : ∃v ∈ b, a ∈ v ∧ v ⊆ u := hb.mem_nhds_iff.1 $ is_open.mem_nhds ou au /-- Any open set is the union of the basis sets contained in it. -/ lemma is_topological_basis.open_eq_sUnion' {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : is_open u) : u = ⋃₀ {s ∈ B | s ⊆ u} := ext $ λ a, ⟨λ ha, let ⟨b, hb, ab, bu⟩ := hB.exists_subset_of_mem_open ha ou in ⟨b, ⟨hb, bu⟩, ab⟩, λ ⟨b, ⟨hb, bu⟩, ab⟩, bu ab⟩ lemma is_topological_basis.open_eq_sUnion {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : is_open u) : ∃ S ⊆ B, u = ⋃₀ S := ⟨{s ∈ B | s ⊆ u}, λ s h, h.1, hB.open_eq_sUnion' ou⟩ lemma is_topological_basis.open_eq_Union {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : is_open u) : ∃ (β : Type u) (f : β → set α), u = (⋃ i, f i) ∧ ∀ i, f i ∈ B := ⟨↥{s ∈ B | s ⊆ u}, coe, by { rw ← sUnion_eq_Union, apply hB.open_eq_sUnion' ou }, λ s, and.left s.2⟩ /-- A point `a` is in the closure of `s` iff all basis sets containing `a` intersect `s`. -/ lemma is_topological_basis.mem_closure_iff {b : set (set α)} (hb : is_topological_basis b) {s : set α} {a : α} : a ∈ closure s ↔ ∀ o ∈ b, a ∈ o → (o ∩ s).nonempty := (mem_closure_iff_nhds_basis' hb.nhds_has_basis).trans $ by simp only [and_imp] /-- A set is dense iff it has non-trivial intersection with all basis sets. -/ lemma is_topological_basis.dense_iff {b : set (set α)} (hb : is_topological_basis b) {s : set α} : dense s ↔ ∀ o ∈ b, set.nonempty o → (o ∩ s).nonempty := begin simp only [dense, hb.mem_closure_iff], exact ⟨λ h o hb ⟨a, ha⟩, h a o hb ha, λ h a o hb ha, h o hb ⟨a, ha⟩⟩ end lemma is_topological_basis.is_open_map_iff {β} [topological_space β] {B : set (set α)} (hB : is_topological_basis B) {f : α → β} : is_open_map f ↔ ∀ s ∈ B, is_open (f '' s) := begin refine ⟨λ H o ho, H _ (hB.is_open ho), λ hf o ho, _⟩, rw [hB.open_eq_sUnion' ho, sUnion_eq_Union, image_Union], exact is_open_Union (λ s, hf s s.2.1) end lemma is_topological_basis.exists_nonempty_subset {B : set (set α)} (hb : is_topological_basis B) {u : set α} (hu : u.nonempty) (ou : is_open u) : ∃ v ∈ B, set.nonempty v ∧ v ⊆ u := begin cases hu with x hx, rw [hb.open_eq_sUnion' ou, mem_sUnion] at hx, rcases hx with ⟨v, hv, hxv⟩, exact ⟨v, hv.1, ⟨x, hxv⟩, hv.2⟩ end lemma is_topological_basis_opens : is_topological_basis { U : set α | is_open U } := is_topological_basis_of_open_of_nhds (by tauto) (by tauto) protected lemma is_topological_basis.prod {β} [topological_space β] {B₁ : set (set α)} {B₂ : set (set β)} (h₁ : is_topological_basis B₁) (h₂ : is_topological_basis B₂) : is_topological_basis (image2 (×ˢ) B₁ B₂) := begin refine is_topological_basis_of_open_of_nhds _ _, { rintro _ ⟨u₁, u₂, hu₁, hu₂, rfl⟩, exact (h₁.is_open hu₁).prod (h₂.is_open hu₂) }, { rintro ⟨a, b⟩ u hu uo, rcases (h₁.nhds_has_basis.prod_nhds h₂.nhds_has_basis).mem_iff.1 (is_open.mem_nhds uo hu) with ⟨⟨s, t⟩, ⟨⟨hs, ha⟩, ht, hb⟩, hu⟩, exact ⟨s ×ˢ t, mem_image2_of_mem hs ht, ⟨ha, hb⟩, hu⟩ } end protected lemma is_topological_basis.inducing {β} [topological_space β] {f : α → β} {T : set (set β)} (hf : inducing f) (h : is_topological_basis T) : is_topological_basis (image (preimage f) T) := begin refine is_topological_basis_of_open_of_nhds _ _, { rintros _ ⟨V, hV, rfl⟩, rwa hf.is_open_iff, refine ⟨V, h.is_open hV, rfl⟩ }, { intros a U ha hU, rw hf.is_open_iff at hU, obtain ⟨V, hV, rfl⟩ := hU, obtain ⟨S, hS, rfl⟩ := h.open_eq_sUnion hV, obtain ⟨W, hW, ha⟩ := ha, refine ⟨f ⁻¹' W, ⟨_, hS hW, rfl⟩, ha, set.preimage_mono $ set.subset_sUnion_of_mem hW⟩ } end lemma is_topological_basis_of_cover {ι} {U : ι → set α} (Uo : ∀ i, is_open (U i)) (Uc : (⋃ i, U i) = univ) {b : Π i, set (set (U i))} (hb : ∀ i, is_topological_basis (b i)) : is_topological_basis (⋃ i : ι, image (coe : U i → α) '' (b i)) := begin refine is_topological_basis_of_open_of_nhds (λ u hu, _) _, { simp only [mem_Union, mem_image] at hu, rcases hu with ⟨i, s, sb, rfl⟩, exact (Uo i).is_open_map_subtype_coe _ ((hb i).is_open sb) }, { intros a u ha uo, rcases Union_eq_univ_iff.1 Uc a with ⟨i, hi⟩, lift a to ↥(U i) using hi, rcases (hb i).exists_subset_of_mem_open (by exact ha) (uo.preimage continuous_subtype_coe) with ⟨v, hvb, hav, hvu⟩, exact ⟨coe '' v, mem_Union.2 ⟨i, mem_image_of_mem _ hvb⟩, mem_image_of_mem _ hav, image_subset_iff.2 hvu⟩ } end protected lemma is_topological_basis.continuous {β : Type*} [topological_space β] {B : set (set β)} (hB : is_topological_basis B) (f : α → β) (hf : ∀ s ∈ B, is_open (f ⁻¹' s)) : continuous f := begin rw hB.eq_generate_from, exact continuous_generated_from hf end variables (α) /-- A separable space is one with a countable dense subset, available through `topological_space.exists_countable_dense`. If `α` is also known to be nonempty, then `topological_space.dense_seq` provides a sequence `ℕ → α` with dense range, see `topological_space.dense_range_dense_seq`. If `α` is a uniform space with countably generated uniformity filter (e.g., an `emetric_space`), then this condition is equivalent to `topological_space.second_countable_topology α`. In this case the latter should be used as a typeclass argument in theorems because Lean can automatically deduce `separable_space` from `second_countable_topology` but it can't deduce `second_countable_topology` and `emetric_space`. -/ class separable_space : Prop := (exists_countable_dense : ∃s:set α, countable s ∧ dense s) lemma exists_countable_dense [separable_space α] : ∃ s : set α, countable s ∧ dense s := separable_space.exists_countable_dense /-- A nonempty separable space admits a sequence with dense range. Instead of running `cases` on the conclusion of this lemma, you might want to use `topological_space.dense_seq` and `topological_space.dense_range_dense_seq`. If `α` might be empty, then `exists_countable_dense` is the main way to use separability of `α`. -/ lemma exists_dense_seq [separable_space α] [nonempty α] : ∃ u : ℕ → α, dense_range u := begin obtain ⟨s : set α, hs, s_dense⟩ := exists_countable_dense α, cases countable_iff_exists_surjective.mp hs with u hu, exact ⟨u, s_dense.mono hu⟩, end /-- A dense sequence in a non-empty separable topological space. If `α` might be empty, then `exists_countable_dense` is the main way to use separability of `α`. -/ def dense_seq [separable_space α] [nonempty α] : ℕ → α := classical.some (exists_dense_seq α) /-- The sequence `dense_seq α` has dense range. -/ @[simp] lemma dense_range_dense_seq [separable_space α] [nonempty α] : dense_range (dense_seq α) := classical.some_spec (exists_dense_seq α) variable {α} /-- In a separable space, a family of nonempty disjoint open sets is countable. -/ lemma _root_.set.pairwise_disjoint.countable_of_is_open [separable_space α] {ι : Type*} {s : ι → set α} {a : set ι} (h : a.pairwise_disjoint s) (ha : ∀ i ∈ a, is_open (s i)) (h'a : ∀ i ∈ a, (s i).nonempty) : countable a := begin rcases eq_empty_or_nonempty a with rfl|H, { exact countable_empty }, haveI : inhabited α, { choose i ia using H, choose y hy using h'a i ia, exact ⟨y⟩ }, rcases exists_countable_dense α with ⟨u, u_count, u_dense⟩, have : ∀ i, i ∈ a → ∃ y, y ∈ s i ∩ u := λ i hi, dense_iff_inter_open.1 u_dense (s i) (ha i hi) (h'a i hi), choose! f hf using this, have f_inj : inj_on f a, { assume i hi j hj hij, have : ¬disjoint (s i) (s j), { rw not_disjoint_iff_nonempty_inter, refine ⟨f i, (hf i hi).1, _⟩, rw hij, exact (hf j hj).1 }, contrapose! this, exact h hi hj this }, apply countable_of_injective_of_countable_image f_inj, apply u_count.mono _, exact image_subset_iff.2 (λ i hi, (hf i hi).2) end /-- In a separable space, a family of disjoint sets with nonempty interiors is countable. -/ lemma _root_.set.pairwise_disjoint.countable_of_nonempty_interior [separable_space α] {ι : Type*} {s : ι → set α} {a : set ι} (h : a.pairwise_disjoint s) (ha : ∀ i ∈ a, (interior (s i)).nonempty) : countable a := (h.mono $ λ i, interior_subset).countable_of_is_open (λ i hi, is_open_interior) ha end topological_space open topological_space lemma is_topological_basis_pi {ι : Type*} {X : ι → Type*} [∀ i, topological_space (X i)] {T : Π i, set (set (X i))} (cond : ∀ i, is_topological_basis (T i)) : is_topological_basis {S : set (Π i, X i) | ∃ (U : Π i, set (X i)) (F : finset ι), (∀ i, i ∈ F → (U i) ∈ T i) ∧ S = (F : set ι).pi U } := begin refine is_topological_basis_of_open_of_nhds _ _, { rintro _ ⟨U, F, h1, rfl⟩, apply is_open_set_pi F.finite_to_set, intros i hi, exact (cond i).is_open (h1 i hi) }, { intros a U ha hU, obtain ⟨I, t, hta, htU⟩ : ∃ (I : finset ι) (t : Π (i : ι), set (X i)), (∀ i, t i ∈ 𝓝 (a i)) ∧ set.pi ↑I t ⊆ U, { rw [← filter.mem_pi', ← nhds_pi], exact hU.mem_nhds ha }, have : ∀ i, ∃ V ∈ T i, a i ∈ V ∧ V ⊆ t i := λ i, (cond i).mem_nhds_iff.1 (hta i), choose V hVT haV hVt, exact ⟨_, ⟨V, I, λ i hi, hVT i, rfl⟩, λ i hi, haV i, (pi_mono $ λ i hi, hVt i).trans htU⟩ }, end lemma is_topological_basis_infi {β : Type*} {ι : Type*} {X : ι → Type*} [t : ∀ i, topological_space (X i)] {T : Π i, set (set (X i))} (cond : ∀ i, is_topological_basis (T i)) (f : Π i, β → X i) : @is_topological_basis β (⨅ i, induced (f i) (t i)) { S | ∃ (U : Π i, set (X i)) (F : finset ι), (∀ i, i ∈ F → U i ∈ T i) ∧ S = ⋂ i (hi : i ∈ F), (f i) ⁻¹' (U i) } := begin convert (is_topological_basis_pi cond).inducing (inducing_infi_to_pi _), ext V, split, { rintros ⟨U, F, h1, h2⟩, have : (F : set ι).pi U = (⋂ (i : ι) (hi : i ∈ F), (λ (z : Π j, X j), z i) ⁻¹' (U i)), by { ext, simp }, refine ⟨(F : set ι).pi U, ⟨U, F, h1, rfl⟩, _⟩, rw [this, h2, set.preimage_Inter], congr' 1, ext1, rw set.preimage_Inter, refl }, { rintros ⟨U, ⟨U, F, h1, rfl⟩, h⟩, refine ⟨U, F, h1, _⟩, have : (F : set ι).pi U = (⋂ (i : ι) (hi : i ∈ F), (λ (z : Π j, X j), z i) ⁻¹' (U i)), by { ext, simp }, rw [← h, this, set.preimage_Inter], congr' 1, ext1, rw set.preimage_Inter, refl } end /-- If `α` is a separable space and `f : α → β` is a continuous map with dense range, then `β` is a separable space as well. E.g., the completion of a separable uniform space is separable. -/ protected lemma dense_range.separable_space {α β : Type*} [topological_space α] [separable_space α] [topological_space β] {f : α → β} (h : dense_range f) (h' : continuous f) : separable_space β := let ⟨s, s_cnt, s_dense⟩ := exists_countable_dense α in ⟨⟨f '' s, countable.image s_cnt f, h.dense_image h' s_dense⟩⟩ lemma dense.exists_countable_dense_subset {α : Type*} [topological_space α] {s : set α} [separable_space s] (hs : dense s) : ∃ t ⊆ s, countable t ∧ dense t := let ⟨t, htc, htd⟩ := exists_countable_dense s in ⟨coe '' t, image_subset_iff.2 $ λ x _, mem_preimage.2 $ subtype.coe_prop _, htc.image coe, hs.dense_range_coe.dense_image continuous_subtype_val htd⟩ /-- Let `s` be a dense set in a topological space `α` with partial order structure. If `s` is a separable space (e.g., if `α` has a second countable topology), then there exists a countable dense subset `t ⊆ s` such that `t` contains bottom/top element of `α` when they exist and belong to `s`. For a dense subset containing neither bot nor top elements, see `dense.exists_countable_dense_subset_no_bot_top`. -/ lemma dense.exists_countable_dense_subset_bot_top {α : Type*} [topological_space α] [partial_order α] {s : set α} [separable_space s] (hs : dense s) : ∃ t ⊆ s, countable t ∧ dense t ∧ (∀ x, is_bot x → x ∈ s → x ∈ t) ∧ (∀ x, is_top x → x ∈ s → x ∈ t) := begin rcases hs.exists_countable_dense_subset with ⟨t, hts, htc, htd⟩, refine ⟨(t ∪ ({x | is_bot x} ∪ {x | is_top x})) ∩ s, _, _, _, _, _⟩, exacts [inter_subset_right _ _, (htc.union ((countable_is_bot α).union (countable_is_top α))).mono (inter_subset_left _ _), htd.mono (subset_inter (subset_union_left _ _) hts), λ x hx hxs, ⟨or.inr $ or.inl hx, hxs⟩, λ x hx hxs, ⟨or.inr $ or.inr hx, hxs⟩] end instance separable_space_univ {α : Type*} [topological_space α] [separable_space α] : separable_space (univ : set α) := (equiv.set.univ α).symm.surjective.dense_range.separable_space (continuous_subtype_mk _ continuous_id) /-- If `α` is a separable topological space with a partial order, then there exists a countable dense set `s : set α` that contains those of both bottom and top elements of `α` that actually exist. For a dense set containing neither bot nor top elements, see `exists_countable_dense_no_bot_top`. -/ lemma exists_countable_dense_bot_top (α : Type*) [topological_space α] [separable_space α] [partial_order α] : ∃ s : set α, countable s ∧ dense s ∧ (∀ x, is_bot x → x ∈ s) ∧ (∀ x, is_top x → x ∈ s) := by simpa using dense_univ.exists_countable_dense_subset_bot_top namespace topological_space universe u variables (α : Type u) [t : topological_space α] include t /-- A first-countable space is one in which every point has a countable neighborhood basis. -/ class first_countable_topology : Prop := (nhds_generated_countable : ∀a:α, (𝓝 a).is_countably_generated) attribute [instance] first_countable_topology.nhds_generated_countable namespace first_countable_topology variable {α} /-- In a first-countable space, a cluster point `x` of a sequence is the limit of some subsequence. -/ lemma tendsto_subseq [first_countable_topology α] {u : ℕ → α} {x : α} (hx : map_cluster_pt x at_top u) : ∃ (ψ : ℕ → ℕ), (strict_mono ψ) ∧ (tendsto (u ∘ ψ) at_top (𝓝 x)) := subseq_tendsto_of_ne_bot hx end first_countable_topology variables {α} instance is_countably_generated_nhds_within (x : α) [is_countably_generated (𝓝 x)] (s : set α) : is_countably_generated (𝓝[s] x) := inf.is_countably_generated _ _ variable (α) /-- A second-countable space is one with a countable basis. -/ class second_countable_topology : Prop := (is_open_generated_countable [] : ∃ b : set (set α), countable b ∧ t = topological_space.generate_from b) variable {α} protected lemma is_topological_basis.second_countable_topology {b : set (set α)} (hb : is_topological_basis b) (hc : countable b) : second_countable_topology α := ⟨⟨b, hc, hb.eq_generate_from⟩⟩ variable (α) lemma exists_countable_basis [second_countable_topology α] : ∃b:set (set α), countable b ∧ ∅ ∉ b ∧ is_topological_basis b := let ⟨b, hb₁, hb₂⟩ := second_countable_topology.is_open_generated_countable α in let b' := (λs, ⋂₀ s) '' {s:set (set α) | finite s ∧ s ⊆ b ∧ (⋂₀ s).nonempty} in ⟨b', ((countable_set_of_finite_subset hb₁).mono (by { simp only [← and_assoc], apply inter_subset_left })).image _, assume ⟨s, ⟨_, _, hn⟩, hp⟩, absurd hn (not_nonempty_iff_eq_empty.2 hp), is_topological_basis_of_subbasis hb₂⟩ /-- A countable topological basis of `α`. -/ def countable_basis [second_countable_topology α] : set (set α) := (exists_countable_basis α).some lemma countable_countable_basis [second_countable_topology α] : countable (countable_basis α) := (exists_countable_basis α).some_spec.1 instance encodable_countable_basis [second_countable_topology α] : encodable (countable_basis α) := (countable_countable_basis α).to_encodable lemma empty_nmem_countable_basis [second_countable_topology α] : ∅ ∉ countable_basis α := (exists_countable_basis α).some_spec.2.1 lemma is_basis_countable_basis [second_countable_topology α] : is_topological_basis (countable_basis α) := (exists_countable_basis α).some_spec.2.2 lemma eq_generate_from_countable_basis [second_countable_topology α] : ‹topological_space α› = generate_from (countable_basis α) := (is_basis_countable_basis α).eq_generate_from variable {α} lemma is_open_of_mem_countable_basis [second_countable_topology α] {s : set α} (hs : s ∈ countable_basis α) : is_open s := (is_basis_countable_basis α).is_open hs lemma nonempty_of_mem_countable_basis [second_countable_topology α] {s : set α} (hs : s ∈ countable_basis α) : s.nonempty := ne_empty_iff_nonempty.1 $ ne_of_mem_of_not_mem hs $ empty_nmem_countable_basis α variable (α) @[priority 100] -- see Note [lower instance priority] instance second_countable_topology.to_first_countable_topology [second_countable_topology α] : first_countable_topology α := ⟨λ x, has_countable_basis.is_countably_generated $ ⟨(is_basis_countable_basis α).nhds_has_basis, (countable_countable_basis α).mono $ inter_subset_left _ _⟩⟩ /-- If `β` is a second-countable space, then its induced topology via `f` on `α` is also second-countable. -/ lemma second_countable_topology_induced (β) [t : topological_space β] [second_countable_topology β] (f : α → β) : @second_countable_topology α (t.induced f) := begin rcases second_countable_topology.is_open_generated_countable β with ⟨b, hb, eq⟩, refine { is_open_generated_countable := ⟨preimage f '' b, hb.image _, _⟩ }, rw [eq, induced_generate_from_eq] end instance subtype.second_countable_topology (s : set α) [second_countable_topology α] : second_countable_topology s := second_countable_topology_induced s α coe /- TODO: more fine grained instances for first_countable_topology, separable_space, t2_space, ... -/ instance {β : Type*} [topological_space β] [second_countable_topology α] [second_countable_topology β] : second_countable_topology (α × β) := ((is_basis_countable_basis α).prod (is_basis_countable_basis β)).second_countable_topology $ (countable_countable_basis α).image2 (countable_countable_basis β) _ instance second_countable_topology_encodable {ι : Type*} {π : ι → Type*} [encodable ι] [t : ∀a, topological_space (π a)] [∀a, second_countable_topology (π a)] : second_countable_topology (∀a, π a) := begin have : t = (λa, generate_from (countable_basis (π a))), from funext (assume a, (is_basis_countable_basis (π a)).eq_generate_from), rw [this, pi_generate_from_eq], constructor, refine ⟨_, _, rfl⟩, have : countable {T : set (Π i, π i) | ∃ (I : finset ι) (s : Π i : I, set (π i)), (∀ i, s i ∈ countable_basis (π i)) ∧ T = {f | ∀ i : I, f i ∈ s i}}, { simp only [set_of_exists, ← exists_prop], refine countable_Union (λ I, countable.bUnion _ (λ _ _, countable_singleton _)), change countable {s : Π i : I, set (π i) | ∀ i, s i ∈ countable_basis (π i)}, exact countable_pi (λ i, countable_countable_basis _) }, convert this using 1, ext1 T, split, { rintro ⟨s, I, hs, rfl⟩, refine ⟨I, λ i, s i, λ i, hs i i.2, _⟩, simp only [set.pi, set_coe.forall'], refl }, { rintro ⟨I, s, hs, rfl⟩, rcases @subtype.surjective_restrict ι (λ i, set (π i)) _ (λ i, i ∈ I) s with ⟨s, rfl⟩, exact ⟨s, I, λ i hi, hs ⟨i, hi⟩, set.ext $ λ f, subtype.forall⟩ } end instance second_countable_topology_fintype {ι : Type*} {π : ι → Type*} [fintype ι] [t : ∀a, topological_space (π a)] [∀a, second_countable_topology (π a)] : second_countable_topology (∀a, π a) := by { letI := fintype.encodable ι, exact topological_space.second_countable_topology_encodable } @[priority 100] -- see Note [lower instance priority] instance second_countable_topology.to_separable_space [second_countable_topology α] : separable_space α := begin choose p hp using λ s : countable_basis α, nonempty_of_mem_countable_basis s.2, exact ⟨⟨range p, countable_range _, (is_basis_countable_basis α).dense_iff.2 $ λ o ho _, ⟨p ⟨o, ho⟩, hp _, mem_range_self _⟩⟩⟩ end variables {α} /-- A countable open cover induces a second-countable topology if all open covers are themselves second countable. -/ lemma second_countable_topology_of_countable_cover {ι} [encodable ι] {U : ι → set α} [∀ i, second_countable_topology (U i)] (Uo : ∀ i, is_open (U i)) (hc : (⋃ i, U i) = univ) : second_countable_topology α := begin have : is_topological_basis (⋃ i, image (coe : U i → α) '' (countable_basis (U i))), from is_topological_basis_of_cover Uo hc (λ i, is_basis_countable_basis (U i)), exact this.second_countable_topology (countable_Union $ λ i, (countable_countable_basis _).image _) end /-- In a second-countable space, an open set, given as a union of open sets, is equal to the union of countably many of those sets. -/ lemma is_open_Union_countable [second_countable_topology α] {ι} (s : ι → set α) (H : ∀ i, is_open (s i)) : ∃ T : set ι, countable T ∧ (⋃ i ∈ T, s i) = ⋃ i, s i := begin let B := {b ∈ countable_basis α | ∃ i, b ⊆ s i}, choose f hf using λ b : B, b.2.2, haveI : encodable B := ((countable_countable_basis α).mono (sep_subset _ _)).to_encodable, refine ⟨_, countable_range f, (Union₂_subset_Union _ _).antisymm (sUnion_subset _)⟩, rintro _ ⟨i, rfl⟩ x xs, rcases (is_basis_countable_basis α).exists_subset_of_mem_open xs (H _) with ⟨b, hb, xb, bs⟩, exact ⟨_, ⟨_, rfl⟩, _, ⟨⟨⟨_, hb, _, bs⟩, rfl⟩, rfl⟩, hf _ (by exact xb)⟩ end lemma is_open_sUnion_countable [second_countable_topology α] (S : set (set α)) (H : ∀ s ∈ S, is_open s) : ∃ T : set (set α), countable T ∧ T ⊆ S ∧ ⋃₀ T = ⋃₀ S := let ⟨T, cT, hT⟩ := is_open_Union_countable (λ s:S, s.1) (λ s, H s.1 s.2) in ⟨subtype.val '' T, cT.image _, image_subset_iff.2 $ λ ⟨x, xs⟩ xt, xs, by rwa [sUnion_image, sUnion_eq_Union]⟩ /-- In a topological space with second countable topology, if `f` is a function that sends each point `x` to a neighborhood of `x`, then for some countable set `s`, the neighborhoods `f x`, `x ∈ s`, cover the whole space. -/ lemma countable_cover_nhds [second_countable_topology α] {f : α → set α} (hf : ∀ x, f x ∈ 𝓝 x) : ∃ s : set α, countable s ∧ (⋃ x ∈ s, f x) = univ := begin rcases is_open_Union_countable (λ x, interior (f x)) (λ x, is_open_interior) with ⟨s, hsc, hsU⟩, suffices : (⋃ x ∈ s, interior (f x)) = univ, from ⟨s, hsc, flip eq_univ_of_subset this $ Union₂_mono $ λ _ _, interior_subset⟩, simp only [hsU, eq_univ_iff_forall, mem_Union], exact λ x, ⟨x, mem_interior_iff_mem_nhds.2 (hf x)⟩ end lemma countable_cover_nhds_within [second_countable_topology α] {f : α → set α} {s : set α} (hf : ∀ x ∈ s, f x ∈ 𝓝[s] x) : ∃ t ⊆ s, countable t ∧ s ⊆ (⋃ x ∈ t, f x) := begin have : ∀ x : s, coe ⁻¹' (f x) ∈ 𝓝 x, from λ x, preimage_coe_mem_nhds_subtype.2 (hf x x.2), rcases countable_cover_nhds this with ⟨t, htc, htU⟩, refine ⟨coe '' t, subtype.coe_image_subset _ _, htc.image _, λ x hx, _⟩, simp only [bUnion_image, eq_univ_iff_forall, ← preimage_Union, mem_preimage] at htU ⊢, exact htU ⟨x, hx⟩ end end topological_space open topological_space variables {α β : Type*} [topological_space α] [topological_space β] {f : α → β} protected lemma inducing.second_countable_topology [second_countable_topology β] (hf : inducing f) : second_countable_topology α := by { rw hf.1, exact second_countable_topology_induced α β f } protected lemma embedding.second_countable_topology [second_countable_topology β] (hf : embedding f) : second_countable_topology α := hf.1.second_countable_topology
8faa2cf7025578ac910597fa4eeec2d8ad0fc532
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/matrix/notation.lean
519325f7169c7e19e20c917c2615d9d768eb5725
[ "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
18,497
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen Notation for vectors and matrices -/ import data.fintype.card import data.matrix.basic import tactic.fin_cases /-! # Matrix and vector notation This file defines notation for vectors and matrices. Given `a b c d : α`, the notation allows us to write `![a, b, c, d] : fin 4 → α`. Nesting vectors gives a matrix, so `![![a, b], ![c, d]] : matrix (fin 2) (fin 2) α`. This file includes `simp` lemmas for applying operations in `data.matrix.basic` to values built out of this notation. ## Main definitions * `vec_empty` is the empty vector (or `0` by `n` matrix) `![]` * `vec_cons` prepends an entry to a vector, so `![a, b]` is `vec_cons a (vec_cons b vec_empty)` ## Implementation notes The `simp` lemmas require that one of the arguments is of the form `vec_cons _ _`. This ensures `simp` works with entries only when (some) entries are already given. In other words, this notation will only appear in the output of `simp` if it already appears in the input. ## Notations The main new notation is `![a, b]`, which gets expanded to `vec_cons a (vec_cons b vec_empty)`. ## Examples Examples of usage can be found in the `test/matrix.lean` file. -/ namespace matrix universe u variables {α : Type u} open_locale matrix section matrix_notation /-- `![]` is the vector with no entries. -/ def vec_empty : fin 0 → α := fin_zero_elim /-- `vec_cons h t` prepends an entry `h` to a vector `t`. The inverse functions are `vec_head` and `vec_tail`. The notation `![a, b, ...]` expands to `vec_cons a (vec_cons b ...)`. -/ def vec_cons {n : ℕ} (h : α) (t : fin n → α) : fin n.succ → α := fin.cons h t notation `![` l:(foldr `, ` (h t, vec_cons h t) vec_empty `]`) := l /-- `vec_head v` gives the first entry of the vector `v` -/ def vec_head {n : ℕ} (v : fin n.succ → α) : α := v 0 /-- `vec_tail v` gives a vector consisting of all entries of `v` except the first -/ def vec_tail {n : ℕ} (v : fin n.succ → α) : fin n → α := v ∘ fin.succ variables {m n : ℕ} /-- Use `![...]` notation for displaying a vector `fin n → α`, for example: ``` #eval ![1, 2] + ![3, 4] -- ![4, 6] ``` -/ instance [has_repr α] : has_repr (fin n → α) := { repr := λ f, "![" ++ (string.intercalate ", " ((list.fin_range n).map (λ n, repr (f n)))) ++ "]" } /-- Use `![...]` notation for displaying a `fin`-indexed matrix, for example: ``` #eval ![![1, 2], ![3, 4]] + ![![3, 4], ![5, 6]] -- ![![4, 6], ![8, 10]] ``` -/ instance [has_repr α] : has_repr (matrix (fin m) (fin n) α) := (by apply_instance : has_repr (fin m → fin n → α)) end matrix_notation variables {m n o : ℕ} {m' n' o' : Type*} [fintype m'] [fintype n'] [fintype o'] lemma empty_eq (v : fin 0 → α) : v = ![] := by { ext i, fin_cases i } section val @[simp] lemma head_fin_const (a : α) : vec_head (λ (i : fin (n + 1)), a) = a := rfl @[simp] lemma cons_val_zero (x : α) (u : fin m → α) : vec_cons x u 0 = x := rfl lemma cons_val_zero' (h : 0 < m.succ) (x : α) (u : fin m → α) : vec_cons x u ⟨0, h⟩ = x := rfl @[simp] lemma cons_val_succ (x : α) (u : fin m → α) (i : fin m) : vec_cons x u i.succ = u i := by simp [vec_cons] @[simp] lemma cons_val_succ' {i : ℕ} (h : i.succ < m.succ) (x : α) (u : fin m → α) : vec_cons x u ⟨i.succ, h⟩ = u ⟨i, nat.lt_of_succ_lt_succ h⟩ := by simp only [vec_cons, fin.cons, fin.cases_succ'] @[simp] lemma head_cons (x : α) (u : fin m → α) : vec_head (vec_cons x u) = x := rfl @[simp] lemma tail_cons (x : α) (u : fin m → α) : vec_tail (vec_cons x u) = u := by { ext, simp [vec_tail] } @[simp] lemma empty_val' {n' : Type*} (j : n') : (λ i, (![] : fin 0 → n' → α) i j) = ![] := empty_eq _ @[simp] lemma cons_val' (v : n' → α) (B : matrix (fin m) n' α) (i j) : vec_cons v B i j = vec_cons (v j) (λ i, B i j) i := by { refine fin.cases _ _ i; simp } @[simp] lemma head_val' (B : matrix (fin m.succ) n' α) (j : n') : vec_head (λ i, B i j) = vec_head B j := rfl @[simp] lemma tail_val' (B : matrix (fin m.succ) n' α) (j : n') : vec_tail (λ i, B i j) = λ i, vec_tail B i j := by { ext, simp [vec_tail] } @[simp] lemma cons_head_tail (u : fin m.succ → α) : vec_cons (vec_head u) (vec_tail u) = u := fin.cons_self_tail _ @[simp] lemma range_cons (x : α) (u : fin n → α) : set.range (vec_cons x u) = {x} ∪ set.range u := set.ext $ λ y, by simp [fin.exists_fin_succ, eq_comm] @[simp] lemma range_empty (u : fin 0 → α) : set.range u = ∅ := set.range_eq_empty.2 $ λ ⟨k⟩, k.elim0 /-- `![a, b, ...] 1` is equal to `b`. The simplifier needs a special lemma for length `≥ 2`, in addition to `cons_val_succ`, because `1 : fin 1 = 0 : fin 1`. -/ @[simp] lemma cons_val_one (x : α) (u : fin m.succ → α) : vec_cons x u 1 = vec_head u := by { rw [← fin.succ_zero_eq_one, cons_val_succ], refl } @[simp] lemma cons_val_fin_one (x : α) (u : fin 0 → α) (i : fin 1) : vec_cons x u i = x := by { fin_cases i, refl } lemma cons_fin_one (x : α) (u : fin 0 → α) : vec_cons x u = (λ _, x) := funext (cons_val_fin_one x u) /-! ### Numeral (`bit0` and `bit1`) indices The following definitions and `simp` lemmas are to allow any numeral-indexed element of a vector given with matrix notation to be extracted by `simp` (even when the numeral is larger than the number of elements in the vector, which is taken modulo that number of elements by virtue of the semantics of `bit0` and `bit1` and of addition on `fin n`). -/ @[simp] lemma empty_append (v : fin n → α) : fin.append (zero_add _).symm ![] v = v := by { ext, simp [fin.append] } @[simp] lemma cons_append (ho : o + 1 = m + 1 + n) (x : α) (u : fin m → α) (v : fin n → α) : fin.append ho (vec_cons x u) v = vec_cons x (fin.append (by rwa [add_assoc, add_comm 1, ←add_assoc, add_right_cancel_iff] at ho) u v) := begin ext i, simp_rw [fin.append], split_ifs with h, { rcases i with ⟨⟨⟩ | i, hi⟩, { simp }, { simp only [nat.succ_eq_add_one, add_lt_add_iff_right, fin.coe_mk] at h, simp [h] } }, { rcases i with ⟨⟨⟩ | i, hi⟩, { simpa using h }, { rw [not_lt, fin.coe_mk, nat.succ_eq_add_one, add_le_add_iff_right] at h, simp [h] } } end /-- `vec_alt0 v` gives a vector with half the length of `v`, with only alternate elements (even-numbered). -/ def vec_alt0 (hm : m = n + n) (v : fin m → α) (k : fin n) : α := v ⟨(k : ℕ) + k, hm.symm ▸ add_lt_add k.property k.property⟩ /-- `vec_alt1 v` gives a vector with half the length of `v`, with only alternate elements (odd-numbered). -/ def vec_alt1 (hm : m = n + n) (v : fin m → α) (k : fin n) : α := v ⟨(k : ℕ) + k + 1, hm.symm ▸ nat.add_succ_lt_add k.property k.property⟩ lemma vec_alt0_append (v : fin n → α) : vec_alt0 rfl (fin.append rfl v v) = v ∘ bit0 := begin ext i, simp_rw [function.comp, bit0, vec_alt0, fin.append], split_ifs with h; congr, { rw fin.coe_mk at h, simp only [fin.ext_iff, fin.coe_add, fin.coe_mk], exact (nat.mod_eq_of_lt h).symm }, { rw [fin.coe_mk, not_lt] at h, simp only [fin.ext_iff, fin.coe_add, fin.coe_mk, nat.mod_eq_sub_mod h], refine (nat.mod_eq_of_lt _).symm, rw nat.sub_lt_left_iff_lt_add h, exact add_lt_add i.property i.property } end lemma vec_alt1_append (v : fin (n + 1) → α) : vec_alt1 rfl (fin.append rfl v v) = v ∘ bit1 := begin ext i, simp_rw [function.comp, vec_alt1, fin.append], cases n, { simp, congr }, { split_ifs with h; simp_rw [bit1, bit0]; congr, { simp only [fin.ext_iff, fin.coe_add, fin.coe_mk], rw fin.coe_mk at h, rw fin.coe_one, rw nat.mod_eq_of_lt (nat.lt_of_succ_lt h), rw nat.mod_eq_of_lt h }, { rw [fin.coe_mk, not_lt] at h, simp only [fin.ext_iff, fin.coe_add, fin.coe_mk, nat.mod_add_mod, fin.coe_one, nat.mod_eq_sub_mod h], refine (nat.mod_eq_of_lt _).symm, rw nat.sub_lt_left_iff_lt_add h, exact nat.add_succ_lt_add i.property i.property } } end @[simp] lemma vec_head_vec_alt0 (hm : (m + 2) = (n + 1) + (n + 1)) (v : fin (m + 2) → α) : vec_head (vec_alt0 hm v) = v 0 := rfl @[simp] lemma vec_head_vec_alt1 (hm : (m + 2) = (n + 1) + (n + 1)) (v : fin (m + 2) → α) : vec_head (vec_alt1 hm v) = v 1 := by simp [vec_head, vec_alt1] @[simp] lemma cons_vec_bit0_eq_alt0 (x : α) (u : fin n → α) (i : fin (n + 1)) : vec_cons x u (bit0 i) = vec_alt0 rfl (fin.append rfl (vec_cons x u) (vec_cons x u)) i := by rw vec_alt0_append @[simp] lemma cons_vec_bit1_eq_alt1 (x : α) (u : fin n → α) (i : fin (n + 1)) : vec_cons x u (bit1 i) = vec_alt1 rfl (fin.append rfl (vec_cons x u) (vec_cons x u)) i := by rw vec_alt1_append @[simp] lemma cons_vec_alt0 (h : m + 1 + 1 = (n + 1) + (n + 1)) (x y : α) (u : fin m → α) : vec_alt0 h (vec_cons x (vec_cons y u)) = vec_cons x (vec_alt0 (by rwa [add_assoc n, add_comm 1, ←add_assoc, ←add_assoc, add_right_cancel_iff, add_right_cancel_iff] at h) u) := begin ext i, simp_rw [vec_alt0], rcases i with ⟨⟨⟩ | i, hi⟩, { refl }, { simp [vec_alt0, nat.succ_add] } end -- Although proved by simp, extracting element 8 of a five-element -- vector does not work by simp unless this lemma is present. @[simp] lemma empty_vec_alt0 (α) {h} : vec_alt0 h (![] : fin 0 → α) = ![] := by simp @[simp] lemma cons_vec_alt1 (h : m + 1 + 1 = (n + 1) + (n + 1)) (x y : α) (u : fin m → α) : vec_alt1 h (vec_cons x (vec_cons y u)) = vec_cons y (vec_alt1 (by rwa [add_assoc n, add_comm 1, ←add_assoc, ←add_assoc, add_right_cancel_iff, add_right_cancel_iff] at h) u) := begin ext i, simp_rw [vec_alt1], rcases i with ⟨⟨⟩ | i, hi⟩, { refl }, { simp [vec_alt1, nat.succ_add] } end -- Although proved by simp, extracting element 9 of a five-element -- vector does not work by simp unless this lemma is present. @[simp] lemma empty_vec_alt1 (α) {h} : vec_alt1 h (![] : fin 0 → α) = ![] := by simp end val section dot_product variables [add_comm_monoid α] [has_mul α] @[simp] lemma dot_product_empty (v w : fin 0 → α) : dot_product v w = 0 := finset.sum_empty @[simp] lemma cons_dot_product (x : α) (v : fin n → α) (w : fin n.succ → α) : dot_product (vec_cons x v) w = x * vec_head w + dot_product v (vec_tail w) := by simp [dot_product, fin.sum_univ_succ, vec_head, vec_tail] @[simp] lemma dot_product_cons (v : fin n.succ → α) (x : α) (w : fin n → α) : dot_product v (vec_cons x w) = vec_head v * x + dot_product (vec_tail v) w := by simp [dot_product, fin.sum_univ_succ, vec_head, vec_tail] end dot_product section col_row @[simp] lemma col_empty (v : fin 0 → α) : col v = vec_empty := empty_eq _ @[simp] lemma col_cons (x : α) (u : fin m → α) : col (vec_cons x u) = vec_cons (λ _, x) (col u) := by { ext i j, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma row_empty : row (vec_empty : fin 0 → α) = λ _, vec_empty := by { ext, refl } @[simp] lemma row_cons (x : α) (u : fin m → α) : row (vec_cons x u) = λ _, vec_cons x u := by { ext, refl } end col_row section transpose @[simp] lemma transpose_empty_rows (A : matrix m' (fin 0) α) : Aᵀ = ![] := empty_eq _ @[simp] lemma transpose_empty_cols : (![] : matrix (fin 0) m' α)ᵀ = λ i, ![] := funext (λ i, empty_eq _) @[simp] lemma cons_transpose (v : n' → α) (A : matrix (fin m) n' α) : (vec_cons v A)ᵀ = λ i, vec_cons (v i) (Aᵀ i) := by { ext i j, refine fin.cases _ _ j; simp } @[simp] lemma head_transpose (A : matrix m' (fin n.succ) α) : vec_head (Aᵀ) = vec_head ∘ A := rfl @[simp] lemma tail_transpose (A : matrix m' (fin n.succ) α) : vec_tail (Aᵀ) = (vec_tail ∘ A)ᵀ := by { ext i j, refl } end transpose section mul variables [semiring α] @[simp] lemma empty_mul (A : matrix (fin 0) n' α) (B : matrix n' o' α) : A ⬝ B = ![] := empty_eq _ @[simp] lemma empty_mul_empty (A : matrix m' (fin 0) α) (B : matrix (fin 0) o' α) : A ⬝ B = 0 := rfl @[simp] lemma mul_empty (A : matrix m' n' α) (B : matrix n' (fin 0) α) : A ⬝ B = λ _, ![] := funext (λ _, empty_eq _) lemma mul_val_succ (A : matrix (fin m.succ) n' α) (B : matrix n' o' α) (i : fin m) (j : o') : (A ⬝ B) i.succ j = (vec_tail A ⬝ B) i j := rfl @[simp] lemma cons_mul (v : n' → α) (A : matrix (fin m) n' α) (B : matrix n' o' α) : vec_cons v A ⬝ B = vec_cons (vec_mul v B) (A ⬝ B) := by { ext i j, refine fin.cases _ _ i, { refl }, simp [mul_val_succ] } end mul section vec_mul variables [semiring α] @[simp] lemma empty_vec_mul (v : fin 0 → α) (B : matrix (fin 0) o' α) : vec_mul v B = 0 := rfl @[simp] lemma vec_mul_empty (v : n' → α) (B : matrix n' (fin 0) α) : vec_mul v B = ![] := empty_eq _ @[simp] lemma cons_vec_mul (x : α) (v : fin n → α) (B : matrix (fin n.succ) o' α) : vec_mul (vec_cons x v) B = x • (vec_head B) + vec_mul v (vec_tail B) := by { ext i, simp [vec_mul] } @[simp] lemma vec_mul_cons (v : fin n.succ → α) (w : o' → α) (B : matrix (fin n) o' α) : vec_mul v (vec_cons w B) = vec_head v • w + vec_mul (vec_tail v) B := by { ext i, simp [vec_mul] } end vec_mul section mul_vec variables [semiring α] @[simp] lemma empty_mul_vec (A : matrix (fin 0) n' α) (v : n' → α) : mul_vec A v = ![] := empty_eq _ @[simp] lemma mul_vec_empty (A : matrix m' (fin 0) α) (v : fin 0 → α) : mul_vec A v = 0 := rfl @[simp] lemma cons_mul_vec (v : n' → α) (A : fin m → n' → α) (w : n' → α) : mul_vec (vec_cons v A) w = vec_cons (dot_product v w) (mul_vec A w) := by { ext i, refine fin.cases _ _ i; simp [mul_vec] } @[simp] lemma mul_vec_cons {α} [comm_semiring α] (A : m' → (fin n.succ) → α) (x : α) (v : fin n → α) : mul_vec A (vec_cons x v) = (x • vec_head ∘ A) + mul_vec (vec_tail ∘ A) v := by { ext i, simp [mul_vec, mul_comm] } end mul_vec section vec_mul_vec variables [semiring α] @[simp] lemma empty_vec_mul_vec (v : fin 0 → α) (w : n' → α) : vec_mul_vec v w = ![] := empty_eq _ @[simp] lemma vec_mul_vec_empty (v : m' → α) (w : fin 0 → α) : vec_mul_vec v w = λ _, ![] := funext (λ i, empty_eq _) @[simp] lemma cons_vec_mul_vec (x : α) (v : fin m → α) (w : n' → α) : vec_mul_vec (vec_cons x v) w = vec_cons (x • w) (vec_mul_vec v w) := by { ext i, refine fin.cases _ _ i; simp [vec_mul_vec] } @[simp] lemma vec_mul_vec_cons (v : m' → α) (x : α) (w : fin n → α) : vec_mul_vec v (vec_cons x w) = λ i, v i • vec_cons x w := by { ext i j, simp [vec_mul_vec]} end vec_mul_vec section smul variables [semiring α] @[simp] lemma smul_empty (x : α) (v : fin 0 → α) : x • v = ![] := empty_eq _ @[simp] lemma smul_mat_empty {m' : Type*} (x : α) (A : fin 0 → m' → α) : x • A = ![] := empty_eq _ @[simp] lemma smul_cons (x y : α) (v : fin n → α) : x • vec_cons y v = vec_cons (x * y) (x • v) := by { ext i, refine fin.cases _ _ i; simp } @[simp] lemma smul_mat_cons (x : α) (v : n' → α) (A : matrix (fin m) n' α) : x • vec_cons v A = vec_cons (x • v) (x • A) := by { ext i, refine fin.cases _ _ i; simp } end smul section add variables [has_add α] @[simp] lemma empty_add_empty (v w : fin 0 → α) : v + w = ![] := empty_eq _ @[simp] lemma cons_add (x : α) (v : fin n → α) (w : fin n.succ → α) : vec_cons x v + w = vec_cons (x + vec_head w) (v + vec_tail w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma add_cons (v : fin n.succ → α) (y : α) (w : fin n → α) : v + vec_cons y w = vec_cons (vec_head v + y) (vec_tail v + w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma head_add (a b : fin n.succ → α) : vec_head (a + b) = vec_head a + vec_head b := rfl @[simp] lemma tail_add (a b : fin n.succ → α) : vec_tail (a + b) = vec_tail a + vec_tail b := rfl end add section sub variables [has_sub α] @[simp] lemma empty_sub_empty (v w : fin 0 → α) : v - w = ![] := empty_eq _ @[simp] lemma cons_sub (x : α) (v : fin n → α) (w : fin n.succ → α) : vec_cons x v - w = vec_cons (x - vec_head w) (v - vec_tail w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma sub_cons (v : fin n.succ → α) (y : α) (w : fin n → α) : v - vec_cons y w = vec_cons (vec_head v - y) (vec_tail v - w) := by { ext i, refine fin.cases _ _ i; simp [vec_head, vec_tail] } @[simp] lemma head_sub (a b : fin n.succ → α) : vec_head (a - b) = vec_head a - vec_head b := rfl @[simp] lemma tail_sub (a b : fin n.succ → α) : vec_tail (a - b) = vec_tail a - vec_tail b := rfl end sub section zero variables [has_zero α] @[simp] lemma zero_empty : (0 : fin 0 → α) = ![] := empty_eq _ @[simp] lemma cons_zero_zero : vec_cons (0 : α) (0 : fin n → α) = 0 := by { ext i j, refine fin.cases _ _ i, { refl }, simp } @[simp] lemma head_zero : vec_head (0 : fin n.succ → α) = 0 := rfl @[simp] lemma tail_zero : vec_tail (0 : fin n.succ → α) = 0 := rfl @[simp] lemma cons_eq_zero_iff {v : fin n → α} {x : α} : vec_cons x v = 0 ↔ x = 0 ∧ v = 0 := ⟨ λ h, ⟨ congr_fun h 0, by { convert congr_arg vec_tail h, simp } ⟩, λ ⟨hx, hv⟩, by simp [hx, hv] ⟩ open_locale classical lemma cons_nonzero_iff {v : fin n → α} {x : α} : vec_cons x v ≠ 0 ↔ (x ≠ 0 ∨ v ≠ 0) := ⟨ λ h, not_and_distrib.mp (h ∘ cons_eq_zero_iff.mpr), λ h, mt cons_eq_zero_iff.mp (not_and_distrib.mpr h) ⟩ end zero section neg variables [has_neg α] @[simp] lemma neg_empty (v : fin 0 → α) : -v = ![] := empty_eq _ @[simp] lemma neg_cons (x : α) (v : fin n → α) : -(vec_cons x v) = vec_cons (-x) (-v) := by { ext i, refine fin.cases _ _ i; simp } @[simp] lemma head_neg (a : fin n.succ → α) : vec_head (-a) = -vec_head a := rfl @[simp] lemma tail_neg (a : fin n.succ → α) : vec_tail (-a) = -vec_tail a := rfl end neg section minor @[simp] lemma minor_empty (A : matrix m' n' α) (row : fin 0 → m') (col : o' → n') : minor A row col = ![] := empty_eq _ @[simp] lemma minor_cons_row (A : matrix m' n' α) (i : m') (row : fin m → m') (col : o' → n') : minor A (vec_cons i row) col = vec_cons (λ j, A i (col j)) (minor A row col) := by { ext i j, refine fin.cases _ _ i; simp [minor] } end minor end matrix
ee30309520a04e6f6b95e10ccc4e2b446b53da51
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/linear_algebra/affine_space/affine_equiv.lean
0f740a267e3e8708947e85912ef17d29a76664d1
[ "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
17,824
lean
/- Copyright (c) 2020 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import linear_algebra.affine_space.affine_map import algebra.invertible /-! # Affine equivalences In this file we define `affine_equiv k P₁ P₂` (notation: `P₁ ≃ᵃ[k] P₂`) to be the type of affine equivalences between `P₁` and `P₂, i.e., equivalences such that both forward and inverse maps are affine maps. We define the following equivalences: * `affine_equiv.refl k P`: the identity map as an `affine_equiv`; * `e.symm`: the inverse map of an `affine_equiv` as an `affine_equiv`; * `e.trans e'`: composition of two `affine_equiv`s; note that the order follows `mathlib`'s `category_theory` convention (apply `e`, then `e'`), not the convention used in function composition and compositions of bundled morphisms. We equip `affine_equiv k P P` with a `group` structure with multiplication corresponding to composition in `affine_equiv.group`. ## Tags affine space, affine equivalence -/ open function set open_locale affine /-- An affine equivalence is an equivalence between affine spaces such that both forward and inverse maps are affine. We define it using an `equiv` for the map and a `linear_equiv` for the linear part in order to allow affine equivalences with good definitional equalities. -/ @[nolint has_nonempty_instance] structure affine_equiv (k P₁ P₂ : Type*) {V₁ V₂ : Type*} [ring k] [add_comm_group V₁] [module k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [module k V₂] [add_torsor V₂ P₂] extends P₁ ≃ P₂ := (linear : V₁ ≃ₗ[k] V₂) (map_vadd' : ∀ (p : P₁) (v : V₁), to_equiv (v +ᵥ p) = linear v +ᵥ to_equiv p) notation P₁ ` ≃ᵃ[`:25 k:25 `] `:0 P₂:0 := affine_equiv k P₁ P₂ variables {k P₁ P₂ P₃ P₄ V₁ V₂ V₃ V₄ : Type*} [ring k] [add_comm_group V₁] [module k V₁] [add_torsor V₁ P₁] [add_comm_group V₂] [module k V₂] [add_torsor V₂ P₂] [add_comm_group V₃] [module k V₃] [add_torsor V₃ P₃] [add_comm_group V₄] [module k V₄] [add_torsor V₄ P₄] namespace affine_equiv include V₁ V₂ instance : has_coe_to_fun (P₁ ≃ᵃ[k] P₂) (λ _, P₁ → P₂) := ⟨λ e, e.to_fun⟩ instance : has_coe (P₁ ≃ᵃ[k] P₂) (P₁ ≃ P₂) := ⟨affine_equiv.to_equiv⟩ variables {k P₁} @[simp] lemma map_vadd (e : P₁ ≃ᵃ[k] P₂) (p : P₁) (v : V₁) : e (v +ᵥ p) = e.linear v +ᵥ e p := e.map_vadd' p v @[simp] lemma coe_to_equiv (e : P₁ ≃ᵃ[k] P₂) : ⇑e.to_equiv = e := rfl /-- Reinterpret an `affine_equiv` as an `affine_map`. -/ def to_affine_map (e : P₁ ≃ᵃ[k] P₂) : P₁ →ᵃ[k] P₂ := { to_fun := e, .. e } instance : has_coe (P₁ ≃ᵃ[k] P₂) (P₁ →ᵃ[k] P₂) := ⟨to_affine_map⟩ @[simp] lemma coe_to_affine_map (e : P₁ ≃ᵃ[k] P₂) : (e.to_affine_map : P₁ → P₂) = (e : P₁ → P₂) := rfl @[simp] lemma to_affine_map_mk (f : P₁ ≃ P₂) (f' : V₁ ≃ₗ[k] V₂) (h) : to_affine_map (mk f f' h) = ⟨f, f', h⟩ := rfl @[norm_cast, simp] lemma coe_coe (e : P₁ ≃ᵃ[k] P₂) : ((e : P₁ →ᵃ[k] P₂) : P₁ → P₂) = e := rfl @[simp] lemma linear_to_affine_map (e : P₁ ≃ᵃ[k] P₂) : e.to_affine_map.linear = e.linear := rfl @[simp] lemma coe_linear (e : P₁ ≃ᵃ[k] P₂) : (e : P₁ →ᵃ[k] P₂).linear = e.linear := rfl lemma to_affine_map_injective : injective (to_affine_map : (P₁ ≃ᵃ[k] P₂) → (P₁ →ᵃ[k] P₂)) := begin rintros ⟨e, el, h⟩ ⟨e', el', h'⟩ H, simp only [to_affine_map_mk, equiv.coe_inj, linear_equiv.to_linear_map_inj] at H, congr, exacts [H.1, H.2] end @[simp] lemma to_affine_map_inj {e e' : P₁ ≃ᵃ[k] P₂} : e.to_affine_map = e'.to_affine_map ↔ e = e' := to_affine_map_injective.eq_iff @[ext] lemma ext {e e' : P₁ ≃ᵃ[k] P₂} (h : ∀ x, e x = e' x) : e = e' := to_affine_map_injective $ affine_map.ext h lemma coe_fn_injective : @injective (P₁ ≃ᵃ[k] P₂) (P₁ → P₂) coe_fn := λ e e' H, ext $ congr_fun H @[simp, norm_cast] lemma coe_fn_inj {e e' : P₁ ≃ᵃ[k] P₂} : (e : P₁ → P₂) = e' ↔ e = e' := coe_fn_injective.eq_iff lemma to_equiv_injective : injective (to_equiv : (P₁ ≃ᵃ[k] P₂) → (P₁ ≃ P₂)) := λ e e' H, ext $ equiv.ext_iff.1 H @[simp] lemma to_equiv_inj {e e' : P₁ ≃ᵃ[k] P₂} : e.to_equiv = e'.to_equiv ↔ e = e' := to_equiv_injective.eq_iff @[simp] lemma coe_mk (e : P₁ ≃ P₂) (e' : V₁ ≃ₗ[k] V₂) (h) : ((⟨e, e', h⟩ : P₁ ≃ᵃ[k] P₂) : P₁ → P₂) = e := rfl /-- Construct an affine equivalence by verifying the relation between the map and its linear part at one base point. Namely, this function takes a map `e : P₁ → P₂`, a linear equivalence `e' : V₁ ≃ₗ[k] V₂`, and a point `p` such that for any other point `p'` we have `e p' = e' (p' -ᵥ p) +ᵥ e p`. -/ def mk' (e : P₁ → P₂) (e' : V₁ ≃ₗ[k] V₂) (p : P₁) (h : ∀ p' : P₁, e p' = e' (p' -ᵥ p) +ᵥ e p) : P₁ ≃ᵃ[k] P₂ := { to_fun := e, inv_fun := λ q' : P₂, e'.symm (q' -ᵥ e p) +ᵥ p, left_inv := λ p', by simp [h p'], right_inv := λ q', by simp [h (e'.symm (q' -ᵥ e p) +ᵥ p)], linear := e', map_vadd' := λ p' v, by { simp [h p', h (v +ᵥ p'), vadd_vsub_assoc, vadd_vadd] } } @[simp] lemma coe_mk' (e : P₁ ≃ P₂) (e' : V₁ ≃ₗ[k] V₂) (p h) : ⇑(mk' e e' p h) = e := rfl @[simp] lemma linear_mk' (e : P₁ ≃ P₂) (e' : V₁ ≃ₗ[k] V₂) (p h) : (mk' e e' p h).linear = e' := rfl /-- Inverse of an affine equivalence as an affine equivalence. -/ @[symm] def symm (e : P₁ ≃ᵃ[k] P₂) : P₂ ≃ᵃ[k] P₁ := { to_equiv := e.to_equiv.symm, linear := e.linear.symm, map_vadd' := λ v p, e.to_equiv.symm.apply_eq_iff_eq_symm_apply.2 $ by simpa using (e.to_equiv.apply_symm_apply v).symm } @[simp] lemma symm_to_equiv (e : P₁ ≃ᵃ[k] P₂) : e.to_equiv.symm = e.symm.to_equiv := rfl @[simp] lemma symm_linear (e : P₁ ≃ᵃ[k] P₂) : e.linear.symm = e.symm.linear := rfl /-- See Note [custom simps projection] -/ def simps.apply (e : P₁ ≃ᵃ[k] P₂) : P₁ → P₂ := e /-- See Note [custom simps projection] -/ def simps.symm_apply (e : P₁ ≃ᵃ[k] P₂) : P₂ → P₁ := e.symm initialize_simps_projections affine_equiv (to_equiv_to_fun → apply, to_equiv_inv_fun → symm_apply, linear → linear as_prefix, -to_equiv) protected lemma bijective (e : P₁ ≃ᵃ[k] P₂) : bijective e := e.to_equiv.bijective protected lemma surjective (e : P₁ ≃ᵃ[k] P₂) : surjective e := e.to_equiv.surjective protected lemma injective (e : P₁ ≃ᵃ[k] P₂) : injective e := e.to_equiv.injective @[simp] lemma range_eq (e : P₁ ≃ᵃ[k] P₂) : range e = univ := e.surjective.range_eq @[simp] lemma apply_symm_apply (e : P₁ ≃ᵃ[k] P₂) (p : P₂) : e (e.symm p) = p := e.to_equiv.apply_symm_apply p @[simp] lemma symm_apply_apply (e : P₁ ≃ᵃ[k] P₂) (p : P₁) : e.symm (e p) = p := e.to_equiv.symm_apply_apply p lemma apply_eq_iff_eq_symm_apply (e : P₁ ≃ᵃ[k] P₂) {p₁ p₂} : e p₁ = p₂ ↔ p₁ = e.symm p₂ := e.to_equiv.apply_eq_iff_eq_symm_apply @[simp] lemma apply_eq_iff_eq (e : P₁ ≃ᵃ[k] P₂) {p₁ p₂ : P₁} : e p₁ = e p₂ ↔ p₁ = p₂ := e.to_equiv.apply_eq_iff_eq variables (k P₁) omit V₂ /-- Identity map as an `affine_equiv`. -/ @[refl] def refl : P₁ ≃ᵃ[k] P₁ := { to_equiv := equiv.refl P₁, linear := linear_equiv.refl k V₁, map_vadd' := λ _ _, rfl } @[simp] lemma coe_refl : ⇑(refl k P₁) = id := rfl @[simp] lemma coe_refl_to_affine_map : ↑(refl k P₁) = affine_map.id k P₁ := rfl @[simp] lemma refl_apply (x : P₁) : refl k P₁ x = x := rfl @[simp] lemma to_equiv_refl : (refl k P₁).to_equiv = equiv.refl P₁ := rfl @[simp] lemma linear_refl : (refl k P₁).linear = linear_equiv.refl k V₁ := rfl @[simp] lemma symm_refl : (refl k P₁).symm = refl k P₁ := rfl variables {k P₁} include V₂ V₃ /-- Composition of two `affine_equiv`alences, applied left to right. -/ @[trans] def trans (e : P₁ ≃ᵃ[k] P₂) (e' : P₂ ≃ᵃ[k] P₃) : P₁ ≃ᵃ[k] P₃ := { to_equiv := e.to_equiv.trans e'.to_equiv, linear := e.linear.trans e'.linear, map_vadd' := λ p v, by simp only [linear_equiv.trans_apply, coe_to_equiv, (∘), equiv.coe_trans, map_vadd] } @[simp] lemma coe_trans (e : P₁ ≃ᵃ[k] P₂) (e' : P₂ ≃ᵃ[k] P₃) : ⇑(e.trans e') = e' ∘ e := rfl @[simp] lemma coe_trans_to_affine_map (e : P₁ ≃ᵃ[k] P₂) (e' : P₂ ≃ᵃ[k] P₃) : (e.trans e' : P₁ →ᵃ[k] P₃) = (e' : P₂ →ᵃ[k] P₃).comp e := rfl @[simp] lemma trans_apply (e : P₁ ≃ᵃ[k] P₂) (e' : P₂ ≃ᵃ[k] P₃) (p : P₁) : e.trans e' p = e' (e p) := rfl include V₄ lemma trans_assoc (e₁ : P₁ ≃ᵃ[k] P₂) (e₂ : P₂ ≃ᵃ[k] P₃) (e₃ : P₃ ≃ᵃ[k] P₄) : (e₁.trans e₂).trans e₃ = e₁.trans (e₂.trans e₃) := ext $ λ _, rfl omit V₃ V₄ @[simp] lemma trans_refl (e : P₁ ≃ᵃ[k] P₂) : e.trans (refl k P₂) = e := ext $ λ _, rfl @[simp] lemma refl_trans (e : P₁ ≃ᵃ[k] P₂) : (refl k P₁).trans e = e := ext $ λ _, rfl @[simp] lemma self_trans_symm (e : P₁ ≃ᵃ[k] P₂) : e.trans e.symm = refl k P₁ := ext e.symm_apply_apply @[simp] lemma symm_trans_self (e : P₁ ≃ᵃ[k] P₂) : e.symm.trans e = refl k P₂ := ext e.apply_symm_apply @[simp] lemma apply_line_map (e : P₁ ≃ᵃ[k] P₂) (a b : P₁) (c : k) : e (affine_map.line_map a b c) = affine_map.line_map (e a) (e b) c := e.to_affine_map.apply_line_map a b c omit V₂ instance : group (P₁ ≃ᵃ[k] P₁) := { one := refl k P₁, mul := λ e e', e'.trans e, inv := symm, mul_assoc := λ e₁ e₂ e₃, trans_assoc _ _ _, one_mul := trans_refl, mul_one := refl_trans, mul_left_inv := self_trans_symm } lemma one_def : (1 : P₁ ≃ᵃ[k] P₁) = refl k P₁ := rfl @[simp] lemma coe_one : ⇑(1 : P₁ ≃ᵃ[k] P₁) = id := rfl lemma mul_def (e e' : P₁ ≃ᵃ[k] P₁) : e * e' = e'.trans e := rfl @[simp] lemma coe_mul (e e' : P₁ ≃ᵃ[k] P₁) : ⇑(e * e') = e ∘ e' := rfl lemma inv_def (e : P₁ ≃ᵃ[k] P₁) : e⁻¹ = e.symm := rfl /-- `affine_equiv.linear` on automorphisms is a `monoid_hom`. -/ @[simps] def linear_hom : (P₁ ≃ᵃ[k] P₁) →* (V₁ ≃ₗ[k] V₁) := { to_fun := linear, map_one' := rfl, map_mul' := λ _ _, rfl } /-- The group of `affine_equiv`s are equivalent to the group of units of `affine_map`. This is the affine version of `linear_map.general_linear_group.general_linear_equiv`. -/ @[simps] def equiv_units_affine_map : (P₁ ≃ᵃ[k] P₁) ≃* (P₁ →ᵃ[k] P₁)ˣ := { to_fun := λ e, ⟨e, e.symm, congr_arg coe e.symm_trans_self, congr_arg coe e.self_trans_symm⟩, inv_fun := λ u, { to_fun := (u : P₁ →ᵃ[k] P₁), inv_fun := (↑(u⁻¹) : P₁ →ᵃ[k] P₁), left_inv := affine_map.congr_fun u.inv_mul, right_inv := affine_map.congr_fun u.mul_inv, linear := linear_map.general_linear_group.general_linear_equiv _ _ $ units.map (by exact affine_map.linear_hom) u, map_vadd' := λ _ _, (u : P₁ →ᵃ[k] P₁).map_vadd _ _ }, left_inv := λ e, affine_equiv.ext $ λ x, rfl, right_inv := λ u, units.ext $ affine_map.ext $ λ x, rfl, map_mul' := λ e₁ e₂, rfl } variable (k) /-- The map `v ↦ v +ᵥ b` as an affine equivalence between a module `V` and an affine space `P` with tangent space `V`. -/ @[simps] def vadd_const (b : P₁) : V₁ ≃ᵃ[k] P₁ := { to_equiv := equiv.vadd_const b, linear := linear_equiv.refl _ _, map_vadd' := λ p v, add_vadd _ _ _ } /-- `p' ↦ p -ᵥ p'` as an equivalence. -/ def const_vsub (p : P₁) : P₁ ≃ᵃ[k] V₁ := { to_equiv := equiv.const_vsub p, linear := linear_equiv.neg k, map_vadd' := λ p' v, by simp [vsub_vadd_eq_vsub_sub, neg_add_eq_sub] } @[simp] lemma coe_const_vsub (p : P₁) : ⇑(const_vsub k p) = (-ᵥ) p := rfl @[simp] lemma coe_const_vsub_symm (p : P₁) : ⇑(const_vsub k p).symm = λ v, -v +ᵥ p := rfl variable (P₁) /-- The map `p ↦ v +ᵥ p` as an affine automorphism of an affine space. Note that there is no need for an `affine_map.const_vadd` as it is always an equivalence. This is roughly to `distrib_mul_action.to_linear_equiv` as `+ᵥ` is to `•`. -/ @[simps apply linear] def const_vadd (v : V₁) : P₁ ≃ᵃ[k] P₁ := { to_equiv := equiv.const_vadd P₁ v, linear := linear_equiv.refl _ _, map_vadd' := λ p w, vadd_comm _ _ _ } @[simp] lemma const_vadd_zero : const_vadd k P₁ 0 = affine_equiv.refl _ _ := ext $ zero_vadd _ @[simp] lemma const_vadd_add (v w : V₁) : const_vadd k P₁ (v + w) = (const_vadd k P₁ w).trans (const_vadd k P₁ v) := ext $ add_vadd _ _ @[simp] lemma const_vadd_symm (v : V₁) : (const_vadd k P₁ v).symm = const_vadd k P₁ (-v) := ext $ λ _, rfl /-- A more bundled version of `affine_equiv.const_vadd`. -/ @[simps] def const_vadd_hom : multiplicative V₁ →* P₁ ≃ᵃ[k] P₁ := { to_fun := λ v, const_vadd k P₁ v.to_add, map_one' := const_vadd_zero _ _, map_mul' := const_vadd_add _ _ } lemma const_vadd_nsmul (n : ℕ) (v : V₁) : const_vadd k P₁ (n • v) = (const_vadd k P₁ v)^n := (const_vadd_hom k P₁).map_pow _ _ lemma const_vadd_zsmul (z : ℤ) (v : V₁) : const_vadd k P₁ (z • v) = (const_vadd k P₁ v)^z := (const_vadd_hom k P₁).map_zpow _ _ section homothety omit V₁ variables {R V P : Type*} [comm_ring R] [add_comm_group V] [module R V] [affine_space V P] include V /-- Fixing a point in affine space, homothety about this point gives a group homomorphism from (the centre of) the units of the scalars into the group of affine equivalences. -/ def homothety_units_mul_hom (p : P) : Rˣ →* P ≃ᵃ[R] P := equiv_units_affine_map.symm.to_monoid_hom.comp $ units.map (affine_map.homothety_hom p) @[simp] lemma coe_homothety_units_mul_hom_apply (p : P) (t : Rˣ) : (homothety_units_mul_hom p t : P → P) = affine_map.homothety p (t : R) := rfl @[simp] lemma coe_homothety_units_mul_hom_apply_symm (p : P) (t : Rˣ) : ((homothety_units_mul_hom p t).symm : P → P) = affine_map.homothety p (↑t⁻¹ : R) := rfl @[simp] lemma coe_homothety_units_mul_hom_eq_homothety_hom_coe (p : P) : (coe : (P ≃ᵃ[R] P) → P →ᵃ[R] P) ∘ homothety_units_mul_hom p = (affine_map.homothety_hom p) ∘ (coe : Rˣ → R) := funext $ λ _, rfl end homothety variable {P₁} open function /-- Point reflection in `x` as a permutation. -/ def point_reflection (x : P₁) : P₁ ≃ᵃ[k] P₁ := (const_vsub k x).trans (vadd_const k x) lemma point_reflection_apply (x y : P₁) : point_reflection k x y = x -ᵥ y +ᵥ x := rfl @[simp] lemma point_reflection_symm (x : P₁) : (point_reflection k x).symm = point_reflection k x := to_equiv_injective $ equiv.point_reflection_symm x @[simp] lemma to_equiv_point_reflection (x : P₁) : (point_reflection k x).to_equiv = equiv.point_reflection x := rfl @[simp] lemma point_reflection_self (x : P₁) : point_reflection k x x = x := vsub_vadd _ _ lemma point_reflection_involutive (x : P₁) : involutive (point_reflection k x : P₁ → P₁) := equiv.point_reflection_involutive x /-- `x` is the only fixed point of `point_reflection x`. This lemma requires `x + x = y + y ↔ x = y`. There is no typeclass to use here, so we add it as an explicit argument. -/ lemma point_reflection_fixed_iff_of_injective_bit0 {x y : P₁} (h : injective (bit0 : V₁ → V₁)) : point_reflection k x y = y ↔ y = x := equiv.point_reflection_fixed_iff_of_injective_bit0 h lemma injective_point_reflection_left_of_injective_bit0 (h : injective (bit0 : V₁ → V₁)) (y : P₁) : injective (λ x : P₁, point_reflection k x y) := equiv.injective_point_reflection_left_of_injective_bit0 h y lemma injective_point_reflection_left_of_module [invertible (2:k)]: ∀ y, injective (λ x : P₁, point_reflection k x y) := injective_point_reflection_left_of_injective_bit0 k $ λ x y h, by rwa [bit0, bit0, ← two_smul k x, ← two_smul k y, (is_unit_of_invertible (2:k)).smul_left_cancel] at h lemma point_reflection_fixed_iff_of_module [invertible (2:k)] {x y : P₁} : point_reflection k x y = y ↔ y = x := ((injective_point_reflection_left_of_module k y).eq_iff' (point_reflection_self k y)).trans eq_comm end affine_equiv namespace linear_equiv /-- Interpret a linear equivalence between modules as an affine equivalence. -/ def to_affine_equiv (e : V₁ ≃ₗ[k] V₂) : V₁ ≃ᵃ[k] V₂ := { to_equiv := e.to_equiv, linear := e, map_vadd' := λ p v, e.map_add v p } @[simp] lemma coe_to_affine_equiv (e : V₁ ≃ₗ[k] V₂) : ⇑e.to_affine_equiv = e := rfl end linear_equiv namespace affine_map open affine_equiv include V₁ lemma line_map_vadd (v v' : V₁) (p : P₁) (c : k) : line_map v v' c +ᵥ p = line_map (v +ᵥ p) (v' +ᵥ p) c := (vadd_const k p).apply_line_map v v' c lemma line_map_vsub (p₁ p₂ p₃ : P₁) (c : k) : line_map p₁ p₂ c -ᵥ p₃ = line_map (p₁ -ᵥ p₃) (p₂ -ᵥ p₃) c := (vadd_const k p₃).symm.apply_line_map p₁ p₂ c lemma vsub_line_map (p₁ p₂ p₃ : P₁) (c : k) : p₁ -ᵥ line_map p₂ p₃ c = line_map (p₁ -ᵥ p₂) (p₁ -ᵥ p₃) c := (const_vsub k p₁).apply_line_map p₂ p₃ c lemma vadd_line_map (v : V₁) (p₁ p₂ : P₁) (c : k) : v +ᵥ line_map p₁ p₂ c = line_map (v +ᵥ p₁) (v +ᵥ p₂) c := (const_vadd k P₁ v).apply_line_map p₁ p₂ c variables {R' : Type*} [comm_ring R'] [module R' V₁] lemma homothety_neg_one_apply (c p : P₁) : homothety c (-1:R') p = point_reflection R' c p := by simp [homothety_apply, point_reflection_apply] end affine_map
d9de020cd9a372cc2ff2b49e95dd9ab6e3552328
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/src/Lean/Compiler/IR/ElimDeadBranches.lean
3fee60b6c9da585e4766b4da05db1d468eec8646
[ "Apache-2.0" ]
permissive
subfish-zhou/leanprover-zh_CN.github.io
30b9fba9bd790720bd95764e61ae796697d2f603
8b2985d4a3d458ceda9361ac454c28168d920d3f
refs/heads/master
1,689,709,967,820
1,632,503,056,000
1,632,503,056,000
409,962,097
1
0
null
null
null
null
UTF-8
Lean
false
false
10,595
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Compiler.IR.Format import Lean.Compiler.IR.Basic import Lean.Compiler.IR.CompilerM namespace Lean.IR.UnreachableBranches /-- Value used in the abstract interpreter -/ inductive Value where | bot -- undefined | top -- any value | ctor (i : CtorInfo) (vs : Array Value) | choice (vs : List Value) deriving Inhabited namespace Value protected partial def beq : Value → Value → Bool | bot, bot => true | top, top => true | ctor i₁ vs₁, ctor i₂ vs₂ => i₁ == i₂ && Array.isEqv vs₁ vs₂ Value.beq | choice vs₁, choice vs₂ => vs₁.all (fun v₁ => vs₂.any fun v₂ => Value.beq v₁ v₂) && vs₂.all (fun v₂ => vs₁.any fun v₁ => Value.beq v₁ v₂) | _, _ => false instance : BEq Value := ⟨Value.beq⟩ partial def addChoice (merge : Value → Value → Value) : List Value → Value → List Value | [], v => [v] | v₁@(ctor i₁ vs₁) :: cs, v₂@(ctor i₂ vs₂) => if i₁ == i₂ then merge v₁ v₂ :: cs else v₁ :: addChoice merge cs v₂ | _, _ => panic! "invalid addChoice" partial def merge : Value → Value → Value | bot, v => v | v, bot => v | top, _ => top | _, top => top | v₁@(ctor i₁ vs₁), v₂@(ctor i₂ vs₂) => if i₁ == i₂ then ctor i₁ $ vs₁.size.fold (init := #[]) fun i r => r.push (merge vs₁[i] vs₂[i]) else choice [v₁, v₂] | choice vs₁, choice vs₂ => choice $ vs₁.foldl (addChoice merge) vs₂ | choice vs, v => choice $ addChoice merge vs v | v, choice vs => choice $ addChoice merge vs v protected partial def format : Value → Format | top => "top" | bot => "bot" | choice vs => format "@" ++ @List.format _ ⟨Value.format⟩ vs | ctor i vs => format "#" ++ if vs.isEmpty then format i.name else Format.paren (format i.name ++ @formatArray _ ⟨Value.format⟩ vs) instance : ToFormat Value := ⟨Value.format⟩ instance : ToString Value := ⟨Format.pretty ∘ Value.format⟩ /- Make sure constructors of recursive inductive datatypes can only occur once in each path. We use this function this function to implement a simple widening operation for our abstract interpreter. -/ partial def truncate (env : Environment) : Value → NameSet → Value | ctor i vs, found => let I := i.name.getPrefix if found.contains I then top else let cont (found' : NameSet) : Value := ctor i (vs.map fun v => truncate env v found') match env.find? I with | some (ConstantInfo.inductInfo d) => if d.isRec then cont (found.insert I) else cont found | _ => cont found | choice vs, found => let newVs := vs.map fun v => truncate env v found if newVs.elem top then top else choice newVs | v, _ => v /- Widening operator that guarantees termination in our abstract interpreter. -/ def widening (env : Environment) (v₁ v₂ : Value) : Value := truncate env (merge v₁ v₂) {} end Value abbrev FunctionSummaries := SMap FunId Value builtin_initialize functionSummariesExt : SimplePersistentEnvExtension (FunId × Value) FunctionSummaries ← registerSimplePersistentEnvExtension { name := `unreachBranchesFunSummary, addImportedFn := fun as => let cache : FunctionSummaries := mkStateFromImportedEntries (fun s (p : FunId × Value) => s.insert p.1 p.2) {} as cache.switch, addEntryFn := fun s ⟨e, n⟩ => s.insert e n } def addFunctionSummary (env : Environment) (fid : FunId) (v : Value) : Environment := functionSummariesExt.addEntry env (fid, v) def getFunctionSummary? (env : Environment) (fid : FunId) : Option Value := (functionSummariesExt.getState env).find? fid abbrev Assignment := Std.HashMap VarId Value structure InterpContext where currFnIdx : Nat := 0 decls : Array Decl env : Environment lctx : LocalContext := {} structure InterpState where assignments : Array Assignment funVals : Std.PArray Value -- we take snapshots during fixpoint computations abbrev M := ReaderT InterpContext (StateM InterpState) open Value def findVarValue (x : VarId) : M Value := do let ctx ← read let s ← get let assignment := s.assignments[ctx.currFnIdx] pure $ assignment.findD x bot def findArgValue (arg : Arg) : M Value := match arg with | Arg.var x => findVarValue x | _ => pure top def updateVarAssignment (x : VarId) (v : Value) : M Unit := do let v' ← findVarValue x let ctx ← read modify fun s => { s with assignments := s.assignments.modify ctx.currFnIdx fun a => a.insert x (merge v v') } def resetVarAssignment (x : VarId) : M Unit := do let ctx ← read modify fun s => { s with assignments := s.assignments.modify ctx.currFnIdx fun a => a.insert x Value.bot } def resetParamAssignment (y : Param) : M Unit := resetVarAssignment y.x partial def projValue : Value → Nat → Value | ctor _ vs, i => vs.getD i bot | choice vs, i => vs.foldl (fun r v => merge r (projValue v i)) bot | v, _ => v def interpExpr : Expr → M Value | Expr.ctor i ys => return ctor i (← ys.mapM fun y => findArgValue y) | Expr.proj i x => return projValue (← findVarValue x) i | Expr.fap fid ys => do let ctx ← read match getFunctionSummary? ctx.env fid with | some v => pure v | none => do let s ← get match ctx.decls.findIdx? (fun decl => decl.name == fid) with | some idx => pure s.funVals[idx] | none => pure top | _ => pure top partial def containsCtor : Value → CtorInfo → Bool | top, _ => true | ctor i _, j => i == j | choice vs, j => vs.any $ fun v => containsCtor v j | _, _ => false def updateCurrFnSummary (v : Value) : M Unit := do let ctx ← read let currFnIdx := ctx.currFnIdx modify fun s => { s with funVals := s.funVals.modify currFnIdx (fun v' => widening ctx.env v v') } /-- Return true if the assignment of at least one parameter has been updated. -/ def updateJPParamsAssignment (ys : Array Param) (xs : Array Arg) : M Bool := do let ctx ← read let currFnIdx := ctx.currFnIdx ys.size.foldM (init := false) fun i r => do let y := ys[i] let x := xs[i] let yVal ← findVarValue y.x let xVal ← findArgValue x let newVal := merge yVal xVal if newVal == yVal then pure r else modify fun s => { s with assignments := s.assignments.modify currFnIdx fun a => a.insert y.x newVal } pure true private partial def resetNestedJPParams : FnBody → M Unit | FnBody.jdecl _ ys b k => do let ctx ← read let currFnIdx := ctx.currFnIdx ys.forM resetParamAssignment /- Remark we don't need to reset the parameters of joint-points nested in `b` since they will be reset if this JP is used. -/ resetNestedJPParams k | FnBody.case _ _ _ alts => alts.forM fun alt => match alt with | Alt.ctor _ b => resetNestedJPParams b | Alt.default b => resetNestedJPParams b | e => do unless e.isTerminal do resetNestedJPParams e.body partial def interpFnBody : FnBody → M Unit | FnBody.vdecl x _ e b => do let v ← interpExpr e updateVarAssignment x v interpFnBody b | FnBody.jdecl j ys v b => withReader (fun ctx => { ctx with lctx := ctx.lctx.addJP j ys v }) do interpFnBody b | FnBody.case _ x _ alts => do let v ← findVarValue x alts.forM fun alt => do match alt with | Alt.ctor i b => if containsCtor v i then interpFnBody b | Alt.default b => interpFnBody b | FnBody.ret x => do let v ← findArgValue x -- dbgTrace ("ret " ++ toString v) $ fun _ => updateCurrFnSummary v | FnBody.jmp j xs => do let ctx ← read let ys := (ctx.lctx.getJPParams j).get! let b := (ctx.lctx.getJPBody j).get! let updated ← updateJPParamsAssignment ys xs if updated then -- We must reset the value of nested join-point parameters since they depend on `ys` values resetNestedJPParams b interpFnBody b | e => do unless e.isTerminal do interpFnBody e.body def inferStep : M Bool := do let ctx ← read modify fun s => { s with assignments := ctx.decls.map fun _ => {} } ctx.decls.size.foldM (init := false) fun idx modified => do match ctx.decls[idx] with | Decl.fdecl (xs := ys) (body := b) .. => do let s ← get let currVals := s.funVals[idx] withReader (fun ctx => { ctx with currFnIdx := idx }) do ys.forM fun y => updateVarAssignment y.x top interpFnBody b let s ← get let newVals := s.funVals[idx] pure (modified || currVals != newVals) | Decl.extern _ _ _ _ => pure modified partial def inferMain : M Unit := do let modified ← inferStep if modified then inferMain else pure () partial def elimDeadAux (assignment : Assignment) : FnBody → FnBody | FnBody.vdecl x t e b => FnBody.vdecl x t e (elimDeadAux assignment b) | FnBody.jdecl j ys v b => FnBody.jdecl j ys (elimDeadAux assignment v) (elimDeadAux assignment b) | FnBody.case tid x xType alts => let v := assignment.findD x bot let alts := alts.map fun alt => match alt with | Alt.ctor i b => Alt.ctor i $ if containsCtor v i then elimDeadAux assignment b else FnBody.unreachable | Alt.default b => Alt.default (elimDeadAux assignment b) FnBody.case tid x xType alts | e => if e.isTerminal then e else let (instr, b) := e.split let b := elimDeadAux assignment b instr.setBody b partial def elimDead (assignment : Assignment) (d : Decl) : Decl := match d with | Decl.fdecl (body := b) .. => d.updateBody! <| elimDeadAux assignment b | other => other end UnreachableBranches open UnreachableBranches def elimDeadBranches (decls : Array Decl) : CompilerM (Array Decl) := do let s ← get let env := s.env let assignments : Array Assignment := decls.map fun _ => {} let funVals := Std.mkPArray decls.size Value.bot let ctx : InterpContext := { decls := decls, env := env } let s : InterpState := { assignments := assignments, funVals := funVals } let (_, s) := (inferMain ctx).run s let funVals := s.funVals let assignments := s.assignments modify fun s => let env := decls.size.fold (init := s.env) fun i env => addFunctionSummary env decls[i].name funVals[i] { s with env := env } pure $ decls.mapIdx fun i decl => elimDead assignments[i] decl end Lean.IR
6213befb03fc670666bc812bfd1e8aa84055a2d3
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/measure_theory/l1_space.lean
bba30610d8c66a3faf24784cfc3e8617cddc836e
[]
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
53,900
lean
/- Copyright (c) 2019 Zhouhang Zhou. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Zhouhang Zhou -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.measure_theory.ae_eq_fun import Mathlib.PostPort universes u_1 u_2 u_3 u_5 u_4 u_6 namespace Mathlib /-! # Integrable functions and `L¹` space In the first part of this file, the predicate `integrable` is defined and basic properties of integrable functions are proved. In the second part, the space `L¹` of equivalence classes of integrable functions under the relation of being almost everywhere equal is defined as a subspace of the space `L⁰`. See the file `src/measure_theory/ae_eq_fun.lean` for information on `L⁰` space. ## Notation * `α →₁ β` is the type of `L¹` space, where `α` is a `measure_space` and `β` is a `normed_group` with a `second_countable_topology`. `f : α →ₘ β` is a "function" in `L¹`. In comments, `[f]` is also used to denote an `L¹` function. `₁` can be typed as `\1`. ## Main definitions * Let `f : α → β` be a function, where `α` is a `measure_space` and `β` a `normed_group`. Then `has_finite_integral f` means `(∫⁻ a, nnnorm (f a)) < ⊤`. * If `β` is moreover a `measurable_space` then `f` is called `integrable` if `f` is `measurable` and `has_finite_integral f` holds. * The space `L¹` is defined as a subspace of `L⁰` : An `ae_eq_fun` `[f] : α →ₘ β` is in the space `L¹` if `edist [f] 0 < ⊤`, which means `(∫⁻ a, edist (f a) 0) < ⊤` if we expand the definition of `edist` in `L⁰`. ## Main statements `L¹`, as a subspace, inherits most of the structures of `L⁰`. ## Implementation notes Maybe `integrable f` should be mean `(∫⁻ a, edist (f a) 0) < ⊤`, so that `integrable` and `ae_eq_fun.integrable` are more aligned. But in the end one can use the lemma `lintegral_nnnorm_eq_lintegral_edist : (∫⁻ a, nnnorm (f a)) = (∫⁻ a, edist (f a) 0)` to switch the two forms. To prove something for an arbitrary integrable function, a useful theorem is `integrable.induction` in the file `set_integral`. ## Tags integrable, function space, l1 -/ namespace measure_theory /-! ### Some results about the Lebesgue integral involving a normed group -/ theorem lintegral_nnnorm_eq_lintegral_edist {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] (f : α → β) : (lintegral μ fun (a : α) => ↑(nnnorm (f a))) = lintegral μ fun (a : α) => edist (f a) 0 := sorry theorem lintegral_norm_eq_lintegral_edist {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] (f : α → β) : (lintegral μ fun (a : α) => ennreal.of_real (norm (f a))) = lintegral μ fun (a : α) => edist (f a) 0 := sorry theorem lintegral_edist_triangle {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [topological_space.second_countable_topology β] [measurable_space β] [opens_measurable_space β] {f : α → β} {g : α → β} {h : α → β} (hf : ae_measurable f) (hg : ae_measurable g) (hh : ae_measurable h) : (lintegral μ fun (a : α) => edist (f a) (g a)) ≤ (lintegral μ fun (a : α) => edist (f a) (h a)) + lintegral μ fun (a : α) => edist (g a) (h a) := sorry theorem lintegral_nnnorm_zero {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] : (lintegral μ fun (a : α) => ↑(nnnorm 0)) = 0 := sorry theorem lintegral_nnnorm_add {α : Type u_1} {β : Type u_2} {γ : Type u_3} [measurable_space α] {μ : measure α} [normed_group β] [normed_group γ] [measurable_space β] [opens_measurable_space β] [measurable_space γ] [opens_measurable_space γ] {f : α → β} {g : α → γ} (hf : ae_measurable f) (hg : ae_measurable g) : (lintegral μ fun (a : α) => ↑(nnnorm (f a)) + ↑(nnnorm (g a))) = (lintegral μ fun (a : α) => ↑(nnnorm (f a))) + lintegral μ fun (a : α) => ↑(nnnorm (g a)) := lintegral_add' (ae_measurable.ennnorm hf) (ae_measurable.ennnorm hg) theorem lintegral_nnnorm_neg {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] {f : α → β} : (lintegral μ fun (a : α) => ↑(nnnorm (Neg.neg f a))) = lintegral μ fun (a : α) => ↑(nnnorm (f a)) := sorry /-! ### The predicate `has_finite_integral` -/ /-- `has_finite_integral f μ` means that the integral `∫⁻ a, ∥f a∥ ∂μ` is finite. `has_finite_integral f` means `has_finite_integral f volume`. -/ def has_finite_integral {α : Type u_1} {β : Type u_2} [measurable_space α] [normed_group β] (f : α → β) (μ : autoParam (measure α) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.measure_theory.volume_tac") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "measure_theory") "volume_tac") [])) := (lintegral μ fun (a : α) => ↑(nnnorm (f a))) < ⊤ theorem has_finite_integral_iff_norm {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] (f : α → β) : has_finite_integral f ↔ (lintegral μ fun (a : α) => ennreal.of_real (norm (f a))) < ⊤ := sorry theorem has_finite_integral_iff_edist {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] (f : α → β) : has_finite_integral f ↔ (lintegral μ fun (a : α) => edist (f a) 0) < ⊤ := sorry theorem has_finite_integral_iff_of_real {α : Type u_1} [measurable_space α] {μ : measure α} {f : α → ℝ} (h : filter.eventually_le (measure.ae μ) 0 f) : has_finite_integral f ↔ (lintegral μ fun (a : α) => ennreal.of_real (f a)) < ⊤ := sorry theorem has_finite_integral.mono {α : Type u_1} {β : Type u_2} {γ : Type u_3} [measurable_space α] {μ : measure α} [normed_group β] [normed_group γ] {f : α → β} {g : α → γ} (hg : has_finite_integral g) (h : filter.eventually (fun (a : α) => norm (f a) ≤ norm (g a)) (measure.ae μ)) : has_finite_integral f := sorry theorem has_finite_integral.mono' {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] {f : α → β} {g : α → ℝ} (hg : has_finite_integral g) (h : filter.eventually (fun (a : α) => norm (f a) ≤ g a) (measure.ae μ)) : has_finite_integral f := has_finite_integral.mono hg (filter.eventually.mono h fun (x : α) (hx : norm (f x) ≤ g x) => le_trans hx (le_abs_self (g x))) theorem has_finite_integral.congr' {α : Type u_1} {β : Type u_2} {γ : Type u_3} [measurable_space α] {μ : measure α} [normed_group β] [normed_group γ] {f : α → β} {g : α → γ} (hf : has_finite_integral f) (h : filter.eventually (fun (a : α) => norm (f a) = norm (g a)) (measure.ae μ)) : has_finite_integral g := has_finite_integral.mono hf (filter.eventually_eq.le (filter.eventually_eq.symm h)) theorem has_finite_integral_congr' {α : Type u_1} {β : Type u_2} {γ : Type u_3} [measurable_space α] {μ : measure α} [normed_group β] [normed_group γ] {f : α → β} {g : α → γ} (h : filter.eventually (fun (a : α) => norm (f a) = norm (g a)) (measure.ae μ)) : has_finite_integral f ↔ has_finite_integral g := { mp := fun (hf : has_finite_integral f) => has_finite_integral.congr' hf h, mpr := fun (hg : has_finite_integral g) => has_finite_integral.congr' hg (filter.eventually_eq.symm h) } theorem has_finite_integral.congr {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] {f : α → β} {g : α → β} (hf : has_finite_integral f) (h : filter.eventually_eq (measure.ae μ) f g) : has_finite_integral g := has_finite_integral.congr' hf (filter.eventually_eq.fun_comp h norm) theorem has_finite_integral_congr {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] {f : α → β} {g : α → β} (h : filter.eventually_eq (measure.ae μ) f g) : has_finite_integral f ↔ has_finite_integral g := has_finite_integral_congr' (filter.eventually_eq.fun_comp h norm) theorem has_finite_integral_const_iff {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] {c : β} : (has_finite_integral fun (x : α) => c) ↔ c = 0 ∨ coe_fn μ set.univ < ⊤ := sorry theorem has_finite_integral_const {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [finite_measure μ] (c : β) : has_finite_integral fun (x : α) => c := iff.mpr has_finite_integral_const_iff (Or.inr (measure_lt_top μ set.univ)) theorem has_finite_integral_of_bounded {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [finite_measure μ] {f : α → β} {C : ℝ} (hC : filter.eventually (fun (a : α) => norm (f a) ≤ C) (measure.ae μ)) : has_finite_integral f := has_finite_integral.mono' (has_finite_integral_const C) hC theorem has_finite_integral.mono_measure {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} {ν : measure α} [normed_group β] {f : α → β} (h : has_finite_integral f) (hμ : μ ≤ ν) : has_finite_integral f := lt_of_le_of_lt (lintegral_mono' hμ (le_refl fun (a : α) => ↑(nnnorm (f a)))) h theorem has_finite_integral.add_measure {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} {ν : measure α} [normed_group β] {f : α → β} (hμ : has_finite_integral f) (hν : has_finite_integral f) : has_finite_integral f := sorry theorem has_finite_integral.left_of_add_measure {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} {ν : measure α} [normed_group β] {f : α → β} (h : has_finite_integral f) : has_finite_integral f := has_finite_integral.mono_measure h (measure.le_add_right (le_refl μ)) theorem has_finite_integral.right_of_add_measure {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} {ν : measure α} [normed_group β] {f : α → β} (h : has_finite_integral f) : has_finite_integral f := has_finite_integral.mono_measure h (measure.le_add_left (le_refl ν)) @[simp] theorem has_finite_integral_add_measure {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} {ν : measure α} [normed_group β] {f : α → β} : has_finite_integral f ↔ has_finite_integral f ∧ has_finite_integral f := sorry theorem has_finite_integral.smul_measure {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] {f : α → β} (h : has_finite_integral f) {c : ennreal} (hc : c < ⊤) : has_finite_integral f := sorry @[simp] theorem has_finite_integral_zero_measure {α : Type u_1} {β : Type u_2} [measurable_space α] [normed_group β] (f : α → β) : has_finite_integral f := sorry @[simp] theorem has_finite_integral_zero (α : Type u_1) (β : Type u_2) [measurable_space α] (μ : measure α) [normed_group β] : has_finite_integral fun (a : α) => 0 := sorry theorem has_finite_integral.neg {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] {f : α → β} (hfi : has_finite_integral f) : has_finite_integral (-f) := sorry @[simp] theorem has_finite_integral_neg_iff {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] {f : α → β} : has_finite_integral (-f) ↔ has_finite_integral f := { mp := fun (h : has_finite_integral (-f)) => neg_neg f ▸ has_finite_integral.neg h, mpr := has_finite_integral.neg } theorem has_finite_integral.norm {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] {f : α → β} (hfi : has_finite_integral f) : has_finite_integral fun (a : α) => norm (f a) := sorry theorem has_finite_integral_norm_iff {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] (f : α → β) : (has_finite_integral fun (a : α) => norm (f a)) ↔ has_finite_integral f := has_finite_integral_congr' (filter.eventually_of_forall fun (x : α) => norm_norm (f x)) theorem all_ae_of_real_F_le_bound {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] {F : ℕ → α → β} {bound : α → ℝ} (h : ∀ (n : ℕ), filter.eventually (fun (a : α) => norm (F n a) ≤ bound a) (measure.ae μ)) (n : ℕ) : filter.eventually (fun (a : α) => ennreal.of_real (norm (F n a)) ≤ ennreal.of_real (bound a)) (measure.ae μ) := filter.eventually.mono (h n) fun (a : α) (h : norm (F n a) ≤ bound a) => ennreal.of_real_le_of_real h theorem all_ae_tendsto_of_real_norm {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] {F : ℕ → α → β} {f : α → β} (h : filter.eventually (fun (a : α) => filter.tendsto (fun (n : ℕ) => F n a) filter.at_top (nhds (f a))) (measure.ae μ)) : filter.eventually (fun (a : α) => filter.tendsto (fun (n : ℕ) => ennreal.of_real (norm (F n a))) filter.at_top (nhds (ennreal.of_real (norm (f a))))) (measure.ae μ) := filter.eventually.mono h fun (a : α) (h : filter.tendsto (fun (n : ℕ) => F n a) filter.at_top (nhds (f a))) => ennreal.tendsto_of_real (filter.tendsto.comp (continuous.tendsto continuous_norm (f a)) h) theorem all_ae_of_real_f_le_bound {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} (h_bound : ∀ (n : ℕ), filter.eventually (fun (a : α) => norm (F n a) ≤ bound a) (measure.ae μ)) (h_lim : filter.eventually (fun (a : α) => filter.tendsto (fun (n : ℕ) => F n a) filter.at_top (nhds (f a))) (measure.ae μ)) : filter.eventually (fun (a : α) => ennreal.of_real (norm (f a)) ≤ ennreal.of_real (bound a)) (measure.ae μ) := sorry theorem has_finite_integral_of_dominated_convergence {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} (bound_has_finite_integral : has_finite_integral bound) (h_bound : ∀ (n : ℕ), filter.eventually (fun (a : α) => norm (F n a) ≤ bound a) (measure.ae μ)) (h_lim : filter.eventually (fun (a : α) => filter.tendsto (fun (n : ℕ) => F n a) filter.at_top (nhds (f a))) (measure.ae μ)) : has_finite_integral f := sorry /- `∥F n a∥ ≤ bound a` and `∥F n a∥ --> ∥f a∥` implies `∥f a∥ ≤ bound a`, and so `∫ ∥f∥ ≤ ∫ bound < ⊤` since `bound` is has_finite_integral -/ theorem tendsto_lintegral_norm_of_dominated_convergence {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [borel_space β] [topological_space.second_countable_topology β] {F : ℕ → α → β} {f : α → β} {bound : α → ℝ} (F_measurable : ∀ (n : ℕ), ae_measurable (F n)) (f_measurable : ae_measurable f) (bound_has_finite_integral : has_finite_integral bound) (h_bound : ∀ (n : ℕ), filter.eventually (fun (a : α) => norm (F n a) ≤ bound a) (measure.ae μ)) (h_lim : filter.eventually (fun (a : α) => filter.tendsto (fun (n : ℕ) => F n a) filter.at_top (nhds (f a))) (measure.ae μ)) : filter.tendsto (fun (n : ℕ) => lintegral μ fun (a : α) => ennreal.of_real (norm (F n a - f a))) filter.at_top (nhds 0) := sorry /- `∥F n a∥ ≤ bound a` and `F n a --> f a` implies `∥f a∥ ≤ bound a`, and thus by the triangle inequality, have `∥F n a - f a∥ ≤ 2 * (bound a). -/ /- On the other hand, `F n a --> f a` implies that `∥F n a - f a∥ --> 0` -/ /- Therefore, by the dominated convergence theorem for nonnegative integration, have ` ∫ ∥f a - F n a∥ --> 0 ` -/ /-! Lemmas used for defining the positive part of a `L¹` function -/ theorem has_finite_integral.max_zero {α : Type u_1} [measurable_space α] {μ : measure α} {f : α → ℝ} (hf : has_finite_integral f) : has_finite_integral fun (a : α) => max (f a) 0 := sorry theorem has_finite_integral.min_zero {α : Type u_1} [measurable_space α] {μ : measure α} {f : α → ℝ} (hf : has_finite_integral f) : has_finite_integral fun (a : α) => min (f a) 0 := sorry theorem has_finite_integral.smul {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] {𝕜 : Type u_5} [normed_field 𝕜] [normed_space 𝕜 β] (c : 𝕜) {f : α → β} : has_finite_integral f → has_finite_integral (c • f) := sorry theorem has_finite_integral_smul_iff {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] {𝕜 : Type u_5} [normed_field 𝕜] [normed_space 𝕜 β] {c : 𝕜} (hc : c ≠ 0) (f : α → β) : has_finite_integral (c • f) ↔ has_finite_integral f := sorry theorem has_finite_integral.const_mul {α : Type u_1} [measurable_space α] {μ : measure α} {f : α → ℝ} (h : has_finite_integral f) (c : ℝ) : has_finite_integral fun (x : α) => c * f x := has_finite_integral.smul c h theorem has_finite_integral.mul_const {α : Type u_1} [measurable_space α] {μ : measure α} {f : α → ℝ} (h : has_finite_integral f) (c : ℝ) : has_finite_integral fun (x : α) => f x * c := sorry /-! ### The predicate `integrable` -/ /-- `integrable f μ` means that `f` is measurable and that the integral `∫⁻ a, ∥f a∥ ∂μ` is finite. `integrable f` means `integrable f volume`. -/ def integrable {α : Type u_1} {β : Type u_2} [measurable_space α] [normed_group β] [measurable_space β] (f : α → β) (μ : autoParam (measure α) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.measure_theory.volume_tac") (Lean.Name.mkStr (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "measure_theory") "volume_tac") [])) := ae_measurable f ∧ has_finite_integral f theorem integrable.ae_measurable {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] {f : α → β} (hf : integrable f) : ae_measurable f := and.left hf theorem integrable.has_finite_integral {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] {f : α → β} (hf : integrable f) : has_finite_integral f := and.right hf theorem integrable.mono {α : Type u_1} {β : Type u_2} {γ : Type u_3} [measurable_space α] {μ : measure α} [normed_group β] [normed_group γ] [measurable_space β] [measurable_space γ] {f : α → β} {g : α → γ} (hg : integrable g) (hf : ae_measurable f) (h : filter.eventually (fun (a : α) => norm (f a) ≤ norm (g a)) (measure.ae μ)) : integrable f := { left := hf, right := has_finite_integral.mono (integrable.has_finite_integral hg) h } theorem integrable.mono' {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] {f : α → β} {g : α → ℝ} (hg : integrable g) (hf : ae_measurable f) (h : filter.eventually (fun (a : α) => norm (f a) ≤ g a) (measure.ae μ)) : integrable f := { left := hf, right := has_finite_integral.mono' (integrable.has_finite_integral hg) h } theorem integrable.congr' {α : Type u_1} {β : Type u_2} {γ : Type u_3} [measurable_space α] {μ : measure α} [normed_group β] [normed_group γ] [measurable_space β] [measurable_space γ] {f : α → β} {g : α → γ} (hf : integrable f) (hg : ae_measurable g) (h : filter.eventually (fun (a : α) => norm (f a) = norm (g a)) (measure.ae μ)) : integrable g := { left := hg, right := has_finite_integral.congr' (integrable.has_finite_integral hf) h } theorem integrable_congr' {α : Type u_1} {β : Type u_2} {γ : Type u_3} [measurable_space α] {μ : measure α} [normed_group β] [normed_group γ] [measurable_space β] [measurable_space γ] {f : α → β} {g : α → γ} (hf : ae_measurable f) (hg : ae_measurable g) (h : filter.eventually (fun (a : α) => norm (f a) = norm (g a)) (measure.ae μ)) : integrable f ↔ integrable g := { mp := fun (h2f : integrable f) => integrable.congr' h2f hg h, mpr := fun (h2g : integrable g) => integrable.congr' h2g hf (filter.eventually_eq.symm h) } theorem integrable.congr {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] {f : α → β} {g : α → β} (hf : integrable f) (h : filter.eventually_eq (measure.ae μ) f g) : integrable g := { left := ae_measurable.congr (and.left hf) h, right := has_finite_integral.congr (and.right hf) h } theorem integrable_congr {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] {f : α → β} {g : α → β} (h : filter.eventually_eq (measure.ae μ) f g) : integrable f ↔ integrable g := { mp := fun (hf : integrable f) => integrable.congr hf h, mpr := fun (hg : integrable g) => integrable.congr hg (filter.eventually_eq.symm h) } theorem integrable_const_iff {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] {c : β} : (integrable fun (x : α) => c) ↔ c = 0 ∨ coe_fn μ set.univ < ⊤ := sorry theorem integrable_const {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [finite_measure μ] (c : β) : integrable fun (x : α) => c := iff.mpr integrable_const_iff (Or.inr (measure_lt_top μ set.univ)) theorem integrable.mono_measure {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} {ν : measure α} [normed_group β] [measurable_space β] {f : α → β} (h : integrable f) (hμ : μ ≤ ν) : integrable f := { left := ae_measurable.mono_measure (integrable.ae_measurable h) hμ, right := has_finite_integral.mono_measure (integrable.has_finite_integral h) hμ } theorem integrable.add_measure {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} {ν : measure α} [normed_group β] [measurable_space β] {f : α → β} (hμ : integrable f) (hν : integrable f) : integrable f := { left := ae_measurable.add_measure (integrable.ae_measurable hμ) (integrable.ae_measurable hν), right := has_finite_integral.add_measure (integrable.has_finite_integral hμ) (integrable.has_finite_integral hν) } theorem integrable.left_of_add_measure {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} {ν : measure α} [normed_group β] [measurable_space β] {f : α → β} (h : integrable f) : integrable f := integrable.mono_measure h (measure.le_add_right (le_refl μ)) theorem integrable.right_of_add_measure {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} {ν : measure α} [normed_group β] [measurable_space β] {f : α → β} (h : integrable f) : integrable f := integrable.mono_measure h (measure.le_add_left (le_refl ν)) @[simp] theorem integrable_add_measure {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} {ν : measure α} [normed_group β] [measurable_space β] {f : α → β} : integrable f ↔ integrable f ∧ integrable f := { mp := fun (h : integrable f) => { left := integrable.left_of_add_measure h, right := integrable.right_of_add_measure h }, mpr := fun (h : integrable f ∧ integrable f) => integrable.add_measure (and.left h) (and.right h) } theorem integrable.smul_measure {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] {f : α → β} (h : integrable f) {c : ennreal} (hc : c < ⊤) : integrable f := { left := ae_measurable.smul_measure (integrable.ae_measurable h) c, right := has_finite_integral.smul_measure (integrable.has_finite_integral h) hc } theorem integrable_map_measure {α : Type u_1} {β : Type u_2} {δ : Type u_4} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [measurable_space δ] [opens_measurable_space β] {f : α → δ} {g : δ → β} (hg : ae_measurable g) (hf : measurable f) : integrable g ↔ integrable (g ∘ f) := sorry theorem lintegral_edist_lt_top {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [opens_measurable_space β] {f : α → β} {g : α → β} (hf : integrable f) (hg : integrable g) : (lintegral μ fun (a : α) => edist (f a) (g a)) < ⊤ := sorry @[simp] theorem integrable_zero (α : Type u_1) (β : Type u_2) [measurable_space α] (μ : measure α) [normed_group β] [measurable_space β] : integrable fun (_x : α) => 0 := sorry theorem integrable.add' {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [opens_measurable_space β] {f : α → β} {g : α → β} (hf : integrable f) (hg : integrable g) : has_finite_integral (f + g) := sorry theorem integrable.add {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [borel_space β] [topological_space.second_countable_topology β] {f : α → β} {g : α → β} (hf : integrable f) (hg : integrable g) : integrable (f + g) := { left := ae_measurable.add (integrable.ae_measurable hf) (integrable.ae_measurable hg), right := integrable.add' hf hg } theorem integrable_finset_sum {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] {ι : Type u_3} [borel_space β] [topological_space.second_countable_topology β] (s : finset ι) {f : ι → α → β} (hf : ∀ (i : ι), integrable (f i)) : integrable fun (a : α) => finset.sum s fun (i : ι) => f i a := sorry theorem integrable.neg {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [borel_space β] {f : α → β} (hf : integrable f) : integrable (-f) := { left := ae_measurable.neg (integrable.ae_measurable hf), right := has_finite_integral.neg (integrable.has_finite_integral hf) } @[simp] theorem integrable_neg_iff {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [borel_space β] {f : α → β} : integrable (-f) ↔ integrable f := { mp := fun (h : integrable (-f)) => neg_neg f ▸ integrable.neg h, mpr := integrable.neg } theorem integrable.sub' {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [opens_measurable_space β] {f : α → β} {g : α → β} (hf : integrable f) (hg : integrable g) : has_finite_integral (f - g) := sorry theorem integrable.sub {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [borel_space β] [topological_space.second_countable_topology β] {f : α → β} {g : α → β} (hf : integrable f) (hg : integrable g) : integrable (f - g) := sorry theorem integrable.norm {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [opens_measurable_space β] {f : α → β} (hf : integrable f) : integrable fun (a : α) => norm (f a) := { left := ae_measurable.norm (integrable.ae_measurable hf), right := has_finite_integral.norm (integrable.has_finite_integral hf) } theorem integrable_norm_iff {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [opens_measurable_space β] {f : α → β} (hf : ae_measurable f) : (integrable fun (a : α) => norm (f a)) ↔ integrable f := sorry theorem integrable.prod_mk {α : Type u_1} {β : Type u_2} {γ : Type u_3} [measurable_space α] {μ : measure α} [normed_group β] [normed_group γ] [measurable_space β] [measurable_space γ] [opens_measurable_space β] [opens_measurable_space γ] {f : α → β} {g : α → γ} (hf : integrable f) (hg : integrable g) : integrable fun (x : α) => (f x, g x) := sorry /-! ### Lemmas used for defining the positive part of a `L¹` function -/ theorem integrable.max_zero {α : Type u_1} [measurable_space α] {μ : measure α} {f : α → ℝ} (hf : integrable f) : integrable fun (a : α) => max (f a) 0 := { left := ae_measurable.max (integrable.ae_measurable hf) (measurable.ae_measurable measurable_const), right := has_finite_integral.max_zero (integrable.has_finite_integral hf) } theorem integrable.min_zero {α : Type u_1} [measurable_space α] {μ : measure α} {f : α → ℝ} (hf : integrable f) : integrable fun (a : α) => min (f a) 0 := { left := ae_measurable.min (integrable.ae_measurable hf) (measurable.ae_measurable measurable_const), right := has_finite_integral.min_zero (integrable.has_finite_integral hf) } theorem integrable.smul {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] {𝕜 : Type u_5} [normed_field 𝕜] [normed_space 𝕜 β] [borel_space β] (c : 𝕜) {f : α → β} (hf : integrable f) : integrable (c • f) := { left := ae_measurable.const_smul (integrable.ae_measurable hf) c, right := has_finite_integral.smul c (integrable.has_finite_integral hf) } theorem integrable_smul_iff {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] {𝕜 : Type u_5} [normed_field 𝕜] [normed_space 𝕜 β] [borel_space β] {c : 𝕜} (hc : c ≠ 0) (f : α → β) : integrable (c • f) ↔ integrable f := and_congr (ae_measurable_const_smul_iff hc) (has_finite_integral_smul_iff hc f) theorem integrable.const_mul {α : Type u_1} [measurable_space α] {μ : measure α} {f : α → ℝ} (h : integrable f) (c : ℝ) : integrable fun (x : α) => c * f x := integrable.smul c h theorem integrable.mul_const {α : Type u_1} [measurable_space α] {μ : measure α} {f : α → ℝ} (h : integrable f) (c : ℝ) : integrable fun (x : α) => f x * c := sorry theorem integrable_smul_const {α : Type u_1} [measurable_space α] {μ : measure α} {𝕜 : Type u_5} [nondiscrete_normed_field 𝕜] [complete_space 𝕜] [measurable_space 𝕜] [borel_space 𝕜] {E : Type u_6} [normed_group E] [normed_space 𝕜 E] [measurable_space E] [borel_space E] {f : α → 𝕜} {c : E} (hc : c ≠ 0) : (integrable fun (x : α) => f x • c) ↔ integrable f := sorry /-! ### The predicate `integrable` on measurable functions modulo a.e.-equality -/ namespace ae_eq_fun /-- A class of almost everywhere equal functions is `integrable` if it has a finite distance to the origin. It means the same thing as the predicate `integrable` over functions. -/ def integrable {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [opens_measurable_space β] (f : ae_eq_fun α β μ) := f ∈ emetric.ball 0 ⊤ theorem integrable_mk {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [opens_measurable_space β] {f : α → β} (hf : ae_measurable f) : integrable (mk f hf) ↔ integrable f := sorry theorem integrable_coe_fn {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [opens_measurable_space β] {f : ae_eq_fun α β μ} : integrable ⇑f ↔ integrable f := sorry theorem integrable_zero {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [opens_measurable_space β] : integrable 0 := emetric.mem_ball_self ennreal.coe_lt_top theorem integrable.add {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] {f : ae_eq_fun α β μ} {g : ae_eq_fun α β μ} : integrable f → integrable g → integrable (f + g) := sorry theorem integrable.neg {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] {f : ae_eq_fun α β μ} : integrable f → integrable (-f) := sorry theorem integrable.sub {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] {f : ae_eq_fun α β μ} {g : ae_eq_fun α β μ} (hf : integrable f) (hg : integrable g) : integrable (f - g) := integrable.add hf (integrable.neg hg) protected theorem is_add_subgroup {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] : is_add_subgroup (emetric.ball 0 ⊤) := is_add_subgroup.mk fun (_x : ae_eq_fun α β μ) => integrable.neg theorem integrable.smul {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] {𝕜 : Type u_5} [normed_field 𝕜] [normed_space 𝕜 β] {c : 𝕜} {f : ae_eq_fun α β μ} : integrable f → integrable (c • f) := sorry end ae_eq_fun /-! ### The `L¹` space of functions -/ /-- The space of equivalence classes of integrable (and measurable) functions, where two integrable functions are equivalent if they agree almost everywhere, i.e., they differ on a set of measure `0`. -/ def l1 (α : Type u_1) (β : Type u_2) [measurable_space α] [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [opens_measurable_space β] (μ : measure α) := Subtype fun (f : ae_eq_fun α β μ) => ae_eq_fun.integrable f namespace l1 protected instance measure_theory.ae_eq_fun.has_coe {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [opens_measurable_space β] : has_coe (l1 α β μ) (ae_eq_fun α β μ) := Mathlib.coe_subtype protected instance has_coe_to_fun {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [opens_measurable_space β] : has_coe_to_fun (l1 α β μ) := has_coe_to_fun.mk (fun (f : l1 α β μ) => α → β) fun (f : l1 α β μ) => ⇑↑f @[simp] theorem coe_coe {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [opens_measurable_space β] (f : l1 α β μ) : ⇑↑f = ⇑f := rfl protected theorem eq {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [opens_measurable_space β] {f : l1 α β μ} {g : l1 α β μ} : ↑f = ↑g → f = g := subtype.eq protected theorem eq_iff {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [opens_measurable_space β] {f : l1 α β μ} {g : l1 α β μ} : ↑f = ↑g ↔ f = g := { mp := l1.eq, mpr := congr_arg coe } /- TODO : order structure of l1-/ /-- `L¹` space forms a `emetric_space`, with the emetric being inherited from almost everywhere functions, i.e., `edist f g = ∫⁻ a, edist (f a) (g a)`. -/ protected instance emetric_space {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [opens_measurable_space β] : emetric_space (l1 α β μ) := subtype.emetric_space /-- `L¹` space forms a `metric_space`, with the metric being inherited from almost everywhere functions, i.e., `edist f g = ennreal.to_real (∫⁻ a, edist (f a) (g a))`. -/ protected instance metric_space {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [opens_measurable_space β] : metric_space (l1 α β μ) := metric_space_emetric_ball 0 ⊤ protected instance add_comm_group {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] : add_comm_group (l1 α β μ) := subtype.add_comm_group protected instance inhabited {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] : Inhabited (l1 α β μ) := { default := 0 } @[simp] theorem coe_zero {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] : ↑0 = 0 := rfl @[simp] theorem coe_add {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) (g : l1 α β μ) : ↑(f + g) = ↑f + ↑g := rfl @[simp] theorem coe_neg {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) : ↑(-f) = -↑f := rfl @[simp] theorem coe_sub {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) (g : l1 α β μ) : ↑(f - g) = ↑f - ↑g := rfl @[simp] theorem edist_eq {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) (g : l1 α β μ) : edist f g = edist ↑f ↑g := rfl theorem dist_eq {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) (g : l1 α β μ) : dist f g = ennreal.to_real (edist ↑f ↑g) := rfl /-- The norm on `L¹` space is defined to be `∥f∥ = ∫⁻ a, edist (f a) 0`. -/ protected instance has_norm {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] : has_norm (l1 α β μ) := has_norm.mk fun (f : l1 α β μ) => dist f 0 theorem norm_eq {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) : norm f = ennreal.to_real (edist (↑f) 0) := rfl protected instance normed_group {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] : normed_group (l1 α β μ) := normed_group.of_add_dist sorry sorry protected instance has_scalar {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] {𝕜 : Type u_5} [normed_field 𝕜] [normed_space 𝕜 β] : has_scalar 𝕜 (l1 α β μ) := has_scalar.mk fun (x : 𝕜) (f : l1 α β μ) => { val := x • ↑f, property := sorry } @[simp] theorem coe_smul {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] {𝕜 : Type u_5} [normed_field 𝕜] [normed_space 𝕜 β] (c : 𝕜) (f : l1 α β μ) : ↑(c • f) = c • ↑f := rfl protected instance semimodule {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] {𝕜 : Type u_5} [normed_field 𝕜] [normed_space 𝕜 β] : semimodule 𝕜 (l1 α β μ) := semimodule.mk sorry sorry protected instance normed_space {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] {𝕜 : Type u_5} [normed_field 𝕜] [normed_space 𝕜 β] : normed_space 𝕜 (l1 α β μ) := normed_space.mk sorry /-- Construct the equivalence class `[f]` of an integrable function `f`. -/ def of_fun {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : α → β) (hf : integrable f) : l1 α β μ := { val := ae_eq_fun.mk f (integrable.ae_measurable hf), property := sorry } @[simp] theorem of_fun_eq_mk {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : α → β) (hf : integrable f) : ↑(of_fun f hf) = ae_eq_fun.mk f (integrable.ae_measurable hf) := rfl theorem of_fun_eq_of_fun {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : α → β) (g : α → β) (hf : integrable f) (hg : integrable g) : of_fun f hf = of_fun g hg ↔ filter.eventually_eq (measure.ae μ) f g := sorry theorem of_fun_zero {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] : of_fun (fun (_x : α) => 0) (integrable_zero α β μ) = 0 := rfl theorem of_fun_add {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : α → β) (g : α → β) (hf : integrable f) (hg : integrable g) : of_fun (f + g) (integrable.add hf hg) = of_fun f hf + of_fun g hg := rfl theorem of_fun_neg {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : α → β) (hf : integrable f) : of_fun (-f) (integrable.neg hf) = -of_fun f hf := rfl theorem of_fun_sub {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : α → β) (g : α → β) (hf : integrable f) (hg : integrable g) : of_fun (f - g) (integrable.sub hf hg) = of_fun f hf - of_fun g hg := sorry theorem norm_of_fun {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : α → β) (hf : integrable f) : norm (of_fun f hf) = ennreal.to_real (lintegral μ fun (a : α) => edist (f a) 0) := rfl theorem norm_of_fun_eq_lintegral_norm {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : α → β) (hf : integrable f) : norm (of_fun f hf) = ennreal.to_real (lintegral μ fun (a : α) => ennreal.of_real (norm (f a))) := sorry theorem of_fun_smul {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] {𝕜 : Type u_5} [normed_field 𝕜] [normed_space 𝕜 β] (f : α → β) (hf : integrable f) (k : 𝕜) : of_fun (fun (a : α) => k • f a) (integrable.smul k hf) = k • of_fun f hf := rfl protected theorem measurable {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) : measurable ⇑f := ae_eq_fun.measurable (subtype.val f) protected theorem ae_measurable {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) : ae_measurable ⇑f := ae_eq_fun.ae_measurable (subtype.val f) theorem measurable_norm {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) : measurable fun (a : α) => norm (coe_fn f a) := measurable.norm (l1.measurable f) protected theorem integrable {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) : integrable ⇑f := iff.mpr ae_eq_fun.integrable_coe_fn (subtype.property f) protected theorem has_finite_integral {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) : has_finite_integral ⇑f := integrable.has_finite_integral (l1.integrable f) theorem integrable_norm {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) : integrable fun (a : α) => norm (coe_fn f a) := iff.mpr (integrable_norm_iff (l1.ae_measurable f)) (l1.integrable f) theorem of_fun_to_fun {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) : of_fun (⇑f) (l1.integrable f) = f := subtype.ext (ae_eq_fun.mk_coe_fn ↑f) theorem mk_to_fun {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) : ae_eq_fun.mk (⇑f) (l1.ae_measurable f) = ↑f := sorry theorem to_fun_of_fun {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : α → β) (hf : integrable f) : filter.eventually_eq (measure.ae μ) (⇑(of_fun f hf)) f := ae_eq_fun.coe_fn_mk f (integrable.ae_measurable hf) theorem zero_to_fun (α : Type u_1) (β : Type u_2) [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] : filter.eventually_eq (measure.ae μ) (⇑0) 0 := ae_eq_fun.coe_fn_zero theorem add_to_fun {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) (g : l1 α β μ) : filter.eventually_eq (measure.ae μ) (⇑(f + g)) (⇑f + ⇑g) := ae_eq_fun.coe_fn_add ↑f ↑g theorem neg_to_fun {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) : filter.eventually_eq (measure.ae μ) (⇑(-f)) (-⇑f) := ae_eq_fun.coe_fn_neg ↑f theorem sub_to_fun {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) (g : l1 α β μ) : filter.eventually_eq (measure.ae μ) (⇑(f - g)) (⇑f - ⇑g) := ae_eq_fun.coe_fn_sub ↑f ↑g theorem dist_to_fun {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) (g : l1 α β μ) : dist f g = ennreal.to_real (lintegral μ fun (x : α) => edist (coe_fn f x) (coe_fn g x)) := sorry theorem norm_eq_nnnorm_to_fun {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) : norm f = ennreal.to_real (lintegral μ fun (a : α) => ↑(nnnorm (coe_fn f a))) := sorry theorem norm_eq_norm_to_fun {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) : norm f = ennreal.to_real (lintegral μ fun (a : α) => ennreal.of_real (norm (coe_fn f a))) := sorry theorem lintegral_edist_to_fun_lt_top {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) (g : l1 α β μ) : (lintegral μ fun (a : α) => edist (coe_fn f a) (coe_fn g a)) < ⊤ := lintegral_edist_lt_top (l1.integrable f) (l1.integrable g) theorem smul_to_fun {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] {𝕜 : Type u_5} [normed_field 𝕜] [normed_space 𝕜 β] (c : 𝕜) (f : l1 α β μ) : filter.eventually_eq (measure.ae μ) (⇑(c • f)) (c • ⇑f) := ae_eq_fun.coe_fn_smul c ↑f theorem norm_eq_lintegral {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) : norm f = ennreal.to_real (lintegral μ fun (x : α) => ↑(nnnorm (coe_fn f x))) := sorry /-- Computing the norm of a difference between two L¹-functions. Note that this is not a special case of `norm_eq_lintegral` since `(f - g) x` and `f x - g x` are not equal (but only a.e.-equal). -/ theorem norm_sub_eq_lintegral {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) (g : l1 α β μ) : norm (f - g) = ennreal.to_real (lintegral μ fun (x : α) => ↑(nnnorm (coe_fn f x - coe_fn g x))) := sorry theorem of_real_norm_eq_lintegral {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) : ennreal.of_real (norm f) = lintegral μ fun (x : α) => ↑(nnnorm (coe_fn f x)) := sorry /-- Computing the norm of a difference between two L¹-functions. Note that this is not a special case of `of_real_norm_eq_lintegral` since `(f - g) x` and `f x - g x` are not equal (but only a.e.-equal). -/ theorem of_real_norm_sub_eq_lintegral {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] (f : l1 α β μ) (g : l1 α β μ) : ennreal.of_real (norm (f - g)) = lintegral μ fun (x : α) => ↑(nnnorm (coe_fn f x - coe_fn g x)) := sorry /-- Positive part of a function in `L¹` space. -/ def pos_part {α : Type u_1} [measurable_space α] {μ : measure α} (f : l1 α ℝ μ) : l1 α ℝ μ := { val := ae_eq_fun.pos_part ↑f, property := sorry } /-- Negative part of a function in `L¹` space. -/ def neg_part {α : Type u_1} [measurable_space α] {μ : measure α} (f : l1 α ℝ μ) : l1 α ℝ μ := pos_part (-f) theorem coe_pos_part {α : Type u_1} [measurable_space α] {μ : measure α} (f : l1 α ℝ μ) : ↑(pos_part f) = ae_eq_fun.pos_part ↑f := rfl theorem pos_part_to_fun {α : Type u_1} [measurable_space α] {μ : measure α} (f : l1 α ℝ μ) : filter.eventually_eq (measure.ae μ) ⇑(pos_part f) fun (a : α) => max (coe_fn f a) 0 := ae_eq_fun.coe_fn_pos_part ↑f theorem neg_part_to_fun_eq_max {α : Type u_1} [measurable_space α] {μ : measure α} (f : l1 α ℝ μ) : filter.eventually (fun (a : α) => coe_fn (neg_part f) a = max (-coe_fn f a) 0) (measure.ae μ) := sorry theorem neg_part_to_fun_eq_min {α : Type u_1} [measurable_space α] {μ : measure α} (f : l1 α ℝ μ) : filter.eventually (fun (a : α) => coe_fn (neg_part f) a = -min (coe_fn f a) 0) (measure.ae μ) := sorry theorem norm_le_norm_of_ae_le {α : Type u_1} {β : Type u_2} [measurable_space α] {μ : measure α} [normed_group β] [measurable_space β] [topological_space.second_countable_topology β] [borel_space β] {f : l1 α β μ} {g : l1 α β μ} (h : filter.eventually (fun (a : α) => norm (coe_fn f a) ≤ norm (coe_fn g a)) (measure.ae μ)) : norm f ≤ norm g := sorry theorem continuous_pos_part {α : Type u_1} [measurable_space α] {μ : measure α} : continuous fun (f : l1 α ℝ μ) => pos_part f := sorry theorem continuous_neg_part {α : Type u_1} [measurable_space α] {μ : measure α} : continuous fun (f : l1 α ℝ μ) => neg_part f := sorry /- TODO: l1 is a complete space -/ end l1 end measure_theory theorem integrable_zero_measure {α : Type u_1} {β : Type u_2} [measurable_space α] [normed_group β] [measurable_space β] {f : α → β} : measure_theory.integrable f := measure_theory.integrable.congr (measure_theory.integrable_zero α β 0) (id (Eq.refl (coe_fn 0 (set_of fun (x : α) => 0 ≠ f x))))
72b7bb3b9865f24eb12fd817553adfa21e6a9f7f
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/linear_algebra/tensor_product_basis.lean
6bad82cf915121d22f2a2a86720db8fe9ff5b73d
[ "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,623
lean
/- Copyright (c) 2021 Jakob von Raumer. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jakob von Raumer -/ import linear_algebra.direct_sum.finsupp import linear_algebra.finsupp_vector_space /-! # Bases and dimensionality of tensor products of modules These can not go into `linear_algebra.tensor_product` since they depend on `linear_algebra.finsupp_vector_space` which in turn imports `linear_algebra.tensor_product`. -/ noncomputable theory open set linear_map submodule section comm_ring variables {R : Type*} {M : Type*} {N : Type*} {ι : Type*} {κ : Type*} variables [comm_ring R] [add_comm_group M] [module R M] [add_comm_group N] [module R N] /-- If b : ι → M and c : κ → N are bases then so is λ i, b i.1 ⊗ₜ c i.2 : ι × κ → M ⊗ N. -/ def basis.tensor_product (b : basis ι R M) (c : basis κ R N) : basis (ι × κ) R (tensor_product R M N) := finsupp.basis_single_one.map ((tensor_product.congr b.repr c.repr).trans $ (finsupp_tensor_finsupp R _ _ _ _).trans $ finsupp.lcongr (equiv.refl _) (tensor_product.lid R R)).symm end comm_ring section field variables {K : Type*} (V W : Type*) variables [field K] [add_comm_group V] [module K V] [add_comm_group W] [module K W] /-- If `V` and `W` are finite dimensional `K` vector spaces, so is `V ⊗ W`. -/ instance finite_dimensional_tensor_product [finite_dimensional K V] [finite_dimensional K W] : finite_dimensional K (tensor_product K V W) := finite_dimensional.of_fintype_basis (basis.tensor_product (basis.of_vector_space K V) (basis.of_vector_space K W)) end field
8a5459026100aadbf5fec36ace726782ba278e2e
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/logic/unnamed_724.lean
7c6d1189c2239ee0d38b44db3a5f04140ba59708
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
486
lean
import data.real.basic def fn_ub (f : ℝ → ℝ) (a : ℝ) : Prop := ∀ x, f x ≤ a def fn_lb (f : ℝ → ℝ) (a : ℝ) : Prop := ∀ x, a ≤ f x def fn_has_ub (f : ℝ → ℝ) := ∃ a, fn_ub f a def fn_has_lb (f : ℝ → ℝ) := ∃ a, fn_lb f a variables {f g : ℝ → ℝ} -- BEGIN example (lbf : fn_has_lb f) (lbg : fn_has_lb g) : fn_has_lb (λ x, f x + g x) := sorry example {c : ℝ} (ubf : fn_has_ub f) (h : c ≥ 0): fn_has_ub (λ x, c * f x) := sorry -- END
d35eabdb74f4e0fc4cf635ffc3ef4aff78b0496d
8eeb99d0fdf8125f5d39a0ce8631653f588ee817
/src/number_theory/divisors.lean
8e6615af5dfebeab1d704834dc991207cb775916
[ "Apache-2.0" ]
permissive
jesse-michael-han/mathlib
a15c58378846011b003669354cbab7062b893cfe
fa6312e4dc971985e6b7708d99a5bc3062485c89
refs/heads/master
1,625,200,760,912
1,602,081,753,000
1,602,081,753,000
181,787,230
0
0
null
1,555,460,682,000
1,555,460,682,000
null
UTF-8
Lean
false
false
5,875
lean
/- Copyright (c) 2020 Aaron Anderson. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Aaron Anderson -/ import algebra.big_operators.basic import tactic /-! # Divisor finsets This file defines sets of divisors of a natural number. This is particularly useful as background for defining Dirichlet convolution. ## Main Definitions Let `n : ℕ`. All of the following definitions are in the `nat` namespace: * `divisors n` is the `finset` of natural numbers that divide `n`. * `proper_divisors n` is the `finset` of natural numbers that divide `n`, other than `n`. * `divisors_antidiagonal n` is the `finset` of pairs `(x,y)` such that `x * y = n`. * `perfect n` is true when the sum of `proper_divisors n` is `n`. ## Implementation details * `divisors 0` is defined to be `{0}`, while `proper_divisors 0`, and `divisors_antidiagonal 0` are defined to be `∅`. ## Tags divisors, perfect numbers -/ open_locale classical open_locale big_operators namespace nat variable (n : ℕ) /-- `divisors n` is the `finset` of divisors of `n`. As a special case, `divisors 0 = {0}`. -/ def divisors : finset ℕ := finset.filter (λ x : ℕ, x ∣ n) (finset.range (n + 1)) /-- `proper_divisors n` is the `finset` of divisors of `n`, other than `n`. As a special case, `proper_divisors 0 = ∅`. -/ def proper_divisors : finset ℕ := finset.filter (λ x : ℕ, x ∣ n) (finset.range n) /-- `divisors_antidiagonal n` is the `finset` of pairs `(x,y)` such that `x * y = n`. As a special case, `divisors_antidiagonal 0 = ∅`. -/ def divisors_antidiagonal : finset (ℕ × ℕ) := ((finset.Ico 1 (n + 1)).product (finset.Ico 1 (n + 1))).filter (λ x, x.fst * x.snd = n) variable {n} lemma proper_divisors.not_self_mem : ¬ n ∈ proper_divisors n := begin rw proper_divisors, simp, end @[simp] lemma mem_proper_divisors {m : ℕ} : n ∈ proper_divisors m ↔ n ∣ m ∧ n < m := begin rw [proper_divisors, and_comm], simp, end lemma divisors_eq_proper_divisors_insert_self : divisors n = has_insert.insert n (proper_divisors n) := by rw [divisors, proper_divisors, finset.range_succ, finset.filter_insert, if_pos (dvd_refl n)] @[simp] lemma mem_divisors {m : ℕ} : n ∈ divisors m ↔ if (m = 0) then n = 0 else n ∣ m := begin cases m, { simp [divisors] }, simp only [divisors, if_neg m.succ_ne_zero, lt_succ_iff, and_iff_right_iff_imp, finset.mem_filter, finset.mem_range], exact nat.le_of_dvd (nat.succ_pos m) end lemma dvd_of_mem_divisors {m : ℕ} (h : n ∈ divisors m) : n ∣ m := begin cases m, { apply dvd_zero }, { rwa [mem_divisors, if_neg (nat.succ_ne_zero _)] at h } end @[simp] lemma mem_divisors_antidiagonal {x : ℕ × ℕ} : x ∈ divisors_antidiagonal n ↔ x.fst * x.snd = n ∧ n ≠ 0 := begin simp only [divisors_antidiagonal, finset.Ico.mem, ne.def, finset.mem_filter, finset.mem_product], rw and_comm, apply and_congr_right, rintro rfl, split; intro h, { rintro h0, linarith }, { repeat {rw [nat.add_one_le_iff, nat.pos_iff_ne_zero, ne.def, nat.lt_add_one_iff] }, rw [mul_eq_zero, decidable.not_or_iff_and_not] at h, refine ⟨⟨h.1, _⟩, ⟨h.2, _⟩⟩, exact nat.le_mul_of_pos_right (nat.pos_of_ne_zero h.2), exact nat.le_mul_of_pos_left (nat.pos_of_ne_zero h.1), } end variable {n} lemma divisor_le {m : ℕ}: n ∈ divisors m → n ≤ m := begin cases m, { simp }, simp only [mem_divisors, if_neg (nat.succ_ne_zero m)], exact nat.le_of_dvd (nat.succ_pos m), end variable (n) @[simp] lemma divisors_zero : divisors 0 = {0} := by { ext, simp } @[simp] lemma proper_divisors_zero : proper_divisors 0 = ∅ := by { ext, simp } @[simp] lemma divisors_antidiagonal_zero : divisors_antidiagonal 0 = ∅ := by { ext, simp } @[simp] lemma divisors_antidiagonal_one : divisors_antidiagonal 1 = {(1,1)} := by { ext, simp [nat.mul_eq_one_iff, prod.ext_iff], } lemma swap_mem_divisors_antidiagonal {n : ℕ} {x : ℕ × ℕ} (h : x ∈ divisors_antidiagonal n) : x.swap ∈ divisors_antidiagonal n := begin rw [mem_divisors_antidiagonal, mul_comm] at h, simpa, end lemma fst_mem_divisors_of_mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} (h : x ∈ divisors_antidiagonal n) : x.fst ∈ divisors n := begin rw mem_divisors_antidiagonal at h, simp [dvd.intro _ h.1, h.2], end lemma snd_mem_divisors_of_mem_antidiagonal {n : ℕ} {x : ℕ × ℕ} (h : x ∈ divisors_antidiagonal n) : x.snd ∈ divisors n := begin rw mem_divisors_antidiagonal at h, simp [dvd.intro_left _ h.1, h.2], end @[simp] lemma map_swap_divisors_antidiagonal {n : ℕ} : (divisors_antidiagonal n).map ⟨prod.swap, prod.swap_right_inverse.injective⟩ = divisors_antidiagonal n := begin ext, simp only [exists_prop, mem_divisors_antidiagonal, finset.mem_map, function.embedding.coe_fn_mk, ne.def, prod.swap_prod_mk, prod.exists], split, { rintros ⟨x, y, ⟨⟨rfl, h⟩, rfl⟩⟩, simp [h, mul_comm] }, { rintros ⟨rfl, h⟩, use [a.snd, a.fst], simp [h, mul_comm] } end lemma sum_divisors_eq_sum_proper_divisors_add_self : ∑ i in divisors n, i = ∑ i in proper_divisors n, i + n := begin cases n, { simp }, { rw [divisors_eq_proper_divisors_insert_self, finset.sum_insert (proper_divisors.not_self_mem), add_comm] } end /-- `n : ℕ` is perfect if and only the sum of the proper divisors of `n` is `n`. -/ def perfect (n : ℕ) : Prop := ∑ i in proper_divisors n, i = n theorem perfect_iff_sum_proper_divisors {n : ℕ} : perfect n ↔ ∑ i in proper_divisors n, i = n := iff.rfl theorem perfect_iff_sum_divisors_eq_two_mul {n : ℕ} : perfect n ↔ ∑ i in divisors n, i = 2 * n := begin rw [perfect, sum_divisors_eq_sum_proper_divisors_add_self, two_mul], split; intro h, { rw h }, { apply add_right_cancel h } end end nat
d69d9a579e984d93fc7be3dba5329488e208acde
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/data/int/bitwise.lean
3cb979f62d6c6072f9507d95c8a9c9cffa26f6d6
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
2,177
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Mario Carneiro -/ prelude import init.data.int.basic init.data.nat.bitwise universe u namespace int def div2 : ℤ → ℤ | (of_nat n) := n.div2 | -[1+ n] := -[1+ n.div2] def bodd : ℤ → bool | (of_nat n) := n.bodd | -[1+ n] := bnot (n.bodd) def bit (b : bool) : ℤ → ℤ := cond b bit1 bit0 def test_bit : ℤ → ℕ → bool | (m : ℕ) n := nat.test_bit m n | -[1+ m] n := bnot (nat.test_bit m n) def nat_bitwise (f : bool → bool → bool) (m n : ℕ) : ℤ := cond (f ff ff) -[1+ nat.bitwise (λx y, bnot (f x y)) m n] (nat.bitwise f m n) def bitwise (f : bool → bool → bool) : ℤ → ℤ → ℤ | (m : ℕ) (n : ℕ) := nat_bitwise f m n | (m : ℕ) -[1+ n] := nat_bitwise (λ x y, f x (bnot y)) m n | -[1+ m] (n : ℕ) := nat_bitwise (λ x y, f (bnot x) y) m n | -[1+ m] -[1+ n] := nat_bitwise (λ x y, f (bnot x) (bnot y)) m n def lnot : ℤ → ℤ | (m : ℕ) := -[1+ m] | -[1+ m] := m def lor : ℤ → ℤ → ℤ | (m : ℕ) (n : ℕ) := nat.lor m n | (m : ℕ) -[1+ n] := -[1+ nat.ldiff n m] | -[1+ m] (n : ℕ) := -[1+ nat.ldiff m n] | -[1+ m] -[1+ n] := -[1+ nat.land m n] def land : ℤ → ℤ → ℤ | (m : ℕ) (n : ℕ) := nat.land m n | (m : ℕ) -[1+ n] := nat.ldiff m n | -[1+ m] (n : ℕ) := nat.ldiff n m | -[1+ m] -[1+ n] := -[1+ nat.lor m n] def ldiff : ℤ → ℤ → ℤ | (m : ℕ) (n : ℕ) := nat.ldiff m n | (m : ℕ) -[1+ n] := nat.land m n | -[1+ m] (n : ℕ) := -[1+ nat.lor m n] | -[1+ m] -[1+ n] := nat.ldiff n m def lxor : ℤ → ℤ → ℤ | (m : ℕ) (n : ℕ) := nat.lxor m n | (m : ℕ) -[1+ n] := -[1+ nat.lxor m n] | -[1+ m] (n : ℕ) := -[1+ nat.lxor m n] | -[1+ m] -[1+ n] := nat.lxor m n def shiftl : ℤ → ℤ → ℤ | (m : ℕ) (n : ℕ) := nat.shiftl m n | (m : ℕ) -[1+ n] := nat.shiftr m (nat.succ n) | -[1+ m] (n : ℕ) := -[1+ nat.shiftl' tt m n] | -[1+ m] -[1+ n] := -[1+ nat.shiftr m (nat.succ n)] def shiftr (m n : ℤ) : ℤ := shiftl m (-n) end int
6cb2e0beb7844ba5c8deaf5c4f0d8c62f0875795
4950bf76e5ae40ba9f8491647d0b6f228ddce173
/src/tactic/core.lean
1f6402696899713c19d36bacbf8adc4aca7cf043
[ "Apache-2.0" ]
permissive
ntzwq/mathlib
ca50b21079b0a7c6781c34b62199a396dd00cee2
36eec1a98f22df82eaccd354a758ef8576af2a7f
refs/heads/master
1,675,193,391,478
1,607,822,996,000
1,607,822,996,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
91,807
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Simon Hudon, Scott Morrison, Keeley Hoek -/ import data.dlist.basic import logic.function.basic import control.basic import meta.expr import meta.rb_map import data.bool import tactic.binder_matching import tactic.lean_core_docs import tactic.interactive_expr import system.io universe variable u attribute [derive [has_reflect, decidable_eq]] tactic.transparency instance : has_lt pos := { lt := λ x y, (x.line, x.column) < (y.line, y.column) } namespace expr open tactic /-- Given an expr `α` representing a type with numeral structure, `of_nat α n` creates the `α`-valued numeral expression corresponding to `n`. -/ protected meta def of_nat (α : expr) : ℕ → tactic expr := nat.binary_rec (tactic.mk_mapp ``has_zero.zero [some α, none]) (λ b n tac, if n = 0 then mk_mapp ``has_one.one [some α, none] else do e ← tac, tactic.mk_app (cond b ``bit1 ``bit0) [e]) /-- Given an expr `α` representing a type with numeral structure, `of_int α n` creates the `α`-valued numeral expression corresponding to `n`. The output is either a numeral or the negation of a numeral. -/ protected meta def of_int (α : expr) : ℤ → tactic expr | (n : ℕ) := expr.of_nat α n | -[1+ n] := do e ← expr.of_nat α (n+1), tactic.mk_app ``has_neg.neg [e] /-- Generates an expression of the form `∃(args), inner`. `args` is assumed to be a list of local constants. When possible, `p ∧ q` is used instead of `∃(_ : p), q`. -/ meta def mk_exists_lst (args : list expr) (inner : expr) : tactic expr := args.mfoldr (λarg i:expr, do t ← infer_type arg, sort l ← infer_type t, return $ if arg.occurs i ∨ l ≠ level.zero then (const `Exists [l] : expr) t (i.lambdas [arg]) else (const `and [] : expr) t i) inner /-- `traverse f e` applies the monadic function `f` to the direct descendants of `e`. -/ meta def traverse {m : Type → Type u} [applicative m] {elab elab' : bool} (f : expr elab → m (expr elab')) : expr elab → m (expr elab') | (var v) := pure $ var v | (sort l) := pure $ sort l | (const n ls) := pure $ const n ls | (mvar n n' e) := mvar n n' <$> f e | (local_const n n' bi e) := local_const n n' bi <$> f e | (app e₀ e₁) := app <$> f e₀ <*> f e₁ | (lam n bi e₀ e₁) := lam n bi <$> f e₀ <*> f e₁ | (pi n bi e₀ e₁) := pi n bi <$> f e₀ <*> f e₁ | (elet n e₀ e₁ e₂) := elet n <$> f e₀ <*> f e₁ <*> f e₂ | (macro mac es) := macro mac <$> list.traverse f es /-- `mfoldl f a e` folds the monadic function `f` over the subterms of the expression `e`, with initial value `a`. -/ meta def mfoldl {α : Type} {m} [monad m] (f : α → expr → m α) : α → expr → m α | x e := prod.snd <$> (state_t.run (e.traverse $ λ e', (get >>= monad_lift ∘ flip f e' >>= put) $> e') x : m _) /-- `kreplace e old new` replaces all occurrences of the expression `old` in `e` with `new`. The occurrences of `old` in `e` are determined using keyed matching with transparency `md`; see `kabstract` for details. If `unify` is true, we may assign metavariables in `e` as we match subterms of `e` against `old`. -/ meta def kreplace (e old new : expr) (md := semireducible) (unify := tt) : tactic expr := do e ← kabstract e old md unify, pure $ e.instantiate_var new end expr namespace interaction_monad open result variables {σ : Type} {α : Type u} /-- `get_state` returns the underlying state inside an interaction monad, from within that monad. -/ -- Note that this is a generalization of `tactic.read` in core. meta def get_state : interaction_monad σ σ := λ state, success state state /-- `set_state` sets the underlying state inside an interaction monad, from within that monad. -/ -- Note that this is a generalization of `tactic.write` in core. meta def set_state (state : σ) : interaction_monad σ unit := λ _, success () state /-- `run_with_state state tac` applies `tac` to the given state `state` and returns the result, subsequently restoring the original state. If `tac` fails, then `run_with_state` does too. -/ meta def run_with_state (state : σ) (tac : interaction_monad σ α) : interaction_monad σ α := λ s, match tac state with | success val _ := success val s | exception fn pos _ := exception fn pos s end end interaction_monad namespace format /-- `join' [a,b,c]` produces the format object `abc`. It differs from `format.join` by using `format.nil` instead of `""` for the empty list. -/ meta def join' (xs : list format) : format := xs.foldl compose nil /-- `intercalate x [a, b, c]` produces the format object `a.x.b.x.c`, where `.` represents `format.join`. -/ meta def intercalate (x : format) : list format → format := join' ∘ list.intersperse x /-- `soft_break` is similar to `line`. Whereas in `group (x ++ line ++ y ++ line ++ z)` the result either fits on one line or in three, `x ++ soft_break ++ y ++ soft_break ++ z` each line break is decided independently -/ meta def soft_break : format := group line /-- Format a list as a comma separated list, without any brackets. -/ meta def comma_separated {α : Type*} [has_to_format α] : list α → format | [] := nil | xs := group (nest 1 $ intercalate ("," ++ soft_break) $ xs.map to_fmt) end format section format open format /-- format a `list` by separating elements with `soft_break` instead of `line` -/ meta def list.to_line_wrap_format {α : Type u} [has_to_format α] (l : list α) : format := bracket "[" "]" (comma_separated l) end format namespace tactic open function /-- Private work function for `add_local_consts_as_local_hyps`: given `mappings : list (expr × expr)` corresponding to pairs `(var, hyp)` of variables and the local hypothesis created as a result and `(var :: rest) : list expr` of more local variables we examine `var` to see if it contains any other variables in `rest`. If it does, we put it to the back of the queue and recurse. If it does not, then we perform replacements inside the type of `var` using the `mappings`, create a new associate local hypothesis, add this to the list of mappings, and recurse. We are done once all local hypotheses have been processed. If the list of passed local constants have types which depend on one another (which can only happen by hand-crafting the `expr`s manually), this function will loop forever. -/ private meta def add_local_consts_as_local_hyps_aux : list (expr × expr) → list expr → tactic (list (expr × expr)) | mappings [] := return mappings | mappings (var :: rest) := do /- Determine if `var` contains any local variables in the lift `rest`. -/ let is_dependent := var.local_type.fold ff $ λ e n b, if b then b else e ∈ rest, /- If so, then skip it---add it to the end of the variable queue. -/ if is_dependent then add_local_consts_as_local_hyps_aux mappings (rest ++ [var]) else do /- Otherwise, replace all of the local constants referenced by the type of `var` with the respective new corresponding local hypotheses as recorded in the list `mappings`. -/ let new_type := var.local_type.replace_subexprs mappings, /- Introduce a new local new local hypothesis `hyp` for `var`, with the correct type. -/ hyp ← assertv var.local_pp_name new_type (var.local_const_set_type new_type), /- Process the next variable in the queue, with the mapping list updated to include the local hypothesis which we just created. -/ add_local_consts_as_local_hyps_aux ((var, hyp) :: mappings) rest /-- `add_local_consts_as_local_hyps vars` add the given list `vars` of `expr.local_const`s to the tactic state. This is harder than it sounds, since the list of local constants which we have been passed can have dependencies between their types. For example, suppose we have two local constants `n : ℕ` and `h : n = 3`. Then we cannot blindly add `h` as a local hypothesis, since we need the `n` to which it refers to be the `n` created as a new local hypothesis, not the old local constant `n` with the same name. Of course, these dependencies can be nested arbitrarily deep. If the list of passed local constants have types which depend on one another (which can only happen by hand-crafting the `expr`s manually), this function will loop forever. -/ meta def add_local_consts_as_local_hyps (vars : list expr) : tactic (list (expr × expr)) := /- The `list.reverse` below is a performance optimisation since the list of available variables reported by the system is often mostly the reverse of the order in which they are dependent. -/ add_local_consts_as_local_hyps_aux [] vars.reverse.erase_dup private meta def get_expl_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_expl_pi_arity_aux new_b, if bi = binder_info.default then return (r + 1) else return r | e := return 0 /-- Compute the arity of explicit arguments of `type`. -/ meta def get_expl_pi_arity (type : expr) : tactic nat := whnf type >>= get_expl_pi_arity_aux /-- Compute the arity of explicit arguments of `fn`'s type. -/ meta def get_expl_arity (fn : expr) : tactic nat := infer_type fn >>= get_expl_pi_arity private meta def get_app_fn_args_whnf_aux (md : transparency) (unfold_ginductive : bool) : list expr → expr → tactic (expr × list expr) := λ args e, do e ← whnf e md unfold_ginductive, match e with | (expr.app t u) := get_app_fn_args_whnf_aux (u :: args) t | _ := pure (e, args) end /-- For `e = f x₁ ... xₙ`, `get_app_fn_args_whnf e` returns `(f, [x₁, ..., xₙ])`. `e` is normalised as necessary; for example: ``` get_app_fn_args_whnf `(let f := g x in f y) = (`(g), [`(x), `(y)]) ``` The returned expression is in whnf, but the arguments are generally not. -/ meta def get_app_fn_args_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic (expr × list expr) := get_app_fn_args_whnf_aux md unfold_ginductive [] e /-- `get_app_fn_whnf e md unfold_ginductive` is like `expr.get_app_fn e` but `e` is normalised as necessary (with transparency `md`). `unfold_ginductive` controls whether constructors of generalised inductive types are unfolded. The returned expression is in whnf. -/ meta def get_app_fn_whnf : expr → opt_param _ semireducible → opt_param _ tt → tactic expr | e md unfold_ginductive := do e ← whnf e md unfold_ginductive, match e with | (expr.app f _) := get_app_fn_whnf f md unfold_ginductive | _ := pure e end /-- `get_app_fn_const_whnf e md unfold_ginductive` expects that `e = C x₁ ... xₙ`, where `C` is a constant, after normalisation with transparency `md`. If so, the name of `C` is returned. Otherwise the tactic fails. `unfold_ginductive` controls whether constructors of generalised inductive types are unfolded. -/ meta def get_app_fn_const_whnf (e : expr) (md := semireducible) (unfold_ginductive := tt) : tactic name := do f ← get_app_fn_whnf e md unfold_ginductive, match f with | (expr.const n _) := pure n | _ := fail format! "expected a constant (possibly applied to some arguments), but got:\n{e}" end /-- `pis loc_consts f` is used to create a pi expression whose body is `f`. `loc_consts` should be a list of local constants. The function will abstract these local constants from `f` and bind them with pi binders. For example, if `a, b` are local constants with types `Ta, Tb`, ``pis [a, b] `(f a b)`` will return the expression `Π (a : Ta) (b : Tb), f a b`. -/ meta def pis : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← pis es f, pure $ expr.pi pp info t (expr.abstract_local f' uniq) | _ f := pure f /-- `lambdas loc_consts f` is used to create a lambda expression whose body is `f`. `loc_consts` should be a list of local constants. The function will abstract these local constants from `f` and bind them with lambda binders. For example, if `a, b` are local constants with types `Ta, Tb`, ``lambdas [a, b] `(f a b)`` will return the expression `λ (a : Ta) (b : Tb), f a b`. -/ meta def lambdas : list expr → expr → tactic expr | (e@(expr.local_const uniq pp info _) :: es) f := do t ← infer_type e, f' ← lambdas es f, pure $ expr.lam pp info t (expr.abstract_local f' uniq) | _ f := pure f -- TODO: move to `declaration` namespace in `meta/expr.lean` /-- `mk_theorem n ls t e` creates a theorem declaration with name `n`, universe parameters named `ls`, type `t`, and body `e`. -/ meta def mk_theorem (n : name) (ls : list name) (t : expr) (e : expr) : declaration := declaration.thm n ls t (task.pure e) /-- `add_theorem_by n ls type tac` uses `tac` to synthesize a term with type `type`, and adds this to the environment as a theorem with name `n` and universe parameters `ls`. -/ meta def add_theorem_by (n : name) (ls : list name) (type : expr) (tac : tactic unit) : tactic expr := do ((), body) ← solve_aux type tac, body ← instantiate_mvars body, add_decl $ mk_theorem n ls type body, return $ expr.const n $ ls.map level.param /-- `eval_expr' α e` attempts to evaluate the expression `e` in the type `α`. This is a variant of `eval_expr` in core. Due to unexplained behavior in the VM, in rare situations the latter will fail but the former will succeed. -/ meta def eval_expr' (α : Type*) [_inst_1 : reflected α] (e : expr) : tactic α := mk_app ``id [e] >>= eval_expr α /-- `mk_fresh_name` returns identifiers starting with underscores, which are not legal when emitted by tactic programs. `mk_user_fresh_name` turns the useful source of random names provided by `mk_fresh_name` into names which are usable by tactic programs. The returned name has four components which are all strings. -/ meta def mk_user_fresh_name : tactic name := do nm ← mk_fresh_name, return $ `user__ ++ nm.pop_prefix.sanitize_name ++ `user__ /-- `has_attribute' attr_name decl_name` checks whether `decl_name` exists and has attribute `attr_name`. -/ meta def has_attribute' (attr_name decl_name : name) : tactic bool := succeeds (has_attribute attr_name decl_name) /-- Checks whether the name is a simp lemma -/ meta def is_simp_lemma : name → tactic bool := has_attribute' `simp /-- Checks whether the name is an instance. -/ meta def is_instance : name → tactic bool := has_attribute' `instance /-- `local_decls` returns a dictionary mapping names to their corresponding declarations. Covers all declarations from the current file. -/ meta def local_decls : tactic (name_map declaration) := do e ← tactic.get_env, let xs := e.fold native.mk_rb_map (λ d s, if environment.in_current_file e d.to_name then s.insert d.to_name d else s), pure xs /-- `get_decls_from` returns a dictionary mapping names to their corresponding declarations. Covers all declarations the files listed in `fs`, with the current file listed as `none`. The path of the file names is expected to be relative to the root of the project (i.e. the location of `leanpkg.toml` when it is present); e.g. `"src/tactic/core.lean"` Possible issue: `get_decls_from` uses `get_cwd`, the current working directory, which may not always point at the root of the project. It would work better if it searched for the root directory or, better yet, if Lean exposed its path information. -/ meta def get_decls_from (fs : list (option string)) : tactic (name_map declaration) := do root ← unsafe_run_io $ io.env.get_cwd, let fs := fs.map (option.map $ λ path, root ++ "/" ++ path), err ← unsafe_run_io $ (fs.filter_map id).mfilter $ (<$>) bnot ∘ io.fs.file_exists, guard (err = []) <|> fail format!"File not found: {err}", e ← tactic.get_env, let xs := e.fold native.mk_rb_map (λ d s, let source := e.decl_olean d.to_name in if source ∈ fs ∧ (source = none → e.in_current_file d.to_name) then s.insert d.to_name d else s), pure xs /-- If `{nm}_{n}` doesn't exist in the environment, returns that, otherwise tries `{nm}_{n+1}` -/ meta def get_unused_decl_name_aux (e : environment) (nm : name) : ℕ → tactic name | n := let nm' := nm.append_suffix ("_" ++ to_string n) in if e.contains nm' then get_unused_decl_name_aux (n+1) else return nm' /-- Return a name which doesn't already exist in the environment. If `nm` doesn't exist, it returns that, otherwise it tries `nm_2`, `nm_3`, ... -/ meta def get_unused_decl_name (nm : name) : tactic name := get_env >>= λ e, if e.contains nm then get_unused_decl_name_aux e nm 2 else return nm /-- Returns a pair `(e, t)`, where `e ← mk_const d.to_name`, and `t = d.type` but with universe params updated to match the fresh universe metavariables in `e`. This should have the same effect as just ```lean do e ← mk_const d.to_name, t ← infer_type e, return (e, t) ``` but is hopefully faster. -/ meta def decl_mk_const (d : declaration) : tactic (expr × expr) := do subst ← d.univ_params.mmap $ λ u, prod.mk u <$> mk_meta_univ, let e : expr := expr.const d.to_name (prod.snd <$> subst), return (e, d.type.instantiate_univ_params subst) /-- Replace every universe metavariable in an expression with a universe parameter. (This is useful when making new declarations.) -/ meta def replace_univ_metas_with_univ_params (e : expr) : tactic expr := do e.list_univ_meta_vars.enum.mmap (λ n, do let n' := (`u).append_suffix ("_" ++ to_string (n.1+1)), unify (expr.sort (level.mvar n.2)) (expr.sort (level.param n'))), instantiate_mvars e /-- `mk_local n` creates a dummy local variable with name `n`. The type of this local constant is a constant with name `n`, so it is very unlikely to be a meaningful expression. -/ meta def mk_local (n : name) : expr := expr.local_const n n binder_info.default (expr.const n []) /-- `mk_psigma [x,y,z]`, with `[x,y,z]` list of local constants of types `x : tx`, `y : ty x` and `z : tz x y`, creates an expression of sigma type: `⟨x,y,z⟩ : Σ' (x : tx) (y : ty x), tz x y`. -/ meta def mk_psigma : list expr → tactic expr | [] := mk_const ``punit | [x@(expr.local_const _ _ _ _)] := pure x | (x@(expr.local_const _ _ _ _) :: xs) := do y ← mk_psigma xs, α ← infer_type x, β ← infer_type y, t ← lambdas [x] β >>= instantiate_mvars, r ← mk_mapp ``psigma.mk [α,t], pure $ r x y | _ := fail "mk_psigma expects a list of local constants" /-- Update the type of a local constant or metavariable. For local constants and metavariables obtained via, for example, `tactic.get_local`, the type stored in the expression is not necessarily the same as the type returned by `infer_type`. This tactic, given a local constant or metavariable, updates the stored type to match the output of `infer_type`. If the input is not a local constant or metavariable, `update_type` does nothing. -/ meta def update_type : expr → tactic expr | e@(expr.local_const ppname uname binfo _) := expr.local_const ppname uname binfo <$> infer_type e | e@(expr.mvar ppname uname _) := expr.mvar ppname uname <$> infer_type e | e := pure e /-- `elim_gen_prod n e _ ns` with `e` an expression of type `psigma _`, applies `cases` on `e` `n` times and uses `ns` to name the resulting variables. Returns a triple: list of new variables, remaining term and unused variable names. -/ meta def elim_gen_prod : nat → expr → list expr → list name → tactic (list expr × expr × list name) | 0 e hs ns := return (hs.reverse, e, ns) | (n + 1) e hs ns := do t ← infer_type e, if t.is_app_of `eq then return (hs.reverse, e, ns) else do [(_, [h, h'], _)] ← cases_core e (ns.take 1), elim_gen_prod n h' (h :: hs) (ns.drop 1) private meta def elim_gen_sum_aux : nat → expr → list expr → tactic (list expr × expr) | 0 e hs := return (hs, e) | (n + 1) e hs := do [(_, [h], _), (_, [h'], _)] ← induction e [], swap, elim_gen_sum_aux n h' (h::hs) /-- `elim_gen_sum n e` applies cases on `e` `n` times. `e` is assumed to be a local constant whose type is a (nested) sum `⊕`. Returns the list of local constants representing the components of `e`. -/ meta def elim_gen_sum (n : nat) (e : expr) : tactic (list expr) := do (hs, h') ← elim_gen_sum_aux n e [], gs ← get_goals, set_goals $ (gs.take (n+1)).reverse ++ gs.drop (n+1), return $ hs.reverse ++ [h'] /-- Given `elab_def`, a tactic to solve the current goal, `extract_def n trusted elab_def` will create an auxiliary definition named `n` and use it to close the goal. If `trusted` is false, it will be a meta definition. -/ meta def extract_def (n : name) (trusted : bool) (elab_def : tactic unit) : tactic unit := do cxt ← list.map expr.to_implicit_local_const <$> local_context, t ← target, (eqns,d) ← solve_aux t elab_def, d ← instantiate_mvars d, t' ← pis cxt t, d' ← lambdas cxt d, let univ := t'.collect_univ_params, add_decl $ declaration.defn n univ t' d' (reducibility_hints.regular 1 tt) trusted, applyc n /-- Attempts to close the goal with `dec_trivial`. -/ meta def exact_dec_trivial : tactic unit := `[exact dec_trivial] /-- Runs a tactic for a result, reverting the state after completion. -/ meta def retrieve {α} (tac : tactic α) : tactic α := λ s, result.cases_on (tac s) (λ a s', result.success a s) result.exception /-- Runs a tactic for a result, reverting the state after completion or error. -/ meta def retrieve' {α} (tac : tactic α) : tactic α := λ s, result.cases_on (tac s) (λ a s', result.success a s) (λ msg pos s', result.exception msg pos s) /-- Repeat a tactic at least once, calling it recursively on all subgoals, until it fails. This tactic fails if the first invocation fails. -/ meta def repeat1 (t : tactic unit) : tactic unit := t; repeat t /-- `iterate_range m n t`: Repeat the given tactic at least `m` times and at most `n` times or until `t` fails. Fails if `t` does not run at least `m` times. -/ meta def iterate_range : ℕ → ℕ → tactic unit → tactic unit | 0 0 t := skip | 0 (n+1) t := try (t >> iterate_range 0 n t) | (m+1) n t := t >> iterate_range m (n-1) t /-- Given a tactic `tac` that takes an expression and returns a new expression and a proof of equality, use that tactic to change the type of the hypotheses listed in `hs`, as well as the goal if `tgt = tt`. Returns `tt` if any types were successfully changed. -/ meta def replace_at (tac : expr → tactic (expr × expr)) (hs : list expr) (tgt : bool) : tactic bool := do to_remove ← hs.mfilter $ λ h, do { h_type ← infer_type h, succeeds $ do (new_h_type, pr) ← tac h_type, assert h.local_pp_name new_h_type, mk_eq_mp pr h >>= tactic.exact }, goal_simplified ← succeeds $ do { guard tgt, (new_t, pr) ← target >>= tac, replace_target new_t pr }, to_remove.mmap' (λ h, try (clear h)), return (¬ to_remove.empty ∨ goal_simplified) /-- `revert_after e` reverts all local constants after local constant `e`. -/ meta def revert_after (e : expr) : tactic ℕ := do l ← local_context, [pos] ← return $ l.indexes_of e | pp e >>= λ s, fail format!"No such local constant {s}", let l := l.drop pos.succ, -- all local hypotheses after `e` revert_lst l /-- `revert_target_deps` reverts all local constants on which the target depends (recursively). Returns the number of local constants that have been reverted. -/ meta def revert_target_deps : tactic ℕ := do tgt ← target, ctx ← local_context, l ← ctx.mfilter (kdepends_on tgt), n ← revert_lst l, if l = [] then return n else do m ← revert_target_deps, return (m + n) /-- `generalize' e n` generalizes the target with respect to `e`. It creates a new local constant with name `n` of the same type as `e` and replaces all occurrences of `e` by `n`. `generalize'` is similar to `generalize` but also succeeds when `e` does not occur in the goal, in which case it just calls `assert`. In contrast to `generalize` it already introduces the generalized variable. -/ meta def generalize' (e : expr) (n : name) : tactic expr := (generalize e n >> intro n) <|> note n none e /-- `intron_no_renames n` calls `intro` `n` times, using the pretty-printing name provided by the binder to name the new local constant. Unlike `intron`, it does not rename introduced constants if the names shadow existing constants. -/ meta def intron_no_renames : ℕ → tactic unit | 0 := pure () | (n+1) := do expr.pi pp_n _ _ _ ← target, intro pp_n, intron_no_renames n /-! ### Various tactics related to local definitions (local constants of the form `x : α := t`) We call `t` the value of `x`. -/ /-- `local_def_value e` returns the value of the expression `e`, assuming that `e` has been defined locally using a `let` expression. Otherwise it fails. -/ meta def local_def_value (e : expr) : tactic expr := pp e >>= λ s, -- running `pp` here, because we cannot access it in the `type_context` monad. tactic.unsafe.type_context.run $ do lctx <- tactic.unsafe.type_context.get_local_context, some ldecl <- return $ lctx.get_local_decl e.local_uniq_name | tactic.unsafe.type_context.fail format!"No such hypothesis {s}.", some let_val <- return ldecl.value | tactic.unsafe.type_context.fail format!"Variable {e} is not a local definition.", return let_val /-- `is_local_def e` succeeds when `e` is a local definition (a local constant of the form `e : α := t`) and otherwise fails. -/ meta def is_local_def (e : expr) : tactic unit := retrieve $ do revert e, expr.elet _ _ _ _ ← target, skip /-- like `split_on_p p xs`, `partition_local_deps_aux vs xs acc` searches for matches in `xs` (using membership to `vs` instead of a predicate) and breaks `xs` when matches are found. whereas `split_on_p p xs` removes the matches, `partition_local_deps_aux vs xs acc` includes them in the following partition. Also, `partition_local_deps_aux vs xs acc` discards the partition running up to the first match. -/ private def partition_local_deps_aux {α} [decidable_eq α] (vs : list α) : list α → list α → list (list α) | [] acc := [acc.reverse] | (l :: ls) acc := if l ∈ vs then acc.reverse :: partition_local_deps_aux ls [l] else partition_local_deps_aux ls (l :: acc) /-- `partition_local_deps vs`, with `vs` a list of local constants, reorders `vs` in the order they appear in the local context together with the variables that follow them. If local context is `[a,b,c,d,e,f]`, and that we call `partition_local_deps [d,b]`, we get `[[d,e,f], [b,c]]`. The head of each list is one of the variables given as a parameter. -/ meta def partition_local_deps (vs : list expr) : tactic (list (list expr)) := do ls ← local_context, pure (partition_local_deps_aux vs ls []).tail.reverse /-- `clear_value [e₀, e₁, e₂, ...]` clears the body of the local definitions `e₀`, `e₁`, `e₂`, ... changing them into regular hypotheses. A hypothesis `e : α := t` is changed to `e : α`. The order of locals `e₀`, `e₁`, `e₂` does not matter as a permutation will be chosen so as to preserve type correctness. This tactic is called `clearbody` in Coq. -/ meta def clear_value (vs : list expr) : tactic unit := do ls ← partition_local_deps vs, ls.mmap' $ λ vs, do { revert_lst vs, (expr.elet v t d b) ← target | fail format!"Cannot clear the body of {vs.head}. It is not a local definition.", let e := expr.pi v binder_info.default t b, type_check e <|> fail format!"Cannot clear the body of {vs.head}. The resulting goal is not type correct.", g ← mk_meta_var e, h ← note `h none g, tactic.exact $ h d, gs ← get_goals, set_goals $ g :: gs }, ls.reverse.mmap' $ λ vs, intro_lst $ vs.map expr.local_pp_name /-- `context_has_local_def` is true iff there is at least one local definition in the context. -/ meta def context_has_local_def : tactic bool := do ctx ← local_context, ctx.many (succeeds ∘ local_def_value) /-- `context_upto_hyp_has_local_def h` is true iff any of the hypotheses in the context up to and including `h` is a local definition. -/ meta def context_upto_hyp_has_local_def (h : expr) : tactic bool := do ff ← succeeds (local_def_value h) | pure tt, ctx ← local_context, let ctx := ctx.take_while (≠ h), ctx.many (succeeds ∘ local_def_value) /-- A variant of `simplify_bottom_up`. Given a tactic `post` for rewriting subexpressions, `simp_bottom_up post e` tries to rewrite `e` starting at the leaf nodes. Returns the resulting expression and a proof of equality. -/ meta def simp_bottom_up' (post : expr → tactic (expr × expr)) (e : expr) (cfg : simp_config := {}) : tactic (expr × expr) := prod.snd <$> simplify_bottom_up () (λ _, (<$>) (prod.mk ()) ∘ post) e cfg /-- Caches unary type classes on a type `α : Type.{univ}`. -/ meta structure instance_cache := (α : expr) (univ : level) (inst : name_map expr) /-- Creates an `instance_cache` for the type `α`. -/ meta def mk_instance_cache (α : expr) : tactic instance_cache := do u ← mk_meta_univ, infer_type α >>= unify (expr.sort (level.succ u)), u ← get_univ_assignment u, return ⟨α, u, mk_name_map⟩ namespace instance_cache /-- If `n` is the name of a type class with one parameter, `get c n` tries to find an instance of `n c.α` by checking the cache `c`. If there is no entry in the cache, it tries to find the instance via type class resolution, and updates the cache. -/ meta def get (c : instance_cache) (n : name) : tactic (instance_cache × expr) := match c.inst.find n with | some i := return (c, i) | none := do e ← mk_app n [c.α] >>= mk_instance, return (⟨c.α, c.univ, c.inst.insert n e⟩, e) end open expr /-- If `e` is a `pi` expression that binds an instance-implicit variable of type `n`, `append_typeclasses e c l` searches `c` for an instance `p` of type `n` and returns `p :: l`. -/ meta def append_typeclasses : expr → instance_cache → list expr → tactic (instance_cache × list expr) | (pi _ binder_info.inst_implicit (app (const n _) (var _)) body) c l := do (c, p) ← c.get n, return (c, p :: l) | _ c l := return (c, l) /-- Creates the application `n c.α p l`, where `p` is a type class instance found in the cache `c`. -/ meta def mk_app (c : instance_cache) (n : name) (l : list expr) : tactic (instance_cache × expr) := do d ← get_decl n, (c, l) ← append_typeclasses d.type.binding_body c l, return (c, (expr.const n [c.univ]).mk_app (c.α :: l)) /-- `c.of_nat n` creates the `c.α`-valued numeral expression corresponding to `n`. -/ protected meta def of_nat (c : instance_cache) (n : ℕ) : tactic (instance_cache × expr) := if n = 0 then c.mk_app ``has_zero.zero [] else do (c, ai) ← c.get ``has_add, (c, oi) ← c.get ``has_one, (c, one) ← c.mk_app ``has_one.one [], return (c, n.binary_rec one $ λ b n e, if n = 0 then one else cond b ((expr.const ``bit1 [c.univ]).mk_app [c.α, oi, ai, e]) ((expr.const ``bit0 [c.univ]).mk_app [c.α, ai, e])) /-- `c.of_int n` creates the `c.α`-valued numeral expression corresponding to `n`. The output is either a numeral or the negation of a numeral. -/ protected meta def of_int (c : instance_cache) : ℤ → tactic (instance_cache × expr) | (n : ℕ) := c.of_nat n | -[1+ n] := do (c, e) ← c.of_nat (n+1), c.mk_app ``has_neg.neg [e] end instance_cache /-- A variation on `assert` where a (possibly incomplete) proof of the assertion is provided as a parameter. ``(h,gs) ← local_proof `h p tac`` creates a local `h : p` and use `tac` to (partially) construct a proof for it. `gs` is the list of remaining goals in the proof of `h`. The benefits over assert are: - unlike with ``h ← assert `h p, tac`` , `h` cannot be used by `tac`; - when `tac` does not complete the proof of `h`, returning the list of goals allows one to write a tactic using `h` and with the confidence that a proof will not boil over to goals left over from the proof of `h`, unlike what would be the case when using `tactic.swap`. -/ meta def local_proof (h : name) (p : expr) (tac₀ : tactic unit) : tactic (expr × list expr) := focus1 $ do h' ← assert h p, [g₀,g₁] ← get_goals, set_goals [g₀], tac₀, gs ← get_goals, set_goals [g₁], return (h', gs) /-- `var_names e` returns a list of the unique names of the initial pi bindings in `e`. -/ meta def var_names : expr → list name | (expr.pi n _ _ b) := n :: var_names b | _ := [] /-- When `struct_n` is the name of a structure type, `subobject_names struct_n` returns two lists of names `(instances, fields)`. The names in `instances` are the projections from `struct_n` to the structures that it extends (assuming it was defined with `old_structure_cmd false`). The names in `fields` are the standard fields of `struct_n`. -/ meta def subobject_names (struct_n : name) : tactic (list name × list name) := do env ← get_env, c ← match env.constructors_of struct_n with | [c] := pure c | [] := if env.is_inductive struct_n then fail format!"{struct_n} does not have constructors" else fail format!"{struct_n} is not an inductive type" | _ := fail "too many constructors" end, vs ← var_names <$> (mk_const c >>= infer_type), fields ← env.structure_fields struct_n, return $ fields.partition (λ fn, ↑("_" ++ fn.to_string) ∈ vs) private meta def expanded_field_list' : name → tactic (dlist $ name × name) | struct_n := do (so,fs) ← subobject_names struct_n, ts ← so.mmap (λ n, do (_, e) ← mk_const (n.update_prefix struct_n) >>= infer_type >>= open_pis, expanded_field_list' $ e.get_app_fn.const_name), return $ dlist.join ts ++ dlist.of_list (fs.map $ prod.mk struct_n) open functor function /-- `expanded_field_list struct_n` produces a list of the names of the fields of the structure named `struct_n`. These are returned as pairs of names `(prefix, name)`, where the full name of the projection is `prefix.name`. `struct_n` cannot be a synonym for a `structure`, it must be itself a `structure` -/ meta def expanded_field_list (struct_n : name) : tactic (list $ name × name) := dlist.to_list <$> expanded_field_list' struct_n /-- Return a list of all type classes which can be instantiated for the given expression. -/ meta def get_classes (e : expr) : tactic (list name) := attribute.get_instances `class >>= list.mfilter (λ n, succeeds $ mk_app n [e] >>= mk_instance) /-- Finds an instance of an implication `cond → tgt`. Returns a pair of a local constant `e` of type `cond`, and an instance of `tgt` that can mention `e`. The local constant `e` is added as an hypothesis to the tactic state, but should not be used, since it has been "proven" by a metavariable. -/ meta def mk_conditional_instance (cond tgt : expr) : tactic (expr × expr) := do f ← mk_meta_var cond, e ← assertv `c cond f, swap, reset_instance_cache, inst ← mk_instance tgt, return (e, inst) open nat /-- Create a list of `n` fresh metavariables. -/ meta def mk_mvar_list : ℕ → tactic (list expr) | 0 := pure [] | (succ n) := (::) <$> mk_mvar <*> mk_mvar_list n /-- Returns the only goal, or fails if there isn't just one goal. -/ meta def get_goal : tactic expr := do gs ← get_goals, match gs with | [a] := return a | [] := fail "there are no goals" | _ := fail "there are too many goals" end /-- `iterate_at_most_on_all_goals n t`: repeat the given tactic at most `n` times on all goals, or until it fails. Always succeeds. -/ meta def iterate_at_most_on_all_goals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := tactic.all_goals' $ (do tac, iterate_at_most_on_all_goals n tac) <|> skip /-- `iterate_at_most_on_subgoals n t`: repeat the tactic `t` at most `n` times on the first goal and on all subgoals thus produced, or until it fails. Fails iff `t` fails on current goal. -/ meta def iterate_at_most_on_subgoals : nat → tactic unit → tactic unit | 0 tac := trace "maximal iterations reached" | (succ n) tac := focus1 (do tac, iterate_at_most_on_all_goals n tac) /-- This makes sure that the execution of the tactic does not change the tactic state. This can be helpful while using rewrite, apply, or expr munging. Remember to instantiate your metavariables before you're done! -/ meta def lock_tactic_state {α} (t : tactic α) : tactic α | s := match t s with | result.success a s' := result.success a s | result.exception msg pos s' := result.exception msg pos s end /-- `apply_list l`, for `l : list (tactic expr)`, tries to apply the lemmas generated by the tactics in `l` on the first goal, and fail if none succeeds. -/ meta def apply_list_expr (opt : apply_cfg) : list (tactic expr) → tactic unit | [] := fail "no matching rule" | (h::t) := (do e ← h, interactive.concat_tags (apply e opt)) <|> apply_list_expr t /-- Constructs a list of `tactic expr` given a list of p-expressions, as follows: - if the p-expression is the name of a theorem, use `i_to_expr_for_apply` on it - if the p-expression is a user attribute, add all the theorems with this attribute to the list. We need to return a list of `tactic expr`, rather than just `expr`, because these expressions will be repeatedly applied against goals, and we need to ensure that metavariables don't get stuck. -/ meta def build_list_expr_for_apply : list pexpr → tactic (list (tactic expr)) | [] := return [] | (h::t) := do tail ← build_list_expr_for_apply t, a ← i_to_expr_for_apply h, (do l ← attribute.get_instances (expr.const_name a), m ← l.mmap (λ n, _root_.to_pexpr <$> mk_const n), -- We reverse the list of lemmas marked with an attribute, -- on the assumption that lemmas proved earlier are more often applicable -- than lemmas proved later. This is a performance optimization. build_list_expr_for_apply (m.reverse ++ t)) <|> return ((i_to_expr_for_apply h) :: tail) /--`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. Unlike `solve_by_elim`, `apply_rules` does not do any backtracking, and just greedily applies a lemma from the list until it can't. -/ meta def apply_rules (hs : list pexpr) (n : nat) (opt : apply_cfg) : tactic unit := do l ← lock_tactic_state $ build_list_expr_for_apply hs, iterate_at_most_on_subgoals n (assumption <|> apply_list_expr opt l) /-- `replace h p` elaborates the pexpr `p`, clears the existing hypothesis named `h` from the local context, and adds a new hypothesis named `h`. The type of this hypothesis is the type of `p`. Fails if there is nothing named `h` in the local context. -/ meta def replace (h : name) (p : pexpr) : tactic unit := do h' ← get_local h, p ← to_expr p, note h none p, clear h' /-- Auxiliary function for `iff_mp` and `iff_mpr`. Takes a name, which should be either `` `iff.mp`` or `` `iff.mpr``. If the passed expression is an iterated function type eventually producing an `iff`, returns an expression with the `iff` converted to either the forwards or backwards implication, as requested. -/ meta def mk_iff_mp_app (iffmp : name) : expr → (nat → expr) → option expr | (expr.pi n bi e t) f := expr.lam n bi e <$> mk_iff_mp_app t (λ n, f (n+1) (expr.var n)) | `(%%a ↔ %%b) f := some $ @expr.const tt iffmp [] a b (f 0) | _ f := none /-- `iff_mp_core e ty` assumes that `ty` is the type of `e`. If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., A → B`. -/ meta def iff_mp_core (e ty: expr) : option expr := mk_iff_mp_app `iff.mp ty (λ_, e) /-- `iff_mpr_core e ty` assumes that `ty` is the type of `e`. If `ty` has the shape `Π ..., A ↔ B`, returns an expression whose type is `Π ..., B → A`. -/ meta def iff_mpr_core (e ty: expr) : option expr := mk_iff_mp_app `iff.mpr ty (λ_, e) /-- Given an expression whose type is (a possibly iterated function producing) an `iff`, create the expression which is the forward implication. -/ meta def iff_mp (e : expr) : tactic expr := do t ← infer_type e, iff_mp_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`" /-- Given an expression whose type is (a possibly iterated function producing) an `iff`, create the expression which is the reverse implication. -/ meta def iff_mpr (e : expr) : tactic expr := do t ← infer_type e, iff_mpr_core e t <|> fail "Target theorem must have the form `Π x y z, a ↔ b`" /-- Attempts to apply `e`, and if that fails, if `e` is an `iff`, try applying both directions separately. -/ meta def apply_iff (e : expr) : tactic (list (name × expr)) := let ap e := tactic.apply e {new_goals := new_goals.non_dep_only} in ap e <|> (iff_mp e >>= ap) <|> (iff_mpr e >>= ap) /-- Configuration options for `apply_any`: * `use_symmetry`: if `apply_any` fails to apply any lemma, call `symmetry` and try again. * `use_exfalso`: if `apply_any` fails to apply any lemma, call `exfalso` and try again. * `apply`: specify an alternative to `tactic.apply`; usually `apply := tactic.eapply`. -/ meta structure apply_any_opt extends apply_cfg := (use_symmetry : bool := tt) (use_exfalso : bool := tt) /-- This is a version of `apply_any` that takes a list of `tactic expr`s instead of `expr`s, and evaluates these as thunks before trying to apply them. We need to do this to avoid metavariables getting stuck during subsequent rounds of `apply`. -/ meta def apply_any_thunk (lemmas : list (tactic expr)) (opt : apply_any_opt := {}) (tac : tactic unit := skip) (on_success : expr → tactic unit := (λ _, skip)) (on_failure : tactic unit := skip) : tactic unit := do let modes := [skip] ++ (if opt.use_symmetry then [symmetry] else []) ++ (if opt.use_exfalso then [exfalso] else []), modes.any_of (λ m, do m, lemmas.any_of (λ H, H >>= (λ e, do apply e opt.to_apply_cfg, on_success e, tac))) <|> (on_failure >> fail "apply_any tactic failed; no lemma could be applied") /-- `apply_any lemmas` tries to apply one of the list `lemmas` to the current goal. `apply_any lemmas opt` allows control over how lemmas are applied. `opt` has fields: * `use_symmetry`: if no lemma applies, call `symmetry` and try again. (Defaults to `tt`.) * `use_exfalso`: if no lemma applies, call `exfalso` and try again. (Defaults to `tt`.) * `apply`: use a tactic other than `tactic.apply` (e.g. `tactic.fapply` or `tactic.eapply`). `apply_any lemmas tac` calls the tactic `tac` after a successful application. Defaults to `skip`. This is used, for example, by `solve_by_elim` to arrange recursive invocations of `apply_any`. -/ meta def apply_any (lemmas : list expr) (opt : apply_any_opt := {}) (tac : tactic unit := skip) : tactic unit := apply_any_thunk (lemmas.map pure) opt tac /-- Try to apply a hypothesis from the local context to the goal. -/ meta def apply_assumption : tactic unit := local_context >>= apply_any /-- `change_core e none` is equivalent to `change e`. It tries to change the goal to `e` and fails if this is not a definitional equality. `change_core e (some h)` assumes `h` is a local constant, and tries to change the type of `h` to `e` by reverting `h`, changing the goal, and reintroducing hypotheses. -/ meta def change_core (e : expr) : option expr → tactic unit | none := tactic.change e | (some h) := do num_reverted : ℕ ← revert h, expr.pi n bi d b ← target, tactic.change $ expr.pi n bi e b, intron num_reverted /-- `change_with_at olde newe hyp` replaces occurences of `olde` with `newe` at hypothesis `hyp`, assuming `olde` and `newe` are defeq when elaborated. -/ meta def change_with_at (olde newe : pexpr) (hyp : name) : tactic unit := do h ← get_local hyp, tp ← infer_type h, olde ← to_expr olde, newe ← to_expr newe, let repl_tp := tp.replace (λ a n, if a = olde then some newe else none), when (repl_tp ≠ tp) $ change_core repl_tp (some h) /-- Returns a list of all metavariables in the current partial proof. This can differ from the list of goals, since the goals can be manually edited. -/ meta def metavariables : tactic (list expr) := expr.list_meta_vars <$> result /-- `sorry_if_contains_sorry` will solve any goal already containing `sorry` in its type with `sorry`, and fail otherwise. -/ meta def sorry_if_contains_sorry : tactic unit := do g ← target, guard g.contains_sorry <|> fail "goal does not contain `sorrry`", tactic.admit /-- Fail if the target contains a metavariable. -/ meta def no_mvars_in_target : tactic unit := expr.has_meta_var <$> target >>= guardb ∘ bnot /-- Succeeds only if the current goal is a proposition. -/ meta def propositional_goal : tactic unit := do g :: _ ← get_goals, is_proof g >>= guardb /-- Succeeds only if we can construct an instance showing the current goal is a subsingleton type. -/ meta def subsingleton_goal : tactic unit := do g :: _ ← get_goals, ty ← infer_type g >>= instantiate_mvars, to_expr ``(subsingleton %%ty) >>= mk_instance >> skip /-- Succeeds only if the current goal is "terminal", in the sense that no other goals depend on it (except possibly through shared metavariables; see `independent_goal`). -/ meta def terminal_goal : tactic unit := propositional_goal <|> subsingleton_goal <|> do g₀ :: _ ← get_goals, mvars ← (λ L, list.erase L g₀) <$> metavariables, mvars.mmap' $ λ g, do t ← infer_type g >>= instantiate_mvars, d ← kdepends_on t g₀, monad.whenb d $ pp t >>= λ s, fail ("The current goal is not terminal: " ++ s.to_string ++ " depends on it.") /-- Succeeds only if the current goal is "independent", in the sense that no other goals depend on it, even through shared meta-variables. -/ meta def independent_goal : tactic unit := no_mvars_in_target >> terminal_goal /-- `triv'` tries to close the first goal with the proof `trivial : true`. Unlike `triv`, it only unfolds reducible definitions, so it sometimes fails faster. -/ meta def triv' : tactic unit := do c ← mk_const `trivial, exact c reducible variable {α : Type} /-- Apply a tactic as many times as possible, collecting the results in a list. Fail if the tactic does not succeed at least once. -/ meta def iterate1 (t : tactic α) : tactic (list α) := do r ← decorate_ex "iterate1 failed: tactic did not succeed" t, L ← iterate t, return (r :: L) /-- Introduces one or more variables and returns the new local constants. Fails if `intro` cannot be applied. -/ meta def intros1 : tactic (list expr) := iterate1 intro1 /-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/ meta def under_binders {α : Type} (t : tactic α) : tactic α := do v ← intros, r ← t, revert_lst v, return r namespace interactive /-- Run a tactic "under binders", by running `intros` before, and `revert` afterwards. -/ meta def under_binders (i : itactic) : itactic := tactic.under_binders i end interactive /-- `successes` invokes each tactic in turn, returning the list of successful results. -/ meta def successes (tactics : list (tactic α)) : tactic (list α) := list.filter_map id <$> monad.sequence (tactics.map (λ t, try_core t)) /-- Try all the tactics in a list, each time starting at the original `tactic_state`, returning the list of successful results, and reverting to the original `tactic_state`. -/ -- Note this is not the same as `successes`, which keeps track of the evolving `tactic_state`. meta def try_all {α : Type} (tactics : list (tactic α)) : tactic (list α) := λ s, result.success (tactics.map $ λ t : tactic α, match t s with | result.success a s' := [a] | _ := [] end).join s /-- Try all the tactics in a list, each time starting at the original `tactic_state`, returning the list of successful results sorted by the value produced by a subsequent execution of the `sort_by` tactic, and reverting to the original `tactic_state`. -/ meta def try_all_sorted {α : Type} (tactics : list (tactic α)) (sort_by : tactic ℕ := num_goals) : tactic (list (α × ℕ)) := λ s, result.success ((tactics.map $ λ t : tactic α, match (do a ← t, n ← sort_by, return (a, n)) s with | result.success a s' := [a] | _ := [] end).join.qsort (λ p q : α × ℕ, p.2 < q.2)) s /-- Return target after instantiating metavars and whnf. -/ private meta def target' : tactic expr := target >>= instantiate_mvars >>= whnf /-- Just like `split`, `fsplit` applies the constructor when the type of the target is an inductive data type with one constructor. However it does not reorder goals or invoke `auto_param` tactics. -/ -- FIXME check if we can remove `auto_param := ff` meta def fsplit : tactic unit := do [c] ← target' >>= get_constructors_for | fail "fsplit tactic failed, target is not an inductive datatype with only one constructor", mk_const c >>= λ e, apply e {new_goals := new_goals.all, auto_param := ff} >> skip run_cmd add_interactive [`fsplit] add_tactic_doc { name := "fsplit", category := doc_category.tactic, decl_names := [`tactic.interactive.fsplit], tags := ["logic", "goal management"] } /-- Calls `injection` on each hypothesis, and then, for each hypothesis on which `injection` succeeds, clears the old hypothesis. -/ meta def injections_and_clear : tactic unit := do l ← local_context, results ← successes $ l.map $ λ e, injection e >> clear e, when (results.empty) (fail "could not use `injection` then `clear` on any hypothesis") run_cmd add_interactive [`injections_and_clear] add_tactic_doc { name := "injections_and_clear", category := doc_category.tactic, decl_names := [`tactic.interactive.injections_and_clear], tags := ["context management"] } /-- Calls `cases` on every local hypothesis, succeeding if it succeeds on at least one hypothesis. -/ meta def case_bash : tactic unit := do l ← local_context, r ← successes (l.reverse.map (λ h, cases h >> skip)), when (r.empty) failed /-- `note_anon t v`, given a proof `v : t`, adds `h : t` to the current context, where the name `h` is fresh. `note_anon none v` will infer the type `t` from `v`. -/ -- While `note` provides a default value for `t`, it doesn't seem this could ever be used. meta def note_anon (t : option expr) (v : expr) : tactic expr := do h ← get_unused_name `h none, note h t v /-- `find_local t` returns a local constant with type t, or fails if none exists. -/ meta def find_local (t : pexpr) : tactic expr := do t' ← to_expr t, (prod.snd <$> solve_aux t' assumption >>= instantiate_mvars) <|> fail format!"No hypothesis found of the form: {t'}" /-- `dependent_pose_core l`: introduce dependent hypotheses, where the proofs depend on the values of the previous local constants. `l` is a list of local constants and their values. -/ meta def dependent_pose_core (l : list (expr × expr)) : tactic unit := do let lc := l.map prod.fst, let lm := l.map (λ⟨l, v⟩, (l.local_uniq_name, v)), old::other_goals ← get_goals, t ← infer_type old, new_goal ← mk_meta_var (t.pis lc), set_goals (old :: new_goal :: other_goals), exact ((new_goal.mk_app lc).instantiate_locals lm), return () /-- Instantiates metavariables that appear in the current goal. -/ meta def instantiate_mvars_in_target : tactic unit := target >>= instantiate_mvars >>= change /-- Instantiates metavariables in all goals. -/ meta def instantiate_mvars_in_goals : tactic unit := all_goals' $ instantiate_mvars_in_target /-- Protect the declaration `n` -/ meta def mk_protected (n : name) : tactic unit := do env ← get_env, set_env (env.mk_protected n) end tactic namespace lean.parser open tactic interaction_monad /-- `emit_command_here str` behaves as if the string `str` were placed as a user command at the current line. -/ meta def emit_command_here (str : string) : lean.parser string := do (_, left) ← with_input command_like str, return left /-- Inner recursion for `emit_code_here`. -/ meta def emit_code_here_aux : string → ℕ → lean.parser unit | str slen := do left ← emit_command_here str, let llen := left.length, when (llen < slen ∧ llen ≠ 0) (emit_code_here_aux left llen) /-- `emit_code_here str` behaves as if the string `str` were placed at the current location in source code. -/ meta def emit_code_here (s : string) : lean.parser unit := emit_code_here_aux s s.length /-- `run_parser p` is like `run_cmd` but for the parser monad. It executes parser `p` at the top level, giving access to operations like `emit_code_here`. -/ @[user_command] meta def run_parser_cmd (_ : interactive.parse $ tk "run_parser") : lean.parser unit := do e ← lean.parser.pexpr 0, p ← eval_pexpr (lean.parser unit) e, p add_tactic_doc { name := "run_parser", category := doc_category.cmd, decl_names := [``run_parser_cmd], tags := ["parsing"] } /-- `get_current_namespace` returns the current namespace (it could be `name.anonymous`). This function deserves a C++ implementation in core lean, and will fail if it is not called from the body of a command (i.e. anywhere else that the `lean.parser` monad can be invoked). -/ meta def get_current_namespace : lean.parser name := do n ← tactic.mk_user_fresh_name, emit_code_here $ sformat!"def {n} := ()", nfull ← tactic.resolve_constant n, return $ nfull.get_nth_prefix n.components.length /-- `get_variables` returns a list of existing variable names, along with their types and binder info. -/ meta def get_variables : lean.parser (list (name × binder_info × expr)) := list.map expr.get_local_const_kind <$> list_available_include_vars /-- `get_included_variables` returns those variables `v` returned by `get_variables` which have been "included" by an `include v` statement and are not (yet) `omit`ed. -/ meta def get_included_variables : lean.parser (list (name × binder_info × expr)) := do ns ← list_include_var_names, list.filter (λ v, v.1 ∈ ns) <$> get_variables /-- From the `lean.parser` monad, synthesize a `tactic_state` which includes all of the local variables referenced in `es : list pexpr`, and those variables which have been `include`ed in the local context---precisely those variables which would be ambiently accessible if we were in a tactic-mode block where the goals had types `es.mmap to_expr`, for example. Returns a new `ts : tactic_state` with these local variables added, and `mappings : list (expr × expr)`, for which pairs `(var, hyp)` correspond to an existing variable `var` and the local hypothesis `hyp` which was added to the tactic state `ts` as a result. -/ meta def synthesize_tactic_state_with_variables_as_hyps (es : list pexpr) : lean.parser (tactic_state × list (expr × expr)) := do /- First, in order to get `to_expr e` to resolve declared `variables`, we add all of the declared variables to a fake `tactic_state`, and perform the resolution. At the end, `to_expr e` has done the work of determining which variables were actually referenced, which we then obtain from `fe` via `expr.list_local_consts` (which, importantly, is not defined for `pexpr`s). -/ vars ← list_available_include_vars, fake_es ← lean.parser.of_tactic $ lock_tactic_state $ do { /- Note that `add_local_consts_as_local_hyps` returns the mappings it generated, but we discard them on this first pass. (We return the mappings generated by our second invocation of this function below.) -/ add_local_consts_as_local_hyps vars, es.mmap to_expr }, /- Now calculate lists of a) the explicitly `include`ed variables and b) the variables which were referenced in `e` when it was resolved to `fake_e`. It is important that we include variables of the kind a) because we want `simp` to have access to declared local instances, and it is important that we only restrict to variables of kind a) and b) together since we do not to recognise a hypothesis which is posited as a `variable` in the environment but not referenced in the `pexpr` we were passed. One use case for this behaviour is running `simp` on the passed `pexpr`, since we do not want simp to use arbitrary hypotheses which were declared as `variables` in the local environment but not referenced in the expression to simplify (as one would be expect generally in tactic mode). -/ included_vars ← list_include_var_names, let referenced_vars := list.join $ fake_es.map $ λ e, e.list_local_consts.map expr.local_pp_name, /- Look up the explicit `included_vars` and the `referenced_vars` (which have appeared in the `pexpr` list which we were passed.) -/ let directly_included_vars := vars.filter $ λ var, (var.local_pp_name ∈ included_vars) ∨ (var.local_pp_name ∈ referenced_vars), /- Inflate the list `directly_included_vars` to include those variables which are "implicitly included" by virtue of reference to one or multiple others. For example, given `variables (n : ℕ) [prime n] [ih : even n]`, a reference to `n` implies that the typeclass instance `prime n` should be included, but `ih : even n` should not. -/ let all_implicitly_included_vars := expr.all_implicitly_included_variables vars directly_included_vars, /- Capture a tactic state where both of these kinds of variables have been added as local hypotheses, and resolve `e` against this state with `to_expr`, this time for real. -/ lean.parser.of_tactic $ do { mappings ← add_local_consts_as_local_hyps all_implicitly_included_vars, ts ← get_state, return (ts, mappings) } end lean.parser namespace tactic variables {α : Type} /-- Hole command used to fill in a structure's field when specifying an instance. In the following: ```lean instance : monad id := {! !} ``` invoking the hole command "Instance Stub" ("Generate a skeleton for the structure under construction.") produces: ```lean instance : monad id := { map := _, map_const := _, pure := _, seq := _, seq_left := _, seq_right := _, bind := _ } ``` -/ @[hole_command] meta def instance_stub : hole_command := { name := "Instance Stub", descr := "Generate a skeleton for the structure under construction.", action := λ _, do tgt ← target >>= whnf, let cl := tgt.get_app_fn.const_name, env ← get_env, fs ← expanded_field_list cl, let fs := fs.map prod.snd, let fs := format.intercalate (",\n " : format) $ fs.map (λ fn, format!"{fn} := _"), let out := format.to_string format!"{{ {fs} }", return [(out,"")] } add_tactic_doc { name := "instance_stub", category := doc_category.hole_cmd, decl_names := [`tactic.instance_stub], tags := ["instances"] } /-- Like `resolve_name` except when the list of goals is empty. In that situation `resolve_name` fails whereas `resolve_name'` simply proceeds on a dummy goal -/ meta def resolve_name' (n : name) : tactic pexpr := do [] ← get_goals | resolve_name n, g ← mk_mvar, set_goals [g], resolve_name n <* set_goals [] private meta def strip_prefix' (n : name) : list string → name → tactic name | s name.anonymous := pure $ s.foldl (flip name.mk_string) name.anonymous | s (name.mk_string a p) := do let n' := s.foldl (flip name.mk_string) name.anonymous, do { n'' ← tactic.resolve_constant n', if n'' = n then pure n' else strip_prefix' (a :: s) p } <|> strip_prefix' (a :: s) p | s n@(name.mk_numeral a p) := pure $ s.foldl (flip name.mk_string) n /-- Strips unnecessary prefixes from a name, e.g. if a namespace is open. -/ meta def strip_prefix : name → tactic name | n@(name.mk_string a a_1) := if (`_private).is_prefix_of n then let n' := n.update_prefix name.anonymous in n' <$ resolve_name' n' <|> pure n else strip_prefix' n [a] a_1 | n := pure n /-- Used to format return strings for the hole commands `match_stub` and `eqn_stub`. -/ meta def mk_patterns (t : expr) : tactic (list format) := do let cl := t.get_app_fn.const_name, env ← get_env, let fs := env.constructors_of cl, fs.mmap $ λ f, do { (vs,_) ← mk_const f >>= infer_type >>= open_pis, let vs := vs.filter (λ v, v.is_default_local), vs ← vs.mmap (λ v, do v' ← get_unused_name v.local_pp_name, pose v' none `(()), pure v' ), vs.mmap' $ λ v, get_local v >>= clear, let args := list.intersperse (" " : format) $ vs.map to_fmt, f ← strip_prefix f, if args.empty then pure $ format!"| {f} := _\n" else pure format!"| ({f} {format.join args}) := _\n" } /-- Hole command used to generate a `match` expression. In the following: ```lean meta def foo (e : expr) : tactic unit := {! e !} ``` invoking hole command "Match Stub" ("Generate a list of equations for a `match` expression") produces: ```lean meta def foo (e : expr) : tactic unit := match e with | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ end ``` -/ @[hole_command] meta def match_stub : hole_command := { name := "Match Stub", descr := "Generate a list of equations for a `match` expression.", action := λ es, do [e] ← pure es | fail "expecting one expression", e ← to_expr e, t ← infer_type e >>= whnf, fs ← mk_patterns t, e ← pp e, let out := format.to_string format!"match {e} with\n{format.join fs}end\n", return [(out,"")] } add_tactic_doc { name := "Match Stub", category := doc_category.hole_cmd, decl_names := [`tactic.match_stub], tags := ["pattern matching"] } /-- Invoking hole command "Equations Stub" ("Generate a list of equations for a recursive definition") in the following: ```lean meta def foo : {! expr → tactic unit !} -- `:=` is omitted ``` produces: ```lean meta def foo : expr → tactic unit | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ ``` A similar result can be obtained by invoking "Equations Stub" on the following: ```lean meta def foo : expr → tactic unit := -- do not forget to write `:=`!! {! !} ``` ```lean meta def foo : expr → tactic unit := -- don't forget to erase `:=`!! | (expr.var a) := _ | (expr.sort a) := _ | (expr.const a a_1) := _ | (expr.mvar a a_1 a_2) := _ | (expr.local_const a a_1 a_2 a_3) := _ | (expr.app a a_1) := _ | (expr.lam a a_1 a_2 a_3) := _ | (expr.pi a a_1 a_2 a_3) := _ | (expr.elet a a_1 a_2 a_3) := _ | (expr.macro a a_1) := _ ``` -/ @[hole_command] meta def eqn_stub : hole_command := { name := "Equations Stub", descr := "Generate a list of equations for a recursive definition.", action := λ es, do t ← match es with | [t] := to_expr t | [] := target | _ := fail "expecting one type" end, e ← whnf t, (v :: _,_) ← open_pis e | fail "expecting a Pi-type", t' ← infer_type v, fs ← mk_patterns t', t ← pp t, let out := if es.empty then format.to_string format!"-- do not forget to erase `:=`!!\n{format.join fs}" else format.to_string format!"{t}\n{format.join fs}", return [(out,"")] } add_tactic_doc { name := "Equations Stub", category := doc_category.hole_cmd, decl_names := [`tactic.eqn_stub], tags := ["pattern matching"] } /-- This command lists the constructors that can be used to satisfy the expected type. Invoking "List Constructors" ("Show the list of constructors of the expected type") in the following hole: ```lean def foo : ℤ ⊕ ℕ := {! !} ``` produces: ```lean def foo : ℤ ⊕ ℕ := {! sum.inl, sum.inr !} ``` and will display: ```lean sum.inl : ℤ → ℤ ⊕ ℕ sum.inr : ℕ → ℤ ⊕ ℕ ``` -/ @[hole_command] meta def list_constructors_hole : hole_command := { name := "List Constructors", descr := "Show the list of constructors of the expected type.", action := λ es, do t ← target >>= whnf, (_,t) ← open_pis t, let cl := t.get_app_fn.const_name, let args := t.get_app_args, env ← get_env, let cs := env.constructors_of cl, ts ← cs.mmap $ λ c, do { e ← mk_const c, t ← infer_type (e.mk_app args) >>= pp, c ← strip_prefix c, pure format!"\n{c} : {t}\n" }, fs ← format.intercalate ", " <$> cs.mmap (strip_prefix >=> pure ∘ to_fmt), let out := format.to_string format!"{{! {fs} !}", trace (format.join ts).to_string, return [(out,"")] } add_tactic_doc { name := "List Constructors", category := doc_category.hole_cmd, decl_names := [`tactic.list_constructors_hole], tags := ["goal information"] } /-- Makes the declaration `classical.prop_decidable` available to type class inference. This asserts that all propositions are decidable, but does not have computational content. -/ meta def classical : tactic unit := do h ← get_unused_name `_inst, mk_const `classical.prop_decidable >>= note h none, reset_instance_cache open expr /-- `mk_comp v e` checks whether `e` is a sequence of nested applications `f (g (h v))`, and if so, returns the expression `f ∘ g ∘ h`. -/ meta def mk_comp (v : expr) : expr → tactic expr | (app f e) := if e = v then pure f else do guard (¬ v.occurs f) <|> fail "bad guard", e' ← mk_comp e >>= instantiate_mvars, f ← instantiate_mvars f, mk_mapp ``function.comp [none,none,none,f,e'] | e := do guard (e = v), t ← infer_type e, mk_mapp ``id [t] /-- Given two expressions `e₀` and `e₁`, return the expression `` `(%%e₀ ↔ %%e₁)``. -/ meta def mk_iff (e₀ : expr) (e₁ : expr) : expr := `(%%e₀ ↔ %%e₁) /-- From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions. -/ meta def mk_higher_order_type : expr → tactic expr | (pi n bi d b@(pi _ _ _ _)) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (pi n bi d ∘ flip abstract_local v.local_uniq_name) <$> mk_higher_order_type b' | (pi n bi d b) := do v ← mk_local_def n d, let b' := (b.instantiate_var v), (l,r) ← match_eq b' <|> fail format!"not an equality {b'}", l' ← mk_comp v l, r' ← mk_comp v r, mk_app ``eq [l',r'] | e := failed open lean.parser interactive.types /-- A user attribute that applies to lemmas of the shape `∀ x, f (g x) = h x`. It derives an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions. -/ @[user_attribute] meta def higher_order_attr : user_attribute unit (option name) := { name := `higher_order, parser := optional ident, descr := "From a lemma of the shape `∀ x, f (g x) = h x` derive an auxiliary lemma of the form `f ∘ g = h` for reasoning about higher-order functions.", after_set := some $ λ lmm _ _, do env ← get_env, decl ← env.get lmm, let num := decl.univ_params.length, let lvls := (list.iota num).map (`l).append_after, let l : expr := expr.const lmm $ lvls.map level.param, t ← infer_type l >>= instantiate_mvars, t' ← mk_higher_order_type t, (_,pr) ← solve_aux t' $ do { intros, applyc ``_root_.funext, intro1, applyc lmm; assumption }, pr ← instantiate_mvars pr, lmm' ← higher_order_attr.get_param lmm, lmm' ← (flip name.update_prefix lmm.get_prefix <$> lmm') <|> pure lmm.add_prime, add_decl $ declaration.thm lmm' lvls t' (pure pr), copy_attribute `simp lmm lmm', copy_attribute `functor_norm lmm lmm' } add_tactic_doc { name := "higher_order", category := doc_category.attr, decl_names := [`tactic.higher_order_attr], tags := ["lemma derivation"] } attribute [higher_order map_comp_pure] map_pure /-- Copies a definition into the `tactic.interactive` namespace to make it usable in proof scripts. It allows one to write ```lean @[interactive] meta def my_tactic := ... ``` instead of ```lean meta def my_tactic := ... run_cmd add_interactive [``my_tactic] ``` -/ @[user_attribute] meta def interactive_attr : user_attribute := { name := `interactive, descr := "Put a definition in the `tactic.interactive` namespace to make it usable in proof scripts.", after_set := some $ λ tac _ _, add_interactive [tac] } add_tactic_doc { name := "interactive", category := doc_category.attr, decl_names := [``tactic.interactive_attr], tags := ["environment"] } /-- Use `refine` to partially discharge the goal, or call `fconstructor` and try again. -/ private meta def use_aux (h : pexpr) : tactic unit := (focus1 (refine h >> done)) <|> (fconstructor >> use_aux) /-- Similar to `existsi`, `use l` will use entries in `l` to instantiate existential obligations at the beginning of a target. Unlike `existsi`, the pexprs in `l` are elaborated with respect to the expected type. ```lean example : ∃ x : ℤ, x = x := by tactic.use ``(42) ``` See the doc string for `tactic.interactive.use` for more information. -/ protected meta def use (l : list pexpr) : tactic unit := focus1 $ seq' (l.mmap' $ λ h, use_aux h <|> fail format!"failed to instantiate goal with {h}") instantiate_mvars_in_target /-- `clear_aux_decl_aux l` clears all expressions in `l` that represent aux decls from the local context. -/ meta def clear_aux_decl_aux : list expr → tactic unit | [] := skip | (e::l) := do cond e.is_aux_decl (tactic.clear e) skip, clear_aux_decl_aux l /-- `clear_aux_decl` clears all expressions from the local context that represent aux decls. -/ meta def clear_aux_decl : tactic unit := local_context >>= clear_aux_decl_aux /-- `apply_at_aux e et [] h ht` (with `et` the type of `e` and `ht` the type of `h`) finds a list of expressions `vs` and returns `(e.mk_args (vs ++ [h]), vs)`. -/ meta def apply_at_aux (arg t : expr) : list expr → expr → expr → tactic (expr × list expr) | vs e (pi n bi d b) := do { v ← mk_meta_var d, apply_at_aux (v :: vs) (e v) (b.instantiate_var v) } <|> (e arg, vs) <$ unify d t | vs e _ := failed /-- `apply_at e h` applies implication `e` on hypothesis `h` and replaces `h` with the result. -/ meta def apply_at (e h : expr) : tactic unit := do ht ← infer_type h, et ← infer_type e, (h', gs') ← apply_at_aux h ht [] e et, note h.local_pp_name none h', clear h, gs' ← gs'.mfilter is_assigned, (g :: gs) ← get_goals, set_goals (g :: gs' ++ gs) /-- `symmetry_hyp h` applies `symmetry` on hypothesis `h`. -/ meta def symmetry_hyp (h : expr) (md := semireducible) : tactic unit := do tgt ← infer_type h, env ← get_env, let r := get_app_fn tgt, match env.symm_for (const_name r) with | (some symm) := do s ← mk_const symm, apply_at s h | none := fail "symmetry tactic failed, target is not a relation application with the expected property." end precedence `setup_tactic_parser`:0 /-- `setup_tactic_parser` is a user command that opens the namespaces used in writing interactive tactics, and declares the local postfix notation `?` for `optional` and `*` for `many`. It does *not* use the `namespace` command, so it will typically be used after `namespace tactic.interactive`. -/ @[user_command] meta def setup_tactic_parser_cmd (_ : interactive.parse $ tk "setup_tactic_parser") : lean.parser unit := emit_code_here " open lean open lean.parser open interactive interactive.types local postfix `?`:9001 := optional local postfix *:9001 := many . " /-- `finally tac finalizer` runs `tac` first, then runs `finalizer` even if `tac` fails. `finally tac finalizer` fails if either `tac` or `finalizer` fails. -/ meta def finally {β} (tac : tactic α) (finalizer : tactic β) : tactic α := λ s, match tac s with | (result.success r s') := (finalizer >> pure r) s' | (result.exception msg p s') := (finalizer >> result.exception msg p) s' end /-- `on_exception handler tac` runs `tac` first, and then runs `handler` only if `tac` failed. -/ meta def on_exception {β} (handler : tactic β) (tac : tactic α) : tactic α | s := match tac s with | result.exception msg p s' := (handler *> result.exception msg p) s' | ok := ok end /-- `decorate_error add_msg tac` prepends `add_msg` to an exception produced by `tac` -/ meta def decorate_error (add_msg : string) (tac : tactic α) : tactic α | s := match tac s with | result.exception msg p s := let msg (_ : unit) : format := match msg with | some msg := add_msg ++ format.line ++ msg () | none := add_msg end in result.exception msg p s | ok := ok end /-- Applies tactic `t`. If it succeeds, revert the state, and return the value. If it fails, returns the error message. -/ meta def retrieve_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) := λ s, match t s with | (interaction_monad.result.success a s') := result.success (sum.inl a) s | (interaction_monad.result.exception msg' _ s') := result.success (sum.inr (msg'.iget ()).to_string) s end /-- Applies tactic `t`. If it succeeds, return the value. If it fails, returns the error message. -/ meta def try_or_report_error {α : Type u} (t : tactic α) : tactic (α ⊕ string) := λ s, match t s with | (interaction_monad.result.success a s') := result.success (sum.inl a) s' | (interaction_monad.result.exception msg' _ s') := result.success (sum.inr (msg'.iget ()).to_string) s end /-- This tactic succeeds if `t` succeeds or fails with message `msg` such that `p msg` is `tt`. -/ meta def succeeds_or_fails_with_msg {α : Type} (t : tactic α) (p : string → bool) : tactic unit := do x ← retrieve_or_report_error t, match x with | (sum.inl _) := skip | (sum.inr msg) := if p msg then skip else fail msg end add_tactic_doc { name := "setup_tactic_parser", category := doc_category.cmd, decl_names := [`tactic.setup_tactic_parser_cmd], tags := ["parsing", "notation"] } /-- `trace_error msg t` executes the tactic `t`. If `t` fails, traces `msg` and the failure message of `t`. -/ meta def trace_error (msg : string) (t : tactic α) : tactic α | s := match t s with | (result.success r s') := result.success r s' | (result.exception (some msg') p s') := (trace msg >> trace (msg' ()) >> result.exception (some msg') p) s' | (result.exception none p s') := result.exception none p s' end /-- ``trace_if_enabled `n msg`` traces the message `msg` only if tracing is enabled for the name `n`. Create new names registered for tracing with `declare_trace n`. Then use `set_option trace.n true/false` to enable or disable tracing for `n`. -/ meta def trace_if_enabled (n : name) {α : Type u} [has_to_tactic_format α] (msg : α) : tactic unit := when_tracing n (trace msg) /-- ``trace_state_if_enabled `n msg`` prints the tactic state, preceded by the optional string `msg`, only if tracing is enabled for the name `n`. -/ meta def trace_state_if_enabled (n : name) (msg : string := "") : tactic unit := when_tracing n ((if msg = "" then skip else trace msg) >> trace_state) /-- This combinator is for testing purposes. It succeeds if `t` fails with message `msg`, and fails otherwise. -/ meta def success_if_fail_with_msg {α : Type u} (t : tactic α) (msg : string) : tactic unit := λ s, match t s with | (interaction_monad.result.exception msg' _ s') := let expected_msg := (msg'.iget ()).to_string in if msg = expected_msg then result.success () s else mk_exception format!"failure messages didn't match. Expected:\n{expected_msg}" none s | (interaction_monad.result.success a s) := mk_exception "success_if_fail_with_msg combinator failed, given tactic succeeded" none s end /-- Construct a `Try this: refine ...` or `Try this: exact ...` string which would construct `g`. -/ meta def tactic_statement (g : expr) : tactic string := do g ← instantiate_mvars g, g ← head_beta g, r ← pp (replace_mvars g), if g.has_meta_var then return (sformat!"Try this: refine {r}") else return (sformat!"Try this: exact {r}") /-- `with_local_goals gs tac` runs `tac` on the goals `gs` and then restores the initial goals and returns the goals `tac` ended on. -/ meta def with_local_goals {α} (gs : list expr) (tac : tactic α) : tactic (α × list expr) := do gs' ← get_goals, set_goals gs, finally (prod.mk <$> tac <*> get_goals) (set_goals gs') /-- like `with_local_goals` but discards the resulting goals -/ meta def with_local_goals' {α} (gs : list expr) (tac : tactic α) : tactic α := prod.fst <$> with_local_goals gs tac /-- Representation of a proof goal that lends itself to comparison. The following goal: ```lean l₀ : T, l₁ : T ⊢ ∀ v : T, foo ``` is represented as ``` (2, ∀ l₀ l₁ v : T, foo) ``` The number 2 indicates that first the two bound variables of the `∀` are actually local constant. Comparing two such goals with `=` rather than `=ₐ` or `is_def_eq` tells us that proof script should not see the difference between the two. -/ meta def packaged_goal := ℕ × expr /-- proof state made of multiple `goal` meant for comparing the result of running different tactics -/ meta def proof_state := list packaged_goal meta instance goal.inhabited : inhabited packaged_goal := ⟨(0,var 0)⟩ meta instance proof_state.inhabited : inhabited proof_state := (infer_instance : inhabited (list packaged_goal)) /-- create a `packaged_goal` corresponding to the current goal -/ meta def get_packaged_goal : tactic packaged_goal := do ls ← local_context, tgt ← target >>= instantiate_mvars, tgt ← pis ls tgt, pure (ls.length, tgt) /-- `goal_of_mvar g`, with `g` a meta variable, creates a `packaged_goal` corresponding to `g` interpretted as a proof goal -/ meta def goal_of_mvar (g : expr) : tactic packaged_goal := with_local_goals' [g] get_packaged_goal /-- `get_proof_state` lists the user visible goal for each goal of the current state and for each goal, abstracts all of the meta variables of the other gaols. This produces a list of goals in the form of `ℕ × expr` where the `expr` encodes the following proof state: ```lean 2 goals l₁ : t₁, l₂ : t₂, l₃ : t₃ ⊢ tgt₁ ⊢ tgt₂ ``` as ```lean [ (3, ∀ (mv : tgt₁) (mv : tgt₂) (l₁ : t₁) (l₂ : t₂) (l₃ : t₃), tgt₁), (0, ∀ (mv : tgt₁) (mv : tgt₂), tgt₂) ] ``` with 2 goals, the first 2 bound variables encode the meta variable of all the goals, the next 3 (in the first goal) and 0 (in the second goal) are the local constants. This representation allows us to compare goals and proof states while ignoring information like the unique name of local constants and the equality or difference of meta variables that encode the same goal. -/ meta def get_proof_state : tactic proof_state := do gs ← get_goals, gs.mmap $ λ g, do ⟨n,g⟩ ← goal_of_mvar g, g ← gs.mfoldl (λ g v, do g ← kabstract g v reducible ff, pure $ pi `goal binder_info.default `(true) g ) g, pure (n,g) /-- Run `tac` in a disposable proof state and return the state. See `proof_state`, `goal` and `get_proof_state`. -/ meta def get_proof_state_after (tac : tactic unit) : tactic (option proof_state) := try_core $ retrieve $ tac >> get_proof_state open lean interactive /-- A type alias for `tactic format`, standing for "pretty print format". -/ meta def pformat := tactic format /-- `mk` lifts `fmt : format` to the tactic monad (`pformat`). -/ meta def pformat.mk (fmt : format) : pformat := pure fmt /-- an alias for `pp`. -/ meta def to_pfmt {α} [has_to_tactic_format α] (x : α) : pformat := pp x meta instance pformat.has_to_tactic_format : has_to_tactic_format pformat := ⟨ id ⟩ meta instance : has_append pformat := ⟨ λ x y, (++) <$> x <*> y ⟩ meta instance tactic.has_to_tactic_format [has_to_tactic_format α] : has_to_tactic_format (tactic α) := ⟨ λ x, x >>= to_pfmt ⟩ private meta def parse_pformat : string → list char → parser pexpr | acc [] := pure ``(to_pfmt %%(reflect acc)) | acc ('\n'::s) := do f ← parse_pformat "" s, pure ``(to_pfmt %%(reflect acc) ++ pformat.mk format.line ++ %%f) | acc ('{'::'{'::s) := parse_pformat (acc ++ "{") s | acc ('{'::s) := do (e, s) ← with_input (lean.parser.pexpr 0) s.as_string, '}'::s ← return s.to_list | fail "'}' expected", f ← parse_pformat "" s, pure ``(to_pfmt %%(reflect acc) ++ to_pfmt %%e ++ %%f) | acc (c::s) := parse_pformat (acc.str c) s reserve prefix `pformat! `:100 /-- See `format!` in `init/meta/interactive_base.lean`. The main differences are that `pp` is called instead of `to_fmt` and that we can use arguments of type `tactic α` in the quotations. Now, consider the following: ```lean e ← to_expr ``(3 + 7), trace format!"{e}" -- outputs `has_add.add.{0} nat nat.has_add (bit1.{0} nat nat.has_one nat.has_add (has_one.one.{0} nat nat.has_one)) ...` trace pformat!"{e}" -- outputs `3 + 7` ``` The difference is significant. And now, the following is expressible: ```lean e ← to_expr ``(3 + 7), trace pformat!"{e} : {infer_type e}" -- outputs `3 + 7 : ℕ` ``` See also: `trace!` and `fail!` -/ @[user_notation] meta def pformat_macro (_ : parse $ tk "pformat!") (s : string) : parser pexpr := do e ← parse_pformat "" s.to_list, return ``(%%e : pformat) reserve prefix `fail! `:100 /-- The combination of `pformat` and `fail`. -/ @[user_notation] meta def fail_macro (_ : parse $ tk "fail!") (s : string) : parser pexpr := do e ← pformat_macro () s, pure ``((%%e : pformat) >>= fail) reserve prefix `trace! `:100 /-- The combination of `pformat` and `trace`. -/ @[user_notation] meta def trace_macro (_ : parse $ tk "trace!") (s : string) : parser pexpr := do e ← pformat_macro () s, pure ``((%%e : pformat) >>= trace) /-- A hackish way to get the `src` directory of mathlib. -/ meta def get_mathlib_dir : tactic string := do e ← get_env, s ← e.decl_olean `tactic.reset_instance_cache, return $ s.popn_back 17 /-- Checks whether a declaration with the given name is declared in mathlib. If you want to run this tactic many times, you should use `environment.is_prefix_of_file` instead, since it is expensive to execute `get_mathlib_dir` many times. -/ meta def is_in_mathlib (n : name) : tactic bool := do ml ← get_mathlib_dir, e ← get_env, return $ e.is_prefix_of_file ml n /-- Runs a tactic by name. If it is a `tactic string`, return whatever string it returns. If it is a `tactic unit`, return the name. (This is mostly used in invoking "self-reporting tactics", e.g. by `tidy` and `hint`.) -/ meta def name_to_tactic (n : name) : tactic string := do d ← get_decl n, e ← mk_const n, let t := d.type, if (t =ₐ `(tactic unit)) then (eval_expr (tactic unit) e) >>= (λ t, t >> (name.to_string <$> strip_prefix n)) else if (t =ₐ `(tactic string)) then (eval_expr (tactic string) e) >>= (λ t, t) else fail!"name_to_tactic cannot take `{n} as input: its type must be `tactic string` or `tactic unit`" /-- auxiliary function for `apply_under_n_pis` -/ private meta def apply_under_n_pis_aux (func arg : pexpr) : ℕ → ℕ → expr → pexpr | n 0 _ := let vars := ((list.range n).reverse.map (@expr.var ff)), bd := vars.foldl expr.app arg.mk_explicit in func bd | n (k+1) (expr.pi nm bi tp bd) := expr.pi nm bi (pexpr.of_expr tp) (apply_under_n_pis_aux (n+1) k bd) | n (k+1) t := apply_under_n_pis_aux n 0 t /-- Assumes `pi_expr` is of the form `Π x1 ... xn xn+1..., _`. Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`. All arguments (implicit and explicit) to `arg` should be supplied. -/ meta def apply_under_n_pis (func arg : pexpr) (pi_expr : expr) (n : ℕ) : pexpr := apply_under_n_pis_aux func arg 0 n pi_expr /-- Assumes `pi_expr` is of the form `Π x1 ... xn, _`. Creates a pexpr of the form `Π x1 ... xn, func (arg x1 ... xn)`. All arguments (implicit and explicit) to `arg` should be supplied. -/ meta def apply_under_pis (func arg : pexpr) (pi_expr : expr) : pexpr := apply_under_n_pis func arg pi_expr pi_expr.pi_arity /-- If `func` is a `pexpr` representing a function that takes an argument `a`, `get_pexpr_arg_arity_with_tgt func tgt` returns the arity of `a`. When `tgt` is a `pi` expr, `func` is elaborated in a context with the domain of `tgt`. Examples: * ```get_pexpr_arg_arity ``(ring) `(true)``` returns 0, since `ring` takes one non-function argument. * ```get_pexpr_arg_arity_with_tgt ``(monad) `(true)``` returns 1, since `monad` takes one argument of type `α → α`. * ```get_pexpr_arg_arity_with_tgt ``(module R) `(Π (R : Type), comm_ring R → true)``` returns 0 -/ meta def get_pexpr_arg_arity_with_tgt (func : pexpr) (tgt : expr) : tactic ℕ := lock_tactic_state $ do mv ← mk_mvar, solve_aux tgt $ intros >> to_expr ``(%%func %%mv), expr.pi_arity <$> (infer_type mv >>= instantiate_mvars) /-- `find_private_decl n none` finds a private declaration named `n` in any of the imported files. `find_private_decl n (some m)` finds a private declaration named `n` in the same file where a declaration named `m` can be found. -/ meta def find_private_decl (n : name) (fr : option name) : tactic name := do env ← get_env, fn ← option_t.run (do fr ← option_t.mk (return fr), d ← monad_lift $ get_decl fr, option_t.mk (return $ env.decl_olean d.to_name) ), let p : string → bool := match fn with | (some fn) := λ x, fn = x | none := λ _, tt end, let xs := env.decl_filter_map (λ d, do fn ← env.decl_olean d.to_name, guard ((`_private).is_prefix_of d.to_name ∧ p fn ∧ d.to_name.update_prefix name.anonymous = n), pure d.to_name), match xs with | [n] := pure n | [] := fail "no such private found" | _ := fail "many matches found" end open lean.parser interactive /-- `import_private foo from bar` finds a private declaration `foo` in the same file as `bar` and creates a local notation to refer to it. `import_private foo` looks for `foo` in all imported files. When possible, make `foo` non-private rather than using this feature. -/ @[user_command] meta def import_private_cmd (_ : parse $ tk "import_private") : lean.parser unit := do n ← ident, fr ← optional (tk "from" *> ident), n ← find_private_decl n fr, c ← resolve_constant n, d ← get_decl n, let c := @expr.const tt c d.univ_levels, new_n ← new_aux_decl_name, add_decl $ declaration.defn new_n d.univ_params d.type c reducibility_hints.abbrev d.is_trusted, let new_not := sformat!"local notation `{n.update_prefix name.anonymous}` := {new_n}", emit_command_here $ new_not, skip . add_tactic_doc { name := "import_private", category := doc_category.cmd, decl_names := [`tactic.import_private_cmd], tags := ["renaming"] } /-- The command `mk_simp_attribute simp_name "description"` creates a simp set with name `simp_name`. Lemmas tagged with `@[simp_name]` will be included when `simp with simp_name` is called. `mk_simp_attribute simp_name none` will use a default description. Appending the command with `with attr1 attr2 ...` will include all declarations tagged with `attr1`, `attr2`, ... in the new simp set. This command is preferred to using ``run_cmd mk_simp_attr `simp_name`` since it adds a doc string to the attribute that is defined. If you need to create a simp set in a file where this command is not available, you should use ```lean run_cmd mk_simp_attr `simp_name run_cmd add_doc_string `simp_attr.simp_name "Description of the simp set here" ``` -/ @[user_command] meta def mk_simp_attribute_cmd (_ : parse $ tk "mk_simp_attribute") : lean.parser unit := do n ← ident, d ← parser.pexpr, d ← to_expr ``(%%d : option string), descr ← eval_expr (option string) d, with_list ← types.with_ident_list <|> return [], mk_simp_attr n with_list, add_doc_string (name.append `simp_attr n) $ descr.get_or_else $ "simp set for " ++ to_string n add_tactic_doc { name := "mk_simp_attribute", category := doc_category.cmd, decl_names := [`tactic.mk_simp_attribute_cmd], tags := ["simplification"] } /-- Given a user attribute name `attr_name`, `get_user_attribute_name attr_name` returns the name of the declaration that defines this attribute. Fails if there is no user attribute with this name. Example: ``get_user_attribute_name `norm_cast`` returns `` `norm_cast.norm_cast_attr`` -/ meta def get_user_attribute_name (attr_name : name) : tactic name := do ns ← attribute.get_instances `user_attribute, ns.mfirst (λ nm, do d ← get_decl nm, e ← mk_app `user_attribute.name [d.value], attr_nm ← eval_expr name e, guard $ attr_nm = attr_name, return nm) <|> fail!"'{attr_name}' is not a user attribute." /-- A tactic to set either a basic attribute or a user attribute, as long as the user attribute has no parameter. If a user attribute with a parameter (that is not `unit`) is set, this function will raise an error. -/ -- possible enhancement if needed: use default value for a user attribute with parameter. meta def set_attribute (attr_name : name) (c_name : name) (persistent := tt) (prio : option nat := none) : tactic unit := do get_decl c_name <|> fail!"unknown declaration {c_name}", s ← try_or_report_error (set_basic_attribute attr_name c_name persistent prio), sum.inr msg ← return s | skip, if msg = (format!"set_basic_attribute tactic failed, '{attr_name}' is not a basic attribute").to_string then do user_attr_nm ← get_user_attribute_name attr_name, user_attr_const ← mk_const user_attr_nm, tac ← eval_pexpr (tactic unit) ``(user_attribute.set %%user_attr_const %%c_name () %%persistent) <|> fail!"Cannot set attribute @[{attr_name}]. The corresponding user attribute {user_attr_nm} has a parameter.", tac else fail msg end tactic /-- `find_defeq red m e` looks for a key in `m` that is defeq to `e` (up to transparency `red`), and returns the value associated with this key if it exists. Otherwise, it fails. -/ meta def list.find_defeq (red : tactic.transparency) {v} (m : list (expr × v)) (e : expr) : tactic (expr × v) := m.mfind $ λ ⟨e', val⟩, tactic.is_def_eq e e' red
8f5ce585be7da58f1ec71a686773f522c4e99e56
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/algebra/tower.lean
896a8397b3fc22543eab75e5c1229d5d33c0c5aa
[ "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
11,811
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import algebra.algebra.subalgebra /-! # Towers of algebras In this file we prove basic facts about towers of algebra. An algebra tower A/S/R is expressed by having instances of `algebra A S`, `algebra R S`, `algebra R A` and `is_scalar_tower R S A`, the later asserting the compatibility condition `(r • s) • a = r • (s • a)`. An important definition is `to_alg_hom R S A`, the canonical `R`-algebra homomorphism `S →ₐ[R] A`. -/ open_locale pointwise universes u v w u₁ v₁ variables (R : Type u) (S : Type v) (A : Type w) (B : Type u₁) (M : Type v₁) namespace algebra variables [comm_semiring R] [semiring A] [algebra R A] variables [add_comm_monoid M] [module R M] [module A M] [is_scalar_tower R A M] variables {A} /-- The `R`-algebra morphism `A → End (M)` corresponding to the representation of the algebra `A` on the `R`-module `M`. This is a stronger version of `distrib_mul_action.to_linear_map`, and could also have been called `algebra.to_module_End`. -/ def lsmul : A →ₐ[R] module.End R M := { to_fun := distrib_mul_action.to_linear_map R M, map_one' := linear_map.ext $ λ _, one_smul A _, map_mul' := λ a b, linear_map.ext $ smul_assoc a b, map_zero' := linear_map.ext $ λ _, zero_smul A _, map_add' := λ a b, linear_map.ext $ λ _, add_smul _ _ _, commutes' := λ r, linear_map.ext $ algebra_map_smul A r, } @[simp] lemma lsmul_coe (a : A) : (lsmul R M a : M → M) = (•) a := rfl lemma lmul_algebra_map (x : R) : lmul R A (algebra_map R A x) = algebra.lsmul R A x := eq.symm $ linear_map.ext $ smul_def x end algebra namespace is_scalar_tower section module variables [comm_semiring R] [semiring A] [algebra R A] variables [add_comm_monoid M] [module R M] [module A M] [is_scalar_tower R A M] variables {R} (A) {M} theorem algebra_map_smul (r : R) (x : M) : algebra_map R A r • x = r • x := by rw [algebra.algebra_map_eq_smul_one, smul_assoc, one_smul] end module section semiring variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B] variables [algebra R S] [algebra S A] [algebra S B] variables {R S A} theorem of_algebra_map_eq [algebra R A] (h : ∀ x, algebra_map R A x = algebra_map S A (algebra_map R S x)) : is_scalar_tower R S A := ⟨λ x y z, by simp_rw [algebra.smul_def, ring_hom.map_mul, mul_assoc, h]⟩ /-- See note [partially-applied ext lemmas]. -/ theorem of_algebra_map_eq' [algebra R A] (h : algebra_map R A = (algebra_map S A).comp (algebra_map R S)) : is_scalar_tower R S A := of_algebra_map_eq $ ring_hom.ext_iff.1 h variables (R S A) instance subalgebra (S₀ : subalgebra R S) : is_scalar_tower S₀ S A := of_algebra_map_eq $ λ x, rfl variables [algebra R A] [algebra R B] variables [is_scalar_tower R S A] [is_scalar_tower R S B] theorem algebra_map_eq : algebra_map R A = (algebra_map S A).comp (algebra_map R S) := ring_hom.ext $ λ x, by simp_rw [ring_hom.comp_apply, algebra.algebra_map_eq_smul_one, smul_assoc, one_smul] theorem algebra_map_apply (x : R) : algebra_map R A x = algebra_map S A (algebra_map R S x) := by rw [algebra_map_eq R S A, ring_hom.comp_apply] instance subalgebra' (S₀ : subalgebra R S) : is_scalar_tower R S₀ A := @is_scalar_tower.of_algebra_map_eq R S₀ A _ _ _ _ _ _ $ λ _, (is_scalar_tower.algebra_map_apply R S A _ : _) @[ext] lemma algebra.ext {S : Type u} {A : Type v} [comm_semiring S] [semiring A] (h1 h2 : algebra S A) (h : ∀ (r : S) (x : A), (by haveI := h1; exact r • x) = r • x) : h1 = h2 := algebra.algebra_ext _ _ $ λ r, by simpa only [@algebra.smul_def _ _ _ _ h1, @algebra.smul_def _ _ _ _ h2, mul_one] using h r 1 /-- In a tower, the canonical map from the middle element to the top element is an algebra homomorphism over the bottom element. -/ def to_alg_hom : S →ₐ[R] A := { commutes' := λ _, (algebra_map_apply _ _ _ _).symm, .. algebra_map S A } lemma to_alg_hom_apply (y : S) : to_alg_hom R S A y = algebra_map S A y := rfl @[simp] lemma coe_to_alg_hom : ↑(to_alg_hom R S A) = algebra_map S A := ring_hom.ext $ λ _, rfl @[simp] lemma coe_to_alg_hom' : (to_alg_hom R S A : S → A) = algebra_map S A := rfl variables {R S A B} @[simp, priority 900] lemma _root_.alg_hom.map_algebra_map (f : A →ₐ[S] B) (r : R) : f (algebra_map R A r) = algebra_map R B r := by rw [algebra_map_apply R S A r, f.commutes, ← algebra_map_apply R S B] variables (R) @[simp, priority 900] lemma _root_.alg_hom.comp_algebra_map_of_tower (f : A →ₐ[S] B) : (f : A →+* B).comp (algebra_map R A) = algebra_map R B := ring_hom.ext f.map_algebra_map variables (R) {S A B} -- conflicts with is_scalar_tower.subalgebra @[priority 999] instance subsemiring (U : subsemiring S) : is_scalar_tower U S A := of_algebra_map_eq $ λ x, rfl @[nolint instance_priority] instance of_ring_hom {R A B : Type*} [comm_semiring R] [comm_semiring A] [comm_semiring B] [algebra R A] [algebra R B] (f : A →ₐ[R] B) : @is_scalar_tower R A B _ (f.to_ring_hom.to_algebra.to_has_scalar) _ := by { letI := (f : A →+* B).to_algebra, exact of_algebra_map_eq (λ x, (f.commutes x).symm) } end semiring end is_scalar_tower section homs variables [comm_semiring R] [comm_semiring S] [semiring A] [semiring B] variables [algebra R S] [algebra S A] [algebra S B] variables [algebra R A] [algebra R B] variables [is_scalar_tower R S A] [is_scalar_tower R S B] variables (R) {A S B} open is_scalar_tower namespace alg_hom /-- R ⟶ S induces S-Alg ⥤ R-Alg -/ def restrict_scalars (f : A →ₐ[S] B) : A →ₐ[R] B := { commutes' := λ r, by { rw [algebra_map_apply R S A, algebra_map_apply R S B], exact f.commutes (algebra_map R S r) }, .. (f : A →+* B) } lemma restrict_scalars_apply (f : A →ₐ[S] B) (x : A) : f.restrict_scalars R x = f x := rfl @[simp] lemma coe_restrict_scalars (f : A →ₐ[S] B) : (f.restrict_scalars R : A →+* B) = f := rfl @[simp] lemma coe_restrict_scalars' (f : A →ₐ[S] B) : (restrict_scalars R f : A → B) = f := rfl lemma restrict_scalars_injective : function.injective (restrict_scalars R : (A →ₐ[S] B) → (A →ₐ[R] B)) := λ f g h, alg_hom.ext (alg_hom.congr_fun h : _) end alg_hom namespace alg_equiv /-- R ⟶ S induces S-Alg ⥤ R-Alg -/ def restrict_scalars (f : A ≃ₐ[S] B) : A ≃ₐ[R] B := { commutes' := λ r, by { rw [algebra_map_apply R S A, algebra_map_apply R S B], exact f.commutes (algebra_map R S r) }, .. (f : A ≃+* B) } lemma restrict_scalars_apply (f : A ≃ₐ[S] B) (x : A) : f.restrict_scalars R x = f x := rfl @[simp] lemma coe_restrict_scalars (f : A ≃ₐ[S] B) : (f.restrict_scalars R : A ≃+* B) = f := rfl @[simp] lemma coe_restrict_scalars' (f : A ≃ₐ[S] B) : (restrict_scalars R f : A → B) = f := rfl lemma restrict_scalars_injective : function.injective (restrict_scalars R : (A ≃ₐ[S] B) → (A ≃ₐ[R] B)) := λ f g h, alg_equiv.ext (alg_equiv.congr_fun h : _) end alg_equiv end homs namespace subalgebra open is_scalar_tower section semiring variables (R) {S A B} [comm_semiring R] [comm_semiring S] [semiring A] [semiring B] variables [algebra R S] [algebra S A] [algebra R A] [algebra S B] [algebra R B] variables [is_scalar_tower R S A] [is_scalar_tower R S B] /-- Given a scalar tower `R`, `S`, `A` of algebras, reinterpret an `S`-subalgebra of `A` an as an `R`-subalgebra. -/ def restrict_scalars (U : subalgebra S A) : subalgebra R A := { algebra_map_mem' := λ x, by { rw algebra_map_apply R S A, exact U.algebra_map_mem _ }, .. U } @[simp] lemma coe_restrict_scalars {U : subalgebra S A} : (restrict_scalars R U : set A) = (U : set A) := rfl @[simp] lemma restrict_scalars_top : restrict_scalars R (⊤ : subalgebra S A) = ⊤ := set_like.coe_injective rfl @[simp] lemma restrict_scalars_to_submodule {U : subalgebra S A} : (U.restrict_scalars R).to_submodule = U.to_submodule.restrict_scalars R := set_like.coe_injective rfl @[simp] lemma mem_restrict_scalars {U : subalgebra S A} {x : A} : x ∈ restrict_scalars R U ↔ x ∈ U := iff.rfl lemma restrict_scalars_injective : function.injective (restrict_scalars R : subalgebra S A → subalgebra R A) := λ U V H, ext $ λ x, by rw [← mem_restrict_scalars R, H, mem_restrict_scalars] /-- Produces an `R`-algebra map from `U.restrict_scalars R` given an `S`-algebra map from `U`. This is a special case of `alg_hom.restrict_scalars` that can be helpful in elaboration. -/ @[simp] def of_restrict_scalars (U : subalgebra S A) (f : U →ₐ[S] B) : U.restrict_scalars R →ₐ[R] B := f.restrict_scalars R end semiring end subalgebra namespace is_scalar_tower open subalgebra variables [comm_semiring R] [comm_semiring S] [comm_semiring A] variables [algebra R S] [algebra S A] [algebra R A] [is_scalar_tower R S A] theorem adjoin_range_to_alg_hom (t : set A) : (algebra.adjoin (to_alg_hom R S A).range t).restrict_scalars R = (algebra.adjoin S t).restrict_scalars R := subalgebra.ext $ λ z, show z ∈ subsemiring.closure (set.range (algebra_map (to_alg_hom R S A).range A) ∪ t : set A) ↔ z ∈ subsemiring.closure (set.range (algebra_map S A) ∪ t : set A), from suffices set.range (algebra_map (to_alg_hom R S A).range A) = set.range (algebra_map S A), by rw this, by { ext z, exact ⟨λ ⟨⟨x, y, h1⟩, h2⟩, ⟨y, h2 ▸ h1⟩, λ ⟨y, hy⟩, ⟨⟨z, y, hy⟩, rfl⟩⟩ } end is_scalar_tower section semiring variables {R S A} variables [comm_semiring R] [semiring S] [add_comm_monoid A] variables [algebra R S] [module S A] [module R A] [is_scalar_tower R S A] namespace submodule open is_scalar_tower theorem smul_mem_span_smul_of_mem {s : set S} {t : set A} {k : S} (hks : k ∈ span R s) {x : A} (hx : x ∈ t) : k • x ∈ span R (s • t) := span_induction hks (λ c hc, subset_span $ set.mem_smul.2 ⟨c, x, hc, hx, rfl⟩) (by { rw zero_smul, exact zero_mem _ }) (λ c₁ c₂ ih₁ ih₂, by { rw add_smul, exact add_mem _ ih₁ ih₂ }) (λ b c hc, by { rw is_scalar_tower.smul_assoc, exact smul_mem _ _ hc }) theorem smul_mem_span_smul {s : set S} (hs : span R s = ⊤) {t : set A} {k : S} {x : A} (hx : x ∈ span R t) : k • x ∈ span R (s • t) := span_induction hx (λ x hx, smul_mem_span_smul_of_mem (hs.symm ▸ mem_top) hx) (by { rw smul_zero, exact zero_mem _ }) (λ x y ihx ihy, by { rw smul_add, exact add_mem _ ihx ihy }) (λ c x hx, smul_comm c k x ▸ smul_mem _ _ hx) theorem smul_mem_span_smul' {s : set S} (hs : span R s = ⊤) {t : set A} {k : S} {x : A} (hx : x ∈ span R (s • t)) : k • x ∈ span R (s • t) := span_induction hx (λ x hx, let ⟨p, q, hp, hq, hpq⟩ := set.mem_smul.1 hx in by { rw [← hpq, smul_smul], exact smul_mem_span_smul_of_mem (hs.symm ▸ mem_top) hq }) (by { rw smul_zero, exact zero_mem _ }) (λ x y ihx ihy, by { rw smul_add, exact add_mem _ ihx ihy }) (λ c x hx, smul_comm c k x ▸ smul_mem _ _ hx) theorem span_smul {s : set S} (hs : span R s = ⊤) (t : set A) : span R (s • t) = (span S t).restrict_scalars R := le_antisymm (span_le.2 $ λ x hx, let ⟨p, q, hps, hqt, hpqx⟩ := set.mem_smul.1 hx in hpqx ▸ (span S t).smul_mem p (subset_span hqt)) $ λ p hp, span_induction hp (λ x hx, one_smul S x ▸ smul_mem_span_smul hs (subset_span hx)) (zero_mem _) (λ _ _, add_mem _) (λ k x hx, smul_mem_span_smul' hs hx) end submodule end semiring section ring namespace algebra variables [comm_semiring R] [ring A] [algebra R A] variables [add_comm_group M] [module A M] [module R M] [is_scalar_tower R A M] lemma lsmul_injective [no_zero_smul_divisors A M] {x : A} (hx : x ≠ 0) : function.injective (lsmul R M x) := smul_right_injective _ hx end algebra end ring
952d43ad4e40422c16047f1f5d41037d6c0aa015
26ac254ecb57ffcb886ff709cf018390161a9225
/src/algebra/direct_sum.lean
b5f171f83eabcd4130137dfac21944abab7d285a
[ "Apache-2.0" ]
permissive
eric-wieser/mathlib
42842584f584359bbe1fc8b88b3ff937c8acd72d
d0df6b81cd0920ad569158c06a3fd5abb9e63301
refs/heads/master
1,669,546,404,255
1,595,254,668,000
1,595,254,668,000
281,173,504
0
0
Apache-2.0
1,595,263,582,000
1,595,263,581,000
null
UTF-8
Lean
false
false
6,363
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Direct sum of abelian groups, indexed by a discrete type. -/ import data.dfinsupp open_locale big_operators universes u v w u₁ variables (ι : Type v) [decidable_eq ι] (β : ι → Type w) [Π i, add_comm_group (β i)] def direct_sum : Type* := Π₀ i, β i namespace direct_sum variables {ι β} instance : add_comm_group (direct_sum ι β) := dfinsupp.add_comm_group instance : inhabited (direct_sum ι β) := ⟨0⟩ variables β def mk : Π s : finset ι, (Π i : (↑s : set ι), β i.1) → direct_sum ι β := dfinsupp.mk def of : Π i : ι, β i → direct_sum ι β := dfinsupp.single variables {β} instance mk.is_add_group_hom (s : finset ι) : is_add_group_hom (mk β s) := { map_add := λ _ _, dfinsupp.mk_add } @[simp] lemma mk_zero (s : finset ι) : mk β s 0 = 0 := is_add_group_hom.map_zero _ @[simp] lemma mk_add (s : finset ι) (x y) : mk β s (x + y) = mk β s x + mk β s y := is_add_hom.map_add _ x y @[simp] lemma mk_neg (s : finset ι) (x) : mk β s (-x) = -mk β s x := is_add_group_hom.map_neg _ x @[simp] lemma mk_sub (s : finset ι) (x y) : mk β s (x - y) = mk β s x - mk β s y := is_add_group_hom.map_sub _ x y instance of.is_add_group_hom (i : ι) : is_add_group_hom (of β i) := { map_add := λ _ _, dfinsupp.single_add } @[simp] lemma of_zero (i : ι) : of β i 0 = 0 := is_add_group_hom.map_zero _ @[simp] lemma of_add (i : ι) (x y) : of β i (x + y) = of β i x + of β i y := is_add_hom.map_add _ x y @[simp] lemma of_neg (i : ι) (x) : of β i (-x) = -of β i x := is_add_group_hom.map_neg _ x @[simp] lemma of_sub (i : ι) (x y) : of β i (x - y) = of β i x - of β i y := is_add_group_hom.map_sub _ x y theorem mk_injective (s : finset ι) : function.injective (mk β s) := dfinsupp.mk_injective s theorem of_injective (i : ι) : function.injective (of β i) := λ x y H, congr_fun (mk_injective _ H) ⟨i, by simp⟩ @[elab_as_eliminator] protected theorem induction_on {C : direct_sum ι β → Prop} (x : direct_sum ι β) (H_zero : C 0) (H_basic : ∀ (i : ι) (x : β i), C (of β i x)) (H_plus : ∀ x y, C x → C y → C (x + y)) : C x := begin apply dfinsupp.induction x H_zero, intros i b f h1 h2 ih, solve_by_elim end variables {γ : Type u₁} [add_comm_group γ] variables (φ : Π i, β i → γ) [Π i, is_add_group_hom (φ i)] variables (φ) def to_group (f : direct_sum ι β) : γ := quotient.lift_on f (λ x, ∑ i in x.2.to_finset, φ i (x.1 i)) $ λ x y H, begin have H1 : x.2.to_finset ∩ y.2.to_finset ⊆ x.2.to_finset, from finset.inter_subset_left _ _, have H2 : x.2.to_finset ∩ y.2.to_finset ⊆ y.2.to_finset, from finset.inter_subset_right _ _, refine (finset.sum_subset H1 _).symm.trans ((finset.sum_congr rfl _).trans (finset.sum_subset H2 _)), { intros i H1 H2, rw finset.mem_inter at H2, rw H i, simp only [multiset.mem_to_finset] at H1 H2, rw [(y.3 i).resolve_left (mt (and.intro H1) H2), is_add_group_hom.map_zero (φ i)] }, { intros i H1, rw H i }, { intros i H1 H2, rw finset.mem_inter at H2, rw ← H i, simp only [multiset.mem_to_finset] at H1 H2, rw [(x.3 i).resolve_left (mt (λ H3, and.intro H3 H1) H2), is_add_group_hom.map_zero (φ i)] } end variables {φ} instance to_group.is_add_group_hom : is_add_group_hom (to_group φ) := { map_add := assume f g, begin refine quotient.induction_on f (λ x, _), refine quotient.induction_on g (λ y, _), change ∑ i in _, _ = (∑ i in _, _) + (∑ i in _, _), simp only, conv { to_lhs, congr, skip, funext, rw is_add_hom.map_add (φ i) }, simp only [finset.sum_add_distrib], congr' 1, { refine (finset.sum_subset _ _).symm, { intro i, simp only [multiset.mem_to_finset, multiset.mem_add], exact or.inl }, { intros i H1 H2, simp only [multiset.mem_to_finset, multiset.mem_add] at H2, rw [(x.3 i).resolve_left H2, is_add_group_hom.map_zero (φ i)] } }, { refine (finset.sum_subset _ _).symm, { intro i, simp only [multiset.mem_to_finset, multiset.mem_add], exact or.inr }, { intros i H1 H2, simp only [multiset.mem_to_finset, multiset.mem_add] at H2, rw [(y.3 i).resolve_left H2, is_add_group_hom.map_zero (φ i)] } } end } variables (φ) @[simp] lemma to_group_zero : to_group φ 0 = 0 := is_add_group_hom.map_zero _ @[simp] lemma to_group_add (x y) : to_group φ (x + y) = to_group φ x + to_group φ y := is_add_hom.map_add _ x y @[simp] lemma to_group_neg (x) : to_group φ (-x) = -to_group φ x := is_add_group_hom.map_neg _ x @[simp] lemma to_group_sub (x y) : to_group φ (x - y) = to_group φ x - to_group φ y := is_add_group_hom.map_sub _ x y @[simp] lemma to_group_of (i) (x : β i) : to_group φ (of β i x) = φ i x := (add_zero _).trans $ congr_arg (φ i) $ show (if H : i ∈ ({i} : finset _) then x else 0) = x, from dif_pos $ finset.mem_singleton_self i variables (ψ : direct_sum ι β → γ) [is_add_group_hom ψ] theorem to_group.unique (f : direct_sum ι β) : ψ f = @to_group _ _ _ _ _ _ (λ i, ψ ∘ of β i) (λ i, is_add_group_hom.comp (of β i) ψ) f := by haveI : ∀ i, is_add_group_hom (ψ ∘ of β i) := (λ _, is_add_group_hom.comp _ _); exact direct_sum.induction_on f (by rw [is_add_group_hom.map_zero ψ, is_add_group_hom.map_zero (to_group (λ i, ψ ∘ of β i))]) (λ i x, by rw [to_group_of]) (λ x y ihx ihy, by rw [is_add_hom.map_add ψ, is_add_hom.map_add (to_group (λ i, ψ ∘ of β i)), ihx, ihy]) variables (β) def set_to_set (S T : set ι) (H : S ⊆ T) : direct_sum S (β ∘ subtype.val) → direct_sum T (β ∘ subtype.val) := to_group $ λ i, of (β ∘ @subtype.val _ T) ⟨i.1, H i.2⟩ variables {β} instance (S T : set ι) (H : S ⊆ T) : is_add_group_hom (set_to_set β S T H) := to_group.is_add_group_hom protected def id (M : Type v) [add_comm_group M] : direct_sum punit (λ _, M) ≃ M := { to_fun := direct_sum.to_group (λ _, id), inv_fun := of (λ _, M) punit.star, left_inv := λ x, direct_sum.induction_on x (by rw [to_group_zero, of_zero]) (λ ⟨⟩ x, by rw [to_group_of]; refl) (λ x y ihx ihy, by rw [to_group_add, of_add, ihx, ihy]), right_inv := λ x, to_group_of _ _ _ } instance : has_coe_to_fun (direct_sum ι β) := dfinsupp.has_coe_to_fun end direct_sum
4c2c04542b46eb8f1dfc7c0219b1ede14fdfe385
5d95c8513fa8592ce314d1f40c23ad5eecfe1e34
/src/universal/homomorphism.lean
51d78e85513938c46ee4d0f518d9c939b79e9861
[ "Apache-2.0" ]
permissive
solovay/lean-universal
6b792513ced2fe82218e7828400743375dd59e24
417ed5e1b030e547912cbfefe34df9d3d01c2b65
refs/heads/master
1,598,052,603,315
1,565,981,123,000
1,565,981,123,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,552
lean
-- Copyright © 2019 François G. Dorais. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. import .basic import .substitution namespace universal variables {τ : Type} {σ : Type*} {sig : signature τ σ} structure homomorphism (alg₁ : algebra sig) (alg₂ : algebra sig) := (map {} (t) : alg₁.sort t → alg₂.sort t) (func (f : σ) : ∀ (xs : Π (i : sig.index f), alg₁.sort i.val), alg₂.func f (λ i, map _ (xs i)) = map _ (alg₁.func f xs)) instance (alg₁ : algebra sig) (alg₂ : algebra sig) : has_coe_to_fun (homomorphism alg₁ alg₂) := { F := λ _, Π {t}, alg₁.sort t → alg₂.sort t , coe := λ h, h.map } namespace homomorphism variables {alg₁ : algebra sig} {alg₂ : algebra sig} {alg₃ : algebra sig} theorem eq : Π {{h₁ h₂ : homomorphism alg₁ alg₂}}, h₁.map = h₂.map → h₁ = h₂ | ⟨_,_⟩ ⟨_,_⟩ rfl := rfl theorem ext {{h₁ h₂ : homomorphism alg₁ alg₂}} : (∀ {t} (x : alg₁.sort t), h₁.map t x = h₂.map t x) → h₁ = h₂ := λ H, eq $ funext $ λ _, funext $ λ x, H x definition id (alg : algebra sig) : homomorphism alg alg := { map := λ _, id , func := λ _ _, rfl } definition comp (h₂₃ : homomorphism alg₂ alg₃) (h₁₂ : homomorphism alg₁ alg₂) : homomorphism alg₁ alg₃ := { map := λ t x, h₂₃.map t (h₁₂.map t x) , func := λ f xs, eq.subst (h₁₂.func f xs) (h₂₃.func f _) } class injective (h : homomorphism alg₁ alg₂) : Prop := intro :: (elim (t) : function.injective (h.map t)) class surjective (h : homomorphism alg₁ alg₂) : Prop := intro :: (elim (t) : function.surjective (h.map t)) instance comp.inj (h₂₃ : homomorphism alg₂ alg₃) (h₁₂ : homomorphism alg₁ alg₂) [injective h₂₃] [injective h₁₂] : injective (comp h₂₃ h₁₂) := ⟨λ t, function.injective_comp (injective.elim h₂₃ t) (injective.elim h₁₂ t)⟩ instance comp.surj (h₂₃ : homomorphism alg₂ alg₃) (h₁₂ : homomorphism alg₁ alg₂) [surjective h₂₃] [surjective h₁₂] : surjective (comp h₂₃ h₁₂) := ⟨λ t, function.surjective_comp (surjective.elim h₂₃ t) (surjective.elim h₁₂ t)⟩ @[priority 0] instance id.inj (alg : algebra sig) : injective (id alg) := ⟨λ _, function.injective_id⟩ @[priority 0] instance id.surj (alg : algebra sig) : surjective (id alg) := ⟨λ _, function.surjective_id⟩ theorem eval (h : homomorphism alg₁ alg₂) {dom} : ∀ {cod} (t : term sig dom cod) (val : Π (i : index dom), alg₁.sort i.val), h.map _ (alg₁.eval t val) = alg₂.eval t (λ i, h.map _ (val i)) | _ (term.proj i) val := rfl | _ (term.func f ts) val := have IH : (λ i, h.map _ (alg₁.eval (ts i) val)) = (λ i, alg₂.eval (ts i) (λ i, h.map _ (val i))), from funext $ λ i, eval (ts i) val, calc h.map _ (alg₁.eval (term.func f ts) val) = h.map _ (alg₁.func f (λ i, alg₁.eval (ts i) val)) : rfl ... = alg₂.func f (λ i, h.map _ (alg₁.eval (ts i) val)) : by rw h.func ... = alg₂.func f (λ i, alg₂.eval (ts i) (λ i, h.map _ (val i))) : by rw IH ... = alg₂.eval (term.func f ts) (λ i, h.map _ (val i)) : by reflexivity end homomorphism namespace algebra.valuation variables {alg₁ : algebra sig} {alg₂ : algebra sig} (h : homomorphism alg₁ alg₂) definition map {dom} (val : algebra.valuation alg₁ dom) : algebra.valuation alg₂ dom := λ i, h (val i) theorem map_eval {dom} (val : algebra.valuation alg₁ dom) : ∀ {cod} (x : term sig dom cod), alg₂.eval x (val.map h) = h.map cod (alg₁.eval x val) | _ (term.proj _) := rfl | _ (term.func f xs) := have (λ i, alg₂.eval (xs i) (val.map h)) = (λ i, h.map _ (alg₁.eval (xs i) val)), from funext $ λ i, map_eval (xs i), calc _ = alg₂.func f (λ i, alg₂.eval (xs i) (val.map h)) : rfl ... = alg₂.func f (λ i, h.map _ (alg₁.eval (xs i) val)) : by rw this ... = h.map _ (alg₁.func f (λ i, alg₁.eval (xs i) val)) : by rw h.func f ... = h.map _ (alg₁.eval (term.func f xs) val) : by rw alg₁.eval_func end algebra.valuation definition algebra.eval_hom (alg : algebra sig) {dom : list τ} (val : Π (i : index dom), alg.sort i.val) : homomorphism (term_algebra sig dom) alg := { map := λ (cod) (t : term sig dom cod), alg.eval t val , func := λ _ _, rfl } definition term.subst_hom {dom₁ dom₂ : list τ} (sub : substitution sig dom₁ dom₂) : homomorphism (term_algebra sig dom₁) (term_algebra sig dom₂) := { map := term.subst sub , func := λ _ _, rfl } end universal
140b813b0f29a2148ced712ae53b1275f6631752
3c9dc4ea6cc92e02634ef557110bde9eae393338
/stage0/src/Lean/Server/FileWorker.lean
26e2855d1cec1897e7fc9572cf86983703d3b2c6
[ "Apache-2.0" ]
permissive
shingtaklam1324/lean4
3d7efe0c8743a4e33d3c6f4adbe1300df2e71492
351285a2e8ad0cef37af05851cfabf31edfb5970
refs/heads/master
1,676,827,679,740
1,610,462,623,000
1,610,552,340,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
21,772
lean
/- Copyright (c) 2020 Marc Huisinga. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Marc Huisinga, Wojciech Nawrocki -/ import Init.System.IO import Std.Data.RBMap import Lean.Environment import Lean.PrettyPrinter import Lean.Data.Lsp import Lean.Data.Json.FromToJson import Lean.Server.Snapshots import Lean.Server.Utils import Lean.Server.AsyncList /-! For general server architecture, see `README.md`. For details of IPC communication, see `Watchdog.lean`. This module implements per-file worker processes. File processing and requests+notifications against a file should be concurrent for two reasons: - By the LSP standard, requests should be cancellable. - Since Lean allows arbitrary user code to be executed during elaboration via the tactic framework, elaboration can be extremely slow and even not halt in some cases. Users should be able to work with the file while this is happening, e.g. make new changes to the file or send requests. To achieve these goals, elaboration is executed in a chain of tasks, where each task corresponds to the elaboration of one command. When the elaboration of one command is done, the next task is spawned. On didChange notifications, we search for the task in which the change occured. If we stumble across a task that has not yet finished before finding the task we're looking for, we terminate it and start the elaboration there, otherwise we start the elaboration at the task where the change occured. Requests iterate over tasks until they find the command that they need to answer the request. In order to not block the main thread, this is done in a request task. If a task that the request task waits for is terminated, a change occured somewhere before the command that the request is looking for and the request sends a "content changed" error. -/ namespace Lean.Server.FileWorker open Lsp open IO open Snapshots open Lean.Parser.Command section Utils private def logSnapContent (s : Snapshot) (text : FileMap) : IO Unit := IO.eprintln s!"[{s.beginPos}, {s.endPos}]: `{text.source.extract s.beginPos (s.endPos-1)}`" inductive TaskError where | aborted | eof | ioError (e : IO.Error) instance : Coe IO.Error TaskError := ⟨TaskError.ioError⟩ structure CancelToken where ref : IO.Ref Bool deriving Inhabited namespace CancelToken def new : IO CancelToken := CancelToken.mk <$> IO.mkRef false def check [MonadExceptOf TaskError m] [MonadLiftT (ST RealWorld) m] [Monad m] (tk : CancelToken) : m Unit := do let c ← tk.ref.get if c = true then throw TaskError.aborted def set (tk : CancelToken) : IO Unit := tk.ref.set true end CancelToken /-- A document editable in the sense that we track the environment and parser state after each command so that edits can be applied without recompiling code appearing earlier in the file. -/ structure EditableDocument where meta : DocumentMeta /- The first snapshot is that after the header. -/ headerSnap : Snapshot /- Subsequent snapshots occur after each command. -/ cmdSnaps : AsyncList TaskError Snapshot cancelTk : CancelToken deriving Inhabited end Utils open IO open Std (RBMap RBMap.empty) open JsonRpc section ServerM -- Pending requests are tracked so that requests can be cancelled by cancelling the corresponding task, -- which would be cancelled by the GC if we did not track these requests. abbrev PendingRequestMap := RBMap RequestID (Task (Except IO.Error Unit)) (fun a b => Decidable.decide (a < b)) structure ServerContext where hIn : FS.Stream hOut : FS.Stream docRef : IO.Ref EditableDocument pendingRequestsRef : IO.Ref PendingRequestMap abbrev ServerM := ReaderT ServerContext IO def updatePendingRequests (map : PendingRequestMap → PendingRequestMap) : ServerM Unit := do (←read).pendingRequestsRef.modify map /-- Elaborates the next command after `parentSnap` and emits diagnostics. -/ private def nextCmdSnap (m : DocumentMeta) (parentSnap : Snapshot) (cancelTk : CancelToken) : ExceptT TaskError ServerM Snapshot := do cancelTk.check let st ← read let maybeSnap ← compileNextCmd m.text.source parentSnap cancelTk.check let sendDiagnostics (msgLog : MessageLog) : IO Unit := do let diagnostics ← msgLog.msgs.mapM (msgToDiagnostic m.text) st.hOut.writeLspNotification { method := "textDocument/publishDiagnostics" param := { uri := m.uri version? := m.version diagnostics := diagnostics.toArray : PublishDiagnosticsParams } } match maybeSnap with | Sum.inl snap => /- NOTE(MH): This relies on the client discarding old diagnostics upon receiving new ones while prefering newer versions over old ones. The former is necessary because we do not explicitly clear older diagnostics, while the latter is necessary because we do not guarantee that diagnostics are emitted in order. Specifically, it may happen that we interrupted this elaboration task right at this point and a newer elaboration task emits diagnostics, after which we emit old diagnostics because we did not yet detect the interrupt. Explicitly clearing diagnostics is difficult for a similar reason, because we cannot guarantee that no further diagnostics are emitted after clearing them. -/ sendDiagnostics <| snap.msgLog.add { fileName := "<ignored>" pos := m.text.toPosition snap.endPos severity := MessageSeverity.information data := "processing..." } snap | Sum.inr msgLog => sendDiagnostics msgLog throw TaskError.eof /-- Elaborates all commands after `initSnap`, emitting the diagnostics. -/ def unfoldCmdSnaps (m : DocumentMeta) (initSnap : Snapshot) (cancelTk : CancelToken) : ServerM (AsyncList TaskError Snapshot) := do -- TODO(MH): check for interrupt with increased precision AsyncList.unfoldAsync (nextCmdSnap m . cancelTk (←read)) initSnap (some fun _ => pure TaskError.aborted) /-- Compiles the contents of a Lean file. -/ def compileDocument (m : DocumentMeta) : ServerM Unit := do let headerSnap@⟨_, _, _, SnapshotData.headerData env msgLog opts⟩ ← Snapshots.compileHeader m.text.source | throwServerError "Internal server error: invalid header snapshot" let cancelTk ← CancelToken.new let cmdSnaps ← unfoldCmdSnaps m headerSnap cancelTk (←read).docRef.set ⟨m, headerSnap, cmdSnaps, cancelTk⟩ /-- Given the new document and `changePos`, the UTF-8 offset of a change into the pre-change source, updates editable doc state. -/ def updateDocument (newMeta : DocumentMeta) (changePos : String.Pos) : ServerM Unit := do -- The watchdog only restarts the file worker when the syntax tree of the header changes. -- If e.g. a newline is deleted, it will not restart this file worker, but we still -- need to reparse the header so that the offsets are correct. let st ← read let oldDoc ← st.docRef.get let newHeaderSnap ← reparseHeader newMeta.text.source oldDoc.headerSnap if newHeaderSnap.stx != oldDoc.headerSnap.stx then throwServerError "Internal server error: header changed but worker wasn't restarted." let ⟨cmdSnaps, e?⟩ ← oldDoc.cmdSnaps.updateFinishedPrefix match e? with -- This case should not be possible. only the main task aborts tasks and ensures that aborted tasks -- do not show up in `snapshots` of an EditableDocument. | some TaskError.aborted => throwServerError "Internal server error: elab task was aborted while still in use." | some (TaskError.ioError ioError) => throw ioError | _ => -- No error or EOF oldDoc.cancelTk.set -- NOTE(WN): we invalidate eagerly as `endPos` consumes input greedily. To re-elaborate only -- when really necessary, we could do a whitespace-aware `Syntax` comparison instead. let mut validSnaps := cmdSnaps.finishedPrefix.takeWhile (fun s => s.endPos < changePos) if validSnaps.length = 0 then let cancelTk ← CancelToken.new let newCmdSnaps ← unfoldCmdSnaps newMeta newHeaderSnap cancelTk st.docRef.set ⟨newMeta, newHeaderSnap, newCmdSnaps, cancelTk⟩ else /- When at least one valid non-header snap exists, it may happen that a change does not fall within the syntactic range of that last snap but still modifies it by appending tokens. We check for this here. We do not currently handle crazy grammars in which an appended token can merge two or more previous commands into one. To do so would require reparsing the entire file. -/ let mut lastSnap := validSnaps.getLast! let preLastSnap := if validSnaps.length ≥ 2 then validSnaps.get! (validSnaps.length - 2) else newHeaderSnap let newLastStx ← parseNextCmd newMeta.text.source preLastSnap if newLastStx != lastSnap.stx then validSnaps ← validSnaps.dropLast lastSnap ← preLastSnap let cancelTk ← CancelToken.new let newSnaps ← unfoldCmdSnaps newMeta lastSnap cancelTk let newCmdSnaps := AsyncList.ofList validSnaps ++ newSnaps st.docRef.set ⟨newMeta, newHeaderSnap, newCmdSnaps, cancelTk⟩ end ServerM /- Notifications are handled in the main thread. They may change global worker state such as the current file contents. -/ section NotificationHandling def handleDidOpen (p : DidOpenTextDocumentParams) : ServerM Unit := let doc := p.textDocument /- NOTE(WN): `toFileMap` marks line beginnings as immediately following "\n", which should be enough to handle both LF and CRLF correctly. This is because LSP always refers to characters by (line, column), so if we get the line number correct it shouldn't matter that there is a CR there. -/ compileDocument ⟨doc.uri, doc.version, doc.text.toFileMap⟩ def handleDidChange (p : DidChangeTextDocumentParams) : ServerM Unit := do let docId := p.textDocument let changes := p.contentChanges let oldDoc ← (←read).docRef.get let some newVersion ← pure docId.version? | throwServerError "Expected version number" if newVersion ≤ oldDoc.meta.version then -- TODO(WN): This happens on restart sometimes. IO.eprintln s!"Got outdated version number: {newVersion} ≤ {oldDoc.meta.version}" else if ¬ changes.isEmpty then let (newDocText, minStartOff) := foldDocumentChanges changes oldDoc.meta.text updateDocument ⟨docId.uri, newVersion, newDocText⟩ minStartOff -- TODO(WN): cancel pending requests? def handleCancelRequest (p : CancelParams) : ServerM Unit := do updatePendingRequests (fun pendingRequests => pendingRequests.erase p.id) end NotificationHandling /- Request handlers are given by `Task`s executed asynchronously. They may be cancelled at any time, so they should check the cancellation token when possible to handle this cooperatively. Any exceptions thrown in a handler will be reported to the client as LSP error responses. -/ section RequestHandling structure RequestError where code : ErrorCode message : String -- TODO(WN): the type is too complicated abbrev RequestM α := ServerM $ Task $ Except IO.Error $ Except RequestError α /- Requests that need data from a certain command should traverse the snapshots by successively getting the next task, meaning that we might need to wait for elaboration. When that happens, the request should send a "content changed" error to the user (this way, the server doesn't get bogged down in requests for an old state of the document). Requests need to manually check for whether their task has been cancelled, so that they can reply with a RequestCancelled error. -/ partial def handleHover (id : RequestID) (p : HoverParams) : ServerM (Task (Except IO.Error (Except RequestError (Option Hover)))) := do let doc ← (←read).docRef.get let text := doc.meta.text let hoverPos := text.lspPosToUtf8Pos p.position let findTask ← doc.cmdSnaps.waitFind? (fun s => s.endPos > hoverPos) let mkHover (s : String) (f : String.Pos) (t : String.Pos) : Hover := { contents := { kind := MarkupKind.plaintext value := s } range? := some { start := text.utf8PosToLspPos f «end» := text.utf8PosToLspPos t } } (IO.mapTask · findTask) fun | Except.error TaskError.aborted => pure $ Except.error { code := ErrorCode.contentModified, message := "File changed." } | Except.error (TaskError.ioError e) => throwThe IO.Error e | Except.error TaskError.eof => pure $ Except.ok none | Except.ok (some snap) => do /- TODO: FIX -/ let mut infoRanges : Array (Nat × String.Pos × String.Pos × Expr) := #[] for t in snap.toCmdState.infoState.trees do /- if let Elab.InfoTree.ofTermInfo i := t then match i.stx.getPos, i.stx.getTailPos with | some pos, some endPos => if pos ≤ hoverPos ∧ hoverPos ≤ endPos then infoRanges := infoRanges.push (endPos - pos, pos, endPos, i.e) | _, _ => pure () -/ pure () match infoRanges.getMax? fun a b => a.1 > b.1 with | some (_, pos, endPos, e) => --st.hLog.putStrLn s!"Picked from {infoRanges.size}" return (Except.ok $ some $ mkHover (toString e) pos endPos -- Type inference fails : Except RequestError _) | none => pure () return Except.ok none | Except.ok none => return Except.ok none def handleWaitForDiagnostics (id : RequestID) (p : WaitForDiagnosticsParam) : ServerM (Task (Except IO.Error (Except RequestError WaitForDiagnostics))) := do let st ← read let e ← st.docRef.get let t ← e.cmdSnaps.waitAll t.map fun _ => Except.ok $ Except.ok WaitForDiagnostics.mk def rangeOfSyntax (text : FileMap) (stx : Syntax) : Range := ⟨text.utf8PosToLspPos <| stx.getHeadInfo.get!.pos.get!, text.utf8PosToLspPos <| stx.getTailPos.get!⟩ partial def handleDocumentSymbol (id : RequestID) (p : DocumentSymbolParams) : ServerM (Task (Except IO.Error (Except RequestError DocumentSymbolResult))) := do let st ← read asTask do let doc ← st.docRef.get let ⟨cmdSnaps, end?⟩ ← doc.cmdSnaps.updateFinishedPrefix let mut stxs := cmdSnaps.finishedPrefix.map (·.stx) if end?.isNone then let lastSnap := cmdSnaps.finishedPrefix.getLastD doc.headerSnap stxs := stxs ++ (← parseAhead doc.meta.text.source lastSnap).toList let (syms, _) := toDocumentSymbols doc.meta.text stxs return Except.ok { syms := syms.toArray } where toDocumentSymbols (text : FileMap) | [] => ([], []) | stx::stxs => match stx with | `(namespace $id) => sectionLikeToDocumentSymbols text stx stxs (id.getId.toString) SymbolKind.namespace id | `(section $(id)?) => sectionLikeToDocumentSymbols text stx stxs ((·.getId.toString) <$> id |>.getD "<section>") SymbolKind.namespace (id.getD stx) | `(end $(id)?) => ([], stx::stxs) | _ => let (syms, stxs') := toDocumentSymbols text stxs if stx.isOfKind ``Lean.Parser.Command.declaration then let (name, selection) := match stx with | `($dm:declModifiers $ak:attrKind instance $[$np:namedPrio]? $[$id:ident$[.{$ls,*}]?]? $sig:declSig $val) => ((·.getId.toString) <$> id |>.getD s!"instance {sig.reprint.getD ""}", id.getD sig) | _ => match stx[1][1] with | `(declId|$id:ident$[.{$ls,*}]?) => (id.getId.toString, id) | _ => (stx[1][0].isIdOrAtom?.getD "<unknown>", stx[1][0]) (DocumentSymbol.mk { name := name kind := SymbolKind.method range := rangeOfSyntax text stx selectionRange := rangeOfSyntax text selection } :: syms, stxs') else (syms, stxs') sectionLikeToDocumentSymbols (text : FileMap) (stx : Syntax) (stxs : List Syntax) (name : String) (kind : SymbolKind) (selection : Syntax) := let (syms, stxs') := toDocumentSymbols text stxs -- discard `end` let (syms', stxs'') := toDocumentSymbols text (stxs'.drop 1) let endStx := match stxs' with | endStx::_ => endStx | [] => (stx::stxs').getLast! (DocumentSymbol.mk { name := name kind := kind range := ⟨(rangeOfSyntax text stx).start, (rangeOfSyntax text endStx).«end»⟩ selectionRange := rangeOfSyntax text selection children? := syms.toArray } :: syms', stxs'') end RequestHandling section MessageHandling def parseParams (paramType : Type) [FromJson paramType] (params : Json) : ServerM paramType := match fromJson? params with | some parsed => pure parsed | none => throwServerError s!"Got param with wrong structure: {params.compress}" def handleNotification (method : String) (params : Json) : ServerM Unit := do let handle := fun paramType [FromJson paramType] (handler : paramType → ServerM Unit) => parseParams paramType params >>= handler match method with | "textDocument/didChange" => handle DidChangeTextDocumentParams handleDidChange | "$/cancelRequest" => handle CancelParams handleCancelRequest | _ => throwServerError s!"Got unsupported notification method: {method}" def queueRequest (id : RequestID) (requestTask : Task (Except IO.Error Unit)) : ServerM Unit := do updatePendingRequests (fun pendingRequests => pendingRequests.insert id requestTask) def handleRequest (id : RequestID) (method : String) (params : Json) : ServerM Unit := do let handle := fun paramType [FromJson paramType] respType [ToJson respType] (handler : RequestID → paramType → RequestM respType) => do let st ← read let p ← parseParams paramType params let t ← handler id p let t₁ ← (IO.mapTask · t) fun | Except.ok (Except.ok resp) => st.hOut.writeLspResponse ⟨id, resp⟩ | Except.ok (Except.error e) => st.hOut.writeLspResponseError { id := id, code := e.code, message := e.message } | Except.error e => st.hOut.writeLspResponseError { id := id, code := ErrorCode.internalError, message := toString e } queueRequest id t₁ match method with | "textDocument/waitForDiagnostics" => handle WaitForDiagnosticsParam WaitForDiagnostics handleWaitForDiagnostics | "textDocument/hover" => handle HoverParams (Option Hover) handleHover | "textDocument/documentSymbol" => handle DocumentSymbolParams DocumentSymbolResult handleDocumentSymbol | _ => throwServerError s!"Got unsupported request: {method}" end MessageHandling section MainLoop partial def mainLoop : ServerM Unit := do let st ← read let msg ← st.hIn.readLspMessage let pendingRequests ← st.pendingRequestsRef.get let filterFinishedTasks (acc : PendingRequestMap) (id : RequestID) (task : Task (Except IO.Error Unit)) : ServerM PendingRequestMap := do if (←hasFinished task) then /- Handler tasks are constructed so that the only possible errors here are failures of writing a response into the stream. -/ if let Except.error e := task.get then throwServerError s!"Failed responding to request {id}: {e}" acc.erase id else acc let pendingRequests ← pendingRequests.foldM filterFinishedTasks pendingRequests st.pendingRequestsRef.set pendingRequests match msg with | Message.request id method (some params) => handleRequest id method (toJson params) mainLoop | Message.notification "exit" none => -- should be sufficient to shut down the file worker. -- references are lost => tasks are marked as cancelled -- => all tasks eventually quit () | Message.notification method (some params) => handleNotification method (toJson params) mainLoop | _ => throwServerError "Got invalid JSON-RPC message" end MainLoop def initAndRunWorker (i o e : FS.Stream) : IO Unit := do let i ← maybeTee "fwIn.txt" false i let o ← maybeTee "fwOut.txt" true o -- TODO(WN): act in accordance with InitializeParams let _ ← i.readLspRequestAs "initialize" InitializeParams let ⟨_, param⟩ ← i.readLspNotificationAs "textDocument/didOpen" DidOpenTextDocumentParams let e ← e.withPrefix s!"[{param.textDocument.uri}] " let _ ← IO.setStderr e let ctx : ServerContext := { hIn := i hOut := o -- `openDocument` will not access `docRef`, but set it docRef := ←IO.mkRef arbitrary pendingRequestsRef := ←IO.mkRef (RBMap.empty : PendingRequestMap) } ReaderT.run (do handleDidOpen param; mainLoop) ctx @[export lean_server_worker_main] def workerMain : IO UInt32 := do let i ← IO.getStdin let o ← IO.getStdout let e ← IO.getStderr try initAndRunWorker i o e return 0 catch err => e.putStrLn s!"Worker error: {err}" return 1 end Lean.Server.FileWorker
7f28c7812a4fe59c1802f0c719890b53bd4a1576
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/ring_theory/integral_closure.lean
15c9d49791ee78b8f7b022d0c8b5a52276edf622
[ "Apache-2.0" ]
permissive
dexmagic/mathlib
ff48eefc56e2412429b31d4fddd41a976eb287ce
7a5d15a955a92a90e1d398b2281916b9c41270b2
refs/heads/master
1,693,481,322,046
1,633,360,193,000
1,633,360,193,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
33,052
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 ring_theory.adjoin.fg import ring_theory.polynomial.scale_roots import ring_theory.polynomial.tower /-! # Integral closure of a subring. 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 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 : polynomial R` evaluated under `f` -/ def ring_hom.is_integral_elem (f : R →+* A) (x : A) := ∃ p : polynomial R, 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 : polynomial R`. 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 -/ 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 : (polynomial R →ₗ[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) theorem is_integral_alg_hom (f : A →ₐ[R] B) {x : A} (hx : is_integral R x) : is_integral R (f x) := let ⟨p, hp, hpx⟩ := hx in ⟨p, hp, by rw [← aeval_def, aeval_alg_hom_apply, aeval_def, hpx, f.map_zero]⟩ @[simp] theorem is_integral_alg_equiv (f : A ≃ₐ[R] B) {x : A} : is_integral R (f x) ↔ is_integral R x := ⟨λ h, by simpa using is_integral_alg_hom f.symm.to_alg_hom h, is_integral_alg_hom 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, monic_map _ hp, by rw [← aeval_def, ← is_scalar_tower.aeval_apply, aeval_def, hpx]⟩ 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 x 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 := begin refine ⟨_, λ h, h.algebra_map⟩, rintros ⟨f, hf, hx⟩, use [f, hf], exact is_scalar_tower.aeval_eq_zero_of_aeval_algebra_map_eq_zero R A B hAB hx, end 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 ⟨_, set.finite_mem_finset _, p.restriction, monic_restriction.2 hmp, _⟩, erw [← aeval_def, is_scalar_tower.aeval_apply _ R, 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_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.product 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.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₁ = (algebra.adjoin S₀ (↑y : set A)).to_subring, { 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 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_mul _ _ (fg_adjoin_singleton_of_integral x hx) (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 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} /-- 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 is_integral_alg_hom f hx }, { intro hy, use [f.symm y, is_integral_alg_hom (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.gsmul {x : A} (h : is_integral R x) (n : ℤ) : is_integral R (n • x) := (integral_closure R A).gsmul_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 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 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 : polynomial A} (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 : polynomial (adjoin R S), 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 monic_map _ pmonic } }, { 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 : 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 is_integral_alg_hom (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 : is_integral R A) (hB : is_integral A B) : 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)) : 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, monic_map f hp, 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), ⟨monic_map (algebra_map R A) hp, _⟩⟩, 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 _), ⟨monic_map _ p_monic, _⟩⟩, 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 : is_integral R A) : is_integral (I.comap (algebra_map R A)).quotient I.quotient := (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 →+* I.quotient).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*} [integral_domain R] [integral_domain S] [algebra R S] (H : 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 : polynomial R` 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 (algebra_map R S).injective_iff.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, nat.sub_add_cancel (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, nat.sub_self, pow_zero, add_eq_zero_iff_eq_neg, eq_comm] at hq, rw [mul_comm, ← neg_mul_eq_neg_mul, finset.sum_mul], convert hq using 2, refine finset.sum_congr rfl (λ i hi, _), have : 1 ≤ p.nat_degree - i := nat.le_sub_left_of_add_le (finset.mem_range.mp hi), rw [mul_assoc, ← pow_succ', nat.sub_add_cancel this] end 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 integral_domain variables {R S : Type*} [comm_ring R] [integral_domain S] [algebra R S] instance : integral_domain (integral_closure R S) := infer_instance end integral_domain
43bff4085b770275b76726852cbbc30a89f940a1
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/simplifier20.lean
bb9b6584d8b2f4069e4ddb5e9e7e7b11ecb694e2
[ "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
535
lean
/- Basic rewriting with eq and generic congruence, with no conditionals -/ namespace test_congr constants a b c : nat axiom H1 : a = b axiom H2 : a = c attribute H1 [simp] attribute H2 [simp] #simplify eq env 0 a -- c attribute H1 [simp] [priority 20000] #simplify eq env 0 a -- b attribute H2 [simp] [priority 30000] #simplify eq env 0 a -- c attribute H1 [simp] [priority 20000] #simplify eq env 0 a -- c attribute H2 [simp] [priority 20000] attribute H1 [simp] [priority 20001] #simplify eq env 0 a -- b end test_congr
b66e1924fe09ff91a3110f1b642cf3283cbf9897
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/topology/subset_properties.lean
b8e32c76c145e52ed5bf835fb14e6d5622be76fb
[ "Apache-2.0" ]
permissive
vaibhavkarve/mathlib
a574aaf68c0a431a47fa82ce0637f0f769826bfe
17f8340912468f49bdc30acdb9a9fa02eeb0473a
refs/heads/master
1,621,263,802,637
1,585,399,588,000
1,585,399,588,000
250,833,447
0
0
Apache-2.0
1,585,410,341,000
1,585,410,341,000
null
UTF-8
Lean
false
false
54,722
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, Yury Kudryashov -/ import topology.continuous_on /-! # Properties of subsets of topological spaces ## Main definitions `compact`, `is_clopen`, `is_irreducible`, `is_connected`, `is_totally_disconnected`, `is_totally_separated` TODO: write better docs ## On the definition of irreducible and connected sets/spaces In informal mathematics, irreducible and connected spaces are assumed to be nonempty. We formalise the predicate without that assumption as `is_preirreducible` and `is_preconnected` respectively. In other words, the only difference is whether the empty space counts as irreducible and/or connected. There are good reasons to consider the empty space to be “too simple to be simple” See also https://ncatlab.org/nlab/show/too+simple+to+be+simple, and in particular https://ncatlab.org/nlab/show/too+simple+to+be+simple#relationship_to_biased_definitions. -/ open set filter classical open_locale classical topological_space universes u v variables {α : Type u} {β : Type v} [topological_space α] /- compact sets -/ section compact /-- A set `s` is compact if for every filter `f` that contains `s`, every set of `f` also meets every neighborhood of some `a ∈ s`. -/ def compact (s : set α) := ∀f, f ≠ ⊥ → f ≤ principal s → ∃a∈s, f ⊓ 𝓝 a ≠ ⊥ lemma compact.inter_right {s t : set α} (hs : compact s) (ht : is_closed t) : compact (s ∩ t) := assume f hnf hstf, let ⟨a, hsa, (ha : f ⊓ 𝓝 a ≠ ⊥)⟩ := hs f hnf (le_trans hstf (le_principal_iff.2 (inter_subset_left _ _))) in have a ∈ t, from ht.mem_of_nhds_within_ne_bot $ ne_bot_of_le_ne_bot (by { rw inf_comm at ha, exact ha }) $ inf_le_inf (le_refl _) (le_trans hstf (le_principal_iff.2 (inter_subset_right _ _))), ⟨a, ⟨hsa, this⟩, ha⟩ lemma compact.inter_left {s t : set α} (ht : compact t) (hs : is_closed s) : compact (s ∩ t) := inter_comm t s ▸ ht.inter_right hs lemma compact_diff {s t : set α} (hs : compact s) (ht : is_open t) : compact (s \ t) := hs.inter_right (is_closed_compl_iff.mpr ht) lemma compact_of_is_closed_subset {s t : set α} (hs : compact s) (ht : is_closed t) (h : t ⊆ s) : compact t := inter_eq_self_of_subset_right h ▸ hs.inter_right ht lemma compact.adherence_nhdset {s t : set α} {f : filter α} (hs : compact s) (hf₂ : f ≤ principal s) (ht₁ : is_open t) (ht₂ : ∀a∈s, 𝓝 a ⊓ f ≠ ⊥ → a ∈ t) : t ∈ f := classical.by_cases mem_sets_of_eq_bot $ assume : f ⊓ principal (- t) ≠ ⊥, let ⟨a, ha, (hfa : f ⊓ principal (-t) ⊓ 𝓝 a ≠ ⊥)⟩ := hs _ this $ inf_le_left_of_le hf₂ in have a ∈ t, from ht₂ a ha $ ne_bot_of_le_ne_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_left, have (-t) ∩ t ∈ nhds_within a (-t), from inter_mem_nhds_within _ (mem_nhds_sets ht₁ this), have A : nhds_within a (-t) = ⊥, from empty_in_sets_eq_bot.1 $ compl_inter_self t ▸ this, have nhds_within a (-t) ≠ ⊥, from ne_bot_of_le_ne_bot hfa $ le_inf inf_le_right $ inf_le_left_of_le inf_le_right, absurd A this lemma compact_iff_ultrafilter_le_nhds {s : set α} : compact s ↔ (∀f, is_ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ 𝓝 a) := ⟨assume hs : compact s, assume f hf hfs, let ⟨a, ha, h⟩ := hs _ hf.left hfs in ⟨a, ha, le_of_ultrafilter hf h⟩, assume hs : (∀f, is_ultrafilter f → f ≤ principal s → ∃a∈s, f ≤ 𝓝 a), assume f hf hfs, let ⟨a, ha, (h : ultrafilter_of f ≤ 𝓝 a)⟩ := hs (ultrafilter_of f) (ultrafilter_ultrafilter_of hf) (le_trans ultrafilter_of_le hfs) in have ultrafilter_of f ⊓ 𝓝 a ≠ ⊥, by simp only [inf_of_le_left, h]; exact (ultrafilter_ultrafilter_of hf).left, ⟨a, ha, ne_bot_of_le_ne_bot this (inf_le_inf ultrafilter_of_le (le_refl _))⟩⟩ /-- For every open cover of a compact set, there exists a finite subcover. -/ lemma compact.elim_finite_subcover {s : set α} {ι : Type v} (hs : compact s) (U : ι → set α) (hUo : ∀i, is_open (U i)) (hsU : s ⊆ ⋃ i, U i) : ∃ t : finset ι, s ⊆ ⋃ i ∈ t, U i := classical.by_contradiction $ assume h, have h : ∀ t : finset ι, ¬ s ⊆ ⋃ i ∈ t, U i, from assume t ht, h ⟨t, ht⟩, let f : filter α := (⨅t:finset ι, principal (s - ⋃ i ∈ t, U i)), ⟨a, ha⟩ := (@ne_empty_iff_nonempty α s).1 (assume h', h ∅ $ h'.symm ▸ empty_subset _) in have f ≠ ⊥, from infi_ne_bot_of_directed ⟨a⟩ (assume t₁ t₂, ⟨t₁ ∪ t₂, principal_mono.mpr $ diff_subset_diff_right $ bUnion_subset_bUnion_left $ finset.subset_union_left _ _, principal_mono.mpr $ diff_subset_diff_right $ bUnion_subset_bUnion_left $ finset.subset_union_right _ _⟩) (assume t, show principal (s \ _) ≠ ⊥, by simp only [ne.def, principal_eq_bot_iff, diff_eq_empty]; exact h _), have f ≤ principal s, from infi_le_of_le ∅ $ show principal (s \ _) ≤ principal s, from le_principal_iff.2 (diff_subset _ _), let ⟨a, ha, (h : f ⊓ 𝓝 a ≠ ⊥)⟩ := hs f ‹f ≠ ⊥› this, ⟨_, ⟨i, rfl⟩, (ha : a ∈ U i)⟩ := hsU ha in have f ≤ principal (- U i), from infi_le_of_le {i} $ principal_mono.mpr $ show s - _ ⊆ - U i, by simp [diff_subset_iff], have is_closed (- U i), from is_open_compl_iff.mp $ by rw compl_compl; exact hUo i, have a ∈ - U i, from is_closed_iff_nhds.mp this _ $ ne_bot_of_le_ne_bot h $ le_inf inf_le_right (inf_le_left_of_le ‹f ≤ principal (- U i)›), this ‹a ∈ U i› /-- For every family of closed sets whose intersection avoids a compact set, there exists a finite subfamily whose intersection avoids this compact set. -/ lemma compact.elim_finite_subfamily_closed {s : set α} {ι : Type v} (hs : compact s) (Z : ι → set α) (hZc : ∀i, is_closed (Z i)) (hsZ : s ∩ (⋂ i, Z i) = ∅) : ∃ t : finset ι, s ∩ (⋂ i ∈ t, Z i) = ∅ := let ⟨t, ht⟩ := hs.elim_finite_subcover (λ i, - Z i) hZc (by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union, exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using hsZ) in ⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union, exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using ht⟩ /-- Cantor's intersection theorem: the intersection of a directed family of nonempty compact closed sets is nonempty. -/ lemma compact.nonempty_Inter_of_directed_nonempty_compact_closed {ι : Type v} [hι : nonempty ι] (Z : ι → set α) (hZd : directed (⊇) Z) (hZn : ∀ i, (Z i).nonempty) (hZc : ∀ i, compact (Z i)) (hZcl : ∀ i, is_closed (Z i)) : (⋂ i, Z i).nonempty := begin apply hι.elim, intro i₀, let Z' := λ i, Z i ∩ Z i₀, suffices : (⋂ i, Z' i).nonempty, { exact nonempty.mono (Inter_subset_Inter $ assume i, inter_subset_left (Z i) (Z i₀)) this }, rw ← ne_empty_iff_nonempty, intro H, obtain ⟨t, ht⟩ : ∃ (t : finset ι), ((Z i₀) ∩ ⋂ (i ∈ t), Z' i) = ∅, from (hZc i₀).elim_finite_subfamily_closed Z' (assume i, is_closed_inter (hZcl i) (hZcl i₀)) (by rw [H, inter_empty]), obtain ⟨i₁, hi₁⟩ : ∃ i₁ : ι, Z i₁ ⊆ Z i₀ ∧ ∀ i ∈ t, Z i₁ ⊆ Z' i, { rcases directed.finset_le hι hZd t with ⟨i, hi⟩, rcases hZd i i₀ with ⟨i₁, hi₁, hi₁₀⟩, use [i₁, hi₁₀], intros j hj, exact subset_inter (subset.trans hi₁ (hi j hj)) hi₁₀ }, suffices : ((Z i₀) ∩ ⋂ (i ∈ t), Z' i).nonempty, { rw ← ne_empty_iff_nonempty at this, contradiction }, refine nonempty.mono _ (hZn i₁), exact subset_inter hi₁.left (subset_bInter hi₁.right) end /-- Cantor's intersection theorem for sequences indexed by `ℕ`: the intersection of a decreasing sequence of nonempty compact closed sets is nonempty. -/ lemma compact.nonempty_Inter_of_sequence_nonempty_compact_closed (Z : ℕ → set α) (hZd : ∀ i, Z (i+1) ⊆ Z i) (hZn : ∀ i, (Z i).nonempty) (hZ0 : compact (Z 0)) (hZcl : ∀ i, is_closed (Z i)) : (⋂ i, Z i).nonempty := have Zmono : _, from @monotone_of_monotone_nat (order_dual _) _ Z hZd, have hZd : directed (⊇) Z, from directed_of_mono Z Zmono, have ∀ i, Z i ⊆ Z 0, from assume i, Zmono $ zero_le i, have hZc : ∀ i, compact (Z i), from assume i, compact_of_is_closed_subset hZ0 (hZcl i) (this i), compact.nonempty_Inter_of_directed_nonempty_compact_closed Z hZd hZn hZc hZcl /-- For every open cover of a compact set, there exists a finite subcover. -/ lemma compact.elim_finite_subcover_image {s : set α} {b : set β} {c : β → set α} (hs : compact s) (hc₁ : ∀i∈b, is_open (c i)) (hc₂ : s ⊆ ⋃i∈b, c i) : ∃b'⊆b, finite b' ∧ s ⊆ ⋃i∈b', c i := begin rcases hs.elim_finite_subcover (λ i, c i.1 : b → set α) _ _ with ⟨d, hd⟩, refine ⟨↑(d.image subtype.val), _, finset.finite_to_set _, _⟩, { intros i hi, erw finset.mem_image at hi, rcases hi with ⟨s, hsd, rfl⟩, exact s.property }, { refine subset.trans hd _, rintros x ⟨_, ⟨s, rfl⟩, ⟨_, ⟨hsd, rfl⟩, H⟩⟩, refine ⟨c s.val, ⟨s.val, _⟩, H⟩, simp [finset.mem_image_of_mem subtype.val hsd] }, { rintro ⟨i, hi⟩, exact hc₁ i hi }, { refine subset.trans hc₂ _, rintros x ⟨_, ⟨i, rfl⟩, ⟨_, ⟨hib, rfl⟩, H⟩⟩, exact ⟨_, ⟨⟨i, hib⟩, rfl⟩, H⟩ }, end /-- A set `s` is compact if for every family of closed sets whose intersection avoids `s`, there exists a finite subfamily whose intersection avoids `s`. -/ theorem compact_of_finite_subfamily_closed {s : set α} (h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) : compact s := assume f hfn hfs, classical.by_contradiction $ assume : ¬ (∃x∈s, f ⊓ 𝓝 x ≠ ⊥), have hf : ∀x∈s, 𝓝 x ⊓ f = ⊥, by simpa only [not_exists, not_not, inf_comm], have ¬ ∃x∈s, ∀t∈f.sets, x ∈ closure t, from assume ⟨x, hxs, hx⟩, have ∅ ∈ 𝓝 x ⊓ f, by rw [empty_in_sets_eq_bot, hf x hxs], let ⟨t₁, ht₁, t₂, ht₂, ht⟩ := by rw [mem_inf_sets] at this; exact this in have ∅ ∈ 𝓝 x ⊓ principal t₂, from (𝓝 x ⊓ principal t₂).sets_of_superset (inter_mem_inf_sets ht₁ (subset.refl t₂)) ht, have 𝓝 x ⊓ principal t₂ = ⊥, by rwa [empty_in_sets_eq_bot] at this, by simp only [closure_eq_nhds] at hx; exact hx t₂ ht₂ this, let ⟨t, ht⟩ := h (λ i : f.sets, closure i.1) (λ i, is_closed_closure) (by simpa [eq_empty_iff_forall_not_mem, not_exists]) in have (⋂i∈t, subtype.val i) ∈ f, from Inter_mem_sets t.finite_to_set $ assume i hi, i.2, have s ∩ (⋂i∈t, subtype.val i) ∈ f, from inter_mem_sets (le_principal_iff.1 hfs) this, have ∅ ∈ f, from mem_sets_of_superset this $ assume x ⟨hxs, hx⟩, let ⟨i, hit, hxi⟩ := (show ∃i ∈ t, x ∉ closure (subtype.val i), by { rw [eq_empty_iff_forall_not_mem] at ht, simpa [hxs, not_forall] using ht x }) in have x ∈ closure i.val, from subset_closure (mem_bInter_iff.mp hx i hit), show false, from hxi this, hfn $ by rwa [empty_in_sets_eq_bot] at this /-- A set `s` is compact if for every open cover of `s`, there exists a finite subcover. -/ lemma compact_of_finite_subcover {s : set α} (h : Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) → s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) : compact s := compact_of_finite_subfamily_closed $ assume ι Z hZc hsZ, let ⟨t, ht⟩ := h (λ i, - Z i) (assume i, is_open_compl_iff.mpr $ hZc i) (by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union, exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using hsZ) in ⟨t, by simpa only [subset_def, not_forall, eq_empty_iff_forall_not_mem, set.mem_Union, exists_prop, set.mem_inter_eq, not_and, iff_self, set.mem_Inter, set.mem_compl_eq] using ht⟩ /-- A set `s` is compact if and only if for every open cover of `s`, there exists a finite subcover. -/ lemma compact_iff_finite_subcover {s : set α} : compact s ↔ (Π {ι : Type u} (U : ι → (set α)), (∀ i, is_open (U i)) → s ⊆ (⋃ i, U i) → (∃ (t : finset ι), s ⊆ (⋃ i ∈ t, U i))) := ⟨assume hs ι, hs.elim_finite_subcover, compact_of_finite_subcover⟩ /-- A set `s` is compact if and only if for every family of closed sets whose intersection avoids `s`, there exists a finite subfamily whose intersection avoids `s`. -/ theorem compact_iff_finite_subfamily_closed {s : set α} : compact s ↔ (Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → s ∩ (⋂ i, Z i) = ∅ → (∃ (t : finset ι), s ∩ (⋂ i ∈ t, Z i) = ∅)) := ⟨assume hs ι, hs.elim_finite_subfamily_closed, compact_of_finite_subfamily_closed⟩ @[simp] lemma compact_empty : compact (∅ : set α) := assume f hnf hsf, not.elim hnf $ empty_in_sets_eq_bot.1 $ le_principal_iff.1 hsf @[simp] lemma compact_singleton {a : α} : compact ({a} : set α) := compact_of_finite_subcover $ assume ι U hUo hsU, let ⟨i, hai⟩ := (show ∃i : ι, a ∈ U i, from mem_Union.1 $ singleton_subset_iff.1 hsU) in ⟨{i}, singleton_subset_iff.2 (by simpa only [finset.bUnion_singleton])⟩ lemma set.finite.compact_bUnion {s : set β} {f : β → set α} (hs : finite s) (hf : ∀i ∈ s, compact (f i)) : compact (⋃i ∈ s, f i) := compact_of_finite_subcover $ assume ι U hUo hsU, have ∀i : subtype s, ∃t : finset ι, f i ⊆ (⋃ j ∈ t, U j), from assume ⟨i, hi⟩, (hf i hi).elim_finite_subcover _ hUo (calc f i ⊆ ⋃i ∈ s, f i : subset_bUnion_of_mem hi ... ⊆ ⋃j, U j : hsU), let ⟨finite_subcovers, h⟩ := axiom_of_choice this in by haveI : fintype (subtype s) := hs.fintype; exact let t := finset.bind finset.univ finite_subcovers in have (⋃i ∈ s, f i) ⊆ (⋃ i ∈ t, U i), from bUnion_subset $ assume i hi, calc f i ⊆ (⋃ j ∈ finite_subcovers ⟨i, hi⟩, U j) : (h ⟨i, hi⟩) ... ⊆ (⋃ j ∈ t, U j) : bUnion_subset_bUnion_left $ assume j hj, finset.mem_bind.mpr ⟨_, finset.mem_univ _, hj⟩, ⟨t, this⟩ lemma compact_Union {f : β → set α} [fintype β] (h : ∀i, compact (f i)) : compact (⋃i, f i) := by rw ← bUnion_univ; exact finite_univ.compact_bUnion (λ i _, h i) lemma set.finite.compact {s : set α} (hs : finite s) : compact s := bUnion_of_singleton s ▸ hs.compact_bUnion (λ _ _, compact_singleton) lemma compact.union {s t : set α} (hs : compact s) (ht : compact t) : compact (s ∪ t) := by rw union_eq_Union; exact compact_Union (λ b, by cases b; assumption) section tube_lemma variables [topological_space β] /-- `nhds_contain_boxes s t` means that any open neighborhood of `s × t` in `α × β` includes a product of an open neighborhood of `s` by an open neighborhood of `t`. -/ def nhds_contain_boxes (s : set α) (t : set β) : Prop := ∀ (n : set (α × β)) (hn : is_open n) (hp : set.prod s t ⊆ n), ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n lemma nhds_contain_boxes.symm {s : set α} {t : set β} : nhds_contain_boxes s t → nhds_contain_boxes t s := assume H n hn hp, let ⟨u, v, uo, vo, su, tv, p⟩ := H (prod.swap ⁻¹' n) (continuous_swap n hn) (by rwa [←image_subset_iff, prod.swap, image_swap_prod]) in ⟨v, u, vo, uo, tv, su, by rwa [←image_subset_iff, prod.swap, image_swap_prod] at p⟩ lemma nhds_contain_boxes.comm {s : set α} {t : set β} : nhds_contain_boxes s t ↔ nhds_contain_boxes t s := iff.intro nhds_contain_boxes.symm nhds_contain_boxes.symm lemma nhds_contain_boxes_of_singleton {x : α} {y : β} : nhds_contain_boxes ({x} : set α) ({y} : set β) := assume n hn hp, let ⟨u, v, uo, vo, xu, yv, hp'⟩ := is_open_prod_iff.mp hn x y (hp $ by simp) in ⟨u, v, uo, vo, by simpa, by simpa, hp'⟩ lemma nhds_contain_boxes_of_compact {s : set α} (hs : compact s) (t : set β) (H : ∀ x ∈ s, nhds_contain_boxes ({x} : set α) t) : nhds_contain_boxes s t := assume n hn hp, have ∀x : subtype s, ∃uv : set α × set β, is_open uv.1 ∧ is_open uv.2 ∧ {↑x} ⊆ uv.1 ∧ t ⊆ uv.2 ∧ set.prod uv.1 uv.2 ⊆ n, from assume ⟨x, hx⟩, have set.prod {x} t ⊆ n, from subset.trans (prod_mono (by simpa) (subset.refl _)) hp, let ⟨ux,vx,H1⟩ := H x hx n hn this in ⟨⟨ux,vx⟩,H1⟩, let ⟨uvs, h⟩ := classical.axiom_of_choice this in have us_cover : s ⊆ ⋃i, (uvs i).1, from assume x hx, set.subset_Union _ ⟨x,hx⟩ (by simpa using (h ⟨x,hx⟩).2.2.1), let ⟨s0, s0_cover⟩ := hs.elim_finite_subcover _ (λi, (h i).1) us_cover in let u := ⋃(i ∈ s0), (uvs i).1 in let v := ⋂(i ∈ s0), (uvs i).2 in have is_open u, from is_open_bUnion (λi _, (h i).1), have is_open v, from is_open_bInter s0.finite_to_set (λi _, (h i).2.1), have t ⊆ v, from subset_bInter (λi _, (h i).2.2.2.1), have set.prod u v ⊆ n, from assume ⟨x',y'⟩ ⟨hx',hy'⟩, have ∃i ∈ s0, x' ∈ (uvs i).1, by simpa using hx', let ⟨i,is0,hi⟩ := this in (h i).2.2.2.2 ⟨hi, (bInter_subset_of_mem is0 : v ⊆ (uvs i).2) hy'⟩, ⟨u, v, ‹is_open u›, ‹is_open v›, s0_cover, ‹t ⊆ v›, ‹set.prod u v ⊆ n›⟩ lemma generalized_tube_lemma {s : set α} (hs : compact s) {t : set β} (ht : compact t) {n : set (α × β)} (hn : is_open n) (hp : set.prod s t ⊆ n) : ∃ (u : set α) (v : set β), is_open u ∧ is_open v ∧ s ⊆ u ∧ t ⊆ v ∧ set.prod u v ⊆ n := have _, from nhds_contain_boxes_of_compact hs t $ assume x _, nhds_contain_boxes.symm $ nhds_contain_boxes_of_compact ht {x} $ assume y _, nhds_contain_boxes_of_singleton, this n hn hp end tube_lemma /-- Type class for compact spaces. Separation is sometimes included in the definition, especially in the French literature, but we do not include it here. -/ class compact_space (α : Type*) [topological_space α] : Prop := (compact_univ : compact (univ : set α)) lemma compact_univ [h : compact_space α] : compact (univ : set α) := h.compact_univ lemma cluster_point_of_compact [compact_space α] {f : filter α} (h : f ≠ ⊥) : ∃ x, f ⊓ 𝓝 x ≠ ⊥ := by simpa using compact_univ f h (by simpa using f.univ_sets) theorem compact_space_of_finite_subfamily_closed {α : Type u} [topological_space α] (h : Π {ι : Type u} (Z : ι → (set α)), (∀ i, is_closed (Z i)) → (⋂ i, Z i) = ∅ → (∃ (t : finset ι), (⋂ i ∈ t, Z i) = ∅)) : compact_space α := { compact_univ := begin apply compact_of_finite_subfamily_closed, intros ι Z, specialize h Z, simpa using h end } lemma is_closed.compact [compact_space α] {s : set α} (h : is_closed s) : compact s := compact_of_is_closed_subset compact_univ h (subset_univ _) variables [topological_space β] lemma compact.image_of_continuous_on {s : set α} {f : α → β} (hs : compact s) (hf : continuous_on f s) : compact (f '' s) := begin intros l lne ls, have ne_bot : l.comap f ⊓ principal s ≠ ⊥, from comap_inf_principal_ne_bot_of_image_mem lne (le_principal_iff.1 ls), rcases hs (l.comap f ⊓ principal s) ne_bot inf_le_right with ⟨a, has, ha⟩, use [f a, mem_image_of_mem f has], rw [inf_assoc, @inf_comm _ _ _ (𝓝 a)] at ha, exact ne_bot_of_le_ne_bot (@@map_ne_bot f ha) (tendsto_comap.inf $ hf a has) end lemma compact.image {s : set α} {f : α → β} (hs : compact s) (hf : continuous f) : compact (f '' s) := hs.image_of_continuous_on hf.continuous_on lemma compact_range [compact_space α] {f : α → β} (hf : continuous f) : compact (range f) := by rw ← image_univ; exact compact_univ.image hf local notation `𝓟` := principal /-- If X is compact then pr₂ : X × Y → Y is a closed map -/ theorem is_closed_proj_of_compact {X : Type*} [topological_space X] [compact_space X] {Y : Type*} [topological_space Y] : is_closed_map (prod.snd : X × Y → Y) := begin set πX := (prod.fst : X × Y → X), set πY := (prod.snd : X × Y → Y), assume C (hC : is_closed C), rw is_closed_iff_nhds at hC ⊢, assume y (y_closure : 𝓝 y ⊓ 𝓟 (πY '' C) ≠ ⊥), have : map πX (comap πY (𝓝 y) ⊓ 𝓟 C) ≠ ⊥, { suffices : map πY (comap πY (𝓝 y) ⊓ 𝓟 C) ≠ ⊥, from map_ne_bot (λ h, this $ by rw h ; exact map_bot ), calc map πY (comap πY (𝓝 y) ⊓ 𝓟 C) = 𝓝 y ⊓ map πY (𝓟 C) : filter.push_pull' _ _ _ ... = 𝓝 y ⊓ 𝓟 (πY '' C) : by rw map_principal ... ≠ ⊥ : y_closure }, obtain ⟨x, hx⟩ : ∃ x, map πX (comap πY (𝓝 y) ⊓ 𝓟 C) ⊓ 𝓝 x ≠ ⊥, from cluster_point_of_compact this, refine ⟨⟨x, y⟩, _, by simp [πY]⟩, apply hC, rw ← filter.map_ne_bot_iff πX, calc map πX (𝓝 (x, y) ⊓ 𝓟 C) = map πX (comap πX (𝓝 x) ⊓ comap πY (𝓝 y) ⊓ 𝓟 C) : by rw [nhds_prod_eq, filter.prod] ... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C ⊓ comap πX (𝓝 x)) : by ac_refl ... = map πX (comap πY (𝓝 y) ⊓ 𝓟 C) ⊓ 𝓝 x : by rw filter.push_pull ... ≠ ⊥ : hx, end lemma embedding.compact_iff_compact_image {s : set α} {f : α → β} (hf : embedding f) : compact s ↔ compact (f '' s) := iff.intro (assume h, h.image hf.continuous) $ assume h, begin rw compact_iff_ultrafilter_le_nhds at ⊢ h, intros u hu us', let u' : filter β := map f u, have : u' ≤ principal (f '' s), begin rw [map_le_iff_le_comap, comap_principal], convert us', exact preimage_image_eq _ hf.inj end, rcases h u' (ultrafilter_map hu) this with ⟨_, ⟨a, ha, ⟨⟩⟩, _⟩, refine ⟨a, ha, _⟩, rwa [hf.induced, nhds_induced, ←map_le_iff_le_comap] end lemma compact_iff_compact_in_subtype {p : α → Prop} {s : set {a // p a}} : compact s ↔ compact (subtype.val '' s) := embedding_subtype_val.compact_iff_compact_image lemma compact_iff_compact_univ {s : set α} : compact s ↔ compact (univ : set (subtype s)) := by rw [compact_iff_compact_in_subtype, image_univ, subtype.val_range]; refl lemma compact_iff_compact_space {s : set α} : compact s ↔ compact_space s := compact_iff_compact_univ.trans ⟨λ h, ⟨h⟩, @compact_space.compact_univ _ _⟩ lemma compact.prod {s : set α} {t : set β} (hs : compact s) (ht : compact t) : compact (set.prod s t) := begin rw compact_iff_ultrafilter_le_nhds at hs ht ⊢, intros f hf hfs, rw le_principal_iff at hfs, rcases hs (map prod.fst f) (ultrafilter_map hf) (le_principal_iff.2 (mem_map_sets_iff.2 ⟨_, hfs, image_subset_iff.2 (λ s h, h.1)⟩)) with ⟨a, sa, ha⟩, rcases ht (map prod.snd f) (ultrafilter_map hf) (le_principal_iff.2 (mem_map_sets_iff.2 ⟨_, hfs, image_subset_iff.2 (λ s h, h.2)⟩)) with ⟨b, tb, hb⟩, rw map_le_iff_le_comap at ha hb, refine ⟨⟨a, b⟩, ⟨sa, tb⟩, _⟩, rw nhds_prod_eq, exact le_inf ha hb end /-- Finite topological spaces are compact. -/ @[priority 100] instance fintype.compact_space [fintype α] : compact_space α := { compact_univ := set.finite_univ.compact } /-- The product of two compact spaces is compact. -/ instance [compact_space α] [compact_space β] : compact_space (α × β) := ⟨by { rw ← univ_prod_univ, exact compact_univ.prod compact_univ }⟩ /-- The disjoint union of two compact spaces is compact. -/ instance [compact_space α] [compact_space β] : compact_space (α ⊕ β) := ⟨begin rw ← range_inl_union_range_inr, exact (compact_range continuous_inl).union (compact_range continuous_inr) end⟩ section tychonoff variables {ι : Type*} {π : ι → Type*} [∀i, topological_space (π i)] /-- Tychonoff's theorem -/ lemma compact_pi_infinite {s : Πi:ι, set (π i)} : (∀i, compact (s i)) → compact {x : Πi:ι, π i | ∀i, x i ∈ s i} := begin simp [compact_iff_ultrafilter_le_nhds, nhds_pi], exact assume h f hf hfs, let p : Πi:ι, filter (π i) := λi, map (λx:Πi:ι, π i, x i) f in have ∀i:ι, ∃a, a∈s i ∧ p i ≤ 𝓝 a, from assume i, h i (p i) (ultrafilter_map hf) $ show (λx:Πi:ι, π i, x i) ⁻¹' s i ∈ f.sets, from mem_sets_of_superset hfs $ assume x (hx : ∀i, x i ∈ s i), hx i, let ⟨a, ha⟩ := classical.axiom_of_choice this in ⟨a, assume i, (ha i).left, assume i, map_le_iff_le_comap.mp $ (ha i).right⟩ end instance pi.compact [∀i:ι, compact_space (π i)] : compact_space (Πi, π i) := ⟨begin have A : compact {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} := compact_pi_infinite (λi, compact_univ), have : {x : Πi:ι, π i | ∀i, x i ∈ (univ : set (π i))} = univ := by ext; simp, rwa this at A, end⟩ end tychonoff instance quot.compact_space {r : α → α → Prop} [compact_space α] : compact_space (quot r) := ⟨by { rw ← range_quot_mk, exact compact_range continuous_quot_mk }⟩ instance quotient.compact_space {s : setoid α} [compact_space α] : compact_space (quotient s) := quot.compact_space /-- There are various definitions of "locally compact space" in the literature, which agree for Hausdorff spaces but not in general. This one is the precise condition on X needed for the evaluation `map C(X, Y) × X → Y` to be continuous for all `Y` when `C(X, Y)` is given the compact-open topology. -/ class locally_compact_space (α : Type*) [topological_space α] : Prop := (local_compact_nhds : ∀ (x : α) (n ∈ 𝓝 x), ∃ s ∈ 𝓝 x, s ⊆ n ∧ compact s) end compact section clopen /-- A set is clopen if it is both open and closed. -/ def is_clopen (s : set α) : Prop := is_open s ∧ is_closed s theorem is_clopen_union {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∪ t) := ⟨is_open_union hs.1 ht.1, is_closed_union hs.2 ht.2⟩ theorem is_clopen_inter {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s ∩ t) := ⟨is_open_inter hs.1 ht.1, is_closed_inter hs.2 ht.2⟩ @[simp] theorem is_clopen_empty : is_clopen (∅ : set α) := ⟨is_open_empty, is_closed_empty⟩ @[simp] theorem is_clopen_univ : is_clopen (univ : set α) := ⟨is_open_univ, is_closed_univ⟩ theorem is_clopen_compl {s : set α} (hs : is_clopen s) : is_clopen (-s) := ⟨hs.2, is_closed_compl_iff.2 hs.1⟩ @[simp] theorem is_clopen_compl_iff {s : set α} : is_clopen (-s) ↔ is_clopen s := ⟨λ h, compl_compl s ▸ is_clopen_compl h, is_clopen_compl⟩ theorem is_clopen_diff {s t : set α} (hs : is_clopen s) (ht : is_clopen t) : is_clopen (s-t) := is_clopen_inter hs (is_clopen_compl ht) end clopen section preirreducible /-- A preirreducible set `s` is one where there is no non-trivial pair of disjoint opens on `s`. -/ def is_preirreducible (s : set α) : Prop := ∀ (u v : set α), is_open u → is_open v → (s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty /-- An irreducible set `s` is one that is nonempty and where there is no non-trivial pair of disjoint opens on `s`. -/ def is_irreducible (s : set α) : Prop := s.nonempty ∧ is_preirreducible s lemma is_irreducible.nonempty {s : set α} (h : is_irreducible s) : s.nonempty := h.1 lemma is_irreducible.is_preirreducible {s : set α} (h : is_irreducible s) : is_preirreducible s := h.2 theorem is_preirreducible_empty : is_preirreducible (∅ : set α) := λ _ _ _ _ _ ⟨x, h1, h2⟩, h1.elim theorem is_irreducible_singleton {x} : is_irreducible ({x} : set α) := ⟨singleton_nonempty x, λ u v _ _ ⟨y, h1, h2⟩ ⟨z, h3, h4⟩, by rw mem_singleton_iff at h1 h3; substs y z; exact ⟨x, or.inl rfl, h2, h4⟩⟩ theorem is_preirreducible.closure {s : set α} (H : is_preirreducible s) : is_preirreducible (closure s) := λ u v hu hv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩, let ⟨p, hpu, hps⟩ := mem_closure_iff.1 hycs u hu hyu in let ⟨q, hqv, hqs⟩ := mem_closure_iff.1 hzcs v hv hzv in let ⟨r, hrs, hruv⟩ := H u v hu hv ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in ⟨r, subset_closure hrs, hruv⟩ lemma is_irreducible.closure {s : set α} (h : is_irreducible s) : is_irreducible (closure s) := ⟨h.nonempty.closure, h.is_preirreducible.closure⟩ theorem exists_preirreducible (s : set α) (H : is_preirreducible s) : ∃ t : set α, is_preirreducible t ∧ s ⊆ t ∧ ∀ u, is_preirreducible u → t ⊆ u → u = t := let ⟨m, hm, hsm, hmm⟩ := zorn.zorn_subset₀ {t : set α | is_preirreducible t} (λ c hc hcc hcn, let ⟨t, htc⟩ := hcn in ⟨⋃₀ c, λ u v hu hv ⟨y, hy, hyu⟩ ⟨z, hz, hzv⟩, let ⟨p, hpc, hyp⟩ := mem_sUnion.1 hy, ⟨q, hqc, hzq⟩ := mem_sUnion.1 hz in or.cases_on (zorn.chain.total hcc hpc hqc) (assume hpq : p ⊆ q, let ⟨x, hxp, hxuv⟩ := hc hqc u v hu hv ⟨y, hpq hyp, hyu⟩ ⟨z, hzq, hzv⟩ in ⟨x, mem_sUnion_of_mem hxp hqc, hxuv⟩) (assume hqp : q ⊆ p, let ⟨x, hxp, hxuv⟩ := hc hpc u v hu hv ⟨y, hyp, hyu⟩ ⟨z, hqp hzq, hzv⟩ in ⟨x, mem_sUnion_of_mem hxp hpc, hxuv⟩), λ x hxc, set.subset_sUnion_of_mem hxc⟩) s H in ⟨m, hm, hsm, λ u hu hmu, hmm _ hu hmu⟩ /-- A maximal irreducible set that contains a given point. -/ def irreducible_component (x : α) : set α := classical.some (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible) lemma irreducible_component_property (x : α) : is_preirreducible (irreducible_component x) ∧ {x} ⊆ (irreducible_component x) ∧ ∀ u, is_preirreducible u → (irreducible_component x) ⊆ u → u = (irreducible_component x) := classical.some_spec (exists_preirreducible {x} is_irreducible_singleton.is_preirreducible) theorem mem_irreducible_component {x : α} : x ∈ irreducible_component x := singleton_subset_iff.1 (irreducible_component_property x).2.1 theorem is_irreducible_irreducible_component {x : α} : is_irreducible (irreducible_component x) := ⟨⟨x, mem_irreducible_component⟩, (irreducible_component_property x).1⟩ theorem eq_irreducible_component {x : α} : ∀ {s : set α}, is_preirreducible s → irreducible_component x ⊆ s → s = irreducible_component x := (irreducible_component_property x).2.2 theorem is_closed_irreducible_component {x : α} : is_closed (irreducible_component x) := closure_eq_iff_is_closed.1 $ eq_irreducible_component is_irreducible_irreducible_component.is_preirreducible.closure subset_closure /-- A preirreducible space is one where there is no non-trivial pair of disjoint opens. -/ class preirreducible_space (α : Type u) [topological_space α] : Prop := (is_preirreducible_univ : is_preirreducible (univ : set α)) section prio set_option default_priority 100 -- see Note [default priority] /-- An irreducible space is one that is nonempty and where there is no non-trivial pair of disjoint opens. -/ class irreducible_space (α : Type u) [topological_space α] extends preirreducible_space α : Prop := (to_nonempty : nonempty α) end prio attribute [instance, priority 50] irreducible_space.to_nonempty -- see Note [lower instance priority] theorem nonempty_preirreducible_inter [preirreducible_space α] {s t : set α} : is_open s → is_open t → s.nonempty → t.nonempty → (s ∩ t).nonempty := by simpa only [univ_inter, univ_subset_iff] using @preirreducible_space.is_preirreducible_univ α _ _ s t theorem is_preirreducible.image [topological_space β] {s : set α} (H : is_preirreducible s) (f : α → β) (hf : continuous_on f s) : is_preirreducible (f '' s) := begin rintros u v hu hv ⟨_, ⟨⟨x, hx, rfl⟩, hxu⟩⟩ ⟨_, ⟨⟨y, hy, rfl⟩, hyv⟩⟩, rw ← set.mem_preimage at hxu hyv, rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩, rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩, have := H u' v' hu' hv', rw [set.inter_comm s u', ← u'_eq] at this, rw [set.inter_comm s v', ← v'_eq] at this, rcases this ⟨x, hxu, hx⟩ ⟨y, hyv, hy⟩ with ⟨z, hzs, hzu', hzv'⟩, refine ⟨f z, mem_image_of_mem f hzs, _, _⟩, all_goals { rw ← set.mem_preimage, apply set.mem_of_mem_inter_left, show z ∈ _ ∩ s, simp [*] } end theorem is_irreducible.image [topological_space β] {s : set α} (H : is_irreducible s) (f : α → β) (hf : continuous_on f s) : is_irreducible (f '' s) := ⟨nonempty_image_iff.mpr H.nonempty, H.is_preirreducible.image f hf⟩ lemma subtype.preirreducible_space {s : set α} (h : is_preirreducible s) : preirreducible_space s := { is_preirreducible_univ := begin intros u v hu hv hsu hsv, rw is_open_induced_iff at hu hv, rcases hu with ⟨u, hu, rfl⟩, rcases hv with ⟨v, hv, rfl⟩, rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩, rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩, rcases h u v hu hv ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩, exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩ end } lemma subtype.irreducible_space {s : set α} (h : is_irreducible s) : irreducible_space s := { is_preirreducible_univ := (subtype.preirreducible_space h.is_preirreducible).is_preirreducible_univ, to_nonempty := h.nonempty.to_subtype } /-- A set `s` is irreducible if and only if for every finite collection of open sets all of whose members intersect `s`, `s` also intersects the intersection of the entire collection (i.e., there is an element of `s` contained in every member of the collection). -/ lemma is_irreducible_iff_sInter {s : set α} : is_irreducible s ↔ ∀ (U : finset (set α)) (hU : ∀ u ∈ U, is_open u) (H : ∀ u ∈ U, (s ∩ u).nonempty), (s ∩ ⋂₀ ↑U).nonempty := begin split; intro h, { intro U, apply finset.induction_on U, { intros, simpa using h.nonempty }, { intros u U hu IH hU H, rw [finset.coe_insert, sInter_insert], apply h.2, { solve_by_elim [finset.mem_insert_self] }, { apply is_open_sInter (finset.finite_to_set U), intros, solve_by_elim [finset.mem_insert_of_mem] }, { solve_by_elim [finset.mem_insert_self] }, { apply IH, all_goals { intros, solve_by_elim [finset.mem_insert_of_mem] } } } }, { split, { simpa using h ∅ _ _; intro u; simp }, intros u v hu hv hu' hv', simpa using h {v,u} _ _, all_goals { intro t, rw [finset.insert_empty_eq_singleton, finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption } } end /-- A set is preirreducible if and only if for every cover by two closed sets, it is contained in one of the two covering sets. -/ lemma is_preirreducible_iff_closed_union_closed {s : set α} : is_preirreducible s ↔ ∀ (z₁ z₂ : set α), is_closed z₁ → is_closed z₂ → s ⊆ z₁ ∪ z₂ → s ⊆ z₁ ∨ s ⊆ z₂ := begin split, all_goals { intros h t₁ t₂ ht₁ ht₂, specialize h (-t₁) (-t₂), simp only [is_open_compl_iff, is_closed_compl_iff] at h, specialize h ht₁ ht₂ }, { contrapose!, simp only [not_subset], rintro ⟨⟨x, hx, hx'⟩, ⟨y, hy, hy'⟩⟩, rcases h ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩ with ⟨z, hz, hz'⟩, rw ← compl_union at hz', exact ⟨z, hz, hz'⟩ }, { rintro ⟨x, hx, hx'⟩ ⟨y, hy, hy'⟩, rw ← compl_inter at h, delta set.nonempty, rw imp_iff_not_or at h, contrapose! h, split, { intros z hz hz', exact h z ⟨hz, hz'⟩ }, { split; intro H; refine H _ ‹_›; assumption } } end /-- A set is irreducible if and only if for every cover by a finite collection of closed sets, it is contained in one of the members of the collection. -/ lemma is_irreducible_iff_sUnion_closed {s : set α} : is_irreducible s ↔ ∀ (Z : finset (set α)) (hZ : ∀ z ∈ Z, is_closed z) (H : s ⊆ ⋃₀ ↑Z), ∃ z ∈ Z, s ⊆ z := begin rw [is_irreducible, is_preirreducible_iff_closed_union_closed], split; intro h, { intro Z, apply finset.induction_on Z, { intros, rw [finset.coe_empty, sUnion_empty] at H, rcases h.1 with ⟨x, hx⟩, exfalso, tauto }, { intros z Z hz IH hZ H, cases h.2 z (⋃₀ ↑Z) _ _ _ with h' h', { exact ⟨z, finset.mem_insert_self _ _, h'⟩ }, { rcases IH _ h' with ⟨z', hz', hsz'⟩, { exact ⟨z', finset.mem_insert_of_mem hz', hsz'⟩ }, { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { solve_by_elim [finset.mem_insert_self] }, { rw sUnion_eq_bUnion, apply is_closed_bUnion (finset.finite_to_set Z), { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { simpa using H } } }, { split, { by_contradiction hs, simpa using h ∅ _ _, { intro z, simp }, { simpa [set.nonempty] using hs } }, intros z₁ z₂ hz₁ hz₂ H, have := h {z₂, z₁} _ _, simp only [exists_prop, finset.insert_empty_eq_singleton, finset.mem_insert, finset.mem_singleton] at this, { rcases this with ⟨z, rfl|rfl, hz⟩; tauto }, { intro t, rw [finset.insert_empty_eq_singleton, finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption }, { simpa using H } } end end preirreducible section preconnected /-- A preconnected set is one where there is no non-trivial open partition. -/ def is_preconnected (s : set α) : Prop := ∀ (u v : set α), is_open u → is_open v → s ⊆ u ∪ v → (s ∩ u).nonempty → (s ∩ v).nonempty → (s ∩ (u ∩ v)).nonempty /-- A connected set is one that is nonempty and where there is no non-trivial open partition. -/ def is_connected (s : set α) : Prop := s.nonempty ∧ is_preconnected s lemma is_connected.nonempty {s : set α} (h : is_connected s) : s.nonempty := h.1 lemma is_connected.is_preconnected {s : set α} (h : is_connected s) : is_preconnected s := h.2 theorem is_preirreducible.is_preconnected {s : set α} (H : is_preirreducible s) : is_preconnected s := λ _ _ hu hv _, H _ _ hu hv theorem is_irreducible.is_connected {s : set α} (H : is_irreducible s) : is_connected s := ⟨H.nonempty, H.is_preirreducible.is_preconnected⟩ theorem is_preconnected_empty : is_preconnected (∅ : set α) := is_preirreducible_empty.is_preconnected theorem is_connected_singleton {x} : is_connected ({x} : set α) := is_irreducible_singleton.is_connected /-- If any point of a set is joined to a fixed point by a preconnected subset, then the original set is preconnected as well. -/ theorem is_preconnected_of_forall {s : set α} (x : α) (H : ∀ y ∈ s, ∃ t ⊆ s, x ∈ t ∧ y ∈ t ∧ is_preconnected t) : is_preconnected s := begin rintros u v hu hv hs ⟨z, zs, zu⟩ ⟨y, ys, yv⟩, have xs : x ∈ s, by { rcases H y ys with ⟨t, ts, xt, yt, ht⟩, exact ts xt }, wlog xu : x ∈ u := hs xs using [u v y z, v u z y], rcases H y ys with ⟨t, ts, xt, yt, ht⟩, have := ht u v hu hv(subset.trans ts hs) ⟨x, xt, xu⟩ ⟨y, yt, yv⟩, exact this.imp (λ z hz, ⟨ts hz.1, hz.2⟩) end /-- If any two points of a set are contained in a preconnected subset, then the original set is preconnected as well. -/ theorem is_preconnected_of_forall_pair {s : set α} (H : ∀ x y ∈ s, ∃ t ⊆ s, x ∈ t ∧ y ∈ t ∧ is_preconnected t) : is_preconnected s := begin rintros u v hu hv hs ⟨x, xs, xu⟩ ⟨y, ys, yv⟩, rcases H x y xs ys with ⟨t, ts, xt, yt, ht⟩, have := ht u v hu hv(subset.trans ts hs) ⟨x, xt, xu⟩ ⟨y, yt, yv⟩, exact this.imp (λ z hz, ⟨ts hz.1, hz.2⟩) end /-- A union of a family of preconnected sets with a common point is preconnected as well. -/ theorem is_preconnected_sUnion (x : α) (c : set (set α)) (H1 : ∀ s ∈ c, x ∈ s) (H2 : ∀ s ∈ c, is_preconnected s) : is_preconnected (⋃₀ c) := begin apply is_preconnected_of_forall x, rintros y ⟨s, sc, ys⟩, exact ⟨s, subset_sUnion_of_mem sc, H1 s sc, ys, H2 s sc⟩ end theorem is_preconnected.union (x : α) {s t : set α} (H1 : x ∈ s) (H2 : x ∈ t) (H3 : is_preconnected s) (H4 : is_preconnected t) : is_preconnected (s ∪ t) := sUnion_pair s t ▸ is_preconnected_sUnion x {s, t} (by rintro r (rfl | rfl | h); [exact H2, exact H1, exact h.elim]) (by rintro r (rfl | rfl | h); [exact H4, exact H3, exact h.elim]) theorem is_connected.union {s t : set α} (H : (s ∩ t).nonempty) (Hs : is_connected s) (Ht : is_connected t) : is_connected (s ∪ t) := begin rcases H with ⟨x, hx⟩, refine ⟨⟨x, mem_union_left t (mem_of_mem_inter_left hx)⟩, _⟩, exact is_preconnected.union x (mem_of_mem_inter_left hx) (mem_of_mem_inter_right hx) Hs.is_preconnected Ht.is_preconnected end theorem is_preconnected.closure {s : set α} (H : is_preconnected s) : is_preconnected (closure s) := λ u v hu hv hcsuv ⟨y, hycs, hyu⟩ ⟨z, hzcs, hzv⟩, let ⟨p, hpu, hps⟩ := mem_closure_iff.1 hycs u hu hyu in let ⟨q, hqv, hqs⟩ := mem_closure_iff.1 hzcs v hv hzv in let ⟨r, hrs, hruv⟩ := H u v hu hv (subset.trans subset_closure hcsuv) ⟨p, hps, hpu⟩ ⟨q, hqs, hqv⟩ in ⟨r, subset_closure hrs, hruv⟩ theorem is_connected.closure {s : set α} (H : is_connected s) : is_connected (closure s) := ⟨H.nonempty.closure, H.is_preconnected.closure⟩ theorem is_preconnected.image [topological_space β] {s : set α} (H : is_preconnected s) (f : α → β) (hf : continuous_on f s) : is_preconnected (f '' s) := begin -- Unfold/destruct definitions in hypotheses rintros u v hu hv huv ⟨_, ⟨x, xs, rfl⟩, xu⟩ ⟨_, ⟨y, ys, rfl⟩, yv⟩, rcases continuous_on_iff'.1 hf u hu with ⟨u', hu', u'_eq⟩, rcases continuous_on_iff'.1 hf v hv with ⟨v', hv', v'_eq⟩, -- Reformulate `huv : f '' s ⊆ u ∪ v` in terms of `u'` and `v'` replace huv : s ⊆ u' ∪ v', { rw [image_subset_iff, preimage_union] at huv, replace huv := subset_inter huv (subset.refl _), rw [inter_distrib_right, u'_eq, v'_eq, ← inter_distrib_right] at huv, exact (subset_inter_iff.1 huv).1 }, -- Now `s ⊆ u' ∪ v'`, so we can apply `‹is_preconnected s›` obtain ⟨z, hz⟩ : (s ∩ (u' ∩ v')).nonempty, { refine H u' v' hu' hv' huv ⟨x, _⟩ ⟨y, _⟩; rw inter_comm, exacts [u'_eq ▸ ⟨xu, xs⟩, v'_eq ▸ ⟨yv, ys⟩] }, rw [← inter_self s, inter_assoc, inter_left_comm s u', ← inter_assoc, inter_comm s, inter_comm s, ← u'_eq, ← v'_eq] at hz, exact ⟨f z, ⟨z, hz.1.2, rfl⟩, hz.1.1, hz.2.1⟩ end theorem is_connected.image [topological_space β] {s : set α} (H : is_connected s) (f : α → β) (hf : continuous_on f s) : is_connected (f '' s) := ⟨nonempty_image_iff.mpr H.nonempty, H.is_preconnected.image f hf⟩ theorem is_preconnected_closed_iff {s : set α} : is_preconnected s ↔ ∀ t t', is_closed t → is_closed t' → s ⊆ t ∪ t' → (s ∩ t).nonempty → (s ∩ t').nonempty → (s ∩ (t ∩ t')).nonempty := ⟨begin rintros h t t' ht ht' htt' ⟨x, xs, xt⟩ ⟨y, ys, yt'⟩, by_contradiction h', rw [← ne_empty_iff_nonempty, ne.def, not_not, ← subset_compl_iff_disjoint, compl_inter] at h', have xt' : x ∉ t', from (h' xs).elim (absurd xt) id, have yt : y ∉ t, from (h' ys).elim id (absurd yt'), have := ne_empty_iff_nonempty.2 (h (-t) (-t') (is_open_compl_iff.2 ht) (is_open_compl_iff.2 ht') h' ⟨y, ys, yt⟩ ⟨x, xs, xt'⟩), rw [ne.def, ← compl_union, ← subset_compl_iff_disjoint, compl_compl] at this, contradiction end, begin rintros h u v hu hv huv ⟨x, xs, xu⟩ ⟨y, ys, yv⟩, by_contradiction h', rw [← ne_empty_iff_nonempty, ne.def, not_not, ← subset_compl_iff_disjoint, compl_inter] at h', have xv : x ∉ v, from (h' xs).elim (absurd xu) id, have yu : y ∉ u, from (h' ys).elim id (absurd yv), have := ne_empty_iff_nonempty.2 (h (-u) (-v) (is_closed_compl_iff.2 hu) (is_closed_compl_iff.2 hv) h' ⟨y, ys, yu⟩ ⟨x, xs, xv⟩), rw [ne.def, ← compl_union, ← subset_compl_iff_disjoint, compl_compl] at this, contradiction end⟩ /-- The connected component of a point is the maximal connected set that contains this point. -/ def connected_component (x : α) : set α := ⋃₀ { s : set α | is_preconnected s ∧ x ∈ s } theorem mem_connected_component {x : α} : x ∈ connected_component x := mem_sUnion_of_mem (mem_singleton x) ⟨is_connected_singleton.is_preconnected, mem_singleton x⟩ theorem is_connected_connected_component {x : α} : is_connected (connected_component x) := ⟨⟨x, mem_connected_component⟩, is_preconnected_sUnion x _ (λ _, and.right) (λ _, and.left)⟩ theorem subset_connected_component {x : α} {s : set α} (H1 : is_preconnected s) (H2 : x ∈ s) : s ⊆ connected_component x := λ z hz, mem_sUnion_of_mem hz ⟨H1, H2⟩ theorem is_closed_connected_component {x : α} : is_closed (connected_component x) := closure_eq_iff_is_closed.1 $ subset.antisymm (subset_connected_component is_connected_connected_component.closure.is_preconnected (subset_closure mem_connected_component)) subset_closure theorem irreducible_component_subset_connected_component {x : α} : irreducible_component x ⊆ connected_component x := subset_connected_component is_irreducible_irreducible_component.is_connected.is_preconnected mem_irreducible_component /-- A preconnected space is one where there is no non-trivial open partition. -/ class preconnected_space (α : Type u) [topological_space α] : Prop := (is_preconnected_univ : is_preconnected (univ : set α)) section prio set_option default_priority 100 -- see Note [default priority] /-- A connected space is a nonempty one where there is no non-trivial open partition. -/ class connected_space (α : Type u) [topological_space α] extends preconnected_space α : Prop := (to_nonempty : nonempty α) end prio attribute [instance, priority 50] connected_space.to_nonempty -- see Note [lower instance priority] @[priority 100] -- see Note [lower instance priority] instance preirreducible_space.preconnected_space (α : Type u) [topological_space α] [preirreducible_space α] : preconnected_space α := ⟨(preirreducible_space.is_preirreducible_univ α).is_preconnected⟩ @[priority 100] -- see Note [lower instance priority] instance irreducible_space.connected_space (α : Type u) [topological_space α] [irreducible_space α] : connected_space α := { to_nonempty := irreducible_space.to_nonempty α } theorem nonempty_inter [preconnected_space α] {s t : set α} : is_open s → is_open t → s ∪ t = univ → s.nonempty → t.nonempty → (s ∩ t).nonempty := by simpa only [univ_inter, univ_subset_iff] using @preconnected_space.is_preconnected_univ α _ _ s t theorem is_clopen_iff [preconnected_space α] {s : set α} : is_clopen s ↔ s = ∅ ∨ s = univ := ⟨λ hs, classical.by_contradiction $ λ h, have h1 : s ≠ ∅ ∧ -s ≠ ∅, from ⟨mt or.inl h, mt (λ h2, or.inr $ (by rw [← compl_compl s, h2, compl_empty] : s = univ)) h⟩, let ⟨_, h2, h3⟩ := nonempty_inter hs.1 hs.2 (union_compl_self s) (ne_empty_iff_nonempty.1 h1.1) (ne_empty_iff_nonempty.1 h1.2) in h3 h2, by rintro (rfl | rfl); [exact is_clopen_empty, exact is_clopen_univ]⟩ lemma subtype.preconnected_space {s : set α} (h : is_preconnected s) : preconnected_space s := { is_preconnected_univ := begin intros u v hu hv hs hsu hsv, rw is_open_induced_iff at hu hv, rcases hu with ⟨u, hu, rfl⟩, rcases hv with ⟨v, hv, rfl⟩, rcases hsu with ⟨⟨x, hxs⟩, hxs', hxu⟩, rcases hsv with ⟨⟨y, hys⟩, hys', hyv⟩, rcases h u v hu hv _ ⟨x, hxs, hxu⟩ ⟨y, hys, hyv⟩ with ⟨z, hzs, ⟨hzu, hzv⟩⟩, exact ⟨⟨z, hzs⟩, ⟨set.mem_univ _, ⟨hzu, hzv⟩⟩⟩, intros z hz, rcases hs (set.mem_univ ⟨z, hz⟩) with hzu|hzv, { left, assumption }, { right, assumption } end } lemma subtype.connected_space {s : set α} (h : is_connected s) : connected_space s := { is_preconnected_univ := (subtype.preconnected_space h.is_preconnected).is_preconnected_univ, to_nonempty := h.nonempty.to_subtype } /-- A set `s` is preconnected if and only if for every cover by two open sets that are disjoint on `s`, it is contained in one of the two covering sets. -/ lemma is_preconnected_iff_subset_of_disjoint {s : set α} : is_preconnected s ↔ ∀ (u v : set α) (hu : is_open u) (hv : is_open v) (hs : s ⊆ u ∪ v) (huv : s ∩ (u ∩ v) = ∅), s ⊆ u ∨ s ⊆ v := begin split; intro h, { intros u v hu hv hs huv, specialize h u v hu hv hs, contrapose! huv, rw ne_empty_iff_nonempty, simp [not_subset] at huv, rcases huv with ⟨⟨x, hxs, hxu⟩, ⟨y, hys, hyv⟩⟩, have hxv : x ∈ v := classical.or_iff_not_imp_left.mp (hs hxs) hxu, have hyu : y ∈ u := classical.or_iff_not_imp_right.mp (hs hys) hyv, exact h ⟨y, hys, hyu⟩ ⟨x, hxs, hxv⟩ }, { intros u v hu hv hs hsu hsv, rw ← ne_empty_iff_nonempty, intro H, specialize h u v hu hv hs H, contrapose H, apply ne_empty_iff_nonempty.mpr, cases h, { rcases hsv with ⟨x, hxs, hxv⟩, exact ⟨x, hxs, ⟨h hxs, hxv⟩⟩ }, { rcases hsu with ⟨x, hxs, hxu⟩, exact ⟨x, hxs, ⟨hxu, h hxs⟩⟩ } } end /-- A set `s` is connected if and only if for every cover by a finite collection of open sets that are pairwise disjoint on `s`, it is contained in one of the members of the collection. -/ lemma is_connected_iff_sUnion_disjoint_open {s : set α} : is_connected s ↔ ∀ (U : finset (set α)) (H : ∀ (u v : set α), u ∈ U → v ∈ U → (s ∩ (u ∩ v)).nonempty → u = v) (hU : ∀ u ∈ U, is_open u) (hs : s ⊆ ⋃₀ ↑U), ∃ u ∈ U, s ⊆ u := begin rw [is_connected, is_preconnected_iff_subset_of_disjoint], split; intro h, { intro U, apply finset.induction_on U, { rcases h.left, suffices : s ⊆ ∅ → false, { simpa }, intro, solve_by_elim }, { intros u U hu IH hs hU H, rw [finset.coe_insert, sUnion_insert] at H, cases h.2 u (⋃₀ ↑U) _ _ H _ with hsu hsU, { exact ⟨u, finset.mem_insert_self _ _, hsu⟩ }, { rcases IH _ _ hsU with ⟨v, hvU, hsv⟩, { exact ⟨v, finset.mem_insert_of_mem hvU, hsv⟩ }, { intros, apply hs; solve_by_elim [finset.mem_insert_of_mem] }, { intros, solve_by_elim [finset.mem_insert_of_mem] } }, { solve_by_elim [finset.mem_insert_self] }, { apply is_open_sUnion, intros, solve_by_elim [finset.mem_insert_of_mem] }, { apply eq_empty_of_subset_empty, rintro x ⟨hxs, hxu, hxU⟩, rw mem_sUnion at hxU, rcases hxU with ⟨v, hvU, hxv⟩, rcases hs u v (finset.mem_insert_self _ _) (finset.mem_insert_of_mem hvU) _ with rfl, { contradiction }, { exact ⟨x, hxs, hxu, hxv⟩ } } } }, { split, { rw ← ne_empty_iff_nonempty, by_contradiction hs, push_neg at hs, subst hs, simpa using h ∅ _ _ _; simp }, intros u v hu hv hs hsuv, rcases h {v, u} _ _ _ with ⟨t, ht, ht'⟩, { rw [finset.insert_empty_eq_singleton, finset.mem_insert, finset.mem_singleton] at ht, rcases ht with rfl|rfl; tauto }, { intros t₁ t₂ ht₁ ht₂ hst, rw ← ne_empty_iff_nonempty at hst, rw [finset.insert_empty_eq_singleton, finset.mem_insert, finset.mem_singleton] at ht₁ ht₂, rcases ht₁ with rfl|rfl; rcases ht₂ with rfl|rfl, all_goals { refl <|> contradiction <|> skip }, rw inter_comm t₁ at hst, contradiction }, { intro t, rw [finset.insert_empty_eq_singleton, finset.mem_insert, finset.mem_singleton], rintro (rfl|rfl); assumption }, { simpa using hs } } end end preconnected section totally_disconnected /-- A set is called totally disconnected if all of its connected components are singletons. -/ def is_totally_disconnected (s : set α) : Prop := ∀ t, t ⊆ s → is_preconnected t → subsingleton t theorem is_totally_disconnected_empty : is_totally_disconnected (∅ : set α) := λ t ht _, ⟨λ ⟨_, h⟩, (ht h).elim⟩ theorem is_totally_disconnected_singleton {x} : is_totally_disconnected ({x} : set α) := λ t ht _, ⟨λ ⟨p, hp⟩ ⟨q, hq⟩, subtype.eq $ show p = q, from (eq_of_mem_singleton (ht hp)).symm ▸ (eq_of_mem_singleton (ht hq)).symm⟩ /-- A space is totally disconnected if all of its connected components are singletons. -/ class totally_disconnected_space (α : Type u) [topological_space α] : Prop := (is_totally_disconnected_univ : is_totally_disconnected (univ : set α)) end totally_disconnected section totally_separated /-- A set `s` is called totally separated if any two points of this set can be separated by two disjoint open sets covering `s`. -/ def is_totally_separated (s : set α) : Prop := ∀ x ∈ s, ∀ y ∈ s, x ≠ y → ∃ u v : set α, is_open u ∧ is_open v ∧ x ∈ u ∧ y ∈ v ∧ s ⊆ u ∪ v ∧ u ∩ v = ∅ theorem is_totally_separated_empty : is_totally_separated (∅ : set α) := λ x, false.elim theorem is_totally_separated_singleton {x} : is_totally_separated ({x} : set α) := λ p hp q hq hpq, (hpq $ (eq_of_mem_singleton hp).symm ▸ (eq_of_mem_singleton hq).symm).elim theorem is_totally_disconnected_of_is_totally_separated {s : set α} (H : is_totally_separated s) : is_totally_disconnected s := λ t hts ht, ⟨λ ⟨x, hxt⟩ ⟨y, hyt⟩, subtype.eq $ classical.by_contradiction $ assume hxy : x ≠ y, let ⟨u, v, hu, hv, hxu, hyv, hsuv, huv⟩ := H x (hts hxt) y (hts hyt) hxy in let ⟨r, hrt, hruv⟩ := ht u v hu hv (subset.trans hts hsuv) ⟨x, hxt, hxu⟩ ⟨y, hyt, hyv⟩ in ((ext_iff _ _).1 huv r).1 hruv⟩ /-- A space is totally separated if any two points can be separated by two disjoint open sets covering the whole space. -/ class totally_separated_space (α : Type u) [topological_space α] : Prop := (is_totally_separated_univ : is_totally_separated (univ : set α)) @[priority 100] -- see Note [lower instance priority] instance totally_separated_space.totally_disconnected_space (α : Type u) [topological_space α] [totally_separated_space α] : totally_disconnected_space α := ⟨is_totally_disconnected_of_is_totally_separated $ totally_separated_space.is_totally_separated_univ α⟩ end totally_separated
ee3fa406c1ebc973c7d1bc1e7dfc9740aaa6aa89
d9ed0fce1c218297bcba93e046cb4e79c83c3af8
/library/init/meta/expr.lean
ea3efe83014206bd63c3267d4866d925d1af378c
[ "Apache-2.0" ]
permissive
leodemoura/lean_clone
005c63aa892a6492f2d4741ee3c2cb07a6be9d7f
cc077554b584d39bab55c360bc12a6fe7957afe6
refs/heads/master
1,610,506,475,484
1,482,348,354,000
1,482,348,543,000
77,091,586
0
0
null
null
null
null
UTF-8
Lean
false
false
7,645
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.level inductive binder_info | default | implicit | strict_implicit | inst_implicit | other meta constant macro_def : Type /- Reflect a C++ expr object. The VM replaces it with the C++ implementation. -/ meta inductive expr | var : unsigned → expr | sort : level → expr | const : name → list level → expr | mvar : name → expr → expr | local_const : name → name → binder_info → expr → expr | app : expr → expr → expr | lam : name → binder_info → expr → expr → expr | pi : name → binder_info → expr → expr → expr | elet : name → expr → expr → expr → expr | macro : macro_def → ∀ n : unsigned, (fin (unsigned.to_nat n) → expr) → expr meta instance : inhabited expr := ⟨expr.sort level.zero⟩ meta constant expr.mk_macro (d : macro_def) : list expr → expr meta constant expr.macro_def_name (d : macro_def) : name meta def expr.mk_var (n : nat) : expr := expr.var (unsigned.of_nat n) -- Compares expressions, including binder names. meta constant expr.has_decidable_eq : decidable_eq expr attribute [instance] expr.has_decidable_eq -- Compares expressions while ignoring binder names. meta constant expr.alpha_eqv : expr → expr → bool notation a ` =ₐ `:50 b:50 := expr.alpha_eqv a b = bool.tt meta constant expr.to_string : expr → string meta instance : has_to_string expr := has_to_string.mk expr.to_string /- Coercion for letting users write (f a) instead of (expr.app f a) -/ meta instance : has_coe_to_fun expr := { F := λ e, expr → expr, coe := λ e, expr.app e } meta constant expr.hash : expr → nat -- Compares expressions, ignoring binder names, and sorting by hash. meta constant expr.lt : expr → expr → bool -- Compares expressions, ignoring binder names. meta constant expr.lex_lt : expr → expr → bool -- Compares expressions, ignoring binder names, and sorting by hash. meta def expr.cmp (a b : expr) : ordering := if expr.lt a b then ordering.lt else if a =ₐ b then ordering.eq else ordering.gt meta constant expr.fold {α : Type} : expr → α → (expr → nat → α → α) → α meta constant expr.replace : expr → (expr → nat → option expr) → expr meta constant expr.abstract_local : expr → name → expr meta constant expr.abstract_locals : expr → list name → expr meta def expr.abstract : expr → expr → expr | e (expr.local_const n m bi t) := e^.abstract_local n | e _ := e meta constant expr.instantiate_var : expr → expr → expr meta constant expr.instantiate_vars : expr → list expr → expr meta constant expr.has_var : expr → bool meta constant expr.has_var_idx : expr → nat → bool meta constant expr.has_local : expr → bool meta constant expr.has_meta_var : expr → bool meta constant expr.lift_vars : expr → nat → nat → expr meta constant expr.lower_vars : expr → nat → nat → expr /- (copy_pos_info src tgt) copy position information from src to tgt. -/ meta constant expr.copy_pos_info : expr → expr → expr meta constant expr.is_internal_cnstr : expr → option unsigned meta constant expr.get_nat_value : expr → option nat namespace expr open decidable -- Compares expressions, ignoring binder names, and sorting by hash. meta instance : has_ordering expr := ⟨ expr.cmp ⟩ meta def app_of_list : expr → list expr → expr | f [] := f | f (p::ps) := app_of_list (f p) ps meta def is_app : expr → bool | (app f a) := tt | e := ff meta def app_fn : expr → expr | (app f a) := f | a := a meta def app_arg : expr → expr | (app f a) := a | a := a meta def get_app_fn : expr → expr | (app f a) := get_app_fn f | a := a meta def get_app_num_args : expr → nat | (app f a) := get_app_num_args f + 1 | e := 0 meta def get_app_args_aux : list expr → expr → list expr | r (app f a) := get_app_args_aux (a::r) f | r e := r meta def get_app_args : expr → list expr := get_app_args_aux [] meta def const_name : expr → name | (const n ls) := n | e := name.anonymous meta def is_constant : expr → bool | (const n ls) := tt | e := ff meta def is_local_constant : expr → bool | (local_const n m bi t) := tt | e := ff meta def local_uniq_name : expr → name | (local_const n m bi t) := n | e := name.anonymous meta def local_pp_name : expr → name | (local_const x n bi t) := n | e := name.anonymous meta def local_type : expr → expr | (local_const _ _ _ t) := t | e := e meta def is_constant_of : expr → name → bool | (const n₁ ls) n₂ := to_bool (n₁ = n₂) | e n := ff meta def is_app_of (e : expr) (n : name) : bool := is_constant_of (get_app_fn e) n meta def is_napp_of (e : expr) (c : name) (n : nat) : bool := to_bool (is_app_of e c ∧ get_app_num_args e = n) meta def is_false (e : expr) : bool := is_constant_of e `false meta def is_not : expr → option expr | (app f a) := if is_constant_of f `not then some a else none | (pi n bi a b) := if is_false b then some a else none | e := none meta def is_eq (e : expr) : option (expr × expr) := if is_napp_of e `eq 3 then some (app_arg (app_fn e), app_arg e) else none meta def is_ne (e : expr) : option (expr × expr) := if is_napp_of e `ne 3 then some (app_arg (app_fn e), app_arg e) else none meta def is_bin_arith_app (e : expr) (op : name) : option (expr × expr) := if is_napp_of e op 4 then some (app_arg (app_fn e), app_arg e) else none meta def is_lt (e : expr) : option (expr × expr) := is_bin_arith_app e `lt meta def is_gt (e : expr) : option (expr × expr) := is_bin_arith_app e `gt meta def is_le (e : expr) : option (expr × expr) := is_bin_arith_app e `le meta def is_ge (e : expr) : option (expr × expr) := is_bin_arith_app e `ge meta def is_heq (e : expr) : option (expr × expr × expr × expr) := if is_napp_of e `heq 4 then some (app_arg (app_fn (app_fn (app_fn e))), app_arg (app_fn (app_fn e)), app_arg (app_fn e), app_arg e) else none meta def is_pi : expr → bool | (pi n bi d b) := tt | e := ff meta def is_arrow : expr → bool | (pi n bi d b) := bnot (has_var b) | e := ff meta def is_let : expr → bool | (elet n t v b) := tt | e := ff meta def binding_name : expr → name | (pi n m d b) := n | (lam n m d b) := n | e := name.anonymous meta def binding_info : expr → binder_info | (pi n bi d b) := bi | (lam n bi d b) := bi | e := binder_info.default meta def binding_domain : expr → expr | (pi n bi d b) := d | (lam n bi d b) := d | e := e meta def binding_body : expr → expr | (pi n bi d b) := b | (lam n bi d b) := b | e := e meta def prop : expr := expr.sort level.zero meta def imp (a b : expr) : expr := pi `a binder_info.default a b meta def and_ (a b : expr) : expr := app (app (const ``and []) a) b meta def not_ (a : expr) : expr := app (const ``not []) a meta def false_ : expr := const ``false [] meta def lambdas : list expr → expr → expr | (local_const uniq pp info t :: es) f := lam pp info t (abstract_local (lambdas es f) uniq) | _ f := f meta def pis : list expr → expr → expr | (local_const uniq pp info t :: es) f := pi pp info t (abstract_local (pis es f) uniq) | _ f := f end expr
adef5a74051846aedb1f6d0eda22a705ca704aed
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/data/vector2.lean
249b1dbb44eff276a71e1510e3c386776d519e6e
[ "Apache-2.0" ]
permissive
sebzim4500/mathlib
e0b5a63b1655f910dee30badf09bd7e191d3cf30
6997cafbd3a7325af5cb318561768c316ceb7757
refs/heads/master
1,585,549,958,618
1,538,221,723,000
1,538,221,723,000
150,869,076
0
0
Apache-2.0
1,538,229,323,000
1,538,229,323,000
null
UTF-8
Lean
false
false
5,948
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Additional theorems about the `vector` type. -/ import data.vector data.list.basic data.sigma data.equiv.basic category.traversable namespace vector variables {α : Type*} {n : ℕ} attribute [simp] head_cons tail_cons instance [inhabited α] : inhabited (vector α n) := ⟨of_fn (λ _, default α)⟩ theorem to_list_injective : function.injective (@to_list α n) := subtype.val_injective @[simp] theorem to_list_of_fn : ∀ {n} (f : fin n → α), to_list (of_fn f) = list.of_fn f | 0 f := rfl | (n+1) f := by rw [of_fn, list.of_fn_succ, to_list_cons, to_list_of_fn] @[simp] theorem mk_to_list : ∀ (v : vector α n) h, (⟨to_list v, h⟩ : vector α n) = v | ⟨l, h₁⟩ h₂ := rfl theorem nth_eq_nth_le : ∀ (v : vector α n) (i), nth v i = v.to_list.nth_le i.1 (by rw to_list_length; exact i.2) | ⟨l, h⟩ i := rfl @[simp] theorem nth_of_fn {n} (f : fin n → α) (i) : nth (of_fn f) i = f i := by rw [nth_eq_nth_le, ← list.nth_le_of_fn f]; congr; apply to_list_of_fn @[simp] theorem of_fn_nth (v : vector α n) : of_fn (nth v) = v := begin rcases v with ⟨l, rfl⟩, apply to_list_injective, change nth ⟨l, eq.refl _⟩ with λ i, nth ⟨l, rfl⟩ i, simp [nth, list.of_fn_nth_le] end @[simp] theorem nth_tail : ∀ (v : vector α n.succ) (i : fin n), nth (tail v) i = nth v i.succ | ⟨a::l, e⟩ ⟨i, h⟩ := by simp [nth_eq_nth_le]; refl @[simp] theorem tail_of_fn {n : ℕ} (f : fin n.succ → α) : tail (of_fn f) = of_fn (λ i, f i.succ) := (of_fn_nth _).symm.trans $ by congr; funext i; simp theorem head'_to_list : ∀ (v : vector α n.succ), (to_list v).head' = some (head v) | ⟨a::l, e⟩ := rfl def reverse (v : vector α n) : vector α n := ⟨v.to_list.reverse, by simp⟩ @[simp] theorem nth_zero : ∀ (v : vector α n.succ), nth v 0 = head v | ⟨a::l, e⟩ := rfl @[simp] theorem head_of_fn {n : ℕ} (f : fin n.succ → α) : head (of_fn f) = f 0 := by rw [← nth_zero, nth_of_fn] @[simp] theorem nth_cons_zero (a : α) (v : vector α n) : nth (a :: v) 0 = a := by simp [nth_zero] @[simp] theorem nth_cons_succ (a : α) (v : vector α n) (i : fin n) : nth (a :: v) i.succ = nth v i := by rw [← nth_tail, tail_cons] def {u} m_of_fn {m} [monad m] {α : Type u} : ∀ {n}, (fin n → m α) → m (vector α n) | 0 f := pure nil | (n+1) f := do a ← f 0, v ← m_of_fn (λi, f i.succ), pure (a :: v) theorem m_of_fn_pure {m} [monad m] [is_lawful_monad m] {α} : ∀ {n} (f : fin n → α), @m_of_fn m _ _ _ (λ i, pure (f i)) = pure (of_fn f) | 0 f := rfl | (n+1) f := by simp [m_of_fn, @m_of_fn_pure n, of_fn] def {u} mmap {m} [monad m] {α} {β : Type u} (f : α → m β) : ∀ {n}, vector α n → m (vector β n) | _ ⟨[], rfl⟩ := pure nil | _ ⟨a::l, rfl⟩ := do h' ← f a, t' ← mmap ⟨l, rfl⟩, pure (h' :: t') @[simp] theorem mmap_nil {m} [monad m] {α β} (f : α → m β) : mmap f nil = pure nil := rfl @[simp] theorem mmap_cons {m} [monad m] {α β} (f : α → m β) (a) : ∀ {n} (v : vector α n), mmap f (a::v) = do h' ← f a, t' ← mmap f v, pure (h' :: t') | _ ⟨l, rfl⟩ := rfl @[extensionality] theorem ext : ∀ {v w : vector α n} (h : ∀ m : fin n, vector.nth v m = vector.nth w m), v = w | ⟨v, hv⟩ ⟨w, hw⟩ h := subtype.eq (list.ext_le (by rw [hv, hw]) (λ m hm hn, h ⟨m, hv ▸ hm⟩)) def to_array : vector α n → array n α | ⟨xs, h⟩ := cast (by rw h) xs.to_array end vector namespace vector universes u variables {n : ℕ} section traverse variables {F G : Type u → Type u} variables [applicative F] [applicative G] open applicative functor open list (cons) nat private def traverse_aux {α β : Type u} (f : α → F β) : Π (x : list α), F (vector β x.length) | [] := pure vector.nil | (x::xs) := vector.cons <$> f x <*> traverse_aux xs protected def traverse {α β : Type u} (f : α → F β) : vector α n → F (vector β n) | ⟨v, Hv⟩ := cast (by rw Hv) $ traverse_aux f v variables [is_lawful_applicative F] [is_lawful_applicative G] variables {α β γ : Type u} @[simp] protected lemma traverse_def (f : α → F β) (x : α) : ∀ (xs : vector α n), (x :: xs).traverse f = cons <$> f x <*> xs.traverse f := by rintro ⟨xs, rfl⟩; refl protected lemma id_traverse : ∀ (x : vector α n), x.traverse id.mk = x := begin rintro ⟨x, rfl⟩, dsimp [vector.traverse, cast], induction x with x xs IH, {refl}, simp! [IH], refl end open function protected lemma comp_traverse (f : β → F γ) (g : α → G β) : ∀ (x : vector α n), vector.traverse (comp.mk ∘ functor.map f ∘ g) x = comp.mk (vector.traverse f <$> vector.traverse g x) := by rintro ⟨x, rfl⟩; dsimp [vector.traverse, cast]; induction x with x xs; simp! [cast, *] with functor_norm; [refl, simp [(∘)]] protected lemma traverse_eq_map_id {α β} (f : α → β) : ∀ (x : vector α n), x.traverse (id.mk ∘ f) = id.mk (map f x) := by rintro ⟨x, rfl⟩; simp!; induction x; simp! * with functor_norm; refl variable (η : applicative_transformation F G) protected lemma naturality {α β : Type*} (f : α → F β) : ∀ (x : vector α n), η (x.traverse f) = x.traverse (@η _ ∘ f) := by rintro ⟨x, rfl⟩; simp! [cast]; induction x with x xs IH; simp! * with functor_norm end traverse instance : traversable.{u} (flip vector n) := { traverse := @vector.traverse n, map := λ α β, @vector.map.{u u} α β n } instance : is_lawful_traversable.{u} (flip vector n) := { id_traverse := @vector.id_traverse n, comp_traverse := @vector.comp_traverse n, traverse_eq_map_id := @vector.traverse_eq_map_id n, naturality := @vector.naturality n, id_map := by intros; cases x; simp! [(<$>)], comp_map := by intros; cases x; simp! [(<$>)] } end vector
6dbecfdf96bacbb5232c2726d08213adf9671a79
dd0f5513e11c52db157d2fcc8456d9401a6cd9da
/10_Structures_and_Records.org.7.lean
03cee2a71615f3668ba7b4b6e348779930f87d8a
[]
no_license
cjmazey/lean-tutorial
ba559a49f82aa6c5848b9bf17b7389bf7f4ba645
381f61c9fcac56d01d959ae0fa6e376f2c4e3b34
refs/heads/master
1,610,286,098,832
1,447,124,923,000
1,447,124,923,000
43,082,433
0
0
null
null
null
null
UTF-8
Lean
false
false
189
lean
import standard namespace hide -- BEGIN structure prod.{u} (A : Type.{u}) (B : Type.{u}) : Type.{max 1 u} := (pr1 : A) (pr2 : B) set_option pp.universes true check prod.mk -- END end hide
5894bffb26b7b17fda68d9adf110fb5fc46592a5
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/group_theory/perm/subgroup_auto.lean
a9a28552a9e5b7d8e0b834a1caa24f1aa97ecc34
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
1,553
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 Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.group_theory.perm.basic import Mathlib.data.fintype.basic import Mathlib.group_theory.subgroup import Mathlib.PostPort universes u_1 u_2 namespace Mathlib /-! # Lemmas about subgroups within the permutations (self-equivalences) of a type `α` This file provides extra lemmas about some `subgroup`s that exist within `equiv.perm α`. `group_theory.subgroup` depends on `group_theory.perm.basic`, so these need to be in a separate file. -/ namespace equiv namespace perm @[simp] theorem sum_congr_hom.card_range {α : Type u_1} {β : Type u_2} [fintype ↥(monoid_hom.range (sum_congr_hom α β))] [fintype (perm α × perm β)] : fintype.card ↥(monoid_hom.range (sum_congr_hom α β)) = fintype.card (perm α × perm β) := iff.mpr fintype.card_eq (Nonempty.intro (equiv.symm (set.range (⇑(sum_congr_hom α β)) sum_congr_hom_injective))) @[simp] theorem sigma_congr_right_hom.card_range {α : Type u_1} {β : α → Type u_2} [fintype ↥(monoid_hom.range (sigma_congr_right_hom β))] [fintype ((a : α) → perm (β a))] : fintype.card ↥(monoid_hom.range (sigma_congr_right_hom β)) = fintype.card ((a : α) → perm (β a)) := iff.mpr fintype.card_eq (Nonempty.intro (equiv.symm (set.range (⇑(sigma_congr_right_hom β)) sigma_congr_right_hom_injective))) end Mathlib
e5e887a95b77bf5ca873f24e773530724926b463
9dc8cecdf3c4634764a18254e94d43da07142918
/src/analysis/normed/group/add_torsor.lean
fcd36ce4130b02116149c4e5e803f53cdce16325
[ "Apache-2.0" ]
permissive
jcommelin/mathlib
d8456447c36c176e14d96d9e76f39841f69d2d9b
ee8279351a2e434c2852345c51b728d22af5a156
refs/heads/master
1,664,782,136,488
1,663,638,983,000
1,663,638,983,000
132,563,656
0
0
Apache-2.0
1,663,599,929,000
1,525,760,539,000
Lean
UTF-8
Lean
false
false
10,541
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Yury Kudryashov -/ import analysis.normed.group.basic import linear_algebra.affine_space.affine_subspace import linear_algebra.affine_space.midpoint /-! # Torsors of additive normed group actions. This file defines torsors of additive normed group actions, with a metric space structure. The motivating case is Euclidean affine spaces. -/ noncomputable theory open_locale nnreal topological_space open filter /-- A `normed_add_torsor V P` is a torsor of an additive seminormed group action by a `seminormed_add_comm_group V` on points `P`. We bundle the pseudometric space structure and require the distance to be the same as results from the norm (which in fact implies the distance yields a pseudometric space, but bundling just the distance and using an instance for the pseudometric space results in type class problems). -/ class normed_add_torsor (V : out_param $ Type*) (P : Type*) [out_param $ seminormed_add_comm_group V] [pseudo_metric_space P] extends add_torsor V P := (dist_eq_norm' : ∀ (x y : P), dist x y = ∥(x -ᵥ y : V)∥) variables {α V P W Q : Type*} [seminormed_add_comm_group V] [pseudo_metric_space P] [normed_add_torsor V P] [normed_add_comm_group W] [metric_space Q] [normed_add_torsor W Q] /-- A `seminormed_add_comm_group` is a `normed_add_torsor` over itself. -/ @[priority 100] instance seminormed_add_comm_group.to_normed_add_torsor : normed_add_torsor V V := { dist_eq_norm' := dist_eq_norm } /-- A nonempty affine subspace of a `normed_add_torsor` is itself a `normed_add_torsor`. -/ @[nolint fails_quickly] -- Because of the add_torsor.nonempty instance. instance affine_subspace.to_normed_add_torsor {R : Type*} [ring R] [module R V] (s : affine_subspace R P) [nonempty s] : normed_add_torsor s.direction s := { dist_eq_norm' := λ x y, normed_add_torsor.dist_eq_norm' ↑x ↑y, ..affine_subspace.to_add_torsor s } include V section variables (V W) /-- The distance equals the norm of subtracting two points. In this lemma, it is necessary to have `V` as an explicit argument; otherwise `rw dist_eq_norm_vsub` sometimes doesn't work. -/ lemma dist_eq_norm_vsub (x y : P) : dist x y = ∥x -ᵥ y∥ := normed_add_torsor.dist_eq_norm' x y /-- The distance equals the norm of subtracting two points. In this lemma, it is necessary to have `V` as an explicit argument; otherwise `rw dist_eq_norm_vsub'` sometimes doesn't work. -/ lemma dist_eq_norm_vsub' (x y : P) : dist x y = ∥y -ᵥ x∥ := (dist_comm _ _).trans (dist_eq_norm_vsub _ _ _) end @[simp] lemma dist_vadd_cancel_left (v : V) (x y : P) : dist (v +ᵥ x) (v +ᵥ y) = dist x y := by rw [dist_eq_norm_vsub V, dist_eq_norm_vsub V, vadd_vsub_vadd_cancel_left] @[simp] lemma dist_vadd_cancel_right (v₁ v₂ : V) (x : P) : dist (v₁ +ᵥ x) (v₂ +ᵥ x) = dist v₁ v₂ := by rw [dist_eq_norm_vsub V, dist_eq_norm, vadd_vsub_vadd_cancel_right] @[simp] lemma dist_vadd_left (v : V) (x : P) : dist (v +ᵥ x) x = ∥v∥ := by simp [dist_eq_norm_vsub V _ x] @[simp] lemma dist_vadd_right (v : V) (x : P) : dist x (v +ᵥ x) = ∥v∥ := by rw [dist_comm, dist_vadd_left] /-- Isometry between the tangent space `V` of a (semi)normed add torsor `P` and `P` given by addition/subtraction of `x : P`. -/ @[simps] def isometric.vadd_const (x : P) : V ≃ᵢ P := { to_equiv := equiv.vadd_const x, isometry_to_fun := isometry.of_dist_eq $ λ _ _, dist_vadd_cancel_right _ _ _ } section variable (P) /-- Self-isometry of a (semi)normed add torsor given by addition of a constant vector `x`. -/ @[simps] def isometric.const_vadd (x : V) : P ≃ᵢ P := { to_equiv := equiv.const_vadd P x, isometry_to_fun := isometry.of_dist_eq $ λ _ _, dist_vadd_cancel_left _ _ _ } end @[simp] lemma dist_vsub_cancel_left (x y z : P) : dist (x -ᵥ y) (x -ᵥ z) = dist y z := by rw [dist_eq_norm, vsub_sub_vsub_cancel_left, dist_comm, dist_eq_norm_vsub V] /-- Isometry between the tangent space `V` of a (semi)normed add torsor `P` and `P` given by subtraction from `x : P`. -/ @[simps] def isometric.const_vsub (x : P) : P ≃ᵢ V := { to_equiv := equiv.const_vsub x, isometry_to_fun := isometry.of_dist_eq $ λ y z, dist_vsub_cancel_left _ _ _ } @[simp] lemma dist_vsub_cancel_right (x y z : P) : dist (x -ᵥ z) (y -ᵥ z) = dist x y := (isometric.vadd_const z).symm.dist_eq x y section pointwise open_locale pointwise @[simp] lemma vadd_ball (x : V) (y : P) (r : ℝ) : x +ᵥ metric.ball y r = metric.ball (x +ᵥ y) r := (isometric.const_vadd P x).image_ball y r @[simp] lemma vadd_closed_ball (x : V) (y : P) (r : ℝ) : x +ᵥ metric.closed_ball y r = metric.closed_ball (x +ᵥ y) r := (isometric.const_vadd P x).image_closed_ball y r @[simp] lemma vadd_sphere (x : V) (y : P) (r : ℝ) : x +ᵥ metric.sphere y r = metric.sphere (x +ᵥ y) r := (isometric.const_vadd P x).image_sphere y r end pointwise lemma dist_vadd_vadd_le (v v' : V) (p p' : P) : dist (v +ᵥ p) (v' +ᵥ p') ≤ dist v v' + dist p p' := by simpa using dist_triangle (v +ᵥ p) (v' +ᵥ p) (v' +ᵥ p') lemma dist_vsub_vsub_le (p₁ p₂ p₃ p₄ : P) : dist (p₁ -ᵥ p₂) (p₃ -ᵥ p₄) ≤ dist p₁ p₃ + dist p₂ p₄ := by { rw [dist_eq_norm, vsub_sub_vsub_comm, dist_eq_norm_vsub V, dist_eq_norm_vsub V], exact norm_sub_le _ _ } lemma nndist_vadd_vadd_le (v v' : V) (p p' : P) : nndist (v +ᵥ p) (v' +ᵥ p') ≤ nndist v v' + nndist p p' := by simp only [← nnreal.coe_le_coe, nnreal.coe_add, ← dist_nndist, dist_vadd_vadd_le] lemma nndist_vsub_vsub_le (p₁ p₂ p₃ p₄ : P) : nndist (p₁ -ᵥ p₂) (p₃ -ᵥ p₄) ≤ nndist p₁ p₃ + nndist p₂ p₄ := by simp only [← nnreal.coe_le_coe, nnreal.coe_add, ← dist_nndist, dist_vsub_vsub_le] lemma edist_vadd_vadd_le (v v' : V) (p p' : P) : edist (v +ᵥ p) (v' +ᵥ p') ≤ edist v v' + edist p p' := by { simp only [edist_nndist], apply_mod_cast nndist_vadd_vadd_le } lemma edist_vsub_vsub_le (p₁ p₂ p₃ p₄ : P) : edist (p₁ -ᵥ p₂) (p₃ -ᵥ p₄) ≤ edist p₁ p₃ + edist p₂ p₄ := by { simp only [edist_nndist], apply_mod_cast nndist_vsub_vsub_le } omit V /-- The pseudodistance defines a pseudometric space structure on the torsor. This is not an instance because it depends on `V` to define a `metric_space P`. -/ def pseudo_metric_space_of_normed_add_comm_group_of_add_torsor (V P : Type*) [seminormed_add_comm_group V] [add_torsor V P] : pseudo_metric_space P := { dist := λ x y, ∥(x -ᵥ y : V)∥, dist_self := λ x, by simp, dist_comm := λ x y, by simp only [←neg_vsub_eq_vsub_rev y x, norm_neg], dist_triangle := begin intros x y z, change ∥x -ᵥ z∥ ≤ ∥x -ᵥ y∥ + ∥y -ᵥ z∥, rw ←vsub_add_vsub_cancel, apply norm_add_le end } /-- The distance defines a metric space structure on the torsor. This is not an instance because it depends on `V` to define a `metric_space P`. -/ def metric_space_of_normed_add_comm_group_of_add_torsor (V P : Type*) [normed_add_comm_group V] [add_torsor V P] : metric_space P := { dist := λ x y, ∥(x -ᵥ y : V)∥, dist_self := λ x, by simp, eq_of_dist_eq_zero := λ x y h, by simpa using h, dist_comm := λ x y, by simp only [←neg_vsub_eq_vsub_rev y x, norm_neg], dist_triangle := begin intros x y z, change ∥x -ᵥ z∥ ≤ ∥x -ᵥ y∥ + ∥y -ᵥ z∥, rw ←vsub_add_vsub_cancel, apply norm_add_le end } include V lemma lipschitz_with.vadd [pseudo_emetric_space α] {f : α → V} {g : α → P} {Kf Kg : ℝ≥0} (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (f +ᵥ g) := λ x y, calc edist (f x +ᵥ g x) (f y +ᵥ g y) ≤ edist (f x) (f y) + edist (g x) (g y) : edist_vadd_vadd_le _ _ _ _ ... ≤ Kf * edist x y + Kg * edist x y : add_le_add (hf x y) (hg x y) ... = (Kf + Kg) * edist x y : (add_mul _ _ _).symm lemma lipschitz_with.vsub [pseudo_emetric_space α] {f g : α → P} {Kf Kg : ℝ≥0} (hf : lipschitz_with Kf f) (hg : lipschitz_with Kg g) : lipschitz_with (Kf + Kg) (f -ᵥ g) := λ x y, calc edist (f x -ᵥ g x) (f y -ᵥ g y) ≤ edist (f x) (f y) + edist (g x) (g y) : edist_vsub_vsub_le _ _ _ _ ... ≤ Kf * edist x y + Kg * edist x y : add_le_add (hf x y) (hg x y) ... = (Kf + Kg) * edist x y : (add_mul _ _ _).symm lemma uniform_continuous_vadd : uniform_continuous (λ x : V × P, x.1 +ᵥ x.2) := (lipschitz_with.prod_fst.vadd lipschitz_with.prod_snd).uniform_continuous lemma uniform_continuous_vsub : uniform_continuous (λ x : P × P, x.1 -ᵥ x.2) := (lipschitz_with.prod_fst.vsub lipschitz_with.prod_snd).uniform_continuous @[priority 100] instance normed_add_torsor.to_has_continuous_vadd : has_continuous_vadd V P := { continuous_vadd := uniform_continuous_vadd.continuous } lemma continuous_vsub : continuous (λ x : P × P, x.1 -ᵥ x.2) := uniform_continuous_vsub.continuous lemma filter.tendsto.vsub {l : filter α} {f g : α → P} {x y : P} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) : tendsto (f -ᵥ g) l (𝓝 (x -ᵥ y)) := (continuous_vsub.tendsto (x, y)).comp (hf.prod_mk_nhds hg) section variables [topological_space α] lemma continuous.vsub {f g : α → P} (hf : continuous f) (hg : continuous g) : continuous (f -ᵥ g) := continuous_vsub.comp (hf.prod_mk hg : _) lemma continuous_at.vsub {f g : α → P} {x : α} (hf : continuous_at f x) (hg : continuous_at g x) : continuous_at (f -ᵥ g) x := hf.vsub hg lemma continuous_within_at.vsub {f g : α → P} {x : α} {s : set α} (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) : continuous_within_at (f -ᵥ g) s x := hf.vsub hg end section variables {R : Type*} [ring R] [topological_space R] [module R V] [has_continuous_smul R V] lemma filter.tendsto.line_map {l : filter α} {f₁ f₂ : α → P} {g : α → R} {p₁ p₂ : P} {c : R} (h₁ : tendsto f₁ l (𝓝 p₁)) (h₂ : tendsto f₂ l (𝓝 p₂)) (hg : tendsto g l (𝓝 c)) : tendsto (λ x, affine_map.line_map (f₁ x) (f₂ x) (g x)) l (𝓝 $ affine_map.line_map p₁ p₂ c) := (hg.smul (h₂.vsub h₁)).vadd h₁ lemma filter.tendsto.midpoint [invertible (2:R)] {l : filter α} {f₁ f₂ : α → P} {p₁ p₂ : P} (h₁ : tendsto f₁ l (𝓝 p₁)) (h₂ : tendsto f₂ l (𝓝 p₂)) : tendsto (λ x, midpoint R (f₁ x) (f₂ x)) l (𝓝 $ midpoint R p₁ p₂) := h₁.line_map h₂ tendsto_const_nhds end
dd22a3e062422a65d0cedcb253b36b4d8141e9e7
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/algebra/char_zero.lean
2640c7b6af0ead7196c20fef68ea277f06ece031
[ "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
3,196
lean
/- Copyright (c) 2014 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro Natural homomorphism from the natural numbers into a monoid with one. -/ import data.nat.cast algebra.field tactic.wlog /-- Typeclass for monoids with characteristic zero. (This is usually stated on fields but it makes sense for any additive monoid with 1.) -/ class char_zero (α : Type*) [add_monoid α] [has_one α] : Prop := (cast_injective : function.injective (coe : ℕ → α)) theorem char_zero_of_inj_zero {α : Type*} [add_monoid α] [has_one α] (add_left_cancel : ∀ a b c : α, a + b = a + c → b = c) (H : ∀ n:ℕ, (n:α) = 0 → n = 0) : char_zero α := ⟨λ m n, begin assume h, wlog hle : m ≤ n, cases nat.le.dest hle with k e, suffices : k = 0, by rw [← e, this, add_zero], apply H, apply add_left_cancel n, rw [← h, ← nat.cast_add, e, add_zero, h] end⟩ -- We have no `left_cancel_add_monoid`, so we restate it for `add_group` -- and `ordered_cancel_comm_monoid`. theorem add_group.char_zero_of_inj_zero {α : Type*} [add_group α] [has_one α] (H : ∀ n:ℕ, (n:α) = 0 → n = 0) : char_zero α := char_zero_of_inj_zero (@add_left_cancel _ _) H theorem ordered_cancel_comm_monoid.char_zero_of_inj_zero {α : Type*} [ordered_cancel_add_comm_monoid α] [has_one α] (H : ∀ n:ℕ, (n:α) = 0 → n = 0) : char_zero α := char_zero_of_inj_zero (@add_left_cancel _ _) H @[priority 100] -- see Note [lower instance priority] instance linear_ordered_semiring.to_char_zero {α : Type*} [linear_ordered_semiring α] : char_zero α := ordered_cancel_comm_monoid.char_zero_of_inj_zero $ λ n h, nat.eq_zero_of_le_zero $ (@nat.cast_le α _ _ _).1 (le_of_eq h) namespace nat variables {α : Type*} [add_monoid α] [has_one α] [char_zero α] theorem cast_injective : function.injective (coe : ℕ → α) := char_zero.cast_injective @[simp, elim_cast] theorem cast_inj {m n : ℕ} : (m : α) = n ↔ m = n := cast_injective.eq_iff @[simp, elim_cast] theorem cast_eq_zero {n : ℕ} : (n : α) = 0 ↔ n = 0 := by rw [← cast_zero, cast_inj] @[elim_cast] theorem cast_ne_zero {n : ℕ} : (n : α) ≠ 0 ↔ n ≠ 0 := not_congr cast_eq_zero end nat @[field_simps] lemma two_ne_zero' {α : Type*} [add_monoid α] [has_one α] [char_zero α] : (2:α) ≠ 0 := have ((2:ℕ):α) ≠ 0, from nat.cast_ne_zero.2 dec_trivial, by rwa [nat.cast_succ, nat.cast_one] at this section variables {α : Type*} [domain α] [char_zero α] lemma add_self_eq_zero {a : α} : a + a = 0 ↔ a = 0 := by simp only [(two_mul a).symm, mul_eq_zero, two_ne_zero', false_or] lemma bit0_eq_zero {a : α} : bit0 a = 0 ↔ a = 0 := add_self_eq_zero end section variables {α : Type*} [division_ring α] [char_zero α] @[simp] lemma half_add_self (a : α) : (a + a) / 2 = a := by rw [← mul_two, mul_div_cancel a two_ne_zero'] @[simp] lemma add_halves' (a : α) : a / 2 + a / 2 = a := by rw [← add_div, half_add_self] lemma sub_half (a : α) : a - a / 2 = a / 2 := by rw [sub_eq_iff_eq_add, add_halves'] lemma half_sub (a : α) : a / 2 - a = - (a / 2) := by rw [← neg_sub, sub_half] end
889b3d992a187c1dbd91eed4fa659322584acc29
432d948a4d3d242fdfb44b81c9e1b1baacd58617
/src/algebra/order.lean
724b1f2fa907213384b39fa65687b4ec9dd6f58e
[ "Apache-2.0" ]
permissive
JLimperg/aesop3
306cc6570c556568897ed2e508c8869667252e8a
a4a116f650cc7403428e72bd2e2c4cda300fe03f
refs/heads/master
1,682,884,916,368
1,620,320,033,000
1,620,320,033,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
14,721
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro -/ import tactic.alias import tactic.lint /-! # Lemmas about inequalities This file contains some lemmas about `≤`/`≥`/`<`/`>`, and `cmp`. * We simplify `a ≥ b` and `a > b` to `b ≤ a` and `b < a`, respectively. This way we can formulate all lemmas using `≤`/`<` avoiding duplication. * In some cases we introduce dot syntax aliases so that, e.g., from `(hab : a ≤ b) (hbc : b ≤ c) (hbc' : b < c)` one can prove `hab.trans hbc : a ≤ c` and `hab.trans_lt hbc' : a < c`. -/ universe u variables {α : Type u} alias le_trans ← has_le.le.trans alias lt_of_le_of_lt ← has_le.le.trans_lt alias le_antisymm ← has_le.le.antisymm alias lt_of_le_of_ne ← has_le.le.lt_of_ne alias lt_of_le_not_le ← has_le.le.lt_of_not_le alias lt_or_eq_of_le ← has_le.le.lt_or_eq alias le_of_lt ← has_lt.lt.le alias lt_trans ← has_lt.lt.trans alias lt_of_lt_of_le ← has_lt.lt.trans_le alias ne_of_lt ← has_lt.lt.ne alias lt_asymm ← has_lt.lt.asymm has_lt.lt.not_lt alias le_of_eq ← eq.le /-- A version of `le_refl` where the argument is implicit -/ lemma le_rfl [preorder α] {x : α} : x ≤ x := le_refl x namespace eq /-- If `x = y` then `y ≤ x`. Note: this lemma uses `y ≤ x` instead of `x ≥ y`, because `le` is used almost exclusively in mathlib. -/ protected lemma ge [preorder α] {x y : α} (h : x = y) : y ≤ x := h.symm.le lemma trans_le [preorder α] {x y z : α} (h1 : x = y) (h2 : y ≤ z) : x ≤ z := h1.le.trans h2 end eq namespace has_le.le @[nolint ge_or_gt] -- see Note [nolint_ge] protected lemma ge [has_le α] {x y : α} (h : x ≤ y) : y ≥ x := h lemma trans_eq [preorder α] {x y z : α} (h1 : x ≤ y) (h2 : y = z) : x ≤ z := h1.trans h2.le lemma lt_iff_ne [partial_order α] {x y : α} (h : x ≤ y) : x < y ↔ x ≠ y := ⟨λ h, h.ne, h.lt_of_ne⟩ lemma le_iff_eq [partial_order α] {x y : α} (h : x ≤ y) : y ≤ x ↔ y = x := ⟨λ h', h'.antisymm h, eq.le⟩ lemma lt_or_le [linear_order α] {a b : α} (h : a ≤ b) (c : α) : a < c ∨ c ≤ b := (lt_or_ge a c).imp id $ λ hc, le_trans hc h lemma le_or_lt [linear_order α] {a b : α} (h : a ≤ b) (c : α) : a ≤ c ∨ c < b := (le_or_gt a c).imp id $ λ hc, lt_of_lt_of_le hc h lemma le_or_le [linear_order α] {a b : α} (h : a ≤ b) (c : α) : a ≤ c ∨ c ≤ b := (h.le_or_lt c).elim or.inl (λ h, or.inr $ le_of_lt h) end has_le.le namespace has_lt.lt @[nolint ge_or_gt] -- see Note [nolint_ge] protected lemma gt [has_lt α] {x y : α} (h : x < y) : y > x := h protected lemma false [preorder α] {x : α} : x < x → false := lt_irrefl x lemma ne' [preorder α] {x y : α} (h : x < y) : y ≠ x := h.ne.symm lemma lt_or_lt [linear_order α] {x y : α} (h : x < y) (z : α) : x < z ∨ z < y := (lt_or_ge z y).elim or.inr (λ hz, or.inl $ h.trans_le hz) end has_lt.lt namespace ge @[nolint ge_or_gt] -- see Note [nolint_ge] protected lemma le [has_le α] {x y : α} (h : x ≥ y) : y ≤ x := h end ge namespace gt @[nolint ge_or_gt] -- see Note [nolint_ge] protected lemma lt [has_lt α] {x y : α} (h : x > y) : y < x := h end gt @[nolint ge_or_gt] -- see Note [nolint_ge] theorem ge_of_eq [preorder α] {a b : α} (h : a = b) : a ≥ b := h.ge @[simp, nolint ge_or_gt] -- see Note [nolint_ge] lemma ge_iff_le [preorder α] {a b : α} : a ≥ b ↔ b ≤ a := iff.rfl @[simp, nolint ge_or_gt] -- see Note [nolint_ge] lemma gt_iff_lt [preorder α] {a b : α} : a > b ↔ b < a := iff.rfl lemma not_le_of_lt [preorder α] {a b : α} (h : a < b) : ¬ b ≤ a := (le_not_le_of_lt h).right alias not_le_of_lt ← has_lt.lt.not_le lemma not_lt_of_le [preorder α] {a b : α} (h : a ≤ b) : ¬ b < a | hab := hab.not_le h alias not_lt_of_le ← has_le.le.not_lt lemma le_iff_eq_or_lt [partial_order α] {a b : α} : a ≤ b ↔ a = b ∨ a < b := le_iff_lt_or_eq.trans or.comm lemma lt_iff_le_and_ne [partial_order α] {a b : α} : a < b ↔ a ≤ b ∧ a ≠ b := ⟨λ h, ⟨le_of_lt h, ne_of_lt h⟩, λ ⟨h1, h2⟩, h1.lt_of_ne h2⟩ lemma eq_iff_le_not_lt [partial_order α] {a b : α} : a = b ↔ a ≤ b ∧ ¬ a < b := ⟨λ h, ⟨h.le, h ▸ lt_irrefl _⟩, λ ⟨h₁, h₂⟩, h₁.antisymm $ classical.by_contradiction $ λ h₃, h₂ (h₁.lt_of_not_le h₃)⟩ lemma eq_or_lt_of_le [partial_order α] {a b : α} (h : a ≤ b) : a = b ∨ a < b := h.lt_or_eq.symm alias eq_or_lt_of_le ← has_le.le.eq_or_lt lemma ne.le_iff_lt [partial_order α] {a b : α} (h : a ≠ b) : a ≤ b ↔ a < b := ⟨λ h', lt_of_le_of_ne h' h, λ h, h.le⟩ @[simp] lemma ne_iff_lt_iff_le [partial_order α] {a b : α} : (a ≠ b ↔ a < b) ↔ a ≤ b := ⟨λ h, classical.by_cases le_of_eq (le_of_lt ∘ h.mp), λ h, ⟨lt_of_le_of_ne h, ne_of_lt⟩⟩ lemma lt_of_not_ge' [linear_order α] {a b : α} (h : ¬ b ≤ a) : a < b := ((le_total _ _).resolve_right h).lt_of_not_le h lemma lt_iff_not_ge' [linear_order α] {x y : α} : x < y ↔ ¬ y ≤ x := ⟨not_le_of_gt, lt_of_not_ge'⟩ lemma ne.lt_or_lt [linear_order α] {a b : α} (h : a ≠ b) : a < b ∨ b < a := lt_or_gt_of_ne h lemma not_lt_iff_eq_or_lt [linear_order α] {a b : α} : ¬ a < b ↔ a = b ∨ b < a := not_lt.trans $ le_iff_eq_or_lt.trans $ or_congr eq_comm iff.rfl lemma exists_ge_of_linear [linear_order α] (a b : α) : ∃ c, a ≤ c ∧ b ≤ c := match le_total a b with | or.inl h := ⟨_, h, le_rfl⟩ | or.inr h := ⟨_, le_rfl, h⟩ end lemma lt_imp_lt_of_le_imp_le {β} [linear_order α] [preorder β] {a b : α} {c d : β} (H : a ≤ b → c ≤ d) (h : d < c) : b < a := lt_of_not_ge' $ λ h', (H h').not_lt h lemma le_imp_le_iff_lt_imp_lt {β} [linear_order α] [linear_order β] {a b : α} {c d : β} : (a ≤ b → c ≤ d) ↔ (d < c → b < a) := ⟨lt_imp_lt_of_le_imp_le, le_imp_le_of_lt_imp_lt⟩ lemma lt_iff_lt_of_le_iff_le' {β} [preorder α] [preorder β] {a b : α} {c d : β} (H : a ≤ b ↔ c ≤ d) (H' : b ≤ a ↔ d ≤ c) : b < a ↔ d < c := lt_iff_le_not_le.trans $ (and_congr H' (not_congr H)).trans lt_iff_le_not_le.symm lemma lt_iff_lt_of_le_iff_le {β} [linear_order α] [linear_order β] {a b : α} {c d : β} (H : a ≤ b ↔ c ≤ d) : b < a ↔ d < c := not_le.symm.trans $ (not_congr H).trans $ not_le lemma le_iff_le_iff_lt_iff_lt {β} [linear_order α] [linear_order β] {a b : α} {c d : β} : (a ≤ b ↔ c ≤ d) ↔ (b < a ↔ d < c) := ⟨lt_iff_lt_of_le_iff_le, λ H, not_lt.symm.trans $ (not_congr H).trans $ not_lt⟩ lemma eq_of_forall_le_iff [partial_order α] {a b : α} (H : ∀ c, c ≤ a ↔ c ≤ b) : a = b := le_antisymm ((H _).1 (le_refl _)) ((H _).2 (le_refl _)) lemma le_of_forall_le [preorder α] {a b : α} (H : ∀ c, c ≤ a → c ≤ b) : a ≤ b := H _ (le_refl _) lemma le_of_forall_le' [preorder α] {a b : α} (H : ∀ c, a ≤ c → b ≤ c) : b ≤ a := H _ (le_refl _) lemma le_of_forall_lt [linear_order α] {a b : α} (H : ∀ c, c < a → c < b) : a ≤ b := le_of_not_lt $ λ h, lt_irrefl _ (H _ h) lemma forall_lt_iff_le [linear_order α] {a b : α} : (∀ ⦃c⦄, c < a → c < b) ↔ a ≤ b := ⟨le_of_forall_lt, λ h c hca, lt_of_lt_of_le hca h⟩ lemma le_of_forall_lt' [linear_order α] {a b : α} (H : ∀ c, a < c → b < c) : b ≤ a := le_of_not_lt $ λ h, lt_irrefl _ (H _ h) lemma forall_lt_iff_le' [linear_order α] {a b : α} : (∀ ⦃c⦄, a < c → b < c) ↔ b ≤ a := ⟨le_of_forall_lt', λ h c hac, lt_of_le_of_lt h hac⟩ lemma eq_of_forall_ge_iff [partial_order α] {a b : α} (H : ∀ c, a ≤ c ↔ b ≤ c) : a = b := le_antisymm ((H _).2 (le_refl _)) ((H _).1 (le_refl _)) /-- monotonicity of `≤` with respect to `→` -/ lemma le_implies_le_of_le_of_le {a b c d : α} [preorder α] (h₀ : c ≤ a) (h₁ : b ≤ d) : a ≤ b → c ≤ d := assume h₂ : a ≤ b, calc c ≤ a : h₀ ... ≤ b : h₂ ... ≤ d : h₁ namespace decidable -- See Note [decidable namespace] lemma le_imp_le_iff_lt_imp_lt {β} [linear_order α] [linear_order β] {a b : α} {c d : β} : (a ≤ b → c ≤ d) ↔ (d < c → b < a) := ⟨lt_imp_lt_of_le_imp_le, le_imp_le_of_lt_imp_lt⟩ -- See Note [decidable namespace] lemma le_iff_le_iff_lt_iff_lt {β} [linear_order α] [linear_order β] {a b : α} {c d : β} : (a ≤ b ↔ c ≤ d) ↔ (b < a ↔ d < c) := ⟨lt_iff_lt_of_le_iff_le, λ H, not_lt.symm.trans $ (not_congr H).trans $ not_lt⟩ end decidable /-- Like `cmp`, but uses a `≤` on the type instead of `<`. Given two elements `x` and `y`, returns a three-way comparison result `ordering`. -/ def cmp_le {α} [has_le α] [@decidable_rel α (≤)] (x y : α) : ordering := if x ≤ y then if y ≤ x then ordering.eq else ordering.lt else ordering.gt theorem cmp_le_swap {α} [has_le α] [is_total α (≤)] [@decidable_rel α (≤)] (x y : α) : (cmp_le x y).swap = cmp_le y x := begin by_cases xy : x ≤ y; by_cases yx : y ≤ x; simp [cmp_le, *, ordering.swap], cases not_or xy yx (total_of _ _ _) end theorem cmp_le_eq_cmp {α} [preorder α] [is_total α (≤)] [@decidable_rel α (≤)] [@decidable_rel α (<)] (x y : α) : cmp_le x y = cmp x y := begin by_cases xy : x ≤ y; by_cases yx : y ≤ x; simp [cmp_le, lt_iff_le_not_le, *, cmp, cmp_using], cases not_or xy yx (total_of _ _ _) end namespace ordering /-- `compares o a b` means that `a` and `b` have the ordering relation `o` between them, assuming that the relation `a < b` is defined -/ @[simp] def compares [has_lt α] : ordering → α → α → Prop | lt a b := a < b | eq a b := a = b | gt a b := a > b theorem compares_swap [has_lt α] {a b : α} {o : ordering} : o.swap.compares a b ↔ o.compares b a := by { cases o, exacts [iff.rfl, eq_comm, iff.rfl] } alias compares_swap ↔ ordering.compares.of_swap ordering.compares.swap theorem swap_eq_iff_eq_swap {o o' : ordering} : o.swap = o' ↔ o = o'.swap := ⟨λ h, by rw [← swap_swap o, h], λ h, by rw [← swap_swap o', h]⟩ theorem compares.eq_lt [preorder α] : ∀ {o} {a b : α}, compares o a b → (o = lt ↔ a < b) | lt a b h := ⟨λ _, h, λ _, rfl⟩ | eq a b h := ⟨λ h, by injection h, λ h', (ne_of_lt h' h).elim⟩ | gt a b h := ⟨λ h, by injection h, λ h', (lt_asymm h h').elim⟩ theorem compares.ne_lt [preorder α] : ∀ {o} {a b : α}, compares o a b → (o ≠ lt ↔ b ≤ a) | lt a b h := ⟨absurd rfl, λ h', (not_le_of_lt h h').elim⟩ | eq a b h := ⟨λ _, ge_of_eq h, λ _ h, by injection h⟩ | gt a b h := ⟨λ _, le_of_lt h, λ _ h, by injection h⟩ theorem compares.eq_eq [preorder α] : ∀ {o} {a b : α}, compares o a b → (o = eq ↔ a = b) | lt a b h := ⟨λ h, by injection h, λ h', (ne_of_lt h h').elim⟩ | eq a b h := ⟨λ _, h, λ _, rfl⟩ | gt a b h := ⟨λ h, by injection h, λ h', (ne_of_gt h h').elim⟩ theorem compares.eq_gt [preorder α] {o} {a b : α} (h : compares o a b) : (o = gt ↔ b < a) := swap_eq_iff_eq_swap.symm.trans h.swap.eq_lt theorem compares.ne_gt [preorder α] {o} {a b : α} (h : compares o a b) : (o ≠ gt ↔ a ≤ b) := (not_congr swap_eq_iff_eq_swap.symm).trans h.swap.ne_lt theorem compares.le_total [preorder α] {a b : α} : ∀ {o}, compares o a b → a ≤ b ∨ b ≤ a | lt h := or.inl (le_of_lt h) | eq h := or.inl (le_of_eq h) | gt h := or.inr (le_of_lt h) theorem compares.le_antisymm [preorder α] {a b : α} : ∀ {o}, compares o a b → a ≤ b → b ≤ a → a = b | lt h _ hba := (not_le_of_lt h hba).elim | eq h _ _ := h | gt h hab _ := (not_le_of_lt h hab).elim theorem compares.inj [preorder α] {o₁} : ∀ {o₂} {a b : α}, compares o₁ a b → compares o₂ a b → o₁ = o₂ | lt a b h₁ h₂ := h₁.eq_lt.2 h₂ | eq a b h₁ h₂ := h₁.eq_eq.2 h₂ | gt a b h₁ h₂ := h₁.eq_gt.2 h₂ theorem compares_iff_of_compares_impl {β : Type*} [linear_order α] [preorder β] {a b : α} {a' b' : β} (h : ∀ {o}, compares o a b → compares o a' b') (o) : compares o a b ↔ compares o a' b' := begin refine ⟨h, λ ho, _⟩, cases lt_trichotomy a b with hab hab, { change compares ordering.lt a b at hab, rwa [ho.inj (h hab)] }, { cases hab with hab hab, { change compares ordering.eq a b at hab, rwa [ho.inj (h hab)] }, { change compares ordering.gt a b at hab, rwa [ho.inj (h hab)] } } end theorem swap_or_else (o₁ o₂) : (or_else o₁ o₂).swap = or_else o₁.swap o₂.swap := by cases o₁; try {refl}; cases o₂; refl theorem or_else_eq_lt (o₁ o₂) : or_else o₁ o₂ = lt ↔ o₁ = lt ∨ (o₁ = eq ∧ o₂ = lt) := by cases o₁; cases o₂; exact dec_trivial end ordering theorem cmp_compares [linear_order α] (a b : α) : (cmp a b).compares a b := begin unfold cmp cmp_using, by_cases a < b; simp [h], by_cases h₂ : b < a; simp [h₂, gt], exact (lt_or_eq_of_le (le_of_not_gt h₂)).resolve_left h end theorem cmp_swap [preorder α] [@decidable_rel α (<)] (a b : α) : (cmp a b).swap = cmp b a := begin unfold cmp cmp_using, by_cases a < b; by_cases h₂ : b < a; simp [h, h₂, gt, ordering.swap], exact lt_asymm h h₂ end /-- Generate a linear order structure from a preorder and `cmp` function. -/ def linear_order_of_compares [preorder α] (cmp : α → α → ordering) (h : ∀ a b, (cmp a b).compares a b) : linear_order α := { le_antisymm := λ a b, (h a b).le_antisymm, le_total := λ a b, (h a b).le_total, decidable_le := λ a b, decidable_of_iff _ (h a b).ne_gt, decidable_lt := λ a b, decidable_of_iff _ (h a b).eq_lt, decidable_eq := λ a b, decidable_of_iff _ (h a b).eq_eq, .. ‹preorder α› } variables [linear_order α] (x y : α) @[simp] lemma cmp_eq_lt_iff : cmp x y = ordering.lt ↔ x < y := ordering.compares.eq_lt (cmp_compares x y) @[simp] lemma cmp_eq_eq_iff : cmp x y = ordering.eq ↔ x = y := ordering.compares.eq_eq (cmp_compares x y) @[simp] lemma cmp_eq_gt_iff : cmp x y = ordering.gt ↔ y < x := ordering.compares.eq_gt (cmp_compares x y) @[simp] lemma cmp_self_eq_eq : cmp x x = ordering.eq := by rw cmp_eq_eq_iff variables {x y} {β : Type*} [linear_order β] {x' y' : β} lemma cmp_eq_cmp_symm : cmp x y = cmp x' y' ↔ cmp y x = cmp y' x' := by { split, rw [←cmp_swap _ y, ←cmp_swap _ y'], cc, rw [←cmp_swap _ x, ←cmp_swap _ x'], cc, } lemma lt_iff_lt_of_cmp_eq_cmp (h : cmp x y = cmp x' y') : x < y ↔ x' < y' := by rw [←cmp_eq_lt_iff, ←cmp_eq_lt_iff, h] lemma le_iff_le_of_cmp_eq_cmp (h : cmp x y = cmp x' y') : x ≤ y ↔ x' ≤ y' := by { rw [←not_lt, ←not_lt, not_iff_not], apply lt_iff_lt_of_cmp_eq_cmp, rwa cmp_eq_cmp_symm }
fe57178eae7ece9763ac73704cad937503153d12
32025d5c2d6e33ad3b6dd8a3c91e1e838066a7f7
/stage0/src/Lean/Message.lean
0722dcb13d5ae047c8e8bd8489bc1c30e80c90e7
[ "Apache-2.0" ]
permissive
walterhu1015/lean4
b2c71b688975177402758924eaa513475ed6ce72
2214d81e84646a905d0b20b032c89caf89c737ad
refs/heads/master
1,671,342,096,906
1,599,695,985,000
1,599,695,985,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
10,834
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Sebastian Ullrich, Leonardo de Moura Message Type used by the Lean frontend -/ import Lean.Data.Position import Lean.Syntax import Lean.MetavarContext import Lean.Environment import Lean.Util.PPExt import Lean.Util.PPGoal namespace Lean def mkErrorStringWithPos (fileName : String) (line col : Nat) (msg : String) : String := fileName ++ ":" ++ toString line ++ ":" ++ toString col ++ " " ++ toString msg inductive MessageSeverity | information | warning | error structure MessageDataContext := (env : Environment) (mctx : MetavarContext) (lctx : LocalContext) (opts : Options) /- Structure message data. We use it for reporting errors, trace messages, etc. -/ inductive MessageData | ofFormat : Format → MessageData | ofSyntax : Syntax → MessageData | ofExpr : Expr → MessageData | ofLevel : Level → MessageData | ofName : Name → MessageData | ofGoal : MVarId → MessageData /- `withContext ctx d` specifies the pretty printing context `(env, mctx, lctx, opts)` for the nested expressions in `d`. -/ | withContext : MessageDataContext → MessageData → MessageData /- Lifted `Format.nest` -/ | nest : Nat → MessageData → MessageData /- Lifted `Format.group` -/ | group : MessageData → MessageData /- Lifted `Format.compose` -/ | compose : MessageData → MessageData → MessageData /- Tagged sections. `Name` should be viewed as a "kind", and is used by `MessageData` inspector functions. Example: an inspector that tries to find "definitional equality failures" may look for the tag "DefEqFailure". -/ | tagged : Name → MessageData → MessageData | node : Array MessageData → MessageData namespace MessageData instance : Inhabited MessageData := ⟨MessageData.ofFormat (arbitrary _)⟩ @[init] def stxMaxDepthOption : IO Unit := registerOption `syntaxMaxDepth { defValue := (2 : Nat), group := "", descr := "maximum depth when displaying syntax objects in messages" } def getSyntaxMaxDepth (opts : Options) : Nat := opts.getNat `syntaxMaxDepth 2 partial def formatAux : Option MessageDataContext → MessageData → Format | _, ofFormat fmt => fmt | _, ofLevel u => fmt u | _, ofName n => fmt n | some ctx, ofSyntax s => s.formatStx (getSyntaxMaxDepth ctx.opts) | none, ofSyntax s => s.formatStx | none, ofExpr e => format (toString e) | some ctx, ofExpr e => ppExpr ctx.env ctx.mctx ctx.lctx ctx.opts e | none, ofGoal mvarId => "goal " ++ format (mkMVar mvarId) | some ctx, ofGoal mvarId => ppGoal ctx.env ctx.mctx ctx.opts mvarId | _, withContext ctx d => formatAux (some ctx) d | ctx, tagged cls d => Format.sbracket (format cls) ++ " " ++ formatAux ctx d | ctx, nest n d => Format.nest n (formatAux ctx d) | ctx, compose d₁ d₂ => formatAux ctx d₁ ++ formatAux ctx d₂ | ctx, group d => Format.group (formatAux ctx d) | ctx, node ds => Format.nest 2 $ ds.foldl (fun r d => r ++ Format.line ++ formatAux ctx d) Format.nil instance : HasAppend MessageData := ⟨compose⟩ instance : HasFormat MessageData := ⟨fun d => formatAux none d⟩ instance : HasToString MessageData := ⟨fun d => toString (format d)⟩ instance coeOfFormat : HasCoe Format MessageData := ⟨ofFormat⟩ instance coeOfLevel : HasCoe Level MessageData := ⟨ofLevel⟩ instance coeOfExpr : HasCoe Expr MessageData := ⟨ofExpr⟩ instance coeOfName : HasCoe Name MessageData := ⟨ofName⟩ instance coeOfSyntax : HasCoe Syntax MessageData := ⟨ofSyntax⟩ instance coeOfOptExpr : HasCoe (Option Expr) MessageData := ⟨fun o => match o with | none => "none" | some e => ofExpr e⟩ partial def arrayExpr.toMessageData (es : Array Expr) : Nat → MessageData → MessageData | i, acc => if h : i < es.size then let e := es.get ⟨i, h⟩; let acc := if i == 0 then acc ++ ofExpr e else acc ++ ", " ++ ofExpr e; arrayExpr.toMessageData (i+1) acc else acc ++ "]" instance coeOfArrayExpr : HasCoe (Array Expr) MessageData := ⟨fun es => arrayExpr.toMessageData es 0 "#["⟩ def bracket (l : String) (f : MessageData) (r : String) : MessageData := group (nest l.length $ l ++ f ++ r) def paren (f : MessageData) : MessageData := bracket "(" f ")" def sbracket (f : MessageData) : MessageData := bracket "[" f "]" def joinSep : List MessageData → MessageData → MessageData | [], sep => Format.nil | [a], sep => a | a::as, sep => a ++ sep ++ joinSep as sep def ofList: List MessageData → MessageData | [] => "[]" | xs => sbracket $ joinSep xs ("," ++ Format.line) def ofArray (msgs : Array MessageData) : MessageData := ofList msgs.toList instance coeOfList : HasCoe (List MessageData) MessageData := ⟨ofList⟩ instance coeOfListExpr : HasCoe (List Expr) MessageData := ⟨fun es => ofList $ es.map ofExpr⟩ end MessageData structure Message := (fileName : String) (pos : Position) (endPos : Option Position := none) (severity : MessageSeverity := MessageSeverity.error) (caption : String := "") (data : MessageData) @[export lean_mk_message] def mkMessageEx (fileName : String) (pos : Position) (endPos : Option Position) (severity : MessageSeverity) (caption : String) (text : String) : Message := { fileName := fileName, pos := pos, endPos := endPos, severity := severity, caption := caption, data := text } namespace Message protected def toString (msg : Message) : String := mkErrorStringWithPos msg.fileName msg.pos.line msg.pos.column ((match msg.severity with | MessageSeverity.information => "" | MessageSeverity.warning => "warning: " | MessageSeverity.error => "error: ") ++ (if msg.caption == "" then "" else msg.caption ++ ":\n") ++ toString (fmt msg.data)) instance : Inhabited Message := ⟨{ fileName := "", pos := ⟨0, 1⟩, data := arbitrary _}⟩ instance : HasToString Message := ⟨Message.toString⟩ @[export lean_message_pos] def getPostEx (msg : Message) : Position := msg.pos @[export lean_message_severity] def getSeverityEx (msg : Message) : MessageSeverity := msg.severity @[export lean_message_string] def getMessageStringEx (msg : Message) : String := toString (fmt msg.data) end Message structure MessageLog := (msgs : Std.PersistentArray Message := {}) namespace MessageLog def empty : MessageLog := ⟨{}⟩ def isEmpty (log : MessageLog) : Bool := log.msgs.isEmpty instance : Inhabited MessageLog := ⟨{}⟩ def add (msg : Message) (log : MessageLog) : MessageLog := ⟨log.msgs.push msg⟩ protected def append (l₁ l₂ : MessageLog) : MessageLog := ⟨l₁.msgs ++ l₂.msgs⟩ instance : HasAppend MessageLog := ⟨MessageLog.append⟩ def hasErrors (log : MessageLog) : Bool := log.msgs.any $ fun m => match m.severity with | MessageSeverity.error => true | _ => false def errorsToWarnings (log : MessageLog) : MessageLog := { msgs := log.msgs.map (fun m => match m.severity with | MessageSeverity.error => { m with severity := MessageSeverity.warning } | _ => m) } def forM {m : Type → Type} [Monad m] (log : MessageLog) (f : Message → m Unit) : m Unit := log.msgs.forM f def toList (log : MessageLog) : List Message := (log.msgs.foldl (fun acc msg => msg :: acc) []).reverse end MessageLog def MessageData.nestD (msg : MessageData) : MessageData := MessageData.nest 2 msg def indentExpr (msg : MessageData) : MessageData := MessageData.nestD (Format.line ++ msg) namespace KernelException private def mkCtx (env : Environment) (lctx : LocalContext) (opts : Options) (msg : MessageData) : MessageData := MessageData.withContext { env := env, mctx := {}, lctx := lctx, opts := opts } msg def toMessageData (e : KernelException) (opts : Options) : MessageData := match e with | unknownConstant env constName => mkCtx env {} opts $ "(kernel) unknown constant " ++ constName | alreadyDeclared env constName => mkCtx env {} opts $ "(kernel) constant has already been declared " ++ constName | declTypeMismatch env decl givenType => let process (n : Name) (expectedType : Expr) : MessageData := "(kernel) declaration type mismatch " ++ n ++ Format.line ++ "has type" ++ indentExpr givenType ++ Format.line ++ "but it is expected to have type" ++ indentExpr expectedType; match decl with | Declaration.defnDecl { name := n, type := type, .. } => process n type | Declaration.thmDecl { name := n, type := type, .. } => process n type | _ => "(kernel) declaration type mismatch" -- TODO fix type checker, type mismatch for mutual decls does not have enough information | declHasMVars env constName _ => mkCtx env {} opts $ "(kernel) declaration has metavariables " ++ constName | declHasFVars env constName _ => mkCtx env {} opts $ "(kernel) declaration has free variables " ++ constName | funExpected env lctx e => mkCtx env lctx opts $ "(kernel) function expected" ++ indentExpr e | typeExpected env lctx e => mkCtx env lctx opts $ "(kernel) type expected" ++ indentExpr e | letTypeMismatch env lctx n _ _ => mkCtx env lctx opts $ "(kernel) let-declaration type mismatch " ++ n | exprTypeMismatch env lctx e _ => mkCtx env lctx opts $ "(kernel) type mismatch at " ++ indentExpr e | appTypeMismatch env lctx e fnType argType => mkCtx env lctx opts $ "application type mismatch" ++ indentExpr e ++ Format.line ++ "argument has type" ++ indentExpr argType ++ Format.line ++ "but function has type" ++ indentExpr fnType | invalidProj env lctx e => mkCtx env lctx opts $ "(kernel) invalid projection" ++ indentExpr e | other msg => "(kernel) " ++ msg end KernelException class AddMessageDataContext (m : Type → Type) := (addMessageDataContext : MessageData → m MessageData) export AddMessageDataContext (addMessageDataContext) instance addMessageDataContextTrans (m n) [AddMessageDataContext m] [MonadLift m n] : AddMessageDataContext n := { addMessageDataContext := fun msg => liftM (addMessageDataContext msg : m _) } def addMessageDataContextPartial {m} [Monad m] [MonadEnv m] [MonadOptions m] (msgData : MessageData) : m MessageData := do env ← getEnv; opts ← getOptions; pure $ MessageData.withContext { env := env, mctx := {}, lctx := {}, opts := opts } msgData def addMessageDataContextFull {m} [Monad m] [MonadEnv m] [MonadMCtx m] [MonadLCtx m] [MonadOptions m] (msgData : MessageData) : m MessageData := do env ← getEnv; mctx ← getMCtx; lctx ← getLCtx; opts ← getOptions; pure $ MessageData.withContext { env := env, mctx := mctx, lctx := lctx, opts := opts } msgData end Lean
94bb0535d3b7d1f4e4330eb75232e7f6b2c4722b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/src/lake/examples/targets/lakefile.lean
20336f9d51b957582fead1b685db3fe0e6e86146
[ "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
990
lean
import Lake open Lake DSL package targets { srcDir := "src" } @[default_target] lean_lib foo { defaultFacets := #[LeanLib.staticFacet] } lean_lib bar { defaultFacets := #[LeanLib.sharedFacet] } lean_lib baz { extraDepTargets := #[`caw] } lean_exe a lean_exe b @[default_target] lean_exe c @[default_target] target meow pkg : Unit := do IO.FS.writeFile (pkg.buildDir / "meow.txt") "Meow!" return .nil target caw pkg : Unit := do IO.FS.writeFile (pkg.buildDir / "caw.txt") "Caw!" return .nil target bark : Unit := do logInfo "Bark!" return .nil target bark_bark : Unit := do bark.fetch package_facet print_name pkg : Unit := do IO.println pkg.name return .nil module_facet get_src mod : FilePath := do inputFile mod.leanFile module_facet print_src mod : Unit := do (← fetch <| mod.facet `get_src).bindSync fun src trace => do IO.println src return ((), trace) library_facet print_name lib : Unit := do IO.println lib.name return .nil
5ec8b50f71987851e98eeb5fdc04bed1f8fb6f2b
2272e503179a58556187901b8698b789fad7e0c4
/src/adjunction.lean
acadee26d731b06a98470304a0fcc601bebcfb7d
[]
no_license
kckennylau/category-theory
f15e582be862379453a5341d83b8cd5ebc686729
b24962838c7370b5257e38b7648040aec95922bb
refs/heads/master
1,583,605,043,449
1,525,154,882,000
1,525,154,882,000
127,633,452
0
0
null
null
null
null
UTF-8
Lean
false
false
6,579
lean
import .natural_transformation universes u v w u₁ v₁ w₁ u₂ v₂ w₂ namespace category @[reducible] def functor.Hom_left {α β} (C : category.{u v} α) (D : category.{u₁ v₁} β) (L : functor D C) : functor (product_category (dual D) C) examples.Set := { F := λ x, C.Mor (L.F x.1) x.2, mor := λ x y F f, C.Comp _ _ _ (C.Comp _ _ _ F.2 f) (L.mor _ _ F.1), Hid := λ x, funext $ λ z, by dsimp [product_category, dual]; rw [L.Hid, C.Hid_right, C.Hid_left]; refl, Hcomp := λ x y z f g, funext $ λ z, by dsimp [product_category, dual, examples.Set]; rw [C.Hassoc, C.Hassoc, C.Hassoc, C.Hassoc, ← L.Hcomp, C.Hassoc]; refl } @[reducible] def functor.Hom_right {α β} (C : category.{u v} α) (D : category.{u₁ v₁} β) (R : functor C D) : functor (product_category (dual D) C) examples.Set := { F := λ x, D.Mor x.1 (R.F x.2), mor := λ x y F f, D.Comp _ _ _ (D.Comp _ _ _ (R.mor _ _ F.2) f) F.1, Hid := λ x, funext $ λ z, by dsimp [product_category, dual]; rw [R.Hid, D.Hid_right, D.Hid_left]; refl, Hcomp := λ x y z f g, funext $ λ z, by dsimp [product_category, dual, examples.Set]; rw [D.Hassoc, D.Hassoc, D.Hassoc, D.Hassoc, ← R.Hcomp, D.Hassoc]; refl } structure adjunction {α β} (C : category.{u v} α) (D : category.{u v} β) : Type (max u v) := (left : functor D C) (right : functor C D) (Hom_iso : natural_isomorphism _ _ (functor.Hom_left C D left) (functor.Hom_right C D right)) section make variables {α : Type u} {β : Type u} variables (C : category.{u v} α) (D : category.{u v} β) variables (left : functor D C) (right : functor C D) variables (extend : Π x y, D.Mor x (right.F y) → C.Mor (left.F x) y) variables (descend : Π x y, C.Mor (left.F x) y → D.Mor x (right.F y)) variables (descend_natural : ∀ (x₁ x₂ y₁ y₂) (cf : C.Mor x₁ x₂) (df : D.Mor y₂ y₁) (t : C.Mor (left.F y₁) x₁), descend _ _ (C.Comp _ _ _ (C.Comp _ _ _ cf t) (left.mor _ _ df)) = D.Comp _ _ _ (D.Comp _ _ _ (right.mor x₁ x₂ cf) (descend _ _ t)) df) variables (extend_natural : ∀ (x₁ x₂ y₁ y₂) (cf : C.Mor x₁ x₂) (df : D.Mor y₂ y₁) (t : D.Mor y₁ (right.F x₁)), extend _ _ (D.Comp _ _ _ (D.Comp _ _ _ (right.mor _ _ cf) t) df) = C.Comp _ _ _ (C.Comp _ _ _ cf (extend _ _ t)) (left.mor y₂ y₁ df)) variables (extend_descend : ∀ x y (f : C.Mor (left.F x) y), extend _ _ (descend _ _ f) = f) variables (descend_extend : ∀ x y (f : D.Mor x (right.F y)), descend _ _ (extend _ _ f) = f) include extend_descend descend_extend def adjunction.make : adjunction C D := { left := left, right := right, Hom_iso := { to_mor := { mor := λ x, descend x.1 x.2, Hcomp := λ x y f, funext $ λ t, descend_natural _ _ _ _ _ _ _ }, inv_mor := { mor := λ x, extend x.1 x.2, Hcomp := λ x y f, funext $ λ t, extend_natural _ _ _ _ _ _ _ }, split_monomorphism := begin dsimp [natural_transformation.comp], congr, funext, dsimp, apply extend_descend end, split_epimorphism := begin dsimp [natural_transformation.comp], congr, funext, dsimp, apply descend_extend end } } end make section free_forgetful variables {α : Type (u+1)} (C : category.{u+1 u} α) variables (free : functor examples.Set.{u} C) variables (forgetful : functor C examples.Set.{u}) variables (extend : Π x y, (x → (forgetful.F y)) → C.Mor (free.F x) y) variables (descend : Π x y, C.Mor (free.F x) y → x → (forgetful.F y)) variables (descend_natural : ∀ (x₁ x₂ y₁ y₂) (cf : C.Mor x₁ x₂) (df : y₂ → y₁) (t : C.Mor (free.F y₁) x₁) z, descend _ _ (C.Comp _ _ _ (C.Comp _ _ _ cf t) (free.mor _ _ df)) z = (forgetful.mor x₁ x₂ cf) ((descend _ _ t) (df z))) variables (extend_natural : ∀ (x₁ x₂ y₁ y₂) (cf : C.Mor x₁ x₂) (df : y₂ → y₁) (t : y₁ → forgetful.F x₁), extend _ _ ((forgetful.mor _ _ cf) ∘ t ∘ df) = C.Comp _ _ _ (C.Comp _ _ _ cf (extend _ _ t)) (free.mor y₂ y₁ df)) variables (extend_descend : ∀ x y (f : C.Mor (free.F x) y), extend _ _ (descend _ _ f) = f) variables (descend_extend : ∀ x y (f : x → (forgetful.F y)), descend _ _ (extend _ _ f) = f) def adjunction.free_forgetful : adjunction.{u+1 u} C examples.Set.{u} := adjunction.make _ _ free forgetful extend descend (λ _ _ _ _ _ _ _, funext $ λ _, descend_natural _ _ _ _ _ _ _ _) extend_natural extend_descend descend_extend end free_forgetful def adjunction.id {α} (C : category.{u v} α) : adjunction C C := adjunction.make _ _ (functor.id C) (functor.id C) (λ x y, id) (λ x y, id) (λ _ _ _ _ _ _ _, rfl) (λ _ _ _ _ _ _ _, rfl) (λ _ _ _, rfl) (λ _ _ _, rfl) def adjunction.comp {α β γ} (C : category.{u v} α) (D : category.{u v} β) (E : category.{u v} γ) (F : adjunction D E) (G : adjunction C D) : adjunction C E := { left := functor.comp _ _ _ G.left F.left, right := functor.comp _ _ _ F.right G.right, Hom_iso := { to_mor := { mor := λ x z, F.3.1.1 (_, _) (G.3.1.1 (_, _) z), Hcomp := λ x y z, funext $ λ t, by have h1 := congr_fun (G.3.1.2 (F.1.1 x.1, x.2) (F.1.1 y.1, y.2) (F.1.2 _ _ z.1, z.2)) t; have h2 := congr_fun (F.3.1.2 (x.1, G.2.1 x.2) (y.1, G.2.1 y.2) (z.1, G.2.2 _ _ z.2)) (G.3.1.1 (_, _) t); dsimp at *; rw [h1, h2] }, inv_mor := { mor := λ x z, G.3.2.1 (_, _) (F.3.2.1 (_, _) z), Hcomp := λ x y z, funext $ λ t, by have h1 := congr_fun (F.3.2.2 (x.1, G.2.1 x.2) (y.1, G.2.1 y.2) (z.1, G.2.2 _ _ z.2)) t; have h2 := congr_fun (G.3.2.2 (F.1.1 x.1, x.2) (F.1.1 y.1, y.2) (F.1.2 _ _ z.1, z.2)) (F.3.2.1 (_, _) t); dsimp at *; rw [h1, h2] }, split_monomorphism := by have h1 := congr_fun (natural_transformation.mk.inj F.3.3); have h2 := congr_fun (natural_transformation.mk.inj G.3.3); dsimp [natural_transformation.comp] at *; congr; funext x f; replace h1 := congr_fun (h1 (x.1, G.2.1 x.2)) (G.3.1.1 (_, _) f); replace h2 := congr_fun (h2 (F.1.1 x.1, x.2)) f; dsimp at *; rw [h1, h2], split_epimorphism := by have h1 := congr_fun (natural_transformation.mk.inj G.3.4); have h2 := congr_fun (natural_transformation.mk.inj F.3.4); dsimp [natural_transformation.comp] at *; congr; funext x f; replace h1 := congr_fun (h1 (F.1.1 x.1, x.2)) (F.3.2.1 (_, _) f); replace h2 := congr_fun (h2 (x.1, G.2.1 x.2)) f; dsimp at *; rw [h1, h2] } } end category
25de1397638efd820b30920d21c125d7f7227ed6
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Init/Control/Lawful.lean
493fb303e4a68e63604c692bcf57e491343de4d6
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
EdAyers/lean4
57ac632d6b0789cb91fab2170e8c9e40441221bd
37ba0df5841bde51dbc2329da81ac23d4f6a4de4
refs/heads/master
1,676,463,245,298
1,660,619,433,000
1,660,619,433,000
183,433,437
1
0
Apache-2.0
1,657,612,672,000
1,556,196,574,000
Lean
UTF-8
Lean
false
false
14,680
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich, Leonardo de Moura -/ prelude import Init.SimpLemmas import Init.Control.Except import Init.Control.StateRef open Function @[simp] theorem monadLift_self [Monad m] (x : m α) : monadLift x = x := rfl class LawfulFunctor (f : Type u → Type v) [Functor f] : Prop where map_const : (Functor.mapConst : α → f β → f α) = Functor.map ∘ const β id_map (x : f α) : id <$> x = x comp_map (g : α → β) (h : β → γ) (x : f α) : (h ∘ g) <$> x = h <$> g <$> x export LawfulFunctor (map_const id_map comp_map) attribute [simp] id_map @[simp] theorem id_map' [Functor m] [LawfulFunctor m] (x : m α) : (fun a => a) <$> x = x := id_map x class LawfulApplicative (f : Type u → Type v) [Applicative f] extends LawfulFunctor f : Prop where seqLeft_eq (x : f α) (y : f β) : x <* y = const β <$> x <*> y seqRight_eq (x : f α) (y : f β) : x *> y = const α id <$> x <*> y pure_seq (g : α → β) (x : f α) : pure g <*> x = g <$> x map_pure (g : α → β) (x : α) : g <$> (pure x : f α) = pure (g x) seq_pure {α β : Type u} (g : f (α → β)) (x : α) : g <*> pure x = (fun h => h x) <$> g seq_assoc {α β γ : Type u} (x : f α) (g : f (α → β)) (h : f (β → γ)) : h <*> (g <*> x) = ((@comp α β γ) <$> h) <*> g <*> x comp_map g h x := (by repeat rw [← pure_seq] simp [seq_assoc, map_pure, seq_pure]) export LawfulApplicative (seqLeft_eq seqRight_eq pure_seq map_pure seq_pure seq_assoc) attribute [simp] map_pure seq_pure @[simp] theorem pure_id_seq [Applicative f] [LawfulApplicative f] (x : f α) : pure id <*> x = x := by simp [pure_seq] class LawfulMonad (m : Type u → Type v) [Monad m] extends LawfulApplicative m : Prop where bind_pure_comp (f : α → β) (x : m α) : x >>= (fun a => pure (f a)) = f <$> x bind_map {α β : Type u} (f : m (α → β)) (x : m α) : f >>= (. <$> x) = f <*> x pure_bind (x : α) (f : α → m β) : pure x >>= f = f x bind_assoc (x : m α) (f : α → m β) (g : β → m γ) : x >>= f >>= g = x >>= fun x => f x >>= g map_pure g x := (by rw [← bind_pure_comp, pure_bind]) seq_pure g x := (by rw [← bind_map]; simp [map_pure, bind_pure_comp]) seq_assoc x g h := (by -- TODO: support for applying `symm` at `simp` arguments have bind_pure_comp_symm {α β : Type u} (f : α → β) (x : m α) : f <$> x = x >>= fun a => pure (f a) := by rw [bind_pure_comp] have bind_map_symm {α β : Type u} (f : m (α → (β : Type u))) (x : m α) : f <*> x = f >>= (. <$> x) := by rw [bind_map] simp[bind_pure_comp_symm, bind_map_symm, bind_assoc, pure_bind]) export LawfulMonad (bind_pure_comp bind_map pure_bind bind_assoc) attribute [simp] pure_bind bind_assoc @[simp] theorem bind_pure [Monad m] [LawfulMonad m] (x : m α) : x >>= pure = x := by show x >>= (fun a => pure (id a)) = x rw [bind_pure_comp, id_map] theorem map_eq_pure_bind [Monad m] [LawfulMonad m] (f : α → β) (x : m α) : f <$> x = x >>= fun a => pure (f a) := by rw [← bind_pure_comp] theorem seq_eq_bind_map {α β : Type u} [Monad m] [LawfulMonad m] (f : m (α → β)) (x : m α) : f <*> x = f >>= (. <$> x) := by rw [← bind_map] theorem bind_congr [Bind m] {x : m α} {f g : α → m β} (h : ∀ a, f a = g a) : x >>= f = x >>= g := by simp [funext h] @[simp] theorem bind_pure_unit [Monad m] [LawfulMonad m] {x : m PUnit} : (x >>= fun _ => pure ⟨⟩) = x := by rw [bind_pure] theorem map_congr [Functor m] {x : m α} {f g : α → β} (h : ∀ a, f a = g a) : (f <$> x : m β) = g <$> x := by simp [funext h] theorem seq_eq_bind {α β : Type u} [Monad m] [LawfulMonad m] (mf : m (α → β)) (x : m α) : mf <*> x = mf >>= fun f => f <$> x := by rw [bind_map] theorem seqRight_eq_bind [Monad m] [LawfulMonad m] (x : m α) (y : m β) : x *> y = x >>= fun _ => y := by rw [seqRight_eq] simp [map_eq_pure_bind, seq_eq_bind_map, const] theorem seqLeft_eq_bind [Monad m] [LawfulMonad m] (x : m α) (y : m β) : x <* y = x >>= fun a => y >>= fun _ => pure a := by rw [seqLeft_eq]; simp [map_eq_pure_bind, seq_eq_bind_map] /-! # Id -/ namespace Id @[simp] theorem map_eq (x : Id α) (f : α → β) : f <$> x = f x := rfl @[simp] theorem bind_eq (x : Id α) (f : α → id β) : x >>= f = f x := rfl @[simp] theorem pure_eq (a : α) : (pure a : Id α) = a := rfl instance : LawfulMonad Id := by refine' { .. } <;> intros <;> rfl end Id /-! # ExceptT -/ namespace ExceptT theorem ext [Monad m] {x y : ExceptT ε m α} (h : x.run = y.run) : x = y := by simp [run] at h assumption @[simp] theorem run_pure [Monad m] (x : α) : run (pure x : ExceptT ε m α) = pure (Except.ok x) := rfl @[simp] theorem run_lift [Monad.{u, v} m] (x : m α) : run (ExceptT.lift x : ExceptT ε m α) = (Except.ok <$> x : m (Except ε α)) := rfl @[simp] theorem run_throw [Monad m] : run (throw e : ExceptT ε m β) = pure (Except.error e) := rfl @[simp] theorem run_bind_lift [Monad m] [LawfulMonad m] (x : m α) (f : α → ExceptT ε m β) : run (ExceptT.lift x >>= f : ExceptT ε m β) = x >>= fun a => run (f a) := by simp[ExceptT.run, ExceptT.lift, bind, ExceptT.bind, ExceptT.mk, ExceptT.bindCont, map_eq_pure_bind] @[simp] theorem bind_throw [Monad m] [LawfulMonad m] (f : α → ExceptT ε m β) : (throw e >>= f) = throw e := by simp [throw, throwThe, MonadExceptOf.throw, bind, ExceptT.bind, ExceptT.bindCont, ExceptT.mk] theorem run_bind [Monad m] (x : ExceptT ε m α) : run (x >>= f : ExceptT ε m β) = run x >>= fun | Except.ok x => run (f x) | Except.error e => pure (Except.error e) := rfl @[simp] theorem lift_pure [Monad m] [LawfulMonad m] (a : α) : ExceptT.lift (pure a) = (pure a : ExceptT ε m α) := by simp [ExceptT.lift, pure, ExceptT.pure] @[simp] theorem run_map [Monad m] [LawfulMonad m] (f : α → β) (x : ExceptT ε m α) : (f <$> x).run = Except.map f <$> x.run := by simp [Functor.map, ExceptT.map, map_eq_pure_bind] apply bind_congr intro a; cases a <;> simp [Except.map] protected theorem seq_eq {α β ε : Type u} [Monad m] (mf : ExceptT ε m (α → β)) (x : ExceptT ε m α) : mf <*> x = mf >>= fun f => f <$> x := rfl protected theorem bind_pure_comp [Monad m] [LawfulMonad m] (f : α → β) (x : ExceptT ε m α) : x >>= pure ∘ f = f <$> x := by intros; rfl protected theorem seqLeft_eq {α β ε : Type u} {m : Type u → Type v} [Monad m] [LawfulMonad m] (x : ExceptT ε m α) (y : ExceptT ε m β) : x <* y = const β <$> x <*> y := by show (x >>= fun a => y >>= fun _ => pure a) = (const (α := α) β <$> x) >>= fun f => f <$> y rw [← ExceptT.bind_pure_comp] apply ext simp [run_bind] apply bind_congr intro | Except.error _ => simp | Except.ok _ => simp [map_eq_pure_bind]; apply bind_congr; intro b; cases b <;> simp [comp, Except.map, const] protected theorem seqRight_eq [Monad m] [LawfulMonad m] (x : ExceptT ε m α) (y : ExceptT ε m β) : x *> y = const α id <$> x <*> y := by show (x >>= fun _ => y) = (const α id <$> x) >>= fun f => f <$> y rw [← ExceptT.bind_pure_comp] apply ext simp [run_bind] apply bind_congr intro a; cases a <;> simp instance [Monad m] [LawfulMonad m] : LawfulMonad (ExceptT ε m) where id_map := by intros; apply ext; simp map_const := by intros; rfl seqLeft_eq := ExceptT.seqLeft_eq seqRight_eq := ExceptT.seqRight_eq pure_seq := by intros; apply ext; simp [ExceptT.seq_eq, run_bind] bind_pure_comp := ExceptT.bind_pure_comp bind_map := by intros; rfl pure_bind := by intros; apply ext; simp [run_bind] bind_assoc := by intros; apply ext; simp [run_bind]; apply bind_congr; intro a; cases a <;> simp end ExceptT /-! # ReaderT -/ namespace ReaderT theorem ext {x y : ReaderT ρ m α} (h : ∀ ctx, x.run ctx = y.run ctx) : x = y := by simp [run] at h exact funext h @[simp] theorem run_pure [Monad m] (a : α) (ctx : ρ) : (pure a : ReaderT ρ m α).run ctx = pure a := rfl @[simp] theorem run_bind [Monad m] (x : ReaderT ρ m α) (f : α → ReaderT ρ m β) (ctx : ρ) : (x >>= f).run ctx = x.run ctx >>= λ a => (f a).run ctx := rfl @[simp] theorem run_mapConst [Monad m] (a : α) (x : ReaderT ρ m β) (ctx : ρ) : (Functor.mapConst a x).run ctx = Functor.mapConst a (x.run ctx) := rfl @[simp] theorem run_map [Monad m] (f : α → β) (x : ReaderT ρ m α) (ctx : ρ) : (f <$> x).run ctx = f <$> x.run ctx := rfl @[simp] theorem run_monadLift [MonadLiftT n m] (x : n α) (ctx : ρ) : (monadLift x : ReaderT ρ m α).run ctx = (monadLift x : m α) := rfl @[simp] theorem run_monadMap [MonadFunctor n m] (f : {β : Type u} → n β → n β) (x : ReaderT ρ m α) (ctx : ρ) : (monadMap @f x : ReaderT ρ m α).run ctx = monadMap @f (x.run ctx) := rfl @[simp] theorem run_read [Monad m] (ctx : ρ) : (ReaderT.read : ReaderT ρ m ρ).run ctx = pure ctx := rfl @[simp] theorem run_seq {α β : Type u} [Monad m] (f : ReaderT ρ m (α → β)) (x : ReaderT ρ m α) (ctx : ρ) : (f <*> x).run ctx = (f.run ctx <*> x.run ctx) := rfl @[simp] theorem run_seqRight [Monad m] (x : ReaderT ρ m α) (y : ReaderT ρ m β) (ctx : ρ) : (x *> y).run ctx = (x.run ctx *> y.run ctx) := rfl @[simp] theorem run_seqLeft [Monad m] (x : ReaderT ρ m α) (y : ReaderT ρ m β) (ctx : ρ) : (x <* y).run ctx = (x.run ctx <* y.run ctx) := rfl instance [Monad m] [LawfulFunctor m] : LawfulFunctor (ReaderT ρ m) where id_map := by intros; apply ext; simp map_const := by intros; funext a b; apply ext; intros; simp [map_const] comp_map := by intros; apply ext; intros; simp [comp_map] instance [Monad m] [LawfulApplicative m] : LawfulApplicative (ReaderT ρ m) where seqLeft_eq := by intros; apply ext; intros; simp [seqLeft_eq] seqRight_eq := by intros; apply ext; intros; simp [seqRight_eq] pure_seq := by intros; apply ext; intros; simp [pure_seq] map_pure := by intros; apply ext; intros; simp [map_pure] seq_pure := by intros; apply ext; intros; simp [seq_pure] seq_assoc := by intros; apply ext; intros; simp [seq_assoc] instance [Monad m] [LawfulMonad m] : LawfulMonad (ReaderT ρ m) where bind_pure_comp := by intros; apply ext; intros; simp [LawfulMonad.bind_pure_comp] bind_map := by intros; apply ext; intros; simp [bind_map] pure_bind := by intros; apply ext; intros; simp bind_assoc := by intros; apply ext; intros; simp end ReaderT /-! # StateRefT -/ instance [Monad m] [LawfulMonad m] : LawfulMonad (StateRefT' ω σ m) := inferInstanceAs (LawfulMonad (ReaderT (ST.Ref ω σ) m)) /-! # StateT -/ namespace StateT theorem ext {x y : StateT σ m α} (h : ∀ s, x.run s = y.run s) : x = y := funext h @[simp] theorem run'_eq [Monad m] (x : StateT σ m α) (s : σ) : run' x s = (·.1) <$> run x s := rfl @[simp] theorem run_pure [Monad m] (a : α) (s : σ) : (pure a : StateT σ m α).run s = pure (a, s) := rfl @[simp] theorem run_bind [Monad m] (x : StateT σ m α) (f : α → StateT σ m β) (s : σ) : (x >>= f).run s = x.run s >>= λ p => (f p.1).run p.2 := by simp [bind, StateT.bind, run] @[simp] theorem run_map {α β σ : Type u} [Monad m] [LawfulMonad m] (f : α → β) (x : StateT σ m α) (s : σ) : (f <$> x).run s = (fun (p : α × σ) => (f p.1, p.2)) <$> x.run s := by simp [Functor.map, StateT.map, run, map_eq_pure_bind] @[simp] theorem run_get [Monad m] (s : σ) : (get : StateT σ m σ).run s = pure (s, s) := rfl @[simp] theorem run_set [Monad m] (s s' : σ) : (set s' : StateT σ m PUnit).run s = pure (⟨⟩, s') := rfl @[simp] theorem run_modify [Monad m] (f : σ → σ) (s : σ) : (modify f : StateT σ m PUnit).run s = pure (⟨⟩, f s) := rfl @[simp] theorem run_modifyGet [Monad m] (f : σ → α × σ) (s : σ) : (modifyGet f : StateT σ m α).run s = pure ((f s).1, (f s).2) := by simp [modifyGet, MonadStateOf.modifyGet, StateT.modifyGet, run] @[simp] theorem run_lift {α σ : Type u} [Monad m] (x : m α) (s : σ) : (StateT.lift x : StateT σ m α).run s = x >>= fun a => pure (a, s) := rfl @[simp] theorem run_bind_lift {α σ : Type u} [Monad m] [LawfulMonad m] (x : m α) (f : α → StateT σ m β) (s : σ) : (StateT.lift x >>= f).run s = x >>= fun a => (f a).run s := by simp [StateT.lift, StateT.run, bind, StateT.bind] @[simp] theorem run_monadLift {α σ : Type u} [Monad m] [MonadLiftT n m] (x : n α) (s : σ) : (monadLift x : StateT σ m α).run s = (monadLift x : m α) >>= fun a => pure (a, s) := rfl @[simp] theorem run_monadMap [Monad m] [MonadFunctor n m] (f : {β : Type u} → n β → n β) (x : StateT σ m α) (s : σ) : (monadMap @f x : StateT σ m α).run s = monadMap @f (x.run s) := rfl @[simp] theorem run_seq {α β σ : Type u} [Monad m] [LawfulMonad m] (f : StateT σ m (α → β)) (x : StateT σ m α) (s : σ) : (f <*> x).run s = (f.run s >>= fun fs => (fun (p : α × σ) => (fs.1 p.1, p.2)) <$> x.run fs.2) := by show (f >>= fun g => g <$> x).run s = _ simp @[simp] theorem run_seqRight [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) (s : σ) : (x *> y).run s = (x.run s >>= fun p => y.run p.2) := by show (x >>= fun _ => y).run s = _ simp @[simp] theorem run_seqLeft {α β σ : Type u} [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) (s : σ) : (x <* y).run s = (x.run s >>= fun p => y.run p.2 >>= fun p' => pure (p.1, p'.2)) := by show (x >>= fun a => y >>= fun _ => pure a).run s = _ simp theorem seqRight_eq [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) : x *> y = const α id <$> x <*> y := by apply ext; intro s simp [map_eq_pure_bind, const] apply bind_congr; intro p; cases p simp [Prod.ext] theorem seqLeft_eq [Monad m] [LawfulMonad m] (x : StateT σ m α) (y : StateT σ m β) : x <* y = const β <$> x <*> y := by apply ext; intro s simp [map_eq_pure_bind] instance [Monad m] [LawfulMonad m] : LawfulMonad (StateT σ m) where id_map := by intros; apply ext; intros; simp[Prod.ext] map_const := by intros; rfl seqLeft_eq := seqLeft_eq seqRight_eq := seqRight_eq pure_seq := by intros; apply ext; intros; simp bind_pure_comp := by intros; apply ext; intros; simp; apply LawfulMonad.bind_pure_comp bind_map := by intros; rfl pure_bind := by intros; apply ext; intros; simp bind_assoc := by intros; apply ext; intros; simp end StateT
400dcbaf87c64c565be9f0f1d3e1aab7f3a194a4
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/algebra/group_with_zero/basic.lean
ab120f32d347f7bb4eee9028818fac739e7eefec
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
13,971
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 algebra.group.basic import algebra.group_with_zero.defs import algebra.group.order_synonym /-! # Groups with an adjoined zero element > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file describes structures that are not usually studied on their own right in mathematics, namely a special sort of monoid: apart from a distinguished “zero element” they form a group, or in other words, they are groups with an adjoined zero element. Examples are: * division rings; * the value monoid of a multiplicative valuation; * in particular, the non-negative real numbers. ## Main definitions Various lemmas about `group_with_zero` and `comm_group_with_zero`. To reduce import dependencies, the type-classes themselves are in `algebra.group_with_zero.defs`. ## Implementation details As is usual in mathlib, we extend the inverse function to the zero element, and require `0⁻¹ = 0`. -/ open_locale classical open function variables {α M₀ G₀ M₀' G₀' F F' : Type*} section section mul_zero_class variables [mul_zero_class M₀] {a b : M₀} lemma left_ne_zero_of_mul : a * b ≠ 0 → a ≠ 0 := mt (λ h, mul_eq_zero_of_left h b) lemma right_ne_zero_of_mul : a * b ≠ 0 → b ≠ 0 := mt (mul_eq_zero_of_right a) lemma ne_zero_and_ne_zero_of_mul (h : a * b ≠ 0) : a ≠ 0 ∧ b ≠ 0 := ⟨left_ne_zero_of_mul h, right_ne_zero_of_mul h⟩ lemma mul_eq_zero_of_ne_zero_imp_eq_zero {a b : M₀} (h : a ≠ 0 → b = 0) : a * b = 0 := if ha : a = 0 then by rw [ha, zero_mul] else by rw [h ha, mul_zero] /-- To match `one_mul_eq_id`. -/ lemma zero_mul_eq_const : ((*) (0 : M₀)) = function.const _ 0 := funext zero_mul /-- To match `mul_one_eq_id`. -/ lemma mul_zero_eq_const : (* (0 : M₀)) = function.const _ 0 := funext mul_zero end mul_zero_class section has_mul variables [has_mul M₀] [has_zero M₀] [no_zero_divisors M₀] {a b : M₀} lemma eq_zero_of_mul_self_eq_zero (h : a * a = 0) : a = 0 := (eq_zero_or_eq_zero_of_mul_eq_zero h).elim id id @[field_simps] theorem mul_ne_zero (ha : a ≠ 0) (hb : b ≠ 0) : a * b ≠ 0 := mt eq_zero_or_eq_zero_of_mul_eq_zero $ not_or_distrib.mpr ⟨ha, hb⟩ end has_mul namespace ne_zero instance mul [has_zero M₀] [has_mul M₀] [no_zero_divisors M₀] {x y : M₀} [ne_zero x] [ne_zero y] : ne_zero (x * y) := ⟨mul_ne_zero out out⟩ end ne_zero end section variables [mul_zero_one_class M₀] /-- In a monoid with zero, if zero equals one, then zero is the only element. -/ lemma eq_zero_of_zero_eq_one (h : (0 : M₀) = 1) (a : M₀) : a = 0 := by rw [← mul_one a, ← h, mul_zero] /-- In a monoid with zero, if zero equals one, then zero is the unique element. Somewhat arbitrarily, we define the default element to be `0`. All other elements will be provably equal to it, but not necessarily definitionally equal. -/ def unique_of_zero_eq_one (h : (0 : M₀) = 1) : unique M₀ := { default := 0, uniq := eq_zero_of_zero_eq_one h } /-- In a monoid with zero, zero equals one if and only if all elements of that semiring are equal. -/ theorem subsingleton_iff_zero_eq_one : (0 : M₀) = 1 ↔ subsingleton M₀ := ⟨λ h, @unique.subsingleton _ (unique_of_zero_eq_one h), λ h, @subsingleton.elim _ h _ _⟩ alias subsingleton_iff_zero_eq_one ↔ subsingleton_of_zero_eq_one _ lemma eq_of_zero_eq_one (h : (0 : M₀) = 1) (a b : M₀) : a = b := @subsingleton.elim _ (subsingleton_of_zero_eq_one h) a b /-- In a monoid with zero, either zero and one are nonequal, or zero is the only element. -/ lemma zero_ne_one_or_forall_eq_0 : (0 : M₀) ≠ 1 ∨ (∀a:M₀, a = 0) := not_or_of_imp eq_zero_of_zero_eq_one end section variables [mul_zero_one_class M₀] [nontrivial M₀] {a b : M₀} lemma left_ne_zero_of_mul_eq_one (h : a * b = 1) : a ≠ 0 := left_ne_zero_of_mul $ ne_zero_of_eq_one h lemma right_ne_zero_of_mul_eq_one (h : a * b = 1) : b ≠ 0 := right_ne_zero_of_mul $ ne_zero_of_eq_one h end section cancel_monoid_with_zero variables [cancel_monoid_with_zero M₀] {a b c : M₀} @[priority 10] -- see Note [lower instance priority] instance cancel_monoid_with_zero.to_no_zero_divisors : no_zero_divisors M₀ := ⟨λ a b ab0, by { by_cases a = 0, { left, exact h }, right, apply cancel_monoid_with_zero.mul_left_cancel_of_ne_zero h, rw [ab0, mul_zero], }⟩ lemma mul_left_inj' (hc : c ≠ 0) : a * c = b * c ↔ a = b := (mul_left_injective₀ hc).eq_iff lemma mul_right_inj' (ha : a ≠ 0) : a * b = a * c ↔ b = c := (mul_right_injective₀ ha).eq_iff @[simp] lemma mul_eq_mul_right_iff : a * c = b * c ↔ a = b ∨ c = 0 := by by_cases hc : c = 0; [simp [hc], simp [mul_left_inj', hc]] @[simp] lemma mul_eq_mul_left_iff : a * b = a * c ↔ b = c ∨ a = 0 := by by_cases ha : a = 0; [simp [ha], simp [mul_right_inj', ha]] lemma mul_right_eq_self₀ : a * b = a ↔ b = 1 ∨ a = 0 := calc a * b = a ↔ a * b = a * 1 : by rw mul_one ... ↔ b = 1 ∨ a = 0 : mul_eq_mul_left_iff lemma mul_left_eq_self₀ : a * b = b ↔ a = 1 ∨ b = 0 := calc a * b = b ↔ a * b = 1 * b : by rw one_mul ... ↔ a = 1 ∨ b = 0 : mul_eq_mul_right_iff @[simp] lemma mul_eq_left₀ (ha : a ≠ 0) : a * b = a ↔ b = 1 := by rw [iff.comm, ←mul_right_inj' ha, mul_one] @[simp] lemma mul_eq_right₀ (hb : b ≠ 0) : a * b = b ↔ a = 1 := by rw [iff.comm, ←mul_left_inj' hb, one_mul] @[simp] lemma left_eq_mul₀ (ha : a ≠ 0) : a = a * b ↔ b = 1 := by rw [eq_comm, mul_eq_left₀ ha] @[simp] lemma right_eq_mul₀ (hb : b ≠ 0) : b = a * b ↔ a = 1 := by rw [eq_comm, mul_eq_right₀ hb] /-- An element of a `cancel_monoid_with_zero` fixed by right multiplication by an element other than one must be zero. -/ theorem eq_zero_of_mul_eq_self_right (h₁ : b ≠ 1) (h₂ : a * b = a) : a = 0 := classical.by_contradiction $ λ ha, h₁ $ mul_left_cancel₀ ha $ h₂.symm ▸ (mul_one a).symm /-- An element of a `cancel_monoid_with_zero` fixed by left multiplication by an element other than one must be zero. -/ theorem eq_zero_of_mul_eq_self_left (h₁ : b ≠ 1) (h₂ : b * a = a) : a = 0 := classical.by_contradiction $ λ ha, h₁ $ mul_right_cancel₀ ha $ h₂.symm ▸ (one_mul a).symm end cancel_monoid_with_zero section group_with_zero variables [group_with_zero G₀] {a b c g h x : G₀} @[simp] lemma mul_inv_cancel_right₀ (h : b ≠ 0) (a : G₀) : (a * b) * b⁻¹ = a := calc (a * b) * b⁻¹ = a * (b * b⁻¹) : mul_assoc _ _ _ ... = a : by simp [h] @[simp] lemma mul_inv_cancel_left₀ (h : a ≠ 0) (b : G₀) : a * (a⁻¹ * b) = b := calc a * (a⁻¹ * b) = (a * a⁻¹) * b : (mul_assoc _ _ _).symm ... = b : by simp [h] lemma inv_ne_zero (h : a ≠ 0) : a⁻¹ ≠ 0 := assume a_eq_0, by simpa [a_eq_0] using mul_inv_cancel h @[simp] lemma inv_mul_cancel (h : a ≠ 0) : a⁻¹ * a = 1 := calc a⁻¹ * a = (a⁻¹ * a) * a⁻¹ * a⁻¹⁻¹ : by simp [inv_ne_zero h] ... = a⁻¹ * a⁻¹⁻¹ : by simp [h] ... = 1 : by simp [inv_ne_zero h] lemma group_with_zero.mul_left_injective (h : x ≠ 0) : function.injective (λ y, x * y) := λ y y' w, by simpa only [←mul_assoc, inv_mul_cancel h, one_mul] using congr_arg (λ y, x⁻¹ * y) w lemma group_with_zero.mul_right_injective (h : x ≠ 0) : function.injective (λ y, y * x) := λ y y' w, by simpa only [mul_assoc, mul_inv_cancel h, mul_one] using congr_arg (λ y, y * x⁻¹) w @[simp] lemma inv_mul_cancel_right₀ (h : b ≠ 0) (a : G₀) : (a * b⁻¹) * b = a := calc (a * b⁻¹) * b = a * (b⁻¹ * b) : mul_assoc _ _ _ ... = a : by simp [h] @[simp] lemma inv_mul_cancel_left₀ (h : a ≠ 0) (b : G₀) : a⁻¹ * (a * b) = b := calc a⁻¹ * (a * b) = (a⁻¹ * a) * b : (mul_assoc _ _ _).symm ... = b : by simp [h] private lemma inv_eq_of_mul (h : a * b = 1) : a⁻¹ = b := by rw [← inv_mul_cancel_left₀ (left_ne_zero_of_mul_eq_one h) b, h, mul_one] @[priority 100] -- See note [lower instance priority] instance group_with_zero.to_division_monoid : division_monoid G₀ := { inv := has_inv.inv, inv_inv := λ a, begin by_cases h : a = 0, { simp [h] }, { exact left_inv_eq_right_inv (inv_mul_cancel $ inv_ne_zero h) (inv_mul_cancel h) } end, mul_inv_rev := λ a b, begin by_cases ha : a = 0, { simp [ha] }, by_cases hb : b = 0, { simp [hb] }, refine inv_eq_of_mul _, simp [mul_assoc, ha, hb] end, inv_eq_of_mul := λ a b, inv_eq_of_mul, ..‹group_with_zero G₀› } @[priority 10] -- see Note [lower instance priority] instance group_with_zero.to_cancel_monoid_with_zero : cancel_monoid_with_zero G₀ := { mul_left_cancel_of_ne_zero := λ x y z hx h, by rw [← inv_mul_cancel_left₀ hx y, h, inv_mul_cancel_left₀ hx z], mul_right_cancel_of_ne_zero := λ x y z hy h, by rw [← mul_inv_cancel_right₀ hy x, h, mul_inv_cancel_right₀ hy z], ..‹group_with_zero G₀› } end group_with_zero section group_with_zero variables [group_with_zero G₀] {a b c : G₀} @[simp] lemma zero_div (a : G₀) : 0 / a = 0 := by rw [div_eq_mul_inv, zero_mul] @[simp] lemma div_zero (a : G₀) : a / 0 = 0 := by rw [div_eq_mul_inv, inv_zero, mul_zero] /-- Multiplying `a` by itself and then by its inverse results in `a` (whether or not `a` is zero). -/ @[simp] lemma mul_self_mul_inv (a : G₀) : a * a * a⁻¹ = a := begin by_cases h : a = 0, { rw [h, inv_zero, mul_zero] }, { rw [mul_assoc, mul_inv_cancel h, mul_one] } end /-- Multiplying `a` by its inverse and then by itself results in `a` (whether or not `a` is zero). -/ @[simp] lemma mul_inv_mul_self (a : G₀) : a * a⁻¹ * a = a := begin by_cases h : a = 0, { rw [h, inv_zero, mul_zero] }, { rw [mul_inv_cancel h, one_mul] } end /-- Multiplying `a⁻¹` by `a` twice results in `a` (whether or not `a` is zero). -/ @[simp] lemma inv_mul_mul_self (a : G₀) : a⁻¹ * a * a = a := begin by_cases h : a = 0, { rw [h, inv_zero, mul_zero] }, { rw [inv_mul_cancel h, one_mul] } end /-- Multiplying `a` by itself and then dividing by itself results in `a`, whether or not `a` is zero. -/ @[simp] lemma mul_self_div_self (a : G₀) : a * a / a = a := by rw [div_eq_mul_inv, mul_self_mul_inv a] /-- Dividing `a` by itself and then multiplying by itself results in `a`, whether or not `a` is zero. -/ @[simp] lemma div_self_mul_self (a : G₀) : a / a * a = a := by rw [div_eq_mul_inv, mul_inv_mul_self a] local attribute [simp] div_eq_mul_inv mul_comm mul_assoc mul_left_comm @[simp] lemma div_self_mul_self' (a : G₀) : a / (a * a) = a⁻¹ := calc a / (a * a) = a⁻¹⁻¹ * a⁻¹ * a⁻¹ : by simp [mul_inv_rev] ... = a⁻¹ : inv_mul_mul_self _ lemma one_div_ne_zero {a : G₀} (h : a ≠ 0) : 1 / a ≠ 0 := by simpa only [one_div] using inv_ne_zero h @[simp] lemma inv_eq_zero {a : G₀} : a⁻¹ = 0 ↔ a = 0 := by rw [inv_eq_iff_eq_inv, inv_zero] @[simp] lemma zero_eq_inv {a : G₀} : 0 = a⁻¹ ↔ 0 = a := eq_comm.trans $ inv_eq_zero.trans eq_comm /-- Dividing `a` by the result of dividing `a` by itself results in `a` (whether or not `a` is zero). -/ @[simp] lemma div_div_self (a : G₀) : a / (a / a) = a := begin rw div_div_eq_mul_div, exact mul_self_div_self a end lemma ne_zero_of_one_div_ne_zero {a : G₀} (h : 1 / a ≠ 0) : a ≠ 0 := assume ha : a = 0, begin rw [ha, div_zero] at h, contradiction end lemma eq_zero_of_one_div_eq_zero {a : G₀} (h : 1 / a = 0) : a = 0 := classical.by_cases (assume ha, ha) (assume ha, ((one_div_ne_zero ha) h).elim) lemma mul_left_surjective₀ {a : G₀} (h : a ≠ 0) : surjective (λ g, a * g) := λ g, ⟨a⁻¹ * g, by simp [← mul_assoc, mul_inv_cancel h]⟩ lemma mul_right_surjective₀ {a : G₀} (h : a ≠ 0) : surjective (λ g, g * a) := λ g, ⟨g * a⁻¹, by simp [mul_assoc, inv_mul_cancel h]⟩ end group_with_zero section comm_group_with_zero variables [comm_group_with_zero G₀] {a b c d : G₀} lemma div_mul_eq_mul_div₀ (a b c : G₀) : (a / c) * b = a * b / c := by simp_rw [div_eq_mul_inv, mul_assoc, mul_comm c⁻¹] end comm_group_with_zero /-! ### Order dual -/ open order_dual instance [h : mul_zero_class α] : mul_zero_class αᵒᵈ := h instance [h : mul_zero_one_class α] : mul_zero_one_class αᵒᵈ := h instance [has_mul α] [has_zero α] [h : no_zero_divisors α] : no_zero_divisors αᵒᵈ := h instance [h : semigroup_with_zero α] : semigroup_with_zero αᵒᵈ := h instance [h : monoid_with_zero α] : monoid_with_zero αᵒᵈ := h instance [h : cancel_monoid_with_zero α] : cancel_monoid_with_zero αᵒᵈ := h instance [h : comm_monoid_with_zero α] : comm_monoid_with_zero αᵒᵈ := h instance [h : cancel_comm_monoid_with_zero α] : cancel_comm_monoid_with_zero αᵒᵈ := h instance [h : group_with_zero α] : group_with_zero αᵒᵈ := h instance [h : comm_group_with_zero α] : comm_group_with_zero αᵒᵈ := h /-! ### Lexicographic order -/ instance [h : mul_zero_class α] : mul_zero_class (lex α) := h instance [h : mul_zero_one_class α] : mul_zero_one_class (lex α) := h instance [has_mul α] [has_zero α] [h : no_zero_divisors α] : no_zero_divisors (lex α) := h instance [h : semigroup_with_zero α] : semigroup_with_zero (lex α) := h instance [h : monoid_with_zero α] : monoid_with_zero (lex α) := h instance [h : cancel_monoid_with_zero α] : cancel_monoid_with_zero (lex α) := h instance [h : comm_monoid_with_zero α] : comm_monoid_with_zero (lex α) := h instance [h : cancel_comm_monoid_with_zero α] : cancel_comm_monoid_with_zero (lex α) := h instance [h : group_with_zero α] : group_with_zero (lex α) := h instance [h : comm_group_with_zero α] : comm_group_with_zero (lex α) := h
fa844566b4116e7570571d226d8ea7231db36b30
1dd0001f48991684032999e18f88be3ece4261d7
/src/instructor/lectures/lecture_9.lean
80a42a0907589f14023ab1a2f0684976e58fcba2
[]
no_license
rayouness/cs2120f21
e0a3fa89a6ac50c8a83e85bd7795a2710aceb7e2
5dfa57f111ec7f322474be1c87992fe1fedd6610
refs/heads/main
1,690,957,987,242
1,632,333,173,000
1,632,333,173,000
399,947,440
0
0
null
null
null
null
UTF-8
Lean
false
false
6,659
lean
/- Negation -/ /- Given an proposition, P, we can form a new proposition, usually written as ¬P, which we pronounce as "not P," and which we define in such as way as to assert that P is not true. -/ /- So what does it mean when we say that *it is true that P is not true*? -/ /- First, if ¬P is true, there should be a proof of it. Second, what that proof should show is that *there can be no proof of P*. -/ /- So the way we're going to say ¬P is to say if P were true then something that is completely impossible would happen. Because the impossible cannot happen, therefore there must be no proof of P. -/ /- What we're going take as "the impossible thing" is that there is a proof of false. Have defined false to be exactly a proposition with no proofs (otherwise it'd be true), so to have a proof of false is an impossibility.) -/ example : false → false := begin assume f, exact f, end example : false → true := begin assume f, exact true.intro, end example : true → true := begin assume t, exact true.intro, end example : true → false := begin assume t, -- stuck end /- So, wow, we just gained a lot of insight! true → true true true → false false false → true true false → false true -/ /- It's this analysis that leads to the definition of ¬P. For any proposition P, we *define* ¬P to be the proposition, P → false. What this means is that if there is a proof of P → false, then you can conclude (by definition) ¬P. This is the introduction rule for ¬. -/ #check not -- see definition in Lean library /- So how do you prove P → false? It's just like any other implication: *assume* that P is true and show that with that you can construct a proof of false. -/ /- Example. Prove ¬ 0 = 1. -/ example : false := begin end example : ¬ false := begin assume f, exact f, end example : ¬ (0 = 1) := begin assume h, end /- To understand how to finish off this last proof, we need to talk more case analysis again. Remember that we've used it to reason from a proof of a disjunction. Suppose we want to know that P ∨ Q → R. We start by assuming that we have a proof, pq, of P ∨ Q, and then we need to show that R follows as a logical consequence. But there are exactly two possible forms that a proof of P ∨ Q can take (or.intro_left p) and (or.intro_right q), where p and q are proofs of P and of Q, respectively. What we therefore need to show is that no matter which of those two forms of proof we have, of P ∨ Q, that the truth of R follows. So we do a case analysis on pq. In the first case, we assume P ∨ Q is true because P is (or.intro_left was used to create the proof). In this case we need to show that P → R. In the second case, where P ∨ Q is true because Q is (or.intro_right was used to create the proof of P ∨ Q), we need to show that Q → R. The general principle is that if you can show that a proposition, R, is true no matter which form of proof you have of some proposition, X, then you have proven that X → R. This is the key idea behind *proof by case analysis*. Show that given any possible proof of P, that Q follows, and that's what gives you a proof of P → Q. A good start is to know just how many cases you have to consider! Given proof of P ∨ Q, how many cases are there? Two. -/ example : ∀ (P Q R : Prop), P ∨ Q → R := begin assume P Q R, assume pq, cases pq, -- or elimination -- stuck here of course end /- Case analysis is a broadly useful proof technique. Here we use it to prove true → true. We assume the premise, true and have to show true. The true.intro rule will work, but let's instead try "case analysis" on the assumed proof of true. What we'll see is that there is only one case (whereas with a proof of P ∨ Q, case analysis presents two cases to consider.) -/ example : true → true := begin assume t, cases t, exact true.intro, end /- The general principle is this: if we have an assumed/arbitrary proof of X and need to show Y, we can try to do this by doing case analysis on the proof of X. If we can show that Y is true *in all cases* (in a context in which we have *some* proof of X) then we have shown that Y must be true in this context. -/ /- The most interesting example of the preceding principle occurs when you're given or you can derive a proof of false. For then all you have to do to show that some proposition, P, follows is to show that it's true for all possible ways in which that proof of false could have been constructed. Remember, there are two ways to construct a proof of P ∨ Q, so case analysis results in two cases to consider; and one way to construct a proof of true, so there's only one case to consider. Now, with a proof of false there are *zero* ways to construct proof, *and so there are zero cases to consider, and the truth of your conclusion follows automatically! -/ /- Here we prove false → false again, but this time instead of using the assumed proof of false to prove false, we do case analysis on the given proof of false. There are no cases to consider, so the proof is complete! -/ example : false → false := begin assume f, cases f, -- instead of exact f, do case analysis end /- 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! -/ /- Here, then, is the general principle for false elimination: how you *use* a proof of false that you have been given, that you've assumed, or that you've derived from a contradiction (as we will see). The theorem states that if you're given any proposition, P, and a proof, f, of false, then in that context, P has a proof and is true. Another way to think about what's going on here is that if you have a proof of false, you are already in a situation that can't possible happen "in reality" -- there is no proof of false -- so you can just ignore this situation. -/ theorem false_elim (P : Prop) (f : false) : P := begin cases f, end /- 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). -/ example : false → false := begin assume f, exact false.elim f, -- Using Lean's version end
ad6c0a1893902e695ed35bfd0befbb84a6b44b2d
f083c4ed5d443659f3ed9b43b1ca5bb037ddeb58
/data/int/order.lean
fbd5645bc590f839bf5e87db0db6c8ca1ddc7ea1
[ "Apache-2.0" ]
permissive
semorrison/mathlib
1be6f11086e0d24180fec4b9696d3ec58b439d10
20b4143976dad48e664c4847b75a85237dca0a89
refs/heads/master
1,583,799,212,170
1,535,634,130,000
1,535,730,505,000
129,076,205
0
0
Apache-2.0
1,551,697,998,000
1,523,442,265,000
Lean
UTF-8
Lean
false
false
7,652
lean
/- Copyright (c) 2016 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad The order relation on the integers. -/ import data.int.basic namespace int lemma of_nat_le_of_nat_of_le {n m : ℕ} (h : n ≤ m) : of_nat n ≤ of_nat m := coe_nat_le_coe_nat_of_le h lemma le_of_of_nat_le_of_nat {n m : ℕ} (h : of_nat n ≤ of_nat m) : n ≤ m := let ⟨i, (hi : of_nat n + of_nat i = of_nat m)⟩ := le.dest h in have i + n = m, by apply int.of_nat_inj; rwa [add_comm, of_nat_add], this ▸ nat.le_add_left _ _ end int /- /- more facts specific to int -/ theorem coe_nat_nonneg (n : ℕ) : 0 ≤ ↑n := trivial theorem coe_nat_pos {n : ℕ} (Hpos : #nat n > 0) : ↑n > 0 := coe_nat_lt_coe_nat_of_lt Hpos theorem coe_nat_succ_pos (n : nat) : ↑(nat.succ n) > 0 := coe_nat_pos !nat.succ_pos theorem exists_eq_coe_nat {a : ℤ} (H : 0 ≤ a) : ∃n : ℕ, a = ↑n := obtain (n : ℕ) (H1 : 0 + ↑n = a), from le.dest H, exists.intro n (!zero_add ▸ (H1⁻¹)) theorem exists_eq_neg_coe_nat {a : ℤ} (H : a ≤ 0) : ∃n : ℕ, a = -(↑n) := have -a ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos H, obtain (n : ℕ) (Hn : -a = ↑n), from exists_eq_coe_nat this, exists.intro n (eq_neg_of_eq_neg (Hn⁻¹)) theorem coe_nat_nat_abs_of_nonneg {a : ℤ} (H : a ≥ 0) : ↑(nat_abs a) = a := obtain (n : ℕ) (Hn : a = ↑n), from exists_eq_coe_nat H, Hn⁻¹ ▸ congr_arg coe_nat (nat_abs_↑n) theorem coe_nat_nat_abs_of_nonpos {a : ℤ} (H : a ≤ 0) : ↑(nat_abs a) = -a := have -a ≥ 0, from iff.mpr !neg_nonneg_iff_nonpos H, calc coe_nat (nat_abs a) = coe_nat (nat_abs (-a)) : nat_abs_neg ... = -a : coe_nat_nat_abs_of_nonneg this theorem coe_nat_nat_abs (b : ℤ) : nat_abs b = abs b := or.elim (le.total 0 b) (assume H : b ≥ 0, coe_nat_nat_abs_of_nonneg H ⬝ (abs_of_nonneg H)⁻¹) (assume H : b ≤ 0, coe_nat_nat_abs_of_nonpos H ⬝ (abs_of_nonpos H)⁻¹) theorem nat_abs_abs (a : ℤ) : nat_abs (abs a) = nat_abs a := abs.by_cases rfl !nat_abs_neg theorem lt_of_add_one_le {a b : ℤ} (H : a + 1 ≤ b) : a < b := obtain (n : nat) (H1 : a + 1 + n = b), from le.dest H, have a + succ n = b, by rw [← H1, add.assoc, add.comm 1], lt.intro this theorem add_one_le_of_lt {a b : ℤ} (H : a < b) : a + 1 ≤ b := obtain (n : nat) (H1 : a + succ n = b), from lt.elim H, have a + 1 + n = b, by rw [← H1, add.assoc, add.comm 1], le.intro this theorem lt_add_one_of_le {a b : ℤ} (H : a ≤ b) : a < b + 1 := lt_add_of_le_of_pos H trivial theorem le_of_lt_add_one {a b : ℤ} (H : a < b + 1) : a ≤ b := have H1 : a + 1 ≤ b + 1, from add_one_le_of_lt H, le_of_add_le_add_right H1 theorem sub_one_le_of_lt {a b : ℤ} (H : a ≤ b) : a - 1 < b := lt_of_add_one_le (begin rw sub_add_cancel, exact H end) theorem lt_of_sub_one_le {a b : ℤ} (H : a - 1 < b) : a ≤ b := !sub_add_cancel ▸ add_one_le_of_lt H theorem le_sub_one_of_lt {a b : ℤ} (H : a < b) : a ≤ b - 1 := le_of_lt_add_one begin rw sub_add_cancel, exact H end theorem lt_of_le_sub_one {a b : ℤ} (H : a ≤ b - 1) : a < b := !sub_add_cancel ▸ (lt_add_one_of_le H) theorem sign_of_succ (n : nat) : sign (nat.succ n) = 1 := sign_of_pos (coe_nat_pos !nat.succ_pos) theorem exists_eq_neg_succ_coe_nat {a : ℤ} : a < 0 → ∃m : ℕ, a = -[1+m] := int.cases_on a (assume (m : nat) H, absurd (coe_nat_nonneg m : 0 ≤ m) (not_le_of_gt H)) (assume (m : nat) H, exists.intro m rfl) theorem eq_one_of_mul_eq_one_right {a b : ℤ} (H : a ≥ 0) (H' : a * b = 1) : a = 1 := have a * b > 0, by rw H'; apply trivial, have b > 0, from pos_of_mul_pos_left this H, have a > 0, from pos_of_mul_pos_right `a * b > 0` (le_of_lt `b > 0`), or.elim (le_or_gt a 1) (assume : a ≤ 1, show a = 1, from le.antisymm this (add_one_le_of_lt `a > 0`)) (assume : a > 1, have a * b ≥ 2 * 1, from mul_le_mul (add_one_le_of_lt `a > 1`) (add_one_le_of_lt `b > 0`) trivial H, have false, by rw H' at this; exact this, false.elim this) theorem eq_one_of_mul_eq_one_left {a b : ℤ} (H : b ≥ 0) (H' : a * b = 1) : b = 1 := eq_one_of_mul_eq_one_right H (!mul.comm ▸ H') theorem eq_one_of_mul_eq_self_left {a b : ℤ} (Hpos : a ≠ 0) (H : b * a = a) : b = 1 := eq_of_mul_eq_mul_right Hpos (H ⬝ (one_mul a)⁻¹) theorem eq_one_of_mul_eq_self_right {a b : ℤ} (Hpos : b ≠ 0) (H : b * a = b) : a = 1 := eq_one_of_mul_eq_self_left Hpos (!mul.comm ▸ H) theorem eq_one_of_dvd_one {a : ℤ} (H : a ≥ 0) (H' : a ∣ 1) : a = 1 := dvd.elim H' (assume b, assume : 1 = a * b, eq_one_of_mul_eq_one_right H this⁻¹) theorem exists_least_of_bdd {P : ℤ → Prop} [HP : decidable_pred P] (Hbdd : ∃ b : ℤ, ∀ z : ℤ, z ≤ b → ¬ P z) (Hinh : ∃ z : ℤ, P z) : ∃ lb : ℤ, P lb ∧ (∀ z : ℤ, z < lb → ¬ P z) := begin cases Hbdd with [b, Hb], cases Hinh with [elt, Helt], existsi b + coe_nat (least (λ n, P (b + ↑n)) (nat.succ (nat_abs (elt - b)))), have Heltb : elt > b, begin apply lt_of_not_ge, intro Hge, apply (Hb _ Hge) Helt end, have H' : P (b + coe_nat (nat_abs (elt - b))), begin rw [coe_nat_nat_abs_of_nonneg (int.le_of_lt (iff.mpr !sub_pos_iff_lt Heltb)), add.comm, sub_add_cancel], apply Helt end, apply and.intro, apply least_of_lt _ !lt_succ_self H', intros z Hz, cases em (z ≤ b) with [Hzb, Hzb], apply Hb _ Hzb, let Hzb' := lt_of_not_ge Hzb, let Hpos := iff.mpr !sub_pos_iff_lt Hzb', have Hzbk : z = b + coe_nat (nat_abs (z - b)), by rw [coe_nat_nat_abs_of_nonneg (int.le_of_lt Hpos), int.add_comm, sub_add_cancel], have Hk : nat_abs (z - b) < least (λ n, P (b + ↑n)) (nat.succ (nat_abs (elt - b))), begin have Hz' := iff.mp !lt_add_iff_sub_lt_left Hz, rw [←coe_nat_nat_abs_of_nonneg (int.le_of_lt Hpos) at Hz'], apply lt_of_coe_nat_lt_coe_nat Hz' end, let Hk' := not_le_of_gt Hk, rw Hzbk, apply λ p, mt (ge_least_of_lt _ p) Hk', apply nat.lt_trans Hk, apply least_lt _ !lt_succ_self H' end theorem exists_greatest_of_bdd {P : ℤ → Prop} [HP : decidable_pred P] (Hbdd : ∃ b : ℤ, ∀ z : ℤ, z ≥ b → ¬ P z) (Hinh : ∃ z : ℤ, P z) : ∃ ub : ℤ, P ub ∧ (∀ z : ℤ, z > ub → ¬ P z) := begin cases Hbdd with [b, Hb], cases Hinh with [elt, Helt], existsi b - coe_nat (least (λ n, P (b - ↑n)) (nat.succ (nat_abs (b - elt)))), have Heltb : elt < b, begin apply lt_of_not_ge, intro Hge, apply (Hb _ Hge) Helt end, have H' : P (b - coe_nat (nat_abs (b - elt))), begin rw [coe_nat_nat_abs_of_nonneg (int.le_of_lt (iff.mpr !sub_pos_iff_lt Heltb)), sub_sub_self], apply Helt end, apply and.intro, apply least_of_lt _ !lt_succ_self H', intros z Hz, cases em (z ≥ b) with [Hzb, Hzb], apply Hb _ Hzb, let Hzb' := lt_of_not_ge Hzb, let Hpos := iff.mpr !sub_pos_iff_lt Hzb', have Hzbk : z = b - coe_nat (nat_abs (b - z)), by rw [coe_nat_nat_abs_of_nonneg (int.le_of_lt Hpos), sub_sub_self], have Hk : nat_abs (b - z) < least (λ n, P (b - ↑n)) (nat.succ (nat_abs (b - elt))), begin have Hz' := iff.mp !lt_add_iff_sub_lt_left (iff.mpr !lt_add_iff_sub_lt_right Hz), rw [←coe_nat_nat_abs_of_nonneg (int.le_of_lt Hpos) at Hz'], apply lt_of_coe_nat_lt_coe_nat Hz' end, let Hk' := not_le_of_gt Hk, rw Hzbk, apply λ p, mt (ge_least_of_lt _ p) Hk', apply nat.lt_trans Hk, apply least_lt _ !lt_succ_self H' end end int -/
22d824485b526255581810774c08869586dadde5
5ae26df177f810c5006841e9c73dc56e01b978d7
/src/topology/bases.lean
989ded3e16e83837605d1ff9092f9f0e25e16281
[ "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
10,502
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 Bases of topologies. Countability axioms. -/ import topology.order data.set.countable open set filter lattice classical namespace topological_space /- countability axioms For our applications we are interested that there exists a countable basis, but we do not need the concrete basis itself. This allows us to declare these type classes as `Prop` to use them as mixins. -/ universe u variables {α : Type u} [t : topological_space α] include t /-- A topological basis is one that satisfies the necessary conditions so that it suffices to take unions of the basis sets to get a topology (without taking finite intersections as well). -/ def is_topological_basis (s : set (set α)) : Prop := (∀t₁∈s, ∀t₂∈s, ∀ x ∈ t₁ ∩ t₂, ∃ t₃∈s, x ∈ t₃ ∧ t₃ ⊆ t₁ ∩ t₂) ∧ (⋃₀ s) = univ ∧ t = generate_from s lemma is_topological_basis_of_subbasis {s : set (set α)} (hs : t = generate_from s) : is_topological_basis ((λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ ⋂₀ f ≠ ∅}) := let b' := (λf, ⋂₀ f) '' {f:set (set α) | finite f ∧ f ⊆ s ∧ ⋂₀ f ≠ ∅} in ⟨assume s₁ ⟨t₁, ⟨hft₁, ht₁b, ht₁⟩, eq₁⟩ s₂ ⟨t₂, ⟨hft₂, ht₂b, ht₂⟩, eq₂⟩, have ie : ⋂₀(t₁ ∪ t₂) = ⋂₀ t₁ ∩ ⋂₀ t₂, from Inf_union, eq₁ ▸ eq₂ ▸ assume x h, ⟨_, ⟨t₁ ∪ t₂, ⟨finite_union hft₁ hft₂, union_subset ht₁b ht₂b, by simpa only [ie] using ne_empty_of_mem h⟩, ie⟩, h, subset.refl _⟩, eq_univ_iff_forall.2 $ assume a, ⟨univ, ⟨∅, ⟨finite_empty, empty_subset _, by rw sInter_empty; exact nonempty_iff_univ_ne_empty.1 ⟨a⟩⟩, sInter_empty⟩, mem_univ _⟩, have generate_from s = generate_from b', from le_antisymm (le_generate_from $ assume u ⟨t, ⟨hft, htb, ne⟩, eq⟩, eq ▸ @is_open_sInter _ (generate_from s) _ hft (assume s hs, generate_open.basic _ $ htb hs)) (le_generate_from $ assume s hs, by_cases (assume : s = ∅, by rw [this]; apply @is_open_empty _ _) (assume : s ≠ ∅, generate_open.basic _ ⟨{s}, ⟨finite_singleton s, singleton_subset_iff.2 hs, by rwa [sInter_singleton]⟩, sInter_singleton s⟩)), this ▸ hs⟩ lemma is_topological_basis_of_open_of_nhds {s : set (set α)} (h_open : ∀ u ∈ s, _root_.is_open u) (h_nhds : ∀(a:α) (u : set α), a ∈ u → _root_.is_open u → ∃v ∈ s, a ∈ v ∧ v ⊆ u) : is_topological_basis s := ⟨assume t₁ ht₁ t₂ ht₂ x ⟨xt₁, xt₂⟩, h_nhds x (t₁ ∩ t₂) ⟨xt₁, xt₂⟩ (is_open_inter _ _ _ (h_open _ ht₁) (h_open _ ht₂)), eq_univ_iff_forall.2 $ assume a, let ⟨u, h₁, h₂, _⟩ := h_nhds a univ trivial (is_open_univ _) in ⟨u, h₁, h₂⟩, le_antisymm (le_generate_from h_open) (assume u hu, (@is_open_iff_nhds α (generate_from _) _).mpr $ assume a hau, let ⟨v, hvs, hav, hvu⟩ := h_nhds a u hau hu in by rw nhds_generate_from; exact infi_le_of_le v (infi_le_of_le ⟨hav, hvs⟩ $ le_principal_iff.2 hvu))⟩ lemma mem_nhds_of_is_topological_basis {a : α} {s : set α} {b : set (set α)} (hb : is_topological_basis b) : s ∈ nhds a ↔ ∃t∈b, a ∈ t ∧ t ⊆ s := begin change s ∈ (nhds a).sets ↔ ∃t∈b, a ∈ t ∧ t ⊆ s, rw [hb.2.2, nhds_generate_from, infi_sets_eq'], { simp only [mem_bUnion_iff, exists_prop, mem_set_of_eq, and_assoc, and.left_comm], refl }, { exact assume s ⟨hs₁, hs₂⟩ t ⟨ht₁, ht₂⟩, have a ∈ s ∩ t, from ⟨hs₁, ht₁⟩, let ⟨u, hu₁, hu₂, hu₃⟩ := hb.1 _ hs₂ _ ht₂ _ this in ⟨u, ⟨hu₂, hu₁⟩, le_principal_iff.2 (subset.trans hu₃ (inter_subset_left _ _)), le_principal_iff.2 (subset.trans hu₃ (inter_subset_right _ _))⟩ }, { rcases eq_univ_iff_forall.1 hb.2.1 a with ⟨i, h1, h2⟩, exact ⟨i, h2, h1⟩ } end lemma is_open_of_is_topological_basis {s : set α} {b : set (set α)} (hb : is_topological_basis b) (hs : s ∈ b) : _root_.is_open s := is_open_iff_mem_nhds.2 $ λ a as, (mem_nhds_of_is_topological_basis hb).2 ⟨s, hs, as, subset.refl _⟩ lemma mem_basis_subset_of_mem_open {b : set (set α)} (hb : is_topological_basis b) {a:α} {u : set α} (au : a ∈ u) (ou : _root_.is_open u) : ∃v ∈ b, a ∈ v ∧ v ⊆ u := (mem_nhds_of_is_topological_basis hb).1 $ mem_nhds_sets ou au lemma sUnion_basis_of_is_open {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : _root_.is_open u) : ∃ S ⊆ B, u = ⋃₀ S := ⟨{s ∈ B | s ⊆ u}, λ s h, h.1, set.ext $ λ a, ⟨λ ha, let ⟨b, hb, ab, bu⟩ := mem_basis_subset_of_mem_open hB ha ou in ⟨b, ⟨hb, bu⟩, ab⟩, λ ⟨b, ⟨hb, bu⟩, ab⟩, bu ab⟩⟩ lemma Union_basis_of_is_open {B : set (set α)} (hB : is_topological_basis B) {u : set α} (ou : _root_.is_open u) : ∃ (β : Type u) (f : β → set α), u = (⋃ i, f i) ∧ ∀ i, f i ∈ B := let ⟨S, sb, su⟩ := sUnion_basis_of_is_open hB ou in ⟨S, subtype.val, su.trans set.sUnion_eq_Union, λ ⟨b, h⟩, sb h⟩ variables (α) /-- A separable space is one with a countable dense subset. -/ class separable_space : Prop := (exists_countable_closure_eq_univ : ∃s:set α, countable s ∧ closure s = univ) /-- A first-countable space is one in which every point has a countable neighborhood basis. -/ class first_countable_topology : Prop := (nhds_generated_countable : ∀a:α, ∃s:set (set α), countable s ∧ nhds a = (⨅t∈s, principal t)) /-- A second-countable space is one with a countable basis. -/ class second_countable_topology : Prop := (is_open_generated_countable : ∃b:set (set α), countable b ∧ t = topological_space.generate_from b) instance second_countable_topology.to_first_countable_topology [second_countable_topology α] : first_countable_topology α := let ⟨b, hb, eq⟩ := second_countable_topology.is_open_generated_countable α in ⟨assume a, ⟨{s | a ∈ s ∧ s ∈ b}, countable_subset (assume x ⟨_, hx⟩, hx) hb, by rw [eq, nhds_generate_from]⟩⟩ lemma second_countable_topology_induced (β) [t : topological_space β] [second_countable_topology β] (f : α → β) : @second_countable_topology α (t.induced f) := begin rcases second_countable_topology.is_open_generated_countable β with ⟨b, hb, eq⟩, refine { is_open_generated_countable := ⟨preimage f '' b, countable_image _ hb, _⟩ }, rw [eq, induced_generate_from_eq] end instance subtype.second_countable_topology (s : set α) [topological_space α] [second_countable_topology α] : second_countable_topology s := second_countable_topology_induced s α coe lemma is_open_generated_countable_inter [second_countable_topology α] : ∃b:set (set α), countable b ∧ ∅ ∉ b ∧ is_topological_basis b := let ⟨b, hb₁, hb₂⟩ := second_countable_topology.is_open_generated_countable α in let b' := (λs, ⋂₀ s) '' {s:set (set α) | finite s ∧ s ⊆ b ∧ ⋂₀ s ≠ ∅} in ⟨b', countable_image _ $ countable_subset (by simp only [(and_assoc _ _).symm]; exact inter_subset_left _ _) (countable_set_of_finite_subset hb₁), assume ⟨s, ⟨_, _, hn⟩, hp⟩, hn hp, is_topological_basis_of_subbasis hb₂⟩ instance second_countable_topology.to_separable_space [second_countable_topology α] : separable_space α := let ⟨b, hb₁, hb₂, hb₃, hb₄, eq⟩ := is_open_generated_countable_inter α in have nhds_eq : ∀a, nhds a = (⨅ s : {s : set α // a ∈ s ∧ s ∈ b}, principal s.val), by intro a; rw [eq, nhds_generate_from, infi_subtype]; refl, have ∀s∈b, ∃a, a ∈ s, from assume s hs, exists_mem_of_ne_empty $ assume eq, hb₂ $ eq ▸ hs, have ∃f:∀s∈b, α, ∀s h, f s h ∈ s, by simp only [skolem] at this; exact this, let ⟨f, hf⟩ := this in ⟨⟨(⋃s∈b, ⋃h:s∈b, {f s h}), countable_bUnion hb₁ (λ _ _, countable_Union_Prop $ λ _, countable_singleton _), set.ext $ assume a, have a ∈ (⋃₀ b), by rw [hb₄]; exact trivial, let ⟨t, ht₁, ht₂⟩ := this in have w : {s : set α // a ∈ s ∧ s ∈ b}, from ⟨t, ht₂, ht₁⟩, suffices (⨅ (x : {s // a ∈ s ∧ s ∈ b}), principal (x.val ∩ ⋃s (h₁ h₂ : s ∈ b), {f s h₂})) ≠ ⊥, by simpa only [closure_eq_nhds, nhds_eq, infi_inf w, inf_principal, mem_set_of_eq, mem_univ, iff_true], infi_neq_bot_of_directed ⟨a⟩ (assume ⟨s₁, has₁, hs₁⟩ ⟨s₂, has₂, hs₂⟩, have a ∈ s₁ ∩ s₂, from ⟨has₁, has₂⟩, let ⟨s₃, hs₃, has₃, hs⟩ := hb₃ _ hs₁ _ hs₂ _ this in ⟨⟨s₃, has₃, hs₃⟩, begin simp only [le_principal_iff, mem_principal_sets, (≥)], simp only [subset_inter_iff] at hs, split; apply inter_subset_inter_left; simp only [hs] end⟩) (assume ⟨s, has, hs⟩, have s ∩ (⋃ (s : set α) (H h : s ∈ b), {f s h}) ≠ ∅, from ne_empty_of_mem ⟨hf _ hs, mem_bUnion hs $ mem_Union.mpr ⟨hs, mem_singleton _⟩⟩, mt principal_eq_bot_iff.1 this) ⟩⟩ variables {α} lemma is_open_Union_countable [second_countable_topology α] {ι} (s : ι → set α) (H : ∀ i, _root_.is_open (s i)) : ∃ T : set ι, countable T ∧ (⋃ i ∈ T, s i) = ⋃ i, s i := let ⟨B, cB, _, bB⟩ := is_open_generated_countable_inter α in begin let B' := {b ∈ B | ∃ i, b ⊆ s i}, choose f hf using λ b:B', b.2.2, haveI : encodable B' := (countable_subset (sep_subset _ _) cB).to_encodable, refine ⟨_, countable_range f, subset.antisymm (bUnion_subset_Union _ _) (sUnion_subset _)⟩, rintro _ ⟨i, rfl⟩ x xs, rcases mem_basis_subset_of_mem_open bB xs (H _) with ⟨b, hb, xb, bs⟩, exact ⟨_, ⟨_, rfl⟩, _, ⟨⟨⟨_, hb, _, bs⟩, rfl⟩, rfl⟩, hf _ (by exact xb)⟩ end lemma is_open_sUnion_countable [second_countable_topology α] (S : set (set α)) (H : ∀ s ∈ S, _root_.is_open s) : ∃ T : set (set α), countable T ∧ T ⊆ S ∧ ⋃₀ T = ⋃₀ S := let ⟨T, cT, hT⟩ := is_open_Union_countable (λ s:S, s.1) (λ s, H s.1 s.2) in ⟨subtype.val '' T, countable_image _ cT, image_subset_iff.2 $ λ ⟨x, xs⟩ xt, xs, by rwa [sUnion_image, sUnion_eq_Union]⟩ end topological_space
e0b5109aebd87e602b7adea3a025d3c1ca506d97
fe84e287c662151bb313504482b218a503b972f3
/src/algebra/prod_equiv.lean
0e03f6f8bd0946f0518e9968dce6e2ffaa3b374b
[]
no_license
NeilStrickland/lean_lib
91e163f514b829c42fe75636407138b5c75cba83
6a9563de93748ace509d9db4302db6cd77d8f92c
refs/heads/master
1,653,408,198,261
1,652,996,419,000
1,652,996,419,000
181,006,067
4
1
null
null
null
null
UTF-8
Lean
false
false
3,985
lean
/- Copyright (c) 2019 Neil Strickland. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Neil Strickland This file contains various addenda to algebra/big_operators. One issue is that I often prefer to work with fintypes and sums/products over all of univ, and it is helpful to have some lemmas specialised to that situation. -/ import algebra.big_operators data.fintype.basic import tactic.squeeze universes uα uβ uγ uδ variables {α : Type uα} {β : Type uβ} {γ : Type uγ} {δ : Type uδ} variables [decidable_eq α] [decidable_eq β] variables [comm_monoid γ] [add_comm_monoid δ] namespace finset open finset lemma mem_range_succ {i n : ℕ} : i ∈ range n.succ ↔ i ≤ n := by {rw[mem_range,nat.lt_succ_iff]} @[to_additive finset.sum_coe_list] lemma prod_coe_list {l : list α} (h : l.nodup) (f : α → γ) : l.to_finset.prod f = (l.map f).prod := begin let s := @finset.mk α l h, have : s = l.to_finset := (list.to_finset_eq h), exact calc l.to_finset.prod f = s.prod f : by rw[← this] ... = ((l : multiset α).map f).prod : rfl ... = ((l.map f) : multiset γ).prod : by rw[multiset.coe_map] ... = (l.map f).prod : by rw[multiset.coe_prod], end @[to_additive finset.sum_equiv] lemma prod_equiv {s : finset α} {t : finset β} (e : {a // a ∈ s} ≃ {b // b ∈ t}) (f : α → γ) (g : β → γ) (hfg : ∀ (a : α) (ha : a ∈ s), f a = g (e ⟨a,ha⟩).val) : s.prod f = t.prod g := prod_bij (λ a a_in_s, (e.to_fun ⟨a,a_in_s⟩).val) (λ a a_in_s, (e.to_fun ⟨a,a_in_s⟩).property) hfg (λ a₁ a₂ a₁_in_s a₂_in_s h, congr_arg subtype.val (e.injective (subtype.eq h))) (λ b b_in_t, let aa := e.inv_fun ⟨b,b_in_t⟩ in exists.intro aa.val begin have ea : aa = ⟨aa.val,aa.property⟩ := subtype.eq rfl, use aa.property, rw[← ea], exact congr_arg subtype.val (e.right_inv ⟨b,b_in_t⟩).symm, end ) @[to_additive finset.univ_sum_equiv] lemma univ_prod_equiv [fintype α] [fintype β] (e : α ≃ β) (g : β → γ) : univ.prod (g ∘ e.to_fun) = univ.prod g := prod_bij (λ a _,e.to_fun a) (λ a _,mem_univ _) (λ a _, @rfl _ (g (e.to_fun a))) (λ a₁ a₂ _ _ h, e.injective h) (λ b _, begin use e.inv_fun b, use mem_univ _, exact (e.right_inv b).symm, end) @[to_additive finset.sum_eq_univ_sum] lemma prod_eq_univ_prod (s : finset α) (f : α → γ) : s.prod f = (@univ {a // a ∈ s} _).prod (λ a, f a.val) := begin have : @univ {a // a ∈ s} _ = s.attach := rfl, rw[← prod_attach,this],refl end @[to_additive finset.sum_univ_product] lemma prod_univ_product [fintype α] [fintype β] (f : α → β → γ) : (@univ (α × β) _).prod (λ ab, f ab.1 ab.2) = (@univ α _).prod (λ a, (@univ β _).prod (f a)) := begin have : @univ (α × β) _ = (@univ α _).product (@univ β _) := rfl, rw[this,prod_product], end @[to_additive finset.sum_over_bool] lemma prod_over_bool (f : bool → γ) : (@univ bool _).prod f = (f ff) * (f tt) := begin let l : list bool := [ff,tt], let h : l.nodup := dec_trivial, have : (@univ bool _) = l.to_finset := dec_trivial, rw[this,prod_coe_list h], simp only [list.map,list.prod_cons,list.prod_nil,mul_one] end lemma prod_range_two (f : ℕ → γ) : (range 2).prod f = f 0 * f 1 := by { rw[← one_mul (f 0)], have : range 2 = list.to_finset [0,1] := rfl, rw[this,prod_coe_list (dec_trivial : list.nodup [0,1])], refl, } lemma sum_range_two (f : ℕ → δ) : (range 2).sum f = f 0 + f 1 := by { rw[← zero_add (f 0)], have : range 2 = list.to_finset [0,1] := rfl, rw[this,sum_coe_list (dec_trivial : list.nodup [0,1])], refl, } @[to_additive finset.sum_eq_zero_of_terms_eq_zero] lemma prod_eq_one_of_terms_eq_one (s : finset α) (f : α → γ) (e : ∀ a, a ∈ s → f a = 1) : s.prod f = 1 := by { have : s.prod f = s.prod (λ a, 1) := prod_congr rfl e, rw[this,prod_const_one]} end finset
2e467b790a5b9faf161e7cb91b9769a5764c35f6
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/tactic/pretty_cases.lean
00c6595df7d10a094c024dc4e5b6e005902c2181
[ "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
2,826
lean
/- Copyright (c) 2020 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon -/ import tactic.core /-! # `pretty_cases` tactic When using `induction` and `cases`, `pretty_cases` prints a `"Try this:"` advice that shows how to structure the proof with `case { ... }` commands. In the following example, we apply induction on a permutation assumption about lists. `pretty_cases` gives us a proof skeleton that explicit selects the branches and explicit names the new local constants: ```lean example {α} (xs ys : list α) (h : xs ~ ys) : true := begin induction h, pretty_cases, -- Try this: -- case list.perm.nil : -- { admit }, -- case list.perm.cons : h_x h_l₁ h_l₂ h_a h_ih -- { admit }, -- case list.perm.swap : h_x h_y h_l -- { admit }, -- case list.perm.trans : h_l₁ h_l₂ h_l₃ h_a h_a_1 h_ih_a h_ih_a_1 -- { admit }, end ``` ## Main definitions * `pretty_cases_advice` return `pretty_cases` advice without printing it * `pretty_cases` main tactic -/ namespace tactic /-- Query the proof goal and print the skeleton of a proof by cases. -/ meta def pretty_cases_advice : tactic string := retrieve $ do gs ← get_goals, cases ← gs.mmap $ λ g, do { t : list name ← get_tag g, let vs := t.tail, let ⟨vs,ts⟩ := vs.span (λ n, name.last_string n = "_arg"), set_goals [g], ls ← local_context, let m := native.rb_map.of_list $ (ls.map expr.local_uniq_name).zip (ls.map expr.local_pp_name), let vs := vs.map $ λ v, (m.find v.get_prefix).get_or_else `_, let var_decls := string.intercalate " " $ vs.map to_string, let var_decls := if vs.empty then "" else " : " ++ var_decls, pure sformat!" case {ts.head}{var_decls}\n {{ admit }" }, let cases := string.intercalate ",\n" cases, pure sformat!"Try this:\n{cases}" namespace interactive /-- Query the proof goal and print the skeleton of a proof by cases. For example, let us consider the following proof: ```lean example {α} (xs ys : list α) (h : xs ~ ys) : true := begin induction h, pretty_cases, -- Try this: -- case list.perm.nil : -- { admit }, -- case list.perm.cons : h_x h_l₁ h_l₂ h_a h_ih -- { admit }, -- case list.perm.swap : h_x h_y h_l -- { admit }, -- case list.perm.trans : h_l₁ h_l₂ h_l₃ h_a h_a_1 h_ih_a h_ih_a_1 -- { admit }, end ``` The output helps the user layout the cases and rename the introduced variables. -/ meta def pretty_cases : tactic unit := pretty_cases_advice >>= trace add_tactic_doc { name := "pretty_cases", category := doc_category.tactic, decl_names := [``tactic.interactive.pretty_cases], tags := ["context management", "goal management"] } end interactive end tactic
46901201af874539a50a2972fcefc7a7139170f9
3984ab8555ab1e1084e22ef652544acdfc231f27
/src/Regret Minimization in Games with Incomplete Information.lean
a95423b5559884210183288975d7114bee055fdc
[]
no_license
mrakgr/CFR-in-Lean
a35c7a478795cc794cc0caff3199cf28c8ee5448
720a3260297bcc158e08833d38964450dcaad2eb
refs/heads/master
1,598,515,917,940
1,572,612,355,000
1,572,612,355,000
217,296,108
0
0
null
null
null
null
UTF-8
Lean
false
false
2,773
lean
import data.rat data.vector def nat.foldl.fin_template {α : nat → Type*} (n' : nat) : ∀ (n : fin n') (s : α 0) (f : ∀ (n : fin n'), (α n.val) → α (n.val+1)), α n.val | ⟨0, _⟩ s f := s | ⟨n+1, lt⟩ s f := let n' : fin n' := ⟨n, buffer.lt_aux_1 lt ⟩ in f n' (nat.foldl.fin_template n' s f) def nat.foldl.fin {α : nat → Type*} : ∀ (n : nat) (s : α 0) (f : ∀ (n : fin n), (α n.val) → α (n.val+1)), α n | 0 s f := s | (n+1) s f := let n' : fin (n+1) := ⟨ n, lt_add_one n ⟩ in f n' (nat.foldl.fin_template (n+1) n' s f) def Infoset := ℕ @[derive [has_lt, has_zero]] def Size := ℕ @[derive [has_neg, has_one]] def Player := ℤ inductive GameTree (infoset_sizes : Infoset → Size) | Terminal (reward : ℚ) : GameTree | Response (id : Infoset) (subnodes : fin (infoset_sizes id) → GameTree) : GameTree def policy_sum {n : ℕ} (f : fin n → ℚ) : ℚ := @nat.foldl.fin (fun i, ℚ) n 0 (fun i s, s + f i) structure Policy (infoset_sizes : Infoset → Size) := (val : ∀ (id : Infoset), fin (infoset_sizes id) → ℚ) (wf : ∀ (id : Infoset), 0 < infoset_sizes id → policy_sum (val id) = 1 ∧ ∀ (i : fin (infoset_sizes id)), 0 <= val id i ∧ val id i <= 1) variable {infoset_sizes : Infoset → Size} -- Calculates the utilities directly. def u.dive (σ : Policy infoset_sizes) : GameTree infoset_sizes → ℚ | (GameTree.Terminal _ reward) := reward | (GameTree.Response id' subnodes) := let σ := σ.val id' in @nat.foldl.fin (fun i, rat) (infoset_sizes id') 0 (fun i s, s + σ i * u.dive (subnodes i)) -- Ignores the utilities of nodes that do not match. def u.template (p : Player) (σ : Policy infoset_sizes) (id : Infoset) : Player → GameTree infoset_sizes → ℚ | p' (GameTree.Terminal _ reward) := 0 | p' (GameTree.Response id' subnodes) := if p = p' ∧ id = id' then let σ' := σ.val id' in @nat.foldl.fin (fun i, rat) (infoset_sizes id') 0 $ fun i s, s + σ' i * u.dive σ (subnodes i) else @nat.foldl.fin (fun i, rat) (infoset_sizes id') 0 $ fun i s, s + u.template (-p') (subnodes i) -- By partially applying u, it would be possible to get the same form as in the paper def u (tree : GameTree infoset_sizes) (p : Player) (σ : Policy infoset_sizes) (id : Infoset) : ℚ := u.template p σ id 1 tree inductive Fin : ℕ → Type | zero : ∀ {n : ℕ}, Fin (n+1) | suc : ∀ {n : ℕ} (i : Fin n), Fin (n+1) inductive Vec (α : Type) : ℕ → Type | nil : ∀ {n : ℕ}, Vec n | cons : ∀ {n : ℕ}, α → Vec n → Vec (n + 1) inductive GameTree' (infoset_sizes : Infoset → Size) | Terminal (reward : ℚ) : GameTree' | Response (id : Infoset) (subnodes : Vec GameTree' (infoset_sizes id)) : GameTree'
396db8b33964499778f98b75614914ef67b632dd
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/category_theory/groupoid_auto.lean
61353ba47cc2148fd46a32541eabc49bc61e1284
[]
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,050
lean
/- Copyright (c) 2018 Reid Barton All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Scott Morrison, David Wärn -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.category_theory.epi_mono import Mathlib.PostPort universes v u l u₂ namespace Mathlib namespace category_theory /-- A `groupoid` is a category such that all morphisms are isomorphisms. -/ class groupoid (obj : Type u) extends category obj where inv : {X Y : obj} → (X ⟶ Y) → (Y ⟶ X) inv_comp' : autoParam (∀ {X Y : obj} (f : X ⟶ Y), inv f ≫ f = 𝟙) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) comp_inv' : autoParam (∀ {X Y : obj} (f : X ⟶ Y), f ≫ inv f = 𝟙) (Lean.Syntax.ident Lean.SourceInfo.none (String.toSubstring "Mathlib.obviously") (Lean.Name.mkStr (Lean.Name.mkStr Lean.Name.anonymous "Mathlib") "obviously") []) @[simp] theorem groupoid.inv_comp {obj : Type u} [c : groupoid obj] {X : obj} {Y : obj} (f : X ⟶ Y) : groupoid.inv f ≫ f = 𝟙 := sorry @[simp] theorem groupoid.comp_inv {obj : Type u} [c : groupoid obj] {X : obj} {Y : obj} (f : X ⟶ Y) : f ≫ groupoid.inv f = 𝟙 := sorry /-- A `large_groupoid` is a groupoid where the objects live in `Type (u+1)` while the morphisms live in `Type u`. -/ /-- def large_groupoid (C : Type (u + 1)) := groupoid C A `small_groupoid` is a groupoid where the objects and morphisms live in the same universe. -/ def small_groupoid (C : Type u) := groupoid C protected instance is_iso.of_groupoid {C : Type u} [groupoid C] {X : C} {Y : C} (f : X ⟶ Y) : is_iso f := is_iso.mk (groupoid.inv f) /-- In a groupoid, isomorphisms are equivalent to morphisms. -/ def groupoid.iso_equiv_hom {C : Type u} [groupoid C] (X : C) (Y : C) : (X ≅ Y) ≃ (X ⟶ Y) := equiv.mk iso.hom (fun (f : X ⟶ Y) => as_iso f) sorry sorry /-- A category where every morphism `is_iso` is a groupoid. -/ def groupoid.of_is_iso {C : Type u} [category C] (all_is_iso : {X Y : C} → (f : X ⟶ Y) → is_iso f) : groupoid C := groupoid.mk fun (X Y : C) (f : X ⟶ Y) => inv f /-- A category where every morphism has a `trunc` retraction is computably a groupoid. -/ def groupoid.of_trunc_split_mono {C : Type u} [category C] (all_split_mono : {X Y : C} → (f : X ⟶ Y) → trunc (split_mono f)) : groupoid C := groupoid.of_is_iso fun (X Y : C) (f : X ⟶ Y) => trunc.rec_on_subsingleton (all_split_mono f) fun (a : split_mono f) => trunc.rec_on_subsingleton (all_split_mono (retraction f)) fun (a_1 : split_mono (retraction f)) => is_iso.of_mono_retraction protected instance induced_category.groupoid {C : Type u} (D : Type u₂) [groupoid D] (F : C → D) : groupoid (induced_category D F) := groupoid.mk fun (X Y : induced_category D F) (f : X ⟶ Y) => groupoid.inv f end Mathlib
7e32277b1088678153378a9f86b5dd7ccf409be5
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/nat/choose/basic.lean
00e1d4f2d4670f7aafa2a1858db8a2687f59cf9f
[ "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
15,140
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Bhavik Mehta, Stuart Presnell -/ import data.nat.factorial.basic /-! # Binomial coefficients This file defines binomial coefficients and proves simple lemmas (i.e. those not requiring more imports). ## Main definition and results * `nat.choose`: binomial coefficients, defined inductively * `nat.choose_eq_factorial_div_factorial`: a proof that `choose n k = n! / (k! * (n - k)!)` * `nat.choose_symm`: symmetry of binomial coefficients * `nat.choose_le_succ_of_lt_half_left`: `choose n k` is increasing for small values of `k` * `nat.choose_le_middle`: `choose n r` is maximised when `r` is `n/2` * `nat.desc_factorial_eq_factorial_mul_choose`: Relates binomial coefficients to the descending factorial. This is used to prove `nat.choose_le_pow` and variants. We provide similar statements for the ascending factorial. * `nat.multichoose`: whereas `choose` counts combinations, `multichoose` counts multicombinations. The fact that this is indeed the correct counting function for multisets is proved in `sym.card_sym_eq_multichoose` in `data/sym/card`. * `nat.multichoose_eq` : a proof that `multichoose n k = (n + k - 1).choose k`. This is central to the "stars and bars" technique in informal mathematics, where we switch between counting multisets of size `k` over an alphabet of size `n` to counting strings of `k` elements ("stars") separated by `n-1` dividers ("bars"). See `data/sym/card` for more detail. ## Tags binomial coefficient, combination, multicombination, stars and bars -/ open_locale nat namespace nat /-- `choose n k` is the number of `k`-element subsets in an `n`-element set. Also known as binomial coefficients. -/ def choose : ℕ → ℕ → ℕ | _ 0 := 1 | 0 (k + 1) := 0 | (n + 1) (k + 1) := choose n k + choose n (k + 1) @[simp] lemma choose_zero_right (n : ℕ) : choose n 0 = 1 := by cases n; refl @[simp] lemma choose_zero_succ (k : ℕ) : choose 0 (succ k) = 0 := rfl lemma choose_succ_succ (n k : ℕ) : choose (succ n) (succ k) = choose n k + choose n (succ k) := rfl lemma choose_eq_zero_of_lt : ∀ {n k}, n < k → choose n k = 0 | _ 0 hk := absurd hk dec_trivial | 0 (k + 1) hk := choose_zero_succ _ | (n + 1) (k + 1) hk := have hnk : n < k, from lt_of_succ_lt_succ hk, have hnk1 : n < k + 1, from lt_of_succ_lt hk, by rw [choose_succ_succ, choose_eq_zero_of_lt hnk, choose_eq_zero_of_lt hnk1] @[simp] lemma choose_self (n : ℕ) : choose n n = 1 := by induction n; simp [*, choose, choose_eq_zero_of_lt (lt_succ_self _)] @[simp] lemma choose_succ_self (n : ℕ) : choose n (succ n) = 0 := choose_eq_zero_of_lt (lt_succ_self _) @[simp] lemma choose_one_right (n : ℕ) : choose n 1 = n := by induction n; simp [*, choose, add_comm] /- The `n+1`-st triangle number is `n` more than the `n`-th triangle number -/ lemma triangle_succ (n : ℕ) : (n + 1) * ((n + 1) - 1) / 2 = n * (n - 1) / 2 + n := begin rw [← add_mul_div_left, mul_comm 2 n, ← mul_add, add_tsub_cancel_right, mul_comm], cases n; refl, apply zero_lt_succ end /-- `choose n 2` is the `n`-th triangle number. -/ lemma choose_two_right (n : ℕ) : choose n 2 = n * (n - 1) / 2 := begin induction n with n ih, simp, {rw triangle_succ n, simp [choose, ih], rw add_comm}, end lemma choose_pos : ∀ {n k}, k ≤ n → 0 < choose n k | 0 _ hk := by rw [nat.eq_zero_of_le_zero hk]; exact dec_trivial | (n + 1) 0 hk := by simp; exact dec_trivial | (n + 1) (k + 1) hk := by rw choose_succ_succ; exact add_pos_of_pos_of_nonneg (choose_pos (le_of_succ_le_succ hk)) (nat.zero_le _) lemma choose_eq_zero_iff {n k : ℕ} : n.choose k = 0 ↔ n < k := ⟨λ h, lt_of_not_ge (mt nat.choose_pos h.symm.not_lt), nat.choose_eq_zero_of_lt⟩ lemma succ_mul_choose_eq : ∀ n k, succ n * choose n k = choose (succ n) (succ k) * succ k | 0 0 := dec_trivial | 0 (k + 1) := by simp [choose] | (n + 1) 0 := by simp | (n + 1) (k + 1) := by rw [choose_succ_succ (succ n) (succ k), add_mul, ←succ_mul_choose_eq, mul_succ, ←succ_mul_choose_eq, add_right_comm, ←mul_add, ←choose_succ_succ, ←succ_mul] lemma choose_mul_factorial_mul_factorial : ∀ {n k}, k ≤ n → choose n k * k! * (n - k)! = n! | 0 _ hk := by simp [nat.eq_zero_of_le_zero hk] | (n + 1) 0 hk := by simp | (n + 1) (succ k) hk := begin cases lt_or_eq_of_le hk with hk₁ hk₁, { have h : choose n k * k.succ! * (n-k)! = (k + 1) * n! := by rw ← choose_mul_factorial_mul_factorial (le_of_succ_le_succ hk); simp [factorial_succ, mul_comm, mul_left_comm], have h₁ : (n - k)! = (n - k) * (n - k.succ)! := by rw [← succ_sub_succ, succ_sub (le_of_lt_succ hk₁), factorial_succ], have h₂ : choose n (succ k) * k.succ! * ((n - k) * (n - k.succ)!) = (n - k) * n! := by rw ← choose_mul_factorial_mul_factorial (le_of_lt_succ hk₁); simp [factorial_succ, mul_comm, mul_left_comm, mul_assoc], have h₃ : k * n! ≤ n * n! := nat.mul_le_mul_right _ (le_of_succ_le_succ hk), rw [choose_succ_succ, add_mul, add_mul, succ_sub_succ, h, h₁, h₂, add_mul, tsub_mul, factorial_succ, ← add_tsub_assoc_of_le h₃, add_assoc, ← add_mul, add_tsub_cancel_left, add_comm] }, { simp [hk₁, mul_comm, choose, tsub_self] } end lemma choose_mul {n k s : ℕ} (hkn : k ≤ n) (hsk : s ≤ k) : n.choose k * k.choose s = n.choose s * (n - s).choose (k - s) := begin have h : 0 < (n - k)! * (k - s)! * s! := mul_pos (mul_pos (factorial_pos _) (factorial_pos _)) (factorial_pos _), refine eq_of_mul_eq_mul_right h _, calc n.choose k * k.choose s * ((n - k)! * (k - s)! * s!) = n.choose k * (k.choose s * s! * (k - s)!) * (n - k)! : by rw [mul_assoc, mul_assoc, mul_assoc, mul_assoc _ s!, mul_assoc, mul_comm (n - k)!, mul_comm s!] ... = n! : by rw [choose_mul_factorial_mul_factorial hsk, choose_mul_factorial_mul_factorial hkn] ... = n.choose s * s! * ((n - s).choose (k - s) * (k - s)! * (n - s - (k - s))!) : by rw [choose_mul_factorial_mul_factorial (tsub_le_tsub_right hkn _), choose_mul_factorial_mul_factorial (hsk.trans hkn)] ... = n.choose s * (n - s).choose (k - s) * ((n - k)! * (k - s)! * s!) : by rw [tsub_tsub_tsub_cancel_right hsk, mul_assoc, mul_left_comm s!, mul_assoc, mul_comm (k - s)!, mul_comm s!, mul_right_comm, ←mul_assoc] end theorem choose_eq_factorial_div_factorial {n k : ℕ} (hk : k ≤ n) : choose n k = n! / (k! * (n - k)!) := begin rw [← choose_mul_factorial_mul_factorial hk, mul_assoc], exact (mul_div_left _ (mul_pos (factorial_pos _) (factorial_pos _))).symm end lemma add_choose (i j : ℕ) : (i + j).choose j = (i + j)! / (i! * j!) := by rw [choose_eq_factorial_div_factorial (nat.le_add_left j i), add_tsub_cancel_right, mul_comm] lemma add_choose_mul_factorial_mul_factorial (i j : ℕ) : (i + j).choose j * i! * j! = (i + j)! := by rw [← choose_mul_factorial_mul_factorial (nat.le_add_left _ _), add_tsub_cancel_right, mul_right_comm] theorem factorial_mul_factorial_dvd_factorial {n k : ℕ} (hk : k ≤ n) : k! * (n - k)! ∣ n! := by rw [←choose_mul_factorial_mul_factorial hk, mul_assoc]; exact dvd_mul_left _ _ lemma factorial_mul_factorial_dvd_factorial_add (i j : ℕ) : i! * j! ∣ (i + j)! := begin convert factorial_mul_factorial_dvd_factorial (le.intro rfl), rw add_tsub_cancel_left end @[simp] lemma choose_symm {n k : ℕ} (hk : k ≤ n) : choose n (n-k) = choose n k := by rw [choose_eq_factorial_div_factorial hk, choose_eq_factorial_div_factorial (nat.sub_le _ _), tsub_tsub_cancel_of_le hk, mul_comm] lemma choose_symm_of_eq_add {n a b : ℕ} (h : n = a + b) : nat.choose n a = nat.choose n b := by { convert nat.choose_symm (nat.le_add_left _ _), rw add_tsub_cancel_right} lemma choose_symm_add {a b : ℕ} : choose (a+b) a = choose (a+b) b := choose_symm_of_eq_add rfl lemma choose_symm_half (m : ℕ) : choose (2 * m + 1) (m + 1) = choose (2 * m + 1) m := by { apply choose_symm_of_eq_add, rw [add_comm m 1, add_assoc 1 m m, add_comm (2 * m) 1, two_mul m] } lemma choose_succ_right_eq (n k : ℕ) : choose n (k + 1) * (k + 1) = choose n k * (n - k) := begin have e : (n+1) * choose n k = choose n k * (k+1) + choose n (k+1) * (k+1), rw [← right_distrib, ← choose_succ_succ, succ_mul_choose_eq], rw [← tsub_eq_of_eq_add_rev e, mul_comm, ← mul_tsub, add_tsub_add_eq_tsub_right] end @[simp] lemma choose_succ_self_right : ∀ (n:ℕ), (n+1).choose n = n+1 | 0 := rfl | (n+1) := by rw [choose_succ_succ, choose_succ_self_right, choose_self] lemma choose_mul_succ_eq (n k : ℕ) : (n.choose k) * (n + 1) = ((n+1).choose k) * (n + 1 - k) := begin induction k with k ih, { simp }, obtain hk | hk := le_or_lt (k + 1) (n + 1), { rw [choose_succ_succ, add_mul, succ_sub_succ, ←choose_succ_right_eq, ←succ_sub_succ, mul_tsub, add_tsub_cancel_of_le (nat.mul_le_mul_left _ hk)] }, rw [choose_eq_zero_of_lt hk, choose_eq_zero_of_lt (n.lt_succ_self.trans hk), zero_mul, zero_mul], end lemma asc_factorial_eq_factorial_mul_choose (n k : ℕ) : n.asc_factorial k = k! * (n + k).choose k := begin rw mul_comm, apply mul_right_cancel₀ (factorial_ne_zero (n + k - k)), rw [choose_mul_factorial_mul_factorial, add_tsub_cancel_right, ←factorial_mul_asc_factorial, mul_comm], exact nat.le_add_left k n, end lemma factorial_dvd_asc_factorial (n k : ℕ) : k! ∣ n.asc_factorial k := ⟨(n+k).choose k, asc_factorial_eq_factorial_mul_choose _ _⟩ lemma choose_eq_asc_factorial_div_factorial (n k : ℕ) : (n + k).choose k = n.asc_factorial k / k! := begin apply mul_left_cancel₀ (factorial_ne_zero k), rw ←asc_factorial_eq_factorial_mul_choose, exact (nat.mul_div_cancel' $ factorial_dvd_asc_factorial _ _).symm, end lemma desc_factorial_eq_factorial_mul_choose (n k : ℕ) : n.desc_factorial k = k! * n.choose k := begin obtain h | h := nat.lt_or_ge n k, { rw [desc_factorial_eq_zero_iff_lt.2 h, choose_eq_zero_of_lt h, mul_zero] }, rw mul_comm, apply mul_right_cancel₀ (factorial_ne_zero (n - k)), rw [choose_mul_factorial_mul_factorial h, ←factorial_mul_desc_factorial h, mul_comm], end lemma factorial_dvd_desc_factorial (n k : ℕ) : k! ∣ n.desc_factorial k := ⟨n.choose k, desc_factorial_eq_factorial_mul_choose _ _⟩ lemma choose_eq_desc_factorial_div_factorial (n k : ℕ) : n.choose k = n.desc_factorial k / k! := begin apply mul_left_cancel₀ (factorial_ne_zero k), rw ←desc_factorial_eq_factorial_mul_choose, exact (nat.mul_div_cancel' $ factorial_dvd_desc_factorial _ _).symm, end /-! ### Inequalities -/ /-- Show that `nat.choose` is increasing for small values of the right argument. -/ lemma choose_le_succ_of_lt_half_left {r n : ℕ} (h : r < n/2) : choose n r ≤ choose n (r+1) := begin refine le_of_mul_le_mul_right _ (lt_tsub_iff_left.mpr (lt_of_lt_of_le h (n.div_le_self 2))), rw ← choose_succ_right_eq, apply nat.mul_le_mul_left, rw [← nat.lt_iff_add_one_le, lt_tsub_iff_left, ← mul_two], exact lt_of_lt_of_le (mul_lt_mul_of_pos_right h zero_lt_two) (n.div_mul_le_self 2), end /-- Show that for small values of the right argument, the middle value is largest. -/ private lemma choose_le_middle_of_le_half_left {n r : ℕ} (hr : r ≤ n/2) : choose n r ≤ choose n (n/2) := decreasing_induction (λ _ k a, (eq_or_lt_of_le a).elim (λ t, t.symm ▸ le_rfl) (λ h, (choose_le_succ_of_lt_half_left h).trans (k h))) hr (λ _, le_rfl) hr /-- `choose n r` is maximised when `r` is `n/2`. -/ lemma choose_le_middle (r n : ℕ) : choose n r ≤ choose n (n/2) := begin cases le_or_gt r n with b b, { cases le_or_lt r (n/2) with a h, { apply choose_le_middle_of_le_half_left a }, { rw ← choose_symm b, apply choose_le_middle_of_le_half_left, rw [div_lt_iff_lt_mul' zero_lt_two] at h, rw [le_div_iff_mul_le' zero_lt_two, tsub_mul, tsub_le_iff_tsub_le, mul_two, add_tsub_cancel_right], exact le_of_lt h } }, { rw choose_eq_zero_of_lt b, apply zero_le } end /-! #### Inequalities about increasing the first argument -/ lemma choose_le_succ (a c : ℕ) : choose a c ≤ choose a.succ c := by cases c; simp [nat.choose_succ_succ] lemma choose_le_add (a b c : ℕ) : choose a c ≤ choose (a + b) c := begin induction b with b_n b_ih, { simp, }, exact le_trans b_ih (choose_le_succ (a + b_n) c), end lemma choose_le_choose {a b : ℕ} (c : ℕ) (h : a ≤ b) : choose a c ≤ choose b c := (add_tsub_cancel_of_le h) ▸ choose_le_add a (b - a) c lemma choose_mono (b : ℕ) : monotone (λ a, choose a b) := λ _ _, choose_le_choose b /-! #### Multichoose Whereas `choose n k` is the number of subsets of cardinality `k` from a type of cardinality `n`, `multichoose n k` is the number of multisets of cardinality `k` from a type of cardinality `n`. Alternatively, whereas `choose n k` counts the number of combinations, i.e. ways to select `k` items (up to permutation) from `n` items without replacement, `multichoose n k` counts the number of multicombinations, i.e. ways to select `k` items (up to permutation) from `n` items with replacement. Note that `multichoose` is *not* the multinomial coefficient, although it can be computed in terms of multinomial coefficients. For details see https://mathworld.wolfram.com/Multichoose.html TODO: Prove that `choose (-n) k = (-1)^k * multichoose n k`, where `choose` is the generalized binomial coefficient. <https://github.com/leanprover-community/mathlib/pull/15072#issuecomment-1171415738> -/ /-- `multichoose n k` is the number of multisets of cardinality `k` from a type of cardinality `n`. -/ def multichoose : ℕ → ℕ → ℕ | _ 0 := 1 | 0 (k + 1) := 0 | (n + 1) (k + 1) := multichoose n (k + 1) + multichoose (n + 1) k @[simp] lemma multichoose_zero_right (n : ℕ) : multichoose n 0 = 1 := by { cases n; simp [multichoose] } @[simp] lemma multichoose_zero_succ (k : ℕ) : multichoose 0 (k + 1) = 0 := by simp [multichoose] lemma multichoose_succ_succ (n k : ℕ) : multichoose (n + 1) (k + 1) = multichoose n (k + 1) + multichoose (n + 1) k := by simp [multichoose] @[simp] lemma multichoose_one (k : ℕ) : multichoose 1 k = 1 := begin induction k with k IH, { simp }, simp [multichoose_succ_succ 0 k, IH], end @[simp] lemma multichoose_two (k : ℕ) : multichoose 2 k = k + 1 := begin induction k with k IH, { simp }, simp [multichoose_succ_succ 1 k, IH], rw add_comm, end @[simp] lemma multichoose_one_right (n : ℕ) : multichoose n 1 = n := begin induction n with n IH, { simp }, simp [multichoose_succ_succ n 0, IH], end lemma multichoose_eq : ∀ (n k : ℕ), multichoose n k = (n + k - 1).choose k | _ 0 := by simp | 0 (k+1) := by simp | (n+1) (k+1) := by { rw [multichoose_succ_succ, add_comm, nat.succ_add_sub_one, ←add_assoc, nat.choose_succ_succ], simp [multichoose_eq] } end nat
dc0c5220cf0db9b2f07e9eb0e45a9838524948b6
957a80ea22c5abb4f4670b250d55534d9db99108
/tests/lean/run/specialize.lean
8acc7effefe931f5b24bafa69baec6454112f665
[ "Apache-2.0" ]
permissive
GaloisInc/lean
aa1e64d604051e602fcf4610061314b9a37ab8cd
f1ec117a24459b59c6ff9e56a1d09d9e9e60a6c0
refs/heads/master
1,592,202,909,807
1,504,624,387,000
1,504,624,387,000
75,319,626
2
1
Apache-2.0
1,539,290,164,000
1,480,616,104,000
C++
UTF-8
Lean
false
false
619
lean
open tactic lemma test1 (x y z : Prop) (f : x → y → z) (xp : x) (yp : y) : z := begin specialize (f xp yp), assumption end lemma test2 (B C : Prop) (f : forall (A : Prop), A → C) (x : B) : C := begin specialize f _ x, exact f, end lemma test3 (B C : Prop) (f : forall {A : Prop}, A → C) (x : B) : C := begin specialize (f x), exact f, end lemma test4 (B C : Prop) (f : forall {A : Prop}, A → C) (x : B) : C := begin specialize (@f _ x), exact f, end lemma test5 (X : Type) [has_add X] (f : forall {A : Type} [has_add A], A → A → A) (x : X) : X := begin specialize (f x x), assumption end
f6d66e80516f2621677f8ce0d6d788a5364db99c
ac89c256db07448984849346288e0eeffe8b20d0
/stage0/src/Init/Data/List/Basic.lean
41ed319700e951cc52c214397d52a648f0911d5f
[ "Apache-2.0" ]
permissive
chepinzhang/lean4
002cc667f35417a418f0ebc9cb4a44559bb0ccac
24fe2875c68549b5481f07c57eab4ad4a0ae5305
refs/heads/master
1,688,942,838,326
1,628,801,942,000
1,628,801,995,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
11,797
lean
/- Copyright (c) 2016 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ prelude import Init.SimpLemmas import Init.Data.Nat.Basic open Decidable List universe u v w variable {α : Type u} {β : Type v} {γ : Type w} namespace List @[simp] theorem length_nil : length ([] : List α) = 0 := rfl def reverseAux : List α → List α → List α | [], r => r | a::l, r => reverseAux l (a::r) def reverse (as : List α) :List α := reverseAux as [] protected def append (as bs : List α) : List α := reverseAux as.reverse bs instance : Append (List α) := ⟨List.append⟩ theorem reverseAux_reverseAux_nil (as bs : List α) : reverseAux (reverseAux as bs) [] = reverseAux bs as := by induction as generalizing bs with | nil => rfl | cons a as ih => simp [reverseAux, ih] @[simp] theorem nil_append (as : List α) : [] ++ as = as := rfl @[simp] theorem append_nil (as : List α) : as ++ [] = as := by show reverseAux (reverseAux as []) [] = as simp [reverseAux_reverseAux_nil, reverseAux] theorem reverseAux_reverseAux (as bs cs : List α) : reverseAux (reverseAux as bs) cs = reverseAux bs (reverseAux (reverseAux as []) cs) := by induction as generalizing bs cs with | nil => rfl | cons a as ih => simp [reverseAux, ih (a::bs), ih [a]] @[simp] theorem cons_append (a : α) (as bs : List α) : (a::as) ++ bs = a::(as ++ bs) := reverseAux_reverseAux as [a] bs theorem append_assoc (as bs cs : List α) : (as ++ bs) ++ cs = as ++ (bs ++ cs) := by induction as with | nil => rfl | cons a as ih => simp [ih] instance : EmptyCollection (List α) := ⟨List.nil⟩ protected def erase {α} [BEq α] : List α → α → List α | [], b => [] | a::as, b => match a == b with | true => as | false => a :: List.erase as b def eraseIdx : List α → Nat → List α | [], _ => [] | a::as, 0 => as | a::as, n+1 => a :: eraseIdx as n def isEmpty : List α → Bool | [] => true | _ :: _ => false @[specialize] def map (f : α → β) : List α → List β | [] => [] | a::as => f a :: map f as @[specialize] def map₂ (f : α → β → γ) : List α → List β → List γ | [], _ => [] | _, [] => [] | a::as, b::bs => f a b :: map₂ f as bs def join : List (List α) → List α | [] => [] | a :: as => a ++ join as @[specialize] def filterMap (f : α → Option β) : List α → List β | [] => [] | a::as => match f a with | none => filterMap f as | some b => b :: filterMap f as @[specialize] def filterAux (p : α → Bool) : List α → List α → List α | [], rs => rs.reverse | a::as, rs => match p a with | true => filterAux p as (a::rs) | false => filterAux p as rs @[inline] def filter (p : α → Bool) (as : List α) : List α := filterAux p as [] @[specialize] def partitionAux (p : α → Bool) : List α → List α × List α → List α × List α | [], (bs, cs) => (bs.reverse, cs.reverse) | a::as, (bs, cs) => match p a with | true => partitionAux p as (a::bs, cs) | false => partitionAux p as (bs, a::cs) @[inline] def partition (p : α → Bool) (as : List α) : List α × List α := partitionAux p as ([], []) def dropWhile (p : α → Bool) : List α → List α | [] => [] | a::l => match p a with | true => dropWhile p l | false => a::l def find? (p : α → Bool) : List α → Option α | [] => none | a::as => match p a with | true => some a | false => find? p as def findSome? (f : α → Option β) : List α → Option β | [] => none | a::as => match f a with | some b => some b | none => findSome? f as def replace [BEq α] : List α → α → α → List α | [], _, _ => [] | a::as, b, c => match a == b with | true => c::as | false => a :: (replace as b c) def elem [BEq α] (a : α) : List α → Bool | [] => false | b::bs => match a == b with | true => true | false => elem a bs def notElem [BEq α] (a : α) (as : List α) : Bool := !(as.elem a) abbrev contains [BEq α] (as : List α) (a : α) : Bool := elem a as def eraseDupsAux {α} [BEq α] : List α → List α → List α | [], bs => bs.reverse | a::as, bs => match bs.elem a with | true => eraseDupsAux as bs | false => eraseDupsAux as (a::bs) def eraseDups {α} [BEq α] (as : List α) : List α := eraseDupsAux as [] def eraseRepsAux {α} [BEq α] : α → List α → List α → List α | a, [], rs => (a::rs).reverse | a, a'::as, rs => match a == a' with | true => eraseRepsAux a as rs | false => eraseRepsAux a' as (a::rs) /-- Erase repeated adjacent elements. -/ def eraseReps {α} [BEq α] : List α → List α | [] => [] | a::as => eraseRepsAux a as [] @[specialize] def spanAux (p : α → Bool) : List α → List α → List α × List α | [], rs => (rs.reverse, []) | a::as, rs => match p a with | true => spanAux p as (a::rs) | false => (rs.reverse, a::as) @[inline] def span (p : α → Bool) (as : List α) : List α × List α := spanAux p as [] @[specialize] def groupByAux (eq : α → α → Bool) : List α → List (List α) → List (List α) | a::as, (ag::g)::gs => match eq a ag with | true => groupByAux eq as ((a::ag::g)::gs) | false => groupByAux eq as ([a]::(ag::g).reverse::gs) | _, gs => gs.reverse @[specialize] def groupBy (p : α → α → Bool) : List α → List (List α) | [] => [] | a::as => groupByAux p as [[a]] def lookup [BEq α] : α → List (α × β) → Option β | _, [] => none | a, (k,b)::es => match a == k with | true => some b | false => lookup a es def removeAll [BEq α] (xs ys : List α) : List α := xs.filter (fun x => ys.notElem x) def drop : Nat → List α → List α | 0, a => a | n+1, [] => [] | n+1, a::as => drop n as def take : Nat → List α → List α | 0, a => [] | n+1, [] => [] | n+1, a::as => a :: take n as def takeWhile (p : α → Bool) : List α → List α | [] => [] | hd :: tl => match p hd with | true => hd :: takeWhile p tl | false => [] @[specialize] def foldr (f : α → β → β) (init : β) : List α → β | [] => init | a :: l => f a (foldr f init l) @[inline] def any (l : List α) (p : α → Bool) : Bool := foldr (fun a r => p a || r) false l @[inline] def all (l : List α) (p : α → Bool) : Bool := foldr (fun a r => p a && r) true l def or (bs : List Bool) : Bool := bs.any id def and (bs : List Bool) : Bool := bs.all id def zipWith (f : α → β → γ) : List α → List β → List γ | x::xs, y::ys => f x y :: zipWith f xs ys | _, _ => [] def zip : List α → List β → List (Prod α β) := zipWith Prod.mk def unzip : List (α × β) → List α × List β | [] => ([], []) | (a, b) :: t => match unzip t with | (al, bl) => (a::al, b::bl) def rangeAux : Nat → List Nat → List Nat | 0, ns => ns | n+1, ns => rangeAux n (n::ns) def range (n : Nat) : List Nat := rangeAux n [] def iota : Nat → List Nat | 0 => [] | m@(n+1) => m :: iota n def enumFrom : Nat → List α → List (Nat × α) | n, [] => nil | n, x :: xs => (n, x) :: enumFrom (n + 1) xs def enum : List α → List (Nat × α) := enumFrom 0 def init : List α → List α | [] => [] | [a] => [] | a::l => a::init l def intersperse (sep : α) : List α → List α | [] => [] | [x] => [x] | x::xs => x :: sep :: intersperse sep xs def intercalate (sep : List α) (xs : List (List α)) : List α := join (intersperse sep xs) @[inline] protected def bind {α : Type u} {β : Type v} (a : List α) (b : α → List β) : List β := join (map b a) @[inline] protected def pure {α : Type u} (a : α) : List α := [a] inductive lt [LT α] : List α → List α → Prop where | nil (b : α) (bs : List α) : lt [] (b::bs) | head {a : α} (as : List α) {b : α} (bs : List α) : a < b → lt (a::as) (b::bs) | tail {a : α} {as : List α} {b : α} {bs : List α} : ¬ a < b → ¬ b < a → lt as bs → lt (a::as) (b::bs) instance [LT α] : LT (List α) := ⟨List.lt⟩ instance hasDecidableLt [LT α] [h : DecidableRel (α:=α) (·<·)] : (l₁ l₂ : List α) → Decidable (l₁ < l₂) | [], [] => isFalse (fun h => nomatch h) | [], b::bs => isTrue (List.lt.nil _ _) | a::as, [] => isFalse (fun h => nomatch h) | a::as, b::bs => match h a b with | isTrue h₁ => isTrue (List.lt.head _ _ h₁) | isFalse h₁ => match h b a with | isTrue h₂ => isFalse (fun h => match h with | List.lt.head _ _ h₁' => absurd h₁' h₁ | List.lt.tail _ h₂' _ => absurd h₂ h₂') | isFalse h₂ => match hasDecidableLt as bs with | isTrue h₃ => isTrue (List.lt.tail h₁ h₂ h₃) | isFalse h₃ => isFalse (fun h => match h with | List.lt.head _ _ h₁' => absurd h₁' h₁ | List.lt.tail _ _ h₃' => absurd h₃' h₃) @[reducible] protected def le [LT α] (a b : List α) : Prop := ¬ b < a instance [LT α] : LE (List α) := ⟨List.le⟩ instance [LT α] [h : DecidableRel ((· < ·) : α → α → Prop)] : (l₁ l₂ : List α) → Decidable (l₁ ≤ l₂) := fun a b => inferInstanceAs (Decidable (Not _)) /-- `isPrefixOf l₁ l₂` returns `true` Iff `l₁` is a prefix of `l₂`. -/ def isPrefixOf [BEq α] : List α → List α → Bool | [], _ => true | _, [] => false | a::as, b::bs => a == b && isPrefixOf as bs /-- `isSuffixOf l₁ l₂` returns `true` Iff `l₁` is a suffix of `l₂`. -/ def isSuffixOf [BEq α] (l₁ l₂ : List α) : Bool := isPrefixOf l₁.reverse l₂.reverse @[specialize] def isEqv : List α → List α → (α → α → Bool) → Bool | [], [], _ => true | a::as, b::bs, eqv => eqv a b && isEqv as bs eqv | _, _, eqv => false protected def beq [BEq α] : List α → List α → Bool | [], [] => true | a::as, b::bs => a == b && List.beq as bs | _, _ => false instance [BEq α] : BEq (List α) := ⟨List.beq⟩ def replicate {α : Type u} (n : Nat) (a : α) : List α := let rec loop : Nat → List α → List α | 0, as => as | n+1, as => loop n (a::as) loop n [] def dropLast {α} : List α → List α | [] => [] | [a] => [] | a::as => a :: dropLast as @[simp] theorem length_replicate (n : Nat) (a : α) : (replicate n a).length = n := let rec aux (n : Nat) (as : List α) : (replicate.loop a n as).length = n + as.length := by induction n generalizing as with | zero => simp [replicate.loop] | succ n ih => simp [replicate.loop, ih, Nat.succ_add, Nat.add_succ] aux n [] @[simp] theorem length_concat (as : List α) (a : α) : (concat as a).length = as.length + 1 := by induction as with | nil => rfl | cons x xs ih => simp [concat, ih] @[simp] theorem length_set (as : List α) (i : Nat) (a : α) : (as.set i a).length = as.length := by induction as generalizing i with | nil => rfl | cons x xs ih => cases i with | zero => rfl | succ i => simp [set, ih] @[simp] theorem length_dropLast (as : List α) : as.dropLast.length = as.length - 1 := by match as with | [] => rfl | [a] => rfl | a::b::as => have ih := length_dropLast (b::as) simp[dropLast, ih] rfl def maximum? [LT α] [DecidableRel (@LT.lt α _)] : List α → Option α | [] => none | a::as => some <| as.foldl max a def minimum? [LE α] [DecidableRel (@LE.le α _)] : List α → Option α | [] => none | a::as => some <| as.foldl min a end List
6447cb625ff7709492617f824924e421152968b2
92bfaf170880e47d55bf51d5a782fffd76db2f5f
/melting_point/core.lean
b6329aa268d5e6aca113d27b76531fc7fcb6e1e6
[]
no_license
forked-from-1kasper/melting_point
d33403e1985d876a2c7c06859962cc0c37570189
e5ea4a0917de086b7e5b122e8d5aa90d2761d147
refs/heads/master
1,624,785,375,577
1,618,305,367,000
1,618,305,367,000
222,729,018
2
0
null
null
null
null
UTF-8
Lean
false
false
162
lean
notation [parsing_only] `𝟎` := empty notation [parsing_only] `𝟏` := unit notation [parsing_only] `★` := unit.star notation [parsing_only] `𝟐` := bool
5b28b82c19208d713bb6524251a387ca7a641ce0
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/algebra/add_torsor.lean
f323c963269104981d7c4292b8b3bdb6ad160e3e
[ "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
14,700
lean
/- Copyright (c) 2020 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers, Yury Kudryashov -/ import algebra.group.prod import algebra.group.type_tags import algebra.group.pi import algebra.pointwise import data.equiv.basic import data.set.finite /-! # Torsors of additive group actions This file defines torsors of additive group actions. ## Notations The group elements are referred to as acting on points. This file defines the notation `+ᵥ` for adding a group element to a point and `-ᵥ` for subtracting two points to produce a group element. ## Implementation notes Affine spaces are the motivating example of torsors of additive group actions. It may be appropriate to refactor in terms of the general definition of group actions, via `to_additive`, when there is a use for multiplicative torsors (currently mathlib only develops the theory of group actions for multiplicative group actions). ## Notations * `v +ᵥ p` is a notation for `has_vadd.vadd`, the left action of an additive monoid; * `p₁ -ᵥ p₂` is a notation for `has_vsub.vsub`, difference between two points in an additive torsor as an element of the corresponding additive group; ## References * https://en.wikipedia.org/wiki/Principal_homogeneous_space * https://en.wikipedia.org/wiki/Affine_space -/ /-- An `add_torsor G P` gives a structure to the nonempty type `P`, acted on by an `add_group G` with a transitive and free action given by the `+ᵥ` operation and a corresponding subtraction given by the `-ᵥ` operation. In the case of a vector space, it is an affine space. -/ class add_torsor (G : out_param Type*) (P : Type*) [out_param $ add_group G] extends add_action G P, has_vsub G P := [nonempty : nonempty P] (vsub_vadd' : ∀ (p1 p2 : P), (p1 -ᵥ p2 : G) +ᵥ p2 = p1) (vadd_vsub' : ∀ (g : G) (p : P), g +ᵥ p -ᵥ p = g) attribute [instance, priority 100, nolint dangerous_instance] add_torsor.nonempty attribute [nolint dangerous_instance] add_torsor.to_has_vsub /-- An `add_group G` is a torsor for itself. -/ @[nolint instance_priority] instance add_group_is_add_torsor (G : Type*) [add_group G] : add_torsor G G := { vsub := has_sub.sub, vsub_vadd' := sub_add_cancel, vadd_vsub' := add_sub_cancel } /-- Simplify subtraction for a torsor for an `add_group G` over itself. -/ @[simp] lemma vsub_eq_sub {G : Type*} [add_group G] (g1 g2 : G) : g1 -ᵥ g2 = g1 - g2 := rfl section general variables {G : Type*} {P : Type*} [add_group G] [T : add_torsor G P] include T /-- Adding the result of subtracting from another point produces that point. -/ @[simp] lemma vsub_vadd (p1 p2 : P) : p1 -ᵥ p2 +ᵥ p2 = p1 := add_torsor.vsub_vadd' p1 p2 /-- Adding a group element then subtracting the original point produces that group element. -/ @[simp] lemma vadd_vsub (g : G) (p : P) : g +ᵥ p -ᵥ p = g := add_torsor.vadd_vsub' g p /-- If the same point added to two group elements produces equal results, those group elements are equal. -/ lemma vadd_right_cancel {g1 g2 : G} (p : P) (h : g1 +ᵥ p = g2 +ᵥ p) : g1 = g2 := by rw [←vadd_vsub g1, h, vadd_vsub] @[simp] lemma vadd_right_cancel_iff {g1 g2 : G} (p : P) : g1 +ᵥ p = g2 +ᵥ p ↔ g1 = g2 := ⟨vadd_right_cancel p, λ h, h ▸ rfl⟩ /-- Adding a group element to the point `p` is an injective function. -/ lemma vadd_right_injective (p : P) : function.injective ((+ᵥ p) : G → P) := λ g1 g2, vadd_right_cancel p /-- Adding a group element to a point, then subtracting another point, produces the same result as subtracting the points then adding the group element. -/ lemma vadd_vsub_assoc (g : G) (p1 p2 : P) : g +ᵥ p1 -ᵥ p2 = g + (p1 -ᵥ p2) := begin apply vadd_right_cancel p2, rw [vsub_vadd, add_vadd, vsub_vadd] end /-- Subtracting a point from itself produces 0. -/ @[simp] lemma vsub_self (p : P) : p -ᵥ p = (0 : G) := by rw [←zero_add (p -ᵥ p), ←vadd_vsub_assoc, vadd_vsub] /-- If subtracting two points produces 0, they are equal. -/ lemma eq_of_vsub_eq_zero {p1 p2 : P} (h : p1 -ᵥ p2 = (0 : G)) : p1 = p2 := by rw [←vsub_vadd p1 p2, h, zero_vadd] /-- Subtracting two points produces 0 if and only if they are equal. -/ @[simp] lemma vsub_eq_zero_iff_eq {p1 p2 : P} : p1 -ᵥ p2 = (0 : G) ↔ p1 = p2 := iff.intro eq_of_vsub_eq_zero (λ h, h ▸ vsub_self _) /-- Cancellation adding the results of two subtractions. -/ @[simp] lemma vsub_add_vsub_cancel (p1 p2 p3 : P) : p1 -ᵥ p2 + (p2 -ᵥ p3) = (p1 -ᵥ p3) := begin apply vadd_right_cancel p3, rw [add_vadd, vsub_vadd, vsub_vadd, vsub_vadd] end /-- Subtracting two points in the reverse order produces the negation of subtracting them. -/ @[simp] lemma neg_vsub_eq_vsub_rev (p1 p2 : P) : -(p1 -ᵥ p2) = (p2 -ᵥ p1) := begin refine neg_eq_of_add_eq_zero (vadd_right_cancel p1 _), rw [vsub_add_vsub_cancel, vsub_self], end /-- Subtracting the result of adding a group element produces the same result as subtracting the points and subtracting that group element. -/ lemma vsub_vadd_eq_vsub_sub (p1 p2 : P) (g : G) : p1 -ᵥ (g +ᵥ p2) = (p1 -ᵥ p2) - g := by rw [←add_right_inj (p2 -ᵥ p1 : G), vsub_add_vsub_cancel, ←neg_vsub_eq_vsub_rev, vadd_vsub, ←add_sub_assoc, ←neg_vsub_eq_vsub_rev, neg_add_self, zero_sub] /-- Cancellation subtracting the results of two subtractions. -/ @[simp] lemma vsub_sub_vsub_cancel_right (p1 p2 p3 : P) : (p1 -ᵥ p3) - (p2 -ᵥ p3) = (p1 -ᵥ p2) := by rw [←vsub_vadd_eq_vsub_sub, vsub_vadd] /-- Convert between an equality with adding a group element to a point and an equality of a subtraction of two points with a group element. -/ lemma eq_vadd_iff_vsub_eq (p1 : P) (g : G) (p2 : P) : p1 = g +ᵥ p2 ↔ p1 -ᵥ p2 = g := ⟨λ h, h.symm ▸ vadd_vsub _ _, λ h, h ▸ (vsub_vadd _ _).symm⟩ lemma vadd_eq_vadd_iff_neg_add_eq_vsub {v₁ v₂ : G} {p₁ p₂ : P} : v₁ +ᵥ p₁ = v₂ +ᵥ p₂ ↔ - v₁ + v₂ = p₁ -ᵥ p₂ := by rw [eq_vadd_iff_vsub_eq, vadd_vsub_assoc, ← add_right_inj (-v₁), neg_add_cancel_left, eq_comm] namespace set open_locale pointwise @[simp] lemma singleton_vsub_self (p : P) : ({p} : set P) -ᵥ {p} = {(0:G)} := by rw [set.singleton_vsub_singleton, vsub_self] instance add_action : add_action (set G) (set P) := { zero_vadd := λ s, by simp [has_vadd.vadd, ←singleton_zero, image2_singleton_left], add_vadd := λ s t p, by { apply image2_assoc, intros, apply add_vadd }, ..(show has_vadd (set G) (set P), by apply_instance) } end set @[simp] lemma vadd_vsub_vadd_cancel_right (v₁ v₂ : G) (p : P) : (v₁ +ᵥ p) -ᵥ (v₂ +ᵥ p) = v₁ - v₂ := by rw [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, vsub_self, add_zero] /-- If the same point subtracted from two points produces equal results, those points are equal. -/ lemma vsub_left_cancel {p1 p2 p : P} (h : p1 -ᵥ p = p2 -ᵥ p) : p1 = p2 := by rwa [←sub_eq_zero, vsub_sub_vsub_cancel_right, vsub_eq_zero_iff_eq] at h /-- The same point subtracted from two points produces equal results if and only if those points are equal. -/ @[simp] lemma vsub_left_cancel_iff {p1 p2 p : P} : (p1 -ᵥ p) = p2 -ᵥ p ↔ p1 = p2 := ⟨vsub_left_cancel, λ h, h ▸ rfl⟩ /-- Subtracting the point `p` is an injective function. -/ lemma vsub_left_injective (p : P) : function.injective ((-ᵥ p) : P → G) := λ p2 p3, vsub_left_cancel /-- If subtracting two points from the same point produces equal results, those points are equal. -/ lemma vsub_right_cancel {p1 p2 p : P} (h : p -ᵥ p1 = p -ᵥ p2) : p1 = p2 := begin refine vadd_left_cancel (p -ᵥ p2) _, rw [vsub_vadd, ← h, vsub_vadd] end /-- Subtracting two points from the same point produces equal results if and only if those points are equal. -/ @[simp] lemma vsub_right_cancel_iff {p1 p2 p : P} : p -ᵥ p1 = p -ᵥ p2 ↔ p1 = p2 := ⟨vsub_right_cancel, λ h, h ▸ rfl⟩ /-- Subtracting a point from the point `p` is an injective function. -/ lemma vsub_right_injective (p : P) : function.injective ((-ᵥ) p : P → G) := λ p2 p3, vsub_right_cancel end general section comm variables {G : Type*} {P : Type*} [add_comm_group G] [add_torsor G P] include G /-- Cancellation subtracting the results of two subtractions. -/ @[simp] lemma vsub_sub_vsub_cancel_left (p1 p2 p3 : P) : (p3 -ᵥ p2) - (p3 -ᵥ p1) = (p1 -ᵥ p2) := by rw [sub_eq_add_neg, neg_vsub_eq_vsub_rev, add_comm, vsub_add_vsub_cancel] @[simp] lemma vadd_vsub_vadd_cancel_left (v : G) (p1 p2 : P) : (v +ᵥ p1) -ᵥ (v +ᵥ p2) = p1 -ᵥ p2 := by rw [vsub_vadd_eq_vsub_sub, vadd_vsub_assoc, add_sub_cancel'] lemma vsub_vadd_comm (p1 p2 p3 : P) : (p1 -ᵥ p2 : G) +ᵥ p3 = p3 -ᵥ p2 +ᵥ p1 := begin rw [←@vsub_eq_zero_iff_eq G, vadd_vsub_assoc, vsub_vadd_eq_vsub_sub], simp end lemma vadd_eq_vadd_iff_sub_eq_vsub {v₁ v₂ : G} {p₁ p₂ : P} : v₁ +ᵥ p₁ = v₂ +ᵥ p₂ ↔ v₂ - v₁ = p₁ -ᵥ p₂ := by rw [vadd_eq_vadd_iff_neg_add_eq_vsub, neg_add_eq_sub] lemma vsub_sub_vsub_comm (p₁ p₂ p₃ p₄ : P) : (p₁ -ᵥ p₂) - (p₃ -ᵥ p₄) = (p₁ -ᵥ p₃) - (p₂ -ᵥ p₄) := by rw [← vsub_vadd_eq_vsub_sub, vsub_vadd_comm, vsub_vadd_eq_vsub_sub] end comm namespace prod variables {G : Type*} {P : Type*} {G' : Type*} {P' : Type*} [add_group G] [add_group G'] [add_torsor G P] [add_torsor G' P'] instance : add_torsor (G × G') (P × P') := { vadd := λ v p, (v.1 +ᵥ p.1, v.2 +ᵥ p.2), zero_vadd := λ p, by simp, add_vadd := by simp [add_vadd], vsub := λ p₁ p₂, (p₁.1 -ᵥ p₂.1, p₁.2 -ᵥ p₂.2), nonempty := prod.nonempty, vsub_vadd' := λ p₁ p₂, show (p₁.1 -ᵥ p₂.1 +ᵥ p₂.1, _) = p₁, by simp, vadd_vsub' := λ v p, show (v.1 +ᵥ p.1 -ᵥ p.1, v.2 +ᵥ p.2 -ᵥ p.2) =v, by simp } @[simp] lemma fst_vadd (v : G × G') (p : P × P') : (v +ᵥ p).1 = v.1 +ᵥ p.1 := rfl @[simp] lemma snd_vadd (v : G × G') (p : P × P') : (v +ᵥ p).2 = v.2 +ᵥ p.2 := rfl @[simp] lemma mk_vadd_mk (v : G) (v' : G') (p : P) (p' : P') : (v, v') +ᵥ (p, p') = (v +ᵥ p, v' +ᵥ p') := rfl @[simp] lemma fst_vsub (p₁ p₂ : P × P') : (p₁ -ᵥ p₂ : G × G').1 = p₁.1 -ᵥ p₂.1 := rfl @[simp] lemma snd_vsub (p₁ p₂ : P × P') : (p₁ -ᵥ p₂ : G × G').2 = p₁.2 -ᵥ p₂.2 := rfl @[simp] lemma mk_vsub_mk (p₁ p₂ : P) (p₁' p₂' : P') : ((p₁, p₁') -ᵥ (p₂, p₂') : G × G') = (p₁ -ᵥ p₂, p₁' -ᵥ p₂') := rfl end prod namespace pi universes u v w variables {I : Type u} {fg : I → Type v} [∀ i, add_group (fg i)] {fp : I → Type w} open add_action add_torsor /-- A product of `add_torsor`s is an `add_torsor`. -/ instance [T : ∀ i, add_torsor (fg i) (fp i)] : add_torsor (Π i, fg i) (Π i, fp i) := { vadd := λ g p, λ i, g i +ᵥ p i, zero_vadd := λ p, funext $ λ i, zero_vadd (fg i) (p i), add_vadd := λ g₁ g₂ p, funext $ λ i, add_vadd (g₁ i) (g₂ i) (p i), vsub := λ p₁ p₂, λ i, p₁ i -ᵥ p₂ i, nonempty := ⟨λ i, classical.choice (T i).nonempty⟩, vsub_vadd' := λ p₁ p₂, funext $ λ i, vsub_vadd (p₁ i) (p₂ i), vadd_vsub' := λ g p, funext $ λ i, vadd_vsub (g i) (p i) } end pi namespace equiv variables {G : Type*} {P : Type*} [add_group G] [add_torsor G P] include G /-- `v ↦ v +ᵥ p` as an equivalence. -/ def vadd_const (p : P) : G ≃ P := { to_fun := λ v, v +ᵥ p, inv_fun := λ p', p' -ᵥ p, left_inv := λ v, vadd_vsub _ _, right_inv := λ p', vsub_vadd _ _ } @[simp] lemma coe_vadd_const (p : P) : ⇑(vadd_const p) = λ v, v+ᵥ p := rfl @[simp] lemma coe_vadd_const_symm (p : P) : ⇑(vadd_const p).symm = λ p', p' -ᵥ p := rfl /-- `p' ↦ p -ᵥ p'` as an equivalence. -/ def const_vsub (p : P) : P ≃ G := { to_fun := (-ᵥ) p, inv_fun := λ v, -v +ᵥ p, left_inv := λ p', by simp, right_inv := λ v, by simp [vsub_vadd_eq_vsub_sub] } @[simp] lemma coe_const_vsub (p : P) : ⇑(const_vsub p) = (-ᵥ) p := rfl @[simp] lemma coe_const_vsub_symm (p : P) : ⇑(const_vsub p).symm = λ v, -v +ᵥ p := rfl variables (P) /-- The permutation given by `p ↦ v +ᵥ p`. -/ def const_vadd (v : G) : equiv.perm P := { to_fun := (+ᵥ) v, inv_fun := (+ᵥ) (-v), left_inv := λ p, by simp [vadd_vadd], right_inv := λ p, by simp [vadd_vadd] } @[simp] lemma coe_const_vadd (v : G) : ⇑(const_vadd P v) = (+ᵥ) v := rfl variable (G) @[simp] lemma const_vadd_zero : const_vadd P (0:G) = 1 := ext $ zero_vadd G variable {G} @[simp] lemma const_vadd_add (v₁ v₂ : G) : const_vadd P (v₁ + v₂) = const_vadd P v₁ * const_vadd P v₂ := ext $ add_vadd v₁ v₂ /-- `equiv.const_vadd` as a homomorphism from `multiplicative G` to `equiv.perm P` -/ def const_vadd_hom : multiplicative G →* equiv.perm P := { to_fun := λ v, const_vadd P v.to_add, map_one' := const_vadd_zero G P, map_mul' := const_vadd_add P } variable {P} open function /-- Point reflection in `x` as a permutation. -/ def point_reflection (x : P) : perm P := (const_vsub x).trans (vadd_const x) lemma point_reflection_apply (x y : P) : point_reflection x y = x -ᵥ y +ᵥ x := rfl @[simp] lemma point_reflection_symm (x : P) : (point_reflection x).symm = point_reflection x := ext $ by simp [point_reflection] @[simp] lemma point_reflection_self (x : P) : point_reflection x x = x := vsub_vadd _ _ lemma point_reflection_involutive (x : P) : involutive (point_reflection x : P → P) := λ y, (equiv.apply_eq_iff_eq_symm_apply _).2 $ by rw point_reflection_symm /-- `x` is the only fixed point of `point_reflection x`. This lemma requires `x + x = y + y ↔ x = y`. There is no typeclass to use here, so we add it as an explicit argument. -/ lemma point_reflection_fixed_iff_of_injective_bit0 {x y : P} (h : injective (bit0 : G → G)) : point_reflection x y = y ↔ y = x := by rw [point_reflection_apply, eq_comm, eq_vadd_iff_vsub_eq, ← neg_vsub_eq_vsub_rev, neg_eq_iff_add_eq_zero, ← bit0, ← bit0_zero, h.eq_iff, vsub_eq_zero_iff_eq, eq_comm] omit G lemma injective_point_reflection_left_of_injective_bit0 {G P : Type*} [add_comm_group G] [add_torsor G P] (h : injective (bit0 : G → G)) (y : P) : injective (λ x : P, point_reflection x y) := λ x₁ x₂ (hy : point_reflection x₁ y = point_reflection x₂ y), by rwa [point_reflection_apply, point_reflection_apply, vadd_eq_vadd_iff_sub_eq_vsub, vsub_sub_vsub_cancel_right, ← neg_vsub_eq_vsub_rev, neg_eq_iff_add_eq_zero, ← bit0, ← bit0_zero, h.eq_iff, vsub_eq_zero_iff_eq] at hy end equiv lemma add_torsor.subsingleton_iff (G P : Type*) [add_group G] [add_torsor G P] : subsingleton G ↔ subsingleton P := begin inhabit P, exact (equiv.vadd_const default).subsingleton_congr, end
0b8eb36075d094d4fafd8256949b1af390172820
36c7a18fd72e5b57229bd8ba36493daf536a19ce
/hott/algebra/relation.hlean
26e6bb4bcbaf23db9cff8ad08f2a40bc69c3ceb5
[ "Apache-2.0" ]
permissive
YHVHvx/lean
732bf0fb7a298cd7fe0f15d82f8e248c11db49e9
038369533e0136dd395dc252084d3c1853accbf2
refs/heads/master
1,610,701,080,210
1,449,128,595,000
1,449,128,595,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,419
hlean
/- 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 → Type) {T2 : Type} (R2 : T2 → T2 → Type) (f : T1 → T2) := (congr : Π{x y}, R1 x y → R2 (f x) (f y)) structure is_congruence2 [class] {T1 : Type} (R1 : T1 → T1 → Type) {T2 : Type} (R2 : T2 → T2 → Type) {T3 : Type} (R3 : T3 → T3 → Type) (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 → Type} {T2 : Type} {R2 : T2 → T2 → Type} {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 → Type} {T2 : Type} {R2 : T2 → T2 → Type} {T3 : Type} {R3 : T3 → T3 → Type} {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 → Type} {T3 : Type} {R3 : T3 → T3 → Type} {g : T2 → T3} (C2 : is_congruence R2 R3 g) ⦃T1 : Type⦄ {R1 : T1 → T1 → Type} {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 → Type} {T3 : Type} {R3 : T3 → T3 → Type} {T4 : Type} {R4 : T4 → T4 → Type} {g : T2 → T3 → T4} (C3 : is_congruence2 R2 R3 R4 g) ⦃T1 : Type⦄ {R1 : T1 → T1 → Type} {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 → Type) (H : relation.reflexive R2) ⦃T1 : Type⦄ (R1 : T1 → T1 → Type) (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 → Type) [C : is_reflexive R2] ⦃T1 : Type⦄ (R1 : T1 → T1 → Type) (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 → Type) : 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
f93a7b40c4272825f366ffdaef581ef830af130c
86f6f4f8d827a196a32bfc646234b73328aeb306
/examples/sets_functions_and_relations/unnamed_612.lean
d5f633ecf1b0b6b653b867808942a78cbcee388d
[]
no_license
jamescheuk91/mathematics_in_lean
09f1f87d2b0dce53464ff0cbe592c568ff59cf5e
4452499264e2975bca2f42565c0925506ba5dda3
refs/heads/master
1,679,716,410,967
1,613,957,947,000
1,613,957,947,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
655
lean
import tactic open set -- BEGIN variables α I : Type* variables A B : I → set α variable s : set α example : s ∩ (⋃ i, A i) = ⋃ i, (A i ∩ s) := begin ext x, simp only [mem_inter_eq, mem_Union], split, { rintros ⟨xs, ⟨i, xAi⟩⟩, exact ⟨i, xAi, xs⟩ }, rintros ⟨i, xAi, xs⟩, exact ⟨xs, ⟨i, xAi⟩⟩ end example : (⋂ i, A i ∩ B i) = (⋂ i, A i) ∩ (⋂ i, B i) := begin ext x, simp only [mem_inter_eq, mem_Inter], split, { intro h, split, { intro i, exact (h i).1 }, intro i, exact (h i).2 }, rintros ⟨h1, h2⟩ i, split, { exact h1 i }, exact h2 i end -- END
be029e3368724adf79e5da5c8e4f3124d0b7adce
8b9f17008684d796c8022dab552e42f0cb6fb347
/library/data/finset/comb.lean
89fb3ce96f6b4945c6dcbbe0bcf018ff5219f47f
[ "Apache-2.0" ]
permissive
chubbymaggie/lean
0d06ae25f9dd396306fb02190e89422ea94afd7b
d2c7b5c31928c98f545b16420d37842c43b4ae9a
refs/heads/master
1,611,313,622,901
1,430,266,839,000
1,430,267,083,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,147
lean
/- Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Module: data.finset Author: Leonardo de Moura Combinators for finite sets -/ import data.finset.basic logic.identities open list quot subtype decidable perm function namespace finset section map variables {A B : Type} variable [h : decidable_eq B] include h definition map (f : A → B) (s : finset A) : finset B := quot.lift_on s (λ l, to_finset (list.map f (elt_of l))) (λ l₁ l₂ p, quot.sound (perm_erase_dup_of_perm (perm_map _ p))) theorem map_empty (f : A → B) : map f ∅ = ∅ := rfl end map section all variables {A : Type} definition all (s : finset A) (p : A → Prop) : Prop := quot.lift_on s (λ l, all (elt_of l) p) (λ l₁ l₂ p, foldr_eq_of_perm (λ a₁ a₂ q, propext !and.left_comm) p true) theorem all_empty (p : A → Prop) : all ∅ p = true := rfl theorem of_mem_of_all {p : A → Prop} {a : A} {s : finset A} : a ∈ s → all s p → p a := quot.induction_on s (λ l i h, list.of_mem_of_all i h) theorem all_implies {p q : A → Prop} {s : finset A} : all s p → (∀ x, p x → q x) → all s q := quot.induction_on s (λ l h₁ h₂, list.all_implies h₁ h₂) variable [h : decidable_eq A] include h theorem all_union {p : A → Prop} {s₁ s₂ : finset A} : all s₁ p → all s₂ p → all (s₁ ∪ s₂) p := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ a₁ a₂, all_union a₁ a₂) theorem all_of_all_union_left {p : A → Prop} {s₁ s₂ : finset A} : all (s₁ ∪ s₂) p → all s₁ p := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ a, list.all_of_all_union_left a) theorem all_of_all_union_right {p : A → Prop} {s₁ s₂ : finset A} : all (s₁ ∪ s₂) p → all s₂ p := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ a, list.all_of_all_union_right a) theorem all_insert_of_all {p : A → Prop} {a : A} {s : finset A} : p a → all s p → all (insert a s) p := quot.induction_on s (λ l h₁ h₂, list.all_insert_of_all h₁ h₂) theorem all_erase_of_all {p : A → Prop} (a : A) {s : finset A}: all s p → all (erase a s) p := quot.induction_on s (λ l h, list.all_erase_of_all a h) theorem all_intersection_of_all_left {p : A → Prop} {s₁ : finset A} (s₂ : finset A) : all s₁ p → all (s₁ ∩ s₂) p := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ h, list.all_intersection_of_all_left _ h) theorem all_intersection_of_all_right {p : A → Prop} {s₁ : finset A} (s₂ : finset A) : all s₂ p → all (s₁ ∩ s₂) p := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ h, list.all_intersection_of_all_right _ h) end all section cross_product variables {A B : Type} definition cross_product (s₁ : finset A) (s₂ : finset B) : finset (A × B) := quot.lift_on₂ s₁ s₂ (λ l₁ l₂, to_finset_of_nodup (list.cross_product (elt_of l₁) (elt_of l₂)) (nodup_cross_product (has_property l₁) (has_property l₂))) (λ v₁ v₂ w₁ w₂ p₁ p₂, quot.sound (perm_cross_product p₁ p₂)) infix * := cross_product theorem empty_cross_product (s : finset B) : @empty A * s = ∅ := quot.induction_on s (λ l, rfl) theorem mem_cross_product {a : A} {b : B} {s₁ : finset A} {s₂ : finset B} : a ∈ s₁ → b ∈ s₂ → (a, b) ∈ s₁ * s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ i₁ i₂, list.mem_cross_product i₁ i₂) theorem mem_of_mem_cross_product_left {a : A} {b : B} {s₁ : finset A} {s₂ : finset B} : (a, b) ∈ s₁ * s₂ → a ∈ s₁ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ i, list.mem_of_mem_cross_product_left i) theorem mem_of_mem_cross_product_right {a : A} {b : B} {s₁ : finset A} {s₂ : finset B} : (a, b) ∈ s₁ * s₂ → b ∈ s₂ := quot.induction_on₂ s₁ s₂ (λ l₁ l₂ i, list.mem_of_mem_cross_product_right i) theorem cross_product_empty (s : finset A) : s * @empty B = ∅ := ext (λ p, match p with | (a, b) := iff.intro (λ i, absurd (mem_of_mem_cross_product_right i) !not_mem_empty) (λ i, absurd i !not_mem_empty) end) end cross_product end finset
4c43b0a89a08f2bd8b0d793370f2ae64f61da1e7
c777c32c8e484e195053731103c5e52af26a25d1
/src/measure_theory/group/fundamental_domain.lean
689cacb93d810c046fbddc92ec1b121c7e5fb3ad
[ "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
31,298
lean
/- Copyright (c) 2021 Yury G. Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury G. Kudryashov -/ import measure_theory.group.action import measure_theory.integral.set_integral /-! # Fundamental domain of a group action A set `s` is said to be a *fundamental domain* of an action of a group `G` on a measurable space `α` with respect to a measure `μ` if * `s` is a measurable set; * the sets `g • s` over all `g : G` cover almost all points of the whole space; * the sets `g • s`, are pairwise a.e. disjoint, i.e., `μ (g₁ • s ∩ g₂ • s) = 0` whenever `g₁ ≠ g₂`; we require this for `g₂ = 1` in the definition, then deduce it for any two `g₁ ≠ g₂`. In this file we prove that in case of a countable group `G` and a measure preserving action, any two fundamental domains have the same measure, and for a `G`-invariant function, its integrals over any two fundamental domains are equal to each other. We also generate additive versions of all theorems in this file using the `to_additive` attribute. ## Main declarations * `measure_theory.is_fundamental_domain`: Predicate for a set to be a fundamental domain of the action of a group * `measure_theory.fundamental_frontier`: Fundamental frontier of a set under the action of a group. Elements of `s` that belong to some other translate of `s`. * `measure_theory.fundamental_interior`: Fundamental interior of a set under the action of a group. Elements of `s` that do not belong to any other translate of `s`. -/ open_locale ennreal pointwise topology nnreal ennreal measure_theory open measure_theory measure_theory.measure set function topological_space filter namespace measure_theory /-- A measurable set `s` is a *fundamental domain* for an additive action of an additive group `G` on a measurable space `α` with respect to a measure `α` if the sets `g +ᵥ s`, `g : G`, are pairwise a.e. disjoint and cover the whole space. -/ @[protect_proj] structure is_add_fundamental_domain (G : Type*) {α : Type*} [has_zero G] [has_vadd G α] [measurable_space α] (s : set α) (μ : measure α . volume_tac) : Prop := (null_measurable_set : null_measurable_set s μ) (ae_covers : ∀ᵐ x ∂μ, ∃ g : G, g +ᵥ x ∈ s) (ae_disjoint : pairwise $ ae_disjoint μ on λ g : G, g +ᵥ s) /-- A measurable set `s` is a *fundamental domain* for an action of a group `G` on a measurable space `α` with respect to a measure `α` if the sets `g • s`, `g : G`, are pairwise a.e. disjoint and cover the whole space. -/ @[protect_proj, to_additive is_add_fundamental_domain] structure is_fundamental_domain (G : Type*) {α : Type*} [has_one G] [has_smul G α] [measurable_space α] (s : set α) (μ : measure α . volume_tac) : Prop := (null_measurable_set : null_measurable_set s μ) (ae_covers : ∀ᵐ x ∂μ, ∃ g : G, g • x ∈ s) (ae_disjoint : pairwise $ ae_disjoint μ on λ g : G, g • s) variables {G H α β E : Type*} namespace is_fundamental_domain variables [group G] [group H] [mul_action G α] [measurable_space α] [mul_action H β] [measurable_space β] [normed_add_comm_group E] {s t : set α} {μ : measure α} /-- If for each `x : α`, exactly one of `g • x`, `g : G`, belongs to a measurable set `s`, then `s` is a fundamental domain for the action of `G` on `α`. -/ @[to_additive "If for each `x : α`, exactly one of `g +ᵥ x`, `g : G`, belongs to a measurable set `s`, then `s` is a fundamental domain for the additive action of `G` on `α`."] lemma mk' (h_meas : null_measurable_set s μ) (h_exists : ∀ x : α, ∃! g : G, g • x ∈ s) : is_fundamental_domain G s μ := { null_measurable_set := h_meas, ae_covers := eventually_of_forall $ λ x, (h_exists x).exists, ae_disjoint := λ a b hab, disjoint.ae_disjoint $ disjoint_left.2 $ λ x hxa hxb, begin rw mem_smul_set_iff_inv_smul_mem at hxa hxb, exact hab (inv_injective $ (h_exists x).unique hxa hxb), end } /-- For `s` to be a fundamental domain, it's enough to check `ae_disjoint (g • s) s` for `g ≠ 1`. -/ @[to_additive "For `s` to be a fundamental domain, it's enough to check `ae_disjoint (g +ᵥ s) s` for `g ≠ 0`."] lemma mk'' (h_meas : null_measurable_set s μ) (h_ae_covers : ∀ᵐ x ∂μ, ∃ g : G, g • x ∈ s) (h_ae_disjoint : ∀ g ≠ (1 : G), ae_disjoint μ (g • s) s) (h_qmp : ∀ (g : G), quasi_measure_preserving ((•) g : α → α) μ μ) : is_fundamental_domain G s μ := { null_measurable_set := h_meas, ae_covers := h_ae_covers, ae_disjoint := pairwise_ae_disjoint_of_ae_disjoint_forall_ne_one h_ae_disjoint h_qmp } /-- If a measurable space has a finite measure `μ` and a countable group `G` acts quasi-measure-preservingly, then to show that a set `s` is a fundamental domain, it is sufficient to check that its translates `g • s` are (almost) disjoint and that the sum `∑' g, μ (g • s)` is sufficiently large. -/ @[to_additive measure_theory.is_add_fundamental_domain.mk_of_measure_univ_le " If a measurable space has a finite measure `μ` and a countable additive group `G` acts quasi-measure-preservingly, then to show that a set `s` is a fundamental domain, it is sufficient to check that its translates `g +ᵥ s` are (almost) disjoint and that the sum `∑' g, μ (g +ᵥ s)` is sufficiently large."] lemma mk_of_measure_univ_le [is_finite_measure μ] [countable G] (h_meas : null_measurable_set s μ) (h_ae_disjoint : ∀ g ≠ (1 : G), ae_disjoint μ (g • s) s) (h_qmp : ∀ (g : G), quasi_measure_preserving ((•) g : α → α) μ μ) (h_measure_univ_le : μ (univ : set α) ≤ ∑' (g : G), μ (g • s)) : is_fundamental_domain G s μ := have ae_disjoint : pairwise (ae_disjoint μ on (λ (g : G), g • s)) := pairwise_ae_disjoint_of_ae_disjoint_forall_ne_one h_ae_disjoint h_qmp, { null_measurable_set := h_meas, ae_disjoint := ae_disjoint, ae_covers := begin replace h_meas : ∀ (g : G), null_measurable_set (g • s) μ := λ g, by { rw [← inv_inv g, ← preimage_smul], exact h_meas.preimage (h_qmp g⁻¹), }, have h_meas' : null_measurable_set {a | ∃ (g : G), g • a ∈ s} μ, { rw ← Union_smul_eq_set_of_exists, exact null_measurable_set.Union h_meas, }, rw [ae_iff_measure_eq h_meas', ← Union_smul_eq_set_of_exists], refine le_antisymm (measure_mono $ subset_univ _) _, rw measure_Union₀ ae_disjoint h_meas, exact h_measure_univ_le, end } @[to_additive] lemma Union_smul_ae_eq (h : is_fundamental_domain G s μ) : (⋃ g : G, g • s) =ᵐ[μ] univ := eventually_eq_univ.2 $ h.ae_covers.mono $ λ x ⟨g, hg⟩, mem_Union.2 ⟨g⁻¹, _, hg, inv_smul_smul _ _⟩ @[to_additive] lemma mono (h : is_fundamental_domain G s μ) {ν : measure α} (hle : ν ≪ μ) : is_fundamental_domain G s ν := ⟨h.1.mono_ac hle, hle h.2, h.ae_disjoint.mono $ λ a b hab, hle hab⟩ @[to_additive] lemma preimage_of_equiv {ν : measure β} (h : is_fundamental_domain G s μ) {f : β → α} (hf : quasi_measure_preserving f ν μ) {e : G → H} (he : bijective e) (hef : ∀ g, semiconj f ((•) (e g)) ((•) g)) : is_fundamental_domain H (f ⁻¹' s) ν := { null_measurable_set := h.null_measurable_set.preimage hf, ae_covers := (hf.ae h.ae_covers).mono $ λ x ⟨g, hg⟩, ⟨e g, by rwa [mem_preimage, hef g x]⟩, ae_disjoint := λ a b hab, begin lift e to G ≃ H using he, have : (e.symm a⁻¹)⁻¹ ≠ (e.symm b⁻¹)⁻¹, by simp [hab], convert (h.ae_disjoint this).preimage hf using 1, simp only [←preimage_smul_inv, preimage_preimage, ←hef _ _, e.apply_symm_apply, inv_inv], end } @[to_additive] lemma image_of_equiv {ν : measure β} (h : is_fundamental_domain G s μ) (f : α ≃ β) (hf : quasi_measure_preserving f.symm ν μ) (e : H ≃ G) (hef : ∀ g, semiconj f ((•) (e g)) ((•) g)) : is_fundamental_domain H (f '' s) ν := begin rw f.image_eq_preimage, refine h.preimage_of_equiv hf e.symm.bijective (λ g x, _), rcases f.surjective x with ⟨x, rfl⟩, rw [← hef _ _, f.symm_apply_apply, f.symm_apply_apply, e.apply_symm_apply] end @[to_additive] lemma pairwise_ae_disjoint_of_ac {ν} (h : is_fundamental_domain G s μ) (hν : ν ≪ μ) : pairwise (λ g₁ g₂ : G, ae_disjoint ν (g₁ • s) (g₂ • s)) := h.ae_disjoint.mono $ λ g₁ g₂ H, hν H @[to_additive] lemma smul_of_comm {G' : Type*} [group G'] [mul_action G' α] [measurable_space G'] [has_measurable_smul G' α] [smul_invariant_measure G' α μ] [smul_comm_class G' G α] (h : is_fundamental_domain G s μ) (g : G') : is_fundamental_domain G (g • s) μ := h.image_of_equiv (mul_action.to_perm g) (measure_preserving_smul _ _).quasi_measure_preserving (equiv.refl _) $ smul_comm g variables [measurable_space G] [has_measurable_smul G α] [smul_invariant_measure G α μ] @[to_additive] lemma null_measurable_set_smul (h : is_fundamental_domain G s μ) (g : G) : null_measurable_set (g • s) μ := h.null_measurable_set.smul g @[to_additive] lemma restrict_restrict (h : is_fundamental_domain G s μ) (g : G) (t : set α) : (μ.restrict t).restrict (g • s) = μ.restrict (g • s ∩ t) := restrict_restrict₀ ((h.null_measurable_set_smul g).mono restrict_le_self) @[to_additive] lemma smul (h : is_fundamental_domain G s μ) (g : G) : is_fundamental_domain G (g • s) μ := h.image_of_equiv (mul_action.to_perm g) (measure_preserving_smul _ _).quasi_measure_preserving ⟨λ g', g⁻¹ * g' * g, λ g', g * g' * g⁻¹, λ g', by simp [mul_assoc], λ g', by simp [mul_assoc]⟩ $ λ g' x, by simp [smul_smul, mul_assoc] variables [countable G] {ν : measure α} @[to_additive] lemma sum_restrict_of_ac (h : is_fundamental_domain G s μ) (hν : ν ≪ μ) : sum (λ g : G, ν.restrict (g • s)) = ν := by rw [← restrict_Union_ae (h.ae_disjoint.mono $ λ i j h, hν h) (λ g, (h.null_measurable_set_smul g).mono_ac hν), restrict_congr_set (hν h.Union_smul_ae_eq), restrict_univ] @[to_additive] lemma lintegral_eq_tsum_of_ac (h : is_fundamental_domain G s μ) (hν : ν ≪ μ) (f : α → ℝ≥0∞) : ∫⁻ x, f x ∂ν = ∑' g : G, ∫⁻ x in g • s, f x ∂ν := by rw [← lintegral_sum_measure, h.sum_restrict_of_ac hν] @[to_additive] lemma sum_restrict (h : is_fundamental_domain G s μ) : sum (λ g : G, μ.restrict (g • s)) = μ := h.sum_restrict_of_ac (refl _) @[to_additive] lemma lintegral_eq_tsum (h : is_fundamental_domain G s μ) (f : α → ℝ≥0∞) : ∫⁻ x, f x ∂μ = ∑' g : G, ∫⁻ x in g • s, f x ∂μ := h.lintegral_eq_tsum_of_ac (refl _) f @[to_additive] lemma lintegral_eq_tsum' (h : is_fundamental_domain G s μ) (f : α → ℝ≥0∞) : ∫⁻ x, f x ∂μ = ∑' g : G, ∫⁻ x in s, f (g⁻¹ • x) ∂μ := calc ∫⁻ x, f x ∂μ = ∑' g : G, ∫⁻ x in g • s, f x ∂μ : h.lintegral_eq_tsum f ... = ∑' g : G, ∫⁻ x in g⁻¹ • s, f x ∂μ : ((equiv.inv G).tsum_eq _).symm ... = ∑' g : G, ∫⁻ x in s, f (g⁻¹ • x) ∂μ : tsum_congr $ λ g, ((measure_preserving_smul g⁻¹ μ).set_lintegral_comp_emb (measurable_embedding_const_smul _) _ _).symm @[to_additive] lemma set_lintegral_eq_tsum (h : is_fundamental_domain G s μ) (f : α → ℝ≥0∞) (t : set α) : ∫⁻ x in t, f x ∂μ = ∑' g : G, ∫⁻ x in t ∩ g • s, f x ∂μ := calc ∫⁻ x in t, f x ∂μ = ∑' g : G, ∫⁻ x in g • s, f x ∂(μ.restrict t) : h.lintegral_eq_tsum_of_ac restrict_le_self.absolutely_continuous _ ... = ∑' g : G, ∫⁻ x in t ∩ g • s, f x ∂μ : by simp only [h.restrict_restrict, inter_comm] @[to_additive] lemma set_lintegral_eq_tsum' (h : is_fundamental_domain G s μ) (f : α → ℝ≥0∞) (t : set α) : ∫⁻ x in t, f x ∂μ = ∑' g : G, ∫⁻ x in g • t ∩ s, f (g⁻¹ • x) ∂μ := calc ∫⁻ x in t, f x ∂μ = ∑' g : G, ∫⁻ x in t ∩ g • s, f x ∂μ : h.set_lintegral_eq_tsum f t ... = ∑' g : G, ∫⁻ x in t ∩ g⁻¹ • s, f x ∂μ : ((equiv.inv G).tsum_eq _).symm ... = ∑' g : G, ∫⁻ x in g⁻¹ • (g • t ∩ s), f (x) ∂μ : by simp only [smul_set_inter, inv_smul_smul] ... = ∑' g : G, ∫⁻ x in g • t ∩ s, f (g⁻¹ • x) ∂μ : tsum_congr $ λ g, ((measure_preserving_smul g⁻¹ μ).set_lintegral_comp_emb (measurable_embedding_const_smul _) _ _).symm @[to_additive] lemma measure_eq_tsum_of_ac (h : is_fundamental_domain G s μ) (hν : ν ≪ μ) (t : set α) : ν t = ∑' g : G, ν (t ∩ g • s) := have H : ν.restrict t ≪ μ, from measure.restrict_le_self.absolutely_continuous.trans hν, by simpa only [set_lintegral_one, pi.one_def, measure.restrict_apply₀ ((h.null_measurable_set_smul _).mono_ac H), inter_comm] using h.lintegral_eq_tsum_of_ac H 1 @[to_additive] lemma measure_eq_tsum' (h : is_fundamental_domain G s μ) (t : set α) : μ t = ∑' g : G, μ (t ∩ g • s) := h.measure_eq_tsum_of_ac absolutely_continuous.rfl t @[to_additive] lemma measure_eq_tsum (h : is_fundamental_domain G s μ) (t : set α) : μ t = ∑' g : G, μ (g • t ∩ s) := by simpa only [set_lintegral_one] using h.set_lintegral_eq_tsum' (λ _, 1) t @[to_additive] lemma measure_zero_of_invariant (h : is_fundamental_domain G s μ) (t : set α) (ht : ∀ g : G, g • t = t) (hts : μ (t ∩ s) = 0) : μ t = 0 := by simp [measure_eq_tsum h, ht, hts] /-- Given a measure space with an action of a finite group `G`, the measure of any `G`-invariant set is determined by the measure of its intersection with a fundamental domain for the action of `G`. -/ @[to_additive measure_eq_card_smul_of_vadd_ae_eq_self "Given a measure space with an action of a finite additive group `G`, the measure of any `G`-invariant set is determined by the measure of its intersection with a fundamental domain for the action of `G`."] lemma measure_eq_card_smul_of_smul_ae_eq_self [finite G] (h : is_fundamental_domain G s μ) (t : set α) (ht : ∀ g : G, (g • t : set α) =ᵐ[μ] t) : μ t = nat.card G • μ (t ∩ s) := begin haveI : fintype G := fintype.of_finite G, rw h.measure_eq_tsum, replace ht : ∀ g : G, ((g • t) ∩ s : set α) =ᵐ[μ] (t ∩ s : set α) := λ g, ae_eq_set_inter (ht g) (ae_eq_refl s), simp_rw [measure_congr (ht _), tsum_fintype, finset.sum_const, nat.card_eq_fintype_card, finset.card_univ], end @[to_additive] protected lemma set_lintegral_eq (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) (f : α → ℝ≥0∞) (hf : ∀ (g : G) x, f (g • x) = f x) : ∫⁻ x in s, f x ∂μ = ∫⁻ x in t, f x ∂μ := calc ∫⁻ x in s, f x ∂μ = ∑' g : G, ∫⁻ x in s ∩ g • t, f x ∂μ : ht.set_lintegral_eq_tsum _ _ ... = ∑' g : G, ∫⁻ x in g • t ∩ s, f (g⁻¹ • x) ∂μ : by simp only [hf, inter_comm] ... = ∫⁻ x in t, f x ∂μ : (hs.set_lintegral_eq_tsum' _ _).symm @[to_additive] lemma measure_set_eq (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) {A : set α} (hA₀ : measurable_set A) (hA : ∀ (g : G), (λ x, g • x) ⁻¹' A = A) : μ (A ∩ s) = μ (A ∩ t) := begin have : ∫⁻ x in s, A.indicator 1 x ∂μ = ∫⁻ x in t, A.indicator 1 x ∂μ, { refine hs.set_lintegral_eq ht (set.indicator A (λ _, 1)) _, intros g x, convert (set.indicator_comp_right (λ x : α, g • x)).symm, rw hA g }, simpa [measure.restrict_apply hA₀, lintegral_indicator _ hA₀] using this end /-- If `s` and `t` are two fundamental domains of the same action, then their measures are equal. -/ @[to_additive "If `s` and `t` are two fundamental domains of the same action, then their measures are equal."] protected lemma measure_eq (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) : μ s = μ t := by simpa only [set_lintegral_one] using hs.set_lintegral_eq ht (λ _, 1) (λ _ _, rfl) @[to_additive] protected lemma ae_strongly_measurable_on_iff {β : Type*} [topological_space β] [pseudo_metrizable_space β] (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) {f : α → β} (hf : ∀ (g : G) x, f (g • x) = f x) : ae_strongly_measurable f (μ.restrict s) ↔ ae_strongly_measurable f (μ.restrict t) := calc ae_strongly_measurable f (μ.restrict s) ↔ ae_strongly_measurable f (measure.sum $ λ g : G, (μ.restrict (g • t ∩ s))) : by simp only [← ht.restrict_restrict, ht.sum_restrict_of_ac restrict_le_self.absolutely_continuous] ... ↔ ∀ g : G, ae_strongly_measurable f (μ.restrict (g • (g⁻¹ • s ∩ t))) : by simp only [smul_set_inter, inter_comm, smul_inv_smul, ae_strongly_measurable_sum_measure_iff] ... ↔ ∀ g : G, ae_strongly_measurable f (μ.restrict (g⁻¹ • (g⁻¹⁻¹ • s ∩ t))) : inv_surjective.forall ... ↔ ∀ g : G, ae_strongly_measurable f (μ.restrict (g⁻¹ • (g • s ∩ t))) : by simp only [inv_inv] ... ↔ ∀ g : G, ae_strongly_measurable f (μ.restrict (g • s ∩ t)) : begin refine forall_congr (λ g, _), have he : measurable_embedding ((•) g⁻¹ : α → α) := measurable_embedding_const_smul _, rw [← image_smul, ← ((measure_preserving_smul g⁻¹ μ).restrict_image_emb he _).ae_strongly_measurable_comp_iff he], simp only [(∘), hf] end ... ↔ ae_strongly_measurable f (μ.restrict t) : by simp only [← ae_strongly_measurable_sum_measure_iff, ← hs.restrict_restrict, hs.sum_restrict_of_ac restrict_le_self.absolutely_continuous] @[to_additive] protected lemma has_finite_integral_on_iff (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) {f : α → E} (hf : ∀ (g : G) x, f (g • x) = f x) : has_finite_integral f (μ.restrict s) ↔ has_finite_integral f (μ.restrict t) := begin dunfold has_finite_integral, rw hs.set_lintegral_eq ht, intros g x, rw hf end @[to_additive] protected lemma integrable_on_iff (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) {f : α → E} (hf : ∀ (g : G) x, f (g • x) = f x) : integrable_on f s μ ↔ integrable_on f t μ := and_congr (hs.ae_strongly_measurable_on_iff ht hf) (hs.has_finite_integral_on_iff ht hf) variables [normed_space ℝ E] [complete_space E] @[to_additive] lemma integral_eq_tsum_of_ac (h : is_fundamental_domain G s μ) (hν : ν ≪ μ) (f : α → E) (hf : integrable f ν) : ∫ x, f x ∂ν = ∑' g : G, ∫ x in g • s, f x ∂ν := begin rw [← measure_theory.integral_sum_measure, h.sum_restrict_of_ac hν], rw h.sum_restrict_of_ac hν, -- Weirdly, these rewrites seem not to be combinable exact hf, end @[to_additive] lemma integral_eq_tsum (h : is_fundamental_domain G s μ) (f : α → E) (hf : integrable f μ) : ∫ x, f x ∂μ = ∑' g : G, ∫ x in g • s, f x ∂μ := integral_eq_tsum_of_ac h (by refl) f hf @[to_additive] lemma integral_eq_tsum' (h : is_fundamental_domain G s μ) (f : α → E) (hf : integrable f μ) : ∫ x, f x ∂μ = ∑' g : G, ∫ x in s, f (g⁻¹ • x) ∂μ := calc ∫ x, f x ∂μ = ∑' g : G, ∫ x in g • s, f x ∂μ : h.integral_eq_tsum f hf ... = ∑' g : G, ∫ x in g⁻¹ • s, f x ∂μ : ((equiv.inv G).tsum_eq _).symm ... = ∑' g : G, ∫ x in s, f (g⁻¹ • x) ∂μ : tsum_congr $ λ g, (measure_preserving_smul g⁻¹ μ).set_integral_image_emb (measurable_embedding_const_smul _) _ _ @[to_additive] lemma set_integral_eq_tsum (h : is_fundamental_domain G s μ) {f : α → E} {t : set α} (hf : integrable_on f t μ) : ∫ x in t, f x ∂μ = ∑' g : G, ∫ x in t ∩ g • s, f x ∂μ := calc ∫ x in t, f x ∂μ = ∑' g : G, ∫ x in g • s, f x ∂(μ.restrict t) : h.integral_eq_tsum_of_ac restrict_le_self.absolutely_continuous f hf ... = ∑' g : G, ∫ x in t ∩ g • s, f x ∂μ : by simp only [h.restrict_restrict, measure_smul, inter_comm] @[to_additive] lemma set_integral_eq_tsum' (h : is_fundamental_domain G s μ) {f : α → E} {t : set α} (hf : integrable_on f t μ) : ∫ x in t, f x ∂μ = ∑' g : G, ∫ x in g • t ∩ s, f (g⁻¹ • x) ∂μ := calc ∫ x in t, f x ∂μ = ∑' g : G, ∫ x in t ∩ g • s, f x ∂μ : h.set_integral_eq_tsum hf ... = ∑' g : G, ∫ x in t ∩ g⁻¹ • s, f x ∂μ : ((equiv.inv G).tsum_eq _).symm ... = ∑' g : G, ∫ x in g⁻¹ • (g • t ∩ s), f (x) ∂μ : by simp only [smul_set_inter, inv_smul_smul] ... = ∑' g : G, ∫ x in g • t ∩ s, f (g⁻¹ • x) ∂μ : tsum_congr $ λ g, (measure_preserving_smul g⁻¹ μ).set_integral_image_emb (measurable_embedding_const_smul _) _ _ @[to_additive] protected lemma set_integral_eq (hs : is_fundamental_domain G s μ) (ht : is_fundamental_domain G t μ) {f : α → E} (hf : ∀ (g : G) x, f (g • x) = f x) : ∫ x in s, f x ∂μ = ∫ x in t, f x ∂μ := begin by_cases hfs : integrable_on f s μ, { have hft : integrable_on f t μ, by rwa ht.integrable_on_iff hs hf, calc ∫ x in s, f x ∂μ = ∑' g : G, ∫ x in s ∩ g • t, f x ∂μ : ht.set_integral_eq_tsum hfs ... = ∑' g : G, ∫ x in g • t ∩ s, f (g⁻¹ • x) ∂μ : by simp only [hf, inter_comm] ... = ∫ x in t, f x ∂μ : (hs.set_integral_eq_tsum' hft).symm, }, { rw [integral_undef hfs, integral_undef], rwa [hs.integrable_on_iff ht hf] at hfs } end /-- If the action of a countable group `G` admits an invariant measure `μ` with a fundamental domain `s`, then every null-measurable set `t` such that the sets `g • t ∩ s` are pairwise a.e.-disjoint has measure at most `μ s`. -/ @[to_additive "If the additive action of a countable group `G` admits an invariant measure `μ` with a fundamental domain `s`, then every null-measurable set `t` such that the sets `g +ᵥ t ∩ s` are pairwise a.e.-disjoint has measure at most `μ s`."] lemma measure_le_of_pairwise_disjoint (hs : is_fundamental_domain G s μ) (ht : null_measurable_set t μ) (hd : pairwise (ae_disjoint μ on (λ g : G, g • t ∩ s))) : μ t ≤ μ s := calc μ t = ∑' g : G, μ (g • t ∩ s) : hs.measure_eq_tsum t ... = μ (⋃ g : G, g • t ∩ s) : eq.symm $ measure_Union₀ hd $ λ g, (ht.smul _).inter hs.null_measurable_set ... ≤ μ s : measure_mono (Union_subset $ λ g, inter_subset_right _ _) /-- If the action of a countable group `G` admits an invariant measure `μ` with a fundamental domain `s`, then every null-measurable set `t` of measure strictly greater than `μ s` contains two points `x y` such that `g • x = y` for some `g ≠ 1`. -/ @[to_additive "If the additive action of a countable group `G` admits an invariant measure `μ` with a fundamental domain `s`, then every null-measurable set `t` of measure strictly greater than `μ s` contains two points `x y` such that `g +ᵥ x = y` for some `g ≠ 0`."] lemma exists_ne_one_smul_eq (hs : is_fundamental_domain G s μ) (htm : null_measurable_set t μ) (ht : μ s < μ t) : ∃ (x y ∈ t) (g ≠ (1 : G)), g • x = y := begin contrapose! ht, refine hs.measure_le_of_pairwise_disjoint htm (pairwise.ae_disjoint $ λ g₁ g₂ hne, _), dsimp [function.on_fun], refine (disjoint.inf_left _ _).inf_right _, rw set.disjoint_left, rintro _ ⟨x, hx, rfl⟩ ⟨y, hy, hxy⟩, refine ht x hx y hy (g₂⁻¹ * g₁) (mt inv_mul_eq_one.1 hne.symm) _, rw [mul_smul, ← hxy, inv_smul_smul] end /-- If `f` is invariant under the action of a countable group `G`, and `μ` is a `G`-invariant measure with a fundamental domain `s`, then the `ess_sup` of `f` restricted to `s` is the same as that of `f` on all of its domain. -/ @[to_additive "If `f` is invariant under the action of a countable additive group `G`, and `μ` is a `G`-invariant measure with a fundamental domain `s`, then the `ess_sup` of `f` restricted to `s` is the same as that of `f` on all of its domain."] lemma ess_sup_measure_restrict (hs : is_fundamental_domain G s μ) {f : α → ℝ≥0∞} (hf : ∀ γ : G, ∀ x: α, f (γ • x) = f x) : ess_sup f (μ.restrict s) = ess_sup f μ := begin refine le_antisymm (ess_sup_mono_measure' measure.restrict_le_self) _, rw [ess_sup_eq_Inf (μ.restrict s) f, ess_sup_eq_Inf μ f], refine Inf_le_Inf _, rintro a (ha : (μ.restrict s) {x : α | a < f x} = 0), rw measure.restrict_apply₀' hs.null_measurable_set at ha, refine measure_zero_of_invariant hs _ _ ha, intros γ, ext x, rw mem_smul_set_iff_inv_smul_mem, simp only [mem_set_of_eq, hf (γ⁻¹) x], end end is_fundamental_domain /-! ### Interior/frontier of a fundamental domain -/ section measurable_space variables (G) [group G] [mul_action G α] (s : set α) {x : α} /-- The boundary of a fundamental domain, those points of the domain that also lie in a nontrivial translate. -/ @[to_additive measure_theory.add_fundamental_frontier "The boundary of a fundamental domain, those points of the domain that also lie in a nontrivial translate."] def fundamental_frontier : set α := s ∩ ⋃ (g : G) (hg : g ≠ 1), g • s /-- The interior of a fundamental domain, those points of the domain not lying in any translate. -/ @[to_additive measure_theory.add_fundamental_interior "The interior of a fundamental domain, those points of the domain not lying in any translate."] def fundamental_interior : set α := s \ ⋃ (g : G) (hg : g ≠ 1), g • s variables {G s} @[simp, to_additive measure_theory.mem_add_fundamental_frontier] lemma mem_fundamental_frontier : x ∈ fundamental_frontier G s ↔ x ∈ s ∧ ∃ (g : G) (hg : g ≠ 1), x ∈ g • s := by simp [fundamental_frontier] @[simp, to_additive measure_theory.mem_add_fundamental_interior] lemma mem_fundamental_interior : x ∈ fundamental_interior G s ↔ x ∈ s ∧ ∀ (g : G) (hg : g ≠ 1), x ∉ g • s := by simp [fundamental_interior] @[to_additive measure_theory.add_fundamental_frontier_subset] lemma fundamental_frontier_subset : fundamental_frontier G s ⊆ s := inter_subset_left _ _ @[to_additive measure_theory.add_fundamental_interior_subset] lemma fundamental_interior_subset : fundamental_interior G s ⊆ s := diff_subset _ _ variables (G s) @[to_additive measure_theory.disjoint_add_fundamental_interior_add_fundamental_frontier] lemma disjoint_fundamental_interior_fundamental_frontier : disjoint (fundamental_interior G s) (fundamental_frontier G s) := disjoint_sdiff_self_left.mono_right inf_le_right @[simp, to_additive measure_theory.add_fundamental_interior_union_add_fundamental_frontier] lemma fundamental_interior_union_fundamental_frontier : fundamental_interior G s ∪ fundamental_frontier G s = s := diff_union_inter _ _ @[simp, to_additive measure_theory.add_fundamental_interior_union_add_fundamental_frontier] lemma fundamental_frontier_union_fundamental_interior : fundamental_frontier G s ∪ fundamental_interior G s = s := inter_union_diff _ _ @[simp, to_additive measure_theory.sdiff_add_fundamental_interior] lemma sdiff_fundamental_interior : s \ fundamental_interior G s = fundamental_frontier G s := sdiff_sdiff_right_self @[simp, to_additive measure_theory.sdiff_add_fundamental_frontier] lemma sdiff_fundamental_frontier : s \ fundamental_frontier G s = fundamental_interior G s := diff_self_inter @[simp, to_additive measure_theory.add_fundamental_frontier_vadd] lemma fundamental_frontier_smul [group H] [mul_action H α] [smul_comm_class H G α] (g : H) : fundamental_frontier G (g • s) = g • fundamental_frontier G s := by simp_rw [fundamental_frontier, smul_set_inter, smul_set_Union, smul_comm g] @[simp, to_additive measure_theory.add_fundamental_interior_vadd] lemma fundamental_interior_smul [group H] [mul_action H α] [smul_comm_class H G α] (g : H) : fundamental_interior G (g • s) = g • fundamental_interior G s := by simp_rw [fundamental_interior, smul_set_sdiff, smul_set_Union, smul_comm g] @[to_additive measure_theory.pairwise_disjoint_add_fundamental_interior] lemma pairwise_disjoint_fundamental_interior : pairwise (disjoint on λ g : G, g • fundamental_interior G s) := begin refine λ a b hab, disjoint_left.2 _, rintro _ ⟨x, hx, rfl⟩ ⟨y, hy, hxy⟩, rw mem_fundamental_interior at hx hy, refine hx.2 (a⁻¹ * b) _ _, rwa [ne.def, inv_mul_eq_iff_eq_mul, mul_one, eq_comm], simpa [mul_smul, ←hxy, mem_inv_smul_set_iff] using hy.1, end variables [countable G] [measurable_space G] [measurable_space α] [has_measurable_smul G α] {μ : measure α} [smul_invariant_measure G α μ] @[to_additive measure_theory.null_measurable_set.add_fundamental_frontier] protected lemma null_measurable_set.fundamental_frontier (hs : null_measurable_set s μ) : null_measurable_set (fundamental_frontier G s) μ := hs.inter $ null_measurable_set.Union $ λ g, null_measurable_set.Union $ λ hg, hs.smul _ @[to_additive measure_theory.null_measurable_set.add_fundamental_interior] protected lemma null_measurable_set.fundamental_interior (hs : null_measurable_set s μ) : null_measurable_set (fundamental_interior G s) μ := hs.diff $ null_measurable_set.Union $ λ g, null_measurable_set.Union $ λ hg, hs.smul _ end measurable_space namespace is_fundamental_domain section group variables [countable G] [group G] [mul_action G α] [measurable_space α] {μ : measure α} {s : set α} (hs : is_fundamental_domain G s μ) include hs @[to_additive measure_theory.is_add_fundamental_domain.measure_add_fundamental_frontier] lemma measure_fundamental_frontier : μ (fundamental_frontier G s) = 0 := by simpa only [fundamental_frontier, Union₂_inter, measure_Union_null_iff', one_smul, measure_Union_null_iff, inter_comm s, function.on_fun] using λ g (hg : g ≠ 1), hs.ae_disjoint hg @[to_additive measure_theory.is_add_fundamental_domain.measure_add_fundamental_interior] lemma measure_fundamental_interior : μ (fundamental_interior G s) = μ s := measure_diff_null' hs.measure_fundamental_frontier end group variables [countable G] [group G] [mul_action G α] [measurable_space α] {μ : measure α} {s : set α} (hs : is_fundamental_domain G s μ) [measurable_space G] [has_measurable_smul G α] [smul_invariant_measure G α μ] include hs protected lemma fundamental_interior : is_fundamental_domain G (fundamental_interior G s) μ := { null_measurable_set := hs.null_measurable_set.fundamental_interior _ _, ae_covers := begin simp_rw [ae_iff, not_exists, ←mem_inv_smul_set_iff, set_of_forall, ←compl_set_of, set_of_mem_eq, ←compl_Union], have : (⋃ g : G, g⁻¹ • s) \ (⋃ g : G, g⁻¹ • fundamental_frontier G s) ⊆ ⋃ g : G, g⁻¹ • fundamental_interior G s, { simp_rw [diff_subset_iff, ←Union_union_distrib, ←smul_set_union, fundamental_frontier_union_fundamental_interior] }, refine eq_bot_mono (μ.mono $ compl_subset_compl.2 this) _, simp only [Union_inv_smul, outer_measure.measure_of_eq_coe, coe_to_outer_measure, compl_sdiff, ennreal.bot_eq_zero, himp_eq, sup_eq_union, @Union_smul_eq_set_of_exists _ _ _ _ s], exact measure_union_null (measure_Union_null $ λ _, measure_smul_null hs.measure_fundamental_frontier _) hs.ae_covers, end, ae_disjoint := (pairwise_disjoint_fundamental_interior _ _).mono $ λ _ _, disjoint.ae_disjoint } end is_fundamental_domain end measure_theory
cedd5de16d678c6b4f521318c768eef9168855de
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/linear_algebra/quadratic_form/complex.lean
be740bbbf6d69e34e46ab2637aa36e81372f9772
[ "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
3,744
lean
/- Copyright (c) 2020 Anne Baanen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Anne Baanen, Kexing Ying, Eric Wieser -/ import linear_algebra.quadratic_form.basic import analysis.special_functions.pow /-! # Quadratic forms over the complex numbers `equivalent_sum_squares`: A nondegenerate quadratic form over the complex numbers is equivalent to a sum of squares. -/ namespace quadratic_form open_locale big_operators open finset variables {ι : Type*} [fintype ι] /-- The isometry between a weighted sum of squares on the complex numbers and the sum of squares, i.e. `weighted_sum_squares` with weights 1 or 0. -/ noncomputable def isometry_sum_squares [decidable_eq ι] (w' : ι → ℂ) : isometry (weighted_sum_squares ℂ w') (weighted_sum_squares ℂ (λ i, if w' i = 0 then 0 else 1 : ι → ℂ)) := begin let w := λ i, if h : w' i = 0 then (1 : units ℂ) else units.mk0 (w' i) h, have hw' : ∀ i : ι, (w i : ℂ) ^ - (1 / 2 : ℂ) ≠ 0, { intros i hi, exact (w i).ne_zero ((complex.cpow_eq_zero_iff _ _).1 hi).1 }, convert (weighted_sum_squares ℂ w').isometry_basis_repr ((pi.basis_fun ℂ ι).units_smul (λ i, (is_unit_iff_ne_zero.2 $ hw' i).unit)), ext1 v, erw [basis_repr_apply, weighted_sum_squares_apply, weighted_sum_squares_apply], refine sum_congr rfl (λ j hj, _), have hsum : (∑ (i : ι), v i • ((is_unit_iff_ne_zero.2 $ hw' i).unit : ℂ) • (pi.basis_fun ℂ ι) i) j = v j • w j ^ - (1 / 2 : ℂ), { rw [finset.sum_apply, sum_eq_single j, pi.basis_fun_apply, is_unit.unit_spec, linear_map.std_basis_apply, pi.smul_apply, pi.smul_apply, function.update_same, smul_eq_mul, smul_eq_mul, smul_eq_mul, mul_one], intros i _ hij, rw [pi.basis_fun_apply, linear_map.std_basis_apply, pi.smul_apply, pi.smul_apply, function.update_noteq hij.symm, pi.zero_apply, smul_eq_mul, smul_eq_mul, mul_zero, mul_zero], intro hj', exact false.elim (hj' hj) }, simp_rw basis.units_smul_apply, erw [hsum, smul_eq_mul], split_ifs, { simp only [h, zero_smul, zero_mul]}, have hww' : w' j = w j, { simp only [w, dif_neg h, units.coe_mk0] }, simp only [hww', one_mul], change v j * v j = ↑(w j) * ((v j * ↑(w j) ^ -(1 / 2 : ℂ)) * (v j * ↑(w j) ^ -(1 / 2 : ℂ))), suffices : v j * v j = w j ^ - (1 / 2 : ℂ) * w j ^ - (1 / 2 : ℂ) * w j * v j * v j, { rw [this], ring }, rw [← complex.cpow_add _ _ (w j).ne_zero, show - (1 / 2 : ℂ) + - (1 / 2) = -1, by ring, complex.cpow_neg_one, inv_mul_cancel (w j).ne_zero, one_mul], end /-- The isometry between a weighted sum of squares on the complex numbers and the sum of squares, i.e. `weighted_sum_squares` with weight `λ i : ι, 1`. -/ noncomputable def isometry_sum_squares_units [decidable_eq ι] (w : ι → units ℂ) : isometry (weighted_sum_squares ℂ w) (weighted_sum_squares ℂ (1 : ι → ℂ)) := begin have hw1 : (λ i, if (w i : ℂ) = 0 then 0 else 1 : ι → ℂ) = 1, { ext i : 1, exact dif_neg (w i).ne_zero }, have := isometry_sum_squares (coe ∘ w), rw hw1 at this, exact this, end /-- A nondegenerate quadratic form on the complex numbers is equivalent to the sum of squares, i.e. `weighted_sum_squares` with weight `λ i : ι, 1`. -/ theorem equivalent_sum_squares {M : Type*} [add_comm_group M] [module ℂ M] [finite_dimensional ℂ M] (Q : quadratic_form ℂ M) (hQ : (associated Q).nondegenerate) : equivalent Q (weighted_sum_squares ℂ (1 : fin (finite_dimensional.finrank ℂ M) → ℂ)) := let ⟨w, ⟨hw₁⟩⟩ := Q.equivalent_weighted_sum_squares_units_of_nondegenerate' hQ in ⟨hw₁.trans (isometry_sum_squares_units w)⟩ end quadratic_form
2425b6d4f867dcdebdf76d69667e26cd3328e6b5
80d0f8071ea62262937ab36f5887a61735adea09
/src/certigrad/tfacts.lean
3d565cc974d65b56fb11d47634140348b2ce3767
[ "Apache-2.0" ]
permissive
wudcscheme/certigrad
94805fa6a61f993c69a824429a103c9613a65a48
c9a06e93f1ec58196d6d3b8563b29868d916727f
refs/heads/master
1,679,386,475,077
1,551,651,022,000
1,551,651,022,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
31,187
lean
/- Copyright (c) 2017 Daniel Selsam. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Daniel Selsam Miscellaneous facts and theorems about tensors. We view tensors as a field extended component-wise. As such, they form an ordered (but not linearly-ordered) commutative ring. They also have division, except the precondition for cancellation is not `x ≠ 0` but `|x| > 0`, which we simplify to `x > 0`. Note: the axioms are by no means minimal. -/ import .tensor .id .reference .env .dvec -- TODO(dhs): move these elsewhere once #1659 is resolved. attribute [congr] dif_ctx_simp_congr attribute [simp] dif_pos dif_neg namespace certigrad namespace T open list axiom const_scalar : ∀ (α : ℝ), const α [] = α attribute [simp] const_scalar axiom const_mul {shape : S} : Π (α β : ℝ), const (α * β) shape = const α shape * const β shape axiom const_neg {shape : S} : Π (α : ℝ), const (- α) shape = - const α shape axiom const_inv {shape : S} : Π (α : ℝ), const α⁻¹ shape = (const α shape)⁻¹ axiom const_zero {shape : S} : const 0 shape = 0 axiom const_one {shape : S} : const 1 shape = 1 axiom const_bit0 {shape : S} : Π (α : ℝ), const (bit0 α) shape = bit0 (const α shape) axiom const_bit1 {shape : S} : Π (α : ℝ), const (bit1 α) shape = bit1 (const α shape) --attribute [simp] const_mul const_neg const_inv const_zero const_one const_bit0 const_bit1 -- Module structure axiom smul.def (α : ℝ) (shape : S) (x : T shape) : α ⬝ x = const α shape * x axiom smul_neg (α : ℝ) : ∀ {shape : S} (x : T shape), α ⬝ (- x) = - (α ⬝ x) axiom smul_addr (α : ℝ) : ∀ (shape : S) (x y : T shape), α ⬝ (x + y) = α ⬝ x + α ⬝ y axiom smul_addl (α β : ℝ) : ∀ (shape : S) (x : T shape), (α + β) ⬝ x = α ⬝ x + β ⬝ x axiom smul_group (α β : ℝ) : ∀ (shape : S) (x : T shape), (α * β) ⬝ x = α ⬝ (β ⬝ x) axiom smul_flip (α β : ℝ) : ∀ (shape : S) (x : T shape), α ⬝ (β ⬝ x) = β ⬝ (α ⬝ x) axiom one_smul : ∀ (shape : S) (x : T shape), (1 : ℝ) ⬝ x = x axiom smul_zero (α : ℝ) : ∀ (shape : S), α ⬝ (0 : T shape) = 0 axiom zero_smul : ∀ (shape : S) (x : T shape), (0 : ℝ) ⬝ x = 0 axiom smul_mul_scalar_right (α : ℝ) : ∀ (x y : ℝ), α ⬝ (x * y) = x ⬝ (α ⬝ y) axiom smul_mul₁ (α : ℝ) : ∀ {shape : S} (x y : T shape), y * (α ⬝ x) = α ⬝ (x * y) axiom smul_mul₂ (α : ℝ) : ∀ {shape : S} (x y : T shape), (α ⬝ x) * y = α ⬝ (x * y) axiom smul_comm (α β : ℝ) : α ⬝ β = β ⬝ α axiom smul_sum {shape : S} (α : ℝ) (x : T shape) : α ⬝ sum x = sum (α ⬝ x) axiom smul_div {shape : S} (α : ℝ) (x y : T shape) : α ⬝ (x / y) = (α ⬝ x) / y axiom smul_scale : ∀ (α : ℝ) (shape : S) (x : T shape), (α ⬝ 1) * x = α ⬝ x axiom smul_scalar : ∀ (α x : ℝ), (α ⬝ x) = α * x -- sum axiom sum_empty_vec (x : T [0]) : sum x = 0 axiom sum_mat_no_cols {nrows : ℕ} (x : T [nrows, 0]) : sum x = 0 axiom sum_zero : Π {shape : S}, sum (0 : T shape) = 0 axiom sum_add {shape : S} (x y : T shape) : sum (x + y) = sum x + sum y axiom sum_neg {shape : S} (x : T shape) : sum (- x) = - (sum x) axiom sum_smul {shape : S} (α : ℝ) (x : T shape) : sum (α ⬝ x) = α * sum x -- Misc axiom sqrt_mul {shape : S} : ∀ (x y : T shape), sqrt (x * y) = sqrt x * sqrt y axiom sqrt_square {shape : S} : ∀ (x : T shape), sqrt (square x) = x axiom prod_mul {shape : S} : ∀ (x y : T shape), prod (x * y) = prod x * prod y axiom mul_inv_pos {shape : S} : ∀ {x y : T shape}, x > 0 → y > 0 → (x * y)⁻¹ = x⁻¹ * y⁻¹ axiom inv_mul_cancel {shape : S} : ∀ {x : T shape}, x > 0 → (x⁻¹ * x) = 1 axiom mul_inv_cancel {shape : S} : ∀ {x : T shape}, x > 0 → (x * x⁻¹) = 1 axiom div_one {shape : S} : ∀ {x : T shape}, x / 1 = x axiom log_one {shape : S} : log (1 : T shape) = (0 : T shape) axiom log_const {shape : S} (α : ℝ) : log (const α shape) = const (log α) shape axiom exp_inv {shape : S} (x : T shape) : (exp x)⁻¹ = exp (- x) axiom neg_div : ∀ {shape : S} {x y : T shape}, -x / y = -(x / y) axiom log_prod : ∀ {shape : S} {x : T shape}, x > 0 → log (prod x) = sum (log x) axiom log_mul : ∀ {shape : S} {x y : T shape}, x > 0 → y > 0 → log (x * y) = log x + log y axiom log_exp : ∀ {shape : S} {x : T shape}, log (exp x) = x axiom log_sqrt : ∀ {shape : S} {x : T shape}, log (sqrt x) = 2⁻¹ * log x axiom log_inv : ∀ {shape : S} {x : T shape}, log (x⁻¹) = - log x -- Signs axiom nz_of_pos {shape : S} : ∀ {x : T shape}, x > 0 → x ≠ 0 axiom nz_of_div {shape : S} : ∀ {x y : T shape}, x ≠ 0 → y ≠ 0 → x / y ≠ 0 axiom nz_iff {shape : S} : ∀ {x : T shape}, x ≠ 0 ↔ x > 0 ∨ x < 0 axiom nneg_of_pos {shape : S} : ∀ {x : T shape}, x > 0 → x ≥ 0 axiom sqrt_pos {shape : S} : ∀ {x : T shape}, x > 0 → sqrt x > 0 axiom pos_of_sqrt_pos {shape : S} : ∀ {x : T shape}, sqrt x > 0 → x > 0 axiom square_nneg {shape : S} : ∀ {x : T shape}, square x ≥ 0 axiom square_pos_of_pos {shape : S} : ∀ {x : T shape}, 0 < x → 0 < square x axiom square_pos_of_neg {shape : S} : ∀ {x : T shape}, x < 0 → 0 < square x axiom exp_pos {shape : S} : ∀ {x : T shape}, exp x > 0 axiom sigmoid_pos {shape : S} : ∀ {x : T shape}, sigmoid x > 0 axiom sigmoid_lt1 {shape : S} : ∀ {x : T shape}, sigmoid x < 1 axiom lt1_alt {shape : S} : ∀ {x : T shape}, x < 1 → 0 < 1 - x axiom one_plus_pos {shape : S} : ∀ {x : T shape}, x > 0 → 1 + x > 0 axiom one_plus_pos_iff {shape : S} : ∀ {x : T shape}, 0 < 1 + x ↔ (- 1 < x) axiom plus_one_pos {shape : S} : ∀ {x : T shape}, x > 0 → x + 1 > 0 axiom one_pos {shape : S} : (1 : T shape) > 0 axiom neg_of_pos {shape : S} {x : T shape} : x > 0 → - x < 0 axiom const_pos_of_pos {shape : S} {x : ℝ} : x > 0 → const x shape > 0 axiom mul_pos_of_pos_pos {shape : S} {x y : T shape} : x > 0 → y > 0 → x * y > 0 axiom eps_pos {shape : S} : eps shape > 0 axiom pi_pos {shape : S} : pi shape > 0 axiom inv_pos {shape : S} {x : T shape} : x > 0 → x⁻¹ > 0 axiom div_pos_pos {shape : S} {x y : T shape} : x > 0 → y > 0 → x / y > 0 axiom add_pos_of_pos_pos {shape : S} {x y : T shape} : x > 0 → y > 0 → x + y > 0 lemma two_pos {shape : S} : (2 : T shape) > 0 := one_plus_pos one_pos lemma two_pi_pos {shape : S} : 2 * pi shape > 0 := mul_pos_of_pos_pos two_pos pi_pos lemma msigmoid_pos {shape : S} {x : T shape} : 0 < 1 - sigmoid x := lt1_alt sigmoid_lt1 -- div axiom div_mul_cancel {shape : S} : ∀ {x y : T shape}, y > 0 → (x / y) * y = x axiom div_div_eq_div_mul {shape : S} : ∀ (x y z : T shape), (x / y) / z = x / (y * z) axiom div_mul_div {shape : S} : ∀ (x y z w : T shape), (x / y) * (z / w) = (x * z) / (y * w) axiom mul_div_mul {shape : S} : ∀ (x y z : T shape), x * (y / z) = (x / z) * y axiom mul_div_mul_alt {shape : S} : ∀ (x y z : T shape), x * (y / z) = (x * y / z) axiom one_div_inv {shape : S} : ∀ (x : T shape), 1 / x = x⁻¹ axiom div_mul_inv {shape : S} : ∀ (x y : T shape), x / y = x * y⁻¹ axiom div_self {shape : S} : ∀ {x : T shape}, x > 0 → x / x = 1 axiom square_div {shape : S} : ∀ {x y : T shape}, square (x / y) = square x / square y axiom div_add_div_same {shape : S} (x y z : T shape) : x / z + y / z = (x + y) / z lemma div_add_div_same_symm {shape : S} (x y z : T shape) : (x + y) / z = x / z + y / z := by rw div_add_div_same lemma div_sub_div_same {shape : S} (x y z : T shape) : x / z - y / z = (x - y) / z := by simp [T.div_add_div_same_symm, neg_div] lemma div_sub_div_same_symm {shape : S} (x y z : T shape) : (x - y) / z = x / z - y / z := by rw div_sub_div_same lemma div_self_square {shape : S} {x : T shape} (H_pos : x > 0) : x / (x * x)= x⁻¹ := calc x / (x * x) = (x / x) / x : by rw -div_div_eq_div_mul ... = 1 / x : by rw div_self H_pos ... = x⁻¹ : by rw one_div_inv -- integrable axiom is_integrable_const : Π {shape₁ shape₂ : S} (c : T shape₂), is_integrable (λ (x : T shape₁), c) lemma is_integrable_zero {shape₁ shape₂ : S} : is_integrable (λ (x : T shape₁), (0 : T shape₂)) := is_integrable_const (0 : T shape₂) axiom is_integrable_scale : Π {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) (α : ℝ), is_integrable f ↔ is_integrable (λ x, α ⬝ f x) axiom is_integrable_neg : Π {shape₁ shape₂ : S} (f : T shape₁ → T shape₂), is_integrable f ↔ is_integrable (λ x, - f x) axiom is_integrable_div : Π {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) (y : T shape₂) (Hy : y > 0), is_integrable f ↔ is_integrable (λ x, (f x) / y) axiom is_integrable_add : Π {shape₁ shape₂ : S} (f g : T shape₁ → T shape₂), (is_integrable f ∧ is_integrable g) ↔ is_integrable (λ x, f x + g x) axiom is_integrable_tmulT {ishape oshape fshape : S} (M : T (ishape ++ oshape)) (f : T fshape → T oshape) : is_integrable f ↔ is_integrable (λ x, tmulT M (f x)) axiom is_integrable_sum : Π {shape₁ shape₂ : S} (f : T shape₁ → T shape₂), (is_integrable f) ↔ is_integrable (λ x, sum (f x)) axiom is_integrable_fscale : Π {shape₁ shape₂ : S} (f : T shape₁ → ℝ) (y : T shape₂), is_integrable f ↔ is_integrable (λ x, f x ⬝ y) -- (provable) axiom is_integrable_const_middle : Π {shape₁ shape₂ : S} (pdf : T shape₁ → ℝ) (c : T shape₂), is_integrable (λ (x : T shape₁), pdf x) ↔ is_integrable (λ (x : T shape₁), pdf x ⬝ c) axiom is_integrable_add_middle : Π {shape₁ shape₂ : S} (pdf : T shape₁ → ℝ) (f g : T shape₁ → T shape₂), (is_integrable (λ (x : T shape₁), pdf x ⬝ f x) ∧ is_integrable (λ (x : T shape₁), pdf x ⬝ g x)) ↔ is_integrable (λ (x : T shape₁), pdf x ⬝ (f x + g x)) -- (provable) axiom is_integrable_tmulT_middle {ishape oshape fshape : S} (M : T (ishape ++ oshape)) (pdf : T fshape → ℝ) (f : T fshape → T oshape) : is_integrable (λ (x : T fshape), pdf x ⬝ f x) ↔ is_integrable (λ (x : T fshape), pdf x ⬝ tmulT M (f x)) -- uniformly integrable axiom is_uniformly_integrable_around_binary : Π {shape₁ shape₂ shape₃ : S} (f : T shape₁ → T shape₁ → T shape₂ → T shape₃) (θ : T shape₁), (is_uniformly_integrable_around (λ θ₀ x, f θ₀ θ x) θ ∧ is_uniformly_integrable_around (λ θ₀ x, f θ θ₀ x) θ) ↔ is_uniformly_integrable_around (λ θ₀ x, f θ₀ θ₀ x) θ lemma uint_left {shape₁ shape₂ shape₃ : S} (f : T shape₁ → T shape₁ → T shape₂ → T shape₃) (θ : T shape₁) : is_uniformly_integrable_around (λ θ₀ x, f θ₀ θ₀ x) θ → is_uniformly_integrable_around (λ θ₀ x, f θ₀ θ x) θ := assume H_uint, (iff.mpr (is_uniformly_integrable_around_binary f θ) H_uint)^.left lemma uint_right {shape₁ shape₂ shape₃ : S} (f : T shape₁ → T shape₁ → T shape₂ → T shape₃) (θ : T shape₁) : is_uniformly_integrable_around (λ θ₀ x, f θ₀ θ₀ x) θ → is_uniformly_integrable_around (λ θ₀ x, f θ θ₀ x) θ := assume H_uint, (iff.mpr (is_uniformly_integrable_around_binary f θ) H_uint)^.right -- (provable) axiom is_uniformly_integrable_around_binary_grad : Π {shape₁ shape₂ : S} (f₁ f₂ : T shape₁ → T shape₂ → ℝ) (θ : T shape₁), (∀ x, is_cdifferentiable (λ θ₀, f₁ θ₀ x) θ) → (∀ x, is_cdifferentiable (λ θ₀, f₂ θ₀ x) θ) → (is_uniformly_integrable_around (λ θ₀ x, f₂ θ₀ x ⬝ ∇ (λ θ₁, f₁ θ₁ x) θ₀) θ ∧ is_uniformly_integrable_around (λ θ₀ x, f₁ θ₀ x ⬝ ∇ (λ θ₁, f₂ θ₁ x) θ₀) θ ↔ is_uniformly_integrable_around (λ θ₀ x, ∇ (λ θ₁, f₁ θ₁ x ⬝ f₂ θ₁ x) θ₀) θ) lemma uint_grad_left {shape₁ shape₂ : S} (f₁ f₂ : T shape₁ → T shape₂ → ℝ) (θ : T shape₁) : (∀ x, is_cdifferentiable (λ θ₀, f₁ θ₀ x) θ) → (∀ x, is_cdifferentiable (λ θ₀, f₂ θ₀ x) θ) → is_uniformly_integrable_around (λ θ₀ x, ∇ (λ θ₁, f₁ θ₁ x ⬝ f₂ θ₁ x) θ₀) θ → is_uniformly_integrable_around (λ θ₀ x, f₂ θ₀ x ⬝ ∇ (λ θ₁, f₁ θ₁ x) θ₀) θ := assume H_cdiff₁ H_cdiff₂ H_uint_grad, (iff.mpr (is_uniformly_integrable_around_binary_grad f₁ f₂ θ H_cdiff₁ H_cdiff₂) H_uint_grad)^.left lemma uint_grad_right {shape₁ shape₂ : S} (f₁ f₂ : T shape₁ → T shape₂ → ℝ) (θ : T shape₁) : (∀ x, is_cdifferentiable (λ θ₀, f₁ θ₀ x) θ) → (∀ x, is_cdifferentiable (λ θ₀, f₂ θ₀ x) θ) → is_uniformly_integrable_around (λ θ₀ x, ∇ (λ θ₁, f₁ θ₁ x ⬝ f₂ θ₁ x) θ₀) θ → is_uniformly_integrable_around (λ θ₀ x, f₁ θ₀ x ⬝ ∇ (λ θ₁, f₂ θ₁ x) θ₀) θ := assume H_cdiff₁ H_cdiff₂ H_uint_grad, (iff.mpr (is_uniformly_integrable_around_binary_grad f₁ f₂ θ H_cdiff₁ H_cdiff₂) H_uint_grad)^.right -- integrals axiom integral_scale : Π {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) (α : ℝ), ∫ (λ x, α ⬝ f x) = α ⬝ ∫ (λ x, f x) axiom integral_neg : Π {shape₁ shape₂ : S} (f : T shape₁ → T shape₂), ∫ (λ x, - (f x)) = - ∫ (λ x, f x) axiom integral_div : Π {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) (y : T shape₂), ∫ (λ x, (f x) / y) = ∫ (λ x, f x) / y axiom integral_add : Π {shape₁ shape₂ : S} (f g : T shape₁ → T shape₂), is_integrable f → is_integrable g → ∫ (λ x, f x + g x) = ∫ (λ x, f x) + ∫ (λ x, g x) axiom integral_fscale : Π {shape₁ shape₂ : S} (f : T shape₁ → ℝ) (y : T shape₂), ∫ (λ x, f x ⬝ y) = ∫ (λ x, f x) ⬝ y axiom integral_pos : ∀ {shape₁ shape₂ : S} (f : T shape₁ → T shape₂), (∀ x, f x > 0) → ∫ (λ x, f x) > 0 axiom integral_nneg : ∀ {shape₁ shape₂ : S} (f : T shape₁ → T shape₂), (∀ x, f x ≥ 0) → ∫ (λ x, f x) ≥ 0 lemma integral_congr {shape₁ shape₂ : S} (f g : T shape₁ → T shape₂) (H_fg : ∀ x, f x = g x) : ∫ f = ∫ g := show ∫ (λ x, f x) = ∫ (λ x, g x), by rw (funext H_fg) axiom integral_sum : Π {shape₁ shape₂ : S} (f : T shape₁ → T shape₂), is_integrable f → ∫ (λ x, sum (f x)) = sum (∫ (λ x, f x)) axiom smul_tmulT {ishape oshape : S} (α : ℝ) (M : T (ishape ++ oshape)) (y : T oshape) : α ⬝ (tmulT M y) = tmulT M (α ⬝ y) axiom integral_tmulT {ishape oshape fshape : S} (M : T (ishape ++ oshape)) (f : T fshape → T oshape) : ∫ (λ x, tmulT M (f x)) = tmulT M (∫ f) axiom integral_continuous : ∀ {ishape tshape fshape : S} (f : T ishape → T tshape → T fshape) (θ : T tshape), (∀ x, is_continuous (f x) θ) → is_continuous (λ θ₀, ∫ (λ x₀, f x₀ θ₀)) θ -- D axiom tmulT_scalar {shape : S} : ∀ (x : T (shape ++ [])) (y : ℝ), tmulT x y = y ⬝ (eq.rec_on (append_nil shape) x) axiom D_scalar {shape : S} (f : T shape → ℝ) (θ : T shape) : (eq.rec_on (append_nil shape) (D f θ) : T shape) = ∇ f θ -- dintegral lemma dintegral_pos {oshape : S} : Π {shapes : list S} {f : dvec T shapes → T oshape}, (∀ x, f x > 0) → dintegral (λ x, f x) > 0 | [] f H := by apply H | (shape::shapes) f H := begin dunfold dintegral, apply integral_pos, intro x, apply dintegral_pos, intro xs, apply H, end lemma dintegral_scale {shape : S} (α : ℝ) : Π {shapes : list S} (f : dvec T shapes → T shape), dintegral (λ (xs : dvec T shapes), α ⬝ f xs) = α ⬝ dintegral (λ xs, f xs) | [] f := rfl | (ds::shapes) f := begin dunfold dintegral, simp [λ x, @dintegral_scale shapes (λ v, f (x ::: v))], rw integral_scale, end lemma is_dintegrable_scale {oshape : S} : Π {shapes : list S} (f : dvec T shapes → T oshape) (α : ℝ), is_dintegrable f ↔ is_dintegrable (λ x, α ⬝ f x) | [] f α := begin split, all_goals { intro, exact trivial } end | (shape::shapes) f α := begin dunfold dintegral is_dintegrable, split, { intro Hf, split, { simp only [dintegral_scale], exact iff.mp (is_integrable_scale _ α) Hf^.left }, { intro x, exact iff.mp (is_dintegrable_scale _ _) (Hf^.right x) } }, { intro Hαf, split, { simp only [dintegral_scale] at Hαf, exact iff.mpr (is_integrable_scale _ α) Hαf^.left }, { intro x, exact iff.mpr (is_dintegrable_scale _ _) (Hαf^.right x) } } end lemma dintegral_add {shape : S} : Π {shapes : list S} (f g : dvec T shapes → T shape), is_dintegrable f → is_dintegrable g → dintegral (λ (xs : dvec T shapes), f xs + g xs) = dintegral (λ (xs : dvec T shapes), f xs) + dintegral (λ (xs : dvec T shapes), g xs) | [] f g Hf Hg := rfl | (ds::shapes) f g Hf Hg := begin dunfold dintegral, simp [λ x, @dintegral_add shapes (λ v, f (x ::: v)) (λ v, g (x :::v)) (Hf^.right x) (Hg^.right x)], rw integral_add _ _ Hf^.left Hg^.left end lemma dintegral_div {shape : S} : Π {shapes : list S} (f : dvec T shapes → T shape) (y : T shape), dintegral (λ (xs : dvec T shapes), (f xs) / y) = dintegral (λ (xs : dvec T shapes), f xs) / y | [] f y := rfl | (ds::shapes) f y := begin dunfold dintegral, simp [λ x, @dintegral_div shapes (λ v, f (x ::: v)) y], rw integral_div end lemma dintegral_add_middle {shape : S} : Π {shapes : list S} (pdf : dvec T shapes → ℝ) (f g : dvec T shapes → T shape), is_dintegrable (λ xs, pdf xs ⬝ f xs) → is_dintegrable (λ xs, pdf xs ⬝ g xs) → dintegral (λ (xs : dvec T shapes), pdf xs ⬝ (f xs + g xs)) = dintegral (λ (xs : dvec T shapes), pdf xs ⬝ f xs) + dintegral (λ (xs : dvec T shapes), pdf xs ⬝ g xs) | [] pdf f g Hf Hg := begin dunfold dintegral, apply smul_addr end | (ds::shapes) pdf f g Hf Hg := begin dunfold dintegral, simp [λ x, @dintegral_add_middle shapes (λ v, pdf (x ::: v)) (λ v, f (x ::: v)) (λ v, g (x :::v)) (Hf^.right x) (Hg^.right x)], rw integral_add _ _ Hf^.left Hg^.left end lemma dintegral_neg_middle {shape : S} : Π {shapes : list S} (pdf : dvec T shapes → ℝ) (f : dvec T shapes → T shape), dintegral (λ (xs : dvec T shapes), pdf xs ⬝ - (f xs)) = - dintegral (λ (xs : dvec T shapes), pdf xs ⬝ f xs) | [] pdf f := begin dunfold dintegral, apply smul_neg end | (ds::shapes) pdf f := begin dunfold dintegral, simp [λ x, @dintegral_neg_middle shapes (λ v, pdf (x ::: v)) (λ v, f (x ::: v))], rw integral_neg end lemma dintegral_mul (α : ℝ) : Π {shapes : list S} (f : dvec T shapes → ℝ), dintegral (λ (xs : dvec T shapes), α * f xs) = α * dintegral (λ xs, f xs) := begin intros shapes f, rw -(const_scalar α), simp [λ s x, eq.symm (smul.def α s x)], simp [λ α f, eq.symm (smul_scalar α f)], exact (dintegral_scale α f) end lemma dintegral_scale_middle {shape : S} (α : ℝ) : Π {shapes : list S} (f : dvec T shapes → ℝ) (g : dvec T shapes → T shape), dintegral (λ (xs : dvec T shapes), f xs ⬝ (α ⬝ g xs)) = α ⬝ dintegral (λ xs, f xs ⬝ g xs) | [] f g := begin dunfold dintegral, simp [T.smul.def, mul_comm], end | (ds::shapes) f g := begin dunfold dintegral, simp [λ x, @dintegral_scale_middle shapes (λ v, f (x ::: v)) (λ v, g (x ::: v))], rw integral_scale, end lemma dintegral_mul_middle (α : ℝ) : Π {shapes : list S} (f : dvec T shapes → ℝ) (g : dvec T shapes → ℝ), dintegral (λ (xs : dvec T shapes), f xs ⬝ (α * g xs)) = α * dintegral (λ xs, f xs ⬝ g xs) := begin intros shapes f g, rw -(const_scalar α), simp [λ s x, eq.symm (smul.def α s x)], simp [λ xs, eq.symm (smul_scalar α (g xs))], rw dintegral_scale_middle α f g, simp [smul_scalar] end lemma dintegral_tmulT {shape₁ shape₂ : S} (M : T (shape₁ ++ shape₂)) : Π {shapes : list S} (f : dvec T shapes → T shape₂), dintegral (λ (xs : dvec T shapes), tmulT M (f xs)) = tmulT M (dintegral (λ xs, f xs)) | [] f := rfl | (ds::shapes) f := begin dunfold dintegral, simp [λ x, @dintegral_tmulT shapes (λ v, f (x ::: v))], rw integral_tmulT end lemma dintegral_tmulT_middle {shape₁ shape₂ : S} (M : T (shape₁ ++ shape₂)) : Π {shapes : list S} (f : dvec T shapes → ℝ) (g : dvec T shapes → T shape₂), dintegral (λ (xs : dvec T shapes), f xs ⬝ (tmulT M (g xs))) = tmulT M (dintegral (λ xs, f xs ⬝ g xs)) := begin intros shapes f g, simp [smul_tmulT, dintegral_tmulT] end lemma dintegral_const_middle {yshape : S} : ∀ {shapes : list S} (pdf : dvec T shapes → ℝ) (H_pdf_pos : ∀ x, pdf x > 0) (H_pdf_int1 : dintegral pdf = 1) (y : T yshape), dintegral (λ (xs : dvec T shapes), pdf xs ⬝ y) = y | [] pdf H_pdf_pos H_pdf_int1 y := begin dunfold dintegral, dunfold dintegral at H_pdf_int1, rw H_pdf_int1, rw one_smul end | (shape::shapes) pdf H_pdf_pos H_pdf_int1 y := let pdf' : T shape → dvec T shapes → ℝ := λ x (xs : dvec T shapes), pdf (x ::: xs) / dintegral (λ (xs : dvec T shapes), pdf (x ::: xs)) in have H_dpos : ∀ (x : T shape), dintegral (λ (xs : dvec T shapes), pdf (x ::: xs)) > 0, from λ x, dintegral_pos (λ x, H_pdf_pos _), have H_pdf'_pos : ∀ (x : T shape) (xs : dvec T shapes), pdf' x xs > 0, from assume (x : T shape) (xs : dvec T shapes), have H₁ : pdf (x ::: xs) > 0, by apply H_pdf_pos, T.div_pos_pos H₁ (H_dpos x), have H_pdf'_int1 : ∀ (x : T shape), dintegral (pdf' x) = 1, from assume (x : T shape), begin dsimp, rw T.dintegral_div, exact div_self (H_dpos x) end, have H_inner₁ : ∀ (x : T shape), dintegral (λ (v : dvec T shapes), pdf (x ::: v) ⬝ y) = dintegral (λ (v : dvec T shapes), (pdf' x v * dintegral (λ (vs : dvec T shapes), pdf (x ::: vs))) ⬝ y), from assume (x : T shape), begin dsimp, apply congr_arg, apply funext, intro xs, rw (T.div_mul_cancel (H_dpos _)) end, have H_inner₂ : ∀ x, dintegral (λ (v : dvec T shapes), (pdf' x v * dintegral (λ (vs : dvec T shapes), pdf (x ::: vs))) ⬝ y) = dintegral (λ (vs : dvec T shapes), pdf (x ::: vs)) ⬝ dintegral (λ (v : dvec T shapes), pdf' x v ⬝ y), from assume (x : T shape), begin dsimp, simp [smul_group, dintegral_scale] end, begin dunfold dintegral, simp [H_inner₁, H_inner₂, (λ x, @dintegral_const_middle shapes (pdf' x) (H_pdf'_pos x) (H_pdf'_int1 x)), integral_fscale], change dintegral (λ (vs : dvec T (shape::shapes)), pdf vs) ⬝ y = y, rw [H_pdf_int1, one_smul] end -- btw axioms axiom is_btw_id {shape : S} : is_btw_exp₂ (λ (x : T shape), x) axiom is_btw_const {shape₁ shape₂ : S} (y : T shape₂) : is_btw_exp₂ (λ (x : T shape₁), y) axiom is_btw_sigmoid {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) : is_btw_exp₂ (λ (x : T shape₁), sigmoid (f x)) axiom is_btw_softplus {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) : is_btw_exp₂ f → is_btw_exp₂ (λ (x : T shape₁), softplus (f x)) axiom is_btw_sum {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) : is_btw_exp₂ f → is_btw_exp₂ (λ (x : T shape₁), sum (f x)) axiom is_btw_log_sigmoid {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) (y : T shape₂) : y > 0 → is_btw_exp₂ f → is_btw_exp₂ (λ (x : T shape₁), log (y + sigmoid (f x))) axiom is_btw_log_1msigmoid {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) (y : T shape₂) : y > 0 → is_btw_exp₂ f → is_btw_exp₂ (λ (x : T shape₁), log (y + (1 - sigmoid (f x)))) axiom is_btw_gemm {shape : S} {m n p : ℕ} (f : T shape → T [m, n]) (g : T shape → T [n, p]) : is_btw_exp₂ f → is_btw_exp₂ g → is_btw_exp₂ (λ x, gemm (f x) (g x)) axiom is_btw_transpose {shape : S} {m n : ℕ} (f : T shape → T [m, n]) : is_btw_exp₂ f → is_btw_exp₂ (λ x, transpose (f x)) axiom is_btw_neg {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) : is_btw_exp₂ f → is_btw_exp₂ (λ x, - (f x)) axiom is_btw_inv {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) : is_btw_exp₂ f → is_btw_exp₂ (λ x, (f x)⁻¹) axiom is_btw_add {shape₁ shape₂ : S} (f g : T shape₁ → T shape₂) : is_btw_exp₂ f → is_btw_exp₂ g → is_btw_exp₂ (λ x, f x + g x) axiom is_btw_mul {shape₁ shape₂ : S} (f g : T shape₁ → T shape₂) : is_btw_exp₂ f → is_btw_exp₂ g → is_btw_exp₂ (λ x, f x * g x) axiom is_btw_sub {shape₁ shape₂ : S} (f g : T shape₁ → T shape₂) : is_btw_exp₂ f → is_btw_exp₂ g → is_btw_exp₂ (λ x, f x - g x) axiom is_btw_div {shape₁ shape₂ : S} (f g : T shape₁ → T shape₂) : is_btw_exp₂ f → is_btw_exp₂ g → is_btw_exp₂ (λ x, f x / g x) axiom is_btw_exp {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) : is_sub_quadratic f → is_btw_exp₂ (λ x, exp (f x)) -- sub quadratic axioms axiom is_sub_quadratic_id {shape : S} : is_sub_quadratic (λ (x : T shape), x) axiom is_sub_quadratic_const {shape₁ shape₂ : S} (y : T shape₂) : is_sub_quadratic (λ (x : T shape₁), y) axiom is_sub_quadratic_gemm {shape : S} {m n p : ℕ} (f : T shape → T [m, n]) (g : T shape → T [n, p]) : is_sub_quadratic f → is_sub_quadratic g → is_sub_quadratic (λ x, gemm (f x) (g x)) axiom is_sub_quadratic_transpose {shape : S} {m n : ℕ} (f : T shape → T [m, n]) : is_sub_quadratic f → is_sub_quadratic (λ x, transpose (f x)) axiom is_sub_quadratic_softplus {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) : is_sub_quadratic f → is_sub_quadratic (λ x, softplus (f x)) axiom is_sub_quadratic_neg {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) : is_sub_quadratic f → is_sub_quadratic (λ x, - (f x)) axiom is_sub_quadratic_mul₁ {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) (y : T shape₂) : is_sub_quadratic f → is_sub_quadratic (λ x, y * f x) axiom is_sub_quadratic_mul₂ {shape₁ shape₂ : S} (f : T shape₁ → T shape₂) (y : T shape₂) : is_sub_quadratic f → is_sub_quadratic (λ x, f x * y) axiom is_sub_quadratic_add {shape₁ shape₂ : S} (f g : T shape₁ → T shape₂) : is_sub_quadratic f → is_sub_quadratic g → is_sub_quadratic (λ x, f x + g x) axiom is_sub_quadratic_sub {shape₁ shape₂ : S} (f g : T shape₁ → T shape₂) : is_sub_quadratic f → is_sub_quadratic g → is_sub_quadratic (λ x, f x - g x) -- is_bounded_btw_exp₂_around {shape₁ shape₂ shape₃ : S} (f : Π (x : T shape₁) (θ : T shape₂), T shape₃) (θ : T shape₂) : Prop axiom is_bbtw_of_btw {shape₁ shape₂ shape₃ : S} (f : Π (x : T shape₁), T shape₃) (θ : T shape₂) : is_btw_exp₂ f → is_bounded_btw_exp₂_around (λ x θ₀, f x) θ axiom is_bbtw_id {shape₁ shape₂ : S} (θ : T shape₂) : is_bounded_btw_exp₂_around (λ (x : T shape₁) (θ₀ : T shape₂), θ₀) θ axiom is_bbtw_softplus {shape₁ shape₂ shape₃ : S} (f : T shape₁ → T shape₂ → T shape₃) (θ : T shape₂) : is_bounded_btw_exp₂_around f θ → is_bounded_btw_exp₂_around (λ x θ₀, softplus (f x θ₀)) θ axiom is_bbtw_sum {shape₁ shape₂ shape₃ : S} (f : T shape₁ → T shape₂ → T shape₃) (θ : T shape₂) : is_bounded_btw_exp₂_around f θ → is_bounded_btw_exp₂_around (λ x θ₀, sum (f x θ₀)) θ axiom is_bbtw_log_sigmoid {shape₁ shape₂ shape₃ : S} (f : T shape₁ → T shape₂ → T shape₃) (y : T shape₃) (θ : T shape₂) : y > 0 → is_bounded_btw_exp₂_around f θ → is_bounded_btw_exp₂_around (λ x θ₀, log (y + sigmoid (f x θ₀))) θ axiom is_bbtw_log_1msigmoid {shape₁ shape₂ shape₃ : S} (f : T shape₁ → T shape₂ → T shape₃) (y : T shape₃) (θ : T shape₂) : y > 0 → is_bounded_btw_exp₂_around f θ → is_bounded_btw_exp₂_around (λ x θ₀, log (y + (1 - sigmoid (f x θ₀)))) θ axiom is_bbtw_gemm {shape₁ shape₂ : S} {m n p : ℕ} (f : T shape₁ → T shape₂ → T [m, n]) (g : T shape₁ → T shape₂ → T [n, p]) (θ : T shape₂) : is_bounded_btw_exp₂_around f θ → is_bounded_btw_exp₂_around g θ → is_bounded_btw_exp₂_around (λ x θ₀, gemm (f x θ₀) (g x θ₀)) θ axiom is_bbtw_neg {shape₁ shape₂ shape₃ : S} (f : T shape₁ → T shape₂ → T shape₃) (θ : T shape₂) : is_bounded_btw_exp₂_around f θ → is_bounded_btw_exp₂_around (λ x θ₀, - f x θ₀) θ axiom is_bbtw_inv {shape₁ shape₂ shape₃ : S} (f : T shape₁ → T shape₂ → T shape₃) (θ : T shape₂) : is_bounded_btw_exp₂_around f θ → is_bounded_btw_exp₂_around (λ x θ₀, (f x θ₀)⁻¹) θ axiom is_bbtw_add {shape₁ shape₂ shape₃ : S} (f g : T shape₁ → T shape₂ → T shape₃) (θ : T shape₂) : is_bounded_btw_exp₂_around f θ → is_bounded_btw_exp₂_around g θ → is_bounded_btw_exp₂_around (λ x θ₀, f x θ₀ + g x θ₀) θ axiom is_bbtw_sub {shape₁ shape₂ shape₃ : S} (f g : T shape₁ → T shape₂ → T shape₃) (θ : T shape₂) : is_bounded_btw_exp₂_around f θ → is_bounded_btw_exp₂_around g θ → is_bounded_btw_exp₂_around (λ x θ₀, f x θ₀ - g x θ₀) θ axiom is_bbtw_mul {shape₁ shape₂ shape₃ : S} (f g : T shape₁ → T shape₂ → T shape₃) (θ : T shape₂) : is_bounded_btw_exp₂_around f θ → is_bounded_btw_exp₂_around g θ → is_bounded_btw_exp₂_around (λ x θ₀, f x θ₀ * g x θ₀) θ axiom is_bbtw_exp {shape₁ shape₂ shape₃ : S} (f : T shape₁ → T shape₂ → T shape₃) (θ : T shape₂) : is_sub_quadratic (λ x, f x θ) → (∀ x, is_sub_quadratic (f x)) → is_bounded_btw_exp₂_around (λ x θ₀, exp (f x θ₀)) θ lemma is_bbtw_bernoulli_neglogpdf {shape₁ shape₂ shape₃ : S} (f : T shape₁ → T shape₂ → T shape₃) (θ : T shape₂) (p : T shape₃) : is_bounded_btw_exp₂_around f θ → is_bounded_btw_exp₂_around (λ x θ₀, bernoulli_neglogpdf (sigmoid (f x θ₀)) p) θ := begin intro H, dunfold bernoulli_neglogpdf, apply is_bbtw_neg, apply is_bbtw_sum, apply is_bbtw_add, apply is_bbtw_mul, apply is_bbtw_of_btw, apply is_btw_const, apply is_bbtw_log_sigmoid, exact eps_pos, exact H, apply is_bbtw_mul, apply is_bbtw_of_btw, apply is_btw_const, apply is_bbtw_log_1msigmoid, exact eps_pos, exact H end -- misc axiom integral_scale_shift_var {shape fshape : S} (f : T shape → T fshape) (α β : T shape) : ∫ (λ x, f (α * x + β)) = ∫ (λ x, prod α⁻¹ ⬝ f x) @[simp] lemma force_ok {shape : S} (x : T shape) : force x shape = x := by { dunfold force, simp } end T -- helper tactic section tactic open tactic list meta def prove_preconditions_core : tactic unit := first (assumption :: map applyc [`certigrad.T.sqrt_pos, `certigrad.T.square_pos_of_pos, `certigrad.T.exp_pos, `certigrad.T.sigmoid_pos, `certigrad.T.sigmoid_lt1, `certigrad.T.lt1_alt, `certigrad.T.one_plus_pos, `certigrad.T.plus_one_pos, `certigrad.T.one_pos, `certigrad.T.neg_of_pos, `certigrad.T.const_pos_of_pos, `certigrad.T.mul_pos_of_pos_pos, `certigrad.T.add_pos_of_pos_pos, `certigrad.T.pi_pos, `certigrad.T.eps_pos, `certigrad.T.inv_pos, `certigrad.T.div_pos_pos, `certigrad.T.two_pos, `certigrad.T.two_pi_pos]) meta def prove_preconditions : tactic unit := repeat prove_preconditions_core end tactic end certigrad
35fc8bd48bddb09e7c1725d4f65041a26c6bb7af
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/has_reflect_auto.lean
b62fae547f47506f57c4d6e513dbbc7fdd3a7189
[]
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
440
lean
/- Copyright (c) 2017 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sebastian Ullrich -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.expr import Mathlib.Lean3Lib.init.util namespace Mathlib /-- `has_reflect α` lets you produce an `expr` from an instance of α. That is, it is a function from α to expr such that the expr has type α. -/ end Mathlib
02ae393207b9f3194e66de95933858238cb47dff
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/vector_subterm_pred.lean
8e9e75d9c29d9b2b3b84a1f445660fa3cdb914ef
[ "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
2,973
lean
import logic data.nat.basic data.sigma open nat eq.ops sigma inductive vector (A : Type) : nat → Type := | nil : vector A zero | cons : A → (Π{n}, vector A n → vector A (succ n)) namespace vector definition vec (A : Type) : Type := Σ n : nat, vector A n definition to_vec {A : Type} {n : nat} (v : vector A n) : vec A := ⟨n, v⟩ inductive direct_subterm (A : Type) : vec A → vec A → Prop := cons : Π (n : nat) (a : A) (v : vector A n), direct_subterm A (to_vec v) (to_vec (cons a v)) definition direct_subterm.wf (A : Type) : well_founded (direct_subterm A) := well_founded.intro (λ (bv : vec A), sigma.rec_on bv (λ (n : nat) (v : vector A n), vector.rec_on v (show acc (direct_subterm A) (to_vec (nil A)), from acc.intro (to_vec (nil A)) (λ (v₂ : vec A) (H : direct_subterm A v₂ (to_vec (nil A))), have gen : ∀ (bv : vec A) (H : direct_subterm A v₂ bv) (Heq : bv = (to_vec (nil A))), acc (direct_subterm A) v₂, from λ bv H, direct_subterm.induction_on H (λ n₁ a₁ v₁ e, have e₁ : succ n₁ = zero, from sigma.no_confusion e (λ e₁ e₂, e₁), nat.no_confusion e₁), gen (to_vec (nil A)) H rfl)) (λ (a₁ : A) (n₁ : nat) (v₁ : vector A n₁) (ih : acc (direct_subterm A) (to_vec v₁)), acc.intro (to_vec (cons a₁ v₁)) (λ (w₁ : vec A) (lt₁ : direct_subterm A w₁ (to_vec (cons a₁ v₁))), have gen : ∀ (bv : vec A) (H : direct_subterm A w₁ bv) (Heq : bv = (to_vec (cons a₁ v₁))), acc (direct_subterm A) w₁, from λ bv H, direct_subterm.induction_on H (λ n₂ a₂ v₂ e, sigma.no_confusion e (λ (e₁ : succ n₂ = succ n₁) (e₂ : @cons A a₂ n₂ v₂ == @cons A a₁ n₁ v₁), nat.no_confusion e₁ (λ (e₃ : n₂ = n₁), have gen₂ : ∀ (m : nat) (Heq₁ : n₂ = m) (v : vector A m) (ih : acc (direct_subterm A) (to_vec v)) (Heq₂ : @cons A a₂ n₂ v₂ == @cons A a₁ m v), acc (direct_subterm A) (to_vec v₂), from λ m Heq₁, eq.rec_on Heq₁ (λ (v : vector A n₂) (ih : acc (direct_subterm A) (to_vec v)) (Heq₂ : @cons A a₂ n₂ v₂ == @cons A a₁ n₂ v), vector.no_confusion (eq_of_heq Heq₂) (λ (e₄ : a₂ = a₁) (e₅ : n₂ = n₂) (e₆ : v₂ == v), eq.rec_on (eq_of_heq (heq.symm e₆)) ih)), gen₂ n₁ e₃ v₁ ih e₂))), gen (to_vec (cons a₁ v₁)) lt₁ rfl)))) definition direct_subterm.wf₂ (A : Type) : well_founded (direct_subterm A) := begin constructor, intro V, cases V with n v, induction v, repeat (constructor; intro y hlt; cases hlt; repeat assumption) end definition subterm (A : Type) := tc (direct_subterm A) definition subterm.wf (A : Type) : well_founded (subterm A) := tc.wf (direct_subterm.wf A) end vector
949238ace2f6292235dc7f9323e0e40413980304
649957717d58c43b5d8d200da34bf374293fe739
/src/ring_theory/polynomial.lean
9c63b5daf17b5baf1ea24d0ff2e0d716b760ad0a
[ "Apache-2.0" ]
permissive
Vtec234/mathlib
b50c7b21edea438df7497e5ed6a45f61527f0370
fb1848bbbfce46152f58e219dc0712f3289d2b20
refs/heads/master
1,592,463,095,113
1,562,737,749,000
1,562,737,749,000
196,202,858
0
0
Apache-2.0
1,562,762,338,000
1,562,762,337,000
null
UTF-8
Lean
false
false
14,089
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau Ring-theoretic supplement of data.polynomial. Main result: Hilbert basis theorem, that if a ring is noetherian then so is its polynomial ring. -/ import data.polynomial data.mv_polynomial import ring_theory.subring import ring_theory.ideals ring_theory.noetherian universes u v w namespace polynomial variables (R : Type u) [comm_ring R] [decidable_eq R] /-- The `R`-submodule of `R[X]` consisting of polynomials of degree ≤ `n`. -/ def degree_le (n : with_bot ℕ) : submodule R (polynomial R) := ⨅ k : ℕ, ⨅ h : ↑k > n, (lcoeff R k).ker variable {R} theorem mem_degree_le {n : with_bot ℕ} {f : polynomial R} : f ∈ degree_le R n ↔ degree f ≤ n := by simp only [degree_le, submodule.mem_infi, degree_le_iff_coeff_zero, linear_map.mem_ker]; refl theorem degree_le_mono {m n : with_bot ℕ} (H : m ≤ n) : degree_le R m ≤ degree_le R n := λ f hf, mem_degree_le.2 (le_trans (mem_degree_le.1 hf) H) theorem degree_le_eq_span_X_pow {n : ℕ} : degree_le R n = submodule.span R ↑((finset.range (n+1)).image (λ n, X^n) : finset (polynomial R)) := begin apply le_antisymm, { intros p hp, replace hp := mem_degree_le.1 hp, rw [← finsupp.sum_single p, finsupp.sum, submodule.mem_coe], refine submodule.sum_mem _ (λ k hk, _), have := with_bot.coe_le_coe.1 (finset.sup_le_iff.1 hp k hk), rw [single_eq_C_mul_X, C_mul'], refine submodule.smul_mem _ _ (submodule.subset_span $ finset.mem_coe.2 $ finset.mem_image.2 ⟨_, finset.mem_range.2 (nat.lt_succ_of_le this), rfl⟩) }, rw [submodule.span_le, finset.coe_image, set.image_subset_iff], intros k hk, apply mem_degree_le.2, apply le_trans (degree_X_pow_le _) (with_bot.coe_le_coe.2 $ nat.le_of_lt_succ $ finset.mem_range.1 hk) end /-- Given a polynomial, return the polynomial whose coefficients are in the ring closure of the original coefficients. -/ def restriction (p : polynomial R) : polynomial (ring.closure (↑p.frange : set R)) := ⟨p.support, λ i, ⟨p.to_fun i, if H : p.to_fun i = 0 then H.symm ▸ is_add_submonoid.zero_mem _ else ring.subset_closure $ finsupp.mem_frange.2 ⟨H, i, rfl⟩⟩, λ i, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ H, subtype.eq H, subtype.mk.inj⟩)⟩ @[simp] theorem coeff_restriction {p : polynomial R} {n : ℕ} : ↑(coeff (restriction p) n) = coeff p n := rfl @[simp] theorem coeff_restriction' {p : polynomial R} {n : ℕ} : (coeff (restriction p) n).1 = coeff p n := rfl @[simp] theorem degree_restriction {p : polynomial R} : (restriction p).degree = p.degree := rfl @[simp] theorem nat_degree_restriction {p : polynomial R} : (restriction p).nat_degree = p.nat_degree := rfl @[simp] theorem monic_restriction {p : polynomial R} : monic (restriction p) ↔ monic p := ⟨λ H, congr_arg subtype.val H, λ H, subtype.eq H⟩ @[simp] theorem restriction_zero : restriction (0 : polynomial R) = 0 := rfl @[simp] theorem restriction_one : restriction (1 : polynomial R) = 1 := ext.2 $ λ i, subtype.eq $ by rw [coeff_restriction', coeff_one, coeff_one]; split_ifs; refl variables {S : Type v} [comm_ring S] {f : R → S} {x : S} theorem eval₂_restriction {p : polynomial R} : eval₂ f x p = eval₂ (f ∘ subtype.val) x p.restriction := rfl section to_subring variables (p : polynomial R) (T : set R) [is_subring T] /-- Given a polynomial `p` and a subring `T` that contains the coefficients of `p`, return the corresponding polynomial whose coefficients are in `T. -/ def to_subring (hp : ↑p.frange ⊆ T) : polynomial T := ⟨p.support, λ i, ⟨p.to_fun i, if H : p.to_fun i = 0 then H.symm ▸ is_add_submonoid.zero_mem _ else hp $ finsupp.mem_frange.2 ⟨H, i, rfl⟩⟩, λ i, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ H, subtype.eq H, subtype.mk.inj⟩)⟩ variables (hp : ↑p.frange ⊆ T) include hp @[simp] theorem coeff_to_subring {n : ℕ} : ↑(coeff (to_subring p T hp) n) = coeff p n := rfl @[simp] theorem coeff_to_subring' {n : ℕ} : (coeff (to_subring p T hp) n).1 = coeff p n := rfl @[simp] theorem degree_to_subring : (to_subring p T hp).degree = p.degree := rfl @[simp] theorem nat_degree_to_subring : (to_subring p T hp).nat_degree = p.nat_degree := rfl @[simp] theorem monic_to_subring : monic (to_subring p T hp) ↔ monic p := ⟨λ H, congr_arg subtype.val H, λ H, subtype.eq H⟩ omit hp @[simp] theorem to_subring_zero : to_subring (0 : polynomial R) T (set.empty_subset _) = 0 := rfl @[simp] theorem to_subring_one : to_subring (1 : polynomial R) T (set.subset.trans (finset.coe_subset.2 finsupp.frange_single) (set.singleton_subset_iff.2 (is_submonoid.one_mem _))) = 1 := ext.2 $ λ i, subtype.eq $ by rw [coeff_to_subring', coeff_one, coeff_one]; split_ifs; refl end to_subring variables (T : set R) [is_subring T] /-- Given a polynomial whose coefficients are in some subring, return the corresponding polynomial whose coefificents are in the ambient ring. -/ def of_subring (p : polynomial T) : polynomial R := ⟨p.support, subtype.val ∘ p.to_fun, λ n, finsupp.mem_support_iff.trans (not_iff_not_of_iff ⟨λ h, congr_arg subtype.val h, λ h, subtype.eq h⟩)⟩ @[simp] theorem frange_of_subring {p : polynomial T} : ↑(p.of_subring T).frange ⊆ T := λ y H, let ⟨hy, x, hx⟩ := finsupp.mem_frange.1 H in hx ▸ (p.to_fun x).2 end polynomial variables {R : Type u} [comm_ring R] [decidable_eq R] namespace ideal open polynomial /-- Transport an ideal of `R[X]` to an `R`-submodule of `R[X]`. -/ def of_polynomial (I : ideal (polynomial R)) : submodule R (polynomial R) := { carrier := I.carrier, zero := I.zero_mem, add := λ _ _, I.add_mem, smul := λ c x H, by rw [← C_mul']; exact submodule.smul_mem _ _ H } variables {I : ideal (polynomial R)} theorem mem_of_polynomial (x) : x ∈ I.of_polynomial ↔ x ∈ I := iff.rfl variables (I) /-- Given an ideal `I` of `R[X]`, make the `R`-submodule of `I` consisting of polynomials of degree ≤ `n`. -/ def degree_le (n : with_bot ℕ) : submodule R (polynomial R) := degree_le R n ⊓ I.of_polynomial /-- Given an ideal `I` of `R[X]`, make the ideal in `R` of leading coefficients of polynomials in `I` with degree ≤ `n`. -/ def leading_coeff_nth (n : ℕ) : ideal R := (I.degree_le n).map $ lcoeff R n theorem mem_leading_coeff_nth (n : ℕ) (x) : x ∈ I.leading_coeff_nth n ↔ ∃ p ∈ I, degree p ≤ n ∧ leading_coeff p = x := begin simp only [leading_coeff_nth, degree_le, submodule.mem_map, lcoeff_apply, submodule.mem_inf, mem_degree_le], split, { rintro ⟨p, ⟨hpdeg, hpI⟩, rfl⟩, cases lt_or_eq_of_le hpdeg with hpdeg hpdeg, { refine ⟨0, I.zero_mem, lattice.bot_le, _⟩, rw [leading_coeff_zero, eq_comm], exact coeff_eq_zero_of_degree_lt hpdeg }, { refine ⟨p, hpI, le_of_eq hpdeg, _⟩, rw [leading_coeff, nat_degree, hpdeg], refl } }, { rintro ⟨p, hpI, hpdeg, rfl⟩, have : nat_degree p + (n - nat_degree p) = n, { exact nat.add_sub_cancel' (nat_degree_le_of_degree_le hpdeg) }, refine ⟨p * X ^ (n - nat_degree p), ⟨_, I.mul_mem_right hpI⟩, _⟩, { apply le_trans (degree_mul_le _ _) _, apply le_trans (add_le_add' (degree_le_nat_degree) (degree_X_pow_le _)) _, rw [← with_bot.coe_add, this], exact le_refl _ }, { rw [leading_coeff, ← coeff_mul_X_pow p (n - nat_degree p), this] } } end theorem mem_leading_coeff_nth_zero (x) : x ∈ I.leading_coeff_nth 0 ↔ C x ∈ I := (mem_leading_coeff_nth _ _ _).trans ⟨λ ⟨p, hpI, hpdeg, hpx⟩, by rwa [← hpx, leading_coeff, nat.eq_zero_of_le_zero (nat_degree_le_of_degree_le hpdeg), ← eq_C_of_degree_le_zero hpdeg], λ hx, ⟨C x, hx, degree_C_le, leading_coeff_C x⟩⟩ theorem leading_coeff_nth_mono {m n : ℕ} (H : m ≤ n) : I.leading_coeff_nth m ≤ I.leading_coeff_nth n := begin intros r hr, simp only [submodule.mem_coe, mem_leading_coeff_nth] at hr ⊢, rcases hr with ⟨p, hpI, hpdeg, rfl⟩, refine ⟨p * X ^ (n - m), I.mul_mem_right hpI, _, leading_coeff_mul_X_pow⟩, refine le_trans (degree_mul_le _ _) _, refine le_trans (add_le_add' hpdeg (degree_X_pow_le _)) _, rw [← with_bot.coe_add, nat.add_sub_cancel' H], exact le_refl _ end /-- Given an ideal `I` in `R[X]`, make the ideal in `R` of the leading coefficients in `I`. -/ def leading_coeff : ideal R := ⨆ n : ℕ, I.leading_coeff_nth n theorem mem_leading_coeff (x) : x ∈ I.leading_coeff ↔ ∃ p ∈ I, polynomial.leading_coeff p = x := begin rw [leading_coeff, submodule.mem_supr_of_directed], simp only [mem_leading_coeff_nth], { split, { rintro ⟨i, p, hpI, hpdeg, rfl⟩, exact ⟨p, hpI, rfl⟩ }, rintro ⟨p, hpI, rfl⟩, exact ⟨nat_degree p, p, hpI, degree_le_nat_degree, rfl⟩ }, { exact ⟨0⟩ }, intros i j, exact ⟨i + j, I.leading_coeff_nth_mono (nat.le_add_right _ _), I.leading_coeff_nth_mono (nat.le_add_left _ _)⟩ end theorem is_fg_degree_le [is_noetherian_ring R] (n : ℕ) : submodule.fg (I.degree_le n) := is_noetherian_submodule_left.1 (is_noetherian_of_fg_of_noetherian _ ⟨_, degree_le_eq_span_X_pow.symm⟩) _ end ideal /-- Hilbert basis theorem. -/ theorem is_noetherian_ring_polynomial [is_noetherian_ring R] : is_noetherian_ring (polynomial R) := ⟨assume I : ideal (polynomial R), let L := I.leading_coeff in let M := well_founded.min (is_noetherian_iff_well_founded.1 (by apply_instance)) (set.range I.leading_coeff_nth) (set.ne_empty_of_mem ⟨0, rfl⟩) in have hm : M ∈ set.range I.leading_coeff_nth := well_founded.min_mem _ _ _, let ⟨N, HN⟩ := hm, ⟨s, hs⟩ := I.is_fg_degree_le N in have hm2 : ∀ k, I.leading_coeff_nth k ≤ M := λ k, or.cases_on (le_or_lt k N) (λ h, HN ▸ I.leading_coeff_nth_mono h) (λ h x hx, classical.by_contradiction $ λ hxm, have ¬M < I.leading_coeff_nth k, by refine well_founded.not_lt_min well_founded_submodule_gt _ _ _; exact ⟨k, rfl⟩, this ⟨HN ▸ I.leading_coeff_nth_mono (le_of_lt h), λ H, hxm (H hx)⟩), have hs2 : ∀ {x}, x ∈ I.degree_le N → x ∈ ideal.span (↑s : set (polynomial R)), from hs ▸ λ x hx, submodule.span_induction hx (λ _ hx, ideal.subset_span hx) (ideal.zero_mem _) (λ _ _, ideal.add_mem _) (λ c f hf, f.C_mul' c ▸ ideal.mul_mem_left _ hf), ⟨s, le_antisymm (ideal.span_le.2 $ λ x hx, have x ∈ I.degree_le N, from hs ▸ submodule.subset_span hx, this.2) $ begin change I ≤ ideal.span ↑s, intros p hp, generalize hn : p.nat_degree = k, induction k using nat.strong_induction_on with k ih generalizing p, cases le_or_lt k N, { subst k, refine hs2 ⟨polynomial.mem_degree_le.2 (le_trans polynomial.degree_le_nat_degree $ with_bot.coe_le_coe.2 h), hp⟩ }, { have hp0 : p ≠ 0, { rintro rfl, cases hn, exact nat.not_lt_zero _ h }, have : (0 : R) ≠ 1, { intro h, apply hp0, ext i, refine (mul_one _).symm.trans _, rw [← h, mul_zero], refl }, letI : nonzero_comm_ring R := { zero_ne_one := this, ..(infer_instance : comm_ring R) }, have : p.leading_coeff ∈ I.leading_coeff_nth N, { rw HN, exact hm2 k ((I.mem_leading_coeff_nth _ _).2 ⟨_, hp, hn ▸ polynomial.degree_le_nat_degree, rfl⟩) }, rw I.mem_leading_coeff_nth at this, rcases this with ⟨q, hq, hdq, hlqp⟩, have hq0 : q ≠ 0, { intro H, rw [← polynomial.leading_coeff_eq_zero] at H, rw [hlqp, polynomial.leading_coeff_eq_zero] at H, exact hp0 H }, have h1 : p.degree = (q * polynomial.X ^ (k - q.nat_degree)).degree, { rw [polynomial.degree_mul_eq', polynomial.degree_X_pow], rw [polynomial.degree_eq_nat_degree hp0, polynomial.degree_eq_nat_degree hq0], rw [← with_bot.coe_add, nat.add_sub_cancel', hn], { refine le_trans (polynomial.nat_degree_le_of_degree_le hdq) (le_of_lt h) }, rw [polynomial.leading_coeff_X_pow, mul_one], exact mt polynomial.leading_coeff_eq_zero.1 hq0 }, have h2 : p.leading_coeff = (q * polynomial.X ^ (k - q.nat_degree)).leading_coeff, { rw [← hlqp, polynomial.leading_coeff_mul_X_pow] }, have := polynomial.degree_sub_lt h1 hp0 h2, rw [polynomial.degree_eq_nat_degree hp0] at this, rw ← sub_add_cancel p (q * polynomial.X ^ (k - q.nat_degree)), refine (ideal.span ↑s).add_mem _ ((ideal.span ↑s).mul_mem_right _), { by_cases hpq : p - q * polynomial.X ^ (k - q.nat_degree) = 0, { rw hpq, exact ideal.zero_mem _ }, refine ih _ _ (I.sub_mem hp (I.mul_mem_right hq)) rfl, rwa [polynomial.degree_eq_nat_degree hpq, with_bot.coe_lt_coe, hn] at this }, exact hs2 ⟨polynomial.mem_degree_le.2 hdq, hq⟩ } end⟩⟩ theorem is_noetherian_ring_mv_polynomial_fin {n : ℕ} [is_noetherian_ring R] : is_noetherian_ring (mv_polynomial (fin n) R) := begin induction n with n ih, { exact is_noetherian_ring_of_ring_equiv R ((mv_polynomial.pempty_ring_equiv R).symm.trans $ mv_polynomial.ring_equiv_of_equiv _ ⟨pempty.elim, fin.elim0, λ x, pempty.elim x, λ x, fin.elim0 x⟩) }, exact @is_noetherian_ring_of_ring_equiv (polynomial (mv_polynomial (fin n) R)) _ (mv_polynomial (fin (n+1)) R) _ ((mv_polynomial.option_equiv_left _ _).symm.trans (mv_polynomial.ring_equiv_of_equiv _ ⟨λ x, option.rec_on x 0 fin.succ, λ x, fin.cases none some x, by rintro ⟨none | x⟩; [refl, exact fin.cases_succ _], λ x, fin.cases rfl (λ i, show (option.rec_on (fin.cases none some (fin.succ i) : option (fin n)) 0 fin.succ : fin n.succ) = _, by rw fin.cases_succ) x⟩)) (@@is_noetherian_ring_polynomial _ _ ih) end theorem is_noetherian_ring_mv_polynomial_of_fintype {σ : Type v} [fintype σ] [decidable_eq σ] [is_noetherian_ring R] : is_noetherian_ring (mv_polynomial σ R) := trunc.induction_on (fintype.equiv_fin σ) $ λ e, @is_noetherian_ring_of_ring_equiv (mv_polynomial (fin (fintype.card σ)) R) _ _ _ (mv_polynomial.ring_equiv_of_equiv _ e.symm) is_noetherian_ring_mv_polynomial_fin
cfdc0c35e23a4b7181f478c66f65de30648eff42
6b2a480f27775cba4f3ae191b1c1387a29de586e
/group_rep1/Projection/test_linear_algebra.lean
913026e76b3f1663d6c60c13918dd95ff6fcc426
[]
no_license
Or7ando/group_representation
a681de2e19d1930a1e1be573d6735a2f0b8356cb
9b576984f17764ebf26c8caa2a542d248f1b50d2
refs/heads/master
1,662,413,107,324
1,590,302,389,000
1,590,302,389,000
258,130,829
0
1
null
null
null
null
UTF-8
Lean
false
false
15,749
lean
import tactic.ring_exp import algebra.module import linear_algebra.basic --infix ` * ` := linear_map.comp namespace Tools.module universes u v v' /-! # Goal : explain how to deal with map between module : for baby user ! * * Linear algebra is one of the first abstract theory seen at school. This tutorial try to answers to * the question : can i make my baby exercice using lean ? * Here we deal with `R-module` and not with `k-vector space` there is nothing different * at the beginning. * This file try to explain the basic command to play with `linear_map` `range` `kernel`. * We also study a special classe of linear endomorphism `Projector` i.e * endomorphism ` p : M →ₗ[R] M` satisfying the relation `p * p = p`. * This classes is important to deal with decomposition a module into `a direct sum`. -/ variables {R : Type u}[comm_ring R]{M : Type v}[add_comm_group M] [module R M ](f : M →ₗ[R]M) example (n : ℕ) (a : R)(hyp : a * n = 1)(x : M) : a • ((n) • x) = x := begin have R : n • x = (n : R) • x, exact semimodule.smul_eq_smul R n x, rw R, rw ← mul_smul, rw hyp, rw one_smul, end open linear_map submodule -- to write ker instead of linear_map.ker /-- We start with the axiom of linear_map ! -/ example (x y : M) : f ( x + y) = f x + f y := map_add f x y /-- For example -/ example ( x y : M) : f ( x + y) = f y + f x := begin rw map_add f , rw add_comm, --- the addition in a module is commutative `[add_comm_group M]` end /-- * The multiplication of a scalar by a vector is denoted by `•` and name `smul` ! -/ example (r : R )(x : M) : f (r • x ) = r • f( x) := f.map_smul r x /-- We give the definition of `ker f`. The standant definition is the subset `ker f := {x ∈ M | f x = 0}` and proof that is a submodule of `M`. In mathlib the definition is not this. -/ example : ker f = comap f ⊥ := rfl /-- `rfl` mean that is the `mathlib definition`. We see that it's construct with a function `linear_map.comap` and with a notation `⊥`. We explain this. 1. `⊥` refer to the bottom element of the set of `submodule` of `M` that mean `⊥ = {0}` 2. `comap f ` is the inverse inmage `f⁻¹`. So `comap f ⊥ := f⁻¹ {0}` this is the set of element of ` x ∈ M` s.t `f x = 0` -/ example (x : M) : x ∈ (⊥ : submodule R M) ↔ x = 0 := mem_bot _ /-- the classical definition of comap ` x ∈ f⁻¹ p ↔ f x ∈ p` -/ example (x : M)(p : submodule R M) : x ∈ comap f p ↔ f x ∈ p := mem_comap /-- the standart for `ker f` -/ example (x : M) : x ∈ ker f ↔ f x = 0 := begin unfold ker, rw mem_comap, rw mem_bot, end /-- * This command is in mathlib ! -/ example (x : M ) : x ∈ ker f ↔ f x = 0 := mem_ker variables (g : M→ₗ[R]M) /-- * a little exercice. I give two proof. The first use property of comap and is `ez` ! -/ lemma exercice (x : M) : x ∈ ker (g * f) ↔ f x ∈ ker g := begin unfold ker, erw comap_comp, --- the erw is important here to change linear map comp and `*` rw mem_comap, end /-- * In the second, i split in detail ! The see an important fact : if you don't use the definition thing are harder ! -/ lemma exercice' (x : M) : x ∈ ker (g * f) ↔ f x ∈ ker g := begin split, intros hyp, rw mem_ker at hyp, rw mem_ker, exact hyp, -- here : important to look the tatic state ' hyp : (g * f ) x = 0 and the goal in not the same ! -- But by definition (g * f )x = g (f x) so it's good , you can 'rw mul_app at hyp,' intros hyp, rw mem_ker at hyp ⊢, -- rewrite at hyp and at the goal ! exact hyp, end lemma Ker_zero : ker (0 : M→ₗ[R]M) = ⊤ := begin rw eq_top_iff', intros x, exact mem_ker.mpr rfl, end /-- * this function is yet in mathlib ! <-/ example : ker f = ⊤ ↔ f = 0 := ker_eq_top /-- * Now we deal with `range f`. The definition is `map f ⊤`. -/ example : range f = map f ⊤ := rfl /-- clasical definition * This command his in mathlib has `mem_range` -/ example : ker (0 : M→ₗ[R]M) = ⊤ := ker_zero /-- * Another mathlib function : `ker_eq_top` * We `redo a proof` ! -/ lemma ker_eq_top' : f = 0 ↔ ker f = ⊤ := begin split, -- separation ↔ -- first part is the previous lemma {intros hyp, rw hyp, exact ker_zero}, intros hyp, rw eq_top_iff' at hyp, ext, change f x = 0, rw ← mem_ker, exact hyp x, end lemma ker_eq_top'' : (∀ x : M, f x = 0) ↔ ker f = ⊤ := begin split, intros, rw ker_eq_top, ext, exact a x, intros, rw ker_eq_top at a, change f x = 0, rw a, exact rfl, end /-! * We see that it complicated for a triviality. * because we don't use realy the definition -/ example : ker f = comap f ⊥ := rfl example : range f = map f ⊤ := rfl /-! * We have to deal with this definition to make stuff simpler -/ lemma ker_eq_top : range f = ⊥ ↔ ker f = ⊤ := begin rw eq_top_iff, rw eq_bot_iff, -- unfold ker range, exact map_le_iff_le_comap, end lemma range_bot_iff {R : Type u} [ comm_ring R]{M : Type v}[add_comm_group M][module R M] (f: M →ₗ[R] M) : (f = 0) ↔ linear_map.range f = ⊥ := begin rw eq_bot_iff, rw linear_map.range_le_bot_iff f, end lemma linear_map.range_sub_ker (R : Type u) [ comm_ring R](M : Type v)[add_comm_group M][module R M] (f g : M →ₗ[R] M) : f * g = 0 ↔ range g ≤ ker f := begin rw range_bot_iff (f * g), rw linear_map.le_ker_iff_map, erw ← submodule.map_comp, exact iff.rfl, end end Tools.module universes u v v' variables {R : Type u}[comm_ring R]{M : Type v}[add_comm_group M] [module R M ] open linear_map def is_projector (p : M →ₗ[R] M) := p * p = p lemma is_projector_ext {p : M →ₗ[R]M} (hyp : is_projector p) : p * p = p := begin unfold is_projector at hyp,exact hyp, end /-- if `p² = p` then `(1-p)² = 1 - p - p +p² = ... = 1-p` -/ lemma Complementary (p : M →ₗ[R]M) (hyp : is_projector p) : is_projector (id - p) := begin change linear_map.id - p with 1 -p, have R : ( 1- p) * (1 -p) = 1 - p -(p - p * p), exact mul_sub (1 - p) 1 p, unfold is_projector, rw R, rw is_projector_ext hyp, simp, end variables (p : M→ₗ[R]M) lemma Projector_apply (x : M) : p ∘ p = ⇑(p * p) := rfl lemma image_in_range (x : M) : p x ∈ range p := by apply mem_range.mpr; use x lemma ker_eq_im_comp (hyp : is_projector p) : range p = ker (id-p) := begin apply submodule.ext,intros x,split,rintros ⟨y,hyp ⟩, rw mem_ker, change x- p x = 0, rw ← hyp.2, change (p - p * p) y = 0, rw is_projector_ext, rw sub_self, exact rfl,assumption, intros hyp, rw mem_ker at hyp, change x-p x = 0 at hyp, rw mem_range, use x, have R : x - p x + p x = p x, rw hyp_1, rw zero_add, rw ← R,simp, end def has_projector (P : submodule R M) := ∃ p : M →ₗ[R]M, is_projector p ∧ linear_map.range (p : M→ₗ[R]M) = P lemma proj_ker (p : M →ₗ[R]M) (hyp : is_projector p) : ∀ m : M, p m ∈ ker (id - p) := begin rw ← ker_eq_im_comp, exact image_in_range p,assumption, end lemma calcul : linear_map.id - (id - p) = p := begin exact sub_sub_self id p, end lemma proj_im(p : M →ₗ[R]M) (hyp : is_projector p) : ∀ m : M, m - p m ∈ ker (p) := begin let H := proj_ker (id-p) (Complementary p hyp), -- let H := specialize (proj_ker (id - p)) (Complementary p hyp) -- unknown identifier 'specialize' rw calcul at H, exact H, end lemma projector_decomp (p : M →ₗ[R]M) (hyp : is_projector p) : ∀ m : M,∃ m_im ∈ range p, ∃ m_ker ∈ ker p, m = m_ker+ m_im := begin intros m, use p m, split, refine image_in_range _ m , use m - p m, split, apply proj_im, assumption,simp, end lemma Unicity (hyp : is_projector p) : (range p) ⊓ (ker p)= ⊥ := begin rw eq_bot_iff, rw submodule.le_def', intros x, rw submodule.mem_bot, intros, rw submodule.mem_inf at H, rcases H with ⟨ IM, KER ⟩ , rw mem_ker at KER, rw mem_range at IM, rcases IM with ⟨ y,hyp_y⟩ , rw ← hyp_y at KER, change (p * p) y = 0 at KER, rw is_projector_ext at KER, rw hyp_y at KER, assumption, assumption, end lemma projector.mem_range (x : M)(hyp : is_projector p) : x ∈ range p ↔ p x = x := begin split, intro hyp, rw mem_range at hyp, rcases hyp with ⟨y,hyp_y ⟩, rw ← hyp_y, change p( p y) with (p *p) y, rw (is_projector_ext hyp), intro hyp, rw ← hyp, apply image_in_range, end lemma projector_im_eq (p q : M→ₗ[R] M) (hyp_p : is_projector p) (hyp_q : is_projector q) : range p = range q ↔ ( p * q = q) ∧ (q * p = p) := begin split, intro hyp, split, {ext,rw mul_app, rw ← projector.mem_range, rw hyp,refine image_in_range q _, assumption}, {ext, rw mul_app,rw ← projector.mem_range,rw ← hyp,refine image_in_range p _, assumption}, intro, apply submodule.ext, intro x, split, {intro,rw ← a.2 at a_1,rw mem_range at *,rcases a_1,use p a_1_w, exact a_1_h,}, {intro,rw ← a.1 at a_1,rw mem_range at *,rcases a_1,use q a_1_w, exact a_1_h,}, end theorem projector.caract_image (p : M→ₗ[R]M) : (∀ x : range p, p x = x ) → is_projector p := begin intro hyp, unfold is_projector, ext,rw mul_app, exact hyp ⟨p x,image_in_range p x ⟩, end lemma range_le_submodule (p : M→ₗ[R]M) (W : submodule R M) : range p ≤ W ↔ ∀ x : M, p x ∈ W := begin split, intros hyp, intro x, let R := image_in_range p x, rw submodule.le_def' at hyp, exact hyp (p x) R, intro, rw submodule.le_def', intro x, intro hyp_range, rw mem_range at hyp_range, rcases hyp_range, rw ← hyp_range_h, exact a hyp_range_w, end theorem projector.caract_image' (p : M→ₗ[R]M) (W : submodule R M) : (range p ≤ W ∧ ∀ w ∈ W, p w = w) → (is_projector p ∧ range p = W) := begin intros hyp, split, apply projector.caract_image, intro y, apply hyp.2 y, rw submodule.le_def' at hyp, apply hyp.1 y, exact y.property, apply le_antisymm , exact hyp.1, rintros w, intro hyp_w, change w ∈ range p, change w ∈ W at hyp_w, rw mem_range, use w, rw hyp.2,assumption, end lemma projector.right_mul (p f : M →ₗ[R] M) [is_projector p] : p * f = f ↔ ∀ x : M, (x ∈ range f → p x = x) := begin split, intro hyp, intro x, rw mem_range, rintros ⟨a,b⟩, rw ← b, change (p * f) a = f a, rw hyp, intro hyp, ext, exact hyp _ (image_in_range f x), end variables (g : M ≃ₗ[R]M) example (N : submodule R M) : N ≤ ⊤ := le_top example (N N' : submodule R M) : (N ≤ N') → (N' ≤ N) → N = N' := le_antisymm open submodule lemma submodule.le_inf (W N N' : submodule R M) : W ≤ N ⊓ N' ↔ (W ≤ N ∧ W ≤ N') := le_inf_iff lemma test' (p f : M →ₗ[R] M) : map f (ker (p * f)) = range f ⊓ ker p := begin apply le_antisymm, rw le_inf_iff, split, {apply map_mono , exact le_top}, {rw linear_map.le_ker_iff_map, erw ← map_comp, rw ← linear_map.le_ker_iff_map, exact le_refl _}, intros x, intros hyp, rcases hyp, erw mem_map, change x ∈ range f at hyp_left, rw mem_range at hyp_left, rcases hyp_left with ⟨y, hyp_y⟩ ,use y, split, swap, assumption, rw mem_ker, change x ∈ ker p at hyp_right, change p( f y) = 0, rw hyp_y, exact mem_ker.mp hyp_right, end lemma test'' (p f : M →ₗ[R] M) : map f (ker (p * f)) = range f ⊓ ker p := begin apply le_antisymm, rw le_inf_iff, split, apply map_le_range, rw map_le_iff_le_comap, { erw comap_comp, refine le_refl _,}, rw le_def', intros x, intros hyp, rcases hyp, rw mem_map, erw mem_range at hyp_left, rcases hyp_left with ⟨y, hyp_y⟩ ,use y, split, swap, assumption, rw mem_ker, change x ∈ ker p at hyp_right, change p( f y) = 0, rw hyp_y, exact mem_ker.mp hyp_right, end open finset lemma sum.range (X :Type v')[fintype X](φ : X → (M →ₗ[R] M))(W : submodule R M) : (∀ x : X, range (φ x) ≤ W) → linear_map.range (finset.sum finset.univ φ ) ≤ W := begin intros hyp, rw le_def', intros m, intros, rw linear_map.mem_range at H, rcases H with ⟨y,hyp_y ⟩, rw ← hyp_y, rw linear_map.sum_apply, apply sum_mem, intros c, intros, let hyp := hyp c, rw le_def' at hyp, apply hyp, exact image_in_range (φ c) y, end lemma range_smulll (a : R)(b : R) (hyp : a * b = 1) : range (a • p) = range p := begin apply le_antisymm, rw le_def', intros x, intros hyp, rw linear_map.mem_range at *, rcases hyp with ⟨ y, hyp_y ⟩, use a • y, rw linear_map.map_smul, exact hyp_y, rw le_def', intros x, intros hyp, rw linear_map.mem_range at *, rcases hyp with ⟨y, hyp_y ⟩, use b • y, rw linear_map.map_smul, erw ← mul_smul, rw mul_comm, rw hyp, rw one_smul, assumption, end lemma sum_proj (X : Type v')[fintype X](W : submodule R M)(a : R) (inve : a * (((fintype.card X) : ℤ) : R) = 1) (φ : X → (M →ₗ[R]M)) (hyp : ∀ x : X, is_projector (φ x)) (hyp_2 : ∀ x : X, range (φ x) = W) : is_projector ( a • (finset.sum finset.univ φ)) ∧ range ( a • (finset.sum finset.univ φ)) = W := begin apply projector.caract_image', split, rw range_smulll, swap, use inve, apply sum.range, intros x, rw hyp_2 x, rw le_def, intros x, intros hyp', change a • _ =x, rw linear_map.sum_apply, have R' : (λ d, φ d x) = (λ d, x), funext, rw ← projector.mem_range (φ d) x (hyp d), rw hyp_2 d, assumption, rw R', rw sum_const, change a • (( fintype.card X) • x) = x, rw semimodule.smul_eq_smul R, rw ← mul_smul, erw inve, rw one_smul, end /-- from : http://desaintar.free.fr/exos/exos_ev.pdf -/ lemma exercice_25 : ker (p ) ≤ ker (p * p) := begin unfold ker at *, change _ ≤ comap (linear_map.comp p p) _ , rw comap_comp, apply comap_mono, exact bot_le, end lemma exercice_25_2 : range (p * p) ≤ range p := begin unfold linear_map.range at *, erw map_comp, apply map_mono, exact le_top, end lemma exercice_26' : ker (p *p) = ker p ↔ range p ⊓ ker (p) = ⊥ := begin rw ← map_comap_eq,rw eq_bot_iff, rw map_le_iff_le_comap, unfold ker, rw ← comap_comp, split, intros, rw ← a, exact le_refl _, intros, apply le_antisymm, exact a, erw comap_comp, apply comap_mono, exact bot_le, end lemma exercice_33 (p q : M →ₗ[R]M)(hyp_p : is_projector p)(hyp_q : is_projector q) (comm : p * q = q * p) : is_projector (p*q) := begin unfold is_projector at *, rw mul_assoc, rw comm, rw ← mul_assoc q q p, rw hyp_q, rw ← comm, rw ← mul_assoc, rw hyp_p, end
6ad6a79ab927e0101285819d571831e7e6ef3d6c
f3a5af2927397cf346ec0e24312bfff077f00425
/src/game/world10/level3.lean
0730e85ba9e932c24c632436169bac90e6265e41
[ "Apache-2.0" ]
permissive
ImperialCollegeLondon/natural_number_game
05c39e1586408cfb563d1a12e1085a90726ab655
f29b6c2884299fc63fdfc81ae5d7daaa3219f9fd
refs/heads/master
1,688,570,964,990
1,636,908,242,000
1,636,908,242,000
195,403,790
277
84
Apache-2.0
1,694,547,955,000
1,562,328,792,000
Lean
UTF-8
Lean
false
false
2,232
lean
import game.world10.level2 -- hide namespace mynat -- hide /- # Inequality world. ## Level 3: `le_succ_of_le` We have seen how the `use` tactic makes progress on goals of the form `⊢ ∃ c, ...`. But what do we do when we have a *hypothesis* of the form `h : ∃ c, ...`? The hypothesis claims that there exists some natural number `c` with some property. How are we going to get to that natural number `c`? It turns out that the `cases` tactic can be used (just like it was used to extract information from `∧` and `∨` and `↔` hypotheses). Let me talk you through the proof of $a\le b\implies a\le\operatorname{succ}(b)$. The goal is an implication so we clearly want to start with `intro h,` . After this, if you *want*, you can do something like `rw le_iff_exists_add at h ⊢,` (get the sideways T with `\|-` then space). This changes the `≤` into its `∃` form in `h` and the goal -- but if you are happy with just *imagining* the `∃` whenever you read a `≤` then you don't need to do this line. Our hypothesis `h` is now `∃ (c : mynat), b = a + c` (or `a ≤ b` if you elected not to do the definitional rewriting) so `cases h with c hc,` gives you the natural number `c` and the hypothesis `hc : b = a + c`. Now use `use` wisely and you're home. -/ /- Lemma For all naturals $a$, $b$, if $a\leq b$ then $a\leq \operatorname{succ}(b)$. -/ theorem le_succ (a b : mynat) : a ≤ b → a ≤ (succ b) := begin [nat_num_game] intro h, cases h with c hc, rw hc, use c + 1, refl, end /- Did you use `succ c` or `c + 1` or `1 + c`? Those numbers are all equal, right? So it doesn't matter which one you use, right? Here's an interesting question. If you copy the proof below into the box above, and then fill in the `???` below with `succ c`, will this proof compile? (move your cursor to after the final comma to see what Lean thinks). What about if you `use 1 + c`? What about if you `use c + 1`? Can you work out what is going on? Does it help if I tell you that the *definition* of `1` is `succ 0`? ``` theorem le_succ (a b : mynat) : a ≤ b → a ≤ (succ b) := begin [nat_num_game] intro h, cases h with c hc, rw hc, use ???, refl, end ``` -/ end mynat -- hide
e277dee72704e71cec06bbc0666f3bb75591d317
4727251e0cd73359b15b664c3170e5d754078599
/test/equiv_rw.lean
a39015992dc926b1036adc85a6cc5c1c4cb7e602
[ "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
10,255
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import tactic.equiv_rw -- Uncomment this line to observe the steps of constructing appropriate equivalences. -- set_option trace.equiv_rw_type true -- This fails if we use `occurs` rather than `kdepends_on` in `equiv_rw_type`. instance : equiv_functor set := { map := λ α β e s, by { equiv_rw e.symm, assumption, } } -- Rewriting a hypothesis along an equivalence. example {α β : Type} (e : α ≃ β) (f : α → ℕ) (h : ∀ b : β, f (e.symm b) = 0) (i : α) : f i = 0 := begin equiv_rw e at i, apply h, end -- Check that dependent hypotheses are reverted and reintroduced. example {α β : Type} (e : α ≃ β) (Z : α → Type) (f : Π a, Z a → ℕ) (h : ∀ (b : β) (x : Z (e.symm b)), f (e.symm b) x = 0) (i : α) (x : Z i) : f i x = 0 := begin equiv_rw e at i, guard_hyp i : β, guard_target f (e.symm i) x = 0, guard_hyp x : Z ((e.symm) i), exact h i x, end -- Rewriting the goal along an equivalence. example {α β : Type} (e : α ≃ β) (b : β) : α := begin equiv_rw e, exact b, end -- Fail if the equivalence can't be used. example {α β γ : Type} (e : β ≃ γ) (a : α) : α := begin success_if_fail { equiv_rw e at a }, success_if_fail { equiv_rw e }, exact a, end -- Verify that `equiv_rw` will rewrite under `equiv_functor` instances. example {α β : Type} (u : unique α) (e : α ≃ β) : β := begin equiv_rw e at u, apply inhabited.default, end example {α β : Type} (p : equiv.perm α) (e : α ≃ β) : equiv.perm β := begin equiv_rw e at p, exact p, end -- We can rewrite the goal under functors. example {α β : Type} (e : α ≃ β) (b : β) : option α := begin equiv_rw e, exact some b, end -- We can rewrite hypotheses under functors. example {α β : Type} (e : α ≃ β) (b : option α) : option β := begin equiv_rw e at b, exact b, end -- We can rewrite hypotheses under compositions of functors. example {α β : Type} (e : α ≃ β) (b : list (list α)) : list β := begin equiv_rw e at b, exact b.join, end -- Check that we can rewrite in the target position of function types. example {α β γ : Type} (e : α ≃ β) (f : γ → β) : γ → α := begin equiv_rw e, exact f, end -- Check that we can rewrite in the source position of function types. example {α β γ : Type} (e : α ≃ β) (f : β → γ) : α → γ := begin equiv_rw e, exact f, end -- Rewriting under multiple functors. example {α β : Type} (e : α ≃ β) (b : β) : list (option α) := begin equiv_rw e, exact [none, some b], end -- Rewriting under multiple functors, including functions. example {α β γ : Type} (e : α ≃ β) (b : β) : γ → list (option α) := begin equiv_rw e, exact (λ g, [none, some b]), end -- Rewriting in multiple positions. example {α β : Type*} [has_add β] (e : α ≃ β) : α → α := begin have : (α → α) ≃ _, { apply equiv.arrow_congr, apply e, apply e, }, equiv_rw e, exact (@id β), end -- Rewriting in multiple positions. example {α β : Type} [has_add β] (e : α ≃ β) : β → α → α := begin equiv_rw e, exact (+), end -- Rewriting in multiple positions. example {α β : Type} [has_add β] (e : α ≃ β) : α → α → α := begin equiv_rw e, exact (+), end example {α β γ : Type} (e : α ≃ β) (s : β ⊕ γ) : α ⊕ γ := begin equiv_rw e, exact s, end example {α β γ : Type} (e : α ≃ β) (s : β ⊕ γ) : (α ⊕ γ) × (γ ⊕ α) := begin equiv_rw e, exact (s, s.swap), end example {α β γ : Type} (e : α ≃ β) (s : α ⊕ γ) : (β ⊕ γ) × (γ ⊕ β) := begin equiv_rw e at s, exact (s, s.swap), end example {α β γ : Type} (e : α ≃ β) (s : (α ⊕ γ) × β) : (β ⊕ γ) := begin success_if_fail { equiv_rw e at s {max_depth := 4} }, equiv_rw e at s, exact s.1, end -- Test generating the actual equivalence using `equiv_rw_type`. example {α β : Type} (e : α ≃ β) (b : β) : α × (ℕ ⊕ ℕ) := begin have e' : α × (ℕ ⊕ ℕ) ≃ _ := by equiv_rw_type e, apply e'.inv_fun, exact (b, sum.inl 0) end example {α β : Type} (e : α ≃ β) (P : α → Prop) (h : { a // P a }) : β := begin equiv_rw e at h, exact h.val, end example {α β : Type} (e : α ≃ β) (P : α → Prop) (h : ∀ a, P a) (b : β) : { a // P a } := begin equiv_rw e, use b, apply h, end example {α β : Type} (e : α ≃ β) (P : α → Prop) (h : ∀ a : α, P a) (b : β) : P (e.symm b) := begin equiv_rw e.symm at b, exact h b, end example {α β : Type} (e : α ≃ β) (P : α → Sort*) (h : Π a : α, P a) (b : β) : P (e.symm b) := begin -- this is a bit perverse, as `equiv_rw e.symm at b` is more natural, -- but this tests rewriting in the argument of a dependent function equiv_rw e at h, exact h _, end -- a poor example, rewriting in the base of a dependent pair example {α β : Type} (P : α → Type) (h : Σ a, P a) (e : α ≃ β) : β := begin equiv_rw e at h, exact h.1 end -- rewriting in the argument of a dependent function can't be done in one step example {α β γ : Type} (e : α ≃ β) (P : α → Type*) (h : Π a : α, (P a) × (option α)) (b : β) : option β := begin equiv_rw e at h, have t := h b, equiv_rw e at t, exact t.2, end -- Demonstrate using `equiv_rw` to build new instances of `equiv_functor` -- Observe that the next three declarations could easily be implemented by a tactic. -- This has been automated in the `transport` branch, -- so we won't attempt to write a deriver handler until we join with that. def semigroup.map {α β : Type} (e : α ≃ β) : semigroup α → semigroup β := begin intro S, refine_struct { .. }, -- transport data fields using `equiv_rw` { have mul := S.mul, equiv_rw e at mul, -- This `equiv_rw` performs the following steps: -- have e' := (equiv.arrow_congr' e (equiv.arrow_congr' e e)), -- have h := (e'.symm_apply_apply mul).symm, -- revert h, -- generalize : (e' mul) = mul', -- intro h, -- clear_dependent mul, -- rename mul' mul, exact mul, }, -- transport axioms by simplifying, and applying the original axiom { intros, dsimp, simp, apply S.mul_assoc, } end example {α β : Type} (e : α ≃ β) (S : semigroup α) : (semigroup.map e S).mul = (equiv.arrow_congr' e (equiv.arrow_congr' e e)) has_mul.mul := rfl example {α β : Type} (e : α ≃ β) (S : semigroup α) (x y : β) : begin haveI := semigroup.map e S, exact x * y = e (e.symm x * e.symm y) end := rfl lemma semigroup.id_map (α : Type) : semigroup.map (equiv.refl α) = id := by { ext, refl, } lemma semigroup.map_map {α β γ : Type} (e : α ≃ β) (f : β ≃ γ) : semigroup.map (e.trans f) = (semigroup.map f) ∘ (semigroup.map e) := by { ext, dsimp [semigroup.map], simp, } -- TODO (after joining the `transport` branch) create a derive handler for this instance : equiv_functor semigroup := { map := λ α β e, semigroup.map e, map_refl' := semigroup.id_map, map_trans' := λ α β γ e f, semigroup.map_map e f, } -- Verify that we can now use `equiv_rw` under `semigroup`: example {α : Type} [I : semigroup α] {β : Type} (e : α ≃ β) : semigroup β := begin equiv_rw e at I, exact I, end -- Now we do `monoid`, to try out a structure with constants. -- The constructions and proofs here are written as uniformly as possible. -- This example is the blueprint for the `transport` tactic. mk_simp_attribute transport_simps "simps useful inside `transport`" attribute [transport_simps] eq_rec_constant cast_eq equiv.to_fun_as_coe equiv.arrow_congr'_apply equiv.symm_apply_apply equiv.apply_eq_iff_eq_symm_apply def monoid.map {α β : Type} (e : α ≃ β) (S : monoid α) : monoid β := begin refine_struct { .. }, { have mul := S.mul, equiv_rw e at mul, exact mul, }, { try { unfold_projs }, simp only with transport_simps, have mul_assoc := S.mul_assoc, equiv_rw e at mul_assoc, solve_by_elim, }, { have one := S.one, equiv_rw e at one, exact one, }, { try { unfold_projs }, simp only with transport_simps, have one_mul := S.one_mul, equiv_rw e at one_mul, solve_by_elim, }, { try { unfold_projs }, simp only with transport_simps, have mul_one := S.mul_one, equiv_rw e at mul_one, solve_by_elim, }, { have npow := S.npow, equiv_rw e at npow, exact npow, }, { try { unfold_projs }, simp only with transport_simps, have npow_zero' := S.npow_zero', equiv_rw e at npow_zero', solve_by_elim, }, { try { unfold_projs }, simp only with transport_simps, have npow_succ' := S.npow_succ', equiv_rw e at npow_succ', solve_by_elim, }, end example {α β : Type} (e : α ≃ β) (S : monoid α) : (monoid.map e S).mul = (equiv.arrow_congr' e (equiv.arrow_congr' e e)) has_mul.mul := rfl example {α β : Type} (e : α ≃ β) (S : monoid α) (x y : β) : begin haveI := monoid.map e S, exact x * y = e (e.symm x * e.symm y) end := rfl example {α β : Type} (e : α ≃ β) (S : monoid α) : begin haveI := monoid.map e S, exact (1 : β) = e (1 : α) end := rfl example {α : Type} {β : Type} (m : α → α → α) (e : α ≃ β) : β → β → β := begin equiv_rw e at m, exact m, end -- This used to fail because metavariables were getting stuck! example {α : Type} {β : Type 2} (m : α → α → α) (e : α ≃ β) : β → β → β := begin equiv_rw e at m, exact m, end -- Rewriting multiple equivalences on target example {α β χ δ : Type} (m : β → β → δ → δ) (e₁ : α ≃ β) (e₂ : χ ≃ δ) : α → α → χ → χ := begin equiv_rw [e₁, e₂], exact m, end -- Rewriting multiple equivalences on a hypothesis example {α β χ δ : Type} (m : α → α → χ → χ) (e₁ : α ≃ β) (e₂ : χ ≃ δ) : β → β → δ → δ := begin equiv_rw [e₁, e₂] at m, exact m, end example {α β χ δ : Type} (m : β → β → β) (e : α ≃ β) : α → α → α := begin equiv_rw e at *, exact m, end
08b4341f6bf5c651fb63f411f737f7ff3856af2e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/category_theory/adjunction/adjoint_functor_theorems.lean
b13c7016fb27c1567475e25e1aa0527b2008ed0c
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
6,434
lean
/- Copyright (c) 2021 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.generator import category_theory.limits.cone_category import category_theory.limits.constructions.weakly_initial import category_theory.limits.functor_category import category_theory.subobject.comma /-! # Adjoint functor theorem This file proves the (general) adjoint functor theorem, in the form: * If `G : D ⥤ C` preserves limits and `D` has limits, and satisfies the solution set condition, then it has a left adjoint: `is_right_adjoint_of_preserves_limits_of_solution_set_condition`. We show that the converse holds, i.e. that if `G` has a left adjoint then it satisfies the solution set condition, see `solution_set_condition_of_is_right_adjoint` (the file `category_theory/adjunction/limits` already shows it preserves limits). We define the *solution set condition* for the functor `G : D ⥤ C` to mean, for every object `A : C`, there is a set-indexed family ${f_i : A ⟶ G (B_i)}$ such that any morphism `A ⟶ G X` factors through one of the `f_i`. This file also proves the special adjoint functor theorem, in the form: * If `G : D ⥤ C` preserves limits and `D` is complete, well-powered and has a small coseparating set, then `G` has a left adjoint: `is_right_adjoint_of_preserves_limits_of_is_coseparating` Finally, we prove the following corollary of the special adjoint functor theorem: * If `C` is complete, well-powered and has a small coseparating set, then it is cocomplete: `has_colimits_of_has_limits_of_is_coseparating` -/ universes v u u' namespace category_theory open limits variables {J : Type v} variables {C : Type u} [category.{v} C] /-- The functor `G : D ⥤ C` satisfies the *solution set condition* if for every `A : C`, there is a family of morphisms `{f_i : A ⟶ G (B_i) // i ∈ ι}` such that given any morphism `h : A ⟶ G X`, there is some `i ∈ ι` such that `h` factors through `f_i`. The key part of this definition is that the indexing set `ι` lives in `Type v`, where `v` is the universe of morphisms of the category: this is the "smallness" condition which allows the general adjoint functor theorem to go through. -/ def solution_set_condition {D : Type u} [category.{v} D] (G : D ⥤ C) : Prop := ∀ (A : C), ∃ (ι : Type v) (B : ι → D) (f : Π (i : ι), A ⟶ G.obj (B i)), ∀ X (h : A ⟶ G.obj X), ∃ (i : ι) (g : B i ⟶ X), f i ≫ G.map g = h section general_adjoint_functor_theorem variables {D : Type u} [category.{v} D] variables (G : D ⥤ C) /-- If `G : D ⥤ C` is a right adjoint it satisfies the solution set condition. -/ lemma solution_set_condition_of_is_right_adjoint [is_right_adjoint G] : solution_set_condition G := begin intros A, refine ⟨punit, λ _, (left_adjoint G).obj A, λ _, (adjunction.of_right_adjoint G).unit.app A, _⟩, intros B h, refine ⟨punit.star, ((adjunction.of_right_adjoint G).hom_equiv _ _).symm h, _⟩, rw [←adjunction.hom_equiv_unit, equiv.apply_symm_apply], end /-- The general adjoint functor theorem says that if `G : D ⥤ C` preserves limits and `D` has them, if `G` satisfies the solution set condition then `G` is a right adjoint. -/ noncomputable def is_right_adjoint_of_preserves_limits_of_solution_set_condition [has_limits D] [preserves_limits G] (hG : solution_set_condition G) : is_right_adjoint G := begin apply is_right_adjoint_of_structured_arrow_initials _, intro A, specialize hG A, choose ι B f g using hG, let B' : ι → structured_arrow A G := λ i, structured_arrow.mk (f i), have hB' : ∀ (A' : structured_arrow A G), ∃ i, nonempty (B' i ⟶ A'), { intros A', obtain ⟨i, _, t⟩ := g _ A'.hom, exact ⟨i, ⟨structured_arrow.hom_mk _ t⟩⟩ }, obtain ⟨T, hT⟩ := has_weakly_initial_of_weakly_initial_set_and_has_products hB', apply has_initial_of_weakly_initial_and_has_wide_equalizers hT, end end general_adjoint_functor_theorem section special_adjoint_functor_theorem variables {D : Type u'} [category.{v} D] /-- The special adjoint functor theorem: if `G : D ⥤ C` preserves limits and `D` is complete, well-powered and has a small coseparating set, then `G` has a left adjoint. -/ noncomputable def is_right_adjoint_of_preserves_limits_of_is_coseparating [has_limits D] [well_powered D] {𝒢 : set D} [small.{v} 𝒢] (h𝒢 : is_coseparating 𝒢) (G : D ⥤ C) [preserves_limits G] : is_right_adjoint G := have ∀ A, has_initial (structured_arrow A G), from λ A, has_initial_of_is_coseparating (structured_arrow.is_coseparating_proj_preimage A G h𝒢), by exactI is_right_adjoint_of_structured_arrow_initials _ /-- The special adjoint functor theorem: if `F : C ⥤ D` preserves colimits and `C` is cocomplete, well-copowered and has a small separating set, then `F` has a right adjoint. -/ noncomputable def is_left_adjoint_of_preserves_colimits_of_is_separatig [has_colimits C] [well_powered Cᵒᵖ] {𝒢 : set C} [small.{v} 𝒢] (h𝒢 : is_separating 𝒢) (F : C ⥤ D) [preserves_colimits F] : is_left_adjoint F := have ∀ A, has_terminal (costructured_arrow F A), from λ A, has_terminal_of_is_separating (costructured_arrow.is_separating_proj_preimage F A h𝒢), by exactI is_left_adjoint_of_costructured_arrow_terminals _ end special_adjoint_functor_theorem namespace limits /-- A consequence of the special adjoint functor theorem: if `C` is complete, well-powered and has a small coseparating set, then it is cocomplete. -/ lemma has_colimits_of_has_limits_of_is_coseparating [has_limits C] [well_powered C] {𝒢 : set C} [small.{v} 𝒢] (h𝒢 : is_coseparating 𝒢) : has_colimits C := { has_colimits_of_shape := λ J hJ, by exactI has_colimits_of_shape_iff_is_right_adjoint_const.2 ⟨is_right_adjoint_of_preserves_limits_of_is_coseparating h𝒢 _⟩ } /-- A consequence of the special adjoint functor theorem: if `C` is cocomplete, well-copowered and has a small separating set, then it is complete. -/ lemma has_limits_of_has_colimits_of_is_separating [has_colimits C] [well_powered Cᵒᵖ] {𝒢 : set C} [small.{v} 𝒢] (h𝒢 : is_separating 𝒢) : has_limits C := { has_limits_of_shape := λ J hJ, by exactI has_limits_of_shape_iff_is_left_adjoint_const.2 ⟨is_left_adjoint_of_preserves_colimits_of_is_separatig h𝒢 _⟩ } end limits end category_theory
ea8ee2fe40d356daa8a46c5f9ec4373269b80892
cf39355caa609c0f33405126beee2739aa3cb77e
/library/init/meta/case_tag.lean
dc40c2d13f0325de8ed645df0d1aee382922b91f
[ "Apache-2.0" ]
permissive
leanprover-community/lean
12b87f69d92e614daea8bcc9d4de9a9ace089d0e
cce7990ea86a78bdb383e38ed7f9b5ba93c60ce0
refs/heads/master
1,687,508,156,644
1,684,951,104,000
1,684,951,104,000
169,960,991
457
107
Apache-2.0
1,686,744,372,000
1,549,790,268,000
C++
UTF-8
Lean
false
false
10,282
lean
/- Copyright (c) 2020 Jannis Limperg. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jannis Limperg -/ prelude import init.meta.tactic /-! # Case tags Case tags are an internal mechanism used by certain tactics to communicate with each other. They are generated by the tactics `cases`, `induction` and `with_cases` ('cases-like tactics'), which generate goals corresponding to the 'cases' of an inductive hypothesis. Each of these goals carries a case tag. They are consumed by the `case` tactic, which focuses on one of these cases. Their purpose is twofold: 1. Give intuitive names to case goals. For example, when performing induction on a natural number, two cases are generated: one tagged with `nat.zero` and one tagged with `nat.succ`. Users can then focus on e.g. the second goal with `case succ {...}`. 2. Communicate which new hypotheses were introduced by the cases-like tactic that generated the goal. For example, when performing induction on a `list α`, the `cons` case introduces two hypotheses corresponding to the two arguments of the `cons` constructor. `case` allows users to name these with `case cons : x xs {...}`. To perform this renaming, `case` needs to know which hypotheses to rename; this information is contained in the case tag for the `cons` goal. ## Module contents This module defines 1. what a case tag is (see `case_tag`); 2. how to render a `case_tag` as a list of names (see `render`); 3. how to parse a `case_tag` from a list of names (see `parse`); 4. how to match a `case_tag` with a sequence of names given by the user (see `match_tag`). -/ namespace tactic namespace interactive /-- A case tag carries the following information: 1. A list of names identifying the case ('case names'). This is usually a list of constructor names, one for each case split that was performed. For example, the sequence of tactics `cases n; cases xs`, where `n` is a natural number and `xs` is a list, will generate four cases tagged as follows: ``` nat.zero, list.nil nat.zero, list.cons nat.succ, list.nil nat.succ, list.cons ``` Note: In the case tag, the case names are stored in reverse order. Thus, the case names of the first case tag would be `list.nil, nat.zero`. This is because when printing a goal tag (as part of a goal state), Lean prints all non-internal names in reverse order. 2. Information about the arguments introduced by the cases-like tactic. Different tactics work slightly different in this regard: 1. The `with_cases` tactic generates goals where the target quantifies over any added hypotheses. For example, `with_cases { cases xs }`, where `xs` is a `list α`, will generate a target of the form `α → list α → ...` in the `cons` case, where the two arguments correspond to the two arguments of the `cons` constructor. Goals of this form are tagged with a `pi` case tag (since the target is a pi type). In addition to the case names, it contains a natural number, `num_arguments`, which specifies how many of the arguments that the target quantifies over were introduced by `with_cases`. For example, given `n : ℕ` and `xs : list α`, the fourth goal generated by `with_cases { cases n; induction xs }` has this form: ``` ... ⊢ ℕ → α → ∀ (xs' : list α), P xs' → ... ``` The corresponding case tag is ``` pi [`list.cons, `nat.succ] 4 ``` since the first four arguments of the target were introduced by `with_cases {...}`. 2. The `cases` and `induction` tactics do not add arguments to the target, but rather introduce them as hypotheses in the local context. Goals of this form are tagged with a `hyps` case tag. In addition to the case names, it contains a list of *unique* names of the hypotheses that were introduced. For example, given `xs : list α`, the second goal generated by `induction xs` has this form: ``` ... x : α xs' : list α ih_xs' : P xs' ⊢ ... ``` The corresponding goal tag is ``` hyps [`list.cons] [`<x>, `<xs'>, `<ih_xs'>] ``` where ````<h>``` denotes the unique name of a hypothesis `h`. Note: Many tactics do not preserve the unique names of hypotheses (particularly those tactics that use `revert`). Therefore, a `hyps` case tag is only guaranteed to be valid directly after it was generated. -/ inductive case_tag | pi (names : list name) (num_arguments : ℕ) | hyps (names : list name) (arguments : list name) open case_tag section open format protected meta def case_tag.to_format : case_tag → format | (pi names num_arguments) := join [ "(pi " , group $ nest 4 $ join $ list.intersperse line [names.to_format, format.of_nat num_arguments] , ")" ] | (hyps names arguments) := join [ "(hyps " , group $ nest 6 $ join $ list.intersperse line [names.to_format, arguments.to_format] , ")" ] end protected def case_tag.repr : case_tag → string | (pi names num_arguments) := "(pi " ++ names.repr ++ " " ++ num_arguments.repr ++ ")" | (hyps names arguments) := "(hyps " ++ names.repr ++ " " ++ arguments.repr ++ ")" protected def case_tag.to_string : case_tag → string | (pi names num_arguments) := "(pi " ++ names.to_string ++ " " ++ to_string num_arguments ++ ")" | (hyps names arguments) := "(hyps " ++ names.to_string ++ " " ++ arguments.to_string ++ ")" namespace case_tag open name (mk_string mk_numeral) meta instance : has_to_format case_tag := ⟨case_tag.to_format⟩ instance : has_repr case_tag := ⟨case_tag.repr⟩ instance : has_to_string case_tag := ⟨case_tag.to_string⟩ /-- The constructor names associated with a case tag. -/ meta def case_names : case_tag → list name | (pi ns _) := ns | (hyps ns _) := ns private meta def render_arguments (args : list name) : list name := args.map (name.mk_string "_arg") /-- Renders a case tag to a goal tag (i.e. a list of names), according to the following schema: - A `pi` tag with names `N₀ ... Nₙ` and number of arguments `a` is rendered as ``` [`_case.pi.a, N₀, ..., Nₙ] ``` - A `hyps` tag with names `N₀ ... Nₙ` and argument names `A₀ ... Aₘ` is rendered as ``` [`_case.hyps, A₀._arg, ..., Aₘ._arg, N₀, ..., Nₙ] ``` -/ meta def render : case_tag → list name | (pi names num_arguments) := mk_numeral (unsigned.of_nat' num_arguments) `_case.pi :: names | (hyps names arguments) := `_case.hyps :: render_arguments arguments ++ names /-- Creates a `pi` case tag from an input tag `in_tag`. The `names` of the resulting tag are the non-internal names in `in_tag` (in the order in which they appear in `in_tag`). `num_arguments` is the number of arguments of the resulting tag. -/ meta def from_tag_pi (in_tag : tag) (num_arguments : ℕ) : case_tag := pi (in_tag.filter (λ n, ¬ n.is_internal)) num_arguments /-- Creates a `hyps` case tag from an input tag `in_tag`. The `names` of the resulting tag are the non-internal names in `in_tag` (in the order in which they appear in `in_tag`). `arguments` is the list of unique hypothesis names of the resulting tag. -/ meta def from_tag_hyps (in_tag : tag) (arguments : list name) : case_tag := hyps (in_tag.filter (λ n, ¬ n.is_internal)) arguments private meta def parse_marker : name → option (option nat) | (mk_numeral n `_case.pi) := some (some n.to_nat) | `_case.hyps := some none | _ := none private meta def parse_arguments : list name → list name × list name | [] := ⟨[], []⟩ | (mk_string "_arg" n :: ns) := let ⟨args, rest⟩ := parse_arguments ns in ⟨n :: args, rest⟩ | ns := ⟨[], ns⟩ /-- Parses a case tag from the list of names produced by `render`. -/ meta def parse : list name → option case_tag | [] := none | (mk_numeral n `_case.pi :: ns) := do guard $ ns.all (λ n, ¬ n.is_internal), some $ pi ns n.to_nat | (`_case.hyps :: ns) := do let ⟨args, ns⟩ := parse_arguments ns, guard $ ns.all (λ n, ¬ n.is_internal), some $ hyps ns args | _ := none /-- Indicates the result of matching a list of names against the names of a case tag. See `match_tag`. -/ inductive match_result | exact_match | fuzzy_match | no_match open match_result namespace match_result /-- The 'minimum' of two match results: - If any of the arguments is `no_match`, the result is `no_match`. - Otherwise, if any of the arguments is `fuzzy_match`, the result is `fuzzy_match`. - Otherwise (iff both arguments are `exact_match`), the result is `exact_match`. -/ def combine : match_result → match_result → match_result | exact_match exact_match := exact_match | exact_match fuzzy_match := fuzzy_match | exact_match no_match := no_match | fuzzy_match no_match := no_match | fuzzy_match _ := fuzzy_match | no_match _ := no_match end match_result private meta def name_match (suffix : name) (n : name) : match_result := if suffix = n then exact_match else if suffix.is_suffix_of n then fuzzy_match else no_match private meta def names_match : list name → list name → match_result | [] [] := exact_match | [] _ := fuzzy_match | (_ :: _) [] := no_match | (n :: ns) (n' :: ns') := (name_match n n').combine (names_match ns ns') /-- Match the `names` of a case tag against a user-supplied list of names `ns`. For this purpose, we consider the `names` in reverse order, i.e. in the order in which they are displayed to the user. The matching then uses the following rules: - If `ns` is exactly the same sequence of names as `names`, this is an exact match. - If `ns` is a *suffix* of `names`, this is a fuzzy match. Additionally, each of the names in `ns` may be a suffix of the corresponding name in `names`. - Otherwise, we have no match. Thus, the tag ``` nat.zero, list.nil ``` is matched by any of these tags: ``` nat.zero, list.nil (exact match) nat.zero, nil (fuzzy match) zero, nil (fuzzy match) nil (fuzzy match) ``` -/ meta def match_tag (ns : list name) (t : case_tag) : match_result := names_match ns.reverse t.case_names end case_tag end interactive end tactic