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
7413bda2f4a08ba3b23e092191552b4168387aa3
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/linear_algebra/tensor_product.lean
bd6ba00172b8b5d3ecb5473c06b2257d81b7f8de
[ "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
44,772
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Mario Carneiro -/ import group_theory.congruence import linear_algebra.basic /-! # Tensor product of modules over commutative semirings. This file constructs the tensor product of modules over commutative semirings. Given a semiring `R` and modules over it `M` and `N`, the standard construction of the tensor product is `tensor_product R M N`. It is also a module over `R`. It comes with a canonical bilinear map `M → N → tensor_product R M N`. Given any bilinear map `M → N → P`, there is a unique linear map `tensor_product R M N → P` whose composition with the canonical bilinear map `M → N → tensor_product R M N` is the given bilinear map `M → N → P`. We start by proving basic lemmas about bilinear maps. ## Notations This file uses the localized notation `M ⊗ N` and `M ⊗[R] N` for `tensor_product R M N`, as well as `m ⊗ₜ n` and `m ⊗ₜ[R] n` for `tensor_product.tmul R m n`. ## Tags bilinear, tensor, tensor product -/ namespace linear_map section semiring variables {R : Type*} [semiring R] {S : Type*} [semiring S] variables {M : Type*} {N : Type*} {P : Type*} variables {M' : Type*} {N' : Type*} {P' : Type*} variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] variables [add_comm_group M'] [add_comm_group N'] [add_comm_group P'] variables [module R M] [module S N] [module R P] [module S P] variables [module R M'] [module S N'] [module R P'] [module S P'] variables [smul_comm_class S R P] [smul_comm_class S R P'] include R variables (R S) /-- Create a bilinear map from a function that is linear in each component. See `mk₂` for the special case where both arguments come from modules over the same ring. -/ def mk₂' (f : M → N → P) (H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n) (H2 : ∀ (c:R) m n, f (c • m) n = c • f m n) (H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂) (H4 : ∀ (c:S) m n, f m (c • n) = c • f m n) : M →ₗ[R] N →ₗ[S] P := { to_fun := λ m, { to_fun := f m, map_add' := H3 m, map_smul' := λ c, H4 c m}, map_add' := λ m₁ m₂, linear_map.ext $ H1 m₁ m₂, map_smul' := λ c m, linear_map.ext $ H2 c m } variables {R S} @[simp] theorem mk₂'_apply (f : M → N → P) {H1 H2 H3 H4} (m : M) (n : N) : (mk₂' R S f H1 H2 H3 H4 : M →ₗ[R] N →ₗ[S] P) m n = f m n := rfl theorem ext₂ {f g : M →ₗ[R] N →ₗ[S] P} (H : ∀ m n, f m n = g m n) : f = g := linear_map.ext (λ m, linear_map.ext $ λ n, H m n) section local attribute [instance] smul_comm_class.symm /-- Given a linear map from `M` to linear maps from `N` to `P`, i.e., a bilinear map from `M × N` to `P`, change the order of variables and get a linear map from `N` to linear maps from `M` to `P`. -/ def flip (f : M →ₗ[R] N →ₗ[S] P) : N →ₗ[S] M →ₗ[R] P := mk₂' S R (λ n m, f m n) (λ n₁ n₂ m, (f m).map_add _ _) (λ c n m, (f m).map_smul _ _) (λ n m₁ m₂, by rw f.map_add; refl) (λ c n m, by rw f.map_smul; refl) end @[simp] theorem flip_apply (f : M →ₗ[R] N →ₗ[S] P) (m : M) (n : N) : flip f n m = f m n := rfl open_locale big_operators variables {R} theorem flip_inj {f g : M →ₗ[R] N →ₗ[S] P} (H : flip f = flip g) : f = g := ext₂ $ λ m n, show flip f n m = flip g n m, by rw H theorem map_zero₂ (f : M →ₗ[R] N →ₗ[S] P) (y) : f 0 y = 0 := (flip f y).map_zero theorem map_neg₂ (f : M' →ₗ[R] N →ₗ[S] P') (x y) : f (-x) y = -f x y := (flip f y).map_neg _ theorem map_sub₂ (f : M' →ₗ[R] N →ₗ[S] P') (x y z) : f (x - y) z = f x z - f y z := (flip f z).map_sub _ _ theorem map_add₂ (f : M →ₗ[R] N →ₗ[S] P) (x₁ x₂ y) : f (x₁ + x₂) y = f x₁ y + f x₂ y := (flip f y).map_add _ _ theorem map_smul₂ (f : M →ₗ[R] N →ₗ[S] P) (r : R) (x y) : f (r • x) y = r • f x y := (flip f y).map_smul _ _ theorem map_sum₂ {ι : Type*} (f : M →ₗ[R] N →ₗ[S] P) (t : finset ι) (x : ι → M) (y) : f (∑ i in t, x i) y = ∑ i in t, f (x i) y := (flip f y).map_sum end semiring section comm_semiring variables {R : Type*} [comm_semiring R] variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] variables [module R M] [module R N] [module R P] [module R Q] variables (R) /-- Create a bilinear map from a function that is linear in each component. This is a shorthand for `mk₂'` for the common case when `R = S`. -/ def mk₂ (f : M → N → P) (H1 : ∀ m₁ m₂ n, f (m₁ + m₂) n = f m₁ n + f m₂ n) (H2 : ∀ (c:R) m n, f (c • m) n = c • f m n) (H3 : ∀ m n₁ n₂, f m (n₁ + n₂) = f m n₁ + f m n₂) (H4 : ∀ (c:R) m n, f m (c • n) = c • f m n) : M →ₗ[R] N →ₗ[R] P := mk₂' R R f H1 H2 H3 H4 @[simp] theorem mk₂_apply (f : M → N → P) {H1 H2 H3 H4} (m : M) (n : N) : (mk₂ R f H1 H2 H3 H4 : M →ₗ[R] N →ₗ[R] P) m n = f m n := rfl variables (R M N P) /-- Given a linear map from `M` to linear maps from `N` to `P`, i.e., a bilinear map `M → N → P`, change the order of variables and get a linear map from `N` to linear maps from `M` to `P`. -/ def lflip : (M →ₗ[R] N →ₗ[R] P) →ₗ[R] N →ₗ[R] M →ₗ[R] P := { to_fun := flip, map_add' := λ _ _, rfl, map_smul' := λ _ _, rfl } variables {R M N P} variables (f : M →ₗ[R] N →ₗ[R] P) @[simp] theorem lflip_apply (m : M) (n : N) : lflip R M N P f n m = f m n := rfl variables (R P) /-- Composing a linear map `M → N` and a linear map `N → P` to form a linear map `M → P`. -/ def lcomp (f : M →ₗ[R] N) : (N →ₗ[R] P) →ₗ[R] M →ₗ[R] P := flip $ linear_map.comp (flip id) f variables {R P} @[simp] theorem lcomp_apply (f : M →ₗ[R] N) (g : N →ₗ P) (x : M) : lcomp R P f g x = g (f x) := rfl variables (R M N P) /-- Composing a linear map `M → N` and a linear map `N → P` to form a linear map `M → P`. -/ def llcomp : (N →ₗ[R] P) →ₗ[R] (M →ₗ[R] N) →ₗ M →ₗ P := flip { to_fun := lcomp R P, map_add' := λ f f', ext₂ $ λ g x, g.map_add _ _, map_smul' := λ (c : R) f, ext₂ $ λ g x, g.map_smul _ _ } variables {R M N P} section @[simp] theorem llcomp_apply (f : N →ₗ[R] P) (g : M →ₗ[R] N) (x : M) : llcomp R M N P f g x = f (g x) := rfl end /-- Composing a linear map `Q → N` and a bilinear map `M → N → P` to form a bilinear map `M → Q → P`. -/ def compl₂ (g : Q →ₗ N) : M →ₗ Q →ₗ P := (lcomp R _ g).comp f @[simp] theorem compl₂_apply (g : Q →ₗ[R] N) (m : M) (q : Q) : f.compl₂ g m q = f m (g q) := rfl /-- Composing a linear map `P → Q` and a bilinear map `M × N → P` to form a bilinear map `M → N → Q`. -/ def compr₂ (g : P →ₗ Q) : M →ₗ N →ₗ Q := linear_map.comp (llcomp R N P Q g) f @[simp] theorem compr₂_apply (g : P →ₗ[R] Q) (m : M) (n : N) : f.compr₂ g m n = g (f m n) := rfl variables (R M) /-- Scalar multiplication as a bilinear map `R → M → M`. -/ def lsmul : R →ₗ M →ₗ M := mk₂ R (•) add_smul (λ _ _ _, mul_smul _ _ _) smul_add (λ r s m, by simp only [smul_smul, smul_eq_mul, mul_comm]) variables {R M} @[simp] theorem lsmul_apply (r : R) (m : M) : lsmul R M r m = r • m := rfl end comm_semiring section comm_ring variables {R M : Type*} [comm_ring R] [add_comm_group M] [module R M] lemma lsmul_injective [no_zero_smul_divisors R M] {x : R} (hx : x ≠ 0) : function.injective (lsmul R M x) := smul_left_injective _ hx lemma ker_lsmul [no_zero_smul_divisors R M] {a : R} (ha : a ≠ 0) : (linear_map.lsmul R M a).ker = ⊥ := linear_map.ker_eq_bot_of_injective (linear_map.lsmul_injective ha) end comm_ring end linear_map section semiring variables {R : Type*} [comm_semiring R] variables {R' : Type*} [monoid R'] variables {R'' : Type*} [semiring R''] variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {S : Type*} variables [add_comm_monoid M] [add_comm_monoid N] [add_comm_monoid P] [add_comm_monoid Q] [add_comm_monoid S] variables [module R M] [module R N] [module R P] [module R Q] [module R S] variables [distrib_mul_action R' M] variables [module R'' M] include R variables (M N) namespace tensor_product section -- open free_add_monoid variables (R) /-- The relation on `free_add_monoid (M × N)` that generates a congruence whose quotient is the tensor product. -/ inductive eqv : free_add_monoid (M × N) → free_add_monoid (M × N) → Prop | of_zero_left : ∀ n : N, eqv (free_add_monoid.of (0, n)) 0 | of_zero_right : ∀ m : M, eqv (free_add_monoid.of (m, 0)) 0 | of_add_left : ∀ (m₁ m₂ : M) (n : N), eqv (free_add_monoid.of (m₁, n) + free_add_monoid.of (m₂, n)) (free_add_monoid.of (m₁ + m₂, n)) | of_add_right : ∀ (m : M) (n₁ n₂ : N), eqv (free_add_monoid.of (m, n₁) + free_add_monoid.of (m, n₂)) (free_add_monoid.of (m, n₁ + n₂)) | of_smul : ∀ (r : R) (m : M) (n : N), eqv (free_add_monoid.of (r • m, n)) (free_add_monoid.of (m, r • n)) | add_comm : ∀ x y, eqv (x + y) (y + x) end end tensor_product variables (R) /-- The tensor product of two modules `M` and `N` over the same commutative semiring `R`. The localized notations are `M ⊗ N` and `M ⊗[R] N`, accessed by `open_locale tensor_product`. -/ def tensor_product : Type* := (add_con_gen (tensor_product.eqv R M N)).quotient variables {R} localized "infix ` ⊗ `:100 := tensor_product _" in tensor_product localized "notation M ` ⊗[`:100 R `] `:0 N:100 := tensor_product R M N" in tensor_product namespace tensor_product section module instance : add_zero_class (M ⊗[R] N) := { .. (add_con_gen (tensor_product.eqv R M N)).add_monoid } instance : add_comm_semigroup (M ⊗[R] N) := { add_comm := λ x y, add_con.induction_on₂ x y $ λ x y, quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.add_comm _ _, .. (add_con_gen (tensor_product.eqv R M N)).add_monoid } instance : inhabited (M ⊗[R] N) := ⟨0⟩ variables (R) {M N} /-- The canonical function `M → N → M ⊗ N`. The localized notations are `m ⊗ₜ n` and `m ⊗ₜ[R] n`, accessed by `open_locale tensor_product`. -/ def tmul (m : M) (n : N) : M ⊗[R] N := add_con.mk' _ $ free_add_monoid.of (m, n) variables {R} infix ` ⊗ₜ `:100 := tmul _ notation x ` ⊗ₜ[`:100 R `] `:0 y:100 := tmul R x y @[elab_as_eliminator] protected theorem induction_on {C : (M ⊗[R] N) → Prop} (z : M ⊗[R] N) (C0 : C 0) (C1 : ∀ {x y}, C $ x ⊗ₜ[R] y) (Cp : ∀ {x y}, C x → C y → C (x + y)) : C z := add_con.induction_on z $ λ x, free_add_monoid.rec_on x C0 $ λ ⟨m, n⟩ y ih, by { rw add_con.coe_add, exact Cp C1 ih } variables (M) @[simp] lemma zero_tmul (n : N) : (0 : M) ⊗ₜ[R] n = 0 := quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero_left _ variables {M} lemma add_tmul (m₁ m₂ : M) (n : N) : (m₁ + m₂) ⊗ₜ n = m₁ ⊗ₜ n + m₂ ⊗ₜ[R] n := eq.symm $ quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_add_left _ _ _ variables (N) @[simp] lemma tmul_zero (m : M) : m ⊗ₜ[R] (0 : N) = 0 := quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_zero_right _ variables {N} lemma tmul_add (m : M) (n₁ n₂ : N) : m ⊗ₜ (n₁ + n₂) = m ⊗ₜ n₁ + m ⊗ₜ[R] n₂ := eq.symm $ quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_add_right _ _ _ section variables (R R' M N) /-- A typeclass for `has_scalar` structures which can be moved across a tensor product. This typeclass is generated automatically from a `is_scalar_tower` instance, but exists so that we can also add an instance for `add_comm_group.int_module`, allowing `z •` to be moved even if `R` does not support negation. Note that `module R' (M ⊗[R] N)` is available even without this typeclass on `R'`; it's only needed if `tensor_product.smul_tmul`, `tensor_product.smul_tmul'`, or `tensor_product.tmul_smul` is used. -/ class compatible_smul [distrib_mul_action R' N] := (smul_tmul : ∀ (r : R') (m : M) (n : N), (r • m) ⊗ₜ n = m ⊗ₜ[R] (r • n)) end /-- Note that this provides the default `compatible_smul R R M N` instance through `mul_action.is_scalar_tower.left`. -/ @[priority 100] instance compatible_smul.is_scalar_tower [has_scalar R' R] [is_scalar_tower R' R M] [distrib_mul_action R' N] [is_scalar_tower R' R N] : compatible_smul R R' M N := ⟨λ r m n, begin conv_lhs {rw ← one_smul R m}, conv_rhs {rw ← one_smul R n}, rw [←smul_assoc, ←smul_assoc], exact (quotient.sound' $ add_con_gen.rel.of _ _ $ eqv.of_smul _ _ _), end⟩ /-- `smul` can be moved from one side of the product to the other .-/ lemma smul_tmul [distrib_mul_action R' N] [compatible_smul R R' M N] (r : R') (m : M) (n : N) : (r • m) ⊗ₜ n = m ⊗ₜ[R] (r • n) := compatible_smul.smul_tmul _ _ _ /-- Auxiliary function to defining scalar multiplication on tensor product. -/ def smul.aux {R' : Type*} [has_scalar R' M] (r : R') : free_add_monoid (M × N) →+ M ⊗[R] N := free_add_monoid.lift $ λ p : M × N, (r • p.1) ⊗ₜ p.2 theorem smul.aux_of {R' : Type*} [has_scalar R' M] (r : R') (m : M) (n : N) : smul.aux r (free_add_monoid.of (m, n)) = (r • m) ⊗ₜ[R] n := rfl variables [smul_comm_class R R' M] variables [smul_comm_class R R'' M] /-- Given two modules over a commutative semiring `R`, if one of the factors carries a (distributive) action of a second type of scalars `R'`, which commutes with the action of `R`, then the tensor product (over `R`) carries an action of `R'`. This instance defines this `R'` action in the case that it is the left module which has the `R'` action. Two natural ways in which this situation arises are: * Extension of scalars * A tensor product of a group representation with a module not carrying an action Note that in the special case that `R = R'`, since `R` is commutative, we just get the usual scalar action on a tensor product of two modules. This special case is important enough that, for performance reasons, we define it explicitly below. -/ instance left_has_scalar : has_scalar R' (M ⊗[R] N) := ⟨λ r, (add_con_gen (tensor_product.eqv R M N)).lift (smul.aux r : _ →+ M ⊗[R] N) $ add_con.add_con_gen_le $ λ x y hxy, match x, y, hxy with | _, _, (eqv.of_zero_left n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, smul.aux_of, smul_zero, zero_tmul] | _, _, (eqv.of_zero_right m) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, smul.aux_of, tmul_zero] | _, _, (eqv.of_add_left m₁ m₂ n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, smul.aux_of, smul_add, add_tmul] | _, _, (eqv.of_add_right m n₁ n₂) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, smul.aux_of, tmul_add] | _, _, (eqv.of_smul s m n) := (add_con.ker_rel _).2 $ by rw [smul.aux_of, smul.aux_of, ←smul_comm, smul_tmul] | _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, add_comm] end⟩ instance : has_scalar R (M ⊗[R] N) := tensor_product.left_has_scalar protected theorem smul_zero (r : R') : (r • 0 : M ⊗[R] N) = 0 := add_monoid_hom.map_zero _ protected theorem smul_add (r : R') (x y : M ⊗[R] N) : r • (x + y) = r • x + r • y := add_monoid_hom.map_add _ _ _ protected theorem zero_smul (x : M ⊗[R] N) : (0 : R'') • x = 0 := have ∀ (r : R'') (m : M) (n : N), r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := λ _ _ _, rfl, tensor_product.induction_on x (by rw tensor_product.smul_zero) (λ m n, by rw [this, zero_smul, zero_tmul]) (λ x y ihx ihy, by rw [tensor_product.smul_add, ihx, ihy, add_zero]) protected theorem one_smul (x : M ⊗[R] N) : (1 : R') • x = x := have ∀ (r : R') (m : M) (n : N), r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := λ _ _ _, rfl, tensor_product.induction_on x (by rw tensor_product.smul_zero) (λ m n, by rw [this, one_smul]) (λ x y ihx ihy, by rw [tensor_product.smul_add, ihx, ihy]) protected theorem add_smul (r s : R'') (x : M ⊗[R] N) : (r + s) • x = r • x + s • x := have ∀ (r : R'') (m : M) (n : N), r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := λ _ _ _, rfl, tensor_product.induction_on x (by simp_rw [tensor_product.smul_zero, add_zero]) (λ m n, by simp_rw [this, add_smul, add_tmul]) (λ x y ihx ihy, by { simp_rw tensor_product.smul_add, rw [ihx, ihy, add_add_add_comm] }) instance : add_comm_monoid (M ⊗[R] N) := { nsmul := λ n v, n • v, nsmul_zero' := by simp [tensor_product.zero_smul], nsmul_succ' := by simp [nat.succ_eq_one_add, tensor_product.one_smul, tensor_product.add_smul], .. tensor_product.add_comm_semigroup _ _, .. tensor_product.add_zero_class _ _} instance left_distrib_mul_action : distrib_mul_action R' (M ⊗[R] N) := have ∀ (r : R') (m : M) (n : N), r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := λ _ _ _, rfl, { smul := (•), smul_add := λ r x y, tensor_product.smul_add r x y, mul_smul := λ r s x, tensor_product.induction_on x (by simp_rw tensor_product.smul_zero) (λ m n, by simp_rw [this, mul_smul]) (λ x y ihx ihy, by { simp_rw tensor_product.smul_add, rw [ihx, ihy] }), one_smul := tensor_product.one_smul, smul_zero := tensor_product.smul_zero } instance : distrib_mul_action R (M ⊗[R] N) := tensor_product.left_distrib_mul_action theorem smul_tmul' (r : R') (m : M) (n : N) : r • (m ⊗ₜ[R] n) = (r • m) ⊗ₜ n := rfl @[simp] lemma tmul_smul [distrib_mul_action R' N] [compatible_smul R R' M N] (r : R') (x : M) (y : N) : x ⊗ₜ (r • y) = r • (x ⊗ₜ[R] y) := (smul_tmul _ _ _).symm instance left_module : module R'' (M ⊗[R] N) := { smul := (•), add_smul := tensor_product.add_smul, zero_smul := tensor_product.zero_smul, ..tensor_product.left_distrib_mul_action } instance : module R (M ⊗[R] N) := tensor_product.left_module section -- Like `R'`, `R'₂` provides a `distrib_mul_action R'₂ (M ⊗[R] N)` variables {R'₂ : Type*} [monoid R'₂] [distrib_mul_action R'₂ M] variables [smul_comm_class R R'₂ M] [has_scalar R'₂ R'] /-- `is_scalar_tower R'₂ R' M` implies `is_scalar_tower R'₂ R' (M ⊗[R] N)` -/ instance is_scalar_tower_left [is_scalar_tower R'₂ R' M] : is_scalar_tower R'₂ R' (M ⊗[R] N) := ⟨λ s r x, tensor_product.induction_on x (by simp) (λ m n, by rw [smul_tmul', smul_tmul', smul_tmul', smul_assoc]) (λ x y ihx ihy, by rw [smul_add, smul_add, smul_add, ihx, ihy])⟩ variables [distrib_mul_action R'₂ N] [distrib_mul_action R' N] variables [compatible_smul R R'₂ M N] [compatible_smul R R' M N] /-- `is_scalar_tower R'₂ R' N` implies `is_scalar_tower R'₂ R' (M ⊗[R] N)` -/ instance is_scalar_tower_right [is_scalar_tower R'₂ R' N] : is_scalar_tower R'₂ R' (M ⊗[R] N) := ⟨λ s r x, tensor_product.induction_on x (by simp) (λ m n, by rw [←tmul_smul, ←tmul_smul, ←tmul_smul, smul_assoc]) (λ x y ihx ihy, by rw [smul_add, smul_add, smul_add, ihx, ihy])⟩ end /-- A short-cut instance for the common case, where the requirements for the `compatible_smul` instances are sufficient. -/ instance is_scalar_tower [has_scalar R' R] [is_scalar_tower R' R M] : is_scalar_tower R' R (M ⊗[R] N) := tensor_product.is_scalar_tower_left -- or right variables (R M N) /-- The canonical bilinear map `M → N → M ⊗[R] N`. -/ def mk : M →ₗ N →ₗ M ⊗[R] N := linear_map.mk₂ R (⊗ₜ) add_tmul (λ c m n, by rw [smul_tmul, tmul_smul]) tmul_add tmul_smul variables {R M N} @[simp] lemma mk_apply (m : M) (n : N) : mk R M N m n = m ⊗ₜ n := rfl lemma ite_tmul (x₁ : M) (x₂ : N) (P : Prop) [decidable P] : (if P then x₁ else 0) ⊗ₜ[R] x₂ = if P then x₁ ⊗ₜ x₂ else 0 := by { split_ifs; simp } lemma tmul_ite (x₁ : M) (x₂ : N) (P : Prop) [decidable P] : x₁ ⊗ₜ[R] (if P then x₂ else 0) = if P then x₁ ⊗ₜ x₂ else 0 := by { split_ifs; simp } section open_locale big_operators lemma sum_tmul {α : Type*} (s : finset α) (m : α → M) (n : N) : (∑ a in s, m a) ⊗ₜ[R] n = ∑ a in s, m a ⊗ₜ[R] n := begin classical, induction s using finset.induction with a s has ih h, { simp, }, { simp [finset.sum_insert has, add_tmul, ih], }, end lemma tmul_sum (m : M) {α : Type*} (s : finset α) (n : α → N) : m ⊗ₜ[R] (∑ a in s, n a) = ∑ a in s, m ⊗ₜ[R] n a := begin classical, induction s using finset.induction with a s has ih h, { simp, }, { simp [finset.sum_insert has, tmul_add, ih], }, end end variables (R M N) /-- The simple (aka pure) elements span the tensor product. -/ lemma span_tmul_eq_top : submodule.span R { t : M ⊗[R] N | ∃ m n, m ⊗ₜ n = t } = ⊤ := begin ext t, simp only [submodule.mem_top, iff_true], apply t.induction_on, { exact submodule.zero_mem _, }, { intros m n, apply submodule.subset_span, use [m, n], }, { intros t₁ t₂ ht₁ ht₂, exact submodule.add_mem _ ht₁ ht₂, }, end end module section UMP variables {M N P Q} variables (f : M →ₗ[R] N →ₗ[R] P) /-- Auxiliary function to constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def lift_aux : (M ⊗[R] N) →+ P := (add_con_gen (tensor_product.eqv R M N)).lift (free_add_monoid.lift $ λ p : M × N, f p.1 p.2) $ add_con.add_con_gen_le $ λ x y hxy, match x, y, hxy with | _, _, (eqv.of_zero_left n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, free_add_monoid.lift_eval_of, f.map_zero₂] | _, _, (eqv.of_zero_right m) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, free_add_monoid.lift_eval_of, (f m).map_zero] | _, _, (eqv.of_add_left m₁ m₂ n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, free_add_monoid.lift_eval_of, f.map_add₂] | _, _, (eqv.of_add_right m n₁ n₂) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, free_add_monoid.lift_eval_of, (f m).map_add] | _, _, (eqv.of_smul r m n) := (add_con.ker_rel _).2 $ by simp_rw [free_add_monoid.lift_eval_of, f.map_smul₂, (f m).map_smul] | _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, add_comm] end lemma lift_aux_tmul (m n) : lift_aux f (m ⊗ₜ n) = f m n := zero_add _ variable {f} @[simp] lemma lift_aux.smul (r : R) (x) : lift_aux f (r • x) = r • lift_aux f x := tensor_product.induction_on x (smul_zero _).symm (λ p q, by rw [← tmul_smul, lift_aux_tmul, lift_aux_tmul, (f p).map_smul]) (λ p q ih1 ih2, by rw [smul_add, (lift_aux f).map_add, ih1, ih2, (lift_aux f).map_add, smul_add]) variable (f) /-- Constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def lift : M ⊗ N →ₗ P := { map_smul' := lift_aux.smul, .. lift_aux f } variable {f} @[simp] lemma lift.tmul (x y) : lift f (x ⊗ₜ y) = f x y := zero_add _ @[simp] lemma lift.tmul' (x y) : (lift f).1 (x ⊗ₜ y) = f x y := lift.tmul _ _ theorem ext {g h : (M ⊗[R] N) →ₗ[R] P} (H : ∀ x y, g (x ⊗ₜ y) = h (x ⊗ₜ y)) : g = h := linear_map.ext $ λ z, tensor_product.induction_on z (by simp_rw linear_map.map_zero) H $ λ x y ihx ihy, by rw [g.map_add, h.map_add, ihx, ihy] theorem lift.unique {g : (M ⊗[R] N) →ₗ[R] P} (H : ∀ x y, g (x ⊗ₜ y) = f x y) : g = lift f := ext $ λ m n, by rw [H, lift.tmul] theorem lift_mk : lift (mk R M N) = linear_map.id := eq.symm $ lift.unique $ λ x y, rfl theorem lift_compr₂ (g : P →ₗ Q) : lift (f.compr₂ g) = g.comp (lift f) := eq.symm $ lift.unique $ λ x y, by simp theorem lift_mk_compr₂ (f : M ⊗ N →ₗ P) : lift ((mk R M N).compr₂ f) = f := by rw [lift_compr₂ f, lift_mk, linear_map.comp_id] /-- Using this as the `@[ext]` lemma instead of `tensor_product.ext` allows `ext` to apply lemmas specific to `M →ₗ _` and `N →ₗ _`. See note [partially-applied ext lemmas]. -/ @[ext] theorem mk_compr₂_inj {g h : M ⊗ N →ₗ P} (H : (mk R M N).compr₂ g = (mk R M N).compr₂ h) : g = h := by rw [← lift_mk_compr₂ g, H, lift_mk_compr₂] example : M → N → (M → N → P) → P := λ m, flip $ λ f, f m variables (R M N P) /-- Linearly constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def uncurry : (M →ₗ[R] N →ₗ[R] P) →ₗ[R] M ⊗[R] N →ₗ[R] P := linear_map.flip $ lift $ (linear_map.lflip _ _ _ _).comp (linear_map.flip linear_map.id) variables {R M N P} @[simp] theorem uncurry_apply (f : M →ₗ[R] N →ₗ[R] P) (m : M) (n : N) : uncurry R M N P f (m ⊗ₜ n) = f m n := by rw [uncurry, linear_map.flip_apply, lift.tmul]; refl variables (R M N P) /-- A linear equivalence constructing a linear map `M ⊗ N → P` given a bilinear map `M → N → P` with the property that its composition with the canonical bilinear map `M → N → M ⊗ N` is the given bilinear map `M → N → P`. -/ def lift.equiv : (M →ₗ N →ₗ P) ≃ₗ (M ⊗ N →ₗ P) := { inv_fun := λ f, (mk R M N).compr₂ f, left_inv := λ f, linear_map.ext₂ $ λ m n, lift.tmul _ _, right_inv := λ f, ext $ λ m n, lift.tmul _ _, .. uncurry R M N P } @[simp] lemma lift.equiv_apply (f : M →ₗ[R] N →ₗ[R] P) (m : M) (n : N) : lift.equiv R M N P f (m ⊗ₜ n) = f m n := uncurry_apply f m n @[simp] lemma lift.equiv_symm_apply (f : M ⊗[R] N →ₗ[R] P) (m : M) (n : N) : (lift.equiv R M N P).symm f m n = f (m ⊗ₜ n) := rfl /-- Given a linear map `M ⊗ N → P`, compose it with the canonical bilinear map `M → N → M ⊗ N` to form a bilinear map `M → N → P`. -/ def lcurry : (M ⊗[R] N →ₗ[R] P) →ₗ[R] M →ₗ[R] N →ₗ[R] P := (lift.equiv R M N P).symm variables {R M N P} @[simp] theorem lcurry_apply (f : M ⊗[R] N →ₗ[R] P) (m : M) (n : N) : lcurry R M N P f m n = f (m ⊗ₜ n) := rfl /-- Given a linear map `M ⊗ N → P`, compose it with the canonical bilinear map `M → N → M ⊗ N` to form a bilinear map `M → N → P`. -/ def curry (f : M ⊗ N →ₗ P) : M →ₗ N →ₗ P := lcurry R M N P f @[simp] theorem curry_apply (f : M ⊗ N →ₗ[R] P) (m : M) (n : N) : curry f m n = f (m ⊗ₜ n) := rfl lemma curry_injective : function.injective (curry : (M ⊗[R] N →ₗ[R] P) → (M →ₗ[R] N →ₗ[R] P)) := λ g h H, mk_compr₂_inj H theorem ext_threefold {g h : (M ⊗[R] N) ⊗[R] P →ₗ[R] Q} (H : ∀ x y z, g ((x ⊗ₜ y) ⊗ₜ z) = h ((x ⊗ₜ y) ⊗ₜ z)) : g = h := begin ext x y z, exact H x y z end -- We'll need this one for checking the pentagon identity! theorem ext_fourfold {g h : ((M ⊗[R] N) ⊗[R] P) ⊗[R] Q →ₗ[R] S} (H : ∀ w x y z, g (((w ⊗ₜ x) ⊗ₜ y) ⊗ₜ z) = h (((w ⊗ₜ x) ⊗ₜ y) ⊗ₜ z)) : g = h := begin ext w x y z, exact H w x y z, end end UMP variables {M N} section variables (R M) /-- The base ring is a left identity for the tensor product of modules, up to linear equivalence. -/ protected def lid : R ⊗ M ≃ₗ M := linear_equiv.of_linear (lift $ linear_map.lsmul R M) (mk R R M 1) (linear_map.ext $ λ _, by simp) (ext $ λ r m, by simp; rw [← tmul_smul, ← smul_tmul, smul_eq_mul, mul_one]) end @[simp] theorem lid_tmul (m : M) (r : R) : ((tensor_product.lid R M) : (R ⊗ M → M)) (r ⊗ₜ m) = r • m := begin dsimp [tensor_product.lid], simp, end @[simp] lemma lid_symm_apply (m : M) : (tensor_product.lid R M).symm m = 1 ⊗ₜ m := rfl section variables (R M N) /-- The tensor product of modules is commutative, up to linear equivalence. -/ protected def comm : M ⊗ N ≃ₗ N ⊗ M := linear_equiv.of_linear (lift (mk R N M).flip) (lift (mk R M N).flip) (ext $ λ m n, rfl) (ext $ λ m n, rfl) @[simp] theorem comm_tmul (m : M) (n : N) : (tensor_product.comm R M N) (m ⊗ₜ n) = n ⊗ₜ m := rfl @[simp] theorem comm_symm_tmul (m : M) (n : N) : (tensor_product.comm R M N).symm (n ⊗ₜ m) = m ⊗ₜ n := rfl end section variables (R M) /-- The base ring is a right identity for the tensor product of modules, up to linear equivalence. -/ protected def rid : M ⊗[R] R ≃ₗ M := linear_equiv.trans (tensor_product.comm R M R) (tensor_product.lid R M) end @[simp] theorem rid_tmul (m : M) (r : R) : (tensor_product.rid R M) (m ⊗ₜ r) = r • m := begin dsimp [tensor_product.rid, tensor_product.comm, tensor_product.lid], simp, end @[simp] lemma rid_symm_apply (m : M) : (tensor_product.rid R M).symm m = m ⊗ₜ 1 := rfl open linear_map section variables (R M N P) /-- The associator for tensor product of R-modules, as a linear equivalence. -/ protected def assoc : (M ⊗[R] N) ⊗[R] P ≃ₗ[R] M ⊗[R] (N ⊗[R] P) := begin refine linear_equiv.of_linear (lift $ lift $ comp (lcurry R _ _ _) $ mk _ _ _) (lift $ comp (uncurry R _ _ _) $ curry $ mk _ _ _) (mk_compr₂_inj $ linear_map.ext $ λ m, ext $ λ n p, _) (mk_compr₂_inj $ flip_inj $ linear_map.ext $ λ p, ext $ λ m n, _); repeat { rw lift.tmul <|> rw compr₂_apply <|> rw comp_apply <|> rw mk_apply <|> rw flip_apply <|> rw lcurry_apply <|> rw uncurry_apply <|> rw curry_apply <|> rw id_apply } end end @[simp] theorem assoc_tmul (m : M) (n : N) (p : P) : (tensor_product.assoc R M N P) ((m ⊗ₜ n) ⊗ₜ p) = m ⊗ₜ (n ⊗ₜ p) := rfl @[simp] theorem assoc_symm_tmul (m : M) (n : N) (p : P) : (tensor_product.assoc R M N P).symm (m ⊗ₜ (n ⊗ₜ p)) = (m ⊗ₜ n) ⊗ₜ p := rfl /-- The tensor product of a pair of linear maps between modules. -/ def map (f : M →ₗ[R] P) (g : N →ₗ Q) : M ⊗ N →ₗ[R] P ⊗ Q := lift $ comp (compl₂ (mk _ _ _) g) f @[simp] theorem map_tmul (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (m : M) (n : N) : map f g (m ⊗ₜ n) = f m ⊗ₜ g n := rfl lemma map_range_eq_span_tmul (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (map f g).range = submodule.span R { t | ∃ m n, (f m) ⊗ₜ (g n) = t } := begin simp only [← submodule.map_top, ← span_tmul_eq_top, submodule.map_span, set.mem_image, set.mem_set_of_eq], congr, ext t, split, { rintros ⟨_, ⟨⟨m, n, rfl⟩, rfl⟩⟩, use [m, n], simp only [map_tmul], }, { rintros ⟨m, n, rfl⟩, use [m ⊗ₜ n, m, n], simp only [map_tmul], }, end /-- Given submodules `p ⊆ P` and `q ⊆ Q`, this is the natural map: `p ⊗ q → P ⊗ Q`. -/ @[simp] def map_incl (p : submodule R P) (q : submodule R Q) : p ⊗[R] q →ₗ[R] P ⊗[R] Q := map p.subtype q.subtype section variables {P' Q' : Type*} variables [add_comm_monoid P'] [module R P'] variables [add_comm_monoid Q'] [module R Q'] lemma map_comp (f₂ : P →ₗ[R] P') (f₁ : M →ₗ[R] P) (g₂ : Q →ₗ[R] Q') (g₁ : N →ₗ[R] Q) : map (f₂.comp f₁) (g₂.comp g₁) = (map f₂ g₂).comp (map f₁ g₁) := ext $ λ _ _, by simp only [linear_map.comp_apply, map_tmul] lemma lift_comp_map (i : P →ₗ[R] Q →ₗ[R] Q') (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (lift i).comp (map f g) = lift ((i.comp f).compl₂ g) := ext $ λ _ _, by simp only [lift.tmul, map_tmul, linear_map.compl₂_apply, linear_map.comp_apply] @[simp] lemma map_id : map (id : M →ₗ[R] M) (id : N →ₗ[R] N) = id := by { ext, simp only [mk_apply, id_coe, compr₂_apply, id.def, map_tmul], } @[simp] lemma map_one : map (1 : M →ₗ[R] M) (1 : N →ₗ[R] N) = 1 := map_id lemma map_mul (f₁ f₂ : M →ₗ[R] M) (g₁ g₂ : N →ₗ[R] N) : map (f₁ * f₂) (g₁ * g₂) = (map f₁ g₁) * (map f₂ g₂) := map_comp f₁ f₂ g₁ g₂ @[simp] lemma map_pow (f : M →ₗ[R] M) (g : N →ₗ[R] N) (n : ℕ) : (map f g)^n = map (f^n) (g^n) := begin induction n with n ih, { simp only [pow_zero, map_one], }, { simp only [pow_succ', ih, map_mul], }, end end /-- If `M` and `P` are linearly equivalent and `N` and `Q` are linearly equivalent then `M ⊗ N` and `P ⊗ Q` are linearly equivalent. -/ def congr (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) : M ⊗ N ≃ₗ[R] P ⊗ Q := linear_equiv.of_linear (map f g) (map f.symm g.symm) (ext $ λ m n, by simp; simp only [linear_equiv.apply_symm_apply]) (ext $ λ m n, by simp; simp only [linear_equiv.symm_apply_apply]) @[simp] theorem congr_tmul (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (m : M) (n : N) : congr f g (m ⊗ₜ n) = f m ⊗ₜ g n := rfl @[simp] theorem congr_symm_tmul (f : M ≃ₗ[R] P) (g : N ≃ₗ[R] Q) (p : P) (q : Q) : (congr f g).symm (p ⊗ₜ q) = f.symm p ⊗ₜ g.symm q := rfl variables (R M N P Q) /-- A tensor product analogue of `mul_left_comm`. -/ def left_comm : M ⊗[R] (N ⊗[R] P) ≃ₗ[R] N ⊗[R] (M ⊗[R] P) := let e₁ := (tensor_product.assoc R M N P).symm, e₂ := congr (tensor_product.comm R M N) (1 : P ≃ₗ[R] P), e₃ := (tensor_product.assoc R N M P) in e₁.trans $ e₂.trans e₃ variables {M N P Q} @[simp] lemma left_comm_tmul (m : M) (n : N) (p : P) : left_comm R M N P (m ⊗ₜ (n ⊗ₜ p)) = n ⊗ₜ (m ⊗ₜ p) := rfl @[simp] lemma left_comm_symm_tmul (m : M) (n : N) (p : P) : (left_comm R M N P).symm (n ⊗ₜ (m ⊗ₜ p)) = m ⊗ₜ (n ⊗ₜ p) := rfl variables (M N P Q) /-- This special case is worth defining explicitly since it is useful for defining multiplication on tensor products of modules carrying multiplications (e.g., associative rings, Lie rings, ...). E.g., suppose `M = P` and `N = Q` and that `M` and `N` carry bilinear multiplications: `M ⊗ M → M` and `N ⊗ N → N`. Using `map`, we can define `(M ⊗ M) ⊗ (N ⊗ N) → M ⊗ N` which, when combined with this definition, yields a bilinear multiplication on `M ⊗ N`: `(M ⊗ N) ⊗ (M ⊗ N) → M ⊗ N`. In particular we could use this to define the multiplication in the `tensor_product.semiring` instance (currently defined "by hand" using `tensor_product.mul`). See also `mul_mul_mul_comm`. -/ def tensor_tensor_tensor_comm : (M ⊗[R] N) ⊗[R] (P ⊗[R] Q) ≃ₗ[R] (M ⊗[R] P) ⊗[R] (N ⊗[R] Q) := let e₁ := tensor_product.assoc R M N (P ⊗[R] Q), e₂ := congr (1 : M ≃ₗ[R] M) (left_comm R N P Q), e₃ := (tensor_product.assoc R M P (N ⊗[R] Q)).symm in e₁.trans $ e₂.trans e₃ variables {M N P Q} @[simp] lemma tensor_tensor_tensor_comm_tmul (m : M) (n : N) (p : P) (q : Q) : tensor_tensor_tensor_comm R M N P Q ((m ⊗ₜ n) ⊗ₜ (p ⊗ₜ q)) = (m ⊗ₜ p) ⊗ₜ (n ⊗ₜ q) := rfl @[simp] lemma tensor_tensor_tensor_comm_symm_tmul (m : M) (n : N) (p : P) (q : Q) : (tensor_tensor_tensor_comm R M N P Q).symm ((m ⊗ₜ p) ⊗ₜ (n ⊗ₜ q)) = (m ⊗ₜ n) ⊗ₜ (p ⊗ₜ q) := rfl end tensor_product namespace linear_map variables {R} (M) {N P Q} /-- `ltensor M f : M ⊗ N →ₗ M ⊗ P` is the natural linear map induced by `f : N →ₗ P`. -/ def ltensor (f : N →ₗ[R] P) : M ⊗ N →ₗ[R] M ⊗ P := tensor_product.map id f /-- `rtensor f M : N₁ ⊗ M →ₗ N₂ ⊗ M` is the natural linear map induced by `f : N₁ →ₗ N₂`. -/ def rtensor (f : N →ₗ[R] P) : N ⊗ M →ₗ[R] P ⊗ M := tensor_product.map f id variables (g : P →ₗ[R] Q) (f : N →ₗ[R] P) @[simp] lemma ltensor_tmul (m : M) (n : N) : f.ltensor M (m ⊗ₜ n) = m ⊗ₜ (f n) := rfl @[simp] lemma rtensor_tmul (m : M) (n : N) : f.rtensor M (n ⊗ₜ m) = (f n) ⊗ₜ m := rfl open tensor_product /-- `ltensor_hom M` is the natural linear map that sends a linear map `f : N →ₗ P` to `M ⊗ f`. -/ def ltensor_hom : (N →ₗ[R] P) →ₗ[R] (M ⊗[R] N →ₗ[R] M ⊗[R] P) := { to_fun := ltensor M, map_add' := λ f g, by { ext x y, simp only [compr₂_apply, mk_apply, add_apply, ltensor_tmul, tmul_add] }, map_smul' := λ r f, by { ext x y, simp only [compr₂_apply, mk_apply, tmul_smul, smul_apply, ltensor_tmul] } } /-- `rtensor_hom M` is the natural linear map that sends a linear map `f : N →ₗ P` to `M ⊗ f`. -/ def rtensor_hom : (N →ₗ[R] P) →ₗ[R] (N ⊗[R] M →ₗ[R] P ⊗[R] M) := { to_fun := λ f, f.rtensor M, map_add' := λ f g, by { ext x y, simp only [compr₂_apply, mk_apply, add_apply, rtensor_tmul, add_tmul] }, map_smul' := λ r f, by { ext x y, simp only [compr₂_apply, mk_apply, smul_tmul, tmul_smul, smul_apply, rtensor_tmul] } } @[simp] lemma coe_ltensor_hom : (ltensor_hom M : (N →ₗ[R] P) → (M ⊗[R] N →ₗ[R] M ⊗[R] P)) = ltensor M := rfl @[simp] lemma coe_rtensor_hom : (rtensor_hom M : (N →ₗ[R] P) → (N ⊗[R] M →ₗ[R] P ⊗[R] M)) = rtensor M := rfl @[simp] lemma ltensor_add (f g : N →ₗ[R] P) : (f + g).ltensor M = f.ltensor M + g.ltensor M := (ltensor_hom M).map_add f g @[simp] lemma rtensor_add (f g : N →ₗ[R] P) : (f + g).rtensor M = f.rtensor M + g.rtensor M := (rtensor_hom M).map_add f g @[simp] lemma ltensor_zero : ltensor M (0 : N →ₗ[R] P) = 0 := (ltensor_hom M).map_zero @[simp] lemma rtensor_zero : rtensor M (0 : N →ₗ[R] P) = 0 := (rtensor_hom M).map_zero @[simp] lemma ltensor_smul (r : R) (f : N →ₗ[R] P) : (r • f).ltensor M = r • (f.ltensor M) := (ltensor_hom M).map_smul r f @[simp] lemma rtensor_smul (r : R) (f : N →ₗ[R] P) : (r • f).rtensor M = r • (f.rtensor M) := (rtensor_hom M).map_smul r f lemma ltensor_comp : (g.comp f).ltensor M = (g.ltensor M).comp (f.ltensor M) := by { ext m n, simp only [compr₂_apply, mk_apply, comp_apply, ltensor_tmul] } lemma rtensor_comp : (g.comp f).rtensor M = (g.rtensor M).comp (f.rtensor M) := by { ext m n, simp only [compr₂_apply, mk_apply, comp_apply, rtensor_tmul] } lemma ltensor_mul (f g : module.End R N) : (f * g).ltensor M = (f.ltensor M) * (g.ltensor M) := ltensor_comp M f g lemma rtensor_mul (f g : module.End R N) : (f * g).rtensor M = (f.rtensor M) * (g.rtensor M) := rtensor_comp M f g variables (N) @[simp] lemma ltensor_id : (id : N →ₗ[R] N).ltensor M = id := map_id @[simp] lemma rtensor_id : (id : N →ₗ[R] N).rtensor M = id := map_id variables {N} @[simp] lemma ltensor_comp_rtensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (g.ltensor P).comp (f.rtensor N) = map f g := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] @[simp] lemma rtensor_comp_ltensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (f.rtensor Q).comp (g.ltensor M) = map f g := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] @[simp] lemma map_comp_rtensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (f' : S →ₗ[R] M) : (map f g).comp (f'.rtensor _) = map (f.comp f') g := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] @[simp] lemma map_comp_ltensor (f : M →ₗ[R] P) (g : N →ₗ[R] Q) (g' : S →ₗ[R] N) : (map f g).comp (g'.ltensor _) = map f (g.comp g') := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] @[simp] lemma rtensor_comp_map (f' : P →ₗ[R] S) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (f'.rtensor _).comp (map f g) = map (f'.comp f) g := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] @[simp] lemma ltensor_comp_map (g' : Q →ₗ[R] S) (f : M →ₗ[R] P) (g : N →ₗ[R] Q) : (g'.ltensor _).comp (map f g) = map f (g'.comp g) := by simp only [ltensor, rtensor, ← map_comp, id_comp, comp_id] variables {M} @[simp] lemma rtensor_pow (f : M →ₗ[R] M) (n : ℕ) : (f.rtensor N)^n = (f^n).rtensor N := by { have h := map_pow f (id : N →ₗ[R] N) n, rwa id_pow at h, } @[simp] lemma ltensor_pow (f : N →ₗ[R] N) (n : ℕ) : (f.ltensor M)^n = (f^n).ltensor M := by { have h := map_pow (id : M →ₗ[R] M) f n, rwa id_pow at h, } end linear_map end semiring section ring variables {R : Type*} [comm_semiring R] variables {M : Type*} {N : Type*} {P : Type*} {Q : Type*} {S : Type*} variables [add_comm_group M] [add_comm_group N] [add_comm_group P] [add_comm_group Q] [add_comm_group S] variables [module R M] [module R N] [module R P] [module R Q] [module R S] namespace tensor_product open_locale tensor_product open linear_map variables (R) /-- Auxiliary function to defining negation multiplication on tensor product. -/ def neg.aux : free_add_monoid (M × N) →+ M ⊗[R] N := free_add_monoid.lift $ λ p : M × N, (-p.1) ⊗ₜ p.2 variables {R} theorem neg.aux_of (m : M) (n : N) : neg.aux R (free_add_monoid.of (m, n)) = (-m) ⊗ₜ[R] n := rfl instance : has_neg (M ⊗[R] N) := { neg := (add_con_gen (tensor_product.eqv R M N)).lift (neg.aux R) $ add_con.add_con_gen_le $ λ x y hxy, match x, y, hxy with | _, _, (eqv.of_zero_left n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, neg.aux_of, neg_zero, zero_tmul] | _, _, (eqv.of_zero_right m) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_zero, neg.aux_of, tmul_zero] | _, _, (eqv.of_add_left m₁ m₂ n) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, neg.aux_of, neg_add, add_tmul] | _, _, (eqv.of_add_right m n₁ n₂) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, neg.aux_of, tmul_add] | _, _, (eqv.of_smul s m n) := (add_con.ker_rel _).2 $ by simp_rw [neg.aux_of, tmul_smul s, smul_tmul', smul_neg] | _, _, (eqv.add_comm x y) := (add_con.ker_rel _).2 $ by simp_rw [add_monoid_hom.map_add, add_comm] end } protected theorem add_left_neg (x : M ⊗[R] N) : -x + x = 0 := tensor_product.induction_on x (by { rw [add_zero], apply (neg.aux R).map_zero, }) (λ x y, by { convert (add_tmul (-x) x y).symm, rw [add_left_neg, zero_tmul], }) (λ x y hx hy, by { unfold has_neg.neg sub_neg_monoid.neg, rw add_monoid_hom.map_add, ac_change (-x + x) + (-y + y) = 0, rw [hx, hy, add_zero], }) instance : add_comm_group (M ⊗[R] N) := { neg := has_neg.neg, sub := _, sub_eq_add_neg := λ _ _, rfl, add_left_neg := λ x, by exact tensor_product.add_left_neg x, gsmul := λ n v, n • v, gsmul_zero' := by simp [tensor_product.zero_smul], gsmul_succ' := by simp [nat.succ_eq_one_add, tensor_product.one_smul, tensor_product.add_smul], gsmul_neg' := λ n x, begin change (- n.succ : ℤ) • x = - (((n : ℤ) + 1) • x), rw [← zero_add (-↑(n.succ) • x), ← tensor_product.add_left_neg (↑(n.succ) • x), add_assoc, ← add_smul, ← sub_eq_add_neg, sub_self, zero_smul, add_zero], refl, end, .. tensor_product.add_comm_monoid } lemma neg_tmul (m : M) (n : N) : (-m) ⊗ₜ n = -(m ⊗ₜ[R] n) := rfl lemma tmul_neg (m : M) (n : N) : m ⊗ₜ (-n) = -(m ⊗ₜ[R] n) := (mk R M N _).map_neg _ lemma tmul_sub (m : M) (n₁ n₂ : N) : m ⊗ₜ (n₁ - n₂) = (m ⊗ₜ[R] n₁) - (m ⊗ₜ[R] n₂) := (mk R M N _).map_sub _ _ lemma sub_tmul (m₁ m₂ : M) (n : N) : (m₁ - m₂) ⊗ₜ n = (m₁ ⊗ₜ[R] n) - (m₂ ⊗ₜ[R] n) := (mk R M N).map_sub₂ _ _ _ /-- While the tensor product will automatically inherit a ℤ-module structure from `add_comm_group.int_module`, that structure won't be compatible with lemmas like `tmul_smul` unless we use a `ℤ-module` instance provided by `tensor_product.left_module`. When `R` is a `ring` we get the required `tensor_product.compatible_smul` instance through `is_scalar_tower`, but when it is only a `semiring` we need to build it from scratch. The instance diamond in `compatible_smul` doesn't matter because it's in `Prop`. -/ instance compatible_smul.int [module ℤ M] [module ℤ N] : compatible_smul R ℤ M N := ⟨λ r m n, int.induction_on r (by simp) (λ r ih, by simpa [add_smul, tmul_add, add_tmul] using ih) (λ r ih, by simpa [sub_smul, tmul_sub, sub_tmul] using ih)⟩ instance compatible_smul.unit {S} [monoid S] [distrib_mul_action S M] [distrib_mul_action S N] [compatible_smul R S M N] : compatible_smul R (units S) M N := ⟨λ s m n, (compatible_smul.smul_tmul (s : S) m n : _)⟩ end tensor_product namespace linear_map @[simp] lemma ltensor_sub (f g : N →ₗ[R] P) : (f - g).ltensor M = f.ltensor M - g.ltensor M := by simp only [← coe_ltensor_hom, map_sub] @[simp] lemma rtensor_sub (f g : N →ₗ[R] P) : (f - g).rtensor M = f.rtensor M - g.rtensor M := by simp only [← coe_rtensor_hom, map_sub] @[simp] lemma ltensor_neg (f : N →ₗ[R] P) : (-f).ltensor M = -(f.ltensor M) := by simp only [← coe_ltensor_hom, map_neg] @[simp] lemma rtensor_neg (f : N →ₗ[R] P) : (-f).rtensor M = -(f.rtensor M) := by simp only [← coe_rtensor_hom, map_neg] end linear_map end ring
6f27b2b91151397ddaf60e21e91dfca03d37d967
46125763b4dbf50619e8846a1371029346f4c3db
/src/topology/local_homeomorph.lean
cd2f988f24ee9b46082034fd89bd4671b24860f6
[ "Apache-2.0" ]
permissive
thjread/mathlib
a9d97612cedc2c3101060737233df15abcdb9eb1
7cffe2520a5518bba19227a107078d83fa725ddc
refs/heads/master
1,615,637,696,376
1,583,953,063,000
1,583,953,063,000
246,680,271
0
0
Apache-2.0
1,583,960,875,000
1,583,960,875,000
null
UTF-8
Lean
false
false
27,894
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import data.equiv.local_equiv topology.continuous_on topology.homeomorph /-! # Local homeomorphisms This file defines homeomorphisms between open subsets of topological spaces. An element `e` of `local_homeomorph α β` is an extension of `local_equiv α β`, i.e., it is a pair of functions `e.to_fun` and `e.inv_fun`, inverse of each other on the sets `e.source` and `e.target`. Additionally, we require that these sets are open, and that the functions are continuous on them. Equivalently, they are homeomorphisms there. Contrary to equivs, we do not register the coercion to functions and we use explicitly to_fun and inv_fun: coercions create unification problems for manifolds. ## Main definitions `homeomorph.to_local_homeomorph`: associating a local homeomorphism to a homeomorphism, with source = target = univ `local_homeomorph.symm` : the inverse of a local homeomorphism `local_homeomorph.trans` : the composition of two local homeomorphisms `local_homeomorph.refl` : the identity local homeomorphism `local_homeomorph.of_set`: the identity on a set `s` `eq_on_source` : equivalence relation describing the "right" notion of equality for local homeomorphisms ## Implementation notes Most statements are copied from their local_equiv versions, although some care is required especially when restricting to subsets, as these should be open subsets. For design notes, see `local_equiv.lean`. -/ open function set open_locale topological_space variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} [topological_space α] [topological_space β] [topological_space γ] [topological_space δ] /-- local homeomorphisms, defined on open subsets of the space -/ structure local_homeomorph (α : Type*) (β : Type*) [topological_space α] [topological_space β] extends local_equiv α β := (open_source : is_open source) (open_target : is_open target) (continuous_to_fun : continuous_on to_fun source) (continuous_inv_fun : continuous_on inv_fun target) /-- A homeomorphism induces a local homeomorphism on the whole space -/ def homeomorph.to_local_homeomorph (e : homeomorph α β) : local_homeomorph α β := { open_source := is_open_univ, open_target := is_open_univ, continuous_to_fun := by { erw ← continuous_iff_continuous_on_univ, exact e.continuous_to_fun }, continuous_inv_fun := by { erw ← continuous_iff_continuous_on_univ, exact e.continuous_inv_fun }, ..e.to_equiv.to_local_equiv } namespace local_homeomorph variables (e : local_homeomorph α β) (e' : local_homeomorph β γ) lemma eq_of_local_equiv_eq {e e' : local_homeomorph α β} (h : e.to_local_equiv = e'.to_local_equiv) : e = e' := begin cases e, cases e', dsimp at *, induction h, refl end /-- Two local homeomorphisms are equal when they have equal to_fun, inv_fun and source. It is not sufficient to have equal to_fun and source, as this only determines inv_fun on the target. This would only be true for a weaker notion of equality, arguably the right one, called `eq_on_source`. -/ @[ext] protected lemma ext (e' : local_homeomorph α β) (h : ∀x, e.to_fun x = e'.to_fun x) (hinv: ∀x, e.inv_fun x = e'.inv_fun x) (hs : e.source = e'.source) : e = e' := eq_of_local_equiv_eq (local_equiv.ext e.to_local_equiv e'.to_local_equiv h hinv hs) /-- The inverse of a local homeomorphism -/ protected def symm : local_homeomorph β α := { open_source := e.open_target, open_target := e.open_source, continuous_to_fun := e.continuous_inv_fun, continuous_inv_fun := e.continuous_to_fun, ..e.to_local_equiv.symm } @[simp] lemma symm_to_local_equiv : e.symm.to_local_equiv = e.to_local_equiv.symm := rfl -- The following lemmas are already simp via local_equiv lemma symm_to_fun : e.symm.to_fun = e.inv_fun := rfl lemma symm_inv_fun : e.symm.inv_fun = e.to_fun := rfl lemma symm_source : e.symm.source = e.target := rfl lemma symm_target : e.symm.target = e.source := rfl @[simp] lemma symm_symm : e.symm.symm = e := eq_of_local_equiv_eq $ by simp /-- A local homeomorphism is continuous at any point of its source -/ lemma continuous_at_to_fun {x : α} (h : x ∈ e.source) : continuous_at e.to_fun x := (e.continuous_to_fun x h).continuous_at (mem_nhds_sets e.open_source h) /-- A local homeomorphism inverse is continuous at any point of its target -/ lemma continuous_at_inv_fun {x : β} (h : x ∈ e.target) : continuous_at e.inv_fun x := e.symm.continuous_at_to_fun h /-- Preimage of interior or interior of preimage coincide for local homeomorphisms, when restricted to the source. -/ lemma preimage_interior (s : set β) : e.source ∩ e.to_fun ⁻¹' (interior s) = e.source ∩ interior (e.to_fun ⁻¹' s) := begin apply subset.antisymm, { exact e.continuous_to_fun.preimage_interior_subset_interior_preimage e.open_source }, { calc e.source ∩ interior (e.to_fun ⁻¹' s) = (e.source ∩ e.to_fun ⁻¹' e.target) ∩ interior (e.to_fun ⁻¹' s) : begin congr, apply (inter_eq_self_of_subset_left _).symm, apply e.to_local_equiv.source_subset_preimage_target, end ... = (e.source ∩ interior (e.to_fun ⁻¹' s)) ∩ (e.to_fun ⁻¹' e.target) : by simp [inter_comm, inter_assoc] ... = (e.source ∩ e.to_fun ⁻¹' (e.inv_fun ⁻¹' (interior (e.to_fun ⁻¹' s)))) ∩ (e.to_fun ⁻¹' e.target) : by rw e.to_local_equiv.source_inter_preimage_inv_preimage ... = e.source ∩ e.to_fun ⁻¹' (e.target ∩ e.inv_fun ⁻¹' (interior (e.to_fun ⁻¹' s))) : by rw [inter_comm e.target, preimage_inter, inter_assoc] ... ⊆ e.source ∩ e.to_fun ⁻¹' (e.target ∩ interior (e.inv_fun ⁻¹' (e.to_fun ⁻¹' s))) : begin apply inter_subset_inter (subset.refl _) (preimage_mono _), exact e.continuous_inv_fun.preimage_interior_subset_interior_preimage e.open_target end ... = e.source ∩ e.to_fun ⁻¹' (interior (e.target ∩ e.inv_fun ⁻¹' (e.to_fun ⁻¹' s))) : by rw [interior_inter, interior_eq_of_open e.open_target] ... = e.source ∩ e.to_fun ⁻¹' (interior (e.target ∩ s)) : by rw e.to_local_equiv.target_inter_inv_preimage_preimage ... = e.source ∩ e.to_fun ⁻¹' e.target ∩ e.to_fun ⁻¹' (interior s) : by rw [interior_inter, preimage_inter, interior_eq_of_open e.open_target, inter_assoc] ... = e.source ∩ e.to_fun ⁻¹' (interior s) : begin congr, apply inter_eq_self_of_subset_left, apply e.to_local_equiv.source_subset_preimage_target end } end /-- The image of an open set in the source is open. -/ lemma image_open_of_open {s : set α} (hs : is_open s) (h : s ⊆ e.source) : is_open (e.to_fun '' s) := begin have : e.to_fun '' s = e.target ∩ e.inv_fun ⁻¹' s := e.to_local_equiv.image_eq_target_inter_inv_preimage h, rw this, exact e.continuous_inv_fun.preimage_open_of_open e.open_target hs end /-- Restricting a local homeomorphism `e` to `e.source ∩ s` when `s` is open. This is sometimes hard to use because of the openness assumption, but it has the advantage that when it can be used then its local_equiv is defeq to local_equiv.restr -/ protected def restr_open (s : set α) (hs : is_open s) : local_homeomorph α β := { open_source := is_open_inter e.open_source hs, open_target := (continuous_on_open_iff e.open_target).1 e.continuous_inv_fun s hs, continuous_to_fun := e.continuous_to_fun.mono (inter_subset_left _ _), continuous_inv_fun := e.continuous_inv_fun.mono (inter_subset_left _ _), ..e.to_local_equiv.restr s} @[simp] lemma restr_open_to_local_equiv (s : set α) (hs : is_open s) : (e.restr_open s hs).to_local_equiv = e.to_local_equiv.restr s := rfl -- Already simp via local_equiv lemma restr_open_source (s : set α) (hs : is_open s) : (e.restr_open s hs).source = e.source ∩ s := rfl /-- Restricting a local homeomorphism `e` to `e.source ∩ interior s`. We use the interior to make sure that the restriction is well defined whatever the set s, since local homeomorphisms are by definition defined on open sets. In applications where `s` is open, this coincides with the restriction of local equivalences -/ protected def restr (s : set α) : local_homeomorph α β := e.restr_open (interior s) is_open_interior @[simp] lemma restr_to_local_equiv (s : set α) : (e.restr s).to_local_equiv = (e.to_local_equiv).restr (interior s) := rfl -- The following lemmas are already simp via local_equiv lemma restr_to_fun (s : set α) : (e.restr s).to_fun = e.to_fun := rfl lemma restr_inv_fun (s : set α) : (e.restr s).inv_fun = e.inv_fun := rfl lemma restr_source (s : set α) : (e.restr s).source = e.source ∩ interior s := rfl lemma restr_target (s : set α) : (e.restr s).target = e.target ∩ e.inv_fun ⁻¹' (interior s) := rfl lemma restr_source' (s : set α) (hs : is_open s) : (e.restr s).source = e.source ∩ s := by rw [e.restr_source, interior_eq_of_open hs] lemma restr_to_local_equiv' (s : set α) (hs : is_open s): (e.restr s).to_local_equiv = e.to_local_equiv.restr s := by rw [e.restr_to_local_equiv, interior_eq_of_open hs] lemma restr_eq_of_source_subset {e : local_homeomorph α β} {s : set α} (h : e.source ⊆ s) : e.restr s = e := begin apply eq_of_local_equiv_eq, rw restr_to_local_equiv, apply local_equiv.restr_eq_of_source_subset, have := interior_mono h, rwa interior_eq_of_open (e.open_source) at this end @[simp] lemma restr_univ {e : local_homeomorph α β} : e.restr univ = e := restr_eq_of_source_subset (subset_univ _) lemma restr_source_inter (s : set α) : e.restr (e.source ∩ s) = e.restr s := begin refine local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) _, simp [interior_eq_of_open e.open_source], rw [← inter_assoc, inter_self] end /-- The identity on the whole space as a local homeomorphism. -/ protected def refl (α : Type*) [topological_space α] : local_homeomorph α α := (homeomorph.refl α).to_local_homeomorph @[simp] lemma refl_local_equiv : (local_homeomorph.refl α).to_local_equiv = local_equiv.refl α := rfl -- The corresponding lemmas for local_equiv are already marked simp. lemma refl_source : (local_homeomorph.refl α).source = univ := rfl lemma refl_target : (local_homeomorph.refl α).target = univ := rfl @[simp] lemma refl_symm : (local_homeomorph.refl α).symm = local_homeomorph.refl α := rfl lemma refl_to_fun : (local_homeomorph.refl α).to_fun = id := rfl lemma refl_inv_fun : (local_homeomorph.refl α).inv_fun = id := rfl section variables {s : set α} (hs : is_open s) /-- The identity local equiv on a set `s` -/ def of_set (s : set α) (hs : is_open s) : local_homeomorph α α := { open_source := hs, open_target := hs, continuous_to_fun := continuous_id.continuous_on, continuous_inv_fun := continuous_id.continuous_on, ..local_equiv.of_set s } @[simp] lemma of_set_to_local_equiv : (of_set s hs).to_local_equiv = local_equiv.of_set s := rfl -- The following lemmas are simp via local_equiv: lemma of_set_source : (of_set s hs).source = s := rfl lemma of_set_target : (of_set s hs).target = s := rfl lemma of_set_to_fun : (of_set s hs).to_fun = id := rfl lemma of_set_inv_fun : (of_set s hs).inv_fun = id := rfl lemma of_set_symm : (of_set s hs).symm = of_set s hs := rfl end /-- Composition of two local homeomorphisms when the target of the first and the source of the second coincide. -/ protected def trans' (h : e.target = e'.source) : local_homeomorph α γ := { open_source := e.open_source, open_target := e'.open_target, continuous_to_fun := begin apply continuous_on.comp e'.continuous_to_fun e.continuous_to_fun, rw ← h, exact e.to_local_equiv.source_subset_preimage_target end, continuous_inv_fun := begin apply continuous_on.comp e.continuous_inv_fun e'.continuous_inv_fun, rw h, exact e'.to_local_equiv.target_subset_preimage_source end, ..local_equiv.trans' e.to_local_equiv e'.to_local_equiv h } /-- Composing two local homeomorphisms, by restricting to the maximal domain where their composition is well defined. -/ protected def trans : local_homeomorph α γ := local_homeomorph.trans' (e.symm.restr_open e'.source e'.open_source).symm (e'.restr_open e.target e.open_target) (by simp [inter_comm]) @[simp] lemma trans_to_local_equiv : (e.trans e').to_local_equiv = e.to_local_equiv.trans e'.to_local_equiv := rfl -- The following lemmas are already simp via local_equiv lemma trans_to_fun : (e.trans e').to_fun = e'.to_fun ∘ e.to_fun := rfl lemma trans_inv_fun : (e.trans e').inv_fun = e.inv_fun ∘ e'.inv_fun := rfl lemma trans_symm_eq_symm_trans_symm : (e.trans e').symm = e'.symm.trans e.symm := by cases e; cases e'; refl /- This could be considered as a simp lemma, but there are many situations where it makes something simple into something more complicated. -/ lemma trans_source : (e.trans e').source = e.source ∩ e.to_fun ⁻¹' e'.source := local_equiv.trans_source e.to_local_equiv e'.to_local_equiv lemma trans_source' : (e.trans e').source = e.source ∩ e.to_fun ⁻¹' (e.target ∩ e'.source) := local_equiv.trans_source' e.to_local_equiv e'.to_local_equiv lemma trans_source'' : (e.trans e').source = e.inv_fun '' (e.target ∩ e'.source) := local_equiv.trans_source'' e.to_local_equiv e'.to_local_equiv lemma image_trans_source : e.to_fun '' (e.trans e').source = e.target ∩ e'.source := local_equiv.image_trans_source e.to_local_equiv e'.to_local_equiv lemma trans_target : (e.trans e').target = e'.target ∩ e'.inv_fun ⁻¹' e.target := rfl lemma trans_target' : (e.trans e').target = e'.target ∩ e'.inv_fun ⁻¹' (e'.source ∩ e.target) := trans_source' e'.symm e.symm lemma trans_target'' : (e.trans e').target = e'.to_fun '' (e'.source ∩ e.target) := trans_source'' e'.symm e.symm lemma inv_image_trans_target : e'.inv_fun '' (e.trans e').target = e'.source ∩ e.target := image_trans_source e'.symm e.symm lemma trans_assoc (e'' : local_homeomorph γ δ) : (e.trans e').trans e'' = e.trans (e'.trans e'') := eq_of_local_equiv_eq $ local_equiv.trans_assoc e.to_local_equiv e'.to_local_equiv e''.to_local_equiv @[simp] lemma trans_refl : e.trans (local_homeomorph.refl β) = e := eq_of_local_equiv_eq $ local_equiv.trans_refl e.to_local_equiv @[simp] lemma refl_trans : (local_homeomorph.refl α).trans e = e := eq_of_local_equiv_eq $ local_equiv.refl_trans e.to_local_equiv lemma trans_of_set {s : set β} (hs : is_open s) : e.trans (of_set s hs) = e.restr (e.to_fun ⁻¹' s) := local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) $ by simp [local_equiv.trans_source, (e.preimage_interior _).symm, interior_eq_of_open hs] lemma trans_of_set' {s : set β} (hs : is_open s) : e.trans (of_set s hs) = e.restr (e.source ∩ e.to_fun ⁻¹' s) := by rw [trans_of_set, restr_source_inter] lemma of_set_trans {s : set α} (hs : is_open s) : (of_set s hs).trans e = e.restr s := local_homeomorph.ext _ _ (λx, rfl) (λx, rfl) $ by simp [local_equiv.trans_source, interior_eq_of_open hs, inter_comm] lemma of_set_trans' {s : set α} (hs : is_open s) : (of_set s hs).trans e = e.restr (e.source ∩ s) := by rw [of_set_trans, restr_source_inter] lemma restr_trans (s : set α) : (e.restr s).trans e' = (e.trans e').restr s := eq_of_local_equiv_eq $ local_equiv.restr_trans e.to_local_equiv e'.to_local_equiv (interior s) /-- `eq_on_source e e'` means that `e` and `e'` have the same source, and coincide there. They should really be considered the same local equiv. -/ def eq_on_source (e e' : local_homeomorph α β) : Prop := e.source = e'.source ∧ (∀x ∈ e.source, e.to_fun x = e'.to_fun x) lemma eq_on_source_iff (e e' : local_homeomorph α β) : eq_on_source e e' ↔ local_equiv.eq_on_source e.to_local_equiv e'.to_local_equiv := by refl /-- `eq_on_source` is an equivalence relation -/ instance : setoid (local_homeomorph α β) := { r := eq_on_source, iseqv := ⟨ λe, (@local_equiv.eq_on_source_setoid α β).iseqv.1 e.to_local_equiv, λe e' h, (@local_equiv.eq_on_source_setoid α β).iseqv.2.1 ((eq_on_source_iff e e').1 h), λe e' e'' h h', (@local_equiv.eq_on_source_setoid α β).iseqv.2.2 ((eq_on_source_iff e e').1 h) ((eq_on_source_iff e' e'').1 h')⟩ } lemma eq_on_source_refl : e ≈ e := setoid.refl _ /-- If two local homeomorphisms are equivalent, so are their inverses -/ lemma eq_on_source_symm {e e' : local_homeomorph α β} (h : e ≈ e') : e.symm ≈ e'.symm := local_equiv.eq_on_source_symm h /-- Two equivalent local homeomorphisms have the same source -/ lemma source_eq_of_eq_on_source {e e' : local_homeomorph α β} (h : e ≈ e') : e.source = e'.source := h.1 /-- Two equivalent local homeomorphisms have the same target -/ lemma target_eq_of_eq_on_source {e e' : local_homeomorph α β} (h : e ≈ e') : e.target = e'.target := (eq_on_source_symm h).1 /-- Two equivalent local homeomorphisms have coinciding `to_fun` on the source -/ lemma apply_eq_of_eq_on_source {e e' : local_homeomorph α β} (h : e ≈ e') {x : α} (hx : x ∈ e.source) : e.to_fun x = e'.to_fun x := h.2 x hx /-- Two equivalent local homeomorphisms have coinciding `inv_fun` on the target -/ lemma inv_apply_eq_of_eq_on_source {e e' : local_homeomorph α β} (h : e ≈ e') {x : β} (hx : x ∈ e.target) : e.inv_fun x = e'.inv_fun x := (eq_on_source_symm h).2 x hx /-- Composition of local homeomorphisms respects equivalence -/ lemma eq_on_source_trans {e e' : local_homeomorph α β} {f f' : local_homeomorph β γ} (he : e ≈ e') (hf : f ≈ f') : e.trans f ≈ e'.trans f' := begin change local_equiv.eq_on_source (e.trans f).to_local_equiv (e'.trans f').to_local_equiv, simp only [trans_to_local_equiv], apply local_equiv.eq_on_source_trans, exact he, exact hf end /-- Restriction of local homeomorphisms respects equivalence -/ lemma eq_on_source_restr {e e' : local_homeomorph α β} (he : e ≈ e') (s : set α) : e.restr s ≈ e'.restr s := local_equiv.eq_on_source_restr he _ /-- Composition of a local homeomorphism and its inverse is equivalent to the restriction of the identity to the source -/ lemma trans_self_symm : e.trans e.symm ≈ local_homeomorph.of_set e.source e.open_source := local_equiv.trans_self_symm _ lemma trans_symm_self : e.symm.trans e ≈ local_homeomorph.of_set e.target e.open_target := e.symm.trans_self_symm lemma eq_of_eq_on_source_univ {e e' : local_homeomorph α β} (h : e ≈ e') (s : e.source = univ) (t : e.target = univ) : e = e' := eq_of_local_equiv_eq $ local_equiv.eq_of_eq_on_source_univ _ _ h s t section prod /-- The product of two local homeomorphisms, as a local homeomorphism on the product space. -/ def prod (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : local_homeomorph (α × γ) (β × δ) := { open_source := is_open_prod e.open_source e'.open_source, open_target := is_open_prod e.open_target e'.open_target, continuous_to_fun := continuous_on.prod (continuous_on.comp e.continuous_to_fun continuous_fst.continuous_on (prod_subset_preimage_fst _ _)) (continuous_on.comp e'.continuous_to_fun continuous_snd.continuous_on (prod_subset_preimage_snd _ _)), continuous_inv_fun := continuous_on.prod (continuous_on.comp e.continuous_inv_fun continuous_fst.continuous_on (prod_subset_preimage_fst _ _)) (continuous_on.comp e'.continuous_inv_fun continuous_snd.continuous_on (prod_subset_preimage_snd _ _)), ..e.to_local_equiv.prod e'.to_local_equiv } @[simp] lemma prod_to_local_equiv (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').to_local_equiv = e.to_local_equiv.prod e'.to_local_equiv := rfl -- The following lemmas are simp via local_equiv: lemma prod_source (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').source = set.prod e.source e'.source := rfl lemma prod_target (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').target = set.prod e.target e'.target := rfl lemma prod_to_fun (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').to_fun = (λp, (e.to_fun p.1, e'.to_fun p.2)) := rfl lemma prod_inv_fun (e : local_homeomorph α β) (e' : local_homeomorph γ δ) : (e.prod e').inv_fun = (λp, (e.inv_fun p.1, e'.inv_fun p.2)) := rfl end prod section continuity /-- Continuity within a set at a point can be read under right composition with a local homeomorphism, if the point is in its target -/ lemma continuous_within_at_iff_continuous_within_at_comp_right {f : β → γ} {s : set β} {x : β} (h : x ∈ e.target) : continuous_within_at f s x ↔ continuous_within_at (f ∘ e.to_fun) (e.to_fun ⁻¹' s) (e.inv_fun x) := begin split, { assume f_cont, have : e.to_fun (e.inv_fun x) = x := e.right_inv h, rw ← this at f_cont, have : e.source ∈ 𝓝 (e.inv_fun x) := mem_nhds_sets e.open_source (e.map_target h), rw [← continuous_within_at_inter this, inter_comm], exact continuous_within_at.comp f_cont ((e.continuous_at_to_fun (e.map_target h)).continuous_within_at) (inter_subset_right _ _) }, { assume fe_cont, have : continuous_within_at ((f ∘ e.to_fun) ∘ e.inv_fun) (s ∩ e.target) x, { apply continuous_within_at.comp fe_cont, apply (e.continuous_at_inv_fun h).continuous_within_at, assume x hx, simp [hx.1, hx.2, e.map_target] }, have : continuous_within_at f (s ∩ e.target) x := continuous_within_at.congr this (λy hy, by simp [hy.2]) (by simp [h]), rwa continuous_within_at_inter at this, exact mem_nhds_sets e.open_target h } end /-- Continuity at a point can be read under right composition with a local homeomorphism, if the point is in its target -/ lemma continuous_at_iff_continuous_at_comp_right {f : β → γ} {x : β} (h : x ∈ e.target) : continuous_at f x ↔ continuous_at (f ∘ e.to_fun) (e.inv_fun x) := by rw [← continuous_within_at_univ, e.continuous_within_at_iff_continuous_within_at_comp_right h, preimage_univ, continuous_within_at_univ] /-- A function is continuous on a set if and only if its composition with a local homeomorphism on the right is continuous on the corresponding set. -/ lemma continuous_on_iff_continuous_on_comp_right {f : β → γ} {s : set β} (h : s ⊆ e.target) : continuous_on f s ↔ continuous_on (f ∘ e.to_fun) (e.source ∩ e.to_fun ⁻¹' s) := begin split, { assume f_cont x hx, have := e.continuous_within_at_iff_continuous_within_at_comp_right (e.map_source hx.1), rw e.left_inv hx.1 at this, have A := f_cont _ hx.2, rw this at A, exact A.mono (inter_subset_right _ _), }, { assume fe_cont x hx, have := e.continuous_within_at_iff_continuous_within_at_comp_right (h hx), rw this, have : e.source ∈ 𝓝 (e.inv_fun x) := mem_nhds_sets e.open_source (e.map_target (h hx)), rw [← continuous_within_at_inter this, inter_comm], exact fe_cont _ (by simp [hx, h hx, e.map_target (h hx)]) } end /-- Continuity within a set at a point can be read under left composition with a local homeomorphism if a neighborhood of the initial point is sent to the source of the local homeomorphism-/ lemma continuous_within_at_iff_continuous_within_at_comp_left {f : γ → α} {s : set γ} {x : γ} (hx : f x ∈ e.source) (h : f ⁻¹' e.source ∈ nhds_within x s) : continuous_within_at f s x ↔ continuous_within_at (e.to_fun ∘ f) s x := begin rw [← continuous_within_at_inter' h, ← continuous_within_at_inter' h], split, { assume f_cont, have : e.source ∈ 𝓝 (f x) := mem_nhds_sets e.open_source hx, apply continuous_within_at.comp (e.continuous_to_fun (f x) hx) f_cont (inter_subset_right _ _) }, { assume fe_cont, have : continuous_within_at (e.inv_fun ∘ (e.to_fun ∘ f)) (s ∩ f ⁻¹' e.source) x, { have : continuous_within_at e.inv_fun univ (e.to_fun (f x)) := (e.continuous_at_inv_fun (e.map_source hx)).continuous_within_at, exact continuous_within_at.comp this fe_cont (subset_univ _) }, exact this.congr (λy hy, by simp [e.left_inv hy.2]) (by simp [e.left_inv hx]) } end /-- Continuity at a point can be read under left composition with a local homeomorphism if a neighborhood of the initial point is sent to the source of the local homeomorphism-/ lemma continuous_at_iff_continuous_at_comp_left {f : γ → α} {x : γ} (h : f ⁻¹' e.source ∈ 𝓝 x) : continuous_at f x ↔ continuous_at (e.to_fun ∘ f) x := begin have hx : f x ∈ e.source := (mem_of_nhds h : _), have h' : f ⁻¹' e.source ∈ nhds_within x univ, by rwa nhds_within_univ, rw [← continuous_within_at_univ, ← continuous_within_at_univ, e.continuous_within_at_iff_continuous_within_at_comp_left hx h'] end /-- A function is continuous on a set if and only if its composition with a local homeomorphism on the left is continuous on the corresponding set. -/ lemma continuous_on_iff_continuous_on_comp_left {f : γ → α} {s : set γ} (h : s ⊆ f ⁻¹' e.source) : continuous_on f s ↔ continuous_on (e.to_fun ∘ f) s := begin split, { assume f_cont, exact continuous_on.comp e.continuous_to_fun f_cont h }, { assume fe_cont, have : continuous_on (e.inv_fun ∘ e.to_fun ∘ f) s, { apply continuous_on.comp e.continuous_inv_fun fe_cont, assume x hx, have : f x ∈ e.source := h hx, simp [this] }, refine continuous_on.congr_mono this (λx hx, _) (subset.refl _), have : f x ∈ e.source := h hx, simp [this] } end end continuity /-- If a local homeomorphism has source and target equal to univ, then it induces a homeomorphism between the whole spaces, expressed in this definition. -/ def to_homeomorph_of_source_eq_univ_target_eq_univ (h : e.source = (univ : set α)) (h' : e.target = univ) : homeomorph α β := { to_fun := e.to_fun, inv_fun := e.inv_fun, left_inv := λx, e.left_inv $ by { rw h, exact mem_univ _ }, right_inv := λx, e.right_inv $ by { rw h', exact mem_univ _ }, continuous_to_fun := begin rw [continuous_iff_continuous_on_univ], convert e.continuous_to_fun, rw h end, continuous_inv_fun := begin rw [continuous_iff_continuous_on_univ], convert e.continuous_inv_fun, rw h' end } @[simp] lemma to_homeomorph_to_fun (h : e.source = (univ : set α)) (h' : e.target = univ) : (e.to_homeomorph_of_source_eq_univ_target_eq_univ h h').to_fun = e.to_fun := rfl @[simp] lemma to_homeomorph_inv_fun (h : e.source = (univ : set α)) (h' : e.target = univ) : (e.to_homeomorph_of_source_eq_univ_target_eq_univ h h').inv_fun = e.inv_fun := rfl end local_homeomorph namespace homeomorph variables (e : homeomorph α β) (e' : homeomorph β γ) /- Register as simp lemmas that the fields of a local homeomorphism built from a homeomorphism correspond to the fields of the original homeomorphism. -/ @[simp] lemma to_local_homeomorph_source : e.to_local_homeomorph.source = univ := rfl @[simp] lemma to_local_homeomorph_target : e.to_local_homeomorph.target = univ := rfl @[simp] lemma to_local_homeomorph_to_fun : e.to_local_homeomorph.to_fun = e.to_fun := rfl @[simp] lemma to_local_homeomorph_inv_fun : e.to_local_homeomorph.inv_fun = e.inv_fun := rfl @[simp] lemma refl_to_local_homeomorph : (homeomorph.refl α).to_local_homeomorph = local_homeomorph.refl α := rfl @[simp] lemma symm_to_local_homeomorph : e.symm.to_local_homeomorph = e.to_local_homeomorph.symm := rfl @[simp] lemma trans_to_local_homeomorph : (e.trans e').to_local_homeomorph = e.to_local_homeomorph.trans e'.to_local_homeomorph := local_homeomorph.eq_of_local_equiv_eq $ equiv.trans_to_local_equiv _ _ end homeomorph
34db740b59dc559fb6863abc9319627017311232
bb31430994044506fa42fd667e2d556327e18dfe
/src/topology/algebra/order/left_right_lim.lean
688e2f22bd5954a9abca523b4eaaf64fd6253a01
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
14,501
lean
/- Copyright (c) 2022 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import topology.order.basic import topology.algebra.order.left_right /-! # Left and right limits We define the (strict) left and right limits of a function. * `left_lim f x` is the strict left limit of `f` at `x` (using `f x` as a garbage value if `x` is isolated to its left). * `right_lim f x` is the strict right limit of `f` at `x` (using `f x` as a garbage value if `x` is isolated to its right). We develop a comprehensive API for monotone functions. Notably, * `monotone.continuous_at_iff_left_lim_eq_right_lim` states that a monotone function is continuous at a point if and only if its left and right limits coincide. * `monotone.countable_not_continuous_at` asserts that a monotone function taking values in a second-countable space has at most countably many discontinuity points. We also port the API to antitone functions. ## TODO Prove corresponding stronger results for strict_mono and strict_anti functions. -/ open set filter open_locale topological_space section variables {α β : Type*} [linear_order α] [topological_space β] /-- Let `f : α → β` be a function from a linear order `α` to a topological_space `β`, and let `a : α`. The limit strictly to the left of `f` at `a`, denoted with `left_lim f a`, is defined by using the order topology on `α`. If `a` is isolated to its left or the function has no left limit, we use `f a` instead to guarantee a good behavior in most cases. -/ @[irreducible] noncomputable def function.left_lim (f : α → β) (a : α) : β := begin classical, haveI : nonempty β := ⟨f a⟩, letI : topological_space α := preorder.topology α, exact if (𝓝[<] a = ⊥) ∨ ¬(∃ y, tendsto f (𝓝[<] a) (𝓝 y)) then f a else lim (𝓝[<] a) f end /-- Let `f : α → β` be a function from a linear order `α` to a topological_space `β`, and let `a : α`. The limit strictly to the right of `f` at `a`, denoted with `right_lim f a`, is defined by using the order topology on `α`. If `a` is isolated to its right or the function has no right limit, , we use `f a` instead to guarantee a good behavior in most cases. -/ noncomputable def function.right_lim (f : α → β) (a : α) : β := @function.left_lim αᵒᵈ β _ _ f a open function lemma left_lim_eq_of_tendsto [hα : topological_space α] [h'α : order_topology α] [t2_space β] {f : α → β} {a : α} {y : β} (h : 𝓝[<] a ≠ ⊥) (h' : tendsto f (𝓝[<] a) (𝓝 y)) : left_lim f a = y := begin have h'' : ∃ y, tendsto f (𝓝[<] a) (𝓝 y) := ⟨y, h'⟩, rw [h'α.topology_eq_generate_intervals] at h h' h'', simp only [left_lim, h, h'', not_true, or_self, if_false], haveI := ne_bot_iff.2 h, exact h'.lim_eq, end lemma left_lim_eq_of_eq_bot [hα : topological_space α] [h'α : order_topology α] (f : α → β) {a : α} (h : 𝓝[<] a = ⊥) : left_lim f a = f a := begin rw [h'α.topology_eq_generate_intervals] at h, simp [left_lim, ite_eq_left_iff, h], end end open function namespace monotone variables {α β : Type*} [linear_order α] [conditionally_complete_linear_order β] [topological_space β] [order_topology β] {f : α → β} (hf : monotone f) {x y : α} include hf lemma left_lim_eq_Sup [topological_space α] [order_topology α] (h : 𝓝[<] x ≠ ⊥) : left_lim f x = Sup (f '' (Iio x)) := left_lim_eq_of_tendsto h (hf.tendsto_nhds_within_Iio x) lemma left_lim_le (h : x ≤ y) : left_lim f x ≤ f y := begin letI : topological_space α := preorder.topology α, haveI : order_topology α := ⟨rfl⟩, rcases eq_or_ne (𝓝[<] x) ⊥ with h'|h', { simpa [left_lim, h'] using hf h }, haveI A : ne_bot (𝓝[<] x) := ne_bot_iff.2 h', rw left_lim_eq_Sup hf h', refine cSup_le _ _, { simp only [nonempty_image_iff], exact (forall_mem_nonempty_iff_ne_bot.2 A) _ self_mem_nhds_within }, { simp only [mem_image, mem_Iio, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂], assume z hz, exact hf (hz.le.trans h) }, end lemma le_left_lim (h : x < y) : f x ≤ left_lim f y := begin letI : topological_space α := preorder.topology α, haveI : order_topology α := ⟨rfl⟩, rcases eq_or_ne (𝓝[<] y) ⊥ with h'|h', { rw left_lim_eq_of_eq_bot _ h', exact hf h.le }, rw left_lim_eq_Sup hf h', refine le_cSup ⟨f y, _⟩ (mem_image_of_mem _ h), simp only [upper_bounds, mem_image, mem_Iio, forall_exists_index, and_imp, forall_apply_eq_imp_iff₂, mem_set_of_eq], assume z hz, exact hf hz.le end @[mono] protected lemma left_lim : monotone (left_lim f) := begin assume x y h, rcases eq_or_lt_of_le h with rfl|hxy, { exact le_rfl }, { exact (hf.left_lim_le le_rfl).trans (hf.le_left_lim hxy) } end lemma le_right_lim (h : x ≤ y) : f x ≤ right_lim f y := hf.dual.left_lim_le h lemma right_lim_le (h : x < y) : right_lim f x ≤ f y := hf.dual.le_left_lim h @[mono] protected lemma right_lim : monotone (right_lim f) := λ x y h, hf.dual.left_lim h lemma left_lim_le_right_lim (h : x ≤ y) : left_lim f x ≤ right_lim f y := (hf.left_lim_le le_rfl).trans (hf.le_right_lim h) lemma right_lim_le_left_lim (h : x < y) : right_lim f x ≤ left_lim f y := begin letI : topological_space α := preorder.topology α, haveI : order_topology α := ⟨rfl⟩, rcases eq_or_ne (𝓝[<] y) ⊥ with h'|h', { simp [left_lim, h'], exact right_lim_le hf h }, obtain ⟨a, ⟨xa, ay⟩⟩ : (Ioo x y).nonempty := forall_mem_nonempty_iff_ne_bot.2 (ne_bot_iff.2 h') (Ioo x y) (Ioo_mem_nhds_within_Iio ⟨h, le_refl _⟩), calc right_lim f x ≤ f a : hf.right_lim_le xa ... ≤ left_lim f y : hf.le_left_lim ay end variables [topological_space α] [order_topology α] lemma tendsto_left_lim (x : α) : tendsto f (𝓝[<] x) (𝓝 (left_lim f x)) := begin rcases eq_or_ne (𝓝[<] x) ⊥ with h'|h', { simp [h'] }, rw left_lim_eq_Sup hf h', exact hf.tendsto_nhds_within_Iio x end lemma tendsto_left_lim_within (x : α) : tendsto f (𝓝[<] x) (𝓝[≤] (left_lim f x)) := begin apply tendsto_nhds_within_of_tendsto_nhds_of_eventually_within f (hf.tendsto_left_lim x), filter_upwards [self_mem_nhds_within] with y hy using hf.le_left_lim hy, end lemma tendsto_right_lim (x : α) : tendsto f (𝓝[>] x) (𝓝 (right_lim f x)) := hf.dual.tendsto_left_lim x lemma tendsto_right_lim_within (x : α) : tendsto f (𝓝[>] x) (𝓝[≥] (right_lim f x)) := hf.dual.tendsto_left_lim_within x /-- A monotone function is continuous to the left at a point if and only if its left limit coincides with the value of the function. -/ lemma continuous_within_at_Iio_iff_left_lim_eq : continuous_within_at f (Iio x) x ↔ left_lim f x = f x := begin rcases eq_or_ne (𝓝[<] x) ⊥ with h'|h', { simp [left_lim_eq_of_eq_bot f h', continuous_within_at, h'] }, haveI : (𝓝[Iio x] x).ne_bot := ne_bot_iff.2 h', refine ⟨λ h, tendsto_nhds_unique (hf.tendsto_left_lim x) h.tendsto, λ h, _⟩, have := hf.tendsto_left_lim x, rwa h at this, end /-- A monotone function is continuous to the right at a point if and only if its right limit coincides with the value of the function. -/ lemma continuous_within_at_Ioi_iff_right_lim_eq : continuous_within_at f (Ioi x) x ↔ right_lim f x = f x := hf.dual.continuous_within_at_Iio_iff_left_lim_eq /-- A monotone function is continuous at a point if and only if its left and right limits coincide. -/ lemma continuous_at_iff_left_lim_eq_right_lim : continuous_at f x ↔ left_lim f x = right_lim f x := begin refine ⟨λ h, _, λ h, _⟩, { have A : left_lim f x = f x, from (hf.continuous_within_at_Iio_iff_left_lim_eq).1 h.continuous_within_at, have B : right_lim f x = f x, from (hf.continuous_within_at_Ioi_iff_right_lim_eq).1 h.continuous_within_at, exact A.trans B.symm }, { have h' : left_lim f x = f x, { apply le_antisymm (left_lim_le hf (le_refl _)), rw h, exact le_right_lim hf (le_refl _) }, refine continuous_at_iff_continuous_left'_right'.2 ⟨_, _⟩, { exact hf.continuous_within_at_Iio_iff_left_lim_eq.2 h' }, { rw h at h', exact hf.continuous_within_at_Ioi_iff_right_lim_eq.2 h' } }, end /-- In a second countable space, the set of points where a monotone function is not right-continuous is at most countable. Superseded by `countable_not_continuous_at` which gives the two-sided version. -/ lemma countable_not_continuous_within_at_Ioi [topological_space.second_countable_topology β] : set.countable {x | ¬(continuous_within_at f (Ioi x) x)} := begin /- If `f` is not continuous on the right at `x`, there is an interval `(f x, z x)` which is not reached by `f`. This gives a family of disjoint open intervals in `β`. Such a family can only be countable as `β` is second-countable. -/ nontriviality α, let s := {x | ¬(continuous_within_at f (Ioi x) x)}, have : ∀ x, x ∈ s → ∃ z, f x < z ∧ ∀ y, x < y → z ≤ f y, { rintros x (hx : ¬(continuous_within_at f (Ioi x) x)), contrapose! hx, refine tendsto_order.2 ⟨λ m hm, _, λ u hu, _⟩, { filter_upwards [self_mem_nhds_within] with y hy using hm.trans_le (hf (le_of_lt hy)) }, rcases hx u hu with ⟨v, xv, fvu⟩, have : Ioo x v ∈ 𝓝[>] x, from Ioo_mem_nhds_within_Ioi ⟨le_refl _, xv⟩, filter_upwards [this] with y hy, apply (hf hy.2.le).trans_lt fvu }, -- choose `z x` such that `f` does not take the values in `(f x, z x)`. choose! z hz using this, have I : inj_on f s, { apply strict_mono_on.inj_on, assume x hx y hy hxy, calc f x < z x : (hz x hx).1 ... ≤ f y : (hz x hx).2 y hxy }, -- show that `f s` is countable by arguing that a disjoint family of disjoint open intervals -- (the intervals `(f x, z x)`) is at most countable. have fs_count : (f '' s).countable, { have A : (f '' s).pairwise_disjoint (λ x, Ioo x (z (inv_fun_on f s x))), { rintros _ ⟨u, us, rfl⟩ _ ⟨v, vs, rfl⟩ huv, wlog h'uv : u ≤ v := le_total u v using [u v, v u] tactic.skip, { rcases eq_or_lt_of_le h'uv with rfl|h''uv, { exact (huv rfl).elim }, apply disjoint_iff_forall_ne.2, rintros a ha b hb rfl, simp [I.left_inv_on_inv_fun_on us, I.left_inv_on_inv_fun_on vs] at ha hb, exact lt_irrefl _ ((ha.2.trans_le ((hz u us).2 v h''uv)).trans hb.1) }, { assume hu hv h'uv, exact (this hv hu h'uv.symm).symm } }, apply set.pairwise_disjoint.countable_of_Ioo A, rintros _ ⟨y, ys, rfl⟩, simpa only [I.left_inv_on_inv_fun_on ys] using (hz y ys).1 }, exact maps_to.countable_of_inj_on (maps_to_image f s) I fs_count, end /-- In a second countable space, the set of points where a monotone function is not left-continuous is at most countable. Superseded by `countable_not_continuous_at` which gives the two-sided version. -/ lemma countable_not_continuous_within_at_Iio [topological_space.second_countable_topology β] : set.countable {x | ¬(continuous_within_at f (Iio x) x)} := hf.dual.countable_not_continuous_within_at_Ioi /-- In a second countable space, the set of points where a monotone function is not continuous is at most countable. -/ lemma countable_not_continuous_at [topological_space.second_countable_topology β] : set.countable {x | ¬(continuous_at f x)} := begin apply (hf.countable_not_continuous_within_at_Ioi.union hf.countable_not_continuous_within_at_Iio).mono _, refine compl_subset_compl.1 _, simp only [compl_union], rintros x ⟨hx, h'x⟩, simp only [mem_set_of_eq, not_not, mem_compl_iff] at hx h'x ⊢, exact continuous_at_iff_continuous_left'_right'.2 ⟨h'x, hx⟩ end end monotone namespace antitone variables {α β : Type*} [linear_order α] [conditionally_complete_linear_order β] [topological_space β] [order_topology β] {f : α → β} (hf : antitone f) {x y : α} include hf lemma le_left_lim (h : x ≤ y) : f y ≤ left_lim f x := hf.dual_right.left_lim_le h lemma left_lim_le (h : x < y) : left_lim f y ≤ f x := hf.dual_right.le_left_lim h @[mono] protected lemma left_lim : antitone (left_lim f) := hf.dual_right.left_lim lemma right_lim_le (h : x ≤ y) : right_lim f y ≤ f x := hf.dual_right.le_right_lim h lemma le_right_lim (h : x < y) : f y ≤ right_lim f x := hf.dual_right.right_lim_le h @[mono] protected lemma right_lim : antitone (right_lim f) := hf.dual_right.right_lim lemma right_lim_le_left_lim (h : x ≤ y) : right_lim f y ≤ left_lim f x := hf.dual_right.left_lim_le_right_lim h lemma left_lim_le_right_lim (h : x < y) : left_lim f y ≤ right_lim f x := hf.dual_right.right_lim_le_left_lim h variables [topological_space α] [order_topology α] lemma tendsto_left_lim (x : α) : tendsto f (𝓝[<] x) (𝓝 (left_lim f x)) := hf.dual_right.tendsto_left_lim x lemma tendsto_left_lim_within (x : α) : tendsto f (𝓝[<] x) (𝓝[≥] (left_lim f x)) := hf.dual_right.tendsto_left_lim_within x lemma tendsto_right_lim (x : α) : tendsto f (𝓝[>] x) (𝓝 (right_lim f x)) := hf.dual_right.tendsto_right_lim x lemma tendsto_right_lim_within (x : α) : tendsto f (𝓝[>] x) (𝓝[≤] (right_lim f x)) := hf.dual_right.tendsto_right_lim_within x /-- An antitone function is continuous to the left at a point if and only if its left limit coincides with the value of the function. -/ lemma continuous_within_at_Iio_iff_left_lim_eq : continuous_within_at f (Iio x) x ↔ left_lim f x = f x := hf.dual_right.continuous_within_at_Iio_iff_left_lim_eq /-- An antitone function is continuous to the right at a point if and only if its right limit coincides with the value of the function. -/ lemma continuous_within_at_Ioi_iff_right_lim_eq : continuous_within_at f (Ioi x) x ↔ right_lim f x = f x := hf.dual_right.continuous_within_at_Ioi_iff_right_lim_eq /-- An antitone function is continuous at a point if and only if its left and right limits coincide. -/ lemma continuous_at_iff_left_lim_eq_right_lim : continuous_at f x ↔ left_lim f x = right_lim f x := hf.dual_right.continuous_at_iff_left_lim_eq_right_lim /-- In a second countable space, the set of points where an antitone function is not continuous is at most countable. -/ lemma countable_not_continuous_at [topological_space.second_countable_topology β] : set.countable {x | ¬(continuous_at f x)} := hf.dual_right.countable_not_continuous_at end antitone
3978ffa4e60b748e964f42dade6a18f1dde976b9
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/52_lean3.lean
a2af776a3d3671c87a21742500caba9432057056
[ "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
412
lean
universe u macro "Type*" : term => `(Type _) open Nat variable {α : Type u} def vec : Type u → Nat → Type* | A, 0 => PUnit | A, succ k => A × vec A k inductive dfin : Nat → Type | fz {n} : dfin (succ n) | fs {n} : dfin n → dfin (succ n) def kth_projn : (n : Nat) → vec α n → dfin n → α | succ n, x, dfin.fz => x.fst | succ n, (x, xs), dfin.fs k => kth_projn n xs k
d82ead9c2f2bb3db654f6ac167754f836c2cbf40
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/measure_theory/decomposition/lebesgue.lean
dcffe4a45b3ef9826ae5f73b7c8337b89c2d86db
[ "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
66,570
lean
/- Copyright (c) 2021 Kexing Ying. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kexing Ying -/ import measure_theory.measure.complex import measure_theory.measure.with_density_vector_measure import measure_theory.function.ae_eq_of_integral /-! # Lebesgue decomposition This file proves the Lebesgue decomposition theorem. The Lebesgue decomposition theorem states that, given two σ-finite measures `μ` and `ν`, there exists a σ-finite measure `ξ` and a measurable function `f` such that `μ = ξ + fν` and `ξ` is mutually singular with respect to `ν`. The Lebesgue decomposition provides the Radon-Nikodym theorem readily. ## Main definitions * `measure_theory.measure.have_lebesgue_decomposition` : A pair of measures `μ` and `ν` is said to `have_lebesgue_decomposition` if there exist a measure `ξ` and a measurable function `f`, such that `ξ` is mutually singular with respect to `ν` and `μ = ξ + ν.with_density f` * `measure_theory.measure.singular_part` : If a pair of measures `have_lebesgue_decomposition`, then `singular_part` chooses the measure from `have_lebesgue_decomposition`, otherwise it returns the zero measure. * `measure_theory.measure.rn_deriv`: If a pair of measures `have_lebesgue_decomposition`, then `rn_deriv` chooses the measurable function from `have_lebesgue_decomposition`, otherwise it returns the zero function. * `measure_theory.signed_measure.have_lebesgue_decomposition` : A signed measure `s` and a measure `μ` is said to `have_lebesgue_decomposition` if both the positive part and negative part of `s` `have_lebesgue_decomposition` with respect to `μ`. * `measure_theory.signed_measure.singular_part` : The singular part between a signed measure `s` and a measure `μ` is simply the singular part of the positive part of `s` with respect to `μ` minus the singular part of the negative part of `s` with respect to `μ`. * `measure_theory.signed_measure.rn_deriv` : The Radon-Nikodym derivative of a signed measure `s` with respect to a measure `μ` is the Radon-Nikodym derivative of the positive part of `s` with respect to `μ` minus the Radon-Nikodym derivative of the negative part of `s` with respect to `μ`. ## Main results * `measure_theory.measure.have_lebesgue_decomposition_of_sigma_finite` : the Lebesgue decomposition theorem. * `measure_theory.measure.eq_singular_part` : Given measures `μ` and `ν`, if `s` is a measure mutually singular to `ν` and `f` is a measurable function such that `μ = s + fν`, then `s = μ.singular_part ν`. * `measure_theory.measure.eq_rn_deriv` : Given measures `μ` and `ν`, if `s` is a measure mutually singular to `ν` and `f` is a measurable function such that `μ = s + fν`, then `f = μ.rn_deriv ν`. * `measure_theory.signed_measure.singular_part_add_with_density_rn_deriv_eq` : the Lebesgue decomposition theorem between a signed measure and a σ-finite positive measure. # Tags Lebesgue decomposition theorem -/ noncomputable theory open_locale classical measure_theory nnreal ennreal variables {α β : Type*} {m : measurable_space α} {μ ν : measure_theory.measure α} include m namespace measure_theory namespace measure /-- A pair of measures `μ` and `ν` is said to `have_lebesgue_decomposition` if there exists a measure `ξ` and a measurable function `f`, such that `ξ` is mutually singular with respect to `ν` and `μ = ξ + ν.with_density f`. -/ class have_lebesgue_decomposition (μ ν : measure α) : Prop := (lebesgue_decomposition : ∃ (p : measure α × (α → ℝ≥0∞)), measurable p.2 ∧ p.1 ⊥ₘ ν ∧ μ = p.1 + ν.with_density p.2) /-- If a pair of measures `have_lebesgue_decomposition`, then `singular_part` chooses the measure from `have_lebesgue_decomposition`, otherwise it returns the zero measure. For sigma-finite measures, `μ = μ.singular_part ν + ν.with_density (μ.rn_deriv ν)`. -/ @[irreducible] def singular_part (μ ν : measure α) : measure α := if h : have_lebesgue_decomposition μ ν then (classical.some h.lebesgue_decomposition).1 else 0 /-- If a pair of measures `have_lebesgue_decomposition`, then `rn_deriv` chooses the measurable function from `have_lebesgue_decomposition`, otherwise it returns the zero function. For sigma-finite measures, `μ = μ.singular_part ν + ν.with_density (μ.rn_deriv ν)`.-/ @[irreducible] def rn_deriv (μ ν : measure α) : α → ℝ≥0∞ := if h : have_lebesgue_decomposition μ ν then (classical.some h.lebesgue_decomposition).2 else 0 lemma have_lebesgue_decomposition_spec (μ ν : measure α) [h : have_lebesgue_decomposition μ ν] : measurable (μ.rn_deriv ν) ∧ (μ.singular_part ν) ⊥ₘ ν ∧ μ = (μ.singular_part ν) + ν.with_density (μ.rn_deriv ν) := begin rw [singular_part, rn_deriv, dif_pos h, dif_pos h], exact classical.some_spec h.lebesgue_decomposition, end lemma have_lebesgue_decomposition_add (μ ν : measure α) [have_lebesgue_decomposition μ ν] : μ = (μ.singular_part ν) + ν.with_density (μ.rn_deriv ν) := (have_lebesgue_decomposition_spec μ ν).2.2 instance have_lebesgue_decomposition_smul (μ ν : measure α) [have_lebesgue_decomposition μ ν] (r : ℝ≥0) : (r • μ).have_lebesgue_decomposition ν := { lebesgue_decomposition := begin obtain ⟨hmeas, hsing, hadd⟩ := have_lebesgue_decomposition_spec μ ν, refine ⟨⟨r • μ.singular_part ν, r • μ.rn_deriv ν⟩, _, hsing.smul _, _⟩, { change measurable ((r : ℝ≥0∞) • _), -- cannot remove this line exact hmeas.const_smul _ }, { change _ = (r : ℝ≥0∞) • _ + ν.with_density ((r : ℝ≥0∞) • _), rw [with_density_smul _ hmeas, ← smul_add, ← hadd], refl } end } @[measurability] lemma measurable_rn_deriv (μ ν : measure α) : measurable $ μ.rn_deriv ν := begin by_cases h : have_lebesgue_decomposition μ ν, { exactI (have_lebesgue_decomposition_spec μ ν).1 }, { rw [rn_deriv, dif_neg h], exact measurable_zero } end lemma mutually_singular_singular_part (μ ν : measure α) : μ.singular_part ν ⊥ₘ ν := begin by_cases h : have_lebesgue_decomposition μ ν, { exactI (have_lebesgue_decomposition_spec μ ν).2.1 }, { rw [singular_part, dif_neg h], exact mutually_singular.zero_left } end lemma singular_part_le (μ ν : measure α) : μ.singular_part ν ≤ μ := begin by_cases hl : have_lebesgue_decomposition μ ν, { casesI (have_lebesgue_decomposition_spec μ ν).2 with _ h, conv_rhs { rw h }, exact measure.le_add_right (le_refl _) }, { rw [singular_part, dif_neg hl], exact measure.zero_le μ } end lemma with_density_rn_deriv_le (μ ν : measure α) : ν.with_density (μ.rn_deriv ν) ≤ μ := begin by_cases hl : have_lebesgue_decomposition μ ν, { casesI (have_lebesgue_decomposition_spec μ ν).2 with _ h, conv_rhs { rw h }, exact measure.le_add_left (le_refl _) }, { rw [rn_deriv, dif_neg hl, with_density_zero], exact measure.zero_le μ } end instance [is_finite_measure μ] : is_finite_measure (μ.singular_part ν) := is_finite_measure_of_le μ $ singular_part_le μ ν instance [sigma_finite μ] : sigma_finite (μ.singular_part ν) := sigma_finite_of_le μ $ singular_part_le μ ν instance [topological_space α] [is_locally_finite_measure μ] : is_locally_finite_measure (μ.singular_part ν) := is_locally_finite_measure_of_le $ singular_part_le μ ν instance [is_finite_measure μ] : is_finite_measure (ν.with_density $ μ.rn_deriv ν) := is_finite_measure_of_le μ $ with_density_rn_deriv_le μ ν instance [sigma_finite μ] : sigma_finite (ν.with_density $ μ.rn_deriv ν) := sigma_finite_of_le μ $ with_density_rn_deriv_le μ ν instance [topological_space α] [is_locally_finite_measure μ] : is_locally_finite_measure (ν.with_density $ μ.rn_deriv ν) := is_locally_finite_measure_of_le $ with_density_rn_deriv_le μ ν lemma lintegral_rn_deriv_lt_top_of_measure_ne_top {μ : measure α} (ν : measure α) {s : set α} (hs : μ s ≠ ∞) : ∫⁻ x in s, μ.rn_deriv ν x ∂ν < ∞ := begin by_cases hl : have_lebesgue_decomposition μ ν, { haveI := hl, obtain ⟨-, -, hadd⟩ := have_lebesgue_decomposition_spec μ ν, suffices : ∫⁻ x in to_measurable μ s, μ.rn_deriv ν x ∂ν < ∞, from lt_of_le_of_lt (lintegral_mono_set (subset_to_measurable _ _)) this, rw [← with_density_apply _ (measurable_set_to_measurable _ _)], refine lt_of_le_of_lt (le_add_left (le_refl _) : _ ≤ μ.singular_part ν (to_measurable μ s) + ν.with_density (μ.rn_deriv ν) (to_measurable μ s)) _, rw [← measure.add_apply, ← hadd, measure_to_measurable], exact hs.lt_top }, { erw [measure.rn_deriv, dif_neg hl, lintegral_zero], exact with_top.zero_lt_top }, end lemma lintegral_rn_deriv_lt_top (μ ν : measure α) [is_finite_measure μ] : ∫⁻ x, μ.rn_deriv ν x ∂ν < ∞ := begin rw [← set_lintegral_univ], exact lintegral_rn_deriv_lt_top_of_measure_ne_top _ (measure_lt_top _ _).ne, end /-- The Radon-Nikodym derivative of a sigma-finite measure `μ` with respect to another measure `ν` is `ν`-almost everywhere finite. -/ theorem rn_deriv_lt_top (μ ν : measure α) [sigma_finite μ] : ∀ᵐ x ∂ν, μ.rn_deriv ν x < ∞ := begin suffices : ∀ n, ∀ᵐ x ∂ν, x ∈ spanning_sets μ n → μ.rn_deriv ν x < ∞, { filter_upwards [ae_all_iff.2 this], assume x hx, exact hx _ (mem_spanning_sets_index _ _) }, assume n, rw ← ae_restrict_iff' (measurable_spanning_sets _ _), apply ae_lt_top (measurable_rn_deriv _ _), refine (lintegral_rn_deriv_lt_top_of_measure_ne_top _ _).ne, exact (measure_spanning_sets_lt_top _ _).ne end /-- Given measures `μ` and `ν`, if `s` is a measure mutually singular to `ν` and `f` is a measurable function such that `μ = s + fν`, then `s = μ.singular_part μ`. This theorem provides the uniqueness of the `singular_part` in the Lebesgue decomposition theorem, while `measure_theory.measure.eq_rn_deriv` provides the uniqueness of the `rn_deriv`. -/ theorem eq_singular_part {s : measure α} {f : α → ℝ≥0∞} (hf : measurable f) (hs : s ⊥ₘ ν) (hadd : μ = s + ν.with_density f) : s = μ.singular_part ν := begin haveI : have_lebesgue_decomposition μ ν := ⟨⟨⟨s, f⟩, hf, hs, hadd⟩⟩, obtain ⟨hmeas, hsing, hadd'⟩ := have_lebesgue_decomposition_spec μ ν, obtain ⟨⟨S, hS₁, hS₂, hS₃⟩, ⟨T, hT₁, hT₂, hT₃⟩⟩ := ⟨hs, hsing⟩, rw hadd' at hadd, have hνinter : ν (S ∩ T)ᶜ = 0, { rw set.compl_inter, refine nonpos_iff_eq_zero.1 (le_trans (measure_union_le _ _) _), rw [hT₃, hS₃, add_zero], exact le_refl _ }, have heq : s.restrict (S ∩ T)ᶜ = (μ.singular_part ν).restrict (S ∩ T)ᶜ, { ext1 A hA, have hf : ν.with_density f (A ∩ (S ∩ T)ᶜ) = 0, { refine with_density_absolutely_continuous ν _ _, rw ← nonpos_iff_eq_zero, exact hνinter ▸ measure_mono (set.inter_subset_right _ _) }, have hrn : ν.with_density (μ.rn_deriv ν) (A ∩ (S ∩ T)ᶜ) = 0, { refine with_density_absolutely_continuous ν _ _, rw ← nonpos_iff_eq_zero, exact hνinter ▸ measure_mono (set.inter_subset_right _ _) }, rw [restrict_apply hA, restrict_apply hA, ← add_zero (s (A ∩ (S ∩ T)ᶜ)), ← hf, ← add_apply, ← hadd, add_apply, hrn, add_zero] }, have heq' : ∀ A : set α, measurable_set A → s A = s.restrict (S ∩ T)ᶜ A, { intros A hA, have hsinter : s (A ∩ (S ∩ T)) = 0, { rw ← nonpos_iff_eq_zero, exact hS₂ ▸ measure_mono (set.subset.trans (set.inter_subset_right _ _) (set.inter_subset_left _ _)) }, rw [restrict_apply hA, ← add_zero (s (A ∩ (S ∩ T)ᶜ)), ← hsinter, ← measure_union, ← set.inter_union_distrib_left, set.compl_union_self, set.inter_univ], { exact disjoint.inter_left' _ ( disjoint.inter_right' _ disjoint_compl_left) }, { measurability }, { measurability } }, ext1 A hA, have hμinter : μ.singular_part ν (A ∩ (S ∩ T)) = 0, { rw ← nonpos_iff_eq_zero, exact hT₂ ▸ measure_mono (set.subset.trans (set.inter_subset_right _ _) (set.inter_subset_right _ _)) }, rw [heq' A hA, heq, ← add_zero ((μ.singular_part ν).restrict (S ∩ T)ᶜ A), ← hμinter, restrict_apply hA, ← measure_union, ← set.inter_union_distrib_left, set.compl_union_self, set.inter_univ], { exact disjoint.inter_left' _ ( disjoint.inter_right' _ disjoint_compl_left) }, { measurability }, { measurability } end lemma singular_part_zero (ν : measure α) : (0 : measure α).singular_part ν = 0 := begin refine (eq_singular_part measurable_zero mutually_singular.zero_left _).symm, rw [zero_add, with_density_zero], end lemma singular_part_smul (μ ν : measure α) (r : ℝ≥0) : (r • μ).singular_part ν = r • (μ.singular_part ν) := begin by_cases hr : r = 0, { rw [hr, zero_smul, zero_smul, singular_part_zero] }, by_cases hl : have_lebesgue_decomposition μ ν, { haveI := hl, refine (eq_singular_part ((measurable_rn_deriv μ ν).const_smul (r : ℝ≥0∞)) (mutually_singular.smul r (have_lebesgue_decomposition_spec _ _).2.1) _).symm, rw [with_density_smul _ (measurable_rn_deriv _ _), ← smul_add, ← have_lebesgue_decomposition_add μ ν, ennreal.smul_def] }, { rw [singular_part, singular_part, dif_neg hl, dif_neg, smul_zero], refine λ hl', hl _, rw ← inv_smul_smul₀ hr μ, exact @measure.have_lebesgue_decomposition_smul _ _ _ _ hl' _ } end lemma singular_part_add (μ₁ μ₂ ν : measure α) [have_lebesgue_decomposition μ₁ ν] [have_lebesgue_decomposition μ₂ ν] : (μ₁ + μ₂).singular_part ν = μ₁.singular_part ν + μ₂.singular_part ν := begin refine (eq_singular_part ((measurable_rn_deriv μ₁ ν).add (measurable_rn_deriv μ₂ ν)) ((have_lebesgue_decomposition_spec _ _).2.1.add_left (have_lebesgue_decomposition_spec _ _).2.1) _).symm, erw with_density_add (measurable_rn_deriv μ₁ ν) (measurable_rn_deriv μ₂ ν), conv_rhs { rw [add_assoc, add_comm (μ₂.singular_part ν), ← add_assoc, ← add_assoc] }, rw [← have_lebesgue_decomposition_add μ₁ ν, add_assoc, add_comm (ν.with_density (μ₂.rn_deriv ν)), ← have_lebesgue_decomposition_add μ₂ ν] end lemma singular_part_with_density (ν : measure α) {f : α → ℝ≥0∞} (hf : measurable f) : (ν.with_density f).singular_part ν = 0 := begin have : ν.with_density f = 0 + ν.with_density f, by rw zero_add, exact (eq_singular_part hf mutually_singular.zero_left this).symm, end /-- Given measures `μ` and `ν`, if `s` is a measure mutually singular to `ν` and `f` is a measurable function such that `μ = s + fν`, then `f = μ.rn_deriv ν`. This theorem provides the uniqueness of the `rn_deriv` in the Lebesgue decomposition theorem, while `measure_theory.measure.eq_singular_part` provides the uniqueness of the `singular_part`. Here, the uniqueness is given in terms of the measures, while the uniqueness in terms of the functions is given in `eq_rn_deriv`. -/ theorem eq_with_density_rn_deriv {s : measure α} {f : α → ℝ≥0∞} (hf : measurable f) (hs : s ⊥ₘ ν) (hadd : μ = s + ν.with_density f) : ν.with_density f = ν.with_density (μ.rn_deriv ν) := begin haveI : have_lebesgue_decomposition μ ν := ⟨⟨⟨s, f⟩, hf, hs, hadd⟩⟩, obtain ⟨hmeas, hsing, hadd'⟩ := have_lebesgue_decomposition_spec μ ν, obtain ⟨⟨S, hS₁, hS₂, hS₃⟩, ⟨T, hT₁, hT₂, hT₃⟩⟩ := ⟨hs, hsing⟩, rw hadd' at hadd, have hνinter : ν (S ∩ T)ᶜ = 0, { rw set.compl_inter, refine nonpos_iff_eq_zero.1 (le_trans (measure_union_le _ _) _), rw [hT₃, hS₃, add_zero], exact le_refl _ }, have heq : (ν.with_density f).restrict (S ∩ T) = (ν.with_density (μ.rn_deriv ν)).restrict (S ∩ T), { ext1 A hA, have hs : s (A ∩ (S ∩ T)) = 0, { rw ← nonpos_iff_eq_zero, exact hS₂ ▸ measure_mono (set.subset.trans (set.inter_subset_right _ _) (set.inter_subset_left _ _)) }, have hsing : μ.singular_part ν (A ∩ (S ∩ T)) = 0, { rw ← nonpos_iff_eq_zero, exact hT₂ ▸ measure_mono (set.subset.trans (set.inter_subset_right _ _) (set.inter_subset_right _ _)) }, rw [restrict_apply hA, restrict_apply hA, ← add_zero (ν.with_density f (A ∩ (S ∩ T))), ← hs, ← add_apply, add_comm, ← hadd, add_apply, hsing, zero_add] }, have heq' : ∀ A : set α, measurable_set A → ν.with_density f A = (ν.with_density f).restrict (S ∩ T) A, { intros A hA, have hνfinter : ν.with_density f (A ∩ (S ∩ T)ᶜ) = 0, { rw ← nonpos_iff_eq_zero, exact with_density_absolutely_continuous ν f hνinter ▸ measure_mono (set.inter_subset_right _ _) }, rw [restrict_apply hA, ← add_zero (ν.with_density f (A ∩ (S ∩ T))), ← hνfinter, ← measure_union, ← set.inter_union_distrib_left, set.union_compl_self, set.inter_univ], { exact disjoint.inter_left' _ (disjoint.inter_right' _ disjoint_compl_right) }, { measurability }, { measurability } }, ext1 A hA, have hνrn : ν.with_density (μ.rn_deriv ν) (A ∩ (S ∩ T)ᶜ) = 0, { rw ← nonpos_iff_eq_zero, exact with_density_absolutely_continuous ν (μ.rn_deriv ν) hνinter ▸ measure_mono (set.inter_subset_right _ _) }, rw [heq' A hA, heq, ← add_zero ((ν.with_density (μ.rn_deriv ν)).restrict (S ∩ T) A), ← hνrn, restrict_apply hA, ← measure_union, ← set.inter_union_distrib_left, set.union_compl_self, set.inter_univ], { exact disjoint.inter_left' _ (disjoint.inter_right' _ disjoint_compl_right) }, { measurability }, { measurability } end /-- Given measures `μ` and `ν`, if `s` is a measure mutually singular to `ν` and `f` is a measurable function such that `μ = s + fν`, then `f = μ.rn_deriv ν`. This theorem provides the uniqueness of the `rn_deriv` in the Lebesgue decomposition theorem, while `measure_theory.measure.eq_singular_part` provides the uniqueness of the `singular_part`. Here, the uniqueness is given in terms of the functions, while the uniqueness in terms of the functions is given in `eq_with_density_rn_deriv`. -/ theorem eq_rn_deriv [sigma_finite ν] {s : measure α} {f : α → ℝ≥0∞} (hf : measurable f) (hs : s ⊥ₘ ν) (hadd : μ = s + ν.with_density f) : f =ᵐ[ν] μ.rn_deriv ν := begin refine ae_eq_of_forall_set_lintegral_eq_of_sigma_finite hf (measurable_rn_deriv μ ν) _, assume a ha h'a, calc ∫⁻ (x : α) in a, f x ∂ν = ν.with_density f a : (with_density_apply f ha).symm ... = ν.with_density (μ.rn_deriv ν) a : by rw eq_with_density_rn_deriv hf hs hadd ... = ∫⁻ (x : α) in a, μ.rn_deriv ν x ∂ν : with_density_apply _ ha end /-- The Radon-Nikodym derivative of `f ν` with respect to `ν` is `f`. -/ theorem rn_deriv_with_density (ν : measure α) [sigma_finite ν] {f : α → ℝ≥0∞} (hf : measurable f) : (ν.with_density f).rn_deriv ν =ᵐ[ν] f := begin have : ν.with_density f = 0 + ν.with_density f, by rw zero_add, exact (eq_rn_deriv hf mutually_singular.zero_left this).symm, end open vector_measure signed_measure /-- If two finite measures `μ` and `ν` are not mutually singular, there exists some `ε > 0` and a measurable set `E`, such that `ν(E) > 0` and `E` is positive with respect to `μ - εν`. This lemma is useful for the Lebesgue decomposition theorem. -/ lemma exists_positive_of_not_mutually_singular (μ ν : measure α) [is_finite_measure μ] [is_finite_measure ν] (h : ¬ μ ⊥ₘ ν) : ∃ ε : ℝ≥0, 0 < ε ∧ ∃ E : set α, measurable_set E ∧ 0 < ν E ∧ 0 ≤[E] μ.to_signed_measure - (ε • ν).to_signed_measure := begin -- for all `n : ℕ`, obtain the Hahn decomposition for `μ - (1 / n) ν` have : ∀ n : ℕ, ∃ i : set α, measurable_set i ∧ 0 ≤[i] (μ.to_signed_measure - ((1 / (n + 1) : ℝ≥0) • ν).to_signed_measure) ∧ (μ.to_signed_measure - ((1 / (n + 1) : ℝ≥0) • ν).to_signed_measure) ≤[iᶜ] 0, { intro, exact exists_compl_positive_negative _ }, choose f hf₁ hf₂ hf₃ using this, -- set `A` to be the intersection of all the negative parts of obtained Hahn decompositions -- and we show that `μ A = 0` set A := ⋂ n, (f n)ᶜ with hA₁, have hAmeas : measurable_set A, { exact measurable_set.Inter (λ n, (hf₁ n).compl) }, have hA₂ : ∀ n : ℕ, (μ.to_signed_measure - ((1 / (n + 1) : ℝ≥0) • ν).to_signed_measure) ≤[A] 0, { intro n, exact restrict_le_restrict_subset _ _ (hf₁ n).compl (hf₃ n) (set.Inter_subset _ _) }, have hA₃ : ∀ n : ℕ, μ A ≤ (1 / (n + 1) : ℝ≥0) * ν A, { intro n, have := nonpos_of_restrict_le_zero _ (hA₂ n), rwa [to_signed_measure_sub_apply hAmeas, sub_nonpos, ennreal.to_real_le_to_real] at this, exacts [ne_of_lt (measure_lt_top _ _), ne_of_lt (measure_lt_top _ _)] }, have hμ : μ A = 0, { lift μ A to ℝ≥0 using ne_of_lt (measure_lt_top _ _) with μA, lift ν A to ℝ≥0 using ne_of_lt (measure_lt_top _ _) with νA, rw ennreal.coe_eq_zero, by_cases hb : 0 < νA, { suffices : ∀ b, 0 < b → μA ≤ b, { by_contra, have h' := this (μA / 2) (nnreal.half_pos (zero_lt_iff.2 h)), rw ← @not_not (μA ≤ μA / 2) at h', exact h' (not_le.2 (nnreal.half_lt_self h)) }, intros c hc, have : ∃ n : ℕ, 1 / (n + 1 : ℝ) < c * νA⁻¹, refine exists_nat_one_div_lt _, { refine mul_pos hc _, rw _root_.inv_pos, exact hb }, rcases this with ⟨n, hn⟩, have hb₁ : (0 : ℝ) < νA⁻¹, { rw _root_.inv_pos, exact hb }, have h' : 1 / (↑n + 1) * νA < c, { rw [← nnreal.coe_lt_coe, ← mul_lt_mul_right hb₁, nnreal.coe_mul, mul_assoc, ← nnreal.coe_inv, ← nnreal.coe_mul, _root_.mul_inv_cancel, ← nnreal.coe_mul, mul_one, nnreal.coe_inv], { convert hn, simp }, { exact ne.symm (ne_of_lt hb) } }, refine le_trans _ (le_of_lt h'), rw [← ennreal.coe_le_coe, ennreal.coe_mul], exact hA₃ n }, { rw [not_lt, le_zero_iff] at hb, specialize hA₃ 0, simp [hb, le_zero_iff] at hA₃, assumption } }, -- since `μ` and `ν` are not mutually singular, `μ A = 0` implies `ν Aᶜ > 0` rw mutually_singular at h, push_neg at h, have := h _ hAmeas hμ, simp_rw [hA₁, set.compl_Inter, compl_compl] at this, -- as `Aᶜ = ⋃ n, f n`, `ν Aᶜ > 0` implies there exists some `n` such that `ν (f n) > 0` obtain ⟨n, hn⟩ := exists_measure_pos_of_not_measure_Union_null this, -- thus, choosing `f n` as the set `E` suffices exact ⟨1 / (n + 1), by simp, f n, hf₁ n, hn, hf₂ n⟩, end namespace lebesgue_decomposition /-- Given two measures `μ` and `ν`, `measurable_le μ ν` is the set of measurable functions `f`, such that, for all measurable sets `A`, `∫⁻ x in A, f x ∂μ ≤ ν A`. This is useful for the Lebesgue decomposition theorem. -/ def measurable_le (μ ν : measure α) : set (α → ℝ≥0∞) := { f | measurable f ∧ ∀ (A : set α) (hA : measurable_set A), ∫⁻ x in A, f x ∂μ ≤ ν A } lemma zero_mem_measurable_le : (0 : α → ℝ≥0∞) ∈ measurable_le μ ν := ⟨measurable_zero, λ A hA, by simp⟩ lemma max_measurable_le (f g : α → ℝ≥0∞) (hf : f ∈ measurable_le μ ν) (hg : g ∈ measurable_le μ ν) (A : set α) (hA : measurable_set A) : ∫⁻ a in A, max (f a) (g a) ∂μ ≤ ∫⁻ a in A ∩ { a | f a ≤ g a }, g a ∂μ + ∫⁻ a in A ∩ { a | g a < f a }, f a ∂μ := begin rw [← lintegral_indicator _ hA, ← lintegral_indicator f, ← lintegral_indicator g, ← lintegral_add], { refine lintegral_mono (λ a, _), by_cases haA : a ∈ A, { by_cases f a ≤ g a, { simp only, rw [set.indicator_of_mem haA, set.indicator_of_mem, set.indicator_of_not_mem, add_zero], simp only [le_refl, max_le_iff, and_true, h], { rintro ⟨_, hc⟩, exact false.elim ((not_lt.2 h) hc) }, { exact ⟨haA, h⟩ } }, { simp only, rw [set.indicator_of_mem haA, set.indicator_of_mem _ f, set.indicator_of_not_mem, zero_add], simp only [true_and, le_refl, max_le_iff, le_of_lt (not_le.1 h)], { rintro ⟨_, hc⟩, exact false.elim (h hc) }, { exact ⟨haA, not_le.1 h⟩ } } }, { simp [set.indicator_of_not_mem haA] } }, { exact measurable.indicator hg.1 (hA.inter (measurable_set_le hf.1 hg.1)) }, { exact measurable.indicator hf.1 (hA.inter (measurable_set_lt hg.1 hf.1)) }, { exact hA.inter (measurable_set_le hf.1 hg.1) }, { exact hA.inter (measurable_set_lt hg.1 hf.1) }, end lemma sup_mem_measurable_le {f g : α → ℝ≥0∞} (hf : f ∈ measurable_le μ ν) (hg : g ∈ measurable_le μ ν) : (λ a, f a ⊔ g a) ∈ measurable_le μ ν := begin simp_rw ennreal.sup_eq_max, refine ⟨measurable.max hf.1 hg.1, λ A hA, _⟩, have h₁ := hA.inter (measurable_set_le hf.1 hg.1), have h₂ := hA.inter (measurable_set_lt hg.1 hf.1), refine le_trans (max_measurable_le f g hf hg A hA) _, refine le_trans (add_le_add (hg.2 _ h₁) (hf.2 _ h₂)) _, { rw [← measure_union _ h₁ h₂], { refine le_of_eq _, congr, convert set.inter_union_compl A _, ext a, simpa }, rintro x ⟨⟨-, hx₁⟩, -, hx₂⟩, exact (not_le.2 hx₂) hx₁ } end lemma supr_succ_eq_sup {α} (f : ℕ → α → ℝ≥0∞) (m : ℕ) (a : α) : (⨆ (k : ℕ) (hk : k ≤ m + 1), f k a) = f m.succ a ⊔ ⨆ (k : ℕ) (hk : k ≤ m), f k a := begin ext x, simp only [option.mem_def, ennreal.some_eq_coe], split; intro h; rw ← h, symmetry, all_goals { set c := (⨆ (k : ℕ) (hk : k ≤ m + 1), f k a) with hc, set d := (f m.succ a ⊔ ⨆ (k : ℕ) (hk : k ≤ m), f k a) with hd, suffices : c ≤ d ∧ d ≤ c, { change c = d, -- removing this line breaks exact le_antisymm this.1 this.2 }, rw [hc, hd], refine ⟨_, _⟩, { refine bsupr_le (λ n hn, _), rcases nat.of_le_succ hn with (h | h), { exact le_sup_of_le_right (le_bsupr n h) }, { exact h ▸ le_sup_left } }, { refine sup_le _ _, { convert @le_bsupr _ _ _ (λ i, i ≤ m + 1) _ m.succ (le_refl _), refl }, { refine bsupr_le (λ n hn, _), have := (le_trans hn (nat.le_succ m)), -- replacing `this` below with the proof breaks exact (le_bsupr n this) } } }, end lemma supr_mem_measurable_le (f : ℕ → α → ℝ≥0∞) (hf : ∀ n, f n ∈ measurable_le μ ν) (n : ℕ) : (λ x, ⨆ k (hk : k ≤ n), f k x) ∈ measurable_le μ ν := begin induction n with m hm, { refine ⟨_, _⟩, { simp [(hf 0).1] }, { intros A hA, simp [(hf 0).2 A hA] } }, { have : (λ (a : α), ⨆ (k : ℕ) (hk : k ≤ m + 1), f k a) = (λ a, f m.succ a ⊔ ⨆ (k : ℕ) (hk : k ≤ m), f k a), { exact funext (λ _, supr_succ_eq_sup _ _ _) }, refine ⟨measurable_supr (λ n, measurable.supr_Prop _ (hf n).1), λ A hA, _⟩, rw this, exact (sup_mem_measurable_le (hf m.succ) hm).2 A hA } end lemma supr_mem_measurable_le' (f : ℕ → α → ℝ≥0∞) (hf : ∀ n, f n ∈ measurable_le μ ν) (n : ℕ) : (⨆ k (hk : k ≤ n), f k) ∈ measurable_le μ ν := begin convert supr_mem_measurable_le f hf n, ext, simp end section supr_lemmas --TODO: these statements should be moved elsewhere omit m lemma supr_monotone {α : Type*} (f : ℕ → α → ℝ≥0∞) : monotone (λ n x, ⨆ k (hk : k ≤ n), f k x) := begin intros n m hnm x, simp only, refine bsupr_le (λ k hk, _), have : k ≤ m := le_trans hk hnm, -- replacing `this` below with the proof breaks exact le_bsupr k this, end lemma supr_monotone' {α : Type*} (f : ℕ → α → ℝ≥0∞) (x : α) : monotone (λ n, ⨆ k (hk : k ≤ n), f k x) := λ n m hnm, supr_monotone f hnm x lemma supr_le_le {α : Type*} (f : ℕ → α → ℝ≥0∞) (n k : ℕ) (hk : k ≤ n) : f k ≤ λ x, ⨆ k (hk : k ≤ n), f k x := λ x, le_bsupr k hk end supr_lemmas /-- `measurable_le_eval μ ν` is the set of `∫⁻ x, f x ∂μ` for all `f ∈ measurable_le μ ν`. -/ def measurable_le_eval (μ ν : measure α) : set ℝ≥0∞ := (λ f : α → ℝ≥0∞, ∫⁻ x, f x ∂μ) '' measurable_le μ ν end lebesgue_decomposition open lebesgue_decomposition /-- Any pair of finite measures `μ` and `ν`, `have_lebesgue_decomposition`. That is to say, there exist a measure `ξ` and a measurable function `f`, such that `ξ` is mutually singular with respect to `ν` and `μ = ξ + ν.with_density f`. This is not an instance since this is also shown for the more general σ-finite measures with `measure_theory.measure.have_lebesgue_decomposition_of_sigma_finite`. -/ theorem have_lebesgue_decomposition_of_finite_measure [is_finite_measure μ] [is_finite_measure ν] : have_lebesgue_decomposition μ ν := ⟨begin have h := @exists_seq_tendsto_Sup _ _ _ _ _ (measurable_le_eval ν μ) ⟨0, 0, zero_mem_measurable_le, by simp⟩ (order_top.bdd_above _), choose g hmono hg₂ f hf₁ hf₂ using h, -- we set `ξ` to be the supremum of an increasing sequence of functions obtained from above set ξ := ⨆ n k (hk : k ≤ n), f k with hξ, -- we see that `ξ` has the largest integral among all functions in `measurable_le` have hξ₁ : Sup (measurable_le_eval ν μ) = ∫⁻ a, ξ a ∂ν, { have := @lintegral_tendsto_of_tendsto_of_monotone _ _ ν (λ n, ⨆ k (hk : k ≤ n), f k) (⨆ n k (hk : k ≤ n), f k) _ _ _, { refine tendsto_nhds_unique _ this, refine tendsto_of_tendsto_of_tendsto_of_le_of_le hg₂ tendsto_const_nhds _ _, { intro n, rw ← hf₂ n, apply lintegral_mono, simp only [supr_apply, supr_le_le f n n (le_refl _)] }, { intro n, exact le_Sup ⟨⨆ (k : ℕ) (hk : k ≤ n), f k, supr_mem_measurable_le' _ hf₁ _, rfl⟩ } }, { intro n, refine measurable.ae_measurable _, convert (supr_mem_measurable_le _ hf₁ n).1, ext, simp }, { refine filter.eventually_of_forall (λ a, _), simp [supr_monotone' f _] }, { refine filter.eventually_of_forall (λ a, _), simp [tendsto_at_top_supr (supr_monotone' f a)] } }, have hξm : measurable ξ, { convert measurable_supr (λ n, (supr_mem_measurable_le _ hf₁ n).1), ext, simp [hξ] }, -- `ξ` is the `f` in the theorem statement and we set `μ₁` to be `μ - ν.with_density ξ` -- since we need `μ₁ + ν.with_density ξ = μ` set μ₁ := μ - ν.with_density ξ with hμ₁, have hle : ν.with_density ξ ≤ μ, { intros B hB, rw [hξ, with_density_apply _ hB], simp_rw [supr_apply], rw lintegral_supr (λ i, (supr_mem_measurable_le _ hf₁ i).1) (supr_monotone _), exact supr_le (λ i, (supr_mem_measurable_le _ hf₁ i).2 B hB) }, haveI : is_finite_measure (ν.with_density ξ), { refine is_finite_measure_with_density _, have hle' := hle set.univ measurable_set.univ, rw [with_density_apply _ measurable_set.univ, measure.restrict_univ] at hle', exact ne_top_of_le_ne_top (measure_ne_top _ _) hle' }, refine ⟨⟨μ₁, ξ⟩, hξm, _, _⟩, { by_contra, -- if they are not mutually singular, then from `exists_positive_of_not_mutually_singular`, -- there exists some `ε > 0` and a measurable set `E`, such that `μ(E) > 0` and `E` is -- positive with respect to `ν - εμ` obtain ⟨ε, hε₁, E, hE₁, hE₂, hE₃⟩ := exists_positive_of_not_mutually_singular μ₁ ν h, simp_rw hμ₁ at hE₃, have hξle : ∀ A, measurable_set A → ∫⁻ a in A, ξ a ∂ν ≤ μ A, { intros A hA, rw hξ, simp_rw [supr_apply], rw lintegral_supr (λ n, (supr_mem_measurable_le _ hf₁ n).1) (supr_monotone _), exact supr_le (λ n, (supr_mem_measurable_le _ hf₁ n).2 A hA) }, -- since `E` is positive, we have `∫⁻ a in A ∩ E, ε + ξ a ∂ν ≤ μ (A ∩ E)` for all `A` have hε₂ : ∀ A : set α, measurable_set A → ∫⁻ a in A ∩ E, ε + ξ a ∂ν ≤ μ (A ∩ E), { intros A hA, have := subset_le_of_restrict_le_restrict _ _ hE₁ hE₃ (set.inter_subset_right A E), rwa [zero_apply, to_signed_measure_sub_apply (hA.inter hE₁), measure.sub_apply (hA.inter hE₁) hle, ennreal.to_real_sub_of_le _ (ne_of_lt (measure_lt_top _ _)), sub_nonneg, le_sub_iff_add_le, ← ennreal.to_real_add, ennreal.to_real_le_to_real, measure.coe_nnreal_smul, pi.smul_apply, with_density_apply _ (hA.inter hE₁), show ε • ν (A ∩ E) = (ε : ℝ≥0∞) * ν (A ∩ E), by refl, ← set_lintegral_const, ← lintegral_add measurable_const hξm] at this, { rw [ne.def, ennreal.add_eq_top, not_or_distrib], exact ⟨ne_of_lt (measure_lt_top _ _), ne_of_lt (measure_lt_top _ _)⟩ }, { exact ne_of_lt (measure_lt_top _ _) }, { exact ne_of_lt (measure_lt_top _ _) }, { exact ne_of_lt (measure_lt_top _ _) }, { rw with_density_apply _ (hA.inter hE₁), exact hξle (A ∩ E) (hA.inter hE₁) }, { apply_instance } }, -- from this, we can show `ξ + ε * E.indicator` is a function in `measurable_le` with -- integral greater than `ξ` have hξε : ξ + E.indicator (λ _, ε) ∈ measurable_le ν μ, { refine ⟨measurable.add hξm (measurable.indicator measurable_const hE₁), λ A hA, _⟩, have : ∫⁻ a in A, (ξ + E.indicator (λ _, ε)) a ∂ν = ∫⁻ a in A ∩ E, ε + ξ a ∂ν + ∫⁻ a in A ∩ Eᶜ, ξ a ∂ν, { rw [lintegral_add measurable_const hξm, add_assoc, ← lintegral_union (hA.inter hE₁) (hA.inter (hE₁.compl)) (disjoint.mono (set.inter_subset_right _ _) (set.inter_subset_right _ _) disjoint_compl_right), set.inter_union_compl], simp_rw [pi.add_apply], rw [lintegral_add hξm (measurable.indicator measurable_const hE₁), add_comm], refine congr_fun (congr_arg has_add.add _) _, rw [set_lintegral_const, lintegral_indicator _ hE₁, set_lintegral_const, measure.restrict_apply hE₁, set.inter_comm] }, conv_rhs { rw ← set.inter_union_compl A E }, rw [this, measure_union _ (hA.inter hE₁) (hA.inter hE₁.compl)], { exact add_le_add (hε₂ A hA) (hξle (A ∩ Eᶜ) (hA.inter hE₁.compl)) }, { exact disjoint.mono (set.inter_subset_right _ _) (set.inter_subset_right _ _) disjoint_compl_right } }, have : ∫⁻ a, ξ a + E.indicator (λ _, ε) a ∂ν ≤ Sup (measurable_le_eval ν μ) := le_Sup ⟨ξ + E.indicator (λ _, ε), hξε, rfl⟩, -- but this contradicts the maximality of `∫⁻ x, ξ x ∂ν` refine not_lt.2 this _, rw [hξ₁, lintegral_add hξm (measurable.indicator (measurable_const) hE₁), lintegral_indicator _ hE₁, set_lintegral_const], refine ennreal.lt_add_right _ (ennreal.mul_pos_iff.2 ⟨ennreal.coe_pos.2 hε₁, hE₂⟩).ne', have := measure_ne_top (ν.with_density ξ) set.univ, rwa [with_density_apply _ measurable_set.univ, measure.restrict_univ] at this }, -- since `ν.with_density ξ ≤ μ`, it is clear that `μ = μ₁ + ν.with_density ξ` { rw hμ₁, ext1 A hA, rw [measure.coe_add, pi.add_apply, measure.sub_apply hA hle, add_comm, add_tsub_cancel_of_le (hle A hA)] }, end⟩ local attribute [instance] have_lebesgue_decomposition_of_finite_measure instance {S : μ.finite_spanning_sets_in {s : set α | measurable_set s}} (n : ℕ) : is_finite_measure (μ.restrict $ S.set n) := ⟨by { rw [restrict_apply measurable_set.univ, set.univ_inter], exact S.finite _ }⟩ /-- **The Lebesgue decomposition theorem**: Any pair of σ-finite measures `μ` and `ν` `have_lebesgue_decomposition`. That is to say, there exist a measure `ξ` and a measurable function `f`, such that `ξ` is mutually singular with respect to `ν` and `μ = ξ + ν.with_density f` -/ @[priority 100] -- see Note [lower instance priority] instance have_lebesgue_decomposition_of_sigma_finite (μ ν : measure α) [sigma_finite μ] [sigma_finite ν] : have_lebesgue_decomposition μ ν := ⟨begin -- Since `μ` and `ν` are both σ-finite, there exists a sequence of pairwise disjoint spanning -- sets which are finite with respect to both `μ` and `ν` obtain ⟨S, T, h₁, h₂⟩ := exists_eq_disjoint_finite_spanning_sets_in μ ν, have h₃ : pairwise (disjoint on T.set) := h₁ ▸ h₂, -- We define `μn` and `νn` as sequences of measures such that `μn n = μ ∩ S n` and -- `νn n = ν ∩ S n` where `S` is the aforementioned finite spanning set sequence. -- Since `S` is spanning, it is clear that `sum μn = μ` and `sum νn = ν` set μn : ℕ → measure α := λ n, μ.restrict (S.set n) with hμn, have hμ : μ = sum μn, { rw [hμn, ← restrict_Union h₂ S.set_mem, S.spanning, restrict_univ] }, set νn : ℕ → measure α := λ n, ν.restrict (T.set n) with hνn, have hν : ν = sum νn, { rw [hνn, ← restrict_Union h₃ T.set_mem, T.spanning, restrict_univ] }, -- As `S` is finite with respect to both `μ` and `ν`, it is clear that `μn n` and `νn n` are -- finite measures for all `n : ℕ`. Thus, we may apply the finite Lebesgue decomposition theorem -- to `μn n` and `νn n`. We define `ξ` as the sum of the singular part of the Lebesgue -- decompositions of `μn n` and `νn n`, and `f` as the sum of the Radon-Nikodym derviatives of -- `μn n` and `νn n` restricted on `S n` set ξ := sum (λ n, singular_part (μn n) (νn n)) with hξ, set f := ∑' n, (S.set n).indicator (rn_deriv (μn n) (νn n)) with hf, -- I claim `ξ` and `f` form a Lebesgue decomposition of `μ` and `ν` refine ⟨⟨ξ, f⟩, _, _, _⟩, { exact measurable.ennreal_tsum' (λ n, measurable.indicator (measurable_rn_deriv (μn n) (νn n)) (S.set_mem n)) }, -- We show that `ξ` is mutually singular with respect to `ν` { choose A hA₁ hA₂ hA₃ using λ n, mutually_singular_singular_part (μn n) (νn n), simp only [hξ], -- We use the set `B := ⋃ j, (S.set j) ∩ A j` where `A n` is the set provided as -- `singular_part (μn n) (νn n) ⊥ₘ νn n` refine ⟨⋃ j, (S.set j) ∩ A j, measurable_set.Union (λ n, (S.set_mem n).inter (hA₁ n)), _, _⟩, -- `ξ B = 0` since `ξ B = ∑ i j, singular_part (μn j) (νn j) (S.set i ∩ A i)` -- `= ∑ i, singular_part (μn i) (νn i) (S.set i ∩ A i)` -- `≤ ∑ i, singular_part (μn i) (νn i) (A i) = 0` -- where the second equality follows as `singular_part (μn j) (νn j) (S.set i ∩ A i)` vanishes -- for all `i ≠ j` { rw [measure_Union], { have : ∀ i, (sum (λ n, (μn n).singular_part (νn n))) (S.set i ∩ A i) = (μn i).singular_part (νn i) (S.set i ∩ A i), { intro i, rw [sum_apply _ ((S.set_mem i).inter (hA₁ i)), tsum_eq_single i], { intros j hij, rw [hμn, ← nonpos_iff_eq_zero], refine le_trans ((singular_part_le _ _) _ ((S.set_mem i).inter (hA₁ i))) (le_of_eq _), rw [restrict_apply ((S.set_mem i).inter (hA₁ i)), set.inter_comm, ← set.inter_assoc], have : disjoint (S.set j) (S.set i) := h₂ j i hij, rw set.disjoint_iff_inter_eq_empty at this, rw [this, set.empty_inter, measure_empty] }, { apply_instance } }, simp_rw [this, tsum_eq_zero_iff ennreal.summable], intro n, exact measure_mono_null (set.inter_subset_right _ _) (hA₂ n) }, { exact h₂.mono (λ i j, disjoint.mono inf_le_left inf_le_left) }, { exact λ n, (S.set_mem n).inter (hA₁ n) } }, -- We will now show `ν Bᶜ = 0`. This follows since `Bᶜ = ⋃ n, S.set n ∩ (A n)ᶜ` and thus, -- `ν Bᶜ = ∑ i, ν (S.set i ∩ (A i)ᶜ) = ∑ i, (νn i) (A i)ᶜ = 0` { have hcompl : is_compl (⋃ n, (S.set n ∩ A n)) (⋃ n, S.set n ∩ (A n)ᶜ), { split, { rintro x ⟨hx₁, hx₂⟩, rw set.mem_Union at hx₁ hx₂, obtain ⟨⟨i, hi₁, hi₂⟩, ⟨j, hj₁, hj₂⟩⟩ := ⟨hx₁, hx₂⟩, have : i = j, { by_contra hij, exact h₂ i j hij ⟨hi₁, hj₁⟩ }, exact hj₂ (this ▸ hi₂) }, { intros x hx, simp only [set.mem_Union, set.sup_eq_union, set.mem_inter_eq, set.mem_union_eq, set.mem_compl_eq, or_iff_not_imp_left], intro h, push_neg at h, rw [set.top_eq_univ, ← S.spanning, set.mem_Union] at hx, obtain ⟨i, hi⟩ := hx, exact ⟨i, hi, h i hi⟩ } }, rw [hcompl.compl_eq, measure_Union, tsum_eq_zero_iff ennreal.summable], { intro n, rw [set.inter_comm, ← restrict_apply (hA₁ n).compl, ← hA₃ n, hνn, h₁] }, { exact h₂.mono (λ i j, disjoint.mono inf_le_left inf_le_left) }, { exact λ n, (S.set_mem n).inter (hA₁ n).compl } } }, -- Finally, it remains to show `μ = ξ + ν.with_density f`. Since `μ = sum μn`, and -- `ξ + ν.with_density f = ∑ n, singular_part (μn n) (νn n)` -- `+ ν.with_density (rn_deriv (μn n) (νn n)) ∩ (S.set n)`, -- it suffices to show that the individual summands are equal. This follows by the -- Lebesgue decomposition properties on the individual `μn n` and `νn n` { simp only [hξ, hf, hμ], rw [with_density_tsum _, sum_add_sum], { refine sum_congr (λ n, _), conv_lhs { rw have_lebesgue_decomposition_add (μn n) (νn n) }, suffices heq : (νn n).with_density ((μn n).rn_deriv (νn n)) = ν.with_density ((S.set n).indicator ((μn n).rn_deriv (νn n))), { rw heq }, rw [hν, with_density_indicator (S.set_mem n), restrict_sum _ (S.set_mem n)], suffices hsumeq : sum (λ (i : ℕ), (νn i).restrict (S.set n)) = νn n, { rw hsumeq }, ext1 s hs, rw [sum_apply _ hs, tsum_eq_single n, hνn, h₁, restrict_restrict (T.set_mem n), set.inter_self], { intros m hm, rw [hνn, h₁, restrict_restrict (T.set_mem n), set.inter_comm, set.disjoint_iff_inter_eq_empty.1 (h₃ m n hm), restrict_empty, coe_zero, pi.zero_apply] }, { apply_instance } }, { exact λ n, measurable.indicator (measurable_rn_deriv _ _) (S.set_mem n) } }, end⟩ end measure namespace signed_measure open measure /-- A signed measure `s` is said to `have_lebesgue_decomposition` with respect to a measure `μ` if the positive part and the negative part of `s` both `have_lebesgue_decomposition` with respect to `μ`. -/ class have_lebesgue_decomposition (s : signed_measure α) (μ : measure α) : Prop := (pos_part : s.to_jordan_decomposition.pos_part.have_lebesgue_decomposition μ) (neg_part : s.to_jordan_decomposition.neg_part.have_lebesgue_decomposition μ) attribute [instance] have_lebesgue_decomposition.pos_part attribute [instance] have_lebesgue_decomposition.neg_part lemma not_have_lebesgue_decomposition_iff (s : signed_measure α) (μ : measure α) : ¬ s.have_lebesgue_decomposition μ ↔ ¬ s.to_jordan_decomposition.pos_part.have_lebesgue_decomposition μ ∨ ¬ s.to_jordan_decomposition.neg_part.have_lebesgue_decomposition μ := ⟨λ h, not_or_of_imp (λ hp hn, h ⟨hp, hn⟩), λ h hl, (not_and_distrib.2 h) ⟨hl.1, hl.2⟩⟩ -- `infer_instance` directly does not work @[priority 100] -- see Note [lower instance priority] instance have_lebesgue_decomposition_of_sigma_finite (s : signed_measure α) (μ : measure α) [sigma_finite μ] : s.have_lebesgue_decomposition μ := { pos_part := infer_instance, neg_part := infer_instance } instance have_lebesgue_decomposition_neg (s : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] : (-s).have_lebesgue_decomposition μ := { pos_part := by { rw [to_jordan_decomposition_neg, jordan_decomposition.neg_pos_part], apply_instance }, neg_part := by { rw [to_jordan_decomposition_neg, jordan_decomposition.neg_neg_part], apply_instance } } instance have_lebesgue_decomposition_smul (s : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] (r : ℝ≥0) : (r • s).have_lebesgue_decomposition μ := { pos_part := by { rw [to_jordan_decomposition_smul, jordan_decomposition.smul_pos_part], apply_instance }, neg_part := by { rw [to_jordan_decomposition_smul, jordan_decomposition.smul_neg_part], apply_instance } } instance have_lebesgue_decomposition_smul_real (s : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] (r : ℝ) : (r • s).have_lebesgue_decomposition μ := begin by_cases hr : 0 ≤ r, { lift r to ℝ≥0 using hr, exact s.have_lebesgue_decomposition_smul μ _ }, { rw not_le at hr, refine { pos_part := by { rw [to_jordan_decomposition_smul_real, jordan_decomposition.real_smul_pos_part_neg _ _ hr], apply_instance }, neg_part := by { rw [to_jordan_decomposition_smul_real, jordan_decomposition.real_smul_neg_part_neg _ _ hr], apply_instance } } } end /-- Given a signed measure `s` and a measure `μ`, `s.singular_part μ` is the signed measure such that `s.singular_part μ + μ.with_densityᵥ (s.rn_deriv μ) = s` and `s.singular_part μ` is mutually singular with respect to `μ`. -/ def singular_part (s : signed_measure α) (μ : measure α) : signed_measure α := (s.to_jordan_decomposition.pos_part.singular_part μ).to_signed_measure - (s.to_jordan_decomposition.neg_part.singular_part μ).to_signed_measure section lemma singular_part_mutually_singular (s : signed_measure α) (μ : measure α) : s.to_jordan_decomposition.pos_part.singular_part μ ⊥ₘ s.to_jordan_decomposition.neg_part.singular_part μ := begin by_cases hl : s.have_lebesgue_decomposition μ, { haveI := hl, obtain ⟨i, hi, hpos, hneg⟩ := s.to_jordan_decomposition.mutually_singular, rw s.to_jordan_decomposition.pos_part.have_lebesgue_decomposition_add μ at hpos, rw s.to_jordan_decomposition.neg_part.have_lebesgue_decomposition_add μ at hneg, rw [add_apply, add_eq_zero_iff] at hpos hneg, exact ⟨i, hi, hpos.1, hneg.1⟩ }, { rw not_have_lebesgue_decomposition_iff at hl, cases hl with hp hn, { rw [measure.singular_part, dif_neg hp], exact mutually_singular.zero_left }, { rw [measure.singular_part, measure.singular_part, dif_neg hn], exact mutually_singular.zero_right } } end lemma singular_part_total_variation (s : signed_measure α) (μ : measure α) : (s.singular_part μ).total_variation = s.to_jordan_decomposition.pos_part.singular_part μ + s.to_jordan_decomposition.neg_part.singular_part μ := begin have : (s.singular_part μ).to_jordan_decomposition = ⟨s.to_jordan_decomposition.pos_part.singular_part μ, s.to_jordan_decomposition.neg_part.singular_part μ, singular_part_mutually_singular s μ⟩, { refine jordan_decomposition.to_signed_measure_injective _, rw to_signed_measure_to_jordan_decomposition, refl }, { rw [total_variation, this] }, end lemma mutually_singular_singular_part (s : signed_measure α) (μ : measure α) : singular_part s μ ⊥ᵥ μ.to_ennreal_vector_measure := begin rw [mutually_singular_ennreal_iff, singular_part_total_variation], change _ ⊥ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ), rw vector_measure.equiv_measure.right_inv μ, exact (mutually_singular_singular_part _ _).add_left (mutually_singular_singular_part _ _) end end /-- The Radon-Nikodym derivative between a signed measure and a positive measure. `rn_deriv s μ` satisfies `μ.with_densityᵥ (s.rn_deriv μ) = s` if and only if `s` is absolutely continuous with respect to `μ` and this fact is known as `measure_theory.signed_measure.absolutely_continuous_iff_with_density_rn_deriv_eq` and can be found in `measure_theory.decomposition.radon_nikodym`. -/ def rn_deriv (s : signed_measure α) (μ : measure α) : α → ℝ := λ x, (s.to_jordan_decomposition.pos_part.rn_deriv μ x).to_real - (s.to_jordan_decomposition.neg_part.rn_deriv μ x).to_real variables {s t : signed_measure α} @[measurability] lemma measurable_rn_deriv (s : signed_measure α) (μ : measure α) : measurable (rn_deriv s μ) := begin rw [rn_deriv], measurability, end lemma integrable_rn_deriv (s : signed_measure α) (μ : measure α) : integrable (rn_deriv s μ) μ := begin refine integrable.sub _ _; { split, measurability, exact has_finite_integral_to_real_of_lintegral_ne_top (lintegral_rn_deriv_lt_top _ μ).ne } end /-- **The Lebesgue Decomposition theorem between a signed measure and a measure**: Given a signed measure `s` and a σ-finite measure `μ`, there exist a signed measure `t` and a measurable and integrable function `f`, such that `t` is mutually singular with respect to `μ` and `s = t + μ.with_densityᵥ f`. In this case `t = s.singular_part μ` and `f = s.rn_deriv μ`. -/ theorem singular_part_add_with_density_rn_deriv_eq [s.have_lebesgue_decomposition μ] : s.singular_part μ + μ.with_densityᵥ (s.rn_deriv μ) = s := begin conv_rhs { rw [← to_signed_measure_to_jordan_decomposition s, jordan_decomposition.to_signed_measure] }, rw [singular_part, rn_deriv, with_densityᵥ_sub' (integrable_to_real_of_lintegral_ne_top _ _) (integrable_to_real_of_lintegral_ne_top _ _), with_densityᵥ_to_real, with_densityᵥ_to_real, sub_eq_add_neg, sub_eq_add_neg, add_comm (s.to_jordan_decomposition.pos_part.singular_part μ).to_signed_measure, ← add_assoc, add_assoc (-(s.to_jordan_decomposition.neg_part.singular_part μ).to_signed_measure), ← to_signed_measure_add, add_comm, ← add_assoc, ← neg_add, ← to_signed_measure_add, add_comm, ← sub_eq_add_neg], convert rfl, -- `convert rfl` much faster than `congr` { exact (s.to_jordan_decomposition.pos_part.have_lebesgue_decomposition_add μ) }, { rw add_comm, exact (s.to_jordan_decomposition.neg_part.have_lebesgue_decomposition_add μ) }, all_goals { exact (lintegral_rn_deriv_lt_top _ _).ne <|> measurability } end lemma jordan_decomposition_add_with_density_mutually_singular {f : α → ℝ} (hf : measurable f) (htμ : t ⊥ᵥ μ.to_ennreal_vector_measure) : t.to_jordan_decomposition.pos_part + μ.with_density (λ (x : α), ennreal.of_real (f x)) ⊥ₘ t.to_jordan_decomposition.neg_part + μ.with_density (λ (x : α), ennreal.of_real (-f x)) := begin rw [mutually_singular_ennreal_iff, total_variation_mutually_singular_iff] at htμ, change _ ⊥ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ) ∧ _ ⊥ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ) at htμ, rw [vector_measure.equiv_measure.right_inv] at htμ, exact ((jordan_decomposition.mutually_singular _).add_right (htμ.1.mono_ac (refl _) (with_density_absolutely_continuous _ _))).add_left ((htμ.2.symm.mono_ac (with_density_absolutely_continuous _ _) (refl _)).add_right (with_density_of_real_mutually_singular hf)) end lemma to_jordan_decomposition_eq_of_eq_add_with_density {f : α → ℝ} (hf : measurable f) (hfi : integrable f μ) (htμ : t ⊥ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) : s.to_jordan_decomposition = @jordan_decomposition.mk α _ (t.to_jordan_decomposition.pos_part + μ.with_density (λ x, ennreal.of_real (f x))) (t.to_jordan_decomposition.neg_part + μ.with_density (λ x, ennreal.of_real (- f x))) (by { haveI := is_finite_measure_with_density_of_real hfi.2, apply_instance }) (by { haveI := is_finite_measure_with_density_of_real hfi.neg.2, apply_instance }) (jordan_decomposition_add_with_density_mutually_singular hf htμ) := begin haveI := is_finite_measure_with_density_of_real hfi.2, haveI := is_finite_measure_with_density_of_real hfi.neg.2, refine to_jordan_decomposition_eq _, simp_rw [jordan_decomposition.to_signed_measure, hadd], ext i hi, rw [vector_measure.sub_apply, to_signed_measure_apply_measurable hi, to_signed_measure_apply_measurable hi, add_apply, add_apply, ennreal.to_real_add, ennreal.to_real_add, add_sub_comm, ← to_signed_measure_apply_measurable hi, ← to_signed_measure_apply_measurable hi, ← vector_measure.sub_apply, ← jordan_decomposition.to_signed_measure, to_signed_measure_to_jordan_decomposition, vector_measure.add_apply, ← to_signed_measure_apply_measurable hi, ← to_signed_measure_apply_measurable hi, with_densityᵥ_eq_with_density_pos_part_sub_with_density_neg_part hfi, vector_measure.sub_apply]; exact (measure_lt_top _ _).ne end private lemma have_lebesgue_decomposition_mk' (μ : measure α) {f : α → ℝ} (hf : measurable f) (hfi : integrable f μ) (htμ : t ⊥ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) : s.have_lebesgue_decomposition μ := begin have htμ' := htμ, rw mutually_singular_ennreal_iff at htμ, change _ ⊥ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ) at htμ, rw [vector_measure.equiv_measure.right_inv, total_variation_mutually_singular_iff] at htμ, refine { pos_part := by { use ⟨t.to_jordan_decomposition.pos_part, λ x, ennreal.of_real (f x)⟩, refine ⟨hf.ennreal_of_real, htμ.1, _⟩, rw to_jordan_decomposition_eq_of_eq_add_with_density hf hfi htμ' hadd }, neg_part := by { use ⟨t.to_jordan_decomposition.neg_part, λ x, ennreal.of_real (-f x)⟩, refine ⟨hf.neg.ennreal_of_real, htμ.2, _⟩, rw to_jordan_decomposition_eq_of_eq_add_with_density hf hfi htμ' hadd } } end lemma have_lebesgue_decomposition_mk (μ : measure α) {f : α → ℝ} (hf : measurable f) (htμ : t ⊥ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) : s.have_lebesgue_decomposition μ := begin by_cases hfi : integrable f μ, { exact have_lebesgue_decomposition_mk' μ hf hfi htμ hadd }, { rw [with_densityᵥ, dif_neg hfi, add_zero] at hadd, refine have_lebesgue_decomposition_mk' μ measurable_zero (integrable_zero _ _ μ) htμ _, rwa [with_densityᵥ_zero, add_zero] } end private theorem eq_singular_part' (t : signed_measure α) {f : α → ℝ} (hf : measurable f) (hfi : integrable f μ) (htμ : t ⊥ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) : t = s.singular_part μ := begin have htμ' := htμ, rw [mutually_singular_ennreal_iff, total_variation_mutually_singular_iff] at htμ, change _ ⊥ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ) ∧ _ ⊥ₘ vector_measure.equiv_measure.to_fun (vector_measure.equiv_measure.inv_fun μ) at htμ, rw [vector_measure.equiv_measure.right_inv] at htμ, { rw [singular_part, ← t.to_signed_measure_to_jordan_decomposition, jordan_decomposition.to_signed_measure], congr, { have hfpos : measurable (λ x, ennreal.of_real (f x)), { measurability }, refine eq_singular_part hfpos htμ.1 _, rw to_jordan_decomposition_eq_of_eq_add_with_density hf hfi htμ' hadd }, { have hfneg : measurable (λ x, ennreal.of_real (-f x)), { measurability }, refine eq_singular_part hfneg htμ.2 _, rw to_jordan_decomposition_eq_of_eq_add_with_density hf hfi htμ' hadd } }, end /-- Given a measure `μ`, signed measures `s` and `t`, and a function `f` such that `t` is mutually singular with respect to `μ` and `s = t + μ.with_densityᵥ f`, we have `t = singular_part s μ`, i.e. `t` is the singular part of the Lebesgue decomposition between `s` and `μ`. -/ theorem eq_singular_part (t : signed_measure α) (f : α → ℝ) (htμ : t ⊥ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) : t = s.singular_part μ := begin by_cases hfi : integrable f μ, { refine eq_singular_part' t hfi.1.measurable_mk (hfi.congr hfi.1.ae_eq_mk) htμ _, convert hadd using 2, exact with_densityᵥ_eq.congr_ae hfi.1.ae_eq_mk.symm }, { rw [with_densityᵥ, dif_neg hfi, add_zero] at hadd, refine eq_singular_part' t measurable_zero (integrable_zero _ _ μ) htμ _, rwa [with_densityᵥ_zero, add_zero] } end lemma singular_part_zero (μ : measure α) : (0 : signed_measure α).singular_part μ = 0 := begin refine (eq_singular_part 0 0 vector_measure.mutually_singular.zero_left _).symm, rw [zero_add, with_densityᵥ_zero], end lemma singular_part_neg (s : signed_measure α) (μ : measure α) : (-s).singular_part μ = - s.singular_part μ := begin have h₁ : ((-s).to_jordan_decomposition.pos_part.singular_part μ).to_signed_measure = (s.to_jordan_decomposition.neg_part.singular_part μ).to_signed_measure, { refine to_signed_measure_congr _, rw [to_jordan_decomposition_neg, jordan_decomposition.neg_pos_part] }, have h₂ : ((-s).to_jordan_decomposition.neg_part.singular_part μ).to_signed_measure = (s.to_jordan_decomposition.pos_part.singular_part μ).to_signed_measure, { refine to_signed_measure_congr _, rw [to_jordan_decomposition_neg, jordan_decomposition.neg_neg_part] }, rw [singular_part, singular_part, neg_sub, h₁, h₂], end lemma singular_part_smul_nnreal (s : signed_measure α) (μ : measure α) (r : ℝ≥0) : (r • s).singular_part μ = r • s.singular_part μ := begin rw [singular_part, singular_part, smul_sub, ← to_signed_measure_smul, ← to_signed_measure_smul], conv_lhs { congr, congr, rw [to_jordan_decomposition_smul, jordan_decomposition.smul_pos_part, singular_part_smul], skip, congr, rw [to_jordan_decomposition_smul, jordan_decomposition.smul_neg_part, singular_part_smul] } end lemma singular_part_smul (s : signed_measure α) (μ : measure α) (r : ℝ) : (r • s).singular_part μ = r • s.singular_part μ := begin by_cases hr : 0 ≤ r, { lift r to ℝ≥0 using hr, exact singular_part_smul_nnreal s μ r }, { rw [singular_part, singular_part], conv_lhs { congr, congr, rw [to_jordan_decomposition_smul_real, jordan_decomposition.real_smul_pos_part_neg _ _ (not_le.1 hr), singular_part_smul], skip, congr, rw [to_jordan_decomposition_smul_real, jordan_decomposition.real_smul_neg_part_neg _ _ (not_le.1 hr), singular_part_smul] }, rw [to_signed_measure_smul, to_signed_measure_smul, ← neg_sub, ← smul_sub], change -(((-r).to_nnreal : ℝ) • _) = _, rw [← neg_smul, real.coe_to_nnreal _ (le_of_lt (neg_pos.mpr (not_le.1 hr))), neg_neg] } end lemma singular_part_add (s t : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] [t.have_lebesgue_decomposition μ] : (s + t).singular_part μ = s.singular_part μ + t.singular_part μ := begin refine (eq_singular_part _ (s.rn_deriv μ + t.rn_deriv μ) ((mutually_singular_singular_part s μ).add_left (mutually_singular_singular_part t μ)) _).symm, erw [with_densityᵥ_add (integrable_rn_deriv s μ) (integrable_rn_deriv t μ)], rw [add_assoc, add_comm (t.singular_part μ), add_assoc, add_comm _ (t.singular_part μ), singular_part_add_with_density_rn_deriv_eq, ← add_assoc, singular_part_add_with_density_rn_deriv_eq], end lemma singular_part_sub (s t : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] [t.have_lebesgue_decomposition μ] : (s - t).singular_part μ = s.singular_part μ - t.singular_part μ := by { rw [sub_eq_add_neg, sub_eq_add_neg, singular_part_add, singular_part_neg] } /-- Given a measure `μ`, signed measures `s` and `t`, and a function `f` such that `t` is mutually singular with respect to `μ` and `s = t + μ.with_densityᵥ f`, we have `f = rn_deriv s μ`, i.e. `f` is the Radon-Nikodym derivative of `s` and `μ`. -/ theorem eq_rn_deriv (t : signed_measure α) (f : α → ℝ) (hfi : integrable f μ) (htμ : t ⊥ᵥ μ.to_ennreal_vector_measure) (hadd : s = t + μ.with_densityᵥ f) : f =ᵐ[μ] s.rn_deriv μ := begin set f' := hfi.1.mk f, have hadd' : s = t + μ.with_densityᵥ f', { convert hadd using 2, exact with_densityᵥ_eq.congr_ae hfi.1.ae_eq_mk.symm }, haveI := have_lebesgue_decomposition_mk μ hfi.1.measurable_mk htμ hadd', refine (integrable.ae_eq_of_with_densityᵥ_eq (integrable_rn_deriv _ _) hfi _).symm, rw [← add_right_inj t, ← hadd, eq_singular_part _ f htμ hadd, singular_part_add_with_density_rn_deriv_eq], end lemma rn_deriv_neg (s : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] : (-s).rn_deriv μ =ᵐ[μ] - s.rn_deriv μ := begin refine integrable.ae_eq_of_with_densityᵥ_eq (integrable_rn_deriv _ _) (integrable_rn_deriv _ _).neg _, rw [with_densityᵥ_neg, ← add_right_inj ((-s).singular_part μ), singular_part_add_with_density_rn_deriv_eq, singular_part_neg, ← neg_add, singular_part_add_with_density_rn_deriv_eq] end lemma rn_deriv_smul (s : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] (r : ℝ) : (r • s).rn_deriv μ =ᵐ[μ] r • s.rn_deriv μ := begin refine integrable.ae_eq_of_with_densityᵥ_eq (integrable_rn_deriv _ _) ((integrable_rn_deriv _ _).smul r) _, change _ = μ.with_densityᵥ ((r : ℝ) • s.rn_deriv μ), rw [with_densityᵥ_smul (rn_deriv s μ) (r : ℝ), ← add_right_inj ((r • s).singular_part μ), singular_part_add_with_density_rn_deriv_eq, singular_part_smul], change _ = _ + r • _, rw [← smul_add, singular_part_add_with_density_rn_deriv_eq], end lemma rn_deriv_add (s t : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] [t.have_lebesgue_decomposition μ] [(s + t).have_lebesgue_decomposition μ] : (s + t).rn_deriv μ =ᵐ[μ] s.rn_deriv μ + t.rn_deriv μ := begin refine integrable.ae_eq_of_with_densityᵥ_eq (integrable_rn_deriv _ _) ((integrable_rn_deriv _ _).add (integrable_rn_deriv _ _)) _, rw [← add_right_inj ((s + t).singular_part μ), singular_part_add_with_density_rn_deriv_eq, with_densityᵥ_add (integrable_rn_deriv _ _) (integrable_rn_deriv _ _), singular_part_add, add_assoc, add_comm (t.singular_part μ), add_assoc, add_comm _ (t.singular_part μ), singular_part_add_with_density_rn_deriv_eq, ← add_assoc, singular_part_add_with_density_rn_deriv_eq], end lemma rn_deriv_sub (s t : signed_measure α) (μ : measure α) [s.have_lebesgue_decomposition μ] [t.have_lebesgue_decomposition μ] [hst : (s - t).have_lebesgue_decomposition μ] : (s - t).rn_deriv μ =ᵐ[μ] s.rn_deriv μ - t.rn_deriv μ := begin rw sub_eq_add_neg at hst, rw [sub_eq_add_neg, sub_eq_add_neg], exactI ae_eq_trans (rn_deriv_add _ _ _) (filter.eventually_eq.add (ae_eq_refl _) (rn_deriv_neg _ _)), end end signed_measure namespace complex_measure /-- A complex measure is said to `have_lebesgue_decomposition` with respect to a positive measure if both its real and imaginary part `have_lebesgue_decomposition` with respect to that measure. -/ class have_lebesgue_decomposition (c : complex_measure α) (μ : measure α) : Prop := (re_part : c.re.have_lebesgue_decomposition μ) (im_part : c.im.have_lebesgue_decomposition μ) attribute [instance] have_lebesgue_decomposition.re_part attribute [instance] have_lebesgue_decomposition.im_part /-- The singular part between a complex measure `c` and a positive measure `μ` is the complex measure satisfying `c.singular_part μ + μ.with_densityᵥ (c.rn_deriv μ) = c`. This property is given by `measure_theory.complex_measure.singular_part_add_with_density_rn_deriv_eq`. -/ def singular_part (c : complex_measure α) (μ : measure α) : complex_measure α := (c.re.singular_part μ).to_complex_measure (c.im.singular_part μ) /-- The Radon-Nikodym derivative between a complex measure and a positive measure. -/ def rn_deriv (c : complex_measure α) (μ : measure α) : α → ℂ := λ x, ⟨c.re.rn_deriv μ x, c.im.rn_deriv μ x⟩ variable {c : complex_measure α} lemma integrable_rn_deriv (c : complex_measure α) (μ : measure α) : integrable (c.rn_deriv μ) μ := begin rw [← mem_ℒp_one_iff_integrable, ← mem_ℒp_re_im_iff], exact ⟨mem_ℒp_one_iff_integrable.2 (signed_measure.integrable_rn_deriv _ _), mem_ℒp_one_iff_integrable.2 (signed_measure.integrable_rn_deriv _ _)⟩ end theorem singular_part_add_with_density_rn_deriv_eq [c.have_lebesgue_decomposition μ] : c.singular_part μ + μ.with_densityᵥ (c.rn_deriv μ) = c := begin conv_rhs { rw [← c.to_complex_measure_to_signed_measure] }, ext i hi, { rw [vector_measure.add_apply, signed_measure.to_complex_measure_apply, complex.add_re, re_apply, with_densityᵥ_apply (c.integrable_rn_deriv μ) hi, ← set_integral_re_add_im (c.integrable_rn_deriv μ).integrable_on], suffices : (c.singular_part μ i).re + ∫ x in i, (c.rn_deriv μ x).re ∂μ = (c i).re, { simpa }, rw [← with_densityᵥ_apply _ hi], { change (c.re.singular_part μ + μ.with_densityᵥ (c.re.rn_deriv μ)) i = _, rw @signed_measure.singular_part_add_with_density_rn_deriv_eq _ _ μ c.re _, refl }, { exact (signed_measure.integrable_rn_deriv _ _) } }, { rw [vector_measure.add_apply, signed_measure.to_complex_measure_apply, complex.add_im, im_apply, with_densityᵥ_apply (c.integrable_rn_deriv μ) hi, ← set_integral_re_add_im (c.integrable_rn_deriv μ).integrable_on], suffices : (c.singular_part μ i).im + ∫ x in i, (c.rn_deriv μ x).im ∂μ = (c i).im, { simpa }, rw [← with_densityᵥ_apply _ hi], { change (c.im.singular_part μ + μ.with_densityᵥ (c.im.rn_deriv μ)) i = _, rw @signed_measure.singular_part_add_with_density_rn_deriv_eq _ _ μ c.im _, refl }, { exact (signed_measure.integrable_rn_deriv _ _) } } end end complex_measure end measure_theory
77e6b2def20658cf46f6e5bc364e6f8937a7ab31
4bcaca5dc83d49803f72b7b5920b75b6e7d9de2d
/stage0/src/Lean/Elab/Term.lean
057301141acf258da675d1aa4f488d78e55e1916
[ "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
69,541
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Sebastian Ullrich -/ import Lean.ResolveName import Lean.Util.Sorry import Lean.Util.ReplaceExpr import Lean.Structure import Lean.Meta.ExprDefEq import Lean.Meta.AppBuilder import Lean.Meta.SynthInstance import Lean.Meta.CollectMVars import Lean.Meta.Coe import Lean.Meta.Tactic.Util import Lean.Hygiene import Lean.Util.RecDepth import Lean.Elab.Log import Lean.Elab.Level import Lean.Elab.Attributes import Lean.Elab.AutoBound import Lean.Elab.InfoTree import Lean.Elab.Open import Lean.Elab.SetOption namespace Lean.Elab.Term /- Set isDefEq configuration for the elaborator. Note that we enable all approximations but `quasiPatternApprox` In Lean3 and Lean 4, we used to use the quasi-pattern approximation during elaboration. The example: ``` def ex : StateT δ (StateT σ Id) σ := monadLift (get : StateT σ Id σ) ``` demonstrates why it produces counterintuitive behavior. We have the `Monad-lift` application: ``` @monadLift ?m ?n ?c ?α (get : StateT σ id σ) : ?n ?α ``` It produces the following unification problem when we process the expected type: ``` ?n ?α =?= StateT δ (StateT σ id) σ ==> (approximate using first-order unification) ?n := StateT δ (StateT σ id) ?α := σ ``` Then, we need to solve: ``` ?m ?α =?= StateT σ id σ ==> instantiate metavars ?m σ =?= StateT σ id σ ==> (approximate since it is a quasi-pattern unification constraint) ?m := fun σ => StateT σ id σ ``` Note that the constraint is not a Milner pattern because σ is in the local context of `?m`. We are ignoring the other possible solutions: ``` ?m := fun σ' => StateT σ id σ ?m := fun σ' => StateT σ' id σ ?m := fun σ' => StateT σ id σ' ``` We need the quasi-pattern approximation for elaborating recursor-like expressions (e.g., dependent `match with` expressions). If we had use first-order unification, then we would have produced the right answer: `?m := StateT σ id` Haskell would work on this example since it always uses first-order unification. -/ def setElabConfig (cfg : Meta.Config) : Meta.Config := { cfg with foApprox := true, ctxApprox := true, constApprox := false, quasiPatternApprox := false } structure Context where fileName : String fileMap : FileMap declName? : Option Name := none macroStack : MacroStack := [] currMacroScope : MacroScope := firstFrontendMacroScope /- When `mayPostpone == true`, an elaboration function may interrupt its execution by throwing `Exception.postpone`. The function `elabTerm` catches this exception and creates fresh synthetic metavariable `?m`, stores `?m` in the list of pending synthetic metavariables, and returns `?m`. -/ mayPostpone : Bool := true /- When `errToSorry` is set to true, the method `elabTerm` catches exceptions and converts them into synthetic `sorry`s. The implementation of choice nodes and overloaded symbols rely on the fact that when `errToSorry` is set to false for an elaboration function `F`, then `errToSorry` remains `false` for all elaboration functions invoked by `F`. That is, it is safe to transition `errToSorry` from `true` to `false`, but we must not set `errToSorry` to `true` when it is currently set to `false`. -/ errToSorry : Bool := true /- When `autoBoundImplicit` is set to true, instead of producing an "unknown identifier" error for unbound variables, we generate an internal exception. This exception is caught at `elabBinders` and `elabTypeWithUnboldImplicit`. Both methods add implicit declarations for the unbound variable and try again. -/ autoBoundImplicit : Bool := false autoBoundImplicits : Std.PArray Expr := {} /-- Map from user name to internal unique name -/ sectionVars : NameMap Name := {} /-- Map from internal name to fvar -/ sectionFVars : NameMap Expr := {} /-- Enable/disable implicit lambdas feature. -/ implicitLambda : Bool := true /-- Saved context for postponed terms and tactics to be executed. -/ structure SavedContext where declName? : Option Name options : Options openDecls : List OpenDecl macroStack : MacroStack errToSorry : Bool /-- We use synthetic metavariables as placeholders for pending elaboration steps. -/ inductive SyntheticMVarKind where -- typeclass instance search | typeClass /- Similar to typeClass, but error messages are different. if `f?` is `some f`, we produce an application type mismatch error message. Otherwise, if `header?` is `some header`, we generate the error `(header ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)` Otherwise, we generate the error `("type mismatch" ++ e ++ "has type" ++ eType ++ "but it is expected to have type" ++ expectedType)` -/ | coe (header? : Option String) (eNew : Expr) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) -- tactic block execution | tactic (tacticCode : Syntax) (ctx : SavedContext) -- `elabTerm` call that threw `Exception.postpone` (input is stored at `SyntheticMVarDecl.ref`) | postponed (ctx : SavedContext) instance : ToString SyntheticMVarKind where toString | SyntheticMVarKind.typeClass => "typeclass" | SyntheticMVarKind.coe .. => "coe" | SyntheticMVarKind.tactic .. => "tactic" | SyntheticMVarKind.postponed .. => "postponed" structure SyntheticMVarDecl where mvarId : MVarId stx : Syntax kind : SyntheticMVarKind inductive MVarErrorKind where | implicitArg (ctx : Expr) | hole | custom (msgData : MessageData) instance : ToString MVarErrorKind where toString | MVarErrorKind.implicitArg ctx => "implicitArg" | MVarErrorKind.hole => "hole" | MVarErrorKind.custom msg => "custom" structure MVarErrorInfo where mvarId : MVarId ref : Syntax kind : MVarErrorKind structure LetRecToLift where ref : Syntax fvarId : FVarId attrs : Array Attribute shortDeclName : Name declName : Name lctx : LocalContext localInstances : LocalInstances type : Expr val : Expr mvarId : MVarId structure State where levelNames : List Name := [] syntheticMVars : List SyntheticMVarDecl := [] mvarErrorInfos : List MVarErrorInfo := [] messages : MessageLog := {} letRecsToLift : List LetRecToLift := [] infoState : InfoState := {} deriving Inhabited abbrev TermElabM := ReaderT Context $ StateRefT State MetaM abbrev TermElab := Syntax → Option Expr → TermElabM Expr -- Make the compiler generate specialized `pure`/`bind` so we do not have to optimize through the -- whole monad stack at every use site. May eventually be covered by `deriving`. instance : Monad TermElabM := let i := inferInstanceAs (Monad TermElabM); { pure := i.pure, bind := i.bind } open Meta instance : Inhabited (TermElabM α) where default := throw arbitrary structure SavedState where meta : Meta.SavedState «elab» : State deriving Inhabited protected def saveState : TermElabM SavedState := do pure { meta := (← Meta.saveState), «elab» := (← get) } def SavedState.restore (s : SavedState) (restoreInfo : Bool := false) : TermElabM Unit := do let traceState ← getTraceState -- We never backtrack trace message let infoState := (← get).infoState -- We also do not backtrack the info nodes when `restoreInfo == false` s.meta.restore set s.elab setTraceState traceState unless restoreInfo do modify fun s => { s with infoState := infoState } instance : MonadBacktrack SavedState TermElabM where saveState := Term.saveState restoreState b := b.restore abbrev TermElabResult (α : Type) := EStateM.Result Exception SavedState α instance [Inhabited α] : Inhabited (TermElabResult α) where default := EStateM.Result.ok arbitrary arbitrary def setMessageLog (messages : MessageLog) : TermElabM Unit := modify fun s => { s with messages := messages } def resetMessageLog : TermElabM Unit := setMessageLog {} def getMessageLog : TermElabM MessageLog := return (← get).messages /-- Execute `x`, save resulting expression and new state. We remove any `Info` created by `x`. The info nodes are committed when we execute `applyResult`. We use `observing` to implement overloaded notation and decls. We want to save `Info` nodes for the chosen alternative. -/ def observing (x : TermElabM α) : TermElabM (TermElabResult α) := do let s ← saveState try let e ← x let sNew ← saveState s.restore (restoreInfo := true) pure (EStateM.Result.ok e sNew) catch | ex@(Exception.error _ _) => let sNew ← saveState s.restore (restoreInfo := true) pure (EStateM.Result.error ex sNew) | ex@(Exception.internal id _) => if id == postponeExceptionId then s.restore (restoreInfo := true) throw ex /-- Apply the result/exception and state captured with `observing`. We use this method to implement overloaded notation and symbols. -/ def applyResult (result : TermElabResult α) : TermElabM α := match result with | EStateM.Result.ok a r => do r.restore (restoreInfo := true); pure a | EStateM.Result.error ex r => do r.restore (restoreInfo := true); throw ex /-- Execute `x`, but keep state modifications only if `x` did not postpone. This method is useful to implement elaboration functions that cannot decide whether they need to postpone or not without updating the state. -/ def commitIfDidNotPostpone (x : TermElabM α) : TermElabM α := do -- We just reuse the implementation of `observing` and `applyResult`. let r ← observing x applyResult r def getLevelNames : TermElabM (List Name) := return (← get).levelNames def getFVarLocalDecl! (fvar : Expr) : TermElabM LocalDecl := do match (← getLCtx).find? fvar.fvarId! with | some d => pure d | none => unreachable! instance : AddErrorMessageContext TermElabM where add ref msg := do let ctx ← read let ref := getBetterRef ref ctx.macroStack let msg ← addMessageContext msg let msg ← addMacroStack msg ctx.macroStack pure (ref, msg) instance : MonadLog TermElabM where getRef := getRef getFileMap := return (← read).fileMap getFileName := return (← read).fileName logMessage msg := do let ctx ← readThe Core.Context let msg := { msg with data := MessageData.withNamingContext { currNamespace := ctx.currNamespace, openDecls := ctx.openDecls } msg.data }; modify fun s => { s with messages := s.messages.add msg } protected def getCurrMacroScope : TermElabM MacroScope := do pure (← read).currMacroScope protected def getMainModule : TermElabM Name := do pure (← getEnv).mainModule protected def withFreshMacroScope (x : TermElabM α) : TermElabM α := do let fresh ← modifyGetThe Core.State (fun st => (st.nextMacroScope, { st with nextMacroScope := st.nextMacroScope + 1 })) withReader (fun ctx => { ctx with currMacroScope := fresh }) x instance : MonadQuotation TermElabM where getCurrMacroScope := Term.getCurrMacroScope getMainModule := Term.getMainModule withFreshMacroScope := Term.withFreshMacroScope instance : MonadInfoTree TermElabM where getInfoState := return (← get).infoState modifyInfoState f := modify fun s => { s with infoState := f s.infoState } /-- Execute `x` but discard changes performed at `Term.State` and `Meta.State`. Recall that the environment is at `Core.State`. Thus, any updates to it will be preserved. This method is useful for performing computations where all metavariable must be resolved or discarded. The info trees are not discarded, however, and wrapped in `InfoTree.Context` to store their metavariable context. -/ def withoutModifyingElabMetaStateWithInfo (x : TermElabM α) : TermElabM α := do let s ← get let sMeta ← getThe Meta.State try withSaveInfoContext x finally modify ({ s with infoState := ·.infoState }) set sMeta /-- Execute `x` bud discard changes performed to the state. However, the info trees and messages are not discarded. -/ private def withoutModifyingStateWithInfoAndMessagesImpl (x : TermElabM α) : TermElabM α := do let saved ← saveState try x finally let s ← get let saved := { saved with elab.infoState := s.infoState, elab.messages := s.messages } restoreState saved unsafe def mkTermElabAttributeUnsafe : IO (KeyedDeclsAttribute TermElab) := mkElabAttribute TermElab `Lean.Elab.Term.termElabAttribute `builtinTermElab `termElab `Lean.Parser.Term `Lean.Elab.Term.TermElab "term" @[implementedBy mkTermElabAttributeUnsafe] constant mkTermElabAttribute : IO (KeyedDeclsAttribute TermElab) builtin_initialize termElabAttribute : KeyedDeclsAttribute TermElab ← mkTermElabAttribute /-- Auxiliary datatatype for presenting a Lean lvalue modifier. We represent a unelaborated lvalue as a `Syntax` (or `Expr`) and `List LVal`. Example: `a.foo[i].1` is represented as the `Syntax` `a` and the list `[LVal.fieldName "foo", LVal.getOp i, LVal.fieldIdx 1]`. Recall that the notation `a[i]` is not just for accessing arrays in Lean. -/ inductive LVal where | fieldIdx (ref : Syntax) (i : Nat) /- Field `suffix?` is for producing better error messages because `x.y` may be a field access or a hierachical/composite name. `ref` is the syntax object representing the field. `targetStx` is the target object being accessed. -/ | fieldName (ref : Syntax) (name : String) (suffix? : Option Name) (targetStx : Syntax) | getOp (ref : Syntax) (idx : Syntax) def LVal.getRef : LVal → Syntax | LVal.fieldIdx ref _ => ref | LVal.fieldName ref .. => ref | LVal.getOp ref _ => ref def LVal.isFieldName : LVal → Bool | LVal.fieldName .. => true | _ => false instance : ToString LVal where toString | LVal.fieldIdx _ i => toString i | LVal.fieldName _ n .. => n | LVal.getOp _ idx => "[" ++ toString idx ++ "]" def getDeclName? : TermElabM (Option Name) := return (← read).declName? def getLetRecsToLift : TermElabM (List LetRecToLift) := return (← get).letRecsToLift def isExprMVarAssigned (mvarId : MVarId) : TermElabM Bool := return (← getMCtx).isExprAssigned mvarId def getMVarDecl (mvarId : MVarId) : TermElabM MetavarDecl := return (← getMCtx).getDecl mvarId def assignLevelMVar (mvarId : MVarId) (val : Level) : TermElabM Unit := modifyThe Meta.State fun s => { s with mctx := s.mctx.assignLevel mvarId val } def withDeclName (name : Name) (x : TermElabM α) : TermElabM α := withReader (fun ctx => { ctx with declName? := name }) x def setLevelNames (levelNames : List Name) : TermElabM Unit := modify fun s => { s with levelNames := levelNames } def withLevelNames (levelNames : List Name) (x : TermElabM α) : TermElabM α := do let levelNamesSaved ← getLevelNames setLevelNames levelNames try x finally setLevelNames levelNamesSaved def withoutErrToSorry (x : TermElabM α) : TermElabM α := withReader (fun ctx => { ctx with errToSorry := false }) x /-- For testing `TermElabM` methods. The #eval command will sign the error. -/ def throwErrorIfErrors : TermElabM Unit := do if (← get).messages.hasErrors then throwError "Error(s)" def traceAtCmdPos (cls : Name) (msg : Unit → MessageData) : TermElabM Unit := withRef Syntax.missing $ trace cls msg def ppGoal (mvarId : MVarId) : TermElabM Format := Meta.ppGoal mvarId open Level (LevelElabM) def liftLevelM (x : LevelElabM α) : TermElabM α := do let ctx ← read let mctx ← getMCtx let ngen ← getNGen let lvlCtx : Level.Context := { options := (← getOptions), ref := (← getRef), autoBoundImplicit := ctx.autoBoundImplicit } match (x lvlCtx).run { ngen := ngen, mctx := mctx, levelNames := (← getLevelNames) } with | EStateM.Result.ok a newS => setMCtx newS.mctx; setNGen newS.ngen; setLevelNames newS.levelNames; pure a | EStateM.Result.error ex _ => throw ex def elabLevel (stx : Syntax) : TermElabM Level := liftLevelM $ Level.elabLevel stx /- Elaborate `x` with `stx` on the macro stack -/ def withMacroExpansion (beforeStx afterStx : Syntax) (x : TermElabM α) : TermElabM α := withMacroExpansionInfo beforeStx afterStx do withReader (fun ctx => { ctx with macroStack := { before := beforeStx, after := afterStx } :: ctx.macroStack }) x /- Add the given metavariable to the list of pending synthetic metavariables. The method `synthesizeSyntheticMVars` is used to process the metavariables on this list. -/ def registerSyntheticMVar (stx : Syntax) (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do modify fun s => { s with syntheticMVars := { mvarId := mvarId, stx := stx, kind := kind } :: s.syntheticMVars } def registerSyntheticMVarWithCurrRef (mvarId : MVarId) (kind : SyntheticMVarKind) : TermElabM Unit := do registerSyntheticMVar (← getRef) mvarId kind def registerMVarErrorHoleInfo (mvarId : MVarId) (ref : Syntax) : TermElabM Unit := do modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.hole } :: s.mvarErrorInfos } def registerMVarErrorImplicitArgInfo (mvarId : MVarId) (ref : Syntax) (app : Expr) : TermElabM Unit := do modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.implicitArg app } :: s.mvarErrorInfos } def registerMVarErrorCustomInfo (mvarId : MVarId) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := do modify fun s => { s with mvarErrorInfos := { mvarId := mvarId, ref := ref, kind := MVarErrorKind.custom msgData } :: s.mvarErrorInfos } def registerCustomErrorIfMVar (e : Expr) (ref : Syntax) (msgData : MessageData) : TermElabM Unit := match e.getAppFn with | Expr.mvar mvarId _ => registerMVarErrorCustomInfo mvarId ref msgData | _ => pure () /- Auxiliary method for reporting errors of the form "... contains metavariables ...". This kind of error is thrown, for example, at `Match.lean` where elaboration cannot continue if there are metavariables in patterns. We only want to log it if we haven't logged any error so far. -/ def throwMVarError (m : MessageData) : TermElabM α := do if (← get).messages.hasErrors then throwAbortTerm else throwError m def MVarErrorInfo.logError (mvarErrorInfo : MVarErrorInfo) (extraMsg? : Option MessageData) : TermElabM Unit := do match mvarErrorInfo.kind with | MVarErrorKind.implicitArg app => do let app ← instantiateMVars app let msg : MessageData := m!"don't know how to synthesize implicit argument{indentExpr app.setAppPPExplicitForExposingMVars}" let msg := msg ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId logErrorAt mvarErrorInfo.ref (appendExtra msg) | MVarErrorKind.hole => do let msg : MessageData := "don't know how to synthesize placeholder" let msg := msg ++ Format.line ++ "context:" ++ Format.line ++ MessageData.ofGoal mvarErrorInfo.mvarId logErrorAt mvarErrorInfo.ref (MessageData.tagged `Elab.synthPlaceholder <| appendExtra msg) | MVarErrorKind.custom msg => logErrorAt mvarErrorInfo.ref (appendExtra msg) where appendExtra (msg : MessageData) : MessageData := match extraMsg? with | none => msg | some extraMsg => msg ++ extraMsg /-- Try to log errors for the unassigned metavariables `pendingMVarIds`. Return `true` if there were "unfilled holes", and we should "abort" declaration. TODO: try to fill "all" holes using synthetic "sorry's" Remark: We only log the "unfilled holes" as new errors if no error has been logged so far. -/ def logUnassignedUsingErrorInfos (pendingMVarIds : Array MVarId) (extraMsg? : Option MessageData := none) : TermElabM Bool := do let s ← get let hasOtherErrors := s.messages.hasErrors let mut hasNewErrors := false let mut alreadyVisited : MVarIdSet := {} for mvarErrorInfo in s.mvarErrorInfos do let mvarId := mvarErrorInfo.mvarId unless alreadyVisited.contains mvarId do alreadyVisited := alreadyVisited.insert mvarId let foundError ← withMVarContext mvarId do /- The metavariable `mvarErrorInfo.mvarId` may have been assigned or delayed assigned to another metavariable that is unassigned. -/ let mvarDeps ← getMVars (mkMVar mvarId) if mvarDeps.any pendingMVarIds.contains then do unless hasOtherErrors do mvarErrorInfo.logError extraMsg? pure true else pure false if foundError then hasNewErrors := true return hasNewErrors /-- Ensure metavariables registered using `registerMVarErrorInfos` (and used in the given declaration) have been assigned. -/ def ensureNoUnassignedMVars (decl : Declaration) : TermElabM Unit := do let pendingMVarIds ← getMVarsAtDecl decl if (← logUnassignedUsingErrorInfos pendingMVarIds) then throwAbortCommand /- Execute `x` without allowing it to postpone elaboration tasks. That is, `tryPostpone` is a noop. -/ def withoutPostponing (x : TermElabM α) : TermElabM α := withReader (fun ctx => { ctx with mayPostpone := false }) x /-- Creates syntax for `(` <ident> `:` <type> `)` -/ def mkExplicitBinder (ident : Syntax) (type : Syntax) : Syntax := mkNode ``Lean.Parser.Term.explicitBinder #[mkAtom "(", mkNullNode #[ident], mkNullNode #[mkAtom ":", type], mkNullNode, mkAtom ")"] /-- Convert unassigned universe level metavariables into parameters. The new parameter names are of the form `u_i` where `i >= nextParamIdx`. The method returns the updated expression and new `nextParamIdx`. Remark: we make sure the generated parameter names do not clash with the universe at `ctx.levelNames`. -/ def levelMVarToParam (e : Expr) (nextParamIdx : Nat := 1) : TermElabM (Expr × Nat) := do let mctx ← getMCtx let levelNames ← getLevelNames let r := mctx.levelMVarToParam (fun n => levelNames.elem n) e `u nextParamIdx setMCtx r.mctx pure (r.expr, r.nextParamIdx) /-- Variant of `levelMVarToParam` where `nextParamIdx` is stored in a state monad. -/ def levelMVarToParam' (e : Expr) : StateRefT Nat TermElabM Expr := do let nextParamIdx ← get let (e, nextParamIdx) ← levelMVarToParam e nextParamIdx set nextParamIdx pure e /-- Auxiliary method for creating fresh binder names. Do not confuse with the method for creating fresh free/meta variable ids. -/ def mkFreshBinderName [Monad m] [MonadQuotation m] : m Name := withFreshMacroScope $ MonadQuotation.addMacroScope `x /-- Auxiliary method for creating a `Syntax.ident` containing a fresh name. This method is intended for creating fresh binder names. It is just a thin layer on top of `mkFreshUserName`. -/ def mkFreshIdent [Monad m] [MonadQuotation m] (ref : Syntax) : m Syntax := return mkIdentFrom ref (← mkFreshBinderName) private def applyAttributesCore (declName : Name) (attrs : Array Attribute) (applicationTime? : Option AttributeApplicationTime) : TermElabM Unit := for attr in attrs do let env ← getEnv match getAttributeImpl env attr.name with | Except.error errMsg => throwError errMsg | Except.ok attrImpl => match applicationTime? with | none => attrImpl.add declName attr.stx attr.kind | some applicationTime => if applicationTime == attrImpl.applicationTime then attrImpl.add declName attr.stx attr.kind /-- Apply given attributes **at** a given application time -/ def applyAttributesAt (declName : Name) (attrs : Array Attribute) (applicationTime : AttributeApplicationTime) : TermElabM Unit := applyAttributesCore declName attrs applicationTime def applyAttributes (declName : Name) (attrs : Array Attribute) : TermElabM Unit := applyAttributesCore declName attrs none def mkTypeMismatchError (header? : Option String) (e : Expr) (eType : Expr) (expectedType : Expr) : TermElabM MessageData := do let header : MessageData := match header? with | some header => m!"{header} " | none => m!"type mismatch{indentExpr e}\n" return m!"{header}{← mkHasTypeButIsExpectedMsg eType expectedType}" def throwTypeMismatchError (header? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) (extraMsg? : Option MessageData := none) : TermElabM α := do /- We ignore `extraMsg?` for now. In all our tests, it contained no useful information. It was always of the form: ``` failed to synthesize instance CoeT <eType> <e> <expectedType> ``` We should revisit this decision in the future and decide whether it may contain useful information or not. -/ let extraMsg := Format.nil /- let extraMsg : MessageData := match extraMsg? with | none => Format.nil | some extraMsg => Format.line ++ extraMsg; -/ match f? with | none => throwError "{← mkTypeMismatchError header? e eType expectedType}{extraMsg}" | some f => Meta.throwAppTypeMismatch f e extraMsg def withoutMacroStackAtErr (x : TermElabM α) : TermElabM α := withTheReader Core.Context (fun (ctx : Core.Context) => { ctx with options := pp.macroStack.set ctx.options false }) x namespace ContainsPendingMVar abbrev M := MonadCacheT Expr Unit (OptionT TermElabM) /-- See `containsPostponedTerm` -/ partial def visit (e : Expr) : M Unit := do checkCache e fun _ => do match e with | Expr.forallE _ d b _ => visit d; visit b | Expr.lam _ d b _ => visit d; visit b | Expr.letE _ t v b _ => visit t; visit v; visit b | Expr.app f a _ => visit f; visit a | Expr.mdata _ b _ => visit b | Expr.proj _ _ b _ => visit b | Expr.fvar fvarId .. => match (← getLocalDecl fvarId) with | LocalDecl.cdecl .. => return () | LocalDecl.ldecl (value := v) .. => visit v | Expr.mvar mvarId .. => let e' ← instantiateMVars e if e' != e then visit e' else match (← getDelayedAssignment? mvarId) with | some d => visit d.val | none => failure | _ => return () end ContainsPendingMVar /-- Return `true` if `e` contains a pending metavariable. Remark: it also visits let-declarations. -/ def containsPendingMVar (e : Expr) : TermElabM Bool := do match (← ContainsPendingMVar.visit e |>.run.run) with | some _ => return false | none => return true /- Try to synthesize metavariable using type class resolution. This method assumes the local context and local instances of `instMVar` coincide with the current local context and local instances. Return `true` if the instance was synthesized successfully, and `false` if the instance contains unassigned metavariables that are blocking the type class resolution procedure. Throw an exception if resolution or assignment irrevocably fails. -/ def synthesizeInstMVarCore (instMVar : MVarId) (maxResultSize? : Option Nat := none) : TermElabM Bool := do let instMVarDecl ← getMVarDecl instMVar let type := instMVarDecl.type let type ← instantiateMVars type let result ← trySynthInstance type maxResultSize? match result with | LOption.some val => if (← isExprMVarAssigned instMVar) then let oldVal ← instantiateMVars (mkMVar instMVar) unless (← isDefEq oldVal val) do if (← containsPendingMVar oldVal <||> containsPendingMVar val) then /- If `val` or `oldVal` contains metavariables directly or indirectly (e.g., in a let-declaration), we return `false` to indicate we should try again later. This is very course grain since the metavariable may not be responsible for the failure. We should refine the test in the future if needed. This check has been added to address dependencies between postponed metavariables. The following example demonstrates the issue fixed by this test. ``` structure Point where x : Nat y : Nat def Point.compute (p : Point) : Point := let p := { p with x := 1 } let p := { p with y := 0 } if (p.x - p.y) > p.x then p else p ``` The `isDefEq` test above fails for `Decidable (p.x - p.y ≤ p.x)` when the structure instance assigned to `p` has not been elaborated yet. -/ return false -- we will try again later let oldValType ← inferType oldVal let valType ← inferType val unless (← isDefEq oldValType valType) do throwError "synthesized type class instance type is not definitionally equal to expected type, synthesized{indentExpr val}\nhas type{indentExpr valType}\nexpected{indentExpr oldValType}" throwError "synthesized type class instance is not definitionally equal to expression inferred by typing rules, synthesized{indentExpr val}\ninferred{indentExpr oldVal}" else unless (← isDefEq (mkMVar instMVar) val) do throwError "failed to assign synthesized type class instance{indentExpr val}" pure true | LOption.undef => pure false -- we will try later | LOption.none => throwError "failed to synthesize instance{indentExpr type}" register_builtin_option autoLift : Bool := { defValue := true descr := "insert monadic lifts (i.e., `liftM` and `liftCoeM`) when needed" } register_builtin_option maxCoeSize : Nat := { defValue := 16 descr := "maximum number of instances used to construct an automatic coercion" } def synthesizeCoeInstMVarCore (instMVar : MVarId) : TermElabM Bool := do synthesizeInstMVarCore instMVar (some (maxCoeSize.get (← getOptions))) /- The coercion from `α` to `Thunk α` cannot be implemented using an instance because it would eagerly evaluate `e` -/ def tryCoeThunk? (expectedType : Expr) (eType : Expr) (e : Expr) : TermElabM (Option Expr) := do match expectedType with | Expr.app (Expr.const ``Thunk u _) arg _ => if (← isDefEq eType arg) then pure (some (mkApp2 (mkConst ``Thunk.mk u) arg (mkSimpleThunk e))) else pure none | _ => pure none def mkCoe (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) (errorMsgHeader? : Option String := none) : TermElabM Expr := do let u ← getLevel eType let v ← getLevel expectedType let coeTInstType := mkAppN (mkConst ``CoeT [u, v]) #[eType, e, expectedType] let mvar ← mkFreshExprMVar coeTInstType MetavarKind.synthetic let eNew := mkAppN (mkConst ``coe [u, v]) #[eType, expectedType, e, mvar] let mvarId := mvar.mvarId! try withoutMacroStackAtErr do if (← synthesizeCoeInstMVarCore mvarId) then expandCoe eNew else -- We create an auxiliary metavariable to represent the result, because we need to execute `expandCoe` -- after we syntheze `mvar` let mvarAux ← mkFreshExprMVar expectedType MetavarKind.syntheticOpaque registerSyntheticMVarWithCurrRef mvarAux.mvarId! (SyntheticMVarKind.coe errorMsgHeader? eNew expectedType eType e f?) return mvarAux catch | Exception.error _ msg => throwTypeMismatchError errorMsgHeader? expectedType eType e f? msg | _ => throwTypeMismatchError errorMsgHeader? expectedType eType e f? /-- Try to apply coercion to make sure `e` has type `expectedType`. Relevant definitions: ``` class CoeT (α : Sort u) (a : α) (β : Sort v) abbrev coe {α : Sort u} {β : Sort v} (a : α) [CoeT α a β] : β ``` -/ private def tryCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do if (← isDefEq expectedType eType) then return e else match (← tryCoeThunk? expectedType eType e) with | some r => return r | none => mkCoe expectedType eType e f? errorMsgHeader? def isTypeApp? (type : Expr) : TermElabM (Option (Expr × Expr)) := do let type ← withReducible $ whnf type match type with | Expr.app m α _ => pure (some ((← instantiateMVars m), (← instantiateMVars α))) | _ => pure none def synthesizeInst (type : Expr) : TermElabM Expr := do let type ← instantiateMVars type match (← trySynthInstance type) with | LOption.some val => pure val | LOption.undef => throwError "failed to synthesize instance{indentExpr type}" | LOption.none => throwError "failed to synthesize instance{indentExpr type}" def isMonadApp (type : Expr) : TermElabM Bool := do let some (m, _) ← isTypeApp? type | pure false return (← isMonad? m) |>.isSome /-- Try to coerce `a : α` into `m β` by first coercing `a : α` into ‵β`, and then using `pure`. The method is only applied if `α` is not monadic (e.g., `Nat → IO Unit`), and the head symbol of the resulting type is not a metavariable (e.g., `?m Unit` or `Bool → ?m Nat`). The main limitation of the approach above is polymorphic code. As usual, coercions and polymorphism do not interact well. In the example above, the lift is successfully applied to `true`, `false` and `!y` since none of them is polymorphic ``` def f (x : Bool) : IO Bool := do let y ← if x == 0 then IO.println "hello"; true else false; !y ``` On the other hand, the following fails since `+` is polymorphic ``` def f (x : Bool) : IO Nat := do IO.prinln x x + x -- Error: failed to synthesize `Add (IO Nat)` ``` -/ private def tryPureCoe? (errorMsgHeader? : Option String) (m β α a : Expr) : TermElabM (Option Expr) := commitWhenSome? do let doIt : TermElabM (Option Expr) := do try let aNew ← tryCoe errorMsgHeader? β α a none let aNew ← mkPure m aNew pure (some aNew) catch _ => pure none forallTelescope α fun _ α => do if (← isMonadApp α) then pure none else if !α.getAppFn.isMVar then doIt else pure none /- Try coercions and monad lifts to make sure `e` has type `expectedType`. If `expectedType` is of the form `n β`, we try monad lifts and other extensions. Otherwise, we just use the basic `tryCoe`. Extensions for monads. Given an expected type of the form `n β`, if `eType` is of the form `α`, but not `m α` 1 - Try to coerce ‵α` into ‵β`, and use `pure` to lift it to `n α`. It only works if `n` implements `Pure` If `eType` is of the form `m α`. We use the following approaches. 1- Try to unify `n` and `m`. If it succeeds, then we use ``` coeM {m : Type u → Type v} {α β : Type u} [∀ a, CoeT α a β] [Monad m] (x : m α) : m β ``` `n` must be a `Monad` to use this one. 2- If there is monad lift from `m` to `n` and we can unify `α` and `β`, we use ``` liftM : ∀ {m : Type u_1 → Type u_2} {n : Type u_1 → Type u_3} [self : MonadLiftT m n] {α : Type u_1}, m α → n α ``` Note that `n` may not be a `Monad` in this case. This happens quite a bit in code such as ``` def g (x : Nat) : IO Nat := do IO.println x pure x def f {m} [MonadLiftT IO m] : m Nat := g 10 ``` 3- If there is a monad lif from `m` to `n` and a coercion from `α` to `β`, we use ``` liftCoeM {m : Type u → Type v} {n : Type u → Type w} {α β : Type u} [MonadLiftT m n] [∀ a, CoeT α a β] [Monad n] (x : m α) : n β ``` Note that approach 3 does not subsume 1 because it is only applicable if there is a coercion from `α` to `β` for all values in `α`. This is not the case for example for `pure $ x > 0` when the expected type is `IO Bool`. The given type is `IO Prop`, and we only have a coercion from decidable propositions. Approach 1 works because it constructs the coercion `CoeT (m Prop) (pure $ x > 0) (m Bool)` using the instance `pureCoeDepProp`. Note that, approach 2 is more powerful than `tryCoe`. Recall that type class resolution never assigns metavariables created by other modules. Now, consider the following scenario ```lean def g (x : Nat) : IO Nat := ... deg h (x : Nat) : StateT Nat IO Nat := do v ← g x; IO.Println v; ... ``` Let's assume there is no other occurrence of `v` in `h`. Thus, we have that the expected of `g x` is `StateT Nat IO ?α`, and the given type is `IO Nat`. So, even if we add a coercion. ``` instance {α m n} [MonadLiftT m n] {α} : Coe (m α) (n α) := ... ``` It is not applicable because TC would have to assign `?α := Nat`. On the other hand, TC can easily solve `[MonadLiftT IO (StateT Nat IO)]` since this goal does not contain any metavariables. And then, we convert `g x` into `liftM $ g x`. -/ private def tryLiftAndCoe (errorMsgHeader? : Option String) (expectedType : Expr) (eType : Expr) (e : Expr) (f? : Option Expr) : TermElabM Expr := do let expectedType ← instantiateMVars expectedType let eType ← instantiateMVars eType let throwMismatch {α} : TermElabM α := throwTypeMismatchError errorMsgHeader? expectedType eType e f? let tryCoeSimple : TermElabM Expr := tryCoe errorMsgHeader? expectedType eType e f? let some (n, β) ← isTypeApp? expectedType | tryCoeSimple let tryPureCoeAndSimple : TermElabM Expr := do if autoLift.get (← getOptions) then match (← tryPureCoe? errorMsgHeader? n β eType e) with | some eNew => pure eNew | none => tryCoeSimple else tryCoeSimple let some (m, α) ← isTypeApp? eType | tryPureCoeAndSimple if (← isDefEq m n) then let some monadInst ← isMonad? n | tryCoeSimple try expandCoe (← mkAppOptM ``coeM #[m, α, β, none, monadInst, e]) catch _ => throwMismatch else if autoLift.get (← getOptions) then try -- Construct lift from `m` to `n` let monadLiftType ← mkAppM ``MonadLiftT #[m, n] let monadLiftVal ← synthesizeInst monadLiftType let u_1 ← getDecLevel α let u_2 ← getDecLevel eType let u_3 ← getDecLevel expectedType let eNew := mkAppN (Lean.mkConst ``liftM [u_1, u_2, u_3]) #[m, n, monadLiftVal, α, e] let eNewType ← inferType eNew if (← isDefEq expectedType eNewType) then return eNew -- approach 2 worked else let some monadInst ← isMonad? n | tryCoeSimple let u ← getLevel α let v ← getLevel β let coeTInstType := Lean.mkForall `a BinderInfo.default α $ mkAppN (mkConst ``CoeT [u, v]) #[α, mkBVar 0, β] let coeTInstVal ← synthesizeInst coeTInstType let eNew ← expandCoe (← mkAppN (Lean.mkConst ``liftCoeM [u_1, u_2, u_3]) #[m, n, α, β, monadLiftVal, coeTInstVal, monadInst, e]) let eNewType ← inferType eNew unless (← isDefEq expectedType eNewType) do throwMismatch return eNew -- approach 3 worked catch _ => /- If `m` is not a monad, then we try to use `tryPureCoe?` and then `tryCoe?`. Otherwise, we just try `tryCoe?`. -/ match (← isMonad? m) with | none => tryPureCoeAndSimple | some _ => tryCoeSimple else tryCoeSimple /-- If `expectedType?` is `some t`, then ensure `t` and `eType` are definitionally equal. If they are not, then try coercions. Argument `f?` is used only for generating error messages. -/ def ensureHasTypeAux (expectedType? : Option Expr) (eType : Expr) (e : Expr) (f? : Option Expr := none) (errorMsgHeader? : Option String := none) : TermElabM Expr := do match expectedType? with | none => pure e | some expectedType => if (← isDefEq eType expectedType) then pure e else tryLiftAndCoe errorMsgHeader? expectedType eType e f? /-- If `expectedType?` is `some t`, then ensure `t` and type of `e` are definitionally equal. If they are not, then try coercions. -/ def ensureHasType (expectedType? : Option Expr) (e : Expr) (errorMsgHeader? : Option String := none) : TermElabM Expr := match expectedType? with | none => pure e | _ => do let eType ← inferType e ensureHasTypeAux expectedType? eType e none errorMsgHeader? private def mkSyntheticSorryFor (expectedType? : Option Expr) : TermElabM Expr := do let expectedType ← match expectedType? with | none => mkFreshTypeMVar | some expectedType => pure expectedType mkSyntheticSorry expectedType private def exceptionToSorry (ex : Exception) (expectedType? : Option Expr) : TermElabM Expr := do let syntheticSorry ← mkSyntheticSorryFor expectedType? logException ex pure syntheticSorry /-- If `mayPostpone == true`, throw `Expection.postpone`. -/ def tryPostpone : TermElabM Unit := do if (← read).mayPostpone then throwPostpone /-- If `mayPostpone == true` and `e`'s head is a metavariable, throw `Exception.postpone`. -/ def tryPostponeIfMVar (e : Expr) : TermElabM Unit := do if e.getAppFn.isMVar then let e ← instantiateMVars e if e.getAppFn.isMVar then tryPostpone def tryPostponeIfNoneOrMVar (e? : Option Expr) : TermElabM Unit := match e? with | some e => tryPostponeIfMVar e | none => tryPostpone def tryPostponeIfHasMVars (expectedType? : Option Expr) (msg : String) : TermElabM Expr := do tryPostponeIfNoneOrMVar expectedType? let some expectedType ← pure expectedType? | throwError "{msg}, expected type must be known" let expectedType ← instantiateMVars expectedType if expectedType.hasExprMVar then tryPostpone throwError "{msg}, expected type contains metavariables{indentExpr expectedType}" pure expectedType def saveContext : TermElabM SavedContext := return { macroStack := (← read).macroStack declName? := (← read).declName? options := (← getOptions) openDecls := (← getOpenDecls) errToSorry := (← read).errToSorry } def withSavedContext (savedCtx : SavedContext) (x : TermElabM α) : TermElabM α := do withReader (fun ctx => { ctx with declName? := savedCtx.declName?, macroStack := savedCtx.macroStack, errToSorry := savedCtx.errToSorry }) <| withTheReader Core.Context (fun ctx => { ctx with options := savedCtx.options, openDecls := savedCtx.openDecls }) x private def postponeElabTerm (stx : Syntax) (expectedType? : Option Expr) : TermElabM Expr := do trace[Elab.postpone] "{stx} : {expectedType?}" let mvar ← mkFreshExprMVar expectedType? MetavarKind.syntheticOpaque let ctx ← read registerSyntheticMVar stx mvar.mvarId! (SyntheticMVarKind.postponed (← saveContext)) pure mvar def getSyntheticMVarDecl? (mvarId : MVarId) : TermElabM (Option SyntheticMVarDecl) := return (← get).syntheticMVars.find? fun d => d.mvarId == mvarId def mkTermInfo (elaborator : Name) (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (isBinder := false) : TermElabM (Sum Info MVarId) := do let isHole? : TermElabM (Option MVarId) := do match e with | Expr.mvar mvarId _ => match (← getSyntheticMVarDecl? mvarId) with | some { kind := SyntheticMVarKind.tactic .., .. } => return mvarId | some { kind := SyntheticMVarKind.postponed .., .. } => return mvarId | _ => return none | _ => pure none match (← isHole?) with | none => return Sum.inl <| Info.ofTermInfo { elaborator, lctx := lctx?.getD (← getLCtx), expr := e, stx, expectedType?, isBinder } | some mvarId => return Sum.inr mvarId def addTermInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr := none) (lctx? : Option LocalContext := none) (elaborator := Name.anonymous) (isBinder := false) : TermElabM Unit := do withInfoContext' (pure ()) (fun _ => mkTermInfo elaborator stx e expectedType? lctx? isBinder) |> discard /- Helper function for `elabTerm` is tries the registered elaboration functions for `stxNode` kind until it finds one that supports the syntax or an error is found. -/ private def elabUsingElabFnsAux (s : SavedState) (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : List (KeyedDeclsAttribute.AttributeEntry TermElab) → TermElabM Expr | [] => do throwError "unexpected syntax{indentD stx}" | (elabFn::elabFns) => try -- record elaborator in info tree, but only when not backtracking to other elaborators (outer `try`) withInfoContext' (mkInfo := mkTermInfo elabFn.declName (expectedType? := expectedType?) stx) (try elabFn.value stx expectedType? catch ex => match ex with | Exception.error ref msg => if (← read).errToSorry then exceptionToSorry ex expectedType? else throw ex | Exception.internal id _ => if (← read).errToSorry && id == abortTermExceptionId then exceptionToSorry ex expectedType? else if id == unsupportedSyntaxExceptionId then throw ex -- to outer try else if catchExPostpone && id == postponeExceptionId then /- If `elab` threw `Exception.postpone`, we reset any state modifications. For example, we want to make sure pending synthetic metavariables created by `elab` before it threw `Exception.postpone` are discarded. Note that we are also discarding the messages created by `elab`. For example, consider the expression. `((f.x a1).x a2).x a3` Now, suppose the elaboration of `f.x a1` produces an `Exception.postpone`. Then, a new metavariable `?m` is created. Then, `?m.x a2` also throws `Exception.postpone` because the type of `?m` is not yet known. Then another, metavariable `?n` is created, and finally `?n.x a3` also throws `Exception.postpone`. If we did not restore the state, we would keep "dead" metavariables `?m` and `?n` on the pending synthetic metavariable list. This is wasteful because when we resume the elaboration of `((f.x a1).x a2).x a3`, we start it from scratch and new metavariables are created for the nested functions. -/ s.restore postponeElabTerm stx expectedType? else throw ex) catch ex => match ex with | Exception.internal id _ => if id == unsupportedSyntaxExceptionId then s.restore -- also removes the info tree created above elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns else throw ex | _ => throw ex private def elabUsingElabFns (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone : Bool) : TermElabM Expr := do let s ← saveState let k := stx.getKind match termElabAttribute.getEntries (← getEnv) k with | [] => throwError "elaboration function for '{k}' has not been implemented{indentD stx}" | elabFns => elabUsingElabFnsAux s stx expectedType? catchExPostpone elabFns instance : MonadMacroAdapter TermElabM where getCurrMacroScope := getCurrMacroScope getNextMacroScope := return (← getThe Core.State).nextMacroScope setNextMacroScope next := modifyThe Core.State fun s => { s with nextMacroScope := next } private def isExplicit (stx : Syntax) : Bool := match stx with | `(@$f) => true | _ => false private def isExplicitApp (stx : Syntax) : Bool := stx.getKind == ``Lean.Parser.Term.app && isExplicit stx[0] /-- Return true if `stx` if a lambda abstraction containing a `{}` or `[]` binder annotation. Example: `fun {α} (a : α) => a` -/ private def isLambdaWithImplicit (stx : Syntax) : Bool := match stx with | `(fun $binders* => $body) => binders.any fun b => b.isOfKind ``Lean.Parser.Term.implicitBinder || b.isOfKind `Lean.Parser.Term.instBinder | _ => false private partial def dropTermParens : Syntax → Syntax := fun stx => match stx with | `(($stx)) => dropTermParens stx | _ => stx private def isHole (stx : Syntax) : Bool := match stx with | `(_) => true | `(? _) => true | `(? $x:ident) => true | _ => false private def isTacticBlock (stx : Syntax) : Bool := match stx with | `(by $x:tacticSeq) => true | _ => false private def isNoImplicitLambda (stx : Syntax) : Bool := match stx with | `(noImplicitLambda% $x:term) => true | _ => false private def isTypeAscription (stx : Syntax) : Bool := match stx with | `(($e : $type)) => true | _ => false def mkNoImplicitLambdaAnnotation (type : Expr) : Expr := mkAnnotation `noImplicitLambda type def hasNoImplicitLambdaAnnotation (type : Expr) : Bool := annotation? `noImplicitLambda type |>.isSome /-- Block usage of implicit lambdas if `stx` is `@f` or `@f arg1 ...` or `fun` with an implicit binder annotation. -/ def blockImplicitLambda (stx : Syntax) : Bool := let stx := dropTermParens stx -- TODO: make it extensible isExplicit stx || isExplicitApp stx || isLambdaWithImplicit stx || isHole stx || isTacticBlock stx || isNoImplicitLambda stx || isTypeAscription stx /-- Return normalized expected type if it is of the form `{a : α} → β` or `[a : α] → β` and `blockImplicitLambda stx` is not true, else return `none`. Remark: implicit lambdas are not triggered by the strict implicit binder annotation `{{a : α}} → β` -/ private def useImplicitLambda? (stx : Syntax) (expectedType? : Option Expr) : TermElabM (Option Expr) := if blockImplicitLambda stx then return none else match expectedType? with | some expectedType => do if hasNoImplicitLambdaAnnotation expectedType then return none else let expectedType ← whnfForall expectedType match expectedType with | Expr.forallE _ _ _ c => if c.binderInfo.isImplicit || c.binderInfo.isInstImplicit then return some expectedType else return none | _ => return none | _ => return none private def decorateErrorMessageWithLambdaImplicitVars (ex : Exception) (impFVars : Array Expr) : TermElabM Exception := do match ex with | Exception.error ref msg => if impFVars.isEmpty then return Exception.error ref msg else let mut msg := m!"{msg}\nthe following variables have been introduced by the implicit lamda feature" for impFVar in impFVars do let auxMsg := m!"{impFVar} : {← inferType impFVar}" let auxMsg ← addMessageContext auxMsg msg := m!"{msg}{indentD auxMsg}" msg := m!"{msg}\nyou can disable implict lambdas using `@` or writing a lambda expression with `\{}` or `[]` binder annotations." return Exception.error ref msg | _ => return ex private def elabImplicitLambdaAux (stx : Syntax) (catchExPostpone : Bool) (expectedType : Expr) (impFVars : Array Expr) : TermElabM Expr := do let body ← elabUsingElabFns stx expectedType catchExPostpone try let body ← ensureHasType expectedType body let r ← mkLambdaFVars impFVars body trace[Elab.implicitForall] r pure r catch ex => throw (← decorateErrorMessageWithLambdaImplicitVars ex impFVars) private partial def elabImplicitLambda (stx : Syntax) (catchExPostpone : Bool) (type : Expr) : TermElabM Expr := loop type #[] where loop | type@(Expr.forallE n d b c), fvars => if c.binderInfo.isExplicit then elabImplicitLambdaAux stx catchExPostpone type fvars else withFreshMacroScope do let n ← MonadQuotation.addMacroScope n withLocalDecl n c.binderInfo d fun fvar => do let type ← whnfForall (b.instantiate1 fvar) loop type (fvars.push fvar) | type, fvars => elabImplicitLambdaAux stx catchExPostpone type fvars /- Main loop for `elabTerm` -/ private partial def elabTermAux (expectedType? : Option Expr) (catchExPostpone : Bool) (implicitLambda : Bool) : Syntax → TermElabM Expr | Syntax.missing => mkSyntheticSorryFor expectedType? | stx => withFreshMacroScope <| withIncRecDepth do trace[Elab.step] "expected type: {expectedType?}, term\n{stx}" checkMaxHeartbeats "elaborator" withNestedTraces do let env ← getEnv match (← liftMacroM (expandMacroImpl? env stx)) with | some (decl, stxNew) => withInfoContext' (mkInfo := mkTermInfo decl (expectedType? := expectedType?) stx) <| withMacroExpansion stx stxNew <| withRef stxNew <| elabTermAux expectedType? catchExPostpone implicitLambda stxNew | _ => let implicit? ← if implicitLambda && (← read).implicitLambda then useImplicitLambda? stx expectedType? else pure none match implicit? with | some expectedType => elabImplicitLambda stx catchExPostpone expectedType | none => elabUsingElabFns stx expectedType? catchExPostpone /-- Store in the `InfoTree` that `e` is a "dot"-completion target. -/ def addDotCompletionInfo (stx : Syntax) (e : Expr) (expectedType? : Option Expr) (field? : Option Syntax := none) : TermElabM Unit := do addCompletionInfo <| CompletionInfo.dot { expr := e, stx, lctx := (← getLCtx), elaborator := Name.anonymous, expectedType? } (field? := field?) (expectedType? := expectedType?) /-- Main function for elaborating terms. It extracts the elaboration methods from the environment using the node kind. Recall that the environment has a mapping from `SyntaxNodeKind` to `TermElab` methods. It creates a fresh macro scope for executing the elaboration method. All unlogged trace messages produced by the elaboration method are logged using the position information at `stx`. If the elaboration method throws an `Exception.error` and `errToSorry == true`, the error is logged and a synthetic sorry expression is returned. If the elaboration throws `Exception.postpone` and `catchExPostpone == true`, a new synthetic metavariable of kind `SyntheticMVarKind.postponed` is created, registered, and returned. The option `catchExPostpone == false` is used to implement `resumeElabTerm` to prevent the creation of another synthetic metavariable when resuming the elaboration. If `implicitLambda == true`, then disable implicit lambdas feature for the given syntax, but not for its subterms. We use this flag to implement, for example, the `@` modifier. If `Context.implicitLambda == false`, then this parameter has no effect. -/ def elabTerm (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) : TermElabM Expr := withRef stx <| elabTermAux expectedType? catchExPostpone implicitLambda stx def elabTermEnsuringType (stx : Syntax) (expectedType? : Option Expr) (catchExPostpone := true) (implicitLambda := true) (errorMsgHeader? : Option String := none) : TermElabM Expr := do let e ← elabTerm stx expectedType? catchExPostpone implicitLambda withRef stx <| ensureHasType expectedType? e errorMsgHeader? /-- Execute `x` and then restore `syntheticMVars`, `levelNames`, `mvarErrorInfos`, and `letRecsToLift`. We use this combinator when we don't want the pending problems created by `x` to persist after its execution. -/ def withoutPending (x : TermElabM α) : TermElabM α := do let saved ← get try x finally modify fun s => { s with syntheticMVars := saved.syntheticMVars, levelNames := saved.levelNames, letRecsToLift := saved.letRecsToLift, mvarErrorInfos := saved.mvarErrorInfos } /-- Execute `x` and return `some` if no new errors were recorded or exceptions was thrown. Otherwise, return `none` -/ def commitIfNoErrors? (x : TermElabM α) : TermElabM (Option α) := do let saved ← saveState modify fun s => { s with messages := {} } try let a ← x if (← get).messages.hasErrors then restoreState saved return none else modify fun s => { s with messages := saved.elab.messages ++ s.messages } return a catch _ => restoreState saved return none /-- Adapt a syntax transformation to a regular, term-producing elaborator. -/ def adaptExpander (exp : Syntax → TermElabM Syntax) : TermElab := fun stx expectedType? => do let stx' ← exp stx withMacroExpansion stx stx' $ elabTerm stx' expectedType? def mkInstMVar (type : Expr) : TermElabM Expr := do let mvar ← mkFreshExprMVar type MetavarKind.synthetic let mvarId := mvar.mvarId! unless (← synthesizeInstMVarCore mvarId) do registerSyntheticMVarWithCurrRef mvarId SyntheticMVarKind.typeClass pure mvar /- Relevant definitions: ``` class CoeSort (α : Sort u) (β : outParam (Sort v)) abbrev coeSort {α : Sort u} {β : Sort v} (a : α) [CoeSort α β] : β ``` -/ private def tryCoeSort (α : Expr) (a : Expr) : TermElabM Expr := do let β ← mkFreshTypeMVar let u ← getLevel α let v ← getLevel β let coeSortInstType := mkAppN (Lean.mkConst ``CoeSort [u, v]) #[α, β] let mvar ← mkFreshExprMVar coeSortInstType MetavarKind.synthetic let mvarId := mvar.mvarId! try withoutMacroStackAtErr do if (← synthesizeCoeInstMVarCore mvarId) then let result ← expandCoe <| mkAppN (Lean.mkConst ``coeSort [u, v]) #[α, β, a, mvar] unless (← isType result) do throwError "failed to coerse{indentExpr a}\nto a type, after applying `coeSort`, result is still not a type{indentExpr result}\nthis is often due to incorrect `CoeSort` instances, the synthesized value for{indentExpr coeSortInstType}\nwas{indentExpr mvar}" return result else throwError "type expected" catch | Exception.error _ msg => throwError "type expected\n{msg}" | _ => throwError "type expected" /-- Make sure `e` is a type by inferring its type and making sure it is a `Expr.sort` or is unifiable with `Expr.sort`, or can be coerced into one. -/ def ensureType (e : Expr) : TermElabM Expr := do if (← isType e) then pure e else let eType ← inferType e let u ← mkFreshLevelMVar if (← isDefEq eType (mkSort u)) then pure e else tryCoeSort eType e /-- Elaborate `stx` and ensure result is a type. -/ def elabType (stx : Syntax) : TermElabM Expr := do let u ← mkFreshLevelMVar let type ← elabTerm stx (mkSort u) withRef stx $ ensureType type /-- Enable auto-bound implicits, and execute `k` while catching auto bound implicit exceptions. When an exception is caught, a new local declaration is created, registered, and `k` is tried to be executed again. -/ partial def withAutoBoundImplicit (k : TermElabM α) : TermElabM α := do let flag := autoBoundImplicitLocal.get (← getOptions) if flag then withReader (fun ctx => { ctx with autoBoundImplicit := flag, autoBoundImplicits := {} }) do let rec loop (s : SavedState) : TermElabM α := do try k catch | ex => match isAutoBoundImplicitLocalException? ex with | some n => -- Restore state, declare `n`, and try again s.restore withLocalDecl n BinderInfo.implicit (← mkFreshTypeMVar) fun x => withReader (fun ctx => { ctx with autoBoundImplicits := ctx.autoBoundImplicits.push x } ) do loop (← saveState) | none => throw ex loop (← saveState) else k def withoutAutoBoundImplicit (k : TermElabM α) : TermElabM α := do withReader (fun ctx => { ctx with autoBoundImplicit := false, autoBoundImplicits := {} }) k /-- Return `autoBoundImplicits ++ xs. This methoid throws an error if a variable in `autoBoundImplicits` depends on some `x` in `xs` -/ def addAutoBoundImplicits (xs : Array Expr) : TermElabM (Array Expr) := do let autoBoundImplicits := (← read).autoBoundImplicits for auto in autoBoundImplicits do let localDecl ← getLocalDecl auto.fvarId! for x in xs do if (← getMCtx).localDeclDependsOn localDecl x.fvarId! then throwError "invalid auto implicit argument '{auto}', it depends on explicitly provided argument '{x}'" return autoBoundImplicits.toArray ++ xs def mkAuxName (suffix : Name) : TermElabM Name := do match (← read).declName? with | none => throwError "auxiliary declaration cannot be created when declaration name is not available" | some declName => Lean.mkAuxName (declName ++ suffix) 1 builtin_initialize registerTraceClass `Elab.letrec /- Return true if mvarId is an auxiliary metavariable created for compiling `let rec` or it is delayed assigned to one. -/ def isLetRecAuxMVar (mvarId : MVarId) : TermElabM Bool := do trace[Elab.letrec] "mvarId: {mkMVar mvarId} letrecMVars: {(← get).letRecsToLift.map (mkMVar $ ·.mvarId)}" let mvarId := (← getMCtx).getDelayedRoot mvarId trace[Elab.letrec] "mvarId root: {mkMVar mvarId}" return (← get).letRecsToLift.any (·.mvarId == mvarId) def resolveLocalName (n : Name) : TermElabM (Option (Expr × List String)) := do let lctx ← getLCtx let view := extractMacroScopes n let rec loop (n : Name) (projs : List String) := match lctx.findFromUserName? { view with name := n }.review with | some decl => if decl.isAuxDecl && !projs.isEmpty then /- We do not consider dot notation for local decls corresponding to recursive functions being defined. The following example would not be elaborated correctly without this case. ``` def foo.aux := 1 def foo : Nat → Nat | n => foo.aux -- should not be interpreted as `(foo).bar` ``` -/ none else some (decl.toExpr, projs) | none => match n with | Name.str pre s _ => loop pre (s::projs) | _ => none return loop view.name [] /- Return true iff `stx` is a `Syntax.ident`, and it is a local variable. -/ def isLocalIdent? (stx : Syntax) : TermElabM (Option Expr) := match stx with | Syntax.ident _ _ val _ => do let r? ← resolveLocalName val match r? with | some (fvar, []) => pure (some fvar) | _ => pure none | _ => pure none /-- Create an `Expr.const` using the given name and explicit levels. Remark: fresh universe metavariables are created if the constant has more universe parameters than `explicitLevels`. -/ def mkConst (constName : Name) (explicitLevels : List Level := []) : TermElabM Expr := do let cinfo ← getConstInfo constName if explicitLevels.length > cinfo.levelParams.length then throwError "too many explicit universe levels for '{constName}'" else let numMissingLevels := cinfo.levelParams.length - explicitLevels.length let us ← mkFreshLevelMVars numMissingLevels pure $ Lean.mkConst constName (explicitLevels ++ us) private def mkConsts (candidates : List (Name × List String)) (explicitLevels : List Level) : TermElabM (List (Expr × List String)) := do candidates.foldlM (init := []) fun result (constName, projs) => do -- TODO: better suppor for `mkConst` failure. We may want to cache the failures, and report them if all candidates fail. let const ← mkConst constName explicitLevels return (const, projs) :: result def resolveName (stx : Syntax) (n : Name) (preresolved : List (Name × List String)) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr × List String)) := do try if let some (e, projs) ← resolveLocalName n then unless explicitLevels.isEmpty do throwError "invalid use of explicit universe parameters, '{e}' is a local" return [(e, projs)] -- check for section variable capture by a quotation let ctx ← read if let some (e, projs) := preresolved.findSome? fun (n, projs) => ctx.sectionFVars.find? n |>.map (·, projs) then return [(e, projs)] -- section variables should shadow global decls if preresolved.isEmpty then process (← resolveGlobalName n) else process preresolved catch ex => if preresolved.isEmpty && explicitLevels.isEmpty then addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (← getLCtx) expectedType? throw ex where process (candidates : List (Name × List String)) : TermElabM (List (Expr × List String)) := do if candidates.isEmpty then if (← read).autoBoundImplicit && isValidAutoBoundImplicitName n then throwAutoBoundImplicitLocal n else throwError "unknown identifier '{Lean.mkConst n}'" if preresolved.isEmpty && explicitLevels.isEmpty then addCompletionInfo <| CompletionInfo.id stx stx.getId (danglingDot := false) (← getLCtx) expectedType? mkConsts candidates explicitLevels /-- Similar to `resolveName`, but creates identifiers for the main part and each projection with position information derived from `ident`. Example: Assume resolveName `v.head.bla.boo` produces `(v.head, ["bla", "boo"])`, then this method produces `(v.head, id, [f₁, f₂])` where `id` is an identifier for `v.head`, and `f₁` and `f₂` are identifiers for fields `"bla"` and `"boo"`. -/ def resolveName' (ident : Syntax) (explicitLevels : List Level) (expectedType? : Option Expr := none) : TermElabM (List (Expr × Syntax × List Syntax)) := do match ident with | Syntax.ident info rawStr n preresolved => let r ← resolveName ident n preresolved explicitLevels expectedType? r.mapM fun (c, fields) => do let ids := ident.identComponents (nFields? := fields.length) return (c, ids.head!, ids.tail!) | _ => throwError "identifier expected" def resolveId? (stx : Syntax) (kind := "term") (withInfo := false) : TermElabM (Option Expr) := match stx with | Syntax.ident _ _ val preresolved => do let rs ← try resolveName stx val preresolved [] catch _ => pure [] let rs := rs.filter fun ⟨f, projs⟩ => projs.isEmpty let fs := rs.map fun (f, _) => f match fs with | [] => pure none | [f] => if withInfo then addTermInfo stx f pure (some f) | _ => throwError "ambiguous {kind}, use fully qualified name, possible interpretations {fs}" | _ => throwError "identifier expected" private def mkSomeContext : Context := { fileName := "<TermElabM>" fileMap := arbitrary } def TermElabM.run (x : TermElabM α) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM (α × State) := withConfig setElabConfig (x ctx |>.run s) @[inline] def TermElabM.run' (x : TermElabM α) (ctx : Context := mkSomeContext) (s : State := {}) : MetaM α := (·.1) <$> x.run ctx s def TermElabM.toIO (x : TermElabM α) (ctxCore : Core.Context) (sCore : Core.State) (ctxMeta : Meta.Context) (sMeta : Meta.State) (ctx : Context) (s : State) : IO (α × Core.State × Meta.State × State) := do let ((a, s), sCore, sMeta) ← (x.run ctx s).toIO ctxCore sCore ctxMeta sMeta pure (a, sCore, sMeta, s) instance [MetaEval α] : MetaEval (TermElabM α) where eval env opts x _ := let x : TermElabM α := do try x finally let s ← get s.messages.forM fun msg => do IO.println (← msg.toString) MetaEval.eval env opts (hideUnit := true) $ x.run' mkSomeContext unsafe def evalExpr (α) (typeName : Name) (value : Expr) : TermElabM α := withoutModifyingEnv do let name ← mkFreshUserName `_tmp let type ← inferType value let type ← whnfD type unless type.isConstOf typeName do throwError "unexpected type at evalExpr{indentExpr type}" let decl := Declaration.defnDecl { name := name, levelParams := [], type := type, value := value, hints := ReducibilityHints.opaque, safety := DefinitionSafety.unsafe } ensureNoUnassignedMVars decl addAndCompile decl evalConst α name private def throwStuckAtUniverseCnstr : TermElabM Unit := do -- This code assumes `entries` is not empty. Note that `processPostponed` uses `exceptionOnFailure` to guarantee this property let entries ← getPostponed let mut found : Std.HashSet (Level × Level) := {} let mut uniqueEntries := #[] for entry in entries do let mut lhs := entry.lhs let mut rhs := entry.rhs if Level.normLt rhs lhs then (lhs, rhs) := (rhs, lhs) unless found.contains (lhs, rhs) do found := found.insert (lhs, rhs) uniqueEntries := uniqueEntries.push entry for i in [1:uniqueEntries.size] do logErrorAt uniqueEntries[i].ref (← mkLevelStuckErrorMessage uniqueEntries[i]) throwErrorAt uniqueEntries[0].ref (← mkLevelStuckErrorMessage uniqueEntries[0]) def withoutPostponingUniverseConstraints (x : TermElabM α) : TermElabM α := do let postponed ← getResetPostponed try let a ← x unless (← processPostponed (mayPostpone := false) (exceptionOnFailure := true)) do throwStuckAtUniverseCnstr setPostponed postponed return a catch ex => setPostponed postponed throw ex end Term open Term in def withoutModifyingStateWithInfoAndMessages [MonadControlT TermElabM m] [Monad m] (x : m α) : m α := do controlAt TermElabM fun runInBase => withoutModifyingStateWithInfoAndMessagesImpl <| runInBase x builtin_initialize registerTraceClass `Elab.postpone registerTraceClass `Elab.coe registerTraceClass `Elab.debug export Term (TermElabM) end Lean.Elab
3d2f40463f2d1e03e130cee283d88d2cddc27461
4fa161becb8ce7378a709f5992a594764699e268
/src/group_theory/order_of_element.lean
0ffe11b6a3ed241c566f8d14fdc086ba810ab61e
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
24,289
lean
/- Copyright (c) 2018 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import group_theory.coset import data.nat.totient import data.set.finite open function open_locale big_operators variables {α : Type*} {s : set α} {a a₁ a₂ b c: α} -- TODO this lemma isn't used anywhere in this file, and should be moved elsewhere. namespace finset open finset lemma mem_range_iff_mem_finset_range_of_mod_eq [decidable_eq α] {f : ℤ → α} {a : α} {n : ℕ} (hn : 0 < n) (h : ∀i, f (i % n) = f i) : a ∈ set.range f ↔ a ∈ (finset.range n).image (λi, f i) := suffices (∃i, f (i % n) = a) ↔ ∃i, i < n ∧ f ↑i = a, by simpa [h], have hn' : 0 < (n : ℤ), from int.coe_nat_lt.mpr hn, iff.intro (assume ⟨i, hi⟩, have 0 ≤ i % ↑n, from int.mod_nonneg _ (ne_of_gt hn'), ⟨int.to_nat (i % n), by rw [←int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos i hn', hi⟩⟩) (assume ⟨i, hi, ha⟩, ⟨i, by rw [int.mod_eq_of_lt (int.coe_zero_le _) (int.coe_nat_lt_coe_nat_of_lt hi), ha]⟩) end finset lemma conj_injective [group α] {x : α} : function.injective (λ (g : α), x * g * x⁻¹) := λ a b h, by simpa [mul_left_inj, mul_right_inj] using h lemma mem_normalizer_fintype [group α] {s : set α} [fintype s] {x : α} (h : ∀ n, n ∈ s → x * n * x⁻¹ ∈ s) : x ∈ is_subgroup.normalizer s := by haveI := classical.prop_decidable; haveI := set.fintype_image s (λ n, x * n * x⁻¹); exact λ n, ⟨h n, λ h₁, have heq : (λ n, x * n * x⁻¹) '' s = s := set.eq_of_subset_of_card_le (λ n ⟨y, hy⟩, hy.2 ▸ h y hy.1) (by rw set.card_image_of_injective s conj_injective), have x * n * x⁻¹ ∈ (λ n, x * n * x⁻¹) '' s := heq.symm ▸ h₁, let ⟨y, hy⟩ := this in conj_injective hy.2 ▸ hy.1⟩ section order_of variable [group α] open quotient_group set @[simp] lemma card_trivial [fintype (is_subgroup.trivial α)] : fintype.card (is_subgroup.trivial α) = 1 := fintype.card_eq_one_iff.2 ⟨⟨(1 : α), by simp⟩, λ ⟨y, hy⟩, subtype.eq $ is_subgroup.mem_trivial.1 hy⟩ variables [fintype α] [dec : decidable_eq α] instance quotient_group.fintype (s : set α) [is_subgroup s] [d : decidable_pred s] : fintype (quotient s) := @quotient.fintype _ _ (left_rel s) (λ _ _, d _) lemma card_eq_card_quotient_mul_card_subgroup (s : set α) [hs : is_subgroup s] [fintype s] [decidable_pred s] : fintype.card α = fintype.card (quotient s) * fintype.card s := by rw ← fintype.card_prod; exact fintype.card_congr (is_subgroup.group_equiv_quotient_times_subgroup hs) lemma card_subgroup_dvd_card (s : set α) [is_subgroup s] [fintype s] : fintype.card s ∣ fintype.card α := by haveI := classical.prop_decidable; simp [card_eq_card_quotient_mul_card_subgroup s] lemma card_quotient_dvd_card (s : set α) [is_subgroup s] [decidable_pred s] [fintype s] : fintype.card (quotient s) ∣ fintype.card α := by simp [card_eq_card_quotient_mul_card_subgroup s] lemma exists_gpow_eq_one (a : α) : ∃i≠0, a ^ (i:ℤ) = 1 := have ¬ injective (λi:ℤ, a ^ i), from not_injective_infinite_fintype _, let ⟨i, j, a_eq, ne⟩ := show ∃(i j : ℤ), a ^ i = a ^ j ∧ i ≠ j, by rw [injective] at this; simpa [classical.not_forall] in have a ^ (i - j) = 1, by simp [sub_eq_add_neg, gpow_add, gpow_neg, a_eq], ⟨i - j, sub_ne_zero.mpr ne, this⟩ @[nolint ge_or_gt] -- see Note [nolint_ge] lemma exists_pow_eq_one (a : α) : ∃i > 0, a ^ i = 1 := let ⟨i, hi, eq⟩ := exists_gpow_eq_one a in begin cases i, { exact ⟨i, nat.pos_of_ne_zero (by simp [int.of_nat_eq_coe, *] at *), eq⟩ }, { exact ⟨i + 1, dec_trivial, inv_eq_one.1 eq⟩ } end include dec /-- `order_of a` is the order of the element `a`, i.e. the `n ≥ 1`, s.t. `a ^ n = 1` -/ def order_of (a : α) : ℕ := nat.find (exists_pow_eq_one a) lemma pow_order_of_eq_one (a : α) : a ^ order_of a = 1 := let ⟨h₁, h₂⟩ := nat.find_spec (exists_pow_eq_one a) in h₂ lemma order_of_pos (a : α) : 0 < order_of a := let ⟨h₁, h₂⟩ := nat.find_spec (exists_pow_eq_one a) in h₁ private lemma pow_injective_aux {n m : ℕ} (a : α) (h : n ≤ m) (hn : n < order_of a) (hm : m < order_of a) (eq : a ^ n = a ^ m) : n = m := decidable.by_contradiction $ assume ne : n ≠ m, have h₁ : m - n > 0, from nat.pos_of_ne_zero (by simp [nat.sub_eq_iff_eq_add h, ne.symm]), have h₂ : a ^ (m - n) = 1, by simp [pow_sub _ h, eq], have le : order_of a ≤ m - n, from nat.find_min' (exists_pow_eq_one a) ⟨h₁, h₂⟩, have lt : m - n < order_of a, from (nat.sub_lt_left_iff_lt_add h).mpr $ nat.lt_add_left _ _ _ hm, lt_irrefl _ (lt_of_le_of_lt le lt) lemma pow_injective_of_lt_order_of {n m : ℕ} (a : α) (hn : n < order_of a) (hm : m < order_of a) (eq : a ^ n = a ^ m) : n = m := (le_total n m).elim (assume h, pow_injective_aux a h hn hm eq) (assume h, (pow_injective_aux a h hm hn eq.symm).symm) lemma order_of_le_card_univ : order_of a ≤ fintype.card α := finset.card_le_of_inj_on ((^) a) (assume n _, fintype.complete _) (assume i j, pow_injective_of_lt_order_of a) lemma pow_eq_mod_order_of {n : ℕ} : a ^ n = a ^ (n % order_of a) := calc a ^ n = a ^ (n % order_of a + order_of a * (n / order_of a)) : by rw [nat.mod_add_div] ... = a ^ (n % order_of a) : by simp [pow_add, pow_mul, pow_order_of_eq_one] lemma gpow_eq_mod_order_of {i : ℤ} : a ^ i = a ^ (i % order_of a) := calc a ^ i = a ^ (i % order_of a + order_of a * (i / order_of a)) : by rw [int.mod_add_div] ... = a ^ (i % order_of a) : by simp [gpow_add, gpow_mul, pow_order_of_eq_one] lemma mem_gpowers_iff_mem_range_order_of {a a' : α} : a' ∈ gpowers a ↔ a' ∈ (finset.range (order_of a)).image ((^) a : ℕ → α) := finset.mem_range_iff_mem_finset_range_of_mod_eq (order_of_pos a) (assume i, gpow_eq_mod_order_of.symm) instance decidable_gpowers : decidable_pred (gpowers a) := assume a', decidable_of_iff' (a' ∈ (finset.range (order_of a)).image ((^) a)) mem_gpowers_iff_mem_range_order_of lemma order_of_dvd_of_pow_eq_one {n : ℕ} (h : a ^ n = 1) : order_of a ∣ n := by_contradiction (λ h₁, nat.find_min _ (show n % order_of a < order_of a, from nat.mod_lt _ (order_of_pos _)) ⟨nat.pos_of_ne_zero (mt nat.dvd_of_mod_eq_zero h₁), by rwa ← pow_eq_mod_order_of⟩) lemma order_of_dvd_iff_pow_eq_one {n : ℕ} : order_of a ∣ n ↔ a ^ n = 1 := ⟨λ h, by rw [pow_eq_mod_order_of, nat.mod_eq_zero_of_dvd h, pow_zero], order_of_dvd_of_pow_eq_one⟩ lemma order_of_le_of_pow_eq_one {n : ℕ} (hn : 0 < n) (h : a ^ n = 1) : order_of a ≤ n := nat.find_min' (exists_pow_eq_one a) ⟨hn, h⟩ lemma sum_card_order_of_eq_card_pow_eq_one {n : ℕ} (hn : 0 < n) : ∑ m in (finset.range n.succ).filter (∣ n), (finset.univ.filter (λ a : α, order_of a = m)).card = (finset.univ.filter (λ a : α, a ^ n = 1)).card := calc ∑ m in (finset.range n.succ).filter (∣ n), (finset.univ.filter (λ a : α, order_of a = m)).card = _ : (finset.card_bind (by { intros, apply finset.disjoint_filter.2, cc })).symm ... = _ : congr_arg finset.card (finset.ext (begin assume a, suffices : order_of a ≤ n ∧ order_of a ∣ n ↔ a ^ n = 1, { simpa [nat.lt_succ_iff], }, exact ⟨λ h, let ⟨m, hm⟩ := h.2 in by rw [hm, pow_mul, pow_order_of_eq_one, _root_.one_pow], λ h, ⟨order_of_le_of_pow_eq_one hn h, order_of_dvd_of_pow_eq_one h⟩⟩ end)) section local attribute [instance] set_fintype lemma order_eq_card_gpowers : order_of a = fintype.card (gpowers a) := begin refine (finset.card_eq_of_bijective _ _ _ _).symm, { exact λn hn, ⟨gpow a n, ⟨n, rfl⟩⟩ }, { exact assume ⟨_, i, rfl⟩ _, have pos: (0:int) < order_of a, from int.coe_nat_lt.mpr $ order_of_pos a, have 0 ≤ i % (order_of a), from int.mod_nonneg _ $ ne_of_gt pos, ⟨int.to_nat (i % order_of a), by rw [← int.coe_nat_lt, int.to_nat_of_nonneg this]; exact ⟨int.mod_lt_of_pos _ pos, subtype.eq gpow_eq_mod_order_of.symm⟩⟩ }, { intros, exact finset.mem_univ _ }, { exact assume i j hi hj eq, pow_injective_of_lt_order_of a hi hj $ by simpa using eq } end @[simp] lemma order_of_one : order_of (1 : α) = 1 := by rw [order_eq_card_gpowers, fintype.card_eq_one_iff]; exact ⟨⟨1, 0, rfl⟩, λ ⟨a, i, ha⟩, by simp [ha.symm]⟩ @[simp] lemma order_of_eq_one_iff : order_of a = 1 ↔ a = 1 := ⟨λ h, by conv { to_lhs, rw [← pow_one a, ← h, pow_order_of_eq_one] }, λ h, by simp [h]⟩ lemma order_of_eq_prime {p : ℕ} [hp : fact p.prime] (hg : a^p = 1) (hg1 : a ≠ 1) : order_of a = p := (hp.2 _ (order_of_dvd_of_pow_eq_one hg)).resolve_left (mt order_of_eq_one_iff.1 hg1) section classical open_locale classical open quotient_group /- TODO: use cardinal theory, introduce `card : set α → ℕ`, or setup decidability for cosets -/ lemma order_of_dvd_card_univ : order_of a ∣ fintype.card α := have ft_prod : fintype (quotient (gpowers a) × (gpowers a)), from fintype.of_equiv α (gpowers.is_subgroup a).group_equiv_quotient_times_subgroup, have ft_s : fintype (gpowers a), from @fintype.fintype_prod_right _ _ _ ft_prod _, have ft_cosets : fintype (quotient (gpowers a)), from @fintype.fintype_prod_left _ _ _ ft_prod ⟨⟨1, is_submonoid.one_mem⟩⟩, have ft : fintype (quotient (gpowers a) × (gpowers a)), from @prod.fintype _ _ ft_cosets ft_s, have eq₁ : fintype.card α = @fintype.card _ ft_cosets * @fintype.card _ ft_s, from calc fintype.card α = @fintype.card _ ft_prod : @fintype.card_congr _ _ _ ft_prod (gpowers.is_subgroup a).group_equiv_quotient_times_subgroup ... = @fintype.card _ (@prod.fintype _ _ ft_cosets ft_s) : congr_arg (@fintype.card _) $ subsingleton.elim _ _ ... = @fintype.card _ ft_cosets * @fintype.card _ ft_s : @fintype.card_prod _ _ ft_cosets ft_s, have eq₂ : order_of a = @fintype.card _ ft_s, from calc order_of a = _ : order_eq_card_gpowers ... = _ : congr_arg (@fintype.card _) $ subsingleton.elim _ _, dvd.intro (@fintype.card (quotient (gpowers a)) ft_cosets) $ by rw [eq₁, eq₂, mul_comm] omit dec @[simp] lemma pow_card_eq_one (a : α) : a ^ fintype.card α = 1 := let ⟨m, hm⟩ := @order_of_dvd_card_univ _ a _ _ _ in by simp [hm, pow_mul, pow_order_of_eq_one] lemma powers_eq_gpowers (a : α) : powers a = gpowers a := set.ext (λ x, ⟨λ ⟨n, hn⟩, ⟨n, by simp * at *⟩, λ ⟨i, hi⟩, ⟨(i % order_of a).nat_abs, by rwa [← gpow_coe_nat, int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (order_of_pos _))), ← gpow_eq_mod_order_of]⟩⟩) end classical open nat lemma order_of_pow (a : α) (n : ℕ) : order_of (a ^ n) = order_of a / gcd (order_of a) n := dvd_antisymm (order_of_dvd_of_pow_eq_one (by rw [← pow_mul, ← nat.mul_div_assoc _ (gcd_dvd_left _ _), mul_comm, nat.mul_div_assoc _ (gcd_dvd_right _ _), pow_mul, pow_order_of_eq_one, _root_.one_pow])) (have gcd_pos : 0 < gcd (order_of a) n, from gcd_pos_of_pos_left n (order_of_pos a), have hdvd : order_of a ∣ n * order_of (a ^ n), from order_of_dvd_of_pow_eq_one (by rw [pow_mul, pow_order_of_eq_one]), coprime.dvd_of_dvd_mul_right (coprime_div_gcd_div_gcd gcd_pos) (dvd_of_mul_dvd_mul_right gcd_pos (by rwa [nat.div_mul_cancel (gcd_dvd_left _ _), mul_assoc, nat.div_mul_cancel (gcd_dvd_right _ _), mul_comm]))) lemma image_range_order_of (a : α) : finset.image (λ i, a ^ i) (finset.range (order_of a)) = (gpowers a).to_finset := by { ext x, rw [set.mem_to_finset, mem_gpowers_iff_mem_range_order_of] } omit dec open_locale classical lemma pow_gcd_card_eq_one_iff {n : ℕ} {a : α} : a ^ n = 1 ↔ a ^ (gcd n (fintype.card α)) = 1 := ⟨λ h, have hn : order_of a ∣ n, from dvd_of_mod_eq_zero $ by_contradiction (λ ha, by rw pow_eq_mod_order_of at h; exact (not_le_of_gt (nat.mod_lt n (order_of_pos a))) (order_of_le_of_pow_eq_one (nat.pos_of_ne_zero ha) h)), let ⟨m, hm⟩ := dvd_gcd hn order_of_dvd_card_univ in by rw [hm, pow_mul, pow_order_of_eq_one, _root_.one_pow], λ h, let ⟨m, hm⟩ := gcd_dvd_left n (fintype.card α) in by rw [hm, pow_mul, h, _root_.one_pow]⟩ end end order_of section cyclic local attribute [instance] set_fintype /-- A group is called *cyclic* if it is generated by a single element. -/ class is_cyclic (α : Type*) [group α] : Prop := (exists_generator [] : ∃ g : α, ∀ x, x ∈ gpowers g) /-- A cyclic group is always commutative. This is not an `instance` because often we have a better proof of `comm_group`. -/ def is_cyclic.comm_group [hg : group α] [is_cyclic α] : comm_group α := { mul_comm := λ x y, show x * y = y * x, from let ⟨g, hg⟩ := is_cyclic.exists_generator α in let ⟨n, hn⟩ := hg x in let ⟨m, hm⟩ := hg y in hm ▸ hn ▸ gpow_mul_comm _ _ _, ..hg } lemma is_cyclic_of_order_of_eq_card [group α] [fintype α] [decidable_eq α] (x : α) (hx : order_of x = fintype.card α) : is_cyclic α := ⟨⟨x, set.eq_univ_iff_forall.1 $ set.eq_of_subset_of_card_le (set.subset_univ _) (by rw [fintype.card_congr (equiv.set.univ α), ← hx, order_eq_card_gpowers])⟩⟩ lemma order_of_eq_card_of_forall_mem_gpowers [group α] [fintype α] [decidable_eq α] {g : α} (hx : ∀ x, x ∈ gpowers g) : order_of g = fintype.card α := by rw [← fintype.card_congr (equiv.set.univ α), order_eq_card_gpowers]; simp [hx]; congr instance [group α] : is_cyclic (is_subgroup.trivial α) := ⟨⟨(1 : is_subgroup.trivial α), λ x, ⟨0, subtype.eq $ eq.symm (is_subgroup.mem_trivial.1 x.2)⟩⟩⟩ instance is_subgroup.is_cyclic [group α] [is_cyclic α] (H : set α) [is_subgroup H] : is_cyclic H := by haveI := classical.prop_decidable; exact let ⟨g, hg⟩ := is_cyclic.exists_generator α in if hx : ∃ (x : α), x ∈ H ∧ x ≠ (1 : α) then let ⟨x, hx₁, hx₂⟩ := hx in let ⟨k, hk⟩ := hg x in have hex : ∃ n : ℕ, 0 < n ∧ g ^ n ∈ H, from ⟨k.nat_abs, nat.pos_of_ne_zero (λ h, hx₂ $ by rw [← hk, int.eq_zero_of_nat_abs_eq_zero h, gpow_zero]), match k, hk with | (k : ℕ), hk := by rw [int.nat_abs_of_nat, ← gpow_coe_nat, hk]; exact hx₁ | -[1+ k], hk := by rw [int.nat_abs_of_neg_succ_of_nat, ← is_subgroup.inv_mem_iff H]; simp * at * end⟩, ⟨⟨⟨g ^ nat.find hex, (nat.find_spec hex).2⟩, λ ⟨x, hx⟩, let ⟨k, hk⟩ := hg x in have hk₁ : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) ∈ gpowers (g ^ nat.find hex), from ⟨k / nat.find hex, eq.symm $ gpow_mul _ _ _⟩, have hk₂ : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) ∈ H, by rw gpow_mul; exact is_subgroup.gpow_mem (nat.find_spec hex).2, have hk₃ : g ^ (k % nat.find hex) ∈ H, from (is_subgroup.mul_mem_cancel_right H hk₂).1 $ by rw [← gpow_add, int.mod_add_div, hk]; exact hx, have hk₄ : k % nat.find hex = (k % nat.find hex).nat_abs, by rw int.nat_abs_of_nonneg (int.mod_nonneg _ (int.coe_nat_ne_zero_iff_pos.2 (nat.find_spec hex).1)), have hk₅ : g ^ (k % nat.find hex ).nat_abs ∈ H, by rwa [← gpow_coe_nat, ← hk₄], have hk₆ : (k % (nat.find hex : ℤ)).nat_abs = 0, from by_contradiction (λ h, nat.find_min hex (int.coe_nat_lt.1 $ by rw [← hk₄]; exact int.mod_lt_of_pos _ (int.coe_nat_pos.2 (nat.find_spec hex).1)) ⟨nat.pos_of_ne_zero h, hk₅⟩), ⟨k / (nat.find hex : ℤ), subtype.coe_ext.2 begin suffices : g ^ ((nat.find hex : ℤ) * (k / nat.find hex)) = x, { simpa [gpow_mul] }, rw [int.mul_div_cancel' (int.dvd_of_mod_eq_zero (int.eq_zero_of_nat_abs_eq_zero hk₆)), hk] end⟩⟩⟩ else have H = is_subgroup.trivial α, from set.ext $ λ x, ⟨λ h, by simp at *; tauto, λ h, by rw [is_subgroup.mem_trivial.1 h]; exact is_submonoid.one_mem⟩, by clear _let_match; subst this; apply_instance open finset nat lemma is_cyclic.card_pow_eq_one_le [group α] [fintype α] [decidable_eq α] [is_cyclic α] {n : ℕ} (hn0 : 0 < n) : (univ.filter (λ a : α, a ^ n = 1)).card ≤ n := let ⟨g, hg⟩ := is_cyclic.exists_generator α in calc (univ.filter (λ a : α, a ^ n = 1)).card ≤ (gpowers (g ^ (fintype.card α / (gcd n (fintype.card α))))).to_finset.card : card_le_of_subset (λ x hx, let ⟨m, hm⟩ := show x ∈ powers g, from (powers_eq_gpowers g).symm ▸ hg x in set.mem_to_finset.2 ⟨(m / (fintype.card α / (gcd n (fintype.card α))) : ℕ), have hgmn : g ^ (m * gcd n (fintype.card α)) = 1, by rw [pow_mul, hm, ← pow_gcd_card_eq_one_iff]; exact (mem_filter.1 hx).2, begin rw [gpow_coe_nat, ← pow_mul, nat.mul_div_cancel_left', hm], refine dvd_of_mul_dvd_mul_right (gcd_pos_of_pos_left (fintype.card α) hn0) _, conv {to_lhs, rw [nat.div_mul_cancel (gcd_dvd_right _ _), ← order_of_eq_card_of_forall_mem_gpowers hg]}, exact order_of_dvd_of_pow_eq_one hgmn end⟩) ... ≤ n : let ⟨m, hm⟩ := gcd_dvd_right n (fintype.card α) in have hm0 : 0 < m, from nat.pos_of_ne_zero (λ hm0, (by rw [hm0, mul_zero, fintype.card_eq_zero_iff] at hm; exact hm 1)), begin rw [← fintype.card_of_finset' _ (λ _, set.mem_to_finset), ← order_eq_card_gpowers, order_of_pow, order_of_eq_card_of_forall_mem_gpowers hg], rw [hm] {occs := occurrences.pos [2,3]}, rw [nat.mul_div_cancel_left _ (gcd_pos_of_pos_left _ hn0), gcd_mul_left_left, hm, nat.mul_div_cancel _ hm0], exact le_of_dvd hn0 (gcd_dvd_left _ _) end lemma is_cyclic.exists_monoid_generator (α : Type*) [group α] [fintype α] [is_cyclic α] : ∃ x : α, ∀ y : α, y ∈ powers x := by simp only [powers_eq_gpowers]; exact is_cyclic.exists_generator α section variables [group α] [fintype α] [decidable_eq α] lemma is_cyclic.image_range_order_of (ha : ∀ x : α, x ∈ gpowers a) : finset.image (λ i, a ^ i) (range (order_of a)) = univ := begin simp only [image_range_order_of, set.eq_univ_iff_forall.mpr ha], convert set.to_finset_univ end lemma is_cyclic.image_range_card (ha : ∀ x : α, x ∈ gpowers a) : finset.image (λ i, a ^ i) (range (fintype.card α)) = univ := by rw [← order_of_eq_card_of_forall_mem_gpowers ha, is_cyclic.image_range_order_of ha] end section totient variables [group α] [fintype α] [decidable_eq α] (hn : ∀ n : ℕ, 0 < n → (univ.filter (λ a : α, a ^ n = 1)).card ≤ n) include hn lemma card_pow_eq_one_eq_order_of_aux (a : α) : (finset.univ.filter (λ b : α, b ^ order_of a = 1)).card = order_of a := le_antisymm (hn _ (order_of_pos _)) (calc order_of a = @fintype.card (gpowers a) (id _) : order_eq_card_gpowers ... ≤ @fintype.card (↑(univ.filter (λ b : α, b ^ order_of a = 1)) : set α) (fintype.of_finset _ (λ _, iff.rfl)) : @fintype.card_le_of_injective (gpowers a) (↑(univ.filter (λ b : α, b ^ order_of a = 1)) : set α) (id _) (id _) (λ b, ⟨b.1, mem_filter.2 ⟨mem_univ _, let ⟨i, hi⟩ := b.2 in by rw [← hi, ← gpow_coe_nat, ← gpow_mul, mul_comm, gpow_mul, gpow_coe_nat, pow_order_of_eq_one, one_gpow]⟩⟩) (λ _ _ h, subtype.eq (subtype.mk.inj h)) ... = (univ.filter (λ b : α, b ^ order_of a = 1)).card : fintype.card_of_finset _ _) open_locale nat -- use φ for nat.totient private lemma card_order_of_eq_totient_aux₁ : ∀ {d : ℕ}, d ∣ fintype.card α → 0 < (univ.filter (λ a : α, order_of a = d)).card → (univ.filter (λ a : α, order_of a = d)).card = φ d | 0 := λ hd hd0, let ⟨a, ha⟩ := card_pos.1 hd0 in absurd (mem_filter.1 ha).2 $ ne_of_gt $ order_of_pos a | (d+1) := λ hd hd0, let ⟨a, ha⟩ := card_pos.1 hd0 in have ha : order_of a = d.succ, from (mem_filter.1 ha).2, have h : ∑ m in (range d.succ).filter (∣ d.succ), (univ.filter (λ a : α, order_of a = m)).card = ∑ m in (range d.succ).filter (∣ d.succ), φ m, from finset.sum_congr rfl (λ m hm, have hmd : m < d.succ, from mem_range.1 (mem_filter.1 hm).1, have hm : m ∣ d.succ, from (mem_filter.1 hm).2, card_order_of_eq_totient_aux₁ (dvd.trans hm hd) (finset.card_pos.2 ⟨a ^ (d.succ / m), mem_filter.2 ⟨mem_univ _, by rw [order_of_pow, ha, gcd_eq_right (div_dvd_of_dvd hm), nat.div_div_self hm (succ_pos _)]⟩⟩)), have hinsert : insert d.succ ((range d.succ).filter (∣ d.succ)) = (range d.succ.succ).filter (∣ d.succ), from (finset.ext $ λ x, ⟨λ h, (mem_insert.1 h).elim (λ h, by simp [h, range_succ]) (by clear _let_match; simp [range_succ]; tauto), by clear _let_match; simp [range_succ] {contextual := tt}; tauto⟩), have hinsert₁ : d.succ ∉ (range d.succ).filter (∣ d.succ), by simp [mem_range, zero_le_one, le_succ], (add_left_inj (∑ m in (range d.succ).filter (∣ d.succ), (univ.filter (λ a : α, order_of a = m)).card)).1 (calc _ = ∑ m in insert d.succ (filter (∣ d.succ) (range d.succ)), (univ.filter (λ a : α, order_of a = m)).card : eq.symm (finset.sum_insert (by simp [mem_range, zero_le_one, le_succ])) ... = ∑ m in (range d.succ.succ).filter (∣ d.succ), (univ.filter (λ a : α, order_of a = m)).card : sum_congr hinsert (λ _ _, rfl) ... = (univ.filter (λ a : α, a ^ d.succ = 1)).card : sum_card_order_of_eq_card_pow_eq_one (succ_pos d) ... = ∑ m in (range d.succ.succ).filter (∣ d.succ), φ m : ha ▸ (card_pow_eq_one_eq_order_of_aux hn a).symm ▸ (sum_totient _).symm ... = _ : by rw [h, ← sum_insert hinsert₁]; exact finset.sum_congr hinsert.symm (λ _ _, rfl)) lemma card_order_of_eq_totient_aux₂ {d : ℕ} (hd : d ∣ fintype.card α) : (univ.filter (λ a : α, order_of a = d)).card = φ d := by_contradiction $ λ h, have h0 : (univ.filter (λ a : α , order_of a = d)).card = 0 := not_not.1 (mt nat.pos_iff_ne_zero.2 (mt (card_order_of_eq_totient_aux₁ hn hd) h)), let c := fintype.card α in have hc0 : 0 < c, from fintype.card_pos_iff.2 ⟨1⟩, lt_irrefl c $ calc c = (univ.filter (λ a : α, a ^ c = 1)).card : congr_arg card $ by simp [finset.ext_iff, c] ... = ∑ m in (range c.succ).filter (∣ c), (univ.filter (λ a : α, order_of a = m)).card : (sum_card_order_of_eq_card_pow_eq_one hc0).symm ... = ∑ m in ((range c.succ).filter (∣ c)).erase d, (univ.filter (λ a : α, order_of a = m)).card : eq.symm (sum_subset (erase_subset _ _) (λ m hm₁ hm₂, have m = d, by simp at *; cc, by simp [*, finset.ext_iff] at *; exact h0)) ... ≤ ∑ m in ((range c.succ).filter (∣ c)).erase d, φ m : sum_le_sum (λ m hm, have hmc : m ∣ c, by simp at hm; tauto, (imp_iff_not_or.1 (card_order_of_eq_totient_aux₁ hn hmc)).elim (λ h, by simp [nat.le_zero_iff.1 (le_of_not_gt h), nat.zero_le]) (λ h, by rw h)) ... < φ d + ∑ m in ((range c.succ).filter (∣ c)).erase d, φ m : lt_add_of_pos_left _ (totient_pos (nat.pos_of_ne_zero (λ h, nat.pos_iff_ne_zero.1 hc0 (eq_zero_of_zero_dvd $ h ▸ hd)))) ... = ∑ m in insert d (((range c.succ).filter (∣ c)).erase d), φ m : eq.symm (sum_insert (by simp)) ... = ∑ m in (range c.succ).filter (∣ c), φ m : finset.sum_congr (finset.insert_erase (mem_filter.2 ⟨mem_range.2 (lt_succ_of_le (le_of_dvd hc0 hd)), hd⟩)) (λ _ _, rfl) ... = c : sum_totient _ lemma is_cyclic_of_card_pow_eq_one_le : is_cyclic α := have (univ.filter (λ a : α, order_of a = fintype.card α)).nonempty, from (card_pos.1 $ by rw [card_order_of_eq_totient_aux₂ hn (dvd_refl _)]; exact totient_pos (fintype.card_pos_iff.2 ⟨1⟩)), let ⟨x, hx⟩ := this in is_cyclic_of_order_of_eq_card x (finset.mem_filter.1 hx).2 end totient lemma is_cyclic.card_order_of_eq_totient [group α] [is_cyclic α] [fintype α] [decidable_eq α] {d : ℕ} (hd : d ∣ fintype.card α) : (univ.filter (λ a : α, order_of a = d)).card = totient d := card_order_of_eq_totient_aux₂ (λ n, is_cyclic.card_pow_eq_one_le) hd end cyclic
58e1c5352a548199e1e2b73b9e3282348607e080
3bdd27ffdff3ffa22d4bb010eba695afcc96bc4a
/src/combinatorics/simplicial_complex/pure.lean
f924339fad4cf02091f8620ae60e64a3c48e195d
[]
no_license
mmasdeu/brouwerfixedpoint
684d712c982c6a8b258b4e2c6b2eab923f2f1289
548270f79ecf12d7e20a256806ccb9fcf57b87e2
refs/heads/main
1,690,539,793,996
1,631,801,831,000
1,631,801,831,000
368,139,809
4
3
null
1,624,453,250,000
1,621,246,034,000
Lean
UTF-8
Lean
false
false
3,371
lean
/- Copyright (c) 2021 Yaël Dillies, Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yaël Dillies, Bhavik Mehta -/ import combinatorics.simplicial_complex.basic namespace affine open set open_locale classical variables {a b m n : ℕ} {E : Type*} [normed_group E] [normed_space ℝ E] {S : simplicial_complex E} {X : finset E} /-- A simplicial complex is pure of dimension n iff all its facets have dimension n. -/ def simplicial_complex.pure_of (S : simplicial_complex E) (n : ℕ) : Prop := ∀ ⦃X⦄, X ∈ S.facets → (X : finset _).card = n /-- A simplicial complex is pure iff all its facets have the same dimension. -/ def simplicial_complex.pure (S : simplicial_complex E) : Prop := ∃ n : ℕ, S.pure_of n def simplicial_complex.full_dimensional (S : simplicial_complex E) : Prop := sorry --S.pure_of (S.dim + 1) /-- The pureness of a pure simplicial complex is the cardinality of its facets. Set to 0 for non pure complexes. -/ noncomputable def simplicial_complex.pureness (S : simplicial_complex E) : ℕ := if hS : S.pure then nat.find hS else 0 lemma pureness_def (hS : S.pure) : S.pure_of S.pureness := begin unfold simplicial_complex.pureness, rw dif_pos hS, exact nat.find_spec hS, end lemma pure_of_empty (h : S.faces = {∅}) : S.pure := begin use 0, rintro X hX, have := facets_subset hX, rw h at this, change X = ∅ at this, rw this, exact finset.card_empty, end variables [finite_dimensional ℝ E] lemma face_card_le_pureness (hS : S.pure_of n) (hX : X ∈ S.faces) : X.card ≤ n := begin obtain ⟨Y, hY, hXY⟩ := subfacet hX, rw ← hS hY, exact finset.card_le_of_subset hXY, end lemma pureness_unique_of_nonempty (hS : S.faces.nonempty) (ha : S.pure_of a) (hb : S.pure_of b) : a = b := begin obtain ⟨X, hX⟩ := hS, obtain ⟨Y, hY, hYX⟩ := subfacet hX, rw [←ha hY, ←hb hY], end lemma pureness_def' (hSnonempty : S.faces.nonempty) (hS : S.pure_of n) : S.pureness = n := pureness_unique_of_nonempty hSnonempty (pureness_def ⟨_, hS⟩) hS lemma facet_iff_dimension_eq_pureness (hS : S.pure_of n) (hX : X ∈ S.faces) : X ∈ S.facets ↔ X.card = n := begin refine ⟨λ hXfacet, hS hXfacet, λ hXcard, ⟨hX, λ Y hY hXY, finset.eq_of_subset_of_card_le hXY _⟩⟩, rw hXcard, exact face_card_le_pureness hS hY, end /-- A simplicial complex is pure iff there exists n such that all faces are subfaces of some (n - 1)-dimensional face. -/ lemma pure_iff : S.pure ↔ ∃ n : ℕ, ∀ {X}, X ∈ S.faces → ∃ {Y}, Y ∈ S.faces ∧ finset.card Y = n ∧ X ⊆ Y := begin split, { rintro hS, use S.pureness, rintro X hX, obtain ⟨Y, hY, hXY⟩ := subfacet hX, exact ⟨Y, facets_subset hY, pureness_def hS hY, hXY⟩ }, { rintro ⟨n, hS⟩, use n, rintro X ⟨hX, hXmax⟩, obtain ⟨Y, hY, hYcard, hXY⟩ := hS hX, rw hXmax hY hXY, exact hYcard } end lemma facets_subset_facets_of_pureness_eq_pureness_of_subcomplex {S₁ S₂ : simplicial_complex E} (hS : S₁.faces ⊆ S₂.faces) (hS₁ : S₁.pure_of n) (hS₂ : S₂.pure_of n) : S₁.facets ⊆ S₂.facets := begin rintro X hX, use hS hX.1, rintro Y hY hXY, apply finset.eq_of_subset_of_card_le hXY, rw hS₁ hX, exact face_card_le_pureness hS₂ hY, end end affine
779c825f07aac6aa03076ed6aa27e22adeded905
e00ea76a720126cf9f6d732ad6216b5b824d20a7
/src/analysis/asymptotics.lean
5697b0c3e817ba47c6fee88e498134718fec363d
[ "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
42,234
lean
/- Copyright (c) 2019 Jeremy Avigad. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jeremy Avigad, Yury Kudryashov -/ import analysis.normed_space.basic topology.local_homeomorph tactic.alias /-! # Asymptotics We introduce these relations: * `is_O_with c f g l` : "f is big O of g along l with constant c"; * `is_O f g l` : "f is big O of g along l"; * `is_o f g l` : "f is little o of g along l". Here `l` is any filter on the domain of `f` and `g`, which are assumed to be the same. The codomains of `f` and `g` do not need to be the same; all that is needed that there is a norm associated with these types, and it is the norm that is compared asymptotically. The relation `is_O_with c` is introduced to factor out common algebraic arguments in the proofs of similar properties of `is_O` and `is_o`. Usually proofs outside of this file should use `is_O` instead. Often the ranges of `f` and `g` will be the real numbers, in which case the norm is the absolute value. In general, we have `is_O f g l ↔ is_O (λ x, ∥f x∥) (λ x, ∥g x∥) l`, and similarly for `is_o`. But our setup allows us to use the notions e.g. with functions to the integers, rationals, complex numbers, or any normed vector space without mentioning the norm explicitly. If `f` and `g` are functions to a normed field like the reals or complex numbers and `g` is always nonzero, we have `is_o f g l ↔ tendsto (λ x, f x / (g x)) l (𝓝 0)`. In fact, the right-to-left direction holds without the hypothesis on `g`, and in the other direction it suffices to assume that `f` is zero wherever `g` is. (This generalization is useful in defining the Fréchet derivative.) -/ open filter set open_locale topological_space namespace asymptotics variables {α : Type*} {β : Type*} {E : Type*} {F : Type*} {G : Type*} {E' : Type*} {F' : Type*} {G' : Type*} {R : Type*} {R' : Type*} {𝕜 : Type*} {𝕜' : Type*} variables [has_norm E] [has_norm F] [has_norm G] [normed_group E'] [normed_group F'] [normed_group G'] [normed_ring R] [normed_ring R'] [normed_field 𝕜] [normed_field 𝕜'] {c c' : ℝ} {f : α → E} {g : α → F} {k : α → G} {f' : α → E'} {g' : α → F'} {k' : α → G'} {l l' : filter α} section defs /-! ### Definitions -/ /-- This version of the Landau notation `is_O_with C f g l` where `f` and `g` are two functions on a type `α` and `l` is a filter on `α`, means that eventually for `l`, `∥f∥` is bounded by `C * ∥g∥`. In other words, `∥f∥ / ∥g∥` is eventually bounded by `C`, modulo division by zero issues that are avoided by this definition. Probably you want to use `is_O` instead of this relation. -/ def is_O_with (c : ℝ) (f : α → E) (g : α → F) (l : filter α) : Prop := ∀ᶠ x in l, ∥ f x ∥ ≤ c * ∥ g x ∥ /-- The Landau notation `is_O f g l` where `f` and `g` are two functions on a type `α` and `l` is a filter on `α`, means that eventually for `l`, `∥f∥` is bounded by a constant multiple of `∥g∥`. In other words, `∥f∥ / ∥g∥` is eventually bounded, modulo division by zero issues that are avoided by this definition. -/ def is_O (f : α → E) (g : α → F) (l : filter α) : Prop := ∃ c : ℝ, is_O_with c f g l /-- The Landau notation `is_o f g l` where `f` and `g` are two functions on a type `α` and `l` is a filter on `α`, means that eventually for `l`, `∥f∥` is bounded by an arbitrarily small constant multiple of `∥g∥`. In other words, `∥f∥ / ∥g∥` tends to `0` along `l`, modulo division by zero issues that are avoided by this definition. -/ def is_o (f : α → E) (g : α → F) (l : filter α) : Prop := ∀ ⦃c : ℝ⦄, 0 < c → is_O_with c f g l end defs /-! ### Conversions -/ theorem is_O_with.is_O (h : is_O_with c f g l) : is_O f g l := ⟨c, h⟩ theorem is_o.is_O_with (hgf : is_o f g l) : is_O_with 1 f g l := hgf zero_lt_one theorem is_o.is_O (hgf : is_o f g l) : is_O f g l := hgf.is_O_with.is_O theorem is_O_with.weaken (h : is_O_with c f g' l) (hc : c ≤ c') : is_O_with c' f g' l := mem_sets_of_superset h $ λ x hx, calc ∥f x∥ ≤ c * ∥g' x∥ : hx ... ≤ _ : mul_le_mul_of_nonneg_right hc (norm_nonneg _) theorem is_O_with.exists_pos (h : is_O_with c f g' l) : ∃ c' (H : 0 < c'), is_O_with c' f g' l := ⟨max c 1, lt_of_lt_of_le zero_lt_one (le_max_right c 1), h.weaken $ le_max_left c 1⟩ theorem is_O.exists_pos (h : is_O f g' l) : ∃ c (H : 0 < c), is_O_with c f g' l := let ⟨c, hc⟩ := h in hc.exists_pos theorem is_O_with.exists_nonneg (h : is_O_with c f g' l) : ∃ c' (H : 0 ≤ c'), is_O_with c' f g' l := let ⟨c, cpos, hc⟩ := h.exists_pos in ⟨c, le_of_lt cpos, hc⟩ theorem is_O.exists_nonneg (h : is_O f g' l) : ∃ c (H : 0 ≤ c), is_O_with c f g' l := let ⟨c, hc⟩ := h in hc.exists_nonneg /-! ### Congruence -/ theorem is_O_with_congr {c₁ c₂} {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hc : c₁ = c₂) (hf : ∀ᶠ x in l, f₁ x = f₂ x) (hg : ∀ᶠ x in l, g₁ x = g₂ x) : is_O_with c₁ f₁ g₁ l ↔ is_O_with c₂ f₂ g₂ l := begin subst c₂, apply filter.congr_sets, filter_upwards [hf, hg], assume x e₁ e₂, dsimp at e₁ e₂ ⊢, rw [e₁, e₂] end theorem is_O_with.congr' {c₁ c₂} {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hc : c₁ = c₂) (hf : ∀ᶠ x in l, f₁ x = f₂ x) (hg : ∀ᶠ x in l, g₁ x = g₂ x) : is_O_with c₁ f₁ g₁ l → is_O_with c₂ f₂ g₂ l := (is_O_with_congr hc hf hg).mp theorem is_O_with.congr {c₁ c₂} {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hc : c₁ = c₂) (hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) : is_O_with c₁ f₁ g₁ l → is_O_with c₂ f₂ g₂ l := λ h, h.congr' hc (univ_mem_sets' hf) (univ_mem_sets' hg) theorem is_O_with.congr_left {f₁ f₂ : α → E} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) : is_O_with c f₁ g l → is_O_with c f₂ g l := is_O_with.congr rfl hf (λ _, rfl) theorem is_O_with.congr_right {g₁ g₂ : α → F} {l : filter α} (hg : ∀ x, g₁ x = g₂ x) : is_O_with c f g₁ l → is_O_with c f g₂ l := is_O_with.congr rfl (λ _, rfl) hg theorem is_O_with.congr_const {c₁ c₂} {l : filter α} (hc : c₁ = c₂) : is_O_with c₁ f g l → is_O_with c₂ f g l := is_O_with.congr hc (λ _, rfl) (λ _, rfl) theorem is_O_congr {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : ∀ᶠ x in l, f₁ x = f₂ x) (hg : ∀ᶠ x in l, g₁ x = g₂ x) : is_O f₁ g₁ l ↔ is_O f₂ g₂ l := exists_congr $ λ c, is_O_with_congr rfl hf hg theorem is_O.congr' {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : ∀ᶠ x in l, f₁ x = f₂ x) (hg : ∀ᶠ x in l, g₁ x = g₂ x) : is_O f₁ g₁ l → is_O f₂ g₂ l := (is_O_congr hf hg).mp theorem is_O.congr {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) : is_O f₁ g₁ l → is_O f₂ g₂ l := λ h, h.congr' (univ_mem_sets' hf) (univ_mem_sets' hg) theorem is_O.congr_left {f₁ f₂ : α → E} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) : is_O f₁ g l → is_O f₂ g l := is_O.congr hf (λ _, rfl) theorem is_O.congr_right {g₁ g₂ : α → E} {l : filter α} (hg : ∀ x, g₁ x = g₂ x) : is_O f g₁ l → is_O f g₂ l := is_O.congr (λ _, rfl) hg theorem is_o_congr {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : ∀ᶠ x in l, f₁ x = f₂ x) (hg : ∀ᶠ x in l, g₁ x = g₂ x) : is_o f₁ g₁ l ↔ is_o f₂ g₂ l := ball_congr (λ c hc, is_O_with_congr (eq.refl c) hf hg) theorem is_o.congr' {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : ∀ᶠ x in l, f₁ x = f₂ x) (hg : ∀ᶠ x in l, g₁ x = g₂ x) : is_o f₁ g₁ l → is_o f₂ g₂ l := (is_o_congr hf hg).mp theorem is_o.congr {f₁ f₂ : α → E} {g₁ g₂ : α → F} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) (hg : ∀ x, g₁ x = g₂ x) : is_o f₁ g₁ l → is_o f₂ g₂ l := λ h, h.congr' (univ_mem_sets' hf) (univ_mem_sets' hg) theorem is_o.congr_left {f₁ f₂ : α → E} {l : filter α} (hf : ∀ x, f₁ x = f₂ x) : is_o f₁ g l → is_o f₂ g l := is_o.congr hf (λ _, rfl) theorem is_o.congr_right {g₁ g₂ : α → E} {l : filter α} (hg : ∀ x, g₁ x = g₂ x) : is_o f g₁ l → is_o f g₂ l := is_o.congr (λ _, rfl) hg /-! ### Filter operations and transitivity -/ theorem is_O_with.comp_tendsto (hcfg : is_O_with c f g l) {k : β → α} {l' : filter β} (hk : tendsto k l' l): is_O_with c (f ∘ k) (g ∘ k) l' := hk hcfg theorem is_O.comp_tendsto (hfg : is_O f g l) {k : β → α} {l' : filter β} (hk : tendsto k l' l) : is_O (f ∘ k) (g ∘ k) l' := hfg.imp (λ c h, h.comp_tendsto hk) theorem is_o.comp_tendsto (hfg : is_o f g l) {k : β → α} {l' : filter β} (hk : tendsto k l' l) : is_o (f ∘ k) (g ∘ k) l' := λ c cpos, (hfg cpos).comp_tendsto hk theorem is_O_with.mono (h : is_O_with c f g l') (hl : l ≤ l') : is_O_with c f g l := hl h theorem is_O.mono (h : is_O f g l') (hl : l ≤ l') : is_O f g l := h.imp (λ c h, h.mono hl) theorem is_o.mono (h : is_o f g l') (hl : l ≤ l') : is_o f g l := λ c cpos, (h cpos).mono hl theorem is_O_with.trans (hfg : is_O_with c f g l) (hgk : is_O_with c' g k l) (hc : 0 ≤ c) : is_O_with (c * c') f k l := begin filter_upwards [hfg, hgk], assume x hx hx', calc ∥f x∥ ≤ c * ∥g x∥ : hx ... ≤ c * (c' * ∥k x∥) : mul_le_mul_of_nonneg_left hx' hc ... = c * c' * ∥k x∥ : (mul_assoc _ _ _).symm end theorem is_O.trans (hfg : is_O f g' l) (hgk : is_O g' k l) : is_O f k l := let ⟨c, cnonneg, hc⟩ := hfg.exists_nonneg, ⟨c', hc'⟩ := hgk in (hc.trans hc' cnonneg).is_O theorem is_o.trans_is_O_with (hfg : is_o f g l) (hgk : is_O_with c g k l) (hc : 0 < c) : is_o f k l := begin intros c' c'pos, have : 0 < c' / c, from div_pos c'pos hc, exact ((hfg this).trans hgk (le_of_lt this)).congr_const (div_mul_cancel _ (ne_of_gt hc)) end theorem is_o.trans_is_O (hfg : is_o f g l) (hgk : is_O g k' l) : is_o f k' l := let ⟨c, cpos, hc⟩ := hgk.exists_pos in hfg.trans_is_O_with hc cpos theorem is_O_with.trans_is_o (hfg : is_O_with c f g l) (hgk : is_o g k l) (hc : 0 < c) : is_o f k l := begin intros c' c'pos, have : 0 < c' / c, from div_pos c'pos hc, exact (hfg.trans (hgk this) (le_of_lt hc)).congr_const (mul_div_cancel' _ (ne_of_gt hc)) end theorem is_O.trans_is_o (hfg : is_O f g' l) (hgk : is_o g' k l) : is_o f k l := let ⟨c, cpos, hc⟩ := hfg.exists_pos in hc.trans_is_o hgk cpos theorem is_o.trans (hfg : is_o f g l) (hgk : is_o g k' l) : is_o f k' l := hfg.trans_is_O hgk.is_O theorem is_o.trans' (hfg : is_o f g' l) (hgk : is_o g' k l) : is_o f k l := hfg.is_O.trans_is_o hgk section variable (l) theorem is_O_with_of_le' (hfg : ∀ x, ∥f x∥ ≤ c * ∥g x∥) : is_O_with c f g l := univ_mem_sets' hfg theorem is_O_with_of_le (hfg : ∀ x, ∥f x∥ ≤ ∥g x∥) : is_O_with 1 f g l := is_O_with_of_le' l $ λ x, by { rw one_mul, exact hfg x } theorem is_O_of_le' (hfg : ∀ x, ∥f x∥ ≤ c * ∥g x∥) : is_O f g l := (is_O_with_of_le' l hfg).is_O theorem is_O_of_le (hfg : ∀ x, ∥f x∥ ≤ ∥g x∥) : is_O f g l := (is_O_with_of_le l hfg).is_O end theorem is_O_with_refl (f : α → E) (l : filter α) : is_O_with 1 f f l := is_O_with_of_le l $ λ _, le_refl _ theorem is_O_refl (f : α → E) (l : filter α) : is_O f f l := (is_O_with_refl f l).is_O theorem is_O_with.trans_le (hfg : is_O_with c f g l) (hgk : ∀ x, ∥g x∥ ≤ ∥k x∥) (hc : 0 ≤ c) : is_O_with c f k l := (hfg.trans (is_O_with_of_le l hgk) hc).congr_const $ mul_one c theorem is_O.trans_le (hfg : is_O f g' l) (hgk : ∀ x, ∥g' x∥ ≤ ∥k x∥) : is_O f k l := hfg.trans (is_O_of_le l hgk) section bot variables (c f g) theorem is_O_with_bot : is_O_with c f g ⊥ := trivial theorem is_O_bot : is_O f g ⊥ := (is_O_with_bot c f g).is_O theorem is_o_bot : is_o f g ⊥ := λ c _, is_O_with_bot c f g end bot theorem is_O_with.join (h : is_O_with c f g l) (h' : is_O_with c f g l') : is_O_with c f g (l ⊔ l') := mem_sup_sets.2 ⟨h, h'⟩ theorem is_O_with.join' (h : is_O_with c f g' l) (h' : is_O_with c' f g' l') : is_O_with (max c c') f g' (l ⊔ l') := mem_sup_sets.2 ⟨(h.weaken $ le_max_left c c'), (h'.weaken $ le_max_right c c')⟩ theorem is_O.join (h : is_O f g' l) (h' : is_O f g' l') : is_O f g' (l ⊔ l') := let ⟨c, hc⟩ := h, ⟨c', hc'⟩ := h' in (hc.join' hc').is_O theorem is_o.join (h : is_o f g l) (h' : is_o f g l') : is_o f g (l ⊔ l') := λ c cpos, (h cpos).join (h' cpos) /-! ### Simplification : norm -/ @[simp] theorem is_O_with_norm_right : is_O_with c f (λ x, ∥g' x∥) l ↔ is_O_with c f g' l := by simp only [is_O_with, norm_norm] alias is_O_with_norm_right ↔ asymptotics.is_O_with.of_norm_right asymptotics.is_O_with.norm_right @[simp] theorem is_O_norm_right : is_O f (λ x, ∥g' x∥) l ↔ is_O f g' l := exists_congr $ λ _, is_O_with_norm_right alias is_O_norm_right ↔ asymptotics.is_O.of_norm_right asymptotics.is_O.norm_right @[simp] theorem is_o_norm_right : is_o f (λ x, ∥g' x∥) l ↔ is_o f g' l := forall_congr $ λ _, forall_congr $ λ _, is_O_with_norm_right alias is_o_norm_right ↔ asymptotics.is_o.of_norm_right asymptotics.is_o.norm_right @[simp] theorem is_O_with_norm_left : is_O_with c (λ x, ∥f' x∥) g l ↔ is_O_with c f' g l := by simp only [is_O_with, norm_norm] alias is_O_with_norm_left ↔ asymptotics.is_O_with.of_norm_left asymptotics.is_O_with.norm_left @[simp] theorem is_O_norm_left : is_O (λ x, ∥f' x∥) g l ↔ is_O f' g l := exists_congr $ λ _, is_O_with_norm_left alias is_O_norm_left ↔ asymptotics.is_O.of_norm_left asymptotics.is_O.norm_left @[simp] theorem is_o_norm_left : is_o (λ x, ∥f' x∥) g l ↔ is_o f' g l := forall_congr $ λ _, forall_congr $ λ _, is_O_with_norm_left alias is_o_norm_left ↔ asymptotics.is_o.of_norm_left asymptotics.is_o.norm_left theorem is_O_with_norm_norm : is_O_with c (λ x, ∥f' x∥) (λ x, ∥g' x∥) l ↔ is_O_with c f' g' l := is_O_with_norm_left.trans is_O_with_norm_right alias is_O_with_norm_norm ↔ asymptotics.is_O_with.of_norm_norm asymptotics.is_O_with.norm_norm theorem is_O_norm_norm : is_O (λ x, ∥f' x∥) (λ x, ∥g' x∥) l ↔ is_O f' g' l := is_O_norm_left.trans is_O_norm_right alias is_O_norm_norm ↔ asymptotics.is_O.of_norm_norm asymptotics.is_O.norm_norm theorem is_o_norm_norm : is_o (λ x, ∥f' x∥) (λ x, ∥g' x∥) l ↔ is_o f' g' l := is_o_norm_left.trans is_o_norm_right alias is_o_norm_norm ↔ asymptotics.is_o.of_norm_norm asymptotics.is_o.norm_norm /-! ### Simplification: negate -/ @[simp] theorem is_O_with_neg_right : is_O_with c f (λ x, -(g' x)) l ↔ is_O_with c f g' l := by simp only [is_O_with, norm_neg] alias is_O_with_neg_right ↔ asymptotics.is_O_with.of_neg_right asymptotics.is_O_with.neg_right @[simp] theorem is_O_neg_right : is_O f (λ x, -(g' x)) l ↔ is_O f g' l := exists_congr $ λ _, is_O_with_neg_right alias is_O_neg_right ↔ asymptotics.is_O.of_neg_right asymptotics.is_O.neg_right @[simp] theorem is_o_neg_right : is_o f (λ x, -(g' x)) l ↔ is_o f g' l := forall_congr $ λ _, forall_congr $ λ _, is_O_with_neg_right alias is_o_neg_right ↔ asymptotics.is_o.of_neg_right asymptotics.is_o.neg_right @[simp] theorem is_O_with_neg_left : is_O_with c (λ x, -(f' x)) g l ↔ is_O_with c f' g l := by simp only [is_O_with, norm_neg] alias is_O_with_neg_left ↔ asymptotics.is_O_with.of_neg_left asymptotics.is_O_with.neg_left @[simp] theorem is_O_neg_left : is_O (λ x, -(f' x)) g l ↔ is_O f' g l := exists_congr $ λ _, is_O_with_neg_left alias is_O_neg_left ↔ asymptotics.is_O.of_neg_left asymptotics.is_O.neg_left @[simp] theorem is_o_neg_left : is_o (λ x, -(f' x)) g l ↔ is_o f' g l := forall_congr $ λ _, forall_congr $ λ _, is_O_with_neg_left alias is_o_neg_left ↔ asymptotics.is_o.of_neg_right asymptotics.is_o.neg_left /-! ### Product of functions (right) -/ lemma is_O_with_fst_prod : is_O_with 1 f' (λ x, (f' x, g' x)) l := is_O_with_of_le l $ λ x, le_max_left _ _ lemma is_O_with_snd_prod : is_O_with 1 g' (λ x, (f' x, g' x)) l := is_O_with_of_le l $ λ x, le_max_right _ _ lemma is_O_fst_prod : is_O f' (λ x, (f' x, g' x)) l := is_O_with_fst_prod.is_O lemma is_O_snd_prod : is_O g' (λ x, (f' x, g' x)) l := is_O_with_snd_prod.is_O section variables (f' k') lemma is_O_with.prod_rightl (h : is_O_with c f g' l) (hc : 0 ≤ c) : is_O_with c f (λ x, (g' x, k' x)) l := (h.trans is_O_with_fst_prod hc).congr_const (mul_one c) lemma is_O.prod_rightl (h : is_O f g' l) : is_O f (λx, (g' x, k' x)) l := let ⟨c, cnonneg, hc⟩ := h.exists_nonneg in (hc.prod_rightl k' cnonneg).is_O lemma is_o.prod_rightl (h : is_o f g' l) : is_o f (λ x, (g' x, k' x)) l := λ c cpos, (h cpos).prod_rightl k' (le_of_lt cpos) lemma is_O_with.prod_rightr (h : is_O_with c f g' l) (hc : 0 ≤ c) : is_O_with c f (λ x, (f' x, g' x)) l := (h.trans is_O_with_snd_prod hc).congr_const (mul_one c) lemma is_O.prod_rightr (h : is_O f g' l) : is_O f (λx, (f' x, g' x)) l := let ⟨c, cnonneg, hc⟩ := h.exists_nonneg in (hc.prod_rightr f' cnonneg).is_O lemma is_o.prod_rightr (h : is_o f g' l) : is_o f (λx, (f' x, g' x)) l := λ c cpos, (h cpos).prod_rightr f' (le_of_lt cpos) end lemma is_O_with.prod_left_same (hf : is_O_with c f' k' l) (hg : is_O_with c g' k' l) : is_O_with c (λ x, (f' x, g' x)) k' l := begin filter_upwards [hf, hg], simp only [mem_set_of_eq], exact λ x, max_le end lemma is_O_with.prod_left (hf : is_O_with c f' k' l) (hg : is_O_with c' g' k' l) : is_O_with (max c c') (λ x, (f' x, g' x)) k' l := (hf.weaken $ le_max_left c c').prod_left_same (hg.weaken $ le_max_right c c') lemma is_O_with.prod_left_fst (h : is_O_with c (λ x, (f' x, g' x)) k' l) : is_O_with c f' k' l := (is_O_with_fst_prod.trans h zero_le_one).congr_const $ one_mul c lemma is_O_with.prod_left_snd (h : is_O_with c (λ x, (f' x, g' x)) k' l) : is_O_with c g' k' l := (is_O_with_snd_prod.trans h zero_le_one).congr_const $ one_mul c lemma is_O_with_prod_left : is_O_with c (λ x, (f' x, g' x)) k' l ↔ is_O_with c f' k' l ∧ is_O_with c g' k' l := ⟨λ h, ⟨h.prod_left_fst, h.prod_left_snd⟩, λ h, h.1.prod_left_same h.2⟩ lemma is_O.prod_left (hf : is_O f' k' l) (hg : is_O g' k' l) : is_O (λ x, (f' x, g' x)) k' l := let ⟨c, hf⟩ := hf, ⟨c', hg⟩ := hg in (hf.prod_left hg).is_O lemma is_O.prod_left_fst (h : is_O (λ x, (f' x, g' x)) k' l) : is_O f' k' l := is_O_fst_prod.trans h lemma is_O.prod_left_snd (h : is_O (λ x, (f' x, g' x)) k' l) : is_O g' k' l := is_O_snd_prod.trans h @[simp] lemma is_O_prod_left : is_O (λ x, (f' x, g' x)) k' l ↔ is_O f' k' l ∧ is_O g' k' l := ⟨λ h, ⟨h.prod_left_fst, h.prod_left_snd⟩, λ h, h.1.prod_left h.2⟩ lemma is_o.prod_left (hf : is_o f' k' l) (hg : is_o g' k' l) : is_o (λ x, (f' x, g' x)) k' l := λ c hc, (hf hc).prod_left_same (hg hc) lemma is_o.prod_left_fst (h : is_o (λ x, (f' x, g' x)) k' l) : is_o f' k' l := is_O_fst_prod.trans_is_o h lemma is_o.prod_left_snd (h : is_o (λ x, (f' x, g' x)) k' l) : is_o g' k' l := is_O_snd_prod.trans_is_o h @[simp] lemma is_o_prod_left : is_o (λ x, (f' x, g' x)) k' l ↔ is_o f' k' l ∧ is_o g' k' l := ⟨λ h, ⟨h.prod_left_fst, h.prod_left_snd⟩, λ h, h.1.prod_left h.2⟩ /-! ### Addition and subtraction -/ section add_sub variables {c₁ c₂ : ℝ} {f₁ f₂ : α → E'} theorem is_O_with.add (h₁ : is_O_with c₁ f₁ g l) (h₂ : is_O_with c₂ f₂ g l) : is_O_with (c₁ + c₂) (λ x, f₁ x + f₂ x) g l := by filter_upwards [h₁, h₂] λ x hx₁ hx₂, calc ∥f₁ x + f₂ x∥ ≤ c₁ * ∥g x∥ + c₂ * ∥g x∥ : norm_add_le_of_le hx₁ hx₂ ... = (c₁ + c₂) * ∥g x∥ : (add_mul _ _ _).symm theorem is_O.add : is_O f₁ g l → is_O f₂ g l → is_O (λ x, f₁ x + f₂ x) g l | ⟨c₁, hc₁⟩ ⟨c₂, hc₂⟩ := (hc₁.add hc₂).is_O theorem is_o.add (h₁ : is_o f₁ g l) (h₂ : is_o f₂ g l) : is_o (λ x, f₁ x + f₂ x) g l := λ c cpos, ((h₁ $ half_pos cpos).add (h₂ $ half_pos cpos)).congr_const (add_halves c) theorem is_O.add_is_o (h₁ : is_O f₁ g l) (h₂ : is_o f₂ g l) : is_O (λ x, f₁ x + f₂ x) g l := h₁.add h₂.is_O theorem is_o.add_is_O (h₁ : is_o f₁ g l) (h₂ : is_O f₂ g l) : is_O (λ x, f₁ x + f₂ x) g l := h₁.is_O.add h₂ theorem is_O_with.add_is_o (h₁ : is_O_with c₁ f₁ g l) (h₂ : is_o f₂ g l) (hc : c₁ < c₂) : is_O_with c₂ (λx, f₁ x + f₂ x) g l := (h₁.add (h₂ (sub_pos.2 hc))).congr_const (add_sub_cancel'_right _ _) theorem is_o.add_is_O_with (h₁ : is_o f₁ g l) (h₂ : is_O_with c₁ f₂ g l) (hc : c₁ < c₂) : is_O_with c₂ (λx, f₁ x + f₂ x) g l := (h₂.add_is_o h₁ hc).congr_left $ λ _, add_comm _ _ theorem is_O_with.sub (h₁ : is_O_with c₁ f₁ g l) (h₂ : is_O_with c₂ f₂ g l) : is_O_with (c₁ + c₂) (λ x, f₁ x - f₂ x) g l := h₁.add h₂.neg_left theorem is_O_with.sub_is_o (h₁ : is_O_with c₁ f₁ g l) (h₂ : is_o f₂ g l) (hc : c₁ < c₂) : is_O_with c₂ (λ x, f₁ x - f₂ x) g l := h₁.add_is_o h₂.neg_left hc theorem is_O.sub (h₁ : is_O f₁ g l) (h₂ : is_O f₂ g l) : is_O (λ x, f₁ x - f₂ x) g l := h₁.add h₂.neg_left theorem is_o.sub (h₁ : is_o f₁ g l) (h₂ : is_o f₂ g l) : is_o (λ x, f₁ x - f₂ x) g l := h₁.add h₂.neg_left end add_sub /-! ### Lemmas about `is_O (f₁ - f₂) g l` / `is_o (f₁ - f₂) g l` treated as a binary relation -/ section is_oO_as_rel variables {f₁ f₂ f₃ : α → E'} theorem is_O_with.symm (h : is_O_with c (λ x, f₁ x - f₂ x) g l) : is_O_with c (λ x, f₂ x - f₁ x) g l := h.neg_left.congr_left $ λ x, neg_sub _ _ theorem is_O_with_comm : is_O_with c (λ x, f₁ x - f₂ x) g l ↔ is_O_with c (λ x, f₂ x - f₁ x) g l := ⟨is_O_with.symm, is_O_with.symm⟩ theorem is_O.symm (h : is_O (λ x, f₁ x - f₂ x) g l) : is_O (λ x, f₂ x - f₁ x) g l := h.neg_left.congr_left $ λ x, neg_sub _ _ theorem is_O_comm : is_O (λ x, f₁ x - f₂ x) g l ↔ is_O (λ x, f₂ x - f₁ x) g l := ⟨is_O.symm, is_O.symm⟩ theorem is_o.symm (h : is_o (λ x, f₁ x - f₂ x) g l) : is_o (λ x, f₂ x - f₁ x) g l := by simpa only [neg_sub] using h.neg_left theorem is_o_comm : is_o (λ x, f₁ x - f₂ x) g l ↔ is_o (λ x, f₂ x - f₁ x) g l := ⟨is_o.symm, is_o.symm⟩ theorem is_O_with.triangle (h₁ : is_O_with c (λ x, f₁ x - f₂ x) g l) (h₂ : is_O_with c' (λ x, f₂ x - f₃ x) g l) : is_O_with (c + c') (λ x, f₁ x - f₃ x) g l := (h₁.add h₂).congr_left $ λ x, sub_add_sub_cancel _ _ _ theorem is_O.triangle (h₁ : is_O (λ x, f₁ x - f₂ x) g l) (h₂ : is_O (λ x, f₂ x - f₃ x) g l) : is_O (λ x, f₁ x - f₃ x) g l := (h₁.add h₂).congr_left $ λ x, sub_add_sub_cancel _ _ _ theorem is_o.triangle (h₁ : is_o (λ x, f₁ x - f₂ x) g l) (h₂ : is_o (λ x, f₂ x - f₃ x) g l) : is_o (λ x, f₁ x - f₃ x) g l := (h₁.add h₂).congr_left $ λ x, sub_add_sub_cancel _ _ _ theorem is_O.congr_of_sub (h : is_O (λ x, f₁ x - f₂ x) g l) : is_O f₁ g l ↔ is_O f₂ g l := ⟨λ h', (h'.sub h).congr_left (λ x, sub_sub_cancel _ _), λ h', (h.add h').congr_left (λ x, sub_add_cancel _ _)⟩ theorem is_o.congr_of_sub (h : is_o (λ x, f₁ x - f₂ x) g l) : is_o f₁ g l ↔ is_o f₂ g l := ⟨λ h', (h'.sub h).congr_left (λ x, sub_sub_cancel _ _), λ h', (h.add h').congr_left (λ x, sub_add_cancel _ _)⟩ end is_oO_as_rel /-! ### Zero, one, and other constants -/ section zero_const variables (g' l) theorem is_o_zero : is_o (λ x, (0 : E')) g' l := λ c hc, univ_mem_sets' $ λ x, by simpa using mul_nonneg (le_of_lt hc) (norm_nonneg $ g' x) theorem is_O_with_zero (hc : 0 < c) : is_O_with c (λ x, (0 : E')) g' l := (is_o_zero g' l) hc theorem is_O_zero : is_O (λ x, (0 : E')) g' l := (is_o_zero g' l).is_O theorem is_O_refl_left : is_O (λ x, f' x - f' x) g' l := (is_O_zero g' l).congr_left $ λ x, (sub_self _).symm theorem is_o_refl_left : is_o (λ x, f' x - f' x) g' l := (is_o_zero g' l).congr_left $ λ x, (sub_self _).symm variables {g' l} theorem is_O_with_zero_right_iff : is_O_with c f' (λ x, (0 : F')) l ↔ ∀ᶠ x in l, f' x = 0 := by simp only [is_O_with, exists_prop, true_and, norm_zero, mul_zero, norm_le_zero_iff] theorem is_O_zero_right_iff : is_O f' (λ x, (0 : F')) l ↔ ∀ᶠ x in l, f' x = 0 := ⟨λ h, let ⟨c, hc⟩ := h in (is_O_with_zero_right_iff).1 hc, λ h, (is_O_with_zero_right_iff.2 h : is_O_with 1 _ _ _).is_O⟩ theorem is_o_zero_right_iff : is_o f' (λ x, (0 : F')) l ↔ ∀ᶠ x in l, f' x = 0 := ⟨λ h, is_O_zero_right_iff.1 h.is_O, λ h c hc, is_O_with_zero_right_iff.2 h⟩ theorem is_O_with_const_const (c : E) {c' : F'} (hc' : c' ≠ 0) (l : filter α) : is_O_with (∥c∥ / ∥c'∥) (λ x : α, c) (λ x, c') l := begin apply univ_mem_sets', intro x, rw [mem_set_of_eq, div_mul_cancel], rwa [ne.def, norm_eq_zero] end theorem is_O_const_const (c : E) {c' : F'} (hc' : c' ≠ 0) (l : filter α) : is_O (λ x : α, c) (λ x, c') l := (is_O_with_const_const c hc' l).is_O end zero_const theorem is_O_with_const_one (c : E) (l : filter α) : is_O_with ∥c∥ (λ x : α, c) (λ x, (1 : 𝕜)) l := begin refine (is_O_with_const_const c _ l).congr_const _, { rw [normed_field.norm_one, div_one] }, { exact one_ne_zero } end theorem is_O_const_one (c : E) (l : filter α) : is_O (λ x : α, c) (λ x, (1 : 𝕜)) l := (is_O_with_const_one c l).is_O section variable (𝕜) theorem is_o_const_iff_is_o_one {c : F'} (hc : c ≠ 0) : is_o f (λ x, c) l ↔ is_o f (λ x, (1:𝕜)) l := ⟨λ h, h.trans_is_O $ is_O_const_one c l, λ h, h.trans_is_O $ is_O_const_const _ hc _⟩ end theorem is_o_const_iff {c : F'} (hc : c ≠ 0) : is_o f' (λ x, c) l ↔ tendsto f' l (𝓝 0) := (is_o_const_iff_is_o_one ℝ hc).trans begin clear hc c, simp only [is_o, is_O_with, normed_field.norm_one, mul_one, metric.nhds_basis_closed_ball.tendsto_right_iff, metric.mem_closed_ball, dist_zero_right] end theorem is_O_const_of_tendsto {y : E'} (h : tendsto f' l (𝓝 y)) {c : F'} (hc : c ≠ 0) : is_O f' (λ x, c) l := begin refine is_O.trans _ (is_O_const_const (∥y∥ + 1) hc l), use 1, simp only [is_O_with, one_mul], have : tendsto (λx, ∥f' x∥) l (𝓝 ∥y∥), from (continuous_norm.tendsto _).comp h, have Iy : ∥y∥ < ∥∥y∥ + 1∥, from lt_of_lt_of_le (lt_add_one _) (le_abs_self _), exact this (ge_mem_nhds Iy) end section variable (𝕜) theorem is_o_one_iff : is_o f' (λ x, (1 : 𝕜)) l ↔ tendsto f' l (𝓝 0) := is_o_const_iff one_ne_zero theorem is_O_one_of_tendsto {y : E'} (h : tendsto f' l (𝓝 y)) : is_O f' (λ x, (1:𝕜)) l := is_O_const_of_tendsto h one_ne_zero theorem is_O.trans_tendsto_nhds (hfg : is_O f g' l) {y : F'} (hg : tendsto g' l (𝓝 y)) : is_O f (λ x, (1:𝕜)) l := hfg.trans $ is_O_one_of_tendsto 𝕜 hg end theorem is_O.trans_tendsto (hfg : is_O f' g' l) (hg : tendsto g' l (𝓝 0)) : tendsto f' l (𝓝 0) := (is_o_one_iff ℝ).1 $ hfg.trans_is_o $ (is_o_one_iff ℝ).2 hg theorem is_o.trans_tendsto (hfg : is_o f' g' l) (hg : tendsto g' l (𝓝 0)) : tendsto f' l (𝓝 0) := hfg.is_O.trans_tendsto hg /-! ### Multiplication by a constant -/ theorem is_O_with_const_mul_self (c : R) (f : α → R) (l : filter α) : is_O_with ∥c∥ (λ x, c * f x) f l := is_O_with_of_le' _ $ λ x, norm_mul_le _ _ theorem is_O_const_mul_self (c : R) (f : α → R) (l : filter α) : is_O (λ x, c * f x) f l := (is_O_with_const_mul_self c f l).is_O theorem is_O_with.const_mul_left {f : α → R} (h : is_O_with c f g l) (c' : R) : is_O_with (∥c'∥ * c) (λ x, c' * f x) g l := (is_O_with_const_mul_self c' f l).trans h (norm_nonneg c') theorem is_O.const_mul_left {f : α → R} (h : is_O f g l) (c' : R) : is_O (λ x, c' * f x) g l := let ⟨c, hc⟩ := h in (hc.const_mul_left c').is_O theorem is_O_with_self_const_mul' (u : units R) (f : α → R) (l : filter α) : is_O_with ∥(↑u⁻¹:R)∥ f (λ x, ↑u * f x) l := (is_O_with_const_mul_self ↑u⁻¹ _ l).congr_left $ λ x, u.inv_mul_cancel_left (f x) theorem is_O_with_self_const_mul (c : 𝕜) (hc : c ≠ 0) (f : α → 𝕜) (l : filter α) : is_O_with ∥c∥⁻¹ f (λ x, c * f x) l := (is_O_with_self_const_mul' (units.mk0 c hc) f l).congr_const $ normed_field.norm_inv c theorem is_O_self_const_mul' {c : R} (hc : is_unit c) (f : α → R) (l : filter α) : is_O f (λ x, c * f x) l := let ⟨u, hu⟩ := hc in hu.symm ▸ (is_O_with_self_const_mul' u f l).is_O theorem is_O_self_const_mul (c : 𝕜) (hc : c ≠ 0) (f : α → 𝕜) (l : filter α) : is_O f (λ x, c * f x) l := is_O_self_const_mul' (is_unit.mk0 c hc) f l theorem is_O_const_mul_left_iff' {f : α → R} {c : R} (hc : is_unit c) : is_O (λ x, c * f x) g l ↔ is_O f g l := ⟨(is_O_self_const_mul' hc f l).trans, λ h, h.const_mul_left c⟩ theorem is_O_const_mul_left_iff {f : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : is_O (λ x, c * f x) g l ↔ is_O f g l := is_O_const_mul_left_iff' $ is_unit.mk0 c hc theorem is_o.const_mul_left {f : α → R} (h : is_o f g l) (c : R) : is_o (λ x, c * f x) g l := (is_O_const_mul_self c f l).trans_is_o h theorem is_o_const_mul_left_iff' {f : α → R} {c : R} (hc : is_unit c) : is_o (λ x, c * f x) g l ↔ is_o f g l := ⟨(is_O_self_const_mul' hc f l).trans_is_o, λ h, h.const_mul_left c⟩ theorem is_o_const_mul_left_iff {f : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : is_o (λ x, c * f x) g l ↔ is_o f g l := is_o_const_mul_left_iff' $ is_unit.mk0 c hc theorem is_O_with.of_const_mul_right {g : α → R} {c : R} (hc' : 0 ≤ c') (h : is_O_with c' f (λ x, c * g x) l) : is_O_with (c' * ∥c∥) f g l := h.trans (is_O_with_const_mul_self c g l) hc' theorem is_O.of_const_mul_right {g : α → R} {c : R} (h : is_O f (λ x, c * g x) l) : is_O f g l := let ⟨c, cnonneg, hc⟩ := h.exists_nonneg in (hc.of_const_mul_right cnonneg).is_O theorem is_O_with.const_mul_right' {g : α → R} {u : units R} {c' : ℝ} (hc' : 0 ≤ c') (h : is_O_with c' f g l) : is_O_with (c' * ∥(↑u⁻¹:R)∥) f (λ x, ↑u * g x) l := h.trans (is_O_with_self_const_mul' _ _ _) hc' theorem is_O_with.const_mul_right {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) {c' : ℝ} (hc' : 0 ≤ c') (h : is_O_with c' f g l) : is_O_with (c' * ∥c∥⁻¹) f (λ x, c * g x) l := h.trans (is_O_with_self_const_mul c hc g l) hc' theorem is_O.const_mul_right' {g : α → R} {c : R} (hc : is_unit c) (h : is_O f g l) : is_O f (λ x, c * g x) l := h.trans (is_O_self_const_mul' hc g l) theorem is_O.const_mul_right {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) (h : is_O f g l) : is_O f (λ x, c * g x) l := h.const_mul_right' $ is_unit.mk0 c hc theorem is_O_const_mul_right_iff' {g : α → R} {c : R} (hc : is_unit c) : is_O f (λ x, c * g x) l ↔ is_O f g l := ⟨λ h, h.of_const_mul_right, λ h, h.const_mul_right' hc⟩ theorem is_O_const_mul_right_iff {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : is_O f (λ x, c * g x) l ↔ is_O f g l := is_O_const_mul_right_iff' $ is_unit.mk0 c hc theorem is_o.of_const_mul_right {g : α → R} {c : R} (h : is_o f (λ x, c * g x) l) : is_o f g l := h.trans_is_O (is_O_const_mul_self c g l) theorem is_o.const_mul_right' {g : α → R} {c : R} (hc : is_unit c) (h : is_o f g l) : is_o f (λ x, c * g x) l := h.trans_is_O (is_O_self_const_mul' hc g l) theorem is_o.const_mul_right {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) (h : is_o f g l) : is_o f (λ x, c * g x) l := h.const_mul_right' $ is_unit.mk0 c hc theorem is_o_const_mul_right_iff' {g : α → R} {c : R} (hc : is_unit c) : is_o f (λ x, c * g x) l ↔ is_o f g l := ⟨λ h, h.of_const_mul_right, λ h, h.const_mul_right' hc⟩ theorem is_o_const_mul_right_iff {g : α → 𝕜} {c : 𝕜} (hc : c ≠ 0) : is_o f (λ x, c * g x) l ↔ is_o f g l := is_o_const_mul_right_iff' $ is_unit.mk0 c hc /-! ### Multiplication -/ theorem is_O_with.mul {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} {c₁ c₂ : ℝ} (h₁ : is_O_with c₁ f₁ g₁ l) (h₂ : is_O_with c₂ f₂ g₂ l) : is_O_with (c₁ * c₂) (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := begin filter_upwards [h₁, h₂], simp only [mem_set_of_eq], intros x hx₁ hx₂, apply le_trans (norm_mul_le _ _), convert mul_le_mul hx₁ hx₂ (norm_nonneg _) (le_trans (norm_nonneg _) hx₁) using 1, rw normed_field.norm_mul, ac_refl end theorem is_O.mul {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : is_O f₁ g₁ l) (h₂ : is_O f₂ g₂ l) : is_O (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := let ⟨c, hc⟩ := h₁, ⟨c', hc'⟩ := h₂ in (hc.mul hc').is_O theorem is_O.mul_is_o {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : is_O f₁ g₁ l) (h₂ : is_o f₂ g₂ l) : is_o (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := begin intros c cpos, rcases h₁.exists_pos with ⟨c', c'pos, hc'⟩, exact (hc'.mul (h₂ (div_pos cpos c'pos))).congr_const (mul_div_cancel' _ (ne_of_gt c'pos)) end theorem is_o.mul_is_O {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : is_o f₁ g₁ l) (h₂ : is_O f₂ g₂ l) : is_o (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := begin intros c cpos, rcases h₂.exists_pos with ⟨c', c'pos, hc'⟩, exact ((h₁ (div_pos cpos c'pos)).mul hc').congr_const (div_mul_cancel _ (ne_of_gt c'pos)) end theorem is_o.mul {f₁ f₂ : α → R} {g₁ g₂ : α → 𝕜} (h₁ : is_o f₁ g₁ l) (h₂ : is_o f₂ g₂ l) : is_o (λ x, f₁ x * f₂ x) (λ x, g₁ x * g₂ x) l := h₁.mul_is_O h₂.is_O /-! ### Scalar multiplication -/ section smul_const variables [normed_space 𝕜 E'] theorem is_O_with.const_smul_left (h : is_O_with c f' g l) (c' : 𝕜) : is_O_with (∥c'∥ * c) (λ x, c' • f' x) g l := by refine ((h.norm_left.const_mul_left (∥c'∥)).congr _ _ (λ _, rfl)).of_norm_left; intros; simp only [norm_norm, norm_smul] theorem is_O_const_smul_left_iff {c : 𝕜} (hc : c ≠ 0) : is_O (λ x, c • f' x) g l ↔ is_O f' g l := begin have cne0 : ∥c∥ ≠ 0, from mt norm_eq_zero.mp hc, rw [←is_O_norm_left], simp only [norm_smul], rw [is_O_const_mul_left_iff cne0, is_O_norm_left], end theorem is_o_const_smul_left (h : is_o f' g l) (c : 𝕜) : is_o (λ x, c • f' x) g l := begin refine ((h.norm_left.const_mul_left (∥c∥)).congr_left _).of_norm_left, exact λ x, (norm_smul _ _).symm end theorem is_o_const_smul_left_iff {c : 𝕜} (hc : c ≠ 0) : is_o (λ x, c • f' x) g l ↔ is_o f' g l := begin have cne0 : ∥c∥ ≠ 0, from mt norm_eq_zero.mp hc, rw [←is_o_norm_left], simp only [norm_smul], rw [is_o_const_mul_left_iff cne0, is_o_norm_left] end theorem is_O_const_smul_right {c : 𝕜} (hc : c ≠ 0) : is_O f (λ x, c • f' x) l ↔ is_O f f' l := begin have cne0 : ∥c∥ ≠ 0, from mt norm_eq_zero.mp hc, rw [←is_O_norm_right], simp only [norm_smul], rw [is_O_const_mul_right_iff cne0, is_O_norm_right] end theorem is_o_const_smul_right {c : 𝕜} (hc : c ≠ 0) : is_o f (λ x, c • f' x) l ↔ is_o f f' l := begin have cne0 : ∥c∥ ≠ 0, from mt norm_eq_zero.mp hc, rw [←is_o_norm_right], simp only [norm_smul], rw [is_o_const_mul_right_iff cne0, is_o_norm_right] end end smul_const section smul variables [normed_space 𝕜 E'] [normed_space 𝕜 F'] theorem is_O_with.smul {k₁ k₂ : α → 𝕜} (h₁ : is_O_with c k₁ k₂ l) (h₂ : is_O_with c' f' g' l) : is_O_with (c * c') (λ x, k₁ x • f' x) (λ x, k₂ x • g' x) l := by refine ((h₁.norm_norm.mul h₂.norm_norm).congr rfl _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_O.smul {k₁ k₂ : α → 𝕜} (h₁ : is_O k₁ k₂ l) (h₂ : is_O f' g' l) : is_O (λ x, k₁ x • f' x) (λ x, k₂ x • g' x) l := by refine ((h₁.norm_norm.mul h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_O.smul_is_o {k₁ k₂ : α → 𝕜} (h₁ : is_O k₁ k₂ l) (h₂ : is_o f' g' l) : is_o (λ x, k₁ x • f' x) (λ x, k₂ x • g' x) l := by refine ((h₁.norm_norm.mul_is_o h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_o.smul_is_O {k₁ k₂ : α → 𝕜} (h₁ : is_o k₁ k₂ l) (h₂ : is_O f' g' l) : is_o (λ x, k₁ x • f' x) (λ x, k₂ x • g' x) l := by refine ((h₁.norm_norm.mul_is_O h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] theorem is_o.smul {k₁ k₂ : α → 𝕜} (h₁ : is_o k₁ k₂ l) (h₂ : is_o f' g' l) : is_o (λ x, k₁ x • f' x) (λ x, k₂ x • g' x) l := by refine ((h₁.norm_norm.mul h₂.norm_norm).congr _ _).of_norm_norm; by intros; simp only [norm_smul] end smul /-! ### Relation between `f = o(g)` and `f / g → 0` -/ theorem is_o.tendsto_0 {f g : α → 𝕜} {l : filter α} (h : is_o f g l) : tendsto (λ x, f x / (g x)) l (𝓝 0) := have eq₁ : is_o (λ x, f x / g x) (λ x, g x / g x) l, from h.mul_is_O (is_O_refl _ _), have eq₂ : is_O (λ x, g x / g x) (λ x, (1 : 𝕜)) l, from is_O_of_le _ (λ x, by by_cases h : ∥g x∥ = 0; simp [h, zero_le_one]), (is_o_one_iff 𝕜).mp (eq₁.trans_is_O eq₂) private theorem is_o_of_tendsto {f g : α → 𝕜} {l : filter α} (hgf : ∀ x, g x = 0 → f x = 0) (h : tendsto (λ x, f x / (g x)) l (𝓝 0)) : is_o f g l := have eq₁ : is_o (λ x, f x / (g x)) (λ x, (1 : 𝕜)) l, from (is_o_one_iff _).mpr h, have eq₂ : is_o (λ x, f x / g x * g x) g l, by convert eq₁.mul_is_O (is_O_refl _ _); simp, have eq₃ : is_O f (λ x, f x / g x * g x) l, begin refine is_O_of_le _ (λ x, _), classical, by_cases H : g x = 0, { simp only [H, hgf _ H, mul_zero] }, { simp only [div_mul_cancel _ H] } end, eq₃.trans_is_o eq₂ theorem is_o_iff_tendsto {f g : α → 𝕜} {l : filter α} (hgf : ∀ x, g x = 0 → f x = 0) : is_o f g l ↔ tendsto (λ x, f x / (g x)) l (𝓝 0) := iff.intro is_o.tendsto_0 (is_o_of_tendsto hgf) /-! ### Miscellanous lemmas -/ theorem is_o_pow_pow {m n : ℕ} (h : m < n) : is_o (λ(x : 𝕜), x^n) (λx, x^m) (𝓝 0) := begin let p := n - m, have nmp : n = m + p := (nat.add_sub_cancel' (le_of_lt h)).symm, have : (λ(x : 𝕜), x^m) = (λx, x^m * 1), by simp only [mul_one], simp only [this, pow_add, nmp], refine is_O.mul_is_o (is_O_refl _ _) ((is_o_one_iff _).2 _), convert (continuous_pow p).tendsto (0 : 𝕜), exact (zero_pow (nat.sub_pos_of_lt h)).symm end theorem is_o_pow_id {n : ℕ} (h : 1 < n) : is_o (λ(x : 𝕜), x^n) (λx, x) (𝓝 0) := by { convert is_o_pow_pow h, simp only [pow_one] } theorem is_O_with.right_le_sub_of_lt_1 {f₁ f₂ : α → E'} (h : is_O_with c f₁ f₂ l) (hc : c < 1) : is_O_with (1 / (1 - c)) f₂ (λx, f₂ x - f₁ x) l := mem_sets_of_superset h $ λ x hx, begin simp only [mem_set_of_eq] at hx ⊢, rw [mul_comm, one_div_eq_inv, ← div_eq_mul_inv, le_div_iff, mul_sub, mul_one, mul_comm], { exact le_trans (sub_le_sub_left hx _) (norm_sub_norm_le _ _) }, { exact sub_pos.2 hc } end theorem is_O_with.right_le_add_of_lt_1 {f₁ f₂ : α → E'} (h : is_O_with c f₁ f₂ l) (hc : c < 1) : is_O_with (1 / (1 - c)) f₂ (λx, f₁ x + f₂ x) l := (h.neg_right.right_le_sub_of_lt_1 hc).neg_right.neg_left.congr rfl (λ x, neg_neg _) (λ x, by rw [neg_sub, sub_neg_eq_add]) end asymptotics namespace local_homeomorph variables {α : Type*} {β : Type*} [topological_space α] [topological_space β] variables {E : Type*} [has_norm E] {F : Type*} [has_norm F] open asymptotics /-- Transfer `is_O_with` over a `local_homeomorph`. -/ lemma is_O_with_congr (e : local_homeomorph α β) {b : β} (hb : b ∈ e.target) {f : β → E} {g : β → F} {C : ℝ} : is_O_with C f g (𝓝 b) ↔ is_O_with C (f ∘ e.to_fun) (g ∘ e.to_fun) (𝓝 (e.inv_fun b)) := ⟨λ h, h.comp_tendsto $ by { convert e.continuous_at_to_fun (e.map_target hb), exact (e.right_inv hb).symm }, λ h, (h.comp_tendsto (e.continuous_at_inv_fun hb)).congr' rfl ((e.eventually_right_inverse hb).mono $ λ x hx, congr_arg f hx) ((e.eventually_right_inverse hb).mono $ λ x hx, congr_arg g hx)⟩ /-- Transfer `is_O` over a `local_homeomorph`. -/ lemma is_O_congr (e : local_homeomorph α β) {b : β} (hb : b ∈ e.target) {f : β → E} {g : β → F} : is_O f g (𝓝 b) ↔ is_O (f ∘ e.to_fun) (g ∘ e.to_fun) (𝓝 (e.inv_fun b)) := exists_congr $ λ C, e.is_O_with_congr hb /-- Transfer `is_o` over a `local_homeomorph`. -/ lemma is_o_congr (e : local_homeomorph α β) {b : β} (hb : b ∈ e.target) {f : β → E} {g : β → F} : is_o f g (𝓝 b) ↔ is_o (f ∘ e.to_fun) (g ∘ e.to_fun) (𝓝 (e.inv_fun b)) := forall_congr $ λ c, forall_congr $ λ hc, e.is_O_with_congr hb end local_homeomorph namespace homeomorph variables {α : Type*} {β : Type*} [topological_space α] [topological_space β] variables {E : Type*} [has_norm E] {F : Type*} [has_norm F] open asymptotics /-- Transfer `is_O_with` over a `homeomorph`. -/ lemma is_O_with_congr (e : α ≃ₜ β) {b : β} {f : β → E} {g : β → F} {C : ℝ} : is_O_with C f g (𝓝 b) ↔ is_O_with C (f ∘ e) (g ∘ e) (𝓝 (e.symm b)) := e.to_local_homeomorph.is_O_with_congr trivial /-- Transfer `is_O` over a `homeomorph`. -/ lemma is_O_congr (e : α ≃ₜ β) {b : β} {f : β → E} {g : β → F} : is_O f g (𝓝 b) ↔ is_O (f ∘ e) (g ∘ e) (𝓝 (e.symm b)) := exists_congr $ λ C, e.is_O_with_congr /-- Transfer `is_o` over a `homeomorph`. -/ lemma is_o_congr (e : α ≃ₜ β) {b : β} {f : β → E} {g : β → F} : is_o f g (𝓝 b) ↔ is_o (f ∘ e) (g ∘ e) (𝓝 (e.symm b)) := forall_congr $ λ c, forall_congr $ λ hc, e.is_O_with_congr end homeomorph
16b5d2bb301c3ef7be9ee679c7496f02a82335b8
4d2583807a5ac6caaffd3d7a5f646d61ca85d532
/src/topology/algebra/group_completion.lean
ff86cb07296227adf43c5b156e713de1497547d9
[ "Apache-2.0" ]
permissive
AntoineChambert-Loir/mathlib
64aabb896129885f12296a799818061bc90da1ff
07be904260ab6e36a5769680b6012f03a4727134
refs/heads/master
1,693,187,631,771
1,636,719,886,000
1,636,719,886,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,939
lean
/- Copyright (c) 2018 Patrick Massot. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Patrick Massot, Johannes Hölzl -/ import algebra.group.hom_instances import topology.uniform_space.completion import topology.algebra.uniform_group /-! # Completion of topological groups: This files endows the completion of a topological abelian group with a group structure. More precisely the instance `uniform_space.completion.add_group` builds an abelian group structure on the completion of an abelian group endowed with a compatible uniform structure. Then the instance `uniform_space.completion.uniform_add_group` proves this group structure is compatible with the completed uniform structure. The compatibility condition is `uniform_add_group`. ## Main declarations: Beyond the instances explained above (that don't have to be explicitly invoked), the main constructions deal with continuous group morphisms. * `add_monoid_hom.extension`: extends a continuous group morphism from `G` to a complete separated group `H` to `completion G`. * `add_monoid_hom.completion`: promotes a continuous group morphism from `G` to `H` into a continuous group morphism from `completion G` to `completion H`. -/ noncomputable theory universes u v section group open uniform_space Cauchy filter set variables {α : Type u} [uniform_space α] instance [has_zero α] : has_zero (completion α) := ⟨(0 : α)⟩ instance [has_neg α] : has_neg (completion α) := ⟨completion.map (λa, -a : α → α)⟩ instance [has_add α] : has_add (completion α) := ⟨completion.map₂ (+)⟩ instance [has_sub α] : has_sub (completion α) := ⟨completion.map₂ has_sub.sub⟩ @[norm_cast] lemma uniform_space.completion.coe_zero [has_zero α] : ((0 : α) : completion α) = 0 := rfl end group namespace uniform_space.completion section uniform_add_group open uniform_space uniform_space.completion variables {α : Type*} [uniform_space α] [add_group α] [uniform_add_group α] @[norm_cast] lemma coe_neg (a : α) : ((- a : α) : completion α) = - a := (map_coe uniform_continuous_neg a).symm @[norm_cast] lemma coe_sub (a b : α) : ((a - b : α) : completion α) = a - b := (map₂_coe_coe a b has_sub.sub uniform_continuous_sub).symm @[norm_cast] lemma coe_add (a b : α) : ((a + b : α) : completion α) = a + b := (map₂_coe_coe a b (+) uniform_continuous_add).symm instance : add_monoid (completion α) := { zero_add := assume a, completion.induction_on a (is_closed_eq (continuous_map₂ continuous_const continuous_id) continuous_id) (assume a, show 0 + (a : completion α) = a, by rw_mod_cast zero_add), add_zero := assume a, completion.induction_on a (is_closed_eq (continuous_map₂ continuous_id continuous_const) continuous_id) (assume a, show (a : completion α) + 0 = a, by rw_mod_cast add_zero), add_assoc := assume a b c, completion.induction_on₃ a b c (is_closed_eq (continuous_map₂ (continuous_map₂ continuous_fst (continuous_fst.comp continuous_snd)) (continuous_snd.comp continuous_snd)) (continuous_map₂ continuous_fst (continuous_map₂ (continuous_fst.comp continuous_snd) (continuous_snd.comp continuous_snd)))) (assume a b c, show (a : completion α) + b + c = a + (b + c), by repeat { rw_mod_cast add_assoc }), .. completion.has_zero, .. completion.has_neg, ..completion.has_add, .. completion.has_sub } instance : sub_neg_monoid (completion α) := { sub_eq_add_neg := λ a b, completion.induction_on₂ a b (is_closed_eq (continuous_map₂ continuous_fst continuous_snd) (continuous_map₂ continuous_fst (continuous_map.comp continuous_snd))) (λ a b, by exact_mod_cast congr_arg coe (sub_eq_add_neg a b)), .. completion.add_monoid, .. completion.has_neg, .. completion.has_sub } instance : add_group (completion α) := { add_left_neg := assume a, completion.induction_on a (is_closed_eq (continuous_map₂ completion.continuous_map continuous_id) continuous_const) (assume a, show - (a : completion α) + a = 0, by { rw_mod_cast add_left_neg, refl }), .. completion.sub_neg_monoid } instance : uniform_add_group (completion α) := ⟨uniform_continuous_map₂ has_sub.sub⟩ /-- The map from a group to its completion as a group hom. -/ @[simps] def to_compl : α →+ completion α := { to_fun := coe, map_add' := coe_add, map_zero' := coe_zero } lemma continuous_to_compl : continuous (to_compl : α → completion α) := continuous_coe α variables {β : Type v} [uniform_space β] [add_group β] [uniform_add_group β] instance {α : Type u} [uniform_space α] [add_comm_group α] [uniform_add_group α] : add_comm_group (completion α) := { add_comm := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_map₂ continuous_fst continuous_snd) (continuous_map₂ continuous_snd continuous_fst)) (assume x y, by { change ↑x + ↑y = ↑y + ↑x, rw [← coe_add, ← coe_add, add_comm]}), .. completion.add_group } end uniform_add_group end uniform_space.completion section add_monoid_hom variables {α β : Type*} [uniform_space α] [add_group α] [uniform_add_group α] [uniform_space β] [add_group β] [uniform_add_group β] open uniform_space uniform_space.completion /-- Extension to the completion of a continuous group hom. -/ def add_monoid_hom.extension [complete_space β] [separated_space β] (f : α →+ β) (hf : continuous f) : completion α →+ β := have hf : uniform_continuous f, from uniform_continuous_of_continuous hf, { to_fun := completion.extension f, map_zero' := by rw [← coe_zero, extension_coe hf, f.map_zero], map_add' := assume a b, completion.induction_on₂ a b (is_closed_eq (continuous_extension.comp continuous_add) ((continuous_extension.comp continuous_fst).add (continuous_extension.comp continuous_snd))) (λ a b, by rw_mod_cast [extension_coe hf, extension_coe hf, extension_coe hf, f.map_add]) } lemma add_monoid_hom.extension_coe [complete_space β] [separated_space β] (f : α →+ β) (hf : continuous f) (a : α) : f.extension hf a = f a := extension_coe (uniform_continuous_of_continuous hf) a @[continuity] lemma add_monoid_hom.continuous_extension [complete_space β] [separated_space β] (f : α →+ β) (hf : continuous f) : continuous (f.extension hf) := continuous_extension /-- Completion of a continuous group hom, as a group hom. -/ def add_monoid_hom.completion (f : α →+ β) (hf : continuous f) : completion α →+ completion β := (to_compl.comp f).extension (continuous_to_compl.comp hf) @[continuity] lemma add_monoid_hom.continuous_completion (f : α →+ β) (hf : continuous f) : continuous (f.completion hf : completion α → completion β) := continuous_map lemma add_monoid_hom.completion_coe (f : α →+ β) (hf : continuous f) (a : α) : f.completion hf a = f a := map_coe (uniform_continuous_of_continuous hf) a lemma add_monoid_hom.completion_zero : (0 : α →+ β).completion continuous_const = 0 := begin ext x, apply completion.induction_on x, { apply is_closed_eq ((0 : α →+ β).continuous_completion continuous_const), simp [continuous_const] }, { intro a, simp [(0 : α →+ β).completion_coe continuous_const, coe_zero] } end lemma add_monoid_hom.completion_add {γ : Type*} [add_comm_group γ] [uniform_space γ] [uniform_add_group γ] (f g : α →+ γ) (hf : continuous f) (hg : continuous g) : (f + g).completion (hf.add hg) = f.completion hf + g.completion hg := begin have hfg := hf.add hg, ext x, apply completion.induction_on x, { exact is_closed_eq ((f+g).continuous_completion hfg) ((f.continuous_completion hf).add (g.continuous_completion hg)) }, { intro a, simp [(f+g).completion_coe hfg, coe_add, f.completion_coe hf, g.completion_coe hg] } end end add_monoid_hom
a2fad626a015c7baba5fa029b38ea316ccb56696
bb31430994044506fa42fd667e2d556327e18dfe
/src/number_theory/divisors.lean
e239857c3e6ad976264c22885d36784419d31717
[ "Apache-2.0" ]
permissive
sgouezel/mathlib
0cb4e5335a2ba189fa7af96d83a377f83270e503
00638177efd1b2534fc5269363ebf42a7871df9a
refs/heads/master
1,674,527,483,042
1,673,665,568,000
1,673,665,568,000
119,598,202
0
0
null
1,517,348,647,000
1,517,348,646,000
null
UTF-8
Lean
false
false
16,197
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.order import data.nat.interval import data.nat.factors /-! # 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 `n` is positive and the sum of `proper_divisors n` is `n`. ## Implementation details * `divisors 0`, `proper_divisors 0`, and `divisors_antidiagonal 0` are defined to be `∅`. ## Tags divisors, perfect numbers -/ open_locale classical open_locale big_operators open finset namespace nat variable (n : ℕ) /-- `divisors n` is the `finset` of divisors of `n`. As a special case, `divisors 0 = ∅`. -/ def divisors : finset ℕ := finset.filter (λ x : ℕ, x ∣ n) (finset.Ico 1 (n + 1)) /-- `proper_divisors n` is the `finset` of divisors of `n`, other than `n`. As a special case, `proper_divisors 0 = ∅`. -/ def proper_divisors : finset ℕ := finset.filter (λ x : ℕ, x ∣ n) (finset.Ico 1 n) /-- `divisors_antidiagonal n` is the `finset` of pairs `(x,y)` such that `x * y = n`. As a special case, `divisors_antidiagonal 0 = ∅`. -/ def divisors_antidiagonal : finset (ℕ × ℕ) := (Ico 1 (n + 1) ×ˢ Ico 1 (n + 1)).filter (λ x, x.fst * x.snd = n) variable {n} @[simp] lemma filter_dvd_eq_divisors (h : n ≠ 0) : (finset.range n.succ).filter (∣ n) = n.divisors := begin ext, simp only [divisors, mem_filter, mem_range, mem_Ico, and.congr_left_iff, iff_and_self], exact λ ha _, succ_le_iff.mpr (pos_of_dvd_of_pos ha h.bot_lt), end @[simp] lemma filter_dvd_eq_proper_divisors (h : n ≠ 0) : (finset.range n).filter (∣ n) = n.proper_divisors := begin ext, simp only [proper_divisors, mem_filter, mem_range, mem_Ico, and.congr_left_iff, iff_and_self], exact λ ha _, succ_le_iff.mpr (pos_of_dvd_of_pos ha h.bot_lt), end lemma proper_divisors.not_self_mem : ¬ n ∈ proper_divisors n := by simp [proper_divisors] @[simp] lemma mem_proper_divisors {m : ℕ} : n ∈ proper_divisors m ↔ n ∣ m ∧ n < m := begin rcases eq_or_ne m 0 with rfl | hm, { simp [proper_divisors] }, simp only [and_comm, ←filter_dvd_eq_proper_divisors hm, mem_filter, mem_range], end lemma divisors_eq_proper_divisors_insert_self_of_pos (h : 0 < n): divisors n = has_insert.insert n (proper_divisors n) := by rw [divisors, proper_divisors, Ico_succ_right_eq_insert_Ico h, finset.filter_insert, if_pos (dvd_refl n)] @[simp] lemma mem_divisors {m : ℕ} : n ∈ divisors m ↔ (n ∣ m ∧ m ≠ 0) := begin rcases eq_or_ne m 0 with rfl | hm, { simp [divisors] }, simp only [hm, ne.def, not_false_iff, and_true, ←filter_dvd_eq_divisors hm, mem_filter, mem_range, and_iff_right_iff_imp, lt_succ_iff], exact le_of_dvd hm.bot_lt, end lemma one_mem_divisors : 1 ∈ divisors n ↔ n ≠ 0 := by simp lemma mem_divisors_self (n : ℕ) (h : n ≠ 0) : n ∈ n.divisors := mem_divisors.2 ⟨dvd_rfl, h⟩ lemma dvd_of_mem_divisors {m : ℕ} (h : n ∈ divisors m) : n ∣ m := begin cases m, { apply dvd_zero }, { simp [mem_divisors.1 h], } end @[simp] lemma mem_divisors_antidiagonal {x : ℕ × ℕ} : x ∈ divisors_antidiagonal n ↔ x.fst * x.snd = n ∧ n ≠ 0 := begin simp only [divisors_antidiagonal, finset.mem_Ico, ne.def, finset.mem_filter, finset.mem_product], rw and_comm, apply and_congr_right, rintro rfl, split; intro h, { contrapose! h, simp [h], }, { rw [nat.lt_add_one_iff, nat.lt_add_one_iff], rw [mul_eq_zero, decidable.not_or_iff_and_not] at h, simp only [succ_le_of_lt (nat.pos_of_ne_zero h.1), succ_le_of_lt (nat.pos_of_ne_zero h.2), true_and], exact ⟨le_mul_of_pos_right (nat.pos_of_ne_zero h.2), le_mul_of_pos_left (nat.pos_of_ne_zero h.1)⟩ } end variable {n} lemma divisor_le {m : ℕ}: n ∈ divisors m → n ≤ m := begin cases m, { simp }, simp only [mem_divisors, m.succ_ne_zero, and_true, ne.def, not_false_iff], exact nat.le_of_dvd (nat.succ_pos m), end lemma divisors_subset_of_dvd {m : ℕ} (hzero : n ≠ 0) (h : m ∣ n) : divisors m ⊆ divisors n := finset.subset_iff.2 $ λ x hx, nat.mem_divisors.mpr (⟨(nat.mem_divisors.mp hx).1.trans h, hzero⟩) lemma divisors_subset_proper_divisors {m : ℕ} (hzero : n ≠ 0) (h : m ∣ n) (hdiff : m ≠ n) : divisors m ⊆ proper_divisors n := begin apply finset.subset_iff.2, intros x hx, exact nat.mem_proper_divisors.2 (⟨(nat.mem_divisors.1 hx).1.trans h, lt_of_le_of_lt (divisor_le hx) (lt_of_le_of_ne (divisor_le (nat.mem_divisors.2 ⟨h, hzero⟩)) hdiff)⟩) end @[simp] lemma divisors_zero : divisors 0 = ∅ := by { ext, simp } @[simp] lemma proper_divisors_zero : proper_divisors 0 = ∅ := by { ext, simp } lemma proper_divisors_subset_divisors : proper_divisors n ⊆ divisors n := filter_subset_filter _ $ Ico_subset_Ico_right n.le_succ @[simp] lemma divisors_one : divisors 1 = {1} := by { ext, simp } @[simp] lemma proper_divisors_one : proper_divisors 1 = ∅ := by rw [proper_divisors, Ico_self, filter_empty] lemma pos_of_mem_divisors {m : ℕ} (h : m ∈ n.divisors) : 0 < m := begin cases m, { rw [mem_divisors, zero_dvd_iff] at h, cases h.2 h.1 }, apply nat.succ_pos, end lemma pos_of_mem_proper_divisors {m : ℕ} (h : m ∈ n.proper_divisors) : 0 < m := pos_of_mem_divisors (proper_divisors_subset_divisors h) lemma one_mem_proper_divisors_iff_one_lt : 1 ∈ n.proper_divisors ↔ 1 < n := by rw [mem_proper_divisors, and_iff_right (one_dvd _)] @[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], } @[simp] lemma swap_mem_divisors_antidiagonal {x : ℕ × ℕ} : x.swap ∈ divisors_antidiagonal n ↔ x ∈ divisors_antidiagonal n := by rw [mem_divisors_antidiagonal, mem_divisors_antidiagonal, mul_comm, prod.swap] lemma fst_mem_divisors_of_mem_antidiagonal {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 {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 : (divisors_antidiagonal n).map (equiv.prod_comm _ _).to_embedding = divisors_antidiagonal n := begin rw [← coe_inj, coe_map, equiv.coe_to_embedding, equiv.coe_prod_comm, set.image_swap_eq_preimage_swap], ext, exact swap_mem_divisors_antidiagonal, end @[simp] lemma image_fst_divisors_antidiagonal : (divisors_antidiagonal n).image prod.fst = divisors n := by { ext, simp [has_dvd.dvd, @eq_comm _ n (_ * _)] } @[simp] lemma image_snd_divisors_antidiagonal : (divisors_antidiagonal n).image prod.snd = divisors n := begin rw [←map_swap_divisors_antidiagonal, map_eq_image, image_image], exact image_fst_divisors_antidiagonal end lemma map_div_right_divisors : n.divisors.map ⟨λ d, (d, n/d), λ p₁ p₂, congr_arg prod.fst⟩ = n.divisors_antidiagonal := begin ext ⟨d, nd⟩, simp only [mem_map, mem_divisors_antidiagonal, function.embedding.coe_fn_mk, mem_divisors, prod.ext_iff, exists_prop, and.left_comm, exists_eq_left], split, { rintro ⟨⟨⟨k, rfl⟩, hn⟩, rfl⟩, rw [nat.mul_div_cancel_left _ (left_ne_zero_of_mul hn).bot_lt], exact ⟨rfl, hn⟩ }, { rintro ⟨rfl, hn⟩, exact ⟨⟨dvd_mul_right _ _, hn⟩, nat.mul_div_cancel_left _ (left_ne_zero_of_mul hn).bot_lt⟩ } end lemma map_div_left_divisors : n.divisors.map ⟨λ d, (n/d, d), λ p₁ p₂, congr_arg prod.snd⟩ = n.divisors_antidiagonal := begin apply finset.map_injective (equiv.prod_comm _ _).to_embedding, rw [map_swap_divisors_antidiagonal, ←map_div_right_divisors, finset.map_map], refl, end lemma sum_divisors_eq_sum_proper_divisors_add_self : ∑ i in divisors n, i = ∑ i in proper_divisors n, i + n := begin cases n, { simp }, { rw [divisors_eq_proper_divisors_insert_self_of_pos (nat.succ_pos _), finset.sum_insert (proper_divisors.not_self_mem), add_comm] } end /-- `n : ℕ` is perfect if and only the sum of the proper divisors of `n` is `n` and `n` is positive. -/ def perfect (n : ℕ) : Prop := (∑ i in proper_divisors n, i = n) ∧ 0 < n theorem perfect_iff_sum_proper_divisors (h : 0 < n) : perfect n ↔ ∑ i in proper_divisors n, i = n := and_iff_left h theorem perfect_iff_sum_divisors_eq_two_mul (h : 0 < n) : perfect n ↔ ∑ i in divisors n, i = 2 * n := begin rw [perfect_iff_sum_proper_divisors h, sum_divisors_eq_sum_proper_divisors_add_self, two_mul], split; intro h, { rw h }, { apply add_right_cancel h } end lemma mem_divisors_prime_pow {p : ℕ} (pp : p.prime) (k : ℕ) {x : ℕ} : x ∈ divisors (p ^ k) ↔ ∃ (j : ℕ) (H : j ≤ k), x = p ^ j := by rw [mem_divisors, nat.dvd_prime_pow pp, and_iff_left (ne_of_gt (pow_pos pp.pos k))] lemma prime.divisors {p : ℕ} (pp : p.prime) : divisors p = {1, p} := begin ext, rw [mem_divisors, dvd_prime pp, and_iff_left pp.ne_zero, finset.mem_insert, finset.mem_singleton] end lemma prime.proper_divisors {p : ℕ} (pp : p.prime) : proper_divisors p = {1} := by rw [← erase_insert (proper_divisors.not_self_mem), ← divisors_eq_proper_divisors_insert_self_of_pos pp.pos, pp.divisors, pair_comm, erase_insert (λ con, pp.ne_one (mem_singleton.1 con))] lemma divisors_prime_pow {p : ℕ} (pp : p.prime) (k : ℕ) : divisors (p ^ k) = (finset.range (k + 1)).map ⟨pow p, pow_right_injective pp.two_le⟩ := by { ext, simp [mem_divisors_prime_pow, pp, nat.lt_succ_iff, @eq_comm _ a] } lemma eq_proper_divisors_of_subset_of_sum_eq_sum {s : finset ℕ} (hsub : s ⊆ n.proper_divisors) : ∑ x in s, x = ∑ x in n.proper_divisors, x → s = n.proper_divisors := begin cases n, { rw [proper_divisors_zero, subset_empty] at hsub, simp [hsub] }, classical, rw [← sum_sdiff hsub], intros h, apply subset.antisymm hsub, rw [← sdiff_eq_empty_iff_subset], contrapose h, rw [← ne.def, ← nonempty_iff_ne_empty] at h, apply ne_of_lt, rw [← zero_add (∑ x in s, x), ← add_assoc, add_zero], apply add_lt_add_right, have hlt := sum_lt_sum_of_nonempty h (λ x hx, pos_of_mem_proper_divisors (sdiff_subset _ _ hx)), simp only [sum_const_zero] at hlt, apply hlt end lemma sum_proper_divisors_dvd (h : ∑ x in n.proper_divisors, x ∣ n) : (∑ x in n.proper_divisors, x = 1) ∨ (∑ x in n.proper_divisors, x = n) := begin cases n, { simp }, cases n, { contrapose! h, simp, }, rw or_iff_not_imp_right, intro ne_n, have hlt : ∑ x in n.succ.succ.proper_divisors, x < n.succ.succ := lt_of_le_of_ne (nat.le_of_dvd (nat.succ_pos _) h) ne_n, symmetry, rw [← mem_singleton, eq_proper_divisors_of_subset_of_sum_eq_sum (singleton_subset_iff.2 (mem_proper_divisors.2 ⟨h, hlt⟩)) sum_singleton, mem_proper_divisors], refine ⟨one_dvd _, nat.succ_lt_succ (nat.succ_pos _)⟩, end @[simp, to_additive] lemma prime.prod_proper_divisors {α : Type*} [comm_monoid α] {p : ℕ} {f : ℕ → α} (h : p.prime) : ∏ x in p.proper_divisors, f x = f 1 := by simp [h.proper_divisors] @[simp, to_additive] lemma prime.prod_divisors {α : Type*} [comm_monoid α] {p : ℕ} {f : ℕ → α} (h : p.prime) : ∏ x in p.divisors, f x = f p * f 1 := by rw [divisors_eq_proper_divisors_insert_self_of_pos h.pos, prod_insert proper_divisors.not_self_mem, h.prod_proper_divisors] lemma proper_divisors_eq_singleton_one_iff_prime : n.proper_divisors = {1} ↔ n.prime := ⟨λ h, begin have h1 := mem_singleton.2 rfl, rw [← h, mem_proper_divisors] at h1, refine nat.prime_def_lt''.mpr ⟨h1.2, λ m hdvd, _⟩, rw [← mem_singleton, ← h, mem_proper_divisors], have hle := nat.le_of_dvd (lt_trans (nat.succ_pos _) h1.2) hdvd, exact or.imp_left (λ hlt, ⟨hdvd, hlt⟩) hle.lt_or_eq end, prime.proper_divisors⟩ lemma sum_proper_divisors_eq_one_iff_prime : ∑ x in n.proper_divisors, x = 1 ↔ n.prime := begin cases n, { simp [nat.not_prime_zero] }, cases n, { simp [nat.not_prime_one] }, rw [← proper_divisors_eq_singleton_one_iff_prime], refine ⟨λ h, _, λ h, h.symm ▸ sum_singleton⟩, rw [@eq_comm (finset ℕ) _ _], apply eq_proper_divisors_of_subset_of_sum_eq_sum (singleton_subset_iff.2 (one_mem_proper_divisors_iff_one_lt.2 (succ_lt_succ (nat.succ_pos _)))) (eq.trans sum_singleton h.symm) end lemma mem_proper_divisors_prime_pow {p : ℕ} (pp : p.prime) (k : ℕ) {x : ℕ} : x ∈ proper_divisors (p ^ k) ↔ ∃ (j : ℕ) (H : j < k), x = p ^ j := begin rw [mem_proper_divisors, nat.dvd_prime_pow pp, ← exists_and_distrib_right], simp only [exists_prop, and_assoc], apply exists_congr, intro a, split; intro h, { rcases h with ⟨h_left, rfl, h_right⟩, rwa pow_lt_pow_iff pp.one_lt at h_right, simpa, }, { rcases h with ⟨h_left, rfl⟩, rwa pow_lt_pow_iff pp.one_lt, simp [h_left, le_of_lt], }, end lemma proper_divisors_prime_pow {p : ℕ} (pp : p.prime) (k : ℕ) : proper_divisors (p ^ k) = (finset.range k).map ⟨pow p, pow_right_injective pp.two_le⟩ := by { ext, simp [mem_proper_divisors_prime_pow, pp, nat.lt_succ_iff, @eq_comm _ a], } @[simp, to_additive] lemma prod_proper_divisors_prime_pow {α : Type*} [comm_monoid α] {k p : ℕ} {f : ℕ → α} (h : p.prime) : ∏ x in (p ^ k).proper_divisors, f x = ∏ x in range k, f (p ^ x) := by simp [h, proper_divisors_prime_pow] @[simp, to_additive sum_divisors_prime_pow] lemma prod_divisors_prime_pow {α : Type*} [comm_monoid α] {k p : ℕ} {f : ℕ → α} (h : p.prime) : ∏ x in (p ^ k).divisors, f x = ∏ x in range (k + 1), f (p ^ x) := by simp [h, divisors_prime_pow] @[to_additive] lemma prod_divisors_antidiagonal {M : Type*} [comm_monoid M] (f : ℕ → ℕ → M) {n : ℕ} : ∏ i in n.divisors_antidiagonal, f i.1 i.2 = ∏ i in n.divisors, f i (n / i) := begin rw [←map_div_right_divisors, finset.prod_map], refl, end @[to_additive] lemma prod_divisors_antidiagonal' {M : Type*} [comm_monoid M] (f : ℕ → ℕ → M) {n : ℕ} : ∏ i in n.divisors_antidiagonal, f i.1 i.2 = ∏ i in n.divisors, f (n / i) i := begin rw [←map_swap_divisors_antidiagonal, finset.prod_map], exact prod_divisors_antidiagonal (λ i j, f j i), end /-- The factors of `n` are the prime divisors -/ lemma prime_divisors_eq_to_filter_divisors_prime (n : ℕ) : n.factors.to_finset = (divisors n).filter prime := begin rcases n.eq_zero_or_pos with rfl | hn, { simp }, { ext q, simpa [hn, hn.ne', mem_factors] using and_comm (prime q) (q ∣ n) } end @[simp] lemma image_div_divisors_eq_divisors (n : ℕ) : image (λ (x : ℕ), n / x) n.divisors = n.divisors := begin by_cases hn : n = 0, { simp [hn] }, ext, split, { rw mem_image, rintros ⟨x, hx1, hx2⟩, rw mem_divisors at *, refine ⟨_,hn⟩, rw ←hx2, exact div_dvd_of_dvd hx1.1 }, { rw [mem_divisors, mem_image], rintros ⟨h1, -⟩, exact ⟨n/a, mem_divisors.mpr ⟨div_dvd_of_dvd h1, hn⟩, nat.div_div_self h1 hn⟩ }, end @[simp, to_additive sum_div_divisors] lemma prod_div_divisors {α : Type*} [comm_monoid α] (n : ℕ) (f : ℕ → α) : ∏ d in n.divisors, f (n/d) = n.divisors.prod f := begin by_cases hn : n = 0, { simp [hn] }, rw ←prod_image, { exact prod_congr (image_div_divisors_eq_divisors n) (by simp) }, { intros x hx y hy h, rw mem_divisors at hx hy, exact (div_eq_iff_eq_of_dvd_dvd hn hx.1 hy.1).mp h } end end nat
e2b6e2cc1b2ed59b268fe86d2e39e8c4c604f7f5
95dcf8dea2baf2b4b0a60d438f27c35ae3dd3990
/src/category_theory/types.lean
c4f0d3f1de79df88805392db81939e7c9af69c19
[ "Apache-2.0" ]
permissive
uniformity1/mathlib
829341bad9dfa6d6be9adaacb8086a8a492e85a4
dd0e9bd8f2e5ec267f68e72336f6973311909105
refs/heads/master
1,588,592,015,670
1,554,219,842,000
1,554,219,842,000
179,110,702
0
0
Apache-2.0
1,554,220,076,000
1,554,220,076,000
null
UTF-8
Lean
false
false
3,110
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 import category_theory.functor_category import category_theory.fully_faithful namespace category_theory universes v v' w u u' -- declare the `v`'s first; see `category_theory.category` for an explanation instance types : large_category (Sort u) := { hom := λ a b, (a → b), id := λ a, id, comp := λ _ _ _ f g, g ∘ f } @[simp] lemma types_hom {α β : Sort u} : (α ⟶ β) = (α → β) := rfl @[simp] lemma types_id {α : Sort u} (a : α) : (𝟙 α : α → α) a = a := rfl @[simp] lemma types_comp {α β γ : Sort u} (f : α → β) (g : β → γ) (a : α) : (((f : α ⟶ β) ≫ (g : β ⟶ γ)) : α ⟶ γ) a = g (f a) := rfl namespace functor_to_types variables {C : Sort u} [𝒞 : category.{v} C] (F G H : C ⥤ Sort w) {X Y Z : C} include 𝒞 variables (σ : F ⟹ G) (τ : G ⟹ H) @[simp] lemma map_comp (f : X ⟶ Y) (g : Y ⟶ Z) (a : F.obj X) : (F.map (f ≫ g)) a = (F.map g) ((F.map f) a) := by simp @[simp] lemma map_id (a : F.obj X) : (F.map (𝟙 X)) a = a := by simp lemma naturality (f : X ⟶ Y) (x : F.obj X) : σ.app Y ((F.map f) x) = (G.map f) (σ.app X x) := congr_fun (σ.naturality f) x @[simp] lemma vcomp (x : F.obj X) : (σ ⊟ τ).app X x = τ.app X (σ.app X x) := rfl variables {D : Sort u'} [𝒟 : category.{u'} D] (I J : D ⥤ C) (ρ : I ⟹ J) {W : D} @[simp] lemma hcomp (x : (I ⋙ F).obj W) : (ρ ◫ σ).app W x = (G.map (ρ.app W)) (σ.app (I.obj W) x) := rfl end functor_to_types def ulift_trivial (V : Type u) : ulift.{u} V ≅ V := by tidy def ulift_functor : Type u ⥤ Type (max u v) := { obj := λ X, ulift.{v} X, map := λ X Y f, λ x : ulift.{v} X, ulift.up (f x.down) } @[simp] lemma ulift_functor.map {X Y : Type u} (f : X ⟶ Y) (x : ulift.{v} X) : ulift_functor.map f x = ulift.up (f x.down) := rfl instance ulift_functor_faithful : fully_faithful ulift_functor := { preimage := λ X Y f x, (f (ulift.up x)).down, injectivity' := λ X Y f g p, funext $ λ x, congr_arg ulift.down ((congr_fun p (ulift.up x)) : ((ulift.up (f x)) = (ulift.up (g x)))) } end category_theory -- Isomorphisms in Type and equivalences. namespace equiv universe u variables {X Y : Sort u} def to_iso (e : X ≃ Y) : X ≅ Y := { hom := e.to_fun, inv := e.inv_fun, hom_inv_id' := funext e.left_inv, inv_hom_id' := funext e.right_inv } @[simp] lemma to_iso_hom {e : X ≃ Y} : e.to_iso.hom = e := rfl @[simp] lemma to_iso_inv {e : X ≃ Y} : e.to_iso.inv = e.symm := rfl end equiv namespace category_theory.iso universe u variables {X Y : Sort u} def to_equiv (i : X ≅ Y) : X ≃ Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := λ x, congr_fun i.hom_inv_id x, right_inv := λ y, congr_fun i.inv_hom_id y } @[simp] lemma to_equiv_fun (i : X ≅ Y) : (i.to_equiv : X → Y) = i.hom := rfl @[simp] lemma to_equiv_symm_fun (i : X ≅ Y) : (i.to_equiv.symm : Y → X) = i.inv := rfl end category_theory.iso
7639c967b42d2da640b2dfec991306de9c04b4ee
b3fced0f3ff82d577384fe81653e47df68bb2fa1
/src/category_theory/monad/algebra.lean
b0468a3be32e7440b9661eb43f046fc6c987b675
[ "Apache-2.0" ]
permissive
ratmice/mathlib
93b251ef5df08b6fd55074650ff47fdcc41a4c75
3a948a6a4cd5968d60e15ed914b1ad2f4423af8d
refs/heads/master
1,599,240,104,318
1,572,981,183,000
1,572,981,183,000
219,830,178
0
0
Apache-2.0
1,572,980,897,000
1,572,980,896,000
null
UTF-8
Lean
false
false
3,286
lean
/- Copyright (c) 2019 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import category_theory.monad.basic import category_theory.adjunction.basic /-! # Eilenberg-Moore algebras for a monad This file defines Eilenberg-Moore algebras for a monad, and provides the category instance for them. Further it defines the adjoint pair of free and forgetful functors, respectively from and to the original category. ## References * [Riehl, *Category theory in context*, Section 5.2.4][riehl2017] -/ namespace category_theory open category universes v₁ u₁ -- declare the `v`'s first; see `category_theory.category` for an explanation variables {C : Type u₁} [𝒞 : category.{v₁} C] include 𝒞 namespace monad /-- An Eilenberg-Moore algebra for a monad `T`. cf Definition 5.2.3 in [Riehl][riehl2017]. -/ structure algebra (T : C ⥤ C) [monad.{v₁} T] : Type (max u₁ v₁) := (A : C) (a : T.obj A ⟶ A) (unit' : (η_ T).app A ≫ a = 𝟙 A . obviously) (assoc' : ((μ_ T).app A ≫ a) = (T.map a ≫ a) . obviously) restate_axiom algebra.unit' restate_axiom algebra.assoc' namespace algebra variables {T : C ⥤ C} [monad.{v₁} T] structure hom (A B : algebra T) := (f : A.A ⟶ B.A) (h' : T.map f ≫ B.a = A.a ≫ f . obviously) restate_axiom hom.h' attribute [simp] hom.h namespace hom @[extensionality] lemma ext {A B : algebra T} (f g : hom A B) (w : f.f = g.f) : f = g := by { cases f, cases g, congr, assumption } @[simps] def id (A : algebra T) : hom A A := { f := 𝟙 A.A } @[simps] def comp {P Q R : algebra T} (f : hom P Q) (g : hom Q R) : hom P R := { f := f.f ≫ g.f, h' := by rw [functor.map_comp, category.assoc, g.h, ←category.assoc, f.h, category.assoc] } end hom /-- The category of Eilenberg-Moore algebras for a monad. cf Definition 5.2.4 in [Riehl][riehl2017]. -/ @[simps] instance EilenbergMoore : category (algebra T) := { hom := hom, id := hom.id, comp := @hom.comp _ _ _ _ } end algebra variables (T : C ⥤ C) [monad.{v₁} T] @[simps] def forget : algebra T ⥤ C := { obj := λ A, A.A, map := λ A B f, f.f } @[simps] def free : C ⥤ algebra T := { obj := λ X, { A := T.obj X, a := (μ_ T).app X, assoc' := (monad.assoc T _).symm }, map := λ X Y f, { f := T.map f, h' := by erw (μ_ T).naturality } } /-- The adjunction between the free and forgetful constructions for Eilenberg-Moore algebras for a monad. cf Lemma 5.2.8 of [Riehl][riehl2017]. -/ def adj : free T ⊣ forget T := adjunction.mk_of_hom_equiv { hom_equiv := λ X Y, { to_fun := λ f, (η_ T).app X ≫ f.f, inv_fun := λ f, { f := T.map f ≫ Y.a, h' := begin dsimp, simp, conv { to_rhs, rw [←category.assoc, ←(μ_ T).naturality, category.assoc], erw algebra.assoc }, refl, end }, left_inv := λ f, begin ext1, dsimp, simp only [free_obj_a, functor.map_comp, algebra.hom.h, category.assoc], erw [←category.assoc, monad.right_unit, id_comp], end, right_inv := λ f, begin dsimp, erw [←category.assoc, ←(η_ T).naturality, functor.id_map, category.assoc, Y.unit, comp_id], end }} end monad end category_theory
4e47a652dffb71291817761c4ff382c3437be8b3
c777c32c8e484e195053731103c5e52af26a25d1
/src/number_theory/legendre_symbol/quadratic_char.lean
b49542517b746b62482b17266fb2722c977b0fcd
[ "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
18,660
lean
/- Copyright (c) 2022 Michael Stoll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Stoll -/ import data.fintype.parity import number_theory.legendre_symbol.zmod_char import field_theory.finite.basic import number_theory.legendre_symbol.gauss_sum /-! # Quadratic characters of finite fields This file defines the quadratic character on a finite field `F` and proves some basic statements about it. ## Tags quadratic character -/ /-! ### Definition of the quadratic character We define the quadratic character of a finite field `F` with values in ℤ. -/ section define /-- Define the quadratic character with values in ℤ on a monoid with zero `α`. It takes the value zero at zero; for non-zero argument `a : α`, it is `1` if `a` is a square, otherwise it is `-1`. This only deserves the name "character" when it is multiplicative, e.g., when `α` is a finite field. See `quadratic_char_fun_mul`. We will later define `quadratic_char` to be a multiplicative character of type `mul_char F ℤ`, when the domain is a finite field `F`. -/ def quadratic_char_fun (α : Type*) [monoid_with_zero α] [decidable_eq α] [decidable_pred (is_square : α → Prop)] (a : α) : ℤ := if a = 0 then 0 else if is_square a then 1 else -1 end define /-! ### Basic properties of the quadratic character We prove some properties of the quadratic character. We work with a finite field `F` here. The interesting case is when the characteristic of `F` is odd. -/ section quadratic_char open mul_char variables {F : Type*} [field F] [fintype F] [decidable_eq F] /-- Some basic API lemmas -/ lemma quadratic_char_fun_eq_zero_iff {a : F} : quadratic_char_fun F a = 0 ↔ a = 0 := begin simp only [quadratic_char_fun], by_cases ha : a = 0, { simp only [ha, eq_self_iff_true, if_true], }, { simp only [ha, if_false, iff_false], split_ifs; simp only [neg_eq_zero, one_ne_zero, not_false_iff], }, end @[simp] lemma quadratic_char_fun_zero : quadratic_char_fun F 0 = 0 := by simp only [quadratic_char_fun, eq_self_iff_true, if_true, id.def] @[simp] lemma quadratic_char_fun_one : quadratic_char_fun F 1 = 1 := by simp only [quadratic_char_fun, one_ne_zero, is_square_one, if_true, if_false, id.def] /-- If `ring_char F = 2`, then `quadratic_char_fun F` takes the value `1` on nonzero elements. -/ lemma quadratic_char_fun_eq_one_of_char_two (hF : ring_char F = 2) {a : F} (ha : a ≠ 0) : quadratic_char_fun F a = 1 := begin simp only [quadratic_char_fun, ha, if_false, ite_eq_left_iff], exact λ h, false.rec _ (h (finite_field.is_square_of_char_two hF a)) end /-- If `ring_char F` is odd, then `quadratic_char_fun F a` can be computed in terms of `a ^ (fintype.card F / 2)`. -/ lemma quadratic_char_fun_eq_pow_of_char_ne_two (hF : ring_char F ≠ 2) {a : F} (ha : a ≠ 0) : quadratic_char_fun F a = if a ^ (fintype.card F / 2) = 1 then 1 else -1 := begin simp only [quadratic_char_fun, ha, if_false], simp_rw finite_field.is_square_iff hF ha, end /-- The quadratic character is multiplicative. -/ lemma quadratic_char_fun_mul (a b : F) : quadratic_char_fun F (a * b) = quadratic_char_fun F a * quadratic_char_fun F b := begin by_cases ha : a = 0, { rw [ha, zero_mul, quadratic_char_fun_zero, zero_mul], }, -- now `a ≠ 0` by_cases hb : b = 0, { rw [hb, mul_zero, quadratic_char_fun_zero, mul_zero], }, -- now `a ≠ 0` and `b ≠ 0` have hab := mul_ne_zero ha hb, by_cases hF : ring_char F = 2, { -- case `ring_char F = 2` rw [quadratic_char_fun_eq_one_of_char_two hF ha, quadratic_char_fun_eq_one_of_char_two hF hb, quadratic_char_fun_eq_one_of_char_two hF hab, mul_one], }, { -- case of odd characteristic rw [quadratic_char_fun_eq_pow_of_char_ne_two hF ha, quadratic_char_fun_eq_pow_of_char_ne_two hF hb, quadratic_char_fun_eq_pow_of_char_ne_two hF hab, mul_pow], cases finite_field.pow_dichotomy hF hb with hb' hb', { simp only [hb', mul_one, eq_self_iff_true, if_true], }, { have h := ring.neg_one_ne_one_of_char_ne_two hF, -- `-1 ≠ 1` simp only [hb', h, mul_neg, mul_one, if_false, ite_mul, neg_mul], cases finite_field.pow_dichotomy hF ha with ha' ha'; simp only [ha', h, neg_neg, eq_self_iff_true, if_true, if_false], }, }, end variables (F) /-- The quadratic character as a multiplicative character. -/ @[simps] def quadratic_char : mul_char F ℤ := { to_fun := quadratic_char_fun F, map_one' := quadratic_char_fun_one, map_mul' := quadratic_char_fun_mul, map_nonunit' := λ a ha, by { rw of_not_not (mt ne.is_unit ha), exact quadratic_char_fun_zero, } } variables {F} /-- The value of the quadratic character on `a` is zero iff `a = 0`. -/ lemma quadratic_char_eq_zero_iff {a : F} : quadratic_char F a = 0 ↔ a = 0 := quadratic_char_fun_eq_zero_iff @[simp] lemma quadratic_char_zero : quadratic_char F 0 = 0 := by simp only [quadratic_char_apply, quadratic_char_fun_zero] /-- For nonzero `a : F`, `quadratic_char F a = 1 ↔ is_square a`. -/ lemma quadratic_char_one_iff_is_square {a : F} (ha : a ≠ 0) : quadratic_char F a = 1 ↔ is_square a := by simp only [quadratic_char_apply, quadratic_char_fun, ha, (dec_trivial : (-1 : ℤ) ≠ 1), if_false, ite_eq_left_iff, imp_false, not_not] /-- The quadratic character takes the value `1` on nonzero squares. -/ lemma quadratic_char_sq_one' {a : F} (ha : a ≠ 0) : quadratic_char F (a ^ 2) = 1 := by simp only [quadratic_char_fun, ha, pow_eq_zero_iff, nat.succ_pos', is_square_sq, if_true, if_false, quadratic_char_apply] /-- The square of the quadratic character on nonzero arguments is `1`. -/ lemma quadratic_char_sq_one {a : F} (ha : a ≠ 0) : (quadratic_char F a) ^ 2 = 1 := by rwa [pow_two, ← map_mul, ← pow_two, quadratic_char_sq_one'] /-- The quadratic character is `1` or `-1` on nonzero arguments. -/ lemma quadratic_char_dichotomy {a : F} (ha : a ≠ 0) : quadratic_char F a = 1 ∨ quadratic_char F a = -1 := sq_eq_one_iff.1 $ quadratic_char_sq_one ha /-- The quadratic character is `1` or `-1` on nonzero arguments. -/ lemma quadratic_char_eq_neg_one_iff_not_one {a : F} (ha : a ≠ 0) : quadratic_char F a = -1 ↔ ¬ quadratic_char F a = 1 := begin refine ⟨λ h, _, λ h₂, (or_iff_right h₂).mp (quadratic_char_dichotomy ha)⟩, rw h, norm_num, end /-- For `a : F`, `quadratic_char F a = -1 ↔ ¬ is_square a`. -/ lemma quadratic_char_neg_one_iff_not_is_square {a : F} : quadratic_char F a = -1 ↔ ¬ is_square a := begin by_cases ha : a = 0, { simp only [ha, is_square_zero, mul_char.map_zero, zero_eq_neg, one_ne_zero, not_true], }, { rw [quadratic_char_eq_neg_one_iff_not_one ha, quadratic_char_one_iff_is_square ha] }, end /-- If `F` has odd characteristic, then `quadratic_char F` takes the value `-1`. -/ lemma quadratic_char_exists_neg_one (hF : ring_char F ≠ 2) : ∃ a, quadratic_char F a = -1 := (finite_field.exists_nonsquare hF).imp $ λ b h₁, quadratic_char_neg_one_iff_not_is_square.mpr h₁ /-- If `ring_char F = 2`, then `quadratic_char F` takes the value `1` on nonzero elements. -/ lemma quadratic_char_eq_one_of_char_two (hF : ring_char F = 2) {a : F} (ha : a ≠ 0) : quadratic_char F a = 1 := quadratic_char_fun_eq_one_of_char_two hF ha /-- If `ring_char F` is odd, then `quadratic_char F a` can be computed in terms of `a ^ (fintype.card F / 2)`. -/ lemma quadratic_char_eq_pow_of_char_ne_two (hF : ring_char F ≠ 2) {a : F} (ha : a ≠ 0) : quadratic_char F a = if a ^ (fintype.card F / 2) = 1 then 1 else -1 := quadratic_char_fun_eq_pow_of_char_ne_two hF ha lemma quadratic_char_eq_pow_of_char_ne_two' (hF : ring_char F ≠ 2) (a : F) : (quadratic_char F a : F) = a ^ (fintype.card F / 2) := begin by_cases ha : a = 0, { have : 0 < fintype.card F / 2 := nat.div_pos fintype.one_lt_card two_pos, simp only [ha, zero_pow this, quadratic_char_apply, quadratic_char_zero, int.cast_zero], }, { rw [quadratic_char_eq_pow_of_char_ne_two hF ha], by_cases ha' : a ^ (fintype.card F / 2) = 1, { simp only [ha', eq_self_iff_true, if_true, int.cast_one], }, { have ha'' := or.resolve_left (finite_field.pow_dichotomy hF ha) ha', simp only [ha'', int.cast_ite, int.cast_one, int.cast_neg, ite_eq_right_iff], exact eq.symm, } } end variables (F) /-- The quadratic character is quadratic as a multiplicative character. -/ lemma quadratic_char_is_quadratic : (quadratic_char F).is_quadratic := begin intro a, by_cases ha : a = 0, { left, rw ha, exact quadratic_char_zero, }, { right, exact quadratic_char_dichotomy ha, }, end variables {F} /-- The quadratic character is nontrivial as a multiplicative character when the domain has odd characteristic. -/ lemma quadratic_char_is_nontrivial (hF : ring_char F ≠ 2) : (quadratic_char F).is_nontrivial := begin rcases quadratic_char_exists_neg_one hF with ⟨a, ha⟩, have hu : is_unit a := by { by_contra hf, rw map_nonunit _ hf at ha, norm_num at ha, }, refine ⟨hu.unit, (_ : quadratic_char F a ≠ 1)⟩, rw ha, norm_num, end /-- The number of solutions to `x^2 = a` is determined by the quadratic character. -/ lemma quadratic_char_card_sqrts (hF : ring_char F ≠ 2) (a : F) : ↑{x : F | x^2 = a}.to_finset.card = quadratic_char F a + 1 := begin -- we consider the cases `a = 0`, `a` is a nonzero square and `a` is a nonsquare in turn by_cases h₀ : a = 0, { simp only [h₀, pow_eq_zero_iff, nat.succ_pos', int.coe_nat_succ, int.coe_nat_zero, mul_char.map_zero, set.set_of_eq_eq_singleton, set.to_finset_card, set.card_singleton], }, { set s := {x : F | x^2 = a}.to_finset with hs, by_cases h : is_square a, { rw (quadratic_char_one_iff_is_square h₀).mpr h, rcases h with ⟨b, h⟩, rw [h, mul_self_eq_zero] at h₀, have h₁ : s = [b, -b].to_finset := by { ext x, simp only [finset.mem_filter, finset.mem_univ, true_and, list.to_finset_cons, list.to_finset_nil, insert_emptyc_eq, finset.mem_insert, finset.mem_singleton], rw ← pow_two at h, simp only [hs, set.mem_to_finset, set.mem_set_of_eq, h], split, { exact eq_or_eq_neg_of_sq_eq_sq _ _, }, { rintro (h₂ | h₂); rw h₂, simp only [neg_sq], }, }, norm_cast, rw [h₁, list.to_finset_cons, list.to_finset_cons, list.to_finset_nil], exact finset.card_doubleton (ne.symm (mt (ring.eq_self_iff_eq_zero_of_char_ne_two hF).mp h₀)), }, { rw quadratic_char_neg_one_iff_not_is_square.mpr h, simp only [int.coe_nat_eq_zero, finset.card_eq_zero, set.to_finset_card, fintype.card_of_finset, set.mem_set_of_eq, add_left_neg], ext x, simp only [iff_false, finset.mem_filter, finset.mem_univ, true_and, finset.not_mem_empty], rw is_square_iff_exists_sq at h, exact λ h', h ⟨_, h'.symm⟩, }, }, end open_locale big_operators /-- The sum over the values of the quadratic character is zero when the characteristic is odd. -/ lemma quadratic_char_sum_zero (hF : ring_char F ≠ 2) : ∑ (a : F), quadratic_char F a = 0 := is_nontrivial.sum_eq_zero (quadratic_char_is_nontrivial hF) end quadratic_char /-! ### Special values of the quadratic character We express `quadratic_char F (-1)` in terms of `χ₄`. -/ section special_values open zmod mul_char variables {F : Type*} [field F] [fintype F] /-- The value of the quadratic character at `-1` -/ lemma quadratic_char_neg_one [decidable_eq F] (hF : ring_char F ≠ 2) : quadratic_char F (-1) = χ₄ (fintype.card F) := begin have h := quadratic_char_eq_pow_of_char_ne_two hF (neg_ne_zero.mpr one_ne_zero), rw [h, χ₄_eq_neg_one_pow (finite_field.odd_card_of_char_ne_two hF)], set n := fintype.card F / 2, cases (nat.even_or_odd n) with h₂ h₂, { simp only [even.neg_one_pow h₂, eq_self_iff_true, if_true], }, { simp only [odd.neg_one_pow h₂, ite_eq_right_iff], exact λ hf, false.rec (1 = -1) (ring.neg_one_ne_one_of_char_ne_two hF hf), }, end /-- `-1` is a square in `F` iff `#F` is not congruent to `3` mod `4`. -/ lemma finite_field.is_square_neg_one_iff : is_square (-1 : F) ↔ fintype.card F % 4 ≠ 3 := begin classical, -- suggested by the linter (instead of `[decidable_eq F]`) by_cases hF : ring_char F = 2, { simp only [finite_field.is_square_of_char_two hF, ne.def, true_iff], exact (λ hf, one_ne_zero $ (nat.odd_of_mod_four_eq_three hf).symm.trans $ finite_field.even_card_of_char_two hF) }, { have h₁ := finite_field.odd_card_of_char_ne_two hF, rw [← quadratic_char_one_iff_is_square (neg_ne_zero.mpr (one_ne_zero' F)), quadratic_char_neg_one hF, χ₄_nat_eq_if_mod_four, h₁], simp only [nat.one_ne_zero, if_false, ite_eq_left_iff, ne.def, (dec_trivial : (-1 : ℤ) ≠ 1), imp_false, not_not], exact ⟨λ h, ne_of_eq_of_ne h (dec_trivial : 1 ≠ 3), or.resolve_right (nat.odd_mod_four_iff.mp h₁)⟩, }, end /-- The value of the quadratic character at `2` -/ lemma quadratic_char_two [decidable_eq F] (hF : ring_char F ≠ 2) : quadratic_char F 2 = χ₈ (fintype.card F) := is_quadratic.eq_of_eq_coe (quadratic_char_is_quadratic F) is_quadratic_χ₈ hF ((quadratic_char_eq_pow_of_char_ne_two' hF 2).trans (finite_field.two_pow_card hF)) /-- `2` is a square in `F` iff `#F` is not congruent to `3` or `5` mod `8`. -/ lemma finite_field.is_square_two_iff : is_square (2 : F) ↔ fintype.card F % 8 ≠ 3 ∧ fintype.card F % 8 ≠ 5 := begin classical, by_cases hF : ring_char F = 2, focus { have h := finite_field.even_card_of_char_two hF, simp only [finite_field.is_square_of_char_two hF, true_iff], }, rotate, focus { have h := finite_field.odd_card_of_char_ne_two hF, rw [← quadratic_char_one_iff_is_square (ring.two_ne_zero hF), quadratic_char_two hF, χ₈_nat_eq_if_mod_eight], simp only [h, nat.one_ne_zero, if_false, ite_eq_left_iff, ne.def, (dec_trivial : (-1 : ℤ) ≠ 1), imp_false, not_not], }, all_goals { rw [← nat.mod_mod_of_dvd _ (by norm_num : 2 ∣ 8)] at h, have h₁ := nat.mod_lt (fintype.card F) (dec_trivial : 0 < 8), revert h₁ h, generalize : fintype.card F % 8 = n, dec_trivial!, } end /-- The value of the quadratic character at `-2` -/ lemma quadratic_char_neg_two [decidable_eq F] (hF : ring_char F ≠ 2) : quadratic_char F (-2) = χ₈' (fintype.card F) := begin rw [(by norm_num : (-2 : F) = (-1) * 2), map_mul, χ₈'_eq_χ₄_mul_χ₈, quadratic_char_neg_one hF, quadratic_char_two hF, @cast_nat_cast _ (zmod 4) _ _ _ (by norm_num : 4 ∣ 8)], end /-- `-2` is a square in `F` iff `#F` is not congruent to `5` or `7` mod `8`. -/ lemma finite_field.is_square_neg_two_iff : is_square (-2 : F) ↔ fintype.card F % 8 ≠ 5 ∧ fintype.card F % 8 ≠ 7 := begin classical, by_cases hF : ring_char F = 2, focus { have h := finite_field.even_card_of_char_two hF, simp only [finite_field.is_square_of_char_two hF, true_iff], }, rotate, focus { have h := finite_field.odd_card_of_char_ne_two hF, rw [← quadratic_char_one_iff_is_square (neg_ne_zero.mpr (ring.two_ne_zero hF)), quadratic_char_neg_two hF, χ₈'_nat_eq_if_mod_eight], simp only [h, nat.one_ne_zero, if_false, ite_eq_left_iff, ne.def, (dec_trivial : (-1 : ℤ) ≠ 1), imp_false, not_not], }, all_goals { rw [← nat.mod_mod_of_dvd _ (by norm_num : 2 ∣ 8)] at h, have h₁ := nat.mod_lt (fintype.card F) (dec_trivial : 0 < 8), revert h₁ h, generalize : fintype.card F % 8 = n, dec_trivial! } end /-- The relation between the values of the quadratic character of one field `F` at the cardinality of another field `F'` and of the quadratic character of `F'` at the cardinality of `F`. -/ lemma quadratic_char_card_card [decidable_eq F] (hF : ring_char F ≠ 2) {F' : Type*} [field F'] [fintype F'] [decidable_eq F'] (hF' : ring_char F' ≠ 2) (h : ring_char F' ≠ ring_char F) : quadratic_char F (fintype.card F') = quadratic_char F' (quadratic_char F (-1) * fintype.card F) := begin let χ := (quadratic_char F).ring_hom_comp (algebra_map ℤ F'), have hχ₁ : χ.is_nontrivial, { obtain ⟨a, ha⟩ := quadratic_char_exists_neg_one hF, have hu : is_unit a, { contrapose ha, exact ne_of_eq_of_ne (map_nonunit (quadratic_char F) ha) (mt zero_eq_neg.mp one_ne_zero), }, use hu.unit, simp only [is_unit.unit_spec, ring_hom_comp_apply, eq_int_cast, ne.def, ha], rw [int.cast_neg, int.cast_one], exact ring.neg_one_ne_one_of_char_ne_two hF', }, have hχ₂ : χ.is_quadratic := is_quadratic.comp (quadratic_char_is_quadratic F) _, have h := char.card_pow_card hχ₁ hχ₂ h hF', rw [← quadratic_char_eq_pow_of_char_ne_two' hF'] at h, exact (is_quadratic.eq_of_eq_coe (quadratic_char_is_quadratic F') (quadratic_char_is_quadratic F) hF' h).symm, end /-- The value of the quadratic character at an odd prime `p` different from `ring_char F`. -/ lemma quadratic_char_odd_prime [decidable_eq F] (hF : ring_char F ≠ 2) {p : ℕ} [fact p.prime] (hp₁ : p ≠ 2) (hp₂ : ring_char F ≠ p) : quadratic_char F p = quadratic_char (zmod p) (χ₄ (fintype.card F) * fintype.card F) := begin rw [← quadratic_char_neg_one hF], have h := quadratic_char_card_card hF (ne_of_eq_of_ne (ring_char_zmod_n p) hp₁) (ne_of_eq_of_ne (ring_char_zmod_n p) hp₂.symm), rwa [card p] at h, end /-- An odd prime `p` is a square in `F` iff the quadratic character of `zmod p` does not take the value `-1` on `χ₄(#F) * #F`. -/ lemma finite_field.is_square_odd_prime_iff (hF : ring_char F ≠ 2) {p : ℕ} [fact p.prime] (hp : p ≠ 2) : is_square (p : F) ↔ quadratic_char (zmod p) (χ₄ (fintype.card F) * fintype.card F) ≠ -1 := begin classical, by_cases hFp : ring_char F = p, { rw [show (p : F) = 0, by { rw ← hFp, exact ring_char.nat.cast_ring_char }], simp only [is_square_zero, ne.def, true_iff, map_mul], obtain ⟨n, _, hc⟩ := finite_field.card F (ring_char F), have hchar : ring_char F = ring_char (zmod p) := by {rw hFp, exact (ring_char_zmod_n p).symm}, conv {congr, to_lhs, congr, skip, rw [hc, nat.cast_pow, map_pow, hchar, map_ring_char], }, simp only [zero_pow n.pos, mul_zero, zero_eq_neg, one_ne_zero, not_false_iff], }, { rw [← iff.not_left (@quadratic_char_neg_one_iff_not_is_square F _ _ _ _), quadratic_char_odd_prime hF hp], exact hFp, }, end end special_values
da6321087a969bebeaebcc00311da89f8160f184
92bfaf170880e47d55bf51d5a782fffd76db2f5f
/melting_point/X.lean
09bf417ccec961ec77194d67c1514fd2f2d56efd
[]
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
374
lean
import melting_point.topology open melting_point.topology inductive X | a | b | c | d namespace X def τ : set (set X) := { { a }, { c }, { a, c }, { a, b, c }, { a, d, c }, ∅, set.univ } example : topology X := begin fapply topology.mk, exact τ, enumeration, repeat { intros x y u v, sinduction u; sinduction v; findset } end end X
a483db86280c773529ca7f2630939fc4ac2e5179
624f6f2ae8b3b1adc5f8f67a365c51d5126be45a
/tests/lean/run/type_class_performance1.lean
26fd6950ad55cd5a0b2b9c07576b6a6611209089
[ "Apache-2.0" ]
permissive
mhuisi/lean4
28d35a4febc2e251c7f05492e13f3b05d6f9b7af
dda44bc47f3e5d024508060dac2bcb59fd12e4c0
refs/heads/master
1,621,225,489,283
1,585,142,689,000
1,585,142,689,000
250,590,438
0
2
Apache-2.0
1,602,443,220,000
1,585,327,814,000
C
UTF-8
Lean
false
false
176
lean
#print USize def foo1 (a b : UInt64) : Bool := a = b def foo2 (a b : UInt16) : Bool := a = b def foo3 (a b : UInt32) : Bool := a = b def foo4 (a b : USize) : Bool := a = b
a3f247235ca9fd5a79a1cdfd4753644da05a208b
947fa6c38e48771ae886239b4edce6db6e18d0fb
/src/group_theory/index.lean
6d1281e746d6ca811f8739f733fdeeba68f68f59
[ "Apache-2.0" ]
permissive
ramonfmir/mathlib
c5dc8b33155473fab97c38bd3aa6723dc289beaa
14c52e990c17f5a00c0cc9e09847af16fabbed25
refs/heads/master
1,661,979,343,526
1,660,830,384,000
1,660,830,384,000
182,072,989
0
0
null
1,555,585,876,000
1,555,585,876,000
null
UTF-8
Lean
false
false
11,624
lean
/- Copyright (c) 2021 Thomas Browning. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Thomas Browning -/ import group_theory.quotient_group import set_theory.cardinal.finite /-! # Index of a Subgroup In this file we define the index of a subgroup, and prove several divisibility properties. Several theorems proved in this file are known as Lagrange's theorem. ## Main definitions - `H.index` : the index of `H : subgroup G` as a natural number, and returns 0 if the index is infinite. - `H.relindex K` : the relative index of `H : subgroup G` in `K : subgroup G` as a natural number, and returns 0 if the relative index is infinite. # Main results - `card_mul_index` : `nat.card H * H.index = nat.card G` - `index_mul_card` : `H.index * fintype.card H = fintype.card G` - `index_dvd_card` : `H.index ∣ fintype.card G` - `index_eq_mul_of_le` : If `H ≤ K`, then `H.index = K.index * (H.subgroup_of K).index` - `index_dvd_of_le` : If `H ≤ K`, then `K.index ∣ H.index` - `relindex_mul_relindex` : `relindex` is multiplicative in towers -/ namespace subgroup open_locale cardinal variables {G : Type*} [group G] (H K L : subgroup G) /-- The index of a subgroup as a natural number, and returns 0 if the index is infinite. -/ @[to_additive "The index of a subgroup as a natural number, and returns 0 if the index is infinite."] noncomputable def index : ℕ := nat.card (G ⧸ H) /-- The relative index of a subgroup as a natural number, and returns 0 if the relative index is infinite. -/ @[to_additive "The relative index of a subgroup as a natural number, and returns 0 if the relative index is infinite."] noncomputable def relindex : ℕ := (H.subgroup_of K).index @[to_additive] lemma index_comap_of_surjective {G' : Type*} [group G'] {f : G' →* G} (hf : function.surjective f) : (H.comap f).index = H.index := begin letI := quotient_group.left_rel H, letI := quotient_group.left_rel (H.comap f), have key : ∀ x y : G', setoid.r x y ↔ setoid.r (f x) (f y), { simp only [quotient_group.left_rel_apply], exact λ x y, iff_of_eq (congr_arg (∈ H) (by rw [f.map_mul, f.map_inv])) }, refine cardinal.to_nat_congr (equiv.of_bijective (quotient.map' f (λ x y, (key x y).mp)) ⟨_, _⟩), { simp_rw [←quotient.eq'] at key, refine quotient.ind' (λ x, _), refine quotient.ind' (λ y, _), exact (key x y).mpr }, { refine quotient.ind' (λ x, _), obtain ⟨y, hy⟩ := hf x, exact ⟨y, (quotient.map'_mk' f _ y).trans (congr_arg quotient.mk' hy)⟩ }, end @[to_additive] lemma index_comap {G' : Type*} [group G'] (f : G' →* G) : (H.comap f).index = H.relindex f.range := eq.trans (congr_arg index (by refl)) ((H.subgroup_of f.range).index_comap_of_surjective f.range_restrict_surjective) variables {H K L} @[to_additive relindex_mul_index] lemma relindex_mul_index (h : H ≤ K) : H.relindex K * K.index = H.index := ((mul_comm _ _).trans (cardinal.to_nat_mul _ _).symm).trans (congr_arg cardinal.to_nat (equiv.cardinal_eq (quotient_equiv_prod_of_le h))).symm @[to_additive] lemma index_dvd_of_le (h : H ≤ K) : K.index ∣ H.index := dvd_of_mul_left_eq (H.relindex K) (relindex_mul_index h) @[to_additive] lemma relindex_dvd_index_of_le (h : H ≤ K) : H.relindex K ∣ H.index := dvd_of_mul_right_eq K.index (relindex_mul_index h) @[to_additive] lemma relindex_subgroup_of (hKL : K ≤ L) : (H.subgroup_of L).relindex (K.subgroup_of L) = H.relindex K := ((index_comap (H.subgroup_of L) (inclusion hKL)).trans (congr_arg _ (inclusion_range hKL))).symm variables (H K L) @[to_additive relindex_mul_relindex] lemma relindex_mul_relindex (hHK : H ≤ K) (hKL : K ≤ L) : H.relindex K * K.relindex L = H.relindex L := begin rw [←relindex_subgroup_of hKL], exact relindex_mul_index (λ x hx, hHK hx), end @[to_additive] lemma inf_relindex_right : (H ⊓ K).relindex K = H.relindex K := begin rw [←subgroup_of_map_subtype, relindex, relindex, subgroup_of, comap_map_eq_self_of_injective], exact subtype.coe_injective, end @[to_additive] lemma inf_relindex_left : (H ⊓ K).relindex H = K.relindex H := by rw [inf_comm, inf_relindex_right] @[to_additive relindex_inf_mul_relindex] lemma relindex_inf_mul_relindex : H.relindex (K ⊓ L) * K.relindex L = (H ⊓ K).relindex L := by rw [←inf_relindex_right H (K ⊓ L), ←inf_relindex_right K L, ←inf_relindex_right (H ⊓ K) L, inf_assoc, relindex_mul_relindex (H ⊓ (K ⊓ L)) (K ⊓ L) L inf_le_right inf_le_right] @[to_additive] lemma inf_relindex_eq_relindex_sup [K.normal] : (H ⊓ K).relindex H = K.relindex (H ⊔ K) := cardinal.to_nat_congr (quotient_group.quotient_inf_equiv_prod_normal_quotient H K).to_equiv @[to_additive] lemma relindex_eq_relindex_sup [K.normal] : K.relindex H = K.relindex (H ⊔ K) := by rw [←inf_relindex_left, inf_relindex_eq_relindex_sup] @[to_additive] lemma relindex_dvd_index_of_normal [H.normal] : H.relindex K ∣ H.index := (relindex_eq_relindex_sup K H).symm ▸ relindex_dvd_index_of_le le_sup_right variables {H K} @[to_additive] lemma relindex_dvd_of_le_left (hHK : H ≤ K) : K.relindex L ∣ H.relindex L := begin apply dvd_of_mul_left_eq ((H ⊓ L).relindex (K ⊓ L)), rw [←inf_relindex_right H L, ←inf_relindex_right K L], exact relindex_mul_relindex (H ⊓ L) (K ⊓ L) L (inf_le_inf_right L hHK) inf_le_right, end variables (H K) @[simp, to_additive] lemma index_top : (⊤ : subgroup G).index = 1 := cardinal.to_nat_eq_one_iff_unique.mpr ⟨quotient_group.subsingleton_quotient_top, ⟨1⟩⟩ @[simp, to_additive] lemma index_bot : (⊥ : subgroup G).index = nat.card G := cardinal.to_nat_congr (quotient_group.quotient_bot.to_equiv) @[to_additive] lemma index_bot_eq_card [fintype G] : (⊥ : subgroup G).index = fintype.card G := index_bot.trans nat.card_eq_fintype_card @[simp, to_additive] lemma relindex_top_left : (⊤ : subgroup G).relindex H = 1 := index_top @[simp, to_additive] lemma relindex_top_right : H.relindex ⊤ = H.index := by rw [←relindex_mul_index (show H ≤ ⊤, from le_top), index_top, mul_one] @[simp, to_additive] lemma relindex_bot_left : (⊥ : subgroup G).relindex H = nat.card H := by rw [relindex, bot_subgroup_of, index_bot] @[to_additive] lemma relindex_bot_left_eq_card [fintype H] : (⊥ : subgroup G).relindex H = fintype.card H := H.relindex_bot_left.trans nat.card_eq_fintype_card @[simp, to_additive] lemma relindex_bot_right : H.relindex ⊥ = 1 := by rw [relindex, subgroup_of_bot_eq_top, index_top] @[simp, to_additive] lemma relindex_self : H.relindex H = 1 := by rw [relindex, subgroup_of_self, index_top] @[simp, to_additive card_mul_index] lemma card_mul_index : nat.card H * H.index = nat.card G := by { rw [←relindex_bot_left, ←index_bot], exact relindex_mul_index bot_le } @[to_additive] lemma index_map {G' : Type*} [group G'] (f : G →* G') : (H.map f).index = (H ⊔ f.ker).index * f.range.index := by rw [←comap_map_eq, index_comap, relindex_mul_index (H.map_le_range f)] @[to_additive] lemma index_map_dvd {G' : Type*} [group G'] {f : G →* G'} (hf : function.surjective f) : (H.map f).index ∣ H.index := begin rw [index_map, f.range_top_of_surjective hf, index_top, mul_one], exact index_dvd_of_le le_sup_left, end @[to_additive] lemma dvd_index_map {G' : Type*} [group G'] {f : G →* G'} (hf : f.ker ≤ H) : H.index ∣ (H.map f).index := begin rw [index_map, sup_of_le_left hf], apply dvd_mul_right, end @[to_additive] lemma index_map_eq {G' : Type*} [group G'] {f : G →* G'} (hf1 : function.surjective f) (hf2 : f.ker ≤ H) : (H.map f).index = H.index := nat.dvd_antisymm (H.index_map_dvd hf1) (H.dvd_index_map hf2) @[to_additive] lemma index_eq_card [fintype (G ⧸ H)] : H.index = fintype.card (G ⧸ H) := nat.card_eq_fintype_card @[to_additive index_mul_card] lemma index_mul_card [fintype G] [hH : fintype H] : H.index * fintype.card H = fintype.card G := by rw [←relindex_bot_left_eq_card, ←index_bot_eq_card, mul_comm]; exact relindex_mul_index bot_le @[to_additive] lemma index_dvd_card [fintype G] : H.index ∣ fintype.card G := begin classical, exact ⟨fintype.card H, H.index_mul_card.symm⟩, end variables {H K L} @[to_additive] lemma relindex_eq_zero_of_le_left (hHK : H ≤ K) (hKL : K.relindex L = 0) : H.relindex L = 0 := eq_zero_of_zero_dvd (hKL ▸ (relindex_dvd_of_le_left L hHK)) @[to_additive] lemma relindex_eq_zero_of_le_right (hKL : K ≤ L) (hHK : H.relindex K = 0) : H.relindex L = 0 := cardinal.to_nat_apply_of_aleph_0_le (le_trans (le_of_not_lt (λ h, cardinal.mk_ne_zero _ ((cardinal.cast_to_nat_of_lt_aleph_0 h).symm.trans (cardinal.nat_cast_inj.mpr hHK)))) (quotient_subgroup_of_embedding_of_le H hKL).cardinal_le) @[to_additive] lemma relindex_le_of_le_left (hHK : H ≤ K) (hHL : H.relindex L ≠ 0) : K.relindex L ≤ H.relindex L := nat.le_of_dvd (nat.pos_of_ne_zero hHL) (relindex_dvd_of_le_left L hHK) @[to_additive] lemma relindex_le_of_le_right (hKL : K ≤ L) (hHL : H.relindex L ≠ 0) : H.relindex K ≤ H.relindex L := cardinal.to_nat_le_of_le_of_lt_aleph_0 (lt_of_not_ge (mt cardinal.to_nat_apply_of_aleph_0_le hHL)) (cardinal.mk_le_of_injective (quotient_subgroup_of_embedding_of_le H hKL).2) @[to_additive] lemma relindex_ne_zero_trans (hHK : H.relindex K ≠ 0) (hKL : K.relindex L ≠ 0) : H.relindex L ≠ 0 := λ h, mul_ne_zero (mt (relindex_eq_zero_of_le_right (show K ⊓ L ≤ K, from inf_le_left)) hHK) hKL ((relindex_inf_mul_relindex H K L).trans (relindex_eq_zero_of_le_left inf_le_left h)) @[to_additive] lemma relindex_inf_ne_zero (hH : H.relindex L ≠ 0) (hK : K.relindex L ≠ 0) : (H ⊓ K).relindex L ≠ 0 := begin replace hH : H.relindex (K ⊓ L) ≠ 0 := mt (relindex_eq_zero_of_le_right inf_le_right) hH, rw ← inf_relindex_right at hH hK ⊢, rw inf_assoc, exact relindex_ne_zero_trans hH hK, end @[to_additive] lemma index_inf_ne_zero (hH : H.index ≠ 0) (hK : K.index ≠ 0) : (H ⊓ K).index ≠ 0 := begin rw ← relindex_top_right at hH hK ⊢, exact relindex_inf_ne_zero hH hK, end @[to_additive] lemma relindex_inf_le : (H ⊓ K).relindex L ≤ H.relindex L * K.relindex L := begin by_cases h : H.relindex L = 0, { exact (le_of_eq (relindex_eq_zero_of_le_left (by exact inf_le_left) h)).trans (zero_le _) }, rw [←inf_relindex_right, inf_assoc, ←relindex_mul_relindex _ _ L inf_le_right inf_le_right, inf_relindex_right, inf_relindex_right], exact mul_le_mul_right' (relindex_le_of_le_right inf_le_right h) (K.relindex L), end @[to_additive] lemma index_inf_le : (H ⊓ K).index ≤ H.index * K.index := by simp_rw [←relindex_top_right, relindex_inf_le] @[simp, to_additive index_eq_one] lemma index_eq_one : H.index = 1 ↔ H = ⊤ := ⟨λ h, quotient_group.subgroup_eq_top_of_subsingleton H (cardinal.to_nat_eq_one_iff_unique.mp h).1, λ h, (congr_arg index h).trans index_top⟩ @[to_additive] lemma index_ne_zero_of_finite [hH : finite (G ⧸ H)] : H.index ≠ 0 := by { casesI nonempty_fintype (G ⧸ H), rw index_eq_card, exact fintype.card_ne_zero } /-- Finite index implies finite quotient. -/ @[to_additive "Finite index implies finite quotient."] noncomputable def fintype_of_index_ne_zero (hH : H.index ≠ 0) : fintype (G ⧸ H) := (cardinal.lt_aleph_0_iff_fintype.mp (lt_of_not_ge (mt cardinal.to_nat_apply_of_aleph_0_le hH))).some @[to_additive one_lt_index_of_ne_top] lemma one_lt_index_of_ne_top [finite (G ⧸ H)] (hH : H ≠ ⊤) : 1 < H.index := nat.one_lt_iff_ne_zero_and_ne_one.mpr ⟨index_ne_zero_of_finite, mt index_eq_one.mp hH⟩ end subgroup
c30ad923683a880941e588ebb3c1adad2438aa91
f68ef9a599ec5575db7b285d4960e63c5d464ccc
/Exercises/Lista 5/cap12-LucasMoschen.lean
db2066835b71b6c876673d340f41d15ba8aa6f49
[]
no_license
lucasmoschen/discrete-mathematics
a38d5970cc571b0b9d202bf6a43efeb8ed6f66e3
0f1945cc5eb094814c926cd6ae4a8b4c5c579a1e
refs/heads/master
1,677,111,757,003
1,611,500,097,000
1,611,500,097,000
205,903,359
1
0
null
null
null
null
UTF-8
Lean
false
false
4,180
lean
open set /- alunos: - Lucas Machado Moschen -/ -- ex 1 section variable U : Type variables A B C : set U example : ∀ x, x ∈ A ∩ C → x ∈ A ∪ B := assume x, assume h: x ∈ A ∩ C, show x ∈ A ∪ B, from or.inl h.left example : ∀ x, x ∈ -(A ∪ B) → x ∈ -A := assume x, assume : x ∈ -(A ∪ B), have ¬ x ∈ (A ∪ B), from this, assume : x ∈ A, show false, from ‹¬ x ∈ (A ∪ B)› (or.inl this) end -- ex 2 section variable {U : Type} /- defining "disjoint" -/ def disj (A B : set U) : Prop := ∀ ⦃x⦄, x ∈ A → x ∈ B → false example (A B : set U) (h : ∀ x, ¬ (x ∈ A ∧ x ∈ B)) : disj A B := assume x, assume h1 : x ∈ A, assume h2 : x ∈ B, have h3 : x ∈ A ∧ x ∈ B, from and.intro h1 h2, show false, from h x h3 -- notice that we do not have to mention x when applying -- h : disj A B example (A B : set U) (h1 : disj A B) (x : U) (h2 : x ∈ A) (h3 : x ∈ B) : false := h1 h2 h3 -- the same is true of ⊆ example (A B : set U) (x : U) (h : A ⊆ B) (h1 : x ∈ A) : x ∈ B := h h1 example (A B C D : set U) (h1 : disj A B) (h2 : C ⊆ A) (h3 : D ⊆ B) : disj C D := assume x, assume g1: x ∈ C, assume g2: x ∈ D, have g3: x ∈ A, from h2 g1, have g4: x ∈ B, from h3 g2, show false, from h1 g3 g4 end -- ex 3 section variables {I U : Type} variables {A : I → set U} {B : I → set U} {C : set U} def Union (A : I → set U) : set U := { x | ∃ i : I, x ∈ A i } def Inter (A : I → set U) : set U := { x | ∀ i : I, x ∈ A i } notation `⋃` binders `, ` r:(scoped f, Union f) := r notation `⋂` binders `, ` r:(scoped f, Inter f) := r theorem Inter.intro {x : U} (h : ∀ i, x ∈ A i) : x ∈ ⋂ i, A i := by simp; assumption @[elab_simple] theorem Inter.elim {x : U} (h : x ∈ ⋂ i, A i) (i : I) : x ∈ A i := by simp at h; apply h theorem Union.intro {x : U} (i : I) (h : x ∈ A i) : x ∈ ⋃ i, A i := by {simp, existsi i, exact h} theorem Union.elim {b : Prop} {x : U} (h₁ : x ∈ ⋃ i, A i) (h₂ : ∀ (i : I), x ∈ A i → b) : b := by {simp at h₁, cases h₁ with i h, exact h₂ i h} example : (⋂ i, A i) ∩ (⋂ i, B i) ⊆ (⋂ i, A i ∩ B i) := assume x, assume h: x ∈ (⋂ i, A i) ∩ (⋂ i, B i), show x ∈ (⋂ i, A i ∩ B i), from Inter.intro (assume i: I, have h1: x ∈ A i, from Inter.elim h.left i, have h2: x ∈ B i, from Inter.elim h.right i, show x ∈ A i ∩ B i, from and.intro h1 h2) example : C ∩ (⋃i, A i) ⊆ ⋃i, C ∩ A i := assume x : U, assume h : x ∈ C ∩ (⋃i, A i), show x ∈ ⋃ i, C ∩ A i, from Union.elim h.right (assume i : I, assume h1: x ∈ A i, show x ∈ ⋃ i, C ∩ A i, from Union.intro i (and.intro h.left h1)) end -- ex 4 section variable {U : Type} variables A B C : set U @[refl] theorem subset.refl (a : set U) : a ⊆ a := assume x, id @[trans] theorem subset.trans {a b c : set U} (ab : a ⊆ b) (bc : b ⊆ c) : a ⊆ c := assume x h, bc (ab h) example (h1 : A ⊆ B) (h2 : B ⊆ C) : A ⊆ C := subset.trans h1 h2 example : A ⊆ A := subset.refl A example (h : A ⊆ B) : powerset A ⊆ powerset B := assume X : set U, assume h1 : X ∈ powerset A, show X ∈ powerset B, from subset.trans h1 h example (h : powerset A ⊆ powerset B) : A ⊆ B := assume x: U, assume h1 : x ∈ A, have h2: {y|x = y} ∈ powerset A, from assume z, assume : z ∈ {y| x = y}, have x = z, from this, show z ∈ A, from eq.subst this h1, have h3: {y| x = y} ∈ powerset B, from h h2, have h4: x ∈ {y| x = y}, from eq.refl x, show x ∈ B, from h3 h4 end
4c01cd05919edacd22ab64ba6b3e9bec8c2774af
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/data/real/basic.lean
d6e0d01b74a5140880e055072eebdbf66f160207
[ "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
24,062
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Floris van Doorn The (classical) real numbers ℝ. This is a direct construction from Cauchy sequences. -/ import order.conditionally_complete_lattice import data.real.cau_seq_completion import algebra.archimedean import algebra.star.basic /-- The type `ℝ` of real numbers constructed as equivalence classes of Cauchy sequences of rational numbers. -/ structure real := of_cauchy :: (cauchy : @cau_seq.completion.Cauchy ℚ _ _ _ abs _) notation `ℝ` := real attribute [pp_using_anonymous_constructor] real namespace real open cau_seq cau_seq.completion variables {x y : ℝ} lemma ext_cauchy_iff : ∀ {x y : real}, x = y ↔ x.cauchy = y.cauchy | ⟨a⟩ ⟨b⟩ := by split; cc lemma ext_cauchy {x y : real} : x.cauchy = y.cauchy → x = y := ext_cauchy_iff.2 /-- The real numbers are isomorphic to the quotient of Cauchy sequences on the rationals. -/ def equiv_Cauchy : ℝ ≃ cau_seq.completion.Cauchy := ⟨real.cauchy, real.of_cauchy, λ ⟨_⟩, rfl, λ _, rfl⟩ -- irreducible doesn't work for instances: https://github.com/leanprover-community/lean/issues/511 @[irreducible] private def zero : ℝ := ⟨0⟩ @[irreducible] private def one : ℝ := ⟨1⟩ @[irreducible] private def add : ℝ → ℝ → ℝ | ⟨a⟩ ⟨b⟩ := ⟨a + b⟩ @[irreducible] private def neg : ℝ → ℝ | ⟨a⟩ := ⟨-a⟩ @[irreducible] private def mul : ℝ → ℝ → ℝ | ⟨a⟩ ⟨b⟩ := ⟨a * b⟩ instance : has_zero ℝ := ⟨zero⟩ instance : has_one ℝ := ⟨one⟩ instance : has_add ℝ := ⟨add⟩ instance : has_neg ℝ := ⟨neg⟩ instance : has_mul ℝ := ⟨mul⟩ lemma zero_cauchy : (⟨0⟩ : ℝ) = 0 := show _ = zero, by rw zero lemma one_cauchy : (⟨1⟩ : ℝ) = 1 := show _ = one, by rw one lemma add_cauchy {a b} : (⟨a⟩ + ⟨b⟩ : ℝ) = ⟨a + b⟩ := show add _ _ = _, by rw add lemma neg_cauchy {a} : (-⟨a⟩ : ℝ) = ⟨-a⟩ := show neg _ = _, by rw neg lemma mul_cauchy {a b} : (⟨a⟩ * ⟨b⟩ : ℝ) = ⟨a * b⟩ := show mul _ _ = _, by rw mul instance : comm_ring ℝ := begin refine_struct { zero := 0, one := 1, mul := (*), add := (+), neg := @has_neg.neg ℝ _, sub := λ a b, a + (-b), npow := @npow_rec _ ⟨1⟩ ⟨(*)⟩, nsmul := @nsmul_rec _ ⟨0⟩ ⟨(+)⟩, gsmul := @gsmul_rec _ ⟨0⟩ ⟨(+)⟩ ⟨@has_neg.neg ℝ _⟩ }; repeat { rintro ⟨_⟩, }; try { refl }; simp [← zero_cauchy, ← one_cauchy, add_cauchy, neg_cauchy, mul_cauchy]; apply add_assoc <|> apply add_comm <|> apply mul_assoc <|> apply mul_comm <|> apply left_distrib <|> apply right_distrib <|> apply sub_eq_add_neg <|> skip end /- Extra instances to short-circuit type class resolution -/ instance : ring ℝ := by apply_instance instance : comm_semiring ℝ := by apply_instance instance : semiring ℝ := by apply_instance instance : add_comm_group ℝ := by apply_instance instance : add_group ℝ := by apply_instance instance : add_comm_monoid ℝ := by apply_instance instance : add_monoid ℝ := by apply_instance instance : add_left_cancel_semigroup ℝ := by apply_instance instance : add_right_cancel_semigroup ℝ := by apply_instance instance : add_comm_semigroup ℝ := by apply_instance instance : add_semigroup ℝ := by apply_instance instance : comm_monoid ℝ := by apply_instance instance : monoid ℝ := by apply_instance instance : comm_semigroup ℝ := by apply_instance instance : semigroup ℝ := by apply_instance instance : has_sub ℝ := by apply_instance instance : inhabited ℝ := ⟨0⟩ /-- The real numbers are a `*`-ring, with the trivial `*`-structure. -/ instance : star_ring ℝ := star_ring_of_comm /-- Coercion `ℚ` → `ℝ` as a `ring_hom`. Note that this is `cau_seq.completion.of_rat`, not `rat.cast`. -/ def of_rat : ℚ →+* ℝ := by refine_struct { to_fun := of_cauchy ∘ of_rat }; simp [of_rat_one, of_rat_zero, of_rat_mul, of_rat_add, one_cauchy, zero_cauchy, ← mul_cauchy, ← add_cauchy] lemma of_rat_apply (x : ℚ) : of_rat x = of_cauchy (cau_seq.completion.of_rat x) := rfl /-- Make a real number from a Cauchy sequence of rationals (by taking the equivalence class). -/ def mk (x : cau_seq ℚ abs) : ℝ := ⟨cau_seq.completion.mk x⟩ theorem mk_eq {f g : cau_seq ℚ abs} : mk f = mk g ↔ f ≈ g := ext_cauchy_iff.trans mk_eq @[irreducible] private def lt : ℝ → ℝ → Prop | ⟨x⟩ ⟨y⟩ := quotient.lift_on₂ x y (<) $ λ f₁ g₁ f₂ g₂ hf hg, propext $ ⟨λ h, lt_of_eq_of_lt (setoid.symm hf) (lt_of_lt_of_eq h hg), λ h, lt_of_eq_of_lt hf (lt_of_lt_of_eq h (setoid.symm hg))⟩ instance : has_lt ℝ := ⟨lt⟩ lemma lt_cauchy {f g} : (⟨⟦f⟧⟩ : ℝ) < ⟨⟦g⟧⟩ ↔ f < g := show lt _ _ ↔ _, by rw lt; refl @[simp] theorem mk_lt {f g : cau_seq ℚ abs} : mk f < mk g ↔ f < g := lt_cauchy lemma mk_zero : mk 0 = 0 := by rw ← zero_cauchy; refl lemma mk_one : mk 1 = 1 := by rw ← one_cauchy; refl lemma mk_add {f g : cau_seq ℚ abs} : mk (f + g) = mk f + mk g := by simp [mk, add_cauchy] lemma mk_mul {f g : cau_seq ℚ abs} : mk (f * g) = mk f * mk g := by simp [mk, mul_cauchy] lemma mk_neg {f : cau_seq ℚ abs} : mk (-f) = -mk f := by simp [mk, neg_cauchy] @[simp] theorem mk_pos {f : cau_seq ℚ abs} : 0 < mk f ↔ pos f := by rw [← mk_zero, mk_lt]; exact iff_of_eq (congr_arg pos (sub_zero f)) @[irreducible] private def le (x y : ℝ) : Prop := x < y ∨ x = y instance : has_le ℝ := ⟨le⟩ private lemma le_def {x y : ℝ} : x ≤ y ↔ x < y ∨ x = y := show le _ _ ↔ _, by rw le @[simp] theorem mk_le {f g : cau_seq ℚ abs} : mk f ≤ mk g ↔ f ≤ g := by simp [le_def, mk_eq]; refl @[elab_as_eliminator] protected lemma ind_mk {C : real → Prop} (x : real) (h : ∀ y, C (mk y)) : C x := begin cases x with x, induction x using quot.induction_on with x, exact h x end theorem add_lt_add_iff_left {a b : ℝ} (c : ℝ) : c + a < c + b ↔ a < b := begin induction a using real.ind_mk, induction b using real.ind_mk, induction c using real.ind_mk, simp only [mk_lt, ← mk_add], show pos _ ↔ pos _, rw add_sub_add_left_eq_sub end instance : partial_order ℝ := { le := (≤), lt := (<), lt_iff_le_not_le := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa using lt_iff_le_not_le, le_refl := λ a, a.ind_mk (by intro a; rw mk_le), le_trans := λ a b c, real.ind_mk a $ λ a, real.ind_mk b $ λ b, real.ind_mk c $ λ c, by simpa using le_trans, lt_iff_le_not_le := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa using lt_iff_le_not_le, le_antisymm := λ a b, real.ind_mk a $ λ a, real.ind_mk b $ λ b, by simpa [mk_eq] using @cau_seq.le_antisymm _ _ a b } instance : preorder ℝ := by apply_instance theorem of_rat_lt {x y : ℚ} : of_rat x < of_rat y ↔ x < y := begin rw [mk_lt] {md := tactic.transparency.semireducible}, exact const_lt end protected theorem zero_lt_one : (0 : ℝ) < 1 := by convert of_rat_lt.2 zero_lt_one; simp protected theorem mul_pos {a b : ℝ} : 0 < a → 0 < b → 0 < a * b := begin induction a using real.ind_mk with a, induction b using real.ind_mk with b, simpa only [mk_lt, mk_pos, ← mk_mul] using cau_seq.mul_pos end instance : ordered_ring ℝ := { add_le_add_left := begin simp only [le_iff_eq_or_lt], rintros a b ⟨rfl, h⟩, { simp }, { exact λ c, or.inr ((add_lt_add_iff_left c).2 ‹_›) } end, zero_le_one := le_of_lt real.zero_lt_one, mul_pos := @real.mul_pos, .. real.comm_ring, .. real.partial_order, .. real.semiring } instance : ordered_semiring ℝ := by apply_instance instance : ordered_add_comm_group ℝ := by apply_instance instance : ordered_cancel_add_comm_monoid ℝ := by apply_instance instance : ordered_add_comm_monoid ℝ := by apply_instance instance : nontrivial ℝ := ⟨⟨0, 1, ne_of_lt real.zero_lt_one⟩⟩ open_locale classical noncomputable instance : linear_order ℝ := { le_total := begin intros a b, induction a using real.ind_mk with a, induction b using real.ind_mk with b, simpa using le_total a b, end, decidable_le := by apply_instance, .. real.partial_order } noncomputable instance : linear_ordered_comm_ring ℝ := { .. real.nontrivial, .. real.ordered_ring, .. real.comm_ring, .. real.linear_order } /- Extra instances to short-circuit type class resolution -/ noncomputable instance : linear_ordered_ring ℝ := by apply_instance noncomputable instance : linear_ordered_semiring ℝ := by apply_instance instance : domain ℝ := { .. real.nontrivial, .. real.comm_ring, .. linear_ordered_ring.to_domain } /-- The real numbers are an ordered `*`-ring, with the trivial `*`-structure. -/ instance : star_ordered_ring ℝ := { star_mul_self_nonneg := λ r, mul_self_nonneg r, } @[irreducible] private noncomputable def inv' : ℝ → ℝ | ⟨a⟩ := ⟨a⁻¹⟩ noncomputable instance : has_inv ℝ := ⟨inv'⟩ lemma inv_cauchy {f} : (⟨f⟩ : ℝ)⁻¹ = ⟨f⁻¹⟩ := show inv' _ = _, by rw inv' noncomputable instance : linear_ordered_field ℝ := { inv := has_inv.inv, mul_inv_cancel := begin rintros ⟨a⟩ h, rw mul_comm, simp only [inv_cauchy, mul_cauchy, ← one_cauchy, ← zero_cauchy, ne.def] at *, exact cau_seq.completion.inv_mul_cancel h, end, inv_zero := by simp [← zero_cauchy, inv_cauchy], ..real.linear_ordered_comm_ring, ..real.domain } /- Extra instances to short-circuit type class resolution -/ noncomputable instance : linear_ordered_add_comm_group ℝ := by apply_instance noncomputable instance field : field ℝ := by apply_instance noncomputable instance : division_ring ℝ := by apply_instance noncomputable instance : integral_domain ℝ := by apply_instance noncomputable instance : distrib_lattice ℝ := by apply_instance noncomputable instance : lattice ℝ := by apply_instance noncomputable instance : semilattice_inf ℝ := by apply_instance noncomputable instance : semilattice_sup ℝ := by apply_instance noncomputable instance : has_inf ℝ := by apply_instance noncomputable instance : has_sup ℝ := by apply_instance noncomputable instance decidable_lt (a b : ℝ) : decidable (a < b) := by apply_instance noncomputable instance decidable_le (a b : ℝ) : decidable (a ≤ b) := by apply_instance noncomputable instance decidable_eq (a b : ℝ) : decidable (a = b) := by apply_instance open rat @[simp] theorem of_rat_eq_cast : ∀ x : ℚ, of_rat x = x := of_rat.eq_rat_cast theorem le_mk_of_forall_le {f : cau_seq ℚ abs} : (∃ i, ∀ j ≥ i, x ≤ f j) → x ≤ mk f := begin intro h, induction x using real.ind_mk with x, apply le_of_not_lt, rw mk_lt, rintro ⟨K, K0, hK⟩, obtain ⟨i, H⟩ := exists_forall_ge_and h (exists_forall_ge_and hK (f.cauchy₃ $ half_pos K0)), apply not_lt_of_le (H _ (le_refl _)).1, rw ← of_rat_eq_cast, rw [mk_lt] {md := tactic.transparency.semireducible}, refine ⟨_, half_pos K0, i, λ j ij, _⟩, have := add_le_add (H _ ij).2.1 (le_of_lt (abs_lt.1 $ (H _ (le_refl _)).2.2 _ ij).1), rwa [← sub_eq_add_neg, sub_self_div_two, sub_apply, sub_add_sub_cancel] at this end theorem mk_le_of_forall_le {f : cau_seq ℚ abs} {x : ℝ} (h : ∃ i, ∀ j ≥ i, (f j : ℝ) ≤ x) : mk f ≤ x := begin cases h with i H, rw [← neg_le_neg_iff, ← mk_neg], exact le_mk_of_forall_le ⟨i, λ j ij, by simp [H _ ij]⟩ end theorem mk_near_of_forall_near {f : cau_seq ℚ abs} {x : ℝ} {ε : ℝ} (H : ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) ≤ ε) : abs (mk f - x) ≤ ε := abs_sub_le_iff.2 ⟨sub_le_iff_le_add'.2 $ mk_le_of_forall_le $ H.imp $ λ i h j ij, sub_le_iff_le_add'.1 (abs_sub_le_iff.1 $ h j ij).1, sub_le.1 $ le_mk_of_forall_le $ H.imp $ λ i h j ij, sub_le.1 (abs_sub_le_iff.1 $ h j ij).2⟩ instance : archimedean ℝ := archimedean_iff_rat_le.2 $ λ x, real.ind_mk x $ λ f, let ⟨M, M0, H⟩ := f.bounded' 0 in ⟨M, mk_le_of_forall_le ⟨0, λ i _, rat.cast_le.2 $ le_of_lt (abs_lt.1 (H i)).2⟩⟩ noncomputable instance : floor_ring ℝ := archimedean.floor_ring _ theorem is_cau_seq_iff_lift {f : ℕ → ℚ} : is_cau_seq abs f ↔ is_cau_seq abs (λ i, (f i : ℝ)) := ⟨λ H ε ε0, let ⟨δ, δ0, δε⟩ := exists_pos_rat_lt ε0 in (H _ δ0).imp $ λ i hi j ij, lt_trans (by simpa using (@rat.cast_lt ℝ _ _ _).2 (hi _ ij)) δε, λ H ε ε0, (H _ (rat.cast_pos.2 ε0)).imp $ λ i hi j ij, (@rat.cast_lt ℝ _ _ _).1 $ by simpa using hi _ ij⟩ theorem of_near (f : ℕ → ℚ) (x : ℝ) (h : ∀ ε > 0, ∃ i, ∀ j ≥ i, abs ((f j : ℝ) - x) < ε) : ∃ h', real.mk ⟨f, h'⟩ = x := ⟨is_cau_seq_iff_lift.2 (of_near _ (const abs x) h), sub_eq_zero.1 $ abs_eq_zero.1 $ eq_of_le_of_forall_le_of_dense (abs_nonneg _) $ λ ε ε0, mk_near_of_forall_near $ (h _ ε0).imp (λ i h j ij, le_of_lt (h j ij))⟩ theorem exists_floor (x : ℝ) : ∃ (ub : ℤ), (ub:ℝ) ≤ x ∧ ∀ (z : ℤ), (z:ℝ) ≤ x → z ≤ ub := int.exists_greatest_of_bdd (let ⟨n, hn⟩ := exists_int_gt x in ⟨n, λ z h', int.cast_le.1 $ le_trans h' $ le_of_lt hn⟩) (let ⟨n, hn⟩ := exists_int_lt x in ⟨n, le_of_lt hn⟩) theorem exists_sup (S : set ℝ) : (∃ x, x ∈ S) → (∃ x, ∀ y ∈ S, y ≤ x) → ∃ x, ∀ y, x ≤ y ↔ ∀ z ∈ S, z ≤ y | ⟨L, hL⟩ ⟨U, hU⟩ := begin choose f hf using begin refine λ d : ℕ, @int.exists_greatest_of_bdd (λ n, ∃ y ∈ S, (n:ℝ) ≤ y * d) _ _, { cases exists_int_gt U with k hk, refine ⟨k * d, λ z h, _⟩, rcases h with ⟨y, yS, hy⟩, refine int.cast_le.1 (le_trans hy _), simp, exact mul_le_mul_of_nonneg_right (le_trans (hU _ yS) (le_of_lt hk)) (nat.cast_nonneg _) }, { exact ⟨⌊L * d⌋, L, hL, floor_le _⟩ } end, have hf₁ : ∀ n > 0, ∃ y ∈ S, ((f n / n:ℚ):ℝ) ≤ y := λ n n0, let ⟨y, yS, hy⟩ := (hf n).1 in ⟨y, yS, by simpa using (div_le_iff ((nat.cast_pos.2 n0):((_:ℝ) < _))).2 hy⟩, have hf₂ : ∀ (n > 0) (y ∈ S), (y - (n:ℕ)⁻¹ : ℝ) < (f n / n:ℚ), { intros n n0 y yS, have := lt_of_lt_of_le (sub_one_lt_floor _) (int.cast_le.2 $ (hf n).2 _ ⟨y, yS, floor_le _⟩), simp [-sub_eq_add_neg], rwa [lt_div_iff ((nat.cast_pos.2 n0):((_:ℝ) < _)), sub_mul, _root_.inv_mul_cancel], exact ne_of_gt (nat.cast_pos.2 n0) }, suffices hg, let g : cau_seq ℚ abs := ⟨λ n, f n / n, hg⟩, refine ⟨mk g, λ y, ⟨λ h x xS, le_trans _ h, λ h, _⟩⟩, { refine le_of_forall_ge_of_dense (λ z xz, _), cases exists_nat_gt (x - z)⁻¹ with K hK, refine le_mk_of_forall_le ⟨K, λ n nK, _⟩, replace xz := sub_pos.2 xz, replace hK := le_trans (le_of_lt hK) (nat.cast_le.2 nK), have n0 : 0 < n := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 xz) hK), refine le_trans _ (le_of_lt $ hf₂ _ n0 _ xS), rwa [le_sub, inv_le ((nat.cast_pos.2 n0):((_:ℝ) < _)) xz] }, { exact mk_le_of_forall_le ⟨1, λ n n1, let ⟨x, xS, hx⟩ := hf₁ _ n1 in le_trans hx (h _ xS)⟩ }, intros ε ε0, suffices : ∀ j k ≥ nat_ceil ε⁻¹, (f j / j - f k / k : ℚ) < ε, { refine ⟨_, λ j ij, abs_lt.2 ⟨_, this _ _ ij (le_refl _)⟩⟩, rw [neg_lt, neg_sub], exact this _ _ (le_refl _) ij }, intros j k ij ik, replace ij := le_trans (le_nat_ceil _) (nat.cast_le.2 ij), replace ik := le_trans (le_nat_ceil _) (nat.cast_le.2 ik), have j0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 ε0) ij), have k0 := nat.cast_pos.1 (lt_of_lt_of_le (inv_pos.2 ε0) ik), rcases hf₁ _ j0 with ⟨y, yS, hy⟩, refine lt_of_lt_of_le ((@rat.cast_lt ℝ _ _ _).1 _) ((inv_le ε0 (nat.cast_pos.2 k0)).1 ik), simpa using sub_lt_iff_lt_add'.2 (lt_of_le_of_lt hy $ sub_lt_iff_lt_add.1 $ hf₂ _ k0 _ yS) end noncomputable instance : has_Sup ℝ := ⟨λ S, if h : (∃ x, x ∈ S) ∧ (∃ x, ∀ y ∈ S, y ≤ x) then classical.some (exists_sup S h.1 h.2) else 0⟩ lemma Sup_def (S : set ℝ) : Sup S = if h : (∃ x, x ∈ S) ∧ (∃ x, ∀ y ∈ S, y ≤ x) then classical.some (exists_sup S h.1 h.2) else 0 := rfl theorem Sup_le (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {y} : Sup S ≤ y ↔ ∀ z ∈ S, z ≤ y := by simp [Sup_def, h₁, h₂]; exact classical.some_spec (exists_sup S h₁ h₂) y theorem lt_Sup (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {y} : y < Sup S ↔ ∃ z ∈ S, y < z := by simpa [not_forall] using not_congr (@Sup_le S h₁ h₂ y) theorem le_Sup (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, y ≤ x) {x} (xS : x ∈ S) : x ≤ Sup S := (Sup_le S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS theorem Sup_le_ub (S : set ℝ) (h₁ : ∃ x, x ∈ S) {ub} (h₂ : ∀ y ∈ S, y ≤ ub) : Sup S ≤ ub := (Sup_le S h₁ ⟨_, h₂⟩).2 h₂ protected lemma is_lub_Sup {s : set ℝ} {a b : ℝ} (ha : a ∈ s) (hb : b ∈ upper_bounds s) : is_lub s (Sup s) := ⟨λ x xs, real.le_Sup s ⟨_, hb⟩ xs, λ u h, real.Sup_le_ub _ ⟨_, ha⟩ h⟩ noncomputable instance : has_Inf ℝ := ⟨λ S, -Sup {x | -x ∈ S}⟩ lemma Inf_def (S : set ℝ) : Inf S = -Sup {x | -x ∈ S} := rfl theorem le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {y} : y ≤ Inf S ↔ ∀ z ∈ S, y ≤ z := begin refine le_neg.trans ((Sup_le _ _ _).trans _), { cases h₁ with x xS, exact ⟨-x, by simp [xS]⟩ }, { cases h₂ with ub h, exact ⟨-ub, λ y hy, le_neg.1 $ h _ hy⟩ }, split; intros H z hz, { exact neg_le_neg_iff.1 (H _ $ by simp [hz]) }, { exact le_neg.2 (H _ hz) } end section -- this proof times out without this local attribute [instance, priority 1000] classical.prop_decidable theorem Inf_lt (S : set ℝ) (h₁ : ∃ x, x ∈ S) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {y} : Inf S < y ↔ ∃ z ∈ S, z < y := by simpa [not_forall] using not_congr (@le_Inf S h₁ h₂ y) end theorem Inf_le (S : set ℝ) (h₂ : ∃ x, ∀ y ∈ S, x ≤ y) {x} (xS : x ∈ S) : Inf S ≤ x := (le_Inf S ⟨_, xS⟩ h₂).1 (le_refl _) _ xS theorem lb_le_Inf (S : set ℝ) (h₁ : ∃ x, x ∈ S) {lb} (h₂ : ∀ y ∈ S, lb ≤ y) : lb ≤ Inf S := (le_Inf S h₁ ⟨_, h₂⟩).2 h₂ noncomputable instance : conditionally_complete_linear_order ℝ := { Sup := has_Sup.Sup, Inf := has_Inf.Inf, le_cSup := assume (s : set ℝ) (a : ℝ) (_ : bdd_above s) (_ : a ∈ s), show a ≤ Sup s, from le_Sup s ‹bdd_above s› ‹a ∈ s›, cSup_le := assume (s : set ℝ) (a : ℝ) (_ : s.nonempty) (H : ∀b∈s, b ≤ a), show Sup s ≤ a, from Sup_le_ub s ‹s.nonempty› H, cInf_le := assume (s : set ℝ) (a : ℝ) (_ : bdd_below s) (_ : a ∈ s), show Inf s ≤ a, from Inf_le s ‹bdd_below s› ‹a ∈ s›, le_cInf := assume (s : set ℝ) (a : ℝ) (_ : s.nonempty) (H : ∀b∈s, a ≤ b), show a ≤ Inf s, from lb_le_Inf s ‹s.nonempty› H, ..real.linear_order, ..real.lattice} lemma lt_Inf_add_pos {s : set ℝ} (h : bdd_below s) (h' : s.nonempty) {ε : ℝ} (hε : 0 < ε) : ∃ a ∈ s, a < Inf s + ε := (Inf_lt _ h' h).1 $ lt_add_of_pos_right _ hε lemma add_pos_lt_Sup {s : set ℝ} (h : bdd_above s) (h' : s.nonempty) {ε : ℝ} (hε : ε < 0) : ∃ a ∈ s, Sup s + ε < a := (real.lt_Sup _ h' h).1 $ add_lt_iff_neg_left.mpr hε lemma Inf_le_iff {s : set ℝ} (h : bdd_below s) (h' : s.nonempty) {a : ℝ} : Inf s ≤ a ↔ ∀ ε, 0 < ε → ∃ x ∈ s, x < a + ε := begin rw le_iff_forall_pos_lt_add, split; intros H ε ε_pos, { exact exists_lt_of_cInf_lt h' (H ε ε_pos) }, { rcases H ε ε_pos with ⟨x, x_in, hx⟩, exact cInf_lt_of_lt h x_in hx } end lemma le_Sup_iff {s : set ℝ} (h : bdd_above s) (h' : s.nonempty) {a : ℝ} : a ≤ Sup s ↔ ∀ ε, ε < 0 → ∃ x ∈ s, a + ε < x := begin rw le_iff_forall_pos_lt_add, refine ⟨λ H ε ε_neg, _, λ H ε ε_pos, _⟩, { exact exists_lt_of_lt_cSup h' (lt_sub_iff_add_lt.mp (H _ (neg_pos.mpr ε_neg))) }, { rcases H _ (neg_lt_zero.mpr ε_pos) with ⟨x, x_in, hx⟩, exact sub_lt_iff_lt_add.mp (lt_cSup_of_lt h x_in hx) } end theorem Sup_empty : Sup (∅ : set ℝ) = 0 := dif_neg $ by simp theorem Sup_of_not_bdd_above {s : set ℝ} (hs : ¬ bdd_above s) : Sup s = 0 := dif_neg $ assume h, hs h.2 theorem Sup_univ : Sup (@set.univ ℝ) = 0 := real.Sup_of_not_bdd_above $ λ ⟨x, h⟩, not_le_of_lt (lt_add_one _) $ h (set.mem_univ _) theorem Inf_empty : Inf (∅ : set ℝ) = 0 := by simp [Inf_def, Sup_empty] theorem Inf_of_not_bdd_below {s : set ℝ} (hs : ¬ bdd_below s) : Inf s = 0 := have bdd_above {x | -x ∈ s} → bdd_below s, from assume ⟨b, hb⟩, ⟨-b, assume x hxs, neg_le.2 $ hb $ by simp [hxs]⟩, have ¬ bdd_above {x | -x ∈ s}, from mt this hs, neg_eq_zero.2 $ Sup_of_not_bdd_above $ this /-- As `0` is the default value for `real.Sup` of the empty set or sets which are not bounded above, it suffices to show that `S` is bounded below by `0` to show that `0 ≤ Inf S`. -/ lemma Sup_nonneg (S : set ℝ) (hS : ∀ x ∈ S, (0:ℝ) ≤ x) : 0 ≤ Sup S := begin rcases S.eq_empty_or_nonempty with rfl | ⟨y, hy⟩, { simp [Sup_empty] }, { apply dite _ (λ h, le_cSup_of_le h hy $ hS y hy) (λ h, (Sup_of_not_bdd_above h).ge) } end /-- As `0` is the default value for `real.Sup` of the empty set, it suffices to show that `S` is bounded above by `0` to show that `Sup S ≤ 0`. -/ lemma Sup_nonpos (S : set ℝ) (hS : ∀ x ∈ S, x ≤ (0:ℝ)) : Sup S ≤ 0 := begin rcases S.eq_empty_or_nonempty with rfl | hS₂, { simp [Sup_empty] }, { apply Sup_le_ub _ hS₂ hS, } end /-- As `0` is the default value for `real.Inf` of the empty set, it suffices to show that `S` is bounded below by `0` to show that `0 ≤ Inf S`. -/ lemma Inf_nonneg (S : set ℝ) (hS : ∀ x ∈ S, (0:ℝ) ≤ x) : 0 ≤ Inf S := begin rcases S.eq_empty_or_nonempty with rfl | hS₂, { simp [Inf_empty] }, { apply lb_le_Inf S hS₂ hS } end /-- As `0` is the default value for `real.Inf` of the empty set or sets which are not bounded below, it suffices to show that `S` is bounded above by `0` to show that `Inf S ≤ 0`. -/ lemma Inf_nonpos (S : set ℝ) (hS : ∀ x ∈ S, x ≤ (0:ℝ)) : Inf S ≤ 0 := begin rcases S.eq_empty_or_nonempty with rfl | ⟨y, hy⟩, { simp [Inf_empty] }, { apply dite _ (λ h, cInf_le_of_le h hy $ hS y hy) (λ h, (Inf_of_not_bdd_below h).le) } end theorem cau_seq_converges (f : cau_seq ℝ abs) : ∃ x, f ≈ const abs x := begin let S := {x : ℝ | const abs x < f}, have lb : ∃ x, x ∈ S := exists_lt f, have ub' : ∀ x, f < const abs x → ∀ y ∈ S, y ≤ x := λ x h y yS, le_of_lt $ const_lt.1 $ cau_seq.lt_trans yS h, have ub : ∃ x, ∀ y ∈ S, y ≤ x := (exists_gt f).imp ub', refine ⟨Sup S, ((lt_total _ _).resolve_left (λ h, _)).resolve_right (λ h, _)⟩, { rcases h with ⟨ε, ε0, i, ih⟩, refine not_lt_of_le (Sup_le_ub S lb (ub' _ _)) (sub_lt_self _ (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, sub_right_comm, le_sub_iff_add_le, add_halves], exact ih _ ij }, { rcases h with ⟨ε, ε0, i, ih⟩, refine not_lt_of_le (le_Sup S ub _) ((lt_add_iff_pos_left _).2 (half_pos ε0)), refine ⟨_, half_pos ε0, i, λ j ij, _⟩, rw [sub_apply, const_apply, add_comm, ← sub_sub, le_sub_iff_add_le, add_halves], exact ih _ ij } end noncomputable instance : cau_seq.is_complete ℝ abs := ⟨cau_seq_converges⟩ end real
206436602e33f2a350d5218494b15722e621954a
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/Lean3Lib/init/meta/match_tactic.lean
9f4126d88b62a5e887bf51589ea66dd7a35e8ba9
[]
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,210
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 -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.meta.interactive_base import Mathlib.Lean3Lib.init.function namespace Mathlib namespace tactic /-- A pattern is an expression `target` containing temporary metavariables. A pattern also contains a list of `outputs` which also depend on these temporary metavariables. When we run `match p e`, the system will match `p.target` with `e` and assign the temporary metavariables. It then returns the outputs with the assigned variables. ## Fields - `target` Term to match. Contains temporary metavariables. - `uoutput` List of universes that are returned on a successful match. - `moutput` List of expressions that are returned on a successful match. - `nuvars` Number of (temporary) universe metavariables in this pattern. - `nmvars` Number of (temporary) metavariables in this pattern. ## Example The pattern for `list.cons h t` returning `h` and `t` would be ``` { target := `(@list.cons ?x_0 ?x_1 ?x_2), uoutput := [], moutput := [?x_1,?x_2], nuvars := 0, nmvars := 3 } ``` -/
f4743bb0664a548625fddc9e4d9e2e9232d57876
d1a52c3f208fa42c41df8278c3d280f075eb020c
/stage0/src/Lean/Meta/ExprDefEq.lean
502d3addc8da6f272cfde824440ee7874e26c410
[ "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
66,475
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.ProjFns import Lean.Structure import Lean.Meta.WHNF import Lean.Meta.InferType import Lean.Meta.FunInfo import Lean.Meta.Check import Lean.Meta.Offset import Lean.Meta.ForEachExpr import Lean.Meta.UnificationHint namespace Lean.Meta /-- Return true `b` is of the form `mk a.1 ... a.n`, and `a` is not a constructor application. If `a` and `b` are constructor applications, the method returns `false` to force `isDefEq` to use `isDefEqArgs`. For example, suppose we are trying to solve the constraint ``` Fin.mk ?n ?h =?= Fin.mk n h ``` If this method is applied, the constraints are reduced to ``` n =?= (Fin.mk ?n ?h).1 h =?= (Fin.mk ?n ?h).2 ``` The first constraint produces the assignment `?n := n`. Then, the second constraint is solved using proof irrelevance without assigning `?h`. TODO: investigate better solutions for the proof irrelevance issue. The problem above can happen is other scenarios. That is, proof irrelevance may prevent us from performing desired mvar assignments. -/ private def isDefEqEtaStruct (a b : Expr) : MetaM Bool := do if !(← getConfig).etaStruct then return false else matchConstCtor b.getAppFn (fun _ => return false) fun ctorVal _ => matchConstCtor a.getAppFn (fun _ => go ctorVal) fun _ _ => return false where go ctorVal := do if ctorVal.numParams + ctorVal.numFields != b.getAppNumArgs then trace[Meta.isDefEq.eta.struct] "failed, insufficient number of arguments at{indentExpr b}" return false else if !isStructureLike (← getEnv) ctorVal.induct then trace[Meta.isDefEq.eta.struct] "failed, type is not a structure{indentExpr b}" return false else if (← isDefEq (← inferType a) (← inferType b)) then checkpointDefEq do let args := b.getAppArgs for i in [ctorVal.numParams : args.size] do let proj := mkProj ctorVal.induct (i - ctorVal.numParams) a trace[Meta.isDefEq.eta.struct] "{a} =?= {b} @ [{i - ctorVal.numParams}], {proj} =?= {args[i]}" unless (← isDefEq proj args[i]) do trace[Meta.isDefEq.eta.struct] "failed, unexpect arg #{i}, projection{indentExpr proj}\nis not defeq to{indentExpr args[i]}" return false return true else return false /-- Try to solve `a := (fun x => t) =?= b` by eta-expanding `b`. Remark: eta-reduction is not a good alternative even in a system without universe cumulativity like Lean. Example: ``` (fun x : A => f ?m) =?= f ``` The left-hand side of the constraint above it not eta-reduced because `?m` is a metavariable. -/ private def isDefEqEta (a b : Expr) : MetaM Bool := do if a.isLambda && !b.isLambda then let bType ← inferType b let bType ← whnfD bType match bType with | Expr.forallE n d _ c => let b' := mkLambda n c.binderInfo d (mkApp b (mkBVar 0)) checkpointDefEq <| Meta.isExprDefEqAux a b' | _ => pure false else return false /-- Support for `Lean.reduceBool` and `Lean.reduceNat` -/ def isDefEqNative (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t let s? ← reduceNative? s let t? ← reduceNative? t match s?, t? with | some s, some t => isDefEq s t | some s, none => isDefEq s t | none, some t => isDefEq s t | none, none => pure LBool.undef /-- Support for reducing Nat basic operations. -/ def isDefEqNat (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t if s.hasFVar || s.hasMVar || t.hasFVar || t.hasMVar then pure LBool.undef else let s? ← reduceNat? s let t? ← reduceNat? t match s?, t? with | some s, some t => isDefEq s t | some s, none => isDefEq s t | none, some t => isDefEq s t | none, none => pure LBool.undef /-- Support for constraints of the form `("..." =?= String.mk cs)` -/ def isDefEqStringLit (s t : Expr) : MetaM LBool := do let isDefEq (s t) : MetaM LBool := toLBoolM <| Meta.isExprDefEqAux s t if s.isStringLit && t.isAppOf `String.mk then isDefEq (toCtorIfLit s) t else if s.isAppOf `String.mk && t.isStringLit then isDefEq s (toCtorIfLit t) else pure LBool.undef /-- Return `true` if `e` is of the form `fun (x_1 ... x_n) => ?m x_1 ... x_n)`, and `?m` is unassigned. Remark: `n` may be 0. -/ def isEtaUnassignedMVar (e : Expr) : MetaM Bool := do match e.etaExpanded? with | some (Expr.mvar mvarId _) => if (← isReadOnlyOrSyntheticOpaqueExprMVar mvarId) then pure false else if (← isExprMVarAssigned mvarId) then pure false else pure true | _ => pure false /- First pass for `isDefEqArgs`. We unify explicit arguments, *and* easy cases Here, we say a case is easy if it is of the form ?m =?= t or t =?= ?m where `?m` is unassigned. These easy cases are not just an optimization. When `?m` is a function, by assigning it to t, we make sure a unification constraint (in the explicit part) ``` ?m t =?= f s ``` is not higher-order. We also handle the eta-expanded cases: ``` fun x₁ ... xₙ => ?m x₁ ... xₙ =?= t t =?= fun x₁ ... xₙ => ?m x₁ ... xₙ ``` This is important because type inference often produces eta-expanded terms, and without this extra case, we could introduce counter intuitive behavior. Pre: `paramInfo.size <= args₁.size = args₂.size` -/ private partial def isDefEqArgsFirstPass (paramInfo : Array ParamInfo) (args₁ args₂ : Array Expr) : MetaM (Option (Array Nat)) := do let rec loop (i : Nat) (postponed : Array Nat) := do if h : i < paramInfo.size then let info := paramInfo.get ⟨i, h⟩ let a₁ := args₁[i] let a₂ := args₂[i] if !info.isExplicit then if (← isEtaUnassignedMVar a₁ <||> isEtaUnassignedMVar a₂) then if (← Meta.isExprDefEqAux a₁ a₂) then loop (i+1) postponed else pure none else loop (i+1) (postponed.push i) else if (← Meta.isExprDefEqAux a₁ a₂) then loop (i+1) postponed else pure none else pure (some postponed) loop 0 #[] @[specialize] private def trySynthPending (e : Expr) : MetaM Bool := do let mvarId? ← getStuckMVar? e match mvarId? with | some mvarId => Meta.synthPending mvarId | none => pure false private partial def isDefEqArgs (f : Expr) (args₁ args₂ : Array Expr) : MetaM Bool := if h : args₁.size = args₂.size then do let finfo ← getFunInfoNArgs f args₁.size let (some postponed) ← isDefEqArgsFirstPass finfo.paramInfo args₁ args₂ | pure false let rec processOtherArgs (i : Nat) : MetaM Bool := do if h₁ : i < args₁.size then let a₁ := args₁.get ⟨i, h₁⟩ let a₂ := args₂.get ⟨i, Eq.subst h h₁⟩ if (← Meta.isExprDefEqAux a₁ a₂) then processOtherArgs (i+1) else pure false else pure true if (← processOtherArgs finfo.paramInfo.size) then postponed.allM fun i => do /- Second pass: unify implicit arguments. In the second pass, we make sure we are unfolding at least non reducible definitions (default setting). -/ let a₁ := args₁[i] let a₂ := args₂[i] let info := finfo.paramInfo[i] if info.isInstImplicit then discard <| trySynthPending a₁ discard <| trySynthPending a₂ withAtLeastTransparency TransparencyMode.default <| Meta.isExprDefEqAux a₁ a₂ else pure false else pure false /-- Check whether the types of the free variables at `fvars` are definitionally equal to the types at `ds₂`. Pre: `fvars.size == ds₂.size` This method also updates the set of local instances, and invokes the continuation `k` with the updated set. We can't use `withNewLocalInstances` because the `isDeq fvarType d₂` may use local instances. -/ @[specialize] partial def isDefEqBindingDomain (fvars : Array Expr) (ds₂ : Array Expr) (k : MetaM Bool) : MetaM Bool := let rec loop (i : Nat) := do if h : i < fvars.size then do let fvar := fvars.get ⟨i, h⟩ let fvarDecl ← getFVarLocalDecl fvar let fvarType := fvarDecl.type let d₂ := ds₂[i] if (← Meta.isExprDefEqAux fvarType d₂) then match (← isClass? fvarType) with | some className => withNewLocalInstance className fvar <| loop (i+1) | none => loop (i+1) else pure false else k loop 0 /- Auxiliary function for `isDefEqBinding` for handling binders `forall/fun`. It accumulates the new free variables in `fvars`, and declare them at `lctx`. We use the domain types of `e₁` to create the new free variables. We store the domain types of `e₂` at `ds₂`. -/ private partial def isDefEqBindingAux (lctx : LocalContext) (fvars : Array Expr) (e₁ e₂ : Expr) (ds₂ : Array Expr) : MetaM Bool := let process (n : Name) (d₁ d₂ b₁ b₂ : Expr) : MetaM Bool := do let d₁ := d₁.instantiateRev fvars let d₂ := d₂.instantiateRev fvars let fvarId ← mkFreshFVarId let lctx := lctx.mkLocalDecl fvarId n d₁ let fvars := fvars.push (mkFVar fvarId) isDefEqBindingAux lctx fvars b₁ b₂ (ds₂.push d₂) match e₁, e₂ with | Expr.forallE n d₁ b₁ _, Expr.forallE _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂ | Expr.lam n d₁ b₁ _, Expr.lam _ d₂ b₂ _ => process n d₁ d₂ b₁ b₂ | _, _ => withReader (fun ctx => { ctx with lctx := lctx }) do isDefEqBindingDomain fvars ds₂ do Meta.isExprDefEqAux (e₁.instantiateRev fvars) (e₂.instantiateRev fvars) @[inline] private def isDefEqBinding (a b : Expr) : MetaM Bool := do let lctx ← getLCtx isDefEqBindingAux lctx #[] a b #[] private def checkTypesAndAssign (mvar : Expr) (v : Expr) : MetaM Bool := traceCtx `Meta.isDefEq.assign.checkTypes do if !mvar.isMVar then trace[Meta.isDefEq.assign.final] "metavariable expected at {mvar} := {v}" return false else -- must check whether types are definitionally equal or not, before assigning and returning true let mvarType ← inferType mvar let vType ← inferType v if (← withTransparency TransparencyMode.default <| Meta.isExprDefEqAux mvarType vType) then trace[Meta.isDefEq.assign.final] "{mvar} := {v}" assignExprMVar mvar.mvarId! v pure true else trace[Meta.isDefEq.assign.typeMismatch] "{mvar} : {mvarType} := {v} : {vType}" pure false /-- Auxiliary method for solving constraints of the form `?m xs := v`. It creates a lambda using `mkLambdaFVars ys v`, where `ys` is a superset of `xs`. `ys` is often equal to `xs`. It is a bigger when there are let-declaration dependencies in `xs`. For example, suppose we have `xs` of the form `#[a, c]` where ``` a : Nat b : Nat := f a c : b = a ``` In this scenario, the type of `?m` is `(x1 : Nat) -> (x2 : f x1 = x1) -> C[x1, x2]`, and type of `v` is `C[a, c]`. Note that, `?m a c` is type correct since `f a = a` is definitionally equal to the type of `c : b = a`, and the type of `?m a c` is equal to the type of `v`. Note that `fun xs => v` is the term `fun (x1 : Nat) (x2 : b = x1) => v` which has type `(x1 : Nat) -> (x2 : b = x1) -> C[x1, x2]` which is not definitionally equal to the type of `?m`, and may not even be type correct. The issue here is that we are not capturing the `let`-declarations. This method collects let-declarations `y` occurring between `xs[0]` and `xs.back` s.t. some `x` in `xs` depends on `y`. `ys` is the `xs` with these extra let-declarations included. In the example above, `ys` is `#[a, b, c]`, and `mkLambdaFVars ys v` produces `fun a => let b := f a; fun (c : b = a) => v` which has a type definitionally equal to the type of `?m`. Recall that the method `checkAssignment` ensures `v` does not contain offending `let`-declarations. This method assumes that for any `xs[i]` and `xs[j]` where `i < j`, we have that `index of xs[i]` < `index of xs[j]`. where the index is the position in the local context. -/ private partial def mkLambdaFVarsWithLetDeps (xs : Array Expr) (v : Expr) : MetaM (Option Expr) := do if not (← hasLetDeclsInBetween) then mkLambdaFVars xs v else let ys ← addLetDeps trace[Meta.debug] "ys: {ys}, v: {v}" mkLambdaFVars ys v where /- Return true if there are let-declarions between `xs[0]` and `xs[xs.size-1]`. We use it a quick-check to avoid the more expensive collection procedure. -/ hasLetDeclsInBetween : MetaM Bool := do let check (lctx : LocalContext) : Bool := Id.run <| do let start := lctx.getFVar! xs[0] |>.index let stop := lctx.getFVar! xs.back |>.index for i in [start+1:stop] do match lctx.getAt? i with | some localDecl => if localDecl.isLet then return true | _ => pure () return false if xs.size <= 1 then pure false else check (← getLCtx) /- Traverse `e` and stores in the state `NameHashSet` any let-declaration with index greater than `(← read)`. The context `Nat` is the position of `xs[0]` in the local context. -/ collectLetDeclsFrom (e : Expr) : ReaderT Nat (StateRefT FVarIdHashSet MetaM) Unit := do let rec visit (e : Expr) : MonadCacheT Expr Unit (ReaderT Nat (StateRefT FVarIdHashSet MetaM)) Unit := checkCache e fun _ => do match e with | Expr.forallE _ d b _ => visit d; visit b | Expr.lam _ d b _ => visit d; visit b | Expr.letE _ t v b _ => visit t; visit v; visit b | Expr.app f a _ => visit f; visit a | Expr.mdata _ b _ => visit b | Expr.proj _ _ b _ => visit b | Expr.fvar fvarId _ => let localDecl ← getLocalDecl fvarId if localDecl.isLet && localDecl.index > (← read) then modify fun s => s.insert localDecl.fvarId | _ => pure () visit (← instantiateMVars e) |>.run /- Auxiliary definition for traversing all declarations between `xs[0]` ... `xs.back` backwards. The `Nat` argument is the current position in the local context being visited, and it is less than or equal to the position of `xs.back` in the local context. The `Nat` context `(← read)` is the position of `xs[0]` in the local context. -/ collectLetDepsAux : Nat → ReaderT Nat (StateRefT FVarIdHashSet MetaM) Unit | 0 => return () | i+1 => do if i+1 == (← read) then return () else match (← getLCtx).getAt? (i+1) with | none => collectLetDepsAux i | some localDecl => if (← get).contains localDecl.fvarId then collectLetDeclsFrom localDecl.type match localDecl.value? with | some val => collectLetDeclsFrom val | _ => pure () collectLetDepsAux i /- Computes the set `ys`. It is a set of `FVarId`s, -/ collectLetDeps : MetaM FVarIdHashSet := do let lctx ← getLCtx let start := lctx.getFVar! xs[0] |>.index let stop := lctx.getFVar! xs.back |>.index let s := xs.foldl (init := {}) fun s x => s.insert x.fvarId! let (_, s) ← collectLetDepsAux stop |>.run start |>.run s return s /- Computes the array `ys` containing let-decls between `xs[0]` and `xs.back` that some `x` in `xs` depends on. -/ addLetDeps : MetaM (Array Expr) := do let lctx ← getLCtx let s ← collectLetDeps /- Convert `s` into the array `ys` -/ let start := lctx.getFVar! xs[0] |>.index let stop := lctx.getFVar! xs.back |>.index let mut ys := #[] for i in [start:stop+1] do match lctx.getAt? i with | none => pure () | some localDecl => if s.contains localDecl.fvarId then ys := ys.push localDecl.toExpr return ys /- Each metavariable is declared in a particular local context. We use the notation `C |- ?m : t` to denote a metavariable `?m` that was declared at the local context `C` with type `t` (see `MetavarDecl`). We also use `?m@C` as a shorthand for `C |- ?m : t` where `t` is the type of `?m`. The following method process the unification constraint ?m@C a₁ ... aₙ =?= t We say the unification constraint is a pattern IFF 1) `a₁ ... aₙ` are pairwise distinct free variables that are ​*not*​ let-variables. 2) `a₁ ... aₙ` are not in `C` 3) `t` only contains free variables in `C` and/or `{a₁, ..., aₙ}` 4) For every metavariable `?m'@C'` occurring in `t`, `C'` is a subprefix of `C` 5) `?m` does not occur in `t` Claim: we don't have to check free variable declarations. That is, if `t` contains a reference to `x : A := v`, we don't need to check `v`. Reason: The reference to `x` is a free variable, and it must be in `C` (by 1 and 3). If `x` is in `C`, then any metavariable occurring in `v` must have been defined in a strict subprefix of `C`. So, condition 4 and 5 are satisfied. If the conditions above have been satisfied, then the solution for the unification constrain is ?m := fun a₁ ... aₙ => t Now, we consider some workarounds/approximations. A1) Suppose `t` contains a reference to `x : A := v` and `x` is not in `C` (failed condition 3) (precise) solution: unfold `x` in `t`. A2) Suppose some `aᵢ` is in `C` (failed condition 2) (approximated) solution (when `config.ctxApprox` is set to true) : ignore condition and also use ?m := fun a₁ ... aₙ => t Here is an example where this approximation fails: Given `C` containing `a : nat`, consider the following two constraints ?m@C a =?= a ?m@C b =?= a If we use the approximation in the first constraint, we get ?m := fun x => x when we apply this solution to the second one we get a failure. IMPORTANT: When applying this approximation we need to make sure the abstracted term `fun a₁ ... aₙ => t` is type correct. The check can only be skipped in the pattern case described above. Consider the following example. Given the local context (α : Type) (a : α) we try to solve ?m α =?= @id α a If we use the approximation above we obtain: ?m := (fun α' => @id α' a) which is a type incorrect term. `a` has type `α` but it is expected to have type `α'`. The problem occurs because the right hand side contains a free variable `a` that depends on the free variable `α` being abstracted. Note that this dependency cannot occur in patterns. We can address this by type checking the term after abstraction. This is not a significant performance bottleneck because this case doesn't happen very often in practice (262 times when compiling stdlib on Jan 2018). The second example is trickier, but it also occurs less frequently (8 times when compiling stdlib on Jan 2018, and all occurrences were at Init/Control when we define monads and auxiliary combinators for them). We considered three options for the addressing the issue on the second example: A3) `a₁ ... aₙ` are not pairwise distinct (failed condition 1). In Lean3, we would try to approximate this case using an approach similar to A2. However, this approximation complicates the code, and is never used in the Lean3 stdlib and mathlib. A4) `t` contains a metavariable `?m'@C'` where `C'` is not a subprefix of `C`. If `?m'` is assigned, we substitute. If not, we create an auxiliary metavariable with a smaller scope. Actually, we let `elimMVarDeps` at `MetavarContext.lean` to perform this step. A5) If some `aᵢ` is not a free variable, then we use first-order unification (if `config.foApprox` is set to true) ?m a_1 ... a_i a_{i+1} ... a_{i+k} =?= f b_1 ... b_k reduces to ?M a_1 ... a_i =?= f a_{i+1} =?= b_1 ... a_{i+k} =?= b_k A6) If (m =?= v) is of the form ?m a_1 ... a_n =?= ?m b_1 ... b_k then we use first-order unification (if `config.foApprox` is set to true) A7) When `foApprox`, we may use another approximation (`constApprox`) for solving constraints of the form ``` ?m s₁ ... sₙ =?= t ``` where `s₁ ... sₙ` are arbitrary terms. We solve them by assigning the constant function to `?m`. ``` ?m := fun _ ... _ => t ``` In general, this approximation may produce bad solutions, and may prevent coercions from being tried. For example, consider the term `pure (x > 0)` with inferred type `?m Prop` and expected type `IO Bool`. In this situation, the elaborator generates the unification constraint ``` ?m Prop =?= IO Bool ``` It is not a higher-order pattern, nor first-order approximation is applicable. However, constant approximation produces the bogus solution `?m := fun _ => IO Bool`, and prevents the system from using the coercion from the decidable proposition `x > 0` to `Bool`. On the other hand, the constant approximation is desirable for elaborating the term ``` let f (x : _) := pure "hello"; f () ``` with expected type `IO String`. In this example, the following unification contraint is generated. ``` ?m () String =?= IO String ``` It is not a higher-order pattern, first-order approximation reduces it to ``` ?m () =?= IO ``` which fails to be solved. However, constant approximation solves it by assigning ``` ?m := fun _ => IO ``` Note that `f`s type is `(x : ?α) -> ?m x String`. The metavariable `?m` may depend on `x`. If `constApprox` is set to true, we use constant approximation. Otherwise, we use a heuristic to decide whether we should apply it or not. The heuristic is based on observing where the constraints above come from. In the first example, the constraint `?m Prop =?= IO Bool` come from polymorphic method where `?m` is expected to be a **function** of type `Type -> Type`. In the second example, the first argument of `?m` is used to model a **potential** dependency on `x`. By using constant approximation here, we are just saying the type of `f` does **not** depend on `x`. We claim this is a reasonable approximation in practice. Moreover, it is expected by any functional programmer used to non-dependently type languages (e.g., Haskell). We distinguish the two cases above by using the field `numScopeArgs` at `MetavarDecl`. This fiels tracks how many metavariable arguments are representing dependencies. -/ def mkAuxMVar (lctx : LocalContext) (localInsts : LocalInstances) (type : Expr) (numScopeArgs : Nat := 0) : MetaM Expr := do mkFreshExprMVarAt lctx localInsts type MetavarKind.natural Name.anonymous numScopeArgs namespace CheckAssignment builtin_initialize checkAssignmentExceptionId : InternalExceptionId ← registerInternalExceptionId `checkAssignment builtin_initialize outOfScopeExceptionId : InternalExceptionId ← registerInternalExceptionId `outOfScope structure State where cache : ExprStructMap Expr := {} structure Context where mvarId : MVarId mvarDecl : MetavarDecl fvars : Array Expr hasCtxLocals : Bool rhs : Expr abbrev CheckAssignmentM := ReaderT Context $ StateRefT State MetaM def throwCheckAssignmentFailure : CheckAssignmentM α := throw <| Exception.internal checkAssignmentExceptionId def throwOutOfScopeFVar : CheckAssignmentM α := throw <| Exception.internal outOfScopeExceptionId private def findCached? (e : Expr) : CheckAssignmentM (Option Expr) := do return (← get).cache.find? e private def cache (e r : Expr) : CheckAssignmentM Unit := do modify fun s => { s with cache := s.cache.insert e r } instance : MonadCache Expr Expr CheckAssignmentM where findCached? := findCached? cache := cache @[inline] private def visit (f : Expr → CheckAssignmentM Expr) (e : Expr) : CheckAssignmentM Expr := if !e.hasExprMVar && !e.hasFVar then pure e else checkCache e (fun _ => f e) private def addAssignmentInfo (msg : MessageData) : CheckAssignmentM MessageData := do let ctx ← read return m!"{msg} @ {mkMVar ctx.mvarId} {ctx.fvars} := {ctx.rhs}" @[inline] def run (x : CheckAssignmentM Expr) (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := do let mvarDecl ← getMVarDecl mvarId let ctx := { mvarId := mvarId, mvarDecl := mvarDecl, fvars := fvars, hasCtxLocals := hasCtxLocals, rhs := v : Context } let x : CheckAssignmentM (Option Expr) := catchInternalIds [outOfScopeExceptionId, checkAssignmentExceptionId] (do let e ← x; return some e) (fun _ => pure none) x.run ctx |>.run' {} mutual partial def checkFVar (fvar : Expr) : CheckAssignmentM Expr := do let ctxMeta ← readThe Meta.Context let ctx ← read if ctx.mvarDecl.lctx.containsFVar fvar then pure fvar else let lctx := ctxMeta.lctx match lctx.findFVar? fvar with | some (LocalDecl.ldecl (value := v) ..) => visit check v | _ => if ctx.fvars.contains fvar then pure fvar else traceM `Meta.isDefEq.assign.outOfScopeFVar do addAssignmentInfo fvar throwOutOfScopeFVar partial def checkMVar (mvar : Expr) : CheckAssignmentM Expr := do let mvarId := mvar.mvarId! let ctx ← read let mctx ← getMCtx if mvarId == ctx.mvarId then traceM `Meta.isDefEq.assign.occursCheck <| addAssignmentInfo "occurs check failed" throwCheckAssignmentFailure else match mctx.getExprAssignment? mvarId with | some v => check v | none => match mctx.findDecl? mvarId with | none => throwUnknownMVar mvarId | some mvarDecl => if ctx.hasCtxLocals then throwCheckAssignmentFailure -- It is not a pattern, then we fail and fall back to FO unification else if mvarDecl.lctx.isSubPrefixOf ctx.mvarDecl.lctx ctx.fvars then /- The local context of `mvar` - free variables being abstracted is a subprefix of the metavariable being assigned. We "substract" variables being abstracted because we use `elimMVarDeps` -/ pure mvar else if mvarDecl.depth != mctx.depth || mvarDecl.kind.isSyntheticOpaque then traceM `Meta.isDefEq.assign.readOnlyMVarWithBiggerLCtx <| addAssignmentInfo (mkMVar mvarId) throwCheckAssignmentFailure else let ctxMeta ← readThe Meta.Context if ctxMeta.config.ctxApprox && ctx.mvarDecl.lctx.isSubPrefixOf mvarDecl.lctx then /- Create an auxiliary metavariable with a smaller context and "checked" type. Note that `mvarType` may be different from `mvarDecl.type`. Example: `mvarType` contains a metavariable that we also need to reduce the context. We remove from `ctx.mvarDecl.lctx` any variable that is not in `mvarDecl.lctx` or in `ctx.fvars`. We don't need to remove the ones in `ctx.fvars` because `elimMVarDeps` will take care of them. First, we collect `toErase` the variables that need to be erased. Notat that if a variable is `ctx.fvars`, but it depends on variable at `toErase`, we must also erase it. -/ let toErase := mvarDecl.lctx.foldl (init := #[]) fun toErase localDecl => if ctx.mvarDecl.lctx.contains localDecl.fvarId then toErase else if ctx.fvars.any fun fvar => fvar.fvarId! == localDecl.fvarId then if mctx.findLocalDeclDependsOn localDecl fun fvarId => toErase.contains fvarId then -- localDecl depends on a variable that will be erased. So, we must add it to `toErase` too toErase.push localDecl.fvarId else toErase else toErase.push localDecl.fvarId let lctx := toErase.foldl (init := mvarDecl.lctx) fun lctx toEraseFVar => lctx.erase toEraseFVar /- Compute new set of local instances. -/ let localInsts := mvarDecl.localInstances.filter fun localInst => toErase.contains localInst.fvar.fvarId! let mvarType ← check mvarDecl.type let newMVar ← mkAuxMVar lctx localInsts mvarType mvarDecl.numScopeArgs modifyThe Meta.State fun s => { s with mctx := s.mctx.assignExpr mvarId newMVar } pure newMVar else traceM `Meta.isDefEq.assign.readOnlyMVarWithBiggerLCtx <| addAssignmentInfo (mkMVar mvarId) throwCheckAssignmentFailure /- Auxiliary function used to "fix" subterms of the form `?m x_1 ... x_n` where `x_i`s are free variables, and one of them is out-of-scope. See `Expr.app` case at `check`. If `ctxApprox` is true, then we solve this case by creating a fresh metavariable ?n with the correct scope, an assigning `?m := fun _ ... _ => ?n` -/ partial def assignToConstFun (mvar : Expr) (numArgs : Nat) (newMVar : Expr) : MetaM Bool := do let mvarType ← inferType mvar forallBoundedTelescope mvarType numArgs fun xs _ => do if xs.size != numArgs then pure false else let some v ← mkLambdaFVarsWithLetDeps xs newMVar | return false match (← checkAssignmentAux mvar.mvarId! #[] false v) with | some v => checkTypesAndAssign mvar v | none => return false -- See checkAssignment partial def checkAssignmentAux (mvarId : MVarId) (fvars : Array Expr) (hasCtxLocals : Bool) (v : Expr) : MetaM (Option Expr) := do run (check v) mvarId fvars hasCtxLocals v partial def checkApp (e : Expr) : CheckAssignmentM Expr := e.withApp fun f args => do let ctxMeta ← readThe Meta.Context if f.isMVar && ctxMeta.config.ctxApprox && args.all Expr.isFVar then let f ← visit checkMVar f catchInternalId outOfScopeExceptionId (do let args ← args.mapM (visit check) return mkAppN f args) (fun ex => do if !f.isMVar then throw ex else if (← isDelayedAssigned f.mvarId!) then throw ex else let eType ← inferType e let mvarType ← check eType /- Create an auxiliary metavariable with a smaller context and "checked" type, assign `?f := fun _ => ?newMVar` Note that `mvarType` may be different from `eType`. -/ let ctx ← read let newMVar ← mkAuxMVar ctx.mvarDecl.lctx ctx.mvarDecl.localInstances mvarType if (← assignToConstFun f args.size newMVar) then pure newMVar else throw ex) else let f ← visit check f let args ← args.mapM (visit check) return mkAppN f args partial def check (e : Expr) : CheckAssignmentM Expr := do match e with | Expr.mdata _ b _ => return e.updateMData! (← visit check b) | Expr.proj _ _ s _ => return e.updateProj! (← visit check s) | Expr.lam _ d b _ => return e.updateLambdaE! (← visit check d) (← visit check b) | Expr.forallE _ d b _ => return e.updateForallE! (← visit check d) (← visit check b) | Expr.letE _ t v b _ => return e.updateLet! (← visit check t) (← visit check v) (← visit check b) | Expr.bvar .. => return e | Expr.sort .. => return e | Expr.const .. => return e | Expr.lit .. => return e | Expr.fvar .. => visit checkFVar e | Expr.mvar .. => visit checkMVar e | Expr.app .. => checkApp e -- TODO: investigate whether the following feature is too expensive or not /- catchInternalIds [checkAssignmentExceptionId, outOfScopeExceptionId] (checkApp e) fun ex => do let e' ← whnfR e if e != e' then check e' else throw ex -/ end end CheckAssignment namespace CheckAssignmentQuick partial def check (hasCtxLocals ctxApprox : Bool) (mctx : MetavarContext) (lctx : LocalContext) (mvarDecl : MetavarDecl) (mvarId : MVarId) (fvars : Array Expr) (e : Expr) : Bool := let rec visit (e : Expr) : Bool := if !e.hasExprMVar && !e.hasFVar then true else match e with | Expr.mdata _ b _ => visit b | Expr.proj _ _ s _ => visit s | Expr.app f a _ => visit f && visit a | Expr.lam _ d b _ => visit d && visit b | Expr.forallE _ d b _ => visit d && visit b | Expr.letE _ t v b _ => visit t && visit v && visit b | Expr.bvar .. => true | Expr.sort .. => true | Expr.const .. => true | Expr.lit .. => true | Expr.fvar fvarId .. => if mvarDecl.lctx.contains fvarId then true else match lctx.find? fvarId with | some (LocalDecl.ldecl (value := v) ..) => false -- need expensive CheckAssignment.check | _ => if fvars.any fun x => x.fvarId! == fvarId then true else false -- We could throw an exception here, but we would have to use ExceptM. So, we let CheckAssignment.check do it | Expr.mvar mvarId' _ => match mctx.getExprAssignment? mvarId' with | some _ => false -- use CheckAssignment.check to instantiate | none => if mvarId' == mvarId then false -- occurs check failed, use CheckAssignment.check to throw exception else match mctx.findDecl? mvarId' with | none => false | some mvarDecl' => if hasCtxLocals then false -- use CheckAssignment.check else if mvarDecl'.lctx.isSubPrefixOf mvarDecl.lctx fvars then true else false -- use CheckAssignment.check visit e end CheckAssignmentQuick /-- Auxiliary function for handling constraints of the form `?m a₁ ... aₙ =?= v`. It will check whether we can perform the assignment ``` ?m := fun fvars => v ``` The result is `none` if the assignment can't be performed. The result is `some newV` where `newV` is a possibly updated `v`. This method may need to unfold let-declarations. -/ def checkAssignment (mvarId : MVarId) (fvars : Array Expr) (v : Expr) : MetaM (Option Expr) := do /- Check whether `mvarId` occurs in the type of `fvars` or not. If it does, return `none` to prevent us from creating the cyclic assignment `?m := fun fvars => v` -/ for fvar in fvars do unless (← occursCheck mvarId (← inferType fvar)) do return none if !v.hasExprMVar && !v.hasFVar then pure (some v) else let mvarDecl ← getMVarDecl mvarId let hasCtxLocals := fvars.any fun fvar => mvarDecl.lctx.containsFVar fvar let ctx ← read let mctx ← getMCtx if CheckAssignmentQuick.check hasCtxLocals ctx.config.ctxApprox mctx ctx.lctx mvarDecl mvarId fvars v then pure (some v) else let v ← instantiateMVars v CheckAssignment.checkAssignmentAux mvarId fvars hasCtxLocals v private def processAssignmentFOApproxAux (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool := match v with | Expr.app f a _ => if args.isEmpty then pure false else Meta.isExprDefEqAux args.back a <&&> Meta.isExprDefEqAux (mkAppRange mvar 0 (args.size - 1) args) f | _ => pure false /- Auxiliary method for applying first-order unification. It is an approximation. Remark: this method is trying to solve the unification constraint: ?m a₁ ... aₙ =?= v It is uses processAssignmentFOApproxAux, if it fails, it tries to unfold `v`. We have added support for unfolding here because we want to be able to solve unification problems such as ?m Unit =?= ITactic where `ITactic` is defined as def ITactic := Tactic Unit -/ private partial def processAssignmentFOApprox (mvar : Expr) (args : Array Expr) (v : Expr) : MetaM Bool := let rec loop (v : Expr) := do let cfg ← getConfig if !cfg.foApprox then pure false else trace[Meta.isDefEq.foApprox] "{mvar} {args} := {v}" let v := v.headBeta if (← checkpointDefEq <| processAssignmentFOApproxAux mvar args v) then pure true else match (← unfoldDefinition? v) with | none => pure false | some v => loop v loop v private partial def simpAssignmentArgAux : Expr → MetaM Expr | Expr.mdata _ e _ => simpAssignmentArgAux e | e@(Expr.fvar fvarId _) => do let decl ← getLocalDecl fvarId match decl.value? with | some value => simpAssignmentArgAux value | _ => pure e | e => pure e /- Auxiliary procedure for processing `?m a₁ ... aₙ =?= v`. We apply it to each `aᵢ`. It instantiates assigned metavariables if `aᵢ` is of the form `f[?n] b₁ ... bₘ`, and then removes metadata, and zeta-expand let-decls. -/ private def simpAssignmentArg (arg : Expr) : MetaM Expr := do let arg ← if arg.getAppFn.hasExprMVar then instantiateMVars arg else pure arg simpAssignmentArgAux arg /- Assign `mvar := fun a_1 ... a_{numArgs} => v`. We use it at `processConstApprox` and `isDefEqMVarSelf` -/ private def assignConst (mvar : Expr) (numArgs : Nat) (v : Expr) : MetaM Bool := do let mvarDecl ← getMVarDecl mvar.mvarId! forallBoundedTelescope mvarDecl.type numArgs fun xs _ => do if xs.size != numArgs then pure false else let some v ← mkLambdaFVarsWithLetDeps xs v | pure false match (← checkAssignment mvar.mvarId! #[] v) with | none => pure false | some v => trace[Meta.isDefEq.constApprox] "{mvar} := {v}" checkTypesAndAssign mvar v private def processConstApprox (mvar : Expr) (numArgs : Nat) (v : Expr) : MetaM Bool := do let cfg ← getConfig let mvarId := mvar.mvarId! let mvarDecl ← getMVarDecl mvarId if mvarDecl.numScopeArgs == numArgs || cfg.constApprox then assignConst mvar numArgs v else pure false /-- Tries to solve `?m a₁ ... aₙ =?= v` by assigning `?m`. It assumes `?m` is unassigned. -/ private partial def processAssignment (mvarApp : Expr) (v : Expr) : MetaM Bool := traceCtx `Meta.isDefEq.assign do trace[Meta.isDefEq.assign] "{mvarApp} := {v}" let mvar := mvarApp.getAppFn let mvarDecl ← getMVarDecl mvar.mvarId! let rec process (i : Nat) (args : Array Expr) (v : Expr) := do let cfg ← getConfig let useFOApprox (args : Array Expr) : MetaM Bool := processAssignmentFOApprox mvar args v <||> processConstApprox mvar args.size v if h : i < args.size then let arg := args.get ⟨i, h⟩ let arg ← simpAssignmentArg arg let args := args.set ⟨i, h⟩ arg match arg with | Expr.fvar fvarId _ => if args[0:i].any fun prevArg => prevArg == arg then useFOApprox args else if mvarDecl.lctx.contains fvarId && !cfg.quasiPatternApprox then useFOApprox args else process (i+1) args v | _ => useFOApprox args else let v ← instantiateMVars v -- enforce A4 if v.getAppFn == mvar then -- using A6 useFOApprox args else let mvarId := mvar.mvarId! match (← checkAssignment mvarId args v) with | none => useFOApprox args | some v => do trace[Meta.isDefEq.assign.beforeMkLambda] "{mvar} {args} := {v}" let some v ← mkLambdaFVarsWithLetDeps args v | return false if args.any (fun arg => mvarDecl.lctx.containsFVar arg) then /- We need to type check `v` because abstraction using `mkLambdaFVars` may have produced a type incorrect term. See discussion at A2 -/ if (← isTypeCorrect v) then checkTypesAndAssign mvar v else trace[Meta.isDefEq.assign.typeError] "{mvar} := {v}" useFOApprox args else checkTypesAndAssign mvar v process 0 mvarApp.getAppArgs v /-- Similar to processAssignment, but if it fails, compute v's whnf and try again. This helps to solve constraints such as `?m =?= { α := ?m, ... }.α` Note this is not perfect solution since we still fail occurs check for constraints such as ```lean ?m =?= List { α := ?m, β := Nat }.β ``` -/ private def processAssignment' (mvarApp : Expr) (v : Expr) : MetaM Bool := do if (← processAssignment mvarApp v) then return true else let vNew ← whnf v if vNew != v then if mvarApp == vNew then return true else processAssignment mvarApp vNew else return false private def isDeltaCandidate? (t : Expr) : MetaM (Option ConstantInfo) := do match t.getAppFn with | Expr.const c _ _ => match (← getConst? c) with | r@(some info) => if info.hasValue then return r else return none | _ => return none | _ => pure none /-- Auxiliary method for isDefEqDelta -/ private def isListLevelDefEq (us vs : List Level) : MetaM LBool := toLBoolM <| isListLevelDefEqAux us vs /-- Auxiliary method for isDefEqDelta -/ private def isDefEqLeft (fn : Name) (t s : Expr) : MetaM LBool := do trace[Meta.isDefEq.delta.unfoldLeft] fn toLBoolM <| Meta.isExprDefEqAux t s /-- Auxiliary method for isDefEqDelta -/ private def isDefEqRight (fn : Name) (t s : Expr) : MetaM LBool := do trace[Meta.isDefEq.delta.unfoldRight] fn toLBoolM <| Meta.isExprDefEqAux t s /-- Auxiliary method for isDefEqDelta -/ private def isDefEqLeftRight (fn : Name) (t s : Expr) : MetaM LBool := do trace[Meta.isDefEq.delta.unfoldLeftRight] fn toLBoolM <| Meta.isExprDefEqAux t s /-- Try to solve `f a₁ ... aₙ =?= f b₁ ... bₙ` by solving `a₁ =?= b₁, ..., aₙ =?= bₙ`. Auxiliary method for isDefEqDelta -/ private def tryHeuristic (t s : Expr) : MetaM Bool := do let mut t := t let mut s := s let tFn := t.getAppFn let sFn := s.getAppFn let info ← getConstInfo tFn.constName! /- We only use the heuristic when `f` is a regular definition or an auxiliary `match` application. That is, it is not marked an abbreviation (e.g., a user-facing projection) or as opaque (e.g., proof). We check whether terms contain metavariables to make sure we can solve constraints such as `S.proj ?x =?= S.proj t` without performing delta-reduction. That is, we are assuming the heuristic implemented by this method is seldom effective when `t` and `s` do not have metavariables, are not structurally equal, and `f` is an abbreviation. On the other hand, by unfolding `f`, we often produce smaller terms. Recall that auxiliary `match` definitions are marked as abbreviations, but we must use the heuristic on them since they will not be unfolded when smartUnfolding is turned on. The abbreviation annotation in this case is used to help the kernel type checker. -/ unless info.hints.isRegular || isMatcherCore (← getEnv) tFn.constName! do unless t.hasExprMVar || s.hasExprMVar do return false traceCtx `Meta.isDefEq.delta do /- We process arguments before universe levels to reduce a source of brittleness in the TC procedure. In the TC procedure, we can solve problems containing metavariables. If the TC procedure tries to assign one of these metavariables, it interrupts the search using a "stuck" exception. The elaborator catches it, and "interprets" it as "we should try again later". Now suppose we have a TC problem, and there are two "local" candidate instances we can try: "bad" and "good". The "bad" candidate is stuck because of a universe metavariable in the TC problem. If we try "bad" first, the TC procedure is interrupted. Moreover, if we have ignored the exception, "bad" would fail anyway trying to assign two different free variables `α =?= β`. Example: `Preorder.{?u} α =?= Preorder.{?v} β`, where `?u` and `?v` are universe metavariables that were not created by the TC procedure. The key issue here is that we have an `isDefEq t s` invocation that is interrupted by the "stuck" exception, but it would have failed anyway if we had continued processing it. By solving the arguments first, we make the example above fail without throwing the "stuck" exception. TODO: instead of throwing an exception as soon as we get stuck, we should just set a flag. Then the entry-point for `isDefEq` checks the flag before returning `true`. -/ checkpointDefEq do let b ← isDefEqArgs tFn t.getAppArgs s.getAppArgs <&&> isListLevelDefEqAux tFn.constLevels! sFn.constLevels! unless b do trace[Meta.isDefEq.delta] "heuristic failed {t} =?= {s}" pure b /-- Auxiliary method for isDefEqDelta -/ private abbrev unfold (e : Expr) (failK : MetaM α) (successK : Expr → MetaM α) : MetaM α := do match (← unfoldDefinition? e) with | some e => successK e | none => failK /-- Auxiliary method for isDefEqDelta -/ private def unfoldBothDefEq (fn : Name) (t s : Expr) : MetaM LBool := do match t, s with | Expr.const _ ls₁ _, Expr.const _ ls₂ _ => isListLevelDefEq ls₁ ls₂ | Expr.app _ _ _, Expr.app _ _ _ => if (← tryHeuristic t s) then pure LBool.true else unfold t (unfold s (pure LBool.false) (fun s => isDefEqRight fn t s)) (fun t => unfold s (isDefEqLeft fn t s) (fun s => isDefEqLeftRight fn t s)) | _, _ => pure LBool.false private def sameHeadSymbol (t s : Expr) : Bool := match t.getAppFn, s.getAppFn with | Expr.const c₁ _ _, Expr.const c₂ _ _ => true | _, _ => false /-- - If headSymbol (unfold t) == headSymbol s, then unfold t - If headSymbol (unfold s) == headSymbol t, then unfold s - Otherwise unfold t and s if possible. Auxiliary method for isDefEqDelta -/ private def unfoldComparingHeadsDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := unfold t (unfold s (pure LBool.undef) -- `t` and `s` failed to be unfolded (fun s => isDefEqRight sInfo.name t s)) (fun tNew => if sameHeadSymbol tNew s then isDefEqLeft tInfo.name tNew s else unfold s (isDefEqLeft tInfo.name tNew s) (fun sNew => if sameHeadSymbol t sNew then isDefEqRight sInfo.name t sNew else isDefEqLeftRight tInfo.name tNew sNew)) /-- If `t` and `s` do not contain metavariables, then use kernel definitional equality heuristics. Otherwise, use `unfoldComparingHeadsDefEq`. Auxiliary method for isDefEqDelta -/ private def unfoldDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := if !t.hasExprMVar && !s.hasExprMVar then /- If `t` and `s` do not contain metavariables, we simulate strategy used in the kernel. -/ if tInfo.hints.lt sInfo.hints then unfold t (unfoldComparingHeadsDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s else if sInfo.hints.lt tInfo.hints then unfold s (unfoldComparingHeadsDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s else unfoldComparingHeadsDefEq tInfo sInfo t s else unfoldComparingHeadsDefEq tInfo sInfo t s /-- When `TransparencyMode` is set to `default` or `all`. If `t` is reducible and `s` is not ==> `isDefEqLeft (unfold t) s` If `s` is reducible and `t` is not ==> `isDefEqRight t (unfold s)` Otherwise, use `unfoldDefEq` Auxiliary method for isDefEqDelta -/ private def unfoldReducibeDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do if (← shouldReduceReducibleOnly) then unfoldDefEq tInfo sInfo t s else let tReducible ← isReducible tInfo.name let sReducible ← isReducible sInfo.name if tReducible && !sReducible then unfold t (unfoldDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s else if !tReducible && sReducible then unfold s (unfoldDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s else unfoldDefEq tInfo sInfo t s /-- If `t` is a projection function application and `s` is not ==> `isDefEqRight t (unfold s)` If `s` is a projection function application and `t` is not ==> `isDefEqRight (unfold t) s` Otherwise, use `unfoldReducibeDefEq` Auxiliary method for isDefEqDelta -/ private def unfoldNonProjFnDefEq (tInfo sInfo : ConstantInfo) (t s : Expr) : MetaM LBool := do let tProj? ← isProjectionFn tInfo.name let sProj? ← isProjectionFn sInfo.name if tProj? && !sProj? then unfold s (unfoldDefEq tInfo sInfo t s) fun s => isDefEqRight sInfo.name t s else if !tProj? && sProj? then unfold t (unfoldDefEq tInfo sInfo t s) fun t => isDefEqLeft tInfo.name t s else unfoldReducibeDefEq tInfo sInfo t s /-- isDefEq by lazy delta reduction. This method implements many different heuristics: 1- If only `t` can be unfolded => then unfold `t` and continue 2- If only `s` can be unfolded => then unfold `s` and continue 3- If `t` and `s` can be unfolded and they have the same head symbol, then a) First try to solve unification by unifying arguments. b) If it fails, unfold both and continue. Implemented by `unfoldBothDefEq` 4- If `t` is a projection function application and `s` is not => then unfold `s` and continue. 5- If `s` is a projection function application and `t` is not => then unfold `t` and continue. Remark: 4&5 are implemented by `unfoldNonProjFnDefEq` 6- If `t` is reducible and `s` is not => then unfold `t` and continue. 7- If `s` is reducible and `t` is not => then unfold `s` and continue Remark: 6&7 are implemented by `unfoldReducibeDefEq` 8- If `t` and `s` do not contain metavariables, then use heuristic used in the Kernel. Implemented by `unfoldDefEq` 9- If `headSymbol (unfold t) == headSymbol s`, then unfold t and continue. 10- If `headSymbol (unfold s) == headSymbol t`, then unfold s 11- Otherwise, unfold `t` and `s` and continue. Remark: 9&10&11 are implemented by `unfoldComparingHeadsDefEq` -/ private def isDefEqDelta (t s : Expr) : MetaM LBool := do let tInfo? ← isDeltaCandidate? t.getAppFn let sInfo? ← isDeltaCandidate? s.getAppFn match tInfo?, sInfo? with | none, none => pure LBool.undef | some tInfo, none => unfold t (pure LBool.undef) fun t => isDefEqLeft tInfo.name t s | none, some sInfo => unfold s (pure LBool.undef) fun s => isDefEqRight sInfo.name t s | some tInfo, some sInfo => if tInfo.name == sInfo.name then unfoldBothDefEq tInfo.name t s else unfoldNonProjFnDefEq tInfo sInfo t s private def isAssigned : Expr → MetaM Bool | Expr.mvar mvarId _ => isExprMVarAssigned mvarId | _ => pure false private def isDelayedAssignedHead (tFn : Expr) (t : Expr) : MetaM Bool := do match tFn with | Expr.mvar mvarId _ => if (← isDelayedAssigned mvarId) then let tNew ← instantiateMVars t return tNew != t else pure false | _ => pure false private def isSynthetic : Expr → MetaM Bool | Expr.mvar mvarId _ => do let mvarDecl ← getMVarDecl mvarId match mvarDecl.kind with | MetavarKind.synthetic => pure true | MetavarKind.syntheticOpaque => pure true | MetavarKind.natural => pure false | _ => pure false private def isAssignable : Expr → MetaM Bool | Expr.mvar mvarId _ => do let b ← isReadOnlyOrSyntheticOpaqueExprMVar mvarId; pure (!b) | _ => pure false private def etaEq (t s : Expr) : Bool := match t.etaExpanded? with | some t => t == s | none => false private def isLetFVar (fvarId : FVarId) : MetaM Bool := do let decl ← getLocalDecl fvarId pure decl.isLet private def isDefEqProofIrrel (t s : Expr) : MetaM LBool := do if (← getConfig).proofIrrelevance then let status ← isProofQuick t match status with | LBool.false => pure LBool.undef | LBool.true => let tType ← inferType t let sType ← inferType s toLBoolM <| Meta.isExprDefEqAux tType sType | LBool.undef => let tType ← inferType t if (← isProp tType) then let sType ← inferType s toLBoolM <| Meta.isExprDefEqAux tType sType else pure LBool.undef else pure LBool.undef /- Try to solve constraint of the form `?m args₁ =?= ?m args₂`. - First try to unify `args₁` and `args₂`, and return true if successful - Otherwise, try to assign `?m` to a constant function of the form `fun x_1 ... x_n => ?n` where `?n` is a fresh metavariable. See `processConstApprox`. -/ private def isDefEqMVarSelf (mvar : Expr) (args₁ args₂ : Array Expr) : MetaM Bool := do if args₁.size != args₂.size then pure false else if (← isDefEqArgs mvar args₁ args₂) then pure true else if !(← isAssignable mvar) then pure false else let cfg ← getConfig let mvarId := mvar.mvarId! let mvarDecl ← getMVarDecl mvarId if mvarDecl.numScopeArgs == args₁.size || cfg.constApprox then let type ← inferType (mkAppN mvar args₁) let auxMVar ← mkAuxMVar mvarDecl.lctx mvarDecl.localInstances type assignConst mvar args₁.size auxMVar else pure false /- Remove unnecessary let-decls -/ private def consumeLet : Expr → Expr | e@(Expr.letE _ _ _ b _) => if b.hasLooseBVars then e else consumeLet b | e => e mutual private partial def isDefEqQuick (t s : Expr) : MetaM LBool := let t := consumeLet t let s := consumeLet s match t, s with | Expr.lit l₁ _, Expr.lit l₂ _ => return (l₁ == l₂).toLBool | Expr.sort u _, Expr.sort v _ => toLBoolM <| isLevelDefEqAux u v | Expr.lam .., Expr.lam .. => if t == s then pure LBool.true else toLBoolM <| isDefEqBinding t s | Expr.forallE .., Expr.forallE .. => if t == s then pure LBool.true else toLBoolM <| isDefEqBinding t s -- | Expr.mdata _ t _, s => isDefEqQuick t s -- | t, Expr.mdata _ s _ => isDefEqQuick t s | Expr.fvar fvarId₁ _, Expr.fvar fvarId₂ _ => do if (← isLetFVar fvarId₁ <||> isLetFVar fvarId₂) then pure LBool.undef else if fvarId₁ == fvarId₂ then pure LBool.true else isDefEqProofIrrel t s | t, s => isDefEqQuickOther t s private partial def isDefEqQuickOther (t s : Expr) : MetaM LBool := do /- We used to eagerly consume all metadata (see commented lines at `isDefEqQuick`), but it was unnecessarily removing helpful annotations for the pretty-printer. For example, consider the following example. ``` constant p : Nat → Prop constant q : Nat → Prop theorem p_of_q : q x → p x := sorry theorem pletfun : p (let_fun x := 0; x + 1) := by -- ⊢ p (let_fun x := 0; x + 1) apply p_of_q -- If we eagerly consume all metadata, the let_fun annotation is lost during `isDefEq` -- ⊢ q ((fun x => x + 1) 0) sorry ``` However, the inaccessible pattern annotation must be consumed. The frontend relies on the fact that is must not be propagated by `isDefEq`. Thus, we consume it here. This is a bit hackish since it is very adhoc. We might other annotations in the future that we should not preserve. Perhaps, we should mark the annotation we do want to preserve ones (e.g., hints for the pretty printer), and consume all other -/ if let some t := inaccessible? t then isDefEqQuick t s else if let some s := inaccessible? s then isDefEqQuick t s else if t == s then return LBool.true else if etaEq t s || etaEq s t then return LBool.true -- t =?= (fun xs => t xs) else let tFn := t.getAppFn let sFn := s.getAppFn if !tFn.isMVar && !sFn.isMVar then return LBool.undef else if (← isAssigned tFn) then let t ← instantiateMVars t isDefEqQuick t s else if (← isAssigned sFn) then let s ← instantiateMVars s isDefEqQuick t s else if (← isDelayedAssignedHead tFn t) then let t ← instantiateMVars t isDefEqQuick t s else if (← isDelayedAssignedHead sFn s) then let s ← instantiateMVars s isDefEqQuick t s /- Remark: we do not eagerly synthesize synthetic metavariables when the constraint is not stuck. Reason: we may fail to solve a constraint of the form `?x =?= A` when the synthesized instance is not definitionally equal to `A`. We left the code here as a remainder of this issue. -/ -- else if (← isSynthetic tFn <&&> trySynthPending tFn) then -- let t ← instantiateMVars t -- isDefEqQuick t s -- else if (← isSynthetic sFn <&&> trySynthPending sFn) then -- let s ← instantiateMVars s -- isDefEqQuick t s else if tFn.isMVar && sFn.isMVar && tFn == sFn then Bool.toLBool <$> isDefEqMVarSelf tFn t.getAppArgs s.getAppArgs else let tAssign? ← isAssignable tFn let sAssign? ← isAssignable sFn let assignableMsg (b : Bool) := if b then "[assignable]" else "[nonassignable]" trace[Meta.isDefEq] "{t} {assignableMsg tAssign?} =?= {s} {assignableMsg sAssign?}" if tAssign? && !sAssign? then toLBoolM <| processAssignment' t s else if !tAssign? && sAssign? then toLBoolM <| processAssignment' s t else if !tAssign? && !sAssign? then if tFn.isMVar || sFn.isMVar then let ctx ← read if ctx.config.isDefEqStuckEx then do trace[Meta.isDefEq.stuck] "{t} =?= {s}" Meta.throwIsDefEqStuck else return LBool.false else return LBool.undef else isDefEqQuickMVarMVar t s -- Both `t` and `s` are terms of the form `?m ...` private partial def isDefEqQuickMVarMVar (t s : Expr) : MetaM LBool := do let tFn := t.getAppFn let sFn := s.getAppFn let tMVarDecl ← getMVarDecl tFn.mvarId! let sMVarDecl ← getMVarDecl sFn.mvarId! if s.isMVar && !t.isMVar then /- Solve `?m t =?= ?n` by trying first `?n := ?m t`. Reason: this assignment is precise. -/ if (← checkpointDefEq (processAssignment s t)) then return LBool.true else toLBoolM <| processAssignment t s else if (← checkpointDefEq (processAssignment t s)) then return LBool.true else toLBoolM <| processAssignment s t end @[inline] def whenUndefDo (x : MetaM LBool) (k : MetaM Bool) : MetaM Bool := do let status ← x match status with | LBool.true => pure true | LBool.false => pure false | LBool.undef => k @[specialize] private def unstuckMVar (e : Expr) (successK : Expr → MetaM Bool) (failK : MetaM Bool): MetaM Bool := do match (← getStuckMVar? e) with | some mvarId => trace[Meta.isDefEq.stuckMVar] "found stuck MVar {mkMVar mvarId} : {← inferType (mkMVar mvarId)}" if (← Meta.synthPending mvarId) then let e ← instantiateMVars e successK e else failK | none => failK private def isDefEqOnFailure (t s : Expr) : MetaM Bool := do trace[Meta.isDefEq.onFailure] "{t} =?= {s}" unstuckMVar t (fun t => Meta.isExprDefEqAux t s) <| unstuckMVar s (fun s => Meta.isExprDefEqAux t s) <| tryUnificationHints t s <||> tryUnificationHints s t private def isDefEqProj : Expr → Expr → MetaM Bool | Expr.proj _ i t _, Expr.proj _ j s _ => pure (i == j) <&&> Meta.isExprDefEqAux t s | Expr.proj structName 0 s _, v => isDefEqSingleton structName s v | v, Expr.proj structName 0 s _ => isDefEqSingleton structName s v | _, _ => pure false where /- If `structName` is a structure with a single field and `(?m ...).1 =?= v`, then solve contraint as `?m ... =?= ⟨v⟩` -/ isDefEqSingleton (structName : Name) (s : Expr) (v : Expr) : MetaM Bool := do let ctorVal := getStructureCtor (← getEnv) structName if ctorVal.numFields != 1 then return false -- It is not a structure with a single field. let sType ← whnf (← inferType s) let sTypeFn := sType.getAppFn if !sTypeFn.isConstOf structName then return false let s ← whnf s let sFn := s.getAppFn if !sFn.isMVar then return false if (← isAssignable sFn) then let ctorApp := mkApp (mkAppN (mkConst ctorVal.name sTypeFn.constLevels!) sType.getAppArgs) v processAssignment' s ctorApp else return false /- Given applications `t` and `s` that are in WHNF (modulo the current transparency setting), check whether they are definitionally equal or not. -/ private def isDefEqApp (t s : Expr) : MetaM Bool := do let tFn := t.getAppFn let sFn := s.getAppFn if tFn.isConst && sFn.isConst && tFn.constName! == sFn.constName! then /- See comment at `tryHeuristic` explaining why we processe arguments before universe levels. -/ if (← checkpointDefEq (isDefEqArgs tFn t.getAppArgs s.getAppArgs <&&> isListLevelDefEqAux tFn.constLevels! sFn.constLevels!)) then return true else isDefEqOnFailure t s else if (← checkpointDefEq (Meta.isExprDefEqAux tFn s.getAppFn <&&> isDefEqArgs tFn t.getAppArgs s.getAppArgs)) then return true else isDefEqOnFailure t s /-- Return `true` if the types of the given expressions is an inductive datatype with an inductive datatype with a single constructor with no fields. -/ private def isDefEqUnitLike (t : Expr) (s : Expr) : MetaM Bool := do if !(← getConfig).etaStruct then return false else let tType ← whnf (← inferType t) matchConstStruct tType.getAppFn (fun _ => return false) fun _ _ ctorVal => do if ctorVal.numFields != 0 then return false else Meta.isExprDefEqAux tType (← inferType s) private def isExprDefEqExpensive (t : Expr) (s : Expr) : MetaM Bool := do if (← (isDefEqEta t s <||> isDefEqEta s t)) then pure true else -- TODO: investigate whether this is the place for putting this check if (← (isDefEqEtaStruct t s <||> isDefEqEtaStruct s t)) then pure true else if (← isDefEqProj t s) then pure true else whenUndefDo (isDefEqNative t s) do whenUndefDo (isDefEqNat t s) do whenUndefDo (isDefEqOffset t s) do whenUndefDo (isDefEqDelta t s) do if t.isConst && s.isConst then if t.constName! == s.constName! then isListLevelDefEqAux t.constLevels! s.constLevels! else return false else if (← t.isApp <&&> s.isApp <&&> isDefEqApp t s) then return true else whenUndefDo (isDefEqStringLit t s) do if (← isDefEqUnitLike t s) then return true else isDefEqOnFailure t s -- We only check DefEq cache for default and all transparency modes private def skipDefEqCache : MetaM Bool := do match (← getConfig).transparency with | TransparencyMode.default => return false | TransparencyMode.all => return false | _ => return true private def mkCacheKey (t : Expr) (s : Expr) : Expr × Expr := if Expr.quickLt t s then (t, s) else (s, t) private def isCached (key : Expr × Expr) : MetaM Bool := do match (← getConfig).transparency with | TransparencyMode.default => return (← get).cache.defEqDefault.contains key | TransparencyMode.all => return (← get).cache.defEqAll.contains key | _ => return false private def cacheResult (key : Expr × Expr) : MetaM Unit := do match (← getConfig).transparency with | TransparencyMode.default => modify fun s => { s with cache.defEqDefault := s.cache.defEqDefault.insert key () } | TransparencyMode.all => modify fun s => { s with cache.defEqAll := s.cache.defEqAll.insert key () } | _ => pure () @[export lean_is_expr_def_eq] partial def isExprDefEqAuxImpl (t : Expr) (s : Expr) : MetaM Bool := withIncRecDepth do trace[Meta.isDefEq.step] "{t} =?= {s}" checkMaxHeartbeats "isDefEq" withNestedTraces do whenUndefDo (isDefEqQuick t s) do whenUndefDo (isDefEqProofIrrel t s) do let t' ← whnfCore t let s' ← whnfCore s if t != t' || s != s' then isExprDefEqAuxImpl t' s' else if (← skipDefEqCache) then isExprDefEqExpensive t s else /- TODO: check whether the following `instantiateMVar`s are expensive or not in practice. Lean 3 does not use them, and may miss caching opportunities since it is not safe to cache when `t` and `s` may contain mvars. The unit test `tryHeuristicPerfIssue2.lean` cannot be solved without these two `instantiateMVar`s. If it becomes a problem, we may use store a flag in the context indicating whether we have already used `instantiateMVar` in outer invocations or not. It is not perfect (we may assign mvars in nested calls), but it should work well enough in practice, and prevent repeated traversals in nested calls. -/ let t ← instantiateMVars t let s ← instantiateMVars s if t.hasMVar || s.hasMVar then -- It is not safe to use DefEq cache if terms contain metavariables isExprDefEqExpensive t s else let k := mkCacheKey t s if (← isCached k) then return true else if (← isExprDefEqExpensive t s) then cacheResult k return true else return false builtin_initialize registerTraceClass `Meta.isDefEq registerTraceClass `Meta.isDefEq.foApprox registerTraceClass `Meta.isDefEq.constApprox registerTraceClass `Meta.isDefEq.delta registerTraceClass `Meta.isDefEq.step registerTraceClass `Meta.isDefEq.assign registerTraceClass `Meta.isDefEq.eta.struct end Lean.Meta
23fc20a679b70a1f86dc0d18d86f0406ae7dfe71
8d65764a9e5f0923a67fc435eb1a5a1d02fd80e3
/src/tactic/tidy.lean
0bc114e95eb3498d62d5f6b56a5c9baa45b0f7b7
[ "Apache-2.0" ]
permissive
troyjlee/mathlib
e18d4b8026e32062ab9e89bc3b003a5d1cfec3f5
45e7eb8447555247246e3fe91c87066506c14875
refs/heads/master
1,689,248,035,046
1,629,470,528,000
1,629,470,528,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,317
lean
/- Copyright (c) 2017 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Scott Morrison -/ import tactic.auto_cases import tactic.chain import tactic.norm_cast namespace tactic namespace tidy /-- Tag interactive tactics (locally) with `[tidy]` to add them to the list of default tactics called by `tidy`. -/ @[user_attribute] meta def tidy_attribute : user_attribute := { name := `tidy, descr := "A tactic that should be called by `tidy`." } add_tactic_doc { name := "tidy", category := doc_category.attr, decl_names := [`tactic.tidy.tidy_attribute], tags := ["search"] } meta def run_tactics : tactic string := do names ← attribute.get_instances `tidy, first (names.map name_to_tactic) <|> fail "no @[tidy] tactics succeeded" @[hint_tactic] meta def ext1_wrapper : tactic string := do ng ← num_goals, ext1 [] {apply_cfg . new_goals := new_goals.all}, ng' ← num_goals, return $ if ng' > ng then "tactic.ext1 [] {new_goals := tactic.new_goals.all}" else "ext1" meta def default_tactics : list (tactic string) := [ reflexivity >> pure "refl", `[exact dec_trivial] >> pure "exact dec_trivial", propositional_goal >> assumption >> pure "assumption", intros1 >>= λ ns, pure ("intros " ++ (" ".intercalate (ns.map (λ e, e.to_string)))), auto_cases, `[apply_auto_param] >> pure "apply_auto_param", `[dsimp at *] >> pure "dsimp at *", `[simp at *] >> pure "simp at *", ext1_wrapper, fsplit >> pure "fsplit", injections_and_clear >> pure "injections_and_clear", propositional_goal >> (`[solve_by_elim]) >> pure "solve_by_elim", `[norm_cast] >> pure "norm_cast", `[unfold_coes] >> pure "unfold_coes", `[unfold_aux] >> pure "unfold_aux", tidy.run_tactics ] meta structure cfg := (trace_result : bool := ff) (trace_result_prefix : string := "Try this: ") (tactics : list (tactic string) := default_tactics) declare_trace tidy meta def core (cfg : cfg := {}) : tactic (list string) := do results ← chain cfg.tactics, when (cfg.trace_result) $ trace (cfg.trace_result_prefix ++ (", ".intercalate results)), return results end tidy meta def tidy (cfg : tidy.cfg := {}) := tactic.tidy.core cfg >> skip namespace interactive open lean.parser interactive /-- Use a variety of conservative tactics to solve goals. `tidy?` reports back the tactic script it found. As an example ```lean example : ∀ x : unit, x = unit.star := begin tidy? -- Prints the trace message: "Try this: intros x, exact dec_trivial" end ``` The default list of tactics is stored in `tactic.tidy.default_tidy_tactics`. This list can be overridden using `tidy { tactics := ... }`. (The list must be a `list` of `tactic string`, so that `tidy?` can report a usable tactic script.) Tactics can also be added to the list by tagging them (locally) with the `[tidy]` attribute. -/ meta def tidy (trace : parse $ optional (tk "?")) (cfg : tidy.cfg := {}) := tactic.tidy { trace_result := trace.is_some, ..cfg } end interactive add_tactic_doc { name := "tidy", category := doc_category.tactic, decl_names := [`tactic.interactive.tidy], tags := ["search", "Try this", "finishing"] } /-- Invoking the hole command `tidy` ("Use `tidy` to complete the goal") runs the tactic of the same name, replacing the hole with the tactic script `tidy` produces. -/ @[hole_command] meta def tidy_hole_cmd : hole_command := { name := "tidy", descr := "Use `tidy` to complete the goal.", action := λ _, do script ← tidy.core, return [("begin " ++ (", ".intercalate script) ++ " end", "by tidy")] } add_tactic_doc { name := "tidy", category := doc_category.hole_cmd, decl_names := [`tactic.tidy_hole_cmd], tags := ["search"] } end tactic
6160f88ad385c53ab04c3bec7be6a74af5aa4cdf
32317185abf7e7c963f4c67c190aec61af6b3628
/tests/lean/852.hlean
d6954c0b4c7e97e685f0c8e92fcfc6be4c805739
[ "Apache-2.0" ]
permissive
Andrew-Zipperer-unorganized/lean
198a2317f21198cd8d26e7085e484b86277f17f7
dcb35008e1474a0abebe632b1dced120e5f8c009
refs/heads/master
1,622,526,520,945
1,453,576,559,000
1,454,612,842,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
119
hlean
import algebra.category.functor.equivalence -- print prefix category.equivalence check @category.equivalence.to._Fun
e638cbfbd95c10ac298a7382b39cafc0fcc720fd
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/algebra/category/Module/monoidal.lean
c66fa8aeefe835ae8e12a1cd4e8a79d5ae6872e4
[ "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
8,974
lean
/- Copyright (c) 2020 Scott Morrison. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kevin Buzzard, Scott Morrison -/ import category_theory.monoidal.braided import algebra.category.Module.basic import linear_algebra.tensor_product /-! # The symmetric monoidal category structure on R-modules Mostly this uses existing machinery in `linear_algebra.tensor_product`. We just need to provide a few small missing pieces to build the `monoidal_category` instance and then the `symmetric_category` instance. If you're happy using the bundled `Module R`, it may be possible to mostly use this as an interface and not need to interact much with the implementation details. -/ universes u open category_theory namespace Module variables {R : Type u} [comm_ring R] namespace monoidal_category -- The definitions inside this namespace are essentially private. -- After we build the `monoidal_category (Module R)` instance, -- you should use that API. open_locale tensor_product /-- (implementation) tensor product of R-modules -/ def tensor_obj (M N : Module R) : Module R := Module.of R (M ⊗[R] N) /-- (implementation) tensor product of morphisms R-modules -/ def tensor_hom {M N M' N' : Module R} (f : M ⟶ N) (g : M' ⟶ N') : tensor_obj M M' ⟶ tensor_obj N N' := tensor_product.map f g lemma tensor_id (M N : Module R) : tensor_hom (𝟙 M) (𝟙 N) = 𝟙 (Module.of R (↥M ⊗ ↥N)) := by tidy lemma tensor_comp {X₁ Y₁ Z₁ X₂ Y₂ Z₂ : Module R} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (g₁ : Y₁ ⟶ Z₁) (g₂ : Y₂ ⟶ Z₂) : tensor_hom (f₁ ≫ g₁) (f₂ ≫ g₂) = tensor_hom f₁ f₂ ≫ tensor_hom g₁ g₂ := by tidy /-- (implementation) the associator for R-modules -/ def associator (M N K : Module R) : tensor_obj (tensor_obj M N) K ≅ tensor_obj M (tensor_obj N K) := linear_equiv.to_Module_iso (tensor_product.assoc R M N K) section /-! The `associator_naturality` and `pentagon` lemmas below are very slow to elaborate. We give them some help by expressing the lemmas first non-categorically, then using `convert _aux using 1` to have the elaborator work as little as possible. -/ open tensor_product (assoc map) private lemma associator_naturality_aux {X₁ X₂ X₃ : Type*} [add_comm_monoid X₁] [add_comm_monoid X₂] [add_comm_monoid X₃] [semimodule R X₁] [semimodule R X₂] [semimodule R X₃] {Y₁ Y₂ Y₃ : Type*} [add_comm_monoid Y₁] [add_comm_monoid Y₂] [add_comm_monoid Y₃] [semimodule R Y₁] [semimodule R Y₂] [semimodule R Y₃] (f₁ : X₁ →ₗ[R] Y₁) (f₂ : X₂ →ₗ[R] Y₂) (f₃ : X₃ →ₗ[R] Y₃) : linear_map.comp ↑(assoc R Y₁ Y₂ Y₃) (map (map f₁ f₂) f₃) = (map f₁ (map f₂ f₃)).comp ↑(assoc R X₁ X₂ X₃) := begin apply tensor_product.ext_threefold, intros x y z, refl end variables (R) private lemma pentagon_aux (W X Y Z : Type*) [add_comm_monoid W] [add_comm_monoid X] [add_comm_monoid Y] [add_comm_monoid Z] [semimodule R W] [semimodule R X] [semimodule R Y] [semimodule R Z] : ((map (1 : W →ₗ[R] W) (assoc R X Y Z).to_linear_map).comp (assoc R W (X ⊗[R] Y) Z).to_linear_map) .comp (map ↑(assoc R W X Y) (1 : Z →ₗ[R] Z)) = (assoc R W X (Y ⊗[R] Z)).to_linear_map.comp (assoc R (W ⊗[R] X) Y Z).to_linear_map := begin apply tensor_product.ext_fourfold, intros w x y z, refl end end lemma associator_naturality {X₁ X₂ X₃ Y₁ Y₂ Y₃ : Module R} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃) : tensor_hom (tensor_hom f₁ f₂) f₃ ≫ (associator Y₁ Y₂ Y₃).hom = (associator X₁ X₂ X₃).hom ≫ tensor_hom f₁ (tensor_hom f₂ f₃) := by convert associator_naturality_aux f₁ f₂ f₃ using 1 lemma pentagon (W X Y Z : Module R) : tensor_hom (associator W X Y).hom (𝟙 Z) ≫ (associator W (tensor_obj X Y) Z).hom ≫ tensor_hom (𝟙 W) (associator X Y Z).hom = (associator (tensor_obj W X) Y Z).hom ≫ (associator W X (tensor_obj Y Z)).hom := by convert pentagon_aux R W X Y Z using 1 /-- (implementation) the left unitor for R-modules -/ def left_unitor (M : Module.{u} R) : Module.of R (R ⊗[R] M) ≅ M := (linear_equiv.to_Module_iso (tensor_product.lid R M) : of R (R ⊗ M) ≅ of R M).trans (of_self_iso M) lemma left_unitor_naturality {M N : Module R} (f : M ⟶ N) : tensor_hom (𝟙 (Module.of R R)) f ≫ (left_unitor N).hom = (left_unitor M).hom ≫ f := begin ext x y, simp, erw [tensor_product.lid_tmul, tensor_product.lid_tmul], rw linear_map.map_smul, refl, end /-- (implementation) the right unitor for R-modules -/ def right_unitor (M : Module.{u} R) : Module.of R (M ⊗[R] R) ≅ M := (linear_equiv.to_Module_iso (tensor_product.rid R M) : of R (M ⊗ R) ≅ of R M).trans (of_self_iso M) lemma right_unitor_naturality {M N : Module R} (f : M ⟶ N) : tensor_hom f (𝟙 (Module.of R R)) ≫ (right_unitor N).hom = (right_unitor M).hom ≫ f := begin ext x y, simp, erw [tensor_product.rid_tmul, tensor_product.rid_tmul], rw linear_map.map_smul, refl, end lemma triangle (M N : Module.{u} R) : (associator M (Module.of R R) N).hom ≫ tensor_hom (𝟙 M) (left_unitor N).hom = tensor_hom (right_unitor M).hom (𝟙 N) := begin apply tensor_product.ext_threefold, intros x y z, change R at y, dsimp [tensor_hom, associator], erw [tensor_product.lid_tmul, tensor_product.rid_tmul], exact (tensor_product.smul_tmul _ _ _).symm end end monoidal_category open monoidal_category instance monoidal_category : monoidal_category (Module.{u} R) := { -- data tensor_obj := tensor_obj, tensor_hom := @tensor_hom _ _, tensor_unit := Module.of R R, associator := associator, left_unitor := left_unitor, right_unitor := right_unitor, -- properties tensor_id' := λ M N, tensor_id M N, tensor_comp' := λ M N K M' N' K' f g h, tensor_comp f g h, associator_naturality' := λ M N K M' N' K' f g h, associator_naturality f g h, left_unitor_naturality' := λ M N f, left_unitor_naturality f, right_unitor_naturality' := λ M N f, right_unitor_naturality f, pentagon' := λ M N K L, pentagon M N K L, triangle' := λ M N, triangle M N, } /-- Remind ourselves that the monoidal unit, being just `R`, is still a commutative ring. -/ instance : comm_ring ((𝟙_ (Module.{u} R) : Module.{u} R) : Type u) := (by apply_instance : comm_ring R) namespace monoidal_category @[simp] lemma hom_apply {K L M N : Module.{u} R} (f : K ⟶ L) (g : M ⟶ N) (k : K) (m : M) : (f ⊗ g) (k ⊗ₜ m) = f k ⊗ₜ g m := rfl @[simp] lemma left_unitor_hom_apply {M : Module.{u} R} (r : R) (m : M) : ((λ_ M).hom : 𝟙_ (Module R) ⊗ M ⟶ M) (r ⊗ₜ[R] m) = r • m := tensor_product.lid_tmul m r @[simp] lemma right_unitor_hom_apply {M : Module.{u} R} (m : M) (r : R) : ((ρ_ M).hom : M ⊗ 𝟙_ (Module R) ⟶ M) (m ⊗ₜ r) = r • m := tensor_product.rid_tmul m r @[simp] lemma associator_hom_apply {M N K : Module.{u} R} (m : M) (n : N) (k : K) : ((α_ M N K).hom : (M ⊗ N) ⊗ K ⟶ M ⊗ (N ⊗ K)) ((m ⊗ₜ n) ⊗ₜ k) = (m ⊗ₜ (n ⊗ₜ k)) := rfl end monoidal_category /-- (implementation) the braiding for R-modules -/ def braiding (M N : Module R) : tensor_obj M N ≅ tensor_obj N M := linear_equiv.to_Module_iso (tensor_product.comm R M N) @[simp] lemma braiding_naturality {X₁ X₂ Y₁ Y₂ : Module.{u} R} (f : X₁ ⟶ Y₁) (g : X₂ ⟶ Y₂) : (f ⊗ g) ≫ (Y₁.braiding Y₂).hom = (X₁.braiding X₂).hom ≫ (g ⊗ f) := begin apply tensor_product.ext, intros x y, refl end @[simp] lemma hexagon_forward (X Y Z : Module.{u} R) : (α_ X Y Z).hom ≫ (braiding X _).hom ≫ (α_ Y Z X).hom = ((braiding X Y).hom ⊗ 𝟙 Z) ≫ (α_ Y X Z).hom ≫ (𝟙 Y ⊗ (braiding X Z).hom) := begin apply tensor_product.ext_threefold, intros x y z, refl, end @[simp] lemma hexagon_reverse (X Y Z : Module.{u} R) : (α_ X Y Z).inv ≫ (braiding _ Z).hom ≫ (α_ Z X Y).inv = (𝟙 X ⊗ (Y.braiding Z).hom) ≫ (α_ X Z Y).inv ≫ ((X.braiding Z).hom ⊗ 𝟙 Y) := begin apply (cancel_epi (α_ X Y Z).hom).1, apply tensor_product.ext_threefold, intros x y z, refl, end /-- The symmetric monoidal structure on `Module R`. -/ instance symmetric_category : symmetric_category (Module.{u} R) := { braiding := braiding, braiding_naturality' := λ X₁ X₂ Y₁ Y₂ f g, braiding_naturality f g, hexagon_forward' := hexagon_forward, hexagon_reverse' := hexagon_reverse, } namespace monoidal_category @[simp] lemma braiding_hom_apply {M N : Module.{u} R} (m : M) (n : N) : ((β_ M N).hom : M ⊗ N ⟶ N ⊗ M) (m ⊗ₜ n) = n ⊗ₜ m := rfl @[simp] lemma braiding_inv_apply {M N : Module.{u} R} (m : M) (n : N) : ((β_ M N).inv : N ⊗ M ⟶ M ⊗ N) (n ⊗ₜ m) = m ⊗ₜ n := rfl end monoidal_category end Module
51c89228b9117e7a120018f7937d317abf77d29d
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/special_functions/pow.lean
d184f3e67b230ecde6ecbd76376770bdde1c4697
[ "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
70,295
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Abhimanyu Pallavi Sudhir, Jean Lo, Calle Sönne, Sébastien Gouëzel, Rémy Degenne -/ import analysis.special_functions.complex.log /-! # Power function on `ℂ`, `ℝ`, `ℝ≥0`, and `ℝ≥0∞` We construct the power functions `x ^ y` where * `x` and `y` are complex numbers, * or `x` and `y` are real numbers, * or `x` is a nonnegative real number and `y` is a real number; * or `x` is a number from `[0, +∞]` (a.k.a. `ℝ≥0∞`) and `y` is a real number. We also prove basic properties of these functions. -/ noncomputable theory open_locale classical real topological_space nnreal ennreal filter open filter namespace complex /-- The complex power function `x^y`, given by `x^y = exp(y log x)` (where `log` is the principal determination of the logarithm), unless `x = 0` where one sets `0^0 = 1` and `0^y = 0` for `y ≠ 0`. -/ noncomputable def cpow (x y : ℂ) : ℂ := if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) noncomputable instance : has_pow ℂ ℂ := ⟨cpow⟩ @[simp] lemma cpow_eq_pow (x y : ℂ) : cpow x y = x ^ y := rfl lemma cpow_def (x y : ℂ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := rfl lemma cpow_def_of_ne_zero {x : ℂ} (hx : x ≠ 0) (y : ℂ) : x ^ y = exp (log x * y) := if_neg hx @[simp] lemma cpow_zero (x : ℂ) : x ^ (0 : ℂ) = 1 := by simp [cpow_def] @[simp] lemma cpow_eq_zero_iff (x y : ℂ) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by { simp only [cpow_def], split_ifs; simp [*, exp_ne_zero] } @[simp] lemma zero_cpow {x : ℂ} (h : x ≠ 0) : (0 : ℂ) ^ x = 0 := by simp [cpow_def, *] lemma zero_cpow_eq_iff {x : ℂ} {a : ℂ} : 0 ^ x = a ↔ (x ≠ 0 ∧ a = 0) ∨ (x = 0 ∧ a = 1) := begin split, { intros hyp, simp [cpow_def] at hyp, by_cases x = 0, { subst h, simp only [if_true, eq_self_iff_true] at hyp, right, exact ⟨rfl, hyp.symm⟩}, { rw if_neg h at hyp, left, exact ⟨h, hyp.symm⟩, }, }, { rintro (⟨h, rfl⟩|⟨rfl,rfl⟩), { exact zero_cpow h, }, { exact cpow_zero _, }, }, end lemma eq_zero_cpow_iff {x : ℂ} {a : ℂ} : a = 0 ^ x ↔ (x ≠ 0 ∧ a = 0) ∨ (x = 0 ∧ a = 1) := by rw [←zero_cpow_eq_iff, eq_comm] @[simp] lemma cpow_one (x : ℂ) : x ^ (1 : ℂ) = x := if hx : x = 0 then by simp [hx, cpow_def] else by rw [cpow_def, if_neg (one_ne_zero : (1 : ℂ) ≠ 0), if_neg hx, mul_one, exp_log hx] @[simp] lemma one_cpow (x : ℂ) : (1 : ℂ) ^ x = 1 := by rw cpow_def; split_ifs; simp [one_ne_zero, *] at * lemma cpow_add {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := by simp [cpow_def]; simp [*, exp_add, mul_add] at * lemma cpow_mul {x y : ℂ} (z : ℂ) (h₁ : -π < (log x * y).im) (h₂ : (log x * y).im ≤ π) : x ^ (y * z) = (x ^ y) ^ z := begin simp only [cpow_def], split_ifs; simp [*, exp_ne_zero, log_exp h₁ h₂, mul_assoc] at * end lemma cpow_neg (x y : ℂ) : x ^ -y = (x ^ y)⁻¹ := by simp [cpow_def]; split_ifs; simp [exp_neg] lemma cpow_sub {x : ℂ} (y z : ℂ) (hx : x ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := by rw [sub_eq_add_neg, cpow_add _ _ hx, cpow_neg, div_eq_mul_inv] lemma cpow_neg_one (x : ℂ) : x ^ (-1 : ℂ) = x⁻¹ := by simpa using cpow_neg x 1 @[simp] lemma cpow_nat_cast (x : ℂ) : ∀ (n : ℕ), x ^ (n : ℂ) = x ^ n | 0 := by simp | (n + 1) := if hx : x = 0 then by simp only [hx, pow_succ, complex.zero_cpow (nat.cast_ne_zero.2 (nat.succ_ne_zero _)), zero_mul] else by simp [cpow_add, hx, pow_add, cpow_nat_cast n] @[simp] lemma cpow_int_cast (x : ℂ) : ∀ (n : ℤ), x ^ (n : ℂ) = x ^ n | (n : ℕ) := by simp; refl | -[1+ n] := by rw zpow_neg_succ_of_nat; simp only [int.neg_succ_of_nat_coe, int.cast_neg, complex.cpow_neg, inv_eq_one_div, int.cast_coe_nat, cpow_nat_cast] lemma cpow_nat_inv_pow (x : ℂ) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℂ)) ^ n = x := begin suffices : im (log x * n⁻¹) ∈ set.Ioc (-π) π, { rw [← cpow_nat_cast, ← cpow_mul _ this.1 this.2, inv_mul_cancel, cpow_one], exact_mod_cast hn.ne' }, rw [mul_comm, ← of_real_nat_cast, ← of_real_inv, of_real_mul_im, ← div_eq_inv_mul], have hn' : 0 < (n : ℝ), by assumption_mod_cast, have hn1 : 1 ≤ (n : ℝ), by exact_mod_cast (nat.succ_le_iff.2 hn), split, { rw lt_div_iff hn', calc -π * n ≤ -π * 1 : mul_le_mul_of_nonpos_left hn1 (neg_nonpos.2 real.pi_pos.le) ... = -π : mul_one _ ... < im (log x) : neg_pi_lt_log_im _ }, { rw div_le_iff hn', calc im (log x) ≤ π : log_im_le_pi _ ... = π * 1 : (mul_one π).symm ... ≤ π * n : mul_le_mul_of_nonneg_left hn1 real.pi_pos.le } end end complex section lim open complex variables {α : Type*} lemma zero_cpow_eq_nhds {b : ℂ} (hb : b ≠ 0) : (0 : ℂ).cpow =ᶠ[𝓝 b] 0 := begin suffices : ∀ᶠ (x : ℂ) in (𝓝 b), x ≠ 0, from this.mono (λ x hx, by rw [cpow_eq_pow, zero_cpow hx, pi.zero_apply]), exact is_open.eventually_mem is_open_ne hb, end lemma cpow_eq_nhds {a b : ℂ} (ha : a ≠ 0) : (λ x, x.cpow b) =ᶠ[𝓝 a] λ x, exp (log x * b) := begin suffices : ∀ᶠ (x : ℂ) in (𝓝 a), x ≠ 0, from this.mono (λ x hx, by { dsimp only, rw [cpow_eq_pow, cpow_def_of_ne_zero hx], }), exact is_open.eventually_mem is_open_ne ha, end lemma cpow_eq_nhds' {p : ℂ × ℂ} (hp_fst : p.fst ≠ 0) : (λ x, x.1 ^ x.2) =ᶠ[𝓝 p] λ x, exp (log x.1 * x.2) := begin suffices : ∀ᶠ (x : ℂ × ℂ) in (𝓝 p), x.1 ≠ 0, from this.mono (λ x hx, by { dsimp only, rw cpow_def_of_ne_zero hx, }), refine is_open.eventually_mem _ hp_fst, change is_open {x : ℂ × ℂ | x.1 = 0}ᶜ, rw is_open_compl_iff, exact is_closed_eq continuous_fst continuous_const, end lemma continuous_at_const_cpow {a b : ℂ} (ha : a ≠ 0) : continuous_at (cpow a) b := begin have cpow_eq : cpow a = λ b, exp (log a * b), by { ext1 b, rw [cpow_eq_pow, cpow_def_of_ne_zero ha], }, rw cpow_eq, exact continuous_exp.continuous_at.comp (continuous_at.mul continuous_at_const continuous_at_id), end lemma continuous_at_const_cpow' {a b : ℂ} (h : b ≠ 0) : continuous_at (cpow a) b := begin by_cases ha : a = 0, { rw [ha, continuous_at_congr (zero_cpow_eq_nhds h)], exact continuous_at_const, }, { exact continuous_at_const_cpow ha, }, end lemma continuous_at_cpow_const {a b : ℂ} (ha : 0 < a.re ∨ a.im ≠ 0) : continuous_at (λ x, cpow x b) a := begin have ha_ne_zero : a ≠ 0, by { intro h, cases ha; { rw h at ha, simpa using ha, }, }, rw continuous_at_congr (cpow_eq_nhds ha_ne_zero), refine continuous_exp.continuous_at.comp _, exact continuous_at.mul (continuous_at_clog ha) continuous_at_const, end lemma continuous_at_cpow {p : ℂ × ℂ} (hp_fst : 0 < p.fst.re ∨ p.fst.im ≠ 0) : continuous_at (λ x : ℂ × ℂ, x.1 ^ x.2) p := begin have hp_fst_ne_zero : p.fst ≠ 0, by { intro h, cases hp_fst; { rw h at hp_fst, simpa using hp_fst, }, }, rw continuous_at_congr (cpow_eq_nhds' hp_fst_ne_zero), refine continuous_exp.continuous_at.comp _, refine continuous_at.mul (continuous_at.comp _ continuous_fst.continuous_at) continuous_snd.continuous_at, exact continuous_at_clog hp_fst, end lemma filter.tendsto.cpow {l : filter α} {f g : α → ℂ} {a b : ℂ} (hf : tendsto f l (𝓝 a)) (hg : tendsto g l (𝓝 b)) (ha : 0 < a.re ∨ a.im ≠ 0) : tendsto (λ x, f x ^ g x) l (𝓝 (a ^ b)) := (@continuous_at_cpow (a,b) ha).tendsto.comp (hf.prod_mk_nhds hg) lemma filter.tendsto.const_cpow {l : filter α} {f : α → ℂ} {a b : ℂ} (hf : tendsto f l (𝓝 b)) (h : a ≠ 0 ∨ b ≠ 0) : tendsto (λ x, a ^ f x) l (𝓝 (a ^ b)) := begin cases h, { exact (continuous_at_const_cpow h).tendsto.comp hf, }, { exact (continuous_at_const_cpow' h).tendsto.comp hf, }, end variables [topological_space α] {f g : α → ℂ} {s : set α} {a : α} lemma continuous_within_at.cpow (hf : continuous_within_at f s a) (hg : continuous_within_at g s a) (h0 : 0 < (f a).re ∨ (f a).im ≠ 0) : continuous_within_at (λ x, f x ^ g x) s a := hf.cpow hg h0 lemma continuous_within_at.const_cpow {b : ℂ} (hf : continuous_within_at f s a) (h : b ≠ 0 ∨ f a ≠ 0) : continuous_within_at (λ x, b ^ f x) s a := hf.const_cpow h lemma continuous_at.cpow (hf : continuous_at f a) (hg : continuous_at g a) (h0 : 0 < (f a).re ∨ (f a).im ≠ 0) : continuous_at (λ x, f x ^ g x) a := hf.cpow hg h0 lemma continuous_at.const_cpow {b : ℂ} (hf : continuous_at f a) (h : b ≠ 0 ∨ f a ≠ 0) : continuous_at (λ x, b ^ f x) a := hf.const_cpow h lemma continuous_on.cpow (hf : continuous_on f s) (hg : continuous_on g s) (h0 : ∀ a ∈ s, 0 < (f a).re ∨ (f a).im ≠ 0) : continuous_on (λ x, f x ^ g x) s := λ a ha, (hf a ha).cpow (hg a ha) (h0 a ha) lemma continuous_on.const_cpow {b : ℂ} (hf : continuous_on f s) (h : b ≠ 0 ∨ ∀ a ∈ s, f a ≠ 0) : continuous_on (λ x, b ^ f x) s := λ a ha, (hf a ha).const_cpow (h.imp id $ λ h, h a ha) lemma continuous.cpow (hf : continuous f) (hg : continuous g) (h0 : ∀ a, 0 < (f a).re ∨ (f a).im ≠ 0) : continuous (λ x, f x ^ g x) := continuous_iff_continuous_at.2 $ λ a, (hf.continuous_at.cpow hg.continuous_at (h0 a)) lemma continuous.const_cpow {b : ℂ} (hf : continuous f) (h : b ≠ 0 ∨ ∀ a, f a ≠ 0) : continuous (λ x, b ^ f x) := continuous_iff_continuous_at.2 $ λ a, (hf.continuous_at.const_cpow $ h.imp id $ λ h, h a) end lim namespace real /-- The real power function `x^y`, defined as the real part of the complex power function. For `x > 0`, it is equal to `exp(y log x)`. For `x = 0`, one sets `0^0=1` and `0^y=0` for `y ≠ 0`. For `x < 0`, the definition is somewhat arbitary as it depends on the choice of a complex determination of the logarithm. With our conventions, it is equal to `exp (y log x) cos (πy)`. -/ noncomputable def rpow (x y : ℝ) := ((x : ℂ) ^ (y : ℂ)).re noncomputable instance : has_pow ℝ ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x y : ℝ) : rpow x y = x ^ y := rfl lemma rpow_def (x y : ℝ) : x ^ y = ((x : ℂ) ^ (y : ℂ)).re := rfl lemma rpow_def_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) := by simp only [rpow_def, complex.cpow_def]; split_ifs; simp [*, (complex.of_real_log hx).symm, -complex.of_real_mul, -is_R_or_C.of_real_mul, (complex.of_real_mul _ _).symm, complex.exp_of_real_re] at * lemma rpow_def_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : x ^ y = exp (log x * y) := by rw [rpow_def_of_nonneg (le_of_lt hx), if_neg (ne_of_gt hx)] lemma exp_mul (x y : ℝ) : exp (x * y) = (exp x) ^ y := by rw [rpow_def_of_pos (exp_pos _), log_exp] lemma rpow_eq_zero_iff_of_nonneg {x y : ℝ} (hx : 0 ≤ x) : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := by { simp only [rpow_def_of_nonneg hx], split_ifs; simp [*, exp_ne_zero] } open_locale real lemma rpow_def_of_neg {x : ℝ} (hx : x < 0) (y : ℝ) : x ^ y = exp (log x * y) * cos (y * π) := begin rw [rpow_def, complex.cpow_def, if_neg], have : complex.log x * y = ↑(log(-x) * y) + ↑(y * π) * complex.I, { simp only [complex.log, abs_of_neg hx, complex.arg_of_real_of_neg hx, complex.abs_of_real, complex.of_real_mul], ring }, { rw [this, complex.exp_add_mul_I, ← complex.of_real_exp, ← complex.of_real_cos, ← complex.of_real_sin, mul_add, ← complex.of_real_mul, ← mul_assoc, ← complex.of_real_mul, complex.add_re, complex.of_real_re, complex.mul_re, complex.I_re, complex.of_real_im, real.log_neg_eq_log], ring }, { rw complex.of_real_eq_zero, exact ne_of_lt hx } end lemma rpow_def_of_nonpos {x : ℝ} (hx : x ≤ 0) (y : ℝ) : x ^ y = if x = 0 then if y = 0 then 1 else 0 else exp (log x * y) * cos (y * π) := by split_ifs; simp [rpow_def, *]; exact rpow_def_of_neg (lt_of_le_of_ne hx h) _ lemma rpow_pos_of_pos {x : ℝ} (hx : 0 < x) (y : ℝ) : 0 < x ^ y := by rw rpow_def_of_pos hx; apply exp_pos @[simp] lemma rpow_zero (x : ℝ) : x ^ (0 : ℝ) = 1 := by simp [rpow_def] @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ) ^ x = 0 := by simp [rpow_def, *] lemma zero_rpow_eq_iff {x : ℝ} {a : ℝ} : 0 ^ x = a ↔ (x ≠ 0 ∧ a = 0) ∨ (x = 0 ∧ a = 1) := begin split, { intros hyp, simp [rpow_def] at hyp, by_cases x = 0, { subst h, simp only [complex.one_re, complex.of_real_zero, complex.cpow_zero] at hyp, exact or.inr ⟨rfl, hyp.symm⟩}, { rw complex.zero_cpow (complex.of_real_ne_zero.mpr h) at hyp, exact or.inl ⟨h, hyp.symm⟩, }, }, { rintro (⟨h,rfl⟩|⟨rfl,rfl⟩), { exact zero_rpow h, }, { exact rpow_zero _, }, }, end lemma eq_zero_rpow_iff {x : ℝ} {a : ℝ} : a = 0 ^ x ↔ (x ≠ 0 ∧ a = 0) ∨ (x = 0 ∧ a = 1) := by rw [←zero_rpow_eq_iff, eq_comm] @[simp] lemma rpow_one (x : ℝ) : x ^ (1 : ℝ) = x := by simp [rpow_def] @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ) ^ x = 1 := by simp [rpow_def] lemma zero_rpow_le_one (x : ℝ) : (0 : ℝ) ^ x ≤ 1 := by { by_cases h : x = 0; simp [h, zero_le_one] } lemma zero_rpow_nonneg (x : ℝ) : 0 ≤ (0 : ℝ) ^ x := by { by_cases h : x = 0; simp [h, zero_le_one] } lemma rpow_nonneg_of_nonneg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : 0 ≤ x ^ y := by rw [rpow_def_of_nonneg hx]; split_ifs; simp only [zero_le_one, le_refl, le_of_lt (exp_pos _)] lemma abs_rpow_le_abs_rpow (x y : ℝ) : |x ^ y| ≤ |x| ^ y := begin rcases lt_trichotomy 0 x with (hx|rfl|hx), { rw [abs_of_pos hx, abs_of_pos (rpow_pos_of_pos hx _)] }, { rw [abs_zero, abs_of_nonneg (rpow_nonneg_of_nonneg le_rfl _)] }, { rw [abs_of_neg hx, rpow_def_of_neg hx, rpow_def_of_pos (neg_pos.2 hx), log_neg_eq_log, abs_mul, abs_of_pos (exp_pos _)], exact mul_le_of_le_one_right (exp_pos _).le (abs_cos_le_one _) } end lemma abs_rpow_le_exp_log_mul (x y : ℝ) : |x ^ y| ≤ exp (log x * y) := begin refine (abs_rpow_le_abs_rpow x y).trans _, by_cases hx : x = 0, { by_cases hy : y = 0; simp [hx, hy, zero_le_one] }, { rw [rpow_def_of_pos (abs_pos.2 hx), log_abs] } end lemma abs_rpow_of_nonneg {x y : ℝ} (hx_nonneg : 0 ≤ x) : |x ^ y| = |x| ^ y := begin have h_rpow_nonneg : 0 ≤ x ^ y, from real.rpow_nonneg_of_nonneg hx_nonneg _, rw [abs_eq_self.mpr hx_nonneg, abs_eq_self.mpr h_rpow_nonneg], end lemma norm_rpow_of_nonneg {x y : ℝ} (hx_nonneg : 0 ≤ x) : ∥x ^ y∥ = ∥x∥ ^ y := by { simp_rw real.norm_eq_abs, exact abs_rpow_of_nonneg hx_nonneg, } end real namespace complex lemma of_real_cpow {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : ((x ^ y : ℝ) : ℂ) = (x : ℂ) ^ (y : ℂ) := by simp [real.rpow_def_of_nonneg hx, complex.cpow_def]; split_ifs; simp [complex.of_real_log hx] @[simp] lemma abs_cpow_real (x : ℂ) (y : ℝ) : abs (x ^ (y : ℂ)) = x.abs ^ y := begin rw [real.rpow_def_of_nonneg (abs_nonneg _), complex.cpow_def], split_ifs; simp [*, abs_of_nonneg (le_of_lt (real.exp_pos _)), complex.log, complex.exp_add, add_mul, mul_right_comm _ I, exp_mul_I, abs_cos_add_sin_mul_I, (complex.of_real_mul _ _).symm, -complex.of_real_mul, -is_R_or_C.of_real_mul] at * end @[simp] lemma abs_cpow_inv_nat (x : ℂ) (n : ℕ) : abs (x ^ (n⁻¹ : ℂ)) = x.abs ^ (n⁻¹ : ℝ) := by rw ← abs_cpow_real; simp [-abs_cpow_real] end complex namespace real variables {x y z : ℝ} lemma rpow_add {x : ℝ} (hx : 0 < x) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z := by simp only [rpow_def_of_pos hx, mul_add, exp_add] lemma rpow_add' {x : ℝ} (hx : 0 ≤ x) {y z : ℝ} (h : y + z ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := begin rcases hx.eq_or_lt with rfl|pos, { rw [zero_rpow h, zero_eq_mul], have : y ≠ 0 ∨ z ≠ 0, from not_and_distrib.1 (λ ⟨hy, hz⟩, h $ hy.symm ▸ hz.symm ▸ zero_add 0), exact this.imp zero_rpow zero_rpow }, { exact rpow_add pos _ _ } end /-- For `0 ≤ x`, the only problematic case in the equality `x ^ y * x ^ z = x ^ (y + z)` is for `x = 0` and `y + z = 0`, where the right hand side is `1` while the left hand side can vanish. The inequality is always true, though, and given in this lemma. -/ lemma le_rpow_add {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ y * x ^ z ≤ x ^ (y + z) := begin rcases le_iff_eq_or_lt.1 hx with H|pos, { by_cases h : y + z = 0, { simp only [H.symm, h, rpow_zero], calc (0 : ℝ) ^ y * 0 ^ z ≤ 1 * 1 : mul_le_mul (zero_rpow_le_one y) (zero_rpow_le_one z) (zero_rpow_nonneg z) zero_le_one ... = 1 : by simp }, { simp [rpow_add', ← H, h] } }, { simp [rpow_add pos] } end lemma rpow_mul {x : ℝ} (hx : 0 ≤ x) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := by rw [← complex.of_real_inj, complex.of_real_cpow (rpow_nonneg_of_nonneg hx _), complex.of_real_cpow hx, complex.of_real_mul, complex.cpow_mul, complex.of_real_cpow hx]; simp only [(complex.of_real_mul _ _).symm, (complex.of_real_log hx).symm, complex.of_real_im, neg_lt_zero, pi_pos, le_of_lt pi_pos] lemma rpow_neg {x : ℝ} (hx : 0 ≤ x) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := by simp only [rpow_def_of_nonneg hx]; split_ifs; simp [*, exp_neg] at * lemma rpow_sub {x : ℝ} (hx : 0 < x) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z := by simp only [sub_eq_add_neg, rpow_add hx, rpow_neg (le_of_lt hx), div_eq_mul_inv] lemma rpow_sub' {x : ℝ} (hx : 0 ≤ x) {y z : ℝ} (h : y - z ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := by { simp only [sub_eq_add_neg] at h ⊢, simp only [rpow_add' hx h, rpow_neg hx, div_eq_mul_inv] } lemma rpow_add_int {x : ℝ} (hx : x ≠ 0) (y : ℝ) (n : ℤ) : x ^ (y + n) = x ^ y * x ^ n := by rw [rpow_def, complex.of_real_add, complex.cpow_add _ _ (complex.of_real_ne_zero.mpr hx), complex.of_real_int_cast, complex.cpow_int_cast, ← complex.of_real_zpow, mul_comm, complex.of_real_mul_re, ← rpow_def, mul_comm] lemma rpow_add_nat {x : ℝ} (hx : x ≠ 0) (y : ℝ) (n : ℕ) : x ^ (y + n) = x ^ y * x ^ n := rpow_add_int hx y n lemma rpow_sub_int {x : ℝ} (hx : x ≠ 0) (y : ℝ) (n : ℤ) : x ^ (y - n) = x ^ y / x ^ n := by simpa using rpow_add_int hx y (-n) lemma rpow_sub_nat {x : ℝ} (hx : x ≠ 0) (y : ℝ) (n : ℕ) : x ^ (y - n) = x ^ y / x ^ n := rpow_sub_int hx y n lemma rpow_add_one {x : ℝ} (hx : x ≠ 0) (y : ℝ) : x ^ (y + 1) = x ^ y * x := by simpa using rpow_add_nat hx y 1 lemma rpow_sub_one {x : ℝ} (hx : x ≠ 0) (y : ℝ) : x ^ (y - 1) = x ^ y / x := by simpa using rpow_sub_nat hx y 1 @[simp, norm_cast] lemma rpow_int_cast (x : ℝ) (n : ℤ) : x ^ (n : ℝ) = x ^ n := by simp only [rpow_def, ← complex.of_real_zpow, complex.cpow_int_cast, complex.of_real_int_cast, complex.of_real_re] @[simp, norm_cast] lemma rpow_nat_cast (x : ℝ) (n : ℕ) : x ^ (n : ℝ) = x ^ n := rpow_int_cast x n lemma rpow_neg_one (x : ℝ) : x ^ (-1 : ℝ) = x⁻¹ := begin suffices H : x ^ ((-1 : ℤ) : ℝ) = x⁻¹, by exact_mod_cast H, simp only [rpow_int_cast, zpow_one, zpow_neg₀], end lemma mul_rpow {x y z : ℝ} (h : 0 ≤ x) (h₁ : 0 ≤ y) : (x*y)^z = x^z * y^z := begin iterate 3 { rw real.rpow_def_of_nonneg }, split_ifs; simp * at *, { have hx : 0 < x, { cases lt_or_eq_of_le h with h₂ h₂, { exact h₂ }, exfalso, apply h_2, exact eq.symm h₂ }, have hy : 0 < y, { cases lt_or_eq_of_le h₁ with h₂ h₂, { exact h₂ }, exfalso, apply h_3, exact eq.symm h₂ }, rw [log_mul (ne_of_gt hx) (ne_of_gt hy), add_mul, exp_add]}, { exact h₁ }, { exact h }, { exact mul_nonneg h h₁ }, end lemma inv_rpow (hx : 0 ≤ x) (y : ℝ) : (x⁻¹)^y = (x^y)⁻¹ := by simp only [← rpow_neg_one, ← rpow_mul hx, mul_comm] lemma div_rpow (hx : 0 ≤ x) (hy : 0 ≤ y) (z : ℝ) : (x / y) ^ z = x^z / y^z := by simp only [div_eq_mul_inv, mul_rpow hx (inv_nonneg.2 hy), inv_rpow hy] lemma log_rpow {x : ℝ} (hx : 0 < x) (y : ℝ) : log (x^y) = y * (log x) := begin apply exp_injective, rw [exp_log (rpow_pos_of_pos hx y), ← exp_log hx, mul_comm, rpow_def_of_pos (exp_pos (log x)) y], end lemma rpow_lt_rpow (hx : 0 ≤ x) (hxy : x < y) (hz : 0 < z) : x^z < y^z := begin rw le_iff_eq_or_lt at hx, cases hx, { rw [← hx, zero_rpow (ne_of_gt hz)], exact rpow_pos_of_pos (by rwa ← hx at hxy) _ }, rw [rpow_def_of_pos hx, rpow_def_of_pos (lt_trans hx hxy), exp_lt_exp], exact mul_lt_mul_of_pos_right (log_lt_log hx hxy) hz end lemma rpow_le_rpow {x y z: ℝ} (h : 0 ≤ x) (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := begin rcases eq_or_lt_of_le h₁ with rfl|h₁', { refl }, rcases eq_or_lt_of_le h₂ with rfl|h₂', { simp }, exact le_of_lt (rpow_lt_rpow h h₁' h₂') end lemma rpow_lt_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := ⟨lt_imp_lt_of_le_imp_le $ λ h, rpow_le_rpow hy h (le_of_lt hz), λ h, rpow_lt_rpow hx h hz⟩ lemma rpow_le_rpow_iff (hx : 0 ≤ x) (hy : 0 ≤ y) (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := le_iff_le_iff_lt_iff_lt.2 $ rpow_lt_rpow_iff hy hx hz lemma rpow_lt_rpow_of_exponent_lt (hx : 1 < x) (hyz : y < z) : x^y < x^z := begin repeat {rw [rpow_def_of_pos (lt_trans zero_lt_one hx)]}, rw exp_lt_exp, exact mul_lt_mul_of_pos_left hyz (log_pos hx), end lemma rpow_le_rpow_of_exponent_le (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos (lt_of_lt_of_le zero_lt_one hx)]}, rw exp_le_exp, exact mul_le_mul_of_nonneg_left hyz (log_nonneg hx), end @[simp] lemma rpow_le_rpow_left_iff (hx : 1 < x) : x ^ y ≤ x ^ z ↔ y ≤ z := begin have x_pos : 0 < x := lt_trans zero_lt_one hx, rw [←log_le_log (rpow_pos_of_pos x_pos y) (rpow_pos_of_pos x_pos z), log_rpow x_pos, log_rpow x_pos, mul_le_mul_right (log_pos hx)], end @[simp] lemma rpow_lt_rpow_left_iff (hx : 1 < x) : x ^ y < x ^ z ↔ y < z := by rw [lt_iff_not_ge', rpow_le_rpow_left_iff hx, lt_iff_not_ge'] lemma rpow_lt_rpow_of_exponent_gt (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_lt_exp, exact mul_lt_mul_of_neg_left hyz (log_neg hx0 hx1), end lemma rpow_le_rpow_of_exponent_ge (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := begin repeat {rw [rpow_def_of_pos hx0]}, rw exp_le_exp, exact mul_le_mul_of_nonpos_left hyz (log_nonpos (le_of_lt hx0) hx1), end @[simp] lemma rpow_le_rpow_left_iff_of_base_lt_one (hx0 : 0 < x) (hx1 : x < 1) : x ^ y ≤ x ^ z ↔ z ≤ y := begin rw [←log_le_log (rpow_pos_of_pos hx0 y) (rpow_pos_of_pos hx0 z), log_rpow hx0, log_rpow hx0, mul_le_mul_right_of_neg (log_neg hx0 hx1)], end @[simp] lemma rpow_lt_rpow_left_iff_of_base_lt_one (hx0 : 0 < x) (hx1 : x < 1) : x ^ y < x ^ z ↔ z < y := by rw [lt_iff_not_ge', rpow_le_rpow_left_iff_of_base_lt_one hx0 hx1, lt_iff_not_ge'] lemma rpow_lt_one {x z : ℝ} (hx1 : 0 ≤ x) (hx2 : x < 1) (hz : 0 < z) : x^z < 1 := by { rw ← one_rpow z, exact rpow_lt_rpow hx1 hx2 hz } lemma rpow_le_one {x z : ℝ} (hx1 : 0 ≤ x) (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := by { rw ← one_rpow z, exact rpow_le_rpow hx1 hx2 hz } lemma rpow_lt_one_of_one_lt_of_neg {x z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 := by { convert rpow_lt_rpow_of_exponent_lt hx hz, exact (rpow_zero x).symm } lemma rpow_le_one_of_one_le_of_nonpos {x z : ℝ} (hx : 1 ≤ x) (hz : z ≤ 0) : x^z ≤ 1 := by { convert rpow_le_rpow_of_exponent_le hx hz, exact (rpow_zero x).symm } lemma one_lt_rpow {x z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := by { rw ← one_rpow z, exact rpow_lt_rpow zero_le_one hx hz } lemma one_le_rpow {x z : ℝ} (hx : 1 ≤ x) (hz : 0 ≤ z) : 1 ≤ x^z := by { rw ← one_rpow z, exact rpow_le_rpow zero_le_one hx hz } lemma one_lt_rpow_of_pos_of_lt_one_of_neg (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) : 1 < x^z := by { convert rpow_lt_rpow_of_exponent_gt hx1 hx2 hz, exact (rpow_zero x).symm } lemma one_le_rpow_of_pos_of_le_one_of_nonpos (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z ≤ 0) : 1 ≤ x^z := by { convert rpow_le_rpow_of_exponent_ge hx1 hx2 hz, exact (rpow_zero x).symm } lemma rpow_lt_one_iff_of_pos (hx : 0 < x) : x ^ y < 1 ↔ 1 < x ∧ y < 0 ∨ x < 1 ∧ 0 < y := by rw [rpow_def_of_pos hx, exp_lt_one_iff, mul_neg_iff, log_pos_iff hx, log_neg_iff hx] lemma rpow_lt_one_iff (hx : 0 ≤ x) : x ^ y < 1 ↔ x = 0 ∧ y ≠ 0 ∨ 1 < x ∧ y < 0 ∨ x < 1 ∧ 0 < y := begin rcases hx.eq_or_lt with (rfl|hx), { rcases em (y = 0) with (rfl|hy); simp [*, lt_irrefl, zero_lt_one] }, { simp [rpow_lt_one_iff_of_pos hx, hx.ne.symm] } end lemma one_lt_rpow_iff_of_pos (hx : 0 < x) : 1 < x ^ y ↔ 1 < x ∧ 0 < y ∨ x < 1 ∧ y < 0 := by rw [rpow_def_of_pos hx, one_lt_exp_iff, mul_pos_iff, log_pos_iff hx, log_neg_iff hx] lemma one_lt_rpow_iff (hx : 0 ≤ x) : 1 < x ^ y ↔ 1 < x ∧ 0 < y ∨ 0 < x ∧ x < 1 ∧ y < 0 := begin rcases hx.eq_or_lt with (rfl|hx), { rcases em (y = 0) with (rfl|hy); simp [*, lt_irrefl, (@zero_lt_one ℝ _ _).not_lt] }, { simp [one_lt_rpow_iff_of_pos hx, hx] } end lemma rpow_le_rpow_of_exponent_ge' (hx0 : 0 ≤ x) (hx1 : x ≤ 1) (hz : 0 ≤ z) (hyz : z ≤ y) : x^y ≤ x^z := begin rcases eq_or_lt_of_le hx0 with rfl | hx0', { rcases eq_or_lt_of_le hz with rfl | hz', { exact (rpow_zero 0).symm ▸ (rpow_le_one hx0 hx1 hyz), }, rw [zero_rpow, zero_rpow]; linarith, }, { exact rpow_le_rpow_of_exponent_ge hx0' hx1 hyz, }, end lemma rpow_left_inj_on {x : ℝ} (hx : x ≠ 0) : set.inj_on (λ y : ℝ, y^x) {y : ℝ | 0 ≤ y} := begin rintros y hy z hz (hyz : y ^ x = z ^ x), rw [←rpow_one y, ←rpow_one z, ←_root_.mul_inv_cancel hx, rpow_mul hy, rpow_mul hz, hyz] end lemma le_rpow_iff_log_le (hx : 0 < x) (hy : 0 < y) : x ≤ y^z ↔ real.log x ≤ z * real.log y := by rw [←real.log_le_log hx (real.rpow_pos_of_pos hy z), real.log_rpow hy] lemma le_rpow_of_log_le (hx : 0 ≤ x) (hy : 0 < y) (h : real.log x ≤ z * real.log y) : x ≤ y^z := begin obtain hx | rfl := hx.lt_or_eq, { exact (le_rpow_iff_log_le hx hy).2 h }, exact (real.rpow_pos_of_pos hy z).le, end lemma lt_rpow_iff_log_lt (hx : 0 < x) (hy : 0 < y) : x < y^z ↔ real.log x < z * real.log y := by rw [←real.log_lt_log_iff hx (real.rpow_pos_of_pos hy z), real.log_rpow hy] lemma lt_rpow_of_log_lt (hx : 0 ≤ x) (hy : 0 < y) (h : real.log x < z * real.log y) : x < y^z := begin obtain hx | rfl := hx.lt_or_eq, { exact (lt_rpow_iff_log_lt hx hy).2 h }, exact real.rpow_pos_of_pos hy z, end lemma rpow_le_one_iff_of_pos (hx : 0 < x) : x ^ y ≤ 1 ↔ 1 ≤ x ∧ y ≤ 0 ∨ x ≤ 1 ∧ 0 ≤ y := by rw [rpow_def_of_pos hx, exp_le_one_iff, mul_nonpos_iff, log_nonneg_iff hx, log_nonpos_iff hx] lemma pow_nat_rpow_nat_inv {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := have hn0 : (n : ℝ) ≠ 0, by simpa [pos_iff_ne_zero] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, mul_inv_cancel hn0, rpow_one] lemma rpow_nat_inv_pow_nat {x : ℝ} (hx : 0 ≤ x) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℝ)) ^ n = x := have hn0 : (n : ℝ) ≠ 0, by simpa [pos_iff_ne_zero] using hn, by rw [← rpow_nat_cast, ← rpow_mul hx, inv_mul_cancel hn0, rpow_one] lemma continuous_at_const_rpow {a b : ℝ} (h : a ≠ 0) : continuous_at (rpow a) b := begin have : rpow a = λ x : ℝ, ((a : ℂ) ^ (x : ℂ)).re, by { ext1 x, rw [rpow_eq_pow, rpow_def], }, rw this, refine complex.continuous_re.continuous_at.comp _, refine (continuous_at_const_cpow _).comp complex.continuous_of_real.continuous_at, norm_cast, exact h, end lemma continuous_at_const_rpow' {a b : ℝ} (h : b ≠ 0) : continuous_at (rpow a) b := begin have : rpow a = λ x : ℝ, ((a : ℂ) ^ (x : ℂ)).re, by { ext1 x, rw [rpow_eq_pow, rpow_def], }, rw this, refine complex.continuous_re.continuous_at.comp _, refine (continuous_at_const_cpow' _).comp complex.continuous_of_real.continuous_at, norm_cast, exact h, end lemma rpow_eq_nhds_of_neg {p : ℝ × ℝ} (hp_fst : p.fst < 0) : (λ x : ℝ × ℝ, x.1 ^ x.2) =ᶠ[𝓝 p] λ x, exp (log x.1 * x.2) * cos (x.2 * π) := begin suffices : ∀ᶠ (x : ℝ × ℝ) in (𝓝 p), x.1 < 0, from this.mono (λ x hx, by { dsimp only, rw rpow_def_of_neg hx, }), exact is_open.eventually_mem (is_open_lt continuous_fst continuous_const) hp_fst, end lemma rpow_eq_nhds_of_pos {p : ℝ × ℝ} (hp_fst : 0 < p.fst) : (λ x : ℝ × ℝ, x.1 ^ x.2) =ᶠ[𝓝 p] λ x, exp (log x.1 * x.2) := begin suffices : ∀ᶠ (x : ℝ × ℝ) in (𝓝 p), 0 < x.1, from this.mono (λ x hx, by { dsimp only, rw rpow_def_of_pos hx, }), exact is_open.eventually_mem (is_open_lt continuous_const continuous_fst) hp_fst, end lemma continuous_at_rpow_of_ne (p : ℝ × ℝ) (hp : p.1 ≠ 0) : continuous_at (λ p : ℝ × ℝ, p.1 ^ p.2) p := begin rw ne_iff_lt_or_gt at hp, cases hp, { rw continuous_at_congr (rpow_eq_nhds_of_neg hp), refine continuous_at.mul _ (continuous_cos.continuous_at.comp _), { refine continuous_exp.continuous_at.comp (continuous_at.mul _ continuous_snd.continuous_at), refine (continuous_at_log _).comp continuous_fst.continuous_at, exact hp.ne, }, { exact continuous_snd.continuous_at.mul continuous_at_const, }, }, { rw continuous_at_congr (rpow_eq_nhds_of_pos hp), refine continuous_exp.continuous_at.comp (continuous_at.mul _ continuous_snd.continuous_at), refine (continuous_at_log _).comp continuous_fst.continuous_at, exact hp.lt.ne.symm, }, end lemma continuous_at_rpow_of_pos (p : ℝ × ℝ) (hp : 0 < p.2) : continuous_at (λ p : ℝ × ℝ, p.1 ^ p.2) p := begin cases p with x y, obtain hx|rfl := ne_or_eq x 0, { exact continuous_at_rpow_of_ne (x, y) hx }, have A : tendsto (λ p : ℝ × ℝ, exp (log p.1 * p.2)) (𝓝[≠] 0 ×ᶠ 𝓝 y) (𝓝 0) := tendsto_exp_at_bot.comp ((tendsto_log_nhds_within_zero.comp tendsto_fst).at_bot_mul hp tendsto_snd), have B : tendsto (λ p : ℝ × ℝ, p.1 ^ p.2) (𝓝[≠] 0 ×ᶠ 𝓝 y) (𝓝 0) := squeeze_zero_norm (λ p, abs_rpow_le_exp_log_mul p.1 p.2) A, have C : tendsto (λ p : ℝ × ℝ, p.1 ^ p.2) (𝓝[{0}] 0 ×ᶠ 𝓝 y) (pure 0), { rw [nhds_within_singleton, tendsto_pure, pure_prod, eventually_map], exact (lt_mem_nhds hp).mono (λ y hy, zero_rpow hy.ne') }, simpa only [← sup_prod, ← nhds_within_union, set.compl_union_self, nhds_within_univ, nhds_prod_eq, continuous_at, zero_rpow hp.ne'] using B.sup (C.mono_right (pure_le_nhds _)) end lemma continuous_at_rpow (p : ℝ × ℝ) (h : p.1 ≠ 0 ∨ 0 < p.2) : continuous_at (λ p : ℝ × ℝ, p.1 ^ p.2) p := h.elim (λ h, continuous_at_rpow_of_ne p h) (λ h, continuous_at_rpow_of_pos p h) end real section variable {α : Type*} lemma filter.tendsto.rpow {l : filter α} {f g : α → ℝ} {x y : ℝ} (hf : tendsto f l (𝓝 x)) (hg : tendsto g l (𝓝 y)) (h : x ≠ 0 ∨ 0 < y) : tendsto (λ t, f t ^ g t) l (𝓝 (x ^ y)) := (real.continuous_at_rpow (x, y) h).tendsto.comp (hf.prod_mk_nhds hg) lemma filter.tendsto.rpow_const {l : filter α} {f : α → ℝ} {x p : ℝ} (hf : tendsto f l (𝓝 x)) (h : x ≠ 0 ∨ 0 ≤ p) : tendsto (λ a, f a ^ p) l (𝓝 (x ^ p)) := if h0 : 0 = p then h0 ▸ by simp [tendsto_const_nhds] else hf.rpow tendsto_const_nhds (h.imp id $ λ h', h'.lt_of_ne h0) variables [topological_space α] {f g : α → ℝ} {s : set α} {x : α} {p : ℝ} lemma continuous_at.rpow (hf : continuous_at f x) (hg : continuous_at g x) (h : f x ≠ 0 ∨ 0 < g x) : continuous_at (λ t, f t ^ g t) x := hf.rpow hg h lemma continuous_within_at.rpow (hf : continuous_within_at f s x) (hg : continuous_within_at g s x) (h : f x ≠ 0 ∨ 0 < g x) : continuous_within_at (λ t, f t ^ g t) s x := hf.rpow hg h lemma continuous_on.rpow (hf : continuous_on f s) (hg : continuous_on g s) (h : ∀ x ∈ s, f x ≠ 0 ∨ 0 < g x) : continuous_on (λ t, f t ^ g t) s := λ t ht, (hf t ht).rpow (hg t ht) (h t ht) lemma continuous.rpow (hf : continuous f) (hg : continuous g) (h : ∀ x, f x ≠ 0 ∨ 0 < g x) : continuous (λ x, f x ^ g x) := continuous_iff_continuous_at.2 $ λ x, (hf.continuous_at.rpow hg.continuous_at (h x)) lemma continuous_within_at.rpow_const (hf : continuous_within_at f s x) (h : f x ≠ 0 ∨ 0 ≤ p) : continuous_within_at (λ x, f x ^ p) s x := hf.rpow_const h lemma continuous_at.rpow_const (hf : continuous_at f x) (h : f x ≠ 0 ∨ 0 ≤ p) : continuous_at (λ x, f x ^ p) x := hf.rpow_const h lemma continuous_on.rpow_const (hf : continuous_on f s) (h : ∀ x ∈ s, f x ≠ 0 ∨ 0 ≤ p) : continuous_on (λ x, f x ^ p) s := λ x hx, (hf x hx).rpow_const (h x hx) lemma continuous.rpow_const (hf : continuous f) (h : ∀ x, f x ≠ 0 ∨ 0 ≤ p) : continuous (λ x, f x ^ p) := continuous_iff_continuous_at.2 $ λ x, hf.continuous_at.rpow_const (h x) end namespace real variables {z x y : ℝ} section sqrt lemma sqrt_eq_rpow (x : ℝ) : sqrt x = x ^ (1/(2:ℝ)) := begin obtain h | h := le_or_lt 0 x, { rw [← mul_self_inj_of_nonneg (sqrt_nonneg _) (rpow_nonneg_of_nonneg h _), mul_self_sqrt h, ← sq, ← rpow_nat_cast, ← rpow_mul h], norm_num }, { have : 1 / (2:ℝ) * π = π / (2:ℝ), ring, rw [sqrt_eq_zero_of_nonpos h.le, rpow_def_of_neg h, this, cos_pi_div_two, mul_zero] } end end sqrt end real section limits open real filter /-- The function `x ^ y` tends to `+∞` at `+∞` for any positive real `y`. -/ lemma tendsto_rpow_at_top {y : ℝ} (hy : 0 < y) : tendsto (λ x : ℝ, x ^ y) at_top at_top := begin rw tendsto_at_top_at_top, intro b, use (max b 0) ^ (1/y), intros x hx, exact le_of_max_le_left (by { convert rpow_le_rpow (rpow_nonneg_of_nonneg (le_max_right b 0) (1/y)) hx (le_of_lt hy), rw [← rpow_mul (le_max_right b 0), (eq_div_iff (ne_of_gt hy)).mp rfl, rpow_one] }), end /-- The function `x ^ (-y)` tends to `0` at `+∞` for any positive real `y`. -/ lemma tendsto_rpow_neg_at_top {y : ℝ} (hy : 0 < y) : tendsto (λ x : ℝ, x ^ (-y)) at_top (𝓝 0) := tendsto.congr' (eventually_eq_of_mem (Ioi_mem_at_top 0) (λ x hx, (rpow_neg (le_of_lt hx) y).symm)) (tendsto_rpow_at_top hy).inv_tendsto_at_top /-- The function `x ^ (a / (b * x + c))` tends to `1` at `+∞`, for any real numbers `a`, `b`, and `c` such that `b` is nonzero. -/ lemma tendsto_rpow_div_mul_add (a b c : ℝ) (hb : 0 ≠ b) : tendsto (λ x, x ^ (a / (b*x+c))) at_top (𝓝 1) := begin refine tendsto.congr' _ ((tendsto_exp_nhds_0_nhds_1.comp (by simpa only [mul_zero, pow_one] using ((@tendsto_const_nhds _ _ _ a _).mul (tendsto_div_pow_mul_exp_add_at_top b c 1 hb (by norm_num))))).comp (tendsto_log_at_top)), apply eventually_eq_of_mem (Ioi_mem_at_top (0:ℝ)), intros x hx, simp only [set.mem_Ioi, function.comp_app] at hx ⊢, rw [exp_log hx, ← exp_log (rpow_pos_of_pos hx (a / (b * x + c))), log_rpow hx (a / (b * x + c))], field_simp, end /-- The function `x ^ (1 / x)` tends to `1` at `+∞`. -/ lemma tendsto_rpow_div : tendsto (λ x, x ^ ((1:ℝ) / x)) at_top (𝓝 1) := by { convert tendsto_rpow_div_mul_add (1:ℝ) _ (0:ℝ) zero_ne_one, ring_nf } /-- The function `x ^ (-1 / x)` tends to `1` at `+∞`. -/ lemma tendsto_rpow_neg_div : tendsto (λ x, x ^ (-(1:ℝ) / x)) at_top (𝓝 1) := by { convert tendsto_rpow_div_mul_add (-(1:ℝ)) _ (0:ℝ) zero_ne_one, ring_nf } end limits namespace nnreal /-- The nonnegative real power function `x^y`, defined for `x : ℝ≥0` and `y : ℝ ` as the restriction of the real power function. For `x > 0`, it is equal to `exp (y log x)`. For `x = 0`, one sets `0 ^ 0 = 1` and `0 ^ y = 0` for `y ≠ 0`. -/ noncomputable def rpow (x : ℝ≥0) (y : ℝ) : ℝ≥0 := ⟨(x : ℝ) ^ y, real.rpow_nonneg_of_nonneg x.2 y⟩ noncomputable instance : has_pow ℝ≥0 ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x : ℝ≥0) (y : ℝ) : rpow x y = x ^ y := rfl @[simp, norm_cast] lemma coe_rpow (x : ℝ≥0) (y : ℝ) : ((x ^ y : ℝ≥0) : ℝ) = (x : ℝ) ^ y := rfl @[simp] lemma rpow_zero (x : ℝ≥0) : x ^ (0 : ℝ) = 1 := nnreal.eq $ real.rpow_zero _ @[simp] lemma rpow_eq_zero_iff {x : ℝ≥0} {y : ℝ} : x ^ y = 0 ↔ x = 0 ∧ y ≠ 0 := begin rw [← nnreal.coe_eq, coe_rpow, ← nnreal.coe_eq_zero], exact real.rpow_eq_zero_iff_of_nonneg x.2 end @[simp] lemma zero_rpow {x : ℝ} (h : x ≠ 0) : (0 : ℝ≥0) ^ x = 0 := nnreal.eq $ real.zero_rpow h @[simp] lemma rpow_one (x : ℝ≥0) : x ^ (1 : ℝ) = x := nnreal.eq $ real.rpow_one _ @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ≥0) ^ x = 1 := nnreal.eq $ real.one_rpow _ lemma rpow_add {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y + z) = x ^ y * x ^ z := nnreal.eq $ real.rpow_add (pos_iff_ne_zero.2 hx) _ _ lemma rpow_add' (x : ℝ≥0) {y z : ℝ} (h : y + z ≠ 0) : x ^ (y + z) = x ^ y * x ^ z := nnreal.eq $ real.rpow_add' x.2 h lemma rpow_mul (x : ℝ≥0) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := nnreal.eq $ real.rpow_mul x.2 y z lemma rpow_neg (x : ℝ≥0) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := nnreal.eq $ real.rpow_neg x.2 _ lemma rpow_neg_one (x : ℝ≥0) : x ^ (-1 : ℝ) = x ⁻¹ := by simp [rpow_neg] lemma rpow_sub {x : ℝ≥0} (hx : x ≠ 0) (y z : ℝ) : x ^ (y - z) = x ^ y / x ^ z := nnreal.eq $ real.rpow_sub (pos_iff_ne_zero.2 hx) y z lemma rpow_sub' (x : ℝ≥0) {y z : ℝ} (h : y - z ≠ 0) : x ^ (y - z) = x ^ y / x ^ z := nnreal.eq $ real.rpow_sub' x.2 h lemma rpow_inv_rpow_self {y : ℝ} (hy : y ≠ 0) (x : ℝ≥0) : (x ^ y) ^ (1 / y) = x := by field_simp [← rpow_mul] lemma rpow_self_rpow_inv {y : ℝ} (hy : y ≠ 0) (x : ℝ≥0) : (x ^ (1 / y)) ^ y = x := by field_simp [← rpow_mul] lemma inv_rpow (x : ℝ≥0) (y : ℝ) : (x⁻¹) ^ y = (x ^ y)⁻¹ := nnreal.eq $ real.inv_rpow x.2 y lemma div_rpow (x y : ℝ≥0) (z : ℝ) : (x / y) ^ z = x ^ z / y ^ z := nnreal.eq $ real.div_rpow x.2 y.2 z lemma sqrt_eq_rpow (x : ℝ≥0) : sqrt x = x ^ (1/(2:ℝ)) := begin refine nnreal.eq _, push_cast, exact real.sqrt_eq_rpow x.1, end @[simp, norm_cast] lemma rpow_nat_cast (x : ℝ≥0) (n : ℕ) : x ^ (n : ℝ) = x ^ n := nnreal.eq $ by simpa only [coe_rpow, coe_pow] using real.rpow_nat_cast x n lemma mul_rpow {x y : ℝ≥0} {z : ℝ} : (x*y)^z = x^z * y^z := nnreal.eq $ real.mul_rpow x.2 y.2 lemma rpow_le_rpow {x y : ℝ≥0} {z: ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := real.rpow_le_rpow x.2 h₁ h₂ lemma rpow_lt_rpow {x y : ℝ≥0} {z: ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z := real.rpow_lt_rpow x.2 h₁ h₂ lemma rpow_lt_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := real.rpow_lt_rpow_iff x.2 y.2 hz lemma rpow_le_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := real.rpow_le_rpow_iff x.2 y.2 hz lemma le_rpow_one_div_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ≤ y ^ (1 / z) ↔ x ^ z ≤ y := by rw [← rpow_le_rpow_iff hz, rpow_self_rpow_inv hz.ne'] lemma rpow_one_div_le_iff {x y : ℝ≥0} {z : ℝ} (hz : 0 < z) : x ^ (1 / z) ≤ y ↔ x ≤ y ^ z := by rw [← rpow_le_rpow_iff hz, rpow_self_rpow_inv hz.ne'] lemma rpow_lt_rpow_of_exponent_lt {x : ℝ≥0} {y z : ℝ} (hx : 1 < x) (hyz : y < z) : x^y < x^z := real.rpow_lt_rpow_of_exponent_lt hx hyz lemma rpow_le_rpow_of_exponent_le {x : ℝ≥0} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := real.rpow_le_rpow_of_exponent_le hx hyz lemma rpow_lt_rpow_of_exponent_gt {x : ℝ≥0} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := real.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz lemma rpow_le_rpow_of_exponent_ge {x : ℝ≥0} {y z : ℝ} (hx0 : 0 < x) (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := real.rpow_le_rpow_of_exponent_ge hx0 hx1 hyz lemma rpow_pos {p : ℝ} {x : ℝ≥0} (hx_pos : 0 < x) : 0 < x^p := begin have rpow_pos_of_nonneg : ∀ {p : ℝ}, 0 < p → 0 < x^p, { intros p hp_pos, rw ←zero_rpow hp_pos.ne', exact rpow_lt_rpow hx_pos hp_pos }, rcases lt_trichotomy 0 p with hp_pos|rfl|hp_neg, { exact rpow_pos_of_nonneg hp_pos }, { simp only [zero_lt_one, rpow_zero] }, { rw [←neg_neg p, rpow_neg, inv_pos], exact rpow_pos_of_nonneg (neg_pos.mpr hp_neg) }, end lemma rpow_lt_one {x : ℝ≥0} {z : ℝ} (hx : 0 ≤ x) (hx1 : x < 1) (hz : 0 < z) : x^z < 1 := real.rpow_lt_one hx hx1 hz lemma rpow_le_one {x : ℝ≥0} {z : ℝ} (hx2 : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := real.rpow_le_one x.2 hx2 hz lemma rpow_lt_one_of_one_lt_of_neg {x : ℝ≥0} {z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 := real.rpow_lt_one_of_one_lt_of_neg hx hz lemma rpow_le_one_of_one_le_of_nonpos {x : ℝ≥0} {z : ℝ} (hx : 1 ≤ x) (hz : z ≤ 0) : x^z ≤ 1 := real.rpow_le_one_of_one_le_of_nonpos hx hz lemma one_lt_rpow {x : ℝ≥0} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := real.one_lt_rpow hx hz lemma one_le_rpow {x : ℝ≥0} {z : ℝ} (h : 1 ≤ x) (h₁ : 0 ≤ z) : 1 ≤ x^z := real.one_le_rpow h h₁ lemma one_lt_rpow_of_pos_of_lt_one_of_neg {x : ℝ≥0} {z : ℝ} (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) : 1 < x^z := real.one_lt_rpow_of_pos_of_lt_one_of_neg hx1 hx2 hz lemma one_le_rpow_of_pos_of_le_one_of_nonpos {x : ℝ≥0} {z : ℝ} (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z ≤ 0) : 1 ≤ x^z := real.one_le_rpow_of_pos_of_le_one_of_nonpos hx1 hx2 hz lemma rpow_le_self_of_le_one {x : ℝ≥0} {z : ℝ} (hx : x ≤ 1) (h_one_le : 1 ≤ z) : x ^ z ≤ x := begin rcases eq_bot_or_bot_lt x with rfl | (h : 0 < x), { have : z ≠ 0 := by linarith, simp [this] }, nth_rewrite 1 ←nnreal.rpow_one x, exact nnreal.rpow_le_rpow_of_exponent_ge h hx h_one_le, end lemma rpow_left_injective {x : ℝ} (hx : x ≠ 0) : function.injective (λ y : ℝ≥0, y^x) := λ y z hyz, by simpa only [rpow_inv_rpow_self hx] using congr_arg (λ y, y ^ (1 / x)) hyz lemma rpow_eq_rpow_iff {x y : ℝ≥0} {z : ℝ} (hz : z ≠ 0) : x ^ z = y ^ z ↔ x = y := (rpow_left_injective hz).eq_iff lemma rpow_left_surjective {x : ℝ} (hx : x ≠ 0) : function.surjective (λ y : ℝ≥0, y^x) := λ y, ⟨y ^ x⁻¹, by simp_rw [←rpow_mul, _root_.inv_mul_cancel hx, rpow_one]⟩ lemma rpow_left_bijective {x : ℝ} (hx : x ≠ 0) : function.bijective (λ y : ℝ≥0, y^x) := ⟨rpow_left_injective hx, rpow_left_surjective hx⟩ lemma eq_rpow_one_div_iff {x y : ℝ≥0} {z : ℝ} (hz : z ≠ 0) : x = y ^ (1 / z) ↔ x ^ z = y := by rw [← rpow_eq_rpow_iff hz, rpow_self_rpow_inv hz] lemma rpow_one_div_eq_iff {x y : ℝ≥0} {z : ℝ} (hz : z ≠ 0) : x ^ (1 / z) = y ↔ x = y ^ z := by rw [← rpow_eq_rpow_iff hz, rpow_self_rpow_inv hz] lemma pow_nat_rpow_nat_inv (x : ℝ≥0) {n : ℕ} (hn : 0 < n) : (x ^ n) ^ (n⁻¹ : ℝ) = x := by { rw [← nnreal.coe_eq, coe_rpow, nnreal.coe_pow], exact real.pow_nat_rpow_nat_inv x.2 hn } lemma rpow_nat_inv_pow_nat (x : ℝ≥0) {n : ℕ} (hn : 0 < n) : (x ^ (n⁻¹ : ℝ)) ^ n = x := by { rw [← nnreal.coe_eq, nnreal.coe_pow, coe_rpow], exact real.rpow_nat_inv_pow_nat x.2 hn } lemma continuous_at_rpow {x : ℝ≥0} {y : ℝ} (h : x ≠ 0 ∨ 0 < y) : continuous_at (λp:ℝ≥0×ℝ, p.1^p.2) (x, y) := begin have : (λp:ℝ≥0×ℝ, p.1^p.2) = real.to_nnreal ∘ (λp:ℝ×ℝ, p.1^p.2) ∘ (λp:ℝ≥0 × ℝ, (p.1.1, p.2)), { ext p, rw [coe_rpow, real.coe_to_nnreal _ (real.rpow_nonneg_of_nonneg p.1.2 _)], refl }, rw this, refine nnreal.continuous_of_real.continuous_at.comp (continuous_at.comp _ _), { apply real.continuous_at_rpow, simp at h, rw ← (nnreal.coe_eq_zero x) at h, exact h }, { exact ((continuous_subtype_val.comp continuous_fst).prod_mk continuous_snd).continuous_at } end lemma _root_.real.to_nnreal_rpow_of_nonneg {x y : ℝ} (hx : 0 ≤ x) : real.to_nnreal (x ^ y) = (real.to_nnreal x) ^ y := begin nth_rewrite 0 ← real.coe_to_nnreal x hx, rw [←nnreal.coe_rpow, real.to_nnreal_coe], end end nnreal open filter lemma filter.tendsto.nnrpow {α : Type*} {f : filter α} {u : α → ℝ≥0} {v : α → ℝ} {x : ℝ≥0} {y : ℝ} (hx : tendsto u f (𝓝 x)) (hy : tendsto v f (𝓝 y)) (h : x ≠ 0 ∨ 0 < y) : tendsto (λ a, (u a) ^ (v a)) f (𝓝 (x ^ y)) := tendsto.comp (nnreal.continuous_at_rpow h) (hx.prod_mk_nhds hy) namespace nnreal lemma continuous_at_rpow_const {x : ℝ≥0} {y : ℝ} (h : x ≠ 0 ∨ 0 ≤ y) : continuous_at (λ z, z^y) x := h.elim (λ h, tendsto_id.nnrpow tendsto_const_nhds (or.inl h)) $ λ h, h.eq_or_lt.elim (λ h, h ▸ by simp only [rpow_zero, continuous_at_const]) (λ h, tendsto_id.nnrpow tendsto_const_nhds (or.inr h)) lemma continuous_rpow_const {y : ℝ} (h : 0 ≤ y) : continuous (λ x : ℝ≥0, x^y) := continuous_iff_continuous_at.2 $ λ x, continuous_at_rpow_const (or.inr h) theorem tendsto_rpow_at_top {y : ℝ} (hy : 0 < y) : tendsto (λ (x : ℝ≥0), x ^ y) at_top at_top := begin rw filter.tendsto_at_top_at_top, intros b, obtain ⟨c, hc⟩ := tendsto_at_top_at_top.mp (tendsto_rpow_at_top hy) b, use c.to_nnreal, intros a ha, exact_mod_cast hc a (real.to_nnreal_le_iff_le_coe.mp ha), end end nnreal namespace ennreal /-- The real power function `x^y` on extended nonnegative reals, defined for `x : ℝ≥0∞` and `y : ℝ` as the restriction of the real power function if `0 < x < ⊤`, and with the natural values for `0` and `⊤` (i.e., `0 ^ x = 0` for `x > 0`, `1` for `x = 0` and `⊤` for `x < 0`, and `⊤ ^ x = 1 / 0 ^ x`). -/ noncomputable def rpow : ℝ≥0∞ → ℝ → ℝ≥0∞ | (some x) y := if x = 0 ∧ y < 0 then ⊤ else (x ^ y : ℝ≥0) | none y := if 0 < y then ⊤ else if y = 0 then 1 else 0 noncomputable instance : has_pow ℝ≥0∞ ℝ := ⟨rpow⟩ @[simp] lemma rpow_eq_pow (x : ℝ≥0∞) (y : ℝ) : rpow x y = x ^ y := rfl @[simp] lemma rpow_zero {x : ℝ≥0∞} : x ^ (0 : ℝ) = 1 := by cases x; { dsimp only [(^), rpow], simp [lt_irrefl] } lemma top_rpow_def (y : ℝ) : (⊤ : ℝ≥0∞) ^ y = if 0 < y then ⊤ else if y = 0 then 1 else 0 := rfl @[simp] lemma top_rpow_of_pos {y : ℝ} (h : 0 < y) : (⊤ : ℝ≥0∞) ^ y = ⊤ := by simp [top_rpow_def, h] @[simp] lemma top_rpow_of_neg {y : ℝ} (h : y < 0) : (⊤ : ℝ≥0∞) ^ y = 0 := by simp [top_rpow_def, asymm h, ne_of_lt h] @[simp] lemma zero_rpow_of_pos {y : ℝ} (h : 0 < y) : (0 : ℝ≥0∞) ^ y = 0 := begin rw [← ennreal.coe_zero, ← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h, asymm h, ne_of_gt h], end @[simp] lemma zero_rpow_of_neg {y : ℝ} (h : y < 0) : (0 : ℝ≥0∞) ^ y = ⊤ := begin rw [← ennreal.coe_zero, ← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h, ne_of_gt h], end lemma zero_rpow_def (y : ℝ) : (0 : ℝ≥0∞) ^ y = if 0 < y then 0 else if y = 0 then 1 else ⊤ := begin rcases lt_trichotomy 0 y with H|rfl|H, { simp [H, ne_of_gt, zero_rpow_of_pos, lt_irrefl] }, { simp [lt_irrefl] }, { simp [H, asymm H, ne_of_lt, zero_rpow_of_neg] } end @[simp] lemma zero_rpow_mul_self (y : ℝ) : (0 : ℝ≥0∞) ^ y * 0 ^ y = 0 ^ y := by { rw zero_rpow_def, split_ifs, exacts [zero_mul _, one_mul _, top_mul_top] } @[norm_cast] lemma coe_rpow_of_ne_zero {x : ℝ≥0} (h : x ≠ 0) (y : ℝ) : (x : ℝ≥0∞) ^ y = (x ^ y : ℝ≥0) := begin rw [← ennreal.some_eq_coe], dsimp only [(^), rpow], simp [h] end @[norm_cast] lemma coe_rpow_of_nonneg (x : ℝ≥0) {y : ℝ} (h : 0 ≤ y) : (x : ℝ≥0∞) ^ y = (x ^ y : ℝ≥0) := begin by_cases hx : x = 0, { rcases le_iff_eq_or_lt.1 h with H|H, { simp [hx, H.symm] }, { simp [hx, zero_rpow_of_pos H, nnreal.zero_rpow (ne_of_gt H)] } }, { exact coe_rpow_of_ne_zero hx _ } end lemma coe_rpow_def (x : ℝ≥0) (y : ℝ) : (x : ℝ≥0∞) ^ y = if x = 0 ∧ y < 0 then ⊤ else (x ^ y : ℝ≥0) := rfl @[simp] lemma rpow_one (x : ℝ≥0∞) : x ^ (1 : ℝ) = x := by cases x; dsimp only [(^), rpow]; simp [zero_lt_one, not_lt_of_le zero_le_one] @[simp] lemma one_rpow (x : ℝ) : (1 : ℝ≥0∞) ^ x = 1 := by { rw [← coe_one, coe_rpow_of_ne_zero one_ne_zero], simp } @[simp] lemma rpow_eq_zero_iff {x : ℝ≥0∞} {y : ℝ} : x ^ y = 0 ↔ (x = 0 ∧ 0 < y) ∨ (x = ⊤ ∧ y < 0) := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [H, top_rpow_of_neg, top_rpow_of_pos, le_of_lt] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, H, zero_rpow_of_neg, zero_rpow_of_pos, le_of_lt] }, { simp [coe_rpow_of_ne_zero h, h] } } end @[simp] lemma rpow_eq_top_iff {x : ℝ≥0∞} {y : ℝ} : x ^ y = ⊤ ↔ (x = 0 ∧ y < 0) ∨ (x = ⊤ ∧ 0 < y) := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [H, top_rpow_of_neg, top_rpow_of_pos, le_of_lt] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, H, zero_rpow_of_neg, zero_rpow_of_pos, le_of_lt] }, { simp [coe_rpow_of_ne_zero h, h] } } end lemma rpow_eq_top_iff_of_pos {x : ℝ≥0∞} {y : ℝ} (hy : 0 < y) : x ^ y = ⊤ ↔ x = ⊤ := by simp [rpow_eq_top_iff, hy, asymm hy] lemma rpow_eq_top_of_nonneg (x : ℝ≥0∞) {y : ℝ} (hy0 : 0 ≤ y) : x ^ y = ⊤ → x = ⊤ := begin rw ennreal.rpow_eq_top_iff, intro h, cases h, { exfalso, rw lt_iff_not_ge at h, exact h.right hy0, }, { exact h.left, }, end lemma rpow_ne_top_of_nonneg {x : ℝ≥0∞} {y : ℝ} (hy0 : 0 ≤ y) (h : x ≠ ⊤) : x ^ y ≠ ⊤ := mt (ennreal.rpow_eq_top_of_nonneg x hy0) h lemma rpow_lt_top_of_nonneg {x : ℝ≥0∞} {y : ℝ} (hy0 : 0 ≤ y) (h : x ≠ ⊤) : x ^ y < ⊤ := lt_top_iff_ne_top.mpr (ennreal.rpow_ne_top_of_nonneg hy0 h) lemma rpow_add {x : ℝ≥0∞} (y z : ℝ) (hx : x ≠ 0) (h'x : x ≠ ⊤) : x ^ (y + z) = x ^ y * x ^ z := begin cases x, { exact (h'x rfl).elim }, have : x ≠ 0 := λ h, by simpa [h] using hx, simp [coe_rpow_of_ne_zero this, nnreal.rpow_add this] end lemma rpow_neg (x : ℝ≥0∞) (y : ℝ) : x ^ -y = (x ^ y)⁻¹ := begin cases x, { rcases lt_trichotomy y 0 with H|H|H; simp [top_rpow_of_pos, top_rpow_of_neg, H, neg_pos.mpr] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with H|H|H; simp [h, zero_rpow_of_pos, zero_rpow_of_neg, H, neg_pos.mpr] }, { have A : x ^ y ≠ 0, by simp [h], simp [coe_rpow_of_ne_zero h, ← coe_inv A, nnreal.rpow_neg] } } end lemma rpow_sub {x : ℝ≥0∞} (y z : ℝ) (hx : x ≠ 0) (h'x : x ≠ ⊤) : x ^ (y - z) = x ^ y / x ^ z := by rw [sub_eq_add_neg, rpow_add _ _ hx h'x, rpow_neg, div_eq_mul_inv] lemma rpow_neg_one (x : ℝ≥0∞) : x ^ (-1 : ℝ) = x ⁻¹ := by simp [rpow_neg] lemma rpow_mul (x : ℝ≥0∞) (y z : ℝ) : x ^ (y * z) = (x ^ y) ^ z := begin cases x, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, zero_rpow_of_neg, zero_rpow_of_pos, top_rpow_of_neg, top_rpow_of_pos, mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] }, { by_cases h : x = 0, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [h, Hy, Hz, zero_rpow_of_neg, zero_rpow_of_pos, top_rpow_of_neg, top_rpow_of_pos, mul_pos_of_neg_of_neg, mul_neg_of_neg_of_pos, mul_neg_of_pos_of_neg] }, { have : x ^ y ≠ 0, by simp [h], simp [coe_rpow_of_ne_zero h, coe_rpow_of_ne_zero this, nnreal.rpow_mul] } } end @[simp, norm_cast] lemma rpow_nat_cast (x : ℝ≥0∞) (n : ℕ) : x ^ (n : ℝ) = x ^ n := begin cases x, { cases n; simp [top_rpow_of_pos (nat.cast_add_one_pos _), top_pow (nat.succ_pos _)] }, { simp [coe_rpow_of_nonneg _ (nat.cast_nonneg n)] } end lemma mul_rpow_eq_ite (x y : ℝ≥0∞) (z : ℝ) : (x * y) ^ z = if (x = 0 ∧ y = ⊤ ∨ x = ⊤ ∧ y = 0) ∧ z < 0 then ⊤ else x ^ z * y ^ z := begin rcases eq_or_ne z 0 with rfl|hz, { simp }, replace hz := hz.lt_or_lt, wlog hxy : x ≤ y := le_total x y using [x y, y x] tactic.skip, { rcases eq_or_ne x 0 with rfl|hx0, { induction y using with_top.rec_top_coe; cases hz with hz hz; simp [*, hz.not_lt] }, rcases eq_or_ne y 0 with rfl|hy0, { exact (hx0 (bot_unique hxy)).elim }, induction x using with_top.rec_top_coe, { cases hz with hz hz; simp [hz, top_unique hxy] }, induction y using with_top.rec_top_coe, { cases hz with hz hz; simp * }, simp only [*, false_and, and_false, false_or, if_false], norm_cast at *, rw [coe_rpow_of_ne_zero (mul_ne_zero hx0 hy0), nnreal.mul_rpow] }, { convert this using 2; simp only [mul_comm, and_comm, or_comm] } end lemma mul_rpow_of_ne_top {x y : ℝ≥0∞} (hx : x ≠ ⊤) (hy : y ≠ ⊤) (z : ℝ) : (x * y) ^ z = x^z * y^z := by simp [*, mul_rpow_eq_ite] @[norm_cast] lemma coe_mul_rpow (x y : ℝ≥0) (z : ℝ) : ((x : ℝ≥0∞) * y) ^ z = x^z * y^z := mul_rpow_of_ne_top coe_ne_top coe_ne_top z lemma mul_rpow_of_ne_zero {x y : ℝ≥0∞} (hx : x ≠ 0) (hy : y ≠ 0) (z : ℝ) : (x * y) ^ z = x ^ z * y ^ z := by simp [*, mul_rpow_eq_ite] lemma mul_rpow_of_nonneg (x y : ℝ≥0∞) {z : ℝ} (hz : 0 ≤ z) : (x * y) ^ z = x ^ z * y ^ z := by simp [hz.not_lt, mul_rpow_eq_ite] lemma inv_rpow (x : ℝ≥0∞) (y : ℝ) : (x⁻¹) ^ y = (x ^ y)⁻¹ := begin rcases eq_or_ne y 0 with rfl|hy, { simp only [rpow_zero, inv_one] }, replace hy := hy.lt_or_lt, rcases eq_or_ne x 0 with rfl|h0, { cases hy; simp * }, rcases eq_or_ne x ⊤ with rfl|h_top, { cases hy; simp * }, apply eq_inv_of_mul_eq_one, rw [← mul_rpow_of_ne_zero (inv_ne_zero.2 h_top) h0, inv_mul_cancel h0 h_top, one_rpow] end lemma div_rpow_of_nonneg (x y : ℝ≥0∞) {z : ℝ} (hz : 0 ≤ z) : (x / y) ^ z = x ^ z / y ^ z := by rw [div_eq_mul_inv, mul_rpow_of_nonneg _ _ hz, inv_rpow, div_eq_mul_inv] lemma strict_mono_rpow_of_pos {z : ℝ} (h : 0 < z) : strict_mono (λ x : ℝ≥0∞, x ^ z) := begin intros x y hxy, lift x to ℝ≥0 using ne_top_of_lt hxy, rcases eq_or_ne y ∞ with rfl|hy, { simp only [top_rpow_of_pos h, coe_rpow_of_nonneg _ h.le, coe_lt_top] }, { lift y to ℝ≥0 using hy, simp only [coe_rpow_of_nonneg _ h.le, nnreal.rpow_lt_rpow (coe_lt_coe.1 hxy) h, coe_lt_coe] } end lemma monotone_rpow_of_nonneg {z : ℝ} (h : 0 ≤ z) : monotone (λ x : ℝ≥0∞, x ^ z) := h.eq_or_lt.elim (λ h0, h0 ▸ by simp only [rpow_zero, monotone_const]) (λ h0, (strict_mono_rpow_of_pos h0).monotone) /-- Bundles `λ x : ℝ≥0∞, x ^ y` into an order isomorphism when `y : ℝ` is positive, where the inverse is `λ x : ℝ≥0∞, x ^ (1 / y)`. -/ @[simps apply] def order_iso_rpow (y : ℝ) (hy : 0 < y) : ℝ≥0∞ ≃o ℝ≥0∞ := (strict_mono_rpow_of_pos hy).order_iso_of_right_inverse (λ x, x ^ y) (λ x, x ^ (1 / y)) (λ x, by { dsimp, rw [←rpow_mul, one_div_mul_cancel hy.ne.symm, rpow_one] }) lemma order_iso_rpow_symm_apply (y : ℝ) (hy : 0 < y) : (order_iso_rpow y hy).symm = order_iso_rpow (1 / y) (one_div_pos.2 hy) := by { simp only [order_iso_rpow, one_div_one_div], refl } lemma rpow_le_rpow {x y : ℝ≥0∞} {z : ℝ} (h₁ : x ≤ y) (h₂ : 0 ≤ z) : x^z ≤ y^z := monotone_rpow_of_nonneg h₂ h₁ lemma rpow_lt_rpow {x y : ℝ≥0∞} {z : ℝ} (h₁ : x < y) (h₂ : 0 < z) : x^z < y^z := strict_mono_rpow_of_pos h₂ h₁ lemma rpow_le_rpow_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x ^ z ≤ y ^ z ↔ x ≤ y := (strict_mono_rpow_of_pos hz).le_iff_le lemma rpow_lt_rpow_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x ^ z < y ^ z ↔ x < y := (strict_mono_rpow_of_pos hz).lt_iff_lt lemma le_rpow_one_div_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x ≤ y ^ (1 / z) ↔ x ^ z ≤ y := begin nth_rewrite 0 ←rpow_one x, nth_rewrite 0 ←@_root_.mul_inv_cancel _ _ z hz.ne', rw [rpow_mul, ←one_div, @rpow_le_rpow_iff _ _ (1/z) (by simp [hz])], end lemma lt_rpow_one_div_iff {x y : ℝ≥0∞} {z : ℝ} (hz : 0 < z) : x < y ^ (1 / z) ↔ x ^ z < y := begin nth_rewrite 0 ←rpow_one x, nth_rewrite 0 ←@_root_.mul_inv_cancel _ _ z (ne_of_lt hz).symm, rw [rpow_mul, ←one_div, @rpow_lt_rpow_iff _ _ (1/z) (by simp [hz])], end lemma rpow_lt_rpow_of_exponent_lt {x : ℝ≥0∞} {y z : ℝ} (hx : 1 < x) (hx' : x ≠ ⊤) (hyz : y < z) : x^y < x^z := begin lift x to ℝ≥0 using hx', rw [one_lt_coe_iff] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_trans zero_lt_one hx)), nnreal.rpow_lt_rpow_of_exponent_lt hx hyz] end lemma rpow_le_rpow_of_exponent_le {x : ℝ≥0∞} {y z : ℝ} (hx : 1 ≤ x) (hyz : y ≤ z) : x^y ≤ x^z := begin cases x, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, top_rpow_of_neg, top_rpow_of_pos, le_refl]; linarith }, { simp only [one_le_coe_iff, some_eq_coe] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_of_lt_of_le zero_lt_one hx)), nnreal.rpow_le_rpow_of_exponent_le hx hyz] } end lemma rpow_lt_rpow_of_exponent_gt {x : ℝ≥0∞} {y z : ℝ} (hx0 : 0 < x) (hx1 : x < 1) (hyz : z < y) : x^y < x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx1 le_top), simp at hx0 hx1, simp [coe_rpow_of_ne_zero (ne_of_gt hx0), nnreal.rpow_lt_rpow_of_exponent_gt hx0 hx1 hyz] end lemma rpow_le_rpow_of_exponent_ge {x : ℝ≥0∞} {y z : ℝ} (hx1 : x ≤ 1) (hyz : z ≤ y) : x^y ≤ x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx1 coe_lt_top), by_cases h : x = 0, { rcases lt_trichotomy y 0 with Hy|Hy|Hy; rcases lt_trichotomy z 0 with Hz|Hz|Hz; simp [Hy, Hz, h, zero_rpow_of_neg, zero_rpow_of_pos, le_refl]; linarith }, { simp at hx1, simp [coe_rpow_of_ne_zero h, nnreal.rpow_le_rpow_of_exponent_ge (bot_lt_iff_ne_bot.mpr h) hx1 hyz] } end lemma rpow_le_self_of_le_one {x : ℝ≥0∞} {z : ℝ} (hx : x ≤ 1) (h_one_le : 1 ≤ z) : x ^ z ≤ x := begin nth_rewrite 1 ←ennreal.rpow_one x, exact ennreal.rpow_le_rpow_of_exponent_ge hx h_one_le, end lemma le_rpow_self_of_one_le {x : ℝ≥0∞} {z : ℝ} (hx : 1 ≤ x) (h_one_le : 1 ≤ z) : x ≤ x ^ z := begin nth_rewrite 0 ←ennreal.rpow_one x, exact ennreal.rpow_le_rpow_of_exponent_le hx h_one_le, end lemma rpow_pos_of_nonneg {p : ℝ} {x : ℝ≥0∞} (hx_pos : 0 < x) (hp_nonneg : 0 ≤ p) : 0 < x^p := begin by_cases hp_zero : p = 0, { simp [hp_zero, ennreal.zero_lt_one], }, { rw ←ne.def at hp_zero, have hp_pos := lt_of_le_of_ne hp_nonneg hp_zero.symm, rw ←zero_rpow_of_pos hp_pos, exact rpow_lt_rpow hx_pos hp_pos, }, end lemma rpow_pos {p : ℝ} {x : ℝ≥0∞} (hx_pos : 0 < x) (hx_ne_top : x ≠ ⊤) : 0 < x^p := begin cases lt_or_le 0 p with hp_pos hp_nonpos, { exact rpow_pos_of_nonneg hx_pos (le_of_lt hp_pos), }, { rw [←neg_neg p, rpow_neg, inv_pos], exact rpow_ne_top_of_nonneg (by simp [hp_nonpos]) hx_ne_top, }, end lemma rpow_lt_one {x : ℝ≥0∞} {z : ℝ} (hx : x < 1) (hz : 0 < z) : x^z < 1 := begin lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx le_top), simp only [coe_lt_one_iff] at hx, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.rpow_lt_one (zero_le x) hx hz], end lemma rpow_le_one {x : ℝ≥0∞} {z : ℝ} (hx : x ≤ 1) (hz : 0 ≤ z) : x^z ≤ 1 := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx coe_lt_top), simp only [coe_le_one_iff] at hx, simp [coe_rpow_of_nonneg _ hz, nnreal.rpow_le_one hx hz], end lemma rpow_lt_one_of_one_lt_of_neg {x : ℝ≥0∞} {z : ℝ} (hx : 1 < x) (hz : z < 0) : x^z < 1 := begin cases x, { simp [top_rpow_of_neg hz, ennreal.zero_lt_one] }, { simp only [some_eq_coe, one_lt_coe_iff] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_trans zero_lt_one hx)), nnreal.rpow_lt_one_of_one_lt_of_neg hx hz] }, end lemma rpow_le_one_of_one_le_of_neg {x : ℝ≥0∞} {z : ℝ} (hx : 1 ≤ x) (hz : z < 0) : x^z ≤ 1 := begin cases x, { simp [top_rpow_of_neg hz, ennreal.zero_lt_one] }, { simp only [one_le_coe_iff, some_eq_coe] at hx, simp [coe_rpow_of_ne_zero (ne_of_gt (lt_of_lt_of_le zero_lt_one hx)), nnreal.rpow_le_one_of_one_le_of_nonpos hx (le_of_lt hz)] }, end lemma one_lt_rpow {x : ℝ≥0∞} {z : ℝ} (hx : 1 < x) (hz : 0 < z) : 1 < x^z := begin cases x, { simp [top_rpow_of_pos hz] }, { simp only [some_eq_coe, one_lt_coe_iff] at hx, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.one_lt_rpow hx hz] } end lemma one_le_rpow {x : ℝ≥0∞} {z : ℝ} (hx : 1 ≤ x) (hz : 0 < z) : 1 ≤ x^z := begin cases x, { simp [top_rpow_of_pos hz] }, { simp only [one_le_coe_iff, some_eq_coe] at hx, simp [coe_rpow_of_nonneg _ (le_of_lt hz), nnreal.one_le_rpow hx (le_of_lt hz)] }, end lemma one_lt_rpow_of_pos_of_lt_one_of_neg {x : ℝ≥0∞} {z : ℝ} (hx1 : 0 < x) (hx2 : x < 1) (hz : z < 0) : 1 < x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_lt_of_le hx2 le_top), simp only [coe_lt_one_iff, coe_pos] at ⊢ hx1 hx2, simp [coe_rpow_of_ne_zero (ne_of_gt hx1), nnreal.one_lt_rpow_of_pos_of_lt_one_of_neg hx1 hx2 hz], end lemma one_le_rpow_of_pos_of_le_one_of_neg {x : ℝ≥0∞} {z : ℝ} (hx1 : 0 < x) (hx2 : x ≤ 1) (hz : z < 0) : 1 ≤ x^z := begin lift x to ℝ≥0 using ne_of_lt (lt_of_le_of_lt hx2 coe_lt_top), simp only [coe_le_one_iff, coe_pos] at ⊢ hx1 hx2, simp [coe_rpow_of_ne_zero (ne_of_gt hx1), nnreal.one_le_rpow_of_pos_of_le_one_of_nonpos hx1 hx2 (le_of_lt hz)], end lemma to_nnreal_rpow (x : ℝ≥0∞) (z : ℝ) : (x.to_nnreal) ^ z = (x ^ z).to_nnreal := begin rcases lt_trichotomy z 0 with H|H|H, { cases x, { simp [H, ne_of_lt] }, by_cases hx : x = 0, { simp [hx, H, ne_of_lt] }, { simp [coe_rpow_of_ne_zero hx] } }, { simp [H] }, { cases x, { simp [H, ne_of_gt] }, simp [coe_rpow_of_nonneg _ (le_of_lt H)] } end lemma to_real_rpow (x : ℝ≥0∞) (z : ℝ) : (x.to_real) ^ z = (x ^ z).to_real := by rw [ennreal.to_real, ennreal.to_real, ←nnreal.coe_rpow, ennreal.to_nnreal_rpow] lemma of_real_rpow_of_pos {x p : ℝ} (hx_pos : 0 < x) : ennreal.of_real x ^ p = ennreal.of_real (x ^ p) := begin simp_rw ennreal.of_real, rw [coe_rpow_of_ne_zero, coe_eq_coe, real.to_nnreal_rpow_of_nonneg hx_pos.le], simp [hx_pos], end lemma of_real_rpow_of_nonneg {x p : ℝ} (hx_nonneg : 0 ≤ x) (hp_nonneg : 0 ≤ p) : ennreal.of_real x ^ p = ennreal.of_real (x ^ p) := begin by_cases hp0 : p = 0, { simp [hp0], }, by_cases hx0 : x = 0, { rw ← ne.def at hp0, have hp_pos : 0 < p := lt_of_le_of_ne hp_nonneg hp0.symm, simp [hx0, hp_pos, hp_pos.ne.symm], }, rw ← ne.def at hx0, exact of_real_rpow_of_pos (hx_nonneg.lt_of_ne hx0.symm), end lemma rpow_left_injective {x : ℝ} (hx : x ≠ 0) : function.injective (λ y : ℝ≥0∞, y^x) := begin intros y z hyz, dsimp only at hyz, rw [←rpow_one y, ←rpow_one z, ←_root_.mul_inv_cancel hx, rpow_mul, rpow_mul, hyz], end lemma rpow_left_surjective {x : ℝ} (hx : x ≠ 0) : function.surjective (λ y : ℝ≥0∞, y^x) := λ y, ⟨y ^ x⁻¹, by simp_rw [←rpow_mul, _root_.inv_mul_cancel hx, rpow_one]⟩ lemma rpow_left_bijective {x : ℝ} (hx : x ≠ 0) : function.bijective (λ y : ℝ≥0∞, y^x) := ⟨rpow_left_injective hx, rpow_left_surjective hx⟩ theorem tendsto_rpow_at_top {y : ℝ} (hy : 0 < y) : tendsto (λ (x : ℝ≥0∞), x ^ y) (𝓝 ⊤) (𝓝 ⊤) := begin rw tendsto_nhds_top_iff_nnreal, intros x, obtain ⟨c, _, hc⟩ := (at_top_basis_Ioi.tendsto_iff at_top_basis_Ioi).mp (nnreal.tendsto_rpow_at_top hy) x trivial, have hc' : set.Ioi (↑c) ∈ 𝓝 (⊤ : ℝ≥0∞) := Ioi_mem_nhds coe_lt_top, refine eventually_of_mem hc' _, intros a ha, by_cases ha' : a = ⊤, { simp [ha', hy] }, lift a to ℝ≥0 using ha', change ↑c < ↑a at ha, rw coe_rpow_of_nonneg _ hy.le, exact_mod_cast hc a (by exact_mod_cast ha), end private lemma continuous_at_rpow_const_of_pos {x : ℝ≥0∞} {y : ℝ} (h : 0 < y) : continuous_at (λ a : ℝ≥0∞, a ^ y) x := begin by_cases hx : x = ⊤, { rw [hx, continuous_at], convert tendsto_rpow_at_top h, simp [h] }, lift x to ℝ≥0 using hx, rw continuous_at_coe_iff, convert continuous_coe.continuous_at.comp (nnreal.continuous_at_rpow_const (or.inr h.le)) using 1, ext1 x, simp [coe_rpow_of_nonneg _ h.le] end @[continuity] lemma continuous_rpow_const {y : ℝ} : continuous (λ a : ℝ≥0∞, a ^ y) := begin apply continuous_iff_continuous_at.2 (λ x, _), rcases lt_trichotomy 0 y with hy|rfl|hy, { exact continuous_at_rpow_const_of_pos hy }, { simp, exact continuous_at_const }, { obtain ⟨z, hz⟩ : ∃ z, y = -z := ⟨-y, (neg_neg _).symm⟩, have z_pos : 0 < z, by simpa [hz] using hy, simp_rw [hz, rpow_neg], exact ennreal.continuous_inv.continuous_at.comp (continuous_at_rpow_const_of_pos z_pos) } end lemma tendsto_const_mul_rpow_nhds_zero_of_pos {c : ℝ≥0∞} (hc : c ≠ ∞) {y : ℝ} (hy : 0 < y) : tendsto (λ x : ℝ≥0∞, c * x ^ y) (𝓝 0) (𝓝 0) := begin convert ennreal.tendsto.const_mul (ennreal.continuous_rpow_const.tendsto 0) _, { simp [hy] }, { exact or.inr hc } end end ennreal lemma filter.tendsto.ennrpow_const {α : Type*} {f : filter α} {m : α → ℝ≥0∞} {a : ℝ≥0∞} (r : ℝ) (hm : tendsto m f (𝓝 a)) : tendsto (λ x, (m x) ^ r) f (𝓝 (a ^ r)) := (ennreal.continuous_rpow_const.tendsto a).comp hm namespace norm_num open tactic theorem rpow_pos (a b : ℝ) (b' : ℕ) (c : ℝ) (hb : b = b') (h : a ^ b' = c) : a ^ b = c := by rw [← h, hb, real.rpow_nat_cast] theorem rpow_neg (a b : ℝ) (b' : ℕ) (c c' : ℝ) (a0 : 0 ≤ a) (hb : b = b') (h : a ^ b' = c) (hc : c⁻¹ = c') : a ^ -b = c' := by rw [← hc, ← h, hb, real.rpow_neg a0, real.rpow_nat_cast] /-- Evaluate `real.rpow a b` where `a` is a rational numeral and `b` is an integer. (This cannot go via the generalized version `prove_rpow'` because `rpow_pos` has a side condition; we do not attempt to evaluate `a ^ b` where `a` and `b` are both negative because it comes out to some garbage.) -/ meta def prove_rpow (a b : expr) : tactic (expr × expr) := do na ← a.to_rat, ic ← mk_instance_cache `(ℝ), match match_sign b with | sum.inl b := do (ic, a0) ← guard (na ≥ 0) >> prove_nonneg ic a, nc ← mk_instance_cache `(ℕ), (ic, nc, b', hb) ← prove_nat_uncast ic nc b, (ic, c, h) ← prove_pow a na ic b', cr ← c.to_rat, (ic, c', hc) ← prove_inv ic c cr, pure (c', (expr.const ``rpow_neg []).mk_app [a, b, b', c, c', a0, hb, h, hc]) | sum.inr ff := pure (`(1:ℝ), expr.const ``real.rpow_zero [] a) | sum.inr tt := do nc ← mk_instance_cache `(ℕ), (ic, nc, b', hb) ← prove_nat_uncast ic nc b, (ic, c, h) ← prove_pow a na ic b', pure (c, (expr.const ``rpow_pos []).mk_app [a, b, b', c, hb, h]) end /-- Generalized version of `prove_cpow`, `prove_nnrpow`, `prove_ennrpow`. -/ meta def prove_rpow' (pos neg zero : name) (α β one a b : expr) : tactic (expr × expr) := do na ← a.to_rat, icα ← mk_instance_cache α, icβ ← mk_instance_cache β, match match_sign b with | sum.inl b := do nc ← mk_instance_cache `(ℕ), (icβ, nc, b', hb) ← prove_nat_uncast icβ nc b, (icα, c, h) ← prove_pow a na icα b', cr ← c.to_rat, (icα, c', hc) ← prove_inv icα c cr, pure (c', (expr.const neg []).mk_app [a, b, b', c, c', hb, h, hc]) | sum.inr ff := pure (one, expr.const zero [] a) | sum.inr tt := do nc ← mk_instance_cache `(ℕ), (icβ, nc, b', hb) ← prove_nat_uncast icβ nc b, (icα, c, h) ← prove_pow a na icα b', pure (c, (expr.const pos []).mk_app [a, b, b', c, hb, h]) end open_locale nnreal ennreal theorem cpow_pos (a b : ℂ) (b' : ℕ) (c : ℂ) (hb : b = b') (h : a ^ b' = c) : a ^ b = c := by rw [← h, hb, complex.cpow_nat_cast] theorem cpow_neg (a b : ℂ) (b' : ℕ) (c c' : ℂ) (hb : b = b') (h : a ^ b' = c) (hc : c⁻¹ = c') : a ^ -b = c' := by rw [← hc, ← h, hb, complex.cpow_neg, complex.cpow_nat_cast] theorem nnrpow_pos (a : ℝ≥0) (b : ℝ) (b' : ℕ) (c : ℝ≥0) (hb : b = b') (h : a ^ b' = c) : a ^ b = c := by rw [← h, hb, nnreal.rpow_nat_cast] theorem nnrpow_neg (a : ℝ≥0) (b : ℝ) (b' : ℕ) (c c' : ℝ≥0) (hb : b = b') (h : a ^ b' = c) (hc : c⁻¹ = c') : a ^ -b = c' := by rw [← hc, ← h, hb, nnreal.rpow_neg, nnreal.rpow_nat_cast] theorem ennrpow_pos (a : ℝ≥0∞) (b : ℝ) (b' : ℕ) (c : ℝ≥0∞) (hb : b = b') (h : a ^ b' = c) : a ^ b = c := by rw [← h, hb, ennreal.rpow_nat_cast] theorem ennrpow_neg (a : ℝ≥0∞) (b : ℝ) (b' : ℕ) (c c' : ℝ≥0∞) (hb : b = b') (h : a ^ b' = c) (hc : c⁻¹ = c') : a ^ -b = c' := by rw [← hc, ← h, hb, ennreal.rpow_neg, ennreal.rpow_nat_cast] /-- Evaluate `complex.cpow a b` where `a` is a rational numeral and `b` is an integer. -/ meta def prove_cpow : expr → expr → tactic (expr × expr) := prove_rpow' ``cpow_pos ``cpow_neg ``complex.cpow_zero `(ℂ) `(ℂ) `(1:ℂ) /-- Evaluate `nnreal.rpow a b` where `a` is a rational numeral and `b` is an integer. -/ meta def prove_nnrpow : expr → expr → tactic (expr × expr) := prove_rpow' ``nnrpow_pos ``nnrpow_neg ``nnreal.rpow_zero `(ℝ≥0) `(ℝ) `(1:ℝ≥0) /-- Evaluate `ennreal.rpow a b` where `a` is a rational numeral and `b` is an integer. -/ meta def prove_ennrpow : expr → expr → tactic (expr × expr) := prove_rpow' ``ennrpow_pos ``ennrpow_neg ``ennreal.rpow_zero `(ℝ≥0∞) `(ℝ) `(1:ℝ≥0∞) /-- Evaluates expressions of the form `rpow a b`, `cpow a b` and `a ^ b` in the special case where `b` is an integer and `a` is a positive rational (so it's really just a rational power). -/ @[norm_num] meta def eval_rpow_cpow : expr → tactic (expr × expr) | `(@has_pow.pow _ _ real.has_pow %%a %%b) := b.to_int >> prove_rpow a b | `(real.rpow %%a %%b) := b.to_int >> prove_rpow a b | `(@has_pow.pow _ _ complex.has_pow %%a %%b) := b.to_int >> prove_cpow a b | `(complex.cpow %%a %%b) := b.to_int >> prove_cpow a b | `(@has_pow.pow _ _ nnreal.real.has_pow %%a %%b) := b.to_int >> prove_nnrpow a b | `(nnreal.rpow %%a %%b) := b.to_int >> prove_nnrpow a b | `(@has_pow.pow _ _ ennreal.real.has_pow %%a %%b) := b.to_int >> prove_ennrpow a b | `(ennreal.rpow %%a %%b) := b.to_int >> prove_ennrpow a b | _ := tactic.failed end norm_num
4d2cf6091910564107d666f5c77ef695f4f8faec
fa01e273a2a9f22530e6adb1ed7d4f54bb15c8d7
/src/N2O/Data/Sum.lean
72b192df1fd59499c2242f3df2ae73a9a200bef0
[ "LicenseRef-scancode-mit-taylor-variant", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
o89/n2o
4c99afb11fff0a1e3dae6b3bc8a3b7fc42c314ac
58c1fbf4ef892ed86bdc6b78ec9ca5a403715c2d
refs/heads/master
1,670,314,676,229
1,669,086,375,000
1,669,086,375,000
200,506,953
16
6
null
null
null
null
UTF-8
Lean
false
false
958
lean
namespace Sum def HasMap {γ α β : Type} : (α → β) → Sum γ α → Sum γ β | f, Sum.inr val => Sum.inr (f val) | _, Sum.inl er => Sum.inl er instance {α : Type} : Functor (Sum α) := { map := @HasMap α } def HasSeq {γ α β : Type} (a : Sum γ (α → β)) (b : Unit → Sum γ α) : Sum γ β := match a, b () with | Sum.inr f, Sum.inr x => Sum.inr (f x) | Sum.inl er, _ => Sum.inl er | _, Sum.inl er => Sum.inl er instance {α : Type} : Applicative (Sum α) := { pure := λ x => Sum.inr x, seq := @HasSeq α } def HasBind {α β γ : Type} : Sum α β → (β → Sum α γ) → Sum α γ | Sum.inr val, f => f val | Sum.inl er, _ => Sum.inl er instance {α : Type} : Monad (Sum α) := { pure := λ x => Sum.inr x, bind := @HasBind α } @[matchPattern] abbrev fail {α β : Type} : α → Sum α β := Sum.inl @[matchPattern] abbrev ok {α β : Type} : β → Sum α β := Sum.inr end Sum
db732553c547cd48353e6bbeb63e4d861e9ffdc9
a0e23cfdd129a671bf3154ee1a8a3a72bf4c7940
/src/Std/Data/BinomialHeap.lean
22596608ed543fbc0ba73fac3518465a4584e73f
[ "Apache-2.0" ]
permissive
WojciechKarpiel/lean4
7f89706b8e3c1f942b83a2c91a3a00b05da0e65b
f6e1314fa08293dea66a329e05b6c196a0189163
refs/heads/master
1,686,633,402,214
1,625,821,189,000
1,625,821,258,000
384,640,886
0
0
Apache-2.0
1,625,903,617,000
1,625,903,026,000
null
UTF-8
Lean
false
false
5,311
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 -/ namespace Std universe u namespace BinomialHeapImp structure HeapNodeAux (α : Type u) (h : Type u) where val : α rank : Nat children : List h inductive Heap (α : Type u) : Type u where | empty : Heap α | heap (ns : List (HeapNodeAux α (Heap α))) : Heap α deriving Inhabited abbrev HeapNode (α) := HeapNodeAux α (Heap α) variable {α : Type u} def hRank : List (HeapNode α) → Nat | [] => 0 | h::_ => h.rank def isEmpty : Heap α → Bool | Heap.empty => true | _ => false def singleton (a : α) : Heap α := Heap.heap [{ val := a, rank := 1, children := [] }] @[specialize] def combine (lt : α → α → Bool) (n₁ n₂ : HeapNode α) : HeapNode α := if lt n₂.val n₁.val then { n₂ with rank := n₂.rank + 1, children := n₂.children ++ [Heap.heap [n₁]] } else { n₁ with rank := n₁.rank + 1, children := n₁.children ++ [Heap.heap [n₂]] } @[specialize] partial def mergeNodes (lt : α → α → Bool) : List (HeapNode α) → List (HeapNode α) → List (HeapNode α) | [], h => h | h, [] => h | f@(h₁ :: t₁), s@(h₂ :: t₂) => if h₁.rank < h₂.rank then h₁ :: mergeNodes lt t₁ s else if h₂.rank < h₁.rank then h₂ :: mergeNodes lt t₂ f else let merged := combine lt h₁ h₂; let r := merged.rank; if r != hRank t₁ then if r != hRank t₂ then merged :: mergeNodes lt t₁ t₂ else mergeNodes lt (merged :: t₁) t₂ else if r != hRank t₂ then mergeNodes lt t₁ (merged :: t₂) else merged :: mergeNodes lt t₁ t₂ @[specialize] def merge (lt : α → α → Bool) : Heap α → Heap α → Heap α | Heap.empty, h => h | h, Heap.empty => h | Heap.heap h₁, Heap.heap h₂ => Heap.heap (mergeNodes lt h₁ h₂) @[specialize] def head? (lt : α → α → Bool) : Heap α → Option α | Heap.empty => none | Heap.heap h => h.foldl (init := none) fun r n => match r with | none => some n.val | some v => if lt v n.val then v else some n.val /- O(log n) -/ @[specialize] def head [Inhabited α] (lt : α → α → Bool) : Heap α → α | Heap.empty => arbitrary | Heap.heap [] => arbitrary | Heap.heap (h::hs) => hs.foldl (init := h.val) fun r n => if lt r n.val then r else n.val @[specialize] def findMin (lt : α → α → Bool) : List (HeapNode α) → Nat → HeapNode α × Nat → HeapNode α × Nat | [], _, r => r | h::hs, idx, (h', idx') => if lt h.val h'.val then findMin lt hs (idx+1) (h, idx) else findMin lt hs (idx+1) (h', idx') def tail (lt : α → α → Bool) : Heap α → Heap α | Heap.empty => Heap.empty | Heap.heap [] => Heap.empty | Heap.heap [h] => match h.children with | [] => Heap.empty | (h::hs) => hs.foldl (merge lt) h | Heap.heap hhs@(h::hs) => let (min, minIdx) := findMin lt hs 1 (h, 0); let rest := hhs.eraseIdx minIdx; min.children.foldl (merge lt) (Heap.heap rest) partial def toList (lt : α → α → Bool) : Heap α → List α | Heap.empty => [] | h => match head? lt h with | none => [] | some a => a :: toList lt (tail lt h) inductive WellFormed (lt : α → α → Bool) : Heap α → Prop where | emptyWff : WellFormed lt Heap.empty | singletonWff (a : α) : WellFormed lt (singleton a) | mergeWff (h₁ h₂ : Heap α) : WellFormed lt h₁ → WellFormed lt h₂ → WellFormed lt (merge lt h₁ h₂) | tailWff (h : Heap α) : WellFormed lt h → WellFormed lt (tail lt h) end BinomialHeapImp open BinomialHeapImp def BinomialHeap (α : Type u) (lt : α → α → Bool) := { h : Heap α // WellFormed lt h } @[inline] def mkBinomialHeap (α : Type u) (lt : α → α → Bool) : BinomialHeap α lt := ⟨Heap.empty, WellFormed.emptyWff⟩ namespace BinomialHeap variable {α : Type u} {lt : α → α → Bool} @[inline] def empty : BinomialHeap α lt := mkBinomialHeap α lt @[inline] def isEmpty : BinomialHeap α lt → Bool | ⟨b, _⟩ => BinomialHeapImp.isEmpty b /- O(1) -/ @[inline] def singleton (a : α) : BinomialHeap α lt := ⟨BinomialHeapImp.singleton a, WellFormed.singletonWff a⟩ /- O(log n) -/ @[inline] def merge : BinomialHeap α lt → BinomialHeap α lt → BinomialHeap α lt | ⟨b₁, h₁⟩, ⟨b₂, h₂⟩ => ⟨BinomialHeapImp.merge lt b₁ b₂, WellFormed.mergeWff b₁ b₂ h₁ h₂⟩ /- O(log n) -/ @[inline] def head [Inhabited α] : BinomialHeap α lt → α | ⟨b, _⟩ => BinomialHeapImp.head lt b /- O(log n) -/ @[inline] def head? : BinomialHeap α lt → Option α | ⟨b, _⟩ => BinomialHeapImp.head? lt b /- O(log n) -/ @[inline] def tail : BinomialHeap α lt → BinomialHeap α lt | ⟨b, h⟩ => ⟨BinomialHeapImp.tail lt b, WellFormed.tailWff b h⟩ /- O(log n) -/ @[inline] def insert (a : α) (h : BinomialHeap α lt) : BinomialHeap α lt := merge (singleton a) h /- O(n log n) -/ @[inline] def toList : BinomialHeap α lt → List α | ⟨b, _⟩ => BinomialHeapImp.toList lt b end BinomialHeap end Std
73060e72a379a7c97248d9a8050886d4fa3b67d2
4727251e0cd73359b15b664c3170e5d754078599
/src/control/fold.lean
efb64c4d35c80ccbd73b2af8457177abcacef40c
[ "Apache-2.0" ]
permissive
Vierkantor/mathlib
0ea59ac32a3a43c93c44d70f441c4ee810ccceca
83bc3b9ce9b13910b57bda6b56222495ebd31c2f
refs/heads/master
1,658,323,012,449
1,652,256,003,000
1,652,256,003,000
209,296,341
0
1
Apache-2.0
1,568,807,655,000
1,568,807,655,000
null
UTF-8
Lean
false
false
14,219
lean
/- Copyright (c) 2018 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Simon Hudon, Sean Leather -/ import algebra.free_monoid import algebra.opposites import control.traversable.instances import control.traversable.lemmas import category_theory.endomorphism import category_theory.types import category_theory.category.Kleisli /-! # List folds generalized to `traversable` Informally, we can think of `foldl` as a special case of `traverse` where we do not care about the reconstructed data structure and, in a state monad, we care about the final state. The obvious way to define `foldl` would be to use the state monad but it is nicer to reason about a more abstract interface with `fold_map` as a primitive and `fold_map_hom` as a defining property. ``` def fold_map {α ω} [has_one ω] [has_mul ω] (f : α → ω) : t α → ω := ... lemma fold_map_hom (α β) [monoid α] [monoid β] (f : α →* β) (g : γ → α) (x : t γ) : f (fold_map g x) = fold_map (f ∘ g) x := ... ``` `fold_map` uses a monoid ω to accumulate a value for every element of a data structure and `fold_map_hom` uses a monoid homomorphism to substitute the monoid used by `fold_map`. The two are sufficient to define `foldl`, `foldr` and `to_list`. `to_list` permits the formulation of specifications in terms of operations on lists. Each fold function can be defined using a specialized monoid. `to_list` uses a free monoid represented as a list with concatenation while `foldl` uses endofunctions together with function composition. The definition through monoids uses `traverse` together with the applicative functor `const m` (where `m` is the monoid). As an implementation, `const` guarantees that no resource is spent on reconstructing the structure during traversal. A special class could be defined for `foldable`, similarly to Haskell, but the author cannot think of instances of `foldable` that are not also `traversable`. -/ universes u v open ulift category_theory mul_opposite namespace monoid variables {m : Type u → Type u} [monad m] variables {α β : Type u} /-- For a list, foldl f x [y₀,y₁] reduces as follows: ``` calc foldl f x [y₀,y₁] = foldl f (f x y₀) [y₁] : rfl ... = foldl f (f (f x y₀) y₁) [] : rfl ... = f (f x y₀) y₁ : rfl ``` with ``` f : α → β → α x : α [y₀,y₁] : list β ``` We can view the above as a composition of functions: ``` ... = f (f x y₀) y₁ : rfl ... = flip f y₁ (flip f y₀ x) : rfl ... = (flip f y₁ ∘ flip f y₀) x : rfl ``` We can use traverse and const to construct this composition: ``` calc const.run (traverse (λ y, const.mk' (flip f y)) [y₀,y₁]) x = const.run ((::) <$> const.mk' (flip f y₀) <*> traverse (λ y, const.mk' (flip f y)) [y₁]) x ... = const.run ((::) <$> const.mk' (flip f y₀) <*> ( (::) <$> const.mk' (flip f y₁) <*> traverse (λ y, const.mk' (flip f y)) [] )) x ... = const.run ((::) <$> const.mk' (flip f y₀) <*> ( (::) <$> const.mk' (flip f y₁) <*> pure [] )) x ... = const.run ( ((::) <$> const.mk' (flip f y₁) <*> pure []) ∘ ((::) <$> const.mk' (flip f y₀)) ) x ... = const.run ( const.mk' (flip f y₁) ∘ const.mk' (flip f y₀) ) x ... = const.run ( flip f y₁ ∘ flip f y₀ ) x ... = f (f x y₀) y₁ ``` And this is how `const` turns a monoid into an applicative functor and how the monoid of endofunctions define `foldl`. -/ @[reducible] def foldl (α : Type u) : Type u := (End α)ᵐᵒᵖ def foldl.mk (f : α → α) : foldl α := op f def foldl.get (x : foldl α) : α → α := unop x @[simps] def foldl.of_free_monoid (f : β → α → β) : free_monoid α →* monoid.foldl β := { to_fun := λ xs, op $ flip (list.foldl f) xs, map_one' := rfl, map_mul' := by intros; simp only [free_monoid.mul_def, flip, unop_op, list.foldl_append, op_inj]; refl } @[reducible] def foldr (α : Type u) : Type u := End α def foldr.mk (f : α → α) : foldr α := f def foldr.get (x : foldr α) : α → α := x @[simps] def foldr.of_free_monoid (f : α → β → β) : free_monoid α →* monoid.foldr β := { to_fun := λ xs, flip (list.foldr f) xs, map_one' := rfl, map_mul' := begin intros, simp only [free_monoid.mul_def, list.foldr_append, flip], refl end } @[reducible] def mfoldl (m : Type u → Type u) [monad m] (α : Type u) : Type u := mul_opposite $ End $ Kleisli.mk m α def mfoldl.mk (f : α → m α) : mfoldl m α := op f def mfoldl.get (x : mfoldl m α) : α → m α := unop x @[simps] def mfoldl.of_free_monoid [is_lawful_monad m] (f : β → α → m β) : free_monoid α →* monoid.mfoldl m β := { to_fun := λ xs, op $ flip (list.mfoldl f) xs, map_one' := rfl, map_mul' := by intros; apply unop_injective; ext; apply list.mfoldl_append } @[reducible] def mfoldr (m : Type u → Type u) [monad m] (α : Type u) : Type u := End $ Kleisli.mk m α def mfoldr.mk (f : α → m α) : mfoldr m α := f def mfoldr.get (x : mfoldr m α) : α → m α := x @[simps] def mfoldr.of_free_monoid [is_lawful_monad m] (f : α → β → m β) : free_monoid α →* monoid.mfoldr m β := { to_fun := λ xs, flip (list.mfoldr f) xs, map_one' := rfl, map_mul' := by intros; ext; apply list.mfoldr_append } end monoid namespace traversable open monoid functor section defs variables {α β : Type u} {t : Type u → Type u} [traversable t] def fold_map {α ω} [has_one ω] [has_mul ω] (f : α → ω) : t α → ω := traverse (const.mk' ∘ f) def foldl (f : α → β → α) (x : α) (xs : t β) : α := (fold_map (foldl.mk ∘ flip f) xs).get x def foldr (f : α → β → β) (x : β) (xs : t α) : β := (fold_map (foldr.mk ∘ f) xs).get x /-- Conceptually, `to_list` collects all the elements of a collection in a list. This idea is formalized by `lemma to_list_spec (x : t α) : to_list x = fold_map free_monoid.mk x`. The definition of `to_list` is based on `foldl` and `list.cons` for speed. It is faster than using `fold_map free_monoid.mk` because, by using `foldl` and `list.cons`, each insertion is done in constant time. As a consequence, `to_list` performs in linear. On the other hand, `fold_map free_monoid.mk` creates a singleton list around each element and concatenates all the resulting lists. In `xs ++ ys`, concatenation takes a time proportional to `length xs`. Since the order in which concatenation is evaluated is unspecified, nothing prevents each element of the traversable to be appended at the end `xs ++ [x]` which would yield a `O(n²)` run time. -/ def to_list : t α → list α := list.reverse ∘ foldl (flip list.cons) [] def length (xs : t α) : ℕ := down $ foldl (λ l _, up $ l.down + 1) (up 0) xs variables {m : Type u → Type u} [monad m] def mfoldl (f : α → β → m α) (x : α) (xs : t β) : m α := (fold_map (mfoldl.mk ∘ flip f) xs).get x def mfoldr (f : α → β → m β) (x : β) (xs : t α) : m β := (fold_map (mfoldr.mk ∘ f) xs).get x end defs section applicative_transformation variables {α β γ : Type u} open function (hiding const) def map_fold [monoid α] [monoid β] (f : α →* β) : applicative_transformation (const α) (const β) := { app := λ x, f, preserves_seq' := by { intros, simp only [f.map_mul, (<*>)], }, preserves_pure' := by { intros, simp only [f.map_one, pure] } } def free.mk : α → free_monoid α := list.ret def free.map (f : α → β) : free_monoid α →* free_monoid β := { to_fun := list.map f, map_mul' := λ x y, by simp only [free_monoid.mul_def, list.map_append, free_add_monoid.add_def], map_one' := by simp only [free_monoid.one_def, list.map, free_add_monoid.zero_def] } lemma free.map_eq_map (f : α → β) (xs : list α) : f <$> xs = free.map f xs := rfl lemma foldl.unop_of_free_monoid (f : β → α → β) (xs : free_monoid α) (a : β) : unop (foldl.of_free_monoid f xs) a = list.foldl f a xs := rfl variables (m : Type u → Type u) [monad m] [is_lawful_monad m] variables {t : Type u → Type u} [traversable t] [is_lawful_traversable t] open is_lawful_traversable lemma fold_map_hom [monoid α] [monoid β] (f : α →* β) (g : γ → α) (x : t γ) : f (fold_map g x) = fold_map (f ∘ g) x := calc f (fold_map g x) = f (traverse (const.mk' ∘ g) x) : rfl ... = (map_fold f).app _ (traverse (const.mk' ∘ g) x) : rfl ... = traverse ((map_fold f).app _ ∘ (const.mk' ∘ g)) x : naturality (map_fold f) _ _ ... = fold_map (f ∘ g) x : rfl lemma fold_map_hom_free [monoid β] (f : free_monoid α →* β) (x : t α) : f (fold_map free.mk x) = fold_map (f ∘ free.mk) x := fold_map_hom f _ x variable {m} lemma fold_mfoldl_cons (f : α → β → m α) (x : β) (y : α) : list.mfoldl f y (free.mk x) = f y x := by simp only [free.mk, list.ret, list.mfoldl, bind_pure] lemma fold_mfoldr_cons (f : β → α → m α) (x : β) (y : α) : list.mfoldr f y (free.mk x) = f x y := by simp only [free.mk, list.ret, list.mfoldr, pure_bind] end applicative_transformation section equalities open is_lawful_traversable list (cons) variables {α β γ : Type u} variables {t : Type u → Type u} [traversable t] [is_lawful_traversable t] @[simp] lemma foldl.of_free_monoid_comp_free_mk (f : α → β → α) : foldl.of_free_monoid f ∘ free.mk = foldl.mk ∘ flip f := rfl @[simp] lemma foldr.of_free_monoid_comp_free_mk (f : β → α → α) : foldr.of_free_monoid f ∘ free.mk = foldr.mk ∘ f := rfl @[simp] lemma mfoldl.of_free_monoid_comp_free_mk {m} [monad m] [is_lawful_monad m] (f : α → β → m α) : mfoldl.of_free_monoid f ∘ free.mk = mfoldl.mk ∘ flip f := by ext; simp [(∘), mfoldl.of_free_monoid, mfoldl.mk, flip, fold_mfoldl_cons]; refl @[simp] lemma mfoldr.of_free_monoid_comp_free_mk {m} [monad m] [is_lawful_monad m] (f : β → α → m α) : mfoldr.of_free_monoid f ∘ free.mk = mfoldr.mk ∘ f := by { ext, simp [(∘), mfoldr.of_free_monoid, mfoldr.mk, flip, fold_mfoldr_cons] } lemma to_list_spec (xs : t α) : to_list xs = (fold_map free.mk xs : free_monoid _) := eq.symm $ calc fold_map free.mk xs = (fold_map free.mk xs).reverse.reverse : by simp only [list.reverse_reverse] ... = (list.foldr cons [] (fold_map free.mk xs).reverse).reverse : by simp only [list.foldr_eta] ... = (unop (foldl.of_free_monoid (flip cons) (fold_map free.mk xs)) []).reverse : by simp [flip,list.foldr_reverse,foldl.of_free_monoid, unop_op] ... = to_list xs : begin rw fold_map_hom_free (foldl.of_free_monoid (flip $ @cons α)), simp only [to_list, foldl, list.reverse_inj, foldl.get, foldl.of_free_monoid_comp_free_mk], all_goals { apply_instance } end lemma fold_map_map [monoid γ] (f : α → β) (g : β → γ) (xs : t α) : fold_map g (f <$> xs) = fold_map (g ∘ f) xs := by simp only [fold_map,traverse_map] lemma foldl_to_list (f : α → β → α) (xs : t β) (x : α) : foldl f x xs = list.foldl f x (to_list xs) := begin rw ← foldl.unop_of_free_monoid, simp only [foldl, to_list_spec, fold_map_hom_free, foldl.of_free_monoid_comp_free_mk, foldl.get] end lemma foldr_to_list (f : α → β → β) (xs : t α) (x : β) : foldr f x xs = list.foldr f x (to_list xs) := begin change _ = foldr.of_free_monoid _ _ _, simp only [foldr, to_list_spec, fold_map_hom_free, foldr.of_free_monoid_comp_free_mk, foldr.get] end lemma to_list_map (f : α → β) (xs : t α) : to_list (f <$> xs) = f <$> to_list xs := by { simp only [to_list_spec,free.map_eq_map,fold_map_hom (free.map f), fold_map_map]; refl } @[simp] theorem foldl_map (g : β → γ) (f : α → γ → α) (a : α) (l : t β) : foldl f a (g <$> l) = foldl (λ x y, f x (g y)) a l := by simp only [foldl, fold_map_map, (∘), flip] @[simp] theorem foldr_map (g : β → γ) (f : γ → α → α) (a : α) (l : t β) : foldr f a (g <$> l) = foldr (f ∘ g) a l := by simp only [foldr, fold_map_map, (∘), flip] @[simp] theorem to_list_eq_self {xs : list α} : to_list xs = xs := begin simp only [to_list_spec, fold_map, traverse], induction xs, case list.nil { refl }, case list.cons : _ _ ih { unfold list.traverse list.ret, rw ih, refl } end theorem length_to_list {xs : t α} : length xs = list.length (to_list xs) := begin unfold length, rw foldl_to_list, generalize : to_list xs = ys, let f := λ (n : ℕ) (a : α), n + 1, transitivity list.foldl f 0 ys, { generalize : 0 = n, induction ys with _ _ ih generalizing n, { simp only [list.foldl_nil] }, { simp only [list.foldl, ih (n+1)] } }, { induction ys with _ tl ih, { simp only [list.length, list.foldl_nil] }, { simp only [list.foldl, list.length], rw [← ih], exact tl.foldl_hom (λx, x+1) f f 0 (λ n x, rfl) } } end variables {m : Type u → Type u} [monad m] [is_lawful_monad m] lemma mfoldl_to_list {f : α → β → m α} {x : α} {xs : t β} : mfoldl f x xs = list.mfoldl f x (to_list xs) := calc mfoldl f x xs = unop (mfoldl.of_free_monoid f (to_list xs)) x : by simp only [mfoldl, to_list_spec, fold_map_hom_free (mfoldl.of_free_monoid f), mfoldl.of_free_monoid_comp_free_mk, mfoldl.get] ... = list.mfoldl f x (to_list xs) : by simp [mfoldl.of_free_monoid, unop_op, flip] lemma mfoldr_to_list (f : α → β → m β) (x : β) (xs : t α) : mfoldr f x xs = list.mfoldr f x (to_list xs) := begin change _ = mfoldr.of_free_monoid f (to_list xs) x, simp only [mfoldr, to_list_spec, fold_map_hom_free (mfoldr.of_free_monoid f), mfoldr.of_free_monoid_comp_free_mk, mfoldr.get] end @[simp] theorem mfoldl_map (g : β → γ) (f : α → γ → m α) (a : α) (l : t β) : mfoldl f a (g <$> l) = mfoldl (λ x y, f x (g y)) a l := by simp only [mfoldl, fold_map_map, (∘), flip] @[simp] theorem mfoldr_map (g : β → γ) (f : γ → α → m α) (a : α) (l : t β) : mfoldr f a (g <$> l) = mfoldr (f ∘ g) a l := by simp only [mfoldr, fold_map_map, (∘), flip] end equalities end traversable
ee232b298321fbeaa5e05a7b75bfcda81bfa2cc2
d642a6b1261b2cbe691e53561ac777b924751b63
/src/category_theory/types.lean
dcd960ea5d59ced70f74e239d66e6417332211eb
[ "Apache-2.0" ]
permissive
cipher1024/mathlib
fee56b9954e969721715e45fea8bcb95f9dc03fe
d077887141000fefa5a264e30fa57520e9f03522
refs/heads/master
1,651,806,490,504
1,573,508,694,000
1,573,508,694,000
107,216,176
0
0
Apache-2.0
1,647,363,136,000
1,508,213,014,000
Lean
UTF-8
Lean
false
false
5,320
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 -/ import category_theory.functor_category import category_theory.fully_faithful import data.equiv.basic namespace category_theory universes v v' w u u' -- declare the `v`'s first; see `category_theory.category` for an explanation instance types : large_category (Type u) := { hom := λ a b, (a → b), id := λ a, id, comp := λ _ _ _ f g, g ∘ f } @[simp] lemma types_hom {α β : Type u} : (α ⟶ β) = (α → β) := rfl @[simp] lemma types_id (X : Type u) : 𝟙 X = id := rfl @[simp] lemma types_comp {X Y Z : Type u} (f : X ⟶ Y) (g : Y ⟶ Z) : f ≫ g = g ∘ f := rfl namespace functor variables {J : Type u} [𝒥 : category.{v} J] include 𝒥 def sections (F : J ⥤ Type w) : set (Π j, F.obj j) := { u | ∀ {j j'} (f : j ⟶ j'), F.map f (u j) = u j'} end functor namespace functor_to_types variables {C : Type u} [𝒞 : category.{v} C] (F G H : C ⥤ Type w) {X Y Z : C} include 𝒞 variables (σ : F ⟶ G) (τ : G ⟶ H) @[simp] lemma map_comp (f : X ⟶ Y) (g : Y ⟶ Z) (a : F.obj X) : (F.map (f ≫ g)) a = (F.map g) ((F.map f) a) := by simp @[simp] lemma map_id (a : F.obj X) : (F.map (𝟙 X)) a = a := by simp lemma naturality (f : X ⟶ Y) (x : F.obj X) : σ.app Y ((F.map f) x) = (G.map f) (σ.app X x) := congr_fun (σ.naturality f) x @[simp] lemma comp (x : F.obj X) : (σ ≫ τ).app X x = τ.app X (σ.app X x) := rfl variables {D : Type u'} [𝒟 : category.{u'} D] (I J : D ⥤ C) (ρ : I ⟶ J) {W : D} @[simp] lemma hcomp (x : (I ⋙ F).obj W) : (ρ ◫ σ).app W x = (G.map (ρ.app W)) (σ.app (I.obj W) x) := rfl end functor_to_types def ulift_trivial (V : Type u) : ulift.{u} V ≅ V := by tidy def ulift_functor : Type u ⥤ Type (max u v) := { obj := λ X, ulift.{v} X, map := λ X Y f, λ x : ulift.{v} X, ulift.up (f x.down) } @[simp] lemma ulift_functor_map {X Y : Type u} (f : X ⟶ Y) (x : ulift.{v} X) : ulift_functor.map f x = ulift.up (f x.down) := rfl instance ulift_functor_full : full ulift_functor := { preimage := λ X Y f x, (f (ulift.up x)).down } instance ulift_functor_faithful : faithful ulift_functor := { injectivity' := λ X Y f g p, funext $ λ x, congr_arg ulift.down ((congr_fun p (ulift.up x)) : ((ulift.up (f x)) = (ulift.up (g x)))) } def hom_of_element {X : Type u} (x : X) : punit ⟶ X := λ _, x lemma hom_of_element_eq_iff {X : Type u} (x y : X) : hom_of_element x = hom_of_element y ↔ x = y := ⟨λ H, congr_fun H punit.star, by cc⟩ lemma mono_iff_injective {X Y : Type u} (f : X ⟶ Y) : mono f ↔ function.injective f := begin split, { intros H x x' h, resetI, rw ←hom_of_element_eq_iff at ⊢ h, exact (cancel_mono f).mp h }, { refine λ H, ⟨λ Z g h H₂, _⟩, ext z, replace H₂ := congr_fun H₂ z, exact H H₂ } end lemma epi_iff_surjective {X Y : Type u} (f : X ⟶ Y) : epi f ↔ function.surjective f := begin split, { intros H, let g : Y ⟶ ulift Prop := λ y, ⟨true⟩, let h : Y ⟶ ulift Prop := λ y, ⟨∃ x, f x = y⟩, suffices : f ≫ g = f ≫ h, { resetI, rw cancel_epi at this, intro y, replace this := congr_fun this y, replace this : true = ∃ x, f x = y := congr_arg ulift.down this, rw ←this, trivial }, ext x, change true ↔ ∃ x', f x' = f x, rw true_iff, exact ⟨x, rfl⟩ }, { intro H, constructor, intros Z g h H₂, apply funext, rw ←forall_iff_forall_surj H, intro x, exact (congr_fun H₂ x : _) } end section /-- `of_type_functor m` converts from Lean's `Type`-based `category` to `category_theory`. This allows us to use these functors in category theory. -/ def of_type_functor (m : Type u → Type v) [_root_.functor m] [is_lawful_functor m] : Type u ⥤ Type v := { obj := m, map := λα β, _root_.functor.map, map_id' := assume α, _root_.functor.map_id, map_comp' := assume α β γ f g, funext $ assume a, is_lawful_functor.comp_map f g _ } variables (m : Type u → Type v) [_root_.functor m] [is_lawful_functor m] @[simp] lemma of_type_functor_obj : (of_type_functor m).obj = m := rfl @[simp] lemma of_type_functor_map {α β} (f : α → β) : (of_type_functor m).map f = (_root_.functor.map f : m α → m β) := rfl end end category_theory -- Isomorphisms in Type and equivalences. namespace equiv universe u variables {X Y : Type u} def to_iso (e : X ≃ Y) : X ≅ Y := { hom := e.to_fun, inv := e.inv_fun, hom_inv_id' := funext e.left_inv, inv_hom_id' := funext e.right_inv } @[simp] lemma to_iso_hom {e : X ≃ Y} : e.to_iso.hom = e := rfl @[simp] lemma to_iso_inv {e : X ≃ Y} : e.to_iso.inv = e.symm := rfl end equiv namespace category_theory.iso universe u variables {X Y : Type u} def to_equiv (i : X ≅ Y) : X ≃ Y := { to_fun := i.hom, inv_fun := i.inv, left_inv := λ x, congr_fun i.hom_inv_id x, right_inv := λ y, congr_fun i.inv_hom_id y } @[simp] lemma to_equiv_fun (i : X ≅ Y) : (i.to_equiv : X → Y) = i.hom := rfl @[simp] lemma to_equiv_symm_fun (i : X ≅ Y) : (i.to_equiv.symm : Y → X) = i.inv := rfl end category_theory.iso
c51f096488298a136f9f9256820400b950ad3211
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/algebra/lie/semisimple.lean
8bca7ecad99092933a4c3e8189f2d45c6c7b9c22
[ "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,433
lean
/- Copyright (c) 2021 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import algebra.lie.solvable /-! # Semisimple Lie algebras The famous Cartan-Dynkin-Killing classification of semisimple Lie algebras renders them one of the most important classes of Lie algebras. In this file we define simple and semisimple Lie algebras and prove some basic related results. ## Main definitions * `lie_module.is_irreducible` * `lie_algebra.is_simple` * `lie_algebra.is_semisimple` * `lie_algebra.is_semisimple_iff_no_solvable_ideals` * `lie_algebra.is_semisimple_iff_no_abelian_ideals` * `lie_algebra.abelian_radical_iff_solvable_is_abelian` ## Tags lie algebra, radical, simple, semisimple -/ universes u v w w₁ w₂ /-- A Lie module is irreducible if it is zero or its only non-trivial Lie submodule is itself. -/ class lie_module.is_irreducible (R : Type u) (L : Type v) (M : Type w) [comm_ring R] [lie_ring L] [lie_algebra R L] [add_comm_group M] [module R M] [lie_ring_module L M] [lie_module R L M] : Prop := (irreducible : ∀ (N : lie_submodule R L M), N ≠ ⊥ → N = ⊤) namespace lie_algebra variables (R : Type u) (L : Type v) variables [comm_ring R] [lie_ring L] [lie_algebra R L] set_option old_structure_cmd true /-- A Lie algebra is simple if it is irreducible as a Lie module over itself via the adjoint action, and it is non-Abelian. -/ class is_simple extends lie_module.is_irreducible R L L : Prop := (non_abelian : ¬is_lie_abelian L) /-- A semisimple Lie algebra is one with trivial radical. Note that the label 'semisimple' is apparently not universally agreed [upon](https://mathoverflow.net/questions/149391/on-radicals-of-a-lie-algebra#comment383669_149391) for general coefficients. We are following [Seligman, page 15](seligman1967) and using the label for the weakest of the various properties which are all equivalent over a field of characteristic zero. -/ class is_semisimple : Prop := (semisimple : radical R L = ⊥) lemma is_semisimple_iff_no_solvable_ideals : is_semisimple R L ↔ ∀ (I : lie_ideal R L), is_solvable R I → I = ⊥ := ⟨λ h, Sup_eq_bot.mp h.semisimple, λ h, ⟨Sup_eq_bot.mpr h⟩⟩ lemma is_semisimple_iff_no_abelian_ideals : is_semisimple R L ↔ ∀ (I : lie_ideal R L), is_lie_abelian I → I = ⊥ := begin rw is_semisimple_iff_no_solvable_ideals, split; intros h₁ I h₂, { haveI : is_lie_abelian I := h₂, apply h₁, exact lie_algebra.of_abelian_is_solvable R I, }, { haveI : is_solvable R I := h₂, rw ← abelian_of_solvable_ideal_eq_bot_iff, apply h₁, exact abelian_derived_abelian_of_ideal I, }, end @[simp] lemma center_eq_bot_of_semisimple [h : is_semisimple R L] : center R L = ⊥ := by { rw is_semisimple_iff_no_abelian_ideals at h, apply h, apply_instance, } /-- A simple Lie algebra is semisimple. -/ @[priority 100] instance is_semisimple_of_is_simple [h : is_simple R L] : is_semisimple R L := begin rw is_semisimple_iff_no_abelian_ideals, intros I hI, tactic.unfreeze_local_instances, obtain ⟨h₁, h₂⟩ := h, by_contradiction contra, rw [h₁ I contra, lie_abelian_iff_equiv_lie_abelian lie_ideal.top_equiv_self] at hI, exact h₂ hI, end -- TODO[gh-6025]: make this an instance once safe to do so lemma subsingleton_of_semisimple_lie_abelian [is_semisimple R L] [h : is_lie_abelian L] : subsingleton (lie_ideal R L) := begin apply subsingleton_of_bot_eq_top, rwa [is_lie_abelian_iff_center_eq_top R L, center_eq_bot_of_semisimple] at h, end lemma abelian_radical_of_semisimple [is_semisimple R L] : is_lie_abelian (radical R L) := by { rw is_semisimple.semisimple, exact is_lie_abelian_bot R L, } /-- The two properties shown to be equivalent here are possible definitions for a Lie algebra to be reductive. Note that there is absolutely [no agreement](https://mathoverflow.net/questions/284713/) on what the label 'reductive' should mean when the coefficients are not a field of characteristic zero. -/ lemma abelian_radical_iff_solvable_is_abelian [is_noetherian R L] : is_lie_abelian (radical R L) ↔ ∀ (I : lie_ideal R L), is_solvable R I → is_lie_abelian I := begin split, { rintros h₁ I h₂, rw lie_ideal.solvable_iff_le_radical at h₂, exact (lie_ideal.hom_of_le_injective h₂).is_lie_abelian h₁, }, { intros h, apply h, apply_instance, }, end end lie_algebra
ad686176c9d5eecf44d68c010c9414e368437849
137c667471a40116a7afd7261f030b30180468c2
/src/measure_theory/borel_space.lean
dea350c11fd77d55c6aae49169ce0606e1dccef4
[ "Apache-2.0" ]
permissive
bragadeesh153/mathlib
46bf814cfb1eecb34b5d1549b9117dc60f657792
b577bb2cd1f96eb47031878256856020b76f73cd
refs/heads/master
1,687,435,188,334
1,626,384,207,000
1,626,384,207,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
65,801
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Yury Kudryashov -/ import measure_theory.ae_measurable_sequence import analysis.complex.basic import analysis.normed_space.finite_dimension import topology.G_delta import measure_theory.arithmetic import topology.semicontinuous import topology.instances.ereal /-! # Borel (measurable) space ## Main definitions * `borel α` : the least `σ`-algebra that contains all open sets; * `class borel_space` : a space with `topological_space` and `measurable_space` structures such that `‹measurable_space α› = borel α`; * `class opens_measurable_space` : a space with `topological_space` and `measurable_space` structures such that all open sets are measurable; equivalently, `borel α ≤ ‹measurable_space α›`. * `borel_space` instances on `empty`, `unit`, `bool`, `nat`, `int`, `rat`; * `measurable` and `borel_space` instances on `ℝ`, `ℝ≥0`, `ℝ≥0∞`. ## Main statements * `is_open.measurable_set`, `is_closed.measurable_set`: open and closed sets are measurable; * `continuous.measurable` : a continuous function is measurable; * `continuous.measurable2` : if `f : α → β` and `g : α → γ` are measurable and `op : β × γ → δ` is continuous, then `λ x, op (f x, g y)` is measurable; * `measurable.add` etc : dot notation for arithmetic operations on `measurable` predicates, and similarly for `dist` and `edist`; * `ae_measurable.add` : similar dot notation for almost everywhere measurable functions; * `measurable.ennreal*` : special cases for arithmetic operations on `ℝ≥0∞`. -/ noncomputable theory open classical set filter measure_theory open_locale classical big_operators topological_space nnreal ennreal universes u v w x y variables {α β γ γ₂ δ : Type*} {ι : Sort y} {s t u : set α} open measurable_space topological_space /-- `measurable_space` structure generated by `topological_space`. -/ def borel (α : Type u) [topological_space α] : measurable_space α := generate_from {s : set α | is_open s} lemma borel_eq_top_of_discrete [topological_space α] [discrete_topology α] : borel α = ⊤ := top_le_iff.1 $ λ s hs, generate_measurable.basic s (is_open_discrete s) lemma borel_eq_top_of_encodable [topological_space α] [t1_space α] [encodable α] : borel α = ⊤ := begin refine (top_le_iff.1 $ λ s hs, bUnion_of_singleton s ▸ _), apply measurable_set.bUnion s.countable_encodable, intros x hx, apply measurable_set.of_compl, apply generate_measurable.basic, exact is_closed_singleton.is_open_compl end lemma borel_eq_generate_from_of_subbasis {s : set (set α)} [t : topological_space α] [second_countable_topology α] (hs : t = generate_from s) : borel α = generate_from s := le_antisymm (generate_from_le $ assume u (hu : t.is_open u), begin rw [hs] at hu, induction hu, case generate_open.basic : u hu { exact generate_measurable.basic u hu }, case generate_open.univ { exact @measurable_set.univ α (generate_from s) }, case generate_open.inter : s₁ s₂ _ _ hs₁ hs₂ { exact @measurable_set.inter α (generate_from s) _ _ hs₁ hs₂ }, case generate_open.sUnion : f hf ih { rcases is_open_sUnion_countable f (by rwa hs) with ⟨v, hv, vf, vu⟩, rw ← vu, exact @measurable_set.sUnion α (generate_from s) _ hv (λ x xv, ih _ (vf xv)) } end) (generate_from_le $ assume u hu, generate_measurable.basic _ $ show t.is_open u, by rw [hs]; exact generate_open.basic _ hu) lemma topological_space.is_topological_basis.borel_eq_generate_from [topological_space α] [second_countable_topology α] {s : set (set α)} (hs : is_topological_basis s) : borel α = generate_from s := borel_eq_generate_from_of_subbasis hs.eq_generate_from lemma is_pi_system_is_open [topological_space α] : is_pi_system (is_open : set α → Prop) := λ s t hs ht hst, is_open.inter hs ht lemma borel_eq_generate_from_is_closed [topological_space α] : borel α = generate_from {s | is_closed s} := le_antisymm (generate_from_le $ λ t ht, @measurable_set.of_compl α _ (generate_from {s | is_closed s}) (generate_measurable.basic _ $ is_closed_compl_iff.2 ht)) (generate_from_le $ λ t ht, @measurable_set.of_compl α _ (borel α) (generate_measurable.basic _ $ is_open_compl_iff.2 ht)) section order_topology variable (α) variables [topological_space α] [second_countable_topology α] [linear_order α] [order_topology α] lemma borel_eq_generate_Iio : borel α = generate_from (range Iio) := begin refine le_antisymm _ (generate_from_le _), { rw borel_eq_generate_from_of_subbasis (@order_topology.topology_eq_generate_intervals α _ _ _), letI : measurable_space α := measurable_space.generate_from (range Iio), have H : ∀ a : α, measurable_set (Iio a) := λ a, generate_measurable.basic _ ⟨_, rfl⟩, refine generate_from_le _, rintro _ ⟨a, rfl | rfl⟩; [skip, apply H], by_cases h : ∃ a', ∀ b, a < b ↔ a' ≤ b, { rcases h with ⟨a', ha'⟩, rw (_ : Ioi a = (Iio a')ᶜ), { exact (H _).compl }, simp [set.ext_iff, ha'] }, { rcases is_open_Union_countable (λ a' : {a' : α // a < a'}, {b | a'.1 < b}) (λ a', is_open_lt' _) with ⟨v, ⟨hv⟩, vu⟩, simp [set.ext_iff] at vu, have : Ioi a = ⋃ x : v, (Iio x.1.1)ᶜ, { simp [set.ext_iff], refine λ x, ⟨λ ax, _, λ ⟨a', ⟨h, av⟩, ax⟩, lt_of_lt_of_le h ax⟩, rcases (vu x).2 _ with ⟨a', h₁, h₂⟩, { exact ⟨a', h₁, le_of_lt h₂⟩ }, refine not_imp_comm.1 (λ h, _) h, exact ⟨x, λ b, ⟨λ ab, le_of_not_lt (λ h', h ⟨b, ab, h'⟩), lt_of_lt_of_le ax⟩⟩ }, rw this, resetI, apply measurable_set.Union, exact λ _, (H _).compl } }, { rw forall_range_iff, intro a, exact generate_measurable.basic _ is_open_Iio } end lemma borel_eq_generate_Ioi : borel α = generate_from (range Ioi) := @borel_eq_generate_Iio (order_dual α) _ (by apply_instance : second_countable_topology α) _ _ end order_topology lemma borel_comap {f : α → β} {t : topological_space β} : @borel α (t.induced f) = (@borel β t).comap f := comap_generate_from.symm lemma continuous.borel_measurable [topological_space α] [topological_space β] {f : α → β} (hf : continuous f) : @measurable α β (borel α) (borel β) f := measurable.of_le_map $ generate_from_le $ λ s hs, generate_measurable.basic (f ⁻¹' s) (hs.preimage hf) /-- A space with `measurable_space` and `topological_space` structures such that all open sets are measurable. -/ class opens_measurable_space (α : Type*) [topological_space α] [h : measurable_space α] : Prop := (borel_le : borel α ≤ h) /-- A space with `measurable_space` and `topological_space` structures such that the `σ`-algebra of measurable sets is exactly the `σ`-algebra generated by open sets. -/ class borel_space (α : Type*) [topological_space α] [measurable_space α] : Prop := (measurable_eq : ‹measurable_space α› = borel α) /-- In a `borel_space` all open sets are measurable. -/ @[priority 100] instance borel_space.opens_measurable {α : Type*} [topological_space α] [measurable_space α] [borel_space α] : opens_measurable_space α := ⟨ge_of_eq $ borel_space.measurable_eq⟩ instance subtype.borel_space {α : Type*} [topological_space α] [measurable_space α] [hα : borel_space α] (s : set α) : borel_space s := ⟨by { rw [hα.1, subtype.measurable_space, ← borel_comap], refl }⟩ instance subtype.opens_measurable_space {α : Type*} [topological_space α] [measurable_space α] [h : opens_measurable_space α] (s : set α) : opens_measurable_space s := ⟨by { rw [borel_comap], exact comap_mono h.1 }⟩ section variables [topological_space α] [measurable_space α] [opens_measurable_space α] [topological_space β] [measurable_space β] [opens_measurable_space β] [topological_space γ] [measurable_space γ] [borel_space γ] [topological_space γ₂] [measurable_space γ₂] [borel_space γ₂] [measurable_space δ] lemma is_open.measurable_set (h : is_open s) : measurable_set s := opens_measurable_space.borel_le _ $ generate_measurable.basic _ h @[measurability] lemma measurable_set_interior : measurable_set (interior s) := is_open_interior.measurable_set lemma is_Gδ.measurable_set (h : is_Gδ s) : measurable_set s := begin rcases h with ⟨S, hSo, hSc, rfl⟩, exact measurable_set.sInter hSc (λ t ht, (hSo t ht).measurable_set) end lemma measurable_set_of_continuous_at {β} [emetric_space β] (f : α → β) : measurable_set {x | continuous_at f x} := (is_Gδ_set_of_continuous_at f).measurable_set lemma is_closed.measurable_set (h : is_closed s) : measurable_set s := h.is_open_compl.measurable_set.of_compl lemma is_compact.measurable_set [t2_space α] (h : is_compact s) : measurable_set s := h.is_closed.measurable_set @[measurability] lemma measurable_set_closure : measurable_set (closure s) := is_closed_closure.measurable_set lemma measurable_of_is_open {f : δ → γ} (hf : ∀ s, is_open s → measurable_set (f ⁻¹' s)) : measurable f := by { rw [‹borel_space γ›.measurable_eq], exact measurable_generate_from hf } lemma measurable_of_is_closed {f : δ → γ} (hf : ∀ s, is_closed s → measurable_set (f ⁻¹' s)) : measurable f := begin apply measurable_of_is_open, intros s hs, rw [← measurable_set.compl_iff, ← preimage_compl], apply hf, rw [is_closed_compl_iff], exact hs end lemma measurable_of_is_closed' {f : δ → γ} (hf : ∀ s, is_closed s → s.nonempty → s ≠ univ → measurable_set (f ⁻¹' s)) : measurable f := begin apply measurable_of_is_closed, intros s hs, cases eq_empty_or_nonempty s with h1 h1, { simp [h1] }, by_cases h2 : s = univ, { simp [h2] }, exact hf s hs h1 h2 end instance nhds_is_measurably_generated (a : α) : (𝓝 a).is_measurably_generated := begin rw [nhds, infi_subtype'], refine @filter.infi_is_measurably_generated _ _ _ _ (λ i, _), exact i.2.2.measurable_set.principal_is_measurably_generated end /-- If `s` is a measurable set, then `𝓝[s] a` is a measurably generated filter for each `a`. This cannot be an `instance` because it depends on a non-instance `hs : measurable_set s`. -/ lemma measurable_set.nhds_within_is_measurably_generated {s : set α} (hs : measurable_set s) (a : α) : (𝓝[s] a).is_measurably_generated := by haveI := hs.principal_is_measurably_generated; exact filter.inf_is_measurably_generated _ _ @[priority 100] -- see Note [lower instance priority] instance opens_measurable_space.to_measurable_singleton_class [t1_space α] : measurable_singleton_class α := ⟨λ x, is_closed_singleton.measurable_set⟩ instance pi.opens_measurable_space {ι : Type*} {π : ι → Type*} [fintype ι] [t' : Π i, topological_space (π i)] [Π i, measurable_space (π i)] [∀ i, second_countable_topology (π i)] [∀ i, opens_measurable_space (π i)] : opens_measurable_space (Π i, π i) := begin constructor, have : Pi.topological_space = generate_from {t | ∃(s:Πa, set (π a)) (i : finset ι), (∀a∈i, s a ∈ countable_basis (π a)) ∧ t = pi ↑i s}, { rw [funext (λ a, @eq_generate_from_countable_basis (π a) _ _), pi_generate_from_eq] }, rw [borel_eq_generate_from_of_subbasis this], apply generate_from_le, rintros _ ⟨s, i, hi, rfl⟩, refine measurable_set.pi i.countable_to_set (λ a ha, is_open.measurable_set _), rw [eq_generate_from_countable_basis (π a)], exact generate_open.basic _ (hi a ha) end instance prod.opens_measurable_space [second_countable_topology α] [second_countable_topology β] : opens_measurable_space (α × β) := begin constructor, rw [((is_basis_countable_basis α).prod (is_basis_countable_basis β)).borel_eq_generate_from], apply generate_from_le, rintros _ ⟨u, v, hu, hv, rfl⟩, exact (is_open_of_mem_countable_basis hu).measurable_set.prod (is_open_of_mem_countable_basis hv).measurable_set end section preorder variables [preorder α] [order_closed_topology α] {a b : α} @[simp, measurability] lemma measurable_set_Ici : measurable_set (Ici a) := is_closed_Ici.measurable_set @[simp, measurability] lemma measurable_set_Iic : measurable_set (Iic a) := is_closed_Iic.measurable_set @[simp, measurability] lemma measurable_set_Icc : measurable_set (Icc a b) := is_closed_Icc.measurable_set instance nhds_within_Ici_is_measurably_generated : (𝓝[Ici b] a).is_measurably_generated := measurable_set_Ici.nhds_within_is_measurably_generated _ instance nhds_within_Iic_is_measurably_generated : (𝓝[Iic b] a).is_measurably_generated := measurable_set_Iic.nhds_within_is_measurably_generated _ instance at_top_is_measurably_generated : (filter.at_top : filter α).is_measurably_generated := @filter.infi_is_measurably_generated _ _ _ _ $ λ a, (measurable_set_Ici : measurable_set (Ici a)).principal_is_measurably_generated instance at_bot_is_measurably_generated : (filter.at_bot : filter α).is_measurably_generated := @filter.infi_is_measurably_generated _ _ _ _ $ λ a, (measurable_set_Iic : measurable_set (Iic a)).principal_is_measurably_generated end preorder section partial_order variables [partial_order α] [order_closed_topology α] [second_countable_topology α] {a b : α} @[measurability] lemma measurable_set_le' : measurable_set {p : α × α | p.1 ≤ p.2} := order_closed_topology.is_closed_le'.measurable_set @[measurability] lemma measurable_set_le {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable_set {a | f a ≤ g a} := hf.prod_mk hg measurable_set_le' end partial_order section linear_order variables [linear_order α] [order_closed_topology α] {a b : α} @[simp, measurability] lemma measurable_set_Iio : measurable_set (Iio a) := is_open_Iio.measurable_set @[simp, measurability] lemma measurable_set_Ioi : measurable_set (Ioi a) := is_open_Ioi.measurable_set @[simp, measurability] lemma measurable_set_Ioo : measurable_set (Ioo a b) := is_open_Ioo.measurable_set @[simp, measurability] lemma measurable_set_Ioc : measurable_set (Ioc a b) := measurable_set_Ioi.inter measurable_set_Iic @[simp, measurability] lemma measurable_set_Ico : measurable_set (Ico a b) := measurable_set_Ici.inter measurable_set_Iio instance nhds_within_Ioi_is_measurably_generated : (𝓝[Ioi b] a).is_measurably_generated := measurable_set_Ioi.nhds_within_is_measurably_generated _ instance nhds_within_Iio_is_measurably_generated : (𝓝[Iio b] a).is_measurably_generated := measurable_set_Iio.nhds_within_is_measurably_generated _ @[measurability] lemma measurable_set_lt' [second_countable_topology α] : measurable_set {p : α × α | p.1 < p.2} := (is_open_lt continuous_fst continuous_snd).measurable_set @[measurability] lemma measurable_set_lt [second_countable_topology α] {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable_set {a | f a < g a} := hf.prod_mk hg measurable_set_lt' lemma set.ord_connected.measurable_set (h : ord_connected s) : measurable_set s := begin let u := ⋃ (x ∈ s) (y ∈ s), Ioo x y, have huopen : is_open u := is_open_bUnion (λ x hx, is_open_bUnion (λ y hy, is_open_Ioo)), have humeas : measurable_set u := huopen.measurable_set, have hfinite : (s \ u).finite, { refine set.finite_of_forall_between_eq_endpoints (s \ u) (λ x hx y hy z hz hxy hyz, _), by_contra h, push_neg at h, exact hy.2 (mem_bUnion_iff.mpr ⟨x, hx.1, mem_bUnion_iff.mpr ⟨z, hz.1, lt_of_le_of_ne hxy h.1, lt_of_le_of_ne hyz h.2⟩⟩) }, have : u ⊆ s := bUnion_subset (λ x hx, bUnion_subset (λ y hy, Ioo_subset_Icc_self.trans (h.out hx hy))), rw ← union_diff_cancel this, exact humeas.union hfinite.measurable_set end lemma is_preconnected.measurable_set (h : is_preconnected s) : measurable_set s := h.ord_connected.measurable_set end linear_order section linear_order variables [linear_order α] [order_closed_topology α] @[measurability] lemma measurable_set_interval {a b : α} : measurable_set (interval a b) := measurable_set_Icc variables [second_countable_topology α] @[measurability] lemma measurable.max {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λ a, max (f a) (g a)) := hf.piecewise (measurable_set_le hg hf) hg @[measurability] lemma ae_measurable.max {f g : δ → α} {μ : measure δ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, max (f a) (g a)) μ := ⟨λ a, max (hf.mk f a) (hg.mk g a), hf.measurable_mk.max hg.measurable_mk, eventually_eq.comp₂ hf.ae_eq_mk _ hg.ae_eq_mk⟩ @[measurability] lemma measurable.min {f g : δ → α} (hf : measurable f) (hg : measurable g) : measurable (λ a, min (f a) (g a)) := hf.piecewise (measurable_set_le hf hg) hg @[measurability] lemma ae_measurable.min {f g : δ → α} {μ : measure δ} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, min (f a) (g a)) μ := ⟨λ a, min (hf.mk f a) (hg.mk g a), hf.measurable_mk.min hg.measurable_mk, eventually_eq.comp₂ hf.ae_eq_mk _ hg.ae_eq_mk⟩ end linear_order /-- A continuous function from an `opens_measurable_space` to a `borel_space` is measurable. -/ lemma continuous.measurable {f : α → γ} (hf : continuous f) : measurable f := hf.borel_measurable.mono opens_measurable_space.borel_le (le_of_eq $ borel_space.measurable_eq) /-- A continuous function from an `opens_measurable_space` to a `borel_space` is ae-measurable. -/ lemma continuous.ae_measurable {f : α → γ} (h : continuous f) (μ : measure α) : ae_measurable f μ := h.measurable.ae_measurable lemma closed_embedding.measurable {f : α → γ} (hf : closed_embedding f) : measurable f := hf.continuous.measurable @[priority 100, to_additive] instance has_continuous_mul.has_measurable_mul [has_mul γ] [has_continuous_mul γ] : has_measurable_mul γ := { measurable_const_mul := λ c, (continuous_const.mul continuous_id).measurable, measurable_mul_const := λ c, (continuous_id.mul continuous_const).measurable } @[priority 100] instance has_continuous_sub.has_measurable_sub [has_sub γ] [has_continuous_sub γ] : has_measurable_sub γ := { measurable_const_sub := λ c, (continuous_const.sub continuous_id).measurable, measurable_sub_const := λ c, (continuous_id.sub continuous_const).measurable } @[priority 100, to_additive] instance topological_group.has_measurable_inv [group γ] [topological_group γ] : has_measurable_inv γ := ⟨continuous_inv.measurable⟩ @[priority 100] instance has_continuous_smul.has_measurable_smul {M α} [topological_space M] [topological_space α] [measurable_space M] [measurable_space α] [opens_measurable_space M] [borel_space α] [has_scalar M α] [has_continuous_smul M α] : has_measurable_smul M α := ⟨λ c, (continuous_const.smul continuous_id).measurable, λ y, (continuous_id.smul continuous_const).measurable⟩ section homeomorph /-- A homeomorphism between two Borel spaces is a measurable equivalence.-/ def homeomorph.to_measurable_equiv (h : γ ≃ₜ γ₂) : γ ≃ᵐ γ₂ := { measurable_to_fun := h.continuous_to_fun.measurable, measurable_inv_fun := h.continuous_inv_fun.measurable, .. h } @[simp] lemma homeomorph.to_measurable_equiv_coe (h : γ ≃ₜ γ₂) : (h.to_measurable_equiv : γ → γ₂) = h := rfl @[simp] lemma homeomorph.to_measurable_equiv_symm_coe (h : γ ≃ₜ γ₂) : (h.to_measurable_equiv.symm : γ₂ → γ) = h.symm := rfl @[measurability] lemma homeomorph.measurable (h : α ≃ₜ γ) : measurable h := h.continuous.measurable end homeomorph lemma measurable_of_continuous_on_compl_singleton [t1_space α] {f : α → γ} (a : α) (hf : continuous_on f {a}ᶜ) : measurable f := measurable_of_measurable_on_compl_singleton a (continuous_on_iff_continuous_restrict.1 hf).measurable lemma continuous.measurable2 [second_countable_topology α] [second_countable_topology β] {f : δ → α} {g : δ → β} {c : α → β → γ} (h : continuous (λ p : α × β, c p.1 p.2)) (hf : measurable f) (hg : measurable g) : measurable (λ a, c (f a) (g a)) := h.measurable.comp (hf.prod_mk hg) lemma continuous.ae_measurable2 [second_countable_topology α] [second_countable_topology β] {f : δ → α} {g : δ → β} {c : α → β → γ} {μ : measure δ} (h : continuous (λ p : α × β, c p.1 p.2)) (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, c (f a) (g a)) μ := h.measurable.comp_ae_measurable (hf.prod_mk hg) @[priority 100] instance has_continuous_inv'.has_measurable_inv [group_with_zero γ] [t1_space γ] [has_continuous_inv' γ] : has_measurable_inv γ := ⟨measurable_of_continuous_on_compl_singleton 0 continuous_on_inv'⟩ @[priority 100, to_additive] instance has_continuous_mul.has_measurable_mul₂ [second_countable_topology γ] [has_mul γ] [has_continuous_mul γ] : has_measurable_mul₂ γ := ⟨continuous_mul.measurable⟩ @[priority 100] instance has_continuous_sub.has_measurable_sub₂ [second_countable_topology γ] [has_sub γ] [has_continuous_sub γ] : has_measurable_sub₂ γ := ⟨continuous_sub.measurable⟩ @[priority 100] instance has_continuous_smul.has_measurable_smul₂ {M α} [topological_space M] [second_countable_topology M] [measurable_space M] [opens_measurable_space M] [topological_space α] [second_countable_topology α] [measurable_space α] [borel_space α] [has_scalar M α] [has_continuous_smul M α] : has_measurable_smul₂ M α := ⟨continuous_smul.measurable⟩ end section borel_space variables [topological_space α] [measurable_space α] [borel_space α] [topological_space β] [measurable_space β] [borel_space β] [topological_space γ] [measurable_space γ] [borel_space γ] [measurable_space δ] lemma pi_le_borel_pi {ι : Type*} {π : ι → Type*} [Π i, topological_space (π i)] [Π i, measurable_space (π i)] [∀ i, borel_space (π i)] : measurable_space.pi ≤ borel (Π i, π i) := begin have : ‹Π i, measurable_space (π i)› = λ i, borel (π i) := funext (λ i, borel_space.measurable_eq), rw [this], exact supr_le (λ i, comap_le_iff_le_map.2 $ (continuous_apply i).borel_measurable) end lemma prod_le_borel_prod : prod.measurable_space ≤ borel (α × β) := begin rw [‹borel_space α›.measurable_eq, ‹borel_space β›.measurable_eq], refine sup_le _ _, { exact comap_le_iff_le_map.mpr continuous_fst.borel_measurable }, { exact comap_le_iff_le_map.mpr continuous_snd.borel_measurable } end instance pi.borel_space {ι : Type*} {π : ι → Type*} [fintype ι] [t' : Π i, topological_space (π i)] [Π i, measurable_space (π i)] [∀ i, second_countable_topology (π i)] [∀ i, borel_space (π i)] : borel_space (Π i, π i) := ⟨le_antisymm pi_le_borel_pi opens_measurable_space.borel_le⟩ instance prod.borel_space [second_countable_topology α] [second_countable_topology β] : borel_space (α × β) := ⟨le_antisymm prod_le_borel_prod opens_measurable_space.borel_le⟩ lemma closed_embedding.measurable_inv_fun [n : nonempty β] {g : β → γ} (hg : closed_embedding g) : measurable (function.inv_fun g) := begin refine measurable_of_is_closed (λ s hs, _), by_cases h : classical.choice n ∈ s, { rw preimage_inv_fun_of_mem hg.to_embedding.inj h, exact (hg.closed_iff_image_closed.mp hs).measurable_set.union hg.closed_range.measurable_set.compl }, { rw preimage_inv_fun_of_not_mem hg.to_embedding.inj h, exact (hg.closed_iff_image_closed.mp hs).measurable_set } end lemma measurable_comp_iff_of_closed_embedding {f : δ → β} (g : β → γ) (hg : closed_embedding g) : measurable (g ∘ f) ↔ measurable f := begin refine ⟨λ hf, _, λ hf, hg.measurable.comp hf⟩, apply measurable_of_is_closed, intros s hs, convert hf (hg.is_closed_map s hs).measurable_set, rw [@preimage_comp _ _ _ f g, preimage_image_eq _ hg.to_embedding.inj] end lemma ae_measurable_comp_iff_of_closed_embedding {f : δ → β} {μ : measure δ} (g : β → γ) (hg : closed_embedding g) : ae_measurable (g ∘ f) μ ↔ ae_measurable f μ := begin by_cases h : nonempty β, { resetI, refine ⟨λ hf, _, λ hf, hg.measurable.comp_ae_measurable hf⟩, convert hg.measurable_inv_fun.comp_ae_measurable hf, ext x, exact (function.left_inverse_inv_fun hg.to_embedding.inj (f x)).symm }, { have H : ¬ nonempty δ, by { contrapose! h, exact nonempty.map f h }, simp [(measurable_of_not_nonempty H (g ∘ f)).ae_measurable, (measurable_of_not_nonempty H f).ae_measurable] } end lemma ae_measurable_comp_right_iff_of_closed_embedding {g : α → β} {μ : measure α} {f : β → δ} (hg : closed_embedding g) : ae_measurable (f ∘ g) μ ↔ ae_measurable f (measure.map g μ) := begin refine ⟨λ h, _, λ h, h.comp_measurable hg.measurable⟩, by_cases hα : nonempty α, swap, { simp [measure.eq_zero_of_not_nonempty hα μ] }, resetI, refine ⟨(h.mk _) ∘ (function.inv_fun g), h.measurable_mk.comp hg.measurable_inv_fun, _⟩, have : μ = measure.map (function.inv_fun g) (measure.map g μ), by rw [measure.map_map hg.measurable_inv_fun hg.measurable, (function.left_inverse_inv_fun hg.to_embedding.inj).comp_eq_id, measure.map_id], rw this at h, filter_upwards [ae_of_ae_map hg.measurable_inv_fun h.ae_eq_mk, ae_map_mem_range g hg.closed_range.measurable_set μ], assume x hx₁ hx₂, convert hx₁, exact ((function.left_inverse_inv_fun hg.to_embedding.inj).right_inv_on_range hx₂).symm, end section linear_order variables [linear_order α] [order_topology α] [second_countable_topology α] lemma measurable_of_Iio {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Iio x)) : measurable f := begin convert measurable_generate_from _, exact borel_space.measurable_eq.trans (borel_eq_generate_Iio _), rintro _ ⟨x, rfl⟩, exact hf x end lemma upper_semicontinuous.measurable [topological_space δ] [opens_measurable_space δ] {f : δ → α} (hf : upper_semicontinuous f) : measurable f := measurable_of_Iio (λ y, (hf.is_open_preimage y).measurable_set) lemma measurable_of_Ioi {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Ioi x)) : measurable f := begin convert measurable_generate_from _, exact borel_space.measurable_eq.trans (borel_eq_generate_Ioi _), rintro _ ⟨x, rfl⟩, exact hf x end lemma lower_semicontinuous.measurable [topological_space δ] [opens_measurable_space δ] {f : δ → α} (hf : lower_semicontinuous f) : measurable f := measurable_of_Ioi (λ y, (hf.is_open_preimage y).measurable_set) lemma measurable_of_Iic {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Iic x)) : measurable f := begin apply measurable_of_Ioi, simp_rw [← compl_Iic, preimage_compl, measurable_set.compl_iff], assumption end lemma measurable_of_Ici {f : δ → α} (hf : ∀ x, measurable_set (f ⁻¹' Ici x)) : measurable f := begin apply measurable_of_Iio, simp_rw [← compl_Ici, preimage_compl, measurable_set.compl_iff], assumption end lemma measurable.is_lub {ι} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_lub {a | ∃ i, f i b = a} (g b)) : measurable g := begin change ∀ b, is_lub (range $ λ i, f i b) (g b) at hg, rw [‹borel_space α›.measurable_eq, borel_eq_generate_Ioi α], apply measurable_generate_from, rintro _ ⟨a, rfl⟩, simp_rw [set.preimage, mem_Ioi, lt_is_lub_iff (hg _), exists_range_iff, set_of_exists], exact measurable_set.Union (λ i, hf i (is_open_lt' _).measurable_set) end private lemma ae_measurable.is_lub_of_nonempty {ι} (hι : nonempty ι) {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_lub {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin let p : δ → (ι → α) → Prop := λ x f', is_lub {a | ∃ i, f' i = a} (g x), let g_seq := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨g x⟩ : nonempty α).some, have hg_seq : ∀ b, is_lub {a | ∃ i, ae_seq hf p i b = a} (g_seq b), { intro b, haveI hα : nonempty α := nonempty.map g ⟨b⟩, simp only [ae_seq, g_seq], split_ifs, { have h_set_eq : {a : α | ∃ (i : ι), (hf i).mk (f i) b = a} = {a : α | ∃ (i : ι), f i b = a}, { ext x, simp_rw [set.mem_set_of_eq, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h], }, rw h_set_eq, exact ae_seq.fun_prop_of_mem_ae_seq_set hf h, }, { have h_singleton : {a : α | ∃ (i : ι), hα.some = a} = {hα.some}, { ext1 x, exact ⟨λ hx, hx.some_spec.symm, λ hx, ⟨hι.some, hx.symm⟩⟩, }, rw h_singleton, exact is_lub_singleton, }, }, refine ⟨g_seq, measurable.is_lub (ae_seq.measurable hf p) hg_seq, _⟩, exact (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨g x⟩ : nonempty α).some) (ae_seq_set hf p) (ae_seq.measure_compl_ae_seq_set_eq_zero hf hg)).symm, end lemma ae_measurable.is_lub {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_lub {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin by_cases hμ : μ = 0, { rw hμ, exact ae_measurable_zero_measure }, haveI : μ.ae.ne_bot := by simpa [ne_bot_iff], by_cases hι : nonempty ι, { exact ae_measurable.is_lub_of_nonempty hι hf hg, }, suffices : ∃ x, g =ᵐ[μ] λ y, g x, by { exact ⟨(λ y, g this.some), measurable_const, this.some_spec⟩, }, have h_empty : ∀ x, {a : α | ∃ (i : ι), f i x = a} = ∅, { intro x, ext1 y, rw [set.mem_set_of_eq, set.mem_empty_eq, iff_false], exact λ hi, hι (nonempty_of_exists hi), }, simp_rw h_empty at hg, exact ⟨hg.exists.some, hg.mono (λ y hy, is_lub.unique hy hg.exists.some_spec)⟩, end lemma measurable.is_glb {ι} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, measurable (f i)) (hg : ∀ b, is_glb {a | ∃ i, f i b = a} (g b)) : measurable g := begin change ∀ b, is_glb (range $ λ i, f i b) (g b) at hg, rw [‹borel_space α›.measurable_eq, borel_eq_generate_Iio α], apply measurable_generate_from, rintro _ ⟨a, rfl⟩, simp_rw [set.preimage, mem_Iio, is_glb_lt_iff (hg _), exists_range_iff, set_of_exists], exact measurable_set.Union (λ i, hf i (is_open_gt' _).measurable_set) end private lemma ae_measurable.is_glb_of_nonempty {ι} (hι : nonempty ι) {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_glb {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin let p : δ → (ι → α) → Prop := λ x f', is_glb {a | ∃ i, f' i = a} (g x), let g_seq := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨g x⟩ : nonempty α).some, have hg_seq : ∀ b, is_glb {a | ∃ i, ae_seq hf p i b = a} (g_seq b), { intro b, haveI hα : nonempty α := nonempty.map g ⟨b⟩, simp only [ae_seq, g_seq], split_ifs, { have h_set_eq : {a : α | ∃ (i : ι), (hf i).mk (f i) b = a} = {a : α | ∃ (i : ι), f i b = a}, { ext x, simp_rw [set.mem_set_of_eq, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h], }, rw h_set_eq, exact ae_seq.fun_prop_of_mem_ae_seq_set hf h, }, { have h_singleton : {a : α | ∃ (i : ι), hα.some = a} = {hα.some}, { ext1 x, exact ⟨λ hx, hx.some_spec.symm, λ hx, ⟨hι.some, hx.symm⟩⟩, }, rw h_singleton, exact is_glb_singleton, }, }, refine ⟨g_seq, measurable.is_glb (ae_seq.measurable hf p) hg_seq, _⟩, exact (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨g x⟩ : nonempty α).some) (ae_seq_set hf p) (ae_seq.measure_compl_ae_seq_set_eq_zero hf hg)).symm, end lemma ae_measurable.is_glb {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} {g : δ → α} (hf : ∀ i, ae_measurable (f i) μ) (hg : ∀ᵐ b ∂μ, is_glb {a | ∃ i, f i b = a} (g b)) : ae_measurable g μ := begin by_cases hμ : μ = 0, { rw hμ, exact ae_measurable_zero_measure }, haveI : μ.ae.ne_bot := by simpa [ne_bot_iff], by_cases hι : nonempty ι, { exact ae_measurable.is_glb_of_nonempty hι hf hg, }, suffices : ∃ x, g =ᵐ[μ] λ y, g x, by { exact ⟨(λ y, g this.some), measurable_const, this.some_spec⟩, }, have h_empty : ∀ x, {a : α | ∃ (i : ι), f i x = a} = ∅, { intro x, ext1 y, rw [set.mem_set_of_eq, set.mem_empty_eq, iff_false], exact λ hi, hι (nonempty_of_exists hi), }, simp_rw h_empty at hg, exact ⟨hg.exists.some, hg.mono (λ y hy, is_glb.unique hy hg.exists.some_spec)⟩, end lemma measurable_of_monotone [linear_order β] [order_topology β] {f : β → α} (hf : monotone f) : measurable f := suffices h : ∀ x, ord_connected (f ⁻¹' Ioi x), from measurable_of_Ioi (λ x, (h x).measurable_set), λ x, ord_connected_def.mpr (λ a ha b hb c hc, lt_of_lt_of_le ha (hf hc.1)) alias measurable_of_monotone ← monotone.measurable lemma measurable_of_antimono [linear_order β] [order_topology β] {f : β → α} (hf : ∀ ⦃x y : β⦄, x ≤ y → f y ≤ f x) : measurable f := suffices h : ∀ x, ord_connected (f ⁻¹' Ioi x), from measurable_of_Ioi (λ x, (h x).measurable_set), λ x, ord_connected_def.mpr (λ a ha b hb c hc, lt_of_lt_of_le hb (hf hc.2)) end linear_order @[measurability] lemma measurable.supr_Prop {α} [measurable_space α] [complete_lattice α] (p : Prop) {f : δ → α} (hf : measurable f) : measurable (λ b, ⨆ h : p, f b) := classical.by_cases (assume h : p, begin convert hf, funext, exact supr_pos h end) (assume h : ¬p, begin convert measurable_const, funext, exact supr_neg h end) @[measurability] lemma measurable.infi_Prop {α} [measurable_space α] [complete_lattice α] (p : Prop) {f : δ → α} (hf : measurable f) : measurable (λ b, ⨅ h : p, f b) := classical.by_cases (assume h : p, begin convert hf, funext, exact infi_pos h end ) (assume h : ¬p, begin convert measurable_const, funext, exact infi_neg h end) section complete_linear_order variables [complete_linear_order α] [order_topology α] [second_countable_topology α] @[measurability] lemma measurable_supr {ι} [encodable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i, f i b) := measurable.is_lub hf $ λ b, is_lub_supr @[measurability] lemma ae_measurable_supr {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨆ i, f i b) μ := ae_measurable.is_lub hf $ (ae_of_all μ (λ b, is_lub_supr)) @[measurability] lemma measurable_infi {ι} [encodable ι] {f : ι → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i, f i b) := measurable.is_glb hf $ λ b, is_glb_infi @[measurability] lemma ae_measurable_infi {ι} {μ : measure δ} [encodable ι] {f : ι → δ → α} (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨅ i, f i b) μ := ae_measurable.is_glb hf $ (ae_of_all μ (λ b, is_glb_infi)) lemma measurable_bsupr {ι} (s : set ι) {f : ι → δ → α} (hs : countable s) (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨆ i ∈ s, f i b) := by { haveI : encodable s := hs.to_encodable, simp only [supr_subtype'], exact measurable_supr (λ i, hf i) } lemma ae_measurable_bsupr {ι} {μ : measure δ} (s : set ι) {f : ι → δ → α} (hs : countable s) (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨆ i ∈ s, f i b) μ := begin haveI : encodable s := hs.to_encodable, simp only [supr_subtype'], exact ae_measurable_supr (λ i, hf i), end lemma measurable_binfi {ι} (s : set ι) {f : ι → δ → α} (hs : countable s) (hf : ∀ i, measurable (f i)) : measurable (λ b, ⨅ i ∈ s, f i b) := by { haveI : encodable s := hs.to_encodable, simp only [infi_subtype'], exact measurable_infi (λ i, hf i) } lemma ae_measurable_binfi {ι} {μ : measure δ} (s : set ι) {f : ι → δ → α} (hs : countable s) (hf : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ b, ⨅ i ∈ s, f i b) μ := begin haveI : encodable s := hs.to_encodable, simp only [infi_subtype'], exact ae_measurable_infi (λ i, hf i), end /-- `liminf` over a general filter is measurable. See `measurable_liminf` for the version over `ℕ`. -/ lemma measurable_liminf' {ι ι'} {f : ι → δ → α} {u : filter ι} (hf : ∀ i, measurable (f i)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable (λ x, liminf u (λ i, f i x)) := begin simp_rw [hu.to_has_basis.liminf_eq_supr_infi], refine measurable_bsupr _ hu.countable _, exact λ i, measurable_binfi _ (hs i) hf end /-- `limsup` over a general filter is measurable. See `measurable_limsup` for the version over `ℕ`. -/ lemma measurable_limsup' {ι ι'} {f : ι → δ → α} {u : filter ι} (hf : ∀ i, measurable (f i)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable (λ x, limsup u (λ i, f i x)) := begin simp_rw [hu.to_has_basis.limsup_eq_infi_supr], refine measurable_binfi _ hu.countable _, exact λ i, measurable_bsupr _ (hs i) hf end /-- `liminf` over `ℕ` is measurable. See `measurable_liminf'` for a version with a general filter. -/ @[measurability] lemma measurable_liminf {f : ℕ → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ x, liminf at_top (λ i, f i x)) := measurable_liminf' hf at_top_countable_basis (λ i, countable_encodable _) /-- `limsup` over `ℕ` is measurable. See `measurable_limsup'` for a version with a general filter. -/ @[measurability] lemma measurable_limsup {f : ℕ → δ → α} (hf : ∀ i, measurable (f i)) : measurable (λ x, limsup at_top (λ i, f i x)) := measurable_limsup' hf at_top_countable_basis (λ i, countable_encodable _) end complete_linear_order section conditionally_complete_linear_order variables [conditionally_complete_linear_order α] [order_topology α] [second_countable_topology α] lemma measurable_cSup {ι} {f : ι → δ → α} {s : set ι} (hs : s.countable) (hf : ∀ i, measurable (f i)) (bdd : ∀ x, bdd_above ((λ i, f i x) '' s)) : measurable (λ x, Sup ((λ i, f i x) '' s)) := begin cases eq_empty_or_nonempty s with h2s h2s, { simp [h2s, measurable_const] }, { apply measurable_of_Iic, intro y, simp_rw [preimage, mem_Iic, cSup_le_iff (bdd _) (h2s.image _), ball_image_iff, set_of_forall], exact measurable_set.bInter hs (λ i hi, measurable_set_le (hf i) measurable_const) } end end conditionally_complete_linear_order /-- Convert a `homeomorph` to a `measurable_equiv`. -/ def homemorph.to_measurable_equiv (h : α ≃ₜ β) : α ≃ᵐ β := { to_equiv := h.to_equiv, measurable_to_fun := h.continuous_to_fun.measurable, measurable_inv_fun := h.continuous_inv_fun.measurable } end borel_space instance empty.borel_space : borel_space empty := ⟨borel_eq_top_of_discrete.symm⟩ instance unit.borel_space : borel_space unit := ⟨borel_eq_top_of_discrete.symm⟩ instance bool.borel_space : borel_space bool := ⟨borel_eq_top_of_discrete.symm⟩ instance nat.borel_space : borel_space ℕ := ⟨borel_eq_top_of_discrete.symm⟩ instance int.borel_space : borel_space ℤ := ⟨borel_eq_top_of_discrete.symm⟩ instance rat.borel_space : borel_space ℚ := ⟨borel_eq_top_of_encodable.symm⟩ instance real.measurable_space : measurable_space ℝ := borel ℝ instance real.borel_space : borel_space ℝ := ⟨rfl⟩ instance nnreal.measurable_space : measurable_space ℝ≥0 := subtype.measurable_space instance nnreal.borel_space : borel_space ℝ≥0 := subtype.borel_space _ instance ennreal.measurable_space : measurable_space ℝ≥0∞ := borel ℝ≥0∞ instance ennreal.borel_space : borel_space ℝ≥0∞ := ⟨rfl⟩ instance ereal.measurable_space : measurable_space ereal := borel ereal instance ereal.borel_space : borel_space ereal := ⟨rfl⟩ instance complex.measurable_space : measurable_space ℂ := borel ℂ instance complex.borel_space : borel_space ℂ := ⟨rfl⟩ section metric_space variables [metric_space α] [measurable_space α] [opens_measurable_space α] variables [measurable_space β] {x : α} {ε : ℝ} open metric @[measurability] lemma measurable_set_ball : measurable_set (metric.ball x ε) := metric.is_open_ball.measurable_set @[measurability] lemma measurable_set_closed_ball : measurable_set (metric.closed_ball x ε) := metric.is_closed_ball.measurable_set @[measurability] lemma measurable_inf_dist {s : set α} : measurable (λ x, inf_dist x s) := (continuous_inf_dist_pt s).measurable @[measurability] lemma measurable.inf_dist {f : β → α} (hf : measurable f) {s : set α} : measurable (λ x, inf_dist (f x) s) := measurable_inf_dist.comp hf @[measurability] lemma measurable_inf_nndist {s : set α} : measurable (λ x, inf_nndist x s) := (continuous_inf_nndist_pt s).measurable @[measurability] lemma measurable.inf_nndist {f : β → α} (hf : measurable f) {s : set α} : measurable (λ x, inf_nndist (f x) s) := measurable_inf_nndist.comp hf variables [second_countable_topology α] @[measurability] lemma measurable_dist : measurable (λ p : α × α, dist p.1 p.2) := continuous_dist.measurable @[measurability] lemma measurable.dist {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, dist (f b) (g b)) := (@continuous_dist α _).measurable2 hf hg @[measurability] lemma measurable_nndist : measurable (λ p : α × α, nndist p.1 p.2) := continuous_nndist.measurable @[measurability] lemma measurable.nndist {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, nndist (f b) (g b)) := (@continuous_nndist α _).measurable2 hf hg end metric_space section emetric_space variables [emetric_space α] [measurable_space α] [opens_measurable_space α] variables [measurable_space β] {x : α} {ε : ℝ≥0∞} open emetric @[measurability] lemma measurable_set_eball : measurable_set (emetric.ball x ε) := emetric.is_open_ball.measurable_set @[measurability] lemma measurable_edist_right : measurable (edist x) := (continuous_const.edist continuous_id).measurable @[measurability] lemma measurable_edist_left : measurable (λ y, edist y x) := (continuous_id.edist continuous_const).measurable @[measurability] lemma measurable_inf_edist {s : set α} : measurable (λ x, inf_edist x s) := continuous_inf_edist.measurable @[measurability] lemma measurable.inf_edist {f : β → α} (hf : measurable f) {s : set α} : measurable (λ x, inf_edist (f x) s) := measurable_inf_edist.comp hf variables [second_countable_topology α] @[measurability] lemma measurable_edist : measurable (λ p : α × α, edist p.1 p.2) := continuous_edist.measurable @[measurability] lemma measurable.edist {f g : β → α} (hf : measurable f) (hg : measurable g) : measurable (λ b, edist (f b) (g b)) := (@continuous_edist α _).measurable2 hf hg @[measurability] lemma ae_measurable.edist {f g : β → α} {μ : measure β} (hf : ae_measurable f μ) (hg : ae_measurable g μ) : ae_measurable (λ a, edist (f a) (g a)) μ := (@continuous_edist α _).ae_measurable2 hf hg end emetric_space namespace real open measurable_space measure_theory lemma borel_eq_generate_from_Ioo_rat : borel ℝ = generate_from (⋃(a b : ℚ) (h : a < b), {Ioo a b}) := is_topological_basis_Ioo_rat.borel_eq_generate_from lemma measure_ext_Ioo_rat {μ ν : measure ℝ} [locally_finite_measure μ] (h : ∀ a b : ℚ, μ (Ioo a b) = ν (Ioo a b)) : μ = ν := begin refine measure.ext_of_generate_from_of_cover_subset borel_eq_generate_from_Ioo_rat _ (subset.refl _) _ _ _ _, { simp only [is_pi_system, mem_Union, mem_singleton_iff], rintros _ _ ⟨a₁, b₁, h₁, rfl⟩ ⟨a₂, b₂, h₂, rfl⟩ ne, simp only [Ioo_inter_Ioo, sup_eq_max, inf_eq_min, ← rat.cast_max, ← rat.cast_min, nonempty_Ioo] at ne ⊢, refine ⟨_, _, _, rfl⟩, assumption_mod_cast }, { exact countable_Union (λ a, (countable_encodable _).bUnion $ λ _ _, countable_singleton _) }, { exact is_topological_basis_Ioo_rat.sUnion_eq }, { simp only [mem_Union, mem_singleton_iff], rintros _ ⟨a, b, h, rfl⟩, refine (measure_mono subset_closure).trans_lt _, rw [closure_Ioo], exacts [is_compact_Icc.finite_measure, rat.cast_lt.2 h] }, { simp only [mem_Union, mem_singleton_iff], rintros _ ⟨a, b, hab, rfl⟩, exact h a b } end lemma borel_eq_generate_from_Iio_rat : borel ℝ = generate_from (⋃ a : ℚ, {Iio a}) := begin let g, swap, apply le_antisymm (_ : _ ≤ g) (measurable_space.generate_from_le (λ t, _)), { rw borel_eq_generate_from_Ioo_rat, refine generate_from_le (λ t, _), simp only [mem_Union], rintro ⟨a, b, h, H⟩, rw [mem_singleton_iff.1 H], rw (set.ext (λ x, _) : Ioo (a : ℝ) b = (⋃c>a, (Iio c)ᶜ) ∩ Iio b), { have hg : ∀ q : ℚ, g.measurable_set' (Iio q) := λ q, generate_measurable.basic (Iio q) (by { simp, exact ⟨_, rfl⟩ }), refine @measurable_set.inter _ g _ _ _ (hg _), refine @measurable_set.bUnion _ _ g _ _ (countable_encodable _) (λ c h, _), exact @measurable_set.compl _ _ g (hg _) }, { suffices : x < ↑b → (↑a < x ↔ ∃ (i : ℚ), a < i ∧ ↑i ≤ x), by simpa, refine λ _, ⟨λ h, _, λ ⟨i, hai, hix⟩, (rat.cast_lt.2 hai).trans_le hix⟩, rcases exists_rat_btwn h with ⟨c, ac, cx⟩, exact ⟨c, rat.cast_lt.1 ac, cx.le⟩ } }, { simp, rintro r rfl, exact is_open_Iio.measurable_set } end end real variable [measurable_space α] @[measurability] lemma measurable_real_to_nnreal : measurable (real.to_nnreal) := nnreal.continuous_of_real.measurable @[measurability] lemma measurable.real_to_nnreal {f : α → ℝ} (hf : measurable f) : measurable (λ x, real.to_nnreal (f x)) := measurable_real_to_nnreal.comp hf @[measurability] lemma ae_measurable.real_to_nnreal {f : α → ℝ} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, real.to_nnreal (f x)) μ := measurable_real_to_nnreal.comp_ae_measurable hf @[measurability] lemma measurable_coe_nnreal_real : measurable (coe : ℝ≥0 → ℝ) := nnreal.continuous_coe.measurable @[measurability] lemma measurable.coe_nnreal_real {f : α → ℝ≥0} (hf : measurable f) : measurable (λ x, (f x : ℝ)) := measurable_coe_nnreal_real.comp hf @[measurability] lemma ae_measurable.coe_nnreal_real {f : α → ℝ≥0} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ℝ)) μ := measurable_coe_nnreal_real.comp_ae_measurable hf @[measurability] lemma measurable_coe_nnreal_ennreal : measurable (coe : ℝ≥0 → ℝ≥0∞) := ennreal.continuous_coe.measurable @[measurability] lemma measurable.coe_nnreal_ennreal {f : α → ℝ≥0} (hf : measurable f) : measurable (λ x, (f x : ℝ≥0∞)) := ennreal.continuous_coe.measurable.comp hf @[measurability] lemma ae_measurable.coe_nnreal_ennreal {f : α → ℝ≥0} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ℝ≥0∞)) μ := ennreal.continuous_coe.measurable.comp_ae_measurable hf @[measurability] lemma measurable.ennreal_of_real {f : α → ℝ} (hf : measurable f) : measurable (λ x, ennreal.of_real (f x)) := ennreal.continuous_of_real.measurable.comp hf /-- The set of finite `ℝ≥0∞` numbers is `measurable_equiv` to `ℝ≥0`. -/ def measurable_equiv.ennreal_equiv_nnreal : {r : ℝ≥0∞ | r ≠ ∞} ≃ᵐ ℝ≥0 := ennreal.ne_top_homeomorph_nnreal.to_measurable_equiv namespace ennreal lemma measurable_of_measurable_nnreal {f : ℝ≥0∞ → α} (h : measurable (λ p : ℝ≥0, f p)) : measurable f := measurable_of_measurable_on_compl_singleton ∞ (measurable_equiv.ennreal_equiv_nnreal.symm.measurable_coe_iff.1 h) /-- `ℝ≥0∞` is `measurable_equiv` to `ℝ≥0 ⊕ unit`. -/ def ennreal_equiv_sum : ℝ≥0∞ ≃ᵐ ℝ≥0 ⊕ unit := { measurable_to_fun := measurable_of_measurable_nnreal measurable_inl, measurable_inv_fun := measurable_sum measurable_coe_nnreal_ennreal (@measurable_const ℝ≥0∞ unit _ _ ∞), .. equiv.option_equiv_sum_punit ℝ≥0 } open function (uncurry) lemma measurable_of_measurable_nnreal_prod [measurable_space β] [measurable_space γ] {f : ℝ≥0∞ × β → γ} (H₁ : measurable (λ p : ℝ≥0 × β, f (p.1, p.2))) (H₂ : measurable (λ x, f (∞, x))) : measurable f := let e : ℝ≥0∞ × β ≃ᵐ ℝ≥0 × β ⊕ unit × β := (ennreal_equiv_sum.prod_congr (measurable_equiv.refl β)).trans (measurable_equiv.sum_prod_distrib _ _ _) in e.symm.measurable_coe_iff.1 $ measurable_sum H₁ (H₂.comp measurable_id.snd) lemma measurable_of_measurable_nnreal_nnreal [measurable_space β] {f : ℝ≥0∞ × ℝ≥0∞ → β} (h₁ : measurable (λ p : ℝ≥0 × ℝ≥0, f (p.1, p.2))) (h₂ : measurable (λ r : ℝ≥0, f (∞, r))) (h₃ : measurable (λ r : ℝ≥0, f (r, ∞))) : measurable f := measurable_of_measurable_nnreal_prod (measurable_swap_iff.1 $ measurable_of_measurable_nnreal_prod (h₁.comp measurable_swap) h₃) (measurable_of_measurable_nnreal h₂) @[measurability] lemma measurable_of_real : measurable ennreal.of_real := ennreal.continuous_of_real.measurable @[measurability] lemma measurable_to_real : measurable ennreal.to_real := ennreal.measurable_of_measurable_nnreal measurable_coe_nnreal_real @[measurability] lemma measurable_to_nnreal : measurable ennreal.to_nnreal := ennreal.measurable_of_measurable_nnreal measurable_id instance : has_measurable_mul₂ ℝ≥0∞ := begin refine ⟨measurable_of_measurable_nnreal_nnreal _ _ _⟩, { simp only [← ennreal.coe_mul, measurable_mul.coe_nnreal_ennreal] }, { simp only [ennreal.top_mul, ennreal.coe_eq_zero], exact measurable_const.piecewise (measurable_set_singleton _) measurable_const }, { simp only [ennreal.mul_top, ennreal.coe_eq_zero], exact measurable_const.piecewise (measurable_set_singleton _) measurable_const } end instance : has_measurable_sub₂ ℝ≥0∞ := ⟨by apply measurable_of_measurable_nnreal_nnreal; simp [← ennreal.coe_sub, continuous_sub.measurable.coe_nnreal_ennreal]⟩ instance : has_measurable_inv ℝ≥0∞ := ⟨ennreal.continuous_inv.measurable⟩ end ennreal @[measurability] lemma measurable.ennreal_to_nnreal {f : α → ℝ≥0∞} (hf : measurable f) : measurable (λ x, (f x).to_nnreal) := ennreal.measurable_to_nnreal.comp hf @[measurability] lemma ae_measurable.ennreal_to_nnreal {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x).to_nnreal) μ := ennreal.measurable_to_nnreal.comp_ae_measurable hf lemma measurable_coe_nnreal_ennreal_iff {f : α → ℝ≥0} : measurable (λ x, (f x : ℝ≥0∞)) ↔ measurable f := ⟨λ h, h.ennreal_to_nnreal, λ h, h.coe_nnreal_ennreal⟩ @[measurability] lemma measurable.ennreal_to_real {f : α → ℝ≥0∞} (hf : measurable f) : measurable (λ x, ennreal.to_real (f x)) := ennreal.measurable_to_real.comp hf @[measurability] lemma ae_measurable.ennreal_to_real {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, ennreal.to_real (f x)) μ := ennreal.measurable_to_real.comp_ae_measurable hf /-- note: `ℝ≥0∞` can probably be generalized in a future version of this lemma. -/ @[measurability] lemma measurable.ennreal_tsum {ι} [encodable ι] {f : ι → α → ℝ≥0∞} (h : ∀ i, measurable (f i)) : measurable (λ x, ∑' i, f i x) := by { simp_rw [ennreal.tsum_eq_supr_sum], apply measurable_supr, exact λ s, s.measurable_sum (λ i _, h i) } @[measurability] lemma measurable.nnreal_tsum {ι} [encodable ι] {f : ι → α → ℝ≥0} (h : ∀ i, measurable (f i)) : measurable (λ x, ∑' i, f i x) := begin simp_rw [nnreal.tsum_eq_to_nnreal_tsum], exact (measurable.ennreal_tsum (λ i, (h i).coe_nnreal_ennreal)).ennreal_to_nnreal, end @[measurability] lemma ae_measurable.ennreal_tsum {ι} [encodable ι] {f : ι → α → ℝ≥0∞} {μ : measure α} (h : ∀ i, ae_measurable (f i) μ) : ae_measurable (λ x, ∑' i, f i x) μ := by { simp_rw [ennreal.tsum_eq_supr_sum], apply ae_measurable_supr, exact λ s, finset.ae_measurable_sum s (λ i _, h i) } @[measurability] lemma measurable_coe_real_ereal : measurable (coe : ℝ → ereal) := continuous_coe_real_ereal.measurable @[measurability] lemma measurable.coe_real_ereal {f : α → ℝ} (hf : measurable f) : measurable (λ x, (f x : ereal)) := measurable_coe_real_ereal.comp hf @[measurability] lemma ae_measurable.coe_real_ereal {f : α → ℝ} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ereal)) μ := measurable_coe_real_ereal.comp_ae_measurable hf /-- The set of finite `ereal` numbers is `measurable_equiv` to `ℝ`. -/ def measurable_equiv.ereal_equiv_real : ({⊥, ⊤} : set ereal).compl ≃ᵐ ℝ := ereal.ne_bot_top_homeomorph_real.to_measurable_equiv lemma ereal.measurable_of_measurable_real {f : ereal → α} (h : measurable (λ p : ℝ, f p)) : measurable f := measurable_of_measurable_on_compl_finite {⊥, ⊤} (by simp) (measurable_equiv.ereal_equiv_real.symm.measurable_coe_iff.1 h) @[measurability] lemma measurable_ereal_to_real : measurable ereal.to_real := ereal.measurable_of_measurable_real (by simpa using measurable_id) @[measurability] lemma measurable.ereal_to_real {f : α → ereal} (hf : measurable f) : measurable (λ x, (f x).to_real) := measurable_ereal_to_real.comp hf @[measurability] lemma ae_measurable.ereal_to_real {f : α → ereal} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x).to_real) μ := measurable_ereal_to_real.comp_ae_measurable hf @[measurability] lemma measurable_coe_ennreal_ereal : measurable (coe : ℝ≥0∞ → ereal) := continuous_coe_ennreal_ereal.measurable @[measurability] lemma measurable.coe_ereal_ennreal {f : α → ℝ≥0∞} (hf : measurable f) : measurable (λ x, (f x : ereal)) := measurable_coe_ennreal_ereal.comp hf @[measurability] lemma ae_measurable.coe_ereal_ennreal {f : α → ℝ≥0∞} {μ : measure α} (hf : ae_measurable f μ) : ae_measurable (λ x, (f x : ereal)) μ := measurable_coe_ennreal_ereal.comp_ae_measurable hf section normed_group variables [normed_group α] [opens_measurable_space α] [measurable_space β] @[measurability] lemma measurable_norm : measurable (norm : α → ℝ) := continuous_norm.measurable @[measurability] lemma measurable.norm {f : β → α} (hf : measurable f) : measurable (λ a, norm (f a)) := measurable_norm.comp hf @[measurability] lemma ae_measurable.norm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) : ae_measurable (λ a, norm (f a)) μ := measurable_norm.comp_ae_measurable hf @[measurability] lemma measurable_nnnorm : measurable (nnnorm : α → ℝ≥0) := continuous_nnnorm.measurable @[measurability] lemma measurable.nnnorm {f : β → α} (hf : measurable f) : measurable (λ a, nnnorm (f a)) := measurable_nnnorm.comp hf @[measurability] lemma ae_measurable.nnnorm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) : ae_measurable (λ a, nnnorm (f a)) μ := measurable_nnnorm.comp_ae_measurable hf @[measurability] lemma measurable_ennnorm : measurable (λ x : α, (nnnorm x : ℝ≥0∞)) := measurable_nnnorm.coe_nnreal_ennreal @[measurability] lemma measurable.ennnorm {f : β → α} (hf : measurable f) : measurable (λ a, (nnnorm (f a) : ℝ≥0∞)) := hf.nnnorm.coe_nnreal_ennreal @[measurability] lemma ae_measurable.ennnorm {f : β → α} {μ : measure β} (hf : ae_measurable f μ) : ae_measurable (λ a, (nnnorm (f a) : ℝ≥0∞)) μ := measurable_ennnorm.comp_ae_measurable hf end normed_group section limits variables [measurable_space β] [metric_space β] [borel_space β] open metric /-- A limit (over a general filter) of measurable `ℝ≥0` valued functions is measurable. The assumption `hs` can be dropped using `filter.is_countably_generated.has_antimono_basis`, but we don't need that case yet. -/ lemma measurable_of_tendsto_nnreal' {ι ι'} {f : ι → α → ℝ≥0} {g : α → ℝ≥0} (u : filter ι) [ne_bot u] (hf : ∀ i, measurable (f i)) (lim : tendsto f u (𝓝 g)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable g := begin rw [tendsto_pi] at lim, rw [← measurable_coe_nnreal_ennreal_iff], have : ∀ x, liminf u (λ n, (f n x : ℝ≥0∞)) = (g x : ℝ≥0∞) := λ x, ((ennreal.continuous_coe.tendsto (g x)).comp (lim x)).liminf_eq, simp_rw [← this], show measurable (λ x, liminf u (λ n, (f n x : ℝ≥0∞))), exact measurable_liminf' (λ i, (hf i).coe_nnreal_ennreal) hu hs, end /-- A sequential limit of measurable `ℝ≥0` valued functions is measurable. -/ lemma measurable_of_tendsto_nnreal {f : ℕ → α → ℝ≥0} {g : α → ℝ≥0} (hf : ∀ i, measurable (f i)) (lim : tendsto f at_top (𝓝 g)) : measurable g := measurable_of_tendsto_nnreal' at_top hf lim at_top_countable_basis (λ i, countable_encodable _) /-- A limit (over a general filter) of measurable functions valued in a metric space is measurable. The assumption `hs` can be dropped using `filter.is_countably_generated.has_antimono_basis`, but we don't need that case yet. -/ lemma measurable_of_tendsto_metric' {ι ι'} {f : ι → α → β} {g : α → β} (u : filter ι) [ne_bot u] (hf : ∀ i, measurable (f i)) (lim : tendsto f u (𝓝 g)) {p : ι' → Prop} {s : ι' → set ι} (hu : u.has_countable_basis p s) (hs : ∀ i, (s i).countable) : measurable g := begin apply measurable_of_is_closed', intros s h1s h2s h3s, have : measurable (λ x, inf_nndist (g x) s), { refine measurable_of_tendsto_nnreal' u (λ i, (hf i).inf_nndist) _ hu hs, swap, rw [tendsto_pi], rw [tendsto_pi] at lim, intro x, exact ((continuous_inf_nndist_pt s).tendsto (g x)).comp (lim x) }, have h4s : g ⁻¹' s = (λ x, inf_nndist (g x) s) ⁻¹' {0}, { ext x, simp [h1s, ← mem_iff_inf_dist_zero_of_closed h1s h2s, ← nnreal.coe_eq_zero] }, rw [h4s], exact this (measurable_set_singleton 0), end /-- A sequential limit of measurable functions valued in a metric space is measurable. -/ lemma measurable_of_tendsto_metric {f : ℕ → α → β} {g : α → β} (hf : ∀ i, measurable (f i)) (lim : tendsto f at_top (𝓝 g)) : measurable g := measurable_of_tendsto_metric' at_top hf lim at_top_countable_basis (λ i, countable_encodable _) lemma ae_measurable_of_tendsto_metric_ae {μ : measure α} {f : ℕ → α → β} {g : α → β} (hf : ∀ n, ae_measurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (g x))) : ae_measurable g μ := begin let p : α → (ℕ → β) → Prop := λ x f', filter.at_top.tendsto (λ n, f' n) (𝓝 (g x)), let hp : ∀ᵐ x ∂μ, p x (λ n, f n x), from h_ae_tendsto, let ae_seq_lim := λ x, ite (x ∈ ae_seq_set hf p) (g x) (⟨f 0 x⟩ : nonempty β).some, refine ⟨ae_seq_lim, _, (ite_ae_eq_of_measure_compl_zero g (λ x, (⟨f 0 x⟩ : nonempty β).some) (ae_seq_set hf p) (ae_seq.measure_compl_ae_seq_set_eq_zero hf hp)).symm⟩, refine measurable_of_tendsto_metric (@ae_seq.measurable α β _ _ _ f μ hf p) _, refine tendsto_pi.mpr (λ x, _), simp_rw [ae_seq, ae_seq_lim], split_ifs with hx, { simp_rw ae_seq.mk_eq_fun_of_mem_ae_seq_set hf hx, exact @ae_seq.fun_prop_of_mem_ae_seq_set α β _ _ _ _ _ _ hf x hx, }, { exact tendsto_const_nhds, }, end lemma measurable_of_tendsto_metric_ae {μ : measure α} [μ.is_complete] {f : ℕ → α → β} {g : α → β} (hf : ∀ n, measurable (f n)) (h_ae_tendsto : ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (g x))) : measurable g := ae_measurable_iff_measurable.mp (ae_measurable_of_tendsto_metric_ae (λ i, (hf i).ae_measurable) h_ae_tendsto) lemma measurable_limit_of_tendsto_metric_ae {μ : measure α} {f : ℕ → α → β} (hf : ∀ n, ae_measurable (f n) μ) (h_ae_tendsto : ∀ᵐ x ∂μ, ∃ l : β, filter.at_top.tendsto (λ n, f n x) (𝓝 l)) : ∃ (f_lim : α → β) (hf_lim_meas : measurable f_lim), ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (f_lim x)) := begin let p : α → (ℕ → β) → Prop := λ x f', ∃ l : β, filter.at_top.tendsto (λ n, f' n) (𝓝 l), have hp_mem : ∀ x, x ∈ ae_seq_set hf p → p x (λ n, f n x), from λ x hx, ae_seq.fun_prop_of_mem_ae_seq_set hf hx, have hμ_compl : μ (ae_seq_set hf p)ᶜ = 0, from ae_seq.measure_compl_ae_seq_set_eq_zero hf h_ae_tendsto, let f_lim : α → β := λ x, dite (x ∈ ae_seq_set hf p) (λ h, (hp_mem x h).some) (λ h, (⟨f 0 x⟩ : nonempty β).some), have hf_lim_conv : ∀ x, x ∈ ae_seq_set hf p → filter.at_top.tendsto (λ n, f n x) (𝓝 (f_lim x)), { intros x hx_conv, simp only [f_lim, hx_conv, dif_pos], exact (hp_mem x hx_conv).some_spec, }, have hf_lim : ∀ x, filter.at_top.tendsto (λ n, ae_seq hf p n x) (𝓝 (f_lim x)), { intros x, simp only [f_lim, ae_seq], split_ifs, { rw funext (λ n, ae_seq.mk_eq_fun_of_mem_ae_seq_set hf h n), exact (hp_mem x h).some_spec, }, { exact tendsto_const_nhds, }, }, have h_ae_tendsto_f_lim : ∀ᵐ x ∂μ, filter.at_top.tendsto (λ n, f n x) (𝓝 (f_lim x)), { refine le_antisymm (le_of_eq (measure_mono_null _ hμ_compl)) (zero_le _), exact set.compl_subset_compl.mpr (λ x hx, hf_lim_conv x hx), }, have h_f_lim_meas : measurable f_lim, from measurable_of_tendsto_metric (ae_seq.measurable hf p) (tendsto_pi.mpr (λ x, hf_lim x)), exact ⟨f_lim, h_f_lim_meas, h_ae_tendsto_f_lim⟩, end end limits namespace continuous_linear_map variables {𝕜 : Type*} [normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E] variables [opens_measurable_space E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] [measurable_space F] [borel_space F] @[measurability] protected lemma measurable (L : E →L[𝕜] F) : measurable L := L.continuous.measurable lemma measurable_comp (L : E →L[𝕜] F) {φ : α → E} (φ_meas : measurable φ) : measurable (λ (a : α), L (φ a)) := L.measurable.comp φ_meas end continuous_linear_map namespace continuous_linear_map variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] {F : Type*} [normed_group F] [normed_space 𝕜 F] instance : measurable_space (E →L[𝕜] F) := borel _ instance : borel_space (E →L[𝕜] F) := ⟨rfl⟩ @[measurability] lemma measurable_apply [measurable_space F] [borel_space F] (x : E) : measurable (λ f : E →L[𝕜] F, f x) := (apply 𝕜 F x).continuous.measurable @[measurability] lemma measurable_apply' [measurable_space E] [opens_measurable_space E] [measurable_space F] [borel_space F] : measurable (λ (x : E) (f : E →L[𝕜] F), f x) := measurable_pi_lambda _ $ λ f, f.measurable @[measurability] lemma measurable_coe [measurable_space F] [borel_space F] : measurable (λ (f : E →L[𝕜] F) (x : E), f x) := measurable_pi_lambda _ measurable_apply end continuous_linear_map section continuous_linear_map_nondiscrete_normed_field variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E] [borel_space E] variables {F : Type*} [normed_group F] [normed_space 𝕜 F] @[measurability] lemma measurable.apply_continuous_linear_map {φ : α → F →L[𝕜] E} (hφ : measurable φ) (v : F) : measurable (λ a, φ a v) := (continuous_linear_map.apply 𝕜 E v).measurable.comp hφ @[measurability] lemma ae_measurable.apply_continuous_linear_map {φ : α → F →L[𝕜] E} {μ : measure α} (hφ : ae_measurable φ μ) (v : F) : ae_measurable (λ a, φ a v) μ := (continuous_linear_map.apply 𝕜 E v).measurable.comp_ae_measurable hφ end continuous_linear_map_nondiscrete_normed_field section normed_space variables {𝕜 : Type*} [nondiscrete_normed_field 𝕜] [complete_space 𝕜] [measurable_space 𝕜] variables [borel_space 𝕜] variables {E : Type*} [normed_group E] [normed_space 𝕜 E] [measurable_space E] [borel_space E] lemma measurable_smul_const {f : α → 𝕜} {c : E} (hc : c ≠ 0) : measurable (λ x, f x • c) ↔ measurable f := measurable_comp_iff_of_closed_embedding (λ y : 𝕜, y • c) (closed_embedding_smul_left hc) lemma ae_measurable_smul_const {f : α → 𝕜} {μ : measure α} {c : E} (hc : c ≠ 0) : ae_measurable (λ x, f x • c) μ ↔ ae_measurable f μ := ae_measurable_comp_iff_of_closed_embedding (λ y : 𝕜, y • c) (closed_embedding_smul_left hc) end normed_space lemma is_compact.measure_lt_top_of_nhds_within [topological_space α] {s : set α} {μ : measure α} (h : is_compact s) (hμ : ∀ x ∈ s, μ.finite_at_filter (𝓝[s] x)) : μ s < ∞ := is_compact.induction_on h (by simp) (λ s t hst ht, (measure_mono hst).trans_lt ht) (λ s t hs ht, (measure_union_le s t).trans_lt (ennreal.add_lt_top.2 ⟨hs, ht⟩)) hμ lemma is_compact.measure_lt_top [topological_space α] {s : set α} {μ : measure α} [locally_finite_measure μ] (h : is_compact s) : μ s < ∞ := h.measure_lt_top_of_nhds_within $ λ x hx, μ.finite_at_nhds_within _ _
a1f26e581e76e16b27b99b5d24f1b0bf77edbf5e
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/ring_theory/coprime/basic.lean
e9b40b49ad2ac6770e5670ba640cf175aea938bb
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
10,545
lean
/- Copyright (c) 2020 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau, Ken Lee, Chris Hughes -/ import tactic.ring import algebra.ring.basic /-! # Coprime elements of a ring ## Main definitions * `is_coprime x y`: that `x` and `y` are coprime, defined to be the existence of `a` and `b` such that `a * x + b * y = 1`. Note that elements with no common divisors are not necessarily coprime, e.g., the multivariate polynomials `x₁` and `x₂` are not coprime. See also `ring_theory.coprime.lemmas` for further development of coprime elements. -/ open_locale classical universes u v section comm_semiring variables {R : Type u} [comm_semiring R] (x y z : R) /-- The proposition that `x` and `y` are coprime, defined to be the existence of `a` and `b` such that `a * x + b * y = 1`. Note that elements with no common divisors are not necessarily coprime, e.g., the multivariate polynomials `x₁` and `x₂` are not coprime. -/ @[simp] def is_coprime : Prop := ∃ a b, a * x + b * y = 1 variables {x y z} theorem is_coprime.symm (H : is_coprime x y) : is_coprime y x := let ⟨a, b, H⟩ := H in ⟨b, a, by rw [add_comm, H]⟩ theorem is_coprime_comm : is_coprime x y ↔ is_coprime y x := ⟨is_coprime.symm, is_coprime.symm⟩ theorem is_coprime_self : is_coprime x x ↔ is_unit x := ⟨λ ⟨a, b, h⟩, is_unit_of_mul_eq_one x (a + b) $ by rwa [mul_comm, add_mul], λ h, let ⟨b, hb⟩ := is_unit_iff_exists_inv'.1 h in ⟨b, 0, by rwa [zero_mul, add_zero]⟩⟩ theorem is_coprime_zero_left : is_coprime 0 x ↔ is_unit x := ⟨λ ⟨a, b, H⟩, is_unit_of_mul_eq_one x b $ by rwa [mul_zero, zero_add, mul_comm] at H, λ H, let ⟨b, hb⟩ := is_unit_iff_exists_inv'.1 H in ⟨1, b, by rwa [one_mul, zero_add]⟩⟩ theorem is_coprime_zero_right : is_coprime x 0 ↔ is_unit x := is_coprime_comm.trans is_coprime_zero_left lemma not_coprime_zero_zero [nontrivial R] : ¬ is_coprime (0 : R) 0 := mt is_coprime_zero_right.mp not_is_unit_zero /-- If a 2-vector `p` satisfies `is_coprime (p 0) (p 1)`, then `p ≠ 0`. -/ lemma is_coprime.ne_zero [nontrivial R] {p : fin 2 → R} (h : is_coprime (p 0) (p 1)) : p ≠ 0 := by { rintro rfl, exact not_coprime_zero_zero h } theorem is_coprime_one_left : is_coprime 1 x := ⟨1, 0, by rw [one_mul, zero_mul, add_zero]⟩ theorem is_coprime_one_right : is_coprime x 1 := ⟨0, 1, by rw [one_mul, zero_mul, zero_add]⟩ theorem is_coprime.dvd_of_dvd_mul_right (H1 : is_coprime x z) (H2 : x ∣ y * z) : x ∣ y := let ⟨a, b, H⟩ := H1 in by { rw [← mul_one y, ← H, mul_add, ← mul_assoc, mul_left_comm], exact dvd_add (dvd_mul_left _ _) (H2.mul_left _) } theorem is_coprime.dvd_of_dvd_mul_left (H1 : is_coprime x y) (H2 : x ∣ y * z) : x ∣ z := let ⟨a, b, H⟩ := H1 in by { rw [← one_mul z, ← H, add_mul, mul_right_comm, mul_assoc b], exact dvd_add (dvd_mul_left _ _) (H2.mul_left _) } theorem is_coprime.mul_left (H1 : is_coprime x z) (H2 : is_coprime y z) : is_coprime (x * y) z := let ⟨a, b, h1⟩ := H1, ⟨c, d, h2⟩ := H2 in ⟨a * c, a * x * d + b * c * y + b * d * z, calc a * c * (x * y) + (a * x * d + b * c * y + b * d * z) * z = (a * x + b * z) * (c * y + d * z) : by ring ... = 1 : by rw [h1, h2, mul_one]⟩ theorem is_coprime.mul_right (H1 : is_coprime x y) (H2 : is_coprime x z) : is_coprime x (y * z) := by { rw is_coprime_comm at H1 H2 ⊢, exact H1.mul_left H2 } theorem is_coprime.mul_dvd (H : is_coprime x y) (H1 : x ∣ z) (H2 : y ∣ z) : x * y ∣ z := begin obtain ⟨a, b, h⟩ := H, rw [← mul_one z, ← h, mul_add], apply dvd_add, { rw [mul_comm z, mul_assoc], exact (mul_dvd_mul_left _ H2).mul_left _ }, { rw [mul_comm b, ← mul_assoc], exact (mul_dvd_mul_right H1 _).mul_right _ } end theorem is_coprime.of_mul_left_left (H : is_coprime (x * y) z) : is_coprime x z := let ⟨a, b, h⟩ := H in ⟨a * y, b, by rwa [mul_right_comm, mul_assoc]⟩ theorem is_coprime.of_mul_left_right (H : is_coprime (x * y) z) : is_coprime y z := by { rw mul_comm at H, exact H.of_mul_left_left } theorem is_coprime.of_mul_right_left (H : is_coprime x (y * z)) : is_coprime x y := by { rw is_coprime_comm at H ⊢, exact H.of_mul_left_left } theorem is_coprime.of_mul_right_right (H : is_coprime x (y * z)) : is_coprime x z := by { rw mul_comm at H, exact H.of_mul_right_left } theorem is_coprime.mul_left_iff : is_coprime (x * y) z ↔ is_coprime x z ∧ is_coprime y z := ⟨λ H, ⟨H.of_mul_left_left, H.of_mul_left_right⟩, λ ⟨H1, H2⟩, H1.mul_left H2⟩ theorem is_coprime.mul_right_iff : is_coprime x (y * z) ↔ is_coprime x y ∧ is_coprime x z := by rw [is_coprime_comm, is_coprime.mul_left_iff, is_coprime_comm, @is_coprime_comm _ _ z] theorem is_coprime.of_coprime_of_dvd_left (h : is_coprime y z) (hdvd : x ∣ y) : is_coprime x z := begin obtain ⟨d, rfl⟩ := hdvd, exact is_coprime.of_mul_left_left h end theorem is_coprime.of_coprime_of_dvd_right (h : is_coprime z y) (hdvd : x ∣ y) : is_coprime z x := (h.symm.of_coprime_of_dvd_left hdvd).symm theorem is_coprime.is_unit_of_dvd (H : is_coprime x y) (d : x ∣ y) : is_unit x := let ⟨k, hk⟩ := d in is_coprime_self.1 $ is_coprime.of_mul_right_left $ show is_coprime x (x * k), from hk ▸ H theorem is_coprime.is_unit_of_dvd' {a b x : R} (h : is_coprime a b) (ha : x ∣ a) (hb : x ∣ b) : is_unit x := (h.of_coprime_of_dvd_left ha).is_unit_of_dvd hb theorem is_coprime.map (H : is_coprime x y) {S : Type v} [comm_semiring S] (f : R →+* S) : is_coprime (f x) (f y) := let ⟨a, b, h⟩ := H in ⟨f a, f b, by rw [← f.map_mul, ← f.map_mul, ← f.map_add, h, f.map_one]⟩ variables {x y z} lemma is_coprime.of_add_mul_left_left (h : is_coprime (x + y * z) y) : is_coprime x y := let ⟨a, b, H⟩ := h in ⟨a, a * z + b, by simpa only [add_mul, mul_add, add_assoc, add_comm, add_left_comm, mul_assoc, mul_comm, mul_left_comm] using H⟩ lemma is_coprime.of_add_mul_right_left (h : is_coprime (x + z * y) y) : is_coprime x y := by { rw mul_comm at h, exact h.of_add_mul_left_left } lemma is_coprime.of_add_mul_left_right (h : is_coprime x (y + x * z)) : is_coprime x y := by { rw is_coprime_comm at h ⊢, exact h.of_add_mul_left_left } lemma is_coprime.of_add_mul_right_right (h : is_coprime x (y + z * x)) : is_coprime x y := by { rw mul_comm at h, exact h.of_add_mul_left_right } lemma is_coprime.of_mul_add_left_left (h : is_coprime (y * z + x) y) : is_coprime x y := by { rw add_comm at h, exact h.of_add_mul_left_left } lemma is_coprime.of_mul_add_right_left (h : is_coprime (z * y + x) y) : is_coprime x y := by { rw add_comm at h, exact h.of_add_mul_right_left } lemma is_coprime.of_mul_add_left_right (h : is_coprime x (x * z + y)) : is_coprime x y := by { rw add_comm at h, exact h.of_add_mul_left_right } lemma is_coprime.of_mul_add_right_right (h : is_coprime x (z * x + y)) : is_coprime x y := by { rw add_comm at h, exact h.of_add_mul_right_right } end comm_semiring namespace is_coprime section comm_ring variables {R : Type u} [comm_ring R] lemma add_mul_left_left {x y : R} (h : is_coprime x y) (z : R) : is_coprime (x + y * z) y := @of_add_mul_left_left R _ _ _ (-z) $ by simpa only [mul_neg_eq_neg_mul_symm, add_neg_cancel_right] using h lemma add_mul_right_left {x y : R} (h : is_coprime x y) (z : R) : is_coprime (x + z * y) y := by { rw mul_comm, exact h.add_mul_left_left z } lemma add_mul_left_right {x y : R} (h : is_coprime x y) (z : R) : is_coprime x (y + x * z) := by { rw is_coprime_comm, exact h.symm.add_mul_left_left z } lemma add_mul_right_right {x y : R} (h : is_coprime x y) (z : R) : is_coprime x (y + z * x) := by { rw is_coprime_comm, exact h.symm.add_mul_right_left z } lemma mul_add_left_left {x y : R} (h : is_coprime x y) (z : R) : is_coprime (y * z + x) y := by { rw add_comm, exact h.add_mul_left_left z } lemma mul_add_right_left {x y : R} (h : is_coprime x y) (z : R) : is_coprime (z * y + x) y := by { rw add_comm, exact h.add_mul_right_left z } lemma mul_add_left_right {x y : R} (h : is_coprime x y) (z : R) : is_coprime x (x * z + y) := by { rw add_comm, exact h.add_mul_left_right z } lemma mul_add_right_right {x y : R} (h : is_coprime x y) (z : R) : is_coprime x (z * x + y) := by { rw add_comm, exact h.add_mul_right_right z } lemma add_mul_left_left_iff {x y z : R} : is_coprime (x + y * z) y ↔ is_coprime x y := ⟨of_add_mul_left_left, λ h, h.add_mul_left_left z⟩ lemma add_mul_right_left_iff {x y z : R} : is_coprime (x + z * y) y ↔ is_coprime x y := ⟨of_add_mul_right_left, λ h, h.add_mul_right_left z⟩ lemma add_mul_left_right_iff {x y z : R} : is_coprime x (y + x * z) ↔ is_coprime x y := ⟨of_add_mul_left_right, λ h, h.add_mul_left_right z⟩ lemma add_mul_right_right_iff {x y z : R} : is_coprime x (y + z * x) ↔ is_coprime x y := ⟨of_add_mul_right_right, λ h, h.add_mul_right_right z⟩ lemma mul_add_left_left_iff {x y z : R} : is_coprime (y * z + x) y ↔ is_coprime x y := ⟨of_mul_add_left_left, λ h, h.mul_add_left_left z⟩ lemma mul_add_right_left_iff {x y z : R} : is_coprime (z * y + x) y ↔ is_coprime x y := ⟨of_mul_add_right_left, λ h, h.mul_add_right_left z⟩ lemma mul_add_left_right_iff {x y z : R} : is_coprime x (x * z + y) ↔ is_coprime x y := ⟨of_mul_add_left_right, λ h, h.mul_add_left_right z⟩ lemma mul_add_right_right_iff {x y z : R} : is_coprime x (z * x + y) ↔ is_coprime x y := ⟨of_mul_add_right_right, λ h, h.mul_add_right_right z⟩ lemma neg_left {x y : R} (h : is_coprime x y) : is_coprime (-x) y := begin obtain ⟨a, b, h⟩ := h, use [-a, b], rwa neg_mul_neg, end lemma neg_left_iff (x y : R) : is_coprime (-x) y ↔ is_coprime x y := ⟨λ h, neg_neg x ▸ h.neg_left, neg_left⟩ lemma neg_right {x y : R} (h : is_coprime x y) : is_coprime x (-y) := h.symm.neg_left.symm lemma neg_right_iff (x y : R) : is_coprime x (-y) ↔ is_coprime x y := ⟨λ h, neg_neg y ▸ h.neg_right, neg_right⟩ lemma neg_neg {x y : R} (h : is_coprime x y) : is_coprime (-x) (-y) := h.neg_left.neg_right lemma neg_neg_iff (x y : R) : is_coprime (-x) (-y) ↔ is_coprime x y := (neg_left_iff _ _).trans (neg_right_iff _ _) end comm_ring lemma sq_add_sq_ne_zero {R : Type*} [linear_ordered_comm_ring R] {a b : R} (h : is_coprime a b) : a ^ 2 + b ^ 2 ≠ 0 := begin intros h', obtain ⟨ha, hb⟩ := (add_eq_zero_iff' (sq_nonneg a) (sq_nonneg b)).mp h', obtain rfl := pow_eq_zero ha, obtain rfl := pow_eq_zero hb, exact not_coprime_zero_zero h end end is_coprime
8ee0870cce81afcf8b458ac9be1ad4a82746ed6b
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/tactic/local_cache.lean
552803c428806dc90b396bbb6356d7ce838e1b2d
[ "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
7,346
lean
/- Copyright (c) 2019 Keeley Hoek. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Keeley Hoek -/ import tactic.core tactic.norm_num namespace tactic namespace local_cache namespace internal variables {α : Type} [reflected α] [has_reflect α] meta def mk_full_namespace (ns : name) : name := `local_cache ++ ns meta def save_data (dn : name) (a : α) [reflected a] : tactic unit := tactic.add_decl $ mk_definition dn [] (reflect α) (reflect a) meta def load_data (dn : name) : tactic α := do e ← tactic.get_env, d ← e.get dn, tactic.eval_expr α d.value meta def poke_data (dn : name) : tactic bool := do e ← tactic.get_env, return (e.get dn).to_bool meta def run_once_under_name {α : Type} [reflected α] [has_reflect α] (t : tactic α) (cache_name : name) : tactic α := do load_data cache_name <|> do { a ← t, save_data cache_name a, return a } -- We maintain two separate caches with different scopes: -- one local to `begin ... end` or `by` blocks, and another -- for entire `def`/`lemma`s. meta structure cache_scope := -- Returns the name of the def used to store the contents of is cache, -- making a new one and recording this in private state if neccesary. (get_name : name → tactic name) -- Same as above but fails instead of making a new name, and never -- mutates state. (try_get_name : name → tactic name) -- Asks whether the namespace `ns` currently has a value-in-cache (present : name → tactic bool) -- Clear cache associated to namespace `ns` (clear : name → tactic unit) namespace block_local -- `mk_new` gives a way to generate a new name if no current one -- exists. private meta def get_name_aux (ns : name) (mk_new : options → name → tactic name) : tactic name := do o ← tactic.get_options, let opt := mk_full_namespace ns, match o.get_string opt "" with | "" := mk_new o opt | s := return $ name.from_components $ s.split (= '.') end meta def get_name (ns : name) : tactic name := get_name_aux ns $ λ o opt, do n ← mk_user_fresh_name, tactic.set_options $ o.set_string opt n.to_string, return n -- Like `get_name`, but fail if `ns` does not have a cached -- decl name (we create a new one above). meta def try_get_name (ns : name) : tactic name := get_name_aux ns $ λ o opt, fail format!"no cache for \"{ns}\"" meta def present (ns : name) : tactic bool := do o ← tactic.get_options, match o.get_string (mk_full_namespace ns) "" with | "" := return ff | s := return tt end meta def clear (ns : name) : tactic unit := do o ← tactic.get_options, set_options $ o.set_string (mk_full_namespace ns) "" end block_local namespace def_local -- Fowler-Noll-Vo hash function (FNV-1a) section fnv_a1 def FNV_OFFSET_BASIS := 0xcbf29ce484222325 def FNV_PRIME := 0x100000001b3 def RADIX := by apply_normed 2^64 def hash_byte (seed : ℕ) (c : char) : ℕ := let n : ℕ := c.to_nat in ((seed.lxor n) * FNV_PRIME) % RADIX def hash_string (s : string) : ℕ := s.to_list.foldl hash_byte FNV_OFFSET_BASIS end fnv_a1 meta def hash_context : tactic string := do ns ← open_namespaces, dn ← decl_name, let flat := ((list.cons dn ns).map to_string).foldl string.append "", return $ (to_string dn) ++ (to_string (hash_string flat)) meta def get_root_name (ns : name) : tactic name := do hc ← hash_context, return $ mk_full_namespace $ hc ++ ns meta def apply_tag (n : name) (tag : ℕ) : name := n ++ to_string format!"t{tag}" meta def mk_dead_name (n : name) : name := n ++ `dead meta def kill_name (n : name) : tactic unit := save_data (mk_dead_name n) () meta def is_name_dead (n : name) : tactic bool := do { witness : unit ← load_data $ mk_dead_name n, return true } <|> return false -- `get_with_status_tag_aux rn n` fails exactly when `rn ++ to_string n` does -- not exist. private meta def get_with_status_tag_aux (rn : name) : ℕ → tactic (ℕ × bool) | tag := do let n := apply_tag rn tag, present ← poke_data n, if ¬present then fail format!"{rn} never seen in cache!" else do is_dead ← is_name_dead n, if is_dead then get_with_status_tag_aux (tag + 1) <|> return (tag, false) else return (tag, true) -- Find the latest tag for the name `rn` and report whether it is alive. meta def get_tag_with_status (rn : name) : tactic (ℕ × bool) := get_with_status_tag_aux rn 0 meta def get_name (ns : name) : tactic name := do rn ← get_root_name ns, (tag, alive) ← get_tag_with_status rn <|> return (0, true), return $ apply_tag rn $ if alive then tag else tag + 1 meta def try_get_name (ns : name) : tactic name := do rn ← get_root_name ns, (tag, alive) ← get_tag_with_status rn, if alive then return $ apply_tag rn tag else fail format!"no cache for \"{ns}\"" meta def present (ns : name) : tactic bool := do rn ← get_root_name ns, (prod.snd <$> get_tag_with_status rn) <|> return false meta def clear (ns : name) : tactic unit := do { n ← try_get_name ns, kill_name n } <|> skip end def_local end internal open internal /-- This scope propogates the cache within a `begin ... end` or `by` block and its decendants. -/ meta def cache_scope.block_local : cache_scope := ⟨ block_local.get_name, block_local.try_get_name, block_local.present, block_local.clear ⟩ /-- This scope propogates the cache within an entire `def`/`lemma`. -/ meta def cache_scope.def_local : cache_scope := ⟨ def_local.get_name, def_local.try_get_name, def_local.present, def_local.clear ⟩ open cache_scope /-- Asks whether the namespace `ns` currently has a value-in-cache. -/ meta def present (ns : name) (s : cache_scope := block_local) : tactic bool := s.present ns /-- Clear cache associated to namespace `ns`. -/ meta def clear (ns : name) (s : cache_scope := block_local) : tactic unit := s.clear ns /-- Gets the (optionally present) value-in-cache for `ns`. -/ meta def get (ns : name) (α : Type) [reflected α] [has_reflect α] (s : cache_scope := block_local) : tactic (option α) := do dn ← some <$> s.try_get_name ns <|> return none, match dn with | none := return none | some dn := some <$> load_data dn end -- Note: we can't just use `<|>` on `load_data` since it will fail -- when a cached value is not present *as well as* when the type of -- `α` is just wrong. end local_cache open local_cache local_cache.internal /-- Using the namespace `ns` as its key, when called for the first time `run_once ns t` runs `t`, then saves and returns the result. Upon subsequent invocations in the same tactic block, with the scope of the caching being inherited by child tactic blocks) we return the cached result directly. You can configure the cached scope to be entire `def`/`lemma`s changing the optional cache_scope argument to `cache_scope.def_local`. Note: the caches backing each scope are different. If `α` is just `unit`, this means we just run `t` once each tactic block. -/ meta def run_once {α : Type} [reflected α] [has_reflect α] (ns : name) (t : tactic α) (s : cache_scope := cache_scope.block_local) : tactic α := s.get_name ns >>= run_once_under_name t end tactic
52e1a57a983096bf9d79d8258fbbbad0b0e1e275
a45212b1526d532e6e83c44ddca6a05795113ddc
/src/data/nat/choose.lean
fb45149ae27056b1221853e2eac75764217a86f2
[ "Apache-2.0" ]
permissive
fpvandoorn/mathlib
b21ab4068db079cbb8590b58fda9cc4bc1f35df4
b3433a51ea8bc07c4159c1073838fc0ee9b8f227
refs/heads/master
1,624,791,089,608
1,556,715,231,000
1,556,715,231,000
165,722,980
5
0
Apache-2.0
1,552,657,455,000
1,547,494,646,000
Lean
UTF-8
Lean
false
false
2,191
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes Mostly based on Jeremy Avigad's choose file in lean 2 -/ import data.nat.basic data.nat.prime import algebra.big_operators open nat lemma nat.prime.dvd_choose {p k : ℕ} (hk : 0 < k) (hkp : k < p) (hp : prime p) : p ∣ choose p k := have h₁ : p ∣ fact p, from hp.dvd_fact.2 (le_refl _), have h₂ : ¬p ∣ fact k, from mt hp.dvd_fact.1 (not_le_of_gt hkp), have h₃ : ¬p ∣ fact (p - k), from mt hp.dvd_fact.1 (not_le_of_gt (nat.sub_lt_self hp.pos hk)), by rw [← choose_mul_fact_mul_fact (le_of_lt hkp), mul_assoc, hp.dvd_mul, hp.dvd_mul] at h₁; exact h₁.resolve_right (not_or_distrib.2 ⟨h₂, h₃⟩) section binomial open finset variables {α : Type*} [comm_semiring α] (x y : α) /-- The binomial theorem -/ theorem add_pow : ∀ n : ℕ, (x + y) ^ n = (range (succ n)).sum (λ m, x ^ m * y ^ (n - m) * choose n m) | 0 := by simp [range_succ] | (succ n) := have h₁ : x * (x ^ n * y ^ (n - n) * choose n n) = x ^ succ n * y ^ (succ n - succ n) * choose (succ n) (succ n), by simp [_root_.pow_succ, mul_assoc, mul_comm, mul_left_comm], have h₂ : y * (x^0 * y^(n - 0) * choose n 0) = x^0 * y^(succ n - 0) * choose (succ n) 0, by simp [_root_.pow_succ, mul_assoc, mul_comm, mul_left_comm], have h₃ : (range n).sum (λ m, x * (x ^ m * y ^ (n - m) * choose n m) + y * (x ^ succ m * y ^ (n - succ m) * choose n (succ m))) = (range n).sum (λ m, x ^ succ m * y ^ (succ n - succ m) * ↑(choose (succ n) (succ m))), from finset.sum_congr rfl $ λ m hm, begin simp only [mul_assoc, mul_left_comm y, mul_left_comm (y ^ (n - succ m)), mul_comm y], rw [← _root_.pow_succ', add_one, ← succ_sub (mem_range.1 hm)], simp [choose_succ_succ, mul_comm, mul_assoc, mul_left_comm, add_mul, mul_add, _root_.pow_succ] end, by rw [_root_.pow_succ, add_pow, add_mul, finset.mul_sum, finset.mul_sum, sum_range_succ, sum_range_succ', sum_range_succ, sum_range_succ', add_assoc, ← add_assoc ((range n).sum _), ← finset.sum_add_distrib, h₁, h₂, h₃] end binomial
4b6d59562fb5cd9a0d872e526c89ceada3d93258
66a6486e19b71391cc438afee5f081a4257564ec
/algebra/product_group.hlean
fd8c2fe477b721ac37ce607a7459b3d74eccc7bf
[ "Apache-2.0" ]
permissive
spiceghello/Spectral
c8ccd1e32d4b6a9132ccee20fcba44b477cd0331
20023aa3de27c22ab9f9b4a177f5a1efdec2b19f
refs/heads/master
1,611,263,374,078
1,523,349,717,000
1,523,349,717,000
92,312,239
0
0
null
1,495,642,470,000
1,495,642,470,000
null
UTF-8
Lean
false
false
3,535
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn, Egbert Rijke, Favonia Constructions with groups -/ import algebra.group_theory hit.set_quotient types.list types.sum .subgroup .quotient_group open eq algebra is_trunc set_quotient relation sigma prod prod.ops sum list trunc function equiv namespace group variables {G G' : Group} {g g' h h' k : G} {A B : AbGroup} /- Binary products (direct product) of Groups -/ definition product_one [constructor] : G × G' := (one, one) definition product_inv [unfold 3] : G × G' → G × G' := λv, (v.1⁻¹, v.2⁻¹) definition product_mul [unfold 3 4] : G × G' → G × G' → G × G' := λv w, (v.1 * w.1, v.2 * w.2) section local notation 1 := product_one local postfix ⁻¹ := product_inv local infix * := product_mul theorem product_mul_assoc (g₁ g₂ g₃ : G × G') : g₁ * g₂ * g₃ = g₁ * (g₂ * g₃) := prod_eq !mul.assoc !mul.assoc theorem product_one_mul (g : G × G') : 1 * g = g := prod_eq !one_mul !one_mul theorem product_mul_one (g : G × G') : g * 1 = g := prod_eq !mul_one !mul_one theorem product_mul_left_inv (g : G × G') : g⁻¹ * g = 1 := prod_eq !mul.left_inv !mul.left_inv theorem product_mul_comm {G G' : AbGroup} (g h : G × G') : g * h = h * g := prod_eq !mul.comm !mul.comm end variables (G G') definition group_prod [constructor] : group (G × G') := group.mk _ product_mul product_mul_assoc product_one product_one_mul product_mul_one product_inv product_mul_left_inv definition product [constructor] : Group := Group.mk _ (group_prod G G') definition ab_group_prod [constructor] (G G' : AbGroup) : ab_group (G × G') := ⦃ab_group, group_prod G G', mul_comm := product_mul_comm⦄ definition ab_product [constructor] (G G' : AbGroup) : AbGroup := AbGroup.mk _ (ab_group_prod G G') infix ` ×g `:60 := group.product infix ` ×ag `:60 := group.ab_product definition product_inl [constructor] (G H : Group) : G →g G ×g H := homomorphism.mk (λx, (x, one)) (λx y, prod_eq !refl !one_mul⁻¹) definition product_inr [constructor] (G H : Group) : H →g G ×g H := homomorphism.mk (λx, (one, x)) (λx y, prod_eq !one_mul⁻¹ !refl) definition Group_sum_elim [constructor] {G H : Group} (I : AbGroup) (φ : G →g I) (ψ : H →g I) : G ×g H →g I := homomorphism.mk (λx, φ x.1 * ψ x.2) abstract (λx y, calc φ (x.1 * y.1) * ψ (x.2 * y.2) = (φ x.1 * φ y.1) * (ψ x.2 * ψ y.2) : by exact ap011 mul (to_respect_mul φ x.1 y.1) (to_respect_mul ψ x.2 y.2) ... = (φ x.1 * ψ x.2) * (φ y.1 * ψ y.2) : by exact interchange I (φ x.1) (φ y.1) (ψ x.2) (ψ y.2)) end definition product_functor [constructor] {G G' H H' : Group} (φ : G →g H) (ψ : G' →g H') : G ×g G' →g H ×g H' := homomorphism.mk (λx, (φ x.1, ψ x.2)) (λx y, prod_eq !to_respect_mul !to_respect_mul) infix ` ×→g `:60 := group.product_functor definition product_isomorphism [constructor] {G G' H H' : Group} (φ : G ≃g H) (ψ : G' ≃g H') : G ×g G' ≃g H ×g H' := isomorphism.mk (φ ×→g ψ) !is_equiv_prod_functor infix ` ×≃g `:60 := group.product_isomorphism definition product_group_mul_eq {G H : Group} (g h : G ×g H) : g * h = product_mul g h := idp end group
7116aad6edbd00ebe7f332860610cc4f83bae8f6
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/run/1848.lean
a59b1bdeb9269346a73428d70f1d5b2572e0c1bc
[ "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
164
lean
abbrev f : Nat → Nat | 0 => 0 | n + 1 => f n termination_by _ n => n mutual abbrev f1 : Nat → Nat | 0 => 0 | n + 1 => f1 n end termination_by _ n => n
41d97c1d213e738b8cb1a438c9813252cb25676a
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/data/int/cast/field.lean
b96ce2bc5415c712dd91a68f0a8ec9aa0b6d6f08
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
1,148
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import data.int.cast.lemmas import algebra.field.defs import algebra.group_with_zero.units.lemmas /-! # Cast of integers into fields This file concerns the canonical homomorphism `ℤ → F`, where `F` is a field. ## Main results * `int.cast_div`: if `n` divides `m`, then `↑(m / n) = ↑m / ↑n` -/ namespace int open nat variables {α : Type*} /-- Auxiliary lemma for norm_cast to move the cast `-↑n` upwards to `↑-↑n`. (The restriction to `field` is necessary, otherwise this would also apply in the case where `R = ℤ` and cause nontermination.) -/ @[norm_cast] lemma cast_neg_nat_cast {R} [field R] (n : ℕ) : ((-n : ℤ) : R) = -n := by simp @[simp] theorem cast_div [field α] {m n : ℤ} (n_dvd : n ∣ m) (n_nonzero : (n : α) ≠ 0) : ((m / n : ℤ) : α) = m / n := begin rcases n_dvd with ⟨k, rfl⟩, have : n ≠ 0, { rintro rfl, simpa using n_nonzero }, rw [int.mul_div_cancel_left _ this, int.cast_mul, mul_div_cancel_left _ n_nonzero], end end int
2dc436497d3386a6be9646972e57ad116822d581
4b846d8dabdc64e7ea03552bad8f7fa74763fc67
/library/init/logic.lean
55b4f0718e6b097694b62a19451a6d64cbacaef0
[ "Apache-2.0" ]
permissive
pacchiano/lean
9324b33f3ac3b5c5647285160f9f6ea8d0d767dc
fdadada3a970377a6df8afcd629a6f2eab6e84e8
refs/heads/master
1,611,357,380,399
1,489,870,101,000
1,489,870,101,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
36,969
lean
/- Copyright (c) 2014 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura, Jeremy Avigad, Floris van Doorn -/ prelude import init.core universes u v w @[inline] def id {α : Sort u} (a : α) : α := a def flip {α : Sort u} {β : Sort v} {φ : Sort w} (f : α → β → φ) : β → α → φ := λ b a, f a b /- implication -/ def implies (a b : Prop) := a → b @[trans] lemma implies.trans {p q r : Prop} (h₁ : implies p q) (h₂ : implies q r) : implies p r := assume hp, h₂ (h₁ hp) def trivial : true := ⟨⟩ @[inline] def absurd {a : Prop} {b : Sort v} (h₁ : a) (h₂ : ¬a) : b := false.rec b (h₂ h₁) lemma not.intro {a : Prop} (h : a → false) : ¬ a := h lemma mt {a b : Prop} (h₁ : a → b) (h₂ : ¬b) : ¬a := assume ha : a, absurd (h₁ ha) h₂ def implies.resolve {a b : Prop} (h : a → b) (nb : ¬ b) : ¬ a := assume ha, nb (h ha) /- not -/ lemma not_false : ¬false := assume h : false, h def non_contradictory (a : Prop) : Prop := ¬¬a lemma non_contradictory_intro {a : Prop} (ha : a) : ¬¬a := assume hna : ¬a, absurd ha hna /- false -/ lemma false.elim {c : Prop} (h : false) : c := false.rec c h /- eq -/ -- proof irrelevance is built in lemma proof_irrel {a : Prop} (h₁ h₂ : a) : h₁ = h₂ := rfl @[simp] lemma id.def {α : Sort u} (a : α) : id a = a := rfl @[inline] def eq.mp {α β : Sort u} : (α = β) → α → β := eq.rec_on @[inline] def eq.mpr {α β : Sort u} : (α = β) → β → α := λ h₁ h₂, eq.rec_on (eq.symm h₁) h₂ lemma eq.substr {α : Sort u} {p : α → Prop} {a b : α} (h₁ : b = a) : p a → p b := eq.subst (eq.symm h₁) lemma congr {α : Sort u} {β : Sort v} {f₁ f₂ : α → β} {a₁ a₂ : α} (h₁ : f₁ = f₂) (h₂ : a₁ = a₂) : f₁ a₁ = f₂ a₂ := eq.subst h₁ (eq.subst h₂ rfl) lemma congr_fun {α : Sort u} {β : α → Sort v} {f g : Π x, β x} (h : f = g) (a : α) : f a = g a := eq.subst h (eq.refl (f a)) lemma congr_arg {α : Sort u} {β : Sort v} {a₁ a₂ : α} (f : α → β) : a₁ = a₂ → f a₁ = f a₂ := congr rfl lemma trans_rel_left {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : r a b) (h₂ : b = c) : r a c := h₂ ▸ h₁ lemma trans_rel_right {α : Sort u} {a b c : α} (r : α → α → Prop) (h₁ : a = b) (h₂ : r b c) : r a c := h₁^.symm ▸ h₂ lemma of_eq_true {p : Prop} (h : p = true) : p := h^.symm ▸ trivial lemma not_of_eq_false {p : Prop} (h : p = false) : ¬p := assume hp, h ▸ hp @[inline] def cast {α β : Sort u} (h : α = β) (a : α) : β := eq.rec a h lemma cast_proof_irrel {α β : Sort u} (h₁ h₂ : α = β) (a : α) : cast h₁ a = cast h₂ a := rfl lemma cast_eq {α : Sort u} (h : α = α) (a : α) : cast h a = a := rfl /- ne -/ @[reducible] def ne {α : Sort u} (a b : α) := ¬(a = b) notation a ≠ b := ne a b @[simp] lemma ne.def {α : Sort u} (a b : α) : a ≠ b = ¬ (a = b) := rfl namespace ne variable {α : Sort u} variables {a b : α} lemma intro (h : a = b → false) : a ≠ b := h lemma elim (h : a ≠ b) : a = b → false := h lemma irrefl (h : a ≠ a) : false := h rfl lemma symm (h : a ≠ b) : b ≠ a := assume (h₁ : b = a), h (h₁^.symm) end ne lemma false_of_ne {α : Sort u} {a : α} : a ≠ a → false := ne.irrefl section variables {p : Prop} lemma ne_false_of_self : p → p ≠ false := assume (hp : p) (heq : p = false), heq ▸ hp lemma ne_true_of_not : ¬p → p ≠ true := assume (hnp : ¬p) (heq : p = true), (heq ▸ hnp) trivial lemma true_ne_false : ¬true = false := ne_false_of_self trivial end attribute [refl] heq.refl section variables {α β φ : Sort u} {a a' : α} {b b' : β} {c : φ} lemma heq.elim {α : Sort u} {a : α} {p : α → Sort v} {b : α} (h₁ : a == b) : p a → p b := eq.rec_on (eq_of_heq h₁) lemma heq.subst {p : ∀ T : Sort u, T → Prop} : a == b → p α a → p β b := heq.rec_on @[symm] lemma heq.symm (h : a == b) : b == a := heq.rec_on h (heq.refl a) lemma heq_of_eq (h : a = a') : a == a' := eq.subst h (heq.refl a) @[trans] lemma heq.trans (h₁ : a == b) (h₂ : b == c) : a == c := heq.subst h₂ h₁ @[trans] lemma heq_of_heq_of_eq (h₁ : a == b) (h₂ : b = b') : a == b' := heq.trans h₁ (heq_of_eq h₂) @[trans] lemma heq_of_eq_of_heq (h₁ : a = a') (h₂ : a' == b) : a == b := heq.trans (heq_of_eq h₁) h₂ def type_eq_of_heq (h : a == b) : α = β := heq.rec_on h (eq.refl α) end lemma eq_rec_heq {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} (h : a = a') (p : φ a), (eq.rec_on h p : φ a') == p | a .a rfl p := heq.refl p lemma heq_of_eq_rec_left {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} {p₁ : φ a} {p₂ : φ a'} (e : a = a') (h₂ : (eq.rec_on e p₁ : φ a') = p₂), p₁ == p₂ | a .a p₁ p₂ (eq.refl .a) h := eq.rec_on h (heq.refl p₁) lemma heq_of_eq_rec_right {α : Sort u} {φ : α → Sort v} : ∀ {a a' : α} {p₁ : φ a} {p₂ : φ a'} (e : a' = a) (h₂ : p₁ = eq.rec_on e p₂), p₁ == p₂ | a .a p₁ p₂ (eq.refl .a) h := have p₁ = p₂, from h, this ▸ heq.refl p₁ lemma of_heq_true {a : Prop} (h : a == true) : a := of_eq_true (eq_of_heq h) lemma eq_rec_compose : ∀ {α β φ : Sort u} (p₁ : β = φ) (p₂ : α = β) (a : α), (eq.rec_on p₁ (eq.rec_on p₂ a : β) : φ) = eq.rec_on (eq.trans p₂ p₁) a | α .α .α (eq.refl .α) (eq.refl .α) a := rfl lemma eq_rec_eq_eq_rec : ∀ {α₁ α₂ : Sort u} {p : α₁ = α₂} {a₁ : α₁} {a₂ : α₂}, (eq.rec_on p a₁ : α₂) = a₂ → a₁ = eq.rec_on (eq.symm p) a₂ | α .α rfl a .a rfl := rfl lemma eq_rec_of_heq_left : ∀ {α₁ α₂ : Sort u} {a₁ : α₁} {a₂ : α₂} (h : a₁ == a₂), (eq.rec_on (type_eq_of_heq h) a₁ : α₂) = a₂ | α .α a .a (heq.refl .a) := rfl lemma eq_rec_of_heq_right {α₁ α₂ : Sort u} {a₁ : α₁} {a₂ : α₂} (h : a₁ == a₂) : a₁ = eq.rec_on (eq.symm (type_eq_of_heq h)) a₂ := eq_rec_eq_eq_rec (eq_rec_of_heq_left h) lemma cast_heq : ∀ {α β : Sort u} (h : α = β) (a : α), cast h a == a | α .α (eq.refl .α) a := heq.refl a /- and -/ notation a /\ b := and a b notation a ∧ b := and a b variables {a b c d : Prop} lemma and.elim (h₁ : a ∧ b) (h₂ : a → b → c) : c := and.rec h₂ h₁ lemma and.swap : a ∧ b → b ∧ a := assume ⟨ha, hb⟩, ⟨hb, ha⟩ def and.symm := @and.swap /- or -/ notation a \/ b := or a b notation a ∨ b := or a b namespace or lemma elim (h₁ : a ∨ b) (h₂ : a → c) (h₃ : b → c) : c := or.rec h₂ h₃ h₁ end or lemma non_contradictory_em (a : Prop) : ¬¬(a ∨ ¬a) := assume not_em : ¬(a ∨ ¬a), have neg_a : ¬a, from assume pos_a : a, absurd (or.inl pos_a) not_em, absurd (or.inr neg_a) not_em def not_not_em := non_contradictory_em lemma or.swap : a ∨ b → b ∨ a := or.rec or.inr or.inl def or.symm := @or.swap /- xor -/ def xor (a b : Prop) := (a ∧ ¬ b) ∨ (b ∧ ¬ a) /- iff -/ structure iff (a b : Prop) : Prop := intro :: (mp : a → b) (mpr : b → a) notation a <-> b := iff a b notation a ↔ b := iff a b lemma iff.elim : ((a → b) → (b → a) → c) → (a ↔ b) → c := iff.rec attribute [recursor 5] iff.elim lemma iff.elim_left : (a ↔ b) → a → b := iff.mp lemma iff.elim_right : (a ↔ b) → b → a := iff.mpr lemma iff_iff_implies_and_implies (a b : Prop) : (a ↔ b) ↔ (a → b) ∧ (b → a) := iff.intro (λ h, and.intro h^.mp h^.mpr) (λ h, iff.intro h^.left h^.right) attribute [refl] lemma iff.refl (a : Prop) : a ↔ a := iff.intro (assume h, h) (assume h, h) lemma iff.rfl {a : Prop} : a ↔ a := iff.refl a attribute [trans] lemma iff.trans (h₁ : a ↔ b) (h₂ : b ↔ c) : a ↔ c := iff.intro (assume ha, iff.mp h₂ (iff.mp h₁ ha)) (assume hc, iff.mpr h₁ (iff.mpr h₂ hc)) attribute [symm] lemma iff.symm (h : a ↔ b) : b ↔ a := iff.intro (iff.elim_right h) (iff.elim_left h) lemma iff.comm : (a ↔ b) ↔ (b ↔ a) := iff.intro iff.symm iff.symm lemma eq.to_iff {a b : Prop} (h : a = b) : a ↔ b := eq.rec_on h iff.rfl lemma neq_of_not_iff {a b : Prop} : ¬(a ↔ b) → a ≠ b := λ h₁ h₂, have a ↔ b, from eq.subst h₂ (iff.refl a), absurd this h₁ lemma not_iff_not_of_iff (h₁ : a ↔ b) : ¬a ↔ ¬b := iff.intro (assume (hna : ¬ a) (hb : b), hna (iff.elim_right h₁ hb)) (assume (hnb : ¬ b) (ha : a), hnb (iff.elim_left h₁ ha)) lemma of_iff_true (h : a ↔ true) : a := iff.mp (iff.symm h) trivial lemma not_of_iff_false : (a ↔ false) → ¬a := iff.mp lemma iff_true_intro (h : a) : a ↔ true := iff.intro (λ hl, trivial) (λ hr, h) lemma iff_false_intro (h : ¬a) : a ↔ false := iff.intro h (false.rec a) lemma not_non_contradictory_iff_absurd (a : Prop) : ¬¬¬a ↔ ¬a := iff.intro (λ (hl : ¬¬¬a) (ha : a), hl (non_contradictory_intro ha)) absurd def not_not_not_iff := not_non_contradictory_iff_absurd lemma imp_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a → b) ↔ (c → d) := iff.intro (λ hab hc, iff.mp h₂ (hab (iff.mpr h₁ hc))) (λ hcd ha, iff.mpr h₂ (hcd (iff.mp h₁ ha))) lemma imp_congr_ctx (h₁ : a ↔ c) (h₂ : c → (b ↔ d)) : (a → b) ↔ (c → d) := iff.intro (λ hab hc, have ha : a, from iff.mpr h₁ hc, have hb : b, from hab ha, iff.mp (h₂ hc) hb) (λ hcd ha, have hc : c, from iff.mp h₁ ha, have hd : d, from hcd hc, iff.mpr (h₂ hc) hd) lemma imp_congr_right (h : a → (b ↔ c)) : (a → b) ↔ (a → c) := iff.intro (take hab ha, iff.elim_left (h ha) (hab ha)) (take hab ha, iff.elim_right (h ha) (hab ha)) lemma not_not_intro (ha : a) : ¬¬a := assume hna : ¬a, hna ha lemma not_of_not_not_not (h : ¬¬¬a) : ¬a := λ ha, absurd (not_not_intro ha) h @[simp] lemma not_true : (¬ true) ↔ false := iff_false_intro (not_not_intro trivial) def not_true_iff := not_true @[simp] lemma not_false_iff : (¬ false) ↔ true := iff_true_intro not_false @[congr] lemma not_congr (h : a ↔ b) : ¬a ↔ ¬b := iff.intro (λ h₁ h₂, h₁ (iff.mpr h h₂)) (λ h₁ h₂, h₁ (iff.mp h h₂)) @[simp] lemma ne_self_iff_false {α : Sort u} (a : α) : (not (a = a)) ↔ false := iff.intro false_of_ne false.elim @[simp] lemma eq_self_iff_true {α : Sort u} (a : α) : (a = a) ↔ true := iff_true_intro rfl @[simp] lemma heq_self_iff_true {α : Sort u} (a : α) : (a == a) ↔ true := iff_true_intro (heq.refl a) @[simp] lemma iff_not_self (a : Prop) : (a ↔ ¬a) ↔ false := iff_false_intro (λ h, have h' : ¬a, from (λ ha, (iff.mp h ha) ha), h' (iff.mpr h h')) @[simp] lemma not_iff_self (a : Prop) : (¬a ↔ a) ↔ false := iff_false_intro (λ h, have h' : ¬a, from (λ ha, (iff.mpr h ha) ha), h' (iff.mp h h')) @[simp] lemma true_iff_false : (true ↔ false) ↔ false := iff_false_intro (λ h, iff.mp h trivial) @[simp] lemma false_iff_true : (false ↔ true) ↔ false := iff_false_intro (λ h, iff.mpr h trivial) lemma false_of_true_iff_false : (true ↔ false) → false := assume h, iff.mp h trivial lemma false_of_true_eq_false : (true = false) → false := assume h, h ▸ trivial lemma true_eq_false_of_false : false → (true = false) := false.elim lemma eq_comm {α : Sort u} {a b : α} : a = b ↔ b = a := ⟨eq.symm, eq.symm⟩ /- and simp rules -/ lemma and.imp (hac : a → c) (hbd : b → d) : a ∧ b → c ∧ d := assume ⟨ha, hb⟩, ⟨hac ha, hbd hb⟩ def and_implies := @and.imp @[congr] lemma and_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∧ b) ↔ (c ∧ d) := iff.intro (and.imp (iff.mp h₁) (iff.mp h₂)) (and.imp (iff.mpr h₁) (iff.mpr h₂)) lemma and_congr_right (h : a → (b ↔ c)) : (a ∧ b) ↔ (a ∧ c) := iff.intro (assume ⟨ha, hb⟩, ⟨ha, iff.elim_left (h ha) hb⟩) (assume ⟨ha, hc⟩, ⟨ha, iff.elim_right (h ha) hc⟩) @[simp] lemma and.comm : a ∧ b ↔ b ∧ a := iff.intro and.swap and.swap lemma and_comm (a b : Prop) : a ∧ b ↔ b ∧ a := and.comm @[simp] lemma and.assoc : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := iff.intro (assume ⟨⟨ha, hb⟩, hc⟩, ⟨ha, ⟨hb, hc⟩⟩) (assume ⟨ha, ⟨hb, hc⟩⟩, ⟨⟨ha, hb⟩, hc⟩) lemma and_assoc (a b : Prop) : (a ∧ b) ∧ c ↔ a ∧ (b ∧ c) := and.assoc @[simp] lemma and.left_comm : a ∧ (b ∧ c) ↔ b ∧ (a ∧ c) := iff.trans (iff.symm and.assoc) (iff.trans (and_congr and.comm (iff.refl c)) and.assoc) lemma and_iff_left {a b : Prop} (hb : b) : (a ∧ b) ↔ a := iff.intro and.left (λ ha, ⟨ha, hb⟩) lemma and_iff_right {a b : Prop} (ha : a) : (a ∧ b) ↔ b := iff.intro and.right (and.intro ha) @[simp] lemma and_true (a : Prop) : a ∧ true ↔ a := and_iff_left trivial @[simp] lemma true_and (a : Prop) : true ∧ a ↔ a := and_iff_right trivial @[simp] lemma and_false (a : Prop) : a ∧ false ↔ false := iff_false_intro and.right @[simp] lemma false_and (a : Prop) : false ∧ a ↔ false := iff_false_intro and.left @[simp] lemma not_and_self (a : Prop) : (¬a ∧ a) ↔ false := iff_false_intro (λ h, and.elim h (λ h₁ h₂, absurd h₂ h₁)) @[simp] lemma and_not_self (a : Prop) : (a ∧ ¬a) ↔ false := iff_false_intro (assume ⟨h₁, h₂⟩, absurd h₁ h₂) @[simp] lemma and_self (a : Prop) : a ∧ a ↔ a := iff.intro and.left (assume h, ⟨h, h⟩) /- or simp rules -/ lemma or.imp (h₂ : a → c) (h₃ : b → d) : a ∨ b → c ∨ d := or.rec (λ h, or.inl (h₂ h)) (λ h, or.inr (h₃ h)) lemma or.imp_left (h : a → b) : a ∨ c → b ∨ c := or.imp h id lemma or.imp_right (h : a → b) : c ∨ a → c ∨ b := or.imp id h @[congr] lemma or_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ∨ b) ↔ (c ∨ d) := iff.intro (or.imp (iff.mp h₁) (iff.mp h₂)) (or.imp (iff.mpr h₁) (iff.mpr h₂)) @[simp] lemma or.comm : a ∨ b ↔ b ∨ a := iff.intro or.swap or.swap lemma or_comm (a b : Prop) : a ∨ b ↔ b ∨ a := or.comm @[simp] lemma or.assoc : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) := iff.intro (or.rec (or.imp_right or.inl) (λ h, or.inr (or.inr h))) (or.rec (λ h, or.inl (or.inl h)) (or.imp_left or.inr)) lemma or_assoc (a b : Prop) : (a ∨ b) ∨ c ↔ a ∨ (b ∨ c) := or.assoc @[simp] lemma or.left_comm : a ∨ (b ∨ c) ↔ b ∨ (a ∨ c) := iff.trans (iff.symm or.assoc) (iff.trans (or_congr or.comm (iff.refl c)) or.assoc) @[simp] lemma or_true (a : Prop) : a ∨ true ↔ true := iff_true_intro (or.inr trivial) @[simp] lemma true_or (a : Prop) : true ∨ a ↔ true := iff_true_intro (or.inl trivial) @[simp] lemma or_false (a : Prop) : a ∨ false ↔ a := iff.intro (or.rec id false.elim) or.inl @[simp] lemma false_or (a : Prop) : false ∨ a ↔ a := iff.trans or.comm (or_false a) @[simp] lemma or_self (a : Prop) : a ∨ a ↔ a := iff.intro (or.rec id id) or.inl lemma not_or {a b : Prop} : ¬ a → ¬ b → ¬ (a ∨ b) | hna hnb (or.inl ha) := absurd ha hna | hna hnb (or.inr hb) := absurd hb hnb /- or resolution rulse -/ def or.resolve_left {a b : Prop} (h : a ∨ b) (na : ¬ a) : b := or.elim h (λ ha, absurd ha na) id def or.neg_resolve_left {a b : Prop} (h : ¬ a ∨ b) (ha : a) : b := or.elim h (λ na, absurd ha na) id def or.resolve_right {a b : Prop} (h : a ∨ b) (nb : ¬ b) : a := or.elim h id (λ hb, absurd hb nb) def or.neg_resolve_right {a b : Prop} (h : a ∨ ¬ b) (hb : b) : a := or.elim h id (λ nb, absurd hb nb) /- iff simp rules -/ @[simp] lemma iff_true (a : Prop) : (a ↔ true) ↔ a := iff.intro (assume h, iff.mpr h trivial) iff_true_intro @[simp] lemma true_iff (a : Prop) : (true ↔ a) ↔ a := iff.trans iff.comm (iff_true a) @[simp] lemma iff_false (a : Prop) : (a ↔ false) ↔ ¬ a := iff.intro iff.mp iff_false_intro @[simp] lemma false_iff (a : Prop) : (false ↔ a) ↔ ¬ a := iff.trans iff.comm (iff_false a) @[simp] lemma iff_self (a : Prop) : (a ↔ a) ↔ true := iff_true_intro iff.rfl @[congr] lemma iff_congr (h₁ : a ↔ c) (h₂ : b ↔ d) : (a ↔ b) ↔ (c ↔ d) := (iff_iff_implies_and_implies a b)^.trans ((and_congr (imp_congr h₁ h₂) (imp_congr h₂ h₁))^.trans (iff_iff_implies_and_implies c d)^.symm) /- implies simp rule -/ @[simp] lemma implies_true_iff (a : Prop) : (a → true) ↔ true := iff.intro (λ h, trivial) (λ ha h, trivial) @[simp] lemma false_implies_iff (a : Prop) : (false → a) ↔ true := iff.intro (λ h, trivial) (λ ha h, false.elim h) /- exists -/ inductive Exists {α : Sort u} (p : α → Prop) : Prop | intro : ∀ (a : α), p a → Exists attribute [intro] Exists.intro @[pattern] def exists.intro := @Exists.intro notation `exists` binders `, ` r:(scoped P, Exists P) := r notation `∃` binders `, ` r:(scoped P, Exists P) := r lemma exists.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₁ : ∃ x, p x) (h₂ : ∀ (a : α), p a → b) : b := Exists.rec h₂ h₁ /- exists unique -/ def exists_unique {α : Sort u} (p : α → Prop) := ∃ x, p x ∧ ∀ y, p y → y = x notation `∃!` binders `, ` r:(scoped P, exists_unique P) := r attribute [intro] lemma exists_unique.intro {α : Sort u} {p : α → Prop} (w : α) (h₁ : p w) (h₂ : ∀ y, p y → y = w) : ∃! x, p x := exists.intro w ⟨h₁, h₂⟩ attribute [recursor 4] lemma exists_unique.elim {α : Sort u} {p : α → Prop} {b : Prop} (h₂ : ∃! x, p x) (h₁ : ∀ x, p x → (∀ y, p y → y = x) → b) : b := exists.elim h₂ (λ w hw, h₁ w (and.left hw) (and.right hw)) lemma exists_unique_of_exists_of_unique {α : Type u} {p : α → Prop} (hex : ∃ x, p x) (hunique : ∀ y₁ y₂, p y₁ → p y₂ → y₁ = y₂) : ∃! x, p x := exists.elim hex (λ x px, exists_unique.intro x px (take y, suppose p y, hunique y x this px)) lemma exists_of_exists_unique {α : Sort u} {p : α → Prop} (h : ∃! x, p x) : ∃ x, p x := exists.elim h (λ x hx, ⟨x, and.left hx⟩) lemma unique_of_exists_unique {α : Sort u} {p : α → Prop} (h : ∃! x, p x) {y₁ y₂ : α} (py₁ : p y₁) (py₂ : p y₂) : y₁ = y₂ := exists_unique.elim h (take x, suppose p x, assume unique : ∀ y, p y → y = x, show y₁ = y₂, from eq.trans (unique _ py₁) (eq.symm (unique _ py₂))) /- exists, forall, exists unique congruences -/ @[congr] lemma forall_congr {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a ↔ q a)) : (∀ a, p a) ↔ ∀ a, q a := iff.intro (λ p a, iff.mp (h a) (p a)) (λ q a, iff.mpr (h a) (q a)) lemma exists_imp_exists {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a → q a)) (p : ∃ a, p a) : ∃ a, q a := exists.elim p (λ a hp, ⟨a, h a hp⟩) @[congr] lemma exists_congr {α : Sort u} {p q : α → Prop} (h : ∀ a, (p a ↔ q a)) : (Exists p) ↔ ∃ a, q a := iff.intro (exists_imp_exists (λ a, iff.mp (h a))) (exists_imp_exists (λ a, iff.mpr (h a))) @[congr] lemma exists_unique_congr {α : Sort u} {p₁ p₂ : α → Prop} (h : ∀ x, p₁ x ↔ p₂ x) : (exists_unique p₁) ↔ (∃! x, p₂ x) := -- exists_congr (λ x, and_congr (h x) (forall_congr (λ y, imp_congr (h y) iff.rfl))) lemma forall_not_of_not_exists {α : Sort u} {p : α → Prop} : ¬(∃ x, p x) → (∀ x, ¬p x) := λ hne x hp, hne ⟨x, hp⟩ /- decidable -/ def decidable.to_bool (p : Prop) [h : decidable p] : bool := decidable.cases_on h (λ h₁, bool.ff) (λ h₂, bool.tt) export decidable (is_true is_false to_bool) instance decidable.true : decidable true := is_true trivial instance decidable.false : decidable false := is_false not_false -- We use "dependent" if-then-else to be able to communicate the if-then-else condition -- to the branches @[inline] def dite (c : Prop) [h : decidable c] {α : Sort u} : (c → α) → (¬ c → α) → α := λ t e, decidable.rec_on h e t /- if-then-else -/ @[inline] def ite (c : Prop) [h : decidable c] {α : Sort u} (t e : α) : α := decidable.rec_on h (λ hnc, e) (λ hc, t) namespace decidable variables {p q : Prop} def rec_on_true [h : decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : p) (h₄ : h₁ h₃) : decidable.rec_on h h₂ h₁ := decidable.rec_on h (λ h, false.rec _ (h h₃)) (λ h, h₄) def rec_on_false [h : decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} (h₃ : ¬p) (h₄ : h₂ h₃) : decidable.rec_on h h₂ h₁ := decidable.rec_on h (λ h, h₄) (λ h, false.rec _ (h₃ h)) def by_cases {q : Sort u} [φ : decidable p] : (p → q) → (¬p → q) → q := dite _ lemma em (p : Prop) [decidable p] : p ∨ ¬p := by_cases or.inl or.inr lemma by_contradiction [decidable p] (h : ¬p → false) : p := if h₁ : p then h₁ else false.rec _ (h h₁) end decidable section variables {p q : Prop} def decidable_of_decidable_of_iff (hp : decidable p) (h : p ↔ q) : decidable q := if hp : p then is_true (iff.mp h hp) else is_false (iff.mp (not_iff_not_of_iff h) hp) def decidable_of_decidable_of_eq (hp : decidable p) (h : p = q) : decidable q := decidable_of_decidable_of_iff hp h^.to_iff protected def or.by_cases [decidable p] [decidable q] {α : Sort u} (h : p ∨ q) (h₁ : p → α) (h₂ : q → α) : α := if hp : p then h₁ hp else if hq : q then h₂ hq else false.rec _ (or.elim h hp hq) end section variables {p q : Prop} instance [decidable p] [decidable q] : decidable (p ∧ q) := if hp : p then if hq : q then is_true ⟨hp, hq⟩ else is_false (assume h : p ∧ q, hq (and.right h)) else is_false (assume h : p ∧ q, hp (and.left h)) instance [decidable p] [decidable q] : decidable (p ∨ q) := if hp : p then is_true (or.inl hp) else if hq : q then is_true (or.inr hq) else is_false (or.rec hp hq) instance [decidable p] : decidable (¬p) := if hp : p then is_false (absurd hp) else is_true hp instance implies.decidable [decidable p] [decidable q] : decidable (p → q) := if hp : p then if hq : q then is_true (assume h, hq) else is_false (assume h : p → q, absurd (h hp) hq) else is_true (assume h, absurd h hp) instance [decidable p] [decidable q] : decidable (p ↔ q) := decidable_of_decidable_of_iff and.decidable (iff_iff_implies_and_implies p q)^.symm end instance {α : Sort u} [decidable_eq α] (a b : α) : decidable (a ≠ b) := implies.decidable lemma bool.ff_ne_tt : ff = tt → false . def is_dec_eq {α : Sort u} (p : α → α → bool) : Prop := ∀ ⦃x y : α⦄, p x y = tt → x = y def is_dec_refl {α : Sort u} (p : α → α → bool) : Prop := ∀ x, p x x = tt open decidable instance : decidable_eq bool | ff ff := is_true rfl | ff tt := is_false bool.ff_ne_tt | tt ff := is_false (ne.symm bool.ff_ne_tt) | tt tt := is_true rfl def decidable_eq_of_bool_pred {α : Sort u} {p : α → α → bool} (h₁ : is_dec_eq p) (h₂ : is_dec_refl p) : decidable_eq α := take x y : α, if hp : p x y = tt then is_true (h₁ hp) else is_false (assume hxy : x = y, absurd (h₂ y) (@eq.rec_on _ _ (λ z, ¬p z y = tt) _ hxy hp)) lemma decidable_eq_inl_refl {α : Sort u} [h : decidable_eq α] (a : α) : h a a = is_true (eq.refl a) := match (h a a) with | (is_true e) := rfl | (is_false n) := absurd rfl n end lemma decidable_eq_inr_neg {α : Sort u} [h : decidable_eq α] {a b : α} : Π n : a ≠ b, h a b = is_false n := assume n, match (h a b) with | (is_true e) := absurd e n | (is_false n₁) := proof_irrel n n₁ ▸ eq.refl (is_false n) end /- inhabited -/ class inhabited (α : Sort u) := (default : α) def default (α : Sort u) [inhabited α] : α := inhabited.default α @[inline, irreducible] def arbitrary (α : Sort u) [inhabited α] : α := default α instance prop.inhabited : inhabited Prop := ⟨true⟩ instance fun.inhabited (α : Sort u) {β : Sort v} [h : inhabited β] : inhabited (α → β) := inhabited.rec_on h (λ b, ⟨λ a, b⟩) instance pi.inhabited (α : Sort u) {β : α → Sort v} [Π x, inhabited (β x)] : inhabited (Π x, β x) := ⟨λ a, default (β a)⟩ instance : inhabited bool := ⟨ff⟩ instance : inhabited pos_num := ⟨pos_num.one⟩ instance : inhabited num := ⟨num.zero⟩ class inductive nonempty (α : Sort u) : Prop | intro : α → nonempty protected def nonempty.elim {α : Sort u} {p : Prop} (h₁ : nonempty α) (h₂ : α → p) : p := nonempty.rec h₂ h₁ instance nonempty_of_inhabited {α : Sort u} [inhabited α] : nonempty α := ⟨default α⟩ lemma nonempty_of_exists {α : Sort u} {p : α → Prop} : (∃ x, p x) → nonempty α | ⟨w, h⟩ := ⟨w⟩ /- subsingleton -/ class inductive subsingleton (α : Sort u) : Prop | intro : (∀ a b : α, a = b) → subsingleton protected def subsingleton.elim {α : Sort u} [h : subsingleton α] : ∀ (a b : α), a = b := subsingleton.rec (λ p, p) h protected def subsingleton.helim {α β : Sort u} [h : subsingleton α] (h : α = β) : ∀ (a : α) (b : β), a == b := eq.rec_on h (λ a b : α, heq_of_eq (subsingleton.elim a b)) instance subsingleton_prop (p : Prop) : subsingleton p := ⟨λ a b, proof_irrel a b⟩ instance (p : Prop) : subsingleton (decidable p) := subsingleton.intro (λ d₁, match d₁ with | (is_true t₁) := (λ d₂, match d₂ with | (is_true t₂) := eq.rec_on (proof_irrel t₁ t₂) rfl | (is_false f₂) := absurd t₁ f₂ end) | (is_false f₁) := (λ d₂, match d₂ with | (is_true t₂) := absurd t₂ f₁ | (is_false f₂) := eq.rec_on (proof_irrel f₁ f₂) rfl end) end) protected lemma rec_subsingleton {p : Prop} [h : decidable p] {h₁ : p → Sort u} {h₂ : ¬p → Sort u} [h₃ : Π (h : p), subsingleton (h₁ h)] [h₄ : Π (h : ¬p), subsingleton (h₂ h)] : subsingleton (decidable.rec_on h h₂ h₁) := match h with | (is_true h) := h₃ h | (is_false h) := h₄ h end lemma if_pos {c : Prop} [h : decidable c] (hc : c) {α : Sort u} {t e : α} : (ite c t e) = t := match h with | (is_true hc) := rfl | (is_false hnc) := absurd hc hnc end lemma if_neg {c : Prop} [h : decidable c] (hnc : ¬c) {α : Sort u} {t e : α} : (ite c t e) = e := match h with | (is_true hc) := absurd hc hnc | (is_false hnc) := rfl end attribute [simp] lemma if_t_t (c : Prop) [h : decidable c] {α : Sort u} (t : α) : (ite c t t) = t := match h with | (is_true hc) := rfl | (is_false hnc) := rfl end lemma implies_of_if_pos {c t e : Prop} [decidable c] (h : ite c t e) : c → t := assume hc, eq.rec_on (if_pos hc : ite c t e = t) h lemma implies_of_if_neg {c t e : Prop} [decidable c] (h : ite c t e) : ¬c → e := assume hnc, eq.rec_on (if_neg hnc : ite c t e = e) h lemma if_ctx_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x y u v : α} (h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) : ite b x y = ite c u v := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end @[congr] lemma if_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x y u v : α} (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = ite c u v := @if_ctx_congr α b c dec_b dec_c x y u v h_c (λ h, h_t) (λ h, h_e) lemma if_ctx_simp_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] {x y u v : α} (h_c : b ↔ c) (h_t : c → x = u) (h_e : ¬c → y = v) : ite b x y = (@ite c (decidable_of_decidable_of_iff dec_b h_c) α u v) := @if_ctx_congr α b c dec_b (decidable_of_decidable_of_iff dec_b h_c) x y u v h_c h_t h_e @[congr] lemma if_simp_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] {x y u v : α} (h_c : b ↔ c) (h_t : x = u) (h_e : y = v) : ite b x y = (@ite c (decidable_of_decidable_of_iff dec_b h_c) α u v) := @if_ctx_simp_congr α b c dec_b x y u v h_c (λ h, h_t) (λ h, h_e) @[simp] lemma if_true {α : Sort u} {h : decidable true} (t e : α) : (@ite true h α t e) = t := if_pos trivial @[simp] lemma if_false {α : Sort u} {h : decidable false} (t e : α) : (@ite false h α t e) = e := if_neg not_false lemma if_ctx_congr_prop {b c x y u v : Prop} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ ite c u v := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end @[congr] lemma if_congr_prop {b c x y u v : Prop} [dec_b : decidable b] [dec_c : decidable c] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ ite c u v := if_ctx_congr_prop h_c (λ h, h_t) (λ h, h_e) lemma if_ctx_simp_congr_prop {b c x y u v : Prop} [dec_b : decidable b] (h_c : b ↔ c) (h_t : c → (x ↔ u)) (h_e : ¬c → (y ↔ v)) : ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) Prop u v) := @if_ctx_congr_prop b c x y u v dec_b (decidable_of_decidable_of_iff dec_b h_c) h_c h_t h_e @[congr] lemma if_simp_congr_prop {b c x y u v : Prop} [dec_b : decidable b] (h_c : b ↔ c) (h_t : x ↔ u) (h_e : y ↔ v) : ite b x y ↔ (@ite c (decidable_of_decidable_of_iff dec_b h_c) Prop u v) := @if_ctx_simp_congr_prop b c x y u v dec_b h_c (λ h, h_t) (λ h, h_e) lemma dif_pos {c : Prop} [h : decidable c] (hc : c) {α : Sort u} {t : c → α} {e : ¬ c → α} : dite c t e = t hc := match h with | (is_true hc) := rfl | (is_false hnc) := absurd hc hnc end lemma dif_neg {c : Prop} [h : decidable c] (hnc : ¬c) {α : Sort u} {t : c → α} {e : ¬ c → α} : dite c t e = e hnc := match h with | (is_true hc) := absurd hc hnc | (is_false hnc) := rfl end lemma dif_ctx_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] [dec_c : decidable c] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (h_c : b ↔ c) (h_t : ∀ (h : c), x (iff.mpr h_c h) = u h) (h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) : (@dite b dec_b α x y) = (@dite c dec_c α u v) := match dec_b, dec_c with | (is_false h₁), (is_false h₂) := h_e h₂ | (is_true h₁), (is_true h₂) := h_t h₂ | (is_false h₁), (is_true h₂) := absurd h₂ (iff.mp (not_iff_not_of_iff h_c) h₁) | (is_true h₁), (is_false h₂) := absurd h₁ (iff.mpr (not_iff_not_of_iff h_c) h₂) end lemma dif_ctx_simp_congr {α : Sort u} {b c : Prop} [dec_b : decidable b] {x : b → α} {u : c → α} {y : ¬b → α} {v : ¬c → α} (h_c : b ↔ c) (h_t : ∀ (h : c), x (iff.mpr h_c h) = u h) (h_e : ∀ (h : ¬c), y (iff.mpr (not_iff_not_of_iff h_c) h) = v h) : (@dite b dec_b α x y) = (@dite c (decidable_of_decidable_of_iff dec_b h_c) α u v) := @dif_ctx_congr α b c dec_b (decidable_of_decidable_of_iff dec_b h_c) x u y v h_c h_t h_e -- Remark: dite and ite are "defally equal" when we ignore the proofs. lemma dif_eq_if (c : Prop) [h : decidable c] {α : Sort u} (t : α) (e : α) : dite c (λ h, t) (λ h, e) = ite c t e := match h with | (is_true hc) := rfl | (is_false hnc) := rfl end instance {c t e : Prop} [d_c : decidable c] [d_t : decidable t] [d_e : decidable e] : decidable (if c then t else e) := match d_c with | (is_true hc) := d_t | (is_false hc) := d_e end instance {c : Prop} {t : c → Prop} {e : ¬c → Prop} [d_c : decidable c] [d_t : ∀ h, decidable (t h)] [d_e : ∀ h, decidable (e h)] : decidable (if h : c then t h else e h) := match d_c with | (is_true hc) := d_t hc | (is_false hc) := d_e hc end def as_true (c : Prop) [decidable c] : Prop := if c then true else false def as_false (c : Prop) [decidable c] : Prop := if c then false else true def of_as_true {c : Prop} [h₁ : decidable c] (h₂ : as_true c) : c := match h₁, h₂ with | (is_true h_c), h₂ := h_c | (is_false h_c), h₂ := false.elim h₂ end /- Universe lifting operation -/ structure {r s} ulift (α : Type s) : Type (max s r) := up :: (down : α) namespace ulift /- Bijection between α and ulift.{v} α -/ lemma up_down {α : Type u} : ∀ (b : ulift.{v} α), up (down b) = b | (up a) := rfl lemma down_up {α : Type u} (a : α) : down (up.{v} a) = a := rfl end ulift /- Universe lifting operation from Sort to Type -/ structure plift (α : Sort u) : Type u := up :: (down : α) namespace plift /- Bijection between α and slift α -/ lemma up_down {α : Sort u} : ∀ (b : plift α), up (down b) = b | (up a) := rfl lemma down_up {α : Sort u} (a : α) : down (up a) = a := rfl end plift /- Equalities for rewriting let-expressions -/ lemma let_value_eq {α : Sort u} {β : Sort v} {a₁ a₂ : α} (b : α → β) : a₁ = a₂ → (let x : α := a₁ in b x) = (let x : α := a₂ in b x) := λ h, eq.rec_on h rfl lemma let_value_heq {α : Sort v} {β : α → Sort u} {a₁ a₂ : α} (b : Π x : α, β x) : a₁ = a₂ → (let x : α := a₁ in b x) == (let x : α := a₂ in b x) := λ h, eq.rec_on h (heq.refl (b a₁)) lemma let_body_eq {α : Sort v} {β : α → Sort u} (a : α) {b₁ b₂ : Π x : α, β x} : (∀ x, b₁ x = b₂ x) → (let x : α := a in b₁ x) = (let x : α := a in b₂ x) := λ h, h a lemma let_eq {α : Sort v} {β : Sort u} {a₁ a₂ : α} {b₁ b₂ : α → β} : a₁ = a₂ → (∀ x, b₁ x = b₂ x) → (let x : α := a₁ in b₁ x) = (let x : α := a₂ in b₂ x) := λ h₁ h₂, eq.rec_on h₁ (h₂ a₁) section relation variables {α : Sort u} {β : Sort v} (r : β → β → Prop) local infix `≺`:50 := r def reflexive := ∀ x, x ≺ x def symmetric := ∀ ⦃x y⦄, x ≺ y → y ≺ x def transitive := ∀ ⦃x y z⦄, x ≺ y → y ≺ z → x ≺ z def equivalence := reflexive r ∧ symmetric r ∧ transitive r def total := ∀ x y, x ≺ y ∨ y ≺ x def mk_equivalence (rfl : reflexive r) (symm : symmetric r) (trans : transitive r) : equivalence r := ⟨rfl, symm, trans⟩ def irreflexive := ∀ x, ¬ x ≺ x def anti_symmetric := ∀ ⦃x y⦄, x ≺ y → y ≺ x → x = y def empty_relation := λ a₁ a₂ : α, false def subrelation (q r : β → β → Prop) := ∀ ⦃x y⦄, q x y → r x y def inv_image (f : α → β) : α → α → Prop := λ a₁ a₂, f a₁ ≺ f a₂ lemma inv_image.trans (f : α → β) (h : transitive r) : transitive (inv_image r f) := λ (a₁ a₂ a₃ : α) (h₁ : inv_image r f a₁ a₂) (h₂ : inv_image r f a₂ a₃), h h₁ h₂ lemma inv_image.irreflexive (f : α → β) (h : irreflexive r) : irreflexive (inv_image r f) := λ (a : α) (h₁ : inv_image r f a a), h (f a) h₁ inductive tc {α : Type u} (r : α → α → Prop) : α → α → Prop | base : ∀ a b, r a b → tc a b | trans : ∀ a b c, tc a b → tc b c → tc a c end relation section binary variables {α : Type u} {β : Type v} variable f : α → α → α variable inv : α → α variable one : α local notation a * b := f a b local notation a ⁻¹ := inv a variable g : α → α → α local notation a + b := g a b def commutative := ∀ a b, a * b = b * a def associative := ∀ a b c, (a * b) * c = a * (b * c) def left_identity := ∀ a, one * a = a def right_identity := ∀ a, a * one = a def right_inverse := ∀ a, a * a⁻¹ = one def left_cancelative := ∀ a b c, a * b = a * c → b = c def right_cancelative := ∀ a b c, a * b = c * b → a = c def left_distributive := ∀ a b c, a * (b + c) = a * b + a * c def right_distributive := ∀ a b c, (a + b) * c = a * c + b * c def right_commutative (h : β → α → β) := ∀ b a₁ a₂, h (h b a₁) a₂ = h (h b a₂) a₁ def left_commutative (h : α → β → β) := ∀ a₁ a₂ b, h a₁ (h a₂ b) = h a₂ (h a₁ b) lemma left_comm : commutative f → associative f → left_commutative f := assume hcomm hassoc, take a b c, calc a*(b*c) = (a*b)*c : eq.symm (hassoc a b c) ... = (b*a)*c : hcomm a b ▸ rfl ... = b*(a*c) : hassoc b a c lemma right_comm : commutative f → associative f → right_commutative f := assume hcomm hassoc, take a b c, calc (a*b)*c = a*(b*c) : hassoc a b c ... = a*(c*b) : hcomm b c ▸ rfl ... = (a*c)*b : eq.symm (hassoc a c b) end binary
743f0383d879e7c63363bad00da0111e3242dc71
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/order/filter/lift.lean
4d53a096d868013f601503bd1d31e97546cd5dea
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
19,330
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import order.filter.bases /-! # Lift filters along filter and set functions -/ open set open_locale classical filter namespace filter variables {α : Type*} {β : Type*} {γ : Type*} {ι : Sort*} section lift /-- A variant on `bind` using a function `g` taking a set instead of a member of `α`. This is essentially a push-forward along a function mapping each set to a filter. -/ protected def lift (f : filter α) (g : set α → filter β) := ⨅s ∈ f, g s variables {f f₁ f₂ : filter α} {g g₁ g₂ : set α → filter β} @[simp] lemma lift_top (g : set α → filter β) : (⊤ : filter α).lift g = g univ := by simp [filter.lift] /-- If `(p : ι → Prop, s : ι → set α)` is a basis of a filter `f`, `g` is a monotone function `set α → filter γ`, and for each `i`, `(pg : β i → Prop, sg : β i → set α)` is a basis of the filter `g (s i)`, then `(λ (i : ι) (x : β i), p i ∧ pg i x, λ (i : ι) (x : β i), sg i x)` is a basis of the filter `f.lift g`. This basis is parametrized by `i : ι` and `x : β i`, so in order to formulate this fact using `has_basis` one has to use `Σ i, β i` as the index type, see `filter.has_basis.lift`. This lemma states the corresponding `mem_iff` statement without using a sigma type. -/ lemma has_basis.mem_lift_iff {ι} {p : ι → Prop} {s : ι → set α} {f : filter α} (hf : f.has_basis p s) {β : ι → Type*} {pg : Π i, β i → Prop} {sg : Π i, β i → set γ} {g : set α → filter γ} (hg : ∀ i, (g $ s i).has_basis (pg i) (sg i)) (gm : monotone g) {s : set γ} : s ∈ f.lift g ↔ ∃ (i : ι) (hi : p i) (x : β i) (hx : pg i x), sg i x ⊆ s := begin refine (mem_binfi_of_directed _ ⟨univ, univ_sets _⟩).trans _, { intros t₁ ht₁ t₂ ht₂, exact ⟨t₁ ∩ t₂, inter_mem ht₁ ht₂, gm $ inter_subset_left _ _, gm $ inter_subset_right _ _⟩ }, { simp only [← (hg _).mem_iff], exact hf.exists_iff (λ t₁ t₂ ht H, gm ht H) } end /-- If `(p : ι → Prop, s : ι → set α)` is a basis of a filter `f`, `g` is a monotone function `set α → filter γ`, and for each `i`, `(pg : β i → Prop, sg : β i → set α)` is a basis of the filter `g (s i)`, then `(λ (i : ι) (x : β i), p i ∧ pg i x, λ (i : ι) (x : β i), sg i x)` is a basis of the filter `f.lift g`. This basis is parametrized by `i : ι` and `x : β i`, so in order to formulate this fact using `has_basis` one has to use `Σ i, β i` as the index type. See also `filter.has_basis.mem_lift_iff` for the corresponding `mem_iff` statement formulated without using a sigma type. -/ lemma has_basis.lift {ι} {p : ι → Prop} {s : ι → set α} {f : filter α} (hf : f.has_basis p s) {β : ι → Type*} {pg : Π i, β i → Prop} {sg : Π i, β i → set γ} {g : set α → filter γ} (hg : ∀ i, (g $ s i).has_basis (pg i) (sg i)) (gm : monotone g) : (f.lift g).has_basis (λ i : Σ i, β i, p i.1 ∧ pg i.1 i.2) (λ i : Σ i, β i, sg i.1 i.2) := begin refine ⟨λ t, (hf.mem_lift_iff hg gm).trans _⟩, simp [sigma.exists, and_assoc, exists_and_distrib_left] end lemma mem_lift_sets (hg : monotone g) {s : set β} : s ∈ f.lift g ↔ ∃t∈f, s ∈ g t := (f.basis_sets.mem_lift_iff (λ s, (g s).basis_sets) hg).trans $ by simp only [id, exists_mem_subset_iff] lemma sInter_lift_sets (hg : monotone g) : ⋂₀ {s | s ∈ f.lift g} = ⋂ s ∈ f, ⋂₀ {t | t ∈ g s} := by simp only [sInter_eq_bInter, mem_set_of_eq, filter.mem_sets, mem_lift_sets hg, Inter_exists, @Inter_comm _ (set β)] lemma mem_lift {s : set β} {t : set α} (ht : t ∈ f) (hs : s ∈ g t) : s ∈ f.lift g := le_principal_iff.mp $ show f.lift g ≤ 𝓟 s, from infi_le_of_le t $ infi_le_of_le ht $ le_principal_iff.mpr hs lemma lift_le {f : filter α} {g : set α → filter β} {h : filter β} {s : set α} (hs : s ∈ f) (hg : g s ≤ h) : f.lift g ≤ h := infi₂_le_of_le s hs hg lemma le_lift {f : filter α} {g : set α → filter β} {h : filter β} : h ≤ f.lift g ↔ ∀ s ∈ f, h ≤ g s := le_infi₂_iff lemma lift_mono (hf : f₁ ≤ f₂) (hg : g₁ ≤ g₂) : f₁.lift g₁ ≤ f₂.lift g₂ := infi_mono $ λ s, infi_mono' $ λ hs, ⟨hf hs, hg s⟩ lemma lift_mono' (hg : ∀s ∈ f, g₁ s ≤ g₂ s) : f.lift g₁ ≤ f.lift g₂ := infi₂_mono hg lemma tendsto_lift {m : γ → β} {l : filter γ} : tendsto m l (f.lift g) ↔ ∀ s ∈ f, tendsto m l (g s) := by simp only [filter.lift, tendsto_infi] lemma map_lift_eq {m : β → γ} (hg : monotone g) : map m (f.lift g) = f.lift (map m ∘ g) := have monotone (map m ∘ g), from map_mono.comp hg, filter.ext $ λ s, by simp only [mem_lift_sets hg, mem_lift_sets this, exists_prop, mem_map, function.comp_app] lemma comap_lift_eq {m : γ → β} : comap m (f.lift g) = f.lift (comap m ∘ g) := by simp only [filter.lift, comap_infi] theorem comap_lift_eq2 {m : β → α} {g : set β → filter γ} (hg : monotone g) : (comap m f).lift g = f.lift (g ∘ preimage m) := le_antisymm (le_infi₂ $ λ s hs, infi₂_le (m ⁻¹' s) ⟨s, hs, subset.rfl⟩) (le_infi₂ $ λ s ⟨s', hs', (h_sub : m ⁻¹' s' ⊆ s)⟩, infi₂_le_of_le s' hs' $ hg h_sub) lemma lift_map_le {g : set β → filter γ} {m : α → β} : (map m f).lift g ≤ f.lift (g ∘ image m) := le_lift.2 $ λ s hs, lift_le (image_mem_map hs) le_rfl lemma map_lift_eq2 {g : set β → filter γ} {m : α → β} (hg : monotone g) : (map m f).lift g = f.lift (g ∘ image m) := lift_map_le.antisymm $ le_lift.2 $ λ s hs, lift_le hs $ hg $ image_preimage_subset _ _ lemma lift_comm {g : filter β} {h : set α → set β → filter γ} : f.lift (λs, g.lift (h s)) = g.lift (λt, f.lift (λs, h s t)) := le_antisymm (le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj, infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi) (le_infi $ assume i, le_infi $ assume hi, le_infi $ assume j, le_infi $ assume hj, infi_le_of_le j $ infi_le_of_le hj $ infi_le_of_le i $ infi_le _ hi) lemma lift_assoc {h : set β → filter γ} (hg : monotone g) : (f.lift g).lift h = f.lift (λs, (g s).lift h) := le_antisymm (le_infi $ assume s, le_infi $ assume hs, le_infi $ assume t, le_infi $ assume ht, infi_le_of_le t $ infi_le _ $ (mem_lift_sets hg).mpr ⟨_, hs, ht⟩) (le_infi $ assume t, le_infi $ assume ht, let ⟨s, hs, h'⟩ := (mem_lift_sets hg).mp ht in infi_le_of_le s $ infi_le_of_le hs $ infi_le_of_le t $ infi_le _ h') lemma lift_lift_same_le_lift {g : set α → set α → filter β} : f.lift (λs, f.lift (g s)) ≤ f.lift (λs, g s s) := le_lift.2 $ λ s hs, lift_le hs $ lift_le hs le_rfl lemma lift_lift_same_eq_lift {g : set α → set α → filter β} (hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)) : f.lift (λs, f.lift (g s)) = f.lift (λs, g s s) := lift_lift_same_le_lift.antisymm $ le_lift.2 $ λ s hs, le_lift.2 $ λ t ht, lift_le (inter_mem hs ht) $ calc g (s ∩ t) (s ∩ t) ≤ g s (s ∩ t) : hg₂ (s ∩ t) (inter_subset_left _ _) ... ≤ g s t : hg₁ s (inter_subset_right _ _) lemma lift_principal {s : set α} (hg : monotone g) : (𝓟 s).lift g = g s := (lift_le (mem_principal_self _) le_rfl).antisymm (le_lift.2 $ λ t ht, hg ht) theorem monotone_lift [preorder γ] {f : γ → filter α} {g : γ → set α → filter β} (hf : monotone f) (hg : monotone g) : monotone (λc, (f c).lift (g c)) := assume a b h, lift_mono (hf h) (hg h) lemma lift_ne_bot_iff (hm : monotone g) : (ne_bot $ f.lift g) ↔ (∀s∈f, ne_bot (g s)) := by simp only [ne_bot_iff, ne.def, ← empty_mem_iff_bot, mem_lift_sets hm, not_exists] @[simp] lemma lift_const {f : filter α} {g : filter β} : f.lift (λx, g) = g := infi_subtype'.trans infi_const @[simp] lemma lift_inf {f : filter α} {g h : set α → filter β} : f.lift (λx, g x ⊓ h x) = f.lift g ⊓ f.lift h := by simp only [filter.lift, infi_inf_eq] @[simp] lemma lift_principal2 {f : filter α} : f.lift 𝓟 = f := le_antisymm (assume s hs, mem_lift hs (mem_principal_self s)) (le_infi $ assume s, le_infi $ assume hs, by simp only [hs, le_principal_iff]) lemma lift_infi_le {f : ι → filter α} {g : set α → filter β} : (infi f).lift g ≤ ⨅ i, (f i).lift g := le_infi $ λ i, lift_mono (infi_le _ _) le_rfl lemma lift_infi [nonempty ι] {f : ι → filter α} {g : set α → filter β} (hg : ∀ s t, g (s ∩ t) = g s ⊓ g t) : (infi f).lift g = (⨅i, (f i).lift g) := begin refine lift_infi_le.antisymm (λ s, _), have H : ∀ t ∈ infi f, (⨅ i, (f i).lift g) ≤ g t, { intros t ht, refine infi_sets_induct ht _ (λ i s t hs ht, _), { inhabit ι, exact infi₂_le_of_le default univ (infi_le _ univ_mem) }, { rw hg, exact le_inf (infi₂_le_of_le i s $ infi_le _ hs) ht } }, simp only [mem_lift_sets (monotone.of_map_inf hg), exists_imp_distrib], exact λ t ht hs, H t ht hs end lemma lift_infi_of_directed [nonempty ι] {f : ι → filter α} {g : set α → filter β} (hf : directed (≥) f) (hg : monotone g) : (infi f).lift g = (⨅i, (f i).lift g) := lift_infi_le.antisymm $ λ s, begin simp only [mem_lift_sets hg, exists_imp_distrib, mem_infi_of_directed hf], exact assume t i ht hs, mem_infi_of_mem i $ mem_lift ht hs end lemma lift_infi_of_map_univ {f : ι → filter α} {g : set α → filter β} (hg : ∀ s t, g (s ∩ t) = g s ⊓ g t) (hg' : g univ = ⊤) : (infi f).lift g = (⨅i, (f i).lift g) := begin casesI is_empty_or_nonempty ι, { simp [infi_of_empty, hg'] }, { exact lift_infi hg } end end lift section lift' /-- Specialize `lift` to functions `set α → set β`. This can be viewed as a generalization of `map`. This is essentially a push-forward along a function mapping each set to a set. -/ protected def lift' (f : filter α) (h : set α → set β) := f.lift (𝓟 ∘ h) variables {f f₁ f₂ : filter α} {h h₁ h₂ : set α → set β} @[simp] lemma lift'_top (h : set α → set β) : (⊤ : filter α).lift' h = 𝓟 (h univ) := lift_top _ lemma mem_lift' {t : set α} (ht : t ∈ f) : h t ∈ (f.lift' h) := le_principal_iff.mp $ show f.lift' h ≤ 𝓟 (h t), from infi_le_of_le t $ infi_le_of_le ht $ le_rfl lemma tendsto_lift' {m : γ → β} {l : filter γ} : tendsto m l (f.lift' h) ↔ ∀ s ∈ f, ∀ᶠ a in l, m a ∈ h s := by simp only [filter.lift', tendsto_lift, tendsto_principal] lemma has_basis.lift' {ι} {p : ι → Prop} {s} (hf : f.has_basis p s) (hh : monotone h) : (f.lift' h).has_basis p (h ∘ s) := begin refine ⟨λ t, (hf.mem_lift_iff _ (monotone_principal.comp hh)).trans _⟩, show ∀ i, (𝓟 (h (s i))).has_basis (λ j : unit, true) (λ (j : unit), h (s i)), from λ i, has_basis_principal _, simp only [exists_const] end lemma mem_lift'_sets (hh : monotone h) {s : set β} : s ∈ f.lift' h ↔ ∃ t ∈ f, h t ⊆ s := mem_lift_sets $ monotone_principal.comp hh lemma eventually_lift'_iff (hh : monotone h) {p : β → Prop} : (∀ᶠ y in f.lift' h, p y) ↔ (∃ t ∈ f, ∀ y ∈ h t, p y) := mem_lift'_sets hh lemma sInter_lift'_sets (hh : monotone h) : ⋂₀ {s | s ∈ f.lift' h} = ⋂ s ∈ f, h s := (sInter_lift_sets (monotone_principal.comp hh)).trans $ Inter₂_congr $ λ s hs, cInf_Ici lemma lift'_le {f : filter α} {g : set α → set β} {h : filter β} {s : set α} (hs : s ∈ f) (hg : 𝓟 (g s) ≤ h) : f.lift' g ≤ h := lift_le hs hg lemma lift'_mono (hf : f₁ ≤ f₂) (hh : h₁ ≤ h₂) : f₁.lift' h₁ ≤ f₂.lift' h₂ := lift_mono hf $ assume s, principal_mono.mpr $ hh s lemma lift'_mono' (hh : ∀s∈f, h₁ s ⊆ h₂ s) : f.lift' h₁ ≤ f.lift' h₂ := infi₂_mono $ λ s hs, principal_mono.mpr $ hh s hs lemma lift'_cong (hh : ∀s∈f, h₁ s = h₂ s) : f.lift' h₁ = f.lift' h₂ := le_antisymm (lift'_mono' $ assume s hs, le_of_eq $ hh s hs) (lift'_mono' $ assume s hs, le_of_eq $ (hh s hs).symm) lemma map_lift'_eq {m : β → γ} (hh : monotone h) : map m (f.lift' h) = f.lift' (image m ∘ h) := calc map m (f.lift' h) = f.lift (map m ∘ 𝓟 ∘ h) : map_lift_eq $ monotone_principal.comp hh ... = f.lift' (image m ∘ h) : by simp only [(∘), filter.lift', map_principal, eq_self_iff_true] lemma lift'_map_le {g : set β → set γ} {m : α → β} : (map m f).lift' g ≤ f.lift' (g ∘ image m) := lift_map_le lemma map_lift'_eq2 {g : set β → set γ} {m : α → β} (hg : monotone g) : (map m f).lift' g = f.lift' (g ∘ image m) := map_lift_eq2 $ monotone_principal.comp hg theorem comap_lift'_eq {m : γ → β} : comap m (f.lift' h) = f.lift' (preimage m ∘ h) := by simp only [filter.lift', comap_lift_eq, (∘), comap_principal] theorem comap_lift'_eq2 {m : β → α} {g : set β → set γ} (hg : monotone g) : (comap m f).lift' g = f.lift' (g ∘ preimage m) := comap_lift_eq2 $ monotone_principal.comp hg lemma lift'_principal {s : set α} (hh : monotone h) : (𝓟 s).lift' h = 𝓟 (h s) := lift_principal $ monotone_principal.comp hh lemma lift'_pure {a : α} (hh : monotone h) : (pure a : filter α).lift' h = 𝓟 (h {a}) := by rw [← principal_singleton, lift'_principal hh] lemma lift'_bot (hh : monotone h) : (⊥ : filter α).lift' h = 𝓟 (h ∅) := by rw [← principal_empty, lift'_principal hh] lemma le_lift' {f : filter α} {h : set α → set β} {g : filter β} : g ≤ f.lift' h ↔ ∀ s ∈ f, h s ∈ g := le_lift.trans $ forall₂_congr $ λ s hs, le_principal_iff lemma principal_le_lift' {t : set β} : 𝓟 t ≤ f.lift' h ↔ ∀ s ∈ f, t ⊆ h s := le_lift' theorem monotone_lift' [preorder γ] {f : γ → filter α} {g : γ → set α → set β} (hf : monotone f) (hg : monotone g) : monotone (λc, (f c).lift' (g c)) := assume a b h, lift'_mono (hf h) (hg h) lemma lift_lift'_assoc {g : set α → set β} {h : set β → filter γ} (hg : monotone g) (hh : monotone h) : (f.lift' g).lift h = f.lift (λs, h (g s)) := calc (f.lift' g).lift h = f.lift (λs, (𝓟 (g s)).lift h) : lift_assoc (monotone_principal.comp hg) ... = f.lift (λs, h (g s)) : by simp only [lift_principal, hh, eq_self_iff_true] lemma lift'_lift'_assoc {g : set α → set β} {h : set β → set γ} (hg : monotone g) (hh : monotone h) : (f.lift' g).lift' h = f.lift' (λs, h (g s)) := lift_lift'_assoc hg (monotone_principal.comp hh) lemma lift'_lift_assoc {g : set α → filter β} {h : set β → set γ} (hg : monotone g) : (f.lift g).lift' h = f.lift (λs, (g s).lift' h) := lift_assoc hg lemma lift_lift'_same_le_lift' {g : set α → set α → set β} : f.lift (λs, f.lift' (g s)) ≤ f.lift' (λs, g s s) := lift_lift_same_le_lift lemma lift_lift'_same_eq_lift' {g : set α → set α → set β} (hg₁ : ∀s, monotone (λt, g s t)) (hg₂ : ∀t, monotone (λs, g s t)) : f.lift (λs, f.lift' (g s)) = f.lift' (λs, g s s) := lift_lift_same_eq_lift (assume s, monotone_principal.comp (hg₁ s)) (assume t, monotone_principal.comp (hg₂ t)) lemma lift'_inf_principal_eq {h : set α → set β} {s : set β} : f.lift' h ⊓ 𝓟 s = f.lift' (λt, h t ∩ s) := by simp only [filter.lift', filter.lift, (∘), ← inf_principal, infi_subtype', ← infi_inf] lemma lift'_ne_bot_iff (hh : monotone h) : (ne_bot (f.lift' h)) ↔ (∀s∈f, (h s).nonempty) := calc (ne_bot (f.lift' h)) ↔ (∀s∈f, ne_bot (𝓟 (h s))) : lift_ne_bot_iff (monotone_principal.comp hh) ... ↔ (∀s∈f, (h s).nonempty) : by simp only [principal_ne_bot_iff] @[simp] lemma lift'_id {f : filter α} : f.lift' id = f := lift_principal2 lemma lift'_infi [nonempty ι] {f : ι → filter α} {g : set α → set β} (hg : ∀ s t, g (s ∩ t) = g s ∩ g t) : (infi f).lift' g = (⨅ i, (f i).lift' g) := lift_infi $ λ s t, by rw [inf_principal, (∘), ← hg] lemma lift'_infi_of_map_univ {f : ι → filter α} {g : set α → set β} (hg : ∀{s t}, g (s ∩ t) = g s ∩ g t) (hg' : g univ = univ) : (infi f).lift' g = (⨅ i, (f i).lift' g) := lift_infi_of_map_univ (λ s t, by rw [inf_principal, (∘), ← hg]) (by rw [function.comp_app, hg', principal_univ]) lemma lift'_inf (f g : filter α) {s : set α → set β} (hs : ∀ t₁ t₂, s (t₁ ∩ t₂) = s t₁ ∩ s t₂) : (f ⊓ g).lift' s = f.lift' s ⊓ g.lift' s := have (⨅ b : bool, cond b f g).lift' s = ⨅ b : bool, (cond b f g).lift' s := lift'_infi @hs, by simpa only [infi_bool_eq] lemma lift'_inf_le (f g : filter α) (s : set α → set β) : (f ⊓ g).lift' s ≤ f.lift' s ⊓ g.lift' s := le_inf (lift'_mono inf_le_left le_rfl) (lift'_mono inf_le_right le_rfl) theorem comap_eq_lift' {f : filter β} {m : α → β} : comap m f = f.lift' (preimage m) := filter.ext $ λ s, (mem_lift'_sets monotone_preimage).symm end lift' section prod variables {f : filter α} lemma prod_def {f : filter α} {g : filter β} : f ×ᶠ g = (f.lift $ λ s, g.lift' $ λ t, s ×ˢ t) := have ∀(s:set α) (t : set β), 𝓟 (s ×ˢ t) = (𝓟 s).comap prod.fst ⊓ (𝓟 t).comap prod.snd, by simp only [principal_eq_iff_eq, comap_principal, inf_principal]; intros; refl, begin simp only [filter.lift', function.comp, this, lift_inf, lift_const, lift_inf], rw [← comap_lift_eq, ← comap_lift_eq], simp only [filter.prod, lift_principal2] end lemma prod_same_eq : f ×ᶠ f = f.lift' (λ t : set α, t ×ˢ t) := prod_def.trans $ lift_lift'_same_eq_lift' (λ s, monotone_const.set_prod monotone_id) (λ t, monotone_id.set_prod monotone_const) lemma mem_prod_same_iff {s : set (α×α)} : s ∈ f ×ᶠ f ↔ (∃t∈f, t ×ˢ t ⊆ s) := by { rw [prod_same_eq, mem_lift'_sets], exact monotone_id.set_prod monotone_id } lemma tendsto_prod_self_iff {f : α × α → β} {x : filter α} {y : filter β} : filter.tendsto f (x ×ᶠ x) y ↔ ∀ W ∈ y, ∃ U ∈ x, ∀ (x x' : α), x ∈ U → x' ∈ U → f (x, x') ∈ W := by simp only [tendsto_def, mem_prod_same_iff, prod_sub_preimage_iff, exists_prop, iff_self] variables {α₁ : Type*} {α₂ : Type*} {β₁ : Type*} {β₂ : Type*} lemma prod_lift_lift {f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → filter β₁} {g₂ : set α₂ → filter β₂} (hg₁ : monotone g₁) (hg₂ : monotone g₂) : (f₁.lift g₁) ×ᶠ (f₂.lift g₂) = f₁.lift (λs, f₂.lift (λt, g₁ s ×ᶠ g₂ t)) := begin simp only [prod_def, lift_assoc hg₁], apply congr_arg, funext x, rw [lift_comm], apply congr_arg, funext y, apply lift'_lift_assoc hg₂ end lemma prod_lift'_lift' {f₁ : filter α₁} {f₂ : filter α₂} {g₁ : set α₁ → set β₁} {g₂ : set α₂ → set β₂} (hg₁ : monotone g₁) (hg₂ : monotone g₂) : f₁.lift' g₁ ×ᶠ f₂.lift' g₂ = f₁.lift (λ s, f₂.lift' (λ t, g₁ s ×ˢ g₂ t)) := calc f₁.lift' g₁ ×ᶠ f₂.lift' g₂ = f₁.lift (λ s, f₂.lift (λ t, 𝓟 (g₁ s) ×ᶠ 𝓟 (g₂ t))) : prod_lift_lift (monotone_principal.comp hg₁) (monotone_principal.comp hg₂) ... = f₁.lift (λ s, f₂.lift (λ t, 𝓟 (g₁ s ×ˢ g₂ t))) : by simp only [prod_principal_principal] end prod end filter
e422184527c86f16c8a184e150d994b8ca3c240b
7b66d83f3b69dae0a3dfb684d7ebe5e9e3f3c913
/src/hints/thursday/afternoon/category_theory/exercise1/hint4.lean
5efa0039d182745f944e32c60cc562a4b69fe91f
[]
permissive
dpochekutov/lftcm2020
58a09e10f0e638075b97884d3c2612eb90296adb
cdfbf1ac089f21058e523db73f2476c9c98ed16a
refs/heads/master
1,669,226,265,076
1,594,629,725,000
1,594,629,725,000
279,213,346
1
0
MIT
1,594,622,757,000
1,594,615,843,000
null
UTF-8
Lean
false
false
790
lean
import algebra.category.CommRing import category_theory.yoneda noncomputable theory open category_theory open opposite open polynomial /-! We can "follow our nose" on the two remaining proof obligations, and in both cases we arrive at a result that is "just about polynomials", so we call `extract_goal` and go prove them as lemmas. -/ def CommRing_forget_representable : Σ (R : CommRing), (forget CommRing) ≅ coyoneda.obj (op R) := ⟨CommRing.of (polynomial ℤ), { hom := { app := λ R r, polynomial.eval₂_ring_hom (algebra_map ℤ R) r, naturality' := λ R S f, begin ext r p, dsimp at *, simp, extract_goal, sorry, end, }, inv := { app := λ R f, begin dsimp at f, exact f X, end, }, inv_hom_id' := begin ext R f p, dsimp at *, extract_goal, sorry, end, }⟩
3977e774d6cf5bb6097db545213345a1a4b657ab
aa5a655c05e5359a70646b7154e7cac59f0b4132
/src/Lean/Elab/PreDefinition/Main.lean
4eca00f2726764d1c15d10f5ed0971b07c17600f
[ "Apache-2.0" ]
permissive
lambdaxymox/lean4
ae943c960a42247e06eff25c35338268d07454cb
278d47c77270664ef29715faab467feac8a0f446
refs/heads/master
1,677,891,867,340
1,612,500,005,000
1,612,500,005,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,364
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Elab.PreDefinition.Basic import Lean.Elab.PreDefinition.Structural import Lean.Elab.PreDefinition.WF namespace Lean.Elab open Meta open Term private def addAndCompilePartial (preDefs : Array PreDefinition) : TermElabM Unit := do for preDef in preDefs do trace[Elab.definition]! "processing {preDef.declName}" forallTelescope preDef.type fun xs type => do let inh ← liftM $ mkInhabitantFor preDef.declName xs type trace[Elab.definition]! "inhabitant for {preDef.declName}" addNonRec { preDef with kind := DefKind.«opaque», value := inh } addAndCompilePartialRec preDefs private def isNonRecursive (preDef : PreDefinition) : Bool := Option.isNone $ preDef.value.find? fun | Expr.const declName _ _ => preDef.declName == declName | _ => false private def partitionPreDefs (preDefs : Array PreDefinition) : Array (Array PreDefinition) := let getPreDef := fun declName => (preDefs.find? fun preDef => preDef.declName == declName).get! let vertices := preDefs.toList.map (·.declName) let successorsOf := fun declName => (getPreDef declName).value.foldConsts [] fun declName successors => if preDefs.any fun preDef => preDef.declName == declName then declName :: successors else successors let sccs := SCC.scc vertices successorsOf sccs.toArray.map fun scc => scc.toArray.map getPreDef private def collectMVarsAtPreDef (preDef : PreDefinition) : StateRefT CollectMVars.State MetaM Unit := do collectMVars preDef.value collectMVars preDef.type private def getMVarsAtPreDef (preDef : PreDefinition) : MetaM (Array MVarId) := do let (_, s) ← (collectMVarsAtPreDef preDef).run {} pure s.result private def ensureNoUnassignedMVarsAtPreDef (preDef : PreDefinition) : TermElabM Unit := do let pendingMVarIds ← liftMetaM $ getMVarsAtPreDef preDef if (← logUnassignedUsingErrorInfos pendingMVarIds) then throwAbortCommand def addPreDefinitions (preDefs : Array PreDefinition) : TermElabM Unit := do for preDef in preDefs do trace[Elab.definition.body]! "{preDef.declName} : {preDef.type} :=\n{preDef.value}" for preDef in preDefs do ensureNoUnassignedMVarsAtPreDef preDef for preDefs in partitionPreDefs preDefs do trace[Elab.definition.scc]! "{preDefs.map (·.declName)}" if preDefs.size == 1 && isNonRecursive preDefs[0] then let preDef := preDefs[0] -- TODO: check why we need `true ==` if true == preDef.modifiers.isNoncomputable then addNonRec preDef else addAndCompileNonRec preDef -- TODO: check why we need `true ==` else if true == preDefs.any (·.modifiers.isUnsafe) then addAndCompileUnsafe preDefs else if preDefs.any (·.modifiers.isPartial) then addAndCompilePartial preDefs else withRef (preDefs[0].ref) do mapError (orelseMergeErrors (structuralRecursion preDefs) (WFRecursion preDefs)) (fun msg => let preDefMsgs := preDefs.toList.map (MessageData.ofExpr $ mkConst ·.declName) m!"fail to show termination for{indentD (MessageData.joinSep preDefMsgs Format.line)}\nwith errors\n{msg}") end Lean.Elab
53710f91572d6860c08899c92095e48f1925213e
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/analysis/complex/circle.lean
1be99911891dd9262788acf4f29fb339c1c687c5
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
4,518
lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import analysis.special_functions.exp import topology.continuous_function.basic import analysis.normed.field.unit_ball /-! # The circle > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file defines `circle` to be the metric sphere (`metric.sphere`) in `ℂ` centred at `0` of radius `1`. We equip it with the following structure: * a submonoid of `ℂ` * a group * a topological group We furthermore define `exp_map_circle` to be the natural map `λ t, exp (t * I)` from `ℝ` to `circle`, and show that this map is a group homomorphism. ## Implementation notes Because later (in `geometry.manifold.instances.sphere`) one wants to equip the circle with a smooth manifold structure borrowed from `metric.sphere`, the underlying set is `{z : ℂ | abs (z - 0) = 1}`. This prevents certain algebraic facts from working definitionally -- for example, the circle is not defeq to `{z : ℂ | abs z = 1}`, which is the kernel of `complex.abs` considered as a homomorphism from `ℂ` to `ℝ`, nor is it defeq to `{z : ℂ | norm_sq z = 1}`, which is the kernel of the homomorphism `complex.norm_sq` from `ℂ` to `ℝ`. -/ noncomputable theory open complex metric open_locale complex_conjugate /-- The unit circle in `ℂ`, here given the structure of a submonoid of `ℂ`. -/ def circle : submonoid ℂ := submonoid.unit_sphere ℂ @[simp] lemma mem_circle_iff_abs {z : ℂ} : z ∈ circle ↔ abs z = 1 := mem_sphere_zero_iff_norm lemma circle_def : ↑circle = {z : ℂ | abs z = 1} := set.ext $ λ z, mem_circle_iff_abs @[simp] lemma abs_coe_circle (z : circle) : abs z = 1 := mem_circle_iff_abs.mp z.2 lemma mem_circle_iff_norm_sq {z : ℂ} : z ∈ circle ↔ norm_sq z = 1 := by simp [complex.abs] @[simp] lemma norm_sq_eq_of_mem_circle (z : circle) : norm_sq z = 1 := by simp [norm_sq_eq_abs] lemma ne_zero_of_mem_circle (z : circle) : (z:ℂ) ≠ 0 := ne_zero_of_mem_unit_sphere z instance : comm_group circle := metric.sphere.comm_group @[simp] lemma coe_inv_circle (z : circle) : ↑(z⁻¹) = (z : ℂ)⁻¹ := rfl lemma coe_inv_circle_eq_conj (z : circle) : ↑(z⁻¹) = conj (z : ℂ) := by rw [coe_inv_circle, inv_def, norm_sq_eq_of_mem_circle, inv_one, of_real_one, mul_one] @[simp] lemma coe_div_circle (z w : circle) : ↑(z / w) = (z:ℂ) / w := circle.subtype.map_div z w /-- The elements of the circle embed into the units. -/ def circle.to_units : circle →* units ℂ := unit_sphere_to_units ℂ -- written manually because `@[simps]` was slow and generated the wrong lemma @[simp] lemma circle.to_units_apply (z : circle) : circle.to_units z = units.mk0 z (ne_zero_of_mem_circle z) := rfl instance : compact_space circle := metric.sphere.compact_space _ _ instance : topological_group circle := metric.sphere.topological_group /-- If `z` is a nonzero complex number, then `conj z / z` belongs to the unit circle. -/ @[simps] def circle.of_conj_div_self (z : ℂ) (hz : z ≠ 0) : circle := ⟨conj z / z, mem_circle_iff_abs.2 $ by rw [map_div₀, abs_conj, div_self (complex.abs.ne_zero hz)]⟩ /-- The map `λ t, exp (t * I)` from `ℝ` to the unit circle in `ℂ`. -/ def exp_map_circle : C(ℝ, circle) := { to_fun := λ t, ⟨exp (t * I), by simp [exp_mul_I, abs_cos_add_sin_mul_I]⟩ } @[simp] lemma exp_map_circle_apply (t : ℝ) : ↑(exp_map_circle t) = complex.exp (t * complex.I) := rfl @[simp] lemma exp_map_circle_zero : exp_map_circle 0 = 1 := subtype.ext $ by rw [exp_map_circle_apply, of_real_zero, zero_mul, exp_zero, submonoid.coe_one] @[simp] lemma exp_map_circle_add (x y : ℝ) : exp_map_circle (x + y) = exp_map_circle x * exp_map_circle y := subtype.ext $ by simp only [exp_map_circle_apply, submonoid.coe_mul, of_real_add, add_mul, complex.exp_add] /-- The map `λ t, exp (t * I)` from `ℝ` to the unit circle in `ℂ`, considered as a homomorphism of groups. -/ @[simps] def exp_map_circle_hom : ℝ →+ (additive circle) := { to_fun := additive.of_mul ∘ exp_map_circle, map_zero' := exp_map_circle_zero, map_add' := exp_map_circle_add } @[simp] lemma exp_map_circle_sub (x y : ℝ) : exp_map_circle (x - y) = exp_map_circle x / exp_map_circle y := exp_map_circle_hom.map_sub x y @[simp] lemma exp_map_circle_neg (x : ℝ) : exp_map_circle (-x) = (exp_map_circle x)⁻¹ := exp_map_circle_hom.map_neg x
cc5f04681d31cffae52ef74ed0c27eea756c43de
737dc4b96c97368cb66b925eeea3ab633ec3d702
/src/Lean/Expr.lean
1239b2641869ac159a7191b7f1120e9637641bfa
[ "Apache-2.0" ]
permissive
Bioye97/lean4
1ace34638efd9913dc5991443777b01a08983289
bc3900cbb9adda83eed7e6affeaade7cfd07716d
refs/heads/master
1,690,589,820,211
1,631,051,000,000
1,631,067,598,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
39,580
lean
/- Copyright (c) 2018 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Data.KVMap import Lean.Level namespace Lean inductive Literal where | natVal (val : Nat) | strVal (val : String) deriving Inhabited, BEq, Repr protected def Literal.hash : Literal → UInt64 | Literal.natVal v => hash v | Literal.strVal v => hash v instance : Hashable Literal := ⟨Literal.hash⟩ def Literal.lt : Literal → Literal → Bool | Literal.natVal _, Literal.strVal _ => true | Literal.natVal v₁, Literal.natVal v₂ => v₁ < v₂ | Literal.strVal v₁, Literal.strVal v₂ => v₁ < v₂ | _, _ => false instance : LT Literal := ⟨fun a b => a.lt b⟩ instance (a b : Literal) : Decidable (a < b) := inferInstanceAs (Decidable (a.lt b)) inductive BinderInfo where | default | implicit | strictImplicit | instImplicit | auxDecl deriving Inhabited, BEq, Repr def BinderInfo.hash : BinderInfo → UInt64 | BinderInfo.default => 947 | BinderInfo.implicit => 1019 | BinderInfo.strictImplicit => 1087 | BinderInfo.instImplicit => 1153 | BinderInfo.auxDecl => 1229 def BinderInfo.isExplicit : BinderInfo → Bool | BinderInfo.implicit => false | BinderInfo.strictImplicit => false | BinderInfo.instImplicit => false | _ => true instance : Hashable BinderInfo := ⟨BinderInfo.hash⟩ def BinderInfo.isInstImplicit : BinderInfo → Bool | BinderInfo.instImplicit => true | _ => false def BinderInfo.isImplicit : BinderInfo → Bool | BinderInfo.implicit => true | _ => false def BinderInfo.isStrictImplicit : BinderInfo → Bool | BinderInfo.strictImplicit => true | _ => false def BinderInfo.isAuxDecl : BinderInfo → Bool | BinderInfo.auxDecl => true | _ => false abbrev MData := KVMap abbrev MData.empty : MData := {} /-- Cached hash code, cached results, and other data for `Expr`. hash : 32-bits hasFVar : 1-bit hasExprMVar : 1-bit hasLevelMVar : 1-bit hasLevelParam : 1-bit nonDepLet : 1-bit binderInfo : 3-bits approxDepth : 8-bits -- the approximate depth is used to minimize the number of hash collisions looseBVarRange : 16-bits -/ def Expr.Data := UInt64 instance: Inhabited Expr.Data := inferInstanceAs (Inhabited UInt64) def Expr.Data.hash (c : Expr.Data) : UInt64 := c.toUInt32.toUInt64 instance : BEq Expr.Data where beq (a b : UInt64) := a == b def Expr.Data.approxDepth (c : Expr.Data) : UInt8 := ((c.shiftRight 40).land 255).toUInt8 def Expr.Data.looseBVarRange (c : Expr.Data) : UInt32 := (c.shiftRight 48).toUInt32 def Expr.Data.hasFVar (c : Expr.Data) : Bool := ((c.shiftRight 32).land 1) == 1 def Expr.Data.hasExprMVar (c : Expr.Data) : Bool := ((c.shiftRight 33).land 1) == 1 def Expr.Data.hasLevelMVar (c : Expr.Data) : Bool := ((c.shiftRight 34).land 1) == 1 def Expr.Data.hasLevelParam (c : Expr.Data) : Bool := ((c.shiftRight 35).land 1) == 1 def Expr.Data.nonDepLet (c : Expr.Data) : Bool := ((c.shiftRight 36).land 1) == 1 @[extern c inline "(uint8_t)((#1 << 24) >> 61)"] def Expr.Data.binderInfo (c : Expr.Data) : BinderInfo := let bi := (c.shiftLeft 24).shiftRight 61 if bi == 0 then BinderInfo.default else if bi == 1 then BinderInfo.implicit else if bi == 2 then BinderInfo.strictImplicit else if bi == 3 then BinderInfo.instImplicit else BinderInfo.auxDecl @[extern c inline "(uint64_t)#1"] def BinderInfo.toUInt64 : BinderInfo → UInt64 | BinderInfo.default => 0 | BinderInfo.implicit => 1 | BinderInfo.strictImplicit => 2 | BinderInfo.instImplicit => 3 | BinderInfo.auxDecl => 4 @[inline] private def Expr.mkDataCore (h : UInt64) (looseBVarRange : Nat) (approxDepth : UInt8) (hasFVar hasExprMVar hasLevelMVar hasLevelParam nonDepLet : Bool) (bi : BinderInfo) : Expr.Data := if looseBVarRange > Nat.pow 2 24 - 1 then panic! "bound variable index is too big" else let r : UInt64 := h.toUInt32.toUInt64 + hasFVar.toUInt64.shiftLeft 32 + hasExprMVar.toUInt64.shiftLeft 33 + hasLevelMVar.toUInt64.shiftLeft 34 + hasLevelParam.toUInt64.shiftLeft 35 + nonDepLet.toUInt64.shiftLeft 36 + bi.toUInt64.shiftLeft 37 + approxDepth.toUInt64.shiftLeft 40 + looseBVarRange.toUInt64.shiftLeft 48 r def Expr.mkData (h : UInt64) (looseBVarRange : Nat := 0) (approxDepth : UInt8 := 0) (hasFVar hasExprMVar hasLevelMVar hasLevelParam : Bool := false) : Expr.Data := Expr.mkDataCore h looseBVarRange approxDepth hasFVar hasExprMVar hasLevelMVar hasLevelParam false BinderInfo.default def Expr.mkDataForBinder (h : UInt64) (looseBVarRange : Nat) (approxDepth : UInt8) (hasFVar hasExprMVar hasLevelMVar hasLevelParam : Bool) (bi : BinderInfo) : Expr.Data := Expr.mkDataCore h looseBVarRange approxDepth hasFVar hasExprMVar hasLevelMVar hasLevelParam false bi def Expr.mkDataForLet (h : UInt64) (looseBVarRange : Nat) (approxDepth : UInt8) (hasFVar hasExprMVar hasLevelMVar hasLevelParam nonDepLet : Bool) : Expr.Data := Expr.mkDataCore h looseBVarRange approxDepth hasFVar hasExprMVar hasLevelMVar hasLevelParam nonDepLet BinderInfo.default open Expr structure FVarId where name : Name deriving Inhabited, BEq, Hashable instance : Repr FVarId where reprPrec n p := reprPrec n.name p def FVarIdSet := Std.RBTree FVarId (Name.quickCmp ·.name ·.name) deriving Inhabited, EmptyCollection instance : ForIn m FVarIdSet FVarId := inferInstanceAs (ForIn _ (Std.RBTree ..) ..) def FVarIdHashSet := Std.HashSet FVarId deriving Inhabited, EmptyCollection def FVarIdMap (α : Type) := Std.RBMap FVarId α (Name.quickCmp ·.name ·.name) instance : EmptyCollection (FVarIdMap α) := inferInstanceAs (EmptyCollection (Std.RBMap ..)) instance : Inhabited (FVarIdMap α) where default := {} /- We use the `E` suffix (short for `Expr`) to avoid collision with keywords. We considered using «...», but it is too inconvenient to use. -/ inductive Expr where | bvar : Nat → Data → Expr -- bound variables | fvar : FVarId → Data → Expr -- free variables | mvar : MVarId → Data → Expr -- meta variables | sort : Level → Data → Expr -- Sort | const : Name → List Level → Data → Expr -- constants | app : Expr → Expr → Data → Expr -- application | lam : Name → Expr → Expr → Data → Expr -- lambda abstraction | forallE : Name → Expr → Expr → Data → Expr -- (dependent) arrow | letE : Name → Expr → Expr → Expr → Data → Expr -- let expressions | lit : Literal → Data → Expr -- literals | mdata : MData → Expr → Data → Expr -- metadata | proj : Name → Nat → Expr → Data → Expr -- projection deriving Inhabited namespace Expr @[inline] def data : Expr → Data | bvar _ d => d | fvar _ d => d | mvar _ d => d | sort _ d => d | const _ _ d => d | app _ _ d => d | lam _ _ _ d => d | forallE _ _ _ d => d | letE _ _ _ _ d => d | lit _ d => d | mdata _ _ d => d | proj _ _ _ d => d def ctorName : Expr → String | bvar _ _ => "bvar" | fvar _ _ => "fvar" | mvar _ _ => "mvar" | sort _ _ => "sort" | const _ _ _ => "const" | app _ _ _ => "app" | lam _ _ _ _ => "lam" | forallE _ _ _ _ => "forallE" | letE _ _ _ _ _ => "letE" | lit _ _ => "lit" | mdata _ _ _ => "mdata" | proj _ _ _ _ => "proj" protected def hash (e : Expr) : UInt64 := e.data.hash instance : Hashable Expr := ⟨Expr.hash⟩ def hasFVar (e : Expr) : Bool := e.data.hasFVar def hasExprMVar (e : Expr) : Bool := e.data.hasExprMVar def hasLevelMVar (e : Expr) : Bool := e.data.hasLevelMVar def hasMVar (e : Expr) : Bool := let d := e.data d.hasExprMVar || d.hasLevelMVar def hasLevelParam (e : Expr) : Bool := e.data.hasLevelParam def approxDepth (e : Expr) : UInt8 := e.data.approxDepth def looseBVarRange (e : Expr) : Nat := e.data.looseBVarRange.toNat def binderInfo (e : Expr) : BinderInfo := e.data.binderInfo @[export lean_expr_hash] def hashEx : Expr → UInt64 := hash @[export lean_expr_has_fvar] def hasFVarEx : Expr → Bool := hasFVar @[export lean_expr_has_expr_mvar] def hasExprMVarEx : Expr → Bool := hasExprMVar @[export lean_expr_has_level_mvar] def hasLevelMVarEx : Expr → Bool := hasLevelMVar @[export lean_expr_has_mvar] def hasMVarEx : Expr → Bool := hasMVar @[export lean_expr_has_level_param] def hasLevelParamEx : Expr → Bool := hasLevelParam @[export lean_expr_loose_bvar_range] def looseBVarRangeEx (e : Expr) : UInt32 := e.data.looseBVarRange @[export lean_expr_binder_info] def binderInfoEx : Expr → BinderInfo := binderInfo end Expr def mkConst (n : Name) (lvls : List Level := []) : Expr := Expr.const n lvls $ mkData (mixHash 5 $ mixHash (hash n) (hash lvls)) 0 0 false false (lvls.any Level.hasMVar) (lvls.any Level.hasParam) def Literal.type : Literal → Expr | Literal.natVal _ => mkConst `Nat | Literal.strVal _ => mkConst `String @[export lean_lit_type] def Literal.typeEx : Literal → Expr := Literal.type def mkBVar (idx : Nat) : Expr := Expr.bvar idx $ mkData (mixHash 7 $ hash idx) (idx+1) def mkSort (lvl : Level) : Expr := Expr.sort lvl $ mkData (mixHash 11 $ hash lvl) 0 0 false false lvl.hasMVar lvl.hasParam def mkFVar (fvarId : FVarId) : Expr := Expr.fvar fvarId $ mkData (mixHash 13 $ hash fvarId) 0 0 true def mkMVar (fvarId : MVarId) : Expr := Expr.mvar fvarId $ mkData (mixHash 17 $ hash fvarId) 0 0 false true def mkMData (m : MData) (e : Expr) : Expr := let d := e.approxDepth+1 Expr.mdata m e $ mkData (mixHash d.toUInt64 $ hash e) e.looseBVarRange d e.hasFVar e.hasExprMVar e.hasLevelMVar e.hasLevelParam def mkProj (s : Name) (i : Nat) (e : Expr) : Expr := let d := e.approxDepth+1 Expr.proj s i e $ mkData (mixHash d.toUInt64 $ mixHash (hash s) $ mixHash (hash i) (hash e)) e.looseBVarRange d e.hasFVar e.hasExprMVar e.hasLevelMVar e.hasLevelParam def mkApp (f a : Expr) : Expr := let d := (max f.approxDepth a.approxDepth) + 1 Expr.app f a $ mkData (mixHash d.toUInt64 $ mixHash (hash f) (hash a)) (max f.looseBVarRange a.looseBVarRange) d (f.hasFVar || a.hasFVar) (f.hasExprMVar || a.hasExprMVar) (f.hasLevelMVar || a.hasLevelMVar) (f.hasLevelParam || a.hasLevelParam) def mkLambda (x : Name) (bi : BinderInfo) (t : Expr) (b : Expr) : Expr := let d := (max t.approxDepth b.approxDepth) + 1 -- let x := x.eraseMacroScopes Expr.lam x t b $ mkDataForBinder (mixHash d.toUInt64 $ mixHash (hash t) (hash b)) (max t.looseBVarRange (b.looseBVarRange - 1)) d (t.hasFVar || b.hasFVar) (t.hasExprMVar || b.hasExprMVar) (t.hasLevelMVar || b.hasLevelMVar) (t.hasLevelParam || b.hasLevelParam) bi def mkForall (x : Name) (bi : BinderInfo) (t : Expr) (b : Expr) : Expr := let d := (max t.approxDepth b.approxDepth) + 1 -- let x := x.eraseMacroScopes Expr.forallE x t b $ mkDataForBinder (mixHash d.toUInt64 $ mixHash (hash t) (hash b)) (max t.looseBVarRange (b.looseBVarRange - 1)) d (t.hasFVar || b.hasFVar) (t.hasExprMVar || b.hasExprMVar) (t.hasLevelMVar || b.hasLevelMVar) (t.hasLevelParam || b.hasLevelParam) bi /- Return `Unit -> type`. Do not confuse with `Thunk type` -/ def mkSimpleThunkType (type : Expr) : Expr := mkForall Name.anonymous BinderInfo.default (Lean.mkConst `Unit) type /- Return `fun (_ : Unit), e` -/ def mkSimpleThunk (type : Expr) : Expr := mkLambda `_ BinderInfo.default (Lean.mkConst `Unit) type def mkLet (x : Name) (t : Expr) (v : Expr) (b : Expr) (nonDep : Bool := false) : Expr := let d := (max (max t.approxDepth v.approxDepth) b.approxDepth) + 1 -- let x := x.eraseMacroScopes Expr.letE x t v b $ mkDataForLet (mixHash d.toUInt64 $ mixHash (hash t) $ mixHash (hash v) (hash b)) (max (max t.looseBVarRange v.looseBVarRange) (b.looseBVarRange - 1)) d (t.hasFVar || v.hasFVar || b.hasFVar) (t.hasExprMVar || v.hasExprMVar || b.hasExprMVar) (t.hasLevelMVar || v.hasLevelMVar || b.hasLevelMVar) (t.hasLevelParam || v.hasLevelParam || b.hasLevelParam) nonDep def mkAppB (f a b : Expr) := mkApp (mkApp f a) b def mkApp2 (f a b : Expr) := mkAppB f a b def mkApp3 (f a b c : Expr) := mkApp (mkAppB f a b) c def mkApp4 (f a b c d : Expr) := mkAppB (mkAppB f a b) c d def mkApp5 (f a b c d e : Expr) := mkApp (mkApp4 f a b c d) e def mkApp6 (f a b c d e₁ e₂ : Expr) := mkAppB (mkApp4 f a b c d) e₁ e₂ def mkApp7 (f a b c d e₁ e₂ e₃ : Expr) := mkApp3 (mkApp4 f a b c d) e₁ e₂ e₃ def mkApp8 (f a b c d e₁ e₂ e₃ e₄ : Expr) := mkApp4 (mkApp4 f a b c d) e₁ e₂ e₃ e₄ def mkApp9 (f a b c d e₁ e₂ e₃ e₄ e₅ : Expr) := mkApp5 (mkApp4 f a b c d) e₁ e₂ e₃ e₄ e₅ def mkApp10 (f a b c d e₁ e₂ e₃ e₄ e₅ e₆ : Expr) := mkApp6 (mkApp4 f a b c d) e₁ e₂ e₃ e₄ e₅ e₆ def mkLit (l : Literal) : Expr := Expr.lit l $ mkData (mixHash 3 (hash l)) def mkRawNatLit (n : Nat) : Expr := mkLit (Literal.natVal n) def mkNatLit (n : Nat) : Expr := let r := mkRawNatLit n mkApp3 (mkConst ``OfNat.ofNat [levelZero]) (mkConst ``Nat) r (mkApp (mkConst ``instOfNatNat) r) def mkStrLit (s : String) : Expr := mkLit (Literal.strVal s) @[export lean_expr_mk_bvar] def mkBVarEx : Nat → Expr := mkBVar @[export lean_expr_mk_fvar] def mkFVarEx : FVarId → Expr := mkFVar @[export lean_expr_mk_mvar] def mkMVarEx : MVarId → Expr := mkMVar @[export lean_expr_mk_sort] def mkSortEx : Level → Expr := mkSort @[export lean_expr_mk_const] def mkConstEx (c : Name) (lvls : List Level) : Expr := mkConst c lvls @[export lean_expr_mk_app] def mkAppEx : Expr → Expr → Expr := mkApp @[export lean_expr_mk_lambda] def mkLambdaEx (n : Name) (d b : Expr) (bi : BinderInfo) : Expr := mkLambda n bi d b @[export lean_expr_mk_forall] def mkForallEx (n : Name) (d b : Expr) (bi : BinderInfo) : Expr := mkForall n bi d b @[export lean_expr_mk_let] def mkLetEx (n : Name) (t v b : Expr) : Expr := mkLet n t v b @[export lean_expr_mk_lit] def mkLitEx : Literal → Expr := mkLit @[export lean_expr_mk_mdata] def mkMDataEx : MData → Expr → Expr := mkMData @[export lean_expr_mk_proj] def mkProjEx : Name → Nat → Expr → Expr := mkProj def mkAppN (f : Expr) (args : Array Expr) : Expr := args.foldl mkApp f private partial def mkAppRangeAux (n : Nat) (args : Array Expr) (i : Nat) (e : Expr) : Expr := if i < n then mkAppRangeAux n args (i+1) (mkApp e (args.get! i)) else e /-- `mkAppRange f i j #[a_1, ..., a_i, ..., a_j, ... ]` ==> the expression `f a_i ... a_{j-1}` -/ def mkAppRange (f : Expr) (i j : Nat) (args : Array Expr) : Expr := mkAppRangeAux j args i f def mkAppRev (fn : Expr) (revArgs : Array Expr) : Expr := revArgs.foldr (fun a r => mkApp r a) fn namespace Expr -- TODO: implement it in Lean @[extern "lean_expr_dbg_to_string"] constant dbgToString (e : @& Expr) : String @[extern "lean_expr_quick_lt"] constant quickLt (a : @& Expr) (b : @& Expr) : Bool @[extern "lean_expr_lt"] constant lt (a : @& Expr) (b : @& Expr) : Bool /- Return true iff `a` and `b` are alpha equivalent. Binder annotations are ignored. -/ @[extern "lean_expr_eqv"] constant eqv (a : @& Expr) (b : @& Expr) : Bool instance : BEq Expr where beq := Expr.eqv /- Return true iff `a` and `b` are equal. Binder names and annotations are taking into account. -/ @[extern "lean_expr_equal"] constant equal (a : @& Expr) (b : @& Expr) : Bool def isSort : Expr → Bool | sort _ _ => true | _ => false def isProp : Expr → Bool | sort (Level.zero ..) _ => true | _ => false def isBVar : Expr → Bool | bvar _ _ => true | _ => false def isMVar : Expr → Bool | mvar _ _ => true | _ => false def isFVar : Expr → Bool | fvar _ _ => true | _ => false def isApp : Expr → Bool | app .. => true | _ => false def isProj : Expr → Bool | proj .. => true | _ => false def isConst : Expr → Bool | const .. => true | _ => false def isConstOf : Expr → Name → Bool | const n _ _, m => n == m | _, _ => false def isForall : Expr → Bool | forallE .. => true | _ => false def isLambda : Expr → Bool | lam .. => true | _ => false def isBinding : Expr → Bool | lam .. => true | forallE .. => true | _ => false def isLet : Expr → Bool | letE .. => true | _ => false def isMData : Expr → Bool | mdata .. => true | _ => false def isLit : Expr → Bool | lit .. => true | _ => false def getForallBody : Expr → Expr | forallE _ _ b .. => getForallBody b | e => e def getAppFn : Expr → Expr | app f a _ => getAppFn f | e => e def getAppNumArgsAux : Expr → Nat → Nat | app f a _, n => getAppNumArgsAux f (n+1) | e, n => n def getAppNumArgs (e : Expr) : Nat := getAppNumArgsAux e 0 private def getAppArgsAux : Expr → Array Expr → Nat → Array Expr | app f a _, as, i => getAppArgsAux f (as.set! i a) (i-1) | _, as, _ => as @[inline] def getAppArgs (e : Expr) : Array Expr := let dummy := mkSort levelZero let nargs := e.getAppNumArgs getAppArgsAux e (mkArray nargs dummy) (nargs-1) private def getAppRevArgsAux : Expr → Array Expr → Array Expr | app f a _, as => getAppRevArgsAux f (as.push a) | _, as => as @[inline] def getAppRevArgs (e : Expr) : Array Expr := getAppRevArgsAux e (Array.mkEmpty e.getAppNumArgs) @[specialize] def withAppAux (k : Expr → Array Expr → α) : Expr → Array Expr → Nat → α | app f a _, as, i => withAppAux k f (as.set! i a) (i-1) | f, as, i => k f as @[inline] def withApp (e : Expr) (k : Expr → Array Expr → α) : α := let dummy := mkSort levelZero let nargs := e.getAppNumArgs withAppAux k e (mkArray nargs dummy) (nargs-1) @[specialize] private def withAppRevAux (k : Expr → Array Expr → α) : Expr → Array Expr → α | app f a _, as => withAppRevAux k f (as.push a) | f, as => k f as @[inline] def withAppRev (e : Expr) (k : Expr → Array Expr → α) : α := withAppRevAux k e (Array.mkEmpty e.getAppNumArgs) def getRevArgD : Expr → Nat → Expr → Expr | app f a _, 0, _ => a | app f _ _, i+1, v => getRevArgD f i v | _, _, v => v def getRevArg! : Expr → Nat → Expr | app f a _, 0 => a | app f _ _, i+1 => getRevArg! f i | _, _ => panic! "invalid index" @[inline] def getArg! (e : Expr) (i : Nat) (n := e.getAppNumArgs) : Expr := getRevArg! e (n - i - 1) @[inline] def getArgD (e : Expr) (i : Nat) (v₀ : Expr) (n := e.getAppNumArgs) : Expr := getRevArgD e (n - i - 1) v₀ def isAppOf (e : Expr) (n : Name) : Bool := match e.getAppFn with | const c _ _ => c == n | _ => false def isAppOfArity : Expr → Name → Nat → Bool | const c _ _, n, 0 => c == n | app f _ _, n, a+1 => isAppOfArity f n a | _, _, _ => false def appFn! : Expr → Expr | app f _ _ => f | _ => panic! "application expected" def appArg! : Expr → Expr | app _ a _ => a | _ => panic! "application expected" def isNatLit : Expr → Bool | lit (Literal.natVal _) _ => true | _ => false def natLit? : Expr → Option Nat | lit (Literal.natVal v) _ => v | _ => none def isStringLit : Expr → Bool | lit (Literal.strVal _) _ => true | _ => false def isCharLit (e : Expr) : Bool := e.isAppOfArity `Char.ofNat 1 && e.appArg!.isNatLit def constName! : Expr → Name | const n _ _ => n | _ => panic! "constant expected" def constName? : Expr → Option Name | const n _ _ => some n | _ => none def constLevels! : Expr → List Level | const _ ls _ => ls | _ => panic! "constant expected" def bvarIdx! : Expr → Nat | bvar idx _ => idx | _ => panic! "bvar expected" def fvarId! : Expr → FVarId | fvar n _ => n | _ => panic! "fvar expected" def mvarId! : Expr → MVarId | mvar n _ => n | _ => panic! "mvar expected" def bindingName! : Expr → Name | forallE n _ _ _ => n | lam n _ _ _ => n | _ => panic! "binding expected" def bindingDomain! : Expr → Expr | forallE _ d _ _ => d | lam _ d _ _ => d | _ => panic! "binding expected" def bindingBody! : Expr → Expr | forallE _ _ b _ => b | lam _ _ b _ => b | _ => panic! "binding expected" def bindingInfo! : Expr → BinderInfo | forallE _ _ _ c => c.binderInfo | lam _ _ _ c => c.binderInfo | _ => panic! "binding expected" def letName! : Expr → Name | letE n _ _ _ _ => n | _ => panic! "let expression expected" def consumeMData : Expr → Expr | mdata _ e _ => consumeMData e | e => e def mdataExpr! : Expr → Expr | mdata _ e _ => e | _ => panic! "mdata expression expected" def hasLooseBVars (e : Expr) : Bool := e.looseBVarRange > 0 /- Remark: the following function assumes `e` does not have loose bound variables. -/ def isArrow (e : Expr) : Bool := match e with | forallE _ _ b _ => !b.hasLooseBVars | _ => false @[extern "lean_expr_has_loose_bvar"] constant hasLooseBVar (e : @& Expr) (bvarIdx : @& Nat) : Bool /-- Return true if `e` contains the loose bound variable `bvarIdx` in an explicit parameter, or in the range if `tryRange == true`. -/ def hasLooseBVarInExplicitDomain : Expr → Nat → Bool → Bool | Expr.forallE _ d b c, bvarIdx, tryRange => (c.binderInfo.isExplicit && hasLooseBVar d bvarIdx) || hasLooseBVarInExplicitDomain b (bvarIdx+1) tryRange | e, bvarIdx, tryRange => tryRange && hasLooseBVar e bvarIdx /-- Lower the loose bound variables `>= s` in `e` by `d`. That is, a loose bound variable `bvar i`. `i >= s` is mapped into `bvar (i-d)`. Remark: if `s < d`, then result is `e` -/ @[extern "lean_expr_lower_loose_bvars"] constant lowerLooseBVars (e : @& Expr) (s d : @& Nat) : Expr /-- Lift loose bound variables `>= s` in `e` by `d`. -/ @[extern "lean_expr_lift_loose_bvars"] constant liftLooseBVars (e : @& Expr) (s d : @& Nat) : Expr /-- `inferImplicit e numParams considerRange` updates the first `numParams` parameter binder annotations of the `e` forall type. It marks any parameter with an explicit binder annotation if there is another explicit arguments that depends on it or the resulting type if `considerRange == true`. Remark: we use this function to infer the bind annotations of inductive datatype constructors, and structure projections. When the `{}` annotation is used in these commands, we set `considerRange == false`. -/ def inferImplicit : Expr → Nat → Bool → Expr | Expr.forallE n d b c, i+1, considerRange => let b := inferImplicit b i considerRange let newInfo := if c.binderInfo.isExplicit && hasLooseBVarInExplicitDomain b 0 considerRange then BinderInfo.implicit else c.binderInfo mkForall n newInfo d b | e, 0, _ => e | e, _, _ => e /-- Instantiate the loose bound variables in `e` using `subst`. That is, a loose `Expr.bvar i` is replaced with `subst[i]`. -/ @[extern "lean_expr_instantiate"] constant instantiate (e : @& Expr) (subst : @& Array Expr) : Expr @[extern "lean_expr_instantiate1"] constant instantiate1 (e : @& Expr) (subst : @& Expr) : Expr /-- Similar to instantiate, but `Expr.bvar i` is replaced with `subst[subst.size - i - 1]` -/ @[extern "lean_expr_instantiate_rev"] constant instantiateRev (e : @& Expr) (subst : @& Array Expr) : Expr /-- Similar to `instantiate`, but consider only the variables `xs` in the range `[beginIdx, endIdx)`. Function panics if `beginIdx <= endIdx <= xs.size` does not hold. -/ @[extern "lean_expr_instantiate_range"] constant instantiateRange (e : @& Expr) (beginIdx endIdx : @& Nat) (xs : @& Array Expr) : Expr /-- Similar to `instantiateRev`, but consider only the variables `xs` in the range `[beginIdx, endIdx)`. Function panics if `beginIdx <= endIdx <= xs.size` does not hold. -/ @[extern "lean_expr_instantiate_rev_range"] constant instantiateRevRange (e : @& Expr) (beginIdx endIdx : @& Nat) (xs : @& Array Expr) : Expr /-- Replace free variables `xs` with loose bound variables. -/ @[extern "lean_expr_abstract"] constant abstract (e : @& Expr) (xs : @& Array Expr) : Expr /-- Similar to `abstract`, but consider only the first `min n xs.size` entries in `xs`. -/ @[extern "lean_expr_abstract_range"] constant abstractRange (e : @& Expr) (n : @& Nat) (xs : @& Array Expr) : Expr /-- Replace occurrences of the free variable `fvar` in `e` with `v` -/ def replaceFVar (e : Expr) (fvar : Expr) (v : Expr) : Expr := (e.abstract #[fvar]).instantiate1 v /-- Replace occurrences of the free variable `fvarId` in `e` with `v` -/ def replaceFVarId (e : Expr) (fvarId : FVarId) (v : Expr) : Expr := replaceFVar e (mkFVar fvarId) v /-- Replace occurrences of the free variables `fvars` in `e` with `vs` -/ def replaceFVars (e : Expr) (fvars : Array Expr) (vs : Array Expr) : Expr := (e.abstract fvars).instantiateRev vs instance : ToString Expr where toString := Expr.dbgToString def isAtomic : Expr → Bool | Expr.const _ _ _ => true | Expr.sort _ _ => true | Expr.bvar _ _ => true | Expr.lit _ _ => true | Expr.mvar _ _ => true | Expr.fvar _ _ => true | _ => false end Expr def mkDecIsTrue (pred proof : Expr) := mkAppB (mkConst `Decidable.isTrue) pred proof def mkDecIsFalse (pred proof : Expr) := mkAppB (mkConst `Decidable.isFalse) pred proof open Std (HashMap HashSet PHashMap PHashSet) abbrev ExprMap (α : Type) := HashMap Expr α abbrev PersistentExprMap (α : Type) := PHashMap Expr α abbrev ExprSet := HashSet Expr abbrev PersistentExprSet := PHashSet Expr abbrev PExprSet := PersistentExprSet /- Auxiliary type for forcing `==` to be structural equality for `Expr` -/ structure ExprStructEq where val : Expr deriving Inhabited instance : Coe Expr ExprStructEq := ⟨ExprStructEq.mk⟩ namespace ExprStructEq protected def beq : ExprStructEq → ExprStructEq → Bool | ⟨e₁⟩, ⟨e₂⟩ => Expr.equal e₁ e₂ protected def hash : ExprStructEq → UInt64 | ⟨e⟩ => e.hash instance : BEq ExprStructEq := ⟨ExprStructEq.beq⟩ instance : Hashable ExprStructEq := ⟨ExprStructEq.hash⟩ instance : ToString ExprStructEq := ⟨fun e => toString e.val⟩ end ExprStructEq abbrev ExprStructMap (α : Type) := HashMap ExprStructEq α abbrev PersistentExprStructMap (α : Type) := PHashMap ExprStructEq α namespace Expr private partial def mkAppRevRangeAux (revArgs : Array Expr) (start : Nat) (b : Expr) (i : Nat) : Expr := if i == start then b else let i := i - 1 mkAppRevRangeAux revArgs start (mkApp b (revArgs.get! i)) i /-- `mkAppRevRange f b e args == mkAppRev f (revArgs.extract b e)` -/ def mkAppRevRange (f : Expr) (beginIdx endIdx : Nat) (revArgs : Array Expr) : Expr := mkAppRevRangeAux revArgs beginIdx f endIdx private def betaRevAux (revArgs : Array Expr) (sz : Nat) : Expr → Nat → Expr | Expr.lam _ _ b _, i => if i + 1 < sz then betaRevAux revArgs sz b (i+1) else let n := sz - (i + 1) mkAppRevRange (b.instantiateRange n sz revArgs) 0 n revArgs | Expr.mdata _ b _, i => betaRevAux revArgs sz b i | b, i => let n := sz - i mkAppRevRange (b.instantiateRange n sz revArgs) 0 n revArgs /-- If `f` is a lambda expression, than "beta-reduce" it using `revArgs`. This function is often used with `getAppRev` or `withAppRev`. Examples: - `betaRev (fun x y => t x y) #[]` ==> `fun x y => t x y` - `betaRev (fun x y => t x y) #[a]` ==> `fun y => t a y` - `betaRev (fun x y => t x y) #[a, b]` ==> t b a` - `betaRev (fun x y => t x y) #[a, b, c, d]` ==> t d c b a` Suppose `t` is `(fun x y => t x y) a b c d`, then `args := t.getAppRev` is `#[d, c, b, a]`, and `betaRev (fun x y => t x y) #[d, c, b, a]` is `t a b c d`. -/ def betaRev (f : Expr) (revArgs : Array Expr) : Expr := if revArgs.size == 0 then f else betaRevAux revArgs revArgs.size f 0 def isHeadBetaTargetFn : Expr → Bool | Expr.lam _ _ _ _ => true | Expr.mdata _ b _ => isHeadBetaTargetFn b | _ => false def headBeta (e : Expr) : Expr := let f := e.getAppFn if f.isHeadBetaTargetFn then betaRev f e.getAppRevArgs else e def isHeadBetaTarget (e : Expr) : Bool := e.getAppFn.isHeadBetaTargetFn private def etaExpandedBody : Expr → Nat → Nat → Option Expr | app f (bvar j _) _, n+1, i => if j == i then etaExpandedBody f n (i+1) else none | _, n+1, _ => none | f, 0, _ => if f.hasLooseBVars then none else some f private def etaExpandedAux : Expr → Nat → Option Expr | lam _ _ b _, n => etaExpandedAux b (n+1) | e, n => etaExpandedBody e n 0 /-- If `e` is of the form `(fun x₁ ... xₙ => f x₁ ... xₙ)` and `f` does not contain `x₁`, ..., `xₙ`, then return `some f`. Otherwise, return `none`. It assumes `e` does not have loose bound variables. Remark: `ₙ` may be 0 -/ def etaExpanded? (e : Expr) : Option Expr := etaExpandedAux e 0 /-- Similar to `etaExpanded?`, but only succeeds if `ₙ ≥ 1`. -/ def etaExpandedStrict? : Expr → Option Expr | lam _ _ b _ => etaExpandedAux b 1 | _ => none def getOptParamDefault? (e : Expr) : Option Expr := if e.isAppOfArity `optParam 2 then some e.appArg! else none def getAutoParamTactic? (e : Expr) : Option Expr := if e.isAppOfArity `autoParam 2 then some e.appArg! else none def isOptParam (e : Expr) : Bool := e.isAppOfArity `optParam 2 def isAutoParam (e : Expr) : Bool := e.isAppOfArity `autoParam 2 /-- Return true iff `e` contains a free variable which statisfies `p`. -/ @[inline] def hasAnyFVar (e : Expr) (p : FVarId → Bool) : Bool := let rec @[specialize] visit (e : Expr) := if !e.hasFVar then false else match e with | Expr.forallE _ d b _ => visit d || visit b | Expr.lam _ d b _ => visit d || visit b | Expr.mdata _ e _ => visit e | Expr.letE _ t v b _ => visit t || visit v || visit b | Expr.app f a _ => visit f || visit a | Expr.proj _ _ e _ => visit e | e@(Expr.fvar fvarId _) => p fvarId | e => false visit e def containsFVar (e : Expr) (fvarId : FVarId) : Bool := e.hasAnyFVar (· == fvarId) /- The update functions here are defined using C code. They will try to avoid allocating new values using pointer equality. The hypotheses `(h : e.is...)` are used to ensure Lean will not crash at runtime. The `update*!` functions are inlined and provide a convenient way of using the update proofs without providing proofs. Note that if they are used under a match-expression, the compiler will eliminate the double-match. -/ @[extern "lean_expr_update_app"] def updateApp (e : Expr) (newFn : Expr) (newArg : Expr) (h : e.isApp) : Expr := mkApp newFn newArg @[inline] def updateApp! (e : Expr) (newFn : Expr) (newArg : Expr) : Expr := match e with | app fn arg c => updateApp (app fn arg c) newFn newArg rfl | _ => panic! "application expected" @[extern "lean_expr_update_const"] def updateConst (e : Expr) (newLevels : List Level) (h : e.isConst) : Expr := mkConst e.constName! newLevels @[inline] def updateConst! (e : Expr) (newLevels : List Level) : Expr := match e with | const n ls c => updateConst (const n ls c) newLevels rfl | _ => panic! "constant expected" @[extern "lean_expr_update_sort"] def updateSort (e : Expr) (newLevel : Level) (h : e.isSort) : Expr := mkSort newLevel @[inline] def updateSort! (e : Expr) (newLevel : Level) : Expr := match e with | sort l c => updateSort (sort l c) newLevel rfl | _ => panic! "level expected" @[extern "lean_expr_update_proj"] def updateProj (e : Expr) (newExpr : Expr) (h : e.isProj) : Expr := match e with | proj s i _ _ => mkProj s i newExpr | _ => e -- unreachable because of `h` @[extern "lean_expr_update_mdata"] def updateMData (e : Expr) (newExpr : Expr) (h : e.isMData) : Expr := match e with | mdata d _ _ => mkMData d newExpr | _ => e -- unreachable because of `h` @[inline] def updateMData! (e : Expr) (newExpr : Expr) : Expr := match e with | mdata d e c => updateMData (mdata d e c) newExpr rfl | _ => panic! "mdata expected" @[inline] def updateProj! (e : Expr) (newExpr : Expr) : Expr := match e with | proj s i e c => updateProj (proj s i e c) newExpr rfl | _ => panic! "proj expected" @[extern "lean_expr_update_forall"] def updateForall (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) (h : e.isForall) : Expr := mkForall e.bindingName! newBinfo newDomain newBody @[inline] def updateForall! (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) : Expr := match e with | forallE n d b c => updateForall (forallE n d b c) newBinfo newDomain newBody rfl | _ => panic! "forall expected" @[inline] def updateForallE! (e : Expr) (newDomain : Expr) (newBody : Expr) : Expr := match e with | forallE n d b c => updateForall (forallE n d b c) c.binderInfo newDomain newBody rfl | _ => panic! "forall expected" @[extern "lean_expr_update_lambda"] def updateLambda (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) (h : e.isLambda) : Expr := mkLambda e.bindingName! newBinfo newDomain newBody @[inline] def updateLambda! (e : Expr) (newBinfo : BinderInfo) (newDomain : Expr) (newBody : Expr) : Expr := match e with | lam n d b c => updateLambda (lam n d b c) newBinfo newDomain newBody rfl | _ => panic! "lambda expected" @[inline] def updateLambdaE! (e : Expr) (newDomain : Expr) (newBody : Expr) : Expr := match e with | lam n d b c => updateLambda (lam n d b c) c.binderInfo newDomain newBody rfl | _ => panic! "lambda expected" @[extern "lean_expr_update_let"] def updateLet (e : Expr) (newType : Expr) (newVal : Expr) (newBody : Expr) (h : e.isLet) : Expr := mkLet e.letName! newType newVal newBody @[inline] def updateLet! (e : Expr) (newType : Expr) (newVal : Expr) (newBody : Expr) : Expr := match e with | letE n t v b c => updateLet (letE n t v b c) newType newVal newBody rfl | _ => panic! "let expression expected" def updateFn : Expr → Expr → Expr | e@(app f a _), g => e.updateApp! (updateFn f g) a | _, g => g partial def eta (e : Expr) : Expr := match e with | Expr.lam _ d b _ => let b' := b.eta match b' with | Expr.app f (Expr.bvar 0 _) _ => if !f.hasLooseBVar 0 then f.lowerLooseBVars 1 1 else e.updateLambdaE! d b' | _ => e.updateLambdaE! d b' | _ => e /- Instantiate level parameters -/ @[inline] def instantiateLevelParamsCore (s : Name → Option Level) (e : Expr) : Expr := let rec @[specialize] visit (e : Expr) : Expr := if !e.hasLevelParam then e else match e with | lam n d b _ => e.updateLambdaE! (visit d) (visit b) | forallE n d b _ => e.updateForallE! (visit d) (visit b) | letE n t v b _ => e.updateLet! (visit t) (visit v) (visit b) | app f a _ => e.updateApp! (visit f) (visit a) | proj _ _ s _ => e.updateProj! (visit s) | mdata _ b _ => e.updateMData! (visit b) | const _ us _ => e.updateConst! (us.map (fun u => u.instantiateParams s)) | sort u _ => e.updateSort! (u.instantiateParams s) | e => e visit e private def getParamSubst : List Name → List Level → Name → Option Level | p::ps, u::us, p' => if p == p' then some u else getParamSubst ps us p' | _, _, _ => none def instantiateLevelParams (e : Expr) (paramNames : List Name) (lvls : List Level) : Expr := instantiateLevelParamsCore (getParamSubst paramNames lvls) e private partial def getParamSubstArray (ps : Array Name) (us : Array Level) (p' : Name) (i : Nat) : Option Level := if h : i < ps.size then let p := ps.get ⟨i, h⟩ if h : i < us.size then let u := us.get ⟨i, h⟩ if p == p' then some u else getParamSubstArray ps us p' (i+1) else none else none def instantiateLevelParamsArray (e : Expr) (paramNames : Array Name) (lvls : Array Level) : Expr := instantiateLevelParamsCore (fun p => getParamSubstArray paramNames lvls p 0) e /- Annotate `e` with the given option. -/ def setOption (e : Expr) (optionName : Name) [KVMap.Value α] (val : α) : Expr := mkMData (MData.empty.set optionName val) e /- Annotate `e` with `pp.explicit := true` The delaborator uses `pp` options. -/ def setPPExplicit (e : Expr) (flag : Bool) := e.setOption `pp.explicit flag def setPPUniverses (e : Expr) (flag : Bool) := e.setOption `pp.universes flag /- If `e` is an application `f a_1 ... a_n` annotate `f`, `a_1` ... `a_n` with `pp.explicit := false`, and annotate `e` with `pp.explicit := true`. -/ def setAppPPExplicit (e : Expr) : Expr := match e with | app .. => let f := e.getAppFn.setPPExplicit false let args := e.getAppArgs.map (·.setPPExplicit false) mkAppN f args |>.setPPExplicit true | _ => e /- Similar for `setAppPPExplicit`, but only annotate children with `pp.explicit := false` if `e` does not contain metavariables. -/ def setAppPPExplicitForExposingMVars (e : Expr) : Expr := match e with | app .. => let f := e.getAppFn.setPPExplicit false let args := e.getAppArgs.map fun arg => if arg.hasMVar then arg else arg.setPPExplicit false mkAppN f args |>.setPPExplicit true | _ => e end Expr def mkAnnotation (kind : Name) (e : Expr) : Expr := mkMData (KVMap.empty.insert kind (DataValue.ofBool true)) e def annotation? (kind : Name) (e : Expr) : Option Expr := match e with | Expr.mdata d b _ => if d.size == 1 && d.getBool kind false then some b else none | _ => none /-- Annotate `e` with the LHS annotation. The delaborator displays expressions of the form `lhs = rhs` as `lhs` when they have this annotation. -/ def mkLHSGoal (e : Expr) : Expr := mkAnnotation `_lhsGoal e def isLHSGoal? (e : Expr) : Option Expr := match annotation? `_lhsGoal e with | none => none | some e => if e.isAppOfArity `Eq 3 then some e.appFn!.appArg! else none def mkFreshFVarId {m : Type → Type} [Monad m] [MonadNameGenerator m] : m FVarId := return { name := (← mkFreshId) } def mkFreshMVarId {m : Type → Type} [Monad m] [MonadNameGenerator m] : m MVarId := return { name := (← mkFreshId) } def mkNot (p : Expr) : Expr := mkApp (mkConst ``Not) p def mkOr (p q : Expr) : Expr := mkApp2 (mkConst ``Or) p q def mkAnd (p q : Expr) : Expr := mkApp2 (mkConst ``And) p q def mkEM (p : Expr) : Expr := mkApp (mkConst ``Classical.em) p end Lean
6c5208d514013f4f008422d91dcad5cb019b80b1
36938939954e91f23dec66a02728db08a7acfcf9
/lean4/deps/x86_semantics/src/X86Semantics/MachineMemory.lean
af5d70891ea24e4f139bfeb67e50ac54c94a5378
[]
no_license
pnwamk/reopt-vcg
f8b56dd0279392a5e1c6aee721be8138e6b558d3
c9f9f185fbefc25c36c4b506bbc85fd1a03c3b6d
refs/heads/master
1,631,145,017,772
1,593,549,019,000
1,593,549,143,000
254,191,418
0
0
null
1,586,377,077,000
1,586,377,077,000
null
UTF-8
Lean
false
false
3,459
lean
import Galois.Init.Nat import Galois.Data.Bitvec import X86Semantics.BufferMap @[reducible] def memaddr := bitvec 64 @[reducible] def byte := UInt8 -- -- FIXME: maybe Nat is more efficient here? -- inductive region -- | has_contents : buffer byte -> region -- | all_zeroes : Nat -> region @[reducible] def init_memory := buffer_map memaddr (fun k k' => Int.ofNat (bitvec.to_nat k) - Int.ofNat (bitvec.to_nat k')) @[reducible] def mutable_memory := RBMap memaddr byte (fun x y => decide (bitvec.ult x y)) -- FIXME: byte? structure memory := ( init : init_memory ) ( mem : mutable_memory ) -- namespace array -- universes u v -- -- FIXME: Maybe make buffer a functor? -- def map' {a : Type u} {b : Type v} {n : Nat} (f : a -> b) (a : array n a) : array n b -- := d_array.mk (fun (i : fin n) => f (a.read i)) -- end array namespace memory @[reducible] def region := ByteArray -- FIXME: buffer/array don't have the usual map -- def char_buffer_to_region (b : char_buffer) : region := -- -- There doesn't seem to be a nicer way of doing this? -- array.to_buffer (array.map' (fun (c : char) => bitvec.of_nat _ c.val) b.to_array) /- Construction -/ def empty : memory := memory.mk buffer_map.empty (mkRBMap _ _ (fun x y => decide (bitvec.ult x y))) def from_init (i : init_memory) : memory := { empty with init := i } /- Reading and writing -/ def store_bytes (m : memory) (addr : memaddr) (bs : List byte) : memory := { m with mem := (List.foldl (fun (v : mutable_memory × memaddr) b => (RBMap.insert v.fst v.snd b, v.snd + 1)) (m.mem, addr) bs).fst } -- lemma {u v} option.bind.is_some {a : Type u} {b : Type v} {v : option a} {f : a -> option b} {x : b}: -- option.bind v f = some x -> (∃v', v = some v' ∧ f v' = some x) := -- begin -- cases v, -- { simp [option.bind] }, -- { simp [option.bind] } -- end -- lemma list.mmap.length_at_option {a b : Type} {f : a -> option b} : ∀{xs : list a} {ys : list b}, -- list.mmap f xs = some ys -> xs.length = ys.length := -- begin -- intros, -- induction xs generalizing ys, -- { simp [list.mmap, option_t.pure, return, pure] at a_1, rw <- a_1, refl}, -- { simp, simp [list.mmap, bind, option.bind] at a_1, -- destruct a_1, intros, -- destruct h, simp, intros, simp [return, pure] at a_3, -- rw (xs_ih a_2), rw <- a_3, simp [list.length] -- } -- end def bitvec.to_byte (b : bitvec 8) : UInt8 := UInt8.ofNat b.to_nat def UInt8.to_bitvec (v : UInt8) : bitvec 8 := bitvec.of_nat 8 v.toNat def read_byte (m : memory) (addr : memaddr) : Option byte := m.mem.find? addr <|> m.init.lookup addr def read_bytes (m : memory) (addr : memaddr) (n : Nat) : Option (List byte) := List.mapM (fun n => read_byte m (addr + bitvec.of_nat 64 n)) (Nat.upto0_lt n) -- lemma read_bytes_length {mem : memory} {addr : memaddr} {n : Nat} {bs : list (bitvec 8)} -- : read_bytes mem addr n = some bs -> bs.length = n := -- begin -- intros H, -- simp [read_bytes] at H, -- have H' := list.mmap.length_at_option H, -- simp [upto0_lt.length_is_n] at H', -- rw H' -- end def store_word {n : Nat} (m : memory) (addr : memaddr) (b : bitvec (8 * n)) : memory := m.store_bytes addr (List.map bitvec.to_byte (b.split_list 8)).reverse def read_word (m : memory) (addr : memaddr) (n : Nat) : Option (bitvec (8 * n)) := (fun (bs : List byte) => bitvec.concat_list (List.map UInt8.to_bitvec bs).reverse (8 * n)) <$> m.read_bytes addr n end memory
1fb35b077e0b40bdca6785c68e3a91d0c2659572
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/sepByIndentQuot.lean
c5590f2dc60101e833aa9c2cb19bf98d1f1d8021
[ "Apache-2.0", "LLVM-exception", "NCSA", "LGPL-3.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.0-or-later", "Spencer-94", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-pcre", "ISC", "LGPL-2.1-only", "LicenseRef-scancode-other-permissive", "SunPro", "CMU-Mach"...
permissive
leanprover/lean4
4bdf9790294964627eb9be79f5e8f6157780b4cc
f1f9dc0f2f531af3312398999d8b8303fa5f096b
refs/heads/master
1,693,360,665,786
1,693,350,868,000
1,693,350,868,000
129,571,436
2,827
311
Apache-2.0
1,694,716,156,000
1,523,760,560,000
Lean
UTF-8
Lean
false
false
320
lean
import Lean open Lean Elab #eval do let x := mkIdent `x let xs := #[x,x,x,x] let ys := xs PrettyPrinter.ppTerm <|<- `(frobnicate { $[$xs:ident := $ys:term],* }) #eval do let x := mkIdent `x let xs := #[x,x,x,x] let ys := xs PrettyPrinter.ppTerm <|<- `(frobnicate { $[$xs:ident := $ys:term]* })
192f3ffca95364f7cdc5a73a352eafd8698cfd65
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/category_theory/sigma/basic.lean
24e2fdd2b5c91816fc99fdc70a303197e1895541
[ "Apache-2.0" ]
permissive
leanprover-community/mathlib
56a2cadd17ac88caf4ece0a775932fa26327ba0e
442a83d738cb208d3600056c489be16900ba701d
refs/heads/master
1,693,584,102,358
1,693,471,902,000
1,693,471,902,000
97,922,418
1,595
352
Apache-2.0
1,694,693,445,000
1,500,624,130,000
Lean
UTF-8
Lean
false
false
7,830
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.whiskering import category_theory.functor.fully_faithful import category_theory.natural_isomorphism /-! # Disjoint union of categories > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. We define the category structure on a sigma-type (disjoint union) of categories. -/ namespace category_theory namespace sigma universes w₁ w₂ w₃ v₁ v₂ u₁ u₂ variables {I : Type w₁} {C : I → Type u₁} [Π i, category.{v₁} (C i)] /-- The type of morphisms of a disjoint union of categories: for `X : C i` and `Y : C j`, a morphism `(i, X) ⟶ (j, Y)` if `i = j` is just a morphism `X ⟶ Y`, and if `i ≠ j` there are no such morphisms. -/ inductive sigma_hom : (Σ i, C i) → (Σ i, C i) → Type (max w₁ v₁ u₁) | mk : Π {i : I} {X Y : C i}, (X ⟶ Y) → sigma_hom ⟨i, X⟩ ⟨i, Y⟩ namespace sigma_hom /-- The identity morphism on an object. -/ def id : Π (X : Σ i, C i), sigma_hom X X | ⟨i, X⟩ := mk (𝟙 _) instance (X : Σ i, C i) : inhabited (sigma_hom X X) := ⟨id X⟩ /-- Composition of sigma homomorphisms. -/ def comp : Π {X Y Z : Σ i, C i}, sigma_hom X Y → sigma_hom Y Z → sigma_hom X Z | _ _ _ (mk f) (mk g) := mk (f ≫ g) instance : category_struct (Σ i, C i) := { hom := sigma_hom, id := id, comp := λ X Y Z f g, comp f g } @[simp] lemma comp_def (i : I) (X Y Z : C i) (f : X ⟶ Y) (g : Y ⟶ Z) : comp (mk f) (mk g) = mk (f ≫ g) := rfl lemma assoc : ∀ (X Y Z W : Σ i, C i) (f : X ⟶ Y) (g : Y ⟶ Z) (h : Z ⟶ W), (f ≫ g) ≫ h = f ≫ g ≫ h | _ _ _ _ (mk f) (mk g) (mk h) := congr_arg mk (category.assoc _ _ _) lemma id_comp : ∀ (X Y : Σ i, C i) (f : X ⟶ Y), 𝟙 X ≫ f = f | _ _ (mk f) := congr_arg mk (category.id_comp _) lemma comp_id : ∀ (X Y : Σ i, C i) (f : X ⟶ Y), f ≫ 𝟙 Y = f | _ _ (mk f) := congr_arg mk (category.comp_id _) end sigma_hom instance sigma : category (Σ i, C i) := { id_comp' := sigma_hom.id_comp, comp_id' := sigma_hom.comp_id, assoc' := sigma_hom.assoc } /-- The inclusion functor into the disjoint union of categories. -/ @[simps map] def incl (i : I) : C i ⥤ Σ i, C i := { obj := λ X, ⟨i, X⟩, map := λ X Y, sigma_hom.mk } @[simp] lemma incl_obj {i : I} (X : C i) : (incl i).obj X = ⟨i, X⟩ := rfl instance (i : I) : full (incl i : C i ⥤ Σ i, C i) := { preimage := λ X Y ⟨f⟩, f, witness' := λ X Y ⟨f⟩, rfl }. instance (i : I) : faithful (incl i : C i ⥤ Σ i, C i) := {}. section variables {D : Type u₂} [category.{v₂} D] (F : Π i, C i ⥤ D) /-- To build a natural transformation over the sigma category, it suffices to specify it restricted to each subcategory. -/ def nat_trans {F G : (Σ i, C i) ⥤ D} (h : Π (i : I), incl i ⋙ F ⟶ incl i ⋙ G) : F ⟶ G := { app := λ ⟨j, X⟩, (h j).app X, naturality' := by { rintro ⟨j, X⟩ ⟨_, _⟩ ⟨f⟩, apply (h j).naturality } } @[simp] lemma nat_trans_app {F G : (Σ i, C i) ⥤ D} (h : Π (i : I), incl i ⋙ F ⟶ incl i ⋙ G) (i : I) (X : C i) : (nat_trans h).app ⟨i, X⟩ = (h i).app X := rfl /-- (Implementation). An auxiliary definition to build the functor `desc`. -/ def desc_map : ∀ (X Y : Σ i, C i), (X ⟶ Y) → ((F X.1).obj X.2 ⟶ (F Y.1).obj Y.2) | _ _ (sigma_hom.mk g) := (F _).map g /-- Given a collection of functors `F i : C i ⥤ D`, we can produce a functor `(Σ i, C i) ⥤ D`. The produced functor `desc F` satisfies: `incl i ⋙ desc F ≅ F i`, i.e. restricted to just the subcategory `C i`, `desc F` agrees with `F i`, and it is unique (up to natural isomorphism) with this property. This witnesses that the sigma-type is the coproduct in Cat. -/ @[simps obj] def desc : (Σ i, C i) ⥤ D := { obj := λ X, (F X.1).obj X.2, map := λ X Y g, desc_map F X Y g, map_id' := by { rintro ⟨i, X⟩, apply (F i).map_id }, map_comp' := by { rintro ⟨i, X⟩ ⟨_, Y⟩ ⟨_, Z⟩ ⟨f⟩ ⟨g⟩, apply (F i).map_comp } } @[simp] lemma desc_map_mk {i : I} (X Y : C i) (f : X ⟶ Y) : (desc F).map (sigma_hom.mk f) = (F i).map f := rfl /-- This shows that when `desc F` is restricted to just the subcategory `C i`, `desc F` agrees with `F i`. -/ -- We hand-generate the simp lemmas about this since they come out cleaner. def incl_desc (i : I) : incl i ⋙ desc F ≅ F i := nat_iso.of_components (λ X, iso.refl _) (by tidy) @[simp] lemma incl_desc_hom_app (i : I) (X : C i) : (incl_desc F i).hom.app X = 𝟙 ((F i).obj X) := rfl @[simp] lemma incl_desc_inv_app (i : I) (X : C i) : (incl_desc F i).inv.app X = 𝟙 ((F i).obj X) := rfl /-- If `q` when restricted to each subcategory `C i` agrees with `F i`, then `q` is isomorphic to `desc F`. -/ def desc_uniq (q : (Σ i, C i) ⥤ D) (h : Π i, incl i ⋙ q ≅ F i) : q ≅ desc F := nat_iso.of_components (λ ⟨i, X⟩, (h i).app X) $ by { rintro ⟨i, X⟩ ⟨_, _⟩ ⟨f⟩, apply (h i).hom.naturality f } @[simp] lemma desc_uniq_hom_app (q : (Σ i, C i) ⥤ D) (h : Π i, incl i ⋙ q ≅ F i) (i : I) (X : C i) : (desc_uniq F q h).hom.app ⟨i, X⟩ = (h i).hom.app X := rfl @[simp] lemma desc_uniq_inv_app (q : (Σ i, C i) ⥤ D) (h : Π i, incl i ⋙ q ≅ F i) (i : I) (X : C i) : (desc_uniq F q h).inv.app ⟨i, X⟩ = (h i).inv.app X := rfl /-- If `q₁` and `q₂` when restricted to each subcategory `C i` agree, then `q₁` and `q₂` are isomorphic. -/ @[simps] def nat_iso {q₁ q₂ : (Σ i, C i) ⥤ D} (h : Π i, incl i ⋙ q₁ ≅ incl i ⋙ q₂) : q₁ ≅ q₂ := { hom := nat_trans (λ i, (h i).hom), inv := nat_trans (λ i, (h i).inv) } end section variables (C) {J : Type w₂} (g : J → I) /-- A function `J → I` induces a functor `Σ j, C (g j) ⥤ Σ i, C i`. -/ def map : (Σ (j : J), C (g j)) ⥤ (Σ (i : I), C i) := desc (λ j, incl (g j)) @[simp] lemma map_obj (j : J) (X : C (g j)) : (sigma.map C g).obj ⟨j, X⟩ = ⟨g j, X⟩ := rfl @[simp] lemma map_map {j : J} {X Y : C (g j)} (f : X ⟶ Y) : (sigma.map C g).map (sigma_hom.mk f) = sigma_hom.mk f := rfl /-- The functor `sigma.map C g` restricted to the subcategory `C j` acts as the inclusion of `g j`. -/ @[simps] def incl_comp_map (j : J) : incl j ⋙ map C g ≅ incl (g j) := iso.refl _ variable (I) /-- The functor `sigma.map` applied to the identity function is just the identity functor. -/ @[simps] def map_id : map C (id : I → I) ≅ 𝟭 (Σ i, C i) := nat_iso (λ i, nat_iso.of_components (λ X, iso.refl _) (by tidy)) variables {I} {K : Type w₃} /-- The functor `sigma.map` applied to a composition is a composition of functors. -/ @[simps] def map_comp (f : K → J) (g : J → I) : map (C ∘ g) f ⋙ (map C g : _) ≅ map C (g ∘ f) := desc_uniq _ _ $ λ k, (iso_whisker_right (incl_comp_map (C ∘ g) f k) (map C g : _) : _) ≪≫ incl_comp_map _ _ _ end namespace functor variables {C} variables {D : I → Type u₁} [∀ i, category.{v₁} (D i)] /-- Assemble an `I`-indexed family of functors into a functor between the sigma types. -/ def sigma (F : Π i, C i ⥤ D i) : (Σ i, C i) ⥤ (Σ i, D i) := desc (λ i, F i ⋙ incl i) end functor namespace nat_trans variables {C} variables {D : I → Type u₁} [∀ i, category.{v₁} (D i)] variables {F G : Π i, C i ⥤ D i} /-- Assemble an `I`-indexed family of natural transformations into a single natural transformation. -/ def sigma (α : Π i, F i ⟶ G i) : functor.sigma F ⟶ functor.sigma G := { app := λ f, sigma_hom.mk ((α f.1).app _), naturality' := begin rintro ⟨i, X⟩ ⟨_, _⟩ ⟨f⟩, change sigma_hom.mk _ = sigma_hom.mk _, rw (α i).naturality, end } end nat_trans end sigma end category_theory
d802ebd879f50099560513a330cd6dfea40d5b98
fa02ed5a3c9c0adee3c26887a16855e7841c668b
/src/geometry/manifold/bump_function.lean
692e0102b0d55321ab4c5abe0ebb9bd02aac21a8
[ "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
28,073
lean
/- Copyright (c) 2021 Yury Kudryashov. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Yury Kudryashov -/ import analysis.calculus.specific_functions import geometry.manifold.diffeomorph import geometry.manifold.instances.real /-! # Smooth bump functions on a smooth manifold In this file we define `smooth_bump_function I c` to be a bundled smooth "bump" function centered at `c`. It is a structure that consists of two real numbers `0 < r < R` with small enough `R`. We define a coercion to function for this type, and for `f : smooth_bump_function I c`, the function `⇑f` written in the extended chart at `f.c` has the following properties: * `f x = 1` in the closed euclidean ball of radius `f.r` centered at `f.c`; * `f x = 0` outside of the euclidean ball of radius `f.R` centered at `f.c`; * `0 ≤ f x ≤ 1` for all `x`. The actual statements involve (pre)images under `ext_chart_at I f.c` and are given as lemmas in the `smooth_bump_function` namespace. We also define `smooth_bump_covering` of a set `s : set M` to be a collection of `smooth_bump_function`s such that their supports is a locally finite family of sets, and for each point `x ∈ s` there exists a bump function `f i` in the collection such that `f i =ᶠ[𝓝 x] 1`. This structure is the main building block in the construction of a smooth partition of unity (see TODO), and can be used instead of a partition of unity in some proofs. We say that `f : smooth_bump_covering I s` is *subordinate* to a map `U : M → set M` if for each index `i`, we have `closure (support (f i)) ⊆ U (f i).c`. This notion is a bit more general than being subordinate to an open covering of `M`, because we make no assumption about the way `U x` depends on `x`. We prove that on a smooth finitely dimensional real manifold with `σ`-compact Hausdorff topology, for any `U : M → set M` such that `∀ x ∈ s, U x ∈ 𝓝 x` there exists a `smooth_bump_covering I s` subordinate to `U`. Then we use this fact to prove a version of the Whitney embedding theorem: any compact real manifold can be embedded into `ℝ^n` for large enough `n`. ## TODO * Prove the weak Whitney embedding theorem: any `σ`-compact smooth `m`-dimensional manifold can be embedded into `ℝ^(2m+1)`. This requires a version of Sard's theorem: for a locally Lipschitz continuous map `f : ℝ^m → ℝ^n`, `m < n`, the range has Hausdorff dimension at most `m`, hence it has measure zero. * Construct a smooth partition of unity. While we can do it now, the formulas will be much nicer if we wait for `finprod` and `finsum` coming in #6355. * Deduce some corollaries from existence of a smooth partition of unity. - Prove that for any disjoint closed sets `s`, `t` there exists a smooth function `f` suth that `f` equals zero on `s` and `f` equals one on `t`. - Build a framework for to transfer local definitions to global using partition of unity and use it to define, e.g., the integral of a differential form over a manifold. ## Tags manifold, smooth bump function, partition of unity, Whitney theorem -/ universes uE uF uH uM variables {E : Type uE} [normed_group E] [normed_space ℝ E] [finite_dimensional ℝ E] {H : Type uH} [topological_space H] (I : model_with_corners ℝ E H) {M : Type uM} [topological_space M] [charted_space H M] [smooth_manifold_with_corners I M] open function filter finite_dimensional set open_locale topological_space manifold classical filter big_operators noncomputable theory /-! ### Smooth bump function In this section we define a structure for a bundled smooth bump function and prove its properties. -/ /-- Given a smooth manifold modelled on a finite dimensional space `E`, `f : smooth_bump_function I M` is a smooth function on `M` such that in the extended chart `e` at `f.c`: * `f x = 1` in the closed euclidean ball of radius `f.r` centered at `f.c`; * `f x = 0` outside of the euclidean ball of radius `f.R` centered at `f.c`; * `0 ≤ f x ≤ 1` for all `x`. The structure contains data required to construct a function with these properties. The function is available as `⇑f` or `f x`. Formal statements of the properties listed above involve some (pre)images under `ext_chart_at I f.c` and are given as lemmas in the `msmooth_bump_function` namespace. -/ structure smooth_bump_function (c : M) extends times_cont_diff_bump (ext_chart_at I c c) := (closed_ball_subset : (euclidean.closed_ball (ext_chart_at I c c) R) ∩ range I ⊆ (ext_chart_at I c).target) variable {M} namespace smooth_bump_function open euclidean (renaming dist -> eudist) variables {c : M} (f : smooth_bump_function I c) {x : M} {I} /-- The function defined by `f : smooth_bump_function c`. Use automatic coercion to function instead. -/ def to_fun : M → ℝ := indicator (chart_at H c).source (f.to_times_cont_diff_bump ∘ ext_chart_at I c) instance : has_coe_to_fun (smooth_bump_function I c) := ⟨_, to_fun⟩ lemma coe_def : ⇑f = indicator (chart_at H c).source (f.to_times_cont_diff_bump ∘ ext_chart_at I c) := rfl lemma R_pos : 0 < f.R := f.to_times_cont_diff_bump.R_pos lemma ball_subset : ball (ext_chart_at I c c) f.R ∩ range I ⊆ (ext_chart_at I c).target := subset.trans (inter_subset_inter_left _ ball_subset_closed_ball) f.closed_ball_subset lemma eq_on_source : eq_on f (f.to_times_cont_diff_bump ∘ ext_chart_at I c) (chart_at H c).source := eq_on_indicator lemma eventually_eq_of_mem_source (hx : x ∈ (chart_at H c).source) : f =ᶠ[𝓝 x] f.to_times_cont_diff_bump ∘ ext_chart_at I c := f.eq_on_source.eventually_eq_of_mem $ is_open.mem_nhds (chart_at H c).open_source hx lemma one_of_dist_le (hs : x ∈ (chart_at H c).source) (hd : eudist (ext_chart_at I c x) (ext_chart_at I c c) ≤ f.r) : f x = 1 := by simp only [f.eq_on_source hs, (∘), f.to_times_cont_diff_bump.one_of_mem_closed_ball hd] lemma support_eq_inter_preimage : support f = (chart_at H c).source ∩ (ext_chart_at I c ⁻¹' ball (ext_chart_at I c c) f.R) := by rw [coe_def, support_indicator, (∘), support_comp_eq_preimage, ← ext_chart_at_source I, ← (ext_chart_at I c).symm_image_target_inter_eq', ← (ext_chart_at I c).symm_image_target_inter_eq', f.to_times_cont_diff_bump.support_eq] lemma open_support : is_open (support f) := by { rw support_eq_inter_preimage, exact ext_chart_preimage_open_of_open I c is_open_ball } lemma support_eq_symm_image : support f = (ext_chart_at I c).symm '' (ball (ext_chart_at I c c) f.R ∩ range I) := begin rw [f.support_eq_inter_preimage, ← ext_chart_at_source I, ← (ext_chart_at I c).symm_image_target_inter_eq', inter_comm], congr' 1 with y, exact and.congr_right_iff.2 (λ hy, ⟨λ h, ext_chart_at_target_subset_range _ _ h, λ h, f.ball_subset ⟨hy, h⟩⟩) end lemma support_subset_source : support f ⊆ (chart_at H c).source := by { rw [f.support_eq_inter_preimage, ← ext_chart_at_source I], exact inter_subset_left _ _ } lemma image_eq_inter_preimage_of_subset_support {s : set M} (hs : s ⊆ support f) : ext_chart_at I c '' s = closed_ball (ext_chart_at I c c) f.R ∩ range I ∩ (ext_chart_at I c).symm ⁻¹' s := begin rw [support_eq_inter_preimage, subset_inter_iff, ← ext_chart_at_source I, ← image_subset_iff] at hs, cases hs with hse hsf, apply subset.antisymm, { refine subset_inter (subset_inter (subset.trans hsf ball_subset_closed_ball) _) _, { rintro _ ⟨x, -, rfl⟩, exact mem_range_self _ }, { rw [(ext_chart_at I c).image_eq_target_inter_inv_preimage hse], exact inter_subset_right _ _ } }, { refine subset.trans (inter_subset_inter_left _ f.closed_ball_subset) _, rw [(ext_chart_at I c).image_eq_target_inter_inv_preimage hse] } end lemma mem_Icc : f x ∈ Icc (0 : ℝ) 1 := begin have : f x = 0 ∨ f x = _, from indicator_eq_zero_or_self _ _ _, cases this; rw this, exacts [left_mem_Icc.2 zero_le_one, ⟨f.to_times_cont_diff_bump.nonneg, f.to_times_cont_diff_bump.le_one⟩] end lemma nonneg : 0 ≤ f x := f.mem_Icc.1 lemma le_one : f x ≤ 1 := f.mem_Icc.2 lemma eventually_eq_one_of_dist_lt (hs : x ∈ (chart_at H c).source) (hd : eudist (ext_chart_at I c x) (ext_chart_at I c c) < f.r) : f =ᶠ[𝓝 x] 1 := begin filter_upwards [is_open.mem_nhds (ext_chart_preimage_open_of_open I c is_open_ball) ⟨hs, hd⟩], rintro z ⟨hzs, hzd : _ < _⟩, exact f.one_of_dist_le hzs hzd.le end lemma eventually_eq_one : f =ᶠ[𝓝 c] 1 := f.eventually_eq_one_of_dist_lt (mem_chart_source _ _) $ by { rw [euclidean.dist, dist_self], exact f.r_pos } @[simp] lemma eq_one : f c = 1 := f.eventually_eq_one.eq_of_nhds lemma support_mem_nhds : support f ∈ 𝓝 c := f.eventually_eq_one.mono $ λ x hx, by { rw hx, exact one_ne_zero } lemma closure_support_mem_nhds : closure (support f) ∈ 𝓝 c := mem_sets_of_superset f.support_mem_nhds subset_closure lemma c_mem_support : c ∈ support f := mem_of_mem_nhds f.support_mem_nhds lemma nonempty_support : (support f).nonempty := ⟨c, f.c_mem_support⟩ lemma compact_symm_image_closed_ball : is_compact ((ext_chart_at I c).symm '' (closed_ball (ext_chart_at I c c) f.R ∩ range I)) := (compact_ball.inter_right I.closed_range).image_of_continuous_on $ (ext_chart_at_continuous_on_symm _ _).mono f.closed_ball_subset /-- Given a smooth bump function `f : smooth_bump_function I c`, the closed ball of radius `f.R` is known to include the support of `f`. These closed balls (in the model normed space `E`) intersected with `set.range I` form a basis of `𝓝[range I] (ext_chart_at I c c)`. -/ lemma nhds_within_range_basis : (𝓝[range I] (ext_chart_at I c c)).has_basis (λ f : smooth_bump_function I c, true) (λ f, closed_ball (ext_chart_at I c c) f.R ∩ range I) := begin refine ((nhds_within_has_basis euclidean.nhds_basis_closed_ball _).restrict_subset (ext_chart_at_target_mem_nhds_within _ _)).to_has_basis' _ _, { rintro R ⟨hR0, hsub⟩, exact ⟨⟨⟨⟨R / 2, R, half_pos hR0, half_lt_self hR0⟩⟩, hsub⟩, trivial, subset.rfl⟩ }, { exact λ f _, inter_mem_sets (mem_nhds_within_of_mem_nhds $ closed_ball_mem_nhds f.R_pos) self_mem_nhds_within } end lemma closed_image_of_closed {s : set M} (hsc : is_closed s) (hs : s ⊆ support f) : is_closed (ext_chart_at I c '' s) := begin rw f.image_eq_inter_preimage_of_subset_support hs, refine continuous_on.preimage_closed_of_closed ((ext_chart_continuous_on_symm _ _).mono f.closed_ball_subset) _ hsc, exact is_closed.inter is_closed_closed_ball I.closed_range end /-- If `f` is a smooth bump function and `s` closed subset of the support of `f` (i.e., of the open ball of radius `f.R`), then there exists `0 < r < f.R` such that `s` is a subset of the open ball of radius `r`. Formally, `s ⊆ e.source ∩ e ⁻¹' (ball (e c) r)`, where `e = ext_chart_at I c`. -/ lemma exists_r_pos_lt_subset_ball {s : set M} (hsc : is_closed s) (hs : s ⊆ support f) : ∃ r (hr : r ∈ Ioo 0 f.R), s ⊆ (chart_at H c).source ∩ ext_chart_at I c ⁻¹' (ball (ext_chart_at I c c) r) := begin set e := ext_chart_at I c, have : is_closed (e '' s) := f.closed_image_of_closed hsc hs, rw [support_eq_inter_preimage, subset_inter_iff, ← image_subset_iff] at hs, rcases euclidean.exists_pos_lt_subset_ball f.R_pos this hs.2 with ⟨r, hrR, hr⟩, exact ⟨r, hrR, subset_inter hs.1 (image_subset_iff.1 hr)⟩ end /-- Replace `r` with another value in the interval `(0, f.R)`. -/ def update_r (r : ℝ) (hr : r ∈ Ioo 0 f.R) : smooth_bump_function I c := ⟨⟨⟨r, f.R, hr.1, hr.2⟩⟩, f.closed_ball_subset⟩ @[simp] lemma update_r_R {r : ℝ} (hr : r ∈ Ioo 0 f.R) : (f.update_r r hr).R = f.R := rfl @[simp] lemma update_r_r {r : ℝ} (hr : r ∈ Ioo 0 f.R) : (f.update_r r hr).r = r := rfl @[simp] lemma support_update_r {r : ℝ} (hr : r ∈ Ioo 0 f.R) : support (f.update_r r hr) = support f := by simp only [support_eq_inter_preimage, update_r_R] instance : inhabited (smooth_bump_function I c) := classical.inhabited_of_nonempty nhds_within_range_basis.nonempty variables [t2_space M] lemma closed_symm_image_closed_ball : is_closed ((ext_chart_at I c).symm '' (closed_ball (ext_chart_at I c c) f.R ∩ range I)) := f.compact_symm_image_closed_ball.is_closed lemma closure_support_subset_symm_image_closed_ball : closure (support f) ⊆ (ext_chart_at I c).symm '' (closed_ball (ext_chart_at I c c) f.R ∩ range I) := begin rw support_eq_symm_image, exact closure_minimal (image_subset _ $ inter_subset_inter_left _ ball_subset_closed_ball) f.closed_symm_image_closed_ball end lemma closure_support_subset_ext_chart_at_source : closure (support f) ⊆ (ext_chart_at I c).source := calc closure (support f) ⊆ (ext_chart_at I c).symm '' (closed_ball (ext_chart_at I c c) f.R ∩ range I) : f.closure_support_subset_symm_image_closed_ball ... ⊆ (ext_chart_at I c).symm '' (ext_chart_at I c).target : image_subset _ f.closed_ball_subset ... = (ext_chart_at I c).source : (ext_chart_at I c).symm_image_target_eq_source lemma closure_support_subset_chart_at_source : closure (support f) ⊆ (chart_at H c).source := by simpa only [ext_chart_at_source] using f.closure_support_subset_ext_chart_at_source lemma compact_closure_support : is_compact (closure $ support f) := compact_of_is_closed_subset f.compact_symm_image_closed_ball is_closed_closure f.closure_support_subset_symm_image_closed_ball variables (I c) /-- The closures of supports of smooth bump functions centered at `c` form a basis of `𝓝 c`. In other words, each of these closures is a neighborhood of `c` and each neighborhood of `c` includes `closure (support f)` for some `f : smooth_bump_function I c`. -/ lemma nhds_basis_closure_support : (𝓝 c).has_basis (λ f : smooth_bump_function I c, true) (λ f, closure $ support f) := begin have : (𝓝 c).has_basis (λ f : smooth_bump_function I c, true) (λ f, (ext_chart_at I c).symm '' (closed_ball (ext_chart_at I c c) f.R ∩ range I)), { rw [← ext_chart_at_symm_map_nhds_within_range I c], exact nhds_within_range_basis.map _ }, refine this.to_has_basis' (λ f hf, ⟨f, trivial, f.closure_support_subset_symm_image_closed_ball⟩) (λ f _, f.closure_support_mem_nhds), end variable {c} /-- Given `s ∈ 𝓝 c`, the supports of smooth bump functions `f : smooth_bump_function I c` such that `closure (support f) ⊆ s` form a basis of `𝓝 c`. In other words, each of these supports is a neighborhood of `c` and each neighborhood of `c` includes `support f` for some `f : smooth_bump_function I c` such that `closure (support f) ⊆ s`. -/ lemma nhds_basis_support {s : set M} (hs : s ∈ 𝓝 c) : (𝓝 c).has_basis (λ f : smooth_bump_function I c, closure (support f) ⊆ s) (λ f, support f) := ((nhds_basis_closure_support I c).restrict_subset hs).to_has_basis' (λ f hf, ⟨f, hf.2, subset_closure⟩) (λ f hf, f.support_mem_nhds) variables [smooth_manifold_with_corners I M] {I} /-- A smooth bump function is infinitely smooth. -/ protected lemma smooth : smooth I 𝓘(ℝ) f := begin refine times_cont_mdiff_of_support (λ x hx, _), have : x ∈ (chart_at H c).source := f.closure_support_subset_chart_at_source hx, refine times_cont_mdiff_at.congr_of_eventually_eq _ (f.eq_on_source.eventually_eq_of_mem $ is_open.mem_nhds (chart_at _ _).open_source this), exact f.to_times_cont_diff_bump.times_cont_diff_at.times_cont_mdiff_at.comp _ (times_cont_mdiff_at_ext_chart_at' this) end protected lemma smooth_at {x} : smooth_at I 𝓘(ℝ) f x := f.smooth.smooth_at /-- If `f : smooth_bump_function I c` is a smooth bump function and `g : M → G` is a function smooth on the source of the chart at `c`, then `f • g` is smooth on the whole manifold. -/ lemma smooth_smul {G} [normed_group G] [normed_space ℝ G] {g : M → G} (hg : smooth_on I 𝓘(ℝ, G) g (chart_at H c).source) : smooth I 𝓘(ℝ, G) (λ x, f x • g x) := begin apply times_cont_mdiff_of_support (λ x hx, _), have : x ∈ (chart_at H c).source, calc x ∈ closure (support (λ x, f x • g x)) : hx ... ⊆ closure (support f) : closure_mono (support_smul_subset_left _ _) ... ⊆ (chart_at _ c).source : f.closure_support_subset_chart_at_source, exact f.smooth_at.smul ((hg _ this).times_cont_mdiff_at $ is_open.mem_nhds (chart_at _ _).open_source this) end end smooth_bump_function /-! ### Covering by supports of smooth bump functions In this section we define `smooth_bump_covering I s` to be a collection of `smooth_bump_function`s such that their supports is a locally finite family of sets and for each `x ∈ s` some function `f i` from the collection is equal to `1` in a neighborhood of `x`. A covering of this type is useful to construct a smooth partition of unity and can be used instead of a partition of unity in some proofs. We prove that on a smooth finite dimensional real manifold with `σ`-compact Hausdorff topology, for any `U : M → set M` such that `∀ x ∈ s, U x ∈ 𝓝 x` there exists a `smooth_bump_covering I s` subordinate to `U`. Then we use this fact to prove a version of the Whitney embedding theorem: any compact real manifold can be embedded into `ℝ^n` for large enough `n`. -/ /-- We say that a collection of `smooth_bump_function`s is a `smooth_bump_covering` of a set `s` if * `(f i).c ∈ s` for all `i`; * the family `λ i, support (f i)` is locally finite; * for each point `x ∈ s` there exists `i` such that `f i =ᶠ[𝓝 x] 1`; in other words, `x` belongs to the interior of `{y | f i y = 1}`; If `M` is a finite dimensional real manifold which is a sigma-compact Hausdorff topological space, then a choice of `smooth_bump_covering` is available as `smooth_bump_covering.choice_set`, see also `smooth_bump_covering.choice` for the case `s = univ` and `smooth_bump_covering.exists_is_subordinate` for a lemma providing a covering subordinate to a given `U : M → set M`. This covering can be used, e.g., to construct a partition of unity and to prove the weak Whitney embedding theorem. -/ structure smooth_bump_covering (s : set M) := (ι : Type uM) (c : ι → M) (to_fun : Π i, smooth_bump_function I (c i)) (c_mem' : ∀ i, c i ∈ s) (locally_finite' : locally_finite (λ i, support (to_fun i))) (eventually_eq_one' : ∀ x ∈ s, ∃ i, to_fun i =ᶠ[𝓝 x] 1) namespace smooth_bump_covering variables {s : set M} {U : M → set M} (fs : smooth_bump_covering I s) {I} instance : has_coe_to_fun (smooth_bump_covering I s) := ⟨_, to_fun⟩ @[simp] lemma coe_mk (ι : Type uM) (c : ι → M) (to_fun : Π i, smooth_bump_function I (c i)) (h₁ h₂ h₃) : ⇑(mk ι c to_fun h₁ h₂ h₃ : smooth_bump_covering I s) = to_fun := rfl /-- We say that `f : smooth_bump_covering I s` is *subordinate* to a map `U : M → set M` if for each index `i`, we have `closure (support (f i)) ⊆ U (f i).c`. This notion is a bit more general than being subordinate to an open covering of `M`, because we make no assumption about the way `U x` depends on `x`. -/ def is_subordinate {s : set M} (f : smooth_bump_covering I s) (U : M → set M) := ∀ i, closure (support $ f i) ⊆ U (f.c i) variable (I) /-- Let `M` be a smooth manifold with corners modelled on a finite dimensional real vector space. Suppose also that `M` is a Hausdorff `σ`-compact topological space. Let `s` be a closed set in `M` and `U : M → set M` be a collection of sets such that `U x ∈ 𝓝 x` for every `x ∈ s`. Then there exists a smooth bump covering of `s` that is subordinate to `U`. -/ lemma exists_is_subordinate [t2_space M] [sigma_compact_space M] (hs : is_closed s) (hU : ∀ x ∈ s, U x ∈ 𝓝 x) : ∃ f : smooth_bump_covering I s, f.is_subordinate U := begin -- First we deduce some missing instances haveI : locally_compact_space H := I.locally_compact, haveI : locally_compact_space M := charted_space.locally_compact H, haveI : normal_space M := normal_of_paracompact_t2, -- Next we choose a covering by supports of smooth bump functions have hB := λ x hx, smooth_bump_function.nhds_basis_support I (hU x hx), rcases refinement_of_locally_compact_sigma_compact_of_nhds_basis_set hs hB with ⟨ι, c, f, hf, hsub', hfin⟩, choose hcs hfU using hf, /- Then we use the shrinking lemma to get a covering by smaller open -/ rcases exists_subset_Union_closed_subset hs (λ i, (f i).open_support) (λ x hx, hfin.point_finite x) hsub' with ⟨V, hsV, hVc, hVf⟩, choose r hrR hr using λ i, (f i).exists_r_pos_lt_subset_ball (hVc i) (hVf i), refine ⟨⟨ι, c, λ i, (f i).update_r (r i) (hrR i), hcs, _, λ x hx, _⟩, λ i, _⟩, { simpa only [smooth_bump_function.support_update_r] }, { refine (mem_Union.1 $ hsV hx).imp (λ i hi, _), exact ((f i).update_r _ _).eventually_eq_one_of_dist_lt ((f i).support_subset_source $ hVf _ hi) (hr i hi).2 }, { simpa only [coe_mk, smooth_bump_function.support_update_r] using hfU i } end /-- Choice of a covering of a closed set `s` by supports of smooth bump functions. -/ def choice_set [t2_space M] [sigma_compact_space M] (s : set M) (hs : is_closed s) : smooth_bump_covering I s := (exists_is_subordinate I hs (λ x hx, univ_mem_sets)).some instance [t2_space M] [sigma_compact_space M] {s : set M} [is_closed s] : inhabited (smooth_bump_covering I s) := ⟨choice_set I s ‹_›⟩ variable (M) /-- Choice of a covering of a manifold by supports of smooth bump functions. -/ def choice [t2_space M] [sigma_compact_space M] : smooth_bump_covering I (univ : set M) := choice_set I univ is_closed_univ variables {I M} protected lemma locally_finite : locally_finite (λ i, support (fs i)) := fs.locally_finite' protected lemma point_finite (x : M) : {i | fs i x ≠ 0}.finite := fs.locally_finite.point_finite x lemma mem_chart_at_source_of_eq_one {i : fs.ι} {x : M} (h : fs i x = 1) : x ∈ (chart_at H (fs.c i)).source := (fs i).support_subset_source $ by simp [h] lemma mem_ext_chart_at_source_of_eq_one {i : fs.ι} {x : M} (h : fs i x = 1) : x ∈ (ext_chart_at I (fs.c i)).source := by { rw ext_chart_at_source, exact fs.mem_chart_at_source_of_eq_one h } /-- Index of a bump function such that `fs i =ᶠ[𝓝 x] 1`. -/ def ind (x : M) (hx : x ∈ s) : fs.ι := (fs.eventually_eq_one' x hx).some lemma eventually_eq_one (x : M) (hx : x ∈ s) : fs (fs.ind x hx) =ᶠ[𝓝 x] 1 := (fs.eventually_eq_one' x hx).some_spec lemma apply_ind (x : M) (hx : x ∈ s) : fs (fs.ind x hx) x = 1 := (fs.eventually_eq_one x hx).eq_of_nhds lemma mem_support_ind (x : M) (hx : x ∈ s) : x ∈ support (fs $ fs.ind x hx) := by simp [fs.apply_ind x hx] lemma mem_chart_at_ind_source (x : M) (hx : x ∈ s) : x ∈ (chart_at H (fs.c (fs.ind x hx))).source := fs.mem_chart_at_source_of_eq_one (fs.apply_ind x hx) lemma mem_ext_chart_at_ind_source (x : M) (hx : x ∈ s) : x ∈ (ext_chart_at I (fs.c (fs.ind x hx))).source := fs.mem_ext_chart_at_source_of_eq_one (fs.apply_ind x hx) section embedding /-! ### Whitney embedding theorem In this section we prove a version of the Whitney embedding theorem: for any compact real manifold `M`, for sufficiently large `n` there exists a smooth embedding `M → ℝ^n`. -/ instance fintype_ι_of_compact [compact_space M] : fintype fs.ι := fs.locally_finite.fintype_of_compact $ λ i, (fs i).nonempty_support variables [t2_space M] [fintype fs.ι] (f : smooth_bump_covering I (univ : set M)) [fintype f.ι] /-- Smooth embedding of `M` into `(E × ℝ) ^ f.ι`. -/ def embedding_pi_tangent : C^∞⟮I, M; 𝓘(ℝ, fs.ι → (E × ℝ)), fs.ι → (E × ℝ)⟯ := { to_fun := λ x i, (fs i x • ext_chart_at I (fs.c i) x, fs i x), times_cont_mdiff_to_fun := times_cont_mdiff_pi_space.2 $ λ i, ((fs i).smooth_smul times_cont_mdiff_on_ext_chart_at).prod_mk_space ((fs i).smooth) } local attribute [simp] lemma embedding_pi_tangent_coe : ⇑fs.embedding_pi_tangent = λ x i, (fs i x • ext_chart_at I (fs.c i) x, fs i x) := rfl lemma embedding_pi_tangent_inj_on : inj_on fs.embedding_pi_tangent s := begin intros x hx y hy h, simp only [embedding_pi_tangent_coe, funext_iff] at h, obtain ⟨h₁, h₂⟩ := prod.mk.inj_iff.1 (h (fs.ind x hx)), rw [fs.apply_ind x hx] at h₂, rw [← h₂, fs.apply_ind x hx, one_smul, one_smul] at h₁, have := fs.mem_ext_chart_at_source_of_eq_one h₂.symm, exact (ext_chart_at I (fs.c _)).inj_on (fs.mem_ext_chart_at_ind_source x hx) this h₁ end lemma embedding_pi_tangent_injective : injective f.embedding_pi_tangent := injective_iff_inj_on_univ.2 f.embedding_pi_tangent_inj_on lemma comp_embedding_pi_tangent_mfderiv (x : M) (hx : x ∈ s) : ((continuous_linear_map.fst ℝ E ℝ).comp (@continuous_linear_map.proj ℝ _ fs.ι (λ _, E × ℝ) _ _ (λ _, infer_instance) (fs.ind x hx))).comp (mfderiv I 𝓘(ℝ, fs.ι → (E × ℝ)) fs.embedding_pi_tangent x) = mfderiv I I (chart_at H (fs.c (fs.ind x hx))) x := begin set L := ((continuous_linear_map.fst ℝ E ℝ).comp (@continuous_linear_map.proj ℝ _ fs.ι (λ _, E × ℝ) _ _ (λ _, infer_instance) (fs.ind x hx))), have := (L.has_mfderiv_at.comp x (fs.embedding_pi_tangent.mdifferentiable_at.has_mfderiv_at)), convert has_mfderiv_at_unique this _, refine (has_mfderiv_at_ext_chart_at I (fs.mem_chart_at_ind_source x hx)).congr_of_eventually_eq _, refine (fs.eventually_eq_one x hx).mono (λ y hy, _), simp only [embedding_pi_tangent_coe, continuous_linear_map.coe_comp', (∘), continuous_linear_map.coe_fst', continuous_linear_map.proj_apply], rw [hy, pi.one_apply, one_smul] end lemma embedding_pi_tangent_ker_mfderiv (x : M) (hx : x ∈ s) : (mfderiv I 𝓘(ℝ, fs.ι → (E × ℝ)) fs.embedding_pi_tangent x).ker = ⊥ := begin apply bot_unique, rw [← (mdifferentiable_chart I (fs.c (fs.ind x hx))).ker_mfderiv_eq_bot (fs.mem_chart_at_ind_source x hx), ← comp_embedding_pi_tangent_mfderiv], exact linear_map.ker_le_ker_comp _ _ end lemma embedding_pi_tangent_injective_mfderiv (x : M) (hx : x ∈ s) : injective (mfderiv I 𝓘(ℝ, fs.ι → (E × ℝ)) fs.embedding_pi_tangent x) := linear_map.ker_eq_bot.1 (fs.embedding_pi_tangent_ker_mfderiv x hx) end embedding /-- Baby version of the Whitney weak embedding theorem: if `M` admits a finite covering by supports of bump functions, then for some `n` it can be immersed into the `n`-dimensional Euclidean space. -/ lemma exists_immersion_finrank [t2_space M] (f : smooth_bump_covering I (univ : set M)) [fintype f.ι] : ∃ (n : ℕ) (e : M → euclidean_space ℝ (fin n)), smooth I (𝓡 n) e ∧ injective e ∧ ∀ x : M, injective (mfderiv I (𝓡 n) e x) := begin set F := euclidean_space ℝ (fin $ finrank ℝ (f.ι → (E × ℝ))), letI : finite_dimensional ℝ (E × ℝ) := by apply_instance, set eEF : (f.ι → (E × ℝ)) ≃L[ℝ] F := continuous_linear_equiv.of_finrank_eq finrank_euclidean_space_fin.symm, refine ⟨_, eEF ∘ f.embedding_pi_tangent, eEF.to_diffeomorph.smooth.comp f.embedding_pi_tangent.smooth, eEF.injective.comp f.embedding_pi_tangent_injective, λ x, _⟩, rw [mfderiv_comp _ eEF.differentiable_at.mdifferentiable_at f.embedding_pi_tangent.mdifferentiable_at, eEF.mfderiv_eq], exact eEF.injective.comp (f.embedding_pi_tangent_injective_mfderiv _ trivial) end end smooth_bump_covering /-- Baby version of the Whitney weak embedding theorem: if `M` admits a finite covering by supports of bump functions, then for some `n` it can be embedded into the `n`-dimensional Euclidean space. -/ lemma exists_embedding_finrank_of_compact [t2_space M] [compact_space M] : ∃ (n : ℕ) (e : M → euclidean_space ℝ (fin n)), smooth I (𝓡 n) e ∧ closed_embedding e ∧ ∀ x : M, injective (mfderiv I (𝓡 n) e x) := begin rcases (smooth_bump_covering.choice I M).exists_immersion_finrank with ⟨n, e, hsmooth, hinj, hinj_mfderiv⟩, exact ⟨n, e, hsmooth, hsmooth.continuous.closed_embedding hinj, hinj_mfderiv⟩ end
d3558b0e91330be898684a1542ab82ca5da5ea7d
5915a2aa3eb6444e6ae7e5cb3c795ac9e1986066
/src/topology/algebra/group.lean
76526560a96fb9c24133a16a746084deadf5a8ca
[ "Apache-2.0" ]
permissive
petari52/mathlib
44200ab49933b86373e8e3ff183d6fea59c33ca1
e8bdc7fc14c6d56d4040892d16929f310e9d03d5
refs/heads/master
1,588,162,505,688
1,552,831,653,000
1,552,831,653,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,675
lean
/- Copyright (c) 2017 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl, Mario Carneiro, Patrick Massot Theory of topological groups. -/ import data.equiv.algebra import group_theory.quotient_group import topology.algebra.monoid topology.order open classical set lattice filter topological_space local attribute [instance] classical.prop_decidable universes u v w variables {α : Type u} {β : Type v} {γ : Type w} section topological_group /-- A topological group is a group in which the multiplication and inversion operations are continuous. -/ class topological_group (α : Type*) [topological_space α] [group α] extends topological_monoid α : Prop := (continuous_inv : continuous (λa:α, a⁻¹)) /-- A topological (additive) group is a group in which the addition and negation operations are continuous. -/ class topological_add_group (α : Type u) [topological_space α] [add_group α] extends topological_add_monoid α : Prop := (continuous_neg : continuous (λa:α, -a)) attribute [to_additive topological_add_group] topological_group attribute [to_additive topological_add_group.mk] topological_group.mk attribute [to_additive topological_add_group.continuous_neg] topological_group.continuous_inv attribute [to_additive topological_add_group.to_topological_add_monoid] topological_group.to_topological_monoid variables [topological_space α] [group α] @[to_additive continuous_neg'] lemma continuous_inv' [topological_group α] : continuous (λx:α, x⁻¹) := topological_group.continuous_inv α @[to_additive continuous_neg] lemma continuous_inv [topological_group α] [topological_space β] {f : β → α} (hf : continuous f) : continuous (λx, (f x)⁻¹) := hf.comp continuous_inv' @[to_additive tendsto_neg] lemma tendsto_inv [topological_group α] {f : β → α} {x : filter β} {a : α} (hf : tendsto f x (nhds a)) : tendsto (λx, (f x)⁻¹) x (nhds a⁻¹) := hf.comp (continuous_iff_continuous_at.mp (topological_group.continuous_inv α) a) @[to_additive prod.topological_add_group] instance [topological_group α] [topological_space β] [group β] [topological_group β] : topological_group (α × β) := { continuous_inv := continuous.prod_mk (continuous_inv continuous_fst) (continuous_inv continuous_snd) } attribute [instance] prod.topological_add_group protected def homeomorph.mul_left [topological_group α] (a : α) : α ≃ₜ α := { continuous_to_fun := continuous_mul continuous_const continuous_id, continuous_inv_fun := continuous_mul continuous_const continuous_id, .. equiv.mul_left a } attribute [to_additive homeomorph.add_left._proof_1] homeomorph.mul_left._proof_1 attribute [to_additive homeomorph.add_left._proof_2] homeomorph.mul_left._proof_2 attribute [to_additive homeomorph.add_left._proof_3] homeomorph.mul_left._proof_3 attribute [to_additive homeomorph.add_left._proof_4] homeomorph.mul_left._proof_4 attribute [to_additive homeomorph.add_left] homeomorph.mul_left @[to_additive is_open_map_add_left] lemma is_open_map_mul_left [topological_group α] (a : α) : is_open_map (λ x, a * x) := (homeomorph.mul_left a).is_open_map protected def homeomorph.mul_right {α : Type*} [topological_space α] [group α] [topological_group α] (a : α) : α ≃ₜ α := { continuous_to_fun := continuous_mul continuous_id continuous_const, continuous_inv_fun := continuous_mul continuous_id continuous_const, .. equiv.mul_right a } attribute [to_additive homeomorph.add_right._proof_1] homeomorph.mul_right._proof_1 attribute [to_additive homeomorph.add_right._proof_2] homeomorph.mul_right._proof_2 attribute [to_additive homeomorph.add_right._proof_3] homeomorph.mul_right._proof_3 attribute [to_additive homeomorph.add_right._proof_4] homeomorph.mul_right._proof_4 attribute [to_additive homeomorph.add_right] homeomorph.mul_right @[to_additive is_open_map_add_right] lemma is_open_map_mul_right [topological_group α] (a : α) : is_open_map (λ x, x * a) := (homeomorph.mul_right a).is_open_map protected def homeomorph.inv (α : Type*) [topological_space α] [group α] [topological_group α] : α ≃ₜ α := { continuous_to_fun := continuous_inv', continuous_inv_fun := continuous_inv', .. equiv.inv α } attribute [to_additive homeomorph.neg._proof_1] homeomorph.inv._proof_1 attribute [to_additive homeomorph.neg._proof_2] homeomorph.inv._proof_2 attribute [to_additive homeomorph.neg] homeomorph.inv @[to_additive exists_nhds_half] lemma exists_nhds_split [topological_group α] {s : set α} (hs : s ∈ nhds (1 : α)) : ∃ V ∈ nhds (1 : α), ∀ v w ∈ V, v * w ∈ s := begin have : ((λa:α×α, a.1 * a.2) ⁻¹' s) ∈ nhds ((1, 1) : α × α) := tendsto_mul' (by simpa using hs), rw nhds_prod_eq at this, rcases mem_prod_iff.1 this with ⟨V₁, H₁, V₂, H₂, H⟩, exact ⟨V₁ ∩ V₂, inter_mem_sets H₁ H₂, assume v w ⟨hv, _⟩ ⟨_, hw⟩, @H (v, w) ⟨hv, hw⟩⟩ end @[to_additive exists_nhds_half_neg] lemma exists_nhds_split_inv [topological_group α] {s : set α} (hs : s ∈ nhds (1 : α)) : ∃ V ∈ nhds (1 : α), ∀ v w ∈ V, v * w⁻¹ ∈ s := begin have : tendsto (λa:α×α, a.1 * (a.2)⁻¹) ((nhds (1:α)).prod (nhds (1:α))) (nhds 1), { simpa using tendsto_mul (@tendsto_fst α α (nhds 1) (nhds 1)) (tendsto_inv tendsto_snd) }, have : ((λa:α×α, a.1 * (a.2)⁻¹) ⁻¹' s) ∈ (nhds (1:α)).prod (nhds (1:α)) := this (by simpa using hs), rcases mem_prod_iff.1 this with ⟨V₁, H₁, V₂, H₂, H⟩, exact ⟨V₁ ∩ V₂, inter_mem_sets H₁ H₂, assume v w ⟨hv, _⟩ ⟨_, hw⟩, @H (v, w) ⟨hv, hw⟩⟩ end @[to_additive exists_nhds_quarter] lemma exists_nhds_split4 [topological_group α] {u : set α} (hu : u ∈ nhds (1 : α)) : ∃ V ∈ nhds (1 : α), ∀ {v w s t}, v ∈ V → w ∈ V → s ∈ V → t ∈ V → v * w * s * t ∈ u := begin rcases exists_nhds_split hu with ⟨W, W_nhd, h⟩, rcases exists_nhds_split W_nhd with ⟨V, V_nhd, h'⟩, existsi [V, V_nhd], intros v w s t v_in w_in s_in t_in, simpa [mul_assoc] using h _ _ (h' v w v_in w_in) (h' s t s_in t_in) end section variable (α) @[to_additive nhds_zero_symm] lemma nhds_one_symm [topological_group α] : comap (λr:α, r⁻¹) (nhds (1 : α)) = nhds (1 : α) := begin have lim : tendsto (λr:α, r⁻¹) (nhds 1) (nhds 1), { simpa using tendsto_inv (@tendsto_id α (nhds 1)) }, refine comap_eq_of_inverse _ _ lim lim, { funext x, simp }, end end @[to_additive nhds_translation_add_neg] lemma nhds_translation_mul_inv [topological_group α] (x : α) : comap (λy:α, y * x⁻¹) (nhds 1) = nhds x := begin refine comap_eq_of_inverse (λy:α, y * x) _ _ _, { funext x; simp }, { suffices : tendsto (λy:α, y * x⁻¹) (nhds x) (nhds (x * x⁻¹)), { simpa }, exact tendsto_mul tendsto_id tendsto_const_nhds }, { suffices : tendsto (λy:α, y * x) (nhds 1) (nhds (1 * x)), { simpa }, exact tendsto_mul tendsto_id tendsto_const_nhds } end @[to_additive topological_add_group.ext] lemma topological_group.ext {G : Type*} [group G] {t t' : topological_space G} [tg : @topological_group G t _] [tg' : @topological_group G t' _] (h : @nhds G t 1 = @nhds G t' 1) : t = t' := eq_of_nhds_eq_nhds $ λ x, by rw [← @nhds_translation_mul_inv G t _ _ x , ← @nhds_translation_mul_inv G t' _ _ x , ← h] end topological_group section quotient_topological_group variables [topological_space α] [group α] [topological_group α] (N : set α) [normal_subgroup N] @[to_additive quotient_add_group.quotient.topological_space] instance : topological_space (quotient_group.quotient N) := by dunfold quotient_group.quotient; apply_instance attribute [instance] quotient_add_group.quotient.topological_space open quotient_group @[to_additive quotient_add_group_saturate] lemma quotient_group_saturate (s : set α) : (coe : α → quotient N) ⁻¹' ((coe : α → quotient N) '' s) = (⋃ x : N, (λ y, y*x.1) '' s) := begin ext x, simp only [mem_preimage_eq, mem_image, mem_Union, quotient_group.eq], split, { exact assume ⟨a, a_in, h⟩, ⟨⟨_, h⟩, a, a_in, mul_inv_cancel_left _ _⟩ }, { exact assume ⟨⟨i, hi⟩, a, ha, eq⟩, ⟨a, ha, by simp only [eq.symm, (mul_assoc _ _ _).symm, inv_mul_cancel_left, hi]⟩ } end @[to_additive quotient_add_group.open_coe] lemma quotient_group.open_coe : is_open_map (coe : α → quotient N) := begin intros s s_op, change is_open ((coe : α → quotient N) ⁻¹' (coe '' s)), rw quotient_group_saturate N s, apply is_open_Union, rintro ⟨n, _⟩, exact is_open_map_mul_right n s s_op end @[to_additive topological_add_group_quotient] instance topological_group_quotient : topological_group (quotient N) := { continuous_mul := begin have cont : continuous ((coe : α → quotient N) ∘ (λ (p : α × α), p.fst * p.snd)) := continuous.comp continuous_mul' continuous_quot_mk, have quot : quotient_map (λ p : α × α, ((p.1:quotient N), (p.2:quotient N))), { apply is_open_map.to_quotient_map, { exact is_open_map.prod (quotient_group.open_coe N) (quotient_group.open_coe N) }, { apply continuous.prod_mk, { exact continuous.comp continuous_fst continuous_quot_mk }, { exact continuous.comp continuous_snd continuous_quot_mk } }, { rintro ⟨⟨x⟩, ⟨y⟩⟩, exact ⟨(x, y), rfl⟩ } }, exact (quotient_map.continuous_iff quot).2 cont, end, continuous_inv := begin apply continuous_quotient_lift, change continuous ((coe : α → quotient N) ∘ (λ (a : α), a⁻¹)), exact continuous.comp continuous_inv' continuous_quot_mk end } attribute [instance] topological_add_group_quotient end quotient_topological_group section topological_add_group variables [topological_space α] [add_group α] lemma continuous_sub [topological_add_group α] [topological_space β] {f : β → α} {g : β → α} (hf : continuous f) (hg : continuous g) : continuous (λx, f x - g x) := by simp; exact continuous_add hf (continuous_neg hg) lemma continuous_sub' [topological_add_group α] : continuous (λp:α×α, p.1 - p.2) := continuous_sub continuous_fst continuous_snd lemma tendsto_sub [topological_add_group α] {f : β → α} {g : β → α} {x : filter β} {a b : α} (hf : tendsto f x (nhds a)) (hg : tendsto g x (nhds b)) : tendsto (λx, f x - g x) x (nhds (a - b)) := by simp; exact tendsto_add hf (tendsto_neg hg) lemma nhds_translation [topological_add_group α] (x : α) : comap (λy:α, y - x) (nhds 0) = nhds x := nhds_translation_add_neg x end topological_add_group /-- additive group with a neighbourhood around 0. Only used to construct a topology and uniform space. This is currently only available for commutative groups, but it can be extended to non-commutative groups too. -/ class add_group_with_zero_nhd (α : Type u) extends add_comm_group α := (Z : filter α) (zero_Z {} : pure 0 ≤ Z) (sub_Z {} : tendsto (λp:α×α, p.1 - p.2) (Z.prod Z) Z) namespace add_group_with_zero_nhd variables (α) [add_group_with_zero_nhd α] local notation `Z` := add_group_with_zero_nhd.Z instance : topological_space α := topological_space.mk_of_nhds $ λa, map (λx, x + a) (Z α) variables {α} lemma neg_Z : tendsto (λa:α, - a) (Z α) (Z α) := have tendsto (λa, (0:α)) (Z α) (Z α), by refine le_trans (assume h, _) zero_Z; simp [univ_mem_sets'] {contextual := tt}, have tendsto (λa:α, 0 - a) (Z α) (Z α), from (tendsto.prod_mk this tendsto_id).comp sub_Z, by simpa lemma add_Z : tendsto (λp:α×α, p.1 + p.2) ((Z α).prod (Z α)) (Z α) := suffices tendsto (λp:α×α, p.1 - -p.2) ((Z α).prod (Z α)) (Z α), by simpa, (tendsto.prod_mk tendsto_fst (tendsto_snd.comp neg_Z)).comp sub_Z lemma exists_Z_half {s : set α} (hs : s ∈ Z α) : ∃ V ∈ Z α, ∀ v w ∈ V, v + w ∈ s := begin have : ((λa:α×α, a.1 + a.2) ⁻¹' s) ∈ (Z α).prod (Z α) := add_Z (by simpa using hs), rcases mem_prod_iff.1 this with ⟨V₁, H₁, V₂, H₂, H⟩, exact ⟨V₁ ∩ V₂, inter_mem_sets H₁ H₂, assume v w ⟨hv, _⟩ ⟨_, hw⟩, @H (v, w) ⟨hv, hw⟩⟩ end lemma nhds_eq (a : α) : nhds a = map (λx, x + a) (Z α) := topological_space.nhds_mk_of_nhds _ _ (assume a, calc pure a = map (λx, x + a) (pure 0) : by simp ... ≤ _ : map_mono zero_Z) (assume b s hs, let ⟨t, ht, eqt⟩ := exists_Z_half hs in have t0 : (0:α) ∈ t, by simpa using zero_Z ht, begin refine ⟨(λx:α, x + b) '' t, image_mem_map ht, _, _⟩, { refine set.image_subset_iff.2 (assume b hbt, _), simpa using eqt 0 b t0 hbt }, { rintros _ ⟨c, hb, rfl⟩, refine (Z α).sets_of_superset ht (assume x hxt, _), simpa using eqt _ _ hxt hb } end) lemma nhds_zero_eq_Z : nhds 0 = Z α := by simp [nhds_eq]; exact filter.map_id instance : topological_add_monoid α := ⟨ continuous_iff_continuous_at.2 $ assume ⟨a, b⟩, begin rw [continuous_at, nhds_prod_eq, nhds_eq, nhds_eq, nhds_eq, filter.prod_map_map_eq, tendsto_map'_iff], suffices : tendsto ((λx:α, (a + b) + x) ∘ (λp:α×α,p.1 + p.2)) (filter.prod (Z α) (Z α)) (map (λx:α, (a + b) + x) (Z α)), { simpa [(∘)] }, exact add_Z.comp tendsto_map end⟩ instance : topological_add_group α := ⟨continuous_iff_continuous_at.2 $ assume a, begin rw [continuous_at, nhds_eq, nhds_eq, tendsto_map'_iff], suffices : tendsto ((λx:α, x - a) ∘ (λx:α, -x)) (Z α) (map (λx:α, x - a) (Z α)), { simpa [(∘)] }, exact neg_Z.comp tendsto_map end⟩ end add_group_with_zero_nhd
aa83b54df4a8c987afeb6a9720bcb9dedcf9656b
0e175f34f8dca5ea099671777e8d7446d7d74227
/library/init/data/int/basic.lean
4c52a0f09601e781a3204e770b62f5b2331081be
[ "Apache-2.0" ]
permissive
utensil-contrib/lean
b31266738071c654d96dac8b35d9ccffc8172fda
a28b9c8f78d982a4e82b1e4f7ce7988d87183ae8
refs/heads/master
1,670,045,564,075
1,597,397,599,000
1,597,397,599,000
287,528,503
0
0
Apache-2.0
1,597,408,338,000
1,597,408,337,000
null
UTF-8
Lean
false
false
23,417
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 integers, with addition, multiplication, and subtraction. -/ prelude import init.data.nat.lemmas init.data.nat.gcd open nat /- the type, coercions, and notation -/ @[derive decidable_eq] inductive int : Type | of_nat : nat → int | neg_succ_of_nat : nat → int notation `ℤ` := int instance : has_coe nat int := ⟨int.of_nat⟩ notation `-[1+ ` n `]` := int.neg_succ_of_nat n protected def int.repr : int → string | (int.of_nat n) := repr n | (int.neg_succ_of_nat n) := "-" ++ repr (succ n) instance : has_repr int := ⟨int.repr⟩ instance : has_to_string int := ⟨int.repr⟩ namespace int protected lemma coe_nat_eq (n : ℕ) : ↑n = int.of_nat n := rfl protected def zero : ℤ := of_nat 0 protected def one : ℤ := of_nat 1 instance : has_zero ℤ := ⟨int.zero⟩ instance : has_one ℤ := ⟨int.one⟩ lemma of_nat_zero : of_nat (0 : nat) = (0 : int) := rfl lemma of_nat_one : of_nat (1 : nat) = (1 : int) := rfl /- definitions of basic functions -/ def neg_of_nat : ℕ → ℤ | 0 := 0 | (succ m) := -[1+ m] def sub_nat_nat (m n : ℕ) : ℤ := match (n - m : nat) with | 0 := of_nat (m - n) -- m ≥ n | (succ k) := -[1+ k] -- m < n, and n - m = succ k end private lemma sub_nat_nat_of_sub_eq_zero {m n : ℕ} (h : n - m = 0) : sub_nat_nat m n = of_nat (m - n) := begin unfold sub_nat_nat, rw h, unfold sub_nat_nat._match_1 end private lemma sub_nat_nat_of_sub_eq_succ {m n k : ℕ} (h : n - m = succ k) : sub_nat_nat m n = -[1+ k] := begin unfold sub_nat_nat, rw h, unfold sub_nat_nat._match_1 end protected def neg : ℤ → ℤ | (of_nat n) := neg_of_nat n | -[1+ n] := succ n protected def add : ℤ → ℤ → ℤ | (of_nat m) (of_nat n) := of_nat (m + n) | (of_nat m) -[1+ n] := sub_nat_nat m (succ n) | -[1+ m] (of_nat n) := sub_nat_nat n (succ m) | -[1+ m] -[1+ n] := -[1+ succ (m + n)] protected def mul : ℤ → ℤ → ℤ | (of_nat m) (of_nat n) := of_nat (m * n) | (of_nat m) -[1+ n] := neg_of_nat (m * succ n) | -[1+ m] (of_nat n) := neg_of_nat (succ m * n) | -[1+ m] -[1+ n] := of_nat (succ m * succ n) instance : has_neg ℤ := ⟨int.neg⟩ instance : has_add ℤ := ⟨int.add⟩ instance : has_mul ℤ := ⟨int.mul⟩ -- defeq to algebra.sub which gives subtraction for arbitrary `add_group`s protected def sub : ℤ → ℤ → ℤ := λ m n, m + -n instance : has_sub ℤ := ⟨int.sub⟩ protected lemma neg_zero : -(0:ℤ) = 0 := rfl lemma of_nat_add (n m : ℕ) : of_nat (n + m) = of_nat n + of_nat m := rfl lemma of_nat_mul (n m : ℕ) : of_nat (n * m) = of_nat n * of_nat m := rfl lemma of_nat_succ (n : ℕ) : of_nat (succ n) = of_nat n + 1 := rfl lemma neg_of_nat_zero : -(of_nat 0) = 0 := rfl lemma neg_of_nat_of_succ (n : ℕ) : -(of_nat (succ n)) = -[1+ n] := rfl lemma neg_neg_of_nat_succ (n : ℕ) : -(-[1+ n]) = of_nat (succ n) := rfl lemma of_nat_eq_coe (n : ℕ) : of_nat n = ↑n := rfl lemma neg_succ_of_nat_coe (n : ℕ) : -[1+ n] = -↑(n + 1) := rfl protected lemma coe_nat_add (m n : ℕ) : (↑(m + n) : ℤ) = ↑m + ↑n := rfl protected lemma coe_nat_mul (m n : ℕ) : (↑(m * n) : ℤ) = ↑m * ↑n := rfl protected lemma coe_nat_zero : ↑(0 : ℕ) = (0 : ℤ) := rfl protected lemma coe_nat_one : ↑(1 : ℕ) = (1 : ℤ) := rfl protected lemma coe_nat_succ (n : ℕ) : (↑(succ n) : ℤ) = ↑n + 1 := rfl protected lemma coe_nat_add_out (m n : ℕ) : ↑m + ↑n = (m + n : ℤ) := rfl protected lemma coe_nat_mul_out (m n : ℕ) : ↑m * ↑n = (↑(m * n) : ℤ) := rfl protected lemma coe_nat_add_one_out (n : ℕ) : ↑n + (1 : ℤ) = ↑(succ n) := rfl /- these are only for internal use -/ private lemma of_nat_add_of_nat (m n : nat) : of_nat m + of_nat n = of_nat (m + n) := rfl private lemma of_nat_add_neg_succ_of_nat (m n : nat) : of_nat m + -[1+ n] = sub_nat_nat m (succ n) := rfl private lemma neg_succ_of_nat_add_of_nat (m n : nat) : -[1+ m] + of_nat n = sub_nat_nat n (succ m) := rfl private lemma neg_succ_of_nat_add_neg_succ_of_nat (m n : nat) : -[1+ m] + -[1+ n] = -[1+ succ (m + n)] := rfl private lemma of_nat_mul_of_nat (m n : nat) : of_nat m * of_nat n = of_nat (m * n) := rfl private lemma of_nat_mul_neg_succ_of_nat (m n : nat) : of_nat m * -[1+ n] = neg_of_nat (m * succ n) := rfl private lemma neg_succ_of_nat_of_nat (m n : nat) : -[1+ m] * of_nat n = neg_of_nat (succ m * n) := rfl private lemma mul_neg_succ_of_nat_neg_succ_of_nat (m n : nat) : -[1+ m] * -[1+ n] = of_nat (succ m * succ n) := rfl local attribute [simp] of_nat_add_of_nat of_nat_mul_of_nat neg_of_nat_zero neg_of_nat_of_succ neg_neg_of_nat_succ of_nat_add_neg_succ_of_nat neg_succ_of_nat_add_of_nat neg_succ_of_nat_add_neg_succ_of_nat of_nat_mul_neg_succ_of_nat neg_succ_of_nat_of_nat mul_neg_succ_of_nat_neg_succ_of_nat /- some basic functions and properties -/ protected lemma coe_nat_inj {m n : ℕ} (h : (↑m : ℤ) = ↑n) : m = n := int.of_nat.inj h lemma of_nat_eq_of_nat_iff (m n : ℕ) : of_nat m = of_nat n ↔ m = n := iff.intro int.of_nat.inj (congr_arg _) protected lemma coe_nat_eq_coe_nat_iff (m n : ℕ) : (↑m : ℤ) = ↑n ↔ m = n := of_nat_eq_of_nat_iff m n lemma neg_succ_of_nat_inj_iff {m n : ℕ} : neg_succ_of_nat m = neg_succ_of_nat n ↔ m = n := ⟨neg_succ_of_nat.inj, assume H, by simp [H]⟩ lemma neg_succ_of_nat_eq (n : ℕ) : -[1+ n] = -(n + 1) := rfl /- neg -/ protected lemma neg_neg : ∀ a : ℤ, -(-a) = a | (of_nat 0) := rfl | (of_nat (n+1)) := rfl | -[1+ n] := rfl protected lemma neg_inj {a b : ℤ} (h : -a = -b) : a = b := by rw [← int.neg_neg a, ← int.neg_neg b, h] protected lemma sub_eq_add_neg {a b : ℤ} : a - b = a + -b := rfl /- basic properties of sub_nat_nat -/ lemma sub_nat_nat_elim (m n : ℕ) (P : ℕ → ℕ → ℤ → Prop) (hp : ∀i n, P (n + i) n (of_nat i)) (hn : ∀i m, P m (m + i + 1) (-[1+ i])) : P m n (sub_nat_nat m n) := begin have H : ∀k, n - m = k → P m n (nat.cases_on k (of_nat (m - n)) (λa, -[1+ a])), { intro k, cases k, { intro e, cases (nat.le.dest (nat.le_of_sub_eq_zero e)) with k h, rw [h.symm, nat.add_sub_cancel_left], apply hp }, { intro heq, have h : m ≤ n, { exact nat.le_of_lt (nat.lt_of_sub_eq_succ heq) }, rw [nat.sub_eq_iff_eq_add h] at heq, rw [heq, nat.add_comm], apply hn } }, delta sub_nat_nat, exact H _ rfl end private lemma sub_nat_nat_add_left {m n : ℕ} : sub_nat_nat (m + n) m = of_nat n := begin dunfold sub_nat_nat, rw [nat.sub_eq_zero_of_le], dunfold sub_nat_nat._match_1, rw [nat.add_sub_cancel_left], apply nat.le_add_right end private lemma sub_nat_nat_add_right {m n : ℕ} : sub_nat_nat m (m + n + 1) = neg_succ_of_nat n := calc sub_nat_nat._match_1 m (m + n + 1) (m + n + 1 - m) = sub_nat_nat._match_1 m (m + n + 1) (m + (n + 1) - m) : by rw [nat.add_assoc] ... = sub_nat_nat._match_1 m (m + n + 1) (n + 1) : by rw [nat.add_sub_cancel_left] ... = neg_succ_of_nat n : rfl private lemma sub_nat_nat_add_add (m n k : ℕ) : sub_nat_nat (m + k) (n + k) = sub_nat_nat m n := sub_nat_nat_elim m n (λm n i, sub_nat_nat (m + k) (n + k) = i) (assume i n, have n + i + k = (n + k) + i, by simp [nat.add_comm, nat.add_left_comm], begin rw [this], exact sub_nat_nat_add_left end) (assume i m, have m + i + 1 + k = (m + k) + i + 1, by simp [nat.add_comm, nat.add_left_comm], begin rw [this], exact sub_nat_nat_add_right end) private lemma sub_nat_nat_of_ge {m n : ℕ} (h : m ≥ n) : sub_nat_nat m n = of_nat (m - n) := sub_nat_nat_of_sub_eq_zero (sub_eq_zero_of_le h) private lemma sub_nat_nat_of_lt {m n : ℕ} (h : m < n) : sub_nat_nat m n = -[1+ pred (n - m)] := have n - m = succ (pred (n - m)), from eq.symm (succ_pred_eq_of_pos (nat.sub_pos_of_lt h)), by rewrite sub_nat_nat_of_sub_eq_succ this /- nat_abs -/ @[simp] def nat_abs : ℤ → ℕ | (of_nat m) := m | -[1+ m] := succ m lemma nat_abs_of_nat (n : ℕ) : nat_abs ↑n = n := rfl lemma eq_zero_of_nat_abs_eq_zero : Π {a : ℤ}, nat_abs a = 0 → a = 0 | (of_nat m) H := congr_arg of_nat H | -[1+ m'] H := absurd H (succ_ne_zero _) lemma nat_abs_pos_of_ne_zero {a : ℤ} (h : a ≠ 0) : nat_abs a > 0 := (eq_zero_or_pos _).resolve_left $ mt eq_zero_of_nat_abs_eq_zero h lemma nat_abs_zero : nat_abs (0 : int) = (0 : nat) := rfl lemma nat_abs_one : nat_abs (1 : int) = (1 : nat) := rfl lemma nat_abs_mul_self : Π {a : ℤ}, ↑(nat_abs a * nat_abs a) = a * a | (of_nat m) := rfl | -[1+ m'] := rfl @[simp] lemma nat_abs_neg (a : ℤ) : nat_abs (-a) = nat_abs a := by {cases a with n n, cases n; refl, refl} lemma nat_abs_eq : Π (a : ℤ), a = nat_abs a ∨ a = -(nat_abs a) | (of_nat m) := or.inl rfl | -[1+ m'] := or.inr rfl lemma eq_coe_or_neg (a : ℤ) : ∃n : ℕ, a = n ∨ a = -n := ⟨_, nat_abs_eq a⟩ /- sign -/ def sign : ℤ → ℤ | (n+1:ℕ) := 1 | 0 := 0 | -[1+ n] := -1 @[simp] theorem sign_zero : sign 0 = 0 := rfl @[simp] theorem sign_one : sign 1 = 1 := rfl @[simp] theorem sign_neg_one : sign (-1) = -1 := rfl /- Quotient and remainder -/ -- There are three main conventions for integer division, -- referred here as the E, F, T rounding conventions. -- All three pairs satisfy the identity x % y + (x / y) * y = x -- unconditionally. -- E-rounding: This pair satisfies 0 ≤ mod x y < nat_abs y for y ≠ 0 protected def div : ℤ → ℤ → ℤ | (m : ℕ) (n : ℕ) := of_nat (m / n) | (m : ℕ) -[1+ n] := -of_nat (m / succ n) | -[1+ m] 0 := 0 | -[1+ m] (n+1:ℕ) := -[1+ m / succ n] | -[1+ m] -[1+ n] := of_nat (succ (m / succ n)) protected def mod : ℤ → ℤ → ℤ | (m : ℕ) n := (m % nat_abs n : ℕ) | -[1+ m] n := sub_nat_nat (nat_abs n) (succ (m % nat_abs n)) -- F-rounding: This pair satisfies fdiv x y = floor (x / y) def fdiv : ℤ → ℤ → ℤ | 0 _ := 0 | (m : ℕ) (n : ℕ) := of_nat (m / n) | (m+1:ℕ) -[1+ n] := -[1+ m / succ n] | -[1+ m] 0 := 0 | -[1+ m] (n+1:ℕ) := -[1+ m / succ n] | -[1+ m] -[1+ n] := of_nat (succ m / succ n) def fmod : ℤ → ℤ → ℤ | 0 _ := 0 | (m : ℕ) (n : ℕ) := of_nat (m % n) | (m+1:ℕ) -[1+ n] := sub_nat_nat (m % succ n) n | -[1+ m] (n : ℕ) := sub_nat_nat n (succ (m % n)) | -[1+ m] -[1+ n] := -of_nat (succ m % succ n) -- T-rounding: This pair satisfies quot x y = round_to_zero (x / y) def quot : ℤ → ℤ → ℤ | (of_nat m) (of_nat n) := of_nat (m / n) | (of_nat m) -[1+ n] := -of_nat (m / succ n) | -[1+ m] (of_nat n) := -of_nat (succ m / n) | -[1+ m] -[1+ n] := of_nat (succ m / succ n) def rem : ℤ → ℤ → ℤ | (of_nat m) (of_nat n) := of_nat (m % n) | (of_nat m) -[1+ n] := of_nat (m % succ n) | -[1+ m] (of_nat n) := -of_nat (succ m % n) | -[1+ m] -[1+ n] := -of_nat (succ m % succ n) instance : has_div ℤ := ⟨int.div⟩ instance : has_mod ℤ := ⟨int.mod⟩ /- gcd -/ def gcd (m n : ℤ) : ℕ := gcd (nat_abs m) (nat_abs n) /- int is a ring -/ /- addition -/ protected lemma add_comm : ∀ a b : ℤ, a + b = b + a | (of_nat n) (of_nat m) := by simp [nat.add_comm] | (of_nat n) -[1+ m] := rfl | -[1+ n] (of_nat m) := rfl | -[1+ n] -[1+m] := by simp [nat.add_comm] protected lemma add_zero : ∀ a : ℤ, a + 0 = a | (of_nat n) := rfl | -[1+ n] := rfl protected lemma zero_add (a : ℤ) : 0 + a = a := int.add_comm a 0 ▸ int.add_zero a private lemma sub_nat_nat_sub {m n : ℕ} (h : m ≥ n) (k : ℕ) : sub_nat_nat (m - n) k = sub_nat_nat m (k + n) := calc sub_nat_nat (m - n) k = sub_nat_nat (m - n + n) (k + n) : by rewrite [sub_nat_nat_add_add] ... = sub_nat_nat m (k + n) : by rewrite [nat.sub_add_cancel h] private lemma sub_nat_nat_add (m n k : ℕ) : sub_nat_nat (m + n) k = of_nat m + sub_nat_nat n k := begin have h := le_or_gt k n, cases h with h' h', { rw [sub_nat_nat_of_ge h'], have h₂ : k ≤ m + n, exact (le_trans h' (le_add_left _ _)), rw [sub_nat_nat_of_ge h₂], simp, rw nat.add_sub_assoc h' }, rw [sub_nat_nat_of_lt h'], simp, rw [succ_pred_eq_of_pos (nat.sub_pos_of_lt h')], transitivity, rw [← nat.sub_add_cancel (le_of_lt h')], apply sub_nat_nat_add_add end private lemma sub_nat_nat_add_neg_succ_of_nat (m n k : ℕ) : sub_nat_nat m n + -[1+ k] = sub_nat_nat m (n + succ k) := begin have h := le_or_gt n m, cases h with h' h', { rw [sub_nat_nat_of_ge h'], simp, rw [sub_nat_nat_sub h', nat.add_comm] }, have h₂ : m < n + succ k, exact nat.lt_of_lt_of_le h' (le_add_right _ _), have h₃ : m ≤ n + k, exact le_of_succ_le_succ h₂, rw [sub_nat_nat_of_lt h', sub_nat_nat_of_lt h₂], simp [nat.add_comm], rw [← add_succ, succ_pred_eq_of_pos (nat.sub_pos_of_lt h'), add_succ, succ_sub h₃, pred_succ], rw [nat.add_comm n, nat.add_sub_assoc (le_of_lt h')] end private lemma add_assoc_aux1 (m n : ℕ) : ∀ c : ℤ, of_nat m + of_nat n + c = of_nat m + (of_nat n + c) | (of_nat k) := by simp [nat.add_assoc] | -[1+ k] := by simp [sub_nat_nat_add] private lemma add_assoc_aux2 (m n k : ℕ) : -[1+ m] + -[1+ n] + of_nat k = -[1+ m] + (-[1+ n] + of_nat k) := begin simp [add_succ], rw [int.add_comm, sub_nat_nat_add_neg_succ_of_nat], simp [add_succ, succ_add, nat.add_comm] end protected lemma add_assoc : ∀ a b c : ℤ, a + b + c = a + (b + c) | (of_nat m) (of_nat n) c := add_assoc_aux1 _ _ _ | (of_nat m) b (of_nat k) := by rw [int.add_comm, ← add_assoc_aux1, int.add_comm (of_nat k), add_assoc_aux1, int.add_comm b] | a (of_nat n) (of_nat k) := by rw [int.add_comm, int.add_comm a, ← add_assoc_aux1, int.add_comm a, int.add_comm (of_nat k)] | -[1+ m] -[1+ n] (of_nat k) := add_assoc_aux2 _ _ _ | -[1+ m] (of_nat n) -[1+ k] := by rw [int.add_comm, ← add_assoc_aux2, int.add_comm (of_nat n), ← add_assoc_aux2, int.add_comm -[1+ m] ] | (of_nat m) -[1+ n] -[1+ k] := by rw [int.add_comm, int.add_comm (of_nat m), int.add_comm (of_nat m), ← add_assoc_aux2, int.add_comm -[1+ k] ] | -[1+ m] -[1+ n] -[1+ k] := by simp [add_succ, nat.add_comm, nat.add_left_comm, neg_of_nat_of_succ] /- negation -/ private lemma sub_nat_self : ∀ n, sub_nat_nat n n = 0 | 0 := rfl | (succ m) := begin rw [sub_nat_nat_of_sub_eq_zero, nat.sub_self, of_nat_zero], rw nat.sub_self end local attribute [simp] sub_nat_self protected lemma add_left_neg : ∀ a : ℤ, -a + a = 0 | (of_nat 0) := rfl | (of_nat (succ m)) := by simp | -[1+ m] := by simp protected lemma add_right_neg (a : ℤ) : a + -a = 0 := by rw [int.add_comm, int.add_left_neg] /- multiplication -/ protected lemma mul_comm : ∀ a b : ℤ, a * b = b * a | (of_nat m) (of_nat n) := by simp [nat.mul_comm] | (of_nat m) -[1+ n] := by simp [nat.mul_comm] | -[1+ m] (of_nat n) := by simp [nat.mul_comm] | -[1+ m] -[1+ n] := by simp [nat.mul_comm] private lemma of_nat_mul_neg_of_nat (m : ℕ) : ∀ n, of_nat m * neg_of_nat n = neg_of_nat (m * n) | 0 := rfl | (succ n) := begin unfold neg_of_nat, simp end private lemma neg_of_nat_mul_of_nat (m n : ℕ) : neg_of_nat m * of_nat n = neg_of_nat (m * n) := begin rw int.mul_comm, simp [of_nat_mul_neg_of_nat, nat.mul_comm] end private lemma neg_succ_of_nat_mul_neg_of_nat (m : ℕ) : ∀ n, -[1+ m] * neg_of_nat n = of_nat (succ m * n) | 0 := rfl | (succ n) := begin unfold neg_of_nat, simp end private lemma neg_of_nat_mul_neg_succ_of_nat (m n : ℕ) : neg_of_nat n * -[1+ m] = of_nat (n * succ m) := begin rw int.mul_comm, simp [neg_succ_of_nat_mul_neg_of_nat, nat.mul_comm] end local attribute [simp] of_nat_mul_neg_of_nat neg_of_nat_mul_of_nat neg_succ_of_nat_mul_neg_of_nat neg_of_nat_mul_neg_succ_of_nat protected lemma mul_assoc : ∀ a b c : ℤ, a * b * c = a * (b * c) | (of_nat m) (of_nat n) (of_nat k) := by simp [nat.mul_assoc] | (of_nat m) (of_nat n) -[1+ k] := by simp [nat.mul_assoc] | (of_nat m) -[1+ n] (of_nat k) := by simp [nat.mul_assoc] | (of_nat m) -[1+ n] -[1+ k] := by simp [nat.mul_assoc] | -[1+ m] (of_nat n) (of_nat k) := by simp [nat.mul_assoc] | -[1+ m] (of_nat n) -[1+ k] := by simp [nat.mul_assoc] | -[1+ m] -[1+ n] (of_nat k) := by simp [nat.mul_assoc] | -[1+ m] -[1+ n] -[1+ k] := by simp [nat.mul_assoc] protected lemma mul_zero : ∀ (a : ℤ), a * 0 = 0 | (of_nat m) := rfl | -[1+ m] := rfl protected lemma zero_mul (a : ℤ) : 0 * a = 0 := int.mul_comm a 0 ▸ int.mul_zero a private lemma neg_of_nat_eq_sub_nat_nat_zero : ∀ n, neg_of_nat n = sub_nat_nat 0 n | 0 := rfl | (succ n) := rfl private lemma of_nat_mul_sub_nat_nat (m n k : ℕ) : of_nat m * sub_nat_nat n k = sub_nat_nat (m * n) (m * k) := begin have h₀ : m > 0 ∨ 0 = m, exact lt_or_eq_of_le (zero_le _), cases h₀ with h₀ h₀, { have h := nat.lt_or_ge n k, cases h with h h, { have h' : m * n < m * k, exact nat.mul_lt_mul_of_pos_left h h₀, rw [sub_nat_nat_of_lt h, sub_nat_nat_of_lt h'], simp, rw [succ_pred_eq_of_pos (nat.sub_pos_of_lt h)], rw [← neg_of_nat_of_succ, nat.mul_sub_left_distrib], rw [← succ_pred_eq_of_pos (nat.sub_pos_of_lt h')], reflexivity }, have h' : m * k ≤ m * n, exact mul_le_mul_left _ h, rw [sub_nat_nat_of_ge h, sub_nat_nat_of_ge h'], simp, rw [nat.mul_sub_left_distrib] }, have h₂ : of_nat 0 = 0, exact rfl, subst h₀, simp [h₂, int.zero_mul, nat.zero_mul] end private lemma neg_of_nat_add (m n : ℕ) : neg_of_nat m + neg_of_nat n = neg_of_nat (m + n) := begin cases m, { cases n, { simp, reflexivity }, simp [nat.zero_add], reflexivity }, cases n, { simp, reflexivity }, simp [nat.succ_add], reflexivity end private lemma neg_succ_of_nat_mul_sub_nat_nat (m n k : ℕ) : -[1+ m] * sub_nat_nat n k = sub_nat_nat (succ m * k) (succ m * n) := begin have h := nat.lt_or_ge n k, cases h with h h, { have h' : succ m * n < succ m * k, exact nat.mul_lt_mul_of_pos_left h (nat.succ_pos m), rw [sub_nat_nat_of_lt h, sub_nat_nat_of_ge (le_of_lt h')], simp [succ_pred_eq_of_pos (nat.sub_pos_of_lt h), nat.mul_sub_left_distrib]}, have h' : n > k ∨ k = n, exact lt_or_eq_of_le h, cases h' with h' h', { have h₁ : succ m * n > succ m * k, exact nat.mul_lt_mul_of_pos_left h' (nat.succ_pos m), rw [sub_nat_nat_of_ge h, sub_nat_nat_of_lt h₁], simp [nat.mul_sub_left_distrib, nat.mul_comm], rw [nat.mul_comm k, nat.mul_comm n, ← succ_pred_eq_of_pos (nat.sub_pos_of_lt h₁), ← neg_of_nat_of_succ], reflexivity }, subst h', simp, reflexivity end local attribute [simp] of_nat_mul_sub_nat_nat neg_of_nat_add neg_succ_of_nat_mul_sub_nat_nat protected lemma distrib_left : ∀ a b c : ℤ, a * (b + c) = a * b + a * c | (of_nat m) (of_nat n) (of_nat k) := by simp [nat.left_distrib] | (of_nat m) (of_nat n) -[1+ k] := begin simp [neg_of_nat_eq_sub_nat_nat_zero], rw ← sub_nat_nat_add, reflexivity end | (of_nat m) -[1+ n] (of_nat k) := begin simp [neg_of_nat_eq_sub_nat_nat_zero], rw [int.add_comm, ← sub_nat_nat_add], reflexivity end | (of_nat m) -[1+ n] -[1+ k] := begin simp, rw [← nat.left_distrib, succ_add] end | -[1+ m] (of_nat n) (of_nat k) := begin simp [nat.mul_comm], rw [← nat.right_distrib, nat.mul_comm] end | -[1+ m] (of_nat n) -[1+ k] := begin simp [neg_of_nat_eq_sub_nat_nat_zero], rw [int.add_comm, ← sub_nat_nat_add], reflexivity end | -[1+ m] -[1+ n] (of_nat k) := begin simp [neg_of_nat_eq_sub_nat_nat_zero], rw [← sub_nat_nat_add], reflexivity end | -[1+ m] -[1+ n] -[1+ k] := begin simp, rw [← nat.left_distrib, succ_add] end protected lemma distrib_right (a b c : ℤ) : (a + b) * c = a * c + b * c := begin rw [int.mul_comm, int.distrib_left], simp [int.mul_comm] end protected lemma zero_ne_one : (0 : int) ≠ 1 := assume h : 0 = 1, succ_ne_zero _ (int.of_nat.inj h).symm lemma of_nat_sub {n m : ℕ} (h : m ≤ n) : of_nat (n - m) = of_nat n - of_nat m := show of_nat (n - m) = of_nat n + neg_of_nat m, from match m, h with | 0, h := rfl | succ m, h := show of_nat (n - succ m) = sub_nat_nat n (succ m), by delta sub_nat_nat; rw sub_eq_zero_of_le h; refl end protected lemma add_left_comm (a b c : ℤ) : a + (b + c) = b + (a + c) := by rw [← int.add_assoc, int.add_comm a, int.add_assoc] protected lemma add_left_cancel {a b c : ℤ} (h : a + b = a + c) : b = c := have -a + (a + b) = -a + (a + c), by rw h, by rwa [← int.add_assoc, ← int.add_assoc, int.add_left_neg, int.zero_add, int.zero_add] at this protected lemma neg_add {a b : ℤ} : - (a + b) = -a + -b := calc - (a + b) = -(a + b) + (a + b) + -a + -b : begin rw [int.add_assoc, int.add_comm (-a), int.add_assoc, int.add_assoc, ← int.add_assoc b], rw [int.add_right_neg, int.zero_add, int.add_right_neg, int.add_zero], end ... = -a + -b : by { rw [int.add_left_neg, int.zero_add] } lemma neg_succ_of_nat_coe' (n : ℕ) : -[1+ n] = -↑n - 1 := by rw [int.sub_eq_add_neg, ← int.neg_add]; refl protected lemma coe_nat_sub {n m : ℕ} : n ≤ m → (↑(m - n) : ℤ) = ↑m - ↑n := of_nat_sub local attribute [simp] int.sub_eq_add_neg protected lemma sub_nat_nat_eq_coe {m n : ℕ} : sub_nat_nat m n = ↑m - ↑n := sub_nat_nat_elim m n (λm n i, i = ↑m - ↑n) (λi n, by { simp [int.coe_nat_add, int.add_left_comm, int.add_assoc, int.add_right_neg], refl }) (λi n, by { rw [int.coe_nat_add, int.coe_nat_add, int.coe_nat_one, int.neg_succ_of_nat_eq, int.sub_eq_add_neg, int.neg_add, int.neg_add, int.neg_add, ← int.add_assoc, ← int.add_assoc, int.add_right_neg, int.zero_add] }) def to_nat : ℤ → ℕ | (n : ℕ) := n | -[1+ n] := 0 theorem to_nat_sub (m n : ℕ) : to_nat (m - n) = m - n := by rw [← int.sub_nat_nat_eq_coe]; exact sub_nat_nat_elim m n (λm n i, to_nat i = m - n) (λi n, by rw [nat.add_sub_cancel_left]; refl) (λi n, by rw [nat.add_assoc, nat.sub_eq_zero_of_le (nat.le_add_right _ _)]; refl) -- Since mod x y is always nonnegative when y ≠ 0, we can make a nat version of it def nat_mod (m n : ℤ) : ℕ := (m % n).to_nat protected lemma one_mul : ∀ (a : ℤ), (1 : ℤ) * a = a | (of_nat n) := show of_nat (1 * n) = of_nat n, by rw nat.one_mul | -[1+ n] := show -[1+ (1 * n)] = -[1+ n], by rw nat.one_mul protected lemma mul_one (a : ℤ) : a * 1 = a := by rw [int.mul_comm, int.one_mul] protected lemma neg_eq_neg_one_mul : ∀ a : ℤ, -a = -1 * a | (of_nat 0) := rfl | (of_nat (n+1)) := show _ = -[1+ (1*n)+0], by { rw nat.one_mul, refl } | -[1+ n] := show _ = of_nat _, by { rw nat.one_mul, refl } theorem sign_mul_nat_abs : ∀ (a : ℤ), sign a * nat_abs a = a | (n+1:ℕ) := int.one_mul _ | 0 := rfl | -[1+ n] := (int.neg_eq_neg_one_mul _).symm end int
e459c1594ec9336b53ff292ccdc2a2dd8748f0ea
a721fe7446524f18ba361625fc01033d9c8b7a78
/src/principia/real/basic.lean
81f79b7c6f53035191704c4dbba4bad81e21f66b
[]
no_license
Sterrs/leaning
8fd80d1f0a6117a220bb2e57ece639b9a63deadc
3901cc953694b33adda86cb88ca30ba99594db31
refs/heads/master
1,627,023,822,744
1,616,515,221,000
1,616,515,221,000
245,512,190
2
0
null
1,616,429,050,000
1,583,527,118,000
Lean
UTF-8
Lean
false
false
3,539
lean
import .cau_seq import ..logic namespace hidden open myring open ordered_myring open myfield open ordered_myfield namespace cau_seq private lemma class_setoid (f g : cau_seq) : ⟦f⟧ = ⟦g⟧ ↔ f ≈ g := iff.intro quotient.exact quotient.sound theorem class_equiv {f g : cau_seq} : ⟦f⟧ = ⟦g⟧ ↔ cau_seq.equivalent f g := begin split; assume h, rwa [←cau_seq.setoid_equiv, ←class_setoid], rwa [class_setoid, cau_seq.setoid_equiv], end variables f g : cau_seq theorem neg_is_cauchy : is_cau_seq $ λ n, -f.val n := begin have hf := f.property, dsimp only [is_cau_seq] at *, intro ε, assume hε, cases hf ε hε with N hN, existsi N, intros n m, assume hn hm, have h := hN n m hn hm, rwa [sub_def, neg_neg, add_comm, ←sub_def, ←abs_neg, neg_sub], end def neg : cau_seq → cau_seq := λ f, ⟨λ n, -f.val n, neg_is_cauchy f⟩ instance : has_neg cau_seq := ⟨neg⟩ def neg_val {n : mynat}: (-f).val n = - f.val n := rfl theorem neg_well_defined : f ≈ g → ⟦-f⟧ = ⟦-g⟧ := begin assume hfg, rw setoid_equiv at hfg, rw class_equiv, dsimp only [equivalent] at *, intros ε hε, cases hfg ε hε with N hN, existsi N, intros n hn, have h := hN n hn, rw [neg_val, neg_val], rwa [sub_def, neg_neg, add_comm, ←sub_def, ←abs_neg, neg_sub], end end cau_seq def real := quotient cau_seq.real_setoid namespace real def coe_myrat (a : myrat) : real := ⟦⟨λ n, a, cau_seq.constant_cauchy a⟩⟧ instance : has_coe myrat real := ⟨coe_myrat⟩ theorem coe_def (a : myrat) : (↑a : real) = ⟦⟨λ n, a, cau_seq.constant_cauchy a⟩⟧ := rfl instance : has_zero real := ⟨↑(0 : myrat)⟩ theorem real_zero : (0 : real) = ↑(0 : myrat) := rfl instance : has_one real := ⟨↑(1 : myrat)⟩ theorem real_one : (1 : real) = ↑(1 : myrat) := rfl def neg : real → real := quotient.lift (λ f, ⟦-f⟧) cau_seq.neg_well_defined instance : has_neg real := ⟨neg⟩ theorem neg_eq_cls {x : real} {f : cau_seq} : x = ⟦f⟧ → -x = ⟦-f⟧ := λ hxf, by rw hxf; refl theorem neg_val (f : cau_seq) (n : mynat): (-f).val n = -f.val n := rfl -- Use this to prove things which hold -- "trivially because there is a myrat theorem showing the sequences are the same" theorem seq_eq_imp_real_eq {x y : real} {f g : cau_seq}: x = ⟦f⟧ → y = ⟦g⟧ → (∀ n, f.val n = g.val n) → x = y := begin assume hxf hyg, subst hxf, subst hyg, assume heq, rw cau_seq.class_equiv, rw ←cau_seq.setoid_equiv, apply cau_seq.seq_eq_impl_cau_seq_equiv, assumption, end theorem coe_neg (a : myrat) : -↑a = (↑(-a) : real) := begin rw coe_def, rw coe_def, rw neg_eq_cls rfl, apply seq_eq_imp_real_eq rfl rfl, intros n, rw cau_seq.neg_val, end open classical theorem eq_iff_coe_eq (a b : myrat) : (↑a : real) = ↑b ↔ a = b := begin rw [coe_def, coe_def, cau_seq.class_equiv], split; assume h, { unfold cau_seq.equivalent at h, rw ←sub_to_zero_iff_eq, rw ←abs_zero_iff_zero, apply ordered_myring.le_antisymm, { rw le_iff_lt_impl_lt, intros ε hε, cases h ε hε with N hN, apply hN N (@mynat.le_refl N), }, { exact abs_nonneg _, }, }, { intros ε hε, existsi (0 : mynat), intros n hn, dsimp, rwa [h, sub_self, abs_zero], }, end theorem nontrivial : (0 : real) ≠ 1 := begin rw [real_zero, real_one], assume hydroxide, rw eq_iff_coe_eq at hydroxide, exact myrat.nontrivial hydroxide, end end real end hidden
9601c7fd03b2716bd8a048dd139d58db5c8be7e8
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/meta/rb_map.lean
45d44a1ac847edd72cea581214bf9146508016a6
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,681
lean
/- Copyright (c) 2018 Robert Y. Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Y. Lewis -/ import data.list.defs /-! # rb_map This file defines additional operations on native rb_maps and rb_sets. These structures are defined in core in `init.meta.rb_map`. They are meta objects, and are generally the most efficient dictionary structures to use for pure metaprogramming right now. -/ namespace native /-! ### Declarations about `rb_set` -/ namespace rb_set meta instance {key} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : inhabited (rb_set key) := ⟨mk_rb_set⟩ /-- `filter s P` returns the subset of elements of `s` satisfying `P`. -/ meta def filter {key} (s : rb_set key) (P : key → bool) : rb_set key := s.fold s (λ a m, if P a then m else m.erase a) /-- `mfilter s P` returns the subset of elements of `s` satisfying `P`, where the check `P` is monadic. -/ meta def mfilter {m} [monad m] {key} (s : rb_set key) (P : key → m bool) : m (rb_set key) := s.fold (pure s) (λ a m, do x ← m, mcond (P a) (pure x) (pure $ x.erase a)) /-- `union s t` returns an rb_set containing every element that appears in either `s` or `t`. -/ meta def union {key} (s t : rb_set key) : rb_set key := s.fold t (λ a t, t.insert a) /-- `of_list_core empty l` turns a list of keys into an `rb_set`. It takes a user_provided `rb_set` to use for the base case. This can be used to pre-seed the set with additional elements, and/or to use a custom comparison operator. -/ meta def of_list_core {key} (base : rb_set key) : list key → rb_map key unit | [] := base | (x::xs) := rb_set.insert (of_list_core xs) x /-- `of_list l` transforms a list `l : list key` into an `rb_set`, inferring an order on the type `key`. -/ meta def of_list {key} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : list key → rb_set key := of_list_core mk_rb_set /-- `sdiff s1 s2` returns the set of elements that are in `s1` but not in `s2`. It does so by folding over `s2`. If `s1` is significantly smaller than `s2`, it may be worth it to reverse the fold. -/ meta def sdiff {α} (s1 s2 : rb_set α) : rb_set α := s2.fold s1 $ λ v s, s.erase v /-- `insert_list s l` inserts each element of `l` into `s`. -/ meta def insert_list {key} (s : rb_set key) (l : list key) : rb_set key := l.foldl rb_set.insert s end rb_set /-! ### Declarations about `rb_map` -/ namespace rb_map meta instance {key data : Type} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : inhabited (rb_map key data) := ⟨mk_rb_map⟩ /-- `find_def default m k` returns the value corresponding to `k` in `m`, if it exists. Otherwise it returns `default`. -/ meta def find_def {key value} (default : value) (m : rb_map key value) (k : key) := (m.find k).get_or_else default /-- `ifind m key` returns the value corresponding to `key` in `m`, if it exists. Otherwise it returns the default value of `value`. -/ meta def ifind {key value} [inhabited value] (m : rb_map key value) (k : key) : value := (m.find k).iget /-- `zfind m key` returns the value corresponding to `key` in `m`, if it exists. Otherwise it returns 0. -/ meta def zfind {key value} [has_zero value] (m : rb_map key value) (k : key) : value := (m.find k).get_or_else 0 /-- Returns the pointwise sum of `m1` and `m2`, treating nonexistent values as 0. -/ meta def add {key value} [has_add value] [has_zero value] [decidable_eq value] (m1 m2 : rb_map key value) : rb_map key value := m1.fold m2 (λ n v m, let nv := v + m2.zfind n in if nv = 0 then m.erase n else m.insert n nv) variables {m : Type → Type*} [monad m] open function /-- `mfilter P s` filters `s` by the monadic predicate `P` on keys and values. -/ meta def mfilter {key val} [has_lt key] [decidable_rel ((<) : key → key → Prop)] (P : key → val → m bool) (s : rb_map key val) : m (rb_map.{0 0} key val) := rb_map.of_list <$> s.to_list.mfilter (uncurry P) /-- `mmap f s` maps the monadic function `f` over values in `s`. -/ meta def mmap {key val val'} [has_lt key] [decidable_rel ((<) : key → key → Prop)] (f : val → m val') (s : rb_map key val) : m (rb_map.{0 0} key val') := rb_map.of_list <$> s.to_list.mmap (λ ⟨a,b⟩, prod.mk a <$> f b) /-- `scale b m` multiplies every value in `m` by `b`. -/ meta def scale {key value} [has_lt key] [decidable_rel ((<) : key → key → Prop)] [has_mul value] (b : value) (m : rb_map key value) : rb_map key value := m.map ((*) b) section open format prod variables {key : Type} {data : Type} [has_to_tactic_format key] [has_to_tactic_format data] private meta def pp_key_data (k : key) (d : data) (first : bool) : tactic format := do fk ← tactic.pp k, fd ← tactic.pp d, return $ (if first then to_fmt "" else to_fmt "," ++ line) ++ fk ++ space ++ to_fmt "←" ++ space ++ fd meta instance : has_to_tactic_format (rb_map key data) := ⟨λ m, do (fmt, _) ← fold m (return (to_fmt "", tt)) (λ k d p, do p ← p, pkd ← pp_key_data k d (snd p), return (fst p ++ pkd, ff)), return $ group $ to_fmt "⟨" ++ nest 1 fmt ++ to_fmt "⟩"⟩ end end rb_map /-! ### Declarations about `rb_lmap` -/ namespace rb_lmap meta instance (key : Type) [has_lt key] [decidable_rel ((<) : key → key → Prop)] (data : Type) : inhabited (rb_lmap key data) := ⟨rb_lmap.mk _ _⟩ /-- Construct a rb_lmap from a list of key-data pairs -/ protected meta def of_list {key : Type} {data : Type} [has_lt key] [decidable_rel ((<) : key → key → Prop)] : list (key × data) → rb_lmap key data | [] := rb_lmap.mk key data | ((k, v)::ls) := (of_list ls).insert k v /-- Returns the list of values of an `rb_lmap`. -/ protected meta def values {key data} (m : rb_lmap key data) : list data := m.fold [] (λ _, (++)) end rb_lmap end native /-! ### Declarations about `name_set` -/ namespace name_set meta instance : inhabited name_set := ⟨mk_name_set⟩ /-- `filter P s` returns the subset of elements of `s` satisfying `P`. -/ meta def filter (P : name → bool) (s : name_set) : name_set := s.fold s (λ a m, if P a then m else m.erase a) /-- `mfilter P s` returns the subset of elements of `s` satisfying `P`, where the check `P` is monadic. -/ meta def mfilter {m} [monad m] (P : name → m bool) (s : name_set) : m name_set := s.fold (pure s) (λ a m, do x ← m, mcond (P a) (pure x) (pure $ x.erase a)) /-- `mmap f s` maps the monadic function `f` over values in `s`. -/ meta def mmap {m} [monad m] (f : name → m name) (s : name_set) : m name_set := s.fold (pure mk_name_set) (λ a m, do x ← m, b ← f a, (pure $ x.insert b)) /-- `insert_list s l` inserts every element of `l` into `s`. -/ meta def insert_list (s : name_set) (l : list name) : name_set := l.foldr (λ n s', s'.insert n) s /-- `local_list_to_name_set lcs` is the set of unique names of the local constants `lcs`. If any of the `lcs` are not local constants, the returned set will contain bogus names. -/ meta def local_list_to_name_set (lcs : list expr) : name_set := lcs.foldl (λ ns h, ns.insert h.local_uniq_name) mk_name_set end name_set /-! ### Declarations about `name_map` -/ namespace name_map meta instance {data : Type} : inhabited (name_map data) := ⟨mk_name_map⟩ end name_map /-! ### Declarations about `expr_set` -/ namespace expr_set /-- `local_set_to_name_set lcs` is the set of unique names of the local constants `lcs`. If any of the `lcs` are not local constants, the returned set will contain bogus names. -/ meta def local_set_to_name_set (lcs : expr_set) : name_set := lcs.fold mk_name_set $ λ h ns, ns.insert h.local_uniq_name end expr_set
4c01eb393fbd78d0f469d6c5b446ef7718ecb217
9be442d9ec2fcf442516ed6e9e1660aa9071b7bd
/stage0/src/Lean/Elab/PreDefinition/Structural/Preprocess.lean
eca66fd091b7122395aad04fad79c1d5996c4ee9
[ "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
870
lean
/- Copyright (c) 2021 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Transform namespace Lean.Elab.Structural open Meta private def shouldBetaReduce (e : Expr) (recFnName : Name) : Bool := if e.isHeadBetaTarget then e.getAppFn.find? (·.isConstOf recFnName) |>.isSome else false /-- Beta reduce terms where the recursive function occurs in the lambda term. This is useful to improve the effectiveness of `elimRecursion`. Example: ``` def f : Nat → Nat | 0 => 1 | i+1 => (fun x => f x) i ``` -/ def preprocess (e : Expr) (recFnName : Name) : CoreM Expr := Core.transform e fun e => return TransformStep.visit <| if shouldBetaReduce e recFnName then e.headBeta else e end Lean.Elab.Structural
9ea1995fe8a2a4c313603ae21db8a533be821ddd
e030b0259b777fedcdf73dd966f3f1556d392178
/tests/lean/bad_structures.lean
022a291cabd4a46109900cc480fd0157b0f3c64e
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
341
lean
prelude namespace foo structure {l} prod (A : Type l) (B : Type l) := (pr1 : A) (pr2 : B) structure {l} prod1 (A : Type l) (B : Type l) : Type := (pr1 : A) (pr2 : B) structure {l} prod2 (A : Type l) (B : Type l) : Type l := (pr1 : A) (pr2 : B) structure {l} prod3 (A : Type l) (B : Type l) : Type (max 1 l) := (pr1 : A) (pr2 : B) end foo
ea3e0714630ea258d2fbf3b8d28809c021198aa6
271e26e338b0c14544a889c31c30b39c989f2e0f
/src/Init/Lean/Compiler/IR/EmitUtil.lean
2a12334bb87fee5a98c7db9913140b1cb5ab3fee
[ "Apache-2.0" ]
permissive
dgorokho/lean4
805f99b0b60c545b64ac34ab8237a8504f89d7d4
e949a052bad59b1c7b54a82d24d516a656487d8a
refs/heads/master
1,607,061,363,851
1,578,006,086,000
1,578,006,086,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
4,162
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ prelude import Init.Control.Conditional import Init.Lean.Compiler.InitAttr import Init.Lean.Compiler.IR.CompilerM /- Helper functions for backend code generators -/ namespace Lean namespace 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 namespace UsesLeanNamespace abbrev M := ReaderT Environment (StateM NameSet) def leanNameSpacePrefix := `Lean partial def visitFnBody : FnBody → M Bool | FnBody.vdecl _ _ v b => let checkFn (f : FunId) : M Bool := if leanNameSpacePrefix.isPrefixOf f then pure true else do { s ← get; if s.contains f then visitFnBody b else do modify (fun s => s.insert f); env ← read; match findEnvDecl env f with | some (Decl.fdecl _ _ _ fbody) => visitFnBody fbody <||> visitFnBody b | other => visitFnBody b }; match v with | Expr.fap f _ => checkFn f | Expr.pap f _ => checkFn f | other => visitFnBody b | FnBody.jdecl _ _ v b => visitFnBody v <||> visitFnBody b | FnBody.case _ _ _ alts => alts.anyM $ fun alt => visitFnBody alt.body | e => if e.isTerminal then pure false else visitFnBody e.body end UsesLeanNamespace def usesLeanNamespace (env : Environment) : Decl → Bool | Decl.fdecl _ _ _ b => (UsesLeanNamespace.visitFnBody b env).run' {} | _ => false 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 => unless e.isTerminal $ collectFnBody e.body def collectInitDecl (fn : Name) : M Unit := do env ← read; match getInitFnNameFor env fn with | some initFn => collect initFn | _ => pure () def collectDecl : Decl → M NameSet | Decl.fdecl fn _ _ b => collectInitDecl fn *> CollectUsedDecls.collectFnBody b *> get | Decl.extern fn _ _ _ => collectInitDecl fn *> get end CollectUsedDecls def collectUsedDecls (env : Environment) (decl : Decl) (used : NameSet := {}) : NameSet := (CollectUsedDecls.collectDecl decl env).run' used abbrev VarTypeMap := HashMap VarId IRType abbrev JPParamsMap := 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 _ 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
32eef9a5fb6820578dcd07bd4f82ffc8d66851ab
302c785c90d40ad3d6be43d33bc6a558354cc2cf
/src/category_theory/monoidal/category.lean
8cd913fa4cdd95797b831aa89e20d00e500fbd34
[ "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
17,524
lean
/- Copyright (c) 2018 Michael Jendrusch. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Jendrusch, Scott Morrison, Bhavik Mehta -/ import category_theory.products.basic /-! # Monoidal categories A monoidal category is a category equipped with a tensor product, unitors, and an associator. In the definition, we provide the tensor product as a pair of functions * `tensor_obj : C → C → C` * `tensor_hom : (X₁ ⟶ Y₁) → (X₂ ⟶ Y₂) → ((X₁ ⊗ X₂) ⟶ (Y₁ ⊗ Y₂))` and allow use of the overloaded notation `⊗` for both. The unitors and associator are provided componentwise. The tensor product can be expressed as a functor via `tensor : C × C ⥤ C`. The unitors and associator are gathered together as natural isomorphisms in `left_unitor_nat_iso`, `right_unitor_nat_iso` and `associator_nat_iso`. Some consequences of the definition are proved in other files, e.g. `(λ_ (𝟙_ C)).hom = (ρ_ (𝟙_ C)).hom` in `category_theory.monoidal.unitors_equal`. ## Implementation Dealing with unitors and associators is painful, and at this stage we do not have a useful implementation of coherence for monoidal categories. In an effort to lessen the pain, we put some effort into choosing the right `simp` lemmas. Generally, the rule is that the component index of a natural transformation "weighs more" in considering the complexity of an expression than does a structural isomorphism (associator, etc). As an example when we prove Proposition 2.2.4 of <http://www-math.mit.edu/~etingof/egnobookfinal.pdf> we state it as a `@[simp]` lemma as ``` (λ_ (X ⊗ Y)).hom = (α_ (𝟙_ C) X Y).inv ≫ (λ_ X).hom ⊗ (𝟙 Y) ``` This is far from completely effective, but seems to prove a useful principle. ## References * Tensor categories, Etingof, Gelaki, Nikshych, Ostrik, http://www-math.mit.edu/~etingof/egnobookfinal.pdf * https://stacks.math.columbia.edu/tag/0FFK. -/ open category_theory universes v u open category_theory open category_theory.category open category_theory.iso namespace category_theory /-- In a monoidal category, we can take the tensor product of objects, `X ⊗ Y` and of morphisms `f ⊗ g`. Tensor product does not need to be strictly associative on objects, but there is a specified associator, `α_ X Y Z : (X ⊗ Y) ⊗ Z ≅ X ⊗ (Y ⊗ Z)`. There is a tensor unit `𝟙_ C`, with specified left and right unitor isomorphisms `λ_ X : 𝟙_ C ⊗ X ≅ X` and `ρ_ X : X ⊗ 𝟙_ C ≅ X`. These associators and unitors satisfy the pentagon and triangle equations. See https://stacks.math.columbia.edu/tag/0FFK. -/ class monoidal_category (C : Type u) [𝒞 : category.{v} C] := -- curried tensor product of objects: (tensor_obj : C → C → C) (infixr ` ⊗ `:70 := tensor_obj) -- This notation is only temporary -- curried tensor product of morphisms: (tensor_hom : Π {X₁ Y₁ X₂ Y₂ : C}, (X₁ ⟶ Y₁) → (X₂ ⟶ Y₂) → ((X₁ ⊗ X₂) ⟶ (Y₁ ⊗ Y₂))) (infixr ` ⊗' `:69 := tensor_hom) -- This notation is only temporary -- tensor product laws: (tensor_id' : ∀ (X₁ X₂ : C), (𝟙 X₁) ⊗' (𝟙 X₂) = 𝟙 (X₁ ⊗ X₂) . obviously) (tensor_comp' : ∀ {X₁ Y₁ Z₁ X₂ Y₂ Z₂ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (g₁ : Y₁ ⟶ Z₁) (g₂ : Y₂ ⟶ Z₂), (f₁ ≫ g₁) ⊗' (f₂ ≫ g₂) = (f₁ ⊗' f₂) ≫ (g₁ ⊗' g₂) . obviously) -- tensor unit: (tensor_unit [] : C) (notation `𝟙_` := tensor_unit) -- associator: (associator : Π X Y Z : C, (X ⊗ Y) ⊗ Z ≅ X ⊗ (Y ⊗ Z)) (notation `α_` := associator) (associator_naturality' : ∀ {X₁ X₂ X₃ Y₁ Y₂ Y₃ : C} (f₁ : X₁ ⟶ Y₁) (f₂ : X₂ ⟶ Y₂) (f₃ : X₃ ⟶ Y₃), ((f₁ ⊗' f₂) ⊗' f₃) ≫ (α_ Y₁ Y₂ Y₃).hom = (α_ X₁ X₂ X₃).hom ≫ (f₁ ⊗' (f₂ ⊗' f₃)) . obviously) -- left unitor: (left_unitor : Π X : C, 𝟙_ ⊗ X ≅ X) (notation `λ_` := left_unitor) (left_unitor_naturality' : ∀ {X Y : C} (f : X ⟶ Y), ((𝟙 𝟙_) ⊗' f) ≫ (λ_ Y).hom = (λ_ X).hom ≫ f . obviously) -- right unitor: (right_unitor : Π X : C, X ⊗ 𝟙_ ≅ X) (notation `ρ_` := right_unitor) (right_unitor_naturality' : ∀ {X Y : C} (f : X ⟶ Y), (f ⊗' (𝟙 𝟙_)) ≫ (ρ_ Y).hom = (ρ_ X).hom ≫ f . obviously) -- pentagon identity: (pentagon' : ∀ W X Y Z : C, ((α_ W X Y).hom ⊗' (𝟙 Z)) ≫ (α_ W (X ⊗ Y) Z).hom ≫ ((𝟙 W) ⊗' (α_ X Y Z).hom) = (α_ (W ⊗ X) Y Z).hom ≫ (α_ W X (Y ⊗ Z)).hom . obviously) -- triangle identity: (triangle' : ∀ X Y : C, (α_ X 𝟙_ Y).hom ≫ ((𝟙 X) ⊗' (λ_ Y).hom) = (ρ_ X).hom ⊗' (𝟙 Y) . obviously) restate_axiom monoidal_category.tensor_id' attribute [simp] monoidal_category.tensor_id restate_axiom monoidal_category.tensor_comp' attribute [reassoc] monoidal_category.tensor_comp -- This would be redundant in the simp set. attribute [simp] monoidal_category.tensor_comp restate_axiom monoidal_category.associator_naturality' attribute [reassoc] monoidal_category.associator_naturality restate_axiom monoidal_category.left_unitor_naturality' attribute [reassoc] monoidal_category.left_unitor_naturality restate_axiom monoidal_category.right_unitor_naturality' attribute [reassoc] monoidal_category.right_unitor_naturality restate_axiom monoidal_category.pentagon' restate_axiom monoidal_category.triangle' attribute [reassoc] monoidal_category.pentagon attribute [simp, reassoc] monoidal_category.triangle open monoidal_category infixr ` ⊗ `:70 := tensor_obj infixr ` ⊗ `:70 := tensor_hom notation `𝟙_` := tensor_unit notation `α_` := associator notation `λ_` := left_unitor notation `ρ_` := right_unitor /-- The tensor product of two isomorphisms is an isomorphism. -/ @[simps] def tensor_iso {C : Type u} {X Y X' Y' : C} [category.{v} C] [monoidal_category.{v} C] (f : X ≅ Y) (g : X' ≅ Y') : X ⊗ X' ≅ Y ⊗ Y' := { hom := f.hom ⊗ g.hom, inv := f.inv ⊗ g.inv, hom_inv_id' := by rw [←tensor_comp, iso.hom_inv_id, iso.hom_inv_id, ←tensor_id], inv_hom_id' := by rw [←tensor_comp, iso.inv_hom_id, iso.inv_hom_id, ←tensor_id] } infixr ` ⊗ `:70 := tensor_iso namespace monoidal_category section variables {C : Type u} [category.{v} C] [monoidal_category.{v} C] instance tensor_is_iso {W X Y Z : C} (f : W ⟶ X) [is_iso f] (g : Y ⟶ Z) [is_iso g] : is_iso (f ⊗ g) := is_iso.of_iso (as_iso f ⊗ as_iso g) @[simp] lemma inv_tensor {W X Y Z : C} (f : W ⟶ X) [is_iso f] (g : Y ⟶ Z) [is_iso g] : inv (f ⊗ g) = inv f ⊗ inv g := by { ext, simp [←tensor_comp], } variables {U V W X Y Z : C} -- When `rewrite_search` lands, add @[search] attributes to -- monoidal_category.tensor_id monoidal_category.tensor_comp monoidal_category.associator_naturality -- monoidal_category.left_unitor_naturality monoidal_category.right_unitor_naturality -- monoidal_category.pentagon monoidal_category.triangle -- tensor_comp_id tensor_id_comp comp_id_tensor_tensor_id -- triangle_assoc_comp_left triangle_assoc_comp_right -- triangle_assoc_comp_left_inv triangle_assoc_comp_right_inv -- left_unitor_tensor left_unitor_tensor_inv -- right_unitor_tensor right_unitor_tensor_inv -- pentagon_inv -- associator_inv_naturality -- left_unitor_inv_naturality -- right_unitor_inv_naturality @[reassoc, simp] lemma comp_tensor_id (f : W ⟶ X) (g : X ⟶ Y) : (f ≫ g) ⊗ (𝟙 Z) = (f ⊗ (𝟙 Z)) ≫ (g ⊗ (𝟙 Z)) := by { rw ←tensor_comp, simp } @[reassoc, simp] lemma id_tensor_comp (f : W ⟶ X) (g : X ⟶ Y) : (𝟙 Z) ⊗ (f ≫ g) = (𝟙 Z ⊗ f) ≫ (𝟙 Z ⊗ g) := by { rw ←tensor_comp, simp } @[simp, reassoc] lemma id_tensor_comp_tensor_id (f : W ⟶ X) (g : Y ⟶ Z) : ((𝟙 Y) ⊗ f) ≫ (g ⊗ (𝟙 X)) = g ⊗ f := by { rw [←tensor_comp], simp } @[simp, reassoc] lemma tensor_id_comp_id_tensor (f : W ⟶ X) (g : Y ⟶ Z) : (g ⊗ (𝟙 W)) ≫ ((𝟙 Z) ⊗ f) = g ⊗ f := by { rw [←tensor_comp], simp } lemma left_unitor_inv_naturality {X X' : C} (f : X ⟶ X') : f ≫ (λ_ X').inv = (λ_ X).inv ≫ (𝟙 _ ⊗ f) := begin apply (cancel_mono (λ_ X').hom).1, simp only [assoc, comp_id, iso.inv_hom_id], rw [left_unitor_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp] end lemma right_unitor_inv_naturality {X X' : C} (f : X ⟶ X') : f ≫ (ρ_ X').inv = (ρ_ X).inv ≫ (f ⊗ 𝟙 _) := begin apply (cancel_mono (ρ_ X').hom).1, simp only [assoc, comp_id, iso.inv_hom_id], rw [right_unitor_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp] end @[simp] lemma right_unitor_conjugation {X Y : C} (f : X ⟶ Y) : (ρ_ X).inv ≫ (f ⊗ (𝟙 (𝟙_ C))) ≫ (ρ_ Y).hom = f := by rw [right_unitor_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp] @[simp] lemma left_unitor_conjugation {X Y : C} (f : X ⟶ Y) : (λ_ X).inv ≫ ((𝟙 (𝟙_ C)) ⊗ f) ≫ (λ_ Y).hom = f := by rw [left_unitor_naturality, ←category.assoc, iso.inv_hom_id, category.id_comp] @[simp] lemma tensor_left_iff {X Y : C} (f g : X ⟶ Y) : ((𝟙 (𝟙_ C)) ⊗ f = (𝟙 (𝟙_ C)) ⊗ g) ↔ (f = g) := by { rw [←cancel_mono (λ_ Y).hom, left_unitor_naturality, left_unitor_naturality], simp } @[simp] lemma tensor_right_iff {X Y : C} (f g : X ⟶ Y) : (f ⊗ (𝟙 (𝟙_ C)) = g ⊗ (𝟙 (𝟙_ C))) ↔ (f = g) := by { rw [←cancel_mono (ρ_ Y).hom, right_unitor_naturality, right_unitor_naturality], simp } -- See Proposition 2.2.4 of <http://www-math.mit.edu/~etingof/egnobookfinal.pdf> lemma left_unitor_tensor' (X Y : C) : ((α_ (𝟙_ C) X Y).hom) ≫ ((λ_ (X ⊗ Y)).hom) = ((λ_ X).hom ⊗ (𝟙 Y)) := by rw [←tensor_left_iff, id_tensor_comp, ←cancel_epi (α_ (𝟙_ C) (𝟙_ C ⊗ X) Y).hom, ←cancel_epi ((α_ (𝟙_ C) (𝟙_ C) X).hom ⊗ 𝟙 Y), pentagon_assoc, triangle, ←associator_naturality, ←comp_tensor_id_assoc, triangle, associator_naturality, tensor_id] @[simp] lemma left_unitor_tensor (X Y : C) : ((λ_ (X ⊗ Y)).hom) = ((α_ (𝟙_ C) X Y).inv) ≫ ((λ_ X).hom ⊗ (𝟙 Y)) := by { rw [←left_unitor_tensor'], simp } lemma left_unitor_tensor_inv' (X Y : C) : ((λ_ (X ⊗ Y)).inv) ≫ ((α_ (𝟙_ C) X Y).inv) = ((λ_ X).inv ⊗ (𝟙 Y)) := eq_of_inv_eq_inv (by simp) @[simp] lemma left_unitor_tensor_inv (X Y : C) : (λ_ (X ⊗ Y)).inv = ((λ_ X).inv ⊗ (𝟙 Y)) ≫ (α_ (𝟙_ C) X Y).hom := by { rw [←left_unitor_tensor_inv'], simp } @[simp] lemma right_unitor_tensor (X Y : C) : (ρ_ (X ⊗ Y)).hom = (α_ X Y (𝟙_ C)).hom ≫ ((𝟙 X) ⊗ (ρ_ Y).hom) := by rw [←tensor_right_iff, comp_tensor_id, ←cancel_mono (α_ X Y (𝟙_ C)).hom, assoc, associator_naturality, ←triangle_assoc, ←triangle, id_tensor_comp, pentagon_assoc, ←associator_naturality, tensor_id] @[simp] lemma right_unitor_tensor_inv (X Y : C) : ((ρ_ (X ⊗ Y)).inv) = ((𝟙 X) ⊗ (ρ_ Y).inv) ≫ ((α_ X Y (𝟙_ C)).inv) := eq_of_inv_eq_inv (by simp) lemma associator_inv_naturality {X Y Z X' Y' Z' : C} (f : X ⟶ X') (g : Y ⟶ Y') (h : Z ⟶ Z') : (f ⊗ (g ⊗ h)) ≫ (α_ X' Y' Z').inv = (α_ X Y Z).inv ≫ ((f ⊗ g) ⊗ h) := by { rw [comp_inv_eq, assoc, associator_naturality], simp } lemma pentagon_inv (W X Y Z : C) : ((𝟙 W) ⊗ (α_ X Y Z).inv) ≫ (α_ W (X ⊗ Y) Z).inv ≫ ((α_ W X Y).inv ⊗ (𝟙 Z)) = (α_ W X (Y ⊗ Z)).inv ≫ (α_ (W ⊗ X) Y Z).inv := category_theory.eq_of_inv_eq_inv (by simp [pentagon]) lemma triangle_assoc_comp_left (X Y : C) : (α_ X (𝟙_ C) Y).hom ≫ ((𝟙 X) ⊗ (λ_ Y).hom) = (ρ_ X).hom ⊗ 𝟙 Y := monoidal_category.triangle X Y @[simp] lemma triangle_assoc_comp_right (X Y : C) : (α_ X (𝟙_ C) Y).inv ≫ ((ρ_ X).hom ⊗ 𝟙 Y) = ((𝟙 X) ⊗ (λ_ Y).hom) := by rw [←triangle_assoc_comp_left, iso.inv_hom_id_assoc] @[simp] lemma triangle_assoc_comp_right_inv (X Y : C) : ((ρ_ X).inv ⊗ 𝟙 Y) ≫ (α_ X (𝟙_ C) Y).hom = ((𝟙 X) ⊗ (λ_ Y).inv) := begin apply (cancel_mono (𝟙 X ⊗ (λ_ Y).hom)).1, simp only [assoc, triangle_assoc_comp_left], rw [←comp_tensor_id, iso.inv_hom_id, ←id_tensor_comp, iso.inv_hom_id] end @[simp] lemma triangle_assoc_comp_left_inv (X Y : C) : ((𝟙 X) ⊗ (λ_ Y).inv) ≫ (α_ X (𝟙_ C) Y).inv = ((ρ_ X).inv ⊗ 𝟙 Y) := begin apply (cancel_mono ((ρ_ X).hom ⊗ 𝟙 Y)).1, simp only [triangle_assoc_comp_right, assoc], rw [←id_tensor_comp, iso.inv_hom_id, ←comp_tensor_id, iso.inv_hom_id] end lemma unitors_equal : (λ_ (𝟙_ C)).hom = (ρ_ (𝟙_ C)).hom := by rw [←tensor_left_iff, ←cancel_epi (α_ (𝟙_ C) (𝟙_ _) (𝟙_ _)).hom, ←cancel_mono (ρ_ (𝟙_ C)).hom, triangle, ←right_unitor_tensor, right_unitor_naturality] end section variables (C : Type u) [category.{v} C] [monoidal_category.{v} C] /-- The tensor product expressed as a functor. -/ def tensor : (C × C) ⥤ C := { obj := λ X, X.1 ⊗ X.2, map := λ {X Y : C × C} (f : X ⟶ Y), f.1 ⊗ f.2 } /-- The left-associated triple tensor product as a functor. -/ def left_assoc_tensor : (C × C × C) ⥤ C := { obj := λ X, (X.1 ⊗ X.2.1) ⊗ X.2.2, map := λ {X Y : C × C × C} (f : X ⟶ Y), (f.1 ⊗ f.2.1) ⊗ f.2.2 } @[simp] lemma left_assoc_tensor_obj (X) : (left_assoc_tensor C).obj X = (X.1 ⊗ X.2.1) ⊗ X.2.2 := rfl @[simp] lemma left_assoc_tensor_map {X Y} (f : X ⟶ Y) : (left_assoc_tensor C).map f = (f.1 ⊗ f.2.1) ⊗ f.2.2 := rfl /-- The right-associated triple tensor product as a functor. -/ def right_assoc_tensor : (C × C × C) ⥤ C := { obj := λ X, X.1 ⊗ (X.2.1 ⊗ X.2.2), map := λ {X Y : C × C × C} (f : X ⟶ Y), f.1 ⊗ (f.2.1 ⊗ f.2.2) } @[simp] lemma right_assoc_tensor_obj (X) : (right_assoc_tensor C).obj X = X.1 ⊗ (X.2.1 ⊗ X.2.2) := rfl @[simp] lemma right_assoc_tensor_map {X Y} (f : X ⟶ Y) : (right_assoc_tensor C).map f = f.1 ⊗ (f.2.1 ⊗ f.2.2) := rfl /-- The functor `λ X, 𝟙_ C ⊗ X`. -/ def tensor_unit_left : C ⥤ C := { obj := λ X, 𝟙_ C ⊗ X, map := λ {X Y : C} (f : X ⟶ Y), (𝟙 (𝟙_ C)) ⊗ f } /-- The functor `λ X, X ⊗ 𝟙_ C`. -/ def tensor_unit_right : C ⥤ C := { obj := λ X, X ⊗ 𝟙_ C, map := λ {X Y : C} (f : X ⟶ Y), f ⊗ (𝟙 (𝟙_ C)) } -- We can express the associator and the unitors, given componentwise above, -- as natural isomorphisms. /-- The associator as a natural isomorphism. -/ @[simps] def associator_nat_iso : left_assoc_tensor C ≅ right_assoc_tensor C := nat_iso.of_components (by { intros, apply monoidal_category.associator }) (by { intros, apply monoidal_category.associator_naturality }) /-- The left unitor as a natural isomorphism. -/ @[simps] def left_unitor_nat_iso : tensor_unit_left C ≅ 𝟭 C := nat_iso.of_components (by { intros, apply monoidal_category.left_unitor }) (by { intros, apply monoidal_category.left_unitor_naturality }) /-- The right unitor as a natural isomorphism. -/ @[simps] def right_unitor_nat_iso : tensor_unit_right C ≅ 𝟭 C := nat_iso.of_components (by { intros, apply monoidal_category.right_unitor }) (by { intros, apply monoidal_category.right_unitor_naturality }) section variables {C} /-- Tensoring on the left with a fixed object, as a functor. -/ @[simps] def tensor_left (X : C) : C ⥤ C := { obj := λ Y, X ⊗ Y, map := λ Y Y' f, (𝟙 X) ⊗ f, } /-- Tensoring on the left with `X ⊗ Y` is naturally isomorphic to tensoring on the left with `Y`, and then again with `X`. -/ def tensor_left_tensor (X Y : C) : tensor_left (X ⊗ Y) ≅ tensor_left Y ⋙ tensor_left X := nat_iso.of_components (associator _ _) (λ Z Z' f, by { dsimp, rw[←tensor_id], apply associator_naturality }) @[simp] lemma tensor_left_tensor_hom_app (X Y Z : C) : (tensor_left_tensor X Y).hom.app Z = (associator X Y Z).hom := rfl @[simp] lemma tensor_left_tensor_inv_app (X Y Z : C) : (tensor_left_tensor X Y).inv.app Z = (associator X Y Z).inv := by { simp [tensor_left_tensor], } /-- Tensoring on the right with a fixed object, as a functor. -/ @[simps] def tensor_right (X : C) : C ⥤ C := { obj := λ Y, Y ⊗ X, map := λ Y Y' f, f ⊗ (𝟙 X), } variables (C) /-- Tensoring on the right, as a functor from `C` into endofunctors of `C`. We later show this is a monoidal functor. -/ @[simps] def tensoring_right : C ⥤ (C ⥤ C) := { obj := tensor_right, map := λ X Y f, { app := λ Z, (𝟙 Z) ⊗ f } } instance : faithful (tensoring_right C) := { map_injective' := λ X Y f g h, begin injections with h, replace h := congr_fun h (𝟙_ C), simpa using h, end } variables {C} /-- Tensoring on the right with `X ⊗ Y` is naturally isomorphic to tensoring on the right with `X`, and then again with `Y`. -/ def tensor_right_tensor (X Y : C) : tensor_right (X ⊗ Y) ≅ tensor_right X ⋙ tensor_right Y := nat_iso.of_components (λ Z, (associator Z X Y).symm) (λ Z Z' f, by { dsimp, rw[←tensor_id], apply associator_inv_naturality }) @[simp] lemma tensor_right_tensor_hom_app (X Y Z : C) : (tensor_right_tensor X Y).hom.app Z = (associator Z X Y).inv := rfl @[simp] lemma tensor_right_tensor_inv_app (X Y Z : C) : (tensor_right_tensor X Y).inv.app Z = (associator Z X Y).hom := by simp [tensor_right_tensor] end end end monoidal_category end category_theory
64058013330bfdf905f965b24ae47f496f97eb3b
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/ppMotives.lean
79458499fd107186943ce641981b7248f70edca3
[ "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
474
lean
set_option pp.motives.pi false #print Nat.add set_option pp.motives.pi true #print Nat.add theorem ex : ∀ {α β : Sort u} (h : α = β) (a : α), HEq (cast h a) a | α, _, rfl, a => HEq.refl a set_option pp.motives.nonConst false #print ex set_option pp.motives.nonConst true #print ex noncomputable def fact (n : Nat) : Nat := Nat.recOn n 1 (fun n acc => (n+1)*acc) set_option pp.motives.all false #print fact set_option pp.motives.all true #print fact
717c64661ebf13467d7739a99691a361b5376a1b
c1a29ca460720df88ab68dc42d9a1a02e029d505
/examples/basics/alg_identities_2_2.lean
6082550207c7d0af7e701bdfbfd8a913616d4dc1
[]
no_license
agusakov/mathematics_in_lean
acb5b3d659e4522ae4b4836ea550527f03f6546c
2539562e4d91c858c73dbecb5b282ce1a7d38b6d
refs/heads/master
1,665,963,365,241
1,592,080,022,000
1,592,080,022,000
272,078,062
0
0
null
1,592,078,772,000
1,592,078,772,000
null
UTF-8
Lean
false
false
17,011
lean
import algebra.ring import tactic import algebra.group import algebra.group_power variables (R : Type*) [ring R] /-Mathematically, a ring consists of a - set, 𝑅, - operations + ×, and - constants 0 and 1, and - an operation 𝑥 ↦ −𝑥 such that: * 𝑅 with + is an abelian group, with 0 as the additive identity and negation as inverse. * Multiplication is associative with identity 1, and multiplication distributes over addition. In Lean, we base our algebraic structures on types rather than sets. Modulo this difference, we can take the ring axioms to be as follows:-/ #check (add_assoc : ∀ a b c : R, a + b + c = a + (b + c)) #check (add_comm : ∀ a b : R, a + b = b + a) #check (zero_add : ∀ a : R, 0 + a = a) #check (add_left_neg : ∀ a : R, -a + a = 0) #check (mul_assoc : ∀ a b c : R, a * b * c = a * (b * c)) #check (mul_one : ∀ a : R, a * 1 = a) #check (one_mul : ∀ a : R, 1 * a = a) #check (mul_add : ∀ a b c : R, a * (b + c) = a * b + a * c) #check (add_mul : ∀ a b c : R, (a + b) * c = a * c + b * c) /-You will learn more about the square brackets in the first line later, but for the time being, suffice it to say that the declaration gives us a type, R, and a ring structure on R. Lean then allows us to use generic ring notation with elements of R, and to make use of a library of theorems about rings. The names of some of the theorems should look familiar: they are exactly the ones we used to calculate with the real numbers in the last section. Lean is good not only for proving things about concrete mathematical structures like the natural numbers and the integers, but also for proving things about abstract structures, characterized axiomatically, like rings. Moreover, Lean supports generic reasoning about both abstract and concrete structures, and can be trained to recognized appropriate instances. So any theorem about rings can be applied to concrete rings like the integers, ℤ, the rational numbers, ℚ, and the complex numbers ℂ. It can also be applied to any instance of an abstract structure that extends rings, such as any ordered ring or any field. Not all important properties of the real numbers hold in an arbitrary ring, however. For example, multiplication on the real numbers is commutative, but that does not hold in general. If you have taken a course in linear algebra, you will recognize that, for every 𝑛, the 𝑛 by 𝑛 matrices of real numbers form a ring in which commutativity fails. If we declare R to be a commutative ring, in fact, all the theorems in the last section continue to hold when we replace ℝ by R.-/ namespace comm variables (R' : Type*) [comm_ring R'] variables a b c d : R' example : (c * b) * a = b * (a * c) := by ring example : (a + b) * (a + b) = a * a + 2 * (a * b) + b * b := by ring example : (a + b) * (a - b) = a^2 - b^2 := by ring example (hyp : c = d * a + b) (hyp' : b = a * d) : c = 2 * a * d := begin rw [hyp, hyp'], ring end end comm /-We leave it to you to check that all the other proofs go through unchanged. The goal of this section is to strengthen the skills you have developed in the last section and apply them to reasoning axiomatically about rings. We will start with the axioms listed above, and use them to derive other facts. Most of the facts we prove are already in mathlib. We will give the versions we prove the same names to help you learn the contents of the library as well as the naming conventions. To avoid error messages from Lean, we will put our versions in a new namespace called my_ring. The next example shows that we do not need add_zero or add_right_neg as ring axioms, because they follow from the other axioms.-/ -- algebra.ring namespace my_ring variables {R' : Type*} [ring R'] theorem add_zero (a : R') : a + 0 = a := by rw [add_comm, zero_add] theorem add_right_neg (a : R') : a + -a = 0 := by rw [add_comm, add_left_neg] #check @my_ring.add_zero #check @add_zero /-The net effect is that we can temporarily reprove a theorem in the library, and then go on using the library version after that. But don’t cheat! In the exercises that follow, take care to use only the general facts about rings that we have proved earlier in this section. (If you are paying careful attention, you may have noticed that we changed the round brackets in (R : Type*) for curly brackets in {R : Type*}. This declares R to be an implicit argument. We will explain what this means in a moment, but don’t worry about it in the meanwhile.) Here is a useful theorem:-/ -- BEGIN theorem neg_add_cancel_left (a b : R') : -a + (a + b) = b := by rw [←add_assoc, add_left_neg, zero_add] -- END /-Prove the companion version:-/ -- BEGIN theorem neg_add_cancel_right (a b : R') : (a + b) + -b = a := by rw [add_assoc, add_right_neg, add_zero] -- END /-Use these to prove the following:-/ -- BEGIN theorem add_left_cancel {a b c : R'} (h : a + b = a + c) : b = c := by rw [← zero_add b, ← add_left_neg a, add_assoc, h, neg_add_cancel_left] theorem add_right_cancel {a b c : R'} (h : a + b = c + b) : a = c := by rw [← add_zero a, ← add_left_neg b, ← add_comm b, ← add_assoc, h, neg_add_cancel_right] -- END /-If you are clever, you can do each of them with three rewrites. We can now explain the use of the curly braces. Imagine you are in a situation where you have a, b, and c in your context, as well as a hypothesis h : a + b = a + c, and you would like to draw the conclusion b = c. In Lean, you can apply a theorem to hypotheses and facts just the same way that you can apply them to objects, so you might think that add_left_cancel a b c h is a proof of the fact b = c. But notice that explicitly writing a, b, and c is redundant, because the hypothesis h makes it clear that those are the objects we have in mind. In this case, typing a few extra characters is not onerous, but if we wanted to apply add_left_cancel to more complicated expressions, writing them would be tedious. In cases like these, Lean allows us to mark arguments as implicit, meaning that they are supposed to be left out and inferred by other means, such as later arguments and hypotheses. The curly brackets in {a b c : R} do exactly that. So, given the statement of the theorem above, the correct expression is simply add_left_cancel h. To illustrate, let us show that a * 0 = 0 follows from the ring axioms.-/ -- BEGIN theorem mul_zero (a : R') : a * 0 = 0 := begin have h : a * 0 + a * 0 = a * 0 + 0, { rw [←mul_add, add_zero, add_zero] }, rw add_left_cancel h end -- END /-We have used a new trick! If you step through the proof, you can see what is going on. The have tactic introduces a new goal, a * 0 + a * 0 = a * 0 + 0, with the same context as the original goal. In the next line, we could have omitted the curly brackets, which serve as an inner begin ... end pair. Using them promotes a modular style of proof: the part of the proof inside the brackets establishes the goal that was introduced by the have. After that, we are back to proving the original goal, except a new hypothesis h has been added: having proved it, we are now free to use it. At this point, the goal is exactly the result of add_left_cancel h. We could equally well have closed the proof with apply add_left_cancel h or exact add_left_cancel h. We will discuss apply and exact in the next section. Remember that multiplication is not assumed to be commutative, so the following theorem also requires some work.-/ -- BEGIN theorem zero_mul (a : R') : 0 * a = 0 := begin have h : 0 * a + 0 * a = 0 * a + 0, { rw [←add_mul, add_zero, add_zero]}, rw add_left_cancel h, end -- END /-By now, you should also be able replace each sorry in the next exercise with a proof, still using only facts about rings that we have established in this section.-/ -- BEGIN theorem neg_eq_of_add_eq_zero {a b : R'} (h : a + b = 0) : -a = b := begin rw ← add_left_neg a at h, rw add_comm a at h, rw add_right_cancel h, end theorem eq_neg_of_add_eq_zero {a b : R'} (h : a + b = 0) : a = -b := begin rw ← add_left_neg b at h, rw add_right_cancel h, end theorem neg_zero : (-0 : R') = 0 := begin apply neg_eq_of_add_eq_zero, rw add_zero end theorem neg_neg (a : R') : -(-a) = a := begin apply neg_eq_of_add_eq_zero, exact add_left_neg a, end -- END /-We had to use the annotation (-0 : R) instead of 0 in the third theorem because without specifying R it is impossible for Lean to infer which 0 we have in mind. In Lean, subtraction in a ring is defined to be addition of the additive inverse.-/ -- BEGIN theorem sub_eq_add_neg (a b : R') : a - b = a + -b := rfl example (a b : R') : a - b = a + -b := by reflexivity -- END /-The proof term rfl is short for reflexivity. Presenting it as a proof of a - b = a + -b forces Lean to unfold the definition and recognize both sides as being the same. The reflexivity tactic, which can be abbreviated as refl, does the same. This is an instance of what is known as a definitional equality in Lean’s underlying logic. This means that not only can one rewrite with sub_eq_add_neg to replace a - b = a + -b, but in some contexts you can use the two sides of the equation interchangeably. For example, you now have enough information to prove the theorem self_sub from the last section: -/ -- BEGIN theorem self_sub (a : R') : a - a = 0 := begin rw sub_eq_add_neg, rw add_comm, exact add_left_neg a, end theorem self_sub' (a : R') : a - a = 0 := begin {rw [sub_eq_add_neg, add_comm, add_left_neg]}, end -- END /-Extra points if you do it two different ways: - once using rw, and - once using either apply or exact. For another example of definitional equality, Lean knows that 1 + 1 = 2 holds in any ring. With a bit of cleverness, you can use that to prove the theorem two_mul from the last section:-/ -- BEGIN lemma one_add_one_eq_two : 1 + 1 = (2 : R') := by refl theorem two_mul (a : R') : 2 * a = a + a := begin {rw [← one_add_one_eq_two, add_mul, one_mul]} end -- END end my_ring /-We close this section by noting that some of the facts about addition and negation that we established above do not need the full strength of the ring axioms, or even commutativity of addition. The weaker notion of a group can be axiomatized as follows: -/ variables (A : Type*) [add_group A] #check (add_assoc : ∀ a b c : A, a + b + c = a + (b + c)) #check (zero_add : ∀ a : A, 0 + a = a) #check (add_left_neg : ∀ a : A, -a + a = 0) /-It is conventional to use additive notation when the group operation is commutative, and multiplicative notation otherwise. So Lean defines a multiplicative version as well as the additive version (and also their abelian variants, add_comm_group and comm_group). -/ variables (G : Type*) [group G] #check (mul_assoc : ∀ a b c : G, a * b * c = a * (b * c)) #check (one_mul : ∀ a : G, 1 * a = a) #check (mul_left_inv : ∀ a : G, a⁻¹ * a = 1) /-If you are feeling cocky, try proving the following facts about groups, using only these axioms. You will need to prove a number of helper lemmas along the way. The proofs we have carried out in this section provide some hints. -/ variables {G' : Type*} [group G'] #check (mul_assoc : ∀ a b c : G', a * b * c = a * (b * c)) #check (one_mul : ∀ a : G', 1 * a = a) #check (mul_left_inv : ∀ a : G', a⁻¹ * a = 1) namespace my_group lemma inv_mul_cancel_left (a b : G') : a⁻¹ * (a * b) = b := by rw [←mul_assoc, mul_left_inv, one_mul] lemma mul_left_cancel {a b c : G'} (h : a * b = a * c) : b = c := by rw [← one_mul b, ← mul_left_inv a, mul_assoc, h, inv_mul_cancel_left] /-lemma inv_eq_of_mul_eq_one {a b : G'} (h : b * a = 1) : b = a⁻¹ := begin rw ← mul_left_inv b at h, rw add_comm a at h, rw add_right_cancel h, end-/ theorem mul_one (a : G') : a * 1 = a := begin have h : a⁻¹ * (a * a⁻¹ * a) = a⁻¹ * a, {rw [mul_assoc, mul_left_inv, ←mul_assoc, mul_left_inv, one_mul]}, rw ← mul_left_inv a, rw ← mul_assoc, apply mul_left_cancel h, end lemma inv_mul_cancel_right (a b : G') : (a * b⁻¹) * b = a := by rw [mul_assoc, mul_left_inv, mul_one] theorem mul_right_inv (a : G') : a * a⁻¹ = 1 := begin rw ← mul_left_inv a, have h1 : 1 * a⁻¹ = a⁻¹ * 1, {rw [one_mul, mul_one]}, have h2 : a⁻¹ * (a * a⁻¹) = a⁻¹ * (a⁻¹ * a), {rw [mul_left_inv, ← mul_assoc, mul_left_inv, h1]}, apply mul_left_cancel h2, end theorem mul_inv_rev (a b : G') : (a * b)⁻¹ = b⁻¹ * a ⁻¹ := begin have h1 : (a * b) * (b⁻¹ * a⁻¹) = 1, {rw [mul_assoc, ← mul_assoc b, mul_right_inv, one_mul, mul_right_inv]}, have h2 : (a * b) * (a * b)⁻¹ = (a * b) * (b⁻¹ * a⁻¹), {rw [mul_right_inv, h1]}, apply mul_left_cancel h2, end end my_group --650 hw 4 q1 namespace my_ring variables {R' : Type*} [ring R'] lemma square_comm {a b : R'} (h : ∀ a : R', a^2 = a) : a*b = b*a := begin have h1 : a + b = a + (b * a + a * b) + b, calc a + b = (a + b)^2: by rw [h] ... = a^2 + b * a + (a * b + b^2) : by {repeat {rw pow_two}, rw mul_add, repeat {rw add_mul}} ... = a + (b * a + a * b) + b : by rw [h a, h b, add_assoc, ← add_assoc (b * a), ← add_assoc], have h2 : -(a * b) = a * b, calc -(a * b) = (-(a * b))^2 : by rw [h] ... = -(a * b) * -(a * b) : by rw [pow_two] ... = (a * b)^2 : by rw [neg_mul_neg, pow_two] ... = a * b : by rw [h], rw add_assoc at h1, rw ← add_zero (a + b) at h1, rw add_assoc at h1, rw add_left_cancel_iff at h1, rw add_comm at h1, rw add_right_cancel_iff at h1, symmetry' at h1, symmetry' at h2, rw h2, rw eq_neg_of_add_eq_zero h1, end lemma cube_comm {a b : R'} (h : ∀ a : R', a^3 = a) : a*b = b*a := begin have h1 : a^3 + b = a^3 + a^2 * b + a * b * a + a * b^2 + b * a^2 + b * a * b + b^2 * a + b^3, calc a^3 + b = a + b: by rw [h] ... = (a + b)^3 : by rw [h] ... = (a + b) * (a + b)^2 : by rw [← pow_succ] ... = (a + b) * (a^2 + a * b + b * a + b^2) : by {repeat {rw pow_two}, rw [← mul_add, add_assoc, ← mul_add, ← add_mul]} --by rw [pow_two, pow_two, pow_two, ← mul_add, add_assoc, ← mul_add, ← add_mul] ... = a * a ^ 2 + a * (a * b) + a * (b * a) + a * b ^ 2 + (b * a ^ 2 + b * (a * b) + b * (b * a) + b * b ^ 2) : by {rw add_mul, repeat {rw mul_add}} ... = a * a ^ 2 + a * a * b + a * b * a + a * b ^ 2 + b * a ^ 2 + b * a * b + b * b * a + b * b ^ 2 : by {repeat {rw ← mul_assoc}, repeat {rw ← add_assoc}} ... = a^3 + a^2 * b + a * b * a + a * b^2 + b * a^2 + b * a * b + b^2 * a + b^3 : by {repeat {rw ← pow_succ}, repeat {rw ← pow_two}}, have h2 : (a - b)^2 = a^2 - a * b - b * a + b^2, calc (a - b)^2 = (a - b) * (a - b): by rw [pow_two] ... = a * a - a * b - b * a + b * b : by sorry /-by rw [sub_mul, mul_sub, mul_sub, add_sub]-/ ... = a^2 - a * b - b * a + b^2 : by sorry, have h3 : a^3 - b = a^3 - a^2 * b - a * b * a + a * b^2 - b * a^2 + b * a * b + b^2 * a - b^3, calc a^3 - b = a - b: by rw [h] ... = (a - b)^3 : by rw [h] ... = (a - b) * (a - b)^2 : by rw [← pow_succ] ... = (a - b) * (a^2 - a * b - b * a + b^2) : by {repeat {rw pow_two}, repeat { rw mul_sub }, repeat { rw sub_mul }, repeat { rw add_sub }, repeat { rw ←sub_add }, repeat { rw ←mul_assoc }} ... = a * b : by rw [h], rw add_assoc at h1, rw ← add_zero (a + b) at h1, rw add_assoc at h1, rw add_left_cancel_iff at h1, rw add_comm at h1, rw add_right_cancel_iff at h1, symmetry' at h1, symmetry' at h2, rw h2, rw eq_neg_of_add_eq_zero h1, end lemma problem_nine_1 {x : R'} (h : ∀ x, ∃ y : R', x * y * x = x) : (∀ a b : R', a * b = 0 → a = 0 ∨ b = 0) := begin exfalso, have h2 := ∃ a b : R', (a * b = 0) → ((a ≠ 0) ∧ (b ≠ 0)), sorry, end variables {α : Type*} [domain α] lemma problem_nine_2 [no_zero_divisors α] {x y : R'} (h1 : x * y * x = x): (y * x * y = y) := begin /-have h3 : x * y * x = x * (y * x * y * x), calc x * y * x = (x * y * x) * y * x : by {rw [h1, h1]} ... = x * (y * x * y * x) : by rw [mul_assoc, mul_assoc, mul_assoc, ← mul_assoc _ _ x, ← mul_assoc y, ← mul_assoc y], rw mul_assoc at h3, rw mul_left_cancel_iff at h3,-/ sorry end end my_ring
fe14a767fde63351d33e200440cf56af85035d04
22e97a5d648fc451e25a06c668dc03ac7ed7bc25
/src/tactic/suggest.lean
8f842946e1a97dfadadfde1a5f47fb1615f1a7d3
[ "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
17,392
lean
/- Copyright (c) 2019 Lucas Allen. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Lucas Allen and Scott Morrison -/ import data.mllist import tactic.solve_by_elim /-! # `suggest` and `library_search` `suggest` and `library_search` are a pair of tactics for applying lemmas from the library to the current goal. * `suggest` prints a list of `exact ...` or `refine ...` statements, which may produce new goals * `library_search` prints a single `exact ...` which closes the goal, or fails -/ namespace tactic open native namespace suggest open solve_by_elim /-- compute the head symbol of an expression, but normalise `>` to `<` and `≥` to `≤` -/ -- We may want to tweak this further? meta def head_symbol : expr → name | (expr.pi _ _ _ t) := head_symbol t | (expr.app f _) := head_symbol f | (expr.const n _) := -- TODO this is a hack; if you suspect more cases here would help, please report them match n with | `gt := `has_lt.lt | `ge := `has_le.le | _ := n end | _ := `_ /-- A declaration can match the head symbol of the current goal in four possible ways: * `ex` : an exact match * `mp` : the declaration returns an `iff`, and the right hand side matches the goal * `mpr` : the declaration returns an `iff`, and the left hand side matches the goal * `both`: the declaration returns an `iff`, and the both sides match the goal -/ @[derive decidable_eq, derive inhabited] inductive head_symbol_match | ex | mp | mpr | both open head_symbol_match /-- a textual representation of a `head_symbol_match`, for trace debugging. -/ def head_symbol_match.to_string : head_symbol_match → string | ex := "exact" | mp := "iff.mp" | mpr := "iff.mpr" | both := "iff.mp and iff.mpr" /-- When we are determining if a given declaration is potentially relevant for the current goal, we compute `unfold_head_symbol` on the head symbol of the declaration, producing a list of names. We consider the declaration potentially relevant if the head symbol of the goal appears in this list. -/ -- This is a hack. meta def unfold_head_symbol : name → list name | `false := [`not, `false] | n := [n] /-- Determine if, and in which way, a given expression matches the specified head symbol. -/ meta def match_head_symbol (hs : name) : expr → option head_symbol_match | (expr.pi _ _ _ t) := match_head_symbol t | `(%%a ↔ %%b) := if `iff = hs then some ex else match (match_head_symbol a, match_head_symbol b) with | (some ex, some ex) := some both | (some ex, _) := some mpr | (_, some ex) := some mp | _ := none end | (expr.app f _) := match_head_symbol f | (expr.const n _) := if list.mem hs (unfold_head_symbol n) then some ex else none | _ := if hs = `_ then some ex else none /-- A package of `declaration` metadata, including the way in which its type matches the head symbol which we are searching for. -/ meta structure decl_data := (d : declaration) (n : name) (m : head_symbol_match) (l : ℕ) -- cached length of name /-- Generate a `decl_data` from the given declaration if it matches the head symbol `hs` for the current goal. -/ -- We used to check here for private declarations, or declarations with certain suffixes. -- It turns out `apply` is so fast, it's better to just try them all. meta def process_declaration (hs : name) (d : declaration) : option decl_data := let n := d.to_name in if ¬ d.is_trusted ∨ n.is_internal then none else (λ m, ⟨d, n, m, n.length⟩) <$> match_head_symbol hs d.type /-- Retrieve all library definitions with a given head symbol. -/ meta def library_defs (hs : name) : tactic (list decl_data) := do env ← get_env, return $ env.decl_filter_map (process_declaration hs) /-- Apply the lemma `e`, then attempt to close all goals using `solve_by_elim opt`, failing if `close_goals = tt` and there are any goals remaining. -/ -- Implementation note: as this is used by both `library_search` and `suggest`, -- we first run `solve_by_elim` separately on a subset of the goals, -- whether or not `close_goals` is set, -- and then if `close_goals = tt`, require that `solve_by_elim { all_goals := tt }` succeeds -- on the remaining goals. meta def apply_and_solve (close_goals : bool) (opt : opt := { }) (e : expr) : tactic unit := opt.apply e >> -- Phase 1 -- Run `solve_by_elim` on each "safe" goal separately, not worrying about failures. -- (We only attempt the "safe" goals in this way in Phase 1. In Phase 2 we will do -- backtracking search across all goals, allowing us to guess solutions that involve data, or -- unify metavariables, but only as long as we can finish all goals.) try (any_goals (independent_goal >> solve_by_elim opt)) >> -- Phase 2 (done <|> -- If there were any goals that we did not attempt solving in the first phase -- (because they weren't propositional, or contained a metavariable) -- as a second phase we attempt to solve all remaining goals at once -- (with backtracking across goals). any_goals (success_if_fail independent_goal) >> solve_by_elim { backtrack_all_goals := tt, ..opt } <|> -- and fail unless `close_goals = ff` guard ¬ close_goals) /-- Apply the declaration `d` (or the forward and backward implications separately, if it is an `iff`), and then attempt to solve the goal using `apply_and_solve`. -/ meta def apply_declaration (close_goals : bool) (opt : opt := { }) (d : decl_data) : tactic unit := let tac := apply_and_solve close_goals opt in do (e, t) ← decl_mk_const d.d, match d.m with | ex := tac e | mp := do l ← iff_mp_core e t, tac l | mpr := do l ← iff_mpr_core e t, tac l | both := (do l ← iff_mp_core e t, tac l) <|> (do l ← iff_mpr_core e t, tac l) end /-- Replace any metavariables in the expression with underscores, in preparation for printing `refine ...` statements. -/ meta def replace_mvars (e : expr) : expr := e.replace (λ e' _, if e'.is_mvar then some (unchecked_cast pexpr.mk_placeholder) else none) /-- Construct a `refine ...` or `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}") /-- An `application` records the result of a successful application of a library lemma. -/ meta structure application := (state : tactic_state) (script : string) (decl : option declaration) (num_goals : ℕ) (hyps_used : ℕ) end suggest open solve_by_elim open suggest declare_trace suggest -- Trace a list of all relevant lemmas -- Call `apply_declaration`, then prepare the tactic script and -- count the number of local hypotheses used. private meta def apply_declaration_script (g : expr) (hyps : list expr) (opt : opt := { }) (d : decl_data) : tactic application := -- (This tactic block is only executed when we evaluate the mllist, -- so we need to do the `focus1` here.) retrieve $ focus1 $ do apply_declaration ff opt d, ng ← num_goals, -- This `instantiate_mvars` is necessary so that we count used hypotheses correctly. g ← instantiate_mvars g, s ← read, m ← tactic_statement g, return { application . state := s, decl := d.d, script := m, num_goals := ng, hyps_used := hyps.countp (λ h, h.occurs g) } -- implementation note: we produce a `tactic (mllist tactic application)` first, -- because it's easier to work in the tactic monad, but in a moment we squash this -- down to an `mllist tactic application`. private meta def suggest_core' (opt : opt := { }) : tactic (mllist tactic application) := do g :: _ ← get_goals, hyps ← local_context, -- Make sure that `solve_by_elim` doesn't just solve the goal immediately: (retrieve (do focus1 $ solve_by_elim opt, s ← read, m ← tactic_statement g, -- This `instantiate_mvars` is necessary so that we count used hypotheses correctly. g ← instantiate_mvars g, return $ mllist.of_list [⟨s, m, none, 0, hyps.countp (λ h, h.occurs g)⟩])) <|> -- Otherwise, let's actually try applying library lemmas. (do -- Collect all definitions with the correct head symbol t ← infer_type g, defs ← library_defs (head_symbol t), -- Sort by length; people like short proofs let defs := defs.qsort(λ d₁ d₂, d₁.l ≤ d₂.l), trace_if_enabled `suggest format!"Found {defs.length} relevant lemmas:", trace_if_enabled `suggest $ defs.map (λ ⟨d, n, m, l⟩, (n, m.to_string)), let defs : mllist tactic _ := mllist.of_list defs, -- Try applying each lemma against the goal, -- recording the tactic script as a string, -- the number of remaining goals, -- and number of local hypotheses used. let results := defs.mfilter_map (apply_declaration_script g hyps opt), -- Now call `symmetry` and try again. -- (Because we are using `mllist`, this is essentially free if we've already found a lemma.) symm_state ← retrieve $ try_core $ symmetry >> read, let results_symm := match symm_state with | (some s) := defs.mfilter_map (λ d, retrieve $ set_state s >> apply_declaration_script g hyps opt d) | none := mllist.nil end, return (results.append results_symm)) /-- The core `suggest` tactic. It attempts to apply a declaration from the library, then solve new goals using `solve_by_elim`. It returns a list of `application`s consisting of fields: * `state`, a tactic state resulting from the successful application of a declaration from the library, * `script`, a string of the form `refine ...` or `exact ...` which will reproduce that tactic state, * `decl`, an `option declaration` indicating the declaration that was applied (or none, if `solve_by_elim` succeeded), * `num_goals`, the number of remaining goals, and * `hyps_used`, the number of local hypotheses used in the solution. -/ meta def suggest_core (opt : opt := { }) : mllist tactic application := (mllist.monad_lift (suggest_core' opt)).join /-- See `suggest_core`. Returns a list of at most `limit` `application`s, sorted by number of goals, and then (reverse) number of hypotheses used. -/ meta def suggest (limit : option ℕ := none) (opt : opt := { }) : tactic (list application) := do let results := suggest_core opt, -- Get the first n elements of the successful lemmas L ← if h : limit.is_some then results.take (option.get h) else results.force, -- Sort by number of remaining goals, then by number of hypotheses used. return $ L.qsort (λ d₁ d₂, d₁.num_goals < d₂.num_goals ∨ (d₁.num_goals = d₂.num_goals ∧ d₁.hyps_used ≥ d₂.hyps_used)) /-- Returns a list of at most `limit` strings, of the form `exact ...` or `refine ...`, which make progress on the current goal using a declaration from the library. -/ meta def suggest_scripts (limit : option ℕ := none) (opt : opt := { }) : tactic (list string) := do L ← suggest limit opt, return $ L.map application.script /-- Returns a string of the form `exact ...`, which closes the current goal. -/ meta def library_search (opt : opt := { }) : tactic string := (suggest_core opt).mfirst (λ a, do guard (a.num_goals = 0), write a.state, return a.script) namespace interactive open tactic open interactive open lean.parser open interactive.types open solve_by_elim local postfix `?`:9001 := optional declare_trace silence_suggest -- Turn off `exact/refine ...` trace messages for `suggest` /-- `suggest` tries to apply suitable theorems/defs from the library, and generates a list of `exact ...` or `refine ...` scripts that could be used at this step. It leaves the tactic state unchanged. It is intended as a complement of the search function in your editor, the `#find` tactic, and `library_search`. `suggest` takes an optional natural number `num` as input and returns the first `num` (or less, if all possibilities are exhausted) possibilities ordered by length of lemma names. The default for `num` is `50`. For performance reasons `suggest` uses monadic lazy lists (`mllist`). This means that `suggest` might miss some results if `num` is not large enough. However, because `suggest` uses monadic lazy lists, smaller values of `num` run faster than larger values. You can add additional lemmas to be used along with local hypotheses after the application of a library lemma, using the same syntax as for `solve_by_elim`, e.g. ``` example {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) := begin suggest [add_lt_add], -- Says: `exact max_eq_left_of_lt (add_lt_add h₁ h₂)` end ``` You can also use `suggest with attr` to include all lemmas with the attribute `attr`. -/ meta def suggest (n : parse (with_desc "n" small_nat)?) (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (opt : opt := { }) : tactic unit := do asms ← mk_assumption_set ff hs attr_names, L ← tactic.suggest_scripts (n.get_or_else 50) { lemma_thunks := return asms, ..opt }, if is_trace_enabled_for `silence_suggest then skip else if L.length = 0 then fail "There are no applicable declarations" else L.mmap trace >> skip /-- `suggest` lists possible usages of the `refine` tactic and leaves the tactic state unchanged. It is intended as a complement of the search function in your editor, the `#find` tactic, and `library_search`. `suggest` takes an optional natural number `num` as input and returns the first `num` (or less, if all possibilities are exhausted) possibilities ordered by length of lemma names. The default for `num` is `50`. For performance reasons `suggest` uses monadic lazy lists (`mllist`). This means that `suggest` might miss some results if `num` is not large enough. However, because `suggest` uses monadic lazy lists, smaller values of `num` run faster than larger values. An example of `suggest` in action, ```lean example (n : nat) : n < n + 1 := begin suggest, sorry end ``` prints the list, ```lean Try this: exact nat.lt.base n Try this: exact nat.lt_succ_self n Try this: refine not_le.mp _ Try this: refine gt_iff_lt.mp _ Try this: refine nat.lt.step _ Try this: refine lt_of_not_ge _ ... ``` -/ add_tactic_doc { name := "suggest", category := doc_category.tactic, decl_names := [`tactic.interactive.suggest], tags := ["search", "Try this"] } declare_trace silence_library_search -- Turn off `exact ...` trace message for `library_search /-- `library_search` attempts to apply every definition in the library whose head symbol matches the goal, and then discharge any new goals using `solve_by_elim`. If it succeeds, it prints a trace message `exact ...` which can replace the invocation of `library_search`. You can add additional lemmas to be used along with local hypotheses after the application of a library lemma, using the same syntax as for `solve_by_elim`, e.g. ``` example {a b c d: nat} (h₁ : a < c) (h₂ : b < d) : max (c + d) (a + b) = (c + d) := begin library_search [add_lt_add], -- Says: `exact max_eq_left_of_lt (add_lt_add h₁ h₂)` end ``` You can also use `suggest with attr` to include all lemmas with the attribute `attr`. -/ meta def library_search (hs : parse simp_arg_list) (attr_names : parse with_ident_list) (opt : opt := { }) : tactic unit := do asms ← mk_assumption_set ff hs attr_names, tactic.library_search {backtrack_all_goals := tt, lemma_thunks := return asms, ..opt} >>= if is_trace_enabled_for `silence_library_search then (λ _, skip) else trace /-- `library_search` is a tactic to identify existing lemmas in the library. It tries to close the current goal by applying a lemma from the library, then discharging any new goals using `solve_by_elim`. Typical usage is: ```lean example (n m k : ℕ) : n * (m - k) = n * m - n * k := by library_search -- Try this: exact nat.mul_sub_left_distrib n m k ``` `library_search` prints a trace message showing the proof it found, shown above as a comment. Typically you will then copy and paste this proof, replacing the call to `library_search`. -/ add_tactic_doc { name := "library_search", category := doc_category.tactic, decl_names := [`tactic.interactive.library_search], tags := ["search", "Try this"] } end interactive /-- Invoking the hole command `library_search` ("Use `library_search` to complete the goal") calls the tactic `library_search` to produce a proof term with the type of the hole. Running it on ```lean example : 0 < 1 := {!!} ``` produces ```lean example : 0 < 1 := nat.one_pos ``` -/ @[hole_command] meta def library_search_hole_cmd : hole_command := { name := "library_search", descr := "Use `library_search` to complete the goal.", action := λ _, do script ← library_search, -- Is there a better API for dropping the 'exact ' prefix on this string? return [((script.mk_iterator.remove 6).to_string, "by library_search")] } add_tactic_doc { name := "library_search", category := doc_category.hole_cmd, decl_names := [`tactic.library_search_hole_cmd], tags := ["search", "Try this"] } end tactic
2de2d2f3703753ac6a03388ce2ff23a404fef42a
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/loopErrorRecovery.lean
577ee72a2e4ccdce7be3f1ab24ec908e3a55c7af
[ "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
44
lean
example : (p ∨ p) → p := fun h => match
f340352e162965315a837c91438c6356d399788f
ad0c7d243dc1bd563419e2767ed42fb323d7beea
/data/polynomial.lean
01d0823dc6ac2076101f5d92130eed57da0a19e5
[ "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
50,172
lean
/- Copyright (c) 2018 Chris Hughes. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Chris Hughes, Johannes Hölzl, Jens Wagemaker Theory of univariate polynomials, represented as `ℕ →₀ α`, where α is a commutative semiring. -/ import data.finsupp algebra.euclidean_domain /-- `polynomial α` is the type of univariate polynomials over `α`. Polynomials should be seen as (semi-)rings with the additional the constructor `X`. `C` is the embedding from `α`. -/ def polynomial (α : Type*) [comm_semiring α] := ℕ →₀ α open finsupp finset lattice namespace polynomial universe u variables {α : Type u} {a b : α} {m n : ℕ} variables [decidable_eq α] section comm_semiring variables [comm_semiring α] {p q : polynomial α} instance : has_coe_to_fun (polynomial α) := finsupp.has_coe_to_fun instance : has_zero (polynomial α) := finsupp.has_zero instance : has_one (polynomial α) := finsupp.has_one instance : has_add (polynomial α) := finsupp.has_add instance : has_mul (polynomial α) := finsupp.has_mul instance : comm_semiring (polynomial α) := finsupp.to_comm_semiring instance : decidable_eq (polynomial α) := finsupp.decidable_eq instance [has_repr α] : has_repr (polynomial α) := ⟨λ p, if p = 0 then "0" else (p.support.sort (≤)).foldr (λ n a, a ++ (if a = "" then "" else " + ") ++ if n = 0 then "C (" ++ repr (p n) ++ ")" else if n = 1 then if (p n) = 1 then "X" else "C (" ++ repr (p n) ++ ") * X" else if (p n) = 1 then "X ^ " ++ repr n else "C (" ++ repr (p n) ++ ") * X ^ " ++ repr n) ""⟩ local attribute [instance] finsupp.to_comm_semiring @[simp] lemma support_zero : (0 : polynomial α).support = ∅ := rfl /-- `C a` is the constant polynomial `a`. -/ def C (a : α) : polynomial α := single 0 a /-- `X` is the polynomial variable (aka indeterminant). -/ def X : polynomial α := single 1 1 /-- `degree p` is the degree of the polynomial `p`, i.e. the largest `X`-exponent in `p`. `degree p = some n` when `p ≠ 0` and `n` is the highest power of `X` that appears in `p`, otherwise `degree 0 = ⊥`. -/ def degree (p : polynomial α) : with_bot ℕ := p.support.sup some def degree_lt_wf : well_founded (λp q : polynomial α, degree p < degree q) := inv_image.wf degree (with_bot.well_founded_lt nat.lt_wf) /-- `nat_degree p` forces `degree p` to ℕ, by fixing the zero polnomial to the 0 degree. -/ def nat_degree (p : polynomial α) : ℕ := (degree p).get_or_else 0 lemma single_eq_C_mul_X : ∀{n}, single n a = C a * X^n | 0 := by simp; refl | (n+1) := calc single (n + 1) a = single n a * X : by rw [X, single_mul_single, mul_one] ... = (C a * X^n) * X : by rw [single_eq_C_mul_X] ... = C a * X^(n+1) : by simp [pow_add, mul_assoc] lemma sum_C_mul_X_eq (p : polynomial α) : p.sum (λn a, C a * X^n) = p := eq.trans (sum_congr rfl $ assume n hn, single_eq_C_mul_X.symm) finsupp.sum_single @[elab_as_eliminator] protected lemma induction_on {M : polynomial α → Prop} (p : polynomial α) (h_C : ∀a, M (C a)) (h_add : ∀p q, M p → M q → M (p + q)) (h_monomial : ∀(n : ℕ) (a : α), M (C a * X^n) → M (C a * X^(n+1))) : M p := have ∀{n:ℕ} {a}, M (C a * X^n), begin assume n a, induction n with n ih, { simp [h_C] }, { exact h_monomial _ _ ih } end, finsupp.induction p (suffices M (C 0), by simpa [C], h_C 0) (assume n a p _ _ hp, suffices M (C a * X^n + p), by rwa [single_eq_C_mul_X], h_add _ _ this hp) @[simp] lemma zero_apply (n : ℕ) : (0 : polynomial α) n = 0 := rfl @[simp] lemma one_apply_zero (n : ℕ) : (1 : polynomial α) 0 = 1 := rfl @[simp] lemma add_apply (p q : polynomial α) (n : ℕ) : (p + q) n = p n + q n := finsupp.add_apply lemma C_apply : (C a : ℕ → α) n = ite (0 = n) a 0 := rfl @[simp] lemma C_apply_zero : (C a : ℕ → α) 0 = a := rfl @[simp] lemma X_apply_one : (X : polynomial α) 1 = 1 := rfl @[simp] lemma C_0 : C (0 : α) = 0 := by simp [C]; refl @[simp] lemma C_1 : C (1 : α) = 1 := rfl @[simp] lemma C_mul : C (a * b) = C a * C b := by simp [C, single_mul_single] @[simp] lemma C_add : C (a + b) = C a + C b := finsupp.single_add instance C.is_semiring_hom : is_semiring_hom (C : α → polynomial α) := ⟨C_0, C_1, λ _ _, C_add, λ _ _, C_mul⟩ @[simp] lemma C_mul_apply (p : polynomial α) : (C a * p) n = a * p n := begin conv in (a * _) { rw [← @sum_single _ _ _ _ _ p, sum_apply] }, rw [mul_def, C, sum_single_index], { simp [single_apply, finsupp.mul_sum], apply sum_congr rfl, assume i hi, by_cases i = n; simp [h] }, simp end lemma C_inj : C a = C b ↔ a = b := ⟨λ h, C_apply_zero.symm.trans (h.symm ▸ C_apply_zero), congr_arg C⟩ @[simp] lemma X_pow_apply (n i : ℕ) : (X ^ n : polynomial α) i = (if n = i then 1 else 0) := suffices (single n 1 : polynomial α) i = (if n = i then 1 else 0), by rw [single_eq_C_mul_X] at this; simpa, single_apply section eval₂ variables {β : Type*} [comm_semiring β] variables (f : α → β) [is_semiring_hom f] (x : β) open is_semiring_hom /-- Evaluate a polynomial `p` given a ring hom `f` from the scalar ring to the target and a value `x` for the variable in the target -/ def eval₂ (p : polynomial α) : β := p.sum (λ e a, f a * x ^ e) @[simp] lemma eval₂_C : (C a).eval₂ f x = f a := by simp [C, eval₂, sum_single_index, map_zero f] @[simp] lemma eval₂_X : X.eval₂ f x = x := by simp [X, eval₂, sum_single_index, map_zero f, map_one f] @[simp] lemma eval₂_zero : (0 : polynomial α).eval₂ f x = 0 := finsupp.sum_zero_index @[simp] lemma eval₂_add : (p + q).eval₂ f x = p.eval₂ f x + q.eval₂ f x := finsupp.sum_add_index (by simp [map_zero f]) (by simp [add_mul, map_add f]) @[simp] lemma eval₂_one : (1 : polynomial α).eval₂ f x = 1 := by rw [← C_1, eval₂_C, map_one f] @[simp] lemma eval₂_mul : (p * q).eval₂ f x = p.eval₂ f x * q.eval₂ f x := begin dunfold eval₂, rw [mul_def, finsupp.sum_mul _ p], simp [finsupp.mul_sum _ q, sum_sum_index, map_zero f, map_add f, add_mul, sum_single_index, map_mul f, pow_add], exact sum_congr rfl (assume i hi, sum_congr rfl $ assume j hj, by ac_refl) end instance eval₂.is_semiring_hom : is_semiring_hom (eval₂ f x) := ⟨eval₂_zero _ _, eval₂_one _ _, λ _ _, eval₂_add _ _, λ _ _, eval₂_mul _ _⟩ lemma eval₂_pow (n : ℕ) : (p ^ n).eval₂ f x = p.eval₂ f x ^ n := map_pow _ _ _ end eval₂ section eval variable {x : α} /-- `eval x p` is the evaluation of the polynomial `p` at `x` -/ def eval : α → polynomial α → α := eval₂ id @[simp] lemma eval_C : (C a).eval x = a := eval₂_C _ _ @[simp] lemma eval_X : X.eval x = x := eval₂_X _ _ @[simp] lemma eval_zero : (0 : polynomial α).eval x = 0 := eval₂_zero _ _ @[simp] lemma eval_add : (p + q).eval x = p.eval x + q.eval x := eval₂_add _ _ @[simp] lemma eval_one : (1 : polynomial α).eval x = 1 := eval₂_one _ _ @[simp] lemma eval_mul : (p * q).eval x = p.eval x * q.eval x := eval₂_mul _ _ instance eval.is_semiring_hom : is_semiring_hom (eval x) := eval₂.is_semiring_hom _ _ lemma eval_pow (n : ℕ) : (p ^ n).eval x = p.eval x ^ n := eval₂_pow _ _ _ /-- `is_root p x` implies `x` is a root of `p`. The evaluation of `p` at `x` is zero -/ def is_root (p : polynomial α) (a : α) : Prop := p.eval a = 0 instance : decidable (is_root p a) := by unfold is_root; apply_instance @[simp] lemma is_root.def : is_root p a ↔ p.eval a = 0 := iff.rfl lemma root_mul_left_of_is_root (p : polynomial α) {q : polynomial α} : is_root q a → is_root (p * q) a := by simp [is_root.def, eval_mul] {contextual := tt} lemma root_mul_right_of_is_root {p : polynomial α} (q : polynomial α) : is_root p a → is_root (p * q) a := by simp [is_root.def, eval_mul] {contextual := tt} end eval section map variables {β : Type*} [comm_semiring β] [decidable_eq β] variables (f : α → β) [is_semiring_hom f] /-- `map f p` maps a polynomial `p` across a ring hom `f` -/ def map : polynomial α → polynomial β := eval₂ (C ∘ f) X @[simp] lemma map_C : (C a).map f = C (f a) := eval₂_C _ _ @[simp] lemma map_X : X.map f = X := eval₂_X _ _ @[simp] lemma map_zero : (0 : polynomial α).map f = 0 := eval₂_zero _ _ @[simp] lemma map_add : (p + q).map f = p.map f + q.map f := eval₂_add _ _ @[simp] lemma map_one : (1 : polynomial α).map f = 1 := eval₂_one _ _ @[simp] lemma map_mul : (p * q).map f = p.map f * q.map f := eval₂_mul _ _ instance map.is_semiring_hom : is_semiring_hom (map f) := eval₂.is_semiring_hom _ _ lemma map_pow (n : ℕ) : (p ^ n).map f = p.map f ^ n := eval₂_pow _ _ _ end map /-- `leading_coeff p` gives the coefficient of the highest power of `X` in `p`-/ def leading_coeff (p : polynomial α) : α := p (nat_degree p) /-- a polynomial is `monic` if its leading coefficient is 1 -/ def monic (p : polynomial α) := leading_coeff p = (1 : α) lemma monic.def : monic p ↔ leading_coeff p = 1 := iff.rfl instance monic.decidable : decidable (monic p) := by unfold monic; apply_instance @[simp] lemma degree_zero : degree (0 : polynomial α) = ⊥ := rfl @[simp] lemma nat_degree_zero : nat_degree (0 : polynomial α) = 0 := by simp [nat_degree]; refl @[simp] lemma degree_C (ha : a ≠ 0) : degree (C a) = (0 : with_bot ℕ) := show sup (ite (a = 0) ∅ {0}) some = 0, by rw [if_neg ha]; refl lemma degree_C_le : degree (C a) ≤ (0 : with_bot ℕ) := by by_cases h : a = 0; simp [h]; exact le_refl _ lemma degree_one_le : degree (1 : polynomial α) ≤ (0 : with_bot ℕ) := by rw [← C_1]; exact degree_C_le lemma degree_eq_bot : degree p = ⊥ ↔ p = 0 := ⟨λ h, by rw [degree, ← max_eq_sup_with_bot] at h; exact support_eq_empty.1 (max_eq_none.1 h), λ h, h.symm ▸ rfl⟩ lemma degree_eq_nat_degree (hp : p ≠ 0) : degree p = (nat_degree p : with_bot ℕ) := let ⟨n, hn⟩ := classical.not_forall.1 (mt option.eq_none_iff_forall_not_mem.2 (mt degree_eq_bot.1 hp)) in have hn : degree p = some n := not_not.1 hn, by rw [nat_degree, hn]; refl @[simp] lemma degree_le_nat_degree : degree p ≤ nat_degree p := begin by_cases hp : p = 0, { simp [hp] }, rw [degree_eq_nat_degree hp], exact le_refl _ end lemma nat_degree_eq_of_degree_eq (h : degree p = degree q) : nat_degree p = nat_degree q := by unfold nat_degree; rw h lemma le_degree_of_ne_zero (h : p n ≠ 0) : (n : with_bot ℕ) ≤ degree p := show @has_le.le (with_bot ℕ) _ (some n : with_bot ℕ) (p.support.sup some : with_bot ℕ), from finset.le_sup ((finsupp.mem_support_iff _ _).2 h) lemma le_nat_degree_of_ne_zero (h : p n ≠ 0) : n ≤ nat_degree p := begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], exact le_degree_of_ne_zero h, { assume h, subst h, exact h rfl } end lemma degree_le_degree (h : q (nat_degree p) ≠ 0) : degree p ≤ degree q := begin by_cases hp : p = 0, { simp [hp] }, { rw [degree_eq_nat_degree hp], exact le_degree_of_ne_zero h } end @[simp] lemma nat_degree_C (a : α) : nat_degree (C a) = 0 := begin by_cases ha : a = 0, { have : C a = 0, { simp [ha] }, rw [nat_degree, degree_eq_bot.2 this], refl }, { rw [nat_degree, degree_C ha], refl } end @[simp] lemma degree_monomial (n : ℕ) (ha : a ≠ 0) : degree (C a * X ^ n) = n := by rw [← single_eq_C_mul_X, degree, support_single_ne_zero ha]; refl lemma degree_monomial_le (n : ℕ) (a : α) : degree (C a * X ^ n) ≤ n := if h : a = 0 then by simp [h] else le_of_eq (degree_monomial n h) lemma eq_zero_of_degree_lt (h : degree p < n) : p n = 0 := not_not.1 (mt le_degree_of_ne_zero (not_le_of_gt h)) lemma apply_nat_degree_eq_zero_of_degree_lt (h : degree p < degree q) : p (nat_degree q) = 0 := eq_zero_of_degree_lt (lt_of_lt_of_le h degree_le_nat_degree) lemma ne_zero_of_degree_gt {n : with_bot ℕ} (h : n < degree p) : p ≠ 0 := mt degree_eq_bot.2 (ne.symm (ne_of_lt (lt_of_le_of_lt bot_le h))) lemma eq_C_of_degree_le_zero (h : degree p ≤ 0) : p = C (p 0) := begin ext n, cases n, { refl }, { have : degree p < ↑(nat.succ n) := lt_of_le_of_lt h (with_bot.some_lt_some.2 (nat.succ_pos _)), rw [C_apply, if_neg (nat.succ_ne_zero _).symm, eq_zero_of_degree_lt this] } end lemma degree_add_le (p q : polynomial α) : degree (p + q) ≤ max (degree p) (degree q) := calc degree (p + q) = ((p + q).support).sup some : rfl ... ≤ (p.support ∪ q.support).sup some : sup_mono support_add ... = p.support.sup some ⊔ q.support.sup some : sup_union ... = _ : with_bot.sup_eq_max _ _ @[simp] lemma leading_coeff_zero : leading_coeff (0 : polynomial α) = 0 := rfl @[simp] lemma leading_coeff_eq_zero : leading_coeff p = 0 ↔ p = 0 := ⟨λ h, by_contradiction $ λ hp, mt (mem_support_iff _ _).1 (not_not.2 h) (mem_of_max (degree_eq_nat_degree hp)), by simp {contextual := tt}⟩ lemma degree_add_eq_of_degree_lt (h : degree p < degree q) : degree (p + q) = degree q := le_antisymm (max_eq_right_of_lt h ▸ degree_add_le _ _) $ degree_le_degree $ begin rw [add_apply, apply_nat_degree_eq_zero_of_degree_lt h, zero_add], exact mt leading_coeff_eq_zero.1 (ne_zero_of_degree_gt h) end lemma degree_add_eq_of_leading_coeff_add_ne_zero (h : leading_coeff p + leading_coeff q ≠ 0) : degree (p + q) = max p.degree q.degree := le_antisymm (degree_add_le _ _) $ match lt_trichotomy (degree p) (degree q) with | or.inl hlt := by rw [degree_add_eq_of_degree_lt hlt, max_eq_right_of_lt hlt]; exact le_refl _ | or.inr (or.inl heq) := le_of_not_gt $ assume hlt : max (degree p) (degree q) > degree (p + q), h $ show leading_coeff p + leading_coeff q = 0, begin rw [heq, max_self] at hlt, rw [leading_coeff, leading_coeff, nat_degree_eq_of_degree_eq heq, ← add_apply], exact apply_nat_degree_eq_zero_of_degree_lt hlt end | or.inr (or.inr hlt) := by rw [add_comm, degree_add_eq_of_degree_lt hlt, max_eq_left_of_lt hlt]; exact le_refl _ end lemma degree_erase_le (p : polynomial α) (n : ℕ) : degree (p.erase n) ≤ degree p := sup_mono (erase_subset _ _) lemma degree_erase_lt (hp : p ≠ 0) : degree (p.erase (nat_degree p)) < degree p := lt_of_le_of_ne (degree_erase_le _ _) $ (degree_eq_nat_degree hp).symm ▸ λ h, not_mem_erase _ _ (mem_of_max h) lemma degree_sum_le {β : Type*} [decidable_eq β] (s : finset β) (f : β → polynomial α) : degree (s.sum f) ≤ s.sup (degree ∘ f) := finset.induction_on s (by simp [finsupp.support_zero]) $ assume a s has ih, calc degree (sum (insert a s) f) ≤ max (degree (f a)) (degree (s.sum f)) : by rw sum_insert has; exact degree_add_le _ _ ... ≤ _ : by rw [sup_insert, with_bot.sup_eq_max]; exact max_le_max (le_refl _) ih lemma degree_mul_le (p q : polynomial α) : degree (p * q) ≤ degree p + degree q := calc degree (p * q) ≤ (p.support).sup (λi, degree (sum q (λj a, C (p i * a) * X ^ (i + j)))) : by simp only [single_eq_C_mul_X.symm]; exact degree_sum_le _ _ ... ≤ p.support.sup (λi, q.support.sup (λj, degree (C (p i * q j) * X ^ (i + j)))) : finset.sup_mono_fun (assume i hi, degree_sum_le _ _) ... ≤ degree p + degree q : begin refine finset.sup_le (λ a ha, finset.sup_le (λ b hb, le_trans (degree_monomial_le _ _) _)), rw [with_bot.coe_add], rw mem_support_iff at ha hb, exact add_le_add' (le_degree_of_ne_zero ha) (le_degree_of_ne_zero hb) end lemma degree_pow_le (p : polynomial α) : ∀ n, degree (p ^ n) ≤ add_monoid.smul n (degree p) | 0 := by rw [pow_zero, add_monoid.zero_smul]; exact degree_one_le | (n+1) := calc degree (p ^ (n + 1)) ≤ degree p + degree (p ^ n) : by rw pow_succ; exact degree_mul_le _ _ ... ≤ _ : by rw succ_smul; exact add_le_add' (le_refl _) (degree_pow_le _) @[simp] lemma leading_coeff_monomial (a : α) (n : ℕ) : leading_coeff (C a * X ^ n) = a := begin by_cases ha : a = 0, { simp [ha] }, { rw [leading_coeff, nat_degree, degree_monomial _ ha, ← single_eq_C_mul_X], exact finsupp.single_eq_same } end @[simp] lemma leading_coeff_C (a : α) : leading_coeff (C a) = a := suffices leading_coeff (C a * X^0) = a, by simpa, leading_coeff_monomial a 0 @[simp] lemma leading_coeff_X : leading_coeff (X : polynomial α) = 1 := suffices leading_coeff (C (1:α) * X^1) = 1, by simpa, leading_coeff_monomial 1 1 @[simp] lemma leading_coeff_one : leading_coeff (1 : polynomial α) = 1 := suffices leading_coeff (C (1:α) * X^0) = 1, by simpa, leading_coeff_monomial 1 0 @[simp] lemma monic_one : monic (1 : polynomial α) := leading_coeff_C _ lemma leading_coeff_add_of_degree_lt (h : degree p < degree q) : leading_coeff (p + q) = leading_coeff q := have p (nat_degree q) = 0, from apply_nat_degree_eq_zero_of_degree_lt h, by simp [leading_coeff, nat_degree_eq_of_degree_eq (degree_add_eq_of_degree_lt h), this] lemma leading_coeff_add_of_degree_eq (h : degree p = degree q) (hlc : leading_coeff p + leading_coeff q ≠ 0) : leading_coeff (p + q) = leading_coeff p + leading_coeff q := have nat_degree (p + q) = nat_degree p, by apply nat_degree_eq_of_degree_eq; rw [degree_add_eq_of_leading_coeff_add_ne_zero hlc, h, max_self], by simp [leading_coeff, this, nat_degree_eq_of_degree_eq h] @[simp] lemma mul_apply_degree_add_degree (p q : polynomial α) : (p * q) (nat_degree p + nat_degree q) = leading_coeff p * leading_coeff q := have ∀i, p i ≠ 0 → i ≠ nat_degree p → q.support.sum (λj, ite (i + j = nat_degree p + nat_degree q) (p i * q j) 0) = 0, begin assume i hpi hid, rw [finset.sum_eq_single (nat_degree q)]; simp [hid], assume j hqj hjd, have hi : j < nat_degree q, from lt_of_le_of_ne (le_nat_degree_of_ne_zero hqj) hjd, have hj : i < nat_degree p, from lt_of_le_of_ne (le_nat_degree_of_ne_zero hpi) hid, exact if_neg (ne_of_lt $ add_lt_add hj hi) end, begin rw [mul_def, sum_apply, finsupp.sum, finset.sum_eq_single (nat_degree p), sum_apply, finsupp.sum, finset.sum_eq_single (nat_degree q)]; simp [single_apply, leading_coeff] {contextual := tt}, assumption end lemma degree_mul_eq' (h : leading_coeff p * leading_coeff q ≠ 0) : degree (p * q) = degree p + degree q := have hp : p ≠ 0 := by refine mt _ h; simp {contextual := tt}, have hq : q ≠ 0 := by refine mt _ h; by simp {contextual := tt}, le_antisymm (degree_mul_le _ _) begin rw [degree_eq_nat_degree hp, degree_eq_nat_degree hq], refine le_degree_of_ne_zero _, rwa mul_apply_degree_add_degree end lemma nat_degree_mul_eq' (h : leading_coeff p * leading_coeff q ≠ 0) : nat_degree (p * q) = nat_degree p + nat_degree q := have hp : p ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, by simpa [h₁] using h), have hq : q ≠ 0 := mt leading_coeff_eq_zero.2 (λ h₁, by simpa [h₁] using h), have hpq : p * q ≠ 0 := λ hpq, by rw [← mul_apply_degree_add_degree, hpq, zero_apply] at h; exact h rfl, option.some_inj.1 (show (nat_degree (p * q) : with_bot ℕ) = nat_degree p + nat_degree q, by rw [← degree_eq_nat_degree hpq, degree_mul_eq' h, degree_eq_nat_degree hp, degree_eq_nat_degree hq]) lemma leading_coeff_mul' (h : leading_coeff p * leading_coeff q ≠ 0) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin unfold leading_coeff, rw [nat_degree_mul_eq' h, mul_apply_degree_add_degree], refl end lemma leading_coeff_pow' : leading_coeff p ^ n ≠ 0 → leading_coeff (p ^ n) = leading_coeff p ^ n := nat.rec_on n (by simp) $ λ n ih h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, by simpa [h₁, pow_succ] using h, have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← ih h₁] at h, by rw [pow_succ, pow_succ, leading_coeff_mul' h₂, ih h₁] lemma degree_pow_eq' : ∀ {n}, leading_coeff p ^ n ≠ 0 → degree (p ^ n) = add_monoid.smul n (degree p) | 0 := λ h, by rw [pow_zero, ← C_1] at *; rw [degree_C h, add_monoid.zero_smul] | (n+1) := λ h, have h₁ : leading_coeff p ^ n ≠ 0 := λ h₁, by simpa [h₁, pow_succ] using h, have h₂ : leading_coeff p * leading_coeff (p ^ n) ≠ 0 := by rwa [pow_succ, ← leading_coeff_pow' h₁] at h, by rw [pow_succ, degree_mul_eq' h₂, succ_smul, degree_pow_eq' h₁] @[simp] lemma leading_coeff_X_pow : ∀ n : ℕ, leading_coeff ((X : polynomial α) ^ n) = 1 | 0 := by simp | (n+1) := if h10 : (1 : α) = 0 then by rw [pow_succ, ← one_mul X, ← C_1, h10]; simp else have h : leading_coeff (X : polynomial α) * leading_coeff (X ^ n) ≠ 0, by rw [leading_coeff_X, leading_coeff_X_pow n, one_mul]; exact h10, by rw [pow_succ, leading_coeff_mul' h, leading_coeff_X, leading_coeff_X_pow, one_mul] end comm_semiring section comm_ring variables [comm_ring α] {p q : polynomial α} instance : comm_ring (polynomial α) := finsupp.to_comm_ring instance : has_scalar α (polynomial α) := finsupp.to_has_scalar instance : module α (polynomial α) := finsupp.to_module α instance C.is_ring_hom : is_ring_hom (@C α _ _) := by apply is_ring_hom.of_semiring instance eval₂.is_ring_hom {β} [comm_ring β] (f : α → β) [is_ring_hom f] {x : β} : is_ring_hom (eval₂ f x) := by apply is_ring_hom.of_semiring instance eval.is_ring_hom {x : α} : is_ring_hom (eval x) := eval₂.is_ring_hom _ instance map.is_ring_hom {β} [comm_ring β] [decidable_eq β] (f : α → β) [is_ring_hom f] : is_ring_hom (map f) := eval₂.is_ring_hom (C ∘ f) @[simp] lemma degree_neg (p : polynomial α) : degree (-p) = degree p := by unfold degree; rw support_neg @[simp] lemma neg_apply (p : polynomial α) (n : ℕ) : (-p) n = -p n := neg_apply @[simp] lemma eval_neg (p : polynomial α) (x : α) : (-p).eval x = -p.eval x := is_ring_hom.map_neg _ @[simp] lemma eval_sub (p q : polynomial α) (x : α) : (p - q).eval x = p.eval x - q.eval x := is_ring_hom.map_sub _ lemma degree_sub_lt (hd : degree p = degree q) (hp0 : p ≠ 0) (hlc : leading_coeff p = leading_coeff q) : degree (p - q) < degree p := have hp : single (nat_degree p) (leading_coeff p) + p.erase (nat_degree p) = p := finsupp.single_add_erase, have hq : single (nat_degree q) (leading_coeff q) + q.erase (nat_degree q) = q := finsupp.single_add_erase, have hd' : nat_degree p = nat_degree q := by unfold nat_degree; rw hd, have hq0 : q ≠ 0 := mt degree_eq_bot.2 (hd ▸ mt degree_eq_bot.1 hp0), calc degree (p - q) = degree (erase (nat_degree q) p + -erase (nat_degree q) q) : by conv {to_lhs, rw [← hp, ← hq, hlc, hd', add_sub_add_left_eq_sub, sub_eq_add_neg]} ... ≤ max (degree (erase (nat_degree q) p)) (degree (erase (nat_degree q) q)) : degree_neg (erase (nat_degree q) q) ▸ degree_add_le _ _ ... < degree p : max_lt_iff.2 ⟨hd' ▸ degree_erase_lt hp0, hd.symm ▸ degree_erase_lt hq0⟩ instance : has_well_founded (polynomial α) := ⟨_, degree_lt_wf⟩ lemma ne_zero_of_ne_zero_of_monic (hp : p ≠ 0) (hq : monic q) : q ≠ 0 | h := begin rw [h, monic.def, leading_coeff_zero] at hq, rw [← mul_one p, ← C_1, ← hq, C_0, mul_zero] at hp, exact hp rfl end lemma div_wf_lemma (h : degree q ≤ degree p ∧ p ≠ 0) (hq : monic q) : degree (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) < degree p := have hp : leading_coeff p ≠ 0 := mt leading_coeff_eq_zero.1 h.2, have hpq : leading_coeff (C (leading_coeff p) * X ^ (nat_degree p - nat_degree q)) * leading_coeff q ≠ 0, by rwa [leading_coeff_monomial, monic.def.1 hq, mul_one], if h0 : p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q = 0 then h0.symm ▸ (lt_of_not_ge $ mt le_bot_iff.1 (mt degree_eq_bot.1 h.2)) else have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic h.2 hq, have hlt : nat_degree q ≤ nat_degree p := with_bot.coe_le_coe.1 (by rw [← degree_eq_nat_degree h.2, ← degree_eq_nat_degree hq0]; exact h.1), degree_sub_lt (by rw [degree_mul_eq' hpq, degree_monomial _ hp, degree_eq_nat_degree h.2, degree_eq_nat_degree hq0, ← with_bot.coe_add, nat.sub_add_cancel hlt]) h.2 (by rw [leading_coeff_mul' hpq, leading_coeff_monomial, monic.def.1 hq, mul_one]) def div_mod_by_monic_aux : Π (p : polynomial α) {q : polynomial α}, monic q → polynomial α × polynomial α | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then let z := C (leading_coeff p) * X^(nat_degree p - nat_degree q) in have wf : _ := div_wf_lemma h hq, let dm := div_mod_by_monic_aux (p - z * q) hq in ⟨z + dm.1, dm.2⟩ else ⟨0, p⟩ using_well_founded {dec_tac := tactic.assumption} /-- `div_by_monic` gives the quotient of `p` by a monic polynomial `q`. -/ def div_by_monic (p q : polynomial α) : polynomial α := if hq : monic q then (div_mod_by_monic_aux p hq).1 else 0 /-- `mod_by_monic` gives the remainder of `p` by a monic polynomial `q`. -/ def mod_by_monic (p q : polynomial α) : polynomial α := if hq : monic q then (div_mod_by_monic_aux p hq).2 else p infixl ` /ₘ ` : 70 := div_by_monic infixl ` %ₘ ` : 70 := mod_by_monic lemma degree_mod_by_monic_lt : ∀ (p : polynomial α) {q : polynomial α} (hq : monic q) (hq0 : q ≠ 0), degree (p %ₘ q) < degree q | p := λ q hq hq0, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma ⟨h.1, h.2⟩ hq, have degree ((p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) %ₘ q) < degree q := degree_mod_by_monic_lt (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq hq0, begin unfold mod_by_monic at this ⊢, unfold div_mod_by_monic_aux, rw dif_pos hq at this ⊢, rw if_pos h, exact this end else or.cases_on (not_and_distrib.1 h) begin unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h], exact lt_of_not_ge, end begin assume hp, unfold mod_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, not_not.1 hp], exact lt_of_le_of_ne bot_le (ne.symm (mt degree_eq_bot.1 hq0)), end using_well_founded {dec_tac := tactic.assumption} lemma mod_by_monic_eq_sub_mul_div : ∀ (p : polynomial α) {q : polynomial α} (hq : monic q), p %ₘ q = p - q * (p /ₘ q) | p := λ q hq, if h : degree q ≤ degree p ∧ p ≠ 0 then have wf : _ := div_wf_lemma h hq, have ih : _ := mod_by_monic_eq_sub_mul_div (p - C (leading_coeff p) * X ^ (nat_degree p - nat_degree q) * q) hq, begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_pos h], rw [mod_by_monic, dif_pos hq] at ih, refine ih.trans _, simp [mul_add, add_mul, mul_comm, hq, h, div_by_monic] end else begin unfold mod_by_monic div_by_monic div_mod_by_monic_aux, rw [dif_pos hq, if_neg h, dif_pos hq, if_neg h], simp end using_well_founded {dec_tac := tactic.assumption} lemma subsingleton_of_monic_zero (h : monic (0 : polynomial α)) : (∀ p q : polynomial α, p = q) ∧ (∀ a b : α, a = b) := by rw [monic.def, leading_coeff_zero] at h; exact ⟨λ p q, by rw [← mul_one p, ← mul_one q, ← C_1, ← h, C_0, mul_zero, mul_zero], λ a b, by rw [← mul_one a, ← mul_one b, ← h, mul_zero, mul_zero]⟩ lemma mod_by_monic_add_div (p : polynomial α) {q : polynomial α} (hq : monic q) : p %ₘ q + q * (p /ₘ q) = p := eq_sub_iff_add_eq.1 (mod_by_monic_eq_sub_mul_div p hq) @[simp] lemma zero_mod_by_monic (p : polynomial α) : 0 %ₘ p = 0 := begin unfold mod_by_monic div_mod_by_monic_aux, split_ifs; simp * at * end @[simp] lemma zero_div_by_monic (p : polynomial α) : 0 /ₘ p = 0 := begin unfold div_by_monic div_mod_by_monic_aux, split_ifs; simp * at * end @[simp] lemma mod_by_monic_zero (p : polynomial α) : p %ₘ 0 = p := if h : monic (0 : polynomial α) then (subsingleton_of_monic_zero h).1 _ _ else begin unfold mod_by_monic div_mod_by_monic_aux, split_ifs; simp * at * end @[simp] lemma div_by_monic_zero (p : polynomial α) : p /ₘ 0 = 0 := if h : monic (0 : polynomial α) then (subsingleton_of_monic_zero h).1 _ _ else begin unfold div_by_monic div_mod_by_monic_aux, split_ifs; simp * at * end lemma div_by_monic_eq_of_not_monic (p : polynomial α) (hq : ¬monic q) : p /ₘ q = 0 := dif_neg hq lemma mod_by_monic_eq_of_not_monic (p : polynomial α) (hq : ¬monic q) : p %ₘ q = p := dif_neg hq lemma mod_by_monic_eq_self_iff (hq : monic q) (hq0 : q ≠ 0) : p %ₘ q = p ↔ degree p < degree q := ⟨λ h, h ▸ degree_mod_by_monic_lt _ hq hq0, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold mod_by_monic div_mod_by_monic_aux; simp *⟩ lemma div_by_monic_eq_zero_iff (hq : monic q) (hq0 : q ≠ 0) : p /ₘ q = 0 ↔ degree p < degree q := ⟨λ h, by have := mod_by_monic_add_div p hq; rwa [h, mul_zero, add_zero, mod_by_monic_eq_self_iff hq hq0] at this, λ h, have ¬ degree q ≤ degree p := not_le_of_gt h, by unfold div_by_monic div_mod_by_monic_aux; simp *⟩ lemma degree_add_div_by_monic (hq : monic q) (h : degree q ≤ degree p) : degree q + degree (p /ₘ q) = degree p := if hq0 : q = 0 then have ∀ (p : polynomial α), p = 0, from λ p, (@subsingleton_of_monic_zero α _ _ (hq0 ▸ hq)).1 _ _, by rw [this (p /ₘ q), this p, this q]; refl else have hdiv0 : p /ₘ q ≠ 0 := by rwa [(≠), div_by_monic_eq_zero_iff hq hq0, not_lt], have hlc : leading_coeff q * leading_coeff (p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul, (≠), leading_coeff_eq_zero], have hmod : degree (p %ₘ q) < degree (q * (p /ₘ q)) := calc degree (p %ₘ q) < degree q : degree_mod_by_monic_lt _ hq hq0 ... ≤ _ : by rw [degree_mul_eq' hlc, degree_eq_nat_degree hq0, degree_eq_nat_degree hdiv0, ← with_bot.coe_add, with_bot.coe_le_coe]; exact nat.le_add_right _ _, calc degree q + degree (p /ₘ q) = degree (q * (p /ₘ q)) : eq.symm (degree_mul_eq' hlc) ... = degree (p %ₘ q + q * (p /ₘ q)) : (degree_add_eq_of_degree_lt hmod).symm ... = _ : congr_arg _ (mod_by_monic_add_div _ hq) lemma degree_div_by_monic_le (p q : polynomial α) : degree (p /ₘ q) ≤ degree p := if hp0 : p = 0 then by simp [hp0] else if hq : monic q then have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq, if h : degree q ≤ degree p then by rw [← degree_add_div_by_monic hq h, degree_eq_nat_degree hq0, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 (not_lt.2 h))]; exact with_bot.coe_le_coe.2 (nat.le_add_left _ _) else by unfold div_by_monic div_mod_by_monic_aux; simp [dif_pos hq, h] else (div_by_monic_eq_of_not_monic p hq).symm ▸ bot_le lemma degree_div_by_monic_lt (p : polynomial α) {q : polynomial α} (hq : monic q) (hp0 : p ≠ 0) (h0q : 0 < degree q) : degree (p /ₘ q) < degree p := have hq0 : q ≠ 0 := ne_zero_of_ne_zero_of_monic hp0 hq, if hpq : degree p < degree q then begin rw [(div_by_monic_eq_zero_iff hq hq0).2 hpq, degree_eq_nat_degree hp0], exact with_bot.bot_lt_some _ end else begin rw [← degree_add_div_by_monic hq (not_lt.1 hpq), degree_eq_nat_degree hq0, degree_eq_nat_degree (mt (div_by_monic_eq_zero_iff hq hq0).1 hpq)], exact with_bot.coe_lt_coe.2 (nat.lt_add_of_pos_left (with_bot.coe_lt_coe.1 $ (degree_eq_nat_degree hq0) ▸ h0q)) end lemma dvd_iff_mod_by_monic_eq_zero (hq : monic q) : p %ₘ q = 0 ↔ q ∣ p := ⟨λ h, by rw [← mod_by_monic_add_div p hq, h, zero_add]; exact dvd_mul_right _ _, λ h, if hq0 : q = 0 then by rw hq0 at hq; exact (subsingleton_of_monic_zero hq).1 _ _ else let ⟨r, hr⟩ := exists_eq_mul_right_of_dvd h in by_contradiction (λ hpq0, have hmod : p %ₘ q = q * (r - p /ₘ q) := by rw [mod_by_monic_eq_sub_mul_div _ hq, mul_sub, ← hr], have degree (q * (r - p /ₘ q)) < degree q := hmod ▸ degree_mod_by_monic_lt _ hq hq0, have hrpq0 : leading_coeff (r - p /ₘ q) ≠ 0 := λ h, hpq0 $ leading_coeff_eq_zero.1 (by rw [hmod, leading_coeff_eq_zero.1 h, mul_zero, leading_coeff_zero]), have hlc : leading_coeff q * leading_coeff (r - p /ₘ q) ≠ 0 := by rwa [monic.def.1 hq, one_mul], by rw [degree_mul_eq' hlc, degree_eq_nat_degree hq0, degree_eq_nat_degree (mt leading_coeff_eq_zero.2 hrpq0)] at this; exact not_lt_of_ge (nat.le_add_right _ _) (with_bot.some_lt_some.1 this))⟩ end comm_ring section nonzero_comm_ring variables [nonzero_comm_ring α] {p q : polynomial α} instance : nonzero_comm_ring (polynomial α) := { zero_ne_one := λ (h : (0 : polynomial α) = 1), @zero_ne_one α _ $ calc (0 : α) = eval 0 0 : eval_zero.symm ... = eval 0 1 : congr_arg _ h ... = 1 : eval_C, ..polynomial.comm_ring } @[simp] lemma degree_one : degree (1 : polynomial α) = (0 : with_bot ℕ) := degree_C (show (1 : α) ≠ 0, from zero_ne_one.symm) @[simp] lemma degree_X : degree (X : polynomial α) = 1 := begin unfold X degree single finsupp.support, rw if_neg (zero_ne_one).symm, refl end @[simp] lemma degree_X_sub_C (a : α) : degree (X - C a) = 1 := begin rw [sub_eq_add_neg, add_comm, ← @degree_X α], by_cases ha : a = 0, { simp [ha] }, exact degree_add_eq_of_degree_lt (by rw [degree_X, degree_neg, degree_C ha]; exact dec_trivial) end @[simp] lemma degree_X_pow : ∀ (n : ℕ), degree ((X : polynomial α) ^ n) = n | 0 := by simp; refl | (n+1) := have h : leading_coeff (X : polynomial α) * leading_coeff (X ^ n) ≠ 0, by rw [leading_coeff_X, leading_coeff_X_pow n, one_mul]; exact zero_ne_one.symm, by rw [pow_succ, degree_mul_eq' h, degree_X, degree_X_pow, add_comm]; refl lemma degree_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : α) : degree ((X : polynomial α) ^ n - C a) = n := have degree (-C a) < degree ((X : polynomial α) ^ n), from calc degree (-C a) ≤ 0 : by rw degree_neg; exact degree_C_le ... < degree ((X : polynomial α) ^ n) : by rwa [degree_X_pow]; exact with_bot.coe_lt_coe.2 hn, by rw [sub_eq_add_neg, add_comm, degree_add_eq_of_degree_lt this, degree_X_pow] lemma X_pow_sub_C_ne_zero {n : ℕ} (hn : 0 < n) (a : α) : (X : polynomial α) ^ n - C a ≠ 0 := mt degree_eq_bot.2 (show degree ((X : polynomial α) ^ n - C a) ≠ ⊥, by rw degree_X_pow_sub_C hn; exact dec_trivial) @[simp] lemma not_monic_zero : ¬monic (0 : polynomial α) := by simp [monic, zero_ne_one] lemma ne_zero_of_monic (h : monic p) : p ≠ 0 := λ h₁, @not_monic_zero α _ _ (h₁ ▸ h) lemma monic_X_sub_C (a : α) : monic (X - C a) := have degree (-C a) < degree (X : polynomial α) := if ha : a = 0 then by simp [ha]; exact dec_trivial else by simp [degree_C ha]; exact dec_trivial, by unfold monic; rw [sub_eq_add_neg, add_comm, leading_coeff_add_of_degree_lt this, leading_coeff_X] lemma root_X_sub_C : is_root (X - C a) b ↔ a = b := by rw [is_root.def, eval_sub, eval_X, eval_C, sub_eq_zero_iff_eq, eq_comm] @[simp] lemma mod_by_monic_X_sub_C_eq_C_eval (p : polynomial α) (a : α) : p %ₘ (X - C a) = C (p.eval a) := have h : (p %ₘ (X - C a)).eval a = p.eval a := by rw [mod_by_monic_eq_sub_mul_div _ (monic_X_sub_C a), eval_sub, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul, sub_zero], have degree (p %ₘ (X - C a)) < 1 := degree_X_sub_C a ▸ degree_mod_by_monic_lt p (monic_X_sub_C a) ((degree_X_sub_C a).symm ▸ ne_zero_of_monic (monic_X_sub_C _)), have degree (p %ₘ (X - C a)) ≤ 0 := begin cases (degree (p %ₘ (X - C a))), { exact bot_le }, { exact with_bot.some_le_some.2 (nat.le_of_lt_succ (with_bot.some_lt_some.1 this)) } end, begin rw [eq_C_of_degree_le_zero this, eval_C] at h, rw [eq_C_of_degree_le_zero this, h] end lemma mul_div_by_monic_eq_iff_is_root : (X - C a) * (p /ₘ (X - C a)) = p ↔ is_root p a := ⟨λ h, by rw [← h, is_root.def, eval_mul, eval_sub, eval_X, eval_C, sub_self, zero_mul], λ h : p.eval a = 0, by conv {to_rhs, rw ← mod_by_monic_add_div p (monic_X_sub_C a)}; rw [mod_by_monic_X_sub_C_eq_C_eval, h, C_0, zero_add]⟩ lemma dvd_iff_is_root : (X - C a) ∣ p ↔ is_root p a := ⟨λ h, by rwa [← dvd_iff_mod_by_monic_eq_zero (monic_X_sub_C _), mod_by_monic_X_sub_C_eq_C_eval, ← C_0, C_inj] at h, λ h, ⟨(p /ₘ (X - C a)), by rw mul_div_by_monic_eq_iff_is_root.2 h⟩⟩ end nonzero_comm_ring section integral_domain variables [integral_domain α] {p q : polynomial α} @[simp] lemma degree_mul_eq : degree (p * q) = degree p + degree q := if hp0 : p = 0 then by simp [hp0] else if hq0 : q = 0 then by simp [hq0] else degree_mul_eq' $ mul_ne_zero (mt leading_coeff_eq_zero.1 hp0) (mt leading_coeff_eq_zero.1 hq0) @[simp] lemma degree_pow_eq (p : polynomial α) (n : ℕ) : degree (p ^ n) = add_monoid.smul n (degree p) := by induction n; simp [*, pow_succ, succ_smul] @[simp] lemma leading_coeff_mul (p q : polynomial α) : leading_coeff (p * q) = leading_coeff p * leading_coeff q := begin by_cases hp : p = 0, { simp [hp] }, { by_cases hq : q = 0, { simp [hq] }, { rw [leading_coeff_mul'], exact mul_ne_zero (mt leading_coeff_eq_zero.1 hp) (mt leading_coeff_eq_zero.1 hq) } } end @[simp] lemma leading_coeff_pow (p : polynomial α) (n : ℕ) : leading_coeff (p ^ n) = leading_coeff p ^ n := by induction n; simp [*, pow_succ] instance : integral_domain (polynomial α) := { eq_zero_or_eq_zero_of_mul_eq_zero := λ a b h, begin have : leading_coeff 0 = leading_coeff a * leading_coeff b := h ▸ leading_coeff_mul a b, rw [leading_coeff_zero, eq_comm] at this, rw [← leading_coeff_eq_zero, ← leading_coeff_eq_zero], exact eq_zero_or_eq_zero_of_mul_eq_zero this end, ..polynomial.nonzero_comm_ring } lemma root_or_root_of_root_mul (h : is_root (p * q) a) : is_root p a ∨ is_root q a := by rw [is_root, eval_mul] at h; exact eq_zero_or_eq_zero_of_mul_eq_zero h lemma degree_pos_of_root (hp : p ≠ 0) (h : is_root p a) : 0 < degree p := lt_of_not_ge $ λ hlt, begin have := eq_C_of_degree_le_zero hlt, rw [is_root, this, eval_C] at h, exact hp (ext (λ n, show p n = 0, from nat.cases_on n h (λ _, eq_zero_of_degree_lt (lt_of_le_of_lt hlt (with_bot.coe_lt_coe.2 (nat.succ_pos _)))))), end lemma degree_le_mul_left (p : polynomial α) (hq : q ≠ 0) : degree p ≤ degree (p * q) := if hp : p = 0 then by simp [hp] else by rw [degree_mul_eq, degree_eq_nat_degree hp, degree_eq_nat_degree hq]; exact with_bot.coe_le_coe.2 (nat.le_add_right _ _) lemma exists_finset_roots : ∀ {p : polynomial α} (hp : p ≠ 0), ∃ s : finset α, (s.card : with_bot ℕ) ≤ degree p ∧ ∀ x, x ∈ s ↔ is_root p x | p := λ hp, by haveI := classical.prop_decidable (∃ x, is_root p x); exact if h : ∃ x, is_root p x then let ⟨x, hx⟩ := h in have hpd : 0 < degree p := degree_pos_of_root hp hx, have hd0 : p /ₘ (X - C x) ≠ 0 := λ h, by have := mul_div_by_monic_eq_iff_is_root.2 hx; simp * at *, have wf : degree (p /ₘ _) < degree p := degree_div_by_monic_lt _ (monic_X_sub_C x) hp ((degree_X_sub_C x).symm ▸ dec_trivial), let ⟨t, htd, htr⟩ := @exists_finset_roots (p /ₘ (X - C x)) hd0 in have hdeg : degree (X - C x) ≤ degree p := begin rw [degree_X_sub_C, degree_eq_nat_degree hp], rw degree_eq_nat_degree hp at hpd, exact with_bot.coe_le_coe.2 (with_bot.coe_lt_coe.1 hpd) end, have hdiv0 : p /ₘ (X - C x) ≠ 0 := mt (div_by_monic_eq_zero_iff (monic_X_sub_C x) (ne_zero_of_monic (monic_X_sub_C x))).1 $ not_lt.2 hdeg, ⟨insert x t, calc (card (insert x t) : with_bot ℕ) ≤ card t + 1 : with_bot.coe_le_coe.2 $ finset.card_insert_le _ _ ... ≤ degree p : by rw [← degree_add_div_by_monic (monic_X_sub_C x) hdeg, degree_X_sub_C, add_comm]; exact add_le_add' (le_refl (1 : with_bot ℕ)) htd, begin assume y, rw [mem_insert, htr, eq_comm, ← root_X_sub_C], conv {to_rhs, rw ← mul_div_by_monic_eq_iff_is_root.2 hx}, exact ⟨λ h, or.cases_on h (root_mul_right_of_is_root _) (root_mul_left_of_is_root _), root_or_root_of_root_mul⟩ end⟩ else ⟨∅, (degree_eq_nat_degree hp).symm ▸ with_bot.coe_le_coe.2 (nat.zero_le _), by clear exists_finset_roots; finish⟩ using_well_founded {dec_tac := tactic.assumption} /-- `roots p` noncomputably gives a finset containing all the roots of `p` -/ noncomputable def roots (p : polynomial α) : finset α := if h : p = 0 then ∅ else classical.some (exists_finset_roots h) lemma card_roots (hp0 : p ≠ 0) : ((roots p).card : with_bot ℕ) ≤ degree p := begin unfold roots, rw dif_neg hp0, exact (classical.some_spec (exists_finset_roots hp0)).1 end @[simp] lemma mem_roots (hp : p ≠ 0) : a ∈ p.roots ↔ is_root p a := by unfold roots; rw dif_neg hp; exact (classical.some_spec (exists_finset_roots hp)).2 _ lemma card_roots_X_pow_sub_C {n : ℕ} (hn : 0 < n) (a : α) : (roots ((X : polynomial α) ^ n - C a)).card ≤ n := with_bot.coe_le_coe.1 $ calc ((roots ((X : polynomial α) ^ n - C a)).card : with_bot ℕ) ≤ degree ((X : polynomial α) ^ n - C a) : card_roots (X_pow_sub_C_ne_zero hn a) ... = n : degree_X_pow_sub_C hn a /-- `nth_roots n a` noncomputably returns the solutions to `x ^ n = a`-/ noncomputable def nth_roots {α : Type*} [integral_domain α] (n : ℕ) (a : α) : finset α := by letI := classical.prop_decidable; exact roots ((X : polynomial α) ^ n - C a) @[simp] lemma mem_nth_roots {α : Type*} [integral_domain α] {n : ℕ} (hn : 0 < n) {a x : α} : x ∈ nth_roots n a ↔ x ^ n = a := by letI := classical.prop_decidable; rw [nth_roots, mem_roots (X_pow_sub_C_ne_zero hn a), is_root.def, eval_sub, eval_C, eval_pow, eval_X, sub_eq_zero_iff_eq] lemma card_nth_roots {α : Type*} [integral_domain α] (n : ℕ) (a : α) : (nth_roots n a).card ≤ n := by letI := classical.prop_decidable; exact if hn : n = 0 then if h : (X : polynomial α) ^ n - C a = 0 then by simp [nat.zero_le, nth_roots, roots, h] else with_bot.coe_le_coe.1 (le_trans (card_roots h) (by rw [hn, pow_zero, ← @C_1 α _, ← is_ring_hom.map_sub (@C α _ _)]; exact degree_C_le)) else by rw [← with_bot.coe_le_coe, ← degree_X_pow_sub_C (nat.pos_of_ne_zero hn) a]; exact card_roots (X_pow_sub_C_ne_zero (nat.pos_of_ne_zero hn) a) end integral_domain section field variables [field α] {p q : polynomial α} instance : vector_space α (polynomial α) := { ..finsupp.to_module α } lemma monic_mul_leading_coeff_inv (h : p ≠ 0) : monic (p * C (leading_coeff p)⁻¹) := by rw [monic, leading_coeff_mul, leading_coeff_C, mul_inv_cancel (show leading_coeff p ≠ 0, from mt leading_coeff_eq_zero.1 h)] lemma degree_mul_leading_coeff_inv (h : p ≠ 0) : degree (p * C (leading_coeff p)⁻¹) = degree p := have h₁ : (leading_coeff p)⁻¹ ≠ 0 := inv_ne_zero (mt leading_coeff_eq_zero.1 h), by rw [degree_mul_eq, degree_C h₁, add_zero] def div (p q : polynomial α) := C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) def mod (p q : polynomial α) := p %ₘ (q * C (leading_coeff q)⁻¹) private lemma quotient_mul_add_remainder_eq_aux (p q : polynomial α) : q * div p q + mod p q = p := if h : q = 0 then by simp [h, mod_by_monic, div, mod] else begin conv {to_rhs, rw ← mod_by_monic_add_div p (monic_mul_leading_coeff_inv h)}, rw [div, mod, add_comm, mul_assoc] end private lemma remainder_lt_aux (p : polynomial α) (hq : q ≠ 0) : degree (mod p q) < degree q := degree_mul_leading_coeff_inv hq ▸ degree_mod_by_monic_lt p (monic_mul_leading_coeff_inv hq) (mul_ne_zero hq (mt leading_coeff_eq_zero.2 (by rw leading_coeff_C; exact inv_ne_zero (mt leading_coeff_eq_zero.1 hq)))) instance : has_div (polynomial α) := ⟨div⟩ instance : has_mod (polynomial α) := ⟨mod⟩ lemma div_def : p / q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)) := rfl lemma mod_def : p % q = p %ₘ (q * C (leading_coeff q)⁻¹) := rfl lemma mod_by_monic_eq_mod (p : polynomial α) (hq : monic q) : p %ₘ q = p % q := show p %ₘ q = p %ₘ (q * C (leading_coeff q)⁻¹), by simp [monic.def.1 hq] lemma div_by_monic_eq_div (p : polynomial α) (hq : monic q) : p /ₘ q = p / q := show p /ₘ q = C (leading_coeff q)⁻¹ * (p /ₘ (q * C (leading_coeff q)⁻¹)), by simp [monic.def.1 hq] lemma mod_X_sub_C_eq_C_eval (p : polynomial α) (a : α) : p % (X - C a) = C (p.eval a) := mod_by_monic_eq_mod p (monic_X_sub_C a) ▸ mod_by_monic_X_sub_C_eq_C_eval _ _ lemma mul_div_eq_iff_is_root : (X - C a) * (p / (X - C a)) = p ↔ is_root p a := div_by_monic_eq_div p (monic_X_sub_C a) ▸ mul_div_by_monic_eq_iff_is_root instance : euclidean_domain (polynomial α) := { quotient := (/), remainder := (%), r := _, r_well_founded := degree_lt_wf, quotient_mul_add_remainder_eq := quotient_mul_add_remainder_eq_aux, remainder_lt := λ p q hq, remainder_lt_aux _ hq, mul_left_not_lt := λ p q hq, not_lt_of_ge (degree_le_mul_left _ hq) } lemma mod_eq_self_iff (hq0 : q ≠ 0) : p % q = p ↔ degree p < degree q := ⟨λ h, h ▸ euclidean_domain.mod_lt _ hq0, λ h, have ¬degree (q * C (leading_coeff q)⁻¹) ≤ degree p := not_le_of_gt $ by rwa degree_mul_leading_coeff_inv hq0, begin rw [mod_def, mod_by_monic, dif_pos (monic_mul_leading_coeff_inv hq0)], unfold div_mod_by_monic_aux, simp [this] end⟩ lemma div_eq_zero_iff (hq0 : q ≠ 0) : p / q = 0 ↔ degree p < degree q := ⟨λ h, by have := euclidean_domain.div_add_mod p q; rwa [h, mul_zero, zero_add, mod_eq_self_iff hq0] at this, λ h, have hlt : degree p < degree (q * C (leading_coeff q)⁻¹), by rwa degree_mul_leading_coeff_inv hq0, have hm : monic (q * C (leading_coeff q)⁻¹) := monic_mul_leading_coeff_inv hq0, by rw [div_def, (div_by_monic_eq_zero_iff hm (ne_zero_of_monic hm)).2 hlt, mul_zero]⟩ lemma degree_add_div (hq0 : q ≠ 0) (hpq : degree q ≤ degree p) : degree q + degree (p / q) = degree p := have degree (p % q) < degree (q * (p / q)) := calc degree (p % q) < degree q : euclidean_domain.mod_lt _ hq0 ... ≤ _ : degree_le_mul_left _ (mt (div_eq_zero_iff hq0).1 (not_lt_of_ge hpq)), by conv {to_rhs, rw [← euclidean_domain.div_add_mod p q, add_comm, degree_add_eq_of_degree_lt this, degree_mul_eq]} end field section derivative variables [comm_semiring α] {β : Type*} /-- `derivative p` formal derivative of the polynomial `p` -/ def derivative (p : polynomial α) : polynomial α := p.sum (λn a, C (a * n) * X^(n - 1)) lemma derivative_apply (p : polynomial α) (n : ℕ) : (derivative p) n = p (n + 1) * (n + 1) := begin rw [derivative], simp [finsupp.sum], rw [finset.sum_eq_single (n + 1)]; simp {contextual := tt}, assume b, cases b; simp [nat.succ_eq_add_one] {contextual := tt}, end @[simp] lemma derivative_zero : derivative (0 : polynomial α) = 0 := finsupp.sum_zero_index lemma derivative_monomial (a : α) (n : ℕ) : derivative (C a * X ^ n) = C (a * n) * X^(n - 1) := by rw [← single_eq_C_mul_X, ← single_eq_C_mul_X, derivative, sum_single_index, single_eq_C_mul_X]; simp; refl @[simp] lemma derivative_C {a : α} : derivative (C a) = 0 := suffices derivative (C a * X^0) = C (a * 0:α) * X ^ 0, by simpa, derivative_monomial a 0 @[simp] lemma derivative_X : derivative (X : polynomial α) = 1 := suffices derivative (C (1:α) * X^1) = C (1 * (1:ℕ)) * X ^ (1 - 1), by simpa, derivative_monomial 1 1 @[simp] lemma derivative_one : derivative (1 : polynomial α) = 0 := derivative_C @[simp] lemma derivative_add {f g : polynomial α} : derivative (f + g) = derivative f + derivative g := by refine finsupp.sum_add_index _ _; simp [add_mul] @[simp] lemma derivative_sum {s : finset β} {f : β → polynomial α} : derivative (s.sum f) = s.sum (λb, derivative (f b)) := begin apply (finset.sum_hom derivative _ _).symm, exact derivative_zero, exact assume x y, derivative_add end @[simp] lemma derivative_mul {f g : polynomial α} : derivative (f * g) = derivative f * g + f * derivative g := calc derivative (f * g) = f.sum (λn a, g.sum (λm b, C ((a * b) * (n + m : ℕ)) * X^((n + m) - 1))) : begin transitivity, exact derivative_sum, transitivity, { apply finset.sum_congr rfl, assume x hx, exact derivative_sum }, apply finset.sum_congr rfl, assume n hn, apply finset.sum_congr rfl, assume m hm, dsimp, transitivity, { apply congr_arg, exact single_eq_C_mul_X }, exact derivative_monomial _ _ end ... = f.sum (λn a, g.sum (λm b, (C (a * n) * X^(n - 1)) * (C b * X^m) + (C (b * m) * X^(m - 1)) * (C a * X^n))) : sum_congr rfl $ assume n hn, sum_congr rfl $ assume m hm, by cases n; cases m; simp [mul_add, add_mul, mul_assoc, mul_comm, mul_left_comm, add_assoc, add_comm, add_left_comm, pow_add, pow_succ] ... = derivative f * g + f * derivative g : begin simp [finsupp.sum_add], conv { to_rhs, congr, { rw [← sum_C_mul_X_eq f, derivative] }, { rw [← sum_C_mul_X_eq g, derivative] }, }, simp [finsupp.mul_sum, finsupp.sum_mul], simp [finsupp.sum, mul_assoc, mul_comm, mul_left_comm] end end derivative section domain variables [integral_domain α] lemma mem_support_derivative [char_zero α] (p : polynomial α) (n : ℕ) : n ∈ (derivative p).support ↔ n + 1 ∈ p.support := suffices (¬(p (n + 1) = 0 ∨ ((1 + n:ℕ) : α) = 0)) ↔ p (n + 1) ≠ 0, by simpa [derivative_apply], by rw [nat.cast_eq_zero]; simp @[simp] lemma degree_derivative_eq [char_zero α] (p : polynomial α) (hp : 0 < nat_degree p) : degree (derivative p) = (nat_degree p - 1 : ℕ) := le_antisymm (le_trans (degree_sum_le _ _) $ sup_le $ assume n hn, have n ≤ nat_degree p, begin rw [← with_bot.coe_le_coe, ← degree_eq_nat_degree], { refine le_degree_of_ne_zero _, simpa using hn }, { assume h, simpa [h] using hn } end, le_trans (degree_monomial_le _ _) $ with_bot.coe_le_coe.2 $ nat.sub_le_sub_right this _) begin refine le_sup _, rw [mem_support_derivative, nat.sub_add_cancel, mem_support_iff], { show ¬ leading_coeff p = 0, rw [leading_coeff_eq_zero], assume h, rw [h, nat_degree_zero] at hp, exact lt_irrefl 0 (lt_of_le_of_lt (zero_le _) hp), }, exact hp end end domain end polynomial
6c5c8334679c181484d84e9f386ca52b4f510755
6432ea7a083ff6ba21ea17af9ee47b9c371760f7
/tests/lean/structDefValueOverride.lean
a03501658378c422985d237b40c2f4c0e173bdd0
[ "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
84
lean
structure A where x : Nat structure B extends A where x := 1 x := 2 -- Error
9c930e107cf54ab7f73831ae82ad6c5062734a6c
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/ring_theory/adjoin.lean
00f3fad033a6d7fa41e2a7c815e20d0f963687d4
[]
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
7,816
lean
/- Copyright (c) 2019 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.ring_theory.polynomial.basic import Mathlib.algebra.algebra.subalgebra import Mathlib.PostPort universes u v w namespace Mathlib /-! # Adjoining elements to form subalgebras This file develops the basic theory of subalgebras of an R-algebra generated by a set of elements. A basic interface for `adjoin` is set up, and various results about finitely-generated subalgebras and submodules are proved. ## Definitions * `fg (S : subalgebra R A)` : A predicate saying that the subalgebra is finitely-generated as an A-algebra ## Tags adjoin, algebra, finitely-generated algebra -/ namespace algebra theorem subset_adjoin {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] {s : set A} : s ⊆ ↑(adjoin R s) := set.subset.trans (set.subset_union_right (set.range ⇑(algebra_map R A)) s) subsemiring.subset_closure theorem adjoin_le {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] {s : set A} {S : subalgebra R A} (H : s ⊆ ↑S) : adjoin R s ≤ S := iff.mpr subsemiring.closure_le (set.union_subset (subalgebra.range_le S) H) theorem adjoin_le_iff {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] {s : set A} {S : subalgebra R A} : adjoin R s ≤ S ↔ s ⊆ ↑S := { mp := set.subset.trans subset_adjoin, mpr := adjoin_le } theorem adjoin_mono {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] {s : set A} {t : set A} (H : s ⊆ t) : adjoin R s ≤ adjoin R t := iff.mpr subsemiring.closure_le (set.subset.trans (set.union_subset_union_right (set.range ⇑(algebra_map R A)) H) subsemiring.subset_closure) @[simp] theorem adjoin_empty (R : Type u) (A : Type v) [comm_semiring R] [semiring A] [algebra R A] : adjoin R ∅ = ⊥ := iff.mpr eq_bot_iff (adjoin_le (set.empty_subset ↑⊥)) theorem adjoin_eq_span (R : Type u) {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (s : set A) : ↑(adjoin R s) = submodule.span R (monoid.closure s) := sorry theorem adjoin_image (R : Type u) {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [semiring B] [algebra R A] [algebra R B] (f : alg_hom R A B) (s : set A) : adjoin R (⇑f '' s) = subalgebra.map (adjoin R s) f := le_antisymm (adjoin_le (set.image_subset (⇑f) subset_adjoin)) (iff.mpr subalgebra.map_le (adjoin_le (iff.mp set.image_subset_iff subset_adjoin))) @[simp] theorem adjoin_insert_adjoin (R : Type u) {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (s : set A) (x : A) : adjoin R (insert x ↑↑(adjoin R s)) = adjoin R (insert x s) := sorry theorem adjoin_union (R : Type u) {A : Type v} [comm_semiring R] [comm_semiring A] [algebra R A] (s : set A) (t : set A) : adjoin R (s ∪ t) = subalgebra.under (adjoin R s) (adjoin (↥(adjoin R s)) t) := sorry theorem adjoin_eq_range (R : Type u) {A : Type v} [comm_semiring R] [comm_semiring A] [algebra R A] (s : set A) : adjoin R s = alg_hom.range (mv_polynomial.aeval coe) := sorry theorem adjoin_singleton_eq_range (R : Type u) {A : Type v} [comm_semiring R] [comm_semiring A] [algebra R A] (x : A) : adjoin R (singleton x) = alg_hom.range (polynomial.aeval x) := sorry theorem adjoin_singleton_one (R : Type u) {A : Type v} [comm_semiring R] [comm_semiring A] [algebra R A] : adjoin R (singleton 1) = ⊥ := iff.mpr eq_bot_iff (adjoin_le (iff.mpr set.singleton_subset_iff (subalgebra.one_mem ⊥))) theorem adjoin_union_coe_submodule (R : Type u) {A : Type v} [comm_semiring R] [comm_semiring A] [algebra R A] (s : set A) (t : set A) : ↑(adjoin R (s ∪ t)) = ↑(adjoin R s) * ↑(adjoin R t) := sorry theorem adjoin_int {R : Type u} [comm_ring R] (s : set R) : adjoin ℤ s = subalgebra_of_is_subring (ring.closure s) := le_antisymm (adjoin_le ring.subset_closure) (ring.closure_subset subset_adjoin) theorem mem_adjoin_iff {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] {s : set A} {x : A} : x ∈ adjoin R s ↔ x ∈ ring.closure (set.range ⇑(algebra_map R A) ∪ s) := sorry theorem adjoin_eq_ring_closure {R : Type u} {A : Type v} [comm_ring R] [ring A] [algebra R A] (s : set A) : ↑(adjoin R s) = ring.closure (set.range ⇑(algebra_map R A) ∪ s) := set.ext fun (x : A) => mem_adjoin_iff theorem fg_trans {R : Type u} {A : Type v} [comm_ring R] [comm_ring A] [algebra R A] {s : set A} {t : set A} (h1 : submodule.fg ↑(adjoin R s)) (h2 : submodule.fg ↑(adjoin (↥(adjoin R s)) t)) : submodule.fg ↑(adjoin R (s ∪ t)) := sorry end algebra namespace subalgebra /-- A subalgebra `S` is finitely generated if there exists `t : finset A` such that `algebra.adjoin R t = S`. -/ def fg {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (S : subalgebra R A) := ∃ (t : finset A), algebra.adjoin R ↑t = S theorem fg_adjoin_finset {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (s : finset A) : fg (algebra.adjoin R ↑s) := Exists.intro s rfl theorem fg_def {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] {S : subalgebra R A} : fg S ↔ ∃ (t : set A), set.finite t ∧ algebra.adjoin R t = S := sorry theorem fg_bot {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] : fg ⊥ := Exists.intro ∅ (algebra.adjoin_empty R A) theorem fg_of_fg_to_submodule {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] {S : subalgebra R A} : submodule.fg ↑S → fg S := sorry theorem fg_of_noetherian {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] [is_noetherian R A] (S : subalgebra R A) : fg S := fg_of_fg_to_submodule (is_noetherian.noetherian ↑S) theorem fg_of_submodule_fg {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (h : submodule.fg ⊤) : fg ⊤ := sorry theorem fg_map {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B] (S : subalgebra R A) (f : alg_hom R A B) (hs : fg S) : fg (map S f) := sorry theorem fg_of_fg_map {R : Type u} {A : Type v} {B : Type w} [comm_semiring R] [semiring A] [algebra R A] [semiring B] [algebra R B] (S : subalgebra R A) (f : alg_hom R A B) (hf : function.injective ⇑f) (hs : fg (map S f)) : fg S := sorry theorem fg_top {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] (S : subalgebra R A) : fg ⊤ ↔ fg S := sorry theorem induction_on_adjoin {R : Type u} {A : Type v} [comm_semiring R] [semiring A] [algebra R A] [is_noetherian R A] (P : subalgebra R A → Prop) (base : P ⊥) (ih : ∀ (S : subalgebra R A) (x : A), P S → P (algebra.adjoin R (insert x ↑S))) (S : subalgebra R A) : P S := sorry end subalgebra /-- The image of a Noetherian R-algebra under an R-algebra map is a Noetherian ring. -/ protected instance alg_hom.is_noetherian_ring_range {R : Type u} {A : Type v} {B : Type w} [comm_ring R] [comm_ring A] [comm_ring B] [algebra R A] [algebra R B] (f : alg_hom R A B) [is_noetherian_ring A] : is_noetherian_ring ↥(alg_hom.range f) := Mathlib.is_noetherian_ring_range (alg_hom.to_ring_hom f) theorem is_noetherian_ring_of_fg {R : Type u} {A : Type v} [comm_ring R] [comm_ring A] [algebra R A] {S : subalgebra R A} (HS : subalgebra.fg S) [is_noetherian_ring R] : is_noetherian_ring ↥S := sorry theorem is_noetherian_ring_closure {R : Type u} [comm_ring R] (s : set R) (hs : set.finite s) : is_noetherian_ring ↥(ring.closure s) := (fun (this : is_noetherian_ring ↥(subalgebra_of_is_subring (ring.closure s))) => this) (algebra.adjoin_int s ▸ is_noetherian_ring_of_fg (iff.mpr subalgebra.fg_def (Exists.intro s { left := hs, right := rfl })))
298314554a6e0e46bb54297525fd59faabaec6a3
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/data/list/defs.lean
74c3dbcb49d371f7767978b086c8265d8a53015d
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
38,253
lean
/- Copyright (c) 2014 Parikshit Khanna. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Parikshit Khanna, Jeremy Avigad, Leonardo de Moura, Floris van Doorn, Mario Carneiro -/ import data.option.defs import logic.basic import tactic.cache /-! ## Definitions on lists This file contains various definitions on lists. It does not contain proofs about these definitions, those are contained in other files in `data/list` -/ namespace list open function nat native (rb_map mk_rb_map rb_map.of_list) universes u v w x variables {α β γ δ ε ζ : Type*} instance [decidable_eq α] : has_sdiff (list α) := ⟨ list.diff ⟩ /-- Split a list at an index. split_at 2 [a, b, c] = ([a, b], [c]) -/ def split_at : ℕ → list α → list α × list α | 0 a := ([], a) | (succ n) [] := ([], []) | (succ n) (x :: xs) := let (l, r) := split_at n xs in (x :: l, r) /-- An auxiliary function for `split_on_p`. -/ def split_on_p_aux {α : Type u} (P : α → Prop) [decidable_pred P] : list α → (list α → list α) → list (list α) | [] f := [f []] | (h :: t) f := if P h then f [] :: split_on_p_aux t id else split_on_p_aux t (λ l, f (h :: l)) /-- Split a list at every element satisfying a predicate. -/ def split_on_p {α : Type u} (P : α → Prop) [decidable_pred P] (l : list α) : list (list α) := split_on_p_aux P l id /-- Split a list at every occurrence of an element. [1,1,2,3,2,4,4].split_on 2 = [[1,1],[3],[4,4]] -/ def split_on {α : Type u} [decidable_eq α] (a : α) (as : list α) : list (list α) := as.split_on_p (=a) /-- Concatenate an element at the end of a list. concat [a, b] c = [a, b, c] -/ @[simp] def concat : list α → α → list α | [] a := [a] | (b::l) a := b :: concat l a /-- `head' xs` returns the first element of `xs` if `xs` is non-empty; it returns `none` otherwise -/ @[simp] def head' : list α → option α | [] := none | (a :: l) := some a /-- Convert a list into an array (whose length is the length of `l`). -/ def to_array (l : list α) : array l.length α := {data := λ v, l.nth_le v.1 v.2} /-- "inhabited" `nth` function: returns `default` instead of `none` in the case that the index is out of bounds. -/ @[simp] def inth [h : inhabited α] (l : list α) (n : nat) : α := (nth l n).iget /-- Apply a function to the nth tail of `l`. Returns the input without using `f` if the index is larger than the length of the list. modify_nth_tail f 2 [a, b, c] = [a, b] ++ f [c] -/ @[simp] def modify_nth_tail (f : list α → list α) : ℕ → list α → list α | 0 l := f l | (n+1) [] := [] | (n+1) (a::l) := a :: modify_nth_tail n l /-- Apply `f` to the head of the list, if it exists. -/ @[simp] def modify_head (f : α → α) : list α → list α | [] := [] | (a::l) := f a :: l /-- Apply `f` to the nth element of the list, if it exists. -/ def modify_nth (f : α → α) : ℕ → list α → list α := modify_nth_tail (modify_head f) /-- Apply `f` to the last element of `l`, if it exists. -/ @[simp] def modify_last (f : α → α) : list α → list α | [] := [] | [x] := [f x] | (x :: xs) := x :: modify_last xs /-- `insert_nth n a l` inserts `a` into the list `l` after the first `n` elements of `l` `insert_nth 2 1 [1, 2, 3, 4] = [1, 2, 1, 3, 4]`-/ def insert_nth (n : ℕ) (a : α) : list α → list α := modify_nth_tail (list.cons a) n section take' variable [inhabited α] /-- Take `n` elements from a list `l`. If `l` has less than `n` elements, append `n - length l` elements `default α`. -/ def take' : ∀ n, list α → list α | 0 l := [] | (n+1) l := l.head :: take' n l.tail end take' /-- Get the longest initial segment of the list whose members all satisfy `p`. take_while (λ x, x < 3) [0, 2, 5, 1] = [0, 2] -/ def take_while (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then a :: take_while l else [] /-- Fold a function `f` over the list from the left, returning the list of partial results. scanl (+) 0 [1, 2, 3] = [0, 1, 3, 6] -/ def scanl (f : α → β → α) : α → list β → list α | a [] := [a] | a (b::l) := a :: scanl (f a b) l /-- Auxiliary definition used to define `scanr`. If `scanr_aux f b l = (b', l')` then `scanr f b l = b' :: l'` -/ def scanr_aux (f : α → β → β) (b : β) : list α → β × list β | [] := (b, []) | (a::l) := let (b', l') := scanr_aux l in (f a b', b' :: l') /-- Fold a function `f` over the list from the right, returning the list of partial results. scanr (+) 0 [1, 2, 3] = [6, 5, 3, 0] -/ def scanr (f : α → β → β) (b : β) (l : list α) : list β := let (b', l') := scanr_aux f b l in b' :: l' /-- Product of a list. prod [a, b, c] = ((1 * a) * b) * c -/ def prod [has_mul α] [has_one α] : list α → α := foldl (*) 1 /-- Sum of a list. sum [a, b, c] = ((0 + a) + b) + c -/ -- Later this will be tagged with `to_additive`, but this can't be done yet because of import -- dependencies. def sum [has_add α] [has_zero α] : list α → α := foldl (+) 0 /-- The alternating sum of a list. -/ def alternating_sum {G : Type*} [has_zero G] [has_add G] [has_neg G] : list G → G | [] := 0 | (g :: []) := g | (g :: h :: t) := g + -h + alternating_sum t /-- The alternating product of a list. -/ def alternating_prod {G : Type*} [has_one G] [has_mul G] [has_inv G] : list G → G | [] := 1 | (g :: []) := g | (g :: h :: t) := g * h⁻¹ * alternating_prod t /-- Given a function `f : α → β ⊕ γ`, `partition_map f l` maps the list by `f` whilst partitioning the result it into a pair of lists, `list β × list γ`, partitioning the `sum.inl _` into the left list, and the `sum.inr _` into the right list. `partition_map (id : ℕ ⊕ ℕ → ℕ ⊕ ℕ) [inl 0, inr 1, inl 2] = ([0,2], [1])` -/ def partition_map (f : α → β ⊕ γ) : list α → list β × list γ | [] := ([],[]) | (x::xs) := match f x with | (sum.inr r) := prod.map id (cons r) $ partition_map xs | (sum.inl l) := prod.map (cons l) id $ partition_map xs end /-- `find p l` is the first element of `l` satisfying `p`, or `none` if no such element exists. -/ def find (p : α → Prop) [decidable_pred p] : list α → option α | [] := none | (a::l) := if p a then some a else find l /-- `mfind tac l` returns the first element of `l` on which `tac` succeeds, and fails otherwise. -/ def mfind {α} {m : Type u → Type v} [monad m] [alternative m] (tac : α → m punit) : list α → m α := list.mfirst $ λ a, tac a $> a /-- `mbfind' p l` returns the first element `a` of `l` for which `p a` returns true. `mbfind'` short-circuits, so `p` is not necessarily run on every `a` in `l`. This is a monadic version of `list.find`. -/ def mbfind' {m : Type u → Type v} [monad m] {α : Type u} (p : α → m (ulift bool)) : list α → m (option α) | [] := pure none | (x :: xs) := do ⟨px⟩ ← p x, if px then pure (some x) else mbfind' xs section variables {m : Type → Type v} [monad m] /-- A variant of `mbfind'` with more restrictive universe levels. -/ def mbfind {α} (p : α → m bool) (xs : list α) : m (option α) := xs.mbfind' (functor.map ulift.up ∘ p) /-- `many p as` returns true iff `p` returns true for any element of `l`. `many` short-circuits, so if `p` returns true for any element of `l`, later elements are not checked. This is a monadic version of `list.any`. -/ -- Implementing this via `mbfind` would give us less universe polymorphism. def many {α : Type u} (p : α → m bool) : list α → m bool | [] := pure false | (x :: xs) := do px ← p x, if px then pure tt else many xs /-- `mall p as` returns true iff `p` returns true for all elements of `l`. `mall` short-circuits, so if `p` returns false for any element of `l`, later elements are not checked. This is a monadic version of `list.all`. -/ def mall {α : Type u} (p : α → m bool) (as : list α) : m bool := bnot <$> many (λ a, bnot <$> p a) as /-- `mbor xs` runs the actions in `xs`, returning true if any of them returns true. `mbor` short-circuits, so if an action returns true, later actions are not run. This is a monadic version of `list.bor`. -/ def mbor : list (m bool) → m bool := many id /-- `mband xs` runs the actions in `xs`, returning true if all of them return true. `mband` short-circuits, so if an action returns false, later actions are not run. This is a monadic version of `list.band`. -/ def mband : list (m bool) → m bool := mall id end /-- Auxiliary definition for `foldl_with_index`. -/ def foldl_with_index_aux (f : ℕ → α → β → α) : ℕ → α → list β → α | _ a [] := a | i a (b :: l) := foldl_with_index_aux (i + 1) (f i a b) l /-- Fold a list from left to right as with `foldl`, but the combining function also receives each element's index. -/ def foldl_with_index (f : ℕ → α → β → α) (a : α) (l : list β) : α := foldl_with_index_aux f 0 a l /-- Auxiliary definition for `foldr_with_index`. -/ def foldr_with_index_aux (f : ℕ → α → β → β) : ℕ → β → list α → β | _ b [] := b | i b (a :: l) := f i a (foldr_with_index_aux (i + 1) b l) /-- Fold a list from right to left as with `foldr`, but the combining function also receives each element's index. -/ def foldr_with_index (f : ℕ → α → β → β) (b : β) (l : list α) : β := foldr_with_index_aux f 0 b l /-- `find_indexes p l` is the list of indexes of elements of `l` that satisfy `p`. -/ def find_indexes (p : α → Prop) [decidable_pred p] (l : list α) : list nat := foldr_with_index (λ i a is, if p a then i :: is else is) [] l /-- Returns the elements of `l` that satisfy `p` together with their indexes in `l`. The returned list is ordered by index. -/ def indexes_values (p : α → Prop) [decidable_pred p] (l : list α) : list (ℕ × α) := foldr_with_index (λ i a l, if p a then (i , a) :: l else l) [] l /-- `indexes_of a l` is the list of all indexes of `a` in `l`. For example: ``` indexes_of a [a, b, a, a] = [0, 2, 3] ``` -/ def indexes_of [decidable_eq α] (a : α) : list α → list nat := find_indexes (eq a) section mfold_with_index variables {m : Type v → Type w} [monad m] /-- Monadic variant of `foldl_with_index`. -/ def mfoldl_with_index {α β} (f : ℕ → β → α → m β) (b : β) (as : list α) : m β := as.foldl_with_index (λ i ma b, do a ← ma, f i a b) (pure b) /-- Monadic variant of `foldr_with_index`. -/ def mfoldr_with_index {α β} (f : ℕ → α → β → m β) (b : β) (as : list α) : m β := as.foldr_with_index (λ i a mb, do b ← mb, f i a b) (pure b) end mfold_with_index section mmap_with_index variables {m : Type v → Type w} [applicative m] /-- Auxiliary definition for `mmap_with_index`. -/ def mmap_with_index_aux {α β} (f : ℕ → α → m β) : ℕ → list α → m (list β) | _ [] := pure [] | i (a :: as) := list.cons <$> f i a <*> mmap_with_index_aux (i + 1) as /-- Applicative variant of `map_with_index`. -/ def mmap_with_index {α β} (f : ℕ → α → m β) (as : list α) : m (list β) := mmap_with_index_aux f 0 as /-- Auxiliary definition for `mmap_with_index'`. -/ def mmap_with_index'_aux {α} (f : ℕ → α → m punit) : ℕ → list α → m punit | _ [] := pure ⟨⟩ | i (a :: as) := f i a *> mmap_with_index'_aux (i + 1) as /-- A variant of `mmap_with_index` specialised to applicative actions which return `unit`. -/ def mmap_with_index' {α} (f : ℕ → α → m punit) (as : list α) : m punit := mmap_with_index'_aux f 0 as end mmap_with_index /-- `lookmap` is a combination of `lookup` and `filter_map`. `lookmap f l` will apply `f : α → option α` to each element of the list, replacing `a → b` at the first value `a` in the list such that `f a = some b`. -/ def lookmap (f : α → option α) : list α → list α | [] := [] | (a::l) := match f a with | some b := b :: l | none := a :: lookmap l end /-- `countp p l` is the number of elements of `l` that satisfy `p`. -/ def countp (p : α → Prop) [decidable_pred p] : list α → nat | [] := 0 | (x::xs) := if p x then succ (countp xs) else countp xs /-- `count a l` is the number of occurrences of `a` in `l`. -/ def count [decidable_eq α] (a : α) : list α → nat := countp (eq a) /-- `is_prefix l₁ l₂`, or `l₁ <+: l₂`, means that `l₁` is a prefix of `l₂`, that is, `l₂` has the form `l₁ ++ t` for some `t`. -/ def is_prefix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, l₁ ++ t = l₂ /-- `is_suffix l₁ l₂`, or `l₁ <:+ l₂`, means that `l₁` is a suffix of `l₂`, that is, `l₂` has the form `t ++ l₁` for some `t`. -/ def is_suffix (l₁ : list α) (l₂ : list α) : Prop := ∃ t, t ++ l₁ = l₂ /-- `is_infix l₁ l₂`, or `l₁ <:+: l₂`, means that `l₁` is a contiguous substring of `l₂`, that is, `l₂` has the form `s ++ l₁ ++ t` for some `s, t`. -/ def is_infix (l₁ : list α) (l₂ : list α) : Prop := ∃ s t, s ++ l₁ ++ t = l₂ infix ` <+: `:50 := is_prefix infix ` <:+ `:50 := is_suffix infix ` <:+: `:50 := is_infix /-- `inits l` is the list of initial segments of `l`. inits [1, 2, 3] = [[], [1], [1, 2], [1, 2, 3]] -/ @[simp] def inits : list α → list (list α) | [] := [[]] | (a::l) := [] :: map (λt, a::t) (inits l) /-- `tails l` is the list of terminal segments of `l`. tails [1, 2, 3] = [[1, 2, 3], [2, 3], [3], []] -/ @[simp] def tails : list α → list (list α) | [] := [[]] | (a::l) := (a::l) :: tails l def sublists'_aux : list α → (list α → list β) → list (list β) → list (list β) | [] f r := f [] :: r | (a::l) f r := sublists'_aux l f (sublists'_aux l (f ∘ cons a) r) /-- `sublists' l` is the list of all (non-contiguous) sublists of `l`. It differs from `sublists` only in the order of appearance of the sublists; `sublists'` uses the first element of the list as the MSB, `sublists` uses the first element of the list as the LSB. sublists' [1, 2, 3] = [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]] -/ def sublists' (l : list α) : list (list α) := sublists'_aux l id [] def sublists_aux : list α → (list α → list β → list β) → list β | [] f := [] | (a::l) f := f [a] (sublists_aux l (λys r, f ys (f (a :: ys) r))) /-- `sublists l` is the list of all (non-contiguous) sublists of `l`; cf. `sublists'` for a different ordering. sublists [1, 2, 3] = [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]] -/ def sublists (l : list α) : list (list α) := [] :: sublists_aux l cons def sublists_aux₁ : list α → (list α → list β) → list β | [] f := [] | (a::l) f := f [a] ++ sublists_aux₁ l (λys, f ys ++ f (a :: ys)) section forall₂ variables {r : α → β → Prop} {p : γ → δ → Prop} /-- `forall₂ R l₁ l₂` means that `l₁` and `l₂` have the same length, and whenever `a` is the nth element of `l₁`, and `b` is the nth element of `l₂`, then `R a b` is satisfied. -/ inductive forall₂ (R : α → β → Prop) : list α → list β → Prop | nil : forall₂ [] [] | cons {a b l₁ l₂} : R a b → forall₂ l₁ l₂ → forall₂ (a::l₁) (b::l₂) attribute [simp] forall₂.nil end forall₂ /-- Auxiliary definition used to define `transpose`. `transpose_aux l L` takes each element of `l` and appends it to the start of each element of `L`. `transpose_aux [a, b, c] [l₁, l₂, l₃] = [a::l₁, b::l₂, c::l₃]` -/ def transpose_aux : list α → list (list α) → list (list α) | [] ls := ls | (a::i) [] := [a] :: transpose_aux i [] | (a::i) (l::ls) := (a::l) :: transpose_aux i ls /-- transpose of a list of lists, treated as a matrix. transpose [[1, 2], [3, 4], [5, 6]] = [[1, 3, 5], [2, 4, 6]] -/ def transpose : list (list α) → list (list α) | [] := [] | (l::ls) := transpose_aux l (transpose ls) /-- List of all sections through a list of lists. A section of `[L₁, L₂, ..., Lₙ]` is a list whose first element comes from `L₁`, whose second element comes from `L₂`, and so on. -/ def sections : list (list α) → list (list α) | [] := [[]] | (l::L) := bind (sections L) $ λ s, map (λ a, a::s) l section permutations /-- An auxiliary function for defining `permutations`. `permutations_aux2 t ts r ys f` is equal to `(ys ++ ts, (insert_left ys t ts).map f ++ r)`, where `insert_left ys t ts` (not explicitly defined) is the list of lists of the form `insert_nth n t (ys ++ ts)` for `0 ≤ n < length ys`. permutations_aux2 10 [4, 5, 6] [] [1, 2, 3] id = ([1, 2, 3, 4, 5, 6], [[10, 1, 2, 3, 4, 5, 6], [1, 10, 2, 3, 4, 5, 6], [1, 2, 10, 3, 4, 5, 6]]) -/ def permutations_aux2 (t : α) (ts : list α) (r : list β) : list α → (list α → β) → list α × list β | [] f := (ts, r) | (y::ys) f := let (us, zs) := permutations_aux2 ys (λx : list α, f (y::x)) in (y :: us, f (t :: y :: us) :: zs) private def meas : (Σ'_:list α, list α) → ℕ × ℕ | ⟨l, i⟩ := (length l + length i, length l) local infix ` ≺ `:50 := inv_image (prod.lex (<) (<)) meas /-- A recursor for pairs of lists. To have `C l₁ l₂` for all `l₁`, `l₂`, it suffices to have it for `l₂ = []` and to be able to pour the elements of `l₁` into `l₂`. -/ @[elab_as_eliminator] def permutations_aux.rec {C : list α → list α → Sort v} (H0 : ∀ is, C [] is) (H1 : ∀ t ts is, C ts (t::is) → C is [] → C (t::ts) is) : ∀ l₁ l₂, C l₁ l₂ | [] is := H0 is | (t::ts) is := have h1 : ⟨ts, t :: is⟩ ≺ ⟨t :: ts, is⟩, from show prod.lex _ _ (succ (length ts + length is), length ts) (succ (length ts) + length is, length (t :: ts)), by rw nat.succ_add; exact prod.lex.right _ (lt_succ_self _), have h2 : ⟨is, []⟩ ≺ ⟨t :: ts, is⟩, from prod.lex.left _ _ (nat.lt_add_of_pos_left (succ_pos _)), H1 t ts is (permutations_aux.rec ts (t::is)) (permutations_aux.rec is []) using_well_founded { dec_tac := tactic.assumption, rel_tac := λ _ _, `[exact ⟨(≺), @inv_image.wf _ _ _ meas (prod.lex_wf lt_wf lt_wf)⟩] } /-- An auxiliary function for defining `permutations`. `permutations_aux ts is` is the set of all permutations of `is ++ ts` that do not fix `ts`. -/ def permutations_aux : list α → list α → list (list α) := @@permutations_aux.rec (λ _ _, list (list α)) (λ is, []) (λ t ts is IH1 IH2, foldr (λy r, (permutations_aux2 t ts r y id).2) IH1 (is :: IH2)) /-- List of all permutations of `l`. permutations [1, 2, 3] = [[1, 2, 3], [2, 1, 3], [3, 2, 1], [2, 3, 1], [3, 1, 2], [1, 3, 2]] -/ def permutations (l : list α) : list (list α) := l :: permutations_aux l [] /-- `permutations'_aux t ts` inserts `t` into every position in `ts`, including the last. This function is intended for use in specifications, so it is simpler than `permutations_aux2`, which plays roughly the same role in `permutations`. Note that `(permutations_aux2 t [] [] ts id).2` is similar to this function, but skips the last position: permutations'_aux 10 [1, 2, 3] = [[10, 1, 2, 3], [1, 10, 2, 3], [1, 2, 10, 3], [1, 2, 3, 10]] (permutations_aux2 10 [] [] [1, 2, 3] id).2 = [[10, 1, 2, 3], [1, 10, 2, 3], [1, 2, 10, 3]] -/ @[simp] def permutations'_aux (t : α) : list α → list (list α) | [] := [[t]] | (y::ys) := (t :: y :: ys) :: (permutations'_aux ys).map (cons y) /-- List of all permutations of `l`. This version of `permutations` is less efficient but has simpler definitional equations. The permutations are in a different order, but are equal up to permutation, as shown by `list.permutations_perm_permutations'`. permutations [1, 2, 3] = [[1, 2, 3], [2, 1, 3], [2, 3, 1], [1, 3, 2], [3, 1, 2], [3, 2, 1]] -/ @[simp] def permutations' : list α → list (list α) | [] := [[]] | (t::ts) := (permutations' ts).bind $ permutations'_aux t end permutations /-- `erasep p l` removes the first element of `l` satisfying the predicate `p`. -/ def erasep (p : α → Prop) [decidable_pred p] : list α → list α | [] := [] | (a::l) := if p a then l else a :: erasep l /-- `extractp p l` returns a pair of an element `a` of `l` satisfying the predicate `p`, and `l`, with `a` removed. If there is no such element `a` it returns `(none, l)`. -/ def extractp (p : α → Prop) [decidable_pred p] : list α → option α × list α | [] := (none, []) | (a::l) := if p a then (some a, l) else let (a', l') := extractp l in (a', a :: l') /-- `revzip l` returns a list of pairs of the elements of `l` paired with the elements of `l` in reverse order. `revzip [1,2,3,4,5] = [(1, 5), (2, 4), (3, 3), (4, 2), (5, 1)]` -/ def revzip (l : list α) : list (α × α) := zip l l.reverse /-- `product l₁ l₂` is the list of pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂`. product [1, 2] [5, 6] = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ def product (l₁ : list α) (l₂ : list β) : list (α × β) := l₁.bind $ λ a, l₂.map $ prod.mk a /-- `sigma l₁ l₂` is the list of dependent pairs `(a, b)` where `a ∈ l₁` and `b ∈ l₂ a`. sigma [1, 2] (λ_, [(5 : ℕ), 6]) = [(1, 5), (1, 6), (2, 5), (2, 6)] -/ protected def sigma {σ : α → Type*} (l₁ : list α) (l₂ : Π a, list (σ a)) : list (Σ a, σ a) := l₁.bind $ λ a, (l₂ a).map $ sigma.mk a /-- Auxliary definition used to define `of_fn`. `of_fn_aux f m h l` returns the first `m` elements of `of_fn f` appended to `l` -/ def of_fn_aux {n} (f : fin n → α) : ∀ m, m ≤ n → list α → list α | 0 h l := l | (succ m) h l := of_fn_aux m (le_of_lt h) (f ⟨m, h⟩ :: l) /-- `of_fn f` with `f : fin n → α` returns the list whose ith element is `f i` `of_fun f = [f 0, f 1, ... , f(n - 1)]` -/ def of_fn {n} (f : fin n → α) : list α := of_fn_aux f n (le_refl _) [] /-- `of_fn_nth_val f i` returns `some (f i)` if `i < n` and `none` otherwise. -/ def of_fn_nth_val {n} (f : fin n → α) (i : ℕ) : option α := if h : i < n then some (f ⟨i, h⟩) else none /-- `disjoint l₁ l₂` means that `l₁` and `l₂` have no elements in common. -/ def disjoint (l₁ l₂ : list α) : Prop := ∀ ⦃a⦄, a ∈ l₁ → a ∈ l₂ → false section pairwise variables (R : α → α → Prop) /-- `pairwise R l` means that all the elements with earlier indexes are `R`-related to all the elements with later indexes. pairwise R [1, 2, 3] ↔ R 1 2 ∧ R 1 3 ∧ R 2 3 For example if `R = (≠)` then it asserts `l` has no duplicates, and if `R = (<)` then it asserts that `l` is (strictly) sorted. -/ inductive pairwise : list α → Prop | nil : pairwise [] | cons : ∀ {a : α} {l : list α}, (∀ a' ∈ l, R a a') → pairwise l → pairwise (a::l) variables {R} @[simp] theorem pairwise_cons {a : α} {l : list α} : pairwise R (a::l) ↔ (∀ a' ∈ l, R a a') ∧ pairwise R l := ⟨λ p, by cases p with a l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ attribute [simp] pairwise.nil instance decidable_pairwise [decidable_rel R] (l : list α) : decidable (pairwise R l) := by induction l with hd tl ih; [exact is_true pairwise.nil, exactI decidable_of_iff' _ pairwise_cons] end pairwise /-- `pw_filter R l` is a maximal sublist of `l` which is `pairwise R`. `pw_filter (≠)` is the erase duplicates function (cf. `erase_dup`), and `pw_filter (<)` finds a maximal increasing subsequence in `l`. For example, pw_filter (<) [0, 1, 5, 2, 6, 3, 4] = [0, 1, 2, 3, 4] -/ def pw_filter (R : α → α → Prop) [decidable_rel R] : list α → list α | [] := [] | (x :: xs) := let IH := pw_filter xs in if ∀ y ∈ IH, R x y then x :: IH else IH section chain variable (R : α → α → Prop) /-- `chain R a l` means that `R` holds between adjacent elements of `a::l`. chain R a [b, c, d] ↔ R a b ∧ R b c ∧ R c d -/ inductive chain : α → list α → Prop | nil {a : α} : chain a [] | cons : ∀ {a b : α} {l : list α}, R a b → chain b l → chain a (b::l) /-- `chain' R l` means that `R` holds between adjacent elements of `l`. chain' R [a, b, c, d] ↔ R a b ∧ R b c ∧ R c d -/ def chain' : list α → Prop | [] := true | (a :: l) := chain R a l variable {R} @[simp] theorem chain_cons {a b : α} {l : list α} : chain R a (b::l) ↔ R a b ∧ chain R b l := ⟨λ p, by cases p with _ a b l n p; exact ⟨n, p⟩, λ ⟨n, p⟩, p.cons n⟩ attribute [simp] chain.nil instance decidable_chain [decidable_rel R] (a : α) (l : list α) : decidable (chain R a l) := by induction l generalizing a; simp only [chain.nil, chain_cons]; resetI; apply_instance instance decidable_chain' [decidable_rel R] (l : list α) : decidable (chain' R l) := by cases l; dunfold chain'; apply_instance end chain /-- `nodup l` means that `l` has no duplicates, that is, any element appears at most once in the list. It is defined as `pairwise (≠)`. -/ def nodup : list α → Prop := pairwise (≠) instance nodup_decidable [decidable_eq α] : ∀ l : list α, decidable (nodup l) := list.decidable_pairwise /-- `erase_dup l` removes duplicates from `l` (taking only the first occurrence). Defined as `pw_filter (≠)`. erase_dup [1, 0, 2, 2, 1] = [0, 2, 1] -/ def erase_dup [decidable_eq α] : list α → list α := pw_filter (≠) /-- `range' s n` is the list of numbers `[s, s+1, ..., s+n-1]`. It is intended mainly for proving properties of `range` and `iota`. -/ @[simp] def range' : ℕ → ℕ → list ℕ | s 0 := [] | s (n+1) := s :: range' (s+1) n /-- Drop `none`s from a list, and replace each remaining `some a` with `a`. -/ def reduce_option {α} : list (option α) → list α := list.filter_map id /-- `ilast' x xs` returns the last element of `xs` if `xs` is non-empty; it returns `x` otherwise -/ @[simp] def ilast' {α} : α → list α → α | a [] := a | a (b::l) := ilast' b l /-- `last' xs` returns the last element of `xs` if `xs` is non-empty; it returns `none` otherwise -/ @[simp] def last' {α} : list α → option α | [] := none | [a] := some a | (b::l) := last' l /-- `rotate l n` rotates the elements of `l` to the left by `n` rotate [0, 1, 2, 3, 4, 5] 2 = [2, 3, 4, 5, 0, 1] -/ def rotate (l : list α) (n : ℕ) : list α := let (l₁, l₂) := list.split_at (n % l.length) l in l₂ ++ l₁ /-- rotate' is the same as `rotate`, but slower. Used for proofs about `rotate`-/ def rotate' : list α → ℕ → list α | [] n := [] | l 0 := l | (a::l) (n+1) := rotate' (l ++ [a]) n section choose variables (p : α → Prop) [decidable_pred p] (l : list α) /-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`, choose the first element with this property. This version returns both `a` and proofs of `a ∈ l` and `p a`. -/ def choose_x : Π l : list α, Π hp : (∃ a, a ∈ l ∧ p a), { a // a ∈ l ∧ p a } | [] hp := false.elim (exists.elim hp (assume a h, not_mem_nil a h.left)) | (l :: ls) hp := if pl : p l then ⟨l, ⟨or.inl rfl, pl⟩⟩ else let ⟨a, ⟨a_mem_ls, pa⟩⟩ := choose_x ls (hp.imp (λ b ⟨o, h₂⟩, ⟨o.resolve_left (λ e, pl $ e ▸ h₂), h₂⟩)) in ⟨a, ⟨or.inr a_mem_ls, pa⟩⟩ /-- Given a decidable predicate `p` and a proof of existence of `a ∈ l` such that `p a`, choose the first element with this property. This version returns `a : α`, and properties are given by `choose_mem` and `choose_property`. -/ def choose (hp : ∃ a, a ∈ l ∧ p a) : α := choose_x p l hp end choose /-- Filters and maps elements of a list -/ def mmap_filter {m : Type → Type v} [monad m] {α β} (f : α → m (option β)) : list α → m (list β) | [] := return [] | (h :: t) := do b ← f h, t' ← t.mmap_filter, return $ match b with none := t' | (some x) := x::t' end /-- `mmap_upper_triangle f l` calls `f` on all elements in the upper triangular part of `l × l`. That is, for each `e ∈ l`, it will run `f e e` and then `f e e'` for each `e'` that appears after `e` in `l`. Example: suppose `l = [1, 2, 3]`. `mmap_upper_triangle f l` will produce the list `[f 1 1, f 1 2, f 1 3, f 2 2, f 2 3, f 3 3]`. -/ def mmap_upper_triangle {m} [monad m] {α β : Type u} (f : α → α → m β) : list α → m (list β) | [] := return [] | (h::t) := do v ← f h h, l ← t.mmap (f h), t ← t.mmap_upper_triangle, return $ (v::l) ++ t /-- `mmap'_diag f l` calls `f` on all elements in the upper triangular part of `l × l`. That is, for each `e ∈ l`, it will run `f e e` and then `f e e'` for each `e'` that appears after `e` in `l`. Example: suppose `l = [1, 2, 3]`. `mmap'_diag f l` will evaluate, in this order, `f 1 1`, `f 1 2`, `f 1 3`, `f 2 2`, `f 2 3`, `f 3 3`. -/ def mmap'_diag {m} [monad m] {α} (f : α → α → m unit) : list α → m unit | [] := return () | (h::t) := f h h >> t.mmap' (f h) >> t.mmap'_diag protected def traverse {F : Type u → Type v} [applicative F] {α β : Type*} (f : α → F β) : list α → F (list β) | [] := pure [] | (x :: xs) := list.cons <$> f x <*> traverse xs /-- `get_rest l l₁` returns `some l₂` if `l = l₁ ++ l₂`. If `l₁` is not a prefix of `l`, returns `none` -/ def get_rest [decidable_eq α] : list α → list α → option (list α) | l [] := some l | [] _ := none | (x::l) (y::l₁) := if x = y then get_rest l l₁ else none /-- `list.slice n m xs` removes a slice of length `m` at index `n` in list `xs`. -/ def slice {α} : ℕ → ℕ → list α → list α | 0 n xs := xs.drop n | (succ n) m [] := [] | (succ n) m (x :: xs) := x :: slice n m xs /-- Left-biased version of `list.map₂`. `map₂_left' f as bs` applies `f` to each pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, `f` is applied to `none` for the remaining `aᵢ`. Returns the results of the `f` applications and the remaining `bs`. ``` map₂_left' prod.mk [1, 2] ['a'] = ([(1, some 'a'), (2, none)], []) map₂_left' prod.mk [1] ['a', 'b'] = ([(1, some 'a')], ['b']) ``` -/ @[simp] def map₂_left' (f : α → option β → γ) : list α → list β → (list γ × list β) | [] bs := ([], bs) | (a :: as) [] := ((a :: as).map (λ a, f a none), []) | (a :: as) (b :: bs) := let rec := map₂_left' as bs in (f a (some b) :: rec.fst, rec.snd) /-- Right-biased version of `list.map₂`. `map₂_right' f as bs` applies `f` to each pair of elements `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, `f` is applied to `none` for the remaining `bᵢ`. Returns the results of the `f` applications and the remaining `as`. ``` map₂_right' prod.mk [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], []) map₂_right' prod.mk [1, 2] ['a'] = ([(some 1, 'a')], [2]) ``` -/ def map₂_right' (f : option α → β → γ) (as : list α) (bs : list β) : (list γ × list α) := map₂_left' (flip f) bs as /-- Left-biased version of `list.zip`. `zip_left' as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, the remaining `aᵢ` are paired with `none`. Also returns the remaining `bs`. ``` zip_left' [1, 2] ['a'] = ([(1, some 'a'), (2, none)], []) zip_left' [1] ['a', 'b'] = ([(1, some 'a')], ['b']) zip_left' = map₂_left' prod.mk ``` -/ def zip_left' : list α → list β → list (α × option β) × list β := map₂_left' prod.mk /-- Right-biased version of `list.zip`. `zip_right' as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, the remaining `bᵢ` are paired with `none`. Also returns the remaining `as`. ``` zip_right' [1] ['a', 'b'] = ([(some 1, 'a'), (none, 'b')], []) zip_right' [1, 2] ['a'] = ([(some 1, 'a')], [2]) zip_right' = map₂_right' prod.mk ``` -/ def zip_right' : list α → list β → list (option α × β) × list α := map₂_right' prod.mk /-- Left-biased version of `list.map₂`. `map₂_left f as bs` applies `f` to each pair `aᵢ ∈ as` and `bᵢ ‌∈ bs`. If `bs` is shorter than `as`, `f` is applied to `none` for the remaining `aᵢ`. ``` map₂_left prod.mk [1, 2] ['a'] = [(1, some 'a'), (2, none)] map₂_left prod.mk [1] ['a', 'b'] = [(1, some 'a')] map₂_left f as bs = (map₂_left' f as bs).fst ``` -/ @[simp] def map₂_left (f : α → option β → γ) : list α → list β → list γ | [] _ := [] | (a :: as) [] := (a :: as).map (λ a, f a none) | (a :: as) (b :: bs) := f a (some b) :: map₂_left as bs /-- Right-biased version of `list.map₂`. `map₂_right f as bs` applies `f` to each pair `aᵢ ∈ as` and `bᵢ ‌∈ bs`. If `as` is shorter than `bs`, `f` is applied to `none` for the remaining `bᵢ`. ``` map₂_right prod.mk [1, 2] ['a'] = [(some 1, 'a')] map₂_right prod.mk [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')] map₂_right f as bs = (map₂_right' f as bs).fst ``` -/ def map₂_right (f : option α → β → γ) (as : list α) (bs : list β) : list γ := map₂_left (flip f) bs as /-- Left-biased version of `list.zip`. `zip_left as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `bs` is shorter than `as`, the remaining `aᵢ` are paired with `none`. ``` zip_left [1, 2] ['a'] = [(1, some 'a'), (2, none)] zip_left [1] ['a', 'b'] = [(1, some 'a')] zip_left = map₂_left prod.mk ``` -/ def zip_left : list α → list β → list (α × option β) := map₂_left prod.mk /-- Right-biased version of `list.zip`. `zip_right as bs` returns the list of pairs `(aᵢ, bᵢ)` for `aᵢ ∈ as` and `bᵢ ∈ bs`. If `as` is shorter than `bs`, the remaining `bᵢ` are paired with `none`. ``` zip_right [1, 2] ['a'] = [(some 1, 'a')] zip_right [1] ['a', 'b'] = [(some 1, 'a'), (none, 'b')] zip_right = map₂_right prod.mk ``` -/ def zip_right : list α → list β → list (option α × β) := map₂_right prod.mk /-- If all elements of `xs` are `some xᵢ`, `all_some xs` returns the `xᵢ`. Otherwise it returns `none`. ``` all_some [some 1, some 2] = some [1, 2] all_some [some 1, none ] = none ``` -/ def all_some : list (option α) → option (list α) | [] := some [] | (some a :: as) := cons a <$> all_some as | (none :: as) := none /-- `fill_nones xs ys` replaces the `none`s in `xs` with elements of `ys`. If there are not enough `ys` to replace all the `none`s, the remaining `none`s are dropped from `xs`. ``` fill_nones [none, some 1, none, none] [2, 3] = [2, 1, 3] ``` -/ def fill_nones {α} : list (option α) → list α → list α | [] _ := [] | (some a :: as) as' := a :: fill_nones as as' | (none :: as) [] := as.reduce_option | (none :: as) (a :: as') := a :: fill_nones as as' /-- `take_list as ns` extracts successive sublists from `as`. For `ns = n₁ ... nₘ`, it first takes the `n₁` initial elements from `as`, then the next `n₂` ones, etc. It returns the sublists of `as` -- one for each `nᵢ` -- and the remaining elements of `as`. If `as` does not have at least as many elements as the sum of the `nᵢ`, the corresponding sublists will have less than `nᵢ` elements. ``` take_list ['a', 'b', 'c', 'd', 'e'] [2, 1, 1] = ([['a', 'b'], ['c'], ['d']], ['e']) take_list ['a', 'b'] [3, 1] = ([['a', 'b'], []], []) ``` -/ def take_list {α} : list α → list ℕ → list (list α) × list α | xs [] := ([], xs) | xs (n :: ns) := let ⟨xs₁, xs₂⟩ := xs.split_at n in let ⟨xss, rest⟩ := take_list xs₂ ns in (xs₁ :: xss, rest) /-- `to_rbmap as` is the map that associates each index `i` of `as` with the corresponding element of `as`. ``` to_rbmap ['a', 'b', 'c'] = rbmap_of [(0, 'a'), (1, 'b'), (2, 'c')] ``` -/ def to_rbmap {α : Type*} : list α → rbmap ℕ α := foldl_with_index (λ i mapp a, mapp.insert i a) (mk_rbmap ℕ α) /-- Auxliary definition used to define `to_chunks`. `to_chunks_aux n xs i` returns `(xs.take i, (xs.drop i).to_chunks (n+1))`, that is, the first `i` elements of `xs`, and the remaining elements chunked into sublists of length `n+1`. -/ def to_chunks_aux {α} (n : ℕ) : list α → ℕ → list α × list (list α) | [] i := ([], []) | (x::xs) 0 := let (l, L) := to_chunks_aux xs n in ([], (x::l)::L) | (x::xs) (i+1) := let (l, L) := to_chunks_aux xs i in (x::l, L) /-- `xs.to_chunks n` splits the list into sublists of size at most `n`, such that `(xs.to_chunks n).join = xs`. ``` [1, 2, 3, 4, 5, 6, 7, 8].to_chunks 10 = [[1, 2, 3, 4, 5, 6, 7, 8]] [1, 2, 3, 4, 5, 6, 7, 8].to_chunks 3 = [[1, 2, 3], [4, 5, 6], [7, 8]] [1, 2, 3, 4, 5, 6, 7, 8].to_chunks 2 = [[1, 2], [3, 4], [5, 6], [7, 8]] [1, 2, 3, 4, 5, 6, 7, 8].to_chunks 0 = [[1, 2, 3, 4, 5, 6, 7, 8]] ``` -/ def to_chunks {α} : ℕ → list α → list (list α) | _ [] := [] | 0 xs := [xs] | (n+1) (x::xs) := let (l, L) := to_chunks_aux n xs n in (x::l)::L /-- Asynchronous version of `list.map`. -/ meta def map_async_chunked {α β} (f : α → β) (xs : list α) (chunk_size := 1024) : list β := ((xs.to_chunks chunk_size).map (λ xs, task.delay (λ _, list.map f xs))).bind task.get /-! We add some n-ary versions of `list.zip_with` for functions with more than two arguments. These can also be written in terms of `list.zip` or `list.zip_with`. For example, `zip_with3 f xs ys zs` could also be written as `zip_with id (zip_with f xs ys) zs` or as `(zip xs $ zip ys zs).map $ λ ⟨x, y, z⟩, f x y z`. -/ /-- Ternary version of `list.zip_with`. -/ def zip_with3 (f : α → β → γ → δ) : list α → list β → list γ → list δ | (x::xs) (y::ys) (z::zs) := f x y z :: zip_with3 xs ys zs | _ _ _ := [] /-- Quaternary version of `list.zip_with`. -/ def zip_with4 (f : α → β → γ → δ → ε) : list α → list β → list γ → list δ → list ε | (x::xs) (y::ys) (z::zs) (u::us) := f x y z u :: zip_with4 xs ys zs us | _ _ _ _ := [] /-- Quinary version of `list.zip_with`. -/ def zip_with5 (f : α → β → γ → δ → ε → ζ) : list α → list β → list γ → list δ → list ε → list ζ | (x::xs) (y::ys) (z::zs) (u::us) (v::vs) := f x y z u v :: zip_with5 xs ys zs us vs | _ _ _ _ _ := [] end list
b3ae4b50f82f73833a62b49ee51a3c318d0b3f18
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/number_theory/legendre_symbol/gauss_sum.lean
1045a100f6a1801deb5786324eefbb7f6fcadb32
[ "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
13,509
lean
/- Copyright (c) 2022 Michael Stoll. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Michael Stoll -/ import number_theory.legendre_symbol.add_character import number_theory.legendre_symbol.zmod_char import algebra.char_p.char_and_card /-! # Gauss sums We define the Gauss sum associated to a multiplicative and an additive character of a finite field and prove some results about them. ## Main definition Let `R` be a finite commutative ring and let `R'` be another commutative ring. If `χ` is a multiplicative character `R → R'` (type `mul_char R R'`) and `ψ` is an additive character `R → R'` (type `add_char R R'`, which abbreviates `(multiplicative R) →* R'`), then the *Gauss sum* of `χ` and `ψ` is `∑ a, χ a * ψ a`. ## Main results Some important results are as follows. * `gauss_sum_mul_gauss_sum_eq_card`: The product of the Gauss sums of `χ` and `ψ` and that of `χ⁻¹` and `ψ⁻¹` is the cardinality of the source ring `R` (if `χ` is nontrivial, `ψ` is primitive and `R` is a field). * `gauss_sum_sq`: The square of the Gauss sum is `χ(-1)` times the cardinality of `R` if in addition `χ` is a quadratic character. * `quad_gauss_sum_frob`: For a quadratic character `χ`, raising the Gauss sum to the `p`th power (where `p` is the characteristic of the target ring `R'`) multiplies it by `χ p`. * `char.card_pow_card`: When `F` and `F'` are finite fields and `χ : F → F'` is a nontrivial quadratic character, then `(χ (-1) * #F)^(#F'/2) = χ (#F')`. * `finite_field.two_pow_card`: For every finite field `F` of odd characteristic, we have `2^(#F/2) = χ₈(#F)` in `F`. This machinery can be used to derive (a generalization of) the Law of Quadratic Reciprocity. ## Tags additive character, multiplicative character, Gauss sum -/ universes u v open_locale big_operators open add_char mul_char section gauss_sum_def -- `R` is the domain of the characters variables {R : Type u} [comm_ring R] [fintype R] -- `R'` is the target of the characters variables {R' : Type v} [comm_ring R'] /-! ### Definition and first properties -/ /-- Definition of the Gauss sum associated to a multiplicative and an additive character. -/ def gauss_sum (χ : mul_char R R') (ψ : add_char R R') : R' := ∑ a, χ a * ψ a /-- Replacing `ψ` by `mul_shift ψ a` and multiplying the Gauss sum by `χ a` does not change it. -/ lemma gauss_sum_mul_shift (χ : mul_char R R') (ψ : add_char R R') (a : Rˣ) : χ a * gauss_sum χ (mul_shift ψ a) = gauss_sum χ ψ := begin simp only [gauss_sum, mul_shift_apply, finset.mul_sum], simp_rw [← mul_assoc, ← map_mul], exact fintype.sum_bijective _ a.mul_left_bijective _ _ (λ x, rfl), end end gauss_sum_def /-! ### The product of two Gauss sums -/ section gauss_sum_prod -- In the following, we need `R` to be a finite field and `R'` to be a domain. variables {R : Type u} [field R] [fintype R] {R' : Type v} [comm_ring R'] [is_domain R'] -- A helper lemma for `gauss_sum_mul_gauss_sum_eq_card` below -- Is this useful enough in other contexts to be public? private lemma gauss_sum_mul_aux {χ : mul_char R R'} (hχ : is_nontrivial χ) (ψ : add_char R R') (b : R) : ∑ a, χ (a * b⁻¹) * ψ (a - b) = ∑ c, χ c * ψ (b * (c - 1)) := begin cases eq_or_ne b 0 with hb hb, { -- case `b = 0` simp only [hb, inv_zero, mul_zero, mul_char.map_zero, zero_mul, finset.sum_const_zero, map_zero_one, mul_one], exact hχ.sum_eq_zero.symm, }, { -- case `b ≠ 0` refine (fintype.sum_bijective _ (mul_left_bijective₀ b hb) _ _ $ λ x, _).symm, rw [mul_assoc, mul_comm x, ← mul_assoc, mul_inv_cancel hb, one_mul, mul_sub, mul_one] }, end /-- We have `gauss_sum χ ψ * gauss_sum χ⁻¹ ψ⁻¹ = fintype.card R` when `χ` is nontrivial and `ψ` is primitive (and `R` is a field). -/ lemma gauss_sum_mul_gauss_sum_eq_card {χ : mul_char R R'} (hχ : is_nontrivial χ) {ψ : add_char R R'} (hψ : is_primitive ψ) : gauss_sum χ ψ * gauss_sum χ⁻¹ ψ⁻¹ = fintype.card R := begin simp only [gauss_sum, add_char.inv_apply, finset.sum_mul, finset.mul_sum, mul_char.inv_apply'], conv in (_ * _ * (_ * _)) { rw [mul_mul_mul_comm, ← map_mul, ← map_add_mul, ← sub_eq_add_neg], }, simp_rw gauss_sum_mul_aux hχ ψ, rw [finset.sum_comm], classical, -- to get `[decidable_eq R]` for `sum_mul_shift` simp_rw [← finset.mul_sum, sum_mul_shift _ hψ, sub_eq_zero, mul_ite, mul_zero], rw [finset.sum_ite_eq' finset.univ (1 : R)], simp only [finset.mem_univ, map_one, one_mul, if_true], end /-- When `χ` is a nontrivial quadratic character, then the square of `gauss_sum χ ψ` is `χ(-1)` times the cardinality of `R`. -/ lemma gauss_sum_sq {χ : mul_char R R'} (hχ₁ : is_nontrivial χ) (hχ₂ : is_quadratic χ) {ψ : add_char R R'} (hψ : is_primitive ψ) : (gauss_sum χ ψ) ^ 2 = χ (-1) * fintype.card R := begin rw [pow_two, ← gauss_sum_mul_gauss_sum_eq_card hχ₁ hψ, hχ₂.inv, mul_rotate'], congr, rw [mul_comm, ← gauss_sum_mul_shift _ _ (-1 : Rˣ), inv_mul_shift], refl, end end gauss_sum_prod /-! ### Gauss sums and Frobenius -/ section gauss_sum_frob variables {R : Type u} [comm_ring R] [fintype R] {R' : Type v} [comm_ring R'] -- We assume that the target ring `R'` has prime characteristic `p`. variables (p : ℕ) [fp : fact p.prime] [hch : char_p R' p] include fp hch /-- When `R'` has prime characteristic `p`, then the `p`th power of the Gauss sum of `χ` and `ψ` is the Gauss sum of `χ^p` and `ψ^p`. -/ lemma gauss_sum_frob (χ : mul_char R R') (ψ : add_char R R') : gauss_sum χ ψ ^ p = gauss_sum (χ ^ p) (ψ ^ p) := begin rw [← frobenius_def, gauss_sum, gauss_sum, map_sum], simp_rw [pow_apply' χ fp.1.pos, map_mul, frobenius_def], refl, end /-- For a quadratic character `χ` and when the characteristic `p` of the target ring is a unit in the source ring, the `p`th power of the Gauss sum of`χ` and `ψ` is `χ p` times the original Gauss sum. -/ lemma mul_char.is_quadratic.gauss_sum_frob (hp : is_unit (p : R)) {χ : mul_char R R'} (hχ : is_quadratic χ) (ψ : add_char R R') : gauss_sum χ ψ ^ p = χ p * gauss_sum χ ψ := by rw [gauss_sum_frob, pow_mul_shift, hχ.pow_char p, ← gauss_sum_mul_shift χ ψ hp.unit, ← mul_assoc, hp.unit_spec, ← pow_two, ← pow_apply' _ (by norm_num : 0 < 2), hχ.sq_eq_one, ← hp.unit_spec, one_apply_coe, one_mul] /-- For a quadratic character `χ` and when the characteristic `p` of the target ring is a unit in the source ring and `n` is a natural number, the `p^n`th power of the Gauss sum of`χ` and `ψ` is `χ (p^n)` times the original Gauss sum. -/ lemma mul_char.is_quadratic.gauss_sum_frob_iter (n : ℕ) (hp : is_unit (p : R)) {χ : mul_char R R'} (hχ : is_quadratic χ) (ψ : add_char R R') : gauss_sum χ ψ ^ (p ^ n) = χ (p ^ n) * gauss_sum χ ψ := begin induction n with n ih, { rw [pow_zero, pow_one, pow_zero, mul_char.map_one, one_mul], }, { rw [pow_succ, mul_comm p, pow_mul, ih, mul_pow, hχ.gauss_sum_frob _ hp, ← mul_assoc, pow_succ, mul_comm (p : R), map_mul, ← pow_apply' χ fp.1.pos (p ^ n), hχ.pow_char p], }, end end gauss_sum_frob /-! ### Values of quadratic characters -/ section gauss_sum_values variables {R : Type u} [comm_ring R] [fintype R] {R' : Type v} [comm_ring R'] [is_domain R'] /-- If the square of the Gauss sum of a quadratic character is `χ(-1) * #R`, then we get, for all `n : ℕ`, the relation `(χ(-1) * #R) ^ (p^n/2) = χ(p^n)`, where `p` is the (odd) characteristic of the target ring `R'`. This version can be used when `R` is not a field, e.g., `ℤ/8ℤ`. -/ lemma char.card_pow_char_pow {χ : mul_char R R'} (hχ : is_quadratic χ) (ψ : add_char R R') (p n : ℕ) [fp : fact p.prime] [hch : char_p R' p] (hp : is_unit (p : R)) (hp' : p ≠ 2) (hg : (gauss_sum χ ψ) ^ 2 = χ (-1) * fintype.card R) : (χ (-1) * fintype.card R) ^ (p ^ n / 2) = χ (p ^ n) := begin have : gauss_sum χ ψ ≠ 0, { intro hf, rw [hf, zero_pow (by norm_num : 0 < 2), eq_comm, mul_eq_zero] at hg, exact not_is_unit_prime_of_dvd_card p ((char_p.cast_eq_zero_iff R' p _).mp $ hg.resolve_left (is_unit_one.neg.map χ).ne_zero) hp }, rw ← hg, apply mul_right_cancel₀ this, rw [← hχ.gauss_sum_frob_iter p n hp ψ, ← pow_mul, mul_comm, ← pow_succ, nat.two_mul_div_two_add_one_of_odd ((fp.1.eq_two_or_odd').resolve_left hp').pow], end /-- When `F` and `F'` are finite fields and `χ : F → F'` is a nontrivial quadratic character, then `(χ(-1) * #F)^(#F'/2) = χ(#F')`. -/ lemma char.card_pow_card {F : Type} [field F] [fintype F] {F' : Type} [field F'] [fintype F'] {χ : mul_char F F'} (hχ₁ : is_nontrivial χ) (hχ₂ : is_quadratic χ) (hch₁ : ring_char F' ≠ ring_char F) (hch₂ : ring_char F' ≠ 2) : (χ (-1) * fintype.card F) ^ (fintype.card F' / 2) = χ (fintype.card F') := begin obtain ⟨n, hp, hc⟩ := finite_field.card F (ring_char F), obtain ⟨n', hp', hc'⟩ := finite_field.card F' (ring_char F'), let ψ := primitive_char_finite_field F F' hch₁, let FF' := cyclotomic_field ψ.n F', have hchar := algebra.ring_char_eq F' FF', apply (algebra_map F' FF').injective, rw [map_pow, map_mul, map_nat_cast, hc', hchar, nat.cast_pow], simp only [← mul_char.ring_hom_comp_apply], haveI := fact.mk hp', haveI := fact.mk (hchar.subst hp'), rw [ne, ← nat.prime_dvd_prime_iff_eq hp' hp, ← is_unit_iff_not_dvd_char, hchar] at hch₁, exact char.card_pow_char_pow (hχ₂.comp _) ψ.char (ring_char FF') n' hch₁ (hchar ▸ hch₂) (gauss_sum_sq (hχ₁.comp $ ring_hom.injective _) (hχ₂.comp _) ψ.prim), end end gauss_sum_values section gauss_sum_two /-! ### The quadratic character of 2 This section proves the following result. For every finite field `F` of odd characteristic, we have `2^(#F/2) = χ₈(#F)` in `F`. This can be used to show that the quadratic character of `F` takes the value `χ₈(#F)` at `2`. The proof uses the Gauss sum of `χ₈` and a primitive additive character on `ℤ/8ℤ`; in this way, the result is reduced to `card_pow_char_pow`. -/ open zmod /-- For every finite field `F` of odd characteristic, we have `2^(#F/2) = χ₈(#F)` in `F`. -/ lemma finite_field.two_pow_card {F : Type*} [fintype F] [field F] (hF : ring_char F ≠ 2) : (2 : F) ^ (fintype.card F / 2) = χ₈ (fintype.card F) := begin have hp2 : ∀ (n : ℕ), (2 ^ n : F) ≠ 0 := λ n, pow_ne_zero n (ring.two_ne_zero hF), obtain ⟨n, hp, hc⟩ := finite_field.card F (ring_char F), -- we work in `FF`, the eighth cyclotomic field extension of `F` let FF := (polynomial.cyclotomic 8 F).splitting_field, haveI : finite_dimensional F FF := polynomial.is_splitting_field.finite_dimensional FF (polynomial.cyclotomic 8 F), haveI : fintype FF := finite_dimensional.fintype_of_fintype F FF, have hchar := algebra.ring_char_eq F FF, have FFp := hchar.subst hp, haveI := fact.mk FFp, have hFF := ne_of_eq_of_ne hchar.symm hF, -- `ring_char FF ≠ 2` have hu : is_unit (ring_char FF : zmod 8), { rw [is_unit_iff_not_dvd_char, ring_char_zmod_n], rw [ne, ← nat.prime_dvd_prime_iff_eq FFp nat.prime_two] at hFF, change ¬ _ ∣ 2 ^ 3, exact mt FFp.dvd_of_dvd_pow hFF }, -- there is a primitive additive character `ℤ/8ℤ → FF`, sending `a + 8ℤ ↦ τ^a` -- with a primitive eighth root of unity `τ` let ψ₈ := primitive_zmod_char 8 F (by convert hp2 3; norm_num), let τ : FF := ψ₈.char 1, have τ_spec : τ ^ 4 = -1, { refine (sq_eq_one_iff.1 _).resolve_left _; { simp only [τ, ← map_nsmul_pow], erw add_char.is_primitive.zmod_char_eq_one_iff 8 ψ₈.prim, dec_trivial } }, -- we consider `χ₈` as a multiplicative character `ℤ/8ℤ → FF` let χ := χ₈.ring_hom_comp (int.cast_ring_hom FF), have hχ : χ (-1) = 1 := norm_num.int_cast_one, have hq : is_quadratic χ := is_quadratic_χ₈.comp _, -- we now show that the Gauss sum of `χ` and `ψ₈` has the relevant property have hg : gauss_sum χ ψ₈.char ^ 2 = χ (-1) * fintype.card (zmod 8), { rw [hχ, one_mul, card, gauss_sum], convert ← congr_arg (^ 2) (fin.sum_univ_eight $ λ x, (χ₈ x : FF) * τ ^ x.val), { ext, congr, apply pow_one }, convert_to (0 + 1 * τ ^ 1 + 0 + (-1) * τ ^ 3 + 0 + (-1) * τ ^ 5 + 0 + 1 * τ ^ 7) ^ 2 = _, { simp only [χ₈_apply, matrix.cons_val_zero, matrix.cons_val_one, matrix.head_cons, matrix.cons_vec_bit0_eq_alt0, matrix.cons_vec_bit1_eq_alt1, matrix.cons_append, matrix.cons_vec_alt0, matrix.cons_vec_alt1, int.cast_zero, int.cast_one, int.cast_neg, zero_mul], refl }, convert_to 8 + (τ ^ 4 + 1) * (τ ^ 10 - 2 * τ ^ 8 - 2 * τ ^ 6 + 6 * τ ^ 4 + τ ^ 2 - 8) = _, { ring }, { rw τ_spec, norm_num } }, -- this allows us to apply `card_pow_char_pow` to our situation have h := char.card_pow_char_pow hq ψ₈.char (ring_char FF) n hu hFF hg, rw [card, ← hchar, hχ, one_mul, ← hc, ← nat.cast_pow (ring_char F), ← hc] at h, -- finally, we change `2` to `8` on the left hand side convert_to (8 : F) ^ (fintype.card F / 2) = _, { rw [(by norm_num : (8 : F) = 2 ^ 2 * 2), mul_pow, (finite_field.is_square_iff hF $ hp2 2).mp ⟨2, pow_two 2⟩, one_mul] }, apply (algebra_map F FF).injective, simp only [map_pow, map_bit0, map_one, map_int_cast], convert h, norm_num, end end gauss_sum_two
3e5f3fc88ab6437dcfdf26b4ed4de840460026b5
05f637fa14ac28031cb1ea92086a0f4eb23ff2b1
/tests/lean/interactive/t9.lean
f83b0d405ac8c2b9faf73ed7b6ab5088b0c10bae
[ "Apache-2.0" ]
permissive
codyroux/lean0.1
1ce92751d664aacff0529e139083304a7bbc8a71
0dc6fb974aa85ed6f305a2f4b10a53a44ee5f0ef
refs/heads/master
1,610,830,535,062
1,402,150,480,000
1,402,150,480,000
19,588,851
2
0
null
null
null
null
UTF-8
Lean
false
false
640
lean
(* import("tactic.lua") *) theorem T1 (A B : Bool) : A /\ B → B /\ A := fun H : A /\ B, let main : B /\ A := (let H1 : B := _, H2 : A := _ in _) in main. conj_hyp. exact. done. conj_hyp. exact. done. apply and_intro. exact. done. (* simple_tac = Repeat(OrElse(conj_hyp_tac(), conj_tac(), assumption_tac())) *) theorem T2 (A B : Bool) : A /\ B → B /\ A := fun H : A /\ B, let H1 : A := _, H2 : B := _, main : B /\ A := _ in main. simple_tac. done. simple_tac. done. simple_tac. done.
697be045230e436b49def6b68995a7050dd62b4a
cc62cd292c1acc80a10b1c645915b70d2cdee661
/src/category_theory/concrete.lean
e69ac58642f45b7a4f0422cfce9ecb40489263b7
[]
no_license
RitaAhmadi/lean-category-theory
4afb881c4b387ee2c8ce706c454fbf9db8897a29
a27b4ae5eac978e9188d2e867c3d11d9a5b87a9e
refs/heads/master
1,651,786,183,402
1,565,604,314,000
1,565,604,314,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
487
lean
-- Copyright (c) 2018 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Scott Morrison import category_theory.equivalence import category_theory.types namespace category_theory universes u v class concrete (C : Type u) [category.{v} C] := (fibre_functor : C ⥤ Sort v) (faithfulness : faithful fibre_functor . obviously) instance : concrete (Type u) := { fibre_functor := functor.id _ } end category_theory
6517131f135ac0f8c89cc5df3323bb75c7648d52
b7f22e51856f4989b970961f794f1c435f9b8f78
/tests/lean/run/blast1.lean
a7acda4fabea650f4d365b7cf17a035a21bcba90
[ "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
95
lean
set_option blast.strategy "preprocess" example (a b : Prop) (Ha : a) (Hb : b) : a := by blast
10d2e3d154ace3476a02c1a3033fbf204dec4e00
2eab05920d6eeb06665e1a6df77b3157354316ad
/src/algebra/group/to_additive.lean
3291e73e0b0bd60fd21346174590e91e6688a359
[ "Apache-2.0" ]
permissive
ayush1801/mathlib
78949b9f789f488148142221606bf15c02b960d2
ce164e28f262acbb3de6281b3b03660a9f744e3c
refs/heads/master
1,692,886,907,941
1,635,270,866,000
1,635,270,866,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
24,598
lean
/- Copyright (c) 2017 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Yury Kudryashov, Floris van Doorn -/ import tactic.transform_decl import tactic.algebra /-! # Transport multiplicative to additive This file defines an attribute `to_additive` that can be used to automatically transport theorems and definitions (but not inductive types and structures) from a multiplicative theory to an additive theory. Usage information is contained in the doc string of `to_additive.attr`. ### Missing features * Automatically transport structures and other inductive types. * For structures, automatically generate theorems like `group α ↔ add_group (additive α)`. -/ namespace to_additive open tactic setup_tactic_parser section performance_hack -- see Note [user attribute parameters] local attribute [semireducible] reflected /-- Temporarily change the `has_reflect` instance for `name`. -/ local attribute [instance, priority 9000] meta def hacky_name_reflect : has_reflect name := λ n, `(id %%(expr.const n []) : name) /-- An auxiliary attribute used to store the names of the additive versions of declarations that have been processed by `to_additive`. -/ @[user_attribute] meta def aux_attr : user_attribute (name_map name) name := { name := `to_additive_aux, descr := "Auxiliary attribute for `to_additive`. DON'T USE IT", parser := failed, cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n', do let n := match n' with | name.mk_string s pre := if s = "_to_additive" then pre else n' | _ := n' end, param ← aux_attr.get_param_untyped n', pure $ dict.insert n param.app_arg.const_name) mk_name_map, []⟩ } end performance_hack section extra_attributes /-- An attribute that tells `@[to_additive]` that certain arguments of this definition are not involved when using `@[to_additive]`. This helps the heuristic of `@[to_additive]` by also transforming definitions if `ℕ` or another fixed type occurs as one of these arguments. -/ @[user_attribute] meta def ignore_args_attr : user_attribute (name_map $ list ℕ) (list ℕ) := { name := `to_additive_ignore_args, descr := "Auxiliary attribute for `to_additive` stating that certain arguments are not additivized.", cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n, do param ← ignore_args_attr.get_param_untyped n, -- see Note [user attribute parameters] return $ dict.insert n (param.to_list expr.to_nat).iget) mk_name_map, []⟩, parser := (lean.parser.small_nat)* } /-- An attribute that is automatically added to declarations tagged with `@[to_additive]`, if needed. This attribute tells which argument is the type where this declaration uses the multiplicative structure. If there are multiple argument, we typically tag the first one. If this argument contains a fixed type, this declaration will note be additivized. See the Heuristics section of `to_additive.attr` for more details. If a declaration is not tagged, it is presumed that the first argument is relevant. `@[to_additive]` uses the function `to_additive.first_multiplicative_arg` to automatically tag declarations. It is ok to update it manually if the automatic tagging made an error. Implementation note: we only allow exactly 1 relevant argument, even though some declarations (like `prod.group`) have multiple arguments with a multiplicative structure on it. The reason is that whether we additivize a declaration is an all-or-nothing decision, and if we will not be able to additivize declarations that (e.g.) talk about multiplication on `ℕ × α` anyway. Warning: adding `@[to_additive_reorder]` with an equal or smaller number than the number in this attribute is currently not supported. -/ @[user_attribute] meta def relevant_arg_attr : user_attribute (name_map ℕ) ℕ := { name := `to_additive_relevant_arg, descr := "Auxiliary attribute for `to_additive` stating which arguments are the types with a " ++ "multiplicative structure.", cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n, do param ← relevant_arg_attr.get_param_untyped n, -- see Note [user attribute parameters] -- we subtract 1 from the values provided by the user. return $ dict.insert n $ param.to_nat.iget.pred) mk_name_map, []⟩, parser := lean.parser.small_nat } /-- An attribute that stores all the declarations that needs their arguments reordered when applying `@[to_additive]`. Currently, we only support swapping consecutive arguments. The list of the natural numbers contains the positions of the first of the two arguments to be swapped. If the first two arguments are swapped, the first two universe variables are also swapped. Example: `@[to_additive_reorder 1 4]` swaps the first two arguments and the arguments in positions 4 and 5. -/ @[user_attribute] meta def reorder_attr : user_attribute (name_map $ list ℕ) (list ℕ) := { name := `to_additive_reorder, descr := "Auxiliary attribute for `to_additive` that stores arguments that need to be reordered.", cache_cfg := ⟨λ ns, ns.mfoldl (λ dict n, do param ← reorder_attr.get_param_untyped n, -- see Note [user attribute parameters] return $ dict.insert n (param.to_list expr.to_nat).iget) mk_name_map, []⟩, parser := do l ← (lean.parser.small_nat)*, guard (l.all (≠ 0)) <|> exceptional.fail "The reorder positions must be positive", return l } end extra_attributes /-- Find the first argument of `nm` that has a multiplicative type-class on it. Returns 1 if there are no types with a multiplicative class as arguments. E.g. `prod.group` returns 1, and `pi.has_one` returns 2. -/ meta def first_multiplicative_arg (nm : name) : tactic ℕ := do d ← get_decl nm, let (es, _) := d.type.pi_binders, l ← es.mmap_with_index $ λ n bi, do { let tgt := bi.type.pi_codomain, let n_bi := bi.type.pi_binders.fst.length, tt ← has_attribute' `to_additive tgt.get_app_fn.const_name | return none, let n2 := tgt.get_app_args.head.get_app_fn.match_var.map $ λ m, n + n_bi - m, return $ n2 }, let l := l.reduce_option, return $ if l = [] then 1 else l.foldr min l.head /-- A command that can be used to have future uses of `to_additive` change the `src` namespace to the `tgt` namespace. For example: ``` run_cmd to_additive.map_namespace `quotient_group `quotient_add_group ``` Later uses of `to_additive` on declarations in the `quotient_group` namespace will be created in the `quotient_add_group` namespaces. -/ meta def map_namespace (src tgt : name) : command := do let n := src.mk_string "_to_additive", let decl := declaration.thm n [] `(unit) (pure (reflect ())), add_decl decl, aux_attr.set n tgt tt /-- `value_type` is the type of the arguments that can be provided to `to_additive`. `to_additive.parser` parses the provided arguments: * `replace_all`: replace all multiplicative declarations, do not use the heuristic. * `trace`: output the generated additive declaration. * `tgt : name`: the name of the target (the additive declaration). * `doc`: an optional doc string. * if `allow_auto_name` is `ff` (default) then `@[to_additive]` will check whether the given name can be auto-generated. -/ @[derive has_reflect, derive inhabited] structure value_type : Type := (replace_all : bool) (trace : bool) (tgt : name) (doc : option string) (allow_auto_name : bool) /-- `add_comm_prefix x s` returns `"comm_" ++ s` if `x = tt` and `s` otherwise. -/ meta def add_comm_prefix : bool → string → string | tt s := "comm_" ++ s | ff s := s /-- Dictionary used by `to_additive.guess_name` to autogenerate names. -/ meta def tr : bool → list string → list string | is_comm ("one" :: "le" :: s) := add_comm_prefix is_comm "nonneg" :: tr ff s | is_comm ("one" :: "lt" :: s) := add_comm_prefix is_comm "pos" :: tr ff s | is_comm ("le" :: "one" :: s) := add_comm_prefix is_comm "nonpos" :: tr ff s | is_comm ("lt" :: "one" :: s) := add_comm_prefix is_comm "neg" :: tr ff s | is_comm ("mul" :: "support" :: s) := add_comm_prefix is_comm "support" :: tr ff s | is_comm ("mul" :: "indicator" :: s) := add_comm_prefix is_comm "indicator" :: tr ff s | is_comm ("mul" :: s) := add_comm_prefix is_comm "add" :: tr ff s | is_comm ("smul" :: s) := add_comm_prefix is_comm "vadd" :: tr ff s | is_comm ("inv" :: s) := add_comm_prefix is_comm "neg" :: tr ff s | is_comm ("div" :: s) := add_comm_prefix is_comm "sub" :: tr ff s | is_comm ("one" :: s) := add_comm_prefix is_comm "zero" :: tr ff s | is_comm ("prod" :: s) := add_comm_prefix is_comm "sum" :: tr ff s | is_comm ("finprod" :: s) := add_comm_prefix is_comm "finsum" :: tr ff s | is_comm ("npow" :: s) := add_comm_prefix is_comm "nsmul" :: tr ff s | is_comm ("gpow" :: s) := add_comm_prefix is_comm "gsmul" :: tr ff s | is_comm ("monoid" :: s) := ("add_" ++ add_comm_prefix is_comm "monoid") :: tr ff s | is_comm ("submonoid" :: s) := ("add_" ++ add_comm_prefix is_comm "submonoid") :: tr ff s | is_comm ("group" :: s) := ("add_" ++ add_comm_prefix is_comm "group") :: tr ff s | is_comm ("subgroup" :: s) := ("add_" ++ add_comm_prefix is_comm "subgroup") :: tr ff s | is_comm ("semigroup" :: s) := ("add_" ++ add_comm_prefix is_comm "semigroup") :: tr ff s | is_comm ("magma" :: s) := ("add_" ++ add_comm_prefix is_comm "magma") :: tr ff s | is_comm ("haar" :: s) := ("add_" ++ add_comm_prefix is_comm "haar") :: tr ff s | is_comm ("prehaar" :: s) := ("add_" ++ add_comm_prefix is_comm "prehaar") :: tr ff s | is_comm ("comm" :: s) := tr tt s | is_comm (x :: s) := (add_comm_prefix is_comm x :: tr ff s) | tt [] := ["comm"] | ff [] := [] /-- Autogenerate target name for `to_additive`. -/ meta def guess_name : string → string := string.map_tokens ''' $ λ s, string.intercalate (string.singleton '_') $ tr ff (s.split_on '_') /-- Return the provided target name or autogenerate one if one was not provided. -/ meta def target_name (src tgt : name) (dict : name_map name) (allow_auto_name : bool) : tactic name := (if tgt.get_prefix ≠ name.anonymous ∨ allow_auto_name -- `tgt` is a full name then pure tgt else match src with | (name.mk_string s pre) := do let tgt_auto := guess_name s, guard (tgt.to_string ≠ tgt_auto ∨ tgt = src) <|> trace ("`to_additive " ++ src.to_string ++ "`: correctly autogenerated target " ++ "name, you may remove the explicit " ++ tgt_auto ++ " argument."), pure $ name.mk_string (if tgt = name.anonymous then tgt_auto else tgt.to_string) (pre.map_prefix dict.find) | _ := fail ("to_additive: can't transport " ++ src.to_string) end) >>= (λ res, if res = src ∧ tgt ≠ src then fail ("to_additive: can't transport " ++ src.to_string ++ " to itself. Give the desired additive name explicitly using `@[to_additive additive_name]`. ") else pure res) /-- the parser for the arguments to `to_additive`. -/ meta def parser : lean.parser value_type := do bang ← option.is_some <$> (tk "!")?, ques ← option.is_some <$> (tk "?")?, tgt ← ident?, e ← texpr?, doc ← match e with | some pe := some <$> ((to_expr pe >>= eval_expr string) : tactic string) | none := pure none end, return ⟨bang, ques, tgt.get_or_else name.anonymous, doc, ff⟩ private meta def proceed_fields_aux (src tgt : name) (prio : ℕ) (f : name → tactic (list string)) : command := do src_fields ← f src, tgt_fields ← f tgt, guard (src_fields.length = tgt_fields.length) <|> fail ("Failed to map fields of " ++ src.to_string), (src_fields.zip tgt_fields).mmap' $ λ names, guard (names.fst = names.snd) <|> aux_attr.set (src.append names.fst) (tgt.append names.snd) tt prio /-- Add the `aux_attr` attribute to the structure fields of `src` so that future uses of `to_additive` will map them to the corresponding `tgt` fields. -/ meta def proceed_fields (env : environment) (src tgt : name) (prio : ℕ) : command := let aux := proceed_fields_aux src tgt prio in do aux (λ n, pure $ list.map name.to_string $ (env.structure_fields n).get_or_else []) >> aux (λ n, (list.map (λ (x : name), "to_" ++ x.to_string) <$> get_tagged_ancestors n)) >> aux (λ n, (env.constructors_of n).mmap $ λ cs, match cs with | (name.mk_string s pre) := (guard (pre = n) <|> fail "Bad constructor name") >> pure s | _ := fail "Bad constructor name" end) /-- The attribute `to_additive` can be used to automatically transport theorems and definitions (but not inductive types and structures) from a multiplicative theory to an additive theory. To use this attribute, just write: ``` @[to_additive] theorem mul_comm' {α} [comm_semigroup α] (x y : α) : x * y = y * x := comm_semigroup.mul_comm ``` This code will generate a theorem named `add_comm'`. It is also possible to manually specify the name of the new declaration, and provide a documentation string: ``` @[to_additive add_foo "add_foo doc string"] /-- foo doc string -/ theorem foo := sorry ``` The transport tries to do the right thing in most cases using several heuristics described below. However, in some cases it fails, and requires manual intervention. If the declaration to be transported has attributes which need to be copied to the additive version, then `to_additive` should come last: ``` @[simp, to_additive] lemma mul_one' {G : Type*} [group G] (x : G) : x * 1 = x := mul_one x ``` The exception to this rule is the `simps` attribute, which should come after `to_additive`: ``` @[to_additive, simps] instance {M N} [has_mul M] [has_mul N] : has_mul (M × N) := ⟨λ p q, ⟨p.1 * q.1, p.2 * q.2⟩⟩ ``` ## Implementation notes The transport process generally works by taking all the names of identifiers appearing in the name, type, and body of a declaration and creating a new declaration by mapping those names to additive versions using a simple string-based dictionary and also using all declarations that have previously been labeled with `to_additive`. In the `mul_comm'` example above, `to_additive` maps: * `mul_comm'` to `add_comm'`, * `comm_semigroup` to `add_comm_semigroup`, * `x * y` to `x + y` and `y * x` to `y + x`, and * `comm_semigroup.mul_comm'` to `add_comm_semigroup.add_comm'`. ### Heuristics `to_additive` uses heuristics to determine whether a particular identifier has to be mapped to its additive version. The basic heuristic is * Only map an identifier to its additive version if its first argument doesn't contain any unapplied identifiers. Examples: * `@has_mul.mul ℕ n m` (i.e. `(n * m : ℕ)`) will not change to `+`, since its first argument is `ℕ`, an identifier not applied to any arguments. * `@has_mul.mul (α × β) x y` will change to `+`. It's first argument contains only the identifier `prod`, but this is applied to arguments, `α` and `β`. * `@has_mul.mul (α × ℤ) x y` will not change to `+`, since its first argument contains `ℤ`. The reasoning behind the heuristic is that the first argument is the type which is "additivized", and this usually doesn't make sense if this is on a fixed type. There are some exceptions to this heuristic: * Identifiers that have the `@[to_additive]` attribute are ignored. For example, multiplication in `↥Semigroup` is replaced by addition in `↥AddSemigroup`. * If an identifier `d` has attribute `@[to_additive_relevant_arg n]` then the argument in position `n` is checked for a fixed type, instead of checking the first argument. `@[to_additive]` will automatically add the attribute `@[to_additive_relevant_arg n]` to a declaration when the first argument has no multiplicative type-class, but argument `n` does. * If an identifier has attribute `@[to_additive_ignore_args n1 n2 ...]` then all the arguments in positions `n1`, `n2`, ... will not be checked for unapplied identifiers (start counting from 1). For example, `times_cont_mdiff_map` has attribute `@[to_additive_ignore_args 21]`, which means that its 21st argument `(n : with_top ℕ)` can contain `ℕ` (usually in the form `has_top.top ℕ ...`) and still be additivized. So `@has_mul.mul (C^∞⟮I, N; I', G⟯) _ f g` will be additivized. ### Troubleshooting If `@[to_additive]` fails because the additive declaration raises a type mismatch, there are various things you can try. The first thing to do is to figure out what `@[to_additive]` did wrong by looking at the type mismatch error. * Option 1: It additivized a declaration `d` that should remain multiplicative. Solution: * Make sure the first argument of `d` is a type with a multiplicative structure. If not, can you reorder the (implicit) arguments of `d` so that the first argument becomes a type with a multiplicative structure (and not some indexing type)? The reason is that `@[to_additive]` doesn't additivize declarations if their first argument contains fixed types like `ℕ` or `ℝ`. See section Heuristics. If the first argument is not the argument with a multiplicative type-class, `@[to_additive]` should have automatically added the attribute `@[to_additive_relevant_arg]` to the declaration. You can test this by running the following (where `d` is the full name of the declaration): ``` run_cmd to_additive.relevant_arg_attr.get_param `d >>= tactic.trace ``` The expected output is `n` where the `n`-th argument of `d` is a type (family) with a multiplicative structure on it. If you get a different output (or a failure), you could add the attribute `@[to_additive_relevant_arg n]` manually, where `n` is an argument with a multiplicative structure. * Option 2: It didn't additivize a declaration that should be additivized. This happened because the heuristic applied, and the first argument contains a fixed type, like `ℕ` or `ℝ`. Solutions: * If the fixed type has an additive counterpart (like `↥Semigroup`), give it the `@[to_additive]` attribute. * If the fixed type occurs inside the `k`-th argument of a declaration `d`, and the `k`-th argument is not connected to the multiplicative structure on `d`, consider adding attribute `[to_additive_ignore_args k]` to `d`. * If you want to disable the heuristic and replace all multiplicative identifiers with their additive counterpart, use `@[to_additive!]`. * Option 3: Arguments / universe levels are incorrectly ordered in the additive version. This likely only happens when the multiplicative declaration involves `pow`/`^`. Solutions: * Ensure that the order of arguments of all relevant declarations are the same for the multiplicative and additive version. This might mean that arguments have an "unnatural" order (e.g. `monoid.npow n x` corresponds to `x ^ n`, but it is convenient that `monoid.npow` has this argument order, since it matches `add_monoid.nsmul n x`. * If this is not possible, add the `[to_additive_reorder k]` to the multiplicative declaration to indicate that the `k`-th and `(k+1)`-st arguments are reordered in the additive version. If neither of these solutions work, and `to_additive` is unable to automatically generate the additive version of a declaration, manually write and prove the additive version. Often the proof of a lemma/theorem can just be the multiplicative version of the lemma applied to `multiplicative G`. Afterwards, apply the attribute manually: ``` attribute [to_additive foo_add_bar] foo_bar ``` This will allow future uses of `to_additive` to recognize that `foo_bar` should be replaced with `foo_add_bar`. ### Handling of hidden definitions Before transporting the “main” declaration `src`, `to_additive` first scans its type and value for names starting with `src`, and transports them. This includes auxiliary definitions like `src._match_1`, `src._proof_1`. After transporting the “main” declaration, `to_additive` transports its equational lemmas. ### Structure fields and constructors If `src` is a structure, then `to_additive` automatically adds structure fields to its mapping, and similarly for constructors of inductive types. For new structures this means that `to_additive` automatically handles coercions, and for old structures it does the same, if ancestry information is present in `@[ancestor]` attributes. The `ancestor` attribute must come before the `to_additive` attribute, and it is essential that the order of the base structures passed to `ancestor` matches between the multiplicative and additive versions of the structure. ### Name generation * If `@[to_additive]` is called without a `name` argument, then the new name is autogenerated. First, it takes the longest prefix of the source name that is already known to `to_additive`, and replaces this prefix with its additive counterpart. Second, it takes the last part of the name (i.e., after the last dot), and replaces common name parts (“mul”, “one”, “inv”, “prod”) with their additive versions. * Namespaces can be transformed using `map_namespace`. For example: ``` run_cmd to_additive.map_namespace `quotient_group `quotient_add_group ``` Later uses of `to_additive` on declarations in the `quotient_group` namespace will be created in the `quotient_add_group` namespaces. * If `@[to_additive]` is called with a `name` argument `new_name` /without a dot/, then `to_additive` updates the prefix as described above, then replaces the last part of the name with `new_name`. * If `@[to_additive]` is called with a `name` argument `new_namespace.new_name` /with a dot/, then `to_additive` uses this new name as is. As a safety check, in the first case `to_additive` double checks that the new name differs from the original one. -/ @[user_attribute] protected meta def attr : user_attribute unit value_type := { name := `to_additive, descr := "Transport multiplicative to additive", parser := parser, after_set := some $ λ src prio persistent, do guard persistent <|> fail "`to_additive` can't be used as a local attribute", env ← get_env, val ← attr.get_param src, dict ← aux_attr.get_cache, ignore ← ignore_args_attr.get_cache, relevant ← relevant_arg_attr.get_cache, reorder ← reorder_attr.get_cache, tgt ← target_name src val.tgt dict val.allow_auto_name, aux_attr.set src tgt tt, let dict := dict.insert src tgt, first_mult_arg ← first_multiplicative_arg src, when (first_mult_arg ≠ 1) $ relevant_arg_attr.set src first_mult_arg tt, if env.contains tgt then proceed_fields env src tgt prio else do transform_decl_with_prefix_dict dict val.replace_all val.trace relevant ignore reorder src tgt [`reducible, `_refl_lemma, `simp, `norm_cast, `instance, `refl, `symm, `trans, `elab_as_eliminator, `no_rsimp, `continuity, `ext, `ematch, `measurability, `alias, `_ext_core, `_ext_lemma_core, `nolint], mwhen (has_attribute' `simps src) (trace "Apply the simps attribute after the to_additive attribute"), mwhen (has_attribute' `mono src) (trace $ "to_additive does not work with mono, apply the mono attribute to both" ++ "versions after"), match val.doc with | some doc := add_doc_string tgt doc | none := skip end } add_tactic_doc { name := "to_additive", category := doc_category.attr, decl_names := [`to_additive.attr], tags := ["transport", "environment", "lemma derivation"] } end to_additive /- map operations -/ attribute [to_additive] has_mul has_one has_inv has_div /- the following types are supported by `@[to_additive]` and mapped to themselves. -/ attribute [to_additive empty] empty attribute [to_additive pempty] pempty attribute [to_additive punit] punit attribute [to_additive unit] unit
4981c5f18bd4bcd617a96ab4ed7b3fd57007c865
cf39355caa609c0f33405126beee2739aa3cb77e
/tests/lean/run/1782.lean
be4062ff69865a10d7e5b0bcff1d30ba926bf4c7
[ "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
706
lean
mutual inductive a, b, c with a : Type | foo : a with b : Type | bar : b with c : Type | baz : c mutual def f, g, h with f : a → nat | a.foo := 0 with g : b → nat | b.bar := 1 with h : c → nat | c.baz := 2 example : f a.foo = 0 := by simp [f] example : g b.bar = 1 := by simp [g] example : h c.baz = 2 := by simp [h] mutual def f_1, f_2, f_3, f_4 with f_1 : a → nat | a.foo := 0 with f_2 : b → nat | b.bar := 1 with f_3 : c → nat | c.baz := 2 with f_4 : nat → nat | 0 := 3 | _ := 4 example : f_1 a.foo = 0 := by simp [f_1] example : f_2 b.bar = 1 := by simp [f_2] example : f_3 c.baz = 2 := by simp [f_3] example : f_4 0 = 3 := by simp [f_4] example : f_4 1 = 4 := by simp [f_4]
20d071434cab61952ad13e6d36fa15f46976b063
35677d2df3f081738fa6b08138e03ee36bc33cad
/src/category_theory/adjunction/limits.lean
560c7e4f92294146df7ede85c0be774d2d9a081d
[ "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
7,687
lean
/- Copyright (c) 2019 Reid Barton. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Reid Barton, Johan Commelin -/ import category_theory.adjunction.basic import category_theory.limits.preserves open opposite namespace category_theory.adjunction open category_theory open category_theory.functor open category_theory.limits universes u₁ u₂ v variables {C : Type u₁} [𝒞 : category.{v} C] {D : Type u₂} [𝒟 : category.{v} D] include 𝒞 𝒟 variables {F : C ⥤ D} {G : D ⥤ C} (adj : F ⊣ G) include adj section preservation_colimits variables {J : Type v} [small_category J] (K : J ⥤ C) def functoriality_right_adjoint : cocone (K ⋙ F) ⥤ cocone K := (cocones.functoriality G) ⋙ (cocones.precompose (K.right_unitor.inv ≫ (whisker_left K adj.unit) ≫ (associator _ _ _).inv)) local attribute [reducible] functoriality_right_adjoint @[simps] def functoriality_unit : 𝟭 (cocone K) ⟶ cocones.functoriality F ⋙ functoriality_right_adjoint adj K := { app := λ c, { hom := adj.unit.app c.X } } @[simps] def functoriality_counit : functoriality_right_adjoint adj K ⋙ cocones.functoriality F ⟶ 𝟭 (cocone (K ⋙ F)) := { app := λ c, { hom := adj.counit.app c.X } } def functoriality_is_left_adjoint : is_left_adjoint (@cocones.functoriality _ _ _ _ K _ _ F) := { right := functoriality_right_adjoint adj K, adj := mk_of_unit_counit { unit := functoriality_unit adj K, counit := functoriality_counit adj K } } /-- A left adjoint preserves colimits. -/ def left_adjoint_preserves_colimits : preserves_colimits F := { preserves_colimits_of_shape := λ J 𝒥, { preserves_colimit := λ F, by exactI { preserves := λ c hc, is_colimit.iso_unique_cocone_morphism.inv (λ s, (((adj.functoriality_is_left_adjoint _).adj).hom_equiv _ _).unique_of_equiv $ is_colimit.iso_unique_cocone_morphism.hom hc _ ) } } }. omit adj @[priority 100] -- see Note [lower instance priority] instance is_equivalence_preserves_colimits (E : C ⥤ D) [is_equivalence E] : preserves_colimits E := left_adjoint_preserves_colimits E.adjunction -- verify the preserve_colimits instance works as expected: example (E : C ⥤ D) [is_equivalence E] (c : cocone K) (h : is_colimit c) : is_colimit (E.map_cocone c) := preserves_colimit.preserves h instance has_colimit_comp_equivalence (E : C ⥤ D) [is_equivalence E] [has_colimit K] : has_colimit (K ⋙ E) := { cocone := E.map_cocone (colimit.cocone K), is_colimit := preserves_colimit.preserves (colimit.is_colimit K) } def has_colimit_of_comp_equivalence (E : C ⥤ D) [is_equivalence E] [has_colimit (K ⋙ E)] : has_colimit K := @has_colimit_of_iso _ _ _ _ (K ⋙ E ⋙ inv E) K (@adjunction.has_colimit_comp_equivalence _ _ _ _ _ _ (K ⋙ E) (inv E) _ _) ((functor.right_unitor _).symm ≪≫ (iso_whisker_left K (fun_inv_id E)).symm) end preservation_colimits section preservation_limits variables {J : Type v} [small_category J] (K : J ⥤ D) def functoriality_left_adjoint : cone (K ⋙ G) ⥤ cone K := (cones.functoriality F) ⋙ (cones.postcompose ((associator _ _ _).hom ≫ (whisker_left K adj.counit) ≫ K.right_unitor.hom)) local attribute [reducible] functoriality_left_adjoint @[simps] def functoriality_unit' : 𝟭 (cone (K ⋙ G)) ⟶ functoriality_left_adjoint adj K ⋙ cones.functoriality G := { app := λ c, { hom := adj.unit.app c.X, } } @[simps] def functoriality_counit' : cones.functoriality G ⋙ functoriality_left_adjoint adj K ⟶ 𝟭 (cone K) := { app := λ c, { hom := adj.counit.app c.X, } } def functoriality_is_right_adjoint : is_right_adjoint (@cones.functoriality _ _ _ _ K _ _ G) := { left := functoriality_left_adjoint adj K, adj := mk_of_unit_counit { unit := functoriality_unit' adj K, counit := functoriality_counit' adj K } } /-- A right adjoint preserves limits. -/ def right_adjoint_preserves_limits : preserves_limits G := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ K, by exactI { preserves := λ c hc, is_limit.iso_unique_cone_morphism.inv (λ s, (((adj.functoriality_is_right_adjoint _).adj).hom_equiv _ _).symm.unique_of_equiv $ is_limit.iso_unique_cone_morphism.hom hc _) } } }. omit adj @[priority 100] -- see Note [lower instance priority] instance is_equivalence_preserves_limits (E : D ⥤ C) [is_equivalence E] : preserves_limits E := right_adjoint_preserves_limits E.inv.adjunction -- verify the preserve_limits instance works as expected: example (E : D ⥤ C) [is_equivalence E] (c : cone K) [h : is_limit c] : is_limit (E.map_cone c) := preserves_limit.preserves h instance has_limit_comp_equivalence (E : D ⥤ C) [is_equivalence E] [has_limit K] : has_limit (K ⋙ E) := { cone := E.map_cone (limit.cone K), is_limit := preserves_limit.preserves (limit.is_limit K) } def has_limit_of_comp_equivalence (E : D ⥤ C) [is_equivalence E] [has_limit (K ⋙ E)] : has_limit K := @has_limit_of_iso _ _ _ _ (K ⋙ E ⋙ inv E) K (@adjunction.has_limit_comp_equivalence _ _ _ _ _ _ (K ⋙ E) (inv E) _ _) ((iso_whisker_left K (fun_inv_id E)) ≪≫ (functor.right_unitor _)) end preservation_limits /-- auxilliary construction for `cocones_iso` -/ @[simps] def cocones_iso_component_hom {J : Type v} [small_category J] {K : J ⥤ C} (Y : D) (t : ((cocones J D).obj (op (K ⋙ F))).obj Y) : (G ⋙ (cocones J C).obj (op K)).obj Y := { app := λ j, (adj.hom_equiv (K.obj j) Y) (t.app j), naturality' := λ j j' f, by erw [← adj.hom_equiv_naturality_left, t.naturality]; dsimp; simp } /-- auxilliary construction for `cocones_iso` -/ @[simps] def cocones_iso_component_inv {J : Type v} [small_category J] {K : J ⥤ C} (Y : D) (t : (G ⋙ (cocones J C).obj (op K)).obj Y) : ((cocones J D).obj (op (K ⋙ F))).obj Y := { app := λ j, (adj.hom_equiv (K.obj j) Y).symm (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_left_symm, ← adj.hom_equiv_naturality_right_symm, t.naturality], dsimp, simp end } -- Note: this is natural in K, but we do not yet have the tools to formulate that. def cocones_iso {J : Type v} [small_category J] {K : J ⥤ C} : (cocones J D).obj (op (K ⋙ F)) ≅ G ⋙ ((cocones J C).obj (op K)) := nat_iso.of_components (λ Y, { hom := cocones_iso_component_hom adj Y, inv := cocones_iso_component_inv adj Y, }) (by tidy) /-- auxilliary construction for `cones_iso` -/ @[simps] def cones_iso_component_hom {J : Type v} [small_category J] {K : J ⥤ D} (X : Cᵒᵖ) (t : (functor.op F ⋙ (cones J D).obj K).obj X) : ((cones J C).obj (K ⋙ G)).obj X := { app := λ j, (adj.hom_equiv (unop X) (K.obj j)) (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_right, ← t.naturality, category.id_comp, category.id_comp], refl end } /-- auxilliary construction for `cones_iso` -/ @[simps] def cones_iso_component_inv {J : Type v} [small_category J] {K : J ⥤ D} (X : Cᵒᵖ) (t : ((cones J C).obj (K ⋙ G)).obj X) : (functor.op F ⋙ (cones J D).obj K).obj X := { app := λ j, (adj.hom_equiv (unop X) (K.obj j)).symm (t.app j), naturality' := λ j j' f, begin erw [← adj.hom_equiv_naturality_right_symm, ← t.naturality, category.id_comp, category.id_comp] end } -- Note: this is natural in K, but we do not yet have the tools to formulate that. def cones_iso {J : Type v} [small_category J] {K : J ⥤ D} : F.op ⋙ ((cones J D).obj K) ≅ (cones J C).obj (K ⋙ G) := nat_iso.of_components (λ X, { hom := cones_iso_component_hom adj X, inv := cones_iso_component_inv adj X, } ) (by tidy) end category_theory.adjunction
18a64a7305c3cd850a36ca4dd6a9d079e99f15df
94e33a31faa76775069b071adea97e86e218a8ee
/src/set_theory/game/birthday.lean
48358f5a9e29ce9f8669b191c6191cf7f7ac41f9
[ "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
4,463
lean
/- Copyright (c) 2022 Violeta Hernández Palacios. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Violeta Hernández Palacios -/ import set_theory.game.ordinal /-! # Birthdays of games The birthday of a game is an ordinal that represents at which "step" the game was constructed. We define it recursively as the least ordinal larger than the birthdays of its left and right games. We prove the basic properties about these. # Main declarations - `pgame.birthday`: The birthday of a pre-game. # Todo - Define the birthdays of `game`s and `surreal`s. - Characterize the birthdays of basic arithmetical operations. -/ universe u open ordinal open_locale pgame namespace pgame /-- The birthday of a pre-game is inductively defined as the least strict upper bound of the birthdays of its left and right games. It may be thought as the "step" in which a certain game is constructed. -/ noncomputable def birthday : pgame.{u} → ordinal.{u} | ⟨xl, xr, xL, xR⟩ := max (lsub.{u u} $ λ i, birthday (xL i)) (lsub.{u u} $ λ i, birthday (xR i)) theorem birthday_def (x : pgame) : birthday x = max (lsub.{u u} (λ i, birthday (x.move_left i))) (lsub.{u u} (λ i, birthday (x.move_right i))) := by { cases x, rw birthday, refl } theorem birthday_move_left_lt {x : pgame} (i : x.left_moves) : (x.move_left i).birthday < x.birthday := by { cases x, rw birthday, exact lt_max_of_lt_left (lt_lsub _ i) } theorem birthday_move_right_lt {x : pgame} (i : x.right_moves) : (x.move_right i).birthday < x.birthday := by { cases x, rw birthday, exact lt_max_of_lt_right (lt_lsub _ i) } theorem lt_birthday_iff {x : pgame} {o : ordinal} : o < x.birthday ↔ (∃ i : x.left_moves, o ≤ (x.move_left i).birthday) ∨ (∃ i : x.right_moves, o ≤ (x.move_right i).birthday) := begin split, { rw birthday_def, intro h, cases lt_max_iff.1 h with h' h', { left, rwa lt_lsub_iff at h' }, { right, rwa lt_lsub_iff at h' } }, { rintro (⟨i, hi⟩ | ⟨i, hi⟩), { exact hi.trans_lt (birthday_move_left_lt i) }, { exact hi.trans_lt (birthday_move_right_lt i) } } end theorem relabelling.birthday_congr : ∀ {x y : pgame.{u}}, x ≡r y → birthday x = birthday y | ⟨xl, xr, xL, xR⟩ ⟨yl, yr, yL, yR⟩ ⟨L, R, hL, hR⟩ := begin rw [birthday, birthday], congr' 1, all_goals { apply lsub_eq_of_range_eq.{u u u}, ext i, split }, { rintro ⟨j, rfl⟩, exact ⟨L j, (hL j).birthday_congr.symm⟩ }, { rintro ⟨j, rfl⟩, refine ⟨L.symm j, relabelling.birthday_congr _⟩, convert hL (L.symm j), rw L.apply_symm_apply }, { rintro ⟨j, rfl⟩, refine ⟨R j, (relabelling.birthday_congr _).symm⟩, convert hR (R j), rw R.symm_apply_apply }, { rintro ⟨j, rfl⟩, exact ⟨R.symm j, (hR j).birthday_congr⟩ } end using_well_founded { dec_tac := pgame_wf_tac } @[simp] theorem birthday_add_zero (x : pgame) : birthday (x + 0) = birthday x := (add_zero_relabelling x).birthday_congr @[simp] theorem birthday_zero_add (x : pgame) : birthday (0 + x) = birthday x := (zero_add_relabelling x).birthday_congr @[simp] theorem birthday_eq_zero (x : pgame) : birthday x = 0 ↔ is_empty x.left_moves ∧ is_empty x.right_moves := by rw [birthday_def, max_eq_zero, lsub_eq_zero_iff, lsub_eq_zero_iff] @[simp] theorem birthday_zero : birthday 0 = 0 := by simp [pempty.is_empty] @[simp] theorem birthday_one : birthday 1 = 1 := by { rw birthday_def, simp } @[simp] theorem birthday_star : birthday star = 1 := by { rw birthday_def, simp } @[simp] theorem neg_birthday : ∀ x : pgame, (-x).birthday = x.birthday | ⟨xl, xr, xL, xR⟩ := begin rw [birthday_def, birthday_def, max_comm], congr; funext; apply neg_birthday end @[simp] theorem to_pgame_birthday (o : ordinal) : o.to_pgame.birthday = o := begin induction o using ordinal.induction with o IH, rw [to_pgame_def, pgame.birthday], simp only [lsub_empty, max_zero_right], nth_rewrite 0 ←lsub_typein o, congr' with x, exact IH _ (typein_lt_self x) end theorem le_birthday : ∀ x : pgame, x ≤ x.birthday.to_pgame | ⟨xl, _, xL, _⟩ := le_def.2 ⟨λ i, or.inl ⟨to_left_moves_to_pgame ⟨_, birthday_move_left_lt i⟩, by simp [le_birthday (xL i)]⟩, is_empty_elim⟩ theorem neg_birthday_le (x : pgame) : -x.birthday.to_pgame ≤ x := let h := le_birthday (-x) in by rwa [neg_birthday, neg_le_iff] at h end pgame
0c472d9568629a61523397f048654a947e9ccefe
01f6b345a06ece970e589d4bbc68ee8b9b2cf58a
/src/minpoly.lean
ad7d1094dc998e27430d82d6c1ecff1e93e6dcb3
[]
no_license
mariainesdff/norm_extensions_journal_submission
6077acb98a7200de4553e653d81d54fb5d2314c8
d396130660935464fbc683f9aaf37fff8a890baa
refs/heads/master
1,686,685,693,347
1,684,065,115,000
1,684,065,115,000
603,823,641
0
0
null
null
null
null
UTF-8
Lean
false
false
6,195
lean
/- Copyright (c) 2023 María Inés de Frutos-Fernández. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: María Inés de Frutos-Fernández -/ import field_theory.normal /-! # Minpoly We prove some auxiliary lemmas about minimal polynomials. ## Main Definitions * `minpoly.alg_equiv` : the canonical `alg_equiv` between `K⟮x⟯`and `K⟮y⟯`, sending `x` to `y`, where `x` and `y` have the same minimal polynomial over `K`, sending `x` to `y`. ## Main Results * `minpoly.eq_of_conj` : For any `σ : L ≃ₐ[K] L` and `x : L`, the minimal polynomials of `x` and `σ x` are equal. * `minpoly.conj_of_root` :If `y : L` is a root of `minpoly K x`, then we can find `σ : L ≃ₐ[K] L)` with `σ x = y`. That is, `x` and `y` are Galois conjugates. ## Tags minpoly, adjoin_root, conj -/ noncomputable theory open polynomial intermediate_field alg_equiv open_locale polynomial section minpoly variables {K L : Type*} [field K] [field L] [algebra K L] namespace adjoin_root /-- The canonical algebraic equivalence between `adjoin_root p` and `adjoin_root q`, where the two polynomial `p q : K[X]` are equal.-/ def id_alg_equiv {p q : K[X]} (hp : p ≠ 0) (hq : q ≠ 0) (h_eq : p = q) : adjoin_root p ≃ₐ[K] adjoin_root q := of_alg_hom (lift_hom p (root q) (by rw [h_eq, aeval_eq, mk_self])) (lift_hom q (root p) (by rw [h_eq, aeval_eq, mk_self])) (power_basis.alg_hom_ext (power_basis hq) (by rw [power_basis_gen hq, alg_hom.coe_comp, function.comp_app, lift_hom_root, lift_hom_root, alg_hom.coe_id, id.def])) (power_basis.alg_hom_ext (power_basis hp) (by rw [power_basis_gen hp, alg_hom.coe_comp, function.comp_app, lift_hom_root, lift_hom_root, alg_hom.coe_id, id.def])) lemma id_alg_equiv_def {p q : K[X]} (hp : p ≠ 0) (hq : q ≠ 0) (h_eq : p = q) : (id_alg_equiv hp hq h_eq).to_fun = (lift_hom p (root q) (by rw [h_eq, aeval_eq, mk_self])) := rfl /-- `id_alg_equiv` sends `adjoin_root.root p` to `adjoin_root.root q`. -/ lemma id_alg_equiv_apply_root {p q : K[X]} (hp : p ≠ 0) (hq : q ≠ 0) (h_eq : p = q) : id_alg_equiv hp hq h_eq (root p) = root q := by rw [← to_fun_eq_coe, id_alg_equiv_def, lift_hom_root] end adjoin_root namespace minpoly /-- Given any `σ : L ≃ₐ[K] L` and any `x : L`, the minimal polynomial of `x` vanishes at `σ x`. -/ @[simp] lemma aeval_conj (σ : L ≃ₐ[K] L) (x : L) : (polynomial.aeval (σ x)) (minpoly K x) = 0 := by rw [polynomial.aeval_alg_equiv, alg_hom.coe_comp, function.comp_app, aeval, map_zero] /-- For any `σ : L ≃ₐ[K] L` and `x : L`, the minimal polynomials of `x` and `σ x` are equal. -/ @[simp] lemma eq_of_conj (h_alg : algebra.is_algebraic K L) (σ : L ≃ₐ[K] L) (x : L) : minpoly K (σ x) = minpoly K x := begin have h_dvd : minpoly K x ∣ minpoly K (σ x), { apply dvd, have hx : σ.symm (σ x) = x := σ.left_inv x, nth_rewrite 0 ← hx, rw [polynomial.aeval_alg_equiv, alg_hom.coe_comp, function.comp_app, aeval, map_zero] }, have h_deg : (minpoly K (σ x)).nat_degree ≤ (minpoly K x).nat_degree, { apply polynomial.nat_degree_le_nat_degree (degree_le_of_ne_zero K _ (ne_zero (is_algebraic_iff_is_integral.mp (h_alg _))) (aeval_conj σ x)) }, exact polynomial.eq_of_monic_of_dvd_of_nat_degree_le (monic (is_algebraic_iff_is_integral.mp (h_alg _))) (monic (is_algebraic_iff_is_integral.mp (h_alg _))) h_dvd h_deg, end /-- The canonical `alg_equiv` between `K⟮x⟯`and `K⟮y⟯`, sending `x` to `y`, where `x` and `y` have the same minimal polynomial over `K`. -/ def alg_equiv (h_alg : algebra.is_algebraic K L) {x y : L} (h_mp : minpoly K x = minpoly K y) : K⟮x⟯ ≃ₐ[K] K⟮y⟯ := trans ((adjoin_root_equiv_adjoin K (is_algebraic_iff_is_integral.mp (h_alg _))).symm) (trans (adjoin_root.id_alg_equiv (ne_zero (is_algebraic_iff_is_integral.mp (h_alg _))) (ne_zero (is_algebraic_iff_is_integral.mp (h_alg _))) h_mp) (adjoin_root_equiv_adjoin K(is_algebraic_iff_is_integral.mp (h_alg _)))) /-- `minpoly.alg_equiv` sends the generator of `K⟮x⟯` to the generator of `K⟮y⟯`. -/ lemma alg_equiv_apply (h_alg : algebra.is_algebraic K L) {x y : L} (h_mp : minpoly K x = minpoly K y) : alg_equiv h_alg h_mp ((adjoin_simple.gen K x)) = (adjoin_simple.gen K y) := begin simp only [alg_equiv], rw [trans_apply, ← adjoin_root_equiv_adjoin_apply_root K (is_algebraic_iff_is_integral.mp (h_alg _)), symm_apply_apply, trans_apply, adjoin_root.id_alg_equiv_apply_root, adjoin_root_equiv_adjoin_apply_root K (is_algebraic_iff_is_integral.mp (h_alg _))], end /-- If `y : L` is a root of `minpoly K x`, then `minpoly K y = minpoly K x`. -/ lemma eq_of_root (h_alg : algebra.is_algebraic K L) {x y : L} (h_ev : (polynomial.aeval y) (minpoly K x) = 0) : minpoly K y = minpoly K x := polynomial.eq_of_monic_of_associated (monic (is_algebraic_iff_is_integral.mp (h_alg _))) (monic (is_algebraic_iff_is_integral.mp (h_alg _))) (irreducible.associated_of_dvd (irreducible (is_algebraic_iff_is_integral.mp (h_alg _))) (irreducible (is_algebraic_iff_is_integral.mp (h_alg _))) (dvd K y h_ev)) /-- If `y : L` is a root of `minpoly K x`, then we can find `σ : L ≃ₐ[K] L)` with `σ x = y`. That is, `x` and `y` are Galois conjugates. -/ lemma conj_of_root (h_alg : algebra.is_algebraic K L) (hn : normal K L) {x y : L} (h_ev : (polynomial.aeval x) (minpoly K y) = 0) : ∃ (σ : L ≃ₐ[K] L), σ x = y := begin set f : K⟮x⟯ ≃ₐ[K] K⟮y⟯ := alg_equiv h_alg (eq_of_root h_alg h_ev), use lift_normal f L, simp_rw ← adjoin_simple.algebra_map_gen K x, rw [lift_normal_commutes f L, alg_equiv_apply, adjoin_simple.algebra_map_gen K y], end /-- If `y : L` is a root of `minpoly K x`, then we can find `σ : L ≃ₐ[K] L)` with `σ y = x`. That is, `x` and `y` are Galois conjugates. -/ lemma conj_of_root' (h_alg : algebra.is_algebraic K L) (hn : normal K L) {x y : L} (h_ev : (polynomial.aeval x) (minpoly K y) = 0) : ∃ (σ : L ≃ₐ[K] L), σ y = x := begin obtain ⟨σ, hσ⟩ := conj_of_root h_alg hn h_ev, use σ.symm, rw [← hσ, symm_apply_apply], end end minpoly end minpoly
709fcee9f629c333bfe93b43beecaf8250f6e2ab
491068d2ad28831e7dade8d6dff871c3e49d9431
/tests/lean/unfold.lean
a743baab2ff92c0f84b3ddeb82ed587856a08222
[ "Apache-2.0" ]
permissive
davidmueller13/lean
65a3ed141b4088cd0a268e4de80eb6778b21a0e9
c626e2e3c6f3771e07c32e82ee5b9e030de5b050
refs/heads/master
1,611,278,313,401
1,444,021,177,000
1,444,021,177,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
704
lean
import data.nat open nat definition f (a b : nat) := a + b example (a b : nat) : f a b = 0 → f b a = 0 := begin intro h, unfold f at h, state, unfold f, state, rewrite [add.comm], exact h end example (a b : nat) : f a b = 0 → f b a = 0 := begin intro h, unfold f at *, state, rewrite [add.comm], exact h end example (a b c : nat) : f c c = 0 → f a b = 0 → f b a = f c c := begin intros [h₁, h₂], unfold f at (h₁, h₂), state, unfold f, rewrite [add.comm, h₁, h₂], end example (a b c : nat) : f c c = 0 → f a b = 0 → f b a = f c c := begin intros [h₁, h₂], unfold f at * ⊢, state, unfold f, rewrite [add.comm, h₁, h₂], end
923d3e896cccff7c24c82c1fd1a56616f802645d
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/module/pid.lean
4e5ee7755ede0179ea0b47b267cecb9f61764d81
[ "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
13,100
lean
/- Copyright (c) 2022 Pierre-Alexandre Bazin. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Pierre-Alexandre Bazin -/ import algebra.module.dedekind_domain import linear_algebra.free_module.pid import algebra.module.projective import algebra.category.Module.biproducts /-! # Structure of finitely generated modules over a PID ## Main statements * `module.equiv_direct_sum_of_is_torsion` : A finitely generated torsion module over a PID is isomorphic to a direct sum of some `R ⧸ R ∙ (p i ^ e i)` where the `p i ^ e i` are prime powers. * `module.equiv_free_prod_direct_sum` : A finitely generated module over a PID is isomorphic to the product of a free module (its torsion free part) and a direct sum of the form above (its torsion submodule). ## Notation * `R` is a PID and `M` is a (finitely generated for main statements) `R`-module, with additional torsion hypotheses in the intermediate lemmas. * `N` is a `R`-module lying over a higher type universe than `R`. This assumption is needed on the final statement for technical reasons. * `p` is an irreducible element of `R` or a tuple of these. ## Implementation details We first prove (`submodule.is_internal_prime_power_torsion_of_pid`) that a finitely generated torsion module is the internal direct sum of its `p i ^ e i`-torsion submodules for some (finitely many) prime powers `p i ^ e i`. This is proved in more generality for a Dedekind domain at `submodule.is_internal_prime_power_torsion`. Then we treat the case of a `p ^ ∞`-torsion module (that is, a module where all elements are cancelled by scalar multiplication by some power of `p`) and apply it to the `p i ^ e i`-torsion submodules (that are `p i ^ ∞`-torsion) to get the result for torsion modules. Then we get the general result using that a torsion free module is free (which has been proved at `module.free_of_finite_type_torsion_free'` at `linear_algebra/free_module/pid.lean`.) ## Tags Finitely generated module, principal ideal domain, classification, structure theorem -/ universes u v open_locale big_operators variables {R : Type u} [comm_ring R] [is_domain R] [is_principal_ideal_ring R] variables {M : Type v} [add_comm_group M] [module R M] variables {N : Type (max u v)} [add_comm_group N] [module R N] open_locale direct_sum open submodule /--A finitely generated torsion module over a PID is an internal direct sum of its `p i ^ e i`-torsion submodules for some primes `p i` and numbers `e i`.-/ theorem submodule.is_internal_prime_power_torsion_of_pid [module.finite R M] (hM : module.is_torsion R M) : ∃ (ι : Type u) [fintype ι] [decidable_eq ι] (p : ι → R) (h : ∀ i, irreducible $ p i) (e : ι → ℕ), by exactI direct_sum.is_internal (λ i, torsion_by R M $ p i ^ e i) := begin obtain ⟨P, dec, hP, e, this⟩ := is_internal_prime_power_torsion hM, refine ⟨P, infer_instance, dec, λ p, is_principal.generator (p : ideal R), _, e, _⟩, { rintro ⟨p, hp⟩, haveI := ideal.is_prime_of_prime (hP p hp), exact (is_principal.prime_generator_of_is_prime p (hP p hp).ne_zero).irreducible }, { convert this, ext p : 1, rw [← torsion_by_span_singleton_eq, ideal.submodule_span_eq, ← ideal.span_singleton_pow, ideal.span_singleton_generator] } end namespace module section p_torsion variables {p : R} (hp : irreducible p) (hM : module.is_torsion' M (submonoid.powers p)) variables [dec : Π x : M, decidable (x = 0)] open ideal submodule.is_principal include dec include hp hM lemma _root_.ideal.torsion_of_eq_span_pow_p_order (x : M) : torsion_of R M x = span {p ^ p_order hM x} := begin dunfold p_order, rw [← (torsion_of R M x).span_singleton_generator, ideal.span_singleton_eq_span_singleton, ← associates.mk_eq_mk_iff_associated, associates.mk_pow], have prop : (λ n : ℕ, p ^ n • x = 0) = λ n : ℕ, (associates.mk $ generator $ torsion_of R M x) ∣ associates.mk p ^ n, { ext n, rw [← associates.mk_pow, associates.mk_dvd_mk, ← mem_iff_generator_dvd], refl }, have := (is_torsion'_powers_iff p).mp hM x, rw prop at this, classical, convert associates.eq_pow_find_of_dvd_irreducible_pow ((associates.irreducible_mk p).mpr hp) this.some_spec, end lemma p_pow_smul_lift {x y : M} {k : ℕ} (hM' : module.is_torsion_by R M (p ^ p_order hM y)) (h : p ^ k • x ∈ R ∙ y) : ∃ a : R, p ^ k • x = p ^ k • a • y := begin by_cases hk : k ≤ p_order hM y, { let f := ((R ∙ p ^ (p_order hM y - k) * p ^ k).quot_equiv_of_eq _ _).trans (quot_torsion_of_equiv_span_singleton R M y), have : f.symm ⟨p ^ k • x, h⟩ ∈ R ∙ ideal.quotient.mk (R ∙ p ^ (p_order hM y - k) * p ^ k) (p ^ k), { rw [← quotient.torsion_by_eq_span_singleton, mem_torsion_by_iff, ← f.symm.map_smul], convert f.symm.map_zero, ext, rw [coe_smul_of_tower, coe_mk, coe_zero, smul_smul, ← pow_add, nat.sub_add_cancel hk, @hM' x], { exact mem_non_zero_divisors_of_ne_zero (pow_ne_zero _ hp.ne_zero) } }, rw submodule.mem_span_singleton at this, obtain ⟨a, ha⟩ := this, use a, rw [f.eq_symm_apply, ← ideal.quotient.mk_eq_mk, ← quotient.mk_smul] at ha, dsimp only [smul_eq_mul, f, linear_equiv.trans_apply, submodule.quot_equiv_of_eq_mk, quot_torsion_of_equiv_span_singleton_apply_mk] at ha, rw [smul_smul, mul_comm], exact congr_arg coe ha.symm, { symmetry, convert ideal.torsion_of_eq_span_pow_p_order hp hM y, rw [← pow_add, nat.sub_add_cancel hk] } }, { use 0, rw [zero_smul, smul_zero, ← nat.sub_add_cancel (le_of_not_le hk), pow_add, mul_smul, hM', smul_zero] } end open submodule.quotient lemma exists_smul_eq_zero_and_mk_eq {z : M} (hz : module.is_torsion_by R M (p ^ p_order hM z)) {k : ℕ} (f : (R ⧸ R ∙ p ^ k) →ₗ[R] M ⧸ R ∙ z) : ∃ x : M, p ^ k • x = 0 ∧ submodule.quotient.mk x = f 1 := begin have f1 := mk_surjective (R ∙ z) (f 1), have : p ^ k • f1.some ∈ R ∙ z, { rw [← quotient.mk_eq_zero, mk_smul, f1.some_spec, ← f.map_smul], convert f.map_zero, change _ • submodule.quotient.mk _ = _, rw [← mk_smul, quotient.mk_eq_zero, algebra.id.smul_eq_mul, mul_one], exact mem_span_singleton_self _ }, obtain ⟨a, ha⟩ := p_pow_smul_lift hp hM hz this, refine ⟨f1.some - a • z, by rw [smul_sub, sub_eq_zero, ha], _⟩, rw [mk_sub, mk_smul, (quotient.mk_eq_zero _).mpr $ mem_span_singleton_self _, smul_zero, sub_zero, f1.some_spec] end open finset multiset omit dec hM /--A finitely generated `p ^ ∞`-torsion module over a PID is isomorphic to a direct sum of some `R ⧸ R ∙ (p ^ e i)` for some `e i`.-/ theorem torsion_by_prime_power_decomposition (hN : module.is_torsion' N (submonoid.powers p)) [h' : module.finite R N] : ∃ (d : ℕ) (k : fin d → ℕ), nonempty $ N ≃ₗ[R] ⨁ (i : fin d), R ⧸ R ∙ (p ^ (k i : ℕ)) := begin obtain ⟨d, s, hs⟩ := @module.finite.exists_fin _ _ _ _ _ h', use d, clear h', unfreezingI { induction d with d IH generalizing N }, { use λ i, fin_zero_elim i, rw [set.range_eq_empty, submodule.span_empty] at hs, haveI : unique N := ⟨⟨0⟩, λ x, by { rw [← mem_bot _, hs], trivial }⟩, exact ⟨0⟩ }, { haveI : Π x : N, decidable (x = 0), classical, apply_instance, obtain ⟨j, hj⟩ := exists_is_torsion_by hN d.succ d.succ_ne_zero s hs, let s' : fin d → N ⧸ R ∙ s j := submodule.quotient.mk ∘ s ∘ j.succ_above, obtain ⟨k, ⟨f⟩⟩ := IH _ s' _; clear IH, { have : ∀ i : fin d, ∃ x : N, p ^ k i • x = 0 ∧ f (submodule.quotient.mk x) = direct_sum.lof R _ _ i 1, { intro i, let fi := f.symm.to_linear_map.comp (direct_sum.lof _ _ _ i), obtain ⟨x, h0, h1⟩ := exists_smul_eq_zero_and_mk_eq hp hN hj fi, refine ⟨x, h0, _⟩, rw h1, simp only [linear_map.coe_comp, f.symm.coe_to_linear_map, f.apply_symm_apply] }, refine ⟨_, ⟨((( @lequiv_prod_of_right_split_exact _ _ _ _ _ _ _ _ _ _ _ _ ((f.trans ulift.module_equiv.{u u v}.symm).to_linear_map.comp $ mkq _) ((direct_sum.to_module _ _ _ $ λ i, (liftq_span_singleton.{u u} (p ^ k i) (linear_map.to_span_singleton _ _ _) (this i).some_spec.left : R ⧸ _ →ₗ[R] _)).comp ulift.module_equiv.to_linear_map) (R ∙ s j).injective_subtype _ _).symm.trans $ ((quot_torsion_of_equiv_span_singleton _ _ _).symm.trans $ quot_equiv_of_eq _ _ $ ideal.torsion_of_eq_span_pow_p_order hp hN _).prod $ ulift.module_equiv).trans $ (@direct_sum.lequiv_prod_direct_sum R _ _ _ (λ i, R ⧸ R ∙ p ^ @option.rec _ (λ _, ℕ) (p_order hN $ s j) k i) _ _).symm).trans $ direct_sum.lequiv_congr_left R (fin_succ_equiv d).symm⟩⟩, { rw [range_subtype, linear_equiv.to_linear_map_eq_coe, linear_equiv.ker_comp, ker_mkq] }, { rw [linear_equiv.to_linear_map_eq_coe, ← f.comp_coe, linear_map.comp_assoc, linear_map.comp_assoc, ← linear_equiv.to_linear_map_eq_coe, linear_equiv.to_linear_map_symm_comp_eq, linear_map.comp_id, ← linear_map.comp_assoc, ← linear_map.comp_assoc], suffices : (f.to_linear_map.comp (R ∙ s j).mkq).comp _ = linear_map.id, { rw [← f.to_linear_map_eq_coe, this, linear_map.id_comp] }, ext i : 3, simp only [linear_map.coe_comp, function.comp_app, mkq_apply], rw [linear_equiv.coe_to_linear_map, linear_map.id_apply, direct_sum.to_module_lof, liftq_span_singleton_apply, linear_map.to_span_singleton_one, ideal.quotient.mk_eq_mk, map_one, (this i).some_spec.right] } }, { exact (mk_surjective _).forall.mpr (λ x, ⟨(@hN x).some, by rw [← quotient.mk_smul, (@hN x).some_spec, quotient.mk_zero]⟩) }, { have hs' := congr_arg (submodule.map $ mkq $ R ∙ s j) hs, rw [submodule.map_span, submodule.map_top, range_mkq] at hs', simp only [mkq_apply] at hs', simp only [s'], rw [set.range_comp (_ ∘ s), fin.range_succ_above], rw [← set.range_comp, ← set.insert_image_compl_eq_range _ j, function.comp_apply, (quotient.mk_eq_zero _).mpr (mem_span_singleton_self _), span_insert_zero] at hs', exact hs' } } end end p_torsion /--A finitely generated torsion module over a PID is isomorphic to a direct sum of some `R ⧸ R ∙ (p i ^ e i)` where the `p i ^ e i` are prime powers.-/ theorem equiv_direct_sum_of_is_torsion [h' : module.finite R N] (hN : module.is_torsion R N) : ∃ (ι : Type u) [fintype ι] (p : ι → R) (h : ∀ i, irreducible $ p i) (e : ι → ℕ), nonempty $ N ≃ₗ[R] ⨁ (i : ι), R ⧸ R ∙ (p i ^ e i) := begin obtain ⟨I, fI, _, p, hp, e, h⟩ := submodule.is_internal_prime_power_torsion_of_pid hN, haveI := fI, have : ∀ i, ∃ (d : ℕ) (k : fin d → ℕ), nonempty $ torsion_by R N (p i ^ e i) ≃ₗ[R] ⨁ j, R ⧸ R ∙ (p i ^ k j), { haveI := is_noetherian_of_fg_of_noetherian' (module.finite_def.mp h'), haveI := λ i, is_noetherian_submodule' (torsion_by R N $ p i ^ e i), exact λ i, torsion_by_prime_power_decomposition (hp i) ((is_torsion'_powers_iff $ p i).mpr $ λ x, ⟨e i, smul_torsion_by _ _⟩) }, refine ⟨Σ i, fin (this i).some, infer_instance, λ ⟨i, j⟩, p i, λ ⟨i, j⟩, hp i, λ ⟨i, j⟩, (this i).some_spec.some j, ⟨(linear_equiv.of_bijective (direct_sum.coe_linear_map _) h.1 h.2).symm.trans $ (dfinsupp.map_range.linear_equiv $ λ i, (this i).some_spec.some_spec.some).trans $ (direct_sum.sigma_lcurry_equiv R).symm.trans (dfinsupp.map_range.linear_equiv $ λ i, quot_equiv_of_eq _ _ _)⟩⟩, cases i with i j, simp only end /--**Structure theorem of finitely generated modules over a PID** : A finitely generated module over a PID is isomorphic to the product of a free module and a direct sum of some `R ⧸ R ∙ (p i ^ e i)` where the `p i ^ e i` are prime powers.-/ theorem equiv_free_prod_direct_sum [h' : module.finite R N] : ∃ (n : ℕ) (ι : Type u) [fintype ι] (p : ι → R) (h : ∀ i, irreducible $ p i) (e : ι → ℕ), nonempty $ N ≃ₗ[R] (fin n →₀ R) × ⨁ (i : ι), R ⧸ R ∙ (p i ^ e i) := begin haveI := is_noetherian_of_fg_of_noetherian' (module.finite_def.mp h'), haveI := is_noetherian_submodule' (torsion R N), haveI := module.finite.of_surjective _ (torsion R N).mkq_surjective, obtain ⟨I, fI, p, hp, e, ⟨h⟩⟩ := equiv_direct_sum_of_is_torsion (@torsion_is_torsion R N _ _ _), obtain ⟨n, ⟨g⟩⟩ := @module.free_of_finite_type_torsion_free' R _ _ _ (N ⧸ torsion R N) _ _ _ _, haveI : module.projective R (N ⧸ torsion R N) := module.projective_of_basis ⟨g⟩, obtain ⟨f, hf⟩ := module.projective_lifting_property _ linear_map.id (torsion R N).mkq_surjective, refine ⟨n, I, fI, p, hp, e, ⟨(lequiv_prod_of_right_split_exact (torsion R N).injective_subtype _ hf).symm.trans $ (h.prod g).trans $ linear_equiv.prod_comm R _ _⟩⟩, rw [range_subtype, ker_mkq] end end module
7e654b099f2cd73ce7caaa374d7cae171a423b21
63abd62053d479eae5abf4951554e1064a4c45b4
/scripts/yaml_check.lean
7e3ba846c293f9e40b3759d1d3c70d70fd9c9e9b
[ "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
1,798
lean
import data.buffer.parser import system.io import tactic.core import all open native section variables {F : Type → Type} [alternative F] def fails {α} (x : F α) : F bool := (x $> ff) <|> pure tt end open io io.fs tactic meta instance coe_tactic_to_io {α} : has_coe (tactic α) (io α) := ⟨run_tactic⟩ meta def list.to_key_val_pairs : list string → list (string × name) | (key::val::nl::l) := if nl = "" then (key, name.from_string val)::list.to_key_val_pairs l else [] | _ := [] /-- Reads the `nolints.txt`, and returns it as an `rb_lmap` from linters to declarations. -/ meta def read_nolints_file (fn : string) : io (list (string × name)) := do cont ← io.fs.read_file fn, let lines := cont.to_string.split (= '\n'), return lines.to_key_val_pairs meta def find_failures (l : list (string × name)) : tactic (list (string × name)) := l.mfilter $ λ ⟨key, decl⟩, fails $ get_decl decl def databases : list (string × string) := [ ("undergrad.txt", "Entries in `docs/undergad.yaml` refer to declarations that don't exist. Please correct the following:"), ("overview.txt", "Entries in `docs/overview.yaml` refer to declarations that don't exist. Please correct the following:"), ("100.txt", "Entries in `docs/100.yaml` refer to declarations that don't exist. Please correct the following:") ] meta def process_db : string × string → io bool | (file, msg) := do entries ← read_nolints_file file, failures ← find_failures entries, when (failures.length > 0) (do trace msg, failures.mmap' $ λ p, trace format!"{p.1} : {p.2}"), return $ failures.length = 0 -- we don't use `list.mall` because we don't want to short circuit on the first failure meta def main : io unit := do databases.mfoldl (λ b p, do r ← process_db p, return $ b && r) tt >>= guardb
d8bf024bddb9135280b803a60dcf5290a0c2432d
01ae0d022f2e2fefdaaa898938c1ac1fbce3b3ab
/categories/isomorphism.lean
a8c39f796d5257cb605860987f7212ce355f4be0
[]
no_license
PatrickMassot/lean-category-theory
0f56a83464396a253c28a42dece16c93baf8ad74
ef239978e91f2e1c3b8e88b6e9c64c155dc56c99
refs/heads/master
1,629,739,187,316
1,512,422,659,000
1,512,422,659,000
113,098,786
0
0
null
1,512,424,022,000
1,512,424,022,000
null
UTF-8
Lean
false
false
2,581
lean
-- Copyright (c) 2017 Scott Morrison. All rights reserved. -- Released under Apache 2.0 license as described in the file LICENSE. -- Authors: Tim Baumann, Stephen Morgan, Scott Morrison import .category open categories namespace categories.isomorphism structure Isomorphism ( C: Category ) ( X Y : C.Obj ) := (morphism : C.Hom X Y) (inverse : C.Hom Y X) (witness_1 : C.compose morphism inverse = C.identity X) (witness_2 : C.compose inverse morphism = C.identity Y) attribute [simp,ematch] Isomorphism.witness_1 Isomorphism.witness_2 instance Isomorphism_coercion_to_morphism { C : Category } { X Y : C.Obj } : has_coe (Isomorphism C X Y) (C.Hom X Y) := { coe := Isomorphism.morphism } definition IsomorphismComposition { C : Category } { X Y Z : C.Obj } ( α : Isomorphism C X Y ) ( β : Isomorphism C Y Z ) : Isomorphism C X Z := { morphism := C.compose α.morphism β.morphism, inverse := C.compose β.inverse α.inverse, witness_1 := ♮, witness_2 := ♮ } @[applicable] lemma {u1 v1} Isomorphism_pointwise_equal { C : Category.{u1 v1} } { X Y : C.Obj } ( α β : Isomorphism C X Y ) ( w : α.morphism = β.morphism ) : α = β := begin induction α with f g wα1 wα2, induction β with h k wβ1 wβ2, simp at w, have p : g = k, begin -- PROJECT why can't we automate this? rewrite ← C.left_identity k, rewrite ← wα2, rewrite C.associativity, rewrite w, rewrite wβ1, simp end, smt_eblast end definition Isomorphism.reverse { C : Category } { X Y : C.Obj } ( I : Isomorphism C X Y ) : Isomorphism C Y X := { morphism := I.inverse, inverse := I.morphism, witness_1 := I.witness_2, witness_2 := I.witness_1 } structure is_Isomorphism { C : Category } { X Y : C.Obj } ( morphism : C.Hom X Y ) := (inverse : C.Hom Y X) (witness_1 : C.compose morphism inverse = C.identity X) (witness_2 : C.compose inverse morphism = C.identity Y) attribute [simp,ematch] is_Isomorphism.witness_1 is_Isomorphism.witness_2 instance is_Isomorphism_coercion_to_morphism { C : Category } { X Y : C.Obj } ( f : C.Hom X Y ): has_coe (is_Isomorphism f) (C.Hom X Y) := { coe := λ _, f } definition Epimorphism { C : Category } { X Y : C.Obj } ( f : C.Hom X Y ) := Π { Z : C.Obj } ( g h : C.Hom Y Z ) ( w : C.compose f g = C.compose f h), g = h definition Monomorphism { C : Category } { X Y : C.Obj } ( f : C.Hom X Y ) := Π { Z : C.Obj } ( g h : C.Hom Z X ) ( w : C.compose g f = C.compose h f), g = h end categories.isomorphism
d28ef6da43f65ef1439c533df7c1ef3e4d0b82b9
63abd62053d479eae5abf4951554e1064a4c45b4
/src/linear_algebra/linear_action.lean
db3875a7907869889b9636bbe57963006a1b4711
[ "Apache-2.0" ]
permissive
Lix0120/mathlib
0020745240315ed0e517cbf32e738d8f9811dd80
e14c37827456fc6707f31b4d1d16f1f3a3205e91
refs/heads/master
1,673,102,855,024
1,604,151,044,000
1,604,151,044,000
308,930,245
0
0
Apache-2.0
1,604,164,710,000
1,604,163,547,000
null
UTF-8
Lean
false
false
3,334
lean
/- Copyright (c) 2020 Oliver Nash. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Oliver Nash -/ import linear_algebra.basic /-! # Linear actions For modules M and N, we can regard a linear map M →ₗ End N as a "linear action" of M on N. In this file we introduce the class `linear_action` to make it easier to work with such actions. ## Tags linear action -/ universes u v section linear_action variables (R : Type u) (M N : Type v) variables [comm_ring R] [add_comm_group M] [add_comm_group N] [module R M] [module R N] /-- A binary operation representing one module acting linearly on another. -/ class linear_action := (act : M → N → N) (add_act : ∀ (m m' : M) (n : N), act (m + m') n = act m n + act m' n) (act_add : ∀ (m : M) (n n' : N), act m (n + n') = act m n + act m n') (act_smul : ∀ (r : R) (m : M) (n : N), act (r • m) n = r • (act m n)) (smul_act : ∀ (r : R) (m : M) (n : N), act m (r • n) = act (r • m) n) @[simp] lemma zero_linear_action [linear_action R M N] (n : N) : linear_action.act R (0 : M) n = 0 := begin let z := linear_action.act R (0 : M) n, have H : z + z = z + 0 := by { rw ←linear_action.add_act, simp, }, exact add_left_cancel H, end @[simp] lemma linear_action_zero [linear_action R M N] (m : M) : linear_action.act R m (0 : N) = 0 := begin let z := linear_action.act R m (0 : N), have H : z + z = z + 0 := by { rw ←linear_action.act_add, simp, }, exact add_left_cancel H, end @[simp] lemma linear_action_add_act [linear_action R M N] (m m' : M) (n : N) : linear_action.act R (m + m') n = linear_action.act R m n + linear_action.act R m' n := linear_action.add_act m m' n @[simp] lemma linear_action_act_add [linear_action R M N] (m : M) (n n' : N) : linear_action.act R m (n + n') = linear_action.act R m n + linear_action.act R m n' := linear_action.act_add m n n' @[simp] lemma linear_action_act_smul [linear_action R M N] (r : R) (m : M) (n : N) : linear_action.act R (r • m) n = r • (linear_action.act R m n) := linear_action.act_smul r m n @[simp] lemma linear_action_smul_act [linear_action R M N] (r : R) (m : M) (n : N) : linear_action.act R m (r • n) = linear_action.act R (r • m) n := linear_action.smul_act r m n end linear_action namespace linear_action variables (R : Type u) (M N : Type v) variables [comm_ring R] [add_comm_group M] [add_comm_group N] [module R M] [module R N] /-- A linear map to the endomorphism algebra yields a linear action. -/ def of_endo_map (α : M →ₗ[R] module.End R N) : linear_action R M N := { act := λ m n, α m n, add_act := by { intros, rw linear_map.map_add, simp, }, act_add := by { intros, simp, }, act_smul := by { intros, rw linear_map.map_smul, simp, }, smul_act := by { intros, repeat { rw linear_map.map_smul }, simp, } } /-- A linear action yields a linear map to the endomorphism algebra. -/ def to_endo_map (α : linear_action R M N) : M →ₗ[R] module.End R N := { to_fun := λ m, { to_fun := λ n, linear_action.act R m n, map_add' := by { intros, simp, }, map_smul' := by { intros, simp, }, }, map_add' := by { intros, ext, simp, }, map_smul' := by { intros, ext, simp, } } end linear_action
1c5fbf7cf3e08f4d681a463924c66c40a00ec4fb
b7f22e51856f4989b970961f794f1c435f9b8f78
/hott/algebra/category/functor/equivalence.hlean
f0c02fe139f04926038073356082d3f621e01935
[ "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
18,926
hlean
/- Copyright (c) 2015 Floris van Doorn. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Floris van Doorn Functors which are equivalences or isomorphisms -/ import .adjoint open eq functor iso prod nat_trans is_equiv equiv is_trunc sigma.ops namespace category variables {C D : Precategory} {F : C ⇒ D} {G : D ⇒ C} structure is_equivalence [class] (F : C ⇒ D) extends is_left_adjoint F := mk' :: (is_iso_unit : is_iso η) (is_iso_counit : is_iso ε) abbreviation inverse := @is_equivalence.G postfix ⁻¹ := inverse --a second notation for the inverse, which is not overloaded (there is no unicode superscript F) postfix [parsing_only] `⁻¹ᴱ`:std.prec.max_plus := inverse definition is_isomorphism [class] (F : C ⇒ D) := fully_faithful F × is_equiv (to_fun_ob F) structure equivalence (C D : Precategory) := (to_functor : C ⇒ D) (struct : is_equivalence to_functor) structure isomorphism (C D : Precategory) := (to_functor : C ⇒ D) (struct : is_isomorphism to_functor) structure weak_equivalence (C D : Precategory) := mk' :: (intermediate : Precategory) (left_functor : intermediate ⇒ C) (right_functor : intermediate ⇒ D) [structl : is_weak_equivalence left_functor] [structr : is_weak_equivalence right_functor] infix ` ≃c `:25 := equivalence infix ` ≅c `:25 := isomorphism infix ` ≃w `:25 := weak_equivalence attribute equivalence.struct isomorphism.struct [instance] [priority 1500] attribute equivalence.to_functor isomorphism.to_functor [coercion] definition is_iso_unit [instance] (F : C ⇒ D) [H : is_equivalence F] : is_iso (unit F) := !is_equivalence.is_iso_unit definition is_iso_counit [instance] (F : C ⇒ D) [H : is_equivalence F] : is_iso (counit F) := !is_equivalence.is_iso_counit definition iso_unit (F : C ⇒ D) [H : is_equivalence F] : F⁻¹ᴱ ∘f F ≅ 1 := (@(iso.mk _) !is_iso_unit)⁻¹ⁱ definition iso_counit (F : C ⇒ D) [H : is_equivalence F] : F ∘f F⁻¹ᴱ ≅ 1 := @(iso.mk _) !is_iso_counit definition split_essentially_surjective_of_is_equivalence [instance] (F : C ⇒ D) [is_equivalence F] : split_essentially_surjective F := begin intro d, fconstructor, { exact F⁻¹ d}, { exact componentwise_iso (@(iso.mk (counit F)) !is_iso_counit) d} end end category namespace category section parameters {C D : Precategory} {F : C ⇒ D} {G : D ⇒ C} (η : G ∘f F ≅ 1) (ε : F ∘f G ≅ 1) private definition ηn : 1 ⟹ G ∘f F := to_inv η private definition εn : F ∘f G ⟹ 1 := to_hom ε private definition ηi (c : C) : G (F c) ≅ c := componentwise_iso η c private definition εi (d : D) : F (G d) ≅ d := componentwise_iso ε d private definition ηi' (c : C) : G (F c) ≅ c := to_fun_iso G (to_fun_iso F (ηi c)⁻¹ⁱ) ⬝i to_fun_iso G (εi (F c)) ⬝i ηi c local attribute ηn εn ηi εi ηi' [reducible] private theorem adj_η_natural {c c' : C} (f : hom c c') : G (F f) ∘ to_inv (ηi' c) = to_inv (ηi' c') ∘ f := let ηi'_nat : G ∘f F ⟹ 1 := calc G ∘f F ⟹ (G ∘f F) ∘f 1 : id_right_natural_rev (G ∘f F) ... ⟹ (G ∘f F) ∘f (G ∘f F) : (G ∘f F) ∘fn ηn ... ⟹ ((G ∘f F) ∘f G) ∘f F : assoc_natural (G ∘f F) G F ... ⟹ (G ∘f (F ∘f G)) ∘f F : assoc_natural_rev G F G ∘nf F ... ⟹ (G ∘f 1) ∘f F : (G ∘fn εn) ∘nf F ... ⟹ G ∘f F : id_right_natural G ∘nf F ... ⟹ 1 : to_hom η in begin refine is_natural_inverse' (G ∘f F) functor.id ηi' ηi'_nat _ f, intro c, esimp, rewrite [+id_left,id_right] end private theorem adjointify_adjH (c : C) : to_hom (εi (F c)) ∘ F (to_hom (ηi' c))⁻¹ = id := begin rewrite [respect_inv], apply comp_inverse_eq_of_eq_comp, rewrite [id_left,↑ηi',+respect_comp,+respect_inv',assoc], apply eq_comp_inverse_of_comp_eq, rewrite [↑εi,-naturality_iso_id ε (F c)], symmetry, exact naturality εn (F (to_hom (ηi c))) end private theorem adjointify_adjK (d : D) : G (to_hom (εi d)) ∘ to_hom (ηi' (G d))⁻¹ⁱ = id := begin apply comp_inverse_eq_of_eq_comp, rewrite [id_left,↑ηi',+respect_inv',assoc], apply eq_comp_inverse_of_comp_eq, rewrite [↑ηi,-naturality_iso_id η (G d),↑εi,naturality_iso_id ε d], exact naturality (to_hom η) (G (to_hom (εi d))), end parameter (G) include η ε definition is_equivalence.mk : is_equivalence F := begin fapply is_equivalence.mk', { exact G}, { fapply nat_trans.mk, { intro c, exact to_inv (ηi' c)}, { intro c c' f, exact adj_η_natural f}}, { exact εn}, { exact adjointify_adjH}, { exact adjointify_adjK}, { exact @(is_natural_iso _) (λc, !is_iso_inverse)}, { unfold εn, apply iso.struct, }, end definition equivalence.MK : C ≃c D := equivalence.mk F is_equivalence.mk end section parameters {C D : Precategory} (F : C ⇒ D) [H₁ : fully_faithful F] [H₂ : split_essentially_surjective F] include H₁ H₂ definition inverse_of_fully_faithful_of_split_essentially_surjective [constructor] : D ⇒ C := begin fapply functor.mk, { exact λd, (H₂ d).1}, { intro d d' g, apply (to_fun_hom F)⁻¹ᶠ, refine to_inv (H₂ d').2 ∘ g ∘ to_hom (H₂ d).2}, { intro d, apply inv_eq_of_eq, rewrite [id_left, respect_id, to_left_inverse]}, { intros d₁ d₂ d₃ g f, apply inv_eq_of_eq, rewrite [respect_comp, +right_inv (to_fun_hom F), +assoc', comp_inverse_cancel_left]} end definition is_equivalence_of_fully_faithful_of_split_essentially_surjective [constructor] : is_equivalence F := begin fapply is_equivalence.mk, { exact inverse_of_fully_faithful_of_split_essentially_surjective}, { fapply natural_iso.mk', { intro c, esimp, apply reflect_iso F, exact (H₂ (F c)).2}, intro c c' f, esimp, apply eq_of_fn_eq_fn' (to_fun_hom F), rewrite [+respect_comp, +right_inv (to_fun_hom F), comp_inverse_cancel_left]}, { fapply natural_iso.mk', { intro c, esimp, exact (H₂ c).2}, intro c c' f, esimp, rewrite [right_inv (to_fun_hom F), comp_inverse_cancel_left]} end end variables {C D E : Precategory} {F : C ⇒ D} --TODO: add variants definition unit_eq_counit_inv (F : C ⇒ D) [H : is_equivalence F] (c : C) : to_fun_hom F (natural_map (unit F) c) = @(is_iso.inverse (counit F (F c))) (@(componentwise_is_iso (counit F)) !is_iso_counit (F c)) := begin apply eq_inverse_of_comp_eq_id, apply counit_unit_eq end definition fully_faithful_of_is_equivalence [instance] [constructor] (F : C ⇒ D) [H : is_equivalence F] : fully_faithful F := begin intro c c', fapply adjointify, { intro g, exact natural_map (@(iso.inverse (unit F)) !is_iso_unit) c' ∘ F⁻¹ g ∘ unit F c}, { intro g, rewrite [+respect_comp,▸*], xrewrite [natural_map_inverse (unit F) c', respect_inv'], apply inverse_comp_eq_of_eq_comp, rewrite [+unit_eq_counit_inv], esimp, exact naturality (counit F)⁻¹ _}, { intro f, xrewrite [▸*,natural_map_inverse (unit F) c'], apply inverse_comp_eq_of_eq_comp, apply naturality (unit F)}, end definition is_isomorphism.mk [constructor] {F : C ⇒ D} (G : D ⇒ C) (p : G ∘f F = 1) (q : F ∘f G = 1) : is_isomorphism F := begin constructor, { apply fully_faithful_of_is_equivalence, fapply is_equivalence.mk, { exact G}, { apply iso_of_eq p}, { apply iso_of_eq q}}, { fapply adjointify, { exact G}, { exact ap010 to_fun_ob q}, { exact ap010 to_fun_ob p}} end definition isomorphism.MK [constructor] (F : C ⇒ D) (G : D ⇒ C) (p : G ∘f F = 1) (q : F ∘f G = 1) : C ≅c D := isomorphism.mk F (is_isomorphism.mk G p q) definition is_equiv_ob_of_is_isomorphism [instance] [unfold 4] (F : C ⇒ D) [H : is_isomorphism F] : is_equiv (to_fun_ob F) := pr2 H definition fully_faithful_of_is_isomorphism [unfold 4] (F : C ⇒ D) [H : is_isomorphism F] : fully_faithful F := pr1 H section local attribute fully_faithful_of_is_isomorphism [instance] definition strict_inverse [constructor] (F : C ⇒ D) [H : is_isomorphism F] : D ⇒ C := begin fapply functor.mk, { intro d, exact (to_fun_ob F)⁻¹ᶠ d}, { intro d d' g, exact (to_fun_hom F)⁻¹ᶠ (inv_of_eq !right_inv ∘ g ∘ hom_of_eq !right_inv)}, { intro d, apply inv_eq_of_eq, rewrite [respect_id,id_left], apply left_inverse}, { intro d₁ d₂ d₃ g₂ g₁, apply inv_eq_of_eq, rewrite [respect_comp F,+right_inv (to_fun_hom F)], rewrite [+assoc], esimp, /-apply ap (λx, (x ∘ _) ∘ _), FAILS-/ refine ap (λx, (x ∘ _) ∘ _) _, refine !id_right⁻¹ ⬝ _, rewrite [▸*,-+assoc], refine ap (λx, _ ∘ _ ∘ x) _, exact !right_inverse⁻¹}, end postfix /-[parsing-only]-/ `⁻¹ˢ`:std.prec.max_plus := strict_inverse definition strict_right_inverse (F : C ⇒ D) [H : is_isomorphism F] : F ∘f F⁻¹ˢ = 1 := begin fapply functor_eq, { intro d, esimp, apply right_inv}, { intro d d' g, rewrite [▸*, right_inv (to_fun_hom F), +assoc], rewrite [↑[hom_of_eq,inv_of_eq,iso.to_inv], right_inverse], rewrite [id_left], apply comp_inverse_cancel_right}, end definition strict_left_inverse (F : C ⇒ D) [H : is_isomorphism F] : F⁻¹ˢ ∘f F = 1 := begin fapply functor_eq, { intro d, esimp, apply left_inv}, { intro d d' g, esimp, apply comp_eq_of_eq_inverse_comp, apply comp_inverse_eq_of_eq_comp, apply inv_eq_of_eq, rewrite [+respect_comp,-assoc], apply ap011 (λx y, x ∘ F g ∘ y), { rewrite [adj], rewrite [▸*,respect_inv_of_eq F]}, { rewrite [adj,▸*,respect_hom_of_eq F]}}, end end definition is_equivalence_of_is_isomorphism [instance] [constructor] (F : C ⇒ D) [is_isomorphism F] : is_equivalence F := begin fapply is_equivalence.mk, { apply F⁻¹ˢ}, { apply iso_of_eq !strict_left_inverse}, { apply iso_of_eq !strict_right_inverse}, end definition equivalence_of_isomorphism [constructor] (F : C ≅c D) : C ≃c D := equivalence.mk F _ theorem is_prop_is_equivalence [instance] {C : Category} {D : Precategory} (F : C ⇒ D) : is_prop (is_equivalence F) := begin have f : is_equivalence F ≃ Σ(H : is_left_adjoint F), is_iso (unit F) × is_iso (counit F), begin fapply equiv.MK, { intro H, induction H, fconstructor: constructor, repeat (esimp;assumption) }, { intro H, induction H with H1 H2, induction H1, induction H2, constructor, repeat (esimp at *;assumption)}, { intro H, induction H with H1 H2, induction H1, induction H2, reflexivity}, { intro H, induction H, reflexivity} end, apply is_trunc_equiv_closed_rev, exact f, end theorem is_prop_is_isomorphism [instance] (F : C ⇒ D) : is_prop (is_isomorphism F) := by unfold is_isomorphism; exact _ /- closure properties -/ definition is_isomorphism_id [instance] [constructor] (C : Precategory) : is_isomorphism (1 : C ⇒ C) := is_isomorphism.mk 1 !functor.id_right !functor.id_right definition is_isomorphism_strict_inverse [constructor] (F : C ⇒ D) [K : is_isomorphism F] : is_isomorphism F⁻¹ˢ := is_isomorphism.mk F !strict_right_inverse !strict_left_inverse definition is_isomorphism_compose [constructor] (G : D ⇒ E) (F : C ⇒ D) [H : is_isomorphism G] [K : is_isomorphism F] : is_isomorphism (G ∘f F) := is_isomorphism.mk (F⁻¹ˢ ∘f G⁻¹ˢ) abstract begin rewrite [functor.assoc,-functor.assoc F⁻¹ˢ,strict_left_inverse,functor.id_right, strict_left_inverse] end end abstract begin rewrite [functor.assoc,-functor.assoc G,strict_right_inverse,functor.id_right, strict_right_inverse] end end definition is_equivalence_id [constructor] (C : Precategory) : is_equivalence (1 : C ⇒ C) := _ definition is_equivalence_inverse [constructor] (F : C ⇒ D) [K : is_equivalence F] : is_equivalence F⁻¹ᴱ := is_equivalence.mk F (iso_counit F) (iso_unit F) definition is_equivalence_compose [constructor] (G : D ⇒ E) (F : C ⇒ D) [H : is_equivalence G] [K : is_equivalence F] : is_equivalence (G ∘f F) := is_equivalence.mk (F⁻¹ᴱ ∘f G⁻¹ᴱ) abstract begin rewrite [functor.assoc,-functor.assoc F⁻¹ᴱ], refine ((_ ∘fi !iso_unit) ∘if _) ⬝i _, refine (iso_of_eq !functor.id_right ∘if _) ⬝i _, apply iso_unit end end abstract begin rewrite [functor.assoc,-functor.assoc G], refine ((_ ∘fi !iso_counit) ∘if _) ⬝i _, refine (iso_of_eq !functor.id_right ∘if _) ⬝i _, apply iso_counit end end variable (C) definition equivalence.refl [refl] [constructor] : C ≃c C := equivalence.mk _ !is_equivalence_id definition isomorphism.refl [refl] [constructor] : C ≅c C := isomorphism.mk _ !is_isomorphism_id variable {C} definition equivalence.symm [symm] [constructor] (H : C ≃c D) : D ≃c C := equivalence.mk _ (is_equivalence_inverse H) definition isomorphism.symm [symm] [constructor] (H : C ≅c D) : D ≅c C := isomorphism.mk _ (is_isomorphism_strict_inverse H) definition equivalence.trans [trans] [constructor] (H : C ≃c D) (K : D ≃c E) : C ≃c E := equivalence.mk _ (is_equivalence_compose K H) definition isomorphism.trans [trans] [constructor] (H : C ≅c D) (K : D ≅c E) : C ≅c E := isomorphism.mk _ (is_isomorphism_compose K H) definition equivalence.to_strict_inverse [unfold 3] (H : C ≃c D) : D ⇒ C := H⁻¹ᴱ definition isomorphism.to_strict_inverse [unfold 3] (H : C ≅c D) : D ⇒ C := H⁻¹ˢ definition is_isomorphism_of_is_equivalence [constructor] {C D : Category} (F : C ⇒ D) [H : is_equivalence F] : is_isomorphism F := begin fapply is_isomorphism.mk, { exact F⁻¹ᴱ}, { apply eq_of_iso, apply iso_unit}, { apply eq_of_iso, apply iso_counit}, end definition isomorphism_of_equivalence [constructor] {C D : Category} (F : C ≃c D) : C ≅c D := isomorphism.mk F !is_isomorphism_of_is_equivalence definition equivalence_eq {C : Category} {D : Precategory} {F F' : C ≃c D} (p : equivalence.to_functor F = equivalence.to_functor F') : F = F' := begin induction F, induction F', exact apd011 equivalence.mk p !is_prop.elimo end definition isomorphism_eq {F F' : C ≅c D} (p : isomorphism.to_functor F = isomorphism.to_functor F') : F = F' := begin induction F, induction F', exact apd011 isomorphism.mk p !is_prop.elimo end definition is_equiv_isomorphism_of_equivalence [constructor] (C D : Category) : is_equiv (@equivalence_of_isomorphism C D) := begin fapply adjointify, { exact isomorphism_of_equivalence}, { intro F, apply equivalence_eq, reflexivity}, { intro F, apply isomorphism_eq, reflexivity}, end definition isomorphism_equiv_equivalence [constructor] (C D : Category) : (C ≅c D) ≃ (C ≃c D) := equiv.mk _ !is_equiv_isomorphism_of_equivalence definition isomorphism_of_eq [constructor] {C D : Precategory} (p : C = D) : C ≅c D := isomorphism.MK (functor_of_eq p) (functor_of_eq p⁻¹) (by induction p; reflexivity) (by induction p; reflexivity) definition equiv_ob_of_isomorphism [constructor] {C D : Precategory} (H : C ≅c D) : C ≃ D := equiv.mk H _ definition equiv_hom_of_isomorphism [constructor] {C D : Precategory} (H : C ≅c D) (c c' : C) : c ⟶ c' ≃ H c ⟶ H c' := equiv.mk (to_fun_hom (isomorphism.to_functor H)) _ /- weak equivalences -/ theorem is_prop_is_weak_equivalence [instance] (F : C ⇒ D) : is_prop (is_weak_equivalence F) := by unfold is_weak_equivalence; exact _ definition is_weak_equivalence_of_is_equivalence [instance] (F : C ⇒ D) [is_equivalence F] : is_weak_equivalence F := (_, _) definition fully_faithful_of_is_weak_equivalence.mk [instance] (F : C ⇒ D) [H : is_weak_equivalence F] : fully_faithful F := pr1 H definition essentially_surjective_of_is_weak_equivalence.mk [instance] (F : C ⇒ D) [H : is_weak_equivalence F] : essentially_surjective F := pr2 H definition is_weak_equivalence_compose (G : D ⇒ E) (F : C ⇒ D) [H : is_weak_equivalence G] [K : is_weak_equivalence F] : is_weak_equivalence (G ∘f F) := (fully_faithful_compose G F, essentially_surjective_compose G F) definition weak_equivalence.mk [constructor] (F : C ⇒ D) (H : is_weak_equivalence F) : C ≃w D := weak_equivalence.mk' C 1 F definition weak_equivalence.symm [unfold 3] : C ≃w D → D ≃w C | (@weak_equivalence.mk' _ _ X F₁ F₂ H₁ H₂) := weak_equivalence.mk' X F₂ F₁ /- TODO definition is_equiv_isomorphism_of_eq [constructor] (C D : Precategory) : is_equiv (@isomorphism_of_eq C D) := begin fapply adjointify, { intro H, fapply Precategory_eq_of_equiv, { apply equiv_ob_of_isomorphism H}, { exact equiv_hom_of_isomorphism H}, { /-exact sorry FAILS-/ intros, esimp, apply respect_comp}}, { intro H, apply isomorphism_eq, esimp, fapply functor_eq: esimp, { intro c, exact sorry}, { exact sorry}}, { intro p, induction p, esimp, exact sorry}, end definition eq_equiv_isomorphism [constructor] (C D : Precategory) : (C = D) ≃ (C ≅c D) := equiv.mk _ !is_equiv_isomorphism_of_eq definition equivalence_of_eq [unfold 3] [reducible] {C D : Precategory} (p : C = D) : C ≃c D := equivalence_of_isomorphism (isomorphism_of_eq p) definition eq_equiv_equivalence [constructor] (C D : Category) : (C = D) ≃ (C ≃c D) := !eq_equiv_isomorphism ⬝e !isomorphism_equiv_equivalence definition is_equivalence_equiv [constructor] (F : C ⇒ D) : is_equivalence F ≃ (fully_faithful F × split_essentially_surjective F) := sorry definition is_equivalence_equiv_is_weak_equivalence [constructor] {C D : Category} (F : C ⇒ D) : is_equivalence F ≃ is_weak_equivalence F := sorry -- weak_equivalence.trans -/ /- TODO? definition is_isomorphism_equiv1 (F : C ⇒ D) : is_equivalence F ≃ Σ(G : D ⇒ C) (η : 1 = G ∘f F) (ε : F ∘f G = 1), sorry ⬝ ap (λ(H : C ⇒ C), F ∘f H) η ⬝ sorry = ap (λ(H : D ⇒ D), H ∘f F) ε⁻¹ := sorry definition is_isomorphism_equiv2 (F : C ⇒ D) : is_equivalence F ≃ ∃(G : D ⇒ C), 1 = G ∘f F × F ∘f G = 1 := sorry -/ end category
67ea7b552e90142dad46b7c66267a1d17117b728
618003631150032a5676f229d13a079ac875ff77
/src/algebra/category/CommRing/limits.lean
040cbc2021ed8abe486e9ca3ad3d35ef8575c44f
[ "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
4,950
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 algebra.category.CommRing.basic /-! # The category of commutative rings has all limits Further, these limits are preserved by the forgetful functor --- that is, the underlying types are just the limits in the category of types. ## Further work A lot of this should be generalised / automated, as it's quite common for concrete categories that the forgetful functor preserves limits. -/ open category_theory open category_theory.limits universe u namespace CommRing variables {J : Type u} [small_category J] instance comm_ring_obj (F : J ⥤ CommRing.{u}) (j) : comm_ring ((F ⋙ forget CommRing).obj j) := by { change comm_ring (F.obj j), apply_instance } instance sections_submonoid (F : J ⥤ CommRing.{u}) : is_submonoid (F ⋙ forget CommRing).sections := { one_mem := λ j j' f, begin erw [functor.comp_map, forget_map_eq_coe, (F.map f).map_one], refl end, mul_mem := λ a b ah bh j j' f, begin erw [functor.comp_map, forget_map_eq_coe, (F.map f).map_mul], dsimp [functor.sections] at ah, rw ah f, dsimp [functor.sections] at bh, rw bh f, refl, end } instance sections_add_submonoid (F : J ⥤ CommRing.{u}) : is_add_submonoid (F ⋙ forget CommRing).sections := { zero_mem := λ j j' f, begin erw [functor.comp_map, forget_map_eq_coe, (F.map f).map_zero], refl, end, add_mem := λ a b ah bh j j' f, begin erw [functor.comp_map, forget_map_eq_coe, (F.map f).map_add], dsimp [functor.sections] at ah, rw ah f, dsimp [functor.sections] at bh, rw bh f, refl, end } instance sections_add_subgroup (F : J ⥤ CommRing.{u}) : is_add_subgroup (F ⋙ forget CommRing).sections := { neg_mem := λ a ah j j' f, begin erw [functor.comp_map, forget_map_eq_coe, (F.map f).map_neg], dsimp [functor.sections] at ah, rw ah f, refl, end, ..(CommRing.sections_add_submonoid F) } instance sections_subring (F : J ⥤ CommRing.{u}) : is_subring (F ⋙ forget CommRing).sections := { ..(CommRing.sections_submonoid F), ..(CommRing.sections_add_subgroup F) } instance limit_comm_ring (F : J ⥤ CommRing.{u}) : comm_ring (limit (F ⋙ forget CommRing)) := @subtype.comm_ring ((Π (j : J), (F ⋙ forget _).obj j)) (by apply_instance) _ (by convert (CommRing.sections_subring F)) /-- `limit.π (F ⋙ forget CommRing) j` as a `ring_hom`. -/ def limit_π_ring_hom (F : J ⥤ CommRing.{u}) (j) : limit (F ⋙ forget CommRing) →+* (F ⋙ forget CommRing).obj j := { to_fun := limit.π (F ⋙ forget CommRing) j, map_one' := by { simp only [types.types_limit_π], refl }, map_zero' := by { simp only [types.types_limit_π], refl }, map_mul' := λ x y, by { simp only [types.types_limit_π], refl }, map_add' := λ x y, by { simp only [types.types_limit_π], refl } } namespace CommRing_has_limits -- The next two definitions are used in the construction of `has_limits CommRing`. -- After that, the limits should be constructed using the generic limits API, -- e.g. `limit F`, `limit.cone F`, and `limit.is_limit F`. /-- Construction of a limit cone in `CommRing`. (Internal use only; use the limits API.) -/ def limit (F : J ⥤ CommRing.{u}) : cone F := { X := ⟨limit (F ⋙ forget _), by apply_instance⟩, π := { app := limit_π_ring_hom F, naturality' := λ j j' f, ring_hom.coe_inj ((limit.cone (F ⋙ forget _)).π.naturality f) } } /-- Witness that the limit cone in `CommRing` is a limit cone. (Internal use only; use the limits API.) -/ def limit_is_limit (F : J ⥤ CommRing.{u}) : is_limit (limit F) := begin refine is_limit.of_faithful (forget CommRing) (limit.is_limit _) (λ s, ⟨_, _, _, _, _⟩) (λ s, rfl); dsimp, { apply subtype.eq, funext, dsimp, erw (s.π.app j).map_one, refl }, { intros x y, apply subtype.eq, funext, dsimp, erw (s.π.app j).map_mul, refl }, { apply subtype.eq, funext, dsimp, erw (s.π.app j).map_zero, refl }, { intros x y, apply subtype.eq, funext, dsimp, erw (s.π.app j).map_add, refl } end end CommRing_has_limits open CommRing_has_limits /-- The category of commutative rings has all limits. -/ instance CommRing_has_limits : has_limits.{u} CommRing.{u} := { has_limits_of_shape := λ J 𝒥, { has_limit := λ F, by exactI { cone := limit F, is_limit := limit_is_limit F } } } /-- The forgetful functor from commutative rings to types preserves all limits. (That is, the underlying types could have been computed instead as limits in the category of types.) -/ instance forget_preserves_limits : preserves_limits (forget CommRing.{u}) := { preserves_limits_of_shape := λ J 𝒥, { preserves_limit := λ F, by exactI preserves_limit_of_preserves_limit_cone (limit.is_limit F) (limit.is_limit (F ⋙ forget _)) } } end CommRing
0509ab01b02aac489b9c3e35d1de082406bbebd1
d1a52c3f208fa42c41df8278c3d280f075eb020c
/tests/lean/ppExpr.lean
dcb3a8c19c33597575c949f897adc357fb8268af
[ "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
656
lean
import Lean /-! Pretty printing tests for `Expr`s that cannot be generated by parsing+elaborating. -/ open Lean def test (e : Expr) : MetaM Unit := do IO.println (← PrettyPrinter.ppExpr Name.anonymous [] e) -- loose bound variable #eval test (mkBVar 0) -- anonymous binder #eval test (mkLambda Name.anonymous BinderInfo.default (mkSort levelZero) (mkBVar 0)) -- pp annotations #eval test $ mkAppN (mkConst `id [levelOne]) #[ mkConst `Nat, mkMData (KVMap.empty.set `pp.explicit true) $ mkAppN (mkConst `id [levelOne]) #[ mkConst `Nat, mkAppN (mkConst `id [levelOne]) #[ mkConst `Nat, mkConst `Nat.zero ]]]
6025adbdb2ce62307f29d91fc05480ba72b59294
4fa161becb8ce7378a709f5992a594764699e268
/src/data/holor.lean
1e6bd8ee4ccc0b40945984ada66485bc3e01a5d5
[ "Apache-2.0" ]
permissive
laughinggas/mathlib
e4aa4565ae34e46e834434284cb26bd9d67bc373
86dcd5cda7a5017c8b3c8876c89a510a19d49aad
refs/heads/master
1,669,496,232,688
1,592,831,995,000
1,592,831,995,000
274,155,979
0
0
Apache-2.0
1,592,835,190,000
1,592,835,189,000
null
UTF-8
Lean
false
false
14,213
lean
/- Copyright (c) 2018 Alexander Bentkamp. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Alexander Bentkamp -/ import algebra.pi_instances /-! # Basic properties of holors Holors are indexed collections of tensor coefficients. Confusingly, they are often called tensors in physics and in the neural network community. A holor is simply a multidimensional array of values. The size of a holor is specified by a `list ℕ`, whose length is called the dimension of the holor. The tensor product of `x₁ : holor α ds₁` and `x₂ : holor α ds₂` is the holor given by `(x₁ ⊗ x₂) (i₁ ++ i₂) = x₁ i₁ * x₂ i₂`. A holor is "of rank at most 1" if it is a tensor product of one-dimensional holors. The CP rank of a holor `x` is the smallest N such that `x` is the sum of N holors of rank at most 1. Based on the tensor library found in <https://www.isa-afp.org/entries/Deep_Learning.html> ## References * <https://en.wikipedia.org/wiki/Tensor_rank_decomposition> -/ universes u open list open_locale big_operators /-- `holor_index ds` is the type of valid index tuples to identify an entry of a holor of dimensions `ds` -/ def holor_index (ds : list ℕ) : Type := { is : list ℕ // forall₂ (<) is ds} namespace holor_index variables {ds₁ ds₂ ds₃ : list ℕ} def take : Π {ds₁ : list ℕ}, holor_index (ds₁ ++ ds₂) → holor_index ds₁ | ds is := ⟨ list.take (length ds) is.1, forall₂_take_append is.1 ds ds₂ is.2 ⟩ def drop : Π {ds₁ : list ℕ}, holor_index (ds₁ ++ ds₂) → holor_index ds₂ | ds is := ⟨ list.drop (length ds) is.1, forall₂_drop_append is.1 ds ds₂ is.2 ⟩ lemma cast_type (is : list ℕ) (eq : ds₁ = ds₂) (h : forall₂ (<) is ds₁) : (cast (congr_arg holor_index eq) ⟨is, h⟩).val = is := by subst eq; refl def assoc_right : holor_index (ds₁ ++ ds₂ ++ ds₃) → holor_index (ds₁ ++ (ds₂ ++ ds₃)) := cast (congr_arg holor_index (append_assoc ds₁ ds₂ ds₃)) def assoc_left : holor_index (ds₁ ++ (ds₂ ++ ds₃)) → holor_index (ds₁ ++ ds₂ ++ ds₃) := cast (congr_arg holor_index (append_assoc ds₁ ds₂ ds₃).symm) lemma take_take : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.take = t.take.take | ⟨ is , h ⟩ := subtype.eq (by simp [assoc_right,take, cast_type, list.take_take, nat.le_add_right, min_eq_left]) lemma drop_take : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.drop.take = t.take.drop | ⟨ is , h ⟩ := subtype.eq (by simp [assoc_right, take, drop, cast_type, list.drop_take]) lemma drop_drop : ∀ t : holor_index (ds₁ ++ ds₂ ++ ds₃), t.assoc_right.drop.drop = t.drop | ⟨ is , h ⟩ := subtype.eq (by simp [add_comm, assoc_right, drop, cast_type, list.drop_drop]) end holor_index /-- Holor (indexed collections of tensor coefficients) -/ def holor (α : Type u) (ds:list ℕ) := holor_index ds → α namespace holor variables {α : Type} {d : ℕ} {ds : list ℕ} {ds₁ : list ℕ} {ds₂ : list ℕ} {ds₃ : list ℕ} instance [inhabited α] : inhabited (holor α ds) := ⟨λ t, default α⟩ instance [has_zero α] : has_zero (holor α ds) := ⟨λ t, 0⟩ instance [has_add α] : has_add (holor α ds) := ⟨λ x y t, x t + y t⟩ instance [has_neg α] : has_neg (holor α ds) := ⟨λ a t, - a t⟩ instance [add_semigroup α] : add_semigroup (holor α ds) := by pi_instance instance [add_comm_semigroup α] : add_comm_semigroup (holor α ds) := by pi_instance instance [add_monoid α] : add_monoid (holor α ds) := by pi_instance instance [add_comm_monoid α] : add_comm_monoid (holor α ds) := by pi_instance instance [add_group α] : add_group (holor α ds) := by pi_instance instance [add_comm_group α] : add_comm_group (holor α ds) := by pi_instance /- scalar product -/ instance [has_mul α] : has_scalar α (holor α ds) := ⟨λ a x, λ t, a * x t⟩ instance [semiring α] : semimodule α (holor α ds) := pi.semimodule _ _ _ /-- The tensor product of two holors. -/ def mul [s : has_mul α] (x : holor α ds₁) (y : holor α ds₂) : holor α (ds₁ ++ ds₂) := λ t, x (t.take) * y (t.drop) local infix ` ⊗ ` : 70 := mul lemma cast_type (eq : ds₁ = ds₂) (a : holor α ds₁) : cast (congr_arg (holor α) eq) a = (λ t, a (cast (congr_arg holor_index eq.symm) t)) := by subst eq; refl def assoc_right : holor α (ds₁ ++ ds₂ ++ ds₃) → holor α (ds₁ ++ (ds₂ ++ ds₃)) := cast (congr_arg (holor α) (append_assoc ds₁ ds₂ ds₃)) def assoc_left : holor α (ds₁ ++ (ds₂ ++ ds₃)) → holor α (ds₁ ++ ds₂ ++ ds₃) := cast (congr_arg (holor α) (append_assoc ds₁ ds₂ ds₃).symm) lemma mul_assoc0 [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) : x ⊗ y ⊗ z = (x ⊗ (y ⊗ z)).assoc_left := funext (assume t : holor_index (ds₁ ++ ds₂ ++ ds₃), begin rw assoc_left, unfold mul, rw mul_assoc, rw [←holor_index.take_take, ←holor_index.drop_take, ←holor_index.drop_drop], rw cast_type, refl, rw append_assoc end) lemma mul_assoc [semigroup α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₃) : mul (mul x y) z == (mul x (mul y z)) := by simp [cast_heq, mul_assoc0, assoc_left]. lemma mul_left_distrib [distrib α] (x : holor α ds₁) (y : holor α ds₂) (z : holor α ds₂) : x ⊗ (y + z) = x ⊗ y + x ⊗ z := funext (λt, left_distrib (x (holor_index.take t)) (y (holor_index.drop t)) (z (holor_index.drop t))) lemma mul_right_distrib [distrib α] (x : holor α ds₁) (y : holor α ds₁) (z : holor α ds₂) : (x + y) ⊗ z = x ⊗ z + y ⊗ z := funext (λt, right_distrib (x (holor_index.take t)) (y (holor_index.take t)) (z (holor_index.drop t))) @[simp] lemma zero_mul {α : Type} [ring α] (x : holor α ds₂) : (0 : holor α ds₁) ⊗ x = 0 := funext (λ t, zero_mul (x (holor_index.drop t))) @[simp] lemma mul_zero {α : Type} [ring α] (x : holor α ds₁) : x ⊗ (0 :holor α ds₂) = 0 := funext (λ t, mul_zero (x (holor_index.take t))) lemma mul_scalar_mul [monoid α] (x : holor α []) (y : holor α ds) : x ⊗ y = x ⟨[], forall₂.nil⟩ • y := by simp [mul, has_scalar.smul, holor_index.take, holor_index.drop] /- holor slices -/ /-- A slice is a subholor consisting of all entries with initial index i. -/ def slice (x : holor α (d :: ds)) (i : ℕ) (h : i < d) : holor α ds := (λ is : holor_index ds, x ⟨ i :: is.1, forall₂.cons h is.2⟩) /-- The 1-dimensional "unit" holor with 1 in the `j`th position. -/ def unit_vec [monoid α] [add_monoid α] (d : ℕ) (j : ℕ) : holor α [d] := λ ti, if ti.1 = [j] then 1 else 0 lemma holor_index_cons_decomp (p: holor_index (d :: ds) → Prop) : Π (t : holor_index (d :: ds)), (∀ i is, Π h : t.1 = i :: is, p ⟨ i :: is, begin rw [←h], exact t.2 end ⟩ ) → p t | ⟨[], hforall₂⟩ hp := absurd (forall₂_nil_left_iff.1 hforall₂) (cons_ne_nil d ds) | ⟨(i :: is), hforall₂⟩ hp := hp i is rfl /-- Two holors are equal if all their slices are equal. -/ lemma slice_eq (x : holor α (d :: ds)) (y : holor α (d :: ds)) (h : slice x = slice y) : x = y := funext $ λ t : holor_index (d :: ds), holor_index_cons_decomp (λ t, x t = y t) t $ λ i is hiis, have hiisdds: forall₂ (<) (i :: is) (d :: ds), begin rw [←hiis], exact t.2 end, have hid: i<d, from (forall₂_cons.1 hiisdds).1, have hisds: forall₂ (<) is ds, from (forall₂_cons.1 hiisdds).2, calc x ⟨i :: is, _⟩ = slice x i hid ⟨is, hisds⟩ : congr_arg (λ t, x t) (subtype.eq rfl) ... = slice y i hid ⟨is, hisds⟩ : by rw h ... = y ⟨i :: is, _⟩ : congr_arg (λ t, y t) (subtype.eq rfl) lemma slice_unit_vec_mul [ring α] {i : ℕ} {j : ℕ} (hid : i < d) (x : holor α ds) : slice (unit_vec d j ⊗ x) i hid = if i=j then x else 0 := funext $ λ t : holor_index ds, if h : i = j then by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h] else by simp [slice, mul, holor_index.take, unit_vec, holor_index.drop, h]; refl lemma slice_add [has_add α] (i : ℕ) (hid : i < d) (x : holor α (d :: ds)) (y : holor α (d :: ds)) : slice x i hid + slice y i hid = slice (x + y) i hid := funext (λ t, by simp [slice,(+)]) lemma slice_zero [has_zero α] (i : ℕ) (hid : i < d) : slice (0 : holor α (d :: ds)) i hid = 0 := funext (λ t, by simp [slice]; refl) lemma slice_sum [add_comm_monoid α] {β : Type} (i : ℕ) (hid : i < d) (s : finset β) (f : β → holor α (d :: ds)) : ∑ x in s, slice (f x) i hid = slice (∑ x in s, f x) i hid := begin letI := classical.dec_eq β, refine finset.induction_on s _ _, { simp [slice_zero] }, { intros _ _ h_not_in ih, rw [finset.sum_insert h_not_in, ih, slice_add, finset.sum_insert h_not_in] } end /-- The original holor can be recovered from its slices by multiplying with unit vectors and summing up. -/ @[simp] lemma sum_unit_vec_mul_slice [ring α] (x : holor α (d :: ds)) : ∑ i in (finset.range d).attach, unit_vec d i.1 ⊗ slice x i.1 (nat.succ_le_of_lt (finset.mem_range.1 i.2)) = x := begin apply slice_eq _ _ _, ext i hid, rw [←slice_sum], simp only [slice_unit_vec_mul hid], rw finset.sum_eq_single (subtype.mk i _), { simp, refl }, { assume (b : {x // x ∈ finset.range d}) (hb : b ∈ (finset.range d).attach) (hbi : b ≠ ⟨i, _⟩), have hbi' : i ≠ b.val, { apply not.imp hbi, { assume h0 : i = b.val, apply subtype.eq, simp only [h0] }, { exact finset.mem_range.2 hid } }, simp [hbi']}, { assume hid' : subtype.mk i _ ∉ finset.attach (finset.range d), exfalso, exact absurd (finset.mem_attach _ _) hid' } end /- CP rank -/ /-- `cprank_max1 x` means `x` has CP rank at most 1, that is, it is the tensor product of 1-dimensional holors. -/ inductive cprank_max1 [has_mul α]: Π {ds}, holor α ds → Prop | nil (x : holor α []) : cprank_max1 x | cons {d} {ds} (x : holor α [d]) (y : holor α ds) : cprank_max1 y → cprank_max1 (x ⊗ y) /-- `cprank_max N x` means `x` has CP rank at most `N`, that is, it can be written as the sum of N holors of rank at most 1. -/ inductive cprank_max [has_mul α] [add_monoid α] : ℕ → Π {ds}, holor α ds → Prop | zero {ds} : cprank_max 0 (0 : holor α ds) | succ n {ds} (x : holor α ds) (y : holor α ds) : cprank_max1 x → cprank_max n y → cprank_max (n+1) (x + y) lemma cprank_max_nil [monoid α] [add_monoid α] (x : holor α nil) : cprank_max 1 x := have h : _, from cprank_max.succ 0 x 0 (cprank_max1.nil x) (cprank_max.zero), by rwa [add_zero x, zero_add] at h lemma cprank_max_1 [monoid α] [add_monoid α] {x : holor α ds} (h : cprank_max1 x) : cprank_max 1 x := have h' : _, from cprank_max.succ 0 x 0 h cprank_max.zero, by rwa [zero_add, add_zero] at h' lemma cprank_max_add [monoid α] [add_monoid α]: ∀ {m : ℕ} {n : ℕ} {x : holor α ds} {y : holor α ds}, cprank_max m x → cprank_max n y → cprank_max (m + n) (x + y) | 0 n x y (cprank_max.zero) hy := by simp [hy] | (m+1) n _ y (cprank_max.succ k x₁ x₂ hx₁ hx₂) hy := begin simp only [add_comm, add_assoc], apply cprank_max.succ, { assumption }, { exact cprank_max_add hx₂ hy } end lemma cprank_max_mul [ring α] : ∀ (n : ℕ) (x : holor α [d]) (y : holor α ds), cprank_max n y → cprank_max n (x ⊗ y) | 0 x _ (cprank_max.zero) := by simp [mul_zero x, cprank_max.zero] | (n+1) x _ (cprank_max.succ k y₁ y₂ hy₁ hy₂) := begin rw mul_left_distrib, rw nat.add_comm, apply cprank_max_add, { exact cprank_max_1 (cprank_max1.cons _ _ hy₁) }, { exact cprank_max_mul k x y₂ hy₂ } end lemma cprank_max_sum [ring α] {β} {n : ℕ} (s : finset β) (f : β → holor α ds) : (∀ x ∈ s, cprank_max n (f x)) → cprank_max (s.card * n) (∑ x in s, f x) := by letI := classical.dec_eq β; exact finset.induction_on s (by simp [cprank_max.zero]) (begin assume x s (h_x_notin_s : x ∉ s) ih h_cprank, simp only [finset.sum_insert h_x_notin_s,finset.card_insert_of_not_mem h_x_notin_s], rw nat.right_distrib, simp only [nat.one_mul, nat.add_comm], have ih' : cprank_max (finset.card s * n) (∑ x in s, f x), { apply ih, assume (x : β) (h_x_in_s: x ∈ s), simp only [h_cprank, finset.mem_insert_of_mem, h_x_in_s] }, exact (cprank_max_add (h_cprank x (finset.mem_insert_self x s)) ih') end) lemma cprank_max_upper_bound [ring α] : Π {ds}, ∀ x : holor α ds, cprank_max ds.prod x | [] x := cprank_max_nil x | (d :: ds) x := have h_summands : Π (i : {x // x ∈ finset.range d}), cprank_max ds.prod (unit_vec d i.1 ⊗ slice x i.1 (mem_range.1 i.2)), from λ i, cprank_max_mul _ _ _ (cprank_max_upper_bound (slice x i.1 (mem_range.1 i.2))), have h_dds_prod : (list.cons d ds).prod = finset.card (finset.range d) * prod ds, by simp [finset.card_range], have cprank_max (finset.card (finset.attach (finset.range d)) * prod ds) (∑ i in finset.attach (finset.range d), unit_vec d (i.val)⊗slice x (i.val) (mem_range.1 i.2)), from cprank_max_sum (finset.range d).attach _ (λ i _, h_summands i), have h_cprank_max_sum : cprank_max (finset.card (finset.range d) * prod ds) (∑ i in finset.attach (finset.range d), unit_vec d (i.val)⊗slice x (i.val) (mem_range.1 i.2)), by rwa [finset.card_attach] at this, begin rw [←sum_unit_vec_mul_slice x], rw [h_dds_prod], exact h_cprank_max_sum, end /-- The CP rank of a holor `x`: the smallest N such that `x` can be written as the sum of N holors of rank at most 1. -/ noncomputable def cprank [ring α] (x : holor α ds) : nat := @nat.find (λ n, cprank_max n x) (classical.dec_pred _) ⟨ds.prod, cprank_max_upper_bound x⟩ lemma cprank_upper_bound [ring α] : Π {ds}, ∀ x : holor α ds, cprank x ≤ ds.prod := λ ds (x : holor α ds), by letI := classical.dec_pred (λ (n : ℕ), cprank_max n x); exact nat.find_min' ⟨ds.prod, show (λ n, cprank_max n x) ds.prod, from cprank_max_upper_bound x⟩ (cprank_max_upper_bound x) end holor
2eb318ec6ce1d440b86cfd00e387ca290574b4cf
74addaa0e41490cbaf2abd313a764c96df57b05d
/Mathlib/data/equiv/local_equiv_auto.lean
c4432e6c275a03653b7d3b186b2587ac79954fcf
[]
no_license
AurelienSaue/Mathlib4_auto
f538cfd0980f65a6361eadea39e6fc639e9dae14
590df64109b08190abe22358fabc3eae000943f2
refs/heads/master
1,683,906,849,776
1,622,564,669,000
1,622,564,669,000
371,723,747
0
0
null
null
null
null
UTF-8
Lean
false
false
27,130
lean
/- Copyright (c) 2019 Sébastien Gouëzel. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Sébastien Gouëzel -/ import Mathlib.PrePort import Mathlib.Lean3Lib.init.default import Mathlib.data.equiv.basic import Mathlib.PostPort universes u_5 u_6 l u_1 u_2 u_3 u_4 namespace Mathlib /-! # Local equivalences This files defines equivalences between subsets of given types. An element `e` of `local_equiv α β` is made of two maps `e.to_fun` and `e.inv_fun` respectively from α to β and from β to α (just like equivs), which are inverse to each other on the subsets `e.source` and `e.target` of respectively α and β. They are designed in particular to define charts on manifolds. The main functionality is `e.trans f`, which composes the two local equivalences by restricting the source and target to the maximal set where the composition makes sense. As for equivs, we register a coercion to functions and use it in our simp normal form: we write `e x` and `e.symm y` instead of `e.to_fun x` and `e.inv_fun y`. ## Main definitions `equiv.to_local_equiv`: associating a local equiv to an equiv, with source = target = univ `local_equiv.symm` : the inverse of a local equiv `local_equiv.trans` : the composition of two local equivs `local_equiv.refl` : the identity local equiv `local_equiv.of_set` : the identity on a set `s` `eq_on_source` : equivalence relation describing the "right" notion of equality for local equivs (see below in implementation notes) ## Implementation notes There are at least three possible implementations of local equivalences: * equivs on subtypes * pairs of functions taking values in `option α` and `option β`, equal to none where the local equivalence is not defined * pairs of functions defined everywhere, keeping the source and target as additional data Each of these implementations has pros and cons. * When dealing with subtypes, one still need to define additional API for composition and restriction of domains. Checking that one always belongs to the right subtype makes things very tedious, and leads quickly to DTT hell (as the subtype `u ∩ v` is not the "same" as `v ∩ u`, for instance). * With option-valued functions, the composition is very neat (it is just the usual composition, and the domain is restricted automatically). These are implemented in `pequiv.lean`. For manifolds, where one wants to discuss thoroughly the smoothness of the maps, this creates however a lot of overhead as one would need to extend all classes of smoothness to option-valued maps. * The local_equiv version as explained above is easier to use for manifolds. The drawback is that there is extra useless data (the values of `to_fun` and `inv_fun` outside of `source` and `target`). In particular, the equality notion between local equivs is not "the right one", i.e., coinciding source and target and equality there. Moreover, there are no local equivs in this sense between an empty type and a nonempty type. Since empty types are not that useful, and since one almost never needs to talk about equal local equivs, this is not an issue in practice. Still, we introduce an equivalence relation `eq_on_source` that captures this right notion of equality, and show that many properties are invariant under this equivalence relation. -/ -- register in the simpset `mfld_simps` several lemmas that are often useful when dealing -- with manifolds namespace tactic.interactive /-- A very basic tactic to show that sets showing up in manifolds coincide or are included in one another. -/ end tactic.interactive /-- Local equivalence between subsets `source` and `target` of α and β respectively. The (global) maps `to_fun : α → β` and `inv_fun : β → α` map `source` to `target` and conversely, and are inverse to each other there. The values of `to_fun` outside of `source` and of `inv_fun` outside of `target` are irrelevant. -/ structure local_equiv (α : Type u_5) (β : Type u_6) where to_fun : α → β inv_fun : β → α source : set α target : set β map_source' : ∀ {x : α}, x ∈ source → to_fun x ∈ target map_target' : ∀ {x : β}, x ∈ target → inv_fun x ∈ source left_inv' : ∀ {x : α}, x ∈ source → inv_fun (to_fun x) = x right_inv' : ∀ {x : β}, x ∈ target → to_fun (inv_fun x) = x /-- Associating a local_equiv to an equiv-/ def equiv.to_local_equiv {α : Type u_1} {β : Type u_2} (e : α ≃ β) : local_equiv α β := local_equiv.mk (equiv.to_fun e) (equiv.inv_fun e) set.univ set.univ sorry sorry sorry sorry namespace local_equiv /-- The inverse of a local equiv -/ protected def symm {α : Type u_1} {β : Type u_2} (e : local_equiv α β) : local_equiv β α := mk (inv_fun e) (to_fun e) (target e) (source e) (map_target' e) (map_source' e) (right_inv' e) (left_inv' e) protected instance has_coe_to_fun {α : Type u_1} {β : Type u_2} : has_coe_to_fun (local_equiv α β) := has_coe_to_fun.mk (fun (x : local_equiv α β) => α → β) to_fun @[simp] theorem coe_mk {α : Type u_1} {β : Type u_2} (f : α → β) (g : β → α) (s : set α) (t : set β) (ml : ∀ {x : α}, x ∈ s → f x ∈ t) (mr : ∀ {x : β}, x ∈ t → g x ∈ s) (il : ∀ {x : α}, x ∈ s → g (f x) = x) (ir : ∀ {x : β}, x ∈ t → f (g x) = x) : ⇑(mk f g s t ml mr il ir) = f := rfl @[simp] theorem coe_symm_mk {α : Type u_1} {β : Type u_2} (f : α → β) (g : β → α) (s : set α) (t : set β) (ml : ∀ {x : α}, x ∈ s → f x ∈ t) (mr : ∀ {x : β}, x ∈ t → g x ∈ s) (il : ∀ {x : α}, x ∈ s → g (f x) = x) (ir : ∀ {x : β}, x ∈ t → f (g x) = x) : ⇑(local_equiv.symm (mk f g s t ml mr il ir)) = g := rfl @[simp] theorem to_fun_as_coe {α : Type u_1} {β : Type u_2} (e : local_equiv α β) : to_fun e = ⇑e := rfl @[simp] theorem inv_fun_as_coe {α : Type u_1} {β : Type u_2} (e : local_equiv α β) : inv_fun e = ⇑(local_equiv.symm e) := rfl @[simp] theorem map_source {α : Type u_1} {β : Type u_2} (e : local_equiv α β) {x : α} (h : x ∈ source e) : coe_fn e x ∈ target e := map_source' e h protected theorem maps_to {α : Type u_1} {β : Type u_2} (e : local_equiv α β) : set.maps_to (⇑e) (source e) (target e) := fun (_x : α) => map_source e @[simp] theorem map_target {α : Type u_1} {β : Type u_2} (e : local_equiv α β) {x : β} (h : x ∈ target e) : coe_fn (local_equiv.symm e) x ∈ source e := map_target' e h theorem symm_maps_to {α : Type u_1} {β : Type u_2} (e : local_equiv α β) : set.maps_to (⇑(local_equiv.symm e)) (target e) (source e) := local_equiv.maps_to (local_equiv.symm e) @[simp] theorem left_inv {α : Type u_1} {β : Type u_2} (e : local_equiv α β) {x : α} (h : x ∈ source e) : coe_fn (local_equiv.symm e) (coe_fn e x) = x := left_inv' e h protected theorem left_inv_on {α : Type u_1} {β : Type u_2} (e : local_equiv α β) : set.left_inv_on (⇑(local_equiv.symm e)) (⇑e) (source e) := fun (_x : α) => left_inv e @[simp] theorem right_inv {α : Type u_1} {β : Type u_2} (e : local_equiv α β) {x : β} (h : x ∈ target e) : coe_fn e (coe_fn (local_equiv.symm e) x) = x := right_inv' e h protected theorem right_inv_on {α : Type u_1} {β : Type u_2} (e : local_equiv α β) : set.right_inv_on (⇑(local_equiv.symm e)) (⇑e) (target e) := fun (_x : β) => right_inv e /-- Associating to a local_equiv an equiv between the source and the target -/ protected def to_equiv {α : Type u_1} {β : Type u_2} (e : local_equiv α β) : ↥(source e) ≃ ↥(target e) := equiv.mk (fun (x : ↥(source e)) => { val := coe_fn e ↑x, property := sorry }) (fun (y : ↥(target e)) => { val := coe_fn (local_equiv.symm e) ↑y, property := sorry }) sorry sorry @[simp] theorem symm_source {α : Type u_1} {β : Type u_2} (e : local_equiv α β) : source (local_equiv.symm e) = target e := rfl @[simp] theorem symm_target {α : Type u_1} {β : Type u_2} (e : local_equiv α β) : target (local_equiv.symm e) = source e := rfl @[simp] theorem symm_symm {α : Type u_1} {β : Type u_2} (e : local_equiv α β) : local_equiv.symm (local_equiv.symm e) = e := sorry /-- A local equiv induces a bijection between its source and target -/ theorem bij_on_source {α : Type u_1} {β : Type u_2} (e : local_equiv α β) : set.bij_on (⇑e) (source e) (target e) := set.inv_on.bij_on { left := local_equiv.left_inv_on e, right := local_equiv.right_inv_on e } (local_equiv.maps_to e) (symm_maps_to e) theorem image_eq_target_inter_inv_preimage {α : Type u_1} {β : Type u_2} (e : local_equiv α β) {s : set α} (h : s ⊆ source e) : ⇑e '' s = target e ∩ ⇑(local_equiv.symm e) ⁻¹' s := sorry theorem image_inter_source_eq {α : Type u_1} {β : Type u_2} (e : local_equiv α β) (s : set α) : ⇑e '' (s ∩ source e) = target e ∩ ⇑(local_equiv.symm e) ⁻¹' (s ∩ source e) := image_eq_target_inter_inv_preimage e (set.inter_subset_right s (source e)) theorem image_inter_source_eq' {α : Type u_1} {β : Type u_2} (e : local_equiv α β) (s : set α) : ⇑e '' (s ∩ source e) = target e ∩ ⇑(local_equiv.symm e) ⁻¹' s := sorry theorem symm_image_eq_source_inter_preimage {α : Type u_1} {β : Type u_2} (e : local_equiv α β) {s : set β} (h : s ⊆ target e) : ⇑(local_equiv.symm e) '' s = source e ∩ ⇑e ⁻¹' s := image_eq_target_inter_inv_preimage (local_equiv.symm e) h theorem symm_image_inter_target_eq {α : Type u_1} {β : Type u_2} (e : local_equiv α β) (s : set β) : ⇑(local_equiv.symm e) '' (s ∩ target e) = source e ∩ ⇑e ⁻¹' (s ∩ target e) := image_inter_source_eq (local_equiv.symm e) s theorem symm_image_inter_target_eq' {α : Type u_1} {β : Type u_2} (e : local_equiv α β) (s : set β) : ⇑(local_equiv.symm e) '' (s ∩ target e) = source e ∩ ⇑e ⁻¹' s := image_inter_source_eq' (local_equiv.symm e) s theorem source_inter_preimage_inv_preimage {α : Type u_1} {β : Type u_2} (e : local_equiv α β) (s : set α) : source e ∩ ⇑e ⁻¹' (⇑(local_equiv.symm e) ⁻¹' s) = source e ∩ s := sorry theorem target_inter_inv_preimage_preimage {α : Type u_1} {β : Type u_2} (e : local_equiv α β) (s : set β) : target e ∩ ⇑(local_equiv.symm e) ⁻¹' (⇑e ⁻¹' s) = target e ∩ s := source_inter_preimage_inv_preimage (local_equiv.symm e) s theorem image_source_eq_target {α : Type u_1} {β : Type u_2} (e : local_equiv α β) : ⇑e '' source e = target e := set.bij_on.image_eq (bij_on_source e) theorem source_subset_preimage_target {α : Type u_1} {β : Type u_2} (e : local_equiv α β) : source e ⊆ ⇑e ⁻¹' target e := fun (x : α) (hx : x ∈ source e) => map_source e hx theorem inv_image_target_eq_source {α : Type u_1} {β : Type u_2} (e : local_equiv α β) : ⇑(local_equiv.symm e) '' target e = source e := set.bij_on.image_eq (bij_on_source (local_equiv.symm e)) theorem target_subset_preimage_source {α : Type u_1} {β : Type u_2} (e : local_equiv α β) : target e ⊆ ⇑(local_equiv.symm e) ⁻¹' source e := fun (x : β) (hx : x ∈ target e) => map_target e hx /-- Two local equivs that have the same `source`, same `to_fun` and same `inv_fun`, coincide. -/ protected theorem ext {α : Type u_1} {β : Type u_2} {e : local_equiv α β} {e' : local_equiv α β} (h : ∀ (x : α), coe_fn e x = coe_fn e' x) (hsymm : ∀ (x : β), coe_fn (local_equiv.symm e) x = coe_fn (local_equiv.symm e') x) (hs : source e = source e') : e = e' := sorry /-- Restricting a local equivalence to e.source ∩ s -/ protected def restr {α : Type u_1} {β : Type u_2} (e : local_equiv α β) (s : set α) : local_equiv α β := mk (⇑e) (⇑(local_equiv.symm e)) (source e ∩ s) (target e ∩ ⇑(local_equiv.symm e) ⁻¹' s) sorry sorry sorry sorry @[simp] theorem restr_coe {α : Type u_1} {β : Type u_2} (e : local_equiv α β) (s : set α) : ⇑(local_equiv.restr e s) = ⇑e := rfl @[simp] theorem restr_coe_symm {α : Type u_1} {β : Type u_2} (e : local_equiv α β) (s : set α) : ⇑(local_equiv.symm (local_equiv.restr e s)) = ⇑(local_equiv.symm e) := rfl @[simp] theorem restr_source {α : Type u_1} {β : Type u_2} (e : local_equiv α β) (s : set α) : source (local_equiv.restr e s) = source e ∩ s := rfl @[simp] theorem restr_target {α : Type u_1} {β : Type u_2} (e : local_equiv α β) (s : set α) : target (local_equiv.restr e s) = target e ∩ ⇑(local_equiv.symm e) ⁻¹' s := rfl theorem restr_eq_of_source_subset {α : Type u_1} {β : Type u_2} {e : local_equiv α β} {s : set α} (h : source e ⊆ s) : local_equiv.restr e s = e := sorry @[simp] theorem restr_univ {α : Type u_1} {β : Type u_2} {e : local_equiv α β} : local_equiv.restr e set.univ = e := restr_eq_of_source_subset (set.subset_univ (source e)) /-- The identity local equiv -/ protected def refl (α : Type u_1) : local_equiv α α := equiv.to_local_equiv (equiv.refl α) @[simp] theorem refl_source {α : Type u_1} : source (local_equiv.refl α) = set.univ := rfl @[simp] theorem refl_target {α : Type u_1} : target (local_equiv.refl α) = set.univ := rfl @[simp] theorem refl_coe {α : Type u_1} : ⇑(local_equiv.refl α) = id := rfl @[simp] theorem refl_symm {α : Type u_1} : local_equiv.symm (local_equiv.refl α) = local_equiv.refl α := rfl @[simp] theorem refl_restr_source {α : Type u_1} (s : set α) : source (local_equiv.restr (local_equiv.refl α) s) = s := sorry @[simp] theorem refl_restr_target {α : Type u_1} (s : set α) : target (local_equiv.restr (local_equiv.refl α) s) = s := sorry /-- The identity local equiv on a set `s` -/ def of_set {α : Type u_1} (s : set α) : local_equiv α α := mk id id s s sorry sorry sorry sorry @[simp] theorem of_set_source {α : Type u_1} (s : set α) : source (of_set s) = s := rfl @[simp] theorem of_set_target {α : Type u_1} (s : set α) : target (of_set s) = s := rfl @[simp] theorem of_set_coe {α : Type u_1} (s : set α) : ⇑(of_set s) = id := rfl @[simp] theorem of_set_symm {α : Type u_1} (s : set α) : local_equiv.symm (of_set s) = of_set s := rfl /-- Composing two local equivs if the target of the first coincides with the source of the second. -/ protected def trans' {α : Type u_1} {β : Type u_2} {γ : Type u_3} (e : local_equiv α β) (e' : local_equiv β γ) (h : target e = source e') : local_equiv α γ := mk (⇑e' ∘ ⇑e) (⇑(local_equiv.symm e) ∘ ⇑(local_equiv.symm e')) (source e) (target e') sorry sorry sorry sorry /-- Composing two local equivs, by restricting to the maximal domain where their composition is well defined. -/ protected def trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} (e : local_equiv α β) (e' : local_equiv β γ) : local_equiv α γ := local_equiv.trans' (local_equiv.symm (local_equiv.restr (local_equiv.symm e) (source e'))) (local_equiv.restr e' (target e)) sorry @[simp] theorem coe_trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} (e : local_equiv α β) (e' : local_equiv β γ) : ⇑(local_equiv.trans e e') = ⇑e' ∘ ⇑e := rfl @[simp] theorem coe_trans_symm {α : Type u_1} {β : Type u_2} {γ : Type u_3} (e : local_equiv α β) (e' : local_equiv β γ) : ⇑(local_equiv.symm (local_equiv.trans e e')) = ⇑(local_equiv.symm e) ∘ ⇑(local_equiv.symm e') := rfl theorem trans_symm_eq_symm_trans_symm {α : Type u_1} {β : Type u_2} {γ : Type u_3} (e : local_equiv α β) (e' : local_equiv β γ) : local_equiv.symm (local_equiv.trans e e') = local_equiv.trans (local_equiv.symm e') (local_equiv.symm e) := sorry @[simp] theorem trans_source {α : Type u_1} {β : Type u_2} {γ : Type u_3} (e : local_equiv α β) (e' : local_equiv β γ) : source (local_equiv.trans e e') = source e ∩ ⇑e ⁻¹' source e' := rfl theorem trans_source' {α : Type u_1} {β : Type u_2} {γ : Type u_3} (e : local_equiv α β) (e' : local_equiv β γ) : source (local_equiv.trans e e') = source e ∩ ⇑e ⁻¹' (target e ∩ source e') := sorry theorem trans_source'' {α : Type u_1} {β : Type u_2} {γ : Type u_3} (e : local_equiv α β) (e' : local_equiv β γ) : source (local_equiv.trans e e') = ⇑(local_equiv.symm e) '' (target e ∩ source e') := sorry theorem image_trans_source {α : Type u_1} {β : Type u_2} {γ : Type u_3} (e : local_equiv α β) (e' : local_equiv β γ) : ⇑e '' source (local_equiv.trans e e') = target e ∩ source e' := image_source_eq_target (local_equiv.symm (local_equiv.restr (local_equiv.symm e) (source e'))) @[simp] theorem trans_target {α : Type u_1} {β : Type u_2} {γ : Type u_3} (e : local_equiv α β) (e' : local_equiv β γ) : target (local_equiv.trans e e') = target e' ∩ ⇑(local_equiv.symm e') ⁻¹' target e := rfl theorem trans_target' {α : Type u_1} {β : Type u_2} {γ : Type u_3} (e : local_equiv α β) (e' : local_equiv β γ) : target (local_equiv.trans e e') = target e' ∩ ⇑(local_equiv.symm e') ⁻¹' (source e' ∩ target e) := trans_source' (local_equiv.symm e') (local_equiv.symm e) theorem trans_target'' {α : Type u_1} {β : Type u_2} {γ : Type u_3} (e : local_equiv α β) (e' : local_equiv β γ) : target (local_equiv.trans e e') = ⇑e' '' (source e' ∩ target e) := trans_source'' (local_equiv.symm e') (local_equiv.symm e) theorem inv_image_trans_target {α : Type u_1} {β : Type u_2} {γ : Type u_3} (e : local_equiv α β) (e' : local_equiv β γ) : ⇑(local_equiv.symm e') '' target (local_equiv.trans e e') = source e' ∩ target e := image_trans_source (local_equiv.symm e') (local_equiv.symm e) theorem trans_assoc {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (e : local_equiv α β) (e' : local_equiv β γ) (e'' : local_equiv γ δ) : local_equiv.trans (local_equiv.trans e e') e'' = local_equiv.trans e (local_equiv.trans e' e'') := sorry @[simp] theorem trans_refl {α : Type u_1} {β : Type u_2} (e : local_equiv α β) : local_equiv.trans e (local_equiv.refl β) = e := sorry @[simp] theorem refl_trans {α : Type u_1} {β : Type u_2} (e : local_equiv α β) : local_equiv.trans (local_equiv.refl α) e = e := sorry theorem trans_refl_restr {α : Type u_1} {β : Type u_2} (e : local_equiv α β) (s : set β) : local_equiv.trans e (local_equiv.restr (local_equiv.refl β) s) = local_equiv.restr e (⇑e ⁻¹' s) := sorry theorem trans_refl_restr' {α : Type u_1} {β : Type u_2} (e : local_equiv α β) (s : set β) : local_equiv.trans e (local_equiv.restr (local_equiv.refl β) s) = local_equiv.restr e (source e ∩ ⇑e ⁻¹' s) := sorry theorem restr_trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} (e : local_equiv α β) (e' : local_equiv β γ) (s : set α) : local_equiv.trans (local_equiv.restr e s) e' = local_equiv.restr (local_equiv.trans e e') s := sorry /-- `eq_on_source e e'` means that `e` and `e'` have the same source, and coincide there. Then `e` and `e'` should really be considered the same local equiv. -/ def eq_on_source {α : Type u_1} {β : Type u_2} (e : local_equiv α β) (e' : local_equiv α β) := source e = source e' ∧ set.eq_on (⇑e) (⇑e') (source e) /-- `eq_on_source` is an equivalence relation -/ protected instance eq_on_source_setoid {α : Type u_1} {β : Type u_2} : setoid (local_equiv α β) := setoid.mk eq_on_source sorry theorem eq_on_source_refl {α : Type u_1} {β : Type u_2} (e : local_equiv α β) : e ≈ e := setoid.refl e /-- Two equivalent local equivs have the same source -/ theorem eq_on_source.source_eq {α : Type u_1} {β : Type u_2} {e : local_equiv α β} {e' : local_equiv α β} (h : e ≈ e') : source e = source e' := and.left h /-- Two equivalent local equivs coincide on the source -/ theorem eq_on_source.eq_on {α : Type u_1} {β : Type u_2} {e : local_equiv α β} {e' : local_equiv α β} (h : e ≈ e') : set.eq_on (⇑e) (⇑e') (source e) := and.right h /-- Two equivalent local equivs have the same target -/ theorem eq_on_source.target_eq {α : Type u_1} {β : Type u_2} {e : local_equiv α β} {e' : local_equiv α β} (h : e ≈ e') : target e = target e' := sorry /-- If two local equivs are equivalent, so are their inverses. -/ theorem eq_on_source.symm' {α : Type u_1} {β : Type u_2} {e : local_equiv α β} {e' : local_equiv α β} (h : e ≈ e') : local_equiv.symm e ≈ local_equiv.symm e' := sorry /-- Two equivalent local equivs have coinciding inverses on the target -/ theorem eq_on_source.symm_eq_on {α : Type u_1} {β : Type u_2} {e : local_equiv α β} {e' : local_equiv α β} (h : e ≈ e') : set.eq_on (⇑(local_equiv.symm e)) (⇑(local_equiv.symm e')) (target e) := eq_on_source.eq_on (eq_on_source.symm' h) /-- Composition of local equivs respects equivalence -/ theorem eq_on_source.trans' {α : Type u_1} {β : Type u_2} {γ : Type u_3} {e : local_equiv α β} {e' : local_equiv α β} {f : local_equiv β γ} {f' : local_equiv β γ} (he : e ≈ e') (hf : f ≈ f') : local_equiv.trans e f ≈ local_equiv.trans e' f' := sorry /-- Restriction of local equivs respects equivalence -/ theorem eq_on_source.restr {α : Type u_1} {β : Type u_2} {e : local_equiv α β} {e' : local_equiv α β} (he : e ≈ e') (s : set α) : local_equiv.restr e s ≈ local_equiv.restr e' s := sorry /-- Preimages are respected by equivalence -/ theorem eq_on_source.source_inter_preimage_eq {α : Type u_1} {β : Type u_2} {e : local_equiv α β} {e' : local_equiv α β} (he : e ≈ e') (s : set β) : source e ∩ ⇑e ⁻¹' s = source e' ∩ ⇑e' ⁻¹' s := sorry /-- Composition of a local equiv and its inverse is equivalent to the restriction of the identity to the source -/ theorem trans_self_symm {α : Type u_1} {β : Type u_2} (e : local_equiv α β) : local_equiv.trans e (local_equiv.symm e) ≈ of_set (source e) := sorry /-- Composition of the inverse of a local equiv and this local equiv is equivalent to the restriction of the identity to the target -/ theorem trans_symm_self {α : Type u_1} {β : Type u_2} (e : local_equiv α β) : local_equiv.trans (local_equiv.symm e) e ≈ of_set (target e) := trans_self_symm (local_equiv.symm e) /-- Two equivalent local equivs are equal when the source and target are univ -/ theorem eq_of_eq_on_source_univ {α : Type u_1} {β : Type u_2} (e : local_equiv α β) (e' : local_equiv α β) (h : e ≈ e') (s : source e = set.univ) (t : target e = set.univ) : e = e' := sorry /-- The product of two local equivs, as a local equiv on the product. -/ def prod {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (e : local_equiv α β) (e' : local_equiv γ δ) : local_equiv (α × γ) (β × δ) := mk (fun (p : α × γ) => (coe_fn e (prod.fst p), coe_fn e' (prod.snd p))) (fun (p : β × δ) => (coe_fn (local_equiv.symm e) (prod.fst p), coe_fn (local_equiv.symm e') (prod.snd p))) (set.prod (source e) (source e')) (set.prod (target e) (target e')) sorry sorry sorry sorry @[simp] theorem prod_source {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (e : local_equiv α β) (e' : local_equiv γ δ) : source (prod e e') = set.prod (source e) (source e') := rfl @[simp] theorem prod_target {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (e : local_equiv α β) (e' : local_equiv γ δ) : target (prod e e') = set.prod (target e) (target e') := rfl @[simp] theorem prod_coe {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (e : local_equiv α β) (e' : local_equiv γ δ) : ⇑(prod e e') = fun (p : α × γ) => (coe_fn e (prod.fst p), coe_fn e' (prod.snd p)) := rfl theorem prod_coe_symm {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (e : local_equiv α β) (e' : local_equiv γ δ) : ⇑(local_equiv.symm (prod e e')) = fun (p : β × δ) => (coe_fn (local_equiv.symm e) (prod.fst p), coe_fn (local_equiv.symm e') (prod.snd p)) := rfl @[simp] theorem prod_symm {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} (e : local_equiv α β) (e' : local_equiv γ δ) : local_equiv.symm (prod e e') = prod (local_equiv.symm e) (local_equiv.symm e') := sorry @[simp] theorem prod_trans {α : Type u_1} {β : Type u_2} {γ : Type u_3} {δ : Type u_4} {η : Type u_5} {ε : Type u_6} (e : local_equiv α β) (f : local_equiv β γ) (e' : local_equiv δ η) (f' : local_equiv η ε) : local_equiv.trans (prod e e') (prod f f') = prod (local_equiv.trans e f) (local_equiv.trans e' f') := sorry end local_equiv namespace set -- All arguments are explicit to avoid missing information in the pretty printer output /-- A bijection between two sets `s : set α` and `t : set β` provides a local equivalence between `α` and `β`. -/ @[simp] theorem bij_on.to_local_equiv_inv_fun {α : Type u_1} {β : Type u_2} [Nonempty α] (f : α → β) (s : set α) (t : set β) (hf : bij_on f s t) (b : β) : local_equiv.inv_fun (bij_on.to_local_equiv f s t hf) b = function.inv_fun_on f s b := Eq.refl (local_equiv.inv_fun (bij_on.to_local_equiv f s t hf) b) /-- A map injective on a subset of its domain provides a local equivalence. -/ @[simp] def inj_on.to_local_equiv {α : Type u_1} {β : Type u_2} [Nonempty α] (f : α → β) (s : set α) (hf : inj_on f s) : local_equiv α β := bij_on.to_local_equiv f s (f '' s) (inj_on.bij_on_image hf) end set namespace equiv /- equivs give rise to local_equiv. We set up simp lemmas to reduce most properties of the local equiv to that of the equiv. -/ @[simp] theorem to_local_equiv_coe {α : Type u_1} {β : Type u_2} (e : α ≃ β) : ⇑(to_local_equiv e) = ⇑e := rfl @[simp] theorem to_local_equiv_symm_coe {α : Type u_1} {β : Type u_2} (e : α ≃ β) : ⇑(local_equiv.symm (to_local_equiv e)) = ⇑(equiv.symm e) := rfl @[simp] theorem to_local_equiv_source {α : Type u_1} {β : Type u_2} (e : α ≃ β) : local_equiv.source (to_local_equiv e) = set.univ := rfl @[simp] theorem to_local_equiv_target {α : Type u_1} {β : Type u_2} (e : α ≃ β) : local_equiv.target (to_local_equiv e) = set.univ := rfl @[simp] theorem refl_to_local_equiv {α : Type u_1} : to_local_equiv (equiv.refl α) = local_equiv.refl α := rfl @[simp] theorem symm_to_local_equiv {α : Type u_1} {β : Type u_2} (e : α ≃ β) : to_local_equiv (equiv.symm e) = local_equiv.symm (to_local_equiv e) := rfl @[simp] theorem trans_to_local_equiv {α : Type u_1} {β : Type u_2} {γ : Type u_3} (e : α ≃ β) (e' : β ≃ γ) : to_local_equiv (equiv.trans e e') = local_equiv.trans (to_local_equiv e) (to_local_equiv e') := sorry end Mathlib
67ccd3a0855fb7a24aabf92bb0b1385465babf1b
8cae430f0a71442d02dbb1cbb14073b31048e4b0
/src/topology/algebra/infinite_sum/order.lean
24371cd77237c94966dabe5795540d1d611c9119
[ "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,633
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 algebra.order.archimedean import topology.algebra.infinite_sum.basic import topology.algebra.order.field import topology.algebra.order.monotone_convergence /-! # Infinite sum in an order > THIS FILE IS SYNCHRONIZED WITH MATHLIB4. > Any changes to this file require a corresponding PR to mathlib4. This file provides lemmas about the interaction of infinite sums and order operations. -/ open finset filter function open_locale big_operators classical variables {ι κ α : Type*} section preorder variables [preorder α] [add_comm_monoid α] [topological_space α] [order_closed_topology α] [t2_space α] {f : ℕ → α} {c : α} lemma tsum_le_of_sum_range_le (hf : summable f) (h : ∀ n, ∑ i in range n, f i ≤ c) : ∑' n, f n ≤ c := let ⟨l, hl⟩ := hf in hl.tsum_eq.symm ▸ le_of_tendsto' hl.tendsto_sum_nat h end preorder section ordered_add_comm_monoid variables [ordered_add_comm_monoid α] [topological_space α] [order_closed_topology α] {f g : ι → α} {a a₁ a₂ : α} lemma has_sum_le (h : ∀ i, f i ≤ g i) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := le_of_tendsto_of_tendsto' hf hg $ λ s, sum_le_sum $ λ i _, h i @[mono] lemma has_sum_mono (hf : has_sum f a₁) (hg : has_sum g a₂) (h : f ≤ g) : a₁ ≤ a₂ := has_sum_le h hf hg lemma has_sum_le_of_sum_le (hf : has_sum f a) (h : ∀ s, ∑ i in s, f i ≤ a₂) : a ≤ a₂ := le_of_tendsto' hf h lemma le_has_sum_of_le_sum (hf : has_sum f a) (h : ∀ s, a₂ ≤ ∑ i in s, f i) : a₂ ≤ a := ge_of_tendsto' hf h lemma has_sum_le_inj {g : κ → α} (e : ι → κ) (he : injective e) (hs : ∀ c ∉ set.range e, 0 ≤ g c) (h : ∀ i, f i ≤ g (e i)) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ ≤ a₂ := have has_sum (λ c, (partial_inv e c).cases_on' 0 f) a₁, begin refine (has_sum_iff_has_sum_of_ne_zero_bij (e ∘ coe) (λ c₁ c₂ hc, he hc) (λ c hc, _) _).2 hf, { rw mem_support at hc, cases eq : partial_inv e c with i; rw eq at hc, { contradiction }, { rw [partial_inv_of_injective he] at eq, exact ⟨⟨i, hc⟩, eq⟩ } }, { rintro c, simp [partial_inv_left he, option.cases_on'] } end, begin refine has_sum_le (λ c, _) this hg, obtain ⟨i, rfl⟩ | h := em (c ∈ set.range e), { rw [partial_inv_left he, option.cases_on'], exact h _ }, { have : partial_inv e c = none := dif_neg h, rw [this, option.cases_on'], exact hs _ h } end lemma tsum_le_tsum_of_inj {g : κ → α} (e : ι → κ) (he : injective e) (hs : ∀ c ∉ set.range e, 0 ≤ g c) (h : ∀ i, f i ≤ g (e i)) (hf : summable f) (hg : summable g) : tsum f ≤ tsum g := has_sum_le_inj _ he hs h hf.has_sum hg.has_sum lemma sum_le_has_sum (s : finset ι) (hs : ∀ i ∉ s, 0 ≤ f i) (hf : has_sum f a) : ∑ i in s, f i ≤ a := ge_of_tendsto hf (eventually_at_top.2 ⟨s, λ t hst, sum_le_sum_of_subset_of_nonneg hst $ λ i hbt hbs, hs i hbs⟩) lemma is_lub_has_sum (h : ∀ i, 0 ≤ f i) (hf : has_sum f a) : is_lub (set.range $ λ s, ∑ i in s, f i) a := is_lub_of_tendsto_at_top (finset.sum_mono_set_of_nonneg h) hf lemma le_has_sum (hf : has_sum f a) (i : ι) (hb : ∀ b' ≠ i, 0 ≤ f b') : f i ≤ a := calc f i = ∑ i in {i}, f i : finset.sum_singleton.symm ... ≤ a : sum_le_has_sum _ (by { convert hb, simp }) hf lemma sum_le_tsum {f : ι → α} (s : finset ι) (hs : ∀ i ∉ s, 0 ≤ f i) (hf : summable f) : ∑ i in s, f i ≤ ∑' i, f i := sum_le_has_sum s hs hf.has_sum lemma le_tsum (hf : summable f) (i : ι) (hb : ∀ b' ≠ i, 0 ≤ f b') : f i ≤ ∑' i, f i := le_has_sum (summable.has_sum hf) i hb lemma tsum_le_tsum (h : ∀ i, f i ≤ g i) (hf : summable f) (hg : summable g) : ∑' i, f i ≤ ∑' i, g i := has_sum_le h hf.has_sum hg.has_sum @[mono] lemma tsum_mono (hf : summable f) (hg : summable g) (h : f ≤ g) : ∑' n, f n ≤ ∑' n, g n := tsum_le_tsum h hf hg lemma tsum_le_of_sum_le (hf : summable f) (h : ∀ s, ∑ i in s, f i ≤ a₂) : ∑' i, f i ≤ a₂ := has_sum_le_of_sum_le hf.has_sum h lemma tsum_le_of_sum_le' (ha₂ : 0 ≤ a₂) (h : ∀ s, ∑ i in s, f i ≤ a₂) : ∑' i, f i ≤ a₂ := begin by_cases hf : summable f, { exact tsum_le_of_sum_le hf h }, { rw tsum_eq_zero_of_not_summable hf, exact ha₂ } end lemma has_sum.nonneg (h : ∀ i, 0 ≤ g i) (ha : has_sum g a) : 0 ≤ a := has_sum_le h has_sum_zero ha lemma has_sum.nonpos (h : ∀ i, g i ≤ 0) (ha : has_sum g a) : a ≤ 0 := has_sum_le h ha has_sum_zero lemma tsum_nonneg (h : ∀ i, 0 ≤ g i) : 0 ≤ ∑' i, g i := begin by_cases hg : summable g, { exact hg.has_sum.nonneg h }, { simp [tsum_eq_zero_of_not_summable hg] } end lemma tsum_nonpos (h : ∀ i, f i ≤ 0) : ∑' i, f i ≤ 0 := begin by_cases hf : summable f, { exact hf.has_sum.nonpos h }, { simp [tsum_eq_zero_of_not_summable hf] } end end ordered_add_comm_monoid section ordered_add_comm_group variables [ordered_add_comm_group α] [topological_space α] [topological_add_group α] [order_closed_topology α] {f g : ι → α} {a₁ a₂ : α} {i : ι} lemma has_sum_lt (h : f ≤ g) (hi : f i < g i) (hf : has_sum f a₁) (hg : has_sum g a₂) : a₁ < a₂ := have update f i 0 ≤ update g i 0 := update_le_update_iff.mpr ⟨rfl.le, λ i _, h i⟩, have 0 - f i + a₁ ≤ 0 - g i + a₂ := has_sum_le this (hf.update i 0) (hg.update i 0), by simpa only [zero_sub, add_neg_cancel_left] using add_lt_add_of_lt_of_le hi this @[mono] lemma has_sum_strict_mono (hf : has_sum f a₁) (hg : has_sum g a₂) (h : f < g) : a₁ < a₂ := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in has_sum_lt hle hi hf hg lemma tsum_lt_tsum (h : f ≤ g) (hi : f i < g i) (hf : summable f) (hg : summable g) : ∑' n, f n < ∑' n, g n := has_sum_lt h hi hf.has_sum hg.has_sum @[mono] lemma tsum_strict_mono (hf : summable f) (hg : summable g) (h : f < g) : ∑' n, f n < ∑' n, g n := let ⟨hle, i, hi⟩ := pi.lt_def.mp h in tsum_lt_tsum hle hi hf hg lemma tsum_pos (hsum : summable g) (hg : ∀ i, 0 ≤ g i) (i : ι) (hi : 0 < g i) : 0 < ∑' i, g i := by { rw ←tsum_zero, exact tsum_lt_tsum hg hi summable_zero hsum } lemma has_sum_zero_iff_of_nonneg (hf : ∀ i, 0 ≤ f i) : has_sum f 0 ↔ f = 0 := begin refine ⟨λ hf', _, _⟩, { ext i, refine (hf i).eq_of_not_gt (λ hi, _), simpa using has_sum_lt hf hi has_sum_zero hf' }, { rintro rfl, exact has_sum_zero } end end ordered_add_comm_group section canonically_ordered_add_monoid variables [canonically_ordered_add_monoid α] [topological_space α] [order_closed_topology α] {f : ι → α} {a : α} lemma le_has_sum' (hf : has_sum f a) (i : ι) : f i ≤ a := le_has_sum hf i $ λ _ _, zero_le _ lemma le_tsum' (hf : summable f) (i : ι) : f i ≤ ∑' i, f i := le_tsum hf i $ λ _ _, zero_le _ lemma has_sum_zero_iff : has_sum f 0 ↔ ∀ x, f x = 0 := begin refine ⟨_, λ h, _⟩, { contrapose!, exact λ ⟨x, hx⟩ h, hx (nonpos_iff_eq_zero.1$ le_has_sum' h x) }, { convert has_sum_zero, exact funext h } end lemma tsum_eq_zero_iff (hf : summable f) : ∑' i, f i = 0 ↔ ∀ x, f x = 0 := by rw [←has_sum_zero_iff, hf.has_sum_iff] lemma tsum_ne_zero_iff (hf : summable f) : ∑' i, f i ≠ 0 ↔ ∃ x, f x ≠ 0 := by rw [ne.def, tsum_eq_zero_iff hf, not_forall] lemma is_lub_has_sum' (hf : has_sum f a) : is_lub (set.range $ λ s, ∑ i in s, f i) a := is_lub_of_tendsto_at_top (finset.sum_mono_set f) hf end canonically_ordered_add_monoid section linear_order /-! For infinite sums taking values in a linearly ordered monoid, the existence of a least upper bound for the finite sums is a criterion for summability. This criterion is useful when applied in a linearly ordered monoid which is also a complete or conditionally complete linear order, such as `ℝ`, `ℝ≥0`, `ℝ≥0∞`, because it is then easy to check the existence of a least upper bound. -/ lemma has_sum_of_is_lub_of_nonneg [linear_ordered_add_comm_monoid α] [topological_space α] [order_topology α] {f : ι → α} (i : α) (h : ∀ i, 0 ≤ f i) (hf : is_lub (set.range $ λ s, ∑ i in s, f i) i) : has_sum f i := tendsto_at_top_is_lub (finset.sum_mono_set_of_nonneg h) hf lemma has_sum_of_is_lub [canonically_linear_ordered_add_monoid α] [topological_space α] [order_topology α] {f : ι → α} (b : α) (hf : is_lub (set.range $ λ s, ∑ i in s, f i) b) : has_sum f b := tendsto_at_top_is_lub (finset.sum_mono_set f) hf lemma summable_abs_iff [linear_ordered_add_comm_group α] [uniform_space α] [uniform_add_group α] [complete_space α] {f : ι → α} : summable (λ x, |f x|) ↔ summable f := have h1 : ∀ x : {x | 0 ≤ f x}, |f x| = f x := λ x, abs_of_nonneg x.2, have h2 : ∀ x : {x | 0 ≤ f x}ᶜ, |f x| = -f x := λ x, abs_of_neg (not_le.1 x.2), calc summable (λ x, |f x|) ↔ summable (λ x : {x | 0 ≤ f x}, |f x|) ∧ summable (λ x : {x | 0 ≤ f x}ᶜ, |f x|) : summable_subtype_and_compl.symm ... ↔ summable (λ x : {x | 0 ≤ f x}, f x) ∧ summable (λ x : {x | 0 ≤ f x}ᶜ, -f x) : by simp only [h1, h2] ... ↔ _ : by simp only [summable_neg_iff, summable_subtype_and_compl] alias summable_abs_iff ↔ summable.of_abs summable.abs --TODO: Change the conclusion to `finite ι` lemma finite_of_summable_const [linear_ordered_add_comm_group α] [topological_space α] [archimedean α] [order_closed_topology α] {b : α} (hb : 0 < b) (hf : summable (λ i : ι, b)) : (set.univ : set ι).finite := begin have H : ∀ s : finset ι, s.card • b ≤ ∑' i : ι, b, { intros s, simpa using sum_le_has_sum s (λ a ha, hb.le) hf.has_sum }, obtain ⟨n, hn⟩ := archimedean.arch (∑' i : ι, b) hb, have : ∀ s : finset ι, s.card ≤ n, { intros s, simpa [nsmul_le_nsmul_iff hb] using (H s).trans hn }, haveI : fintype ι := fintype_of_finset_card_le n this, exact set.finite_univ end end linear_order lemma summable.tendsto_top_of_pos [linear_ordered_field α] [topological_space α] [order_topology α] {f : ℕ → α} (hf : summable f⁻¹) (hf' : ∀ n, 0 < f n) : tendsto f at_top at_top := begin rw ←inv_inv f, apply filter.tendsto.inv_tendsto_zero, apply tendsto_nhds_within_of_tendsto_nhds_of_eventually_within _ (summable.tendsto_at_top_zero hf), rw eventually_iff_exists_mem, refine ⟨set.Ioi 0, Ioi_mem_at_top _, λ _ _, _⟩, rw [set.mem_Ioi, inv_eq_one_div, one_div, pi.inv_apply, _root_.inv_pos], exact hf' _, end
d99935953564a62516ca37752a94fcf6f65eef67
77c5b91fae1b966ddd1db969ba37b6f0e4901e88
/src/data/nat/factorial/basic.lean
02234da69b69fe914aa20ae37e5b3ae9352e6c04
[ "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
14,936
lean
/- Copyright (c) 2018 Mario Carneiro. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Mario Carneiro, Chris Hughes, Floris van Doorn, Yaël Dillies -/ import data.nat.basic import data.nat.pow /-! # Factorial and variants This file defines the factorial, along with the ascending and descending variants. ## Main declarations * `factorial`: The factorial. * `asc_factorial`: The ascending factorial. Note that it runs from `n + 1` to `n + k` and *not* from`n` to `n + k - 1`. We might want to change that in the future. * `desc_factorial`: The descending factorial. It runs from `n - k` to `n`. -/ namespace nat /-- `nat.factorial n` is the factorial of `n`. -/ @[simp] def factorial : ℕ → ℕ | 0 := 1 | (succ n) := succ n * factorial n localized "notation n `!`:10000 := nat.factorial n" in nat section factorial variables {m n : ℕ} @[simp] theorem factorial_zero : 0! = 1 := rfl @[simp] theorem factorial_succ (n : ℕ) : n.succ! = succ n * n! := rfl @[simp] theorem factorial_one : 1! = 1 := rfl @[simp] theorem factorial_two : 2! = 2 := rfl theorem mul_factorial_pred (hn : 0 < n) : n * (n - 1)! = n! := nat.sub_add_cancel hn ▸ rfl theorem factorial_pos : ∀ n, 0 < n! | 0 := zero_lt_one | (succ n) := mul_pos (succ_pos _) (factorial_pos n) theorem factorial_ne_zero (n : ℕ) : n! ≠ 0 := ne_of_gt (factorial_pos _) theorem factorial_dvd_factorial {m n} (h : m ≤ n) : m! ∣ n! := begin induction n with n IH; simp, { have := nat.eq_zero_of_le_zero h, subst m, simp }, obtain he | hl := h.eq_or_lt, { subst m, simp }, exact (IH (le_of_lt_succ hl)).mul_left _, end theorem dvd_factorial : ∀ {m n}, 0 < m → m ≤ n → m ∣ n! | (succ m) n _ h := dvd_of_mul_right_dvd (factorial_dvd_factorial h) @[mono] theorem factorial_le {m n} (h : m ≤ n) : m! ≤ n! := le_of_dvd (factorial_pos _) (factorial_dvd_factorial h) lemma factorial_mul_pow_le_factorial : ∀ {m n : ℕ}, m! * m.succ ^ n ≤ (m + n)! | m 0 := by simp | m (n+1) := by rw [← add_assoc, nat.factorial_succ, mul_comm (nat.succ _), pow_succ', ← mul_assoc]; exact mul_le_mul factorial_mul_pow_le_factorial (nat.succ_le_succ (nat.le_add_right _ _)) (nat.zero_le _) (nat.zero_le _) lemma monotone_factorial : monotone factorial := λ n m, factorial_le lemma factorial_lt (hn : 0 < n) : n! < m! ↔ n < m := begin split; intro h, { rw [← not_le], intro hmn, apply not_le_of_lt h (factorial_le hmn) }, have : ∀ n, 0 < n → n! < n.succ!, { intros k hk, rw [factorial_succ, succ_mul, lt_add_iff_pos_left], apply mul_pos hk (factorial_pos k) }, induction h with k hnk generalizing hn, { exact this _ hn, }, refine lt_trans (h_ih hn) (this _ _), exact lt_trans hn (lt_of_succ_le hnk), end lemma one_lt_factorial : 1 < n! ↔ 1 < n := by { convert factorial_lt _, refl, exact one_pos } lemma factorial_eq_one : n! = 1 ↔ n ≤ 1 := begin split; intro h, { rw [← not_lt, ← one_lt_factorial, h], apply lt_irrefl }, cases h with h h, refl, cases h, refl, end lemma factorial_inj (hn : 1 < n!) : n! = m! ↔ n = m := begin split; intro h, { obtain hnm | hnm | hnm := lt_trichotomy n m, { exfalso, rw [← factorial_lt, h] at hnm, exact lt_irrefl _ hnm, rw [one_lt_factorial] at hn, exact lt_trans one_pos hn }, { exact hnm }, exfalso, rw [h, one_lt_factorial] at hn, rw [←factorial_lt (lt_trans one_pos hn), h] at hnm, exact lt_irrefl _ hnm, }, { rw h }, end lemma self_le_factorial : ∀ n : ℕ, n ≤ n! | 0 := zero_le_one | (k + 1) := le_mul_of_one_le_right k.zero_lt_succ.le (nat.one_le_of_lt $ nat.factorial_pos _) lemma lt_factorial_self {n : ℕ} (hi : 3 ≤ n) : n < n! := begin rw [← succ_pred_eq_of_pos ((zero_lt_two.trans (lt.base 2)).trans_le hi), factorial_succ], exact lt_mul_of_one_lt_right ((pred n).succ_pos) ((one_lt_two.trans_le (le_pred_of_lt (succ_le_iff.mp hi))).trans_le (self_le_factorial _)), end lemma add_factorial_succ_lt_factorial_add_succ {i : ℕ} (n : ℕ) (hi : 2 ≤ i) : i + (n + 1)! < (i + n + 1)! := begin rw [factorial_succ (i + _), succ_eq_add_one, add_mul, one_mul], have : i ≤ i + n := le.intro rfl, exact add_lt_add_of_lt_of_le (this.trans_lt ((lt_mul_iff_one_lt_right (zero_lt_two.trans_le (hi.trans this))).mpr (lt_iff_le_and_ne.mpr ⟨(i + n).factorial_pos, λ g, nat.not_succ_le_self 1 ((hi.trans this).trans (factorial_eq_one.mp g.symm))⟩))) (factorial_le ((le_of_eq (add_comm n 1)).trans ((add_le_add_iff_right n).mpr (one_le_two.trans hi)))), end lemma add_factorial_lt_factorial_add {i n : ℕ} (hi : 2 ≤ i) (hn : 1 ≤ n) : i + n! < (i + n)! := begin cases hn, { rw factorial_one, exact lt_factorial_self (succ_le_succ hi) }, exact add_factorial_succ_lt_factorial_add_succ _ hi, end lemma add_factorial_succ_le_factorial_add_succ (i : ℕ) (n : ℕ) : i + (n + 1)! ≤ (i + (n + 1))! := begin obtain i2 | (_ | ⟨_, i0⟩) := le_or_lt 2 i, { exact (n.add_factorial_succ_lt_factorial_add_succ i2).le }, { change 1 + (n + 1)! ≤ (1 + n + 1) * (1 + n)!, rw [add_mul, one_mul, add_comm 1 n], exact (add_le_add_iff_right _).mpr (one_le_mul (nat.le_add_left 1 n) (n + 1).factorial_pos) }, rw [nat.le_zero_iff.mp (nat.succ_le_succ_iff.mp i0), zero_add, zero_add] end lemma add_factorial_le_factorial_add (i : ℕ) {n : ℕ} (n1 : 1 ≤ n) : i + n! ≤ (i + n)! := begin cases n1 with h, { exact self_le_factorial _ }, exact add_factorial_succ_le_factorial_add_succ i h, end lemma factorial_mul_pow_sub_le_factorial {n m : ℕ} (hnm : n ≤ m) : n! * n ^ (m - n) ≤ m! := begin suffices : n! * (n + 1) ^ (m - n) ≤ m!, { apply trans _ this, rw mul_le_mul_left, apply pow_le_pow_of_le_left (zero_le n) (le_succ n), exact factorial_pos n,}, convert nat.factorial_mul_pow_le_factorial, exact (nat.add_sub_of_le hnm).symm, end end factorial /-! ### Ascending and descending factorials -/ section asc_factorial /-- `n.asc_factorial k = (n + k)! / n!` (as seen in `nat.asc_factorial_eq_div`), but implemented recursively to allow for "quick" computation when using `norm_num`. This is closely related to `pochhammer`, but much less general. -/ def asc_factorial (n : ℕ) : ℕ → ℕ | 0 := 1 | (k + 1) := (n + k + 1) * asc_factorial k @[simp] lemma asc_factorial_zero (n : ℕ) : n.asc_factorial 0 = 1 := rfl @[simp] lemma zero_asc_factorial (k : ℕ) : (0 : ℕ).asc_factorial k = k! := begin induction k with t ht, refl, unfold asc_factorial, rw [ht, zero_add, nat.factorial_succ], end lemma asc_factorial_succ {n k : ℕ} : n.asc_factorial k.succ = (n + k + 1) * n.asc_factorial k := rfl lemma succ_asc_factorial (n : ℕ) : ∀ k, (n + 1) * n.succ.asc_factorial k = (n + k + 1) * n.asc_factorial k | 0 := by rw [add_zero, asc_factorial_zero, asc_factorial_zero] | (k + 1) := by rw [asc_factorial, mul_left_comm, succ_asc_factorial, asc_factorial, succ_add, ←add_assoc] /-- `n.asc_factorial k = (n + k)! / n!` but without ℕ-division. See `nat.asc_factorial_eq_div` for the version with ℕ-division. -/ theorem factorial_mul_asc_factorial (n : ℕ) : ∀ k, n! * n.asc_factorial k = (n + k)! | 0 := by rw [asc_factorial, add_zero, mul_one] | (k + 1) := by rw [asc_factorial_succ, mul_left_comm, factorial_mul_asc_factorial, ← add_assoc, factorial] /-- Avoid in favor of `nat.factorial_mul_asc_factorial` if you can. ℕ-division isn't worth it. -/ lemma asc_factorial_eq_div (n k : ℕ) : n.asc_factorial k = (n + k)! / n! := begin apply mul_left_cancel₀ (factorial_ne_zero n), rw factorial_mul_asc_factorial, exact (nat.mul_div_cancel' $ factorial_dvd_factorial $ le.intro rfl).symm end lemma asc_factorial_of_sub {n k : ℕ} (h : k < n) : (n - k) * (n - k).asc_factorial k = (n - (k + 1)).asc_factorial (k + 1) := begin set t := n - k.succ with ht, suffices h' : n - k = t.succ, by rw [←ht, h', succ_asc_factorial, asc_factorial_succ], rw [ht, succ_eq_add_one, ←sub_sub_assoc h (succ_pos _), succ_sub_one], end lemma pow_succ_le_asc_factorial (n : ℕ) : ∀ (k : ℕ), (n + 1)^k ≤ n.asc_factorial k | 0 := by rw [asc_factorial_zero, pow_zero] | (k + 1) := begin rw pow_succ, exact nat.mul_le_mul (nat.add_le_add_right le_self_add _) (pow_succ_le_asc_factorial k), end lemma pow_lt_asc_factorial' (n k : ℕ) : (n + 1)^(k + 2) < n.asc_factorial (k + 2) := begin rw pow_succ, exact nat.mul_lt_mul (nat.add_lt_add_right (nat.lt_add_of_pos_right succ_pos') 1) (pow_succ_le_asc_factorial n _) (pow_pos succ_pos' _), end lemma pow_lt_asc_factorial (n : ℕ) : ∀ {k : ℕ}, 2 ≤ k → (n + 1)^k < n.asc_factorial k | 0 := by rintro ⟨⟩ | 1 := by rintro (_ | ⟨_, ⟨⟩⟩) | (k + 2) := λ _, pow_lt_asc_factorial' n k lemma asc_factorial_le_pow_add (n : ℕ) : ∀ (k : ℕ), n.asc_factorial k ≤ (n + k)^k | 0 := by rw [asc_factorial_zero, pow_zero] | (k + 1) := begin rw [asc_factorial_succ, pow_succ], exact nat.mul_le_mul_of_nonneg_left ((asc_factorial_le_pow_add k).trans (nat.pow_le_pow_of_le_left (le_succ _) _)), end lemma asc_factorial_lt_pow_add (n : ℕ) : ∀ {k : ℕ}, 2 ≤ k → n.asc_factorial k < (n + k)^k | 0 := by rintro ⟨⟩ | 1 := by rintro (_ | ⟨_, ⟨⟩⟩) | (k + 2) := λ _, begin rw [asc_factorial_succ, pow_succ], refine nat.mul_lt_mul' (le_refl _) ((asc_factorial_le_pow_add n _).trans_lt (pow_lt_pow_of_lt_left (lt_add_one _) (succ_pos _))) (succ_pos _), end lemma asc_factorial_pos (n k : ℕ) : 0 < n.asc_factorial k := (pow_pos (succ_pos n) k).trans_le (pow_succ_le_asc_factorial n k) end asc_factorial section desc_factorial /-- `n.desc_factorial k = n! / (n - k)!` (as seen in `nat.desc_factorial_eq_div`), but implemented recursively to allow for "quick" computation when using `norm_num`. This is closely related to `pochhammer`, but much less general. -/ def desc_factorial (n : ℕ) : ℕ → ℕ | 0 := 1 | (k + 1) := (n - k) * desc_factorial k @[simp] lemma desc_factorial_zero (n : ℕ) : n.desc_factorial 0 = 1 := rfl @[simp] lemma desc_factorial_succ (n k : ℕ) : n.desc_factorial k.succ = (n - k) * n.desc_factorial k := rfl lemma zero_desc_factorial_succ (k : ℕ) : (0 : ℕ).desc_factorial k.succ = 0 := by rw [desc_factorial_succ, nat.zero_sub, zero_mul] @[simp] lemma desc_factorial_one (n : ℕ) : n.desc_factorial 1 = n := by rw [desc_factorial_succ, desc_factorial_zero, mul_one, nat.sub_zero] @[simp] lemma succ_desc_factorial_succ (n : ℕ) : ∀ k : ℕ, (n + 1).desc_factorial (k + 1) = (n + 1) * n.desc_factorial k | 0 := by rw [desc_factorial_zero, desc_factorial_one, mul_one] | (succ k) := by rw [desc_factorial_succ, succ_desc_factorial_succ, desc_factorial_succ, succ_sub_succ, mul_left_comm] lemma succ_desc_factorial (n : ℕ) : ∀ k, (n + 1 - k) * (n + 1).desc_factorial k = (n + 1) * n.desc_factorial k | 0 := by rw [nat.sub_zero, desc_factorial_zero, desc_factorial_zero] | (k + 1) := by rw [desc_factorial, succ_desc_factorial, desc_factorial_succ, succ_sub_succ, mul_left_comm] lemma desc_factorial_self : ∀ n : ℕ, n.desc_factorial n = n! | 0 := by rw [desc_factorial_zero, factorial_zero] | (succ n) := by rw [succ_desc_factorial_succ, desc_factorial_self, factorial_succ] @[simp] lemma desc_factorial_eq_zero_iff_lt {n : ℕ} : ∀ {k : ℕ}, n.desc_factorial k = 0 ↔ n < k | 0 := by simp only [desc_factorial_zero, nat.one_ne_zero, nat.not_lt_zero] | (succ k) := begin rw [desc_factorial_succ, mul_eq_zero, desc_factorial_eq_zero_iff_lt, lt_succ_iff, nat.sub_eq_zero_iff_le, lt_iff_le_and_ne, or_iff_left_iff_imp, and_imp], exact λ h _, h, end alias nat.desc_factorial_eq_zero_iff_lt ↔ _ nat.desc_factorial_of_lt lemma add_desc_factorial_eq_asc_factorial (n : ℕ) : ∀ k : ℕ, (n + k).desc_factorial k = n.asc_factorial k | 0 := by rw [asc_factorial_zero, desc_factorial_zero] | (succ k) := by rw [nat.add_succ, succ_desc_factorial_succ, asc_factorial_succ, add_desc_factorial_eq_asc_factorial] /-- `n.desc_factorial k = n! / (n - k)!` but without ℕ-division. See `nat.desc_factorial_eq_div` for the version using ℕ-division. -/ theorem factorial_mul_desc_factorial : ∀ {n k : ℕ}, k ≤ n → (n - k)! * n.desc_factorial k = n! | n 0 := λ _, by rw [desc_factorial_zero, mul_one, nat.sub_zero] | 0 (succ k) := λ h, by { exfalso, exact not_succ_le_zero k h } | (succ n) (succ k) := λ h, by rw [succ_desc_factorial_succ, succ_sub_succ, ←mul_assoc, mul_comm (n - k)!, mul_assoc, factorial_mul_desc_factorial (nat.succ_le_succ_iff.1 h), factorial_succ] /-- Avoid in favor of `nat.factorial_mul_desc_factorial` if you can. ℕ-division isn't worth it. -/ lemma desc_factorial_eq_div {n k : ℕ} (h : k ≤ n) : n.desc_factorial k = n! / (n - k)! := begin apply mul_left_cancel₀ (factorial_ne_zero (n - k)), rw factorial_mul_desc_factorial h, exact (nat.mul_div_cancel' $ factorial_dvd_factorial $ nat.sub_le n k).symm, end lemma pow_sub_le_desc_factorial (n : ℕ) : ∀ (k : ℕ), (n + 1 - k)^k ≤ n.desc_factorial k | 0 := by rw [desc_factorial_zero, pow_zero] | (k + 1) := begin rw [desc_factorial_succ, pow_succ, succ_sub_succ], exact nat.mul_le_mul_of_nonneg_left (le_trans (nat.pow_le_pow_of_le_left (nat.sub_le_sub_right (le_succ _) _) k) (pow_sub_le_desc_factorial k)), end lemma pow_sub_lt_desc_factorial' {n : ℕ} : ∀ {k : ℕ}, k + 2 ≤ n → (n - (k + 1))^(k + 2) < n.desc_factorial (k + 2) | 0 := λ h, begin rw [desc_factorial_succ, pow_succ, pow_one, desc_factorial_one], exact nat.mul_lt_mul_of_pos_left (nat.sub_lt_self (lt_of_lt_of_le zero_lt_two h) zero_lt_one) (nat.sub_pos_of_lt h), end | (k + 1) := λ h, begin rw [desc_factorial_succ, pow_succ], refine nat.mul_lt_mul_of_pos_left ((nat.pow_le_pow_of_le_left (nat.sub_le_sub_right (le_succ n) _) _).trans_lt _) (nat.sub_pos_of_lt h), rw succ_sub_succ, exact (pow_sub_lt_desc_factorial' ((le_succ _).trans h)), end lemma pow_sub_lt_desc_factorial {n : ℕ} : ∀ {k : ℕ}, 2 ≤ k → k ≤ n → (n + 1 - k)^k < n.desc_factorial k | 0 := by rintro ⟨⟩ | 1 := by rintro (_ | ⟨_, ⟨⟩⟩) | (k + 2) := λ _ h, by { rw succ_sub_succ, exact pow_sub_lt_desc_factorial' h } lemma desc_factorial_le_pow (n : ℕ) : ∀ (k : ℕ), n.desc_factorial k ≤ n^k | 0 := by rw [desc_factorial_zero, pow_zero] | (k + 1) := begin rw [desc_factorial_succ, pow_succ], exact nat.mul_le_mul (nat.sub_le _ _) (desc_factorial_le_pow k), end lemma desc_factorial_lt_pow {n : ℕ} (hn : 1 ≤ n) : ∀ {k : ℕ}, 2 ≤ k → n.desc_factorial k < n^k | 0 := by rintro ⟨⟩ | 1 := by rintro (_ | ⟨_, ⟨⟩⟩) | (k + 2) := λ _, begin rw [desc_factorial_succ, pow_succ', mul_comm], exact nat.mul_lt_mul' (desc_factorial_le_pow _ _) (nat.sub_lt_self hn k.zero_lt_succ) (pow_pos hn _), end end desc_factorial end nat
b61d67f84ea7d47489681f32e2ba65ed49a3985a
e030b0259b777fedcdf73dd966f3f1556d392178
/tests/lean/run/IO2.lean
065ad0cdac57bb4a8966ca6a6370fb50c7be321c
[ "Apache-2.0" ]
permissive
fgdorais/lean
17b46a095b70b21fa0790ce74876658dc5faca06
c3b7c54d7cca7aaa25328f0a5660b6b75fe26055
refs/heads/master
1,611,523,590,686
1,484,412,902,000
1,484,412,902,000
38,489,734
0
0
null
1,435,923,380,000
1,435,923,379,000
null
UTF-8
Lean
false
false
392
lean
import system.io open list /- B and unit must be in the same universe So, we must put B at Type₁ or use poly_unit since unit is at Type₁ -/ definition foreach {A : Type} {B : Type} : list A → (A → io B) → io poly_unit | [] f := return poly_unit.star | (x::xs) f := do f x, foreach xs f vm_eval foreach [1,2,3,4,5] (λ i, do put_str "value: ", put_nat i, put_str "\n")
9f29391587f4b24f16a0bc05d99278d24a578d65
618003631150032a5676f229d13a079ac875ff77
/src/category_theory/connected.lean
a9e3b1d6b8cf75b0f48c51fd93643b3d9a71dbf3
[ "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
8,802
lean
/- Copyright (c) 2020 Bhavik Mehta. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Bhavik Mehta -/ import category_theory.const import category_theory.discrete_category import category_theory.eq_to_hom /-! # Connected category Define a connected category as a _nonempty_ category for which every functor to a discrete category is isomorphic to the constant functor. NB. Some authors include the empty category as connected, we do not. We instead are interested in categories with exactly one 'connected component'. We give some equivalent definitions: - A nonempty category for which every functor to a discrete category is constant on objects. See `any_functor_const_on_obj` and `connected.of_any_functor_const_on_obj`. - A nonempty category for which every function `F` for which the presence of a morphism `f : j₁ ⟶ j₂` implies `F j₁ = F j₂` must be constant everywhere. See `constant_of_preserves_morphisms` and `connected.of_constant_of_preserves_morphisms`. - A nonempty category for which any subset of its elements containing the default and closed under morphisms is everything. See `induct_on_objects` and `connected.of_induct`. - A nonempty category for which every object is related under the reflexive transitive closure of the relation "there is a morphism in some direction from `j₁` to `j₂`". See `connected_zigzag` and `zigzag_connected`. - A nonempty category for which for any two objects there is a sequence of morphisms (some reversed) from one to the other. See `exists_zigzag'` and `connected_of_zigzag`. We also prove the result that the functor given by `(X × -)` preserves any connected limit. That is, any limit of shape `J` where `J` is a connected category is preserved by the functor `(X × -)`. -/ universes v₁ v₂ u₁ u₂ open category_theory.category namespace category_theory section connected -- See note [default priority] set_option default_priority 100 /-- We define a connected category as a _nonempty_ category for which every functor to a discrete category is constant. NB. Some authors include the empty category as connected, we do not. We instead are interested in categories with exactly one 'connected component'. This allows us to show that the functor X ⨯ - preserves connected limits. -/ class connected (J : Type v₂) [category.{v₁} J] extends inhabited J := (iso_constant : Π {α : Type v₂} (F : J ⥤ discrete α), F ≅ (functor.const J).obj (F.obj default)) end connected variables {J : Type v₂} [category.{v₁} J] /-- If J is connected, any functor to a discrete category is constant on objects. The converse is given in `connected.of_any_functor_const_on_obj`. -/ lemma any_functor_const_on_obj [connected J] {α : Type v₂} (F : J ⥤ discrete α) (j : J) : F.obj j = F.obj (default J) := ((connected.iso_constant F).hom.app j).down.1 /-- If any functor to a discrete category is constant on objects, J is connected. The converse of `any_functor_const_on_obj`. -/ def connected.of_any_functor_const_on_obj [inhabited J] (h : ∀ {α : Type v₂} (F : J ⥤ discrete α), ∀ (j : J), F.obj j = F.obj (default J)) : connected J := { iso_constant := λ α F, nat_iso.of_components (λ B, eq_to_iso (h F B)) (λ _ _ _, subsingleton.elim _ _) } /-- If `J` is connected, then given any function `F` such that the presence of a morphism `j₁ ⟶ j₂` implies `F j₁ = F j₂`, we have that `F` is constant. This can be thought of as a local-to-global property. The converse is shown in `connected.of_constant_of_preserves_morphisms` -/ lemma constant_of_preserves_morphisms [connected J] {α : Type v₂} (F : J → α) (h : ∀ (j₁ j₂ : J) (f : j₁ ⟶ j₂), F j₁ = F j₂) (j : J) : F j = F (default J) := any_functor_const_on_obj { obj := F, map := λ _ _ f, eq_to_hom (h _ _ f) } j /-- `J` is connected if: given any function `F : J → α` which is constant for any `j₁, j₂` for which there is a morphism `j₁ ⟶ j₂`, then `F` is constant. This can be thought of as a local-to-global property. The converse of `constant_of_preserves_morphisms`. -/ def connected.of_constant_of_preserves_morphisms [inhabited J] (h : ∀ {α : Type v₂} (F : J → α), (∀ {j₁ j₂ : J} (f : j₁ ⟶ j₂), F j₁ = F j₂) → (∀ j : J, F j = F (default J))) : connected J := connected.of_any_functor_const_on_obj (λ _ F, h F.obj (λ _ _ f, (F.map f).down.1)) /-- An inductive-like property for the objects of a connected category. If `default J` is in the set `p`, and `p` is closed under morphisms of `J`, then `p` contains all of `J`. The converse is given in `connected.of_induct`. -/ lemma induct_on_objects [connected J] (p : set J) (h0 : default J ∈ p) (h1 : ∀ {j₁ j₂ : J} (f : j₁ ⟶ j₂), j₁ ∈ p ↔ j₂ ∈ p) (j : J) : j ∈ p := begin injection (constant_of_preserves_morphisms (λ k, ulift.up (k ∈ p)) (λ j₁ j₂ f, _) j) with i, rwa i, dsimp, exact congr_arg ulift.up (propext (h1 f)), end /-- If any maximal connected component of J containing the default is all of J, then J is connected. The converse of `induct_on_objects`. -/ def connected.of_induct [inhabited J] (h : ∀ (p : set J), default J ∈ p → (∀ {j₁ j₂ : J} (f : j₁ ⟶ j₂), j₁ ∈ p ↔ j₂ ∈ p) → ∀ (j : J), j ∈ p) : connected J := connected.of_constant_of_preserves_morphisms (λ α F a, h {j | F j = F (default J)} rfl (λ _ _ f, by simp [a f] )) /-- j₁ and j₂ are related by `zag` if there is a morphism between them. -/ @[reducible] def zag (j₁ j₂ : J) : Prop := nonempty (j₁ ⟶ j₂) ∨ nonempty (j₂ ⟶ j₁) /-- `j₁` and `j₂` are related by `zigzag` if there is a chain of morphisms from `j₁` to `j₂`, with backward morphisms allowed. -/ @[reducible] def zigzag : J → J → Prop := relation.refl_trans_gen zag /-- Any equivalence relation containing (⟶) holds for all pairs of a connected category. -/ lemma equiv_relation [connected J] (r : J → J → Prop) (hr : _root_.equivalence r) (h : ∀ {j₁ j₂ : J} (f : j₁ ⟶ j₂), r j₁ j₂) : ∀ (j₁ j₂ : J), r j₁ j₂ := begin have z: ∀ (j : J), r (default J) j := induct_on_objects (λ k, r (default J) k) (hr.1 (default J)) (λ _ _ f, ⟨λ t, hr.2.2 t (h f), λ t, hr.2.2 t (hr.2.1 (h f))⟩), intros, apply hr.2.2 (hr.2.1 (z _)) (z _) end /-- In a connected category, any two objects are related by `zigzag`. -/ lemma connected_zigzag [connected J] (j₁ j₂ : J) : zigzag j₁ j₂ := equiv_relation _ (mk_equivalence _ relation.reflexive_refl_trans_gen (relation.refl_trans_gen.symmetric (λ _ _ _, by rwa [zag, or_comm])) relation.transitive_refl_trans_gen) (λ _ _ f, relation.refl_trans_gen.single (or.inl (nonempty.intro f))) _ _ /-- If any two objects in an inhabited category are related by `zigzag`, the category is connected. -/ def zigzag_connected [inhabited J] (h : ∀ (j₁ j₂ : J), zigzag j₁ j₂) : connected J := begin apply connected.of_induct, intros, have: ∀ (j₁ j₂ : J), zigzag j₁ j₂ → (j₁ ∈ p ↔ j₂ ∈ p), { introv k, induction k, { refl }, { rw k_ih, rcases k_a_1 with ⟨⟨_⟩⟩ | ⟨⟨_⟩⟩, apply a_1 k_a_1, apply (a_1 k_a_1).symm } }, rwa this j (default J) (h _ _) end lemma exists_zigzag' [connected J] (j₁ j₂ : J) : ∃ l, list.chain zag j₁ l ∧ list.last (j₁ :: l) (list.cons_ne_nil _ _) = j₂ := list.exists_chain_of_relation_refl_trans_gen (connected_zigzag _ _) /-- If any two objects in an inhabited category are linked by a sequence of (potentially reversed) morphisms, then J is connected. The converse of `exists_zigzag'`. -/ def connected_of_zigzag [inhabited J] (h : ∀ (j₁ j₂ : J), ∃ l, list.chain zag j₁ l ∧ list.last (j₁ :: l) (list.cons_ne_nil _ _) = j₂) : connected J := begin apply connected.of_induct, intros p d k j, obtain ⟨l, zags, lst⟩ := h j (default J), apply list.chain.induction p l zags lst _ d, rintros _ _ (⟨⟨_⟩⟩ | ⟨⟨_⟩⟩), { exact (k a).2 }, { exact (k a).1 } end variables {C : Type u₂} [category.{v₂} C] /-- For objects `X Y : C`, any natural transformation `α : const X ⟶ const Y` from a connected category must be constant. This is the key property of connected categories which we use to establish properties about limits. -/ lemma nat_trans_from_connected [conn : connected J] {X Y : C} (α : (functor.const J).obj X ⟶ (functor.const J).obj Y) : ∀ (j : J), α.app j = (α.app (default J) : X ⟶ Y) := @constant_of_preserves_morphisms _ _ _ (X ⟶ Y) (λ j, α.app j) (λ _ _ f, (by { have := α.naturality f, erw [id_comp, comp_id] at this, exact this.symm })) end category_theory
70adfe23ae0b83e4acdd8b49a3678c1b506b0165
ebf7140a9ea507409ff4c994124fa36e79b4ae35
/src/solutions/thursday/order.lean
bd5ab73211c4dd4692546c0b2f0fa70bb8e5ce67
[]
no_license
fundou/lftcm2020
3e88d58a92755ea5dd49f19c36239c35286ecf5e
99d11bf3bcd71ffeaef0250caa08ecc46e69b55b
refs/heads/master
1,685,610,799,304
1,624,070,416,000
1,624,070,416,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
19,816
lean
/- # Orders Groups, rings, fields, modules etc are in the "algebra hierarchy". Metric and topological spaces are in the "topology hierarchy". The other important hierarchy is the "order hierarchy". It starts with partially ordered sets, and then goes on to lattices. Because I like algebra, let's demonstrate the order hierarchy by making an algebraic type, namely the type of subgroups of a group G, and then working up the order hierarchy with it. Subgroups of a group are ordered by inclusion, and this is where we shall start. We will then define infs and sups, and bot and top, and go on from there. -/ import tactic -- We will be using all of the theory of subsets of a type -- without further comment (e.g. `inter_subset_left A B : A ∩ B ⊆ A`) -- so let's open the `set` namespace. open set -- The type of subgroups of a group G is called `subgroup G` in Lean. -- It already has a lattice structure in Lean. -- So let's just redo the entire theory and call it `subgp G`. /-- The type of subgroups of a group `G`. -/ structure subgp (G : Type) [group G] := -- A subgroup of G is a sub*set* of G, called `carrier` (carrier : set G) -- and then axioms saying it's closed under the group structure (i.e. *, 1, ⁻¹) (mul_mem {a b : G} : a ∈ carrier → b ∈ carrier → a * b ∈ carrier) (one_mem : (1 : G) ∈ carrier) (inv_mem {a : G} : a ∈ carrier → a⁻¹ ∈ carrier) namespace subgp /- Note in particular that we have a function `subgp.carrier : subgp G → set G`, sending a subgroup of `G` to the underlying subset (`set G` is the type of subsets of G). -/ -- Let G be a group, let H,J,K be subgroups of G, and let a,b,c be elements of G. variables {G : Type} [group G] (H J K : subgp G) (a b c : G) /- # Extensionality One of the first things you should consider proving about a newly-defined type is an extensionality lemma: a sensible criterion to check that two terms are equal. When are two subgroups of `G` equal? A subgroup is defined by four things: a subset, and three proofs. But two proofs of a proposition `P` are equal by definition in Lean, so two subgroups of `G` are equal iff their underlying subsets are equal, which is true iff their underlying subsets have the same elements. Let's give names to these basic results because they'll show up everywhere. Let's start by showing that two subgroups are equal if their underlying subsets are equal. This is precisely the statement that `∀ H J : subgp G, H.carrier = J.carrier → H = J`, and a good name for this would be `carrier_injective`. We adopt the Lean tradition of putting as many things to the left of the `:` as we can; it doesn't change the statement of the theorem. -/ lemma carrier_injective (H J : subgp G) (h : H.carrier = J.carrier) : H = J := begin -- take H and J apart cases H, cases J, -- and note that they are the same set, and then a bunch of proofs -- which are equal by definition, so it's obvious simp * at *, end -- Now let's prove that two subgroups are equal iff they have the same elements. -- This is the most useful "extensionality lemma" so we tag it `@[ext]`. @[ext] theorem ext {H J : subgp G} (h : ∀ (x : G), x ∈ H.carrier ↔ x ∈ J.carrier) : H = J := begin -- it suffices to prove the subsets are equal apply carrier_injective, -- Now let's use extensionality for subsets ext x, exact h x, end -- We also want the `iff` version of this. theorem ext_iff {H J : subgp G} : H = J ↔ ∀ (x : G), x ∈ H.carrier ↔ x ∈ J.carrier := begin -- sorry split, { -- one way is just a rewrite! intro h, rw h, simp, }, { -- the other way we just did exact subgp.ext, } -- sorry end /- ## Partial orders -/ -- These are familiar to most mathematicians. We will put a partial order -- structure on `subgp G`. In other words, we will create a term of -- type `partial_order (subgp G)`. -- Let's define `H ≤ J` to mean `H.carrier ⊆ J.carrier`, using the `has_le` notation typeclass instance : has_le (subgp G) := ⟨λ H J, H.carrier ⊆ J.carrier⟩ -- "tidy" is a one-size-fits-all tactic which solves certain kinds of "follow your nose" goals. instance : partial_order (subgp G) := { le := (≤), le_refl := by tidy, le_trans := by tidy, le_antisymm := by tidy } /- Here is a second proof. If X → Y is injective, and Y is partially ordered, then X inherits a partial order. This construction (it's not a theorem, because it involves data) is called `partial_order.lift`. Applying it to the injection `subgp.carrier` and the fact that Lean already knows that `set G` is partially ordered, turns into this second construction, (which I won't call an `instance` because if I did then I would have committed the sin of making two terms of type `partial_order (subgp G)`, and `partial_order (subgp G)` is a class so should have at most one instance): -/ -- partial_order.lift is the function which pulls a partial order back along an injection. example : partial_order (subgp G) := partial_order.lift subgp.carrier carrier_injective /- Note that we magically just inherited `<` notatation, because `#check partial_order` tells you that `partial_order` extends `preorder`, which extends `has_lt`, which is a notation typeclass. In other words, `#check (H < J)` makes sense, and is a `Prop`. In fact `H < J` is defined to mean `H ≤ J ∧ ¬ (J ≤ H)`. # From partial orders to lattices. Let's now prove that `subgp G` is a `semilattice_inf_top`. This is a class which extends `partial_order` -- it is a partial order equipped with a top element, and a function `inf : subgp G → subgp G → subgp G` (called "inf" or "meet" or "greatest lower bound", satisfying some axioms. In our case, `top` will be the subgroup `G` of `G` (or more precisely `univ`), and `inf` will just be intersection. The work we need to do is to check that these are subgroups, and to prove the axioms for a `semilattice_inf_top`, which we'll come to later. First let's define `top` -- the biggest subgroup. The underlying carrier is `univ : set G`, i.e. the subset `G` of `G`. I'll leave it to you to prove that the subgroup axioms hold! The useful piece of interface for `univ` you'll need is `mem_univ g : g ∈ univ`. -/ def top : subgp G := { carrier := set.univ, mul_mem := begin -- sorry intros, apply mem_univ, -- sorry end, one_mem := begin -- sorry apply mem_univ, -- sorry end, inv_mem := begin -- sorry intros, apply mem_univ, -- sorry end } -- Add the `⊤` notation (typed with `\top`) for this subgroup: instance : has_top (subgp G) := ⟨top⟩ -- Now `#check (⊤ : subgp G)` works /- We'll now prove the theorem that the intersection of two subgroups is a subgroup. This is a *definition* in Lean, indeed it is a construction which given two subgroups `H` and `K` of `G` produces a third subgroup `H ⊓ K` (Lean's notation for `inf H K`). The part of the interface for `∩` you'll need is that `a ∈ B ∩ C` is definitionally equal to `a ∈ B ∧ a ∈ C`, so you can use `split` if you have a goal `⊢ a ∈ B ∩ C`, and you can use `cases h` if you have a hypothesis `h : a ∈ B ∩ C`. Don't forget `mul_mem H`, `one_mem H` and `inv_mem H`, the axioms for `H` if `H : subgp G`. -/ /-- "Theorem" : intersection of two subgps is a subgp -/ definition inf (H K : subgp G) : subgp G := { carrier := H.carrier ∩ K.carrier, mul_mem := begin -- sorry rintros a b ⟨haH, haK⟩ ⟨hbH, hbK⟩, split, { apply H.mul_mem haH hbH }, { apply K.mul_mem haK hbK }, -- sorry end, one_mem := begin -- sorry split, { apply one_mem }, { apply one_mem }, -- sorry end, inv_mem := begin -- sorry rintros a ⟨haH, haK⟩, exact ⟨H.inv_mem haH, K.inv_mem haK⟩, -- sorry end } -- Add the `⊓` notation (type with `\inf`) for the intersection (inf) of two subgroups: instance : has_inf (subgp G) := ⟨inf⟩ -- We now check the four axioms for a semilattice_inf_top. -- They are called `le_top`, `inf_le_left`, `inf_le_right` and `le_inf`. -- You might be able to guess the statementss of the axioms -- from their names. lemma le_top (H : subgp G) : H ≤ ⊤ := begin -- sorry intros x hx, apply mem_univ, -- sorry end lemma inf_le_left (H K : subgp G) : H ⊓ K ≤ H := begin -- by definition this says `H.carrier ∩ K.carrier ⊆ H.carrier` change H.carrier ∩ K.carrier ⊆ H.carrier, -- now try `library_search`, to find that this is called `inter_subset_left apply inter_subset_left, end lemma inf_le_right (H K : subgp G) : H ⊓ K ≤ K := /- inline sorry -/inter_subset_right _ _/- inline sorry -/ -- Can you use `library_search`, or other methods, to find the name of the -- statement that if `A B C : set G` then `A ⊆ B → A ⊆ C → A ⊆ (B ∩ C)`? lemma le_inf (H J K : subgp G) (h1 : H ≤ J) (h2 : H ≤ K) : H ≤ J ⊓ K := /- inline sorry -/subset_inter h1 h2/- inline sorry -/ -- Now we're ready to make the instance. instance : semilattice_inf_top (subgp G) := { top := top, le_top := le_top, inf := inf, inf_le_left := inf_le_left, inf_le_right := inf_le_right, le_inf := le_inf, .. subgp.partial_order } -- don't forget to inlude the partial order /- The logic behind `semilattice_inf_top` is that it is the simplest class which is closed under all finite "meet"s. The meet of 0 subgroups is `top`, the meet of one subgroup is the subgroup, the meet of two subgroups is their inf, and for three or more you proceed by induction. We could now go on to make a `semilattice_sup_bot` structure, and then a lattice structure. But let's jump straight to the strongest type in the order hierarchy -- a `complete_lattice`. This has arbitrary `Inf` and `Sup`s. So let's first note that we can do better than finite intersections -- we can take arbitrary intersections! Let's now define the `Inf` of an arbitrary set of subgroups of `G`. The part of the interface for sets you'll need to know here is that if `S` is a set of subsets of `G`, then `⋂₀ S` is notation for their intersection, and to work with it you'll need to know `set.mem_sInter : g ∈ ⋂₀ S ↔ ∀ (U : set G), U ∈ S → g ∈ U`. -/ def Inf (S : set (subgp G)) : subgp G := { carrier := Inf (subgp.carrier '' S), mul_mem := begin -- sorry intros x y hx hy, rw mem_sInter at hx hy ⊢, rintro t ⟨H, hH, rfl⟩, apply H.mul_mem, apply hx, use H, tauto, apply hy, use H, tauto, -- sorry end, one_mem := begin -- sorry rw mem_sInter, rintro t ⟨H, hH, rfl⟩, apply subgp.one_mem, -- sorry end, inv_mem := begin -- sorry intros x hx, rw mem_sInter at hx ⊢, rintro t ⟨H, Hh, rfl⟩, apply H.inv_mem, apply hx, use [H, Hh], -- sorry end } -- We now equip `subgp G` with an Inf. I think the notation is `⨅`, or `\Inf`, -- but I find it hard to use, and `#print notation ⨅` returns garbage. instance : has_Inf (subgp G) := ⟨Inf⟩ /- # Complete lattices Let's jump straight from `semilattice_inf_bot` to `complete_lattice`. A complete lattice has arbitrary Infs and arbitrary Sups, and satisfies some other axioms which you can probably imagine. Our next goal is to make `subgp G` into a complete lattice. We will do it in two ways. The first way is to show that if our `Inf` satisfies `(∀ (S : set (subgp G)), is_glb S (Inf S))` then we can build a complete lattice from this, using `complete_lattice_of_Inf`. -/ instance : complete_lattice (subgp G) := complete_lattice_of_Inf _ begin -- ⊢ ∀ (s : set (subgp G)), is_glb s (has_Inf.Inf s) -- See if you can figure out what this says, and how to prove it. -- You might find the function `is_glb.of_image` useful. -- sorry intro S, apply @is_glb.of_image _ _ _ _ subgp.carrier, intros, refl, apply is_glb_Inf, -- sorry end /- Now let me show you another way to do this. # Galois connections A Galois conection is a pair of adjoint functors between two partially ordered sets, considered as categories whose hom sets Hom(H,J) have size 1 if H ≤ J and size 0 otherwise. In other words, a Galois connection between two partial orders α and β is a pair of monotone functions `l : α → β` and `u : β → α` such that `∀ (a : α) (b : β), l a ≤ b ↔ a ≤ u b`. There is an example coming from Galois theory (between subfields and subgroups), and an example coming from classical algebraic geometry (between affine varieties and ideals); note that in both cases you have to use the opposite partial order on one side to make everything covariant. The examples we want to keep in mind here are: 1) α = subsets of G, β = subgroups of G, l = "subgroup generated by", u = `carrier` 2) X : Type, α := set (set X), β := topologies on X, l = topology generated by a collection of open sets, u = the open sets regarded as subsets. As you can imagine, there are a bunch of abstract theorems with simple proofs proved for Galois connections. You can see them by `#check galois_connection`, jumping to the definition, and reading the next 150 lines of the mathlib file after the definition. Examples of theorems you might recognise from contexts where you have seen this before: lemma le_u_l (a : α) : a ≤ u (l a) := ... lemma l_u_le (b : β) : l (u b) ≤ b := ... lemma u_l_u_eq_u : u ∘ l ∘ u = u := ... lemma l_u_l_eq_l : l ∘ u ∘ l = l := ... # Galois insertions A particularly cool kind of Galois connection is a Galois insertion, which is a Galois connection such that `l ∘ u = id`. This is true for both the examples we're keeping in mind (the subgroup of `G` generated by a subgroup is the same subgroup; the topology on `X` generated by a topology is the same topology). Our new goal: let's make subgroups of a group into a complete lattice, using the fact that `carrier` is part of a Galois insertion. -/ -- The adjoint functor to the `carrier` functor is the `span` functor -- from subsets to subgps. Here we will CHEAT by using `Inf` to -- define `span`. We could have built `span` directly with -- an inductive definition. def span (S : set G) : subgp G := Inf {H : subgp G | S ⊆ H.carrier} -- Here are some theorems about it. lemma monotone_carrier : monotone (subgp.carrier : subgp G → set G) := /- inline sorry -/λ H J, id/- inline sorry -/ lemma monotone_span : monotone (span : set G → subgp G) := /- inline sorry -/λ S T h, Inf_le_Inf $ λ H hH x hx, hH $ h hx/- inline sorry -/ lemma subset_span (S : set G) : S ≤ (span S).carrier := begin -- sorry rintro x hx _ ⟨H, hH, rfl⟩, exact hH hx, -- sorry end lemma span_subgp (H : subgp G) : span H.carrier = H := begin -- sorry ext, split, { intro hx, unfold span at hx, replace hx := mem_sInter.1 hx, apply hx, use H, simp }, { intro h, apply subset_span, exact h}, -- sorry end -- We have proved all the things we need to show that `span` and `carrier` -- form a Galois insertion, using `galois_insertion.monotone_intro`. def gi_subgp : galois_insertion (span : set G → subgp G) (subgp.carrier : subgp G → set G) := galois_insertion.monotone_intro monotone_carrier monotone_span subset_span span_subgp -- Note that `set G` is already a complete lattice: example : complete_lattice (set G) := by apply_instance -- and now `subgp G` can also be made into a complete lattice, by -- a theorem about Galois insertions. Again, I don't use `instance` -- because we already made the instance above. example : complete_lattice (subgp G) := galois_insertion.lift_complete_lattice gi_subgp end subgp -- Because Alex defined the topology generated by a collection of subsets -- yesterday, I'll show you how you can use Galois insertions to prove -- that if `X : Type` then the type of topological space structures on `X` -- is a complete lattice. We use the topology generated by a collection -- of subsets, which is a functor adjoint to the forgetful functor. -- We start by literally copying some stuff from Alex' talk. open set @[ext] class topological_space (X : Type) := (is_open : set X → Prop) -- why set X → Prop not set (set X)? former plays -- nicer with typeclasses later (univ_mem : is_open univ) (union : ∀ (B : set (set X)) (h : ∀ b ∈ B, is_open b), is_open (⋃₀ B)) (inter : ∀ (A B : set X) (hA : is_open A) (hB : is_open B), is_open (A ∩ B)) namespace topological_space def forget {X : Type} : topological_space X → set (set X) := @is_open X /-- The open sets of the least topology containing a collection of basic sets. -/ inductive generated_open (X : Type) (g : set (set X)) : set X → Prop | basic : ∀ s ∈ g, generated_open s | univ : generated_open univ | inter : ∀s t, generated_open s → generated_open t → generated_open (s ∩ t) | sUnion : ∀k, (∀ s ∈ k, generated_open s) → generated_open (⋃₀ k) /-- The smallest topological space containing the collection `g` of basic sets -/ def generate_from {X : Type} (g : set (set X)) : topological_space X := { is_open := generated_open X g, univ_mem := /- inline sorry -/generated_open.univ/- inline sorry -/, inter := /- inline sorry -/generated_open.inter/- inline sorry -/, union := /- inline sorry -/generated_open.sUnion/- inline sorry -/ } -- Recall that `topological_space X` is the type of topological space structures -- on `X`. Our Galois insertion will use the adjoint functors -- `generate_from` and `is_open`. -- We'd better start by giving the collection of topological space structures on X -- a partial order: instance (X : Type) : partial_order (topological_space X) := partial_order.lift (forget) begin -- need to show that a top space is determined by its open sets intros τ₁ τ₂ h, cases τ₁, cases τ₂, simp [forget, *] at *, end -- Exercise (LONG): First, show that we have a Galois insertion. lemma monotone_is_open {X : Type} : monotone (forget : topological_space X → set (set X)) := begin -- sorry intros τ₁ τ₂, intro h, intros U hU, exact h hU, -- sorry end lemma monotone_span {X : Type} : monotone (generate_from : set (set X) → topological_space X) := begin -- sorry intros C₁ C₂, intro h, intros U hU, induction hU with V hV V W _ _ hV2 hW2 C _ hC, { apply generated_open.basic, apply h, assumption }, { apply generated_open.univ }, { apply generated_open.inter, exact hV2, exact hW2}, { apply generated_open.sUnion, exact hC }, -- sorry end lemma subset_forget {X : Type} (Us : set (set X)) : Us ≤ forget (generate_from Us) := begin -- sorry intros U hU, apply generated_open.basic, assumption, -- sorry end lemma generate_forget {X : Type} (τ : topological_space X) : generate_from (forget τ) = τ := begin -- sorry ext U, split, { intro hU, induction hU with V hV V W _ _ hV2 hW2 C _ hC, { exact hV }, { apply univ_mem }, { apply inter _ _ hV2 hW2 }, { apply union _ hC }}, { -- easy way intro hU, apply generated_open.basic, exact hU } -- sorry end def gi_top (X : Type) : galois_insertion (generate_from : set (set X) → topological_space X) (forget : topological_space X → set (set X)) := galois_insertion.monotone_intro monotone_is_open monotone_span subset_forget generate_forget /- Then deduce that the type of topological space structures on X is a complete lattice, i.e. that there is a good definition of arbitrary Infs and Sups of topological space structures on a type, and they satisfy all the correct properties of Infs and Sups. In other words, -/ example (X : Type) : complete_lattice (topological_space X) := galois_insertion.lift_complete_lattice (gi_top X) end topological_space
6648f9353bb1ea8ab56bdfcc2cf2e9fd3a035aeb
ae1e94c332e17c7dc7051ce976d5a9eebe7ab8a5
/stage0/src/Std/Data/AssocList.lean
b947416c37bb62df7bd57ecc458ccc2b16e36e8b
[ "Apache-2.0" ]
permissive
dupuisf/lean4
d082d13b01243e1de29ae680eefb476961221eef
6a39c65bd28eb0e28c3870188f348c8914502718
refs/heads/master
1,676,948,755,391
1,610,665,114,000
1,610,665,114,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
3,108
lean
/- Copyright (c) 2019 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura -/ universes u v w w' namespace Std /- List-like type to avoid extra level of indirection -/ inductive AssocList (α : Type u) (β : Type v) where | nil : AssocList α β | cons (key : α) (value : β) (tail : AssocList α β) : AssocList α β deriving Inhabited namespace AssocList variables {α : Type u} {β : Type v} {δ : Type w} {m : Type w → Type w} [Monad m] abbrev empty : AssocList α β := nil instance : EmptyCollection (AssocList α β) := ⟨empty⟩ abbrev insert (m : AssocList α β) (k : α) (v : β) : AssocList α β := m.cons k v def isEmpty : AssocList α β → Bool | nil => true | _ => false @[specialize] def foldlM (f : δ → α → β → m δ) : (init : δ) → AssocList α β → m δ | d, nil => pure d | d, cons a b es => do let d ← f d a b foldlM f d es @[inline] def foldl (f : δ → α → β → δ) (init : δ) (as : AssocList α β) : δ := Id.run (foldlM f init as) def mapKey (f : α → δ) : AssocList α β → AssocList δ β | nil => nil | cons k v t => cons (f k) v (mapKey f t) def mapVal (f : β → δ) : AssocList α β → AssocList α δ | nil => nil | cons k v t => cons k (f v) (mapVal f t) def findEntry? [BEq α] (a : α) : AssocList α β → Option (α × β) | nil => none | cons k v es => match k == a with | true => some (k, v) | false => findEntry? a es def find? [BEq α] (a : α) : AssocList α β → Option β | nil => none | cons k v es => match k == a with | true => some v | false => find? a es def contains [BEq α] (a : α) : AssocList α β → Bool | nil => false | cons k v es => k == a || contains a es def replace [BEq α] (a : α) (b : β) : AssocList α β → AssocList α β | nil => nil | cons k v es => match k == a with | true => cons a b es | false => cons k v (replace a b es) def erase [BEq α] (a : α) : AssocList α β → AssocList α β | nil => nil | cons k v es => match k == a with | true => es | false => cons k v (erase a es) def any (p : α → β → Bool) : AssocList α β → Bool | nil => false | cons k v es => p k v || any p es def all (p : α → β → Bool) : AssocList α β → Bool | nil => true | cons k v es => p k v && all p es @[inline] def forIn {α : Type u} {β : Type v} {δ : Type w} {m : Type w → Type w'} [Monad m] (as : AssocList α β) (init : δ) (f : (α × β) → δ → m (ForInStep δ)) : m δ := let rec @[specialize] loop | d, nil => pure d | d, cons k v es => do match (← f (k, v) d) with | ForInStep.done d => pure d | ForInStep.yield d => loop d es loop init as end Std.AssocList def List.toAssocList {α : Type u} {β : Type v} : List (α × β) → Std.AssocList α β | [] => Std.AssocList.nil | (a,b) :: es => Std.AssocList.cons a b (toAssocList es)
ea61a81ae6a06de932a38a7471a4d6804c8f6cbc
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/algebra/order/field/canonical/defs.lean
6cfa773e4c813d44d6649f12ffa08a1a741224c7
[ "Apache-2.0" ]
permissive
alreadydone/mathlib
dc0be621c6c8208c581f5170a8216c5ba6721927
c982179ec21091d3e102d8a5d9f5fe06c8fafb73
refs/heads/master
1,685,523,275,196
1,670,184,141,000
1,670,184,141,000
287,574,545
0
0
Apache-2.0
1,670,290,714,000
1,597,421,623,000
Lean
UTF-8
Lean
false
false
1,385
lean
/- Copyright (c) 2014 Robert Lewis. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Robert Lewis, Leonardo de Moura, Mario Carneiro, Floris van Doorn -/ import algebra.order.field.defs import algebra.order.ring.canonical import algebra.order.with_zero /-! # Canonically ordered semifields -/ set_option old_structure_cmd true variables {α : Type*} /-- A canonically linear ordered field is a linear ordered field in which `a ≤ b` iff there exists `c` with `b = a + c`. -/ @[protect_proj, ancestor canonically_ordered_comm_semiring linear_ordered_semifield] class canonically_linear_ordered_semifield (α : Type*) extends canonically_ordered_comm_semiring α, linear_ordered_semifield α @[priority 100] -- See note [lower instance priority] instance canonically_linear_ordered_semifield.to_linear_ordered_comm_group_with_zero [canonically_linear_ordered_semifield α] : linear_ordered_comm_group_with_zero α := { mul_le_mul_left := λ a b h c, mul_le_mul_of_nonneg_left h $ zero_le _, ..‹canonically_linear_ordered_semifield α› } @[priority 100] -- See note [lower instance priority] instance canonically_linear_ordered_semifield.to_canonically_linear_ordered_add_monoid [canonically_linear_ordered_semifield α] : canonically_linear_ordered_add_monoid α := { ..‹canonically_linear_ordered_semifield α› }
0558ffe8adacd6bc3b18118408668dfc9c934efa
bbecf0f1968d1fba4124103e4f6b55251d08e9c4
/src/data/equiv/fin.lean
7820c1e2f4a19de1fa03e4abefa3c24a60d77904
[ "Apache-2.0" ]
permissive
waynemunro/mathlib
e3fd4ff49f4cb43d4a8ded59d17be407bc5ee552
065a70810b5480d584033f7bbf8e0409480c2118
refs/heads/master
1,693,417,182,397
1,634,644,781,000
1,634,644,781,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
13,806
lean
/- Copyright (c) 2018 Kenny Lau. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Kenny Lau -/ import data.fin.basic import data.equiv.basic import tactic.norm_num /-! # Equivalences for `fin n` -/ universe variables u variables {m n : ℕ} /-- Equivalence between `fin 0` and `empty`. -/ def fin_zero_equiv : fin 0 ≃ empty := equiv.equiv_empty _ /-- Equivalence between `fin 0` and `pempty`. -/ def fin_zero_equiv' : fin 0 ≃ pempty.{u} := equiv.equiv_pempty _ /-- Equivalence between `fin 1` and `unit`. -/ def fin_one_equiv : fin 1 ≃ unit := equiv_punit_of_unique /-- Equivalence between `fin 2` and `bool`. -/ def fin_two_equiv : fin 2 ≃ bool := ⟨@fin.cases 1 (λ_, bool) ff (λ_, tt), λb, cond b 1 0, begin refine fin.cases _ _, by norm_num, refine fin.cases _ _, by norm_num, exact λi, fin_zero_elim i end, begin rintro ⟨_|_⟩, { refl }, { rw ← fin.succ_zero_eq_one, refl } end⟩ /-- `Π i : fin 2, α i` is equivalent to `α 0 × α 1`. See also `fin_two_arrow_equiv` for a non-dependent version and `prod_equiv_pi_fin_two` for a version with inputs `α β : Type u`. -/ @[simps {fully_applied := ff}] def pi_fin_two_equiv (α : fin 2 → Type u) : (Π i, α i) ≃ α 0 × α 1 := { to_fun := λ f, (f 0, f 1), inv_fun := λ p, fin.cons p.1 $ fin.cons p.2 fin_zero_elim, left_inv := λ f, funext $ fin.forall_fin_two.2 ⟨rfl, rfl⟩, right_inv := λ ⟨x, y⟩, rfl } /-- A product space `α × β` is equivalent to the space `Π i : fin 2, γ i`, where `γ = fin.cons α (fin.cons β fin_zero_elim)`. See also `pi_fin_two_equiv` and `fin_two_arrow_equiv`. -/ @[simps {fully_applied := ff }] def prod_equiv_pi_fin_two (α β : Type u) : α × β ≃ Π i : fin 2, @fin.cons _ (λ _, Type u) α (fin.cons β fin_zero_elim) i := (pi_fin_two_equiv (fin.cons α (fin.cons β fin_zero_elim))).symm /-- The space of functions `fin 2 → α` is equivalent to `α × α`. See also `pi_fin_two_equiv` and `prod_equiv_pi_fin_two`. -/ @[simps {fully_applied := ff}] def fin_two_arrow_equiv (α : Type*) : (fin 2 → α) ≃ α × α := pi_fin_two_equiv (λ _, α) /-- `Π i : fin 2, α i` is order equivalent to `α 0 × α 1`. See also `order_iso.fin_two_arrow_equiv` for a non-dependent version. -/ def order_iso.pi_fin_two_iso (α : fin 2 → Type u) [Π i, preorder (α i)] : (Π i, α i) ≃o α 0 × α 1 := { to_equiv := pi_fin_two_equiv α, map_rel_iff' := λ f g, iff.symm fin.forall_fin_two } /-- The space of functions `fin 2 → α` is order equivalent to `α × α`. See also `order_iso.pi_fin_two_iso`. -/ def order_iso.fin_two_arrow_iso (α : Type*) [preorder α] : (fin 2 → α) ≃o α × α := order_iso.pi_fin_two_iso (λ _, α) /-- The 'identity' equivalence between `fin n` and `fin m` when `n = m`. -/ def fin_congr {n m : ℕ} (h : n = m) : fin n ≃ fin m := (fin.cast h).to_equiv @[simp] lemma fin_congr_apply_mk {n m : ℕ} (h : n = m) (k : ℕ) (w : k < n) : fin_congr h ⟨k, w⟩ = ⟨k, by { subst h, exact w }⟩ := rfl @[simp] lemma fin_congr_symm {n m : ℕ} (h : n = m) : (fin_congr h).symm = fin_congr h.symm := rfl @[simp] lemma fin_congr_apply_coe {n m : ℕ} (h : n = m) (k : fin n) : (fin_congr h k : ℕ) = k := by { cases k, refl, } lemma fin_congr_symm_apply_coe {n m : ℕ} (h : n = m) (k : fin m) : ((fin_congr h).symm k : ℕ) = k := by { cases k, refl, } /-- An equivalence that removes `i` and maps it to `none`. This is a version of `fin.pred_above` that produces `option (fin n)` instead of mapping both `i.cast_succ` and `i.succ` to `i`. -/ def fin_succ_equiv' {n : ℕ} (i : fin (n + 1)) : fin (n + 1) ≃ option (fin n) := { to_fun := i.insert_nth none some, inv_fun := λ x, x.cases_on' i (fin.succ_above i), left_inv := λ x, fin.succ_above_cases i (by simp) (λ j, by simp) x, right_inv := λ x, by cases x; dsimp; simp } @[simp] lemma fin_succ_equiv'_at {n : ℕ} (i : fin (n + 1)) : (fin_succ_equiv' i) i = none := by simp [fin_succ_equiv'] @[simp] lemma fin_succ_equiv'_succ_above {n : ℕ} (i : fin (n + 1)) (j : fin n) : fin_succ_equiv' i (i.succ_above j) = some j := @fin.insert_nth_apply_succ_above n (λ _, option (fin n)) i _ _ _ lemma fin_succ_equiv'_below {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : m.cast_succ < i) : (fin_succ_equiv' i) m.cast_succ = some m := by rw [← fin.succ_above_below _ _ h, fin_succ_equiv'_succ_above] lemma fin_succ_equiv'_above {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : i ≤ m.cast_succ) : (fin_succ_equiv' i) m.succ = some m := by rw [← fin.succ_above_above _ _ h, fin_succ_equiv'_succ_above] @[simp] lemma fin_succ_equiv'_symm_none {n : ℕ} (i : fin (n + 1)) : (fin_succ_equiv' i).symm none = i := rfl @[simp] lemma fin_succ_equiv'_symm_some {n : ℕ} (i : fin (n + 1)) (j : fin n) : (fin_succ_equiv' i).symm (some j) = i.succ_above j := rfl lemma fin_succ_equiv'_symm_some_below {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : m.cast_succ < i) : (fin_succ_equiv' i).symm (some m) = m.cast_succ := fin.succ_above_below i m h lemma fin_succ_equiv'_symm_some_above {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : i ≤ m.cast_succ) : (fin_succ_equiv' i).symm (some m) = m.succ := fin.succ_above_above i m h lemma fin_succ_equiv'_symm_coe_below {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : m.cast_succ < i) : (fin_succ_equiv' i).symm m = m.cast_succ := fin_succ_equiv'_symm_some_below h lemma fin_succ_equiv'_symm_coe_above {n : ℕ} {i : fin (n + 1)} {m : fin n} (h : i ≤ m.cast_succ) : (fin_succ_equiv' i).symm m = m.succ := fin_succ_equiv'_symm_some_above h /-- Equivalence between `fin (n + 1)` and `option (fin n)`. This is a version of `fin.pred` that produces `option (fin n)` instead of requiring a proof that the input is not `0`. -/ def fin_succ_equiv (n : ℕ) : fin (n + 1) ≃ option (fin n) := fin_succ_equiv' 0 @[simp] lemma fin_succ_equiv_zero {n : ℕ} : (fin_succ_equiv n) 0 = none := by cases n; refl @[simp] lemma fin_succ_equiv_succ {n : ℕ} (m : fin n): (fin_succ_equiv n) m.succ = some m := fin_succ_equiv'_above (fin.zero_le _) @[simp] lemma fin_succ_equiv_symm_none {n : ℕ} : (fin_succ_equiv n).symm none = 0 := fin_succ_equiv'_symm_none _ @[simp] lemma fin_succ_equiv_symm_some {n : ℕ} (m : fin n) : (fin_succ_equiv n).symm (some m) = m.succ := congr_fun fin.succ_above_zero m @[simp] lemma fin_succ_equiv_symm_coe {n : ℕ} (m : fin n) : (fin_succ_equiv n).symm m = m.succ := fin_succ_equiv_symm_some m /-- The equiv version of `fin.pred_above_zero`. -/ lemma fin_succ_equiv'_zero {n : ℕ} : fin_succ_equiv' (0 : fin (n + 1)) = fin_succ_equiv n := rfl /-- `equiv` between `fin (n + 1)` and `option (fin n)` sending `fin.last n` to `none` -/ def fin_succ_equiv_last {n : ℕ} : fin (n + 1) ≃ option (fin n) := fin_succ_equiv' (fin.last n) @[simp] lemma fin_succ_equiv_last_cast_succ {n : ℕ} (i : fin n) : fin_succ_equiv_last i.cast_succ = some i := fin_succ_equiv'_below i.2 @[simp] lemma fin_succ_equiv_last_last {n : ℕ} : fin_succ_equiv_last (fin.last n) = none := by simp [fin_succ_equiv_last] @[simp] lemma fin_succ_equiv_last_symm_some {n : ℕ} (i : fin n) : fin_succ_equiv_last.symm (some i) = i.cast_succ := fin_succ_equiv'_symm_some_below i.2 @[simp] lemma fin_succ_equiv_last_symm_coe {n : ℕ} (i : fin n) : fin_succ_equiv_last.symm ↑i = i.cast_succ := fin_succ_equiv'_symm_some_below i.2 @[simp] lemma fin_succ_equiv_last_symm_none {n : ℕ} : fin_succ_equiv_last.symm none = fin.last n := fin_succ_equiv'_symm_none _ /-- Equivalence between `fin m ⊕ fin n` and `fin (m + n)` -/ def fin_sum_fin_equiv : fin m ⊕ fin n ≃ fin (m + n) := { to_fun := sum.elim (fin.cast_add n) (fin.nat_add m), inv_fun := λ i, @fin.add_cases m n (λ _, fin m ⊕ fin n) sum.inl sum.inr i, left_inv := λ x, by { cases x with y y; dsimp; simp }, right_inv := λ x, by refine fin.add_cases (λ i, _) (λ i, _) x; simp } @[simp] lemma fin_sum_fin_equiv_apply_left (i : fin m) : (fin_sum_fin_equiv (sum.inl i) : fin (m + n)) = fin.cast_add n i := rfl @[simp] lemma fin_sum_fin_equiv_apply_right (i : fin n) : (fin_sum_fin_equiv (sum.inr i) : fin (m + n)) = fin.nat_add m i := rfl @[simp] lemma fin_sum_fin_equiv_symm_apply_cast_add (x : fin m) : fin_sum_fin_equiv.symm (fin.cast_add n x) = sum.inl x := fin_sum_fin_equiv.symm_apply_apply (sum.inl x) @[simp] lemma fin_sum_fin_equiv_symm_apply_nat_add (x : fin n) : fin_sum_fin_equiv.symm (fin.nat_add m x) = sum.inr x := fin_sum_fin_equiv.symm_apply_apply (sum.inr x) /-- The equivalence between `fin (m + n)` and `fin (n + m)` which rotates by `n`. -/ def fin_add_flip : fin (m + n) ≃ fin (n + m) := (fin_sum_fin_equiv.symm.trans (equiv.sum_comm _ _)).trans fin_sum_fin_equiv @[simp] lemma fin_add_flip_apply_cast_add (k : fin m) (n : ℕ) : fin_add_flip (fin.cast_add n k) = fin.nat_add n k := by simp [fin_add_flip] @[simp] lemma fin_add_flip_apply_nat_add (k : fin n) (m : ℕ) : fin_add_flip (fin.nat_add m k) = fin.cast_add m k := by simp [fin_add_flip] @[simp] lemma fin_add_flip_apply_mk_left {k : ℕ} (h : k < m) (hk : k < m + n := nat.lt_add_right k m n h) (hnk : n + k < n + m := add_lt_add_left h n) : fin_add_flip (⟨k, hk⟩ : fin (m + n)) = ⟨n + k, hnk⟩ := by convert fin_add_flip_apply_cast_add ⟨k, h⟩ n @[simp] lemma fin_add_flip_apply_mk_right {k : ℕ} (h₁ : m ≤ k) (h₂ : k < m + n) : fin_add_flip (⟨k, h₂⟩ : fin (m + n)) = ⟨k - m, sub_le_self'.trans_lt $ add_comm m n ▸ h₂⟩ := begin convert fin_add_flip_apply_nat_add ⟨k - m, (sub_lt_iff_right h₁).2 _⟩ m, { simp [add_sub_cancel_of_le h₁] }, { rwa add_comm } end /-- Rotate `fin n` one step to the right. -/ def fin_rotate : Π n, equiv.perm (fin n) | 0 := equiv.refl _ | (n+1) := fin_add_flip.trans (fin_congr (add_comm _ _)) lemma fin_rotate_of_lt {k : ℕ} (h : k < n) : fin_rotate (n+1) ⟨k, lt_of_lt_of_le h (nat.le_succ _)⟩ = ⟨k + 1, nat.succ_lt_succ h⟩ := begin dsimp [fin_rotate], simp [h, add_comm], end lemma fin_rotate_last' : fin_rotate (n+1) ⟨n, lt_add_one _⟩ = ⟨0, nat.zero_lt_succ _⟩ := begin dsimp [fin_rotate], rw fin_add_flip_apply_mk_right, simp, end lemma fin_rotate_last : fin_rotate (n+1) (fin.last _) = 0 := fin_rotate_last' lemma fin.snoc_eq_cons_rotate {α : Type*} (v : fin n → α) (a : α) : @fin.snoc _ (λ _, α) v a = (λ i, @fin.cons _ (λ _, α) a v (fin_rotate _ i)) := begin ext ⟨i, h⟩, by_cases h' : i < n, { rw [fin_rotate_of_lt h', fin.snoc, fin.cons, dif_pos h'], refl, }, { have h'' : n = i, { simp only [not_lt] at h', exact (nat.eq_of_le_of_lt_succ h' h).symm, }, subst h'', rw [fin_rotate_last', fin.snoc, fin.cons, dif_neg (lt_irrefl _)], refl, } end @[simp] lemma fin_rotate_zero : fin_rotate 0 = equiv.refl _ := rfl @[simp] lemma fin_rotate_one : fin_rotate 1 = equiv.refl _ := subsingleton.elim _ _ @[simp] lemma fin_rotate_succ_apply {n : ℕ} (i : fin n.succ) : fin_rotate n.succ i = i + 1 := begin cases n, { simp }, rcases i.le_last.eq_or_lt with rfl|h, { simp [fin_rotate_last] }, { cases i, simp only [fin.lt_iff_coe_lt_coe, fin.coe_last, fin.coe_mk] at h, simp [fin_rotate_of_lt h, fin.eq_iff_veq, fin.add_def, nat.mod_eq_of_lt (nat.succ_lt_succ h)] }, end @[simp] lemma fin_rotate_apply_zero {n : ℕ} : fin_rotate n.succ 0 = 1 := by rw [fin_rotate_succ_apply, zero_add] lemma coe_fin_rotate_of_ne_last {n : ℕ} {i : fin n.succ} (h : i ≠ fin.last n) : (fin_rotate n.succ i : ℕ) = i + 1 := begin rw fin_rotate_succ_apply, have : (i : ℕ) < n := lt_of_le_of_ne (nat.succ_le_succ_iff.mp i.2) (fin.coe_injective.ne h), exact fin.coe_add_one_of_lt this end lemma coe_fin_rotate {n : ℕ} (i : fin n.succ) : (fin_rotate n.succ i : ℕ) = if i = fin.last n then 0 else i + 1 := by rw [fin_rotate_succ_apply, fin.coe_add_one i] /-- Equivalence between `fin m × fin n` and `fin (m * n)` -/ def fin_prod_fin_equiv : fin m × fin n ≃ fin (m * n) := { to_fun := λ x, ⟨x.2.1 + n * x.1.1, calc x.2.1 + n * x.1.1 + 1 = x.1.1 * n + x.2.1 + 1 : by ac_refl ... ≤ x.1.1 * n + n : nat.add_le_add_left x.2.2 _ ... = (x.1.1 + 1) * n : eq.symm $ nat.succ_mul _ _ ... ≤ m * n : nat.mul_le_mul_right _ x.1.2⟩, inv_fun := λ x, have H : 0 < n, from nat.pos_of_ne_zero $ λ H, nat.not_lt_zero x.1 $ by subst H; from x.2, (⟨x.1 / n, (nat.div_lt_iff_lt_mul _ _ H).2 x.2⟩, ⟨x.1 % n, nat.mod_lt _ H⟩), left_inv := λ ⟨x, y⟩, have H : 0 < n, from nat.pos_of_ne_zero $ λ H, nat.not_lt_zero y.1 $ H ▸ y.2, prod.ext (fin.eq_of_veq $ calc (y.1 + n * x.1) / n = y.1 / n + x.1 : nat.add_mul_div_left _ _ H ... = 0 + x.1 : by rw nat.div_eq_of_lt y.2 ... = x.1 : nat.zero_add x.1) (fin.eq_of_veq $ calc (y.1 + n * x.1) % n = y.1 % n : nat.add_mul_mod_self_left _ _ _ ... = y.1 : nat.mod_eq_of_lt y.2), right_inv := λ x, fin.eq_of_veq $ nat.mod_add_div _ _ } /-- Promote a `fin n` into a larger `fin m`, as a subtype where the underlying values are retained. This is the `order_iso` version of `fin.cast_le`. -/ @[simps apply symm_apply] def fin.cast_le_order_iso {n m : ℕ} (h : n ≤ m) : fin n ≃o {i : fin m // (i : ℕ) < n} := { to_fun := λ i, ⟨fin.cast_le h i, by simpa using i.is_lt⟩, inv_fun := λ i, ⟨i, i.prop⟩, left_inv := λ _, by simp, right_inv := λ _, by simp, map_rel_iff' := λ _ _, by simp } /-- `fin 0` is a subsingleton. -/ instance subsingleton_fin_zero : subsingleton (fin 0) := fin_zero_equiv.subsingleton /-- `fin 1` is a subsingleton. -/ instance subsingleton_fin_one : subsingleton (fin 1) := fin_one_equiv.subsingleton
fd84913fc6a80a6913e69ad4e94651ba5949861f
7453f4f6074a6d5ce92b7bee2b29c409c061fbef
/src/Interpolation/rolle_general-fin.lean
bf80fb9eca8e57e31630d7610c574fdb6f856500
[ "Apache-2.0" ]
permissive
stanescuUW/numerical-analysis-with-Lean
b7b26755b8e925279f3afc1caa16b0666fc77ef8
98e6974f8b68cc5232ceff40535d776a33444c73
refs/heads/master
1,670,371,433,242
1,598,204,960,000
1,598,204,960,000
282,081,575
0
0
null
null
null
null
UTF-8
Lean
false
false
6,555
lean
import analysis.calculus.local_extr import analysis.calculus.times_cont_diff import analysis.calculus.iterated_deriv import tactic data.fin import .fin_lemmas open set namespace rolle_general -- Result below thanks to Sebastien Gouezel -- It will be added to mathlib in a more general form lemma times_cont_diff_on_succ_iff_deriv_within_of_Ioo (a b : ℝ) (f : ℝ → ℝ) (n : ℕ) (hf : times_cont_diff_on ℝ (n+1) f (Ioo a b) ) : times_cont_diff_on ℝ n (deriv f) (Ioo a b) := begin have : deriv f = (λ u : ℝ →L[ℝ] ℝ, u 1) ∘ (fderiv ℝ f), by { ext x, refl }, simp only [this], have : times_cont_diff_on ℝ n (fderiv ℝ f) (Ioo a b), { apply ((times_cont_diff_on_succ_iff_fderiv_within (unique_diff_on_Ioo a b)).1 hf).2.congr, assume x hx, calc fderiv ℝ f x = fderiv_within ℝ f univ x : by simp ... = fderiv_within ℝ f (univ ∩ Ioo a b) x : (fderiv_within_inter (Ioo_mem_nhds hx.1 hx.2) unique_diff_within_at_univ).symm ... = fderiv_within ℝ f (Ioo a b) x : by simp }, apply times_cont_diff.comp_times_cont_diff_on _ this, exact (is_bounded_bilinear_map_apply.is_bounded_linear_map_left _).times_cont_diff end -- This constructs the sequence of points where the derivative is zero -- given points where the function is zero (repeated standard Rolle application) lemma exist_points_deriv (n : ℕ) (x : fin (n+2) → ℝ) (hx : strict_mono x) : ∀ (f : ℝ → ℝ), continuous_on f ( Icc (x 0) (x (n+1)) ) → (∀ i, f (x i) = 0) → ∃ (xp : fin(n+1) → ℝ), strict_mono xp ∧ ∀ (i : fin (n+1)), xp i ∈ ( Ioo (x 0) (x (n+1)) ) ∧ deriv f (xp i) = 0 := begin intros f hf hxi, have h1 : ∀ (i : fin (n+1)), ∃ y ∈ (Ioo (x i) (x (i+1))), deriv f y = 0, intro i, apply exists_deriv_eq_zero, -- show x i < x (i+1) exact hx (fin_lt_succ n i), -- show f continuous on Icc (x i) (x (i+1)) have h02 : Icc (x i) (x (i+1)) ⊆ Icc (x 0) (x (n+1)), intros z hz, cases hz with hz1 hz2, split, have g3 := (strict_mono.le_iff_le hx).mpr (fin.zero_le i), linarith, -- use strict_mono x have g3 := (strict_mono.le_iff_le hx).mpr (fin_le_last_val n (i+1)), linarith, exact continuous_on.mono hf h02, -- show f (x i) = f (x (i+1)) rw [hxi i, hxi (i+1)], -- this is just normal Rolle, exists_deriv_eq_zero choose xp hxp using h1, use xp, split, intros i j hij, cases (hxp i).1 with hi1 hi2, cases (hxp j).1 with hj1 hj2, rcases lt_trichotomy ((i+1) : fin (n+2) ) (j : fin (n+2)) with h1|h2|h3, -- case (i+1) < j have hii1 := hx h1, linarith, -- case (i+1) = j rw h2 at hi2, linarith, -- case j < (i+1) is not possible because i < j exfalso, have h3n : (j : ℕ) < ((i + 1) : ℕ), { norm_num at h3, change (j.val : fin (n+2)).val < (i.val.succ : fin (n+2)).val at h3, rwa [fin.coe_val_of_lt (show j.1 < n + 2, by linarith [j.2]), fin.coe_val_of_lt (show i.1 + 1 < n + 2, by linarith [i.2])] at h3, }, have gf1 := nat.lt_succ_iff.mp h3n, --strange as it looks, linarith still needs this have hijn : (i : ℕ) < (j : ℕ), exact hij, linarith, intro i, split, swap, exact (hxp i).2, split, cases ((hxp i).1) with g01 g02, have := (strict_mono.le_iff_le hx).mpr (@fin.zero_le (n+1) i), linarith, cases ((hxp i).1) with g01 g02, have := (strict_mono.le_iff_le hx).mpr (fin_le_last_val n (i+1)), linarith, done end theorem general_rolle (n : ℕ) (x : fin (n+2) → ℝ) (hx : strict_mono x) : ∀ (f : ℝ → ℝ), times_cont_diff_on ℝ n f ( Icc (x 0) (x (n+1)) ) → (∀ i, f (x i) = 0) → ∃ c ∈ Ioo (x 0) (x (n+1)), iterated_deriv (n+1) f c = 0 := begin induction n with d hd, { -- base case, just plain Rolle `exists_deriv_eq_zero` intros f hf hi, norm_cast at hf, rw times_cont_diff_on_zero at hf, have h1 : 0 < 1, linarith, -- ?? The above was needed because linarith fails on next one without it: have h2 : (0 : fin 2) < (1 : fin 2), exact h1, -- linarith fails !!!??? have hx01 := hx h2, clear h1, clear h2, have heq : f (x 0) = f (x 1), rw [hi 0, hi 1], have h5 := exists_deriv_eq_zero f hx01 hf heq, rw iterated_deriv_one, have g : (((0 : ℕ) + 1) : fin 2) = 1, norm_cast, rw g, exact h5, }, { -- induction step -- the derivative is in Cᵈ intros f hf hi, have hfc := times_cont_diff_on.continuous_on hf, have H := exist_points_deriv d.succ x hx f hfc hi, --cases H with xp hxp, cases hxp with hxpx hxpi, rcases H with ⟨ xp, ⟨ hxpx, hxpi ⟩ ⟩, set g := deriv f with hg, have hf1 : times_cont_diff_on ℝ d.succ f (Ioo (x 0) (x (d.succ+1))), have hf11 : Ioo (x 0) (x (d.succ + 1)) ⊆ Icc (x 0) (x (d.succ + 1)), exact Ioo_subset_Icc_self, exact times_cont_diff_on.mono hf hf11, have hder0 := times_cont_diff_on_succ_iff_deriv_within_of_Ioo (x 0) (x (d.succ +1)) f d hf1, have hder : times_cont_diff_on ℝ d g (Icc (xp 0) (xp (d+1))), have hdr0 : Icc (xp 0) (xp (d+1)) ⊆ Ioo (x 0) (x (d.succ + 1)), intros z hz, cases hz with hz1 hz2, split, cases (hxpi 0).1 with h0z0 h0z1, linarith, cases (hxpi d.succ).1 with hdz0 hdz1, norm_cast at hz2, linarith, exact times_cont_diff_on.mono hder0 hdr0, have hdg := hd xp hxpx g hder, clear hd, have H1 : ∀ i, g (xp i) = 0, intro i, exact (hxpi i).2, have G := hdg H1, have K : iterated_deriv (d.succ + 1) f = iterated_deriv d.succ g, apply iterated_deriv_succ', rw ← K at G, rcases G with ⟨ c, ⟨ ⟨hc10, hc11⟩, hc2 ⟩ ⟩, use c, split, swap, exact hc2, have hxp0 := (hxpi 0).1, cases hxp0 with hxp01 hxp02, split, linarith, have hxp1 := (hxpi d.succ).1, cases hxp1 with hxp11 hxp12, have hxpeq0 : d+1 = d.succ, rw nat.succ_eq_add_one, have hxpeq1 : ((d+1) : fin (d.succ + 1) ) = d.succ, norm_cast, rw hxpeq1 at hc11, linarith, }, done end end rolle_general
9a08f153a1cd2ffd04cb315ddde73d81ed130e29
82b86ba2ae0d5aed0f01f49c46db5afec0eb2bd7
/src/Lean/Meta/AbstractNestedProofs.lean
31df03878657514c40db642688b49e585a4368cf
[ "Apache-2.0" ]
permissive
banksonian/lean4
3a2e6b0f1eb63aa56ff95b8d07b2f851072d54dc
78da6b3aa2840693eea354a41e89fc5b212a5011
refs/heads/master
1,673,703,624,165
1,605,123,551,000
1,605,123,551,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
2,610
lean
/- Copyright (c) 2020 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Leonardo de Moura -/ import Lean.Meta.Closure namespace Lean.Meta namespace AbstractNestedProofs def isNonTrivialProof (e : Expr) : MetaM Bool := do if !(← isProof e) then pure false else e.withApp fun f args => pure $ !f.isAtomic || args.any fun arg => !arg.isAtomic structure Context := (baseName : Name) structure State := (nextIdx : Nat := 1) abbrev M := ReaderT Context $ MonadCacheT Expr Expr $ StateRefT State MetaM private def mkAuxLemma (e : Expr) : M Expr := do let ctx ← read let s ← get let lemmaName ← mkAuxName (ctx.baseName ++ `proof) s.nextIdx modify fun s => { s with nextIdx := s.nextIdx + 1 } mkAuxDefinitionFor lemmaName e partial def visit (e : Expr) : M Expr := do if e.isAtomic then pure e else let visitBinders (xs : Array Expr) (k : M Expr) : M Expr := do let localInstances ← getLocalInstances let mut lctx ← getLCtx for x in xs do let xFVarId := x.fvarId! let localDecl ← getLocalDecl xFVarId let type ← visit localDecl.type let localDecl := localDecl.setType type let localDecl ← match localDecl.value? with | some value => do let value ← visit value; pure $ localDecl.setValue value | none => pure localDecl lctx :=lctx.modifyLocalDecl xFVarId fun _ => localDecl withLCtx lctx localInstances k checkCache e fun e => do if (← isNonTrivialProof e) then mkAuxLemma e else match e with | Expr.lam _ _ _ _ => lambdaLetTelescope e fun xs b => visitBinders xs do mkLambdaFVars xs (← visit b) | Expr.letE _ _ _ _ _ => lambdaLetTelescope e fun xs b => visitBinders xs do mkLambdaFVars xs (← visit b) | Expr.forallE _ _ _ _ => forallTelescope e fun xs b => visitBinders xs do mkForallFVars xs (← visit b) | Expr.mdata _ b _ => return e.updateMData! (← visit b) | Expr.proj _ _ b _ => return e.updateProj! (← visit b) | Expr.app _ _ _ => e.withApp fun f args => return mkAppN f (← args.mapM visit) | _ => pure e end AbstractNestedProofs /-- Replace proofs nested in `e` with new lemmas. The new lemmas have names of the form `mainDeclName.proof_<idx>` -/ def abstractNestedProofs (mainDeclName : Name) (e : Expr) : MetaM Expr := AbstractNestedProofs.visit e $.run { baseName := mainDeclName } $.run $.run' { nextIdx := 1 } end Lean.Meta
5d390a4998d50c7875a3df47083108b3e08a4c50
9dc8cecdf3c4634764a18254e94d43da07142918
/src/geometry/euclidean/oriented_angle.lean
c803acefa02d39276eeefc6caf6799440a4a17eb
[ "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
83,662
lean
/- Copyright (c) 2022 Joseph Myers. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Joseph Myers -/ import analysis.complex.arg import analysis.inner_product_space.orientation import analysis.inner_product_space.pi_L2 import analysis.special_functions.complex.circle import geometry.euclidean.basic /-! # Oriented angles. This file defines oriented angles in real inner product spaces. ## Main definitions * `orientation.oangle` is the oriented angle between two vectors with respect to an orientation. * `orientation.rotation` is the rotation by an oriented angle with respect to an orientation. ## Implementation notes The definitions here use the `real.angle` type, angles modulo `2 * π`. For some purposes, angles modulo `π` are more convenient, because results are true for such angles with less configuration dependence. Results that are only equalities modulo `π` can be represented modulo `2 * π` as equalities of `(2 : ℤ) • θ`. Definitions and results in the `orthonormal` namespace, with respect to a particular choice of orthonormal basis, are mainly for use in setting up the API and proving that certain definitions do not depend on the choice of basis for a given orientation. Applications should generally use the definitions and results in the `orientation` namespace instead. ## References * Evan Chen, Euclidean Geometry in Mathematical Olympiads. -/ noncomputable theory open_locale real open_locale real_inner_product_space namespace orthonormal variables {V : Type*} [inner_product_space ℝ V] variables {b : basis (fin 2) ℝ V} (hb : orthonormal ℝ b) include hb /-- The oriented angle from `x` to `y`, modulo `2 * π`. If either vector is 0, this is 0. -/ def oangle (x y : V) : real.angle := complex.arg ((complex.isometry_of_orthonormal hb).symm y / (complex.isometry_of_orthonormal hb).symm x) /-- Oriented angles are continuous when the vectors involved are nonzero. -/ lemma continuous_at_oangle {x : V × V} (hx1 : x.1 ≠ 0) (hx2 : x.2 ≠ 0) : continuous_at (λ y : V × V, hb.oangle y.1 y.2) x := (complex.continuous_at_arg_coe_angle (by simp [hx1, hx2])).comp $ continuous_at.div ((complex.isometry_of_orthonormal hb).symm.continuous.comp continuous_snd).continuous_at ((complex.isometry_of_orthonormal hb).symm.continuous.comp continuous_fst).continuous_at (by simp [hx1]) /-- If the first vector passed to `oangle` is 0, the result is 0. -/ @[simp] lemma oangle_zero_left (x : V) : hb.oangle 0 x = 0 := by simp [oangle] /-- If the second vector passed to `oangle` is 0, the result is 0. -/ @[simp] lemma oangle_zero_right (x : V) : hb.oangle x 0 = 0 := by simp [oangle] /-- If the two vectors passed to `oangle` are the same, the result is 0. -/ @[simp] lemma oangle_self (x : V) : hb.oangle x x = 0 := begin by_cases h : x = 0; simp [oangle, h] end /-- Swapping the two vectors passed to `oangle` negates the angle. -/ lemma oangle_rev (x y : V) : hb.oangle y x = -hb.oangle x y := begin simp only [oangle], convert complex.arg_inv_coe_angle _, exact (inv_div _ _).symm end /-- Adding the angles between two vectors in each order results in 0. -/ @[simp] lemma oangle_add_oangle_rev (x y : V) : hb.oangle x y + hb.oangle y x = 0 := by simp [hb.oangle_rev y x] /-- Negating the first vector passed to `oangle` adds `π` to the angle. -/ lemma oangle_neg_left {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : hb.oangle (-x) y = hb.oangle x y + π := begin simp only [oangle, div_neg_eq_neg_div, map_neg], refine complex.arg_neg_coe_angle _, simp [hx, hy] end /-- Negating the second vector passed to `oangle` adds `π` to the angle. -/ lemma oangle_neg_right {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : hb.oangle x (-y) = hb.oangle x y + π := begin simp only [oangle, neg_div, map_neg], refine complex.arg_neg_coe_angle _, simp [hx, hy] end /-- Negating the first vector passed to `oangle` does not change twice the angle. -/ @[simp] lemma two_zsmul_oangle_neg_left (x y : V) : (2 : ℤ) • hb.oangle (-x) y = (2 : ℤ) • hb.oangle x y := begin by_cases hx : x = 0, { simp [hx] }, { by_cases hy : y = 0, { simp [hy] }, { simp [hb.oangle_neg_left hx hy] } } end /-- Negating the second vector passed to `oangle` does not change twice the angle. -/ @[simp] lemma two_zsmul_oangle_neg_right (x y : V) : (2 : ℤ) • hb.oangle x (-y) = (2 : ℤ) • hb.oangle x y := begin by_cases hx : x = 0, { simp [hx] }, { by_cases hy : y = 0, { simp [hy] }, { simp [hb.oangle_neg_right hx hy] } } end /-- Negating both vectors passed to `oangle` does not change the angle. -/ @[simp] lemma oangle_neg_neg (x y : V) : hb.oangle (-x) (-y) = hb.oangle x y := by simp [oangle, neg_div_neg_eq] /-- Negating the first vector produces the same angle as negating the second vector. -/ lemma oangle_neg_left_eq_neg_right (x y : V) : hb.oangle (-x) y = hb.oangle x (-y) := by rw [←neg_neg y, oangle_neg_neg, neg_neg] /-- The angle between the negation of a nonzero vector and that vector is `π`. -/ @[simp] lemma oangle_neg_self_left {x : V} (hx : x ≠ 0) : hb.oangle (-x) x = π := by simp [oangle_neg_left, hx] /-- The angle between a nonzero vector and its negation is `π`. -/ @[simp] lemma oangle_neg_self_right {x : V} (hx : x ≠ 0) : hb.oangle x (-x) = π := by simp [oangle_neg_right, hx] /-- Twice the angle between the negation of a vector and that vector is 0. -/ @[simp] lemma two_zsmul_oangle_neg_self_left (x : V) : (2 : ℤ) • hb.oangle (-x) x = 0 := begin by_cases hx : x = 0; simp [hx] end /-- Twice the angle between a vector and its negation is 0. -/ @[simp] lemma two_zsmul_oangle_neg_self_right (x : V) : (2 : ℤ) • hb.oangle x (-x) = 0 := begin by_cases hx : x = 0; simp [hx] end /-- Adding the angles between two vectors in each order, with the first vector in each angle negated, results in 0. -/ @[simp] lemma oangle_add_oangle_rev_neg_left (x y : V) : hb.oangle (-x) y + hb.oangle (-y) x = 0 := by rw [oangle_neg_left_eq_neg_right, oangle_rev, add_left_neg] /-- Adding the angles between two vectors in each order, with the second vector in each angle negated, results in 0. -/ @[simp] lemma oangle_add_oangle_rev_neg_right (x y : V) : hb.oangle x (-y) + hb.oangle y (-x) = 0 := by rw [hb.oangle_rev (-x), oangle_neg_left_eq_neg_right, add_neg_self] /-- Multiplying the first vector passed to `oangle` by a positive real does not change the angle. -/ @[simp] lemma oangle_smul_left_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : hb.oangle (r • x) y = hb.oangle x y := begin simp only [oangle, linear_isometry_equiv.map_smul, complex.real_smul], rw [mul_comm, div_mul_eq_div_mul_one_div, one_div, mul_comm, ←complex.of_real_inv], congr' 1, exact complex.arg_real_mul _ (inv_pos.2 hr) end /-- Multiplying the second vector passed to `oangle` by a positive real does not change the angle. -/ @[simp] lemma oangle_smul_right_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : hb.oangle x (r • y) = hb.oangle x y := begin simp only [oangle, linear_isometry_equiv.map_smul, complex.real_smul], congr' 1, rw mul_div_assoc, exact complex.arg_real_mul _ hr end /-- Multiplying the first vector passed to `oangle` by a negative real produces the same angle as negating that vector. -/ @[simp] lemma oangle_smul_left_of_neg (x y : V) {r : ℝ} (hr : r < 0) : hb.oangle (r • x) y = hb.oangle (-x) y := by rw [←neg_neg r, neg_smul, ←smul_neg, hb.oangle_smul_left_of_pos _ _ (neg_pos_of_neg hr)] /-- Multiplying the second vector passed to `oangle` by a negative real produces the same angle as negating that vector. -/ @[simp] lemma oangle_smul_right_of_neg (x y : V) {r : ℝ} (hr : r < 0) : hb.oangle x (r • y) = hb.oangle x (-y) := by rw [←neg_neg r, neg_smul, ←smul_neg, hb.oangle_smul_right_of_pos _ _ (neg_pos_of_neg hr)] /-- The angle between a nonnegative multiple of a vector and that vector is 0. -/ @[simp] lemma oangle_smul_left_self_of_nonneg (x : V) {r : ℝ} (hr : 0 ≤ r) : hb.oangle (r • x) x = 0 := begin rcases hr.lt_or_eq with (h|h), { simp [h] }, { simp [h.symm] } end /-- The angle between a vector and a nonnegative multiple of that vector is 0. -/ @[simp] lemma oangle_smul_right_self_of_nonneg (x : V) {r : ℝ} (hr : 0 ≤ r) : hb.oangle x (r • x) = 0 := begin rcases hr.lt_or_eq with (h|h), { simp [h] }, { simp [h.symm] } end /-- The angle between two nonnegative multiples of the same vector is 0. -/ @[simp] lemma oangle_smul_smul_self_of_nonneg (x : V) {r₁ r₂ : ℝ} (hr₁ : 0 ≤ r₁) (hr₂ : 0 ≤ r₂) : hb.oangle (r₁ • x) (r₂ • x) = 0 := begin rcases hr₁.lt_or_eq with (h|h), { simp [h, hr₂] }, { simp [h.symm] } end /-- Multiplying the first vector passed to `oangle` by a nonzero real does not change twice the angle. -/ @[simp] lemma two_zsmul_oangle_smul_left_of_ne_zero (x y : V) {r : ℝ} (hr : r ≠ 0) : (2 : ℤ) • hb.oangle (r • x) y = (2 : ℤ) • hb.oangle x y := begin rcases hr.lt_or_lt with (h|h); simp [h] end /-- Multiplying the second vector passed to `oangle` by a nonzero real does not change twice the angle. -/ @[simp] lemma two_zsmul_oangle_smul_right_of_ne_zero (x y : V) {r : ℝ} (hr : r ≠ 0) : (2 : ℤ) • hb.oangle x (r • y) = (2 : ℤ) • hb.oangle x y := begin rcases hr.lt_or_lt with (h|h); simp [h] end /-- Twice the angle between a multiple of a vector and that vector is 0. -/ @[simp] lemma two_zsmul_oangle_smul_left_self (x : V) {r : ℝ} : (2 : ℤ) • hb.oangle (r • x) x = 0 := begin rcases lt_or_le r 0 with (h|h); simp [h] end /-- Twice the angle between a vector and a multiple of that vector is 0. -/ @[simp] lemma two_zsmul_oangle_smul_right_self (x : V) {r : ℝ} : (2 : ℤ) • hb.oangle x (r • x) = 0 := begin rcases lt_or_le r 0 with (h|h); simp [h] end /-- Twice the angle between two multiples of a vector is 0. -/ @[simp] lemma two_zsmul_oangle_smul_smul_self (x : V) {r₁ r₂ : ℝ} : (2 : ℤ) • hb.oangle (r₁ • x) (r₂ • x) = 0 := begin by_cases h : r₁ = 0; simp [h] end /-- The oriented angle between two vectors is zero if and only if the angle with the vectors swapped is zero. -/ lemma oangle_eq_zero_iff_oangle_rev_eq_zero {x y : V} : hb.oangle x y = 0 ↔ hb.oangle y x = 0 := by rw [oangle_rev, neg_eq_zero] /-- The oriented angle between two vectors is zero if and only if they are on the same ray. -/ lemma oangle_eq_zero_iff_same_ray {x y : V} : hb.oangle x y = 0 ↔ same_ray ℝ x y := by rw [oangle, complex.arg_coe_angle_eq_iff_eq_to_real, real.angle.to_real_zero, ←complex.same_ray_iff_arg_div_eq_zero, ←linear_isometry_equiv.coe_to_linear_equiv, same_ray_map_iff, same_ray_comm] /-- The oriented angle between two vectors is `π` if and only if the angle with the vectors swapped is `π`. -/ lemma oangle_eq_pi_iff_oangle_rev_eq_pi {x y : V} : hb.oangle x y = π ↔ hb.oangle y x = π := by rw [oangle_rev, neg_eq_iff_neg_eq, eq_comm, real.angle.neg_coe_pi] /-- The oriented angle between two vectors is `π` if and only they are nonzero and the first is on the same ray as the negation of the second. -/ lemma oangle_eq_pi_iff_same_ray_neg {x y : V} : hb.oangle x y = π ↔ x ≠ 0 ∧ y ≠ 0 ∧ same_ray ℝ x (-y) := begin rw [←hb.oangle_eq_zero_iff_same_ray], split, { intro h, by_cases hx : x = 0, { simpa [hx, real.angle.pi_ne_zero.symm] using h }, by_cases hy : y = 0, { simpa [hy, real.angle.pi_ne_zero.symm] using h }, refine ⟨hx, hy, _⟩, rw [hb.oangle_neg_right hx hy, h, real.angle.coe_pi_add_coe_pi] }, { rintro ⟨hx, hy, h⟩, rwa [hb.oangle_neg_right hx hy, ←real.angle.sub_coe_pi_eq_add_coe_pi, sub_eq_zero] at h } end /-- The oriented angle between two vectors is zero or `π` if and only if those two vectors are not linearly independent. -/ lemma oangle_eq_zero_or_eq_pi_iff_not_linear_independent {x y : V} : (hb.oangle x y = 0 ∨ hb.oangle x y = π) ↔ ¬ _root_.linear_independent ℝ ![x, y] := by rw [oangle_eq_zero_iff_same_ray, oangle_eq_pi_iff_same_ray_neg, same_ray_or_ne_zero_and_same_ray_neg_iff_not_linear_independent] /-- The oriented angle between two vectors is zero or `π` if and only if the first vector is zero or the second is a multiple of the first. -/ lemma oangle_eq_zero_or_eq_pi_iff_right_eq_smul {x y : V} : (hb.oangle x y = 0 ∨ hb.oangle x y = π) ↔ (x = 0 ∨ ∃ r : ℝ, y = r • x) := begin rw [oangle_eq_zero_iff_same_ray, oangle_eq_pi_iff_same_ray_neg], refine ⟨λ h, _, λ h, _⟩, { rcases h with h|⟨-, -, h⟩, { by_cases hx : x = 0, { simp [hx] }, obtain ⟨r, -, rfl⟩ := h.exists_nonneg_left hx, exact or.inr ⟨r, rfl⟩ }, { by_cases hx : x = 0, { simp [hx] }, obtain ⟨r, -, hy⟩ := h.exists_nonneg_left hx, refine or.inr ⟨-r, _⟩, simp [hy] } }, { rcases h with rfl|⟨r, rfl⟩, { simp }, by_cases hx : x = 0, { simp [hx] }, rcases lt_trichotomy r 0 with hr|hr|hr, { rw ←neg_smul, exact or.inr ⟨hx, smul_ne_zero.2 ⟨hr.ne, hx⟩, same_ray_pos_smul_right x (left.neg_pos_iff.2 hr)⟩ }, { simp [hr] }, { exact or.inl (same_ray_pos_smul_right x hr) } } end /-- The oriented angle between two vectors is not zero or `π` if and only if those two vectors are linearly independent. -/ lemma oangle_ne_zero_and_ne_pi_iff_linear_independent {x y : V} : (hb.oangle x y ≠ 0 ∧ hb.oangle x y ≠ π) ↔ _root_.linear_independent ℝ ![x, y] := by rw [←not_or_distrib, ←not_iff_not, not_not, oangle_eq_zero_or_eq_pi_iff_not_linear_independent] /-- Two vectors are equal if and only if they have equal norms and zero angle between them. -/ lemma eq_iff_norm_eq_and_oangle_eq_zero (x y : V) : x = y ↔ ∥x∥ = ∥y∥ ∧ hb.oangle x y = 0 := begin split, { intro h, simp [h] }, { rintro ⟨hn, ha⟩, rw [oangle] at ha, by_cases hy0 : y = 0, { simpa [hy0] using hn }, { have hx0 : x ≠ 0 := norm_ne_zero_iff.1 (hn.symm ▸ norm_ne_zero_iff.2 hy0), have hx0' : (complex.isometry_of_orthonormal hb).symm x ≠ 0, { simp [hx0] }, have hy0' : (complex.isometry_of_orthonormal hb).symm y ≠ 0, { simp [hy0] }, rw [complex.arg_div_coe_angle hy0' hx0', sub_eq_zero, complex.arg_coe_angle_eq_iff, complex.arg_eq_arg_iff hy0' hx0', ←complex.norm_eq_abs, ←complex.norm_eq_abs, linear_isometry_equiv.norm_map, linear_isometry_equiv.norm_map, hn, ←complex.of_real_div, div_self (norm_ne_zero_iff.2 hy0), complex.of_real_one, one_mul, linear_isometry_equiv.map_eq_iff] at ha, exact ha.symm } } end /-- Two vectors with equal norms are equal if and only if they have zero angle between them. -/ lemma eq_iff_oangle_eq_zero_of_norm_eq {x y : V} (h : ∥x∥ = ∥y∥) : x = y ↔ hb.oangle x y = 0 := ⟨λ he, ((hb.eq_iff_norm_eq_and_oangle_eq_zero x y).1 he).2, λ ha, (hb.eq_iff_norm_eq_and_oangle_eq_zero x y).2 ⟨h, ha⟩⟩ /-- Two vectors with zero angle between them are equal if and only if they have equal norms. -/ lemma eq_iff_norm_eq_of_oangle_eq_zero {x y : V} (h : hb.oangle x y = 0) : x = y ↔ ∥x∥ = ∥y∥ := ⟨λ he, ((hb.eq_iff_norm_eq_and_oangle_eq_zero x y).1 he).1, λ hn, (hb.eq_iff_norm_eq_and_oangle_eq_zero x y).2 ⟨hn, h⟩⟩ /-- Given three nonzero vectors, the angle between the first and the second plus the angle between the second and the third equals the angle between the first and the third. -/ @[simp] lemma oangle_add {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : hb.oangle x y + hb.oangle y z = hb.oangle x z := begin simp_rw [oangle], rw ←complex.arg_mul_coe_angle, { rw [mul_comm, div_mul_div_cancel], simp [hy] }, { simp [hx, hy] }, { simp [hy, hz] } end /-- Given three nonzero vectors, the angle between the second and the third plus the angle between the first and the second equals the angle between the first and the third. -/ @[simp] lemma oangle_add_swap {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : hb.oangle y z + hb.oangle x y = hb.oangle x z := by rw [add_comm, hb.oangle_add hx hy hz] /-- Given three nonzero vectors, the angle between the first and the third minus the angle between the first and the second equals the angle between the second and the third. -/ @[simp] lemma oangle_sub_left {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : hb.oangle x z - hb.oangle x y = hb.oangle y z := by rw [sub_eq_iff_eq_add, hb.oangle_add_swap hx hy hz] /-- Given three nonzero vectors, the angle between the first and the third minus the angle between the second and the third equals the angle between the first and the second. -/ @[simp] lemma oangle_sub_right {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : hb.oangle x z - hb.oangle y z = hb.oangle x y := by rw [sub_eq_iff_eq_add, hb.oangle_add hx hy hz] /-- Given three nonzero vectors, adding the angles between them in cyclic order results in 0. -/ @[simp] lemma oangle_add_cyc3 {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : hb.oangle x y + hb.oangle y z + hb.oangle z x = 0 := by simp [hx, hy, hz] /-- Given three nonzero vectors, adding the angles between them in cyclic order, with the first vector in each angle negated, results in π. If the vectors add to 0, this is a version of the sum of the angles of a triangle. -/ @[simp] lemma oangle_add_cyc3_neg_left {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : hb.oangle (-x) y + hb.oangle (-y) z + hb.oangle (-z) x = π := by rw [hb.oangle_neg_left hx hy, hb.oangle_neg_left hy hz, hb.oangle_neg_left hz hx, (show hb.oangle x y + π + (hb.oangle y z + π) + (hb.oangle z x + π) = hb.oangle x y + hb.oangle y z + hb.oangle z x + (π + π + π : real.angle), by abel), hb.oangle_add_cyc3 hx hy hz, real.angle.coe_pi_add_coe_pi, zero_add, zero_add] /-- Given three nonzero vectors, adding the angles between them in cyclic order, with the second vector in each angle negated, results in π. If the vectors add to 0, this is a version of the sum of the angles of a triangle. -/ @[simp] lemma oangle_add_cyc3_neg_right {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : hb.oangle x (-y) + hb.oangle y (-z) + hb.oangle z (-x) = π := by simp_rw [←oangle_neg_left_eq_neg_right, hb.oangle_add_cyc3_neg_left hx hy hz] /-- Pons asinorum, oriented vector angle form. -/ lemma oangle_sub_eq_oangle_sub_rev_of_norm_eq {x y : V} (h : ∥x∥ = ∥y∥) : hb.oangle x (x - y) = hb.oangle (y - x) y := begin by_cases hx : x = 0, { simp [hx] }, { have hy : y ≠ 0 := norm_ne_zero_iff.1 (h ▸ norm_ne_zero_iff.2 hx), simp_rw [hb.oangle_rev y, oangle, linear_isometry_equiv.map_sub, ←complex.arg_conj_coe_angle, sub_div, div_self (((complex.isometry_of_orthonormal hb).symm.map_eq_zero_iff).not.2 hx), div_self (((complex.isometry_of_orthonormal hb).symm.map_eq_zero_iff).not.2 hy), map_sub, map_one], rw ←inv_div, simp_rw [complex.inv_def, complex.norm_sq_div, ←complex.sq_abs, ←complex.norm_eq_abs, linear_isometry_equiv.norm_map, h], simp [hy] } end /-- The angle at the apex of an isosceles triangle is `π` minus twice a base angle, oriented vector angle form. -/ lemma oangle_eq_pi_sub_two_zsmul_oangle_sub_of_norm_eq {x y : V} (hn : x ≠ y) (h : ∥x∥ = ∥y∥) : hb.oangle y x = π - (2 : ℤ) • hb.oangle (y - x) y := begin rw two_zsmul, rw [←hb.oangle_sub_eq_oangle_sub_rev_of_norm_eq h] { occs := occurrences.pos [1] }, rw [eq_sub_iff_add_eq, ←oangle_neg_neg, ←add_assoc], have hy : y ≠ 0, { rintro rfl, rw [norm_zero, norm_eq_zero] at h, exact hn h }, have hx : x ≠ 0 := norm_ne_zero_iff.1 (h.symm ▸ norm_ne_zero_iff.2 hy), convert hb.oangle_add_cyc3_neg_right (neg_ne_zero.2 hy) hx (sub_ne_zero_of_ne hn.symm); simp end /-- Angle at center of a circle equals twice angle at circumference, oriented vector angle form. -/ lemma oangle_eq_two_zsmul_oangle_sub_of_norm_eq {x y z : V} (hxyne : x ≠ y) (hxzne : x ≠ z) (hxy : ∥x∥ = ∥y∥) (hxz : ∥x∥ = ∥z∥) : hb.oangle y z = (2 : ℤ) • hb.oangle (y - x) (z - x) := begin have hy : y ≠ 0, { rintro rfl, rw [norm_zero, norm_eq_zero] at hxy, exact hxyne hxy }, have hx : x ≠ 0 := norm_ne_zero_iff.1 (hxy.symm ▸ norm_ne_zero_iff.2 hy), have hz : z ≠ 0 := norm_ne_zero_iff.1 (hxz ▸ norm_ne_zero_iff.2 hx), calc hb.oangle y z = hb.oangle x z - hb.oangle x y : (hb.oangle_sub_left hx hy hz).symm ... = (π - (2 : ℤ) • hb.oangle (x - z) x) - (π - (2 : ℤ) • hb.oangle (x - y) x) : by rw [hb.oangle_eq_pi_sub_two_zsmul_oangle_sub_of_norm_eq hxzne.symm hxz.symm, hb.oangle_eq_pi_sub_two_zsmul_oangle_sub_of_norm_eq hxyne.symm hxy.symm] ... = (2 : ℤ) • (hb.oangle (x - y) x - hb.oangle (x - z) x) : by abel ... = (2 : ℤ) • hb.oangle (x - y) (x - z) : by rw hb.oangle_sub_right (sub_ne_zero_of_ne hxyne) (sub_ne_zero_of_ne hxzne) hx ... = (2 : ℤ) • hb.oangle (y - x) (z - x) : by rw [←oangle_neg_neg, neg_sub, neg_sub] end /-- Angle at center of a circle equals twice angle at circumference, oriented vector angle form with radius specified. -/ lemma oangle_eq_two_zsmul_oangle_sub_of_norm_eq_real {x y z : V} (hxyne : x ≠ y) (hxzne : x ≠ z) {r : ℝ} (hx : ∥x∥ = r) (hy : ∥y∥ = r) (hz : ∥z∥ = r) : hb.oangle y z = (2 : ℤ) • hb.oangle (y - x) (z - x) := hb.oangle_eq_two_zsmul_oangle_sub_of_norm_eq hxyne hxzne (hy.symm ▸ hx) (hz.symm ▸ hx) /-- Oriented vector angle version of "angles in same segment are equal" and "opposite angles of a cyclic quadrilateral add to π", for oriented angles mod π (for which those are the same result), represented here as equality of twice the angles. -/ lemma two_zsmul_oangle_sub_eq_two_zsmul_oangle_sub_of_norm_eq {x₁ x₂ y z : V} (hx₁yne : x₁ ≠ y) (hx₁zne : x₁ ≠ z) (hx₂yne : x₂ ≠ y) (hx₂zne : x₂ ≠ z) {r : ℝ} (hx₁ : ∥x₁∥ = r) (hx₂ : ∥x₂∥ = r) (hy : ∥y∥ = r) (hz : ∥z∥ = r) : (2 : ℤ) • hb.oangle (y - x₁) (z - x₁) = (2 : ℤ) • hb.oangle (y - x₂) (z - x₂) := hb.oangle_eq_two_zsmul_oangle_sub_of_norm_eq_real hx₁yne hx₁zne hx₁ hy hz ▸ hb.oangle_eq_two_zsmul_oangle_sub_of_norm_eq_real hx₂yne hx₂zne hx₂ hy hz /-- A rotation by the oriented angle `θ`. -/ def rotation (θ : real.angle) : V ≃ₗᵢ[ℝ] V := ((complex.isometry_of_orthonormal hb).symm.trans (rotation (real.angle.exp_map_circle θ))).trans (complex.isometry_of_orthonormal hb) /-- The determinant of `rotation` (as a linear map) is equal to `1`. -/ @[simp] lemma det_rotation (θ : real.angle) : ((hb.rotation θ).to_linear_equiv : V →ₗ[ℝ] V).det = 1 := by simp [rotation, ←linear_isometry_equiv.to_linear_equiv_symm, ←linear_equiv.comp_coe] /-- The determinant of `rotation` (as a linear equiv) is equal to `1`. -/ @[simp] lemma linear_equiv_det_rotation (θ : real.angle) : (hb.rotation θ).to_linear_equiv.det = 1 := by simp [rotation, ←linear_isometry_equiv.to_linear_equiv_symm] /-- The inverse of `rotation` is rotation by the negation of the angle. -/ @[simp] lemma rotation_symm (θ : real.angle) : (hb.rotation θ).symm = hb.rotation (-θ) := by simp [rotation, linear_isometry_equiv.trans_assoc] /-- Rotation by 0 is the identity. -/ @[simp] lemma rotation_zero : hb.rotation 0 = linear_isometry_equiv.refl ℝ V := by simp [rotation] /-- Rotation by π is negation. -/ lemma rotation_pi : hb.rotation π = linear_isometry_equiv.neg ℝ := begin ext x, simp [rotation] end /-- Rotating twice is equivalent to rotating by the sum of the angles. -/ @[simp] lemma rotation_trans (θ₁ θ₂ : real.angle) : (hb.rotation θ₁).trans (hb.rotation θ₂) = hb.rotation (θ₂ + θ₁) := begin simp only [rotation, ←linear_isometry_equiv.trans_assoc], ext1 x, simp end /-- Rotating the first vector by `θ` subtracts `θ` from the angle between two vectors. -/ @[simp] lemma oangle_rotation_left {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : hb.oangle (hb.rotation θ x) y = hb.oangle x y - θ := begin simp [oangle, rotation, complex.arg_div_coe_angle, complex.arg_mul_coe_angle, hx, hy, ne_zero_of_mem_circle], abel end /-- Rotating the second vector by `θ` adds `θ` to the angle between two vectors. -/ @[simp] lemma oangle_rotation_right {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : hb.oangle x (hb.rotation θ y) = hb.oangle x y + θ := begin simp [oangle, rotation, complex.arg_div_coe_angle, complex.arg_mul_coe_angle, hx, hy, ne_zero_of_mem_circle], abel end /-- The rotation of a vector by `θ` has an angle of `-θ` from that vector. -/ @[simp] lemma oangle_rotation_self_left {x : V} (hx : x ≠ 0) (θ : real.angle) : hb.oangle (hb.rotation θ x) x = -θ := by simp [hx] /-- A vector has an angle of `θ` from the rotation of that vector by `θ`. -/ @[simp] lemma oangle_rotation_self_right {x : V} (hx : x ≠ 0) (θ : real.angle) : hb.oangle x (hb.rotation θ x) = θ := by simp [hx] /-- Rotating the first vector by the angle between the two vectors results an an angle of 0. -/ @[simp] lemma oangle_rotation_oangle_left (x y : V) : hb.oangle (hb.rotation (hb.oangle x y) x) y = 0 := begin by_cases hx : x = 0, { simp [hx] }, { by_cases hy : y = 0, { simp [hy] }, { simp [hx, hy] } } end /-- Rotating the first vector by the angle between the two vectors and swapping the vectors results an an angle of 0. -/ @[simp] lemma oangle_rotation_oangle_right (x y : V) : hb.oangle y (hb.rotation (hb.oangle x y) x) = 0 := begin rw [oangle_rev], simp end /-- Rotating both vectors by the same angle does not change the angle between those vectors. -/ @[simp] lemma oangle_rotation (x y : V) (θ : real.angle) : hb.oangle (hb.rotation θ x) (hb.rotation θ y) = hb.oangle x y := begin by_cases hx : x = 0; by_cases hy : y = 0; simp [hx, hy] end /-- A rotation of a nonzero vector equals that vector if and only if the angle is zero. -/ @[simp] lemma rotation_eq_self_iff_angle_eq_zero {x : V} (hx : x ≠ 0) (θ : real.angle) : hb.rotation θ x = x ↔ θ = 0 := begin split, { intro h, rw eq_comm, simpa [hx, h] using hb.oangle_rotation_right hx hx θ }, { intro h, simp [h] } end /-- A nonzero vector equals a rotation of that vector if and only if the angle is zero. -/ @[simp] lemma eq_rotation_self_iff_angle_eq_zero {x : V} (hx : x ≠ 0) (θ : real.angle) : x = hb.rotation θ x ↔ θ = 0 := by rw [←hb.rotation_eq_self_iff_angle_eq_zero hx, eq_comm] /-- A rotation of a vector equals that vector if and only if the vector or the angle is zero. -/ lemma rotation_eq_self_iff (x : V) (θ : real.angle) : hb.rotation θ x = x ↔ x = 0 ∨ θ = 0 := begin by_cases h : x = 0; simp [h] end /-- A vector equals a rotation of that vector if and only if the vector or the angle is zero. -/ lemma eq_rotation_self_iff (x : V) (θ : real.angle) : x = hb.rotation θ x ↔ x = 0 ∨ θ = 0 := by rw [←rotation_eq_self_iff, eq_comm] /-- Rotating a vector by the angle to another vector gives the second vector if and only if the norms are equal. -/ @[simp] lemma rotation_oangle_eq_iff_norm_eq (x y : V) : hb.rotation (hb.oangle x y) x = y ↔ ∥x∥ = ∥y∥ := begin split, { intro h, rw [←h, linear_isometry_equiv.norm_map] }, { intro h, rw hb.eq_iff_oangle_eq_zero_of_norm_eq; simp [h] } end /-- The angle between two nonzero vectors is `θ` if and only if the second vector is the first rotated by `θ` and scaled by the ratio of the norms. -/ lemma oangle_eq_iff_eq_norm_div_norm_smul_rotation_of_ne_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : hb.oangle x y = θ ↔ y = (∥y∥ / ∥x∥) • hb.rotation θ x := begin have hp := div_pos (norm_pos_iff.2 hy) (norm_pos_iff.2 hx), split, { rintro rfl, rw [←linear_isometry_equiv.map_smul, ←hb.oangle_smul_left_of_pos x y hp, eq_comm, rotation_oangle_eq_iff_norm_eq, norm_smul, real.norm_of_nonneg hp.le, div_mul_cancel _ (norm_ne_zero_iff.2 hx)] }, { intro hye, rw [hye, hb.oangle_smul_right_of_pos _ _ hp, hb.oangle_rotation_self_right hx] } end /-- The angle between two nonzero vectors is `θ` if and only if the second vector is the first rotated by `θ` and scaled by a positive real. -/ lemma oangle_eq_iff_eq_pos_smul_rotation_of_ne_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : hb.oangle x y = θ ↔ ∃ r : ℝ, 0 < r ∧ y = r • hb.rotation θ x := begin split, { intro h, rw hb.oangle_eq_iff_eq_norm_div_norm_smul_rotation_of_ne_zero hx hy at h, exact ⟨∥y∥ / ∥x∥, div_pos (norm_pos_iff.2 hy) (norm_pos_iff.2 hx), h⟩ }, { rintro ⟨r, hr, rfl⟩, rw [hb.oangle_smul_right_of_pos _ _ hr, hb.oangle_rotation_self_right hx] } end /-- The angle between two vectors is `θ` if and only if they are nonzero and the second vector is the first rotated by `θ` and scaled by the ratio of the norms, or `θ` and at least one of the vectors are zero. -/ lemma oangle_eq_iff_eq_norm_div_norm_smul_rotation_or_eq_zero {x y : V} (θ : real.angle) : hb.oangle x y = θ ↔ (x ≠ 0 ∧ y ≠ 0 ∧ y = (∥y∥ / ∥x∥) • hb.rotation θ x) ∨ (θ = 0 ∧ (x = 0 ∨ y = 0)) := begin by_cases hx : x = 0, { simp [hx, eq_comm] }, { by_cases hy : y = 0, { simp [hy, eq_comm] }, { rw hb.oangle_eq_iff_eq_norm_div_norm_smul_rotation_of_ne_zero hx hy, simp [hx, hy] } } end /-- The angle between two vectors is `θ` if and only if they are nonzero and the second vector is the first rotated by `θ` and scaled by a positive real, or `θ` and at least one of the vectors are zero. -/ lemma oangle_eq_iff_eq_pos_smul_rotation_or_eq_zero {x y : V} (θ : real.angle) : hb.oangle x y = θ ↔ (x ≠ 0 ∧ y ≠ 0 ∧ ∃ r : ℝ, 0 < r ∧ y = r • hb.rotation θ x) ∨ (θ = 0 ∧ (x = 0 ∨ y = 0)) := begin by_cases hx : x = 0, { simp [hx, eq_comm] }, { by_cases hy : y = 0, { simp [hy, eq_comm] }, { rw hb.oangle_eq_iff_eq_pos_smul_rotation_of_ne_zero hx hy, simp [hx, hy] } } end /-- Complex conjugation as a linear isometric equivalence in `V`. Note that this definition depends on the choice of basis, not just on its orientation; for most geometrical purposes, the `reflection` definitions should be preferred instead. -/ def conj_lie : V ≃ₗᵢ[ℝ] V := ((complex.isometry_of_orthonormal hb).symm.trans complex.conj_lie).trans (complex.isometry_of_orthonormal hb) /-- The determinant of `conj_lie` (as a linear map) is equal to `-1`. -/ @[simp] lemma det_conj_lie : (hb.conj_lie.to_linear_equiv : V →ₗ[ℝ] V).det = -1 := by simp [conj_lie, ←linear_isometry_equiv.to_linear_equiv_symm, ←linear_equiv.comp_coe] /-- The determinant of `conj_lie` (as a linear equiv) is equal to `-1`. -/ @[simp] lemma linear_equiv_det_conj_lie : hb.conj_lie.to_linear_equiv.det = -1 := by simp [conj_lie, ←linear_isometry_equiv.to_linear_equiv_symm] /-- `conj_lie` is its own inverse. -/ @[simp] lemma conj_lie_symm : hb.conj_lie.symm = hb.conj_lie := rfl /-- Applying `conj_lie` to both vectors negates the angle between those vectors. -/ @[simp] lemma oangle_conj_lie (x y : V) : hb.oangle (hb.conj_lie x) (hb.conj_lie y) = -hb.oangle x y := by simp only [orthonormal.conj_lie, linear_isometry_equiv.symm_apply_apply, orthonormal.oangle, eq_self_iff_true, function.comp_app, complex.arg_coe_angle_eq_iff, linear_isometry_equiv.coe_trans, neg_inj, complex.conj_lie_apply, complex.arg_conj_coe_angle, ← map_div₀ (star_ring_end ℂ)] /-- Any linear isometric equivalence in `V` is `rotation` or `conj_lie` composed with `rotation`. -/ lemma exists_linear_isometry_equiv_eq (f : V ≃ₗᵢ[ℝ] V) : ∃ θ : real.angle, f = hb.rotation θ ∨ f = hb.conj_lie.trans (hb.rotation θ) := begin cases linear_isometry_complex (((complex.isometry_of_orthonormal hb).trans f).trans (complex.isometry_of_orthonormal hb).symm) with a ha, use complex.arg a, rcases ha with (ha|ha), { left, simp only [rotation, ←ha, linear_isometry_equiv.trans_assoc, linear_isometry_equiv.refl_trans, linear_isometry_equiv.symm_trans_self, real.angle.exp_map_circle_coe, exp_map_circle_arg], simp [←linear_isometry_equiv.trans_assoc] }, { right, simp only [rotation, conj_lie, linear_isometry_equiv.trans_assoc, real.angle.exp_map_circle_coe, exp_map_circle_arg], simp only [←linear_isometry_equiv.trans_assoc, linear_isometry_equiv.self_trans_symm, linear_isometry_equiv.trans_refl], simp_rw [linear_isometry_equiv.trans_assoc complex.conj_lie, ←ha], simp only [linear_isometry_equiv.trans_assoc, linear_isometry_equiv.refl_trans, linear_isometry_equiv.symm_trans_self], simp [←linear_isometry_equiv.trans_assoc] } end /-- Any linear isometric equivalence in `V` with positive determinant is `rotation`. -/ lemma exists_linear_isometry_equiv_eq_of_det_pos {f : V ≃ₗᵢ[ℝ] V} (hd : 0 < (f.to_linear_equiv : V →ₗ[ℝ] V).det) : ∃ θ : real.angle, f = hb.rotation θ := begin rcases hb.exists_linear_isometry_equiv_eq f with ⟨θ, (hf|hf)⟩, { exact ⟨θ, hf⟩ }, { simp [hf, ←linear_equiv.coe_det] at hd, norm_num at hd } end /-- Any linear isometric equivalence in `V` with negative determinant is `conj_lie` composed with `rotation`. -/ lemma exists_linear_isometry_equiv_eq_of_det_neg {f : V ≃ₗᵢ[ℝ] V} (hd : (f.to_linear_equiv : V →ₗ[ℝ] V).det < 0) : ∃ θ : real.angle, f = hb.conj_lie.trans (hb.rotation θ) := begin rcases hb.exists_linear_isometry_equiv_eq f with ⟨θ, (hf|hf)⟩, { simp [hf, ←linear_equiv.coe_det] at hd, norm_num at hd }, { exact ⟨θ, hf⟩ } end /-- Two bases with the same orientation are related by a `rotation`. -/ lemma exists_linear_isometry_equiv_map_eq_of_orientation_eq {b₂ : basis (fin 2) ℝ V} (hb₂ : orthonormal ℝ b₂) (ho : b.orientation = b₂.orientation) : ∃ θ : real.angle, b₂ = b.map (hb.rotation θ).to_linear_equiv := begin have h : b₂ = b.map (hb.equiv hb₂ (equiv.refl _)).to_linear_equiv, { rw hb.map_equiv, simp }, rw [eq_comm, h, b.orientation_comp_linear_equiv_eq_iff_det_pos] at ho, cases hb.exists_linear_isometry_equiv_eq_of_det_pos ho with θ hθ, rw hθ at h, exact ⟨θ, h⟩ end /-- Two bases with opposite orientations are related by `conj_lie` composed with a `rotation`. -/ lemma exists_linear_isometry_equiv_map_eq_of_orientation_eq_neg {b₂ : basis (fin 2) ℝ V} (hb₂ : orthonormal ℝ b₂) (ho : b.orientation = -b₂.orientation) : ∃ θ : real.angle, b₂ = b.map (hb.conj_lie.trans (hb.rotation θ)).to_linear_equiv := begin have h : b₂ = b.map (hb.equiv hb₂ (equiv.refl _)).to_linear_equiv, { rw hb.map_equiv, simp }, rw [eq_neg_iff_eq_neg, h, b.orientation_comp_linear_equiv_eq_neg_iff_det_neg] at ho, cases hb.exists_linear_isometry_equiv_eq_of_det_neg ho with θ hθ, rw hθ at h, exact ⟨θ, h⟩ end /-- The angle between two vectors, with respect to a basis given by `basis.map` with a linear isometric equivalence, equals the angle between those two vectors, transformed by the inverse of that equivalence, with respect to the original basis. -/ @[simp] lemma oangle_map (x y : V) (f : V ≃ₗᵢ[ℝ] V) : (hb.map_linear_isometry_equiv f).oangle x y = hb.oangle (f.symm x) (f.symm y) := by simp [oangle] /-- The value of `oangle` does not depend on the choice of basis for a given orientation. -/ lemma oangle_eq_of_orientation_eq {b₂ : basis (fin 2) ℝ V} (hb₂ : orthonormal ℝ b₂) (ho : b.orientation = b₂.orientation) (x y : V) : hb.oangle x y = hb₂.oangle x y := begin obtain ⟨θ, rfl⟩ := hb.exists_linear_isometry_equiv_map_eq_of_orientation_eq hb₂ ho, simp [hb] end /-- Negating the orientation negates the value of `oangle`. -/ lemma oangle_eq_neg_of_orientation_eq_neg {b₂ : basis (fin 2) ℝ V} (hb₂ : orthonormal ℝ b₂) (ho : b.orientation = -b₂.orientation) (x y : V) : hb.oangle x y = -hb₂.oangle x y := begin obtain ⟨θ, rfl⟩ := hb.exists_linear_isometry_equiv_map_eq_of_orientation_eq_neg hb₂ ho, rw hb.oangle_map, simp [hb] end /-- `rotation` does not depend on the choice of basis for a given orientation. -/ lemma rotation_eq_of_orientation_eq {b₂ : basis (fin 2) ℝ V} (hb₂ : orthonormal ℝ b₂) (ho : b.orientation = b₂.orientation) (θ : real.angle) : hb.rotation θ = hb₂.rotation θ := begin obtain ⟨θ₂, rfl⟩ := hb.exists_linear_isometry_equiv_map_eq_of_orientation_eq hb₂ ho, simp_rw [rotation, complex.map_isometry_of_orthonormal hb], simp only [linear_isometry_equiv.trans_assoc, linear_isometry_equiv.self_trans_symm, linear_isometry_equiv.refl_trans, linear_isometry_equiv.symm_trans], simp only [←linear_isometry_equiv.trans_assoc, _root_.rotation_symm, _root_.rotation_trans, mul_comm (real.angle.exp_map_circle θ), ←mul_assoc, mul_right_inv, one_mul] end /-- Negating the orientation negates the angle in `rotation`. -/ lemma rotation_eq_rotation_neg_of_orientation_eq_neg {b₂ : basis (fin 2) ℝ V} (hb₂ : orthonormal ℝ b₂) (ho : b.orientation = -b₂.orientation) (θ : real.angle) : hb.rotation θ = hb₂.rotation (-θ) := begin obtain ⟨θ₂, rfl⟩ := hb.exists_linear_isometry_equiv_map_eq_of_orientation_eq_neg hb₂ ho, simp_rw [rotation, complex.map_isometry_of_orthonormal hb, conj_lie], simp only [linear_isometry_equiv.trans_assoc, linear_isometry_equiv.self_trans_symm, linear_isometry_equiv.refl_trans, linear_isometry_equiv.symm_trans], congr' 1, simp only [←linear_isometry_equiv.trans_assoc, _root_.rotation_symm, linear_isometry_equiv.symm_symm, linear_isometry_equiv.self_trans_symm, linear_isometry_equiv.trans_refl, complex.conj_lie_symm], congr' 1, ext1 x, simp only [linear_isometry_equiv.coe_trans, function.comp_app, rotation_apply, complex.conj_lie_apply, map_mul, star_ring_end_self_apply, ←coe_inv_circle_eq_conj, inv_inv, real.angle.exp_map_circle_neg, ←mul_assoc], congr' 1, simp only [mul_comm (real.angle.exp_map_circle θ₂ : ℂ), mul_assoc], rw [←submonoid.coe_mul, mul_left_inv, submonoid.coe_one, mul_one] end /-- The inner product of two vectors is the product of the norms and the cosine of the oriented angle between the vectors. -/ lemma inner_eq_norm_mul_norm_mul_cos_oangle (x y : V) : ⟪x, y⟫ = ∥x∥ * ∥y∥ * real.angle.cos (hb.oangle x y) := begin by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, rw [oangle, real.angle.cos_coe, complex.cos_arg], swap, { simp [hx, hy] }, simp_rw [complex.abs_div, ←complex.norm_eq_abs, linear_isometry_equiv.norm_map, complex.div_re, ←complex.sq_abs, ←complex.norm_eq_abs, linear_isometry_equiv.norm_map, complex.isometry_of_orthonormal_symm_apply, complex.add_re, complex.add_im, is_R_or_C.I, complex.mul_I_re, complex.mul_I_im, complex.of_real_re, complex.of_real_im, basis.coord_apply, neg_zero, zero_add, add_zero], conv_lhs { rw [←b.sum_repr x, ←b.sum_repr y] }, simp_rw [hb.inner_sum, (dec_trivial : (finset.univ : finset (fin 2)) = {0, 1}), star_ring_end_apply, star_trivial], rw [finset.sum_insert (dec_trivial : (0 : fin 2) ∉ ({1} : finset (fin 2))), finset.sum_singleton], field_simp only [norm_ne_zero_iff.2 hx, norm_ne_zero_iff.2 hy, ne.def, not_false_iff], ring end /-- The cosine of the oriented angle between two nonzero vectors is the inner product divided by the product of the norms. -/ lemma cos_oangle_eq_inner_div_norm_mul_norm {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : real.angle.cos (hb.oangle x y) = ⟪x, y⟫ / (∥x∥ * ∥y∥) := begin rw hb.inner_eq_norm_mul_norm_mul_cos_oangle, field_simp [norm_ne_zero_iff.2 hx, norm_ne_zero_iff.2 hy], ring end /-- The cosine of the oriented angle between two nonzero vectors equals that of the unoriented angle. -/ lemma cos_oangle_eq_cos_angle {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : real.angle.cos (hb.oangle x y) = real.cos (inner_product_geometry.angle x y) := by rw [hb.cos_oangle_eq_inner_div_norm_mul_norm hx hy, inner_product_geometry.cos_angle] /-- The oriented angle between two nonzero vectors is plus or minus the unoriented angle. -/ lemma oangle_eq_angle_or_eq_neg_angle {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : hb.oangle x y = inner_product_geometry.angle x y ∨ hb.oangle x y = -inner_product_geometry.angle x y := real.angle.cos_eq_real_cos_iff_eq_or_eq_neg.1 $ hb.cos_oangle_eq_cos_angle hx hy /-- The unoriented angle between two nonzero vectors is the absolute value of the oriented angle, converted to a real. -/ lemma angle_eq_abs_oangle_to_real {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : inner_product_geometry.angle x y = |(hb.oangle x y).to_real| := begin have h0 := inner_product_geometry.angle_nonneg x y, have hpi := inner_product_geometry.angle_le_pi x y, rcases hb.oangle_eq_angle_or_eq_neg_angle hx hy with (h|h), { rw [h, eq_comm, real.angle.abs_to_real_coe_eq_self_iff], exact ⟨h0, hpi⟩ }, { rw [h, eq_comm, real.angle.abs_to_real_neg_coe_eq_self_iff], exact ⟨h0, hpi⟩ } end /-- If the sign of the oriented angle between two vectors is zero, either one of the vectors is zero or the unoriented angle is 0 or π. -/ lemma eq_zero_or_angle_eq_zero_or_pi_of_sign_oangle_eq_zero {x y : V} (h : (hb.oangle x y).sign = 0) : x = 0 ∨ y = 0 ∨ inner_product_geometry.angle x y = 0 ∨ inner_product_geometry.angle x y = π := begin by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, rw hb.angle_eq_abs_oangle_to_real hx hy, rw real.angle.sign_eq_zero_iff at h, rcases h with h|h; simp [h, real.pi_pos.le] end /-- If two unoriented angles are equal, and the signs of the corresponding oriented angles are equal, then the oriented angles are equal (even in degenerate cases). -/ lemma oangle_eq_of_angle_eq_of_sign_eq {w x y z : V} (h : inner_product_geometry.angle w x = inner_product_geometry.angle y z) (hs : (hb.oangle w x).sign = (hb.oangle y z).sign) : hb.oangle w x = hb.oangle y z := begin by_cases h0 : (w = 0 ∨ x = 0) ∨ (y = 0 ∨ z = 0), { have hs' : (hb.oangle w x).sign = 0 ∧ (hb.oangle y z).sign = 0, { rcases h0 with (rfl|rfl)|rfl|rfl, { simpa using hs.symm }, { simpa using hs.symm }, { simpa using hs }, { simpa using hs } }, rcases hs' with ⟨hswx, hsyz⟩, have h' : inner_product_geometry.angle w x = π / 2 ∧ inner_product_geometry.angle y z = π / 2, { rcases h0 with (rfl|rfl)|rfl|rfl, { simpa using h.symm }, { simpa using h.symm }, { simpa using h }, { simpa using h } }, rcases h' with ⟨hwx, hyz⟩, have hpi : π / 2 ≠ π, { intro hpi, rw [div_eq_iff, eq_comm, ←sub_eq_zero, mul_two, add_sub_cancel] at hpi, { exact real.pi_pos.ne.symm hpi }, { exact two_ne_zero } }, have h0wx : (w = 0 ∨ x = 0), { have h0' := hb.eq_zero_or_angle_eq_zero_or_pi_of_sign_oangle_eq_zero hswx, simpa [hwx, real.pi_pos.ne.symm, hpi] using h0' }, have h0yz : (y = 0 ∨ z = 0), { have h0' := hb.eq_zero_or_angle_eq_zero_or_pi_of_sign_oangle_eq_zero hsyz, simpa [hyz, real.pi_pos.ne.symm, hpi] using h0' }, rcases h0wx with h0wx|h0wx; rcases h0yz with h0yz|h0yz; simp [h0wx, h0yz] }, { push_neg at h0, rw real.angle.eq_iff_abs_to_real_eq_of_sign_eq hs, rwa [hb.angle_eq_abs_oangle_to_real h0.1.1 h0.1.2, hb.angle_eq_abs_oangle_to_real h0.2.1 h0.2.2] at h } end /-- If the signs of two oriented angles between nonzero vectors are equal, the oriented angles are equal if and only if the unoriented angles are equal. -/ lemma oangle_eq_iff_angle_eq_of_sign_eq {w x y z : V} (hw : w ≠ 0) (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) (hs : (hb.oangle w x).sign = (hb.oangle y z).sign) : inner_product_geometry.angle w x = inner_product_geometry.angle y z ↔ hb.oangle w x = hb.oangle y z := begin refine ⟨λ h, hb.oangle_eq_of_angle_eq_of_sign_eq h hs, λ h, _⟩, rw [hb.angle_eq_abs_oangle_to_real hw hx, hb.angle_eq_abs_oangle_to_real hy hz, h] end /-- The oriented angle between two nonzero vectors is zero if and only if the unoriented angle is zero. -/ lemma oangle_eq_zero_iff_angle_eq_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : hb.oangle x y = 0 ↔ inner_product_geometry.angle x y = 0 := begin refine ⟨λ h, _, λ h, _⟩, { simpa [hb.angle_eq_abs_oangle_to_real hx hy] }, { have ha := hb.oangle_eq_angle_or_eq_neg_angle hx hy, rw h at ha, simpa using ha } end /-- The oriented angle between two vectors is `π` if and only if the unoriented angle is `π`. -/ lemma oangle_eq_pi_iff_angle_eq_pi {x y : V} : hb.oangle x y = π ↔ inner_product_geometry.angle x y = π := begin by_cases hx : x = 0, { simp [hx, real.angle.pi_ne_zero.symm, div_eq_mul_inv, mul_right_eq_self₀, not_or_distrib, real.pi_ne_zero], norm_num }, by_cases hy : y = 0, { simp [hy, real.angle.pi_ne_zero.symm, div_eq_mul_inv, mul_right_eq_self₀, not_or_distrib, real.pi_ne_zero], norm_num }, refine ⟨λ h, _, λ h, _⟩, { rw [hb.angle_eq_abs_oangle_to_real hx hy, h], simp [real.pi_pos.le] }, { have ha := hb.oangle_eq_angle_or_eq_neg_angle hx hy, rw h at ha, simpa using ha } end /-- Negating the first vector passed to `oangle` negates the sign of the angle. -/ @[simp] lemma oangle_sign_neg_left (x y : V) : (hb.oangle (-x) y).sign = -((hb.oangle x y).sign) := begin by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, rw [hb.oangle_neg_left hx hy, real.angle.sign_add_pi] end /-- Negating the second vector passed to `oangle` negates the sign of the angle. -/ @[simp] lemma oangle_sign_neg_right (x y : V) : (hb.oangle x (-y)).sign = -((hb.oangle x y).sign) := begin by_cases hx : x = 0, { simp [hx] }, by_cases hy : y = 0, { simp [hy] }, rw [hb.oangle_neg_right hx hy, real.angle.sign_add_pi] end /-- Multiplying the first vector passed to `oangle` by a real multiplies the sign of the angle by the sign of the real. -/ @[simp] lemma oangle_sign_smul_left (x y : V) (r : ℝ) : (hb.oangle (r • x) y).sign = sign r * (hb.oangle x y).sign := begin rcases lt_trichotomy r 0 with h|h|h; simp [h] end /-- Multiplying the second vector passed to `oangle` by a real multiplies the sign of the angle by the sign of the real. -/ @[simp] lemma oangle_sign_smul_right (x y : V) (r : ℝ) : (hb.oangle x (r • y)).sign = sign r * (hb.oangle x y).sign := begin rcases lt_trichotomy r 0 with h|h|h; simp [h] end /-- Auxiliary lemma for the proof of `oangle_sign_smul_add_right`; not intended to be used outside of that proof. -/ lemma oangle_smul_add_right_eq_zero_or_eq_pi_iff {x y : V} (r : ℝ) : (hb.oangle x (r • x + y) = 0 ∨ hb.oangle x (r • x + y) = π) ↔ (hb.oangle x y = 0 ∨ hb.oangle x y = π) := begin simp_rw [oangle_eq_zero_or_eq_pi_iff_not_linear_independent, fintype.not_linear_independent_iff, fin.sum_univ_two, fin.exists_fin_two], refine ⟨λ h, _, λ h, _⟩, { rcases h with ⟨m, h, hm⟩, change m 0 • x + m 1 • (r • x + y) = 0 at h, refine ⟨![m 0 + m 1 * r, m 1], _⟩, change (m 0 + m 1 * r) • x + m 1 • y = 0 ∧ (m 0 + m 1 * r ≠ 0 ∨ m 1 ≠ 0), rw [smul_add, smul_smul, ←add_assoc, ←add_smul] at h, refine ⟨h, not_and_distrib.1 (λ h0, _)⟩, obtain ⟨h0, h1⟩ := h0, rw h1 at h0 hm, rw [zero_mul, add_zero] at h0, simpa [h0] using hm }, { rcases h with ⟨m, h, hm⟩, change m 0 • x + m 1 • y = 0 at h, refine ⟨![m 0 - m 1 * r, m 1], _⟩, change (m 0 - m 1 * r) • x + m 1 • (r • x + y) = 0 ∧ (m 0 - m 1 * r ≠ 0 ∨ m 1 ≠ 0), rw [sub_smul, smul_add, smul_smul, ←add_assoc, sub_add_cancel], refine ⟨h, not_and_distrib.1 (λ h0, _)⟩, obtain ⟨h0, h1⟩ := h0, rw h1 at h0 hm, rw [zero_mul, sub_zero] at h0, simpa [h0] using hm } end /-- Adding a multiple of the first vector passed to `oangle` to the second vector does not change the sign of the angle. -/ @[simp] lemma oangle_sign_smul_add_right (x y : V) (r : ℝ) : (hb.oangle x (r • x + y)).sign = (hb.oangle x y).sign := begin by_cases h : hb.oangle x y = 0 ∨ hb.oangle x y = π, { rwa [real.angle.sign_eq_zero_iff.2 h, real.angle.sign_eq_zero_iff, oangle_smul_add_right_eq_zero_or_eq_pi_iff] }, have h' : ∀ r' : ℝ, hb.oangle x (r' • x + y) ≠ 0 ∧ hb.oangle x (r' • x + y) ≠ π, { intro r', rwa [←hb.oangle_smul_add_right_eq_zero_or_eq_pi_iff r', not_or_distrib] at h }, let s : set (V × V) := (λ r' : ℝ, (x, r' • x + y)) '' set.univ, have hc : is_connected s := is_connected_univ.image _ ((continuous_const.prod_mk ((continuous_id.smul continuous_const).add continuous_const)).continuous_on), have hf : continuous_on (λ z : V × V, hb.oangle z.1 z.2) s, { refine continuous_at.continuous_on (λ z hz, hb.continuous_at_oangle _ _), all_goals { simp_rw [s, set.mem_image] at hz, obtain ⟨r', -, rfl⟩ := hz, simp only [prod.fst, prod.snd], intro hz }, { simpa [hz] using (h' 0).1 }, { simpa [hz] using (h' r').1 } }, have hs : ∀ z : V × V, z ∈ s → hb.oangle z.1 z.2 ≠ 0 ∧ hb.oangle z.1 z.2 ≠ π, { intros z hz, simp_rw [s, set.mem_image] at hz, obtain ⟨r', -, rfl⟩ := hz, exact h' r' }, have hx : (x, y) ∈ s, { convert set.mem_image_of_mem (λ r' : ℝ, (x, r' • x + y)) (set.mem_univ 0), simp }, have hy : (x, r • x + y) ∈ s := set.mem_image_of_mem _ (set.mem_univ _), convert real.angle.sign_eq_of_continuous_on hc hf hs hx hy end /-- Adding a multiple of the second vector passed to `oangle` to the first vector does not change the sign of the angle. -/ @[simp] lemma oangle_sign_add_smul_left (x y : V) (r : ℝ) : (hb.oangle (x + r • y) y).sign = (hb.oangle x y).sign := by simp_rw [hb.oangle_rev y, real.angle.sign_neg, add_comm x, oangle_sign_smul_add_right] /-- Subtracting a multiple of the first vector passed to `oangle` from the second vector does not change the sign of the angle. -/ @[simp] lemma oangle_sign_sub_smul_right (x y : V) (r : ℝ) : (hb.oangle x (y - r • x)).sign = (hb.oangle x y).sign := by rw [sub_eq_add_neg, ←neg_smul, add_comm, oangle_sign_smul_add_right] /-- Subtracting a multiple of the second vector passed to `oangle` from the first vector does not change the sign of the angle. -/ @[simp] lemma oangle_sign_sub_smul_left (x y : V) (r : ℝ) : (hb.oangle (x - r • y) y).sign = (hb.oangle x y).sign := by rw [sub_eq_add_neg, ←neg_smul, oangle_sign_add_smul_left] /-- The sign of the angle between a vector, and a linear combination of that vector with a second vector, is the sign of the factor by which the second vector is multiplied in that combination multiplied by the sign of the angle between the two vectors. -/ @[simp] lemma oangle_sign_smul_add_smul_right (x y : V) (r₁ r₂ : ℝ) : (hb.oangle x (r₁ • x + r₂ • y)).sign = sign r₂ * (hb.oangle x y).sign := begin rw ←hb.oangle_sign_smul_add_right x (r₁ • x + r₂ • y) (-r₁), simp end /-- The sign of the angle between a linear combination of two vectors and the second vector is the sign of the factor by which the first vector is multiplied in that combination multiplied by the sign of the angle between the two vectors. -/ @[simp] lemma oangle_sign_smul_add_smul_left (x y : V) (r₁ r₂ : ℝ) : (hb.oangle (r₁ • x + r₂ • y) y).sign = sign r₁ * (hb.oangle x y).sign := by simp_rw [hb.oangle_rev y, real.angle.sign_neg, add_comm (r₁ • x), oangle_sign_smul_add_smul_right, mul_neg] /-- The sign of the angle between two linear combinations of two vectors is the sign of the determinant of the factors in those combinations multiplied by the sign of the angle between the two vectors. -/ lemma oangle_sign_smul_add_smul_smul_add_smul (x y : V) (r₁ r₂ r₃ r₄ : ℝ) : (hb.oangle (r₁ • x + r₂ • y) (r₃ • x + r₄ • y)).sign = sign (r₁ * r₄ - r₂ * r₃) * (hb.oangle x y).sign := begin by_cases hr₁ : r₁ = 0, { rw [hr₁, zero_smul, zero_mul, zero_add, zero_sub, left.sign_neg, oangle_sign_smul_left, add_comm, oangle_sign_smul_add_smul_right, oangle_rev, real.angle.sign_neg, sign_mul, mul_neg, mul_neg, neg_mul, mul_assoc] }, { rw [←hb.oangle_sign_smul_add_right (r₁ • x + r₂ • y) (r₃ • x + r₄ • y) (-r₃ / r₁), smul_add, smul_smul, smul_smul, div_mul_cancel _ hr₁, neg_smul, ←add_assoc, add_comm (-(r₃ • x)), ←sub_eq_add_neg, sub_add_cancel, ←add_smul, oangle_sign_smul_right, oangle_sign_smul_add_smul_left, ←mul_assoc, ←sign_mul, add_mul, mul_assoc, mul_comm r₂ r₁, ←mul_assoc, div_mul_cancel _ hr₁, add_comm, neg_mul, ←sub_eq_add_neg, mul_comm r₄, mul_comm r₃] } end end orthonormal namespace orientation open finite_dimensional variables {V : Type*} [inner_product_space ℝ V] variables [hd2 : fact (finrank ℝ V = 2)] (o : orientation ℝ V (fin 2)) include hd2 o local notation `ob` := o.fin_orthonormal_basis_orthonormal dec_trivial hd2.out /-- The oriented angle from `x` to `y`, modulo `2 * π`. If either vector is 0, this is 0. See `inner_product_geometry.angle` for the corresponding unoriented angle definition. -/ def oangle (x y : V) : real.angle := (ob).oangle x y /-- Oriented angles are continuous when the vectors involved are nonzero. -/ lemma continuous_at_oangle {x : V × V} (hx1 : x.1 ≠ 0) (hx2 : x.2 ≠ 0) : continuous_at (λ y : V × V, o.oangle y.1 y.2) x := (ob).continuous_at_oangle hx1 hx2 /-- If the first vector passed to `oangle` is 0, the result is 0. -/ @[simp] lemma oangle_zero_left (x : V) : o.oangle 0 x = 0 := (ob).oangle_zero_left x /-- If the second vector passed to `oangle` is 0, the result is 0. -/ @[simp] lemma oangle_zero_right (x : V) : o.oangle x 0 = 0 := (ob).oangle_zero_right x /-- If the two vectors passed to `oangle` are the same, the result is 0. -/ @[simp] lemma oangle_self (x : V) : o.oangle x x = 0 := (ob).oangle_self x /-- Swapping the two vectors passed to `oangle` negates the angle. -/ lemma oangle_rev (x y : V) : o.oangle y x = -o.oangle x y := (ob).oangle_rev x y /-- Adding the angles between two vectors in each order results in 0. -/ @[simp] lemma oangle_add_oangle_rev (x y : V) : o.oangle x y + o.oangle y x = 0 := (ob).oangle_add_oangle_rev x y /-- Negating the first vector passed to `oangle` adds `π` to the angle. -/ lemma oangle_neg_left {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : o.oangle (-x) y = o.oangle x y + π := (ob).oangle_neg_left hx hy /-- Negating the second vector passed to `oangle` adds `π` to the angle. -/ lemma oangle_neg_right {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : o.oangle x (-y) = o.oangle x y + π := (ob).oangle_neg_right hx hy /-- Negating the first vector passed to `oangle` does not change twice the angle. -/ @[simp] lemma two_zsmul_oangle_neg_left (x y : V) : (2 : ℤ) • o.oangle (-x) y = (2 : ℤ) • o.oangle x y := (ob).two_zsmul_oangle_neg_left x y /-- Negating the second vector passed to `oangle` does not change twice the angle. -/ @[simp] lemma two_zsmul_oangle_neg_right (x y : V) : (2 : ℤ) • o.oangle x (-y) = (2 : ℤ) • o.oangle x y := (ob).two_zsmul_oangle_neg_right x y /-- Negating both vectors passed to `oangle` does not change the angle. -/ @[simp] lemma oangle_neg_neg (x y : V) : o.oangle (-x) (-y) = o.oangle x y := (ob).oangle_neg_neg x y /-- Negating the first vector produces the same angle as negating the second vector. -/ lemma oangle_neg_left_eq_neg_right (x y : V) : o.oangle (-x) y = o.oangle x (-y) := (ob).oangle_neg_left_eq_neg_right x y /-- The angle between the negation of a nonzero vector and that vector is `π`. -/ @[simp] lemma oangle_neg_self_left {x : V} (hx : x ≠ 0) : o.oangle (-x) x = π := (ob).oangle_neg_self_left hx /-- The angle between a nonzero vector and its negation is `π`. -/ @[simp] lemma oangle_neg_self_right {x : V} (hx : x ≠ 0) : o.oangle x (-x) = π := (ob).oangle_neg_self_right hx /-- Twice the angle between the negation of a vector and that vector is 0. -/ @[simp] lemma two_zsmul_oangle_neg_self_left (x : V) : (2 : ℤ) • o.oangle (-x) x = 0 := (ob).two_zsmul_oangle_neg_self_left x /-- Twice the angle between a vector and its negation is 0. -/ @[simp] lemma two_zsmul_oangle_neg_self_right (x : V) : (2 : ℤ) • o.oangle x (-x) = 0 := (ob).two_zsmul_oangle_neg_self_right x /-- Adding the angles between two vectors in each order, with the first vector in each angle negated, results in 0. -/ @[simp] lemma oangle_add_oangle_rev_neg_left (x y : V) : o.oangle (-x) y + o.oangle (-y) x = 0 := (ob).oangle_add_oangle_rev_neg_left x y /-- Adding the angles between two vectors in each order, with the second vector in each angle negated, results in 0. -/ @[simp] lemma oangle_add_oangle_rev_neg_right (x y : V) : o.oangle x (-y) + o.oangle y (-x) = 0 := (ob).oangle_add_oangle_rev_neg_right x y /-- Multiplying the first vector passed to `oangle` by a positive real does not change the angle. -/ @[simp] lemma oangle_smul_left_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : o.oangle (r • x) y = o.oangle x y := (ob).oangle_smul_left_of_pos x y hr /-- Multiplying the second vector passed to `oangle` by a positive real does not change the angle. -/ @[simp] lemma oangle_smul_right_of_pos (x y : V) {r : ℝ} (hr : 0 < r) : o.oangle x (r • y) = o.oangle x y := (ob).oangle_smul_right_of_pos x y hr /-- Multiplying the first vector passed to `oangle` by a negative real produces the same angle as negating that vector. -/ @[simp] lemma oangle_smul_left_of_neg (x y : V) {r : ℝ} (hr : r < 0) : o.oangle (r • x) y = o.oangle (-x) y := (ob).oangle_smul_left_of_neg x y hr /-- Multiplying the second vector passed to `oangle` by a negative real produces the same angle as negating that vector. -/ @[simp] lemma oangle_smul_right_of_neg (x y : V) {r : ℝ} (hr : r < 0) : o.oangle x (r • y) = o.oangle x (-y) := (ob).oangle_smul_right_of_neg x y hr /-- The angle between a nonnegative multiple of a vector and that vector is 0. -/ @[simp] lemma oangle_smul_left_self_of_nonneg (x : V) {r : ℝ} (hr : 0 ≤ r) : o.oangle (r • x) x = 0 := (ob).oangle_smul_left_self_of_nonneg x hr /-- The angle between a vector and a nonnegative multiple of that vector is 0. -/ @[simp] lemma oangle_smul_right_self_of_nonneg (x : V) {r : ℝ} (hr : 0 ≤ r) : o.oangle x (r • x) = 0 := (ob).oangle_smul_right_self_of_nonneg x hr /-- The angle between two nonnegative multiples of the same vector is 0. -/ @[simp] lemma oangle_smul_smul_self_of_nonneg (x : V) {r₁ r₂ : ℝ} (hr₁ : 0 ≤ r₁) (hr₂ : 0 ≤ r₂) : o.oangle (r₁ • x) (r₂ • x) = 0 := (ob).oangle_smul_smul_self_of_nonneg x hr₁ hr₂ /-- Multiplying the first vector passed to `oangle` by a nonzero real does not change twice the angle. -/ @[simp] lemma two_zsmul_oangle_smul_left_of_ne_zero (x y : V) {r : ℝ} (hr : r ≠ 0) : (2 : ℤ) • o.oangle (r • x) y = (2 : ℤ) • o.oangle x y := (ob).two_zsmul_oangle_smul_left_of_ne_zero x y hr /-- Multiplying the second vector passed to `oangle` by a nonzero real does not change twice the angle. -/ @[simp] lemma two_zsmul_oangle_smul_right_of_ne_zero (x y : V) {r : ℝ} (hr : r ≠ 0) : (2 : ℤ) • o.oangle x (r • y) = (2 : ℤ) • o.oangle x y := (ob).two_zsmul_oangle_smul_right_of_ne_zero x y hr /-- Twice the angle between a multiple of a vector and that vector is 0. -/ @[simp] lemma two_zsmul_oangle_smul_left_self (x : V) {r : ℝ} : (2 : ℤ) • o.oangle (r • x) x = 0 := (ob).two_zsmul_oangle_smul_left_self x /-- Twice the angle between a vector and a multiple of that vector is 0. -/ @[simp] lemma two_zsmul_oangle_smul_right_self (x : V) {r : ℝ} : (2 : ℤ) • o.oangle x (r • x) = 0 := (ob).two_zsmul_oangle_smul_right_self x /-- Twice the angle between two multiples of a vector is 0. -/ @[simp] lemma two_zsmul_oangle_smul_smul_self (x : V) {r₁ r₂ : ℝ} : (2 : ℤ) • o.oangle (r₁ • x) (r₂ • x) = 0 := (ob).two_zsmul_oangle_smul_smul_self x /-- The oriented angle between two vectors is zero if and only if the angle with the vectors swapped is zero. -/ lemma oangle_eq_zero_iff_oangle_rev_eq_zero {x y : V} : o.oangle x y = 0 ↔ o.oangle y x = 0 := (ob).oangle_eq_zero_iff_oangle_rev_eq_zero /-- The oriented angle between two vectors is zero if and only if they are on the same ray. -/ lemma oangle_eq_zero_iff_same_ray {x y : V} : o.oangle x y = 0 ↔ same_ray ℝ x y := (ob).oangle_eq_zero_iff_same_ray /-- The oriented angle between two vectors is `π` if and only if the angle with the vectors swapped is `π`. -/ lemma oangle_eq_pi_iff_oangle_rev_eq_pi {x y : V} : o.oangle x y = π ↔ o.oangle y x = π := (ob).oangle_eq_pi_iff_oangle_rev_eq_pi /-- The oriented angle between two vectors is `π` if and only they are nonzero and the first is on the same ray as the negation of the second. -/ lemma oangle_eq_pi_iff_same_ray_neg {x y : V} : o.oangle x y = π ↔ x ≠ 0 ∧ y ≠ 0 ∧ same_ray ℝ x (-y) := (ob).oangle_eq_pi_iff_same_ray_neg /-- The oriented angle between two vectors is zero or `π` if and only if those two vectors are not linearly independent. -/ lemma oangle_eq_zero_or_eq_pi_iff_not_linear_independent {x y : V} : (o.oangle x y = 0 ∨ o.oangle x y = π) ↔ ¬ linear_independent ℝ ![x, y] := (ob).oangle_eq_zero_or_eq_pi_iff_not_linear_independent /-- The oriented angle between two vectors is zero or `π` if and only if the first vector is zero or the second is a multiple of the first. -/ lemma oangle_eq_zero_or_eq_pi_iff_right_eq_smul {x y : V} : (o.oangle x y = 0 ∨ o.oangle x y = π) ↔ (x = 0 ∨ ∃ r : ℝ, y = r • x) := (ob).oangle_eq_zero_or_eq_pi_iff_right_eq_smul /-- The oriented angle between two vectors is not zero or `π` if and only if those two vectors are linearly independent. -/ lemma oangle_ne_zero_and_ne_pi_iff_linear_independent {x y : V} : (o.oangle x y ≠ 0 ∧ o.oangle x y ≠ π) ↔ linear_independent ℝ ![x, y] := (ob).oangle_ne_zero_and_ne_pi_iff_linear_independent /-- Two vectors are equal if and only if they have equal norms and zero angle between them. -/ lemma eq_iff_norm_eq_and_oangle_eq_zero (x y : V) : x = y ↔ ∥x∥ = ∥y∥ ∧ o.oangle x y = 0 := (ob).eq_iff_norm_eq_and_oangle_eq_zero x y /-- Two vectors with equal norms are equal if and only if they have zero angle between them. -/ lemma eq_iff_oangle_eq_zero_of_norm_eq {x y : V} (h : ∥x∥ = ∥y∥) : x = y ↔ o.oangle x y = 0 := (ob).eq_iff_oangle_eq_zero_of_norm_eq h /-- Two vectors with zero angle between them are equal if and only if they have equal norms. -/ lemma eq_iff_norm_eq_of_oangle_eq_zero {x y : V} (h : o.oangle x y = 0) : x = y ↔ ∥x∥ = ∥y∥ := (ob).eq_iff_norm_eq_of_oangle_eq_zero h /-- Given three nonzero vectors, the angle between the first and the second plus the angle between the second and the third equals the angle between the first and the third. -/ @[simp] lemma oangle_add {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : o.oangle x y + o.oangle y z = o.oangle x z := (ob).oangle_add hx hy hz /-- Given three nonzero vectors, the angle between the second and the third plus the angle between the first and the second equals the angle between the first and the third. -/ @[simp] lemma oangle_add_swap {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : o.oangle y z + o.oangle x y = o.oangle x z := (ob).oangle_add_swap hx hy hz /-- Given three nonzero vectors, the angle between the first and the third minus the angle between the first and the second equals the angle between the second and the third. -/ @[simp] lemma oangle_sub_left {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : o.oangle x z - o.oangle x y = o.oangle y z := (ob).oangle_sub_left hx hy hz /-- Given three nonzero vectors, the angle between the first and the third minus the angle between the second and the third equals the angle between the first and the second. -/ @[simp] lemma oangle_sub_right {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : o.oangle x z - o.oangle y z = o.oangle x y := (ob).oangle_sub_right hx hy hz /-- Given three nonzero vectors, adding the angles between them in cyclic order results in 0. -/ @[simp] lemma oangle_add_cyc3 {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : o.oangle x y + o.oangle y z + o.oangle z x = 0 := (ob).oangle_add_cyc3 hx hy hz /-- Given three nonzero vectors, adding the angles between them in cyclic order, with the first vector in each angle negated, results in π. If the vectors add to 0, this is a version of the sum of the angles of a triangle. -/ @[simp] lemma oangle_add_cyc3_neg_left {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : o.oangle (-x) y + o.oangle (-y) z + o.oangle (-z) x = π := (ob).oangle_add_cyc3_neg_left hx hy hz /-- Given three nonzero vectors, adding the angles between them in cyclic order, with the second vector in each angle negated, results in π. If the vectors add to 0, this is a version of the sum of the angles of a triangle. -/ @[simp] lemma oangle_add_cyc3_neg_right {x y z : V} (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) : o.oangle x (-y) + o.oangle y (-z) + o.oangle z (-x) = π := (ob).oangle_add_cyc3_neg_right hx hy hz /-- Pons asinorum, oriented vector angle form. -/ lemma oangle_sub_eq_oangle_sub_rev_of_norm_eq {x y : V} (h : ∥x∥ = ∥y∥) : o.oangle x (x - y) = o.oangle (y - x) y := (ob).oangle_sub_eq_oangle_sub_rev_of_norm_eq h /-- The angle at the apex of an isosceles triangle is `π` minus twice a base angle, oriented vector angle form. -/ lemma oangle_eq_pi_sub_two_zsmul_oangle_sub_of_norm_eq {x y : V} (hn : x ≠ y) (h : ∥x∥ = ∥y∥) : o.oangle y x = π - (2 : ℤ) • o.oangle (y - x) y := (ob).oangle_eq_pi_sub_two_zsmul_oangle_sub_of_norm_eq hn h /-- Angle at center of a circle equals twice angle at circumference, oriented vector angle form. -/ lemma oangle_eq_two_zsmul_oangle_sub_of_norm_eq {x y z : V} (hxyne : x ≠ y) (hxzne : x ≠ z) (hxy : ∥x∥ = ∥y∥) (hxz : ∥x∥ = ∥z∥) : o.oangle y z = (2 : ℤ) • o.oangle (y - x) (z - x) := (ob).oangle_eq_two_zsmul_oangle_sub_of_norm_eq hxyne hxzne hxy hxz /-- Angle at center of a circle equals twice angle at circumference, oriented vector angle form with radius specified. -/ lemma oangle_eq_two_zsmul_oangle_sub_of_norm_eq_real {x y z : V} (hxyne : x ≠ y) (hxzne : x ≠ z) {r : ℝ} (hx : ∥x∥ = r) (hy : ∥y∥ = r) (hz : ∥z∥ = r) : o.oangle y z = (2 : ℤ) • o.oangle (y - x) (z - x) := (ob).oangle_eq_two_zsmul_oangle_sub_of_norm_eq_real hxyne hxzne hx hy hz /-- Oriented vector angle version of "angles in same segment are equal" and "opposite angles of a cyclic quadrilateral add to π", for oriented angles mod π (for which those are the same result), represented here as equality of twice the angles. -/ lemma two_zsmul_oangle_sub_eq_two_zsmul_oangle_sub_of_norm_eq {x₁ x₂ y z : V} (hx₁yne : x₁ ≠ y) (hx₁zne : x₁ ≠ z) (hx₂yne : x₂ ≠ y) (hx₂zne : x₂ ≠ z) {r : ℝ} (hx₁ : ∥x₁∥ = r) (hx₂ : ∥x₂∥ = r) (hy : ∥y∥ = r) (hz : ∥z∥ = r) : (2 : ℤ) • o.oangle (y - x₁) (z - x₁) = (2 : ℤ) • o.oangle (y - x₂) (z - x₂) := (ob).two_zsmul_oangle_sub_eq_two_zsmul_oangle_sub_of_norm_eq hx₁yne hx₁zne hx₂yne hx₂zne hx₁ hx₂ hy hz /-- A rotation by the oriented angle `θ`. -/ def rotation (θ : real.angle) : V ≃ₗᵢ[ℝ] V := (ob).rotation θ /-- The determinant of `rotation` (as a linear map) is equal to `1`. -/ @[simp] lemma det_rotation (θ : real.angle) : ((o.rotation θ).to_linear_equiv : V →ₗ[ℝ] V).det = 1 := (ob).det_rotation θ /-- The determinant of `rotation` (as a linear equiv) is equal to `1`. -/ @[simp] lemma linear_equiv_det_rotation (θ : real.angle) : (o.rotation θ).to_linear_equiv.det = 1 := (ob).linear_equiv_det_rotation θ /-- The inverse of `rotation` is rotation by the negation of the angle. -/ @[simp] lemma rotation_symm (θ : real.angle) : (o.rotation θ).symm = o.rotation (-θ) := (ob).rotation_symm θ /-- Rotation by 0 is the identity. -/ @[simp] lemma rotation_zero : o.rotation 0 = linear_isometry_equiv.refl ℝ V := (ob).rotation_zero /-- Rotation by π is negation. -/ lemma rotation_pi : o.rotation π = linear_isometry_equiv.neg ℝ := (ob).rotation_pi /-- Rotating twice is equivalent to rotating by the sum of the angles. -/ @[simp] lemma rotation_trans (θ₁ θ₂ : real.angle) : (o.rotation θ₁).trans (o.rotation θ₂) = o.rotation (θ₂ + θ₁) := (ob).rotation_trans θ₁ θ₂ /-- Rotating the first vector by `θ` subtracts `θ` from the angle between two vectors. -/ @[simp] lemma oangle_rotation_left {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : o.oangle (o.rotation θ x) y = o.oangle x y - θ := (ob).oangle_rotation_left hx hy θ /-- Rotating the second vector by `θ` adds `θ` to the angle between two vectors. -/ @[simp] lemma oangle_rotation_right {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : o.oangle x (o.rotation θ y) = o.oangle x y + θ := (ob).oangle_rotation_right hx hy θ /-- The rotation of a vector by `θ` has an angle of `-θ` from that vector. -/ @[simp] lemma oangle_rotation_self_left {x : V} (hx : x ≠ 0) (θ : real.angle) : o.oangle (o.rotation θ x) x = -θ := (ob).oangle_rotation_self_left hx θ /-- A vector has an angle of `θ` from the rotation of that vector by `θ`. -/ @[simp] lemma oangle_rotation_self_right {x : V} (hx : x ≠ 0) (θ : real.angle) : o.oangle x (o.rotation θ x) = θ := (ob).oangle_rotation_self_right hx θ /-- Rotating the first vector by the angle between the two vectors results an an angle of 0. -/ @[simp] lemma oangle_rotation_oangle_left (x y : V) : o.oangle (o.rotation (o.oangle x y) x) y = 0 := (ob).oangle_rotation_oangle_left x y /-- Rotating the first vector by the angle between the two vectors and swapping the vectors results an an angle of 0. -/ @[simp] lemma oangle_rotation_oangle_right (x y : V) : o.oangle y (o.rotation (o.oangle x y) x) = 0 := (ob).oangle_rotation_oangle_right x y /-- Rotating both vectors by the same angle does not change the angle between those vectors. -/ @[simp] lemma oangle_rotation (x y : V) (θ : real.angle) : o.oangle (o.rotation θ x) (o.rotation θ y) = o.oangle x y := (ob).oangle_rotation x y θ /-- A rotation of a nonzero vector equals that vector if and only if the angle is zero. -/ @[simp] lemma rotation_eq_self_iff_angle_eq_zero {x : V} (hx : x ≠ 0) (θ : real.angle) : o.rotation θ x = x ↔ θ = 0 := (ob).rotation_eq_self_iff_angle_eq_zero hx θ /-- A nonzero vector equals a rotation of that vector if and only if the angle is zero. -/ @[simp] lemma eq_rotation_self_iff_angle_eq_zero {x : V} (hx : x ≠ 0) (θ : real.angle) : x = o.rotation θ x ↔ θ = 0 := (ob).eq_rotation_self_iff_angle_eq_zero hx θ /-- A rotation of a vector equals that vector if and only if the vector or the angle is zero. -/ lemma rotation_eq_self_iff (x : V) (θ : real.angle) : o.rotation θ x = x ↔ x = 0 ∨ θ = 0 := (ob).rotation_eq_self_iff x θ /-- A vector equals a rotation of that vector if and only if the vector or the angle is zero. -/ lemma eq_rotation_self_iff (x : V) (θ : real.angle) : x = o.rotation θ x ↔ x = 0 ∨ θ = 0 := (ob).eq_rotation_self_iff x θ /-- Rotating a vector by the angle to another vector gives the second vector if and only if the norms are equal. -/ @[simp] lemma rotation_oangle_eq_iff_norm_eq (x y : V) : o.rotation (o.oangle x y) x = y ↔ ∥x∥ = ∥y∥ := (ob).rotation_oangle_eq_iff_norm_eq x y /-- The angle between two nonzero vectors is `θ` if and only if the second vector is the first rotated by `θ` and scaled by the ratio of the norms. -/ lemma oangle_eq_iff_eq_norm_div_norm_smul_rotation_of_ne_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : o.oangle x y = θ ↔ y = (∥y∥ / ∥x∥) • o.rotation θ x := (ob).oangle_eq_iff_eq_norm_div_norm_smul_rotation_of_ne_zero hx hy θ /-- The angle between two nonzero vectors is `θ` if and only if the second vector is the first rotated by `θ` and scaled by a positive real. -/ lemma oangle_eq_iff_eq_pos_smul_rotation_of_ne_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) (θ : real.angle) : o.oangle x y = θ ↔ ∃ r : ℝ, 0 < r ∧ y = r • o.rotation θ x := (ob).oangle_eq_iff_eq_pos_smul_rotation_of_ne_zero hx hy θ /-- The angle between two vectors is `θ` if and only if they are nonzero and the second vector is the first rotated by `θ` and scaled by the ratio of the norms, or `θ` and at least one of the vectors are zero. -/ lemma oangle_eq_iff_eq_norm_div_norm_smul_rotation_or_eq_zero {x y : V} (θ : real.angle) : o.oangle x y = θ ↔ (x ≠ 0 ∧ y ≠ 0 ∧ y = (∥y∥ / ∥x∥) • o.rotation θ x) ∨ (θ = 0 ∧ (x = 0 ∨ y = 0)) := (ob).oangle_eq_iff_eq_norm_div_norm_smul_rotation_or_eq_zero θ /-- The angle between two vectors is `θ` if and only if they are nonzero and the second vector is the first rotated by `θ` and scaled by a positive real, or `θ` and at least one of the vectors are zero. -/ lemma oangle_eq_iff_eq_pos_smul_rotation_or_eq_zero {x y : V} (θ : real.angle) : o.oangle x y = θ ↔ (x ≠ 0 ∧ y ≠ 0 ∧ ∃ r : ℝ, 0 < r ∧ y = r • o.rotation θ x) ∨ (θ = 0 ∧ (x = 0 ∨ y = 0)) := (ob).oangle_eq_iff_eq_pos_smul_rotation_or_eq_zero θ /-- Any linear isometric equivalence in `V` with positive determinant is `rotation`. -/ lemma exists_linear_isometry_equiv_eq_of_det_pos {f : V ≃ₗᵢ[ℝ] V} (hd : 0 < (f.to_linear_equiv : V →ₗ[ℝ] V).det) : ∃ θ : real.angle, f = o.rotation θ := (ob).exists_linear_isometry_equiv_eq_of_det_pos hd /-- The angle between two vectors, with respect to an orientation given by `orientation.map` with a linear isometric equivalence, equals the angle between those two vectors, transformed by the inverse of that equivalence, with respect to the original orientation. -/ @[simp] lemma oangle_map (x y : V) (f : V ≃ₗᵢ[ℝ] V) : (orientation.map (fin 2) f.to_linear_equiv o).oangle x y = o.oangle (f.symm x) (f.symm y) := begin convert (ob).oangle_map x y f using 1, refine orthonormal.oangle_eq_of_orientation_eq _ _ _ _ _, simp_rw [basis.orientation_map, orientation.fin_orthonormal_basis_orientation] end /-- `orientation.oangle` equals `orthonormal.oangle` for any orthonormal basis with that orientation. -/ lemma oangle_eq_basis_oangle {b : basis (fin 2) ℝ V} (hb : orthonormal ℝ b) (h : b.orientation = o) (x y : V) : o.oangle x y = hb.oangle x y := begin rw oangle, refine orthonormal.oangle_eq_of_orientation_eq _ _ _ _ _, simp [h] end /-- Negating the orientation negates the value of `oangle`. -/ lemma oangle_neg_orientation_eq_neg (x y : V) : (-o).oangle x y = -(o.oangle x y) := begin simp_rw oangle, refine orthonormal.oangle_eq_neg_of_orientation_eq_neg _ _ _ _ _, simp_rw orientation.fin_orthonormal_basis_orientation end /-- `orientation.rotation` equals `orthonormal.rotation` for any orthonormal basis with that orientation. -/ lemma rotation_eq_basis_rotation {b : basis (fin 2) ℝ V} (hb : orthonormal ℝ b) (h : b.orientation = o) (θ : ℝ) : o.rotation θ = hb.rotation θ := begin rw rotation, refine orthonormal.rotation_eq_of_orientation_eq _ _ _ _, simp [h] end /-- Negating the orientation negates the angle in `rotation`. -/ lemma rotation_neg_orientation_eq_neg (θ : real.angle) : (-o).rotation θ = o.rotation (-θ) := begin simp_rw rotation, refine orthonormal.rotation_eq_rotation_neg_of_orientation_eq_neg _ _ _ _, simp_rw orientation.fin_orthonormal_basis_orientation end /-- The inner product of two vectors is the product of the norms and the cosine of the oriented angle between the vectors. -/ lemma inner_eq_norm_mul_norm_mul_cos_oangle (x y : V) : ⟪x, y⟫ = ∥x∥ * ∥y∥ * real.angle.cos (o.oangle x y) := (ob).inner_eq_norm_mul_norm_mul_cos_oangle x y /-- The cosine of the oriented angle between two nonzero vectors is the inner product divided by the product of the norms. -/ lemma cos_oangle_eq_inner_div_norm_mul_norm {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : real.angle.cos (o.oangle x y) = ⟪x, y⟫ / (∥x∥ * ∥y∥) := (ob).cos_oangle_eq_inner_div_norm_mul_norm hx hy /-- The cosine of the oriented angle between two nonzero vectors equals that of the unoriented angle. -/ lemma cos_oangle_eq_cos_angle {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : real.angle.cos (o.oangle x y) = real.cos (inner_product_geometry.angle x y) := (ob).cos_oangle_eq_cos_angle hx hy /-- The oriented angle between two nonzero vectors is plus or minus the unoriented angle. -/ lemma oangle_eq_angle_or_eq_neg_angle {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : o.oangle x y = inner_product_geometry.angle x y ∨ o.oangle x y = -inner_product_geometry.angle x y := (ob).oangle_eq_angle_or_eq_neg_angle hx hy /-- The unoriented angle between two nonzero vectors is the absolute value of the oriented angle, converted to a real. -/ lemma angle_eq_abs_oangle_to_real {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : inner_product_geometry.angle x y = |(o.oangle x y).to_real| := (ob).angle_eq_abs_oangle_to_real hx hy /-- If the sign of the oriented angle between two vectors is zero, either one of the vectors is zero or the unoriented angle is 0 or π. -/ lemma eq_zero_or_angle_eq_zero_or_pi_of_sign_oangle_eq_zero {x y : V} (h : (o.oangle x y).sign = 0) : x = 0 ∨ y = 0 ∨ inner_product_geometry.angle x y = 0 ∨ inner_product_geometry.angle x y = π := (ob).eq_zero_or_angle_eq_zero_or_pi_of_sign_oangle_eq_zero h /-- If two unoriented angles are equal, and the signs of the corresponding oriented angles are equal, then the oriented angles are equal (even in degenerate cases). -/ lemma oangle_eq_of_angle_eq_of_sign_eq {w x y z : V} (h : inner_product_geometry.angle w x = inner_product_geometry.angle y z) (hs : (o.oangle w x).sign = (o.oangle y z).sign) : o.oangle w x = o.oangle y z := (ob).oangle_eq_of_angle_eq_of_sign_eq h hs /-- If the signs of two oriented angles between nonzero vectors are equal, the oriented angles are equal if and only if the unoriented angles are equal. -/ lemma oangle_eq_iff_angle_eq_of_sign_eq {w x y z : V} (hw : w ≠ 0) (hx : x ≠ 0) (hy : y ≠ 0) (hz : z ≠ 0) (hs : (o.oangle w x).sign = (o.oangle y z).sign) : inner_product_geometry.angle w x = inner_product_geometry.angle y z ↔ o.oangle w x = o.oangle y z := (ob).oangle_eq_iff_angle_eq_of_sign_eq hw hx hy hz hs /-- The oriented angle between two nonzero vectors is zero if and only if the unoriented angle is zero. -/ lemma oangle_eq_zero_iff_angle_eq_zero {x y : V} (hx : x ≠ 0) (hy : y ≠ 0) : o.oangle x y = 0 ↔ inner_product_geometry.angle x y = 0 := (ob).oangle_eq_zero_iff_angle_eq_zero hx hy /-- The oriented angle between two vectors is `π` if and only if the unoriented angle is `π`. -/ lemma oangle_eq_pi_iff_angle_eq_pi {x y : V} : o.oangle x y = π ↔ inner_product_geometry.angle x y = π := (ob).oangle_eq_pi_iff_angle_eq_pi /-- Negating the first vector passed to `oangle` negates the sign of the angle. -/ @[simp] lemma oangle_sign_neg_left (x y : V) : (o.oangle (-x) y).sign = -((o.oangle x y).sign) := (ob).oangle_sign_neg_left x y /-- Negating the second vector passed to `oangle` negates the sign of the angle. -/ @[simp] lemma oangle_sign_neg_right (x y : V) : (o.oangle x (-y)).sign = -((o.oangle x y).sign) := (ob).oangle_sign_neg_right x y /-- Multiplying the first vector passed to `oangle` by a real multiplies the sign of the angle by the sign of the real. -/ @[simp] lemma oangle_sign_smul_left (x y : V) (r : ℝ) : (o.oangle (r • x) y).sign = sign r * (o.oangle x y).sign := (ob).oangle_sign_smul_left x y r /-- Multiplying the second vector passed to `oangle` by a real multiplies the sign of the angle by the sign of the real. -/ @[simp] lemma oangle_sign_smul_right (x y : V) (r : ℝ) : (o.oangle x (r • y)).sign = sign r * (o.oangle x y).sign := (ob).oangle_sign_smul_right x y r /-- Adding a multiple of the first vector passed to `oangle` to the second vector does not change the sign of the angle. -/ @[simp] lemma oangle_sign_smul_add_right (x y : V) (r : ℝ) : (o.oangle x (r • x + y)).sign = (o.oangle x y).sign := (ob).oangle_sign_smul_add_right x y r /-- Adding a multiple of the second vector passed to `oangle` to the first vector does not change the sign of the angle. -/ @[simp] lemma oangle_sign_add_smul_left (x y : V) (r : ℝ) : (o.oangle (x + r • y) y).sign = (o.oangle x y).sign := (ob).oangle_sign_add_smul_left x y r /-- Subtracting a multiple of the first vector passed to `oangle` from the second vector does not change the sign of the angle. -/ @[simp] lemma oangle_sign_sub_smul_right (x y : V) (r : ℝ) : (o.oangle x (y - r • x)).sign = (o.oangle x y).sign := (ob).oangle_sign_sub_smul_right x y r /-- Subtracting a multiple of the second vector passed to `oangle` from the first vector does not change the sign of the angle. -/ @[simp] lemma oangle_sign_sub_smul_left (x y : V) (r : ℝ) : (o.oangle (x - r • y) y).sign = (o.oangle x y).sign := (ob).oangle_sign_sub_smul_left x y r /-- The sign of the angle between a vector, and a linear combination of that vector with a second vector, is the sign of the factor by which the second vector is multiplied in that combination multiplied by the sign of the angle between the two vectors. -/ @[simp] lemma oangle_sign_smul_add_smul_right (x y : V) (r₁ r₂ : ℝ) : (o.oangle x (r₁ • x + r₂ • y)).sign = sign r₂ * (o.oangle x y).sign := (ob).oangle_sign_smul_add_smul_right x y r₁ r₂ /-- The sign of the angle between a linear combination of two vectors and the second vector is the sign of the factor by which the first vector is multiplied in that combination multiplied by the sign of the angle between the two vectors. -/ @[simp] lemma oangle_sign_smul_add_smul_left (x y : V) (r₁ r₂ : ℝ) : (o.oangle (r₁ • x + r₂ • y) y).sign = sign r₁ * (o.oangle x y).sign := (ob).oangle_sign_smul_add_smul_left x y r₁ r₂ /-- The sign of the angle between two linear combinations of two vectors is the sign of the determinant of the factors in those combinations multiplied by the sign of the angle between the two vectors. -/ lemma oangle_sign_smul_add_smul_smul_add_smul (x y : V) (r₁ r₂ r₃ r₄ : ℝ) : (o.oangle (r₁ • x + r₂ • y) (r₃ • x + r₄ • y)).sign = sign (r₁ * r₄ - r₂ * r₃) * (o.oangle x y).sign := (ob).oangle_sign_smul_add_smul_smul_add_smul x y r₁ r₂ r₃ r₄ end orientation
733d69a84d840059c20dc212da1094373dc2f620
618003631150032a5676f229d13a079ac875ff77
/src/data/string/defs.lean
8f99f1282902b66b5dae946bfa02dd6f695d9149
[ "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,622
lean
/- Copyright (c) 2019 Simon Hudon. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Simon Hudon, Keeley Hoek, Floris van Doorn -/ import data.list.defs namespace string /-- `s.split_on c` tokenizes `s : string` on `c : char`. -/ def split_on (s : string) (c : char) : list string := split (= c) s /-- `string.map_tokens c f s` tokenizes `s : string` on `c : char`, maps `f` over each token, and then reassembles the string by intercalating the separator token `c` over the mapped tokens. -/ def map_tokens (c : char) (f : string → string) : string → string := intercalate (singleton c) ∘ list.map f ∘ split (= c) /-- Tests whether the first string is a prefix of the second string. -/ def is_prefix_of (x y : string) : bool := x.to_list.is_prefix_of y.to_list /-- Tests whether the first string is a suffix of the second string. -/ def is_suffix_of (x y : string) : bool := x.to_list.is_suffix_of y.to_list /-- `x.starts_with y` is true if `y` is a prefix of `x`, and is false otherwise. -/ abbreviation starts_with (x y : string) : bool := y.is_prefix_of x /-- `x.ends_with y` is true if `y` is a suffix of `x`, and is false otherwise. -/ abbreviation ends_with (x y : string) : bool := y.is_suffix_of x /-- `get_rest s t` returns `some r` if `s = t ++ r`. If `t` is not a prefix of `s`, returns `none` -/ def get_rest (s t : string) : option string := list.as_string <$> s.to_list.get_rest t.to_list /-- Removes the first `n` elements from the string `s` -/ def popn (s : string) (n : nat) : string := (s.mk_iterator.nextn n).next_to_string end string
b8c95831ac7405cf912f201ad0fe95c09440b94d
4727251e0cd73359b15b664c3170e5d754078599
/src/analysis/normed_space/operator_norm.lean
487928749e3cc281b842c88169f66a860a059a6d
[ "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
87,134
lean
/- Copyright (c) 2019 Jan-David Salchow. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Jan-David Salchow, Sébastien Gouëzel, Jean Lo -/ import algebra.algebra.tower import analysis.asymptotics.asymptotics import analysis.normed_space.linear_isometry import analysis.normed_space.riesz_lemma /-! # Operator norm on the space of continuous linear maps Define the operator norm on the space of continuous (semi)linear maps between normed spaces, and prove its basic properties. In particular, show that this space is itself a normed space. Since a lot of elementary properties don't require `∥x∥ = 0 → x = 0` we start setting up the theory for `semi_normed_group` and we specialize to `normed_group` at the end. Note that most of statements that apply to semilinear maps only hold when the ring homomorphism is isometric, as expressed by the typeclass `[ring_hom_isometric σ]`. -/ noncomputable theory open_locale classical nnreal topological_space -- the `ₗ` subscript variables are for special cases about linear (as opposed to semilinear) maps variables {𝕜 𝕜₂ 𝕜₃ E Eₗ F Fₗ G Gₗ : Type*} section semi_normed variables [semi_normed_group E] [semi_normed_group Eₗ] [semi_normed_group F] [semi_normed_group Fₗ] variables [semi_normed_group G] [semi_normed_group Gₗ] open metric continuous_linear_map section normed_field /-! Most statements in this file require the field to be non-discrete, as this is necessary to deduce an inequality `∥f x∥ ≤ C ∥x∥` from the continuity of f. However, the other direction always holds. In this section, we just assume that `𝕜` is a normed field. In the remainder of the file, it will be non-discrete. -/ variables [normed_field 𝕜] [normed_field 𝕜₂] [normed_space 𝕜 E] [normed_space 𝕜₂ F] variables [normed_space 𝕜 G] {σ : 𝕜 →+* 𝕜₂} (f : E →ₛₗ[σ] F) lemma linear_map.lipschitz_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : lipschitz_with (real.to_nnreal C) f := f.to_add_monoid_hom.lipschitz_of_bound C h lemma linear_map.lipschitz_of_bound_nnnorm (C : ℝ≥0) (h : ∀ x, ∥f x∥₊ ≤ C * ∥x∥₊) : lipschitz_with C f := f.to_add_monoid_hom.lipschitz_of_bound_nnnorm C h theorem linear_map.antilipschitz_of_bound {K : ℝ≥0} (h : ∀ x, ∥x∥ ≤ K * ∥f x∥) : antilipschitz_with K f := antilipschitz_with.of_le_mul_dist $ λ x y, by simpa only [dist_eq_norm, f.map_sub] using h (x - y) lemma linear_map.bound_of_antilipschitz {K : ℝ≥0} (h : antilipschitz_with K f) (x) : ∥x∥ ≤ K * ∥f x∥ := by simpa only [dist_zero_right, f.map_zero] using h.le_mul_dist x 0 lemma linear_map.uniform_continuous_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : uniform_continuous f := (f.lipschitz_of_bound C h).uniform_continuous lemma linear_map.continuous_of_bound (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : continuous f := (f.lipschitz_of_bound C h).continuous /-- Construct a continuous linear map from a linear map and a bound on this linear map. The fact that the norm of the continuous linear map is then controlled is given in `linear_map.mk_continuous_norm_le`. -/ def linear_map.mk_continuous (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : E →SL[σ] F := ⟨f, linear_map.continuous_of_bound f C h⟩ /-- Reinterpret a linear map `𝕜 →ₗ[𝕜] E` as a continuous linear map. This construction is generalized to the case of any finite dimensional domain in `linear_map.to_continuous_linear_map`. -/ def linear_map.to_continuous_linear_map₁ (f : 𝕜 →ₗ[𝕜] E) : 𝕜 →L[𝕜] E := f.mk_continuous (∥f 1∥) $ λ x, le_of_eq $ by { conv_lhs { rw ← mul_one x }, rw [← smul_eq_mul, f.map_smul, norm_smul, mul_comm] } /-- Construct a continuous linear map from a linear map and the existence of a bound on this linear map. If you have an explicit bound, use `linear_map.mk_continuous` instead, as a norm estimate will follow automatically in `linear_map.mk_continuous_norm_le`. -/ def linear_map.mk_continuous_of_exists_bound (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) : E →SL[σ] F := ⟨f, let ⟨C, hC⟩ := h in linear_map.continuous_of_bound f C hC⟩ lemma continuous_of_linear_of_boundₛₗ {f : E → F} (h_add : ∀ x y, f (x + y) = f x + f y) (h_smul : ∀ (c : 𝕜) x, f (c • x) = (σ c) • f x) {C : ℝ} (h_bound : ∀ x, ∥f x∥ ≤ C*∥x∥) : continuous f := let φ : E →ₛₗ[σ] F := { to_fun := f, map_add' := h_add, map_smul' := h_smul } in φ.continuous_of_bound C h_bound lemma continuous_of_linear_of_bound {f : E → G} (h_add : ∀ x y, f (x + y) = f x + f y) (h_smul : ∀ (c : 𝕜) x, f (c • x) = c • f x) {C : ℝ} (h_bound : ∀ x, ∥f x∥ ≤ C*∥x∥) : continuous f := let φ : E →ₗ[𝕜] G := { to_fun := f, map_add' := h_add, map_smul' := h_smul } in φ.continuous_of_bound C h_bound @[simp, norm_cast] lemma linear_map.mk_continuous_coe (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : ((f.mk_continuous C h) : E →ₛₗ[σ] F) = f := rfl @[simp] lemma linear_map.mk_continuous_apply (C : ℝ) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) (x : E) : f.mk_continuous C h x = f x := rfl @[simp, norm_cast] lemma linear_map.mk_continuous_of_exists_bound_coe (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) : ((f.mk_continuous_of_exists_bound h) : E →ₛₗ[σ] F) = f := rfl @[simp] lemma linear_map.mk_continuous_of_exists_bound_apply (h : ∃C, ∀x, ∥f x∥ ≤ C * ∥x∥) (x : E) : f.mk_continuous_of_exists_bound h x = f x := rfl @[simp] lemma linear_map.to_continuous_linear_map₁_coe (f : 𝕜 →ₗ[𝕜] E) : (f.to_continuous_linear_map₁ : 𝕜 →ₗ[𝕜] E) = f := rfl @[simp] lemma linear_map.to_continuous_linear_map₁_apply (f : 𝕜 →ₗ[𝕜] E) (x) : f.to_continuous_linear_map₁ x = f x := rfl end normed_field variables [nondiscrete_normed_field 𝕜] [nondiscrete_normed_field 𝕜₂] [nondiscrete_normed_field 𝕜₃] [normed_space 𝕜 E] [normed_space 𝕜 Eₗ] [normed_space 𝕜₂ F] [normed_space 𝕜 Fₗ] [normed_space 𝕜₃ G] [normed_space 𝕜 Gₗ] {σ₁₂ : 𝕜 →+* 𝕜₂} {σ₂₃ : 𝕜₂ →+* 𝕜₃} {σ₁₃ : 𝕜 →+* 𝕜₃} [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] /-- If `∥x∥ = 0` and `f` is continuous then `∥f x∥ = 0`. -/ lemma norm_image_of_norm_zero {f : E →ₛₗ[σ₁₂] F} (hf : continuous f) {x : E} (hx : ∥x∥ = 0) : ∥f x∥ = 0 := begin refine le_antisymm (le_of_forall_pos_le_add (λ ε hε, _)) (norm_nonneg (f x)), rcases normed_group.tendsto_nhds_nhds.1 (hf.tendsto 0) ε hε with ⟨δ, δ_pos, hδ⟩, replace hδ := hδ x, rw [sub_zero, hx] at hδ, replace hδ := le_of_lt (hδ δ_pos), rw [linear_map.map_zero, sub_zero] at hδ, rwa [zero_add] end section variables [ring_hom_isometric σ₁₂] [ring_hom_isometric σ₂₃] lemma linear_map.bound_of_shell_semi_normed (f : E →ₛₗ[σ₁₂] F) {ε C : ℝ} (ε_pos : 0 < ε) {c : 𝕜} (hc : 1 < ∥c∥) (hf : ∀ x, ε / ∥c∥ ≤ ∥x∥ → ∥x∥ < ε → ∥f x∥ ≤ C * ∥x∥) {x : E} (hx : ∥x∥ ≠ 0) : ∥f x∥ ≤ C * ∥x∥ := begin rcases rescale_to_shell_semi_normed hc ε_pos hx with ⟨δ, hδ, δxle, leδx, δinv⟩, have := hf (δ • x) leδx δxle, simpa only [f.map_smulₛₗ, norm_smul, mul_left_comm C, mul_le_mul_left (norm_pos_iff.2 hδ), ring_hom_isometric.is_iso] using hf (δ • x) leδx δxle end /-- A continuous linear map between seminormed spaces is bounded when the field is nondiscrete. The continuity ensures boundedness on a ball of some radius `ε`. The nondiscreteness is then used to rescale any element into an element of norm in `[ε/C, ε]`, whose image has a controlled norm. The norm control for the original element follows by rescaling. -/ lemma linear_map.bound_of_continuous (f : E →ₛₗ[σ₁₂] F) (hf : continuous f) : ∃ C, 0 < C ∧ (∀ x : E, ∥f x∥ ≤ C * ∥x∥) := begin rcases normed_group.tendsto_nhds_nhds.1 (hf.tendsto 0) 1 zero_lt_one with ⟨ε, ε_pos, hε⟩, simp only [sub_zero, f.map_zero] at hε, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, have : 0 < ∥c∥ / ε, from div_pos (zero_lt_one.trans hc) ε_pos, refine ⟨∥c∥ / ε, this, λ x, _⟩, by_cases hx : ∥x∥ = 0, { rw [hx, mul_zero], exact le_of_eq (norm_image_of_norm_zero hf hx) }, refine f.bound_of_shell_semi_normed ε_pos hc (λ x hle hlt, _) hx, refine (hε _ hlt).le.trans _, rwa [← div_le_iff' this, one_div_div] end end namespace continuous_linear_map theorem bound [ring_hom_isometric σ₁₂] (f : E →SL[σ₁₂] F) : ∃ C, 0 < C ∧ (∀ x : E, ∥f x∥ ≤ C * ∥x∥) := f.to_linear_map.bound_of_continuous f.2 section open filter /-- A linear map which is a homothety is a continuous linear map. Since the field `𝕜` need not have `ℝ` as a subfield, this theorem is not directly deducible from the corresponding theorem about isometries plus a theorem about scalar multiplication. Likewise for the other theorems about homotheties in this file. -/ def of_homothety (f : E →ₛₗ[σ₁₂] F) (a : ℝ) (hf : ∀x, ∥f x∥ = a * ∥x∥) : E →SL[σ₁₂] F := f.mk_continuous a (λ x, le_of_eq (hf x)) variable (𝕜) lemma to_span_singleton_homothety (x : E) (c : 𝕜) : ∥linear_map.to_span_singleton 𝕜 E x c∥ = ∥x∥ * ∥c∥ := by {rw mul_comm, exact norm_smul _ _} /-- Given an element `x` of a normed space `E` over a field `𝕜`, the natural continuous linear map from `𝕜` to `E` by taking multiples of `x`.-/ def to_span_singleton (x : E) : 𝕜 →L[𝕜] E := of_homothety (linear_map.to_span_singleton 𝕜 E x) ∥x∥ (to_span_singleton_homothety 𝕜 x) lemma to_span_singleton_apply (x : E) (r : 𝕜) : to_span_singleton 𝕜 x r = r • x := by simp [to_span_singleton, of_homothety, linear_map.to_span_singleton] lemma to_span_singleton_add (x y : E) : to_span_singleton 𝕜 (x + y) = to_span_singleton 𝕜 x + to_span_singleton 𝕜 y := by { ext1, simp [to_span_singleton_apply], } lemma to_span_singleton_smul' (𝕜') [normed_field 𝕜'] [normed_space 𝕜' E] [smul_comm_class 𝕜 𝕜' E] (c : 𝕜') (x : E) : to_span_singleton 𝕜 (c • x) = c • to_span_singleton 𝕜 x := by { ext1, rw [to_span_singleton_apply, smul_apply, to_span_singleton_apply, smul_comm], } lemma to_span_singleton_smul (c : 𝕜) (x : E) : to_span_singleton 𝕜 (c • x) = c • to_span_singleton 𝕜 x := to_span_singleton_smul' 𝕜 𝕜 c x variables (𝕜 E) /-- Given a unit-length element `x` of a normed space `E` over a field `𝕜`, the natural linear isometry map from `𝕜` to `E` by taking multiples of `x`.-/ def _root_.linear_isometry.to_span_singleton {v : E} (hv : ∥v∥ = 1) : 𝕜 →ₗᵢ[𝕜] E := { norm_map' := λ x, by simp [norm_smul, hv], .. linear_map.to_span_singleton 𝕜 E v } variables {𝕜 E} @[simp] lemma _root_.linear_isometry.to_span_singleton_apply {v : E} (hv : ∥v∥ = 1) (a : 𝕜) : linear_isometry.to_span_singleton 𝕜 E hv a = a • v := rfl @[simp] lemma _root_.linear_isometry.coe_to_span_singleton {v : E} (hv : ∥v∥ = 1) : (linear_isometry.to_span_singleton 𝕜 E hv).to_linear_map = linear_map.to_span_singleton 𝕜 E v := rfl end section op_norm open set real /-- The operator norm of a continuous linear map is the inf of all its bounds. -/ def op_norm (f : E →SL[σ₁₂] F) := Inf {c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥} instance has_op_norm : has_norm (E →SL[σ₁₂] F) := ⟨op_norm⟩ lemma norm_def (f : E →SL[σ₁₂] F) : ∥f∥ = Inf {c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥} := rfl -- So that invocations of `le_cInf` make sense: we show that the set of -- bounds is nonempty and bounded below. lemma bounds_nonempty [ring_hom_isometric σ₁₂] {f : E →SL[σ₁₂] F} : ∃ c, c ∈ { c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥ } := let ⟨M, hMp, hMb⟩ := f.bound in ⟨M, le_of_lt hMp, hMb⟩ lemma bounds_bdd_below {f : E →SL[σ₁₂] F} : bdd_below { c | 0 ≤ c ∧ ∀ x, ∥f x∥ ≤ c * ∥x∥ } := ⟨0, λ _ ⟨hn, _⟩, hn⟩ /-- If one controls the norm of every `A x`, then one controls the norm of `A`. -/ lemma op_norm_le_bound (f : E →SL[σ₁₂] F) {M : ℝ} (hMp: 0 ≤ M) (hM : ∀ x, ∥f x∥ ≤ M * ∥x∥) : ∥f∥ ≤ M := cInf_le bounds_bdd_below ⟨hMp, hM⟩ theorem op_norm_le_of_lipschitz {f : E →SL[σ₁₂] F} {K : ℝ≥0} (hf : lipschitz_with K f) : ∥f∥ ≤ K := f.op_norm_le_bound K.2 $ λ x, by simpa only [dist_zero_right, f.map_zero] using hf.dist_le_mul x 0 lemma op_norm_eq_of_bounds {φ : E →SL[σ₁₂] F} {M : ℝ} (M_nonneg : 0 ≤ M) (h_above : ∀ x, ∥φ x∥ ≤ M*∥x∥) (h_below : ∀ N ≥ 0, (∀ x, ∥φ x∥ ≤ N*∥x∥) → M ≤ N) : ∥φ∥ = M := le_antisymm (φ.op_norm_le_bound M_nonneg h_above) ((le_cInf_iff continuous_linear_map.bounds_bdd_below ⟨M, M_nonneg, h_above⟩).mpr $ λ N ⟨N_nonneg, hN⟩, h_below N N_nonneg hN) lemma op_norm_neg (f : E →SL[σ₁₂] F) : ∥-f∥ = ∥f∥ := by simp only [norm_def, neg_apply, norm_neg] theorem antilipschitz_of_bound (f : E →SL[σ₁₂] F) {K : ℝ≥0} (h : ∀ x, ∥x∥ ≤ K * ∥f x∥) : antilipschitz_with K f := linear_map.antilipschitz_of_bound _ h lemma bound_of_antilipschitz (f : E →SL[σ₁₂] F) {K : ℝ≥0} (h : antilipschitz_with K f) (x) : ∥x∥ ≤ K * ∥f x∥ := linear_map.bound_of_antilipschitz _ h x section variables [ring_hom_isometric σ₁₂] [ring_hom_isometric σ₂₃] (f g : E →SL[σ₁₂] F) (h : F →SL[σ₂₃] G) (x : E) lemma op_norm_nonneg : 0 ≤ ∥f∥ := le_cInf bounds_nonempty (λ _ ⟨hx, _⟩, hx) /-- The fundamental property of the operator norm: `∥f x∥ ≤ ∥f∥ * ∥x∥`. -/ theorem le_op_norm : ∥f x∥ ≤ ∥f∥ * ∥x∥ := begin obtain ⟨C, Cpos, hC⟩ := f.bound, replace hC := hC x, by_cases h : ∥x∥ = 0, { rwa [h, mul_zero] at ⊢ hC }, have hlt : 0 < ∥x∥ := lt_of_le_of_ne (norm_nonneg x) (ne.symm h), exact (div_le_iff hlt).mp (le_cInf bounds_nonempty (λ c ⟨_, hc⟩, (div_le_iff hlt).mpr $ by { apply hc })), end theorem dist_le_op_norm (x y : E) : dist (f x) (f y) ≤ ∥f∥ * dist x y := by simp_rw [dist_eq_norm, ← map_sub, f.le_op_norm] theorem le_op_norm_of_le {c : ℝ} {x} (h : ∥x∥ ≤ c) : ∥f x∥ ≤ ∥f∥ * c := le_trans (f.le_op_norm x) (mul_le_mul_of_nonneg_left h f.op_norm_nonneg) theorem le_of_op_norm_le {c : ℝ} (h : ∥f∥ ≤ c) (x : E) : ∥f x∥ ≤ c * ∥x∥ := (f.le_op_norm x).trans (mul_le_mul_of_nonneg_right h (norm_nonneg x)) lemma ratio_le_op_norm : ∥f x∥ / ∥x∥ ≤ ∥f∥ := div_le_of_nonneg_of_le_mul (norm_nonneg _) f.op_norm_nonneg (le_op_norm _ _) /-- The image of the unit ball under a continuous linear map is bounded. -/ lemma unit_le_op_norm : ∥x∥ ≤ 1 → ∥f x∥ ≤ ∥f∥ := mul_one ∥f∥ ▸ f.le_op_norm_of_le lemma op_norm_le_of_shell {f : E →SL[σ₁₂] F} {ε C : ℝ} (ε_pos : 0 < ε) (hC : 0 ≤ C) {c : 𝕜} (hc : 1 < ∥c∥) (hf : ∀ x, ε / ∥c∥ ≤ ∥x∥ → ∥x∥ < ε → ∥f x∥ ≤ C * ∥x∥) : ∥f∥ ≤ C := begin refine f.op_norm_le_bound hC (λ x, _), by_cases hx : ∥x∥ = 0, { rw [hx, mul_zero], exact le_of_eq (norm_image_of_norm_zero f.2 hx) }, exact linear_map.bound_of_shell_semi_normed f ε_pos hc hf hx end lemma op_norm_le_of_ball {f : E →SL[σ₁₂] F} {ε : ℝ} {C : ℝ} (ε_pos : 0 < ε) (hC : 0 ≤ C) (hf : ∀ x ∈ ball (0 : E) ε, ∥f x∥ ≤ C * ∥x∥) : ∥f∥ ≤ C := begin rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine op_norm_le_of_shell ε_pos hC hc (λ x _ hx, hf x _), rwa ball_zero_eq end lemma op_norm_le_of_nhds_zero {f : E →SL[σ₁₂] F} {C : ℝ} (hC : 0 ≤ C) (hf : ∀ᶠ x in 𝓝 (0 : E), ∥f x∥ ≤ C * ∥x∥) : ∥f∥ ≤ C := let ⟨ε, ε0, hε⟩ := metric.eventually_nhds_iff_ball.1 hf in op_norm_le_of_ball ε0 hC hε lemma op_norm_le_of_shell' {f : E →SL[σ₁₂] F} {ε C : ℝ} (ε_pos : 0 < ε) (hC : 0 ≤ C) {c : 𝕜} (hc : ∥c∥ < 1) (hf : ∀ x, ε * ∥c∥ ≤ ∥x∥ → ∥x∥ < ε → ∥f x∥ ≤ C * ∥x∥) : ∥f∥ ≤ C := begin by_cases h0 : c = 0, { refine op_norm_le_of_ball ε_pos hC (λ x hx, hf x _ _), { simp [h0] }, { rwa ball_zero_eq at hx } }, { rw [← inv_inv c, norm_inv, inv_lt_one_iff_of_pos (norm_pos_iff.2 $ inv_ne_zero h0)] at hc, refine op_norm_le_of_shell ε_pos hC hc _, rwa [norm_inv, div_eq_mul_inv, inv_inv] } end /-- The operator norm satisfies the triangle inequality. -/ theorem op_norm_add_le : ∥f + g∥ ≤ ∥f∥ + ∥g∥ := (f + g).op_norm_le_bound (add_nonneg f.op_norm_nonneg g.op_norm_nonneg) $ λ x, (norm_add_le_of_le (f.le_op_norm x) (g.le_op_norm x)).trans_eq (add_mul _ _ _).symm /-- The norm of the `0` operator is `0`. -/ theorem op_norm_zero : ∥(0 : E →SL[σ₁₂] F)∥ = 0 := le_antisymm (cInf_le bounds_bdd_below ⟨le_rfl, λ _, le_of_eq (by { rw [zero_mul], exact norm_zero })⟩) (op_norm_nonneg _) /-- The norm of the identity is at most `1`. It is in fact `1`, except when the space is trivial where it is `0`. It means that one can not do better than an inequality in general. -/ lemma norm_id_le : ∥id 𝕜 E∥ ≤ 1 := op_norm_le_bound _ zero_le_one (λx, by simp) /-- If there is an element with norm different from `0`, then the norm of the identity equals `1`. (Since we are working with seminorms supposing that the space is non-trivial is not enough.) -/ lemma norm_id_of_nontrivial_seminorm (h : ∃ (x : E), ∥x∥ ≠ 0) : ∥id 𝕜 E∥ = 1 := le_antisymm norm_id_le $ let ⟨x, hx⟩ := h in have _ := (id 𝕜 E).ratio_le_op_norm x, by rwa [id_apply, div_self hx] at this lemma op_norm_smul_le {𝕜' : Type*} [normed_field 𝕜'] [normed_space 𝕜' F] [smul_comm_class 𝕜₂ 𝕜' F] (c : 𝕜') (f : E →SL[σ₁₂] F) : ∥c • f∥ ≤ ∥c∥ * ∥f∥ := ((c • f).op_norm_le_bound (mul_nonneg (norm_nonneg _) (op_norm_nonneg _)) (λ _, begin erw [norm_smul, mul_assoc], exact mul_le_mul_of_nonneg_left (le_op_norm _ _) (norm_nonneg _) end)) /-- Continuous linear maps themselves form a seminormed space with respect to the operator norm. -/ instance to_semi_normed_group : semi_normed_group (E →SL[σ₁₂] F) := semi_normed_group.of_core _ ⟨op_norm_zero, λ x y, op_norm_add_le x y, op_norm_neg⟩ lemma nnnorm_def (f : E →SL[σ₁₂] F) : ∥f∥₊ = Inf {c | ∀ x, ∥f x∥₊ ≤ c * ∥x∥₊} := begin ext, rw [nnreal.coe_Inf, coe_nnnorm, norm_def, nnreal.coe_image], simp_rw [← nnreal.coe_le_coe, nnreal.coe_mul, coe_nnnorm, mem_set_of_eq, subtype.coe_mk, exists_prop], end /-- If one controls the norm of every `A x`, then one controls the norm of `A`. -/ lemma op_nnnorm_le_bound (f : E →SL[σ₁₂] F) (M : ℝ≥0) (hM : ∀ x, ∥f x∥₊ ≤ M * ∥x∥₊) : ∥f∥₊ ≤ M := op_norm_le_bound f (zero_le M) hM theorem op_nnnorm_le_of_lipschitz {f : E →SL[σ₁₂] F} {K : ℝ≥0} (hf : lipschitz_with K f) : ∥f∥₊ ≤ K := op_norm_le_of_lipschitz hf lemma op_nnnorm_eq_of_bounds {φ : E →SL[σ₁₂] F} (M : ℝ≥0) (h_above : ∀ x, ∥φ x∥ ≤ M*∥x∥) (h_below : ∀ N, (∀ x, ∥φ x∥₊ ≤ N*∥x∥₊) → M ≤ N) : ∥φ∥₊ = M := subtype.ext $ op_norm_eq_of_bounds (zero_le M) h_above $ subtype.forall'.mpr h_below instance to_normed_space {𝕜' : Type*} [normed_field 𝕜'] [normed_space 𝕜' F] [smul_comm_class 𝕜₂ 𝕜' F] : normed_space 𝕜' (E →SL[σ₁₂] F) := ⟨op_norm_smul_le⟩ include σ₁₃ /-- The operator norm is submultiplicative. -/ lemma op_norm_comp_le (f : E →SL[σ₁₂] F) : ∥h.comp f∥ ≤ ∥h∥ * ∥f∥ := (cInf_le bounds_bdd_below ⟨mul_nonneg (op_norm_nonneg _) (op_norm_nonneg _), λ x, by { rw mul_assoc, exact h.le_op_norm_of_le (f.le_op_norm x) } ⟩) lemma op_nnnorm_comp_le [ring_hom_isometric σ₁₃] (f : E →SL[σ₁₂] F) : ∥h.comp f∥₊ ≤ ∥h∥₊ * ∥f∥₊ := op_norm_comp_le h f omit σ₁₃ /-- Continuous linear maps form a seminormed ring with respect to the operator norm. -/ instance to_semi_normed_ring : semi_normed_ring (E →L[𝕜] E) := { norm_mul := λ f g, op_norm_comp_le f g, .. continuous_linear_map.to_semi_normed_group } /-- For a normed space `E`, continuous linear endomorphisms form a normed algebra with respect to the operator norm. -/ instance to_normed_algebra : normed_algebra 𝕜 (E →L[𝕜] E) := { .. continuous_linear_map.to_normed_space, .. continuous_linear_map.algebra } theorem le_op_nnnorm : ∥f x∥₊ ≤ ∥f∥₊ * ∥x∥₊ := f.le_op_norm x theorem nndist_le_op_nnnorm (x y : E) : nndist (f x) (f y) ≤ ∥f∥₊ * nndist x y := dist_le_op_norm f x y /-- continuous linear maps are Lipschitz continuous. -/ theorem lipschitz : lipschitz_with ∥f∥₊ f := (f : E →ₛₗ[σ₁₂] F).lipschitz_of_bound_nnnorm _ f.le_op_nnnorm /-- Evaluation of a continuous linear map `f` at a point is Lipschitz continuous in `f`. -/ theorem lipschitz_apply (x : E) : lipschitz_with ∥x∥₊ (λ f : E →SL[σ₁₂] F, f x) := lipschitz_with_iff_norm_sub_le.2 $ λ f g, ((f - g).le_op_norm x).trans_eq (mul_comm _ _) end section lemma op_norm_ext [ring_hom_isometric σ₁₃] (f : E →SL[σ₁₂] F) (g : E →SL[σ₁₃] G) (h : ∀ x, ∥f x∥ = ∥g x∥) : ∥f∥ = ∥g∥ := op_norm_eq_of_bounds (norm_nonneg _) (λ x, by { rw h x, exact le_op_norm _ _ }) (λ c hc h₂, op_norm_le_bound _ hc (λ z, by { rw ←h z, exact h₂ z })) variables [ring_hom_isometric σ₂₃] theorem op_norm_le_bound₂ (f : E →SL[σ₁₃] F →SL[σ₂₃] G) {C : ℝ} (h0 : 0 ≤ C) (hC : ∀ x y, ∥f x y∥ ≤ C * ∥x∥ * ∥y∥) : ∥f∥ ≤ C := f.op_norm_le_bound h0 $ λ x, (f x).op_norm_le_bound (mul_nonneg h0 (norm_nonneg _)) $ hC x theorem le_op_norm₂ [ring_hom_isometric σ₁₃] (f : E →SL[σ₁₃] F →SL[σ₂₃] G) (x : E) (y : F) : ∥f x y∥ ≤ ∥f∥ * ∥x∥ * ∥y∥ := (f x).le_of_op_norm_le (f.le_op_norm x) y end @[simp] lemma op_norm_prod (f : E →L[𝕜] Fₗ) (g : E →L[𝕜] Gₗ) : ∥f.prod g∥ = ∥(f, g)∥ := le_antisymm (op_norm_le_bound _ (norm_nonneg _) $ λ x, by simpa only [prod_apply, prod.norm_def, max_mul_of_nonneg, norm_nonneg] using max_le_max (le_op_norm f x) (le_op_norm g x)) $ max_le (op_norm_le_bound _ (norm_nonneg _) $ λ x, (le_max_left _ _).trans ((f.prod g).le_op_norm x)) (op_norm_le_bound _ (norm_nonneg _) $ λ x, (le_max_right _ _).trans ((f.prod g).le_op_norm x)) @[simp] lemma op_nnnorm_prod (f : E →L[𝕜] Fₗ) (g : E →L[𝕜] Gₗ) : ∥f.prod g∥₊ = ∥(f, g)∥₊ := subtype.ext $ op_norm_prod f g /-- `continuous_linear_map.prod` as a `linear_isometry_equiv`. -/ def prodₗᵢ (R : Type*) [semiring R] [module R Fₗ] [module R Gₗ] [has_continuous_const_smul R Fₗ] [has_continuous_const_smul R Gₗ] [smul_comm_class 𝕜 R Fₗ] [smul_comm_class 𝕜 R Gₗ] : (E →L[𝕜] Fₗ) × (E →L[𝕜] Gₗ) ≃ₗᵢ[R] (E →L[𝕜] Fₗ × Gₗ) := ⟨prodₗ R, λ ⟨f, g⟩, op_norm_prod f g⟩ /-- A continuous linear map is an isometry if and only if it preserves the norm. (Note: Do you really want to use this lemma? Try using the bundled structure `linear_isometry` instead.) -/ lemma isometry_iff_norm (f : E →SL[σ₁₂] F) : isometry f ↔ ∀x, ∥f x∥ = ∥x∥ := f.to_linear_map.to_add_monoid_hom.isometry_iff_norm variables [ring_hom_isometric σ₁₂] (f : E →SL[σ₁₂] F) @[simp, nontriviality] lemma op_norm_subsingleton [subsingleton E] : ∥f∥ = 0 := begin refine le_antisymm _ (norm_nonneg _), apply op_norm_le_bound _ rfl.ge, intros x, simp [subsingleton.elim x 0] end end op_norm section is_O variables [ring_hom_isometric σ₁₂] (c : 𝕜) (f g : E →SL[σ₁₂] F) (h : F →SL[σ₂₃] G) (x y z : E) open asymptotics theorem is_O_with_id (l : filter E) : is_O_with ∥f∥ f (λ x, x) l := is_O_with_of_le' _ f.le_op_norm theorem is_O_id (l : filter E) : is_O f (λ x, x) l := (f.is_O_with_id l).is_O theorem is_O_with_comp [ring_hom_isometric σ₂₃] {α : Type*} (g : F →SL[σ₂₃] G) (f : α → F) (l : filter α) : is_O_with ∥g∥ (λ x', g (f x')) f l := (g.is_O_with_id ⊤).comp_tendsto le_top theorem is_O_comp [ring_hom_isometric σ₂₃] {α : Type*} (g : F →SL[σ₂₃] G) (f : α → F) (l : filter α) : is_O (λ x', g (f x')) f l := (g.is_O_with_comp f l).is_O theorem is_O_with_sub (f : E →SL[σ₁₂] F) (l : filter E) (x : E) : is_O_with ∥f∥ (λ x', f (x' - x)) (λ x', x' - x) l := f.is_O_with_comp _ l theorem is_O_sub (f : E →SL[σ₁₂] F) (l : filter E) (x : E) : is_O (λ x', f (x' - x)) (λ x', x' - x) l := f.is_O_comp _ l end is_O end continuous_linear_map namespace linear_isometry lemma norm_to_continuous_linear_map_le (f : E →ₛₗᵢ[σ₁₂] F) : ∥f.to_continuous_linear_map∥ ≤ 1 := f.to_continuous_linear_map.op_norm_le_bound zero_le_one $ λ x, by simp end linear_isometry namespace linear_map /-- If a continuous linear map is constructed from a linear map via the constructor `mk_continuous`, then its norm is bounded by the bound given to the constructor if it is nonnegative. -/ lemma mk_continuous_norm_le (f : E →ₛₗ[σ₁₂] F) {C : ℝ} (hC : 0 ≤ C) (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : ∥f.mk_continuous C h∥ ≤ C := continuous_linear_map.op_norm_le_bound _ hC h /-- If a continuous linear map is constructed from a linear map via the constructor `mk_continuous`, then its norm is bounded by the bound or zero if bound is negative. -/ lemma mk_continuous_norm_le' (f : E →ₛₗ[σ₁₂] F) {C : ℝ} (h : ∀x, ∥f x∥ ≤ C * ∥x∥) : ∥f.mk_continuous C h∥ ≤ max C 0 := continuous_linear_map.op_norm_le_bound _ (le_max_right _ _) $ λ x, (h x).trans $ mul_le_mul_of_nonneg_right (le_max_left _ _) (norm_nonneg x) variables [ring_hom_isometric σ₂₃] /-- Create a bilinear map (represented as a map `E →L[𝕜] F →L[𝕜] G`) from the corresponding linear map and a bound on the norm of the image. The linear map can be constructed using `linear_map.mk₂`. -/ def mk_continuous₂ (f : E →ₛₗ[σ₁₃] F →ₛₗ[σ₂₃] G) (C : ℝ) (hC : ∀ x y, ∥f x y∥ ≤ C * ∥x∥ * ∥y∥) : E →SL[σ₁₃] F →SL[σ₂₃] G := linear_map.mk_continuous { to_fun := λ x, (f x).mk_continuous (C * ∥x∥) (hC x), map_add' := λ x y, by { ext z, simp }, map_smul' := λ c x, by { ext z, simp } } (max C 0) $ λ x, (mk_continuous_norm_le' _ _).trans_eq $ by rw [max_mul_of_nonneg _ _ (norm_nonneg x), zero_mul] @[simp] lemma mk_continuous₂_apply (f : E →ₛₗ[σ₁₃] F →ₛₗ[σ₂₃] G) {C : ℝ} (hC : ∀ x y, ∥f x y∥ ≤ C * ∥x∥ * ∥y∥) (x : E) (y : F) : f.mk_continuous₂ C hC x y = f x y := rfl lemma mk_continuous₂_norm_le' (f : E →ₛₗ[σ₁₃] F →ₛₗ[σ₂₃] G) {C : ℝ} (hC : ∀ x y, ∥f x y∥ ≤ C * ∥x∥ * ∥y∥) : ∥f.mk_continuous₂ C hC∥ ≤ max C 0 := mk_continuous_norm_le _ (le_max_iff.2 $ or.inr le_rfl) _ lemma mk_continuous₂_norm_le (f : E →ₛₗ[σ₁₃] F →ₛₗ[σ₂₃] G) {C : ℝ} (h0 : 0 ≤ C) (hC : ∀ x y, ∥f x y∥ ≤ C * ∥x∥ * ∥y∥) : ∥f.mk_continuous₂ C hC∥ ≤ C := (f.mk_continuous₂_norm_le' hC).trans_eq $ max_eq_left h0 end linear_map namespace continuous_linear_map variables [ring_hom_isometric σ₂₃] [ring_hom_isometric σ₁₃] /-- Flip the order of arguments of a continuous bilinear map. For a version bundled as `linear_isometry_equiv`, see `continuous_linear_map.flipL`. -/ def flip (f : E →SL[σ₁₃] F →SL[σ₂₃] G) : F →SL[σ₂₃] E →SL[σ₁₃] G := linear_map.mk_continuous₂ (linear_map.mk₂'ₛₗ σ₂₃ σ₁₃ (λ y x, f x y) (λ x y z, (f z).map_add x y) (λ c y x, (f x).map_smulₛₗ c y) (λ z x y, by rw [f.map_add, add_apply]) (λ c y x, by rw [map_smulₛₗ, smul_apply])) ∥f∥ (λ y x, (f.le_op_norm₂ x y).trans_eq $ by rw mul_right_comm) private lemma le_norm_flip (f : E →SL[σ₁₃] F →SL[σ₂₃] G) : ∥f∥ ≤ ∥flip f∥ := f.op_norm_le_bound₂ (norm_nonneg _) $ λ x y, by { rw mul_right_comm, exact (flip f).le_op_norm₂ y x } @[simp] lemma flip_apply (f : E →SL[σ₁₃] F →SL[σ₂₃] G) (x : E) (y : F) : f.flip y x = f x y := rfl @[simp] lemma flip_flip (f : E →SL[σ₁₃] F →SL[σ₂₃] G) : f.flip.flip = f := by { ext, refl } @[simp] lemma op_norm_flip (f : E →SL[σ₁₃] F →SL[σ₂₃] G) : ∥f.flip∥ = ∥f∥ := le_antisymm (by simpa only [flip_flip] using le_norm_flip f.flip) (le_norm_flip f) @[simp] lemma flip_add (f g : E →SL[σ₁₃] F →SL[σ₂₃] G) : (f + g).flip = f.flip + g.flip := rfl @[simp] lemma flip_smul (c : 𝕜₃) (f : E →SL[σ₁₃] F →SL[σ₂₃] G) : (c • f).flip = c • f.flip := rfl variables (E F G σ₁₃ σ₂₃) /-- Flip the order of arguments of a continuous bilinear map. This is a version bundled as a `linear_isometry_equiv`. For an unbundled version see `continuous_linear_map.flip`. -/ def flipₗᵢ' : (E →SL[σ₁₃] F →SL[σ₂₃] G) ≃ₗᵢ[𝕜₃] (F →SL[σ₂₃] E →SL[σ₁₃] G) := { to_fun := flip, inv_fun := flip, map_add' := flip_add, map_smul' := flip_smul, left_inv := flip_flip, right_inv := flip_flip, norm_map' := op_norm_flip } variables {E F G σ₁₃ σ₂₃} @[simp] lemma flipₗᵢ'_symm : (flipₗᵢ' E F G σ₂₃ σ₁₃).symm = flipₗᵢ' F E G σ₁₃ σ₂₃ := rfl @[simp] lemma coe_flipₗᵢ' : ⇑(flipₗᵢ' E F G σ₂₃ σ₁₃) = flip := rfl variables (𝕜 E Fₗ Gₗ) /-- Flip the order of arguments of a continuous bilinear map. This is a version bundled as a `linear_isometry_equiv`. For an unbundled version see `continuous_linear_map.flip`. -/ def flipₗᵢ : (E →L[𝕜] Fₗ →L[𝕜] Gₗ) ≃ₗᵢ[𝕜] (Fₗ →L[𝕜] E →L[𝕜] Gₗ) := { to_fun := flip, inv_fun := flip, map_add' := flip_add, map_smul' := flip_smul, left_inv := flip_flip, right_inv := flip_flip, norm_map' := op_norm_flip } variables {𝕜 E Fₗ Gₗ} @[simp] lemma flipₗᵢ_symm : (flipₗᵢ 𝕜 E Fₗ Gₗ).symm = flipₗᵢ 𝕜 Fₗ E Gₗ := rfl @[simp] lemma coe_flipₗᵢ : ⇑(flipₗᵢ 𝕜 E Fₗ Gₗ) = flip := rfl variables (F σ₁₂) [ring_hom_isometric σ₁₂] /-- The continuous semilinear map obtained by applying a continuous semilinear map at a given vector. This is the continuous version of `linear_map.applyₗ`. -/ def apply' : E →SL[σ₁₂] (E →SL[σ₁₂] F) →L[𝕜₂] F := flip (id 𝕜₂ (E →SL[σ₁₂] F)) variables {F σ₁₂} @[simp] lemma apply_apply' (v : E) (f : E →SL[σ₁₂] F) : apply' F σ₁₂ v f = f v := rfl variables (𝕜 Fₗ) /-- The continuous semilinear map obtained by applying a continuous semilinear map at a given vector. This is the continuous version of `linear_map.applyₗ`. -/ def apply : E →L[𝕜] (E →L[𝕜] Fₗ) →L[𝕜] Fₗ := flip (id 𝕜 (E →L[𝕜] Fₗ)) variables {𝕜 Fₗ} @[simp] lemma apply_apply (v : E) (f : E →L[𝕜] Fₗ) : apply 𝕜 Fₗ v f = f v := rfl variables (σ₁₂ σ₂₃ E F G) /-- Composition of continuous semilinear maps as a continuous semibilinear map. -/ def compSL : (F →SL[σ₂₃] G) →L[𝕜₃] (E →SL[σ₁₂] F) →SL[σ₂₃] (E →SL[σ₁₃] G) := linear_map.mk_continuous₂ (linear_map.mk₂'ₛₗ (ring_hom.id 𝕜₃) σ₂₃ comp add_comp smul_comp comp_add (λ c f g, by { ext, simp only [map_smulₛₗ, coe_smul', coe_comp', function.comp_app, pi.smul_apply] })) 1 $ λ f g, by simpa only [one_mul] using op_norm_comp_le f g variables {𝕜 E F G} include σ₁₃ @[simp] lemma compSL_apply (f : F →SL[σ₂₃] G) (g : E →SL[σ₁₂] F) : compSL E F G σ₁₂ σ₂₃ f g = f.comp g := rfl omit σ₁₃ variables (𝕜 E Fₗ Gₗ) /-- Composition of continuous linear maps as a continuous bilinear map. -/ def compL : (Fₗ →L[𝕜] Gₗ) →L[𝕜] (E →L[𝕜] Fₗ) →L[𝕜] (E →L[𝕜] Gₗ) := compSL E Fₗ Gₗ (ring_hom.id 𝕜) (ring_hom.id 𝕜) @[simp] lemma compL_apply (f : Fₗ →L[𝕜] Gₗ) (g : E →L[𝕜] Fₗ) : compL 𝕜 E Fₗ Gₗ f g = f.comp g := rfl variables (Eₗ) {𝕜 E Fₗ Gₗ} /-- Apply `L(x,-)` pointwise to bilinear maps, as a continuous bilinear map -/ @[simps apply] def precompR (L : E →L[𝕜] Fₗ →L[𝕜] Gₗ) : E →L[𝕜] (Eₗ →L[𝕜] Fₗ) →L[𝕜] (Eₗ →L[𝕜] Gₗ) := (compL 𝕜 Eₗ Fₗ Gₗ).comp L /-- Apply `L(-,y)` pointwise to bilinear maps, as a continuous bilinear map -/ def precompL (L : E →L[𝕜] Fₗ →L[𝕜] Gₗ) : (Eₗ →L[𝕜] E) →L[𝕜] Fₗ →L[𝕜] (Eₗ →L[𝕜] Gₗ) := (precompR Eₗ (flip L)).flip section prod universes u₁ u₂ u₃ u₄ variables (M₁ : Type u₁) [semi_normed_group M₁] [normed_space 𝕜 M₁] (M₂ : Type u₂) [semi_normed_group M₂] [normed_space 𝕜 M₂] (M₃ : Type u₃) [semi_normed_group M₃] [normed_space 𝕜 M₃] (M₄ : Type u₄) [semi_normed_group M₄] [normed_space 𝕜 M₄] variables {Eₗ} (𝕜) /-- `continuous_linear_map.prod_map` as a continuous linear map. -/ def prod_mapL : ((M₁ →L[𝕜] M₂) × (M₃ →L[𝕜] M₄)) →L[𝕜] ((M₁ × M₃) →L[𝕜] (M₂ × M₄)) := continuous_linear_map.copy (have Φ₁ : (M₁ →L[𝕜] M₂) →L[𝕜] (M₁ →L[𝕜] M₂ × M₄), from continuous_linear_map.compL 𝕜 M₁ M₂ (M₂ × M₄) (continuous_linear_map.inl 𝕜 M₂ M₄), have Φ₂ : (M₃ →L[𝕜] M₄) →L[𝕜] (M₃ →L[𝕜] M₂ × M₄), from continuous_linear_map.compL 𝕜 M₃ M₄ (M₂ × M₄) (continuous_linear_map.inr 𝕜 M₂ M₄), have Φ₁' : _, from (continuous_linear_map.compL 𝕜 (M₁ × M₃) M₁ (M₂ × M₄)).flip (continuous_linear_map.fst 𝕜 M₁ M₃), have Φ₂' : _ , from (continuous_linear_map.compL 𝕜 (M₁ × M₃) M₃ (M₂ × M₄)).flip (continuous_linear_map.snd 𝕜 M₁ M₃), have Ψ₁ : ((M₁ →L[𝕜] M₂) × (M₃ →L[𝕜] M₄)) →L[𝕜] (M₁ →L[𝕜] M₂), from continuous_linear_map.fst 𝕜 (M₁ →L[𝕜] M₂) (M₃ →L[𝕜] M₄), have Ψ₂ : ((M₁ →L[𝕜] M₂) × (M₃ →L[𝕜] M₄)) →L[𝕜] (M₃ →L[𝕜] M₄), from continuous_linear_map.snd 𝕜 (M₁ →L[𝕜] M₂) (M₃ →L[𝕜] M₄), Φ₁' ∘L Φ₁ ∘L Ψ₁ + Φ₂' ∘L Φ₂ ∘L Ψ₂) (λ p : (M₁ →L[𝕜] M₂) × (M₃ →L[𝕜] M₄), p.1.prod_map p.2) (begin apply funext, rintros ⟨φ, ψ⟩, apply continuous_linear_map.ext (λ x, _), simp only [add_apply, coe_comp', coe_fst', function.comp_app, compL_apply, flip_apply, coe_snd', inl_apply, inr_apply, prod.mk_add_mk, add_zero, zero_add, coe_prod_map', prod_map, prod.mk.inj_iff, eq_self_iff_true, and_self], refl end) variables {M₁ M₂ M₃ M₄} @[simp] lemma prod_mapL_apply (p : (M₁ →L[𝕜] M₂) × (M₃ →L[𝕜] M₄)) : continuous_linear_map.prod_mapL 𝕜 M₁ M₂ M₃ M₄ p = p.1.prod_map p.2 := rfl variables {X : Type*} [topological_space X] lemma _root_.continuous.prod_mapL {f : X → M₁ →L[𝕜] M₂} {g : X → M₃ →L[𝕜] M₄} (hf : continuous f) (hg : continuous g) : continuous (λ x, (f x).prod_map (g x)) := (prod_mapL 𝕜 M₁ M₂ M₃ M₄).continuous.comp (hf.prod_mk hg) lemma _root_.continuous.prod_map_equivL {f : X → M₁ ≃L[𝕜] M₂} {g : X → M₃ ≃L[𝕜] M₄} (hf : continuous (λ x, (f x : M₁ →L[𝕜] M₂))) (hg : continuous (λ x, (g x : M₃ →L[𝕜] M₄))) : continuous (λ x, ((f x).prod (g x) : M₁ × M₃ →L[𝕜] M₂ × M₄)) := (prod_mapL 𝕜 M₁ M₂ M₃ M₄).continuous.comp (hf.prod_mk hg) lemma _root_.continuous_on.prod_mapL {f : X → M₁ →L[𝕜] M₂} {g : X → M₃ →L[𝕜] M₄} {s : set X} (hf : continuous_on f s) (hg : continuous_on g s) : continuous_on (λ x, (f x).prod_map (g x)) s := ((prod_mapL 𝕜 M₁ M₂ M₃ M₄).continuous.comp_continuous_on (hf.prod hg) : _) lemma _root_.continuous_on.prod_map_equivL {f : X → M₁ ≃L[𝕜] M₂} {g : X → M₃ ≃L[𝕜] M₄} {s : set X} (hf : continuous_on (λ x, (f x : M₁ →L[𝕜] M₂)) s) (hg : continuous_on (λ x, (g x : M₃ →L[𝕜] M₄)) s) : continuous_on (λ x, ((f x).prod (g x) : M₁ × M₃ →L[𝕜] M₂ × M₄)) s := (prod_mapL 𝕜 M₁ M₂ M₃ M₄).continuous.comp_continuous_on (hf.prod hg) end prod variables {𝕜 E Fₗ Gₗ} section multiplication_linear variables (𝕜) (𝕜' : Type*) [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] /-- Left multiplication in a normed algebra as a continuous bilinear map. -/ def lmul : 𝕜' →L[𝕜] 𝕜' →L[𝕜] 𝕜' := (algebra.lmul 𝕜 𝕜').to_linear_map.mk_continuous₂ 1 $ λ x y, by simpa using norm_mul_le x y @[simp] lemma lmul_apply (x y : 𝕜') : lmul 𝕜 𝕜' x y = x * y := rfl @[simp] lemma op_norm_lmul_apply_le (x : 𝕜') : ∥lmul 𝕜 𝕜' x∥ ≤ ∥x∥ := (op_norm_le_bound _ (norm_nonneg x) (norm_mul_le x)) /-- Left multiplication in a normed algebra as a linear isometry to the space of continuous linear maps. -/ def lmulₗᵢ [norm_one_class 𝕜'] : 𝕜' →ₗᵢ[𝕜] 𝕜' →L[𝕜] 𝕜' := { to_linear_map := lmul 𝕜 𝕜', norm_map' := λ x, le_antisymm (op_norm_lmul_apply_le _ _ _) (by { convert ratio_le_op_norm _ (1 : 𝕜'), simp [norm_one], apply_instance }) } @[simp] lemma coe_lmulₗᵢ [norm_one_class 𝕜'] : ⇑(lmulₗᵢ 𝕜 𝕜') = lmul 𝕜 𝕜' := rfl @[simp] lemma op_norm_lmul_apply [norm_one_class 𝕜'] (x : 𝕜') : ∥lmul 𝕜 𝕜' x∥ = ∥x∥ := (lmulₗᵢ 𝕜 𝕜').norm_map x /-- Right-multiplication in a normed algebra, considered as a continuous linear map. -/ def lmul_right : 𝕜' →L[𝕜] 𝕜' →L[𝕜] 𝕜' := (lmul 𝕜 𝕜').flip @[simp] lemma lmul_right_apply (x y : 𝕜') : lmul_right 𝕜 𝕜' x y = y * x := rfl @[simp] lemma op_norm_lmul_right_apply_le (x : 𝕜') : ∥lmul_right 𝕜 𝕜' x∥ ≤ ∥x∥ := op_norm_le_bound _ (norm_nonneg x) (λ y, (norm_mul_le y x).trans_eq (mul_comm _ _)) @[simp] lemma op_norm_lmul_right_apply [norm_one_class 𝕜'] (x : 𝕜') : ∥lmul_right 𝕜 𝕜' x∥ = ∥x∥ := le_antisymm (op_norm_lmul_right_apply_le _ _ _) (by { convert ratio_le_op_norm _ (1 : 𝕜'), simp [norm_one], apply_instance }) /-- Right-multiplication in a normed algebra, considered as a linear isometry to the space of continuous linear maps. -/ def lmul_rightₗᵢ [norm_one_class 𝕜'] : 𝕜' →ₗᵢ[𝕜] 𝕜' →L[𝕜] 𝕜' := { to_linear_map := lmul_right 𝕜 𝕜', norm_map' := op_norm_lmul_right_apply 𝕜 𝕜' } @[simp] lemma coe_lmul_rightₗᵢ [norm_one_class 𝕜'] : ⇑(lmul_rightₗᵢ 𝕜 𝕜') = lmul_right 𝕜 𝕜' := rfl /-- Simultaneous left- and right-multiplication in a normed algebra, considered as a continuous trilinear map. -/ def lmul_left_right : 𝕜' →L[𝕜] 𝕜' →L[𝕜] 𝕜' →L[𝕜] 𝕜' := ((compL 𝕜 𝕜' 𝕜' 𝕜').comp (lmul_right 𝕜 𝕜')).flip.comp (lmul 𝕜 𝕜') @[simp] lemma lmul_left_right_apply (x y z : 𝕜') : lmul_left_right 𝕜 𝕜' x y z = x * z * y := rfl lemma op_norm_lmul_left_right_apply_apply_le (x y : 𝕜') : ∥lmul_left_right 𝕜 𝕜' x y∥ ≤ ∥x∥ * ∥y∥ := (op_norm_comp_le _ _).trans $ (mul_comm _ _).trans_le $ mul_le_mul (op_norm_lmul_apply_le _ _ _) (op_norm_lmul_right_apply_le _ _ _) (norm_nonneg _) (norm_nonneg _) lemma op_norm_lmul_left_right_apply_le (x : 𝕜') : ∥lmul_left_right 𝕜 𝕜' x∥ ≤ ∥x∥ := op_norm_le_bound _ (norm_nonneg x) (op_norm_lmul_left_right_apply_apply_le 𝕜 𝕜' x) lemma op_norm_lmul_left_right_le : ∥lmul_left_right 𝕜 𝕜'∥ ≤ 1 := op_norm_le_bound _ zero_le_one (λ x, (one_mul ∥x∥).symm ▸ op_norm_lmul_left_right_apply_le 𝕜 𝕜' x) end multiplication_linear section smul_linear variables (𝕜) (𝕜' : Type*) [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] [normed_space 𝕜' E] [is_scalar_tower 𝕜 𝕜' E] /-- Scalar multiplication as a continuous bilinear map. -/ def lsmul : 𝕜' →L[𝕜] E →L[𝕜] E := ((algebra.lsmul 𝕜 E).to_linear_map : 𝕜' →ₗ[𝕜] E →ₗ[𝕜] E).mk_continuous₂ 1 $ λ c x, by simpa only [one_mul] using (norm_smul c x).le @[simp] lemma lsmul_apply (c : 𝕜') (x : E) : lsmul 𝕜 𝕜' c x = c • x := rfl variables {𝕜'} lemma norm_to_span_singleton (x : E) : ∥to_span_singleton 𝕜 x∥ = ∥x∥ := begin refine op_norm_eq_of_bounds (norm_nonneg _) (λ x, _) (λ N hN_nonneg h, _), { rw [to_span_singleton_apply, norm_smul, mul_comm], }, { specialize h 1, rw [to_span_singleton_apply, norm_smul, mul_comm] at h, exact (mul_le_mul_right (by simp)).mp h, }, end variables {𝕜} lemma op_norm_lsmul_apply_le (x : 𝕜') : ∥(lsmul 𝕜 𝕜' x : E →L[𝕜] E)∥ ≤ ∥x∥ := continuous_linear_map.op_norm_le_bound _ (norm_nonneg x) $ λ y, (norm_smul x y).le /-- The norm of `lsmul` is at most 1 in any semi-normed group. -/ lemma op_norm_lsmul_le : ∥(lsmul 𝕜 𝕜' : 𝕜' →L[𝕜] E →L[𝕜] E)∥ ≤ 1 := begin refine continuous_linear_map.op_norm_le_bound _ zero_le_one (λ x, _), simp_rw [one_mul], exact op_norm_lsmul_apply_le _, end end smul_linear section restrict_scalars variables {𝕜' : Type*} [nondiscrete_normed_field 𝕜'] [normed_algebra 𝕜' 𝕜] variables [normed_space 𝕜' E] [is_scalar_tower 𝕜' 𝕜 E] variables [normed_space 𝕜' Fₗ] [is_scalar_tower 𝕜' 𝕜 Fₗ] @[simp] lemma norm_restrict_scalars (f : E →L[𝕜] Fₗ) : ∥f.restrict_scalars 𝕜'∥ = ∥f∥ := le_antisymm (op_norm_le_bound _ (norm_nonneg _) $ λ x, f.le_op_norm x) (op_norm_le_bound _ (norm_nonneg _) $ λ x, f.le_op_norm x) variables (𝕜 E Fₗ 𝕜') (𝕜'' : Type*) [ring 𝕜''] [module 𝕜'' Fₗ] [has_continuous_const_smul 𝕜'' Fₗ] [smul_comm_class 𝕜 𝕜'' Fₗ] [smul_comm_class 𝕜' 𝕜'' Fₗ] /-- `continuous_linear_map.restrict_scalars` as a `linear_isometry`. -/ def restrict_scalars_isometry : (E →L[𝕜] Fₗ) →ₗᵢ[𝕜''] (E →L[𝕜'] Fₗ) := ⟨restrict_scalarsₗ 𝕜 E Fₗ 𝕜' 𝕜'', norm_restrict_scalars⟩ variables {𝕜 E Fₗ 𝕜' 𝕜''} @[simp] lemma coe_restrict_scalars_isometry : ⇑(restrict_scalars_isometry 𝕜 E Fₗ 𝕜' 𝕜'') = restrict_scalars 𝕜' := rfl @[simp] lemma restrict_scalars_isometry_to_linear_map : (restrict_scalars_isometry 𝕜 E Fₗ 𝕜' 𝕜'').to_linear_map = restrict_scalarsₗ 𝕜 E Fₗ 𝕜' 𝕜'' := rfl variables (𝕜 E Fₗ 𝕜' 𝕜'') /-- `continuous_linear_map.restrict_scalars` as a `continuous_linear_map`. -/ def restrict_scalarsL : (E →L[𝕜] Fₗ) →L[𝕜''] (E →L[𝕜'] Fₗ) := (restrict_scalars_isometry 𝕜 E Fₗ 𝕜' 𝕜'').to_continuous_linear_map variables {𝕜 E Fₗ 𝕜' 𝕜''} @[simp] lemma coe_restrict_scalarsL : (restrict_scalarsL 𝕜 E Fₗ 𝕜' 𝕜'' : (E →L[𝕜] Fₗ) →ₗ[𝕜''] (E →L[𝕜'] Fₗ)) = restrict_scalarsₗ 𝕜 E Fₗ 𝕜' 𝕜'' := rfl @[simp] lemma coe_restrict_scalarsL' : ⇑(restrict_scalarsL 𝕜 E Fₗ 𝕜' 𝕜'') = restrict_scalars 𝕜' := rfl end restrict_scalars end continuous_linear_map namespace submodule lemma norm_subtypeL_le (K : submodule 𝕜 E) : ∥K.subtypeL∥ ≤ 1 := K.subtypeₗᵢ.norm_to_continuous_linear_map_le end submodule section has_sum -- Results in this section hold for continuous additive monoid homomorphisms or equivalences but we -- don't have bundled continuous additive homomorphisms. variables {ι R R₂ M M₂ : Type*} [semiring R] [semiring R₂] [add_comm_monoid M] [module R M] [add_comm_monoid M₂] [module R₂ M₂] [topological_space M] [topological_space M₂] {σ : R →+* R₂} {σ' : R₂ →+* R} [ring_hom_inv_pair σ σ'] [ring_hom_inv_pair σ' σ] /-- Applying a continuous linear map commutes with taking an (infinite) sum. -/ protected lemma continuous_linear_map.has_sum {f : ι → M} (φ : M →SL[σ] M₂) {x : M} (hf : has_sum f x) : has_sum (λ (b:ι), φ (f b)) (φ x) := by simpa only using hf.map φ.to_linear_map.to_add_monoid_hom φ.continuous alias continuous_linear_map.has_sum ← has_sum.mapL protected lemma continuous_linear_map.summable {f : ι → M} (φ : M →SL[σ] M₂) (hf : summable f) : summable (λ b:ι, φ (f b)) := (hf.has_sum.mapL φ).summable alias continuous_linear_map.summable ← summable.mapL protected lemma continuous_linear_map.map_tsum [t2_space M₂] {f : ι → M} (φ : M →SL[σ] M₂) (hf : summable f) : φ (∑' z, f z) = ∑' z, φ (f z) := (hf.has_sum.mapL φ).tsum_eq.symm include σ' /-- Applying a continuous linear map commutes with taking an (infinite) sum. -/ protected lemma continuous_linear_equiv.has_sum {f : ι → M} (e : M ≃SL[σ] M₂) {y : M₂} : has_sum (λ (b:ι), e (f b)) y ↔ has_sum f (e.symm y) := ⟨λ h, by simpa only [e.symm.coe_coe, e.symm_apply_apply] using h.mapL (e.symm : M₂ →SL[σ'] M), λ h, by simpa only [e.coe_coe, e.apply_symm_apply] using (e : M →SL[σ] M₂).has_sum h⟩ protected lemma continuous_linear_equiv.summable {f : ι → M} (e : M ≃SL[σ] M₂) : summable (λ b:ι, e (f b)) ↔ summable f := ⟨λ hf, (e.has_sum.1 hf.has_sum).summable, (e : M →SL[σ] M₂).summable⟩ lemma continuous_linear_equiv.tsum_eq_iff [t2_space M] [t2_space M₂] {f : ι → M} (e : M ≃SL[σ] M₂) {y : M₂} : ∑' z, e (f z) = y ↔ ∑' z, f z = e.symm y := begin by_cases hf : summable f, { exact ⟨λ h, (e.has_sum.mp ((e.summable.mpr hf).has_sum_iff.mpr h)).tsum_eq, λ h, (e.has_sum.mpr (hf.has_sum_iff.mpr h)).tsum_eq⟩ }, { have hf' : ¬summable (λ z, e (f z)) := λ h, hf (e.summable.mp h), rw [tsum_eq_zero_of_not_summable hf, tsum_eq_zero_of_not_summable hf'], exact ⟨by { rintro rfl, simp }, λ H, by simpa using (congr_arg (λ z, e z) H)⟩ } end protected lemma continuous_linear_equiv.map_tsum [t2_space M] [t2_space M₂] {f : ι → M} (e : M ≃SL[σ] M₂) : e (∑' z, f z) = ∑' z, e (f z) := by { refine symm (e.tsum_eq_iff.mpr _), rw e.symm_apply_apply _ } end has_sum namespace continuous_linear_equiv section variables {σ₂₁ : 𝕜₂ →+* 𝕜} [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] [ring_hom_isometric σ₁₂] variables (e : E ≃SL[σ₁₂] F) include σ₂₁ protected lemma lipschitz : lipschitz_with (∥(e : E →SL[σ₁₂] F)∥₊) e := (e : E →SL[σ₁₂] F).lipschitz theorem is_O_comp {α : Type*} (f : α → E) (l : filter α) : asymptotics.is_O (λ x', e (f x')) f l := (e : E →SL[σ₁₂] F).is_O_comp f l theorem is_O_sub (l : filter E) (x : E) : asymptotics.is_O (λ x', e (x' - x)) (λ x', x' - x) l := (e : E →SL[σ₁₂] F).is_O_sub l x end variables {σ₂₁ : 𝕜₂ →+* 𝕜} [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] include σ₂₁ lemma homothety_inverse (a : ℝ) (ha : 0 < a) (f : E ≃ₛₗ[σ₁₂] F) : (∀ (x : E), ∥f x∥ = a * ∥x∥) → (∀ (y : F), ∥f.symm y∥ = a⁻¹ * ∥y∥) := begin intros hf y, calc ∥(f.symm) y∥ = a⁻¹ * (a * ∥ (f.symm) y∥) : _ ... = a⁻¹ * ∥f ((f.symm) y)∥ : by rw hf ... = a⁻¹ * ∥y∥ : by simp, rw [← mul_assoc, inv_mul_cancel (ne_of_lt ha).symm, one_mul], end /-- A linear equivalence which is a homothety is a continuous linear equivalence. -/ def of_homothety (f : E ≃ₛₗ[σ₁₂] F) (a : ℝ) (ha : 0 < a) (hf : ∀x, ∥f x∥ = a * ∥x∥) : E ≃SL[σ₁₂] F := { to_linear_equiv := f, continuous_to_fun := f.to_linear_map.continuous_of_bound a (λ x, le_of_eq (hf x)), continuous_inv_fun := f.symm.to_linear_map.continuous_of_bound a⁻¹ (λ x, le_of_eq (homothety_inverse a ha f hf x)) } variables [ring_hom_isometric σ₂₁] (e : E ≃SL[σ₁₂] F) theorem is_O_comp_rev {α : Type*} (f : α → E) (l : filter α) : asymptotics.is_O f (λ x', e (f x')) l := (e.symm.is_O_comp _ l).congr_left $ λ _, e.symm_apply_apply _ theorem is_O_sub_rev (l : filter E) (x : E) : asymptotics.is_O (λ x', x' - x) (λ x', e (x' - x)) l := e.is_O_comp_rev _ _ omit σ₂₁ variable (𝕜) lemma to_span_nonzero_singleton_homothety (x : E) (h : x ≠ 0) (c : 𝕜) : ∥linear_equiv.to_span_nonzero_singleton 𝕜 E x h c∥ = ∥x∥ * ∥c∥ := continuous_linear_map.to_span_singleton_homothety _ _ _ end continuous_linear_equiv variables {σ₂₁ : 𝕜₂ →+* 𝕜} [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] include σ₂₁ /-- Construct a continuous linear equivalence from a linear equivalence together with bounds in both directions. -/ def linear_equiv.to_continuous_linear_equiv_of_bounds (e : E ≃ₛₗ[σ₁₂] F) (C_to C_inv : ℝ) (h_to : ∀ x, ∥e x∥ ≤ C_to * ∥x∥) (h_inv : ∀ x : F, ∥e.symm x∥ ≤ C_inv * ∥x∥) : E ≃SL[σ₁₂] F := { to_linear_equiv := e, continuous_to_fun := e.to_linear_map.continuous_of_bound C_to h_to, continuous_inv_fun := e.symm.to_linear_map.continuous_of_bound C_inv h_inv } omit σ₂₁ namespace continuous_linear_map variables {E' F' : Type*} [semi_normed_group E'] [semi_normed_group F'] variables {𝕜₁' : Type*} {𝕜₂' : Type*} [nondiscrete_normed_field 𝕜₁'] [nondiscrete_normed_field 𝕜₂'] [normed_space 𝕜₁' E'] [normed_space 𝕜₂' F'] {σ₁' : 𝕜₁' →+* 𝕜} {σ₁₃' : 𝕜₁' →+* 𝕜₃} {σ₂' : 𝕜₂' →+* 𝕜₂} {σ₂₃' : 𝕜₂' →+* 𝕜₃} [ring_hom_comp_triple σ₁' σ₁₃ σ₁₃'] [ring_hom_comp_triple σ₂' σ₂₃ σ₂₃'] [ring_hom_isometric σ₂₃] [ring_hom_isometric σ₁₃'] [ring_hom_isometric σ₂₃'] /-- Compose a bilinear map `E →SL[σ₁₃] F →SL[σ₂₃] G` with two linear maps `E' →SL[σ₁'] E` and `F' →SL[σ₂'] F`. -/ def bilinear_comp (f : E →SL[σ₁₃] F →SL[σ₂₃] G) (gE : E' →SL[σ₁'] E) (gF : F' →SL[σ₂'] F) : E' →SL[σ₁₃'] F' →SL[σ₂₃'] G := ((f.comp gE).flip.comp gF).flip include σ₁₃' σ₂₃' @[simp] lemma bilinear_comp_apply (f : E →SL[σ₁₃] F →SL[σ₂₃] G) (gE : E' →SL[σ₁'] E) (gF : F' →SL[σ₂'] F) (x : E') (y : F') : f.bilinear_comp gE gF x y = f (gE x) (gF y) := rfl omit σ₁₃' σ₂₃' variables [ring_hom_isometric σ₁₃] [ring_hom_isometric σ₁'] [ring_hom_isometric σ₂'] /-- Derivative of a continuous bilinear map `f : E →L[𝕜] F →L[𝕜] G` interpreted as a map `E × F → G` at point `p : E × F` evaluated at `q : E × F`, as a continuous bilinear map. -/ def deriv₂ (f : E →L[𝕜] Fₗ →L[𝕜] Gₗ) : (E × Fₗ) →L[𝕜] (E × Fₗ) →L[𝕜] Gₗ := f.bilinear_comp (fst _ _ _) (snd _ _ _) + f.flip.bilinear_comp (snd _ _ _) (fst _ _ _) @[simp] lemma coe_deriv₂ (f : E →L[𝕜] Fₗ →L[𝕜] Gₗ) (p : E × Fₗ) : ⇑(f.deriv₂ p) = λ q : E × Fₗ, f p.1 q.2 + f q.1 p.2 := rfl lemma map_add_add (f : E →L[𝕜] Fₗ →L[𝕜] Gₗ) (x x' : E) (y y' : Fₗ) : f (x + x') (y + y') = f x y + f.deriv₂ (x, y) (x', y') + f x' y' := by simp only [map_add, add_apply, coe_deriv₂, add_assoc] end continuous_linear_map end semi_normed section normed variables [normed_group E] [normed_group F] [normed_group G] [normed_group Fₗ] open metric continuous_linear_map section normed_field variables [normed_field 𝕜] [normed_space 𝕜 E] [normed_space 𝕜 F] (f : E →ₗ[𝕜] F) lemma linear_map.continuous_iff_is_closed_ker {f : E →ₗ[𝕜] 𝕜} : continuous f ↔ is_closed (f.ker : set E) := begin -- the continuity of f obviously implies that its kernel is closed refine ⟨λh, (t1_space.t1 (0 : 𝕜)).preimage h, λh, _⟩, -- for the other direction, we assume that the kernel is closed by_cases hf : ∀x, x ∈ f.ker, { -- if `f = 0`, its continuity is obvious have : (f : E → 𝕜) = (λx, 0), by { ext x, simpa using hf x }, rw this, exact continuous_const }, { /- if `f` is not zero, we use an element `x₀ ∉ ker f` such that `∥x₀∥ ≤ 2 ∥x₀ - y∥` for all `y ∈ ker f`, given by Riesz's lemma, and prove that `2 ∥f x₀∥ / ∥x₀∥` gives a bound on the operator norm of `f`. For this, start from an arbitrary `x` and note that `y = x₀ - (f x₀ / f x) x` belongs to the kernel of `f`. Applying the above inequality to `x₀` and `y` readily gives the conclusion. -/ push_neg at hf, let r : ℝ := (2 : ℝ)⁻¹, have : 0 ≤ r, by norm_num [r], have : r < 1, by norm_num [r], obtain ⟨x₀, x₀ker, h₀⟩ : ∃ (x₀ : E), x₀ ∉ f.ker ∧ ∀ y ∈ linear_map.ker f, r * ∥x₀∥ ≤ ∥x₀ - y∥, from riesz_lemma h hf this, have : x₀ ≠ 0, { assume h, have : x₀ ∈ f.ker, by { rw h, exact (linear_map.ker f).zero_mem }, exact x₀ker this }, have rx₀_ne_zero : r * ∥x₀∥ ≠ 0, by { simp [norm_eq_zero, this], }, have : ∀x, ∥f x∥ ≤ (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥, { assume x, by_cases hx : f x = 0, { rw [hx, norm_zero], apply_rules [mul_nonneg, norm_nonneg, inv_nonneg.2] }, { let y := x₀ - (f x₀ * (f x)⁻¹ ) • x, have fy_zero : f y = 0, by calc f y = f x₀ - (f x₀ * (f x)⁻¹ ) * f x : by simp [y] ... = 0 : by { rw [mul_assoc, inv_mul_cancel hx, mul_one, sub_eq_zero_of_eq], refl }, have A : r * ∥x₀∥ ≤ ∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥, from calc r * ∥x₀∥ ≤ ∥x₀ - y∥ : h₀ _ (linear_map.mem_ker.2 fy_zero) ... = ∥(f x₀ * (f x)⁻¹ ) • x∥ : by { dsimp [y], congr, abel } ... = ∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥ : by rw [norm_smul, norm_mul, norm_inv], calc ∥f x∥ = (r * ∥x₀∥)⁻¹ * (r * ∥x₀∥) * ∥f x∥ : by rwa [inv_mul_cancel, one_mul] ... ≤ (r * ∥x₀∥)⁻¹ * (∥f x₀∥ * ∥f x∥⁻¹ * ∥x∥) * ∥f x∥ : begin apply mul_le_mul_of_nonneg_right (mul_le_mul_of_nonneg_left A _) (norm_nonneg _), exact inv_nonneg.2 (mul_nonneg (by norm_num) (norm_nonneg _)) end ... = (∥f x∥ ⁻¹ * ∥f x∥) * (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥ : by ring ... = (((r * ∥x₀∥)⁻¹) * ∥f x₀∥) * ∥x∥ : by { rw [inv_mul_cancel, one_mul], simp [norm_eq_zero, hx] } } }, exact linear_map.continuous_of_bound f _ this } end end normed_field section variables [nondiscrete_normed_field 𝕜] [nondiscrete_normed_field 𝕜₂] [nondiscrete_normed_field 𝕜₃] [normed_space 𝕜 E] [normed_space 𝕜₂ F] [normed_space 𝕜₃ G] [normed_space 𝕜 Fₗ] (c : 𝕜) {σ₁₂ : 𝕜 →+* 𝕜₂} {σ₂₃ : 𝕜₂ →+* 𝕜₃} (f g : E →SL[σ₁₂] F) (x y z : E) lemma linear_map.bound_of_shell [ring_hom_isometric σ₁₂] (f : E →ₛₗ[σ₁₂] F) {ε C : ℝ} (ε_pos : 0 < ε) {c : 𝕜} (hc : 1 < ∥c∥) (hf : ∀ x, ε / ∥c∥ ≤ ∥x∥ → ∥x∥ < ε → ∥f x∥ ≤ C * ∥x∥) (x : E) : ∥f x∥ ≤ C * ∥x∥ := begin by_cases hx : x = 0, { simp [hx] }, exact linear_map.bound_of_shell_semi_normed f ε_pos hc hf (ne_of_lt (norm_pos_iff.2 hx)).symm end /-- `linear_map.bound_of_ball_bound'` is a version of this lemma over a field satisfying `is_R_or_C` that produces a concrete bound. -/ lemma linear_map.bound_of_ball_bound {r : ℝ} (r_pos : 0 < r) (c : ℝ) (f : E →ₗ[𝕜] Fₗ) (h : ∀ z ∈ metric.ball (0 : E) r, ∥f z∥ ≤ c) : ∃ C, ∀ (z : E), ∥f z∥ ≤ C * ∥z∥ := begin cases @nondiscrete_normed_field.non_trivial 𝕜 _ with k hk, use c * (∥k∥ / r), intro z, refine linear_map.bound_of_shell _ r_pos hk (λ x hko hxo, _) _, calc ∥f x∥ ≤ c : h _ (mem_ball_zero_iff.mpr hxo) ... ≤ c * ((∥x∥ * ∥k∥) / r) : le_mul_of_one_le_right _ _ ... = _ : by ring, { exact le_trans (norm_nonneg _) (h 0 (by simp [r_pos])) }, { rw [div_le_iff (zero_lt_one.trans hk)] at hko, exact (one_le_div r_pos).mpr hko } end namespace continuous_linear_map section op_norm open set real /-- An operator is zero iff its norm vanishes. -/ theorem op_norm_zero_iff [ring_hom_isometric σ₁₂] : ∥f∥ = 0 ↔ f = 0 := iff.intro (λ hn, continuous_linear_map.ext (λ x, norm_le_zero_iff.1 (calc _ ≤ ∥f∥ * ∥x∥ : le_op_norm _ _ ... = _ : by rw [hn, zero_mul]))) (λ hf, le_antisymm (cInf_le bounds_bdd_below ⟨le_rfl, λ _, le_of_eq (by { rw [zero_mul, hf], exact norm_zero })⟩) (op_norm_nonneg _)) /-- If a normed space is non-trivial, then the norm of the identity equals `1`. -/ @[simp] lemma norm_id [nontrivial E] : ∥id 𝕜 E∥ = 1 := begin refine norm_id_of_nontrivial_seminorm _, obtain ⟨x, hx⟩ := exists_ne (0 : E), exact ⟨x, ne_of_gt (norm_pos_iff.2 hx)⟩, end instance norm_one_class [nontrivial E] : norm_one_class (E →L[𝕜] E) := ⟨norm_id⟩ /-- Continuous linear maps themselves form a normed space with respect to the operator norm. -/ instance to_normed_group [ring_hom_isometric σ₁₂] : normed_group (E →SL[σ₁₂] F) := normed_group.of_core _ ⟨λ f, op_norm_zero_iff f, op_norm_add_le, op_norm_neg⟩ /-- Continuous linear maps form a normed ring with respect to the operator norm. -/ instance to_normed_ring : normed_ring (E →L[𝕜] E) := { norm_mul := op_norm_comp_le, .. continuous_linear_map.to_normed_group } variable {f} lemma homothety_norm [ring_hom_isometric σ₁₂] [nontrivial E] (f : E →SL[σ₁₂] F) {a : ℝ} (hf : ∀x, ∥f x∥ = a * ∥x∥) : ∥f∥ = a := begin obtain ⟨x, hx⟩ : ∃ (x : E), x ≠ 0 := exists_ne 0, rw ← norm_pos_iff at hx, have ha : 0 ≤ a, by simpa only [hf, hx, zero_le_mul_right] using norm_nonneg (f x), apply le_antisymm (f.op_norm_le_bound ha (λ y, le_of_eq (hf y))), simpa only [hf, hx, mul_le_mul_right] using f.le_op_norm x, end lemma to_span_singleton_norm (x : E) : ∥to_span_singleton 𝕜 x∥ = ∥x∥ := homothety_norm _ (to_span_singleton_homothety 𝕜 x) variable (f) theorem uniform_embedding_of_bound {K : ℝ≥0} (hf : ∀ x, ∥x∥ ≤ K * ∥f x∥) : uniform_embedding f := (f.to_linear_map.antilipschitz_of_bound hf).uniform_embedding f.uniform_continuous /-- If a continuous linear map is a uniform embedding, then it is expands the distances by a positive factor.-/ theorem antilipschitz_of_uniform_embedding (f : E →L[𝕜] Fₗ) (hf : uniform_embedding f) : ∃ K, antilipschitz_with K f := begin obtain ⟨ε, εpos, hε⟩ : ∃ (ε : ℝ) (H : ε > 0), ∀ {x y : E}, dist (f x) (f y) < ε → dist x y < 1, from (uniform_embedding_iff.1 hf).2.2 1 zero_lt_one, let δ := ε/2, have δ_pos : δ > 0 := half_pos εpos, have H : ∀{x}, ∥f x∥ ≤ δ → ∥x∥ ≤ 1, { assume x hx, have : dist x 0 ≤ 1, { refine (hε _).le, rw [f.map_zero, dist_zero_right], exact hx.trans_lt (half_lt_self εpos) }, simpa using this }, rcases normed_field.exists_one_lt_norm 𝕜 with ⟨c, hc⟩, refine ⟨⟨δ⁻¹, _⟩ * ∥c∥₊, f.to_linear_map.antilipschitz_of_bound $ λx, _⟩, exact inv_nonneg.2 (le_of_lt δ_pos), by_cases hx : f x = 0, { have : f x = f 0, by { simp [hx] }, have : x = 0 := (uniform_embedding_iff.1 hf).1 this, simp [this] }, { rcases rescale_to_shell hc δ_pos hx with ⟨d, hd, dxlt, ledx, dinv⟩, rw [← f.map_smul d] at dxlt, have : ∥d • x∥ ≤ 1 := H dxlt.le, calc ∥x∥ = ∥d∥⁻¹ * ∥d • x∥ : by rwa [← norm_inv, ← norm_smul, ← mul_smul, inv_mul_cancel, one_smul] ... ≤ ∥d∥⁻¹ * 1 : mul_le_mul_of_nonneg_left this (inv_nonneg.2 (norm_nonneg _)) ... ≤ δ⁻¹ * ∥c∥ * ∥f x∥ : by rwa [mul_one] } end section completeness open_locale topological_space open filter variables {E' : Type*} [semi_normed_group E'] [normed_space 𝕜 E'] [ring_hom_isometric σ₁₂] /-- Construct a bundled continuous (semi)linear map from a map `f : E → F` and a proof of the fact that it belongs to the closure of the image of a bounded set `s : set (E →SL[σ₁₂] F)` under coercion to function. Coercion to function of the result is definitionally equal to `f`. -/ @[simps apply { fully_applied := ff }] def of_mem_closure_image_coe_bounded (f : E' → F) {s : set (E' →SL[σ₁₂] F)} (hs : bounded s) (hf : f ∈ closure ((coe_fn : (E' →SL[σ₁₂] F) → E' → F) '' s)) : E' →SL[σ₁₂] F := begin -- `f` is a linear map due to `linear_map_of_mem_closure_range_coe` refine (linear_map_of_mem_closure_range_coe f _).mk_continuous_of_exists_bound _, { refine closure_mono (image_subset_iff.2 $ λ g hg, _) hf, exact ⟨g, rfl⟩ }, { -- We need to show that `f` has bounded norm. Choose `C` such that `∥g∥ ≤ C` for all `g ∈ s`. rcases bounded_iff_forall_norm_le.1 hs with ⟨C, hC⟩, -- Then `∥g x∥ ≤ C * ∥x∥` for all `g ∈ s`, `x : E`, hence `∥f x∥ ≤ C * ∥x∥` for all `x`. have : ∀ x, is_closed {g : E' → F | ∥g x∥ ≤ C * ∥x∥}, from λ x, is_closed_Iic.preimage (@continuous_apply E' (λ _, F) _ x).norm, refine ⟨C, λ x, (this x).closure_subset_iff.2 (image_subset_iff.2 $ λ g hg, _) hf⟩, exact g.le_of_op_norm_le (hC _ hg) _ } end /-- Let `f : E → F` be a map, let `g : α → E →SL[σ₁₂] F` be a family of continuous (semi)linear maps that takes values in a bounded set and converges to `f` pointwise along a nontrivial filter. Then `f` is a continuous (semi)linear map. -/ @[simps apply { fully_applied := ff }] def of_tendsto_of_bounded_range {α : Type*} {l : filter α} [l.ne_bot] (f : E' → F) (g : α → E' →SL[σ₁₂] F) (hf : tendsto (λ a x, g a x) l (𝓝 f)) (hg : bounded (set.range g)) : E' →SL[σ₁₂] F := of_mem_closure_image_coe_bounded f hg $ mem_closure_of_tendsto hf $ eventually_of_forall $ λ a, mem_image_of_mem _ $ set.mem_range_self _ /-- If a Cauchy sequence of continuous linear map converges to a continuous linear map pointwise, then it converges to the same map in norm. This lemma is used to prove that the space of continuous linear maps is complete provided that the codomain is a complete space. -/ lemma tendsto_of_tendsto_pointwise_of_cauchy_seq {f : ℕ → E' →SL[σ₁₂] F} {g : E' →SL[σ₁₂] F} (hg : tendsto (λ n x, f n x) at_top (𝓝 g)) (hf : cauchy_seq f) : tendsto f at_top (𝓝 g) := begin /- Since `f` is a Cauchy sequence, there exists `b → 0` such that `∥f n - f m∥ ≤ b N` for any `m, n ≥ N`. -/ rcases cauchy_seq_iff_le_tendsto_0.1 hf with ⟨b, hb₀, hfb, hb_lim⟩, -- Since `b → 0`, it suffices to show that `∥f n x - g x∥ ≤ b n * ∥x∥` for all `n` and `x`. suffices : ∀ n x, ∥f n x - g x∥ ≤ b n * ∥x∥, from tendsto_iff_norm_tendsto_zero.2 (squeeze_zero (λ n, norm_nonneg _) (λ n, op_norm_le_bound _ (hb₀ n) (this n)) hb_lim), intros n x, -- Note that `f m x → g x`, hence `∥f n x - f m x∥ → ∥f n x - g x∥` as `m → ∞` have : tendsto (λ m, ∥f n x - f m x∥) at_top (𝓝 (∥f n x - g x∥)), from (tendsto_const_nhds.sub $ tendsto_pi_nhds.1 hg _).norm, -- Thus it suffices to verify `∥f n x - f m x∥ ≤ b n * ∥x∥` for `m ≥ n`. refine le_of_tendsto this (eventually_at_top.2 ⟨n, λ m hm, _⟩), -- This inequality follows from `∥f n - f m∥ ≤ b n`. exact (f n - f m).le_of_op_norm_le (hfb _ _ _ le_rfl hm) _ end /-- If the target space is complete, the space of continuous linear maps with its norm is also complete. This works also if the source space is seminormed. -/ instance [complete_space F] : complete_space (E' →SL[σ₁₂] F) := begin -- We show that every Cauchy sequence converges. refine metric.complete_of_cauchy_seq_tendsto (λ f hf, _), -- The evaluation at any point `v : E` is Cauchy. have cau : ∀ v, cauchy_seq (λ n, f n v), from λ v, hf.map (lipschitz_apply v).uniform_continuous, -- We assemble the limits points of those Cauchy sequences -- (which exist as `F` is complete) -- into a function which we call `G`. choose G hG using λv, cauchy_seq_tendsto_of_complete (cau v), -- Next, we show that this `G` is a continuous linear map. -- This is done in `continuous_linear_map.of_tendsto_of_bounded_range`. set Glin : E' →SL[σ₁₂] F := of_tendsto_of_bounded_range _ _ (tendsto_pi_nhds.mpr hG) hf.bounded_range, -- Finally, `f n` converges to `Glin` in norm because of -- `continuous_linear_map.tendsto_of_tendsto_pointwise_of_cauchy_seq` exact ⟨Glin, tendsto_of_tendsto_pointwise_of_cauchy_seq (tendsto_pi_nhds.2 hG) hf⟩ end /-- Let `s` be a bounded set in the space of continuous (semi)linear maps `E →SL[σ] F` taking values in a proper space. Then `s` interpreted as a set in the space of maps `E → F` with topology of pointwise convergence is precompact: its closure is a compact set. -/ lemma is_compact_closure_image_coe_of_bounded [proper_space F] {s : set (E' →SL[σ₁₂] F)} (hb : bounded s) : is_compact (closure ((coe_fn : (E' →SL[σ₁₂] F) → E' → F) '' s)) := have ∀ x, is_compact (closure (apply' F σ₁₂ x '' s)), from λ x, ((apply' F σ₁₂ x).lipschitz.bounded_image hb).is_compact_closure, compact_closure_of_subset_compact (is_compact_pi_infinite this) (image_subset_iff.2 $ λ g hg x, subset_closure $ mem_image_of_mem _ hg) /-- Let `s` be a bounded set in the space of continuous (semi)linear maps `E →SL[σ] F` taking values in a proper space. If `s` interpreted as a set in the space of maps `E → F` with topology of pointwise convergence is closed, then it is compact. TODO: reformulate this in terms of a type synonym with the right topology. -/ lemma is_compact_image_coe_of_bounded_of_closed_image [proper_space F] {s : set (E' →SL[σ₁₂] F)} (hb : bounded s) (hc : is_closed ((coe_fn : (E' →SL[σ₁₂] F) → E' → F) '' s)) : is_compact ((coe_fn : (E' →SL[σ₁₂] F) → E' → F) '' s) := hc.closure_eq ▸ is_compact_closure_image_coe_of_bounded hb /-- If a set `s` of semilinear functions is bounded and is closed in the weak-* topology, then its image under coercion to functions `E → F` is a closed set. We don't have a name for `E →SL[σ] F` with weak-* topology in `mathlib`, so we use an equivalent condition (see `is_closed_induced_iff'`). TODO: reformulate this in terms of a type synonym with the right topology. -/ lemma is_closed_image_coe_of_bounded_of_weak_closed {s : set (E' →SL[σ₁₂] F)} (hb : bounded s) (hc : ∀ f, (⇑f : E' → F) ∈ closure ((coe_fn : (E' →SL[σ₁₂] F) → E' → F) '' s) → f ∈ s) : is_closed ((coe_fn : (E' →SL[σ₁₂] F) → E' → F) '' s) := is_closed_of_closure_subset $ λ f hf, ⟨of_mem_closure_image_coe_bounded f hb hf, hc (of_mem_closure_image_coe_bounded f hb hf) hf, rfl⟩ /-- If a set `s` of semilinear functions is bounded and is closed in the weak-* topology, then its image under coercion to functions `E → F` is a compact set. We don't have a name for `E →SL[σ] F` with weak-* topology in `mathlib`, so we use an equivalent condition (see `is_closed_induced_iff'`). -/ lemma is_compact_image_coe_of_bounded_of_weak_closed [proper_space F] {s : set (E' →SL[σ₁₂] F)} (hb : bounded s) (hc : ∀ f, (⇑f : E' → F) ∈ closure ((coe_fn : (E' →SL[σ₁₂] F) → E' → F) '' s) → f ∈ s) : is_compact ((coe_fn : (E' →SL[σ₁₂] F) → E' → F) '' s) := is_compact_image_coe_of_bounded_of_closed_image hb $ is_closed_image_coe_of_bounded_of_weak_closed hb hc /-- A closed ball is closed in the weak-* topology. We don't have a name for `E →SL[σ] F` with weak-* topology in `mathlib`, so we use an equivalent condition (see `is_closed_induced_iff'`). -/ lemma is_weak_closed_closed_ball (f₀ : E' →SL[σ₁₂] F) (r : ℝ) ⦃f : E' →SL[σ₁₂] F⦄ (hf : ⇑f ∈ closure ((coe_fn : (E' →SL[σ₁₂] F) → E' → F) '' (closed_ball f₀ r))) : f ∈ closed_ball f₀ r := begin have hr : 0 ≤ r, from nonempty_closed_ball.1 (nonempty_image_iff.1 (closure_nonempty_iff.1 ⟨_, hf⟩)), refine mem_closed_ball_iff_norm.2 (op_norm_le_bound _ hr $ λ x, _), have : is_closed {g : E' → F | ∥g x - f₀ x∥ ≤ r * ∥x∥}, from is_closed_Iic.preimage ((@continuous_apply E' (λ _, F) _ x).sub continuous_const).norm, refine this.closure_subset_iff.2 (image_subset_iff.2 $ λ g hg, _) hf, exact (g - f₀).le_of_op_norm_le (mem_closed_ball_iff_norm.1 hg) _ end /-- The set of functions `f : E → F` that represent continuous linear maps `f : E →SL[σ₁₂] F` at distance `≤ r` from `f₀ : E →SL[σ₁₂] F` is closed in the topology of pointwise convergence. This is one of the key steps in the proof of the **Banach-Alaoglu** theorem. -/ lemma is_closed_image_coe_closed_ball (f₀ : E →SL[σ₁₂] F) (r : ℝ) : is_closed ((coe_fn : (E →SL[σ₁₂] F) → E → F) '' closed_ball f₀ r) := is_closed_image_coe_of_bounded_of_weak_closed bounded_closed_ball (is_weak_closed_closed_ball f₀ r) /-- **Banach-Alaoglu** theorem. The set of functions `f : E → F` that represent continuous linear maps `f : E →SL[σ₁₂] F` at distance `≤ r` from `f₀ : E →SL[σ₁₂] F` is compact in the topology of pointwise convergence. Other versions of this theorem can be found in `analysis.normed_space.weak_dual`. -/ lemma is_compact_image_coe_closed_ball [proper_space F] (f₀ : E →SL[σ₁₂] F) (r : ℝ) : is_compact ((coe_fn : (E →SL[σ₁₂] F) → E → F) '' closed_ball f₀ r) := is_compact_image_coe_of_bounded_of_weak_closed bounded_closed_ball $ is_weak_closed_closed_ball f₀ r end completeness section uniformly_extend variables [complete_space F] (e : E →L[𝕜] Fₗ) (h_dense : dense_range e) section variables (h_e : uniform_inducing e) /-- Extension of a continuous linear map `f : E →SL[σ₁₂] F`, with `E` a normed space and `F` a complete normed space, along a uniform and dense embedding `e : E →L[𝕜] Fₗ`. -/ def extend : Fₗ →SL[σ₁₂] F := /- extension of `f` is continuous -/ have cont : _ := (uniform_continuous_uniformly_extend h_e h_dense f.uniform_continuous).continuous, /- extension of `f` agrees with `f` on the domain of the embedding `e` -/ have eq : _ := uniformly_extend_of_ind h_e h_dense f.uniform_continuous, { to_fun := (h_e.dense_inducing h_dense).extend f, map_add' := begin refine h_dense.induction_on₂ _ _, { exact is_closed_eq (cont.comp continuous_add) ((cont.comp continuous_fst).add (cont.comp continuous_snd)) }, { assume x y, simp only [eq, ← e.map_add], exact f.map_add _ _ }, end, map_smul' := λk, begin refine (λ b, h_dense.induction_on b _ _), { exact is_closed_eq (cont.comp (continuous_const_smul _)) ((continuous_const_smul _).comp cont) }, { assume x, rw ← map_smul, simp only [eq], exact map_smulₛₗ _ _ _ }, end, cont := cont } lemma extend_unique (g : Fₗ →SL[σ₁₂] F) (H : g.comp e = f) : extend f e h_dense h_e = g := continuous_linear_map.coe_fn_injective $ uniformly_extend_unique h_e h_dense (continuous_linear_map.ext_iff.1 H) g.continuous @[simp] lemma extend_zero : extend (0 : E →SL[σ₁₂] F) e h_dense h_e = 0 := extend_unique _ _ _ _ _ (zero_comp _) end section variables {N : ℝ≥0} (h_e : ∀x, ∥x∥ ≤ N * ∥e x∥) [ring_hom_isometric σ₁₂] local notation `ψ` := f.extend e h_dense (uniform_embedding_of_bound _ h_e).to_uniform_inducing /-- If a dense embedding `e : E →L[𝕜] G` expands the norm by a constant factor `N⁻¹`, then the norm of the extension of `f` along `e` is bounded by `N * ∥f∥`. -/ lemma op_norm_extend_le : ∥ψ∥ ≤ N * ∥f∥ := begin have uni : uniform_inducing e := (uniform_embedding_of_bound _ h_e).to_uniform_inducing, have eq : ∀x, ψ (e x) = f x := uniformly_extend_of_ind uni h_dense f.uniform_continuous, by_cases N0 : 0 ≤ N, { refine op_norm_le_bound ψ _ (is_closed_property h_dense (is_closed_le _ _) _), { exact mul_nonneg N0 (norm_nonneg _) }, { exact continuous_norm.comp (cont ψ) }, { exact continuous_const.mul continuous_norm }, { assume x, rw eq, calc ∥f x∥ ≤ ∥f∥ * ∥x∥ : le_op_norm _ _ ... ≤ ∥f∥ * (N * ∥e x∥) : mul_le_mul_of_nonneg_left (h_e x) (norm_nonneg _) ... ≤ N * ∥f∥ * ∥e x∥ : by rw [mul_comm ↑N ∥f∥, mul_assoc] } }, { have he : ∀ x : E, x = 0, { assume x, have N0 : N ≤ 0 := le_of_lt (lt_of_not_ge N0), rw ← norm_le_zero_iff, exact le_trans (h_e x) (mul_nonpos_of_nonpos_of_nonneg N0 (norm_nonneg _)) }, have hf : f = 0, { ext, simp only [he x, zero_apply, map_zero] }, have hψ : ψ = 0, { rw hf, apply extend_zero }, rw [hψ, hf, norm_zero, norm_zero, mul_zero] } end end end uniformly_extend end op_norm end continuous_linear_map namespace linear_isometry @[simp] lemma norm_to_continuous_linear_map [nontrivial E] [ring_hom_isometric σ₁₂] (f : E →ₛₗᵢ[σ₁₂] F) : ∥f.to_continuous_linear_map∥ = 1 := f.to_continuous_linear_map.homothety_norm $ by simp variables {σ₁₃ : 𝕜 →+* 𝕜₃} [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] include σ₁₃ /-- Postcomposition of a continuous linear map with a linear isometry preserves the operator norm. -/ lemma norm_to_continuous_linear_map_comp [ring_hom_isometric σ₁₂] (f : F →ₛₗᵢ[σ₂₃] G) {g : E →SL[σ₁₂] F} : ∥f.to_continuous_linear_map.comp g∥ = ∥g∥ := op_norm_ext (f.to_continuous_linear_map.comp g) g (λ x, by simp only [norm_map, coe_to_continuous_linear_map, coe_comp']) omit σ₁₃ end linear_isometry end namespace continuous_linear_map variables [nondiscrete_normed_field 𝕜] [nondiscrete_normed_field 𝕜₂] [nondiscrete_normed_field 𝕜₃] [normed_space 𝕜 E] [normed_space 𝕜₂ F] [normed_space 𝕜₃ G] [normed_space 𝕜 Fₗ] (c : 𝕜) {σ₁₂ : 𝕜 →+* 𝕜₂} {σ₂₃ : 𝕜₂ →+* 𝕜₃} variables {𝕜₂' : Type*} [nondiscrete_normed_field 𝕜₂'] {F' : Type*} [normed_group F'] [normed_space 𝕜₂' F'] {σ₂' : 𝕜₂' →+* 𝕜₂} {σ₂'' : 𝕜₂ →+* 𝕜₂'} {σ₂₃' : 𝕜₂' →+* 𝕜₃} [ring_hom_inv_pair σ₂' σ₂''] [ring_hom_inv_pair σ₂'' σ₂'] [ring_hom_comp_triple σ₂' σ₂₃ σ₂₃'] [ring_hom_comp_triple σ₂'' σ₂₃' σ₂₃] [ring_hom_isometric σ₂₃] [ring_hom_isometric σ₂'] [ring_hom_isometric σ₂''] [ring_hom_isometric σ₂₃'] include σ₂'' σ₂₃' /-- Precomposition with a linear isometry preserves the operator norm. -/ lemma op_norm_comp_linear_isometry_equiv (f : F →SL[σ₂₃] G) (g : F' ≃ₛₗᵢ[σ₂'] F) : ∥f.comp g.to_linear_isometry.to_continuous_linear_map∥ = ∥f∥ := begin casesI subsingleton_or_nontrivial F', { haveI := g.symm.to_linear_equiv.to_equiv.subsingleton, simp }, refine le_antisymm _ _, { convert f.op_norm_comp_le g.to_linear_isometry.to_continuous_linear_map, simp [g.to_linear_isometry.norm_to_continuous_linear_map] }, { convert (f.comp g.to_linear_isometry.to_continuous_linear_map).op_norm_comp_le g.symm.to_linear_isometry.to_continuous_linear_map, { ext, simp }, haveI := g.symm.surjective.nontrivial, simp [g.symm.to_linear_isometry.norm_to_continuous_linear_map] }, end omit σ₂'' σ₂₃' /-- The norm of the tensor product of a scalar linear map and of an element of a normed space is the product of the norms. -/ @[simp] lemma norm_smul_right_apply (c : E →L[𝕜] 𝕜) (f : Fₗ) : ∥smul_right c f∥ = ∥c∥ * ∥f∥ := begin refine le_antisymm _ _, { apply op_norm_le_bound _ (mul_nonneg (norm_nonneg _) (norm_nonneg _)) (λx, _), calc ∥(c x) • f∥ = ∥c x∥ * ∥f∥ : norm_smul _ _ ... ≤ (∥c∥ * ∥x∥) * ∥f∥ : mul_le_mul_of_nonneg_right (le_op_norm _ _) (norm_nonneg _) ... = ∥c∥ * ∥f∥ * ∥x∥ : by ring }, { by_cases h : f = 0, { simp [h] }, { have : 0 < ∥f∥ := norm_pos_iff.2 h, rw ← le_div_iff this, apply op_norm_le_bound _ (div_nonneg (norm_nonneg _) (norm_nonneg f)) (λx, _), rw [div_mul_eq_mul_div, le_div_iff this], calc ∥c x∥ * ∥f∥ = ∥c x • f∥ : (norm_smul _ _).symm ... = ∥smul_right c f x∥ : rfl ... ≤ ∥smul_right c f∥ * ∥x∥ : le_op_norm _ _ } }, end /-- The non-negative norm of the tensor product of a scalar linear map and of an element of a normed space is the product of the non-negative norms. -/ @[simp] lemma nnnorm_smul_right_apply (c : E →L[𝕜] 𝕜) (f : Fₗ) : ∥smul_right c f∥₊ = ∥c∥₊ * ∥f∥₊ := nnreal.eq $ c.norm_smul_right_apply f variables (𝕜 E Fₗ) /-- `continuous_linear_map.smul_right` as a continuous trilinear map: `smul_rightL (c : E →L[𝕜] 𝕜) (f : F) (x : E) = c x • f`. -/ def smul_rightL : (E →L[𝕜] 𝕜) →L[𝕜] Fₗ →L[𝕜] E →L[𝕜] Fₗ := linear_map.mk_continuous₂ { to_fun := smul_rightₗ, map_add' := λ c₁ c₂, by { ext x, simp only [add_smul, coe_smul_rightₗ, add_apply, smul_right_apply, linear_map.add_apply] }, map_smul' := λ m c, by { ext x, simp only [smul_smul, coe_smul_rightₗ, algebra.id.smul_eq_mul, coe_smul', smul_right_apply, linear_map.smul_apply, ring_hom.id_apply, pi.smul_apply] } } 1 $ λ c x, by simp only [coe_smul_rightₗ, one_mul, norm_smul_right_apply, linear_map.coe_mk] variables {𝕜 E Fₗ} @[simp] lemma norm_smul_rightL_apply (c : E →L[𝕜] 𝕜) (f : Fₗ) : ∥smul_rightL 𝕜 E Fₗ c f∥ = ∥c∥ * ∥f∥ := norm_smul_right_apply c f @[simp] lemma norm_smul_rightL (c : E →L[𝕜] 𝕜) [nontrivial Fₗ] : ∥smul_rightL 𝕜 E Fₗ c∥ = ∥c∥ := continuous_linear_map.homothety_norm _ c.norm_smul_right_apply variables (𝕜) (𝕜' : Type*) section variables [normed_ring 𝕜'] [normed_algebra 𝕜 𝕜'] @[simp] lemma op_norm_lmul [norm_one_class 𝕜'] : ∥lmul 𝕜 𝕜'∥ = 1 := by haveI := norm_one_class.nontrivial 𝕜'; exact (lmulₗᵢ 𝕜 𝕜').norm_to_continuous_linear_map @[simp] lemma op_norm_lmul_right [norm_one_class 𝕜'] : ∥lmul_right 𝕜 𝕜'∥ = 1 := (op_norm_flip (@lmul 𝕜 _ 𝕜' _ _)).trans (op_norm_lmul _ _) end /-- The norm of `lsmul` equals 1 in any nontrivial normed group. This is `continuous_linear_map.op_norm_lsmul_le` as an equality. -/ @[simp] lemma op_norm_lsmul [normed_field 𝕜'] [normed_algebra 𝕜 𝕜'] [normed_space 𝕜' E] [is_scalar_tower 𝕜 𝕜' E] [nontrivial E] : ∥(lsmul 𝕜 𝕜' : 𝕜' →L[𝕜] E →L[𝕜] E)∥ = 1 := begin refine continuous_linear_map.op_norm_eq_of_bounds zero_le_one (λ x, _) (λ N hN h, _), { rw one_mul, exact op_norm_lsmul_apply_le _, }, obtain ⟨y, hy⟩ := exists_ne (0 : E), have := le_of_op_norm_le _ (h 1) y, simp_rw [lsmul_apply, one_smul, norm_one, mul_one] at this, refine le_of_mul_le_mul_right _ (norm_pos_iff.mpr hy), simp_rw [one_mul, this] end end continuous_linear_map namespace submodule variables [nondiscrete_normed_field 𝕜] [nondiscrete_normed_field 𝕜₂] [nondiscrete_normed_field 𝕜₃] [normed_space 𝕜 E] [normed_space 𝕜₂ F] {σ₁₂ : 𝕜 →+* 𝕜₂} lemma norm_subtypeL (K : submodule 𝕜 E) [nontrivial K] : ∥K.subtypeL∥ = 1 := K.subtypeₗᵢ.norm_to_continuous_linear_map end submodule namespace continuous_linear_equiv variables [nondiscrete_normed_field 𝕜] [nondiscrete_normed_field 𝕜₂] [nondiscrete_normed_field 𝕜₃] [normed_space 𝕜 E] [normed_space 𝕜₂ F] {σ₁₂ : 𝕜 →+* 𝕜₂} {σ₂₁ : 𝕜₂ →+* 𝕜} [ring_hom_inv_pair σ₁₂ σ₂₁] [ring_hom_inv_pair σ₂₁ σ₁₂] section variables [ring_hom_isometric σ₂₁] protected lemma antilipschitz (e : E ≃SL[σ₁₂] F) : antilipschitz_with ∥(e.symm : F →SL[σ₂₁] E)∥₊ e := e.symm.lipschitz.to_right_inverse e.left_inv lemma one_le_norm_mul_norm_symm [ring_hom_isometric σ₁₂] [nontrivial E] (e : E ≃SL[σ₁₂] F) : 1 ≤ ∥(e : E →SL[σ₁₂] F)∥ * ∥(e.symm : F →SL[σ₂₁] E)∥ := begin rw [mul_comm], convert (e.symm : F →SL[σ₂₁] E).op_norm_comp_le (e : E →SL[σ₁₂] F), rw [e.coe_symm_comp_coe, continuous_linear_map.norm_id] end include σ₂₁ lemma norm_pos [ring_hom_isometric σ₁₂] [nontrivial E] (e : E ≃SL[σ₁₂] F) : 0 < ∥(e : E →SL[σ₁₂] F)∥ := pos_of_mul_pos_right (lt_of_lt_of_le zero_lt_one e.one_le_norm_mul_norm_symm) (norm_nonneg _) omit σ₂₁ lemma norm_symm_pos [ring_hom_isometric σ₁₂] [nontrivial E] (e : E ≃SL[σ₁₂] F) : 0 < ∥(e.symm : F →SL[σ₂₁] E)∥ := pos_of_mul_pos_left (lt_of_lt_of_le zero_lt_one e.one_le_norm_mul_norm_symm) (norm_nonneg _) lemma nnnorm_symm_pos [ring_hom_isometric σ₁₂] [nontrivial E] (e : E ≃SL[σ₁₂] F) : 0 < ∥(e.symm : F →SL[σ₂₁] E)∥₊ := e.norm_symm_pos lemma subsingleton_or_norm_symm_pos [ring_hom_isometric σ₁₂] (e : E ≃SL[σ₁₂] F) : subsingleton E ∨ 0 < ∥(e.symm : F →SL[σ₂₁] E)∥ := begin rcases subsingleton_or_nontrivial E with _i|_i; resetI, { left, apply_instance }, { right, exact e.norm_symm_pos } end lemma subsingleton_or_nnnorm_symm_pos [ring_hom_isometric σ₁₂] (e : E ≃SL[σ₁₂] F) : subsingleton E ∨ 0 < ∥(e.symm : F →SL[σ₂₁] E)∥₊ := subsingleton_or_norm_symm_pos e variable (𝕜) /-- Given a nonzero element `x` of a normed space `E₁` over a field `𝕜`, the natural continuous linear equivalence from `E₁` to the span of `x`.-/ def to_span_nonzero_singleton (x : E) (h : x ≠ 0) : 𝕜 ≃L[𝕜] (𝕜 ∙ x) := of_homothety (linear_equiv.to_span_nonzero_singleton 𝕜 E x h) ∥x∥ (norm_pos_iff.mpr h) (to_span_nonzero_singleton_homothety 𝕜 x h) /-- Given a nonzero element `x` of a normed space `E₁` over a field `𝕜`, the natural continuous linear map from the span of `x` to `𝕜`.-/ def coord (x : E) (h : x ≠ 0) : (𝕜 ∙ x) →L[𝕜] 𝕜 := (to_span_nonzero_singleton 𝕜 x h).symm @[simp] lemma coe_to_span_nonzero_singleton_symm {x : E} (h : x ≠ 0) : ⇑(to_span_nonzero_singleton 𝕜 x h).symm = coord 𝕜 x h := rfl @[simp] lemma coord_to_span_nonzero_singleton {x : E} (h : x ≠ 0) (c : 𝕜) : coord 𝕜 x h (to_span_nonzero_singleton 𝕜 x h c) = c := (to_span_nonzero_singleton 𝕜 x h).symm_apply_apply c @[simp] lemma to_span_nonzero_singleton_coord {x : E} (h : x ≠ 0) (y : 𝕜 ∙ x) : to_span_nonzero_singleton 𝕜 x h (coord 𝕜 x h y) = y := (to_span_nonzero_singleton 𝕜 x h).apply_symm_apply y @[simp] lemma coord_norm (x : E) (h : x ≠ 0) : ∥coord 𝕜 x h∥ = ∥x∥⁻¹ := begin have hx : 0 < ∥x∥ := (norm_pos_iff.mpr h), haveI : nontrivial (𝕜 ∙ x) := submodule.nontrivial_span_singleton h, exact continuous_linear_map.homothety_norm _ (λ y, homothety_inverse _ hx _ (to_span_nonzero_singleton_homothety 𝕜 x h) _) end @[simp] lemma coord_self (x : E) (h : x ≠ 0) : (coord 𝕜 x h) (⟨x, submodule.mem_span_singleton_self x⟩ : 𝕜 ∙ x) = 1 := linear_equiv.coord_self 𝕜 E x h variables {𝕜} {𝕜₄ : Type*} [nondiscrete_normed_field 𝕜₄] variables {H : Type*} [normed_group H] [normed_space 𝕜₄ H] [normed_space 𝕜₃ G] variables {σ₂₃ : 𝕜₂ →+* 𝕜₃} {σ₁₃ : 𝕜 →+* 𝕜₃} variables {σ₃₄ : 𝕜₃ →+* 𝕜₄} {σ₄₃ : 𝕜₄ →+* 𝕜₃} variables {σ₂₄ : 𝕜₂ →+* 𝕜₄} {σ₁₄ : 𝕜 →+* 𝕜₄} variables [ring_hom_inv_pair σ₃₄ σ₄₃] [ring_hom_inv_pair σ₄₃ σ₃₄] variables [ring_hom_comp_triple σ₂₁ σ₁₄ σ₂₄] [ring_hom_comp_triple σ₂₄ σ₄₃ σ₂₃] variables [ring_hom_comp_triple σ₁₂ σ₂₃ σ₁₃] [ring_hom_comp_triple σ₁₃ σ₃₄ σ₁₄] variables [ring_hom_isometric σ₁₄] [ring_hom_isometric σ₂₃] variables [ring_hom_isometric σ₄₃] [ring_hom_isometric σ₂₄] variables [ring_hom_isometric σ₁₃] [ring_hom_isometric σ₁₂] variables [ring_hom_isometric σ₃₄] include σ₂₁ σ₃₄ σ₁₃ σ₂₄ /-- A pair of continuous (semi)linear equivalences generates an continuous (semi)linear equivalence between the spaces of continuous (semi)linear maps. -/ def arrow_congrSL (e₁₂ : E ≃SL[σ₁₂] F) (e₄₃ : H ≃SL[σ₄₃] G) : (E →SL[σ₁₄] H) ≃SL[σ₄₃] (F →SL[σ₂₃] G) := { map_add' := λ f g, by simp only [equiv.to_fun_as_coe, add_comp, comp_add, continuous_linear_equiv.arrow_congr_equiv_apply], map_smul' := λ t f, by simp only [equiv.to_fun_as_coe, smul_comp, comp_smulₛₗ, continuous_linear_equiv.arrow_congr_equiv_apply], continuous_to_fun := (compSL F H G σ₂₄ σ₄₃ e₄₃).continuous.comp (continuous_linear_map.flip (compSL F E H σ₂₁ σ₁₄) e₁₂.symm).continuous, continuous_inv_fun := (compSL E G H σ₁₃ σ₃₄ e₄₃.symm).continuous.comp (continuous_linear_map.flip (compSL E F G σ₁₂ σ₂₃) e₁₂).continuous, .. e₁₂.arrow_congr_equiv e₄₃, } omit σ₂₁ σ₃₄ σ₁₃ σ₂₄ /-- A pair of continuous linear equivalences generates an continuous linear equivalence between the spaces of continuous linear maps. -/ def arrow_congr {F H : Type*} [normed_group F] [normed_group H] [normed_space 𝕜 F] [normed_space 𝕜 G] [normed_space 𝕜 H] (e₁ : E ≃L[𝕜] F) (e₂ : H ≃L[𝕜] G) : (E →L[𝕜] H) ≃L[𝕜] (F →L[𝕜] G) := arrow_congrSL e₁ e₂ end end continuous_linear_equiv end normed /-- A bounded bilinear form `B` in a real normed space is *coercive* if there is some positive constant C such that `C * ∥u∥ * ∥u∥ ≤ B u u`. -/ def is_coercive [normed_group E] [normed_space ℝ E] (B : E →L[ℝ] E →L[ℝ] ℝ) : Prop := ∃ C, (0 < C) ∧ ∀ u, C * ∥u∥ * ∥u∥ ≤ B u u
a748e3b1858dca5032776e901131b5f14faed16e
d406927ab5617694ec9ea7001f101b7c9e3d9702
/src/topology/basic.lean
12f0028be14377cb5031ba83f3779e464917747b
[ "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
73,446
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, Jeremy Avigad -/ import order.filter.ultrafilter import order.filter.partial import algebra.support import order.filter.lift /-! # Basic theory of topological spaces. The main definition is the type class `topological space α` which endows a type `α` with a topology. Then `set α` gets predicates `is_open`, `is_closed` and functions `interior`, `closure` and `frontier`. Each point `x` of `α` gets a neighborhood filter `𝓝 x`. A filter `F` on `α` has `x` as a cluster point if `cluster_pt x F : 𝓝 x ⊓ F ≠ ⊥`. A map `f : ι → α` clusters at `x` along `F : filter ι` if `map_cluster_pt x F f : cluster_pt x (map f F)`. In particular the notion of cluster point of a sequence `u` is `map_cluster_pt x at_top u`. For topological spaces `α` and `β`, a function `f : α → β` and a point `a : α`, `continuous_at f a` means `f` is continuous at `a`, and global continuity is `continuous f`. There is also a version of continuity `pcontinuous` for partially defined functions. ## Notation * `𝓝 x`: the filter `nhds x` of neighborhoods of a point `x`; * `𝓟 s`: the principal filter of a set `s`; * `𝓝[s] x`: the filter `nhds_within x s` of neighborhoods of a point `x` within a set `s`; * `𝓝[≤] x`: the filter `nhds_within x (set.Iic x)` of left-neighborhoods of `x`; * `𝓝[≥] x`: the filter `nhds_within x (set.Ici x)` of right-neighborhoods of `x`; * `𝓝[<] x`: the filter `nhds_within x (set.Iio x)` of punctured left-neighborhoods of `x`; * `𝓝[>] x`: the filter `nhds_within x (set.Ioi x)` of punctured right-neighborhoods of `x`; * `𝓝[≠] x`: the filter `nhds_within x {x}ᶜ` of punctured neighborhoods of `x`. ## Implementation notes Topology in mathlib heavily uses filters (even more than in Bourbaki). See explanations in <https://leanprover-community.github.io/theories/topology.html>. ## References * [N. Bourbaki, *General Topology*][bourbaki1966] * [I. M. James, *Topologies and Uniformities*][james1999] ## Tags topological space, interior, closure, frontier, neighborhood, continuity, continuous function -/ noncomputable theory open set filter classical open_locale classical filter universes u v w /-! ### Topological spaces -/ /-- A topology on `α`. -/ @[protect_proj] structure topological_space (α : Type u) := (is_open : set α → Prop) (is_open_univ : is_open univ) (is_open_inter : ∀s t, is_open s → is_open t → is_open (s ∩ t)) (is_open_sUnion : ∀s, (∀t∈s, is_open t) → is_open (⋃₀ s)) attribute [class] topological_space /-- A constructor for topologies by specifying the closed sets, and showing that they satisfy the appropriate conditions. -/ def topological_space.of_closed {α : Type u} (T : set (set α)) (empty_mem : ∅ ∈ T) (sInter_mem : ∀ A ⊆ T, ⋂₀ A ∈ T) (union_mem : ∀ A B ∈ T, A ∪ B ∈ T) : topological_space α := { is_open := λ X, Xᶜ ∈ T, is_open_univ := by simp [empty_mem], is_open_inter := λ s t hs ht, by simpa only [compl_inter] using union_mem sᶜ hs tᶜ ht, is_open_sUnion := λ s hs, by rw set.compl_sUnion; exact sInter_mem (compl '' s) (λ z ⟨y, hy, hz⟩, by simpa [hz.symm] using hs y hy) } section topological_space variables {α : Type u} {β : Type v} {ι : Sort w} {a : α} {s s₁ s₂ t : set α} {p p₁ p₂ : α → Prop} @[ext] lemma topological_space_eq : ∀ {f g : topological_space α}, f.is_open = g.is_open → f = g | ⟨a, _, _, _⟩ ⟨b, _, _, _⟩ rfl := rfl section variables [topological_space α] /-- `is_open s` means that `s` is open in the ambient topological space on `α` -/ def is_open (s : set α) : Prop := topological_space.is_open ‹_› s @[simp] lemma is_open_univ : is_open (univ : set α) := topological_space.is_open_univ _ lemma is_open.inter (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∩ s₂) := topological_space.is_open_inter _ s₁ s₂ h₁ h₂ lemma is_open_sUnion {s : set (set α)} (h : ∀t ∈ s, is_open t) : is_open (⋃₀ s) := topological_space.is_open_sUnion _ s h end lemma topological_space_eq_iff {t t' : topological_space α} : t = t' ↔ ∀ s, @is_open α t s ↔ @is_open α t' s := ⟨λ h s, h ▸ iff.rfl, λ h, by { ext, exact h _ }⟩ lemma is_open_fold {s : set α} {t : topological_space α} : t.is_open s = @is_open α t s := rfl variables [topological_space α] lemma is_open_Union {f : ι → set α} (h : ∀i, is_open (f i)) : is_open (⋃i, f i) := is_open_sUnion $ by rintro _ ⟨i, rfl⟩; exact h i lemma is_open_bUnion {s : set β} {f : β → set α} (h : ∀i∈s, is_open (f i)) : is_open (⋃i∈s, f i) := is_open_Union $ assume i, is_open_Union $ assume hi, h i hi lemma is_open.union (h₁ : is_open s₁) (h₂ : is_open s₂) : is_open (s₁ ∪ s₂) := by rw union_eq_Union; exact is_open_Union (bool.forall_bool.2 ⟨h₂, h₁⟩) @[simp] lemma is_open_empty : is_open (∅ : set α) := by rw ← sUnion_empty; exact is_open_sUnion (assume a, false.elim) lemma is_open_sInter {s : set (set α)} (hs : s.finite) : (∀t ∈ s, is_open t) → is_open (⋂₀ s) := finite.induction_on hs (λ _, by rw sInter_empty; exact is_open_univ) $ λ a s has hs ih h, by rw sInter_insert; exact is_open.inter (h _ $ mem_insert _ _) (ih $ λ t, h t ∘ mem_insert_of_mem _) lemma is_open_bInter {s : set β} {f : β → set α} (hs : s.finite) : (∀i∈s, is_open (f i)) → is_open (⋂i∈s, f i) := finite.induction_on hs (λ _, by rw bInter_empty; exact is_open_univ) (λ a s has hs ih h, by rw bInter_insert; exact is_open.inter (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi)))) lemma is_open_Inter [finite β] {s : β → set α} (h : ∀ i, is_open (s i)) : is_open (⋂ i, s i) := suffices is_open (⋂ (i : β) (hi : i ∈ @univ β), s i), by simpa, is_open_bInter finite_univ (λ i _, h i) lemma is_open_Inter_prop {p : Prop} {s : p → set α} (h : ∀ h : p, is_open (s h)) : is_open (Inter s) := by by_cases p; simp * lemma is_open_bInter_finset {s : finset β} {f : β → set α} (h : ∀ i ∈ s, is_open (f i)) : is_open (⋂ i ∈ s, f i) := is_open_bInter (to_finite _) h lemma is_open_const {p : Prop} : is_open {a : α | p} := by_cases (assume : p, begin simp only [this]; exact is_open_univ end) (assume : ¬ p, begin simp only [this]; exact is_open_empty end) lemma is_open.and : is_open {a | p₁ a} → is_open {a | p₂ a} → is_open {a | p₁ a ∧ p₂ a} := is_open.inter /-- A set is closed if its complement is open -/ class is_closed (s : set α) : Prop := (is_open_compl : is_open sᶜ) @[simp] lemma is_open_compl_iff {s : set α} : is_open sᶜ ↔ is_closed s := ⟨λ h, ⟨h⟩, λ h, h.is_open_compl⟩ @[simp] lemma is_closed_empty : is_closed (∅ : set α) := by { rw [← is_open_compl_iff, compl_empty], exact is_open_univ } @[simp] lemma is_closed_univ : is_closed (univ : set α) := by { rw [← is_open_compl_iff, compl_univ], exact is_open_empty } lemma is_closed.union : is_closed s₁ → is_closed s₂ → is_closed (s₁ ∪ s₂) := λ h₁ h₂, by { rw [← is_open_compl_iff] at *, rw compl_union, exact is_open.inter h₁ h₂ } lemma is_closed_sInter {s : set (set α)} : (∀t ∈ s, is_closed t) → is_closed (⋂₀ s) := by simpa only [← is_open_compl_iff, compl_sInter, sUnion_image] using is_open_bUnion lemma is_closed_Inter {f : ι → set α} (h : ∀i, is_closed (f i)) : is_closed (⋂i, f i ) := is_closed_sInter $ assume t ⟨i, (heq : f i = t)⟩, heq ▸ h i lemma is_closed_bInter {s : set β} {f : β → set α} (h : ∀ i ∈ s, is_closed (f i)) : is_closed (⋂ i ∈ s, f i) := is_closed_Inter $ λ i, is_closed_Inter $ h i @[simp] lemma is_closed_compl_iff {s : set α} : is_closed sᶜ ↔ is_open s := by rw [←is_open_compl_iff, compl_compl] lemma is_open.is_closed_compl {s : set α} (hs : is_open s) : is_closed sᶜ := is_closed_compl_iff.2 hs lemma is_open.sdiff {s t : set α} (h₁ : is_open s) (h₂ : is_closed t) : is_open (s \ t) := is_open.inter h₁ $ is_open_compl_iff.mpr h₂ lemma is_closed.inter (h₁ : is_closed s₁) (h₂ : is_closed s₂) : is_closed (s₁ ∩ s₂) := by { rw [← is_open_compl_iff] at *, rw compl_inter, exact is_open.union h₁ h₂ } lemma is_closed.sdiff {s t : set α} (h₁ : is_closed s) (h₂ : is_open t) : is_closed (s \ t) := is_closed.inter h₁ (is_closed_compl_iff.mpr h₂) lemma is_closed_bUnion {s : set β} {f : β → set α} (hs : s.finite) : (∀i∈s, is_closed (f i)) → is_closed (⋃i∈s, f i) := finite.induction_on hs (λ _, by rw bUnion_empty; exact is_closed_empty) (λ a s has hs ih h, by rw bUnion_insert; exact is_closed.union (h a (mem_insert _ _)) (ih (λ i hi, h i (mem_insert_of_mem _ hi)))) lemma is_closed_Union [finite β] {s : β → set α} (h : ∀ i, is_closed (s i)) : is_closed (⋃ i, s i) := suffices is_closed (⋃ (i : β) (hi : i ∈ @univ β), s i), by convert this; simp [set.ext_iff], is_closed_bUnion finite_univ (λ i _, h i) lemma is_closed_Union_prop {p : Prop} {s : p → set α} (h : ∀ h : p, is_closed (s h)) : is_closed (Union s) := by by_cases p; simp * lemma is_closed_imp {p q : α → Prop} (hp : is_open {x | p x}) (hq : is_closed {x | q x}) : is_closed {x | p x → q x} := have {x | p x → q x} = {x | p x}ᶜ ∪ {x | q x}, from set.ext $ λ x, imp_iff_not_or, by rw [this]; exact is_closed.union (is_closed_compl_iff.mpr hp) hq lemma is_closed.not : is_closed {a | p a} → is_open {a | ¬ p a} := is_open_compl_iff.mpr /-! ### Interior of a set -/ /-- The interior of a set `s` is the largest open subset of `s`. -/ def interior (s : set α) : set α := ⋃₀ {t | is_open t ∧ t ⊆ s} lemma mem_interior {s : set α} {x : α} : x ∈ interior s ↔ ∃ t ⊆ s, is_open t ∧ x ∈ t := by simp only [interior, mem_sUnion, mem_set_of_eq, exists_prop, and_assoc, and.left_comm] @[simp] lemma is_open_interior {s : set α} : is_open (interior s) := is_open_sUnion $ assume t ⟨h₁, h₂⟩, h₁ lemma interior_subset {s : set α} : interior s ⊆ s := sUnion_subset $ assume t ⟨h₁, h₂⟩, h₂ lemma interior_maximal {s t : set α} (h₁ : t ⊆ s) (h₂ : is_open t) : t ⊆ interior s := subset_sUnion_of_mem ⟨h₂, h₁⟩ lemma is_open.interior_eq {s : set α} (h : is_open s) : interior s = s := subset.antisymm interior_subset (interior_maximal (subset.refl s) h) lemma interior_eq_iff_is_open {s : set α} : interior s = s ↔ is_open s := ⟨assume h, h ▸ is_open_interior, is_open.interior_eq⟩ lemma subset_interior_iff_is_open {s : set α} : s ⊆ interior s ↔ is_open s := by simp only [interior_eq_iff_is_open.symm, subset.antisymm_iff, interior_subset, true_and] lemma is_open.subset_interior_iff {s t : set α} (h₁ : is_open s) : s ⊆ interior t ↔ s ⊆ t := ⟨assume h, subset.trans h interior_subset, assume h₂, interior_maximal h₂ h₁⟩ lemma subset_interior_iff {s t : set α} : t ⊆ interior s ↔ ∃ U, is_open U ∧ t ⊆ U ∧ U ⊆ s := ⟨λ h, ⟨interior s, is_open_interior, h, interior_subset⟩, λ ⟨U, hU, htU, hUs⟩, htU.trans (interior_maximal hUs hU)⟩ @[mono] lemma interior_mono {s t : set α} (h : s ⊆ t) : interior s ⊆ interior t := interior_maximal (subset.trans interior_subset h) is_open_interior @[simp] lemma interior_empty : interior (∅ : set α) = ∅ := is_open_empty.interior_eq @[simp] lemma interior_univ : interior (univ : set α) = univ := is_open_univ.interior_eq @[simp] lemma interior_eq_univ {s : set α} : interior s = univ ↔ s = univ := ⟨λ h, univ_subset_iff.mp $ h.symm.trans_le interior_subset, λ h, h.symm ▸ interior_univ⟩ @[simp] lemma interior_interior {s : set α} : interior (interior s) = interior s := is_open_interior.interior_eq @[simp] lemma interior_inter {s t : set α} : interior (s ∩ t) = interior s ∩ interior t := subset.antisymm (subset_inter (interior_mono $ inter_subset_left s t) (interior_mono $ inter_subset_right s t)) (interior_maximal (inter_subset_inter interior_subset interior_subset) $ is_open.inter is_open_interior is_open_interior) @[simp] lemma finset.interior_Inter {ι : Type*} (s : finset ι) (f : ι → set α) : interior (⋂ i ∈ s, f i) = ⋂ i ∈ s, interior (f i) := begin classical, refine s.induction_on (by simp) _, intros i s h₁ h₂, simp [h₂], end @[simp] lemma interior_Inter {ι : Type*} [finite ι] (f : ι → set α) : interior (⋂ i, f i) = ⋂ i, interior (f i) := by { casesI nonempty_fintype ι, convert finset.univ.interior_Inter f; simp } lemma interior_union_is_closed_of_interior_empty {s t : set α} (h₁ : is_closed s) (h₂ : interior t = ∅) : interior (s ∪ t) = interior s := have interior (s ∪ t) ⊆ s, from assume x ⟨u, ⟨(hu₁ : is_open u), (hu₂ : u ⊆ s ∪ t)⟩, (hx₁ : x ∈ u)⟩, classical.by_contradiction $ assume hx₂ : x ∉ s, have u \ s ⊆ t, from assume x ⟨h₁, h₂⟩, or.resolve_left (hu₂ h₁) h₂, have u \ s ⊆ interior t, by rwa (is_open.sdiff hu₁ h₁).subset_interior_iff, have u \ s ⊆ ∅, by rwa h₂ at this, this ⟨hx₁, hx₂⟩, subset.antisymm (interior_maximal this is_open_interior) (interior_mono $ subset_union_left _ _) lemma is_open_iff_forall_mem_open : is_open s ↔ ∀ x ∈ s, ∃ t ⊆ s, is_open t ∧ x ∈ t := by rw ← subset_interior_iff_is_open; simp only [subset_def, mem_interior] lemma interior_Inter_subset (s : ι → set α) : interior (⋂ i, s i) ⊆ ⋂ i, interior (s i) := subset_Inter $ λ i, interior_mono $ Inter_subset _ _ lemma interior_Inter₂_subset (p : ι → Sort*) (s : Π i, p i → set α) : interior (⋂ i j, s i j) ⊆ ⋂ i j, interior (s i j) := (interior_Inter_subset _).trans $ Inter_mono $ λ i, interior_Inter_subset _ lemma interior_sInter_subset (S : set (set α)) : interior (⋂₀ S) ⊆ ⋂ s ∈ S, interior s := calc interior (⋂₀ S) = interior (⋂ s ∈ S, s) : by rw sInter_eq_bInter ... ⊆ ⋂ s ∈ S, interior s : interior_Inter₂_subset _ _ /-! ### Closure of a set -/ /-- The closure of `s` is the smallest closed set containing `s`. -/ def closure (s : set α) : set α := ⋂₀ {t | is_closed t ∧ s ⊆ t} @[simp] lemma is_closed_closure {s : set α} : is_closed (closure s) := is_closed_sInter $ assume t ⟨h₁, h₂⟩, h₁ lemma subset_closure {s : set α} : s ⊆ closure s := subset_sInter $ assume t ⟨h₁, h₂⟩, h₂ lemma not_mem_of_not_mem_closure {s : set α} {P : α} (hP : P ∉ closure s) : P ∉ s := λ h, hP (subset_closure h) lemma closure_minimal {s t : set α} (h₁ : s ⊆ t) (h₂ : is_closed t) : closure s ⊆ t := sInter_subset_of_mem ⟨h₂, h₁⟩ lemma disjoint.closure_left {s t : set α} (hd : disjoint s t) (ht : is_open t) : disjoint (closure s) t := disjoint_compl_left.mono_left $ closure_minimal hd.subset_compl_right ht.is_closed_compl lemma disjoint.closure_right {s t : set α} (hd : disjoint s t) (hs : is_open s) : disjoint s (closure t) := (hd.symm.closure_left hs).symm lemma is_closed.closure_eq {s : set α} (h : is_closed s) : closure s = s := subset.antisymm (closure_minimal (subset.refl s) h) subset_closure lemma is_closed.closure_subset {s : set α} (hs : is_closed s) : closure s ⊆ s := closure_minimal (subset.refl _) hs lemma is_closed.closure_subset_iff {s t : set α} (h₁ : is_closed t) : closure s ⊆ t ↔ s ⊆ t := ⟨subset.trans subset_closure, assume h, closure_minimal h h₁⟩ lemma is_closed.mem_iff_closure_subset {s : set α} (hs : is_closed s) {x : α} : x ∈ s ↔ closure ({x} : set α) ⊆ s := (hs.closure_subset_iff.trans set.singleton_subset_iff).symm @[mono] lemma closure_mono {s t : set α} (h : s ⊆ t) : closure s ⊆ closure t := closure_minimal (subset.trans h subset_closure) is_closed_closure lemma monotone_closure (α : Type*) [topological_space α] : monotone (@closure α _) := λ _ _, closure_mono lemma diff_subset_closure_iff {s t : set α} : s \ t ⊆ closure t ↔ s ⊆ closure t := by rw [diff_subset_iff, union_eq_self_of_subset_left subset_closure] lemma closure_inter_subset_inter_closure (s t : set α) : closure (s ∩ t) ⊆ closure s ∩ closure t := (monotone_closure α).map_inf_le s t lemma is_closed_of_closure_subset {s : set α} (h : closure s ⊆ s) : is_closed s := by rw subset.antisymm subset_closure h; exact is_closed_closure lemma closure_eq_iff_is_closed {s : set α} : closure s = s ↔ is_closed s := ⟨assume h, h ▸ is_closed_closure, is_closed.closure_eq⟩ lemma closure_subset_iff_is_closed {s : set α} : closure s ⊆ s ↔ is_closed s := ⟨is_closed_of_closure_subset, is_closed.closure_subset⟩ @[simp] lemma closure_empty : closure (∅ : set α) = ∅ := is_closed_empty.closure_eq @[simp] lemma closure_empty_iff (s : set α) : closure s = ∅ ↔ s = ∅ := ⟨subset_eq_empty subset_closure, λ h, h.symm ▸ closure_empty⟩ @[simp] lemma closure_nonempty_iff {s : set α} : (closure s).nonempty ↔ s.nonempty := by simp only [← ne_empty_iff_nonempty, ne.def, closure_empty_iff] alias closure_nonempty_iff ↔ set.nonempty.of_closure set.nonempty.closure @[simp] lemma closure_univ : closure (univ : set α) = univ := is_closed_univ.closure_eq @[simp] lemma closure_closure {s : set α} : closure (closure s) = closure s := is_closed_closure.closure_eq @[simp] lemma closure_union {s t : set α} : closure (s ∪ t) = closure s ∪ closure t := subset.antisymm (closure_minimal (union_subset_union subset_closure subset_closure) $ is_closed.union is_closed_closure is_closed_closure) ((monotone_closure α).le_map_sup s t) @[simp] lemma finset.closure_bUnion {ι : Type*} (s : finset ι) (f : ι → set α) : closure (⋃ i ∈ s, f i) = ⋃ i ∈ s, closure (f i) := begin classical, refine s.induction_on (by simp) _, intros i s h₁ h₂, simp [h₂], end @[simp] lemma closure_Union {ι : Type*} [finite ι] (f : ι → set α) : closure (⋃ i, f i) = ⋃ i, closure (f i) := by { casesI nonempty_fintype ι, convert finset.univ.closure_bUnion f; simp } lemma interior_subset_closure {s : set α} : interior s ⊆ closure s := subset.trans interior_subset subset_closure lemma closure_eq_compl_interior_compl {s : set α} : closure s = (interior sᶜ)ᶜ := begin rw [interior, closure, compl_sUnion, compl_image_set_of], simp only [compl_subset_compl, is_open_compl_iff], end @[simp] lemma interior_compl {s : set α} : interior sᶜ = (closure s)ᶜ := by simp [closure_eq_compl_interior_compl] @[simp] lemma closure_compl {s : set α} : closure sᶜ = (interior s)ᶜ := by simp [closure_eq_compl_interior_compl] theorem mem_closure_iff {s : set α} {a : α} : a ∈ closure s ↔ ∀ o, is_open o → a ∈ o → (o ∩ s).nonempty := ⟨λ h o oo ao, classical.by_contradiction $ λ os, have s ⊆ oᶜ, from λ x xs xo, os ⟨x, xo, xs⟩, closure_minimal this (is_closed_compl_iff.2 oo) h ao, λ H c ⟨h₁, h₂⟩, classical.by_contradiction $ λ nc, let ⟨x, hc, hs⟩ := (H _ h₁.is_open_compl nc) in hc (h₂ hs)⟩ lemma closure_inter_open_nonempty_iff {s t : set α} (h : is_open t) : (closure s ∩ t).nonempty ↔ (s ∩ t).nonempty := ⟨λ ⟨x, hxcs, hxt⟩, inter_comm t s ▸ mem_closure_iff.1 hxcs t h hxt, λ h, h.mono $ inf_le_inf_right t subset_closure⟩ lemma filter.le_lift'_closure (l : filter α) : l ≤ l.lift' closure := le_lift'.2 $ λ s hs, mem_of_superset hs subset_closure lemma filter.has_basis.lift'_closure {l : filter α} {p : ι → Prop} {s : ι → set α} (h : l.has_basis p s) : (l.lift' closure).has_basis p (λ i, closure (s i)) := h.lift' (monotone_closure α) lemma filter.has_basis.lift'_closure_eq_self {l : filter α} {p : ι → Prop} {s : ι → set α} (h : l.has_basis p s) (hc : ∀ i, p i → is_closed (s i)) : l.lift' closure = l := le_antisymm (h.ge_iff.2 $ λ i hi, (hc i hi).closure_eq ▸ mem_lift' (h.mem_of_mem hi)) l.le_lift'_closure @[simp] lemma filter.lift'_closure_eq_bot {l : filter α} : l.lift' closure = ⊥ ↔ l = ⊥ := ⟨λ h, bot_unique $ h ▸ l.le_lift'_closure, λ h, h.symm ▸ by rw [lift'_bot (monotone_closure _), closure_empty, principal_empty]⟩ /-- A set is dense in a topological space if every point belongs to its closure. -/ def dense (s : set α) : Prop := ∀ x, x ∈ closure s lemma dense_iff_closure_eq {s : set α} : dense s ↔ closure s = univ := eq_univ_iff_forall.symm lemma dense.closure_eq {s : set α} (h : dense s) : closure s = univ := dense_iff_closure_eq.mp h lemma interior_eq_empty_iff_dense_compl {s : set α} : interior s = ∅ ↔ dense sᶜ := by rw [dense_iff_closure_eq, closure_compl, compl_univ_iff] lemma dense.interior_compl {s : set α} (h : dense s) : interior sᶜ = ∅ := interior_eq_empty_iff_dense_compl.2 $ by rwa compl_compl /-- The closure of a set `s` is dense if and only if `s` is dense. -/ @[simp] lemma dense_closure {s : set α} : dense (closure s) ↔ dense s := by rw [dense, dense, closure_closure] alias dense_closure ↔ dense.of_closure dense.closure @[simp] lemma dense_univ : dense (univ : set α) := λ x, subset_closure trivial /-- A set is dense if and only if it has a nonempty intersection with each nonempty open set. -/ lemma dense_iff_inter_open {s : set α} : dense s ↔ ∀ U, is_open U → U.nonempty → (U ∩ s).nonempty := begin split ; intro h, { rintros U U_op ⟨x, x_in⟩, exact mem_closure_iff.1 (by simp only [h.closure_eq]) U U_op x_in }, { intro x, rw mem_closure_iff, intros U U_op x_in, exact h U U_op ⟨_, x_in⟩ }, end alias dense_iff_inter_open ↔ dense.inter_open_nonempty _ lemma dense.exists_mem_open {s : set α} (hs : dense s) {U : set α} (ho : is_open U) (hne : U.nonempty) : ∃ x ∈ s, x ∈ U := let ⟨x, hx⟩ := hs.inter_open_nonempty U ho hne in ⟨x, hx.2, hx.1⟩ lemma dense.nonempty_iff {s : set α} (hs : dense s) : s.nonempty ↔ nonempty α := ⟨λ ⟨x, hx⟩, ⟨x⟩, λ ⟨x⟩, let ⟨y, hy⟩ := hs.inter_open_nonempty _ is_open_univ ⟨x, trivial⟩ in ⟨y, hy.2⟩⟩ lemma dense.nonempty [h : nonempty α] {s : set α} (hs : dense s) : s.nonempty := hs.nonempty_iff.2 h @[mono] lemma dense.mono {s₁ s₂ : set α} (h : s₁ ⊆ s₂) (hd : dense s₁) : dense s₂ := λ x, closure_mono h (hd x) /-- Complement to a singleton is dense if and only if the singleton is not an open set. -/ lemma dense_compl_singleton_iff_not_open {x : α} : dense ({x}ᶜ : set α) ↔ ¬is_open ({x} : set α) := begin fsplit, { intros hd ho, exact (hd.inter_open_nonempty _ ho (singleton_nonempty _)).ne_empty (inter_compl_self _) }, { refine λ ho, dense_iff_inter_open.2 (λ U hU hne, inter_compl_nonempty_iff.2 $ λ hUx, _), obtain rfl : U = {x}, from eq_singleton_iff_nonempty_unique_mem.2 ⟨hne, hUx⟩, exact ho hU } end /-! ### Frontier of a set -/ /-- The frontier of a set is the set of points between the closure and interior. -/ def frontier (s : set α) : set α := closure s \ interior s @[simp] lemma closure_diff_interior (s : set α) : closure s \ interior s = frontier s := rfl @[simp] lemma closure_diff_frontier (s : set α) : closure s \ frontier s = interior s := by rw [frontier, diff_diff_right_self, inter_eq_self_of_subset_right interior_subset_closure] @[simp] lemma self_diff_frontier (s : set α) : s \ frontier s = interior s := by rw [frontier, diff_diff_right, diff_eq_empty.2 subset_closure, inter_eq_self_of_subset_right interior_subset, empty_union] lemma frontier_eq_closure_inter_closure {s : set α} : frontier s = closure s ∩ closure sᶜ := by rw [closure_compl, frontier, diff_eq] lemma frontier_subset_closure {s : set α} : frontier s ⊆ closure s := diff_subset _ _ lemma is_closed.frontier_subset (hs : is_closed s) : frontier s ⊆ s := frontier_subset_closure.trans hs.closure_eq.subset lemma frontier_closure_subset {s : set α} : frontier (closure s) ⊆ frontier s := diff_subset_diff closure_closure.subset $ interior_mono subset_closure lemma frontier_interior_subset {s : set α} : frontier (interior s) ⊆ frontier s := diff_subset_diff (closure_mono interior_subset) interior_interior.symm.subset /-- The complement of a set has the same frontier as the original set. -/ @[simp] lemma frontier_compl (s : set α) : frontier sᶜ = frontier s := by simp only [frontier_eq_closure_inter_closure, compl_compl, inter_comm] @[simp] lemma frontier_univ : frontier (univ : set α) = ∅ := by simp [frontier] @[simp] lemma frontier_empty : frontier (∅ : set α) = ∅ := by simp [frontier] lemma frontier_inter_subset (s t : set α) : frontier (s ∩ t) ⊆ (frontier s ∩ closure t) ∪ (closure s ∩ frontier t) := begin simp only [frontier_eq_closure_inter_closure, compl_inter, closure_union], convert inter_subset_inter_left _ (closure_inter_subset_inter_closure s t), simp only [inter_distrib_left, inter_distrib_right, inter_assoc], congr' 2, apply inter_comm end lemma frontier_union_subset (s t : set α) : frontier (s ∪ t) ⊆ (frontier s ∩ closure tᶜ) ∪ (closure sᶜ ∩ frontier t) := by simpa only [frontier_compl, ← compl_union] using frontier_inter_subset sᶜ tᶜ lemma is_closed.frontier_eq {s : set α} (hs : is_closed s) : frontier s = s \ interior s := by rw [frontier, hs.closure_eq] lemma is_open.frontier_eq {s : set α} (hs : is_open s) : frontier s = closure s \ s := by rw [frontier, hs.interior_eq] lemma is_open.inter_frontier_eq {s : set α} (hs : is_open s) : s ∩ frontier s = ∅ := by rw [hs.frontier_eq, inter_diff_self] /-- The frontier of a set is closed. -/ lemma is_closed_frontier {s : set α} : is_closed (frontier s) := by rw frontier_eq_closure_inter_closure; exact is_closed.inter is_closed_closure is_closed_closure /-- The frontier of a closed set has no interior point. -/ lemma interior_frontier {s : set α} (h : is_closed s) : interior (frontier s) = ∅ := begin have A : frontier s = s \ interior s, from h.frontier_eq, have B : interior (frontier s) ⊆ interior s, by rw A; exact interior_mono (diff_subset _ _), have C : interior (frontier s) ⊆ frontier s := interior_subset, have : interior (frontier s) ⊆ (interior s) ∩ (s \ interior s) := subset_inter B (by simpa [A] using C), rwa [inter_diff_self, subset_empty_iff] at this, end lemma closure_eq_interior_union_frontier (s : set α) : closure s = interior s ∪ frontier s := (union_diff_cancel interior_subset_closure).symm lemma closure_eq_self_union_frontier (s : set α) : closure s = s ∪ frontier s := (union_diff_cancel' interior_subset subset_closure).symm lemma disjoint.frontier_left (ht : is_open t) (hd : disjoint s t) : disjoint (frontier s) t := subset_compl_iff_disjoint_right.1 $ frontier_subset_closure.trans $ closure_minimal (disjoint_left.1 hd) $ is_closed_compl_iff.2 ht lemma disjoint.frontier_right (hs : is_open s) (hd : disjoint s t) : disjoint s (frontier t) := (hd.symm.frontier_left hs).symm lemma frontier_eq_inter_compl_interior {s : set α} : frontier s = (interior s)ᶜ ∩ (interior (sᶜ))ᶜ := by { rw [←frontier_compl, ←closure_compl], refl } lemma compl_frontier_eq_union_interior {s : set α} : (frontier s)ᶜ = interior s ∪ interior sᶜ := begin rw frontier_eq_inter_compl_interior, simp only [compl_inter, compl_compl], end /-! ### Neighborhoods -/ /-- A set is called a neighborhood of `a` if it contains an open set around `a`. The set of all neighborhoods of `a` forms a filter, the neighborhood filter at `a`, is here defined as the infimum over the principal filters of all open sets containing `a`. -/ @[irreducible] def nhds (a : α) : filter α := (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s) localized "notation (name := nhds) `𝓝` := nhds" in topological_space /-- The "neighborhood within" filter. Elements of `𝓝[s] a` are sets containing the intersection of `s` and a neighborhood of `a`. -/ def nhds_within (a : α) (s : set α) : filter α := 𝓝 a ⊓ 𝓟 s localized "notation (name := nhds_within) `𝓝[` s `] ` x:100 := nhds_within x s" in topological_space localized "notation (name := nhds_within.ne) `𝓝[≠] ` x:100 := nhds_within x {x}ᶜ" in topological_space localized "notation (name := nhds_within.ge) `𝓝[≥] ` x:100 := nhds_within x (set.Ici x)" in topological_space localized "notation (name := nhds_within.le) `𝓝[≤] ` x:100 := nhds_within x (set.Iic x)" in topological_space localized "notation (name := nhds_within.gt) `𝓝[>] ` x:100 := nhds_within x (set.Ioi x)" in topological_space localized "notation (name := nhds_within.lt) `𝓝[<] ` x:100 := nhds_within x (set.Iio x)" in topological_space lemma nhds_def (a : α) : 𝓝 a = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 s) := by rw nhds lemma nhds_def' (a : α) : 𝓝 a = ⨅ (s : set α) (hs : is_open s) (ha : a ∈ s), 𝓟 s := by simp only [nhds_def, mem_set_of_eq, and_comm (a ∈ _), infi_and] /-- The open sets containing `a` are a basis for the neighborhood filter. See `nhds_basis_opens'` for a variant using open neighborhoods instead. -/ lemma nhds_basis_opens (a : α) : (𝓝 a).has_basis (λ s : set α, a ∈ s ∧ is_open s) (λ s, s) := begin rw nhds_def, exact has_basis_binfi_principal (λ s ⟨has, hs⟩ t ⟨hat, ht⟩, ⟨s ∩ t, ⟨⟨has, hat⟩, is_open.inter hs ht⟩, ⟨inter_subset_left _ _, inter_subset_right _ _⟩⟩) ⟨univ, ⟨mem_univ a, is_open_univ⟩⟩ end lemma nhds_basis_closeds (a : α) : (𝓝 a).has_basis (λ s : set α, a ∉ s ∧ is_closed s) compl := ⟨λ t, (nhds_basis_opens a).mem_iff.trans $ compl_surjective.exists.trans $ by simp only [is_open_compl_iff, mem_compl_iff]⟩ /-- A filter lies below the neighborhood filter at `a` iff it contains every open set around `a`. -/ lemma le_nhds_iff {f a} : f ≤ 𝓝 a ↔ ∀ s : set α, a ∈ s → is_open s → s ∈ f := by simp [nhds_def] /-- To show a filter is above the neighborhood filter at `a`, it suffices to show that it is above the principal filter of some open set `s` containing `a`. -/ lemma nhds_le_of_le {f a} {s : set α} (h : a ∈ s) (o : is_open s) (sf : 𝓟 s ≤ f) : 𝓝 a ≤ f := by rw nhds_def; exact infi_le_of_le s (infi_le_of_le ⟨h, o⟩ sf) lemma mem_nhds_iff {a : α} {s : set α} : s ∈ 𝓝 a ↔ ∃ t ⊆ s, is_open t ∧ a ∈ t := (nhds_basis_opens a).mem_iff.trans ⟨λ ⟨t, ⟨hat, ht⟩, hts⟩, ⟨t, hts, ht, hat⟩, λ ⟨t, hts, ht, hat⟩, ⟨t, ⟨hat, ht⟩, hts⟩⟩ /-- A predicate is true in a neighborhood of `a` iff it is true for all the points in an open set containing `a`. -/ lemma eventually_nhds_iff {a : α} {p : α → Prop} : (∀ᶠ x in 𝓝 a, p x) ↔ ∃ (t : set α), (∀ x ∈ t, p x) ∧ is_open t ∧ a ∈ t := mem_nhds_iff.trans $ by simp only [subset_def, exists_prop, mem_set_of_eq] lemma map_nhds {a : α} {f : α → β} : map f (𝓝 a) = (⨅ s ∈ {s : set α | a ∈ s ∧ is_open s}, 𝓟 (image f s)) := ((nhds_basis_opens a).map f).eq_binfi lemma mem_of_mem_nhds {a : α} {s : set α} : s ∈ 𝓝 a → a ∈ s := λ H, let ⟨t, ht, _, hs⟩ := mem_nhds_iff.1 H in ht hs /-- If a predicate is true in a neighborhood of `a`, then it is true for `a`. -/ lemma filter.eventually.self_of_nhds {p : α → Prop} {a : α} (h : ∀ᶠ y in 𝓝 a, p y) : p a := mem_of_mem_nhds h lemma is_open.mem_nhds {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) : s ∈ 𝓝 a := mem_nhds_iff.2 ⟨s, subset.refl _, hs, ha⟩ lemma is_open.mem_nhds_iff {a : α} {s : set α} (hs : is_open s) : s ∈ 𝓝 a ↔ a ∈ s := ⟨mem_of_mem_nhds, λ ha, mem_nhds_iff.2 ⟨s, subset.refl _, hs, ha⟩⟩ lemma is_closed.compl_mem_nhds {a : α} {s : set α} (hs : is_closed s) (ha : a ∉ s) : sᶜ ∈ 𝓝 a := hs.is_open_compl.mem_nhds (mem_compl ha) lemma is_open.eventually_mem {a : α} {s : set α} (hs : is_open s) (ha : a ∈ s) : ∀ᶠ x in 𝓝 a, x ∈ s := is_open.mem_nhds hs ha /-- The open neighborhoods of `a` are a basis for the neighborhood filter. See `nhds_basis_opens` for a variant using open sets around `a` instead. -/ lemma nhds_basis_opens' (a : α) : (𝓝 a).has_basis (λ s : set α, s ∈ 𝓝 a ∧ is_open s) (λ x, x) := begin convert nhds_basis_opens a, ext s, exact and.congr_left_iff.2 is_open.mem_nhds_iff end /-- If `U` is a neighborhood of each point of a set `s` then it is a neighborhood of `s`: it contains an open set containing `s`. -/ lemma exists_open_set_nhds {s U : set α} (h : ∀ x ∈ s, U ∈ 𝓝 x) : ∃ V : set α, s ⊆ V ∧ is_open V ∧ V ⊆ U := begin have := λ x hx, (nhds_basis_opens x).mem_iff.1 (h x hx), choose! Z hZ hZU using this, choose hZmem hZo using hZ, exact ⟨⋃ x ∈ s, Z x, λ x hx, mem_bUnion hx (hZmem x hx), is_open_bUnion hZo, Union₂_subset hZU⟩ end /-- If `U` is a neighborhood of each point of a set `s` then it is a neighborhood of s: it contains an open set containing `s`. -/ lemma exists_open_set_nhds' {s U : set α} (h : U ∈ ⨆ x ∈ s, 𝓝 x) : ∃ V : set α, s ⊆ V ∧ is_open V ∧ V ⊆ U := exists_open_set_nhds (by simpa using h) /-- If a predicate is true in a neighbourhood of `a`, then for `y` sufficiently close to `a` this predicate is true in a neighbourhood of `y`. -/ lemma filter.eventually.eventually_nhds {p : α → Prop} {a : α} (h : ∀ᶠ y in 𝓝 a, p y) : ∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝 y, p x := let ⟨t, htp, hto, ha⟩ := eventually_nhds_iff.1 h in eventually_nhds_iff.2 ⟨t, λ x hx, eventually_nhds_iff.2 ⟨t, htp, hto, hx⟩, hto, ha⟩ @[simp] lemma eventually_eventually_nhds {p : α → Prop} {a : α} : (∀ᶠ y in 𝓝 a, ∀ᶠ x in 𝓝 y, p x) ↔ ∀ᶠ x in 𝓝 a, p x := ⟨λ h, h.self_of_nhds, λ h, h.eventually_nhds⟩ @[simp] lemma eventually_mem_nhds {s : set α} {a : α} : (∀ᶠ x in 𝓝 a, s ∈ 𝓝 x) ↔ s ∈ 𝓝 a := eventually_eventually_nhds @[simp] lemma nhds_bind_nhds : (𝓝 a).bind 𝓝 = 𝓝 a := filter.ext $ λ s, eventually_eventually_nhds @[simp] lemma eventually_eventually_eq_nhds {f g : α → β} {a : α} : (∀ᶠ y in 𝓝 a, f =ᶠ[𝓝 y] g) ↔ f =ᶠ[𝓝 a] g := eventually_eventually_nhds lemma filter.eventually_eq.eq_of_nhds {f g : α → β} {a : α} (h : f =ᶠ[𝓝 a] g) : f a = g a := h.self_of_nhds @[simp] lemma eventually_eventually_le_nhds [has_le β] {f g : α → β} {a : α} : (∀ᶠ y in 𝓝 a, f ≤ᶠ[𝓝 y] g) ↔ f ≤ᶠ[𝓝 a] g := eventually_eventually_nhds /-- If two functions are equal in a neighbourhood of `a`, then for `y` sufficiently close to `a` these functions are equal in a neighbourhood of `y`. -/ lemma filter.eventually_eq.eventually_eq_nhds {f g : α → β} {a : α} (h : f =ᶠ[𝓝 a] g) : ∀ᶠ y in 𝓝 a, f =ᶠ[𝓝 y] g := h.eventually_nhds /-- If `f x ≤ g x` in a neighbourhood of `a`, then for `y` sufficiently close to `a` we have `f x ≤ g x` in a neighbourhood of `y`. -/ lemma filter.eventually_le.eventually_le_nhds [has_le β] {f g : α → β} {a : α} (h : f ≤ᶠ[𝓝 a] g) : ∀ᶠ y in 𝓝 a, f ≤ᶠ[𝓝 y] g := h.eventually_nhds theorem all_mem_nhds (x : α) (P : set α → Prop) (hP : ∀ s t, s ⊆ t → P s → P t) : (∀ s ∈ 𝓝 x, P s) ↔ (∀ s, is_open s → x ∈ s → P s) := ((nhds_basis_opens x).forall_iff hP).trans $ by simp only [and_comm (x ∈ _), and_imp] theorem all_mem_nhds_filter (x : α) (f : set α → set β) (hf : ∀ s t, s ⊆ t → f s ⊆ f t) (l : filter β) : (∀ s ∈ 𝓝 x, f s ∈ l) ↔ (∀ s, is_open s → x ∈ s → f s ∈ l) := all_mem_nhds _ _ (λ s t ssubt h, mem_of_superset h (hf s t ssubt)) theorem rtendsto_nhds {r : rel β α} {l : filter β} {a : α} : rtendsto r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.core s ∈ l) := all_mem_nhds_filter _ _ (λ s t, id) _ theorem rtendsto'_nhds {r : rel β α} {l : filter β} {a : α} : rtendsto' r l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → r.preimage s ∈ l) := by { rw [rtendsto'_def], apply all_mem_nhds_filter, apply rel.preimage_mono } theorem ptendsto_nhds {f : β →. α} {l : filter β} {a : α} : ptendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.core s ∈ l) := rtendsto_nhds theorem ptendsto'_nhds {f : β →. α} {l : filter β} {a : α} : ptendsto' f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f.preimage s ∈ l) := rtendsto'_nhds theorem tendsto_nhds {f : β → α} {l : filter β} {a : α} : tendsto f l (𝓝 a) ↔ (∀ s, is_open s → a ∈ s → f ⁻¹' s ∈ l) := all_mem_nhds_filter _ _ (λ s t h, preimage_mono h) _ lemma tendsto_at_top_nhds [nonempty β] [semilattice_sup β] {f : β → α} {a : α} : (tendsto f at_top (𝓝 a)) ↔ ∀ U : set α, a ∈ U → is_open U → ∃ N, ∀ n, N ≤ n → f n ∈ U := (at_top_basis.tendsto_iff (nhds_basis_opens a)).trans $ by simp only [and_imp, exists_prop, true_and, mem_Ici, ge_iff_le] lemma tendsto_const_nhds {a : α} {f : filter β} : tendsto (λb:β, a) f (𝓝 a) := tendsto_nhds.mpr $ assume s hs ha, univ_mem' $ assume _, ha lemma tendsto_at_top_of_eventually_const {ι : Type*} [semilattice_sup ι] [nonempty ι] {x : α} {u : ι → α} {i₀ : ι} (h : ∀ i ≥ i₀, u i = x) : tendsto u at_top (𝓝 x) := tendsto.congr' (eventually_eq.symm (eventually_at_top.mpr ⟨i₀, h⟩)) tendsto_const_nhds lemma tendsto_at_bot_of_eventually_const {ι : Type*} [semilattice_inf ι] [nonempty ι] {x : α} {u : ι → α} {i₀ : ι} (h : ∀ i ≤ i₀, u i = x) : tendsto u at_bot (𝓝 x) := tendsto.congr' (eventually_eq.symm (eventually_at_bot.mpr ⟨i₀, h⟩)) tendsto_const_nhds lemma pure_le_nhds : pure ≤ (𝓝 : α → filter α) := assume a s hs, mem_pure.2 $ mem_of_mem_nhds hs lemma tendsto_pure_nhds {α : Type*} [topological_space β] (f : α → β) (a : α) : tendsto f (pure a) (𝓝 (f a)) := (tendsto_pure_pure f a).mono_right (pure_le_nhds _) lemma order_top.tendsto_at_top_nhds {α : Type*} [partial_order α] [order_top α] [topological_space β] (f : α → β) : tendsto f at_top (𝓝 $ f ⊤) := (tendsto_at_top_pure f).mono_right (pure_le_nhds _) @[simp] instance nhds_ne_bot {a : α} : ne_bot (𝓝 a) := ne_bot_of_le (pure_le_nhds a) /-! ### Cluster points In this section we define [cluster points](https://en.wikipedia.org/wiki/Limit_point) (also known as limit points and accumulation points) of a filter and of a sequence. -/ /-- A point `x` is a cluster point of a filter `F` if `𝓝 x ⊓ F ≠ ⊥`. Also known as an accumulation point or a limit point, but beware that terminology varies. This is *not* the same as asking `𝓝[≠] x ⊓ F ≠ ⊥`. See `mem_closure_iff_cluster_pt` in particular. -/ def cluster_pt (x : α) (F : filter α) : Prop := ne_bot (𝓝 x ⊓ F) lemma cluster_pt.ne_bot {x : α} {F : filter α} (h : cluster_pt x F) : ne_bot (𝓝 x ⊓ F) := h lemma filter.has_basis.cluster_pt_iff {ιa ιF} {pa : ιa → Prop} {sa : ιa → set α} {pF : ιF → Prop} {sF : ιF → set α} {F : filter α} (ha : (𝓝 a).has_basis pa sa) (hF : F.has_basis pF sF) : cluster_pt a F ↔ ∀ ⦃i⦄ (hi : pa i) ⦃j⦄ (hj : pF j), (sa i ∩ sF j).nonempty := ha.inf_basis_ne_bot_iff hF lemma cluster_pt_iff {x : α} {F : filter α} : cluster_pt x F ↔ ∀ ⦃U : set α⦄ (hU : U ∈ 𝓝 x) ⦃V⦄ (hV : V ∈ F), (U ∩ V).nonempty := inf_ne_bot_iff /-- `x` is a cluster point of a set `s` if every neighbourhood of `x` meets `s` on a nonempty set. See also `mem_closure_iff_cluster_pt`. -/ lemma cluster_pt_principal_iff {x : α} {s : set α} : cluster_pt x (𝓟 s) ↔ ∀ U ∈ 𝓝 x, (U ∩ s).nonempty := inf_principal_ne_bot_iff lemma cluster_pt_principal_iff_frequently {x : α} {s : set α} : cluster_pt x (𝓟 s) ↔ ∃ᶠ y in 𝓝 x, y ∈ s := by simp only [cluster_pt_principal_iff, frequently_iff, set.nonempty, exists_prop, mem_inter_iff] lemma cluster_pt.of_le_nhds {x : α} {f : filter α} (H : f ≤ 𝓝 x) [ne_bot f] : cluster_pt x f := by rwa [cluster_pt, inf_eq_right.mpr H] lemma cluster_pt.of_le_nhds' {x : α} {f : filter α} (H : f ≤ 𝓝 x) (hf : ne_bot f) : cluster_pt x f := cluster_pt.of_le_nhds H lemma cluster_pt.of_nhds_le {x : α} {f : filter α} (H : 𝓝 x ≤ f) : cluster_pt x f := by simp only [cluster_pt, inf_eq_left.mpr H, nhds_ne_bot] lemma cluster_pt.mono {x : α} {f g : filter α} (H : cluster_pt x f) (h : f ≤ g) : cluster_pt x g := ⟨ne_bot_of_le_ne_bot H.ne $ inf_le_inf_left _ h⟩ lemma cluster_pt.of_inf_left {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) : cluster_pt x f := H.mono inf_le_left lemma cluster_pt.of_inf_right {x : α} {f g : filter α} (H : cluster_pt x $ f ⊓ g) : cluster_pt x g := H.mono inf_le_right lemma ultrafilter.cluster_pt_iff {x : α} {f : ultrafilter α} : cluster_pt x f ↔ ↑f ≤ 𝓝 x := ⟨f.le_of_inf_ne_bot', λ h, cluster_pt.of_le_nhds h⟩ /-- A point `x` is a cluster point of a sequence `u` along a filter `F` if it is a cluster point of `map u F`. -/ def map_cluster_pt {ι :Type*} (x : α) (F : filter ι) (u : ι → α) : Prop := cluster_pt x (map u F) lemma map_cluster_pt_iff {ι :Type*} (x : α) (F : filter ι) (u : ι → α) : map_cluster_pt x F u ↔ ∀ s ∈ 𝓝 x, ∃ᶠ a in F, u a ∈ s := by { simp_rw [map_cluster_pt, cluster_pt, inf_ne_bot_iff_frequently_left, frequently_map], refl } lemma map_cluster_pt_of_comp {ι δ :Type*} {F : filter ι} {φ : δ → ι} {p : filter δ} {x : α} {u : ι → α} [ne_bot p] (h : tendsto φ p F) (H : tendsto (u ∘ φ) p (𝓝 x)) : map_cluster_pt x F u := begin have := calc map (u ∘ φ) p = map u (map φ p) : map_map ... ≤ map u F : map_mono h, have : map (u ∘ φ) p ≤ 𝓝 x ⊓ map u F, from le_inf H this, exact ne_bot_of_le this end /-! ### Interior, closure and frontier in terms of neighborhoods -/ lemma interior_eq_nhds' {s : set α} : interior s = {a | s ∈ 𝓝 a} := set.ext $ λ x, by simp only [mem_interior, mem_nhds_iff, mem_set_of_eq] lemma interior_eq_nhds {s : set α} : interior s = {a | 𝓝 a ≤ 𝓟 s} := interior_eq_nhds'.trans $ by simp only [le_principal_iff] lemma mem_interior_iff_mem_nhds {s : set α} {a : α} : a ∈ interior s ↔ s ∈ 𝓝 a := by rw [interior_eq_nhds', mem_set_of_eq] @[simp] lemma interior_mem_nhds {s : set α} {a : α} : interior s ∈ 𝓝 a ↔ s ∈ 𝓝 a := ⟨λ h, mem_of_superset h interior_subset, λ h, is_open.mem_nhds is_open_interior (mem_interior_iff_mem_nhds.2 h)⟩ lemma interior_set_of_eq {p : α → Prop} : interior {x | p x} = {x | ∀ᶠ y in 𝓝 x, p y} := interior_eq_nhds' lemma is_open_set_of_eventually_nhds {p : α → Prop} : is_open {x | ∀ᶠ y in 𝓝 x, p y} := by simp only [← interior_set_of_eq, is_open_interior] lemma subset_interior_iff_nhds {s V : set α} : s ⊆ interior V ↔ ∀ x ∈ s, V ∈ 𝓝 x := show (∀ x, x ∈ s → x ∈ _) ↔ _, by simp_rw mem_interior_iff_mem_nhds lemma is_open_iff_nhds {s : set α} : is_open s ↔ ∀a∈s, 𝓝 a ≤ 𝓟 s := calc is_open s ↔ s ⊆ interior s : subset_interior_iff_is_open.symm ... ↔ (∀a∈s, 𝓝 a ≤ 𝓟 s) : by rw [interior_eq_nhds]; refl lemma is_open_iff_mem_nhds {s : set α} : is_open s ↔ ∀a∈s, s ∈ 𝓝 a := is_open_iff_nhds.trans $ forall_congr $ λ _, imp_congr_right $ λ _, le_principal_iff /-- A set `s` is open iff for every point `x` in `s` and every `y` close to `x`, `y` is in `s`. -/ lemma is_open_iff_eventually {s : set α} : is_open s ↔ ∀ x, x ∈ s → ∀ᶠ y in 𝓝 x, y ∈ s := is_open_iff_mem_nhds theorem is_open_iff_ultrafilter {s : set α} : is_open s ↔ (∀ (x ∈ s) (l : ultrafilter α), ↑l ≤ 𝓝 x → s ∈ l) := by simp_rw [is_open_iff_mem_nhds, ← mem_iff_ultrafilter] lemma is_open_singleton_iff_nhds_eq_pure (a : α) : is_open ({a} : set α) ↔ 𝓝 a = pure a := begin split, { intros h, apply le_antisymm _ (pure_le_nhds a), rw le_pure_iff, exact h.mem_nhds (mem_singleton a) }, { intros h, simp [is_open_iff_nhds, h] } end lemma mem_closure_iff_frequently {s : set α} {a : α} : a ∈ closure s ↔ ∃ᶠ x in 𝓝 a, x ∈ s := by rw [filter.frequently, filter.eventually, ← mem_interior_iff_mem_nhds, closure_eq_compl_interior_compl]; refl alias mem_closure_iff_frequently ↔ _ filter.frequently.mem_closure /-- A set `s` is closed iff for every point `x`, if there is a point `y` close to `x` that belongs to `s` then `x` is in `s`. -/ lemma is_closed_iff_frequently {s : set α} : is_closed s ↔ ∀ x, (∃ᶠ y in 𝓝 x, y ∈ s) → x ∈ s := begin rw ← closure_subset_iff_is_closed, apply forall_congr (λ x, _), rw mem_closure_iff_frequently end /-- The set of cluster points of a filter is closed. In particular, the set of limit points of a sequence is closed. -/ lemma is_closed_set_of_cluster_pt {f : filter α} : is_closed {x | cluster_pt x f} := begin simp only [cluster_pt, inf_ne_bot_iff_frequently_left, set_of_forall, imp_iff_not_or], refine is_closed_Inter (λ p, is_closed.union _ _); apply is_closed_compl_iff.2, exacts [is_open_set_of_eventually_nhds, is_open_const] end theorem mem_closure_iff_cluster_pt {s : set α} {a : α} : a ∈ closure s ↔ cluster_pt a (𝓟 s) := mem_closure_iff_frequently.trans cluster_pt_principal_iff_frequently.symm lemma mem_closure_iff_nhds_ne_bot {s : set α} : a ∈ closure s ↔ 𝓝 a ⊓ 𝓟 s ≠ ⊥ := mem_closure_iff_cluster_pt.trans ne_bot_iff lemma mem_closure_iff_nhds_within_ne_bot {s : set α} {x : α} : x ∈ closure s ↔ ne_bot (𝓝[s] x) := mem_closure_iff_cluster_pt /-- If `x` is not an isolated point of a topological space, then `{x}ᶜ` is dense in the whole space. -/ lemma dense_compl_singleton (x : α) [ne_bot (𝓝[≠] x)] : dense ({x}ᶜ : set α) := begin intro y, unfreezingI { rcases eq_or_ne y x with rfl|hne }, { rwa mem_closure_iff_nhds_within_ne_bot }, { exact subset_closure hne } end /-- If `x` is not an isolated point of a topological space, then the closure of `{x}ᶜ` is the whole space. -/ @[simp] lemma closure_compl_singleton (x : α) [ne_bot (𝓝[≠] x)] : closure {x}ᶜ = (univ : set α) := (dense_compl_singleton x).closure_eq /-- If `x` is not an isolated point of a topological space, then the interior of `{x}` is empty. -/ @[simp] lemma interior_singleton (x : α) [ne_bot (𝓝[≠] x)] : interior {x} = (∅ : set α) := interior_eq_empty_iff_dense_compl.2 (dense_compl_singleton x) lemma not_is_open_singleton (x : α) [ne_bot (𝓝[≠] x)] : ¬ is_open ({x} : set α) := dense_compl_singleton_iff_not_open.1 (dense_compl_singleton x) lemma closure_eq_cluster_pts {s : set α} : closure s = {a | cluster_pt a (𝓟 s)} := set.ext $ λ x, mem_closure_iff_cluster_pt theorem mem_closure_iff_nhds {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ 𝓝 a, (t ∩ s).nonempty := mem_closure_iff_cluster_pt.trans cluster_pt_principal_iff theorem mem_closure_iff_nhds' {s : set α} {a : α} : a ∈ closure s ↔ ∀ t ∈ 𝓝 a, ∃ y : s, ↑y ∈ t := by simp only [mem_closure_iff_nhds, set.inter_nonempty_iff_exists_right, set_coe.exists, subtype.coe_mk] theorem mem_closure_iff_comap_ne_bot {A : set α} {x : α} : x ∈ closure A ↔ ne_bot (comap (coe : A → α) (𝓝 x)) := by simp_rw [mem_closure_iff_nhds, comap_ne_bot_iff, set.inter_nonempty_iff_exists_right, set_coe.exists, subtype.coe_mk] theorem mem_closure_iff_nhds_basis' {a : α} {p : ι → Prop} {s : ι → set α} (h : (𝓝 a).has_basis p s) {t : set α} : a ∈ closure t ↔ ∀ i, p i → (s i ∩ t).nonempty := mem_closure_iff_cluster_pt.trans $ (h.cluster_pt_iff (has_basis_principal _)).trans $ by simp only [exists_prop, forall_const] theorem mem_closure_iff_nhds_basis {a : α} {p : ι → Prop} {s : ι → set α} (h : (𝓝 a).has_basis p s) {t : set α} : a ∈ closure t ↔ ∀ i, p i → ∃ y ∈ t, y ∈ s i := (mem_closure_iff_nhds_basis' h).trans $ by simp only [set.nonempty, mem_inter_iff, exists_prop, and_comm] /-- `x` belongs to the closure of `s` if and only if some ultrafilter supported on `s` converges to `x`. -/ lemma mem_closure_iff_ultrafilter {s : set α} {x : α} : x ∈ closure s ↔ ∃ (u : ultrafilter α), s ∈ u ∧ ↑u ≤ 𝓝 x := by simp [closure_eq_cluster_pts, cluster_pt, ← exists_ultrafilter_iff, and.comm] lemma is_closed_iff_cluster_pt {s : set α} : is_closed s ↔ ∀a, cluster_pt a (𝓟 s) → a ∈ s := calc is_closed s ↔ closure s ⊆ s : closure_subset_iff_is_closed.symm ... ↔ (∀a, cluster_pt a (𝓟 s) → a ∈ s) : by simp only [subset_def, mem_closure_iff_cluster_pt] lemma is_closed_iff_nhds {s : set α} : is_closed s ↔ ∀ x, (∀ U ∈ 𝓝 x, (U ∩ s).nonempty) → x ∈ s := by simp_rw [is_closed_iff_cluster_pt, cluster_pt, inf_principal_ne_bot_iff] lemma is_closed.interior_union_left {s t : set α} (h : is_closed s) : interior (s ∪ t) ⊆ s ∪ interior t := λ a ⟨u, ⟨⟨hu₁, hu₂⟩, ha⟩⟩, (classical.em (a ∈ s)).imp_right $ λ h, mem_interior.mpr ⟨u ∩ sᶜ, λ x hx, (hu₂ hx.1).resolve_left hx.2, is_open.inter hu₁ is_closed.is_open_compl, ⟨ha, h⟩⟩ lemma is_closed.interior_union_right {s t : set α} (h : is_closed t) : interior (s ∪ t) ⊆ interior s ∪ t := by simpa only [union_comm] using h.interior_union_left lemma is_open.inter_closure {s t : set α} (h : is_open s) : s ∩ closure t ⊆ closure (s ∩ t) := compl_subset_compl.mp $ by simpa only [← interior_compl, compl_inter] using is_closed.interior_union_left h.is_closed_compl lemma is_open.closure_inter {s t : set α} (h : is_open t) : closure s ∩ t ⊆ closure (s ∩ t) := by simpa only [inter_comm] using h.inter_closure lemma dense.open_subset_closure_inter {s t : set α} (hs : dense s) (ht : is_open t) : t ⊆ closure (t ∩ s) := calc t = t ∩ closure s : by rw [hs.closure_eq, inter_univ] ... ⊆ closure (t ∩ s) : ht.inter_closure lemma mem_closure_of_mem_closure_union {s₁ s₂ : set α} {x : α} (h : x ∈ closure (s₁ ∪ s₂)) (h₁ : s₁ᶜ ∈ 𝓝 x) : x ∈ closure s₂ := begin rw mem_closure_iff_nhds_ne_bot at *, rwa ← calc 𝓝 x ⊓ principal (s₁ ∪ s₂) = 𝓝 x ⊓ (principal s₁ ⊔ principal s₂) : by rw sup_principal ... = (𝓝 x ⊓ principal s₁) ⊔ (𝓝 x ⊓ principal s₂) : inf_sup_left ... = ⊥ ⊔ 𝓝 x ⊓ principal s₂ : by rw inf_principal_eq_bot.mpr h₁ ... = 𝓝 x ⊓ principal s₂ : bot_sup_eq end /-- The intersection of an open dense set with a dense set is a dense set. -/ lemma dense.inter_of_open_left {s t : set α} (hs : dense s) (ht : dense t) (hso : is_open s) : dense (s ∩ t) := λ x, (closure_minimal hso.inter_closure is_closed_closure) $ by simp [hs.closure_eq, ht.closure_eq] /-- The intersection of a dense set with an open dense set is a dense set. -/ lemma dense.inter_of_open_right {s t : set α} (hs : dense s) (ht : dense t) (hto : is_open t) : dense (s ∩ t) := inter_comm t s ▸ ht.inter_of_open_left hs hto lemma dense.inter_nhds_nonempty {s t : set α} (hs : dense s) {x : α} (ht : t ∈ 𝓝 x) : (s ∩ t).nonempty := let ⟨U, hsub, ho, hx⟩ := mem_nhds_iff.1 ht in (hs.inter_open_nonempty U ho ⟨x, hx⟩).mono $ λ y hy, ⟨hy.2, hsub hy.1⟩ lemma closure_diff {s t : set α} : closure s \ closure t ⊆ closure (s \ t) := calc closure s \ closure t = (closure t)ᶜ ∩ closure s : by simp only [diff_eq, inter_comm] ... ⊆ closure ((closure t)ᶜ ∩ s) : (is_open_compl_iff.mpr $ is_closed_closure).inter_closure ... = closure (s \ closure t) : by simp only [diff_eq, inter_comm] ... ⊆ closure (s \ t) : closure_mono $ diff_subset_diff (subset.refl s) subset_closure lemma filter.frequently.mem_of_closed {a : α} {s : set α} (h : ∃ᶠ x in 𝓝 a, x ∈ s) (hs : is_closed s) : a ∈ s := hs.closure_subset h.mem_closure lemma is_closed.mem_of_frequently_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} (hs : is_closed s) (h : ∃ᶠ x in b, f x ∈ s) (hf : tendsto f b (𝓝 a)) : a ∈ s := (hf.frequently $ show ∃ᶠ x in b, (λ y, y ∈ s) (f x), from h).mem_of_closed hs lemma is_closed.mem_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} [ne_bot b] (hs : is_closed s) (hf : tendsto f b (𝓝 a)) (h : ∀ᶠ x in b, f x ∈ s) : a ∈ s := hs.mem_of_frequently_of_tendsto h.frequently hf lemma mem_closure_of_frequently_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} (h : ∃ᶠ x in b, f x ∈ s) (hf : tendsto f b (𝓝 a)) : a ∈ closure s := filter.frequently.mem_closure $ hf.frequently h lemma mem_closure_of_tendsto {f : β → α} {b : filter β} {a : α} {s : set α} [ne_bot b] (hf : tendsto f b (𝓝 a)) (h : ∀ᶠ x in b, f x ∈ s) : a ∈ closure s := mem_closure_of_frequently_of_tendsto h.frequently hf /-- Suppose that `f` sends the complement to `s` to a single point `a`, and `l` is some filter. Then `f` tends to `a` along `l` restricted to `s` if and only if it tends to `a` along `l`. -/ lemma tendsto_inf_principal_nhds_iff_of_forall_eq {f : β → α} {l : filter β} {s : set β} {a : α} (h : ∀ x ∉ s, f x = a) : tendsto f (l ⊓ 𝓟 s) (𝓝 a) ↔ tendsto f l (𝓝 a) := begin rw [tendsto_iff_comap, tendsto_iff_comap], replace h : 𝓟 sᶜ ≤ comap f (𝓝 a), { rintros U ⟨t, ht, htU⟩ x hx, have : f x ∈ t, from (h x hx).symm ▸ mem_of_mem_nhds ht, exact htU this }, refine ⟨λ h', _, le_trans inf_le_left⟩, have := sup_le h' h, rw [sup_inf_right, sup_principal, union_compl_self, principal_univ, inf_top_eq, sup_le_iff] at this, exact this.1 end /-! ### Limits of filters in topological spaces -/ section lim /-- If `f` is a filter, then `Lim f` is a limit of the filter, if it exists. -/ noncomputable def Lim [nonempty α] (f : filter α) : α := epsilon $ λa, f ≤ 𝓝 a /-- If `f` is a filter satisfying `ne_bot f`, then `Lim' f` is a limit of the filter, if it exists. -/ def Lim' (f : filter α) [ne_bot f] : α := @Lim _ _ (nonempty_of_ne_bot f) f /-- If `F` is an ultrafilter, then `filter.ultrafilter.Lim F` is a limit of the filter, if it exists. Note that dot notation `F.Lim` can be used for `F : ultrafilter α`. -/ def ultrafilter.Lim : ultrafilter α → α := λ F, Lim' F /-- If `f` is a filter in `β` and `g : β → α` is a function, then `lim f` is a limit of `g` at `f`, if it exists. -/ noncomputable def lim [nonempty α] (f : filter β) (g : β → α) : α := Lim (f.map g) /-- If a filter `f` is majorated by some `𝓝 a`, then it is majorated by `𝓝 (Lim f)`. We formulate this lemma with a `[nonempty α]` argument of `Lim` derived from `h` to make it useful for types without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ lemma le_nhds_Lim {f : filter α} (h : ∃a, f ≤ 𝓝 a) : f ≤ 𝓝 (@Lim _ _ (nonempty_of_exists h) f) := epsilon_spec h /-- If `g` tends to some `𝓝 a` along `f`, then it tends to `𝓝 (lim f g)`. We formulate this lemma with a `[nonempty α]` argument of `lim` derived from `h` to make it useful for types without a `[nonempty α]` instance. Because of the built-in proof irrelevance, Lean will unify this instance with any other instance. -/ lemma tendsto_nhds_lim {f : filter β} {g : β → α} (h : ∃ a, tendsto g f (𝓝 a)) : tendsto g f (𝓝 $ @lim _ _ _ (nonempty_of_exists h) f g) := le_nhds_Lim h end lim end topological_space /-! ### Continuity -/ section continuous variables {α : Type*} {β : Type*} {γ : Type*} {δ : Type*} variables [topological_space α] [topological_space β] [topological_space γ] open_locale topological_space /-- A function between topological spaces is continuous if the preimage of every open set is open. Registered as a structure to make sure it is not unfolded by Lean. -/ structure continuous (f : α → β) : Prop := (is_open_preimage : ∀s, is_open s → is_open (f ⁻¹' s)) lemma continuous_def {f : α → β} : continuous f ↔ (∀s, is_open s → is_open (f ⁻¹' s)) := ⟨λ hf s hs, hf.is_open_preimage s hs, λ h, ⟨h⟩⟩ lemma is_open.preimage {f : α → β} (hf : continuous f) {s : set β} (h : is_open s) : is_open (f ⁻¹' s) := hf.is_open_preimage s h lemma continuous.congr {f g : α → β} (h : continuous f) (h' : ∀ x, f x = g x) : continuous g := by { convert h, ext, rw h' } /-- A function between topological spaces is continuous at a point `x₀` if `f x` tends to `f x₀` when `x` tends to `x₀`. -/ def continuous_at (f : α → β) (x : α) := tendsto f (𝓝 x) (𝓝 (f x)) lemma continuous_at.tendsto {f : α → β} {x : α} (h : continuous_at f x) : tendsto f (𝓝 x) (𝓝 (f x)) := h lemma continuous_at_def {f : α → β} {x : α} : continuous_at f x ↔ ∀ A ∈ 𝓝 (f x), f ⁻¹' A ∈ 𝓝 x := iff.rfl lemma continuous_at_congr {f g : α → β} {x : α} (h : f =ᶠ[𝓝 x] g) : continuous_at f x ↔ continuous_at g x := by simp only [continuous_at, tendsto_congr' h, h.eq_of_nhds] lemma continuous_at.congr {f g : α → β} {x : α} (hf : continuous_at f x) (h : f =ᶠ[𝓝 x] g) : continuous_at g x := (continuous_at_congr h).1 hf lemma continuous_at.preimage_mem_nhds {f : α → β} {x : α} {t : set β} (h : continuous_at f x) (ht : t ∈ 𝓝 (f x)) : f ⁻¹' t ∈ 𝓝 x := h ht lemma eventually_eq_zero_nhds {M₀} [has_zero M₀] {a : α} {f : α → M₀} : f =ᶠ[𝓝 a] 0 ↔ a ∉ closure (function.support f) := by rw [← mem_compl_iff, ← interior_compl, mem_interior_iff_mem_nhds, function.compl_support]; refl lemma cluster_pt.map {x : α} {la : filter α} {lb : filter β} (H : cluster_pt x la) {f : α → β} (hfc : continuous_at f x) (hf : tendsto f la lb) : cluster_pt (f x) lb := ⟨ne_bot_of_le_ne_bot ((map_ne_bot_iff f).2 H).ne $ hfc.tendsto.inf hf⟩ /-- See also `interior_preimage_subset_preimage_interior`. -/ lemma preimage_interior_subset_interior_preimage {f : α → β} {s : set β} (hf : continuous f) : f⁻¹' (interior s) ⊆ interior (f⁻¹' s) := interior_maximal (preimage_mono interior_subset) (is_open_interior.preimage hf) lemma continuous_id : continuous (id : α → α) := continuous_def.2 $ assume s h, h lemma continuous.comp {g : β → γ} {f : α → β} (hg : continuous g) (hf : continuous f) : continuous (g ∘ f) := continuous_def.2 $ assume s h, (h.preimage hg).preimage hf lemma continuous.iterate {f : α → α} (h : continuous f) (n : ℕ) : continuous (f^[n]) := nat.rec_on n continuous_id (λ n ihn, ihn.comp h) lemma continuous_at.comp {g : β → γ} {f : α → β} {x : α} (hg : continuous_at g (f x)) (hf : continuous_at f x) : continuous_at (g ∘ f) x := hg.comp hf lemma continuous.tendsto {f : α → β} (hf : continuous f) (x) : tendsto f (𝓝 x) (𝓝 (f x)) := ((nhds_basis_opens x).tendsto_iff $ nhds_basis_opens $ f x).2 $ λ t ⟨hxt, ht⟩, ⟨f ⁻¹' t, ⟨hxt, ht.preimage hf⟩, subset.refl _⟩ /-- A version of `continuous.tendsto` that allows one to specify a simpler form of the limit. E.g., one can write `continuous_exp.tendsto' 0 1 exp_zero`. -/ lemma continuous.tendsto' {f : α → β} (hf : continuous f) (x : α) (y : β) (h : f x = y) : tendsto f (𝓝 x) (𝓝 y) := h ▸ hf.tendsto x lemma continuous.continuous_at {f : α → β} {x : α} (h : continuous f) : continuous_at f x := h.tendsto x lemma continuous_iff_continuous_at {f : α → β} : continuous f ↔ ∀ x, continuous_at f x := ⟨continuous.tendsto, assume hf : ∀x, tendsto f (𝓝 x) (𝓝 (f x)), continuous_def.2 $ assume s, assume hs : is_open s, have ∀a, f a ∈ s → s ∈ 𝓝 (f a), from λ a ha, is_open.mem_nhds hs ha, show is_open (f ⁻¹' s), from is_open_iff_nhds.2 $ λ a ha, le_principal_iff.2 $ hf _ (this a ha)⟩ lemma continuous_at_const {x : α} {b : β} : continuous_at (λ a:α, b) x := tendsto_const_nhds lemma continuous_const {b : β} : continuous (λa:α, b) := continuous_iff_continuous_at.mpr $ assume a, continuous_at_const lemma filter.eventually_eq.continuous_at {x : α} {f : α → β} {y : β} (h : f =ᶠ[𝓝 x] (λ _, y)) : continuous_at f x := (continuous_at_congr h).2 tendsto_const_nhds lemma continuous_of_const {f : α → β} (h : ∀ x y, f x = f y) : continuous f := continuous_iff_continuous_at.mpr $ λ x, filter.eventually_eq.continuous_at $ eventually_of_forall (λ y, h y x) lemma continuous_at_id {x : α} : continuous_at id x := continuous_id.continuous_at lemma continuous_at.iterate {f : α → α} {x : α} (hf : continuous_at f x) (hx : f x = x) (n : ℕ) : continuous_at (f^[n]) x := nat.rec_on n continuous_at_id $ λ n ihn, show continuous_at (f^[n] ∘ f) x, from continuous_at.comp (hx.symm ▸ ihn) hf lemma continuous_iff_is_closed {f : α → β} : continuous f ↔ (∀s, is_closed s → is_closed (f ⁻¹' s)) := ⟨assume hf s hs, by simpa using (continuous_def.1 hf sᶜ hs.is_open_compl).is_closed_compl, assume hf, continuous_def.2 $ assume s, by rw [←is_closed_compl_iff, ←is_closed_compl_iff]; exact hf _⟩ lemma is_closed.preimage {f : α → β} (hf : continuous f) {s : set β} (h : is_closed s) : is_closed (f ⁻¹' s) := continuous_iff_is_closed.mp hf s h lemma mem_closure_image {f : α → β} {x : α} {s : set α} (hf : continuous_at f x) (hx : x ∈ closure s) : f x ∈ closure (f '' s) := mem_closure_of_frequently_of_tendsto ((mem_closure_iff_frequently.1 hx).mono (λ x, mem_image_of_mem _)) hf lemma continuous_at_iff_ultrafilter {f : α → β} {x} : continuous_at f x ↔ ∀ g : ultrafilter α, ↑g ≤ 𝓝 x → tendsto f g (𝓝 (f x)) := tendsto_iff_ultrafilter f (𝓝 x) (𝓝 (f x)) lemma continuous_iff_ultrafilter {f : α → β} : continuous f ↔ ∀ x (g : ultrafilter α), ↑g ≤ 𝓝 x → tendsto f g (𝓝 (f x)) := by simp only [continuous_iff_continuous_at, continuous_at_iff_ultrafilter] lemma continuous.closure_preimage_subset {f : α → β} (hf : continuous f) (t : set β) : closure (f ⁻¹' t) ⊆ f ⁻¹' (closure t) := begin rw ← (is_closed_closure.preimage hf).closure_eq, exact closure_mono (preimage_mono subset_closure), end lemma continuous.frontier_preimage_subset {f : α → β} (hf : continuous f) (t : set β) : frontier (f ⁻¹' t) ⊆ f ⁻¹' (frontier t) := diff_subset_diff (hf.closure_preimage_subset t) (preimage_interior_subset_interior_preimage hf) /-! ### Continuity and partial functions -/ /-- Continuity of a partial function -/ def pcontinuous (f : α →. β) := ∀ s, is_open s → is_open (f.preimage s) lemma open_dom_of_pcontinuous {f : α →. β} (h : pcontinuous f) : is_open f.dom := by rw [←pfun.preimage_univ]; exact h _ is_open_univ lemma pcontinuous_iff' {f : α →. β} : pcontinuous f ↔ ∀ {x y} (h : y ∈ f x), ptendsto' f (𝓝 x) (𝓝 y) := begin split, { intros h x y h', simp only [ptendsto'_def, mem_nhds_iff], rintros s ⟨t, tsubs, opent, yt⟩, exact ⟨f.preimage t, pfun.preimage_mono _ tsubs, h _ opent, ⟨y, yt, h'⟩⟩ }, intros hf s os, rw is_open_iff_nhds, rintros x ⟨y, ys, fxy⟩ t, rw [mem_principal], assume h : f.preimage s ⊆ t, change t ∈ 𝓝 x, apply mem_of_superset _ h, have h' : ∀ s ∈ 𝓝 y, f.preimage s ∈ 𝓝 x, { intros s hs, have : ptendsto' f (𝓝 x) (𝓝 y) := hf fxy, rw ptendsto'_def at this, exact this s hs }, show f.preimage s ∈ 𝓝 x, apply h', rw mem_nhds_iff, exact ⟨s, set.subset.refl _, os, ys⟩ end /-- If a continuous map `f` maps `s` to `t`, then it maps `closure s` to `closure t`. -/ lemma set.maps_to.closure {s : set α} {t : set β} {f : α → β} (h : maps_to f s t) (hc : continuous f) : maps_to f (closure s) (closure t) := begin simp only [maps_to, mem_closure_iff_cluster_pt], exact λ x hx, hx.map hc.continuous_at (tendsto_principal_principal.2 h) end lemma image_closure_subset_closure_image {f : α → β} {s : set α} (h : continuous f) : f '' closure s ⊆ closure (f '' s) := ((maps_to_image f s).closure h).image_subset lemma closure_subset_preimage_closure_image {f : α → β} {s : set α} (h : continuous f) : closure s ⊆ f ⁻¹' (closure (f '' s)) := by { rw ← set.image_subset_iff, exact image_closure_subset_closure_image h } lemma map_mem_closure {s : set α} {t : set β} {f : α → β} {a : α} (hf : continuous f) (ha : a ∈ closure s) (ht : maps_to f s t) : f a ∈ closure t := ht.closure hf ha /-- If a continuous map `f` maps `s` to a closed set `t`, then it maps `closure s` to `t`. -/ lemma set.maps_to.closure_left {s : set α} {t : set β} {f : α → β} (h : maps_to f s t) (hc : continuous f) (ht : is_closed t) : maps_to f (closure s) t := ht.closure_eq ▸ h.closure hc /-! ### Function with dense range -/ section dense_range variables {κ ι : Type*} (f : κ → β) (g : β → γ) /-- `f : ι → β` has dense range if its range (image) is a dense subset of β. -/ def dense_range := dense (range f) variables {f} /-- A surjective map has dense range. -/ lemma function.surjective.dense_range (hf : function.surjective f) : dense_range f := λ x, by simp [hf.range_eq] lemma dense_range_id : dense_range (id : α → α) := function.surjective.dense_range function.surjective_id lemma dense_range_iff_closure_range : dense_range f ↔ closure (range f) = univ := dense_iff_closure_eq lemma dense_range.closure_range (h : dense_range f) : closure (range f) = univ := h.closure_eq lemma dense.dense_range_coe {s : set α} (h : dense s) : dense_range (coe : s → α) := by simpa only [dense_range, subtype.range_coe_subtype] lemma continuous.range_subset_closure_image_dense {f : α → β} (hf : continuous f) {s : set α} (hs : dense s) : range f ⊆ closure (f '' s) := by { rw [← image_univ, ← hs.closure_eq], exact image_closure_subset_closure_image hf } /-- The image of a dense set under a continuous map with dense range is a dense set. -/ lemma dense_range.dense_image {f : α → β} (hf' : dense_range f) (hf : continuous f) {s : set α} (hs : dense s) : dense (f '' s) := (hf'.mono $ hf.range_subset_closure_image_dense hs).of_closure /-- If `f` has dense range and `s` is an open set in the codomain of `f`, then the image of the preimage of `s` under `f` is dense in `s`. -/ lemma dense_range.subset_closure_image_preimage_of_is_open (hf : dense_range f) {s : set β} (hs : is_open s) : s ⊆ closure (f '' (f ⁻¹' s)) := by { rw image_preimage_eq_inter_range, exact hf.open_subset_closure_inter hs } /-- If a continuous map with dense range maps a dense set to a subset of `t`, then `t` is a dense set. -/ lemma dense_range.dense_of_maps_to {f : α → β} (hf' : dense_range f) (hf : continuous f) {s : set α} (hs : dense s) {t : set β} (ht : maps_to f s t) : dense t := (hf'.dense_image hf hs).mono ht.image_subset /-- Composition of a continuous map with dense range and a function with dense range has dense range. -/ lemma dense_range.comp {g : β → γ} {f : κ → β} (hg : dense_range g) (hf : dense_range f) (cg : continuous g) : dense_range (g ∘ f) := by { rw [dense_range, range_comp], exact hg.dense_image cg hf } lemma dense_range.nonempty_iff (hf : dense_range f) : nonempty κ ↔ nonempty β := range_nonempty_iff_nonempty.symm.trans hf.nonempty_iff lemma dense_range.nonempty [h : nonempty β] (hf : dense_range f) : nonempty κ := hf.nonempty_iff.mpr h /-- Given a function `f : α → β` with dense range and `b : β`, returns some `a : α`. -/ def dense_range.some (hf : dense_range f) (b : β) : κ := classical.choice $ hf.nonempty_iff.mpr ⟨b⟩ lemma dense_range.exists_mem_open (hf : dense_range f) {s : set β} (ho : is_open s) (hs : s.nonempty) : ∃ a, f a ∈ s := exists_range_iff.1 $ hf.exists_mem_open ho hs lemma dense_range.mem_nhds {f : κ → β} (h : dense_range f) {b : β} {U : set β} (U_in : U ∈ 𝓝 b) : ∃ a, f a ∈ U := let ⟨a, ha⟩ := h.exists_mem_open is_open_interior ⟨b, mem_interior_iff_mem_nhds.2 U_in⟩ in ⟨a, interior_subset ha⟩ end dense_range end continuous /-- The library contains many lemmas stating that functions/operations are continuous. There are many ways to formulate the continuity of operations. Some are more convenient than others. Note: for the most part this note also applies to other properties (`measurable`, `differentiable`, `continuous_on`, ...). ### The traditional way As an example, let's look at addition `(+) : M → M → M`. We can state that this is continuous in different definitionally equal ways (omitting some typing information) * `continuous (λ p, p.1 + p.2)`; * `continuous (function.uncurry (+))`; * `continuous ↿(+)`. (`↿` is notation for recursively uncurrying a function) However, lemmas with this conclusion are not nice to use in practice because 1. They confuse the elaborator. The following two examples fail, because of limitations in the elaboration process. ``` variables {M : Type*} [has_add M] [topological_space M] [has_continuous_add M] example : continuous (λ x : M, x + x) := continuous_add.comp _ example : continuous (λ x : M, x + x) := continuous_add.comp (continuous_id.prod_mk continuous_id) ``` The second is a valid proof, which is accepted if you write it as `continuous_add.comp (continuous_id.prod_mk continuous_id : _)` 2. If the operation has more than 2 arguments, they are impractical to use, because in your application the arguments in the domain might be in a different order or associated differently. ### The convenient way A much more convenient way to write continuity lemmas is like `continuous.add`: ``` continuous.add {f g : X → M} (hf : continuous f) (hg : continuous g) : continuous (λ x, f x + g x) ``` The conclusion can be `continuous (f + g)`, which is definitionally equal. This has the following advantages * It supports projection notation, so is shorter to write. * `continuous.add _ _` is recognized correctly by the elaborator and gives useful new goals. * It works generally, since the domain is a variable. As an example for an unary operation, we have `continuous.neg`. ``` continuous.neg {f : α → G} (hf : continuous f) : continuous (λ x, -f x) ``` For unary functions, the elaborator is not confused when applying the traditional lemma (like `continuous_neg`), but it's still convenient to have the short version available (compare `hf.neg.neg.neg` with `continuous_neg.comp $ continuous_neg.comp $ continuous_neg.comp hf`). As a harder example, consider an operation of the following type: ``` def strans {x : F} (γ γ' : path x x) (t₀ : I) : path x x ``` The precise definition is not important, only its type. The correct continuity principle for this operation is something like this: ``` {f : X → F} {γ γ' : ∀ x, path (f x) (f x)} {t₀ s : X → I} (hγ : continuous ↿γ) (hγ' : continuous ↿γ') (ht : continuous t₀) (hs : continuous s) : continuous (λ x, strans (γ x) (γ' x) (t x) (s x)) ``` Note that *all* arguments of `strans` are indexed over `X`, even the basepoint `x`, and the last argument `s` that arises since `path x x` has a coercion to `I → F`. The paths `γ` and `γ'` (which are unary functions from `I`) become binary functions in the continuity lemma. ### Summary * Make sure that your continuity lemmas are stated in the most general way, and in a convenient form. That means that: - The conclusion has a variable `X` as domain (not something like `Y × Z`); - Wherever possible, all point arguments `c : Y` are replaced by functions `c : X → Y`; - All `n`-ary function arguments are replaced by `n+1`-ary functions (`f : Y → Z` becomes `f : X → Y → Z`); - All (relevant) arguments have continuity assumptions, and perhaps there are additional assumptions needed to make the operation continuous; - The function in the conclusion is fully applied. * These remarks are mostly about the format of the *conclusion* of a continuity lemma. In assumptions it's fine to state that a function with more than 1 argument is continuous using `↿` or `function.uncurry`. ### Functions with discontinuities In some cases, you want to work with discontinuous functions, and in certain expressions they are still continuous. For example, consider the fractional part of a number, `fract : ℝ → ℝ`. In this case, you want to add conditions to when a function involving `fract` is continuous, so you get something like this: (assumption `hf` could be weakened, but the important thing is the shape of the conclusion) ``` lemma continuous_on.comp_fract {X Y : Type*} [topological_space X] [topological_space Y] {f : X → ℝ → Y} {g : X → ℝ} (hf : continuous ↿f) (hg : continuous g) (h : ∀ s, f s 0 = f s 1) : continuous (λ x, f x (fract (g x))) ``` With `continuous_at` you can be even more precise about what to prove in case of discontinuities, see e.g. `continuous_at.comp_div_cases`. -/ library_note "continuity lemma statement"
b9050b25d27d25083af42bc400fb2f4a82bed5fb
ac49064e8a9a038e07cf5574b4fccd8a70d115c8
/hott/types/prod.hlean
242dadb6a60f830d36a160353a772a1fcba86887
[ "Apache-2.0" ]
permissive
Bolt64/lean2
7c75016729569e04a3f403c7a4fc7c1de4377c9d
75fd8162488214a959dbe3303a185cbbb83f60f9
refs/heads/master
1,611,290,445,156
1,493,763,922,000
1,493,763,922,000
81,566,307
0
0
null
1,486,732,167,000
1,486,732,167,000
null
UTF-8
Lean
false
false
10,529
hlean
/- 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, Jakob von Raumer Ported from Coq HoTT Theorems about products -/ open eq equiv is_equiv is_trunc prod prod.ops unit variables {A A' B B' C D : Type} {P Q : A → Type} {a a' a'' : A} {b b₁ b₂ b' b'' : B} {u v w : A × B} namespace prod /- Paths in a product space -/ protected definition eta [unfold 3] (u : A × B) : (pr₁ u, pr₂ u) = u := by cases u; reflexivity definition pair_eq [unfold 7 8] (pa : a = a') (pb : b = b') : (a, b) = (a', b') := ap011 prod.mk pa pb definition prod_eq [unfold 3 4 5 6] (H₁ : u.1 = v.1) (H₂ : u.2 = v.2) : u = v := by cases u; cases v; exact pair_eq H₁ H₂ definition eq_pr1 [unfold 5] (p : u = v) : u.1 = v.1 := ap pr1 p definition eq_pr2 [unfold 5] (p : u = v) : u.2 = v.2 := ap pr2 p namespace ops postfix `..1`:(max+1) := eq_pr1 postfix `..2`:(max+1) := eq_pr2 end ops open ops protected definition ap_pr1 (p : u = v) : ap pr1 p = p..1 := idp protected definition ap_pr2 (p : u = v) : ap pr2 p = p..2 := idp definition pair_prod_eq (p : u.1 = v.1) (q : u.2 = v.2) : ((prod_eq p q)..1, (prod_eq p q)..2) = (p, q) := by induction u; induction v; esimp at *; induction p; induction q; reflexivity definition prod_eq_pr1 (p : u.1 = v.1) (q : u.2 = v.2) : (prod_eq p q)..1 = p := (pair_prod_eq p q)..1 definition prod_eq_pr2 (p : u.1 = v.1) (q : u.2 = v.2) : (prod_eq p q)..2 = q := (pair_prod_eq p q)..2 definition prod_eq_eta (p : u = v) : prod_eq (p..1) (p..2) = p := by induction p; induction u; reflexivity -- the uncurried version of prod_eq. We will prove that this is an equivalence definition prod_eq_unc (H : u.1 = v.1 × u.2 = v.2) : u = v := by cases H with H₁ H₂;exact prod_eq H₁ H₂ definition pair_prod_eq_unc : Π(pq : u.1 = v.1 × u.2 = v.2), ((prod_eq_unc pq)..1, (prod_eq_unc pq)..2) = pq | pair_prod_eq_unc (pq₁, pq₂) := pair_prod_eq pq₁ pq₂ definition prod_eq_unc_pr1 (pq : u.1 = v.1 × u.2 = v.2) : (prod_eq_unc pq)..1 = pq.1 := (pair_prod_eq_unc pq)..1 definition prod_eq_unc_pr2 (pq : u.1 = v.1 × u.2 = v.2) : (prod_eq_unc pq)..2 = pq.2 := (pair_prod_eq_unc pq)..2 definition prod_eq_unc_eta (p : u = v) : prod_eq_unc (p..1, p..2) = p := prod_eq_eta p definition is_equiv_prod_eq [instance] [constructor] (u v : A × B) : is_equiv (prod_eq_unc : u.1 = v.1 × u.2 = v.2 → u = v) := adjointify prod_eq_unc (λp, (p..1, p..2)) prod_eq_unc_eta pair_prod_eq_unc definition prod_eq_equiv [constructor] (u v : A × B) : (u = v) ≃ (u.1 = v.1 × u.2 = v.2) := (equiv.mk prod_eq_unc _)⁻¹ᵉ definition ap_prod_mk_left (p : a = a') : ap (λa, prod.mk a b) p = prod_eq p idp := ap_eq_ap011_left prod.mk p b definition ap_prod_mk_right (p : b = b') : ap (λb, prod.mk a b) p = prod_eq idp p := ap_eq_ap011_right prod.mk a p /- Groupoid structure -/ definition prod_eq_inv (p : a = a') (q : b = b') : (prod_eq p q)⁻¹ = prod_eq p⁻¹ q⁻¹ := by cases p; cases q; reflexivity definition prod_eq_concat (p : a = a') (p' : a' = a'') (q : b = b') (q' : b' = b'') : prod_eq p q ⬝ prod_eq p' q' = prod_eq (p ⬝ p') (q ⬝ q') := by cases p; cases q; cases p'; cases q'; reflexivity definition prod_eq_concat_idp (p : a = a') (q : b = b') : prod_eq p idp ⬝ prod_eq idp q = prod_eq p q := by cases p; cases q; reflexivity /- Transport -/ definition prod_transport (p : a = a') (u : P a × Q a) : p ▸ u = (p ▸ u.1, p ▸ u.2) := by induction p; induction u; reflexivity definition prod_eq_transport (p : a = a') (q : b = b') {R : A × B → Type} (r : R (a, b)) : (prod_eq p q) ▸ r = p ▸ q ▸ r := by induction p; induction q; reflexivity /- Pathovers -/ definition etao (p : a = a') (bc : P a × Q a) : bc =[p] (p ▸ bc.1, p ▸ bc.2) := by induction p; induction bc; apply idpo definition prod_pathover (p : a = a') (u : P a × Q a) (v : P a' × Q a') (r : u.1 =[p] v.1) (s : u.2 =[p] v.2) : u =[p] v := begin induction u, induction v, esimp at *, induction r, induction s using idp_rec_on, apply idpo end /- TODO: * define the projections from the type u =[p] v * show that the uncurried version of prod_pathover is an equivalence -/ /- Functorial action -/ variables (f : A → A') (g : B → B') definition prod_functor [unfold 7] (u : A × B) : A' × B' := (f u.1, g u.2) definition ap_prod_functor (p : u.1 = v.1) (q : u.2 = v.2) : ap (prod_functor f g) (prod_eq p q) = prod_eq (ap f p) (ap g q) := by induction u; induction v; esimp at *; induction p; induction q; reflexivity /- Helpers for functions of two arguments -/ definition ap_diagonal {a a' : A} (p : a = a') : ap (λx : A, (x,x)) p = prod_eq p p := by cases p; constructor definition ap_binary (m : A → B → C) (p : a = a') (q : b = b') : ap (λz : A × B, m z.1 z.2) (prod_eq p q) = ap (m a) q ⬝ ap (λx : A, m x b') p := by cases p; cases q; constructor definition ap_prod_elim {A B C : Type} {a a' : A} {b b' : B} (m : A → B → C) (p : a = a') (q : b = b') : ap (prod.rec m) (prod_eq p q) = ap (m a) q ⬝ ap (λx : A, m x b') p := by cases p; cases q; constructor definition ap_prod_elim_idp {A B C : Type} {a a' : A} (m : A → B → C) (p : a = a') (b : B) : ap (prod.rec m) (prod_eq p idp) = ap (λx : A, m x b) p := ap_prod_elim m p idp ⬝ !idp_con /- Equivalences -/ definition is_equiv_prod_functor [instance] [constructor] [H : is_equiv f] [H : is_equiv g] : is_equiv (prod_functor f g) := begin apply adjointify _ (prod_functor f⁻¹ g⁻¹), intro u, induction u, rewrite [▸*,right_inv f,right_inv g], intro u, induction u, rewrite [▸*,left_inv f,left_inv g], end definition prod_equiv_prod_of_is_equiv [constructor] [H : is_equiv f] [H : is_equiv g] : A × B ≃ A' × B' := equiv.mk (prod_functor f g) _ definition prod_equiv_prod [constructor] (f : A ≃ A') (g : B ≃ B') : A × B ≃ A' × B' := equiv.mk (prod_functor f g) _ -- rename definition prod_equiv_prod_left [constructor] (g : B ≃ B') : A × B ≃ A × B' := prod_equiv_prod equiv.rfl g -- rename definition prod_equiv_prod_right [constructor] (f : A ≃ A') : A × B ≃ A' × B := prod_equiv_prod f equiv.rfl /- Symmetry -/ definition is_equiv_flip [instance] [constructor] (A B : Type) : is_equiv (flip : A × B → B × A) := adjointify flip flip (λu, destruct u (λb a, idp)) (λu, destruct u (λa b, idp)) definition prod_comm_equiv [constructor] (A B : Type) : A × B ≃ B × A := equiv.mk flip _ /- Associativity -/ definition prod_assoc_equiv [constructor] (A B C : Type) : A × (B × C) ≃ (A × B) × C := begin fapply equiv.MK, { intro z, induction z with a z, induction z with b c, exact (a, b, c)}, { intro z, induction z with z c, induction z with a b, exact (a, (b, c))}, { intro z, induction z with z c, induction z with a b, reflexivity}, { intro z, induction z with a z, induction z with b c, reflexivity}, end definition prod_contr_equiv [constructor] (A B : Type) [H : is_contr B] : A × B ≃ A := equiv.MK pr1 (λx, (x, !center)) (λx, idp) (λx, by cases x with a b; exact pair_eq idp !center_eq) definition prod_unit_equiv [constructor] (A : Type) : A × unit ≃ A := !prod_contr_equiv definition prod_empty_equiv (A : Type) : A × empty ≃ empty := begin fapply equiv.MK, { intro x, cases x with a e, cases e }, { intro e, cases e }, { intro e, cases e }, { intro x, cases x with a e, cases e } end /- Universal mapping properties -/ definition is_equiv_prod_rec [instance] [constructor] (P : A × B → Type) : is_equiv (prod.rec : (Πa b, P (a, b)) → Πu, P u) := adjointify _ (λg a b, g (a, b)) (λg, eq_of_homotopy (λu, by induction u;reflexivity)) (λf, idp) definition equiv_prod_rec [constructor] (P : A × B → Type) : (Πa b, P (a, b)) ≃ (Πu, P u) := equiv.mk prod.rec _ definition imp_imp_equiv_prod_imp [constructor] (A B C : Type) : (A → B → C) ≃ (A × B → C) := !equiv_prod_rec definition prod_corec_unc [unfold 4] {P Q : A → Type} (u : (Πa, P a) × (Πa, Q a)) (a : A) : P a × Q a := (u.1 a, u.2 a) definition is_equiv_prod_corec [constructor] (P Q : A → Type) : is_equiv (prod_corec_unc : (Πa, P a) × (Πa, Q a) → Πa, P a × Q a) := adjointify _ (λg, (λa, (g a).1, λa, (g a).2)) (by intro g; apply eq_of_homotopy; intro a; esimp; induction (g a); reflexivity) (by intro h; induction h with f g; reflexivity) definition equiv_prod_corec [constructor] (P Q : A → Type) : ((Πa, P a) × (Πa, Q a)) ≃ (Πa, P a × Q a) := equiv.mk _ !is_equiv_prod_corec definition imp_prod_imp_equiv_imp_prod [constructor] (A B C : Type) : (A → B) × (A → C) ≃ (A → (B × C)) := !equiv_prod_corec theorem is_trunc_prod (A B : Type) (n : trunc_index) [HA : is_trunc n A] [HB : is_trunc n B] : is_trunc n (A × B) := begin revert A B HA HB, induction n with n IH, all_goals intro A B HA HB, { fapply is_contr.mk, exact (!center, !center), intro u, apply prod_eq, all_goals apply center_eq}, { apply is_trunc_succ_intro, intro u v, apply is_trunc_equiv_closed_rev, apply prod_eq_equiv, exact IH _ _ _ _} end end prod attribute prod.is_trunc_prod [instance] [priority 1510] namespace prod /- pointed products -/ open pointed definition pointed_prod [instance] [constructor] (A B : Type) [H1 : pointed A] [H2 : pointed B] : pointed (A × B) := pointed.mk (pt,pt) definition pprod [constructor] (A B : Type*) : Type* := pointed.mk' (A × B) infixr ` ×* `:35 := pprod definition ppr1 [constructor] {A B : Type*} : A ×* B →* A := pmap.mk pr1 idp definition ppr2 [constructor] {A B : Type*} : A ×* B →* B := pmap.mk pr2 idp definition tprod [constructor] {n : trunc_index} (A B : n-Type) : n-Type := trunctype.mk (A × B) _ infixr `×t`:30 := tprod definition ptprod [constructor] {n : ℕ₋₂} (A B : n-Type*) : n-Type* := ptrunctype.mk' n (A × B) end prod
b305cb81d013ab4ead54de9cab1f9ef6bcfd1cc3
d9d511f37a523cd7659d6f573f990e2a0af93c6f
/src/linear_algebra/finsupp_vector_space.lean
3ff281847f97531bdecabec51e22e906ca86f957
[ "Apache-2.0" ]
permissive
hikari0108/mathlib
b7ea2b7350497ab1a0b87a09d093ecc025a50dfa
a9e7d333b0cfd45f13a20f7b96b7d52e19fa2901
refs/heads/master
1,690,483,608,260
1,631,541,580,000
1,631,541,580,000
null
0
0
null
null
null
null
UTF-8
Lean
false
false
7,956
lean
/- Copyright (c) 2019 Johannes Hölzl. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Johannes Hölzl -/ import data.mv_polynomial import linear_algebra.dimension import linear_algebra.direct_sum.finsupp import linear_algebra.finite_dimensional import linear_algebra.std_basis /-! # Linear structures on function with finite support `ι →₀ M` This file contains results on the `R`-module structure on functions of finite support from a type `ι` to an `R`-module `M`, in particular in the case that `R` is a field. Furthermore, it contains some facts about isomorphisms of vector spaces from equality of dimension as well as the cardinality of finite dimensional vector spaces. ## TODO Move the second half of this file to more appropriate other files. -/ noncomputable theory local attribute [instance, priority 100] classical.prop_decidable open set linear_map submodule namespace finsupp section ring variables {R : Type*} {M : Type*} {ι : Type*} variables [ring R] [add_comm_group M] [module R M] lemma linear_independent_single {φ : ι → Type*} {f : Π ι, φ ι → M} (hf : ∀i, linear_independent R (f i)) : linear_independent R (λ ix : Σ i, φ i, single ix.1 (f ix.1 ix.2)) := begin apply @linear_independent_Union_finite R _ _ _ _ ι φ (λ i x, single i (f i x)), { assume i, have h_disjoint : disjoint (span R (range (f i))) (ker (lsingle i)), { rw ker_lsingle, exact disjoint_bot_right }, apply (hf i).map h_disjoint }, { intros i t ht hit, refine (disjoint_lsingle_lsingle {i} t (disjoint_singleton_left.2 hit)).mono _ _, { rw span_le, simp only [supr_singleton], rw range_coe, apply range_comp_subset_range }, { refine supr_le_supr (λ i, supr_le_supr _), intros hi, rw span_le, rw range_coe, apply range_comp_subset_range } } end open linear_map submodule /-- The basis on `ι →₀ M` with basis vectors `λ ⟨i, x⟩, single i (b i x)`. -/ protected def basis {φ : ι → Type*} (b : ∀ i, basis (φ i) R M) : basis (Σ i, φ i) R (ι →₀ M) := basis.of_repr { to_fun := λ g, { to_fun := λ ix, (b ix.1).repr (g ix.1) ix.2, support := g.support.sigma (λ i, ((b i).repr (g i)).support), mem_support_to_fun := λ ix, by { simp only [finset.mem_sigma, mem_support_iff, and_iff_right_iff_imp, ne.def], intros b hg, simpa [hg] using b } }, inv_fun := λ g, { to_fun := λ i, (b i).repr.symm (g.comap_domain _ (set.inj_on_of_injective sigma_mk_injective _)), support := g.support.image sigma.fst, mem_support_to_fun := λ i, by { rw [ne.def, ← (b i).repr.injective.eq_iff, (b i).repr.apply_symm_apply, ext_iff], simp only [exists_prop, linear_equiv.map_zero, comap_domain_apply, zero_apply, exists_and_distrib_right, mem_support_iff, exists_eq_right, sigma.exists, finset.mem_image, not_forall] } }, left_inv := λ g, by { ext i, rw ← (b i).repr.injective.eq_iff, ext x, simp only [coe_mk, linear_equiv.apply_symm_apply, comap_domain_apply] }, right_inv := λ g, by { ext ⟨i, x⟩, simp only [coe_mk, linear_equiv.apply_symm_apply, comap_domain_apply] }, map_add' := λ g h, by { ext ⟨i, x⟩, simp only [coe_mk, add_apply, linear_equiv.map_add] }, map_smul' := λ c h, by { ext ⟨i, x⟩, simp only [coe_mk, smul_apply, linear_equiv.map_smul] } } @[simp] lemma basis_repr {φ : ι → Type*} (b : ∀ i, basis (φ i) R M) (g : ι →₀ M) (ix) : (finsupp.basis b).repr g ix = (b ix.1).repr (g ix.1) ix.2 := rfl @[simp] lemma coe_basis {φ : ι → Type*} (b : ∀ i, basis (φ i) R M) : ⇑(finsupp.basis b) = λ (ix : Σ i, φ i), single ix.1 (b ix.1 ix.2) := funext $ λ ⟨i, x⟩, basis.apply_eq_iff.mpr $ begin ext ⟨j, y⟩, by_cases h : i = j, { cases h, simp only [basis_repr, single_eq_same, basis.repr_self, basis.finsupp.single_apply_left sigma_mk_injective] }, simp only [basis_repr, single_apply, h, false_and, if_false, linear_equiv.map_zero, zero_apply] end /-- The basis on `ι →₀ M` with basis vectors `λ i, single i 1`. -/ @[simps] protected def basis_single_one : basis ι R (ι →₀ R) := basis.of_repr (linear_equiv.refl _ _) @[simp] lemma coe_basis_single_one : (finsupp.basis_single_one : ι → (ι →₀ R)) = λ i, finsupp.single i 1 := funext $ λ i, basis.apply_eq_iff.mpr rfl end ring section dim universes u v variables {K : Type u} {V : Type v} {ι : Type v} variables [field K] [add_comm_group V] [module K V] lemma dim_eq : module.rank K (ι →₀ V) = cardinal.mk ι * module.rank K V := begin let bs := basis.of_vector_space K V, rw [← cardinal.lift_inj, cardinal.lift_mul, ← bs.mk_eq_dim, ← (finsupp.basis (λa:ι, bs)).mk_eq_dim, ← cardinal.sum_mk, ← cardinal.lift_mul, cardinal.lift_inj], { simp only [cardinal.mk_image_eq (single_injective.{u u} _), cardinal.sum_const] } end end dim end finsupp section module /- We use `universe variables` instead of `universes` here because universes introduced by the `universes` keyword do not get replaced by metavariables once a lemma has been proven. So if you prove a lemma using universe `u`, you can only apply it to universe `u` in other lemmas of the same section. -/ universe variables u v w variables {K : Type u} {V V₁ V₂ : Type v} {V' : Type w} variables [field K] variables [add_comm_group V] [module K V] variables [add_comm_group V₁] [module K V₁] variables [add_comm_group V₂] [module K V₂] variables [add_comm_group V'] [module K V'] open module lemma equiv_of_dim_eq_lift_dim (h : cardinal.lift.{v w} (module.rank K V) = cardinal.lift.{w v} (module.rank K V')) : nonempty (V ≃ₗ[K] V') := begin haveI := classical.dec_eq V, haveI := classical.dec_eq V', let m := basis.of_vector_space K V, let m' := basis.of_vector_space K V', rw [←cardinal.lift_inj.1 m.mk_eq_dim, ←cardinal.lift_inj.1 m'.mk_eq_dim] at h, rcases quotient.exact h with ⟨e⟩, let e := (equiv.ulift.symm.trans e).trans equiv.ulift, exact ⟨(m.repr ≪≫ₗ (finsupp.dom_lcongr e)) ≪≫ₗ m'.repr.symm⟩ end /-- Two `K`-vector spaces are equivalent if their dimension is the same. -/ def equiv_of_dim_eq_dim (h : module.rank K V₁ = module.rank K V₂) : V₁ ≃ₗ[K] V₂ := begin classical, exact classical.choice (equiv_of_dim_eq_lift_dim (cardinal.lift_inj.2 h)) end /-- An `n`-dimensional `K`-vector space is equivalent to `fin n → K`. -/ def fin_dim_vectorspace_equiv (n : ℕ) (hn : (module.rank K V) = n) : V ≃ₗ[K] (fin n → K) := begin have : cardinal.lift.{v u} (n : cardinal.{v}) = cardinal.lift.{u v} (n : cardinal.{u}), by simp, have hn := cardinal.lift_inj.{v u}.2 hn, rw this at hn, rw ←@dim_fin_fun K _ n at hn, exact classical.choice (equiv_of_dim_eq_lift_dim hn), end end module section module universes u open module variables (K V : Type u) [field K] [add_comm_group V] [module K V] lemma cardinal_mk_eq_cardinal_mk_field_pow_dim [finite_dimensional K V] : cardinal.mk V = cardinal.mk K ^ module.rank K V := begin let s := basis.of_vector_space_index K V, let hs := basis.of_vector_space K V, calc cardinal.mk V = cardinal.mk (s →₀ K) : quotient.sound ⟨hs.repr.to_equiv⟩ ... = cardinal.mk (s → K) : quotient.sound ⟨finsupp.equiv_fun_on_fintype⟩ ... = _ : by rw [← cardinal.lift_inj.1 hs.mk_eq_dim, cardinal.power_def] end lemma cardinal_lt_omega_of_finite_dimensional [fintype K] [finite_dimensional K V] : cardinal.mk V < cardinal.omega := begin rw cardinal_mk_eq_cardinal_mk_field_pow_dim K V, exact cardinal.power_lt_omega (cardinal.lt_omega_iff_fintype.2 ⟨infer_instance⟩) (is_noetherian.dim_lt_omega K V), end end module
170a9ff304b0721def404161d9578921fe1475b5
57c233acf9386e610d99ed20ef139c5f97504ba3
/src/analysis/complex/circle.lean
639d945da36f00c933fdbe125c26b342e64770ce
[ "Apache-2.0" ]
permissive
robertylewis/mathlib
3d16e3e6daf5ddde182473e03a1b601d2810952c
1d13f5b932f5e40a8308e3840f96fc882fae01f0
refs/heads/master
1,651,379,945,369
1,644,276,960,000
1,644,276,960,000
98,875,504
0
0
Apache-2.0
1,644,253,514,000
1,501,495,700,000
Lean
UTF-8
Lean
false
false
4,784
lean
/- Copyright (c) 2021 Heather Macbeth. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Authors: Heather Macbeth -/ import analysis.special_functions.exp import topology.continuous_function.basic /-! # The circle This file defines `circle` to be the metric sphere (`metric.sphere`) in `ℂ` centred at `0` of radius `1`. We equip it with the following structure: * a submonoid of `ℂ` * a group * a topological group We furthermore define `exp_map_circle` to be the natural map `λ t, exp (t * I)` from `ℝ` to `circle`, and show that this map is a group homomorphism. ## Implementation notes Because later (in `geometry.manifold.instances.sphere`) one wants to equip the circle with a smooth manifold structure borrowed from `metric.sphere`, the underlying set is `{z : ℂ | abs (z - 0) = 1}`. This prevents certain algebraic facts from working definitionally -- for example, the circle is not defeq to `{z : ℂ | abs z = 1}`, which is the kernel of `complex.abs` considered as a homomorphism from `ℂ` to `ℝ`, nor is it defeq to `{z : ℂ | norm_sq z = 1}`, which is the kernel of the homomorphism `complex.norm_sq` from `ℂ` to `ℝ`. -/ noncomputable theory open complex metric open_locale complex_conjugate /-- The unit circle in `ℂ`, here given the structure of a submonoid of `ℂ`. -/ def circle : submonoid ℂ := { carrier := sphere (0:ℂ) 1, one_mem' := by simp, mul_mem' := λ a b, begin simp only [norm_eq_abs, mem_sphere_zero_iff_norm], intros ha hb, simp [ha, hb], end } @[simp] lemma mem_circle_iff_abs {z : ℂ} : z ∈ circle ↔ abs z = 1 := mem_sphere_zero_iff_norm lemma circle_def : ↑circle = {z : ℂ | abs z = 1} := set.ext $ λ z, mem_circle_iff_abs @[simp] lemma abs_coe_circle (z : circle) : abs z = 1 := mem_circle_iff_abs.mp z.2 lemma mem_circle_iff_norm_sq {z : ℂ} : z ∈ circle ↔ norm_sq z = 1 := by rw [mem_circle_iff_abs, complex.abs, real.sqrt_eq_one] @[simp] lemma norm_sq_eq_of_mem_circle (z : circle) : norm_sq z = 1 := by simp [norm_sq_eq_abs] lemma ne_zero_of_mem_circle (z : circle) : (z:ℂ) ≠ 0 := ne_zero_of_mem_unit_sphere z instance : comm_group circle := { inv := λ z, ⟨conj (z : ℂ), by simp⟩, mul_left_inv := λ z, subtype.ext $ by { simp [has_inv.inv, ← norm_sq_eq_conj_mul_self, ← mul_self_abs] }, .. circle.to_comm_monoid } lemma coe_inv_circle_eq_conj (z : circle) : ↑(z⁻¹) = conj (z : ℂ) := rfl @[simp] lemma coe_inv_circle (z : circle) : ↑(z⁻¹) = (z : ℂ)⁻¹ := begin rw coe_inv_circle_eq_conj, apply eq_inv_of_mul_right_eq_one, rw [mul_comm, ← complex.norm_sq_eq_conj_mul_self], simp, end @[simp] lemma coe_div_circle (z w : circle) : ↑(z / w) = (z:ℂ) / w := show ↑(z * w⁻¹) = (z:ℂ) * w⁻¹, by simp /-- The elements of the circle embed into the units. -/ @[simps] def circle.to_units : circle →* units ℂ := { to_fun := λ x, units.mk0 x $ ne_zero_of_mem_circle _, map_one' := units.ext rfl, map_mul' := λ x y, units.ext rfl } instance : compact_space circle := metric.sphere.compact_space _ _ -- the following result could instead be deduced from the Lie group structure on the circle using -- `topological_group_of_lie_group`, but that seems a little awkward since one has to first provide -- and then forget the model space instance : topological_group circle := { continuous_mul := let h : continuous (λ x : circle, (x : ℂ)) := continuous_subtype_coe in continuous_induced_rng (continuous_mul.comp (h.prod_map h)), continuous_inv := continuous_induced_rng $ complex.conj_cle.continuous.comp continuous_subtype_coe } /-- The map `λ t, exp (t * I)` from `ℝ` to the unit circle in `ℂ`. -/ def exp_map_circle : C(ℝ, circle) := { to_fun := λ t, ⟨exp (t * I), by simp [exp_mul_I, abs_cos_add_sin_mul_I]⟩ } @[simp] lemma exp_map_circle_apply (t : ℝ) : ↑(exp_map_circle t) = complex.exp (t * complex.I) := rfl @[simp] lemma exp_map_circle_zero : exp_map_circle 0 = 1 := subtype.ext $ by rw [exp_map_circle_apply, of_real_zero, zero_mul, exp_zero, submonoid.coe_one] @[simp] lemma exp_map_circle_add (x y : ℝ) : exp_map_circle (x + y) = exp_map_circle x * exp_map_circle y := subtype.ext $ by simp only [exp_map_circle_apply, submonoid.coe_mul, of_real_add, add_mul, complex.exp_add] /-- The map `λ t, exp (t * I)` from `ℝ` to the unit circle in `ℂ`, considered as a homomorphism of groups. -/ @[simps] def exp_map_circle_hom : ℝ →+ (additive circle) := { to_fun := additive.of_mul ∘ exp_map_circle, map_zero' := exp_map_circle_zero, map_add' := exp_map_circle_add } @[simp] lemma exp_map_circle_sub (x y : ℝ) : exp_map_circle (x - y) = exp_map_circle x / exp_map_circle y := exp_map_circle_hom.map_sub x y
ee6f597ec89e7cd795cc1956d4d4f40cd9a6b99b
18425d4bab0b5e4677ef791d0065e16639493248
/finitary.lean
9867b74213e367cda4db780abdb5cf0fbaeb0287
[ "MIT" ]
permissive
tizmd/lean-finitary
5feb94a2474b55c0f23e4b61b9ac42403bf222f7
8958fdb3fa3d9fcc304e116fd339448875025e95
refs/heads/master
1,611,397,193,043
1,497,517,825,000
1,497,517,825,000
93,048,842
0
0
null
null
null
null
UTF-8
Lean
false
false
1,412
lean
import .equipotent .data.fin.misc universe u def finitary (α : Type u) (n) := equipotent α (fin n) def permutation (n) := finitary (fin n) n namespace finitary def eq_of_finitary_fin {m n} : finitary (fin m) n → m = n := assume H, decidable.by_contradiction $ assume ne, or.elim (lt_or_gt_of_ne ne) (assume Hlt, fin.not_injective_of_gt _ Hlt (bijection.injective_of_bijection H.bijection.inverse)) (assume Hgt, fin.not_injective_of_gt _ Hgt (bijection.injective_of_bijection H.bijection)) variable {α : Type u} lemma univalence {m n} : finitary α n → finitary α m → n = m := assume Hn Hm, eq_of_finitary_fin (equipotent.trans (equipotent.symm Hn) Hm) lemma {v} equipotent_of_eq {n} {β : Type v} : finitary α n → finitary β n → equipotent α β := assume Ha Hb, equipotent.trans Ha (equipotent.symm Hb) def empty_0 : finitary empty 0 := { map := empty.rec _, bijection := { inv := fin.elim0, left_inverse_of_inv := empty.rec _, right_inverse_of_inv := take i, absurd i.is_lt (nat.not_lt_zero _) } } private lemma fin1_eq_zero : ∀ i : fin 1, i = 0 | ⟨0, is_lt⟩ := rfl | ⟨n+1, is_lt⟩ := absurd (nat.lt_of_succ_lt_succ is_lt) (nat.not_lt_zero _) instance : subsingleton (fin 1) := subsingleton.intro (λ i j, begin rw fin1_eq_zero i, rw fin1_eq_zero j end) end finitary